Coordinated latest-only result/read foundations; actual installed-client compatibility is explicitly deferred post-merge.
Separate finalized local runs:109 lifecycle/security/replay cases;2 real isolated readiness fixture cases;116 integrated result/provider/router/schema cases.
Final review fix:44 declarations/90 expanded macOS cases PASS, compiled inventory and signed isolated host verified; lint527files/zero violations.
Full configured iOS targets:1310 tests/1358 executions PASS. Separate UI-only:21 tests/24 executions PASS. Zero failures, skips, runtime warnings or global issues; owned simulator/processes drained and deleted.
Actual schema exports:876 assertions and3 recovery descriptors PASS;5 readiness verifier tests PASS. Root independently rehashed23 final macOS and39 iOS artifacts without mismatches.
Actual installed-client AC6.3 remains UNVERIFIED and explicitly owner-approved deferred post-merge. No client setup/settings/model turn/live data repair/deployment.
Ready to push
All actionable pre-push findings fixed and internally re-reviewed. Required native Xcode checks and lint passed; actual results are listed separately below. AC6.3 installed-client compatibility is unverified and owner-approved deferred to post-merge MacBook validation.
d86f3adfd3cca7d4eea0ce601894034821fe5eb6 T-2383: finalize Rune task state with recorded client deferral 071633f1e3e8ef49c82fdcc60fdcdf52196990d6 T-2383: record full pre-push verification and deferred client acceptance d65d305ccfbe7554fa65acf7ab9d0f3bcb2ffe76 T-2383: document result contract and approved client-test deferral 9c41be669c39662ca98826ed601f60c126bc6af8 T-2383: fix read categories and bound catalog projection 6bc20e16bd29137526d5f4a804e7c84829e6e073 T-2383: hand off verified local implementation and bounded client gate 57b86265ba03b74bc863022969bc939b56a44187 T-2383: changelog for verified local structured result implementation 91248e858d5ff899252c0a13f0165fb950bff661 T-2383: record real isolated readiness fixture GREEN 5bef12e06aa7d2ce8498cf1e0d156813e0e1f085 T-2383: record verified synthetic readiness GREEN 68ba166c060d1d4e10298d1330c8603065cf206b T-2383: support inspected legacy xctestrun target layout in launcher 764b07e6e56341173f9da8c1af7be0d968d7b6ba T-2383: bound ordinary probes and accommodate readiness SSE hold d502388a69584003c4199bbdbb91dd1fbab2b443 T-2383: implement isolated actual-wire readiness fixture and verifier d697ff18e75fdb8d6f346b54a77f8522dc271d7c T-2383: record finalized GREEN and qualified readiness RED 623addfb586fbcff73bbdc024dbfa24651782d1f T-2383: specify isolated readiness trace and negotiation evidence RED f9bf5a6977d67066305787bb8fa2df4e816bad14 T-2383: record finalized subscription GREEN and readiness RED start cbc4aedaf3702514a6ab80bdd0d9d2209a8b70ad T-2383: retain bounded allocator rendezvous fixture compatibility 087d492139c7732398502c2e80e8bf212d99635d T-2383: match subscription writer concurrent execution isolation b94fb1e90a97720ccaced713a49d65d9989f450b T-2383: remove agreed obsolete Settings session forwarders 900b353c22cd9e75e3d7aa61a0d51cb9a95bb21b T-2383: record exact fixture and catalog source handoffs e00e9a0e28ecfb5f40f9c140ae22d24840693f55 T-2383: preserve write lifecycle semantics over modern transport 21356d50bf86ec8a467cfa31f342655d13e523f0 T-2383: integrate exact T63 catalog failure repair 0071ca4bb39fcc3a72b2ee7918e8886083d0b642 T-2383: record source readiness and focused fixture handoffs 405ffc76fe64afaa9e9cf96c46375cc128ad3aca T-2383: port transport regressions to modern request contracts 4ddbfc8774aa2bd95da545d14de8065bf12f16f9 T-2383: drain HTTP fixture async channels safely 868ed04b4150baf6512757b8006810096ecaaeb9 T-2383: implement request-scoped subscription delivery and cleanup bd5c42a456e297e28960c008d6eedbfc4d14c4ce T-2383: integrate exact T63 diagnostics handoff 74cbabfd56fe0629c2580a3a2445a2b9f76676c2 T-2383: record subscription RED and client approval scope fe497b641a1101c86ca4c5b8047952100762b25c T-2383: import T63 subscription broadcaster getter 9f2eb39c5c504b9884e6fe7c0b042d0d08314fdb T-2383: preserve plain forbidden subscription responses 3abdf24ad296311e860f8abcc7df56494f120e6d T-2383: require valid subscription fixture HTTP methods 6e005c0b8b3b5b8988c1102d3a8dc24cf2545fc0 T-2383: import subscription response fixture module 1fa4c95e46ded7ed16cae4d396a8089bf3e69dc9 T-2383: import notification fixture lock dependency b3710a4a5fdac64fad712f89450a0c0529af82fe T-2383: import subscription fixture lock dependency c6c9f4156c002a93823f6f24795f379eeba4a119 T-2383: prepare Settings owner request and client setup proposal f40dfb36b3582f6f1320aaee730d31f2dea958a1 T-2383: record recovered subscription RED readiness 4366824782a417073166ba0f61d16ed2e41425ad T-2383: specify request-scoped subscription RED coverage e45bc003786778156677d8b3033d7394779dd7b8 docs: complete task 17 acceptance and handoff ec1b72136853a3b45587fb387feb382b58a83ec3 Import exact owner structured-value discovery oracle correction 197be8cebb74b81849d3236d6f5daacb8905eefc docs: preserve executed retention evidence and classify schema fixture failure 66cca0739361897e88b25dc2add1dfe8bdaf53e6 docs: record exact fixture isolation handoff for corrected acceptance 022ce9a2b0d53923c637447431b302a474f37433 Import exact owner MainActor fixture correction 12fa3438c7635683fac1984c01a7296b9b22f21f docs: preserve actual combined build failure and owner fixture correction e46ba9d864ac12e790320dd87ef4ed60d39d0e51 Align modern aggregate fixture parameter indentation f8752ba3ed4f2f91374b1134723c878553cc9f3f docs: reconcile manifests and close retained integration findings 2e37a8a2cc0178add8419cea9b8bad6d93146bea Import exact opaque portfolio replay and modern route fixtures 180d46f33f14c51d0697c9030c66c0eba74e2f56 docs: record integrated owner source and remaining acceptance inputs 9b1e4da9fc2242d5d7c3376d9338fba819af8cc7 Import exact corrected ordinary read preparation and terminal pins 47bd166a26975cf4b18bfa101344a491d2b64f04 Import exact reviewed reusable prepared owner component ef419b1f0d9415adf857916473d1c24c20de74a0 docs: track bounded owner validation review resolution 9fd93e479f3d673f1518de6364a291f1f9603d98 docs: record exact reusable source review and assembly dependencies ba9479aa6dbd3d0a77e274fcc6746776119986f4 Align modern retention fixture charge and operation-aware aggregation e3839e9dc4572e0f0639f296854265860da8f879 docs: record retained owner checkpoint and replay gate findings a94cd0eda36d680e16a81e6874abb712e0ed45d4 docs: record common retained-read GREEN source and owner ABI 0af0bfc1da9538a384807678cffec9192c91b8de Prepare immutable modern read pages and reuse frozen fragments 52492d7959e179f2c4e2a9f9cd60db7b7b732e14 docs: complete retained read RED and package parallel owner GREEN handoff e92dc6b6b08b9c35fe03244dead2020e1cf84041 docs: record authorized exact owner correction and new RED slot 936d10bd178ac28e42e3f34712310c693940a2a5 test: import reviewed owner metadata macro correction 57809bf1971431d1a1163a8bce4c0e3df9ab509d docs: record targeted owner fixture compiler finding and correction handoff 72b92998eb9a867d4a3c1757ec5b35fabeb339ab docs: pin reviewed unexecuted accounting correction readiness d6b9890107aad2b3144de1cf124fb251884728cd docs: record second compile-only failure and released slot f93d55473e7d5b68a1e5d290fed3365ee7a4975d test(mcp): handle private-page accounting assertion errors cf97fcd10d8c0ed2257c72cd745e1daf2ef20c6d docs: preserve combined RED compile failure and exact correction 01a903d9bd1c457fcd39572a8b4b16ec8aaa8446 test: import exact prepared owner fixture dependencies 2102864cb1be7c0535484fe5254afce577aabe46 test(mcp): qualify saved comment fixture type 88bc63e25de45379498432e9346a7541dde8cab0 docs: record combined retention RED imports and coordination 5678381eea99515e42eac35276d113f00d0e93eb test(mcp): cover expanded modern read retention boundaries cb106028f5b79af011cf8da68a5d4a1ce32aebe5 test: import reusable prepared owner RED fixtures 4c3da7b10e84a886725411d69e28695cbee26d98 Import T63 explicit read provider evidence fixtures 2e8033cd8a3c2d7e98852311ad97ea866defd43e Import T63 task16 read preparation and ordinary RED declarations f06d9f350f92acbc6cf1bca4aa26273646902dfa Import T2382 reusable prepared-owner RED seams fcc4ce9da2dc26414569722f15828201fb0929ae Record task16 common declaration and focused RED readiness f2517f6eb05b07d097dd5c074d08c16c50a087d7 test(mcp): prepare modern retained read page RED boundary 0d248999e82b0069d804835fa21e6bd6c8bb9d5d Start task16 and bundle retained-read owner coordination 18a3483033b98d5a19f9f4f708629483ad453ada Import T63 immutable prepared-page carrier ABI b21e358c8a5ea1e287afe332c1fc50d83303ce19 Deliver verified API15 result contract and exact consumer handoff 160181e0259d67333693e8cfc237ba58dd324539 Record combined task15 results and focused fixture correction readiness 543c4a757e4cb7f9f73c973d7cb1be5725c8f342 test(mcp): provide required limits in saved-read fixtures d29fdaa7bb5f60830674cb32df39903b06f487d3 test(mcp): import NIOCore for binding notification fixture 59becc9441b8c8df965f762010aa839bc2d30fcd Record task15 binding checkpoint and exact focused GREEN readiness a8fcc71506ff61ee5b6f0e320ace5a064e30c915 feat(mcp): bind modern result providers and effect-aware transport 8f1b16f37bfadc2bac9b28269061819e96fa22fb Record corrected four-body RED and first task15 source boundary fb776a03c366c7f1bed447eaeb98a8bfcaf06508 T-2383: implement effect-aware selection and value-only provider evidence bc8354f7812ee35859b0566c0d1a6e966bfec2ab Record finalized metadata controls and owner availability delivery b51ab962018f34d12fda220a1b115af384526de9 Import T63 synchronous maintenance availability snapshot after drain 1a69d41bf618d94dce79f131d7238377db32ec52 Record exact owner factory patch consumption after drain 8be5d55579a703b4e64eac46f4e528ea191bf61d Import T63 modern descriptor factory at drained checkpoint c3b4902a78a4177d4925fdf7eab6dc14bc82269f Record correction compile limit and immutable availability owner seam 8b3c95477847d6e7c47b19939968e22c4020a763 T-2383: mark historic receipt fixture requirements as throwing 76fa6620743307219e31fe7ec3abe1191d466da3 Close meaningful provider RED boundary and advance approved task15 5b20464c866bc4d334c4df9916b26e42306bba8e T-2383: correct provider RED metadata receipts and async transport fixtures dafdb266d8f6ec4d9b7fd6fa8336cae076ac02dc Record minimal retained-owner modern descriptor factory request 48892dc1ce88b746f58c7e3a45066f9ba6bdfd27 Classify meaningful task14 RED and narrow fixture correction plan 70edd4d11927d99aa94a11679b95525d89be3079 Record task14 actual partial RED and fixture blockers 561557ef3d31904617ccdd266c0bc4009dd5ec04 test(mcp): specify provider and modern routing integration 71a10ff092e66cb25c85c9b109e76de444177bad Record verified T63 read hook import and checkpoint boundary 6a39611292aba4646f23d32fae574ddffdea2bd7 Import T63 optional modern read encoder hooks a4aaab15e549a6950263fe96d4df70cd950ccd4b Record task14 helper handoff and read encoder seam requests 80e9dc4c39b49eaa90d552dc50d00b83ac7b208a test(mcp): accept ordered HTTP header fields 1fd409b10bfdbbd6f07df252d8c6107d07e51d44 T-2383: record exact combined baseline and owner seams 1a19dfda6761ac788db47821a838fb14f7de3e4b build: import owner-pinned portfolio baseline dependencies 36030cfc9118b32c4791d16b873050a8505ab73f build: reconcile pinned Stage B shared baselines 38ad6631b35be9ca95c7a936861ef7cf3d39385e T-2383: complete verified preparation GREEN and release slot 66e39d7b00196a4e14228acb4ab80fa4f2a33980 T-2383: record reviewed preparation GREEN readiness 1135a88b75e8170506ca465db9b1d0c4e2f13ab4 feat: prepare charged immutable result backing 41d5114da7d21eff65e990ba6d339073ee3e9e3e T-2383: complete meaningful preparation RED and release slot fec9ecf8d1eb1b8af9b9a99e9ff2965c0c2e37ec T-2383: record direct user testing approval 3f27454d5cebecf183e6bcb48aa9135e18fe2ed2 T-2383: accept pinned modern production ownership transfer 13125f8b58da8645b5fb73a3b437e2ee24ffd3f9 T-2383: record unchanged retry denial and release 82c11e2b31ab738dafdb1a4459c766e7ffc3a9de T-2383: record blocked RED attempt and unused slot release 3f7f835f1f350283f4d5ff620b58b1d7c76cce08 T-2383: record reviewed preparation RED readiness 70d103a05ae68334cc6f6c65ff919187a00ffb6f test: prepare retained result budget RED fixtures 1e0c8f67b64530c9f62b5e7d98c1f29e26ba34a6 T-2383: record verified schema GREEN and release task9 slot 2df0648c74eb3cd7343463b12124a17335e71cc1 T-2383: record reviewed schema GREEN readiness and recovery separation 1f20e115d3da01b8913dba9157fe1e84907dcfbc T-2383: restrict saved retry presentation to protected writes a25bf996a8e73edb7972cc85780248df9c83e654 T-2383: implement immutable structured result schema descriptor 0695c7c7c6d46b1f0eae5e0641796f0c0a333c7e T-2383: record meaningful schema RED and finalization limits 83e5ff796aa686ecf46dcf5683719aa89791a0eb T-2383: record reviewed schema RED readiness and coordination 912ddbca727065e5ee426ff165b286b8b9c7f58c T-2383: specify structured output schema RED corpus 3e9f8fee816e3656e39f09cb7999d2a3a91ba779 T-2383 Record corrected encoder GREEN and release 754729455b2640361d5df37c6e3142f4a66fad39 T-2383 Record guarded rerun approval provenance restriction 49f18baf1de9df6af614948bd660a9429faee7b2 T-2383 Record reviewed oracle correction readiness ffe2c33bac157cee7b05cd481157c5bffc9d485f T-2383: keep envelope fixture validation independent of numeric range 2718163b7d5cef72d3c0675acf5127d50331aba3 T-2383 Record encoder GREEN oracle failure and scoped teardown dd4a89b8cf071d435ae131b13f0a34b19febf6ed T-2383 Record reviewed encoder source readiness 3ba1cfbc157a0682dbdec211b4cbcd9ac269aea1 T-2383: draft lossless complete result and fallback encoder 61df37e92305b61595caef1d0a18e818849ac8dc T-2383 Record meaningful encoder RED and teardown limits 7a3a740a9be0d6e048773f2317ef3e423f02be1f T-2383 Record reviewed encoder RED readiness gate a480d06341b7dd5e4a48c5ca77fec1d3e393f155 T-2383: draft complete encoder and fallback RED fixtures c6fbbd1a125f28e62c331117985324dfa965ccae T-2383 Record isolated presentation and protocol GREEN 41740d1889ed558cecb0e6d50c1604d3656d76a7 T-2383 Record integrated isolation source and verification gates fbbe7cb0ff0dd884dc79f6f9cedf652946065275 T-2383 Integrate reviewed modern protocol source for isolated GREEN a1fa7f50c644c2bda7f1efc9a2a923bd59d9aedd T-2383 Integrate reviewed presentation source for isolated GREEN a540514ccc2c61f21794524f00908725a55f4a60 T-2383 Integrate verified T63 isolated Stage A foundation b7625fda2555ddbc768e5da5e8de3d11339ba152 Revert "Apply isolated development bootstrap to T2383 without read-interface changes" 9f6808e9670978dcca740de915d6a9883e951143 Apply isolated development bootstrap to T2383 without read-interface changes 4eade7b1c8ebd7e1619dfa7715e4f41b2cb6809e T-2383 Record exact-base isolation verification handoff b500543369ebbd53f01634fa829bf74a8fceabe5 T-63 Verify isolated Stage A bounded read routing c614a9b03c560926fb850326752fcff444059e88 T-63 Import SwiftData in publication failure fixture 6806262ba2520616af20920c8c60e61a538b4379 T-63 Integrate inspected isolated development and host component 46bec7c386624ce755c11940ef58bf046999cb02 T-63 Read import applicability on MainActor feeb7df8e115edcc0139072c08c0968c3ce157dc T-2383: document pending common seam and isolation holds bb0f5244c236827ef997e8bb035fb82efbf31473 T-2383: preserve read-only duplicate and last-write evidence 95b0d306581c46004aa1960e4d5b4b2c8fe34207 T-2383: record reviewed presentation and protocol GREEN readiness 36f7ee328f53250413beff825af3ae826e25d3d0 T-63 Prepare minimal coordinator lifecycle and encoder failure acceptance f4bd03a638dbdb0c56c04c4506a5aaaf864fb054 T-2383: Repair presentation gaps after supplemental RED 4df42cc0d7ec34babca7e5a8e73ad196d0f5c6c2 T-2383: record owner-authorised presentation supplemental RED 943986edb612b9ad4e0af7bf22400908aca7ac3f T-63 Finish prepared-result scope before physical receipt e3b37e337da2b1b9a508bfd3ab7306e19bba4ac7 T-2383: Record meaningful supplemental presentation RED 5cd715b8a34ab40ac23525c39c29a36dd1f4c97b T-63 Wire bounded ordinary single reads for focused verification afe774197103d47215f65de9bc56be64d683ec5f T-2383: record critic RED and focused execution approval blocker 469f4fd0c86866fb891f45d839f9039988b14869 T-2383: Record critic subscription and name conformance RED evidence b6b616e07aeea669e51b66d4ade900c7ca598a06 T-2383: Fix subscription filter and name header conformance 52fea714e2edcc75aa8432ce7ac59c6e69d8ea68 T-2383: Record critic subscription and name conformance RED evidence 391c15998cf3c9054e71ede77dd7edb8e6787c29 T-2383: Specify missing presentation behavior in supplemental RED 7fbf51079c043dd1c3ee4a9958cec5e368ca2c6f T-63 Record server baseline and staged routing implementation 366a1adf57935efc017bd4fa2d03ce06be1618ce T-2383: Add critic RED cases for subscription filters and header names e3812b1f5388e866ac31657e8eda2dd7c5b46e2d T-63 Record compiled capability RED evidence 1652913db72bd2a5bf00dd109fca547d8477db3a T-2383: Draft source-only result presentation 60f1e5a4c614192a3d9f344c8a50332a3ceebbfc T-2383: record protocol review blockers and phone transfer cb3aeefb9d131934150e7211dc832062da7148fd T-63 Prepare stopped-read routing and write preservation fixtures 3cfd28a8a8f7d707f9a03ca4bcdd0aed4e4f71b9 T-2383: Distinguish protocol resource limits and document valid ID boundary 0dfeed2bcacecf41c00b50122121aa95f4681fd5 T-2383: record protocol supplemental RED and execution boundaries a9553bcd5bfdf7a12ba33cbf5da3c384b885bc24 T-63 Await physical receipt independently of permit drain a3928576aef1da83cffe1cec3ed5b1b7b7697747 T-2383: Record supplemental protocol resource-bound RED evidence 55a903e009b2497336df2ef4b5910a1f952959ac T-2383: Integrate approved protocol resource docs and presentation RED 58dc4a7faadc40364136f926252a6b345096a761 T-63 Prepare admission and captured-helper contract fixtures 9b2cef375541399fc2069b49fdcfabe396aef39a T-2383: Record supplemental protocol resource-bound RED evidence 272489a590bb2c9cc3dd2af705a4fee26b6f649d T-2383: record verified presentation RED checkpoint 89fab6562d523cfb1b61e2d131cb95a74ef01e55 T-2383: integrate verified presentation RED task4 55116ca868d4b9f1f25bc3bd2eff6ad37ecf8e4a T-2383: record demonstrated source-only presentation RED 99f8cbcdb780afec5639734639d36902c816acc7 T-2383: format audited project presentation fixture 008f6fee75da6e1859dacb14ed18d4e6136f0925 T-2383: correct public record identity selector documentation c5e18a6cec68fbc33de608fd815ee93fe082ca87 T-63: Plan staged bounded routing integration a93bbf8d89cfdf21d59eea4fcf4b1fa646bebc89 T-2383: align presentation RED fixtures with actual query identities 54bfe9880fd575eb4dcc75dd3d47384f055b2d74 T-63: Record staged shared integration ownership 099415e832afc312a94e9521e3704eba729e441d T-63: Record actual bounded routing RED evidence c7c31ea54e6394b65054ca509addda015ae8d661 T-2383: document request-ID resource bound and protocol cap diagnostics d0257710df8d581d4e253493e97e9dd8037ee8ef T-63: Detect late retained publication in routing deadline fixtures cf900adf884b7fd79da0f07abf9b6f4d8d2206e1 T-2383: Add supplemental numeric ID and JSON resource boundary fixtures 35d768118c37b8b4909b47b20e498f63eff86753 T-63: Prepare bounded single-read routing regressions cb876b07c69d7be5fb49cf2c27b387a7bbe0a545 T-2383: draft source-only presentation RED contracts 817a80a4272b7b0beded533ba469cafc7d559654 T-2383: Implement pure modern request validation and discovery 15bde9e182efb723d0ea637e2e997b061dca59ad T-2383: record verified source delivery and next interface gates df3c23b5371b2c8c649ab19daecef6ae7fac8cda T-2383: integrate verified lossless parser and source factories 0a939303d9f8f6b93d89f6ec1fefa6ff446a0869 T-2383: close source construction boundary and record GREEN dc85eabb5b35a6bd6b9ee16908d72aeb2c55bf15 T-63: Preserve read compatibility before canonical capture 70aa408cf488297aaa5d2f13cb441778ca4a1f23 T-2383: mark parser implementation in progress 31bc425ba3a066497c6a9dcdedb1ed9dcdffdf03 T-2383: draft bounded lossless parser and source factories 48a9f73a21b292a3adaa6861cee9c7cc99bee38b T-2383: record cap RED integration and pending parser GREEN gate fe5a95b48292ba615f74036ad8908892b83700ab T-2383: integrate evidenced32-level parser cap RED 22abd9d20d782f68e42547a89cac474af08859e0 T-63: Cover foreign milestone canonical scope isolation ed9f2fbfff303aaec2b89b7fc9ef9b7bd441a007 T-2383: record demonstrated parser-cap RED 0dd7e4a02f05cc08f5a2fa0ada5fb6003b0b9412 T-2383: record integrated lint and phone transfer outcomes 4bfd3907808ea4d4166d2e42244fb56e41265662 T-63: Keep selected milestone serialization failures visible 0e09add23b784cab0c9f1cb6d301ce768ab92287 T-2383: record baseline RED integration and released test slot 7a5c856c23808a3690ca047b3925a6fa1d6c7d9e T-63: Reproduce canonical serialization before read selection 6dfffd51789af1b74cc7500c7cbf77edf5de7fec T-2383: integrate evidenced modern protocol RED fixtures db8173c42834362923d6758244c5ab6c3abb5c22 T-2383: Record focused modern protocol RED evidence 128823d0e80e15f9f4d19d7401acdaeba5bc984b T-2383: declare approved parser cap and draft boundary RED cases 4a9d1bea1c844bed6de9f285cc82d575f5a69a3e T-2383: record owner-approved parser nesting limit dbcd0e2331b45cf97cd35e51dfa4545968a432e2 T-2383: integrate evidenced lossless-source RED fixtures 8f9c4ce07864e2536d27fa7c072137b9996bb9f8 T-2383: record demonstrated source and parser RED 0e96755eb61ac5c7b38a467cecf08be9ca574561 T-63: Add legacy read failure and empty-query regressions 9ff0b45d174e8a10b81b8564ec3d5772cb7d8e97 T-2383: record RED draft readiness and compact fallback constraint a928cb778d81189cf89b2ee28f8ba6c51d3997cb T-2383: Make duplicate metadata fixture independent of slash escaping 0ff987610b6a7a41dfce8d5ace288ff1fd64544f T-63: Prepare saved read projections with frozen metadata 498d5156f973fb0770a66803c6c30768fb548067 T-2383: distinguish scalar identity in JSON key RED fixtures 26f4dda6df7c167235ac746e4de45f71f6025f2d T-2383: Draft modern protocol RED fixtures and parser gate d255562ef1d5b4fe781f7c5f5027e5013b8cbaba T-2383: draft lossless JSON and source RED properties 9df81c0d3316d118a544cc2ce3a5a808c96ff29b T-2383: gate modern protocol GREEN on the shared parser a047851edcbb6f26ce809982a3ff8d5e663da5c7 T-2383: record declaration validation and isolated RED ownership 5856efaecd68caa6a9f19c6b37eb8d6cd8b55bc2 T-63 Add scope and read precedence regressions 8ea94ce0b3b9a3b73fcee330aed0c9883a08e92f T-2383: declare immutable result and modern protocol boundaries 581065de5034c423a2ae67185f4199b2b0d76327 docs(T2383): record task approval and start implementation workflow b58298a7aa6e4c5f492331b4aadb4e3277c3f707 docs(T2383): complete Rune task reviews and delivery gates a694c2711d5b275ccc9646bf5efd8bc10bbefd56 T-63 Bound scoped capture bodies and index comment evidence 595c61cb1e22b42ad7f971c448cd717ced7e4913 docs(T2383): record design approval and draft Rune task plan 90c29f20ca07205d3422e11350fbd6782cf895c9 T-63 Reproduce scoped capture body expansion 02b734b742ec661f8bd17b0cb39e749f56b05c89 T-63 Cover frozen read service metadata and failures 7970a9c5f7db57a05167fccac53e6798a033dfbd docs(T2383): align batch-owned serialization failure vocabulary c4422ef9b631e0dfb0c16057ace9fcb1c6c45754 docs(T2383): complete internal design reviews and shared contracts 0d43fab3dcabac86bed5b7424163145ae0e7b637 T-63 Add saved read projection regression cases b633ea1303dfc45a1ecbbd510e63e71744ba9bf3 docs(T2383): draft approved-requirements result and protocol design 6b34e83742ecacb67f2f2fecd6116e25b7be2078 T-63: Implement atomic publication and ordinary retention cbe6bc524305f48088aec11db5bac3180b6fe3b8 T-63: Reproduce canonical capture serialization category regression f8adade12abff376245bbb071543b4c2ac0bda24 T-63: Add red publication capacity and transaction regressions d183b774d88f0dffa29e94a35d9d238954cbe76c T-2383: require Claude Code and Desktop migration readiness bc1642183e9c7f67dae37fc68249ce89216d35fe T-63: Record integrated foundation and implementation progress 7f5d7ceabe8fec726ceaa76ec4973f33f64ecdf1 T-63: Integrate verified bounded import evidence and refresh policy 7c11a2317a2b46304c4d1e227791bc024ea212c4 T-63: Integrate saved capture and bounded transport foundation 1d1496f443b0f94e4a1ac040a7da32beca783ba9 T-63: Record verified capture and transport foundation handoff 3747cadb1e1719e3ff6dc1e3a4196bb704715840 T-63: Make pending batch fallback selection atomic across restart 66dfa233df077d5b23535514982ce17e7160bea9 T-63: Cover large fallback initialization and required capture failures e11979cb006b0acc1ee1f45f10abc962394fb80c T-63: verify scoped import observation repair in app tests 801f37c666ef99ef9fbc2e6d25739318662a7547 T-63: retain scoped import evidence through capture e5fc7253851b9c45812f142fcb18dadcc4a360f1 T-63: Record foundation review corrections and verification limits c07d808e11583a209ebece82c9b5c3429bce8208 T-63: reproduce same-store import evidence replacement 8c2eacd2a36e0bcceea2a3cbce76cbd84d25aa9a T-2383: record completed internal requirements reviews 8d25a0bcbdaa0f652dbfa9966039f619751c49ea T-63: Select prebuilt batch fallback without waiting for assembly 604d171a23d26424e2a92c2583bffdeaca2cffee T-2383: draft latest-only structured-result requirements 9a305b9202feddf0d1ce15f22a09b00b5623b7cb T-63: Add whole batch fallback and terminal race regressions e91138d69f3ac8a9e791d92a0adeae76dd745b3f T-63: Return bounded encoded reads independently of MainActor 74c4947f8e3c7e121e5c3d45d309dde730905efe T-63: Add actual router deadline and retained permit regressions 577a132078ec0bf4bac4a545190afab8f700d32b T-2383: assess latest MCP protocol and compatibility scope 8d69d65cf4c71a60ff890db81b7590c1a140e0de T-63: record import and refresh app test verification c944a441a5466e0a9a2f2850ed174c9e4df50996 T-63: Separate canonical comments from physical attribution d38e0dc2698fa10f9a15eeb924f2f0eee57d9ce8 T-63: Reproduce duplicate UUID comment attribution 294d3d7fa644c1b43fa2289b2eb20271533922ae T-63: scope refresh completion observation to applicable imports f760f606d9fc8e543f183370a303bf4412742f09 T-63: implement conservative import evidence and bounded refresh 6932030706fac455d8c7e02ed1a1944d6eb2f82b T-63: Capture saved records behind a persistent history fence 05519fbd6210d85a3ae4a883e80186eea22d4610 T-63: add import evidence and refresh policy tests 5746139af42bbebfb2eb9565cec9dd3d35b664f3 T-2383: record structured result scope for approval fc7dea2d951671ced77f3fbb85b3c3f581afeb07 T-63: Add saved capture risk regression tests 7a9c299260ba6648b1bef2afc0777ff3aeabcb74 T-63: record shared interface handoff contracts 52e488279d3738f8e730232c0e3a2cfd18a8925d T-63: clarify portfolio evidence and publication grouping seams 1b34efb98dcac2248ae5d666bc4f5aec8b787e41 T-63: define shared read capture and publication contracts 8b0433a8de2fb1624f9f70ebfccb1313a079851e T-63: record task approval and planned spec a03f4e6e11c4aa32ace54a24744d99fe8b82da47 docs: plan reviewed T-63 implementation tasks 0f50d68985e13a8e645f3e8f0f6462ad3bb6a3dc docs: clarify shared read capture scope contract cec8280379b02067573713088ee519d5d1940f36 docs: prepare reviewed T-63 bounded-read design c651dfa0bb7718cb9bd85529bdf25d1831dc958d T-63: prepare reviewed requirements for approval a14a6a4643f25a3006fc5d73d844a05eea073c12 T-63: prepare scope and shared freshness contract for approval Agents receive structured data alongside the unchanged original text. Saved responses remain distinct from added explanations, so retry evidence does not quietly change.
Immutable source and independent presentation feed a common byte encoder. Frozen read fragments and metadata are charged before atomic publication. Modern requests validate per-request metadata/headers before dispatch; subscriptions use POST/SSE registrations.
Request IDs never enter retained tool fragments. Cancellation suppresses delivery/publication while physical work retains admission slots. Mutation fallback bytes are fully prepared before effects and selected without reentering failed encoding. Unreadable/contradictory evidence preserves text and cannot establish no effect; source retry facts remain authoritative.
Transit/Transit/MCP/Results/MCPResultSource.swift
Why it matters. Historical receipt fields, exact text and error presence remain distinct from supplemental presentation.
What to look at. MCPResultSource.make
Transit/Transit/MCP/Results/MCPResultEncoder.swift
Why it matters. After-effect encoding failures cannot fabricate no-effect outcomes or create fresh keys.
What to look at. prepareMutationFallback
Transit/Transit/MCP/Protocol/MCPModernValidator.swift
Why it matters. Legacy sessions, wire arrays and mutating notifications cannot reach effects.
What to look at. validate
Transit/Transit/MCP/Reads/MCPReadCoordinator.swift
Why it matters. Timeout/cancellation does not create late retained successes or undercount unfinished work.
What to look at. execute
Transit/Transit/MCP/Reads/MCPReadProjection+Catalog.swift
Why it matters. Avoid quadratic whole-task scans and fail closed on ambiguous physical identities.
What to look at. catalogTaskIndex/projects/milestones
docs/mcp-result-contract.md
Why it matters. Callers can locate source payloads, classify recovery and avoid obsolete transport instructions.
What to look at. Result contract version1
Owner Sentinel_c0dbfe3212888191bc01744c855f67bb permits merge before actual installed-client compatibility testing. No client setup/model turn/deployment ran here.
T572 remains separately scoped. UUID-associated link entries report unavailable; no guessed entity-opening URI.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| major | plain-text failure categories | Known fresh failures lost semantic category | Existing typed provider failure evidence supplied; source text unchanged |
| major | portfolio error classification | Known snapshot/identity errors omitted from categories | Explicit known-code mappings and restart-read regression |
| major | catalog projection | Repeated whole task scans and no cancellation checkpoints | Duplicate-safe physical index and original-operation checkpoints |
| major | caller documentation | Missing result contract and obsolete sessions/batches | Versioned contract supplied and caller docs corrected; actual client deferral explicit |
| minor | portfolio helper reuse | Optional helper duplication | Skipped broader refactor; behavior already validated and unrelated to blockers |
Source: local run at 2026-10-04T13:47:38.062854+00:00 · snapshot d86f3adfd3cca7d4eea0ce601894034821fe5eb6
Baseline: none
Execution: not run · JUnit: none · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
The test runner could not be detected.
Derived by declaration name, from the diff (no baseline run).
No declaration pattern applies to tests/validation/bootstrap_mcp_result_schema_tests.sh; those files yield nothing.
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 201205bd4e786c7f152d8f99006b37da7da888c7.
268 files: 191 code · 77 docs. Click to expand.
diff --git a/Makefile b/Makefileindex 7d1ce83..8401a14 100644--- a/Makefile+++ b/Makefile@@ -5,8 +5,8 @@ SHELL = /bin/bash SCHEME = Transit PROJECT = Transit/Transit.xcodeproj-BUNDLE_ID = me.nore.ig.Transit CONFIG ?= Debug+BUNDLE_ID = $(if $(filter Debug,$(CONFIG)),me.nore.ig.Transit.development,me.nore.ig.Transit) # Pipe through xcbeautify if available, otherwise raw output XCBEAUTIFY := $(shell command -v xcbeautify 2>/dev/null)@@ -72,7 +72,7 @@ test-create-task-project-schema-guard: python3 tests/validation/create_task_project_schema_guard.py .PHONY: lint-lint: test-model-container-ownership-guard test-create-task-project-schema-guard+lint: test-model-container-ownership-guard test-create-task-project-schema-guard test-development-configuration swiftlint lint --strict --cache-path $(SWIFTLINT_CACHE) .PHONY: lint-fix@@ -146,6 +146,50 @@ build: build-ios build-macos # 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++# These standalone executables never launch Transit. Runtime children use a+# network-denying sandbox and synthetic stores confined to DerivedData/tmp.+.PHONY: test-development-isolation+test-development-isolation: prepare-cache-dirs test-development-configuration+ xcrun swiftc -parse-as-library -module-cache-path $(CLANG_MODULE_CACHE) \+ Transit/Transit/Services/AppPersistencePolicy.swift tests/development-isolation/PolicyProbe.swift \+ -o $(DERIVED_DATA)/persistence-policy-probe+ xcrun swiftc -parse-as-library -default-isolation MainActor -module-cache-path $(CLANG_MODULE_CACHE) \+ $(MCP_PROBE_MODELS) Transit/Transit/MCP/Writes/{MCPCanonicalJSON,MCPRecordRevision}.swift \+ Transit/Transit/Services/{AppPersistencePolicy,IsolatedPersistenceConfiguration}.swift \+ tests/development-isolation/MigrationProbe.swift \+ -o $(DERIVED_DATA)/isolated-migration-probe+ xcrun swiftc -parse-as-library -default-isolation MainActor -module-cache-path $(CLANG_MODULE_CACHE) \+ $(MCP_PROBE_MODELS) \+ Transit/Transit/Services/{AppPersistencePolicy,AppDisplayIDAllocators,DisplayIDAllocator,CloudKitCounterStore,UsedDisplayIDs,DisplayIDRecordLookup,ModelFetching}.swift \+ tests/development-isolation/BootstrapProbe.swift -o $(DERIVED_DATA)/isolated-bootstrap-probe+ python3 tests/development-isolation/run.py $(DERIVED_DATA)/persistence-policy-probe \+ $(DERIVED_DATA)/isolated-migration-probe $(DERIVED_DATA)/isolated-bootstrap-probe \+ $(DERIVED_DATA)/isolation-verification.json++.PHONY: test-development-configuration+test-development-configuration:+ python3 tests/development-isolation/configuration_guard.py++.PHONY: build-development-macos+build-development-macos: prepare-cache-dirs+ $(PIPEFAIL) $(XCODEBUILD_ENV) xcodebuild build \+ -project $(PROJECT) -scheme TransitDevelopment -configuration Debug \+ -destination 'platform=macOS' -jobs 2 \+ -disableAutomaticPackageResolution -onlyUsePackageVersionsFromResolvedFile \+ $(XCODEBUILD_CACHE_FLAGS) CODE_SIGNING_ALLOWED=NO $(PIPE_PRETTY)++# Single opt-in host fixture; inspect the signed artifact before launching it.+SMOKE_DERIVED_DATA ?= $(DERIVED_DATA)/isolation-host+.PHONY: test-isolated-host-smoke+test-isolated-host-smoke: prepare-cache-dirs test-development-configuration+ $(PIPEFAIL) $(XCODEBUILD_ENV) xcodebuild build-for-testing \+ -project $(PROJECT) -scheme TransitIsolationSmoke -configuration Debug \+ -destination 'platform=macOS,arch=arm64' -jobs 2 -parallel-testing-enabled NO \+ -disableAutomaticPackageResolution -onlyUsePackageVersionsFromResolvedFile \+ -derivedDataPath $(SMOKE_DERIVED_DATA) CODE_SIGN_IDENTITY=- CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM= $(PIPE_PRETTY)+ python3 tests/development-isolation/host_smoke.py $(SMOKE_DERIVED_DATA)/Build/Products+ .PHONY: test-mcp-write-guards test-mcp-write-guards: prepare-cache-dirs xcrun swiftc $(MCP_PROBE_SWIFT_FLAGS) -parse-as-library -default-isolation MainActor -module-cache-path $(CLANG_MODULE_CACHE) \
diff --git a/Transit/Configuration/Development.entitlements b/Transit/Configuration/Development.entitlementsnew file mode 100644index 0000000..73c96ac--- /dev/null+++ b/Transit/Configuration/Development.entitlements@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.security.network.server</key>+ <true/>+ <key>com.apple.security.network.client</key>+ <true/>+</dict>+</plist>
diff --git a/Transit/Configuration/DevelopmentInfo.plist b/Transit/Configuration/DevelopmentInfo.plistnew file mode 100644index 0000000..bcaee96--- /dev/null+++ b/Transit/Configuration/DevelopmentInfo.plist@@ -0,0 +1,17 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>UIApplicationShortcutItems</key>+ <array>+ <dict>+ <key>UIApplicationShortcutItemType</key>+ <string>com.arjen.transit.new-task</string>+ <key>UIApplicationShortcutItemTitle</key>+ <string>New Task</string>+ <key>UIApplicationShortcutItemIconSymbolName</key>+ <string>plus.square</string>+ </dict>+ </array>+</dict>+</plist>
diff --git a/Transit/Transit.xcodeproj/project.pbxproj b/Transit/Transit.xcodeproj/project.pbxprojindex e9d10d3..47fa36d 100644--- a/Transit/Transit.xcodeproj/project.pbxproj+++ b/Transit/Transit.xcodeproj/project.pbxproj@@ -8,6 +8,7 @@ /* Begin PBXBuildFile section */ 964919FC2F4B2C8D002D5489 /* Hummingbird in Frameworks */ = {isa = PBXBuildFile; productRef = A1MCP00022F5A000000000002 /* Hummingbird */; };+ DE710000000000000000000A /* Hummingbird in Frameworks */ = {isa = PBXBuildFile; productRef = A1MCP00022F5A000000000002 /* Hummingbird */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */@@ -25,12 +26,27 @@ remoteGlobalIDString = D48D3EA82F3A033000139F85; remoteInfo = Transit; };+ DE720000000000000000000A /* Isolation smoke proxy */ = {+ isa = PBXContainerItemProxy;+ containerPortal = D48D3EA12F3A033000139F85;+ proxyType = 1;+ remoteGlobalIDString = DE7100000000000000000001;+ remoteInfo = TransitDevelopment;+ }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ D48D3EA92F3A033000139F85 /* Transit.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Transit.app; sourceTree = BUILT_PRODUCTS_DIR; }; D48D3EBA2F3A033100139F85 /* TransitTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = TransitTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; D48D3EC42F3A033100139F85 /* TransitUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = TransitUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };+ DE7100000000000000000002 /* Transit.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = TransitDevelopment.app; sourceTree = BUILT_PRODUCTS_DIR; };+ DE7200000000000000000002 /* Isolation smoke product */ = {+ isa = PBXFileReference;+ explicitFileType = wrapper.cfbundle;+ includeInIndex = 0;+ path = TransitIsolationSmokeTests.xctest;+ sourceTree = BUILT_PRODUCTS_DIR;+ }; /* End PBXFileReference section */ /* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */@@ -41,6 +57,13 @@ ); target = D48D3EA82F3A033000139F85 /* Transit */; };+ DE7100000000000000000009 /* Exceptions for "Transit" folder in "Transit" target */ = {+ isa = PBXFileSystemSynchronizedBuildFileExceptionSet;+ membershipExceptions = (+ Info.plist,+ );+ target = DE7100000000000000000001 /* Transit */;+ }; /* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ /* Begin PBXFileSystemSynchronizedRootGroup section */@@ -48,6 +71,7 @@ isa = PBXFileSystemSynchronizedRootGroup; exceptions = ( D48D3ECC2F3A033100139F85 /* Exceptions for "Transit" folder in "Transit" target */,+ DE7100000000000000000009 /* Development source exceptions */, ); path = Transit; sourceTree = "<group>";@@ -62,6 +86,11 @@ path = TransitUITests; sourceTree = "<group>"; };+ DE7200000000000000000003 /* Isolation smoke group */ = {+ isa = PBXFileSystemSynchronizedRootGroup;+ path = TransitIsolationSmokeTests;+ sourceTree = "<group>";+ }; /* End PBXFileSystemSynchronizedRootGroup section */ /* Begin PBXFrameworksBuildPhase section */@@ -87,6 +116,21 @@ ); runOnlyForDeploymentPostprocessing = 0; };+ DE7100000000000000000004 /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ DE710000000000000000000A /* Hummingbird in Frameworks */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ DE7200000000000000000005 /* Isolation smoke frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */@@ -95,6 +139,7 @@ children = ( D48D3EAB2F3A033000139F85 /* Transit */, D48D3EBD2F3A033100139F85 /* TransitTests */,+ DE7200000000000000000003 /* TransitIsolationSmokeTests */, D48D3EC72F3A033100139F85 /* TransitUITests */, D48D3EAA2F3A033000139F85 /* Products */, );@@ -104,7 +149,9 @@ isa = PBXGroup; children = ( D48D3EA92F3A033000139F85 /* Transit.app */,+ DE7100000000000000000002 /* TransitDevelopment.app */, D48D3EBA2F3A033100139F85 /* TransitTests.xctest */,+ DE7200000000000000000002 /* TransitIsolationSmokeTests.xctest */, D48D3EC42F3A033100139F85 /* TransitUITests.xctest */, ); name = Products;@@ -182,6 +229,50 @@ productReference = D48D3EC42F3A033100139F85 /* TransitUITests.xctest */; productType = "com.apple.product-type.bundle.ui-testing"; };+ DE7100000000000000000001 /* Transit */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = DE7100000000000000000006 /* Build configuration list for PBXNativeTarget "Transit" */;+ buildPhases = (+ DE7100000000000000000003 /* Sources */,+ DE7100000000000000000004 /* Frameworks */,+ DE7100000000000000000005 /* Resources */,+ );+ buildRules = (+ );+ dependencies = (+ );+ fileSystemSynchronizedGroups = (+ D48D3EAB2F3A033000139F85 /* Transit */,+ );+ name = TransitDevelopment;+ packageProductDependencies = (+ A1MCP00022F5A000000000002 /* Hummingbird */,+ );+ productName = TransitDevelopment;+ productReference = DE7100000000000000000002 /* Transit.app */;+ productType = "com.apple.product-type.application";+ };+ DE7200000000000000000001 /* Isolation smoke target */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = DE7200000000000000000007;+ buildPhases = (+ DE7200000000000000000004,+ DE7200000000000000000005,+ DE7200000000000000000006,+ );+ buildRules = (+ );+ dependencies = (+ DE720000000000000000000B,+ );+ fileSystemSynchronizedGroups = (+ DE7200000000000000000003,+ );+ name = TransitIsolationSmokeTests;+ productName = TransitIsolationSmokeTests;+ productReference = DE7200000000000000000002;+ productType = "com.apple.product-type.bundle.unit-test";+ }; /* End PBXNativeTarget section */ /* Begin PBXProject section */@@ -222,7 +313,9 @@ projectDirPath = ""; projectRoot = ""; targets = (+ DE7200000000000000000001 /* TransitIsolationSmokeTests */, D48D3EA82F3A033000139F85 /* Transit */,+ DE7100000000000000000001 /* TransitDevelopment */, D48D3EB92F3A033100139F85 /* TransitTests */, D48D3EC32F3A033100139F85 /* TransitUITests */, );@@ -251,6 +344,20 @@ ); runOnlyForDeploymentPostprocessing = 0; };+ DE7100000000000000000005 /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ DE7200000000000000000006 /* Isolation smoke resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */@@ -275,6 +382,20 @@ ); runOnlyForDeploymentPostprocessing = 0; };+ DE7100000000000000000003 /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ DE7200000000000000000004 /* Isolation smoke sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */@@ -288,6 +409,11 @@ target = D48D3EA82F3A033000139F85 /* Transit */; targetProxy = D48D3EC52F3A033100139F85 /* PBXContainerItemProxy */; };+ DE720000000000000000000B /* Isolation smoke dependency */ = {+ isa = PBXTargetDependency;+ target = DE7100000000000000000001;+ targetProxy = DE720000000000000000000A;+ }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */@@ -296,7 +422,7 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;- CODE_SIGN_ENTITLEMENTS = Transit/Transit.entitlements;+ CODE_SIGN_ENTITLEMENTS = Configuration/Development.entitlements; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1;@@ -306,8 +432,8 @@ ENABLE_PREVIEWS = YES; ENABLE_USER_SELECTED_FILES = readonly; GENERATE_INFOPLIST_FILE = YES;- INFOPLIST_FILE = Transit/Info.plist;- INFOPLIST_KEY_CFBundleDisplayName = Transit;+ INFOPLIST_FILE = Configuration/DevelopmentInfo.plist;+ INFOPLIST_KEY_CFBundleDisplayName = "Transit Development"; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity"; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES;@@ -324,10 +450,10 @@ "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 26.0; MARKETING_VERSION = 1.0;- PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.Transit;+ PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.Transit.development; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = "";- REGISTER_APP_GROUPS = YES;+ REGISTER_APP_GROUPS = NO; SDKROOT = auto; STRING_CATALOG_GENERATE_SYMBOLS = YES; SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx xros xrsimulator";@@ -518,7 +644,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 26.2; MACOSX_DEPLOYMENT_TARGET = 26.2; MARKETING_VERSION = 1.0;- PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.TransitTests;+ PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.Transit.development.tests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = auto; STRING_CATALOG_GENERATE_SYMBOLS = NO;@@ -569,7 +695,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 26.2; MACOSX_DEPLOYMENT_TARGET = 26.2; MARKETING_VERSION = 1.0;- PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.TransitUITests;+ PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.Transit.development.uitests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = auto; STRING_CATALOG_GENERATE_SYMBOLS = NO;@@ -609,6 +735,162 @@ }; name = Release; };+ DE7100000000000000000007 /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) TRANSIT_DEVELOPMENT";+ PRODUCT_MODULE_NAME = Transit;+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_ENTITLEMENTS = Configuration/Development.entitlements;+ CODE_SIGN_IDENTITY = "Apple Development";+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = V24684SCZN;+ ENABLE_APP_SANDBOX = YES;+ ENABLE_HARDENED_RUNTIME = YES;+ ENABLE_PREVIEWS = YES;+ ENABLE_USER_SELECTED_FILES = readonly;+ GENERATE_INFOPLIST_FILE = YES;+ INFOPLIST_FILE = Configuration/DevelopmentInfo.plist;+ INFOPLIST_KEY_CFBundleDisplayName = "Transit Development";+ INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity";+ "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;+ "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES;+ "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES;+ "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphonesimulator*]" = YES;+ "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphoneos*]" = YES;+ "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphonesimulator*]" = YES;+ "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphoneos*]" = UIStatusBarStyleDefault;+ "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault;+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ IPHONEOS_DEPLOYMENT_TARGET = 26.0;+ LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";+ "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks";+ MACOSX_DEPLOYMENT_TARGET = 26.0;+ MARKETING_VERSION = 1.0;+ PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.Transit.development;+ PRODUCT_NAME = "$(TARGET_NAME)";+ PROVISIONING_PROFILE_SPECIFIER = "";+ REGISTER_APP_GROUPS = NO;+ SDKROOT = auto;+ STRING_CATALOG_GENERATE_SYMBOLS = YES;+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx xros xrsimulator";+ SWIFT_APPROACHABLE_CONCURRENCY = YES;+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;+ SWIFT_EMIT_LOC_STRINGS = YES;+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+ SWIFT_VERSION = 6.0;+ TARGETED_DEVICE_FAMILY = "1,2,7";+ XROS_DEPLOYMENT_TARGET = 26.0;+ };+ name = Debug;+ };+ DE7100000000000000000008 /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) TRANSIT_DEVELOPMENT";+ PRODUCT_MODULE_NAME = Transit;+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_ENTITLEMENTS = Configuration/Development.entitlements;+ CODE_SIGN_IDENTITY = "Apple Development";+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = V24684SCZN;+ ENABLE_APP_SANDBOX = YES;+ ENABLE_HARDENED_RUNTIME = YES;+ ENABLE_PREVIEWS = YES;+ ENABLE_USER_SELECTED_FILES = readonly;+ GENERATE_INFOPLIST_FILE = YES;+ INFOPLIST_FILE = Configuration/DevelopmentInfo.plist;+ INFOPLIST_KEY_CFBundleDisplayName = "Transit Development";+ INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity";+ "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;+ "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES;+ "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES;+ "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphonesimulator*]" = YES;+ "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphoneos*]" = YES;+ "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphonesimulator*]" = YES;+ "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphoneos*]" = UIStatusBarStyleDefault;+ "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault;+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ IPHONEOS_DEPLOYMENT_TARGET = 26.0;+ LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";+ "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks";+ MACOSX_DEPLOYMENT_TARGET = 26.0;+ MARKETING_VERSION = 1.0;+ PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.Transit.development;+ PRODUCT_NAME = "$(TARGET_NAME)";+ PROVISIONING_PROFILE_SPECIFIER = "";+ REGISTER_APP_GROUPS = NO;+ SDKROOT = auto;+ STRING_CATALOG_GENERATE_SYMBOLS = YES;+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx xros xrsimulator";+ SWIFT_APPROACHABLE_CONCURRENCY = YES;+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;+ SWIFT_EMIT_LOC_STRINGS = YES;+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+ SWIFT_VERSION = 6.0;+ TARGETED_DEVICE_FAMILY = "1,2,7";+ XROS_DEPLOYMENT_TARGET = 26.0;+ };+ name = Release;+ };+ DE7200000000000000000008 /* Isolation smoke debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ BUNDLE_LOADER = "$(TEST_HOST)";+ MARKETING_VERSION = 1.0;+ DEVELOPMENT_TEAM = V24684SCZN;+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx xros xrsimulator";+ PRODUCT_BUNDLE_IDENTIFIER = "me.nore.ig.Transit.development.smoke-tests";+ CURRENT_PROJECT_VERSION = 1;+ STRING_CATALOG_GENERATE_SYMBOLS = NO;+ MACOSX_DEPLOYMENT_TARGET = 26.2;+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/TransitDevelopment.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/TransitDevelopment";+ TARGETED_DEVICE_FAMILY = "1,2,7";+ CODE_SIGN_STYLE = Automatic;+ XROS_DEPLOYMENT_TARGET = 26.2;+ SDKROOT = auto;+ SWIFT_VERSION = 6.0;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_APPROACHABLE_CONCURRENCY = YES;+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 26.2;+ SWIFT_EMIT_LOC_STRINGS = NO;+ GENERATE_INFOPLIST_FILE = YES;+ };+ name = Debug;+ };+ DE7200000000000000000009 /* Isolation smoke release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ BUNDLE_LOADER = "$(TEST_HOST)";+ MARKETING_VERSION = 1.0;+ DEVELOPMENT_TEAM = V24684SCZN;+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx xros xrsimulator";+ PRODUCT_BUNDLE_IDENTIFIER = "me.nore.ig.Transit.development.smoke-tests";+ CURRENT_PROJECT_VERSION = 1;+ STRING_CATALOG_GENERATE_SYMBOLS = NO;+ MACOSX_DEPLOYMENT_TARGET = 26.2;+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/TransitDevelopment.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/TransitDevelopment";+ TARGETED_DEVICE_FAMILY = "1,2,7";+ CODE_SIGN_STYLE = Automatic;+ XROS_DEPLOYMENT_TARGET = 26.2;+ SDKROOT = auto;+ SWIFT_VERSION = 6.0;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_APPROACHABLE_CONCURRENCY = YES;+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 26.2;+ SWIFT_EMIT_LOC_STRINGS = NO;+ GENERATE_INFOPLIST_FILE = YES;+ };+ name = Release;+ }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */@@ -648,6 +930,24 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };+ DE7100000000000000000006 /* Build configuration list for PBXNativeTarget "Transit" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ DE7100000000000000000007 /* Debug */,+ DE7100000000000000000008 /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Debug;+ };+ DE7200000000000000000007 /* Isolation smoke configlist */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ DE7200000000000000000008,+ DE7200000000000000000009,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Debug;+ }; /* End XCConfigurationList section */ /* Begin XCRemoteSwiftPackageReference section */
diff --git a/Transit/Transit.xcodeproj/xcshareddata/xcschemes/Transit.xcscheme b/Transit/Transit.xcodeproj/xcshareddata/xcschemes/Transit.xcschemenew file mode 100644index 0000000..3956c78--- /dev/null+++ b/Transit/Transit.xcodeproj/xcshareddata/xcschemes/Transit.xcscheme@@ -0,0 +1,34 @@+<Scheme LastUpgradeVersion="2620" version="1.3">+ <BuildAction parallelizeBuildables="NO" buildImplicitDependencies="YES">+ <BuildActionEntries>+ <BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES">+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="D48D3EA82F3A033000139F85" BuildableName="Transit.app" BlueprintName="Transit" ReferencedContainer="container:Transit.xcodeproj" />+ </BuildActionEntry>+ </BuildActionEntries>+ </BuildAction>+ <TestAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.IDEFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv="NO">+ <Testables>+ <TestableReference skipped="NO" parallelizable="NO">+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="D48D3EB92F3A033100139F85" BuildableName="TransitTests.xctest" BlueprintName="TransitTests" ReferencedContainer="container:Transit.xcodeproj" />+ </TestableReference>+ <TestableReference skipped="NO" parallelizable="NO">+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="D48D3EC32F3A033100139F85" BuildableName="TransitUITests.xctest" BlueprintName="TransitUITests" ReferencedContainer="container:Transit.xcodeproj" />+ </TestableReference>+ </Testables>+ <EnvironmentVariables>+ <EnvironmentVariable key="TRANSIT_PERSISTENCE_MODE" value="unit-test" isEnabled="YES" />+ </EnvironmentVariables>+ </TestAction>+ <LaunchAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.IDEFoundation.Launcher.LLDB" launchStyle="0" useCustomWorkingDirectory="NO" ignoresPersistentStateOnLaunch="NO" debugDocumentVersioning="YES" debugServiceExtension="internal" allowLocationSimulation="YES">+ <BuildableProductRunnable runnableDebuggingMode="0">+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="D48D3EA82F3A033000139F85" BuildableName="Transit.app" BlueprintName="Transit" ReferencedContainer="container:Transit.xcodeproj" />+ </BuildableProductRunnable>+ </LaunchAction>+ <ProfileAction buildConfiguration="Release" shouldUseLaunchSchemeArgsEnv="YES" savedToolIdentifier="" useCustomWorkingDirectory="NO" debugDocumentVersioning="YES">+ <BuildableProductRunnable runnableDebuggingMode="0">+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="D48D3EA82F3A033000139F85" BuildableName="Transit.app" BlueprintName="Transit" ReferencedContainer="container:Transit.xcodeproj" />+ </BuildableProductRunnable>+ </ProfileAction>+ <AnalyzeAction buildConfiguration="Debug" />+ <ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES" />+</Scheme>
diff --git a/Transit/Transit.xcodeproj/xcshareddata/xcschemes/TransitDevelopment.xcscheme b/Transit/Transit.xcodeproj/xcshareddata/xcschemes/TransitDevelopment.xcschemenew file mode 100644index 0000000..7620e49--- /dev/null+++ b/Transit/Transit.xcodeproj/xcshareddata/xcschemes/TransitDevelopment.xcscheme@@ -0,0 +1,24 @@+<Scheme LastUpgradeVersion="2620" version="1.3">+ <BuildAction parallelizeBuildables="NO" buildImplicitDependencies="YES">+ <BuildActionEntries>+ <BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES">+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="DE7100000000000000000001" BuildableName="TransitDevelopment.app" BlueprintName="TransitDevelopment" ReferencedContainer="container:Transit.xcodeproj" />+ </BuildActionEntry>+ </BuildActionEntries>+ </BuildAction>+ <TestAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.IDEFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv="NO">+ <Testables />+ </TestAction>+ <LaunchAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.IDEFoundation.Launcher.LLDB" launchStyle="0" useCustomWorkingDirectory="NO" ignoresPersistentStateOnLaunch="NO" debugDocumentVersioning="YES" debugServiceExtension="internal" allowLocationSimulation="YES">+ <BuildableProductRunnable runnableDebuggingMode="0">+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="DE7100000000000000000001" BuildableName="TransitDevelopment.app" BlueprintName="TransitDevelopment" ReferencedContainer="container:Transit.xcodeproj" />+ </BuildableProductRunnable>+ </LaunchAction>+ <ProfileAction buildConfiguration="Release" shouldUseLaunchSchemeArgsEnv="YES" savedToolIdentifier="" useCustomWorkingDirectory="NO" debugDocumentVersioning="YES">+ <BuildableProductRunnable runnableDebuggingMode="0">+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="DE7100000000000000000001" BuildableName="TransitDevelopment.app" BlueprintName="TransitDevelopment" ReferencedContainer="container:Transit.xcodeproj" />+ </BuildableProductRunnable>+ </ProfileAction>+ <AnalyzeAction buildConfiguration="Debug" />+ <ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES" />+</Scheme>
diff --git a/Transit/Transit.xcodeproj/xcshareddata/xcschemes/TransitIsolationSmoke.xcscheme b/Transit/Transit.xcodeproj/xcshareddata/xcschemes/TransitIsolationSmoke.xcschemenew file mode 100644index 0000000..1b5003f--- /dev/null+++ b/Transit/Transit.xcodeproj/xcshareddata/xcschemes/TransitIsolationSmoke.xcscheme@@ -0,0 +1,31 @@+<Scheme LastUpgradeVersion="2620" version="1.3">+ <BuildAction parallelizeBuildables="NO" buildImplicitDependencies="YES">+ <BuildActionEntries>+ <BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES">+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="DE7100000000000000000001" BuildableName="TransitDevelopment.app" BlueprintName="TransitDevelopment" ReferencedContainer="container:Transit.xcodeproj" />+ </BuildActionEntry>+ </BuildActionEntries>+ </BuildAction>+ <TestAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.IDEFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv="NO">+ <Testables>+ <TestableReference skipped="NO" parallelizable="NO">+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="DE7200000000000000000001" BuildableName="TransitIsolationSmokeTests.xctest" BlueprintName="TransitIsolationSmokeTests" ReferencedContainer="container:Transit.xcodeproj" />+ </TestableReference>+ </Testables>+ <EnvironmentVariables>+ <EnvironmentVariable key="TRANSIT_PERSISTENCE_MODE" value="unit-test" isEnabled="YES" />+ </EnvironmentVariables>+ </TestAction>+ <LaunchAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.IDEFoundation.Launcher.LLDB" launchStyle="0" useCustomWorkingDirectory="NO" ignoresPersistentStateOnLaunch="NO" debugDocumentVersioning="YES" debugServiceExtension="internal" allowLocationSimulation="YES">+ <BuildableProductRunnable runnableDebuggingMode="0">+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="DE7100000000000000000001" BuildableName="TransitDevelopment.app" BlueprintName="TransitDevelopment" ReferencedContainer="container:Transit.xcodeproj" />+ </BuildableProductRunnable>+ </LaunchAction>+ <ProfileAction buildConfiguration="Release" shouldUseLaunchSchemeArgsEnv="YES" savedToolIdentifier="" useCustomWorkingDirectory="NO" debugDocumentVersioning="YES">+ <BuildableProductRunnable runnableDebuggingMode="0">+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="DE7100000000000000000001" BuildableName="TransitDevelopment.app" BlueprintName="TransitDevelopment" ReferencedContainer="container:Transit.xcodeproj" />+ </BuildableProductRunnable>+ </ProfileAction>+ <AnalyzeAction buildConfiguration="Debug" />+ <ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES" />+</Scheme>
diff --git a/Transit/Transit/MCP/MCPPortfolioCaptureCharge.swift b/Transit/Transit/MCP/MCPPortfolioCaptureCharge.swiftnew file mode 100644index 0000000..bf24ef6--- /dev/null+++ b/Transit/Transit/MCP/MCPPortfolioCaptureCharge.swift@@ -0,0 +1,96 @@+#if os(macOS)+import Foundation++/// Logical encoded backing-view bytes, including typed identity/activity evidence and opaque metadata.+/// This is a retention charge, not a heap-memory estimate.+nonisolated enum MCPPortfolioCaptureCharge {+ static func bytes(_ capsule: MCPPreparedReadCapture, operation: MCPReadOperation) throws -> Int {+ let view = capsule.view+ var scope: [String: Any] = ["kind": "wholePortfolio"]+ if case .projects(let keys) = view.captureScope { scope = ["kind": "projects", "keys": keys.map(key)] }+ let duration = view.createdAt.duration(to: view.retentionDeadline).components+ var count = try MCPPortfolioReadEncoding.encode([+ "scope": scope, "completeness": "completePortfolio", "createdAtOffset": 0,+ "retentionSeconds": duration.seconds, "retentionAttoseconds": duration.attoseconds,+ "projects": [], "tasks": [], "milestones": [], "comments": [], "frozenMetadata": NSNull()+ ]).count+ try add(capsule.frozenMetadataBytes.count, to: &count)+ try records(view.projects, operation: operation, count: &count, encode: project)+ 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)+ return count+ }++ private static func add(_ bytes: Int, to count: inout Int) throws {+ let (sum, overflow) = count.addingReportingOverflow(bytes)+ guard !overflow, sum <= MCPPortfolioReadEncoding.byteLimit else { throw PublicationRejection.capacity }+ count = sum+ }++ private static func records<Record>(+ _ values: [Record], operation: MCPReadOperation, count: inout Int,+ encode: (Record) -> [String: Any]+ ) throws {+ // Each array's syntax and element separators are charged alongside its records.+ try add(2 + values.count, to: &count)+ for (position, value) in values.enumerated() {+ if position.isMultiple(of: 256) { try MCPPortfolioReadEncoding.check(operation) }+ try add(MCPPortfolioReadEncoding.encode(encode(value)).count, to: &count)+ }+ }++ private static func key(_ value: LocalRecordKey) -> String { value.encodedIdentifier.base64EncodedString() }+ private static func optionalKey(_ value: LocalRecordKey?) -> Any { value.map(key) as Any? ?? NSNull() }+ private static func optionalID(_ value: UUID?) -> Any { value.map(\.uuidString) as Any? ?? NSNull() }+ private static func optionalBytes(_ value: Data?) -> Any { value?.base64EncodedString() as Any? ?? NSNull() }+ private static func optionalDate(_ value: Date?) -> Any {+ value.map(\.timeIntervalSinceReferenceDate) as Any? ?? NSNull()+ }++ private static func project(_ value: ReadProject) -> [String: Any] {+ ["physicalKey": key(value.physicalKey), "id": value.id.uuidString, "name": value.name,+ "description": value.projectDescription, "gitRepo": value.gitRepo as Any? ?? NSNull(),+ "colorHex": value.colorHex, "taskKeys": value.taskKeys.map(key), "milestoneKeys": value.milestoneKeys.map(key),+ "selectedRecordJSON": value.selectedRecordJSON.base64EncodedString()]+ }++ private static func task(_ value: ReadTask) -> [String: Any] {+ ["physicalKey": key(value.physicalKey), "id": value.id.uuidString,+ "displayId": value.permanentDisplayId as Any? ?? NSNull(), "name": value.name,+ "description": value.taskDescription as Any? ?? NSNull(),+ "projectKey": optionalKey(value.projectKey), "milestoneKey": optionalKey(value.milestoneKey),+ "storedProjectID": optionalID(value.storedProjectID), "storedMilestoneID": optionalID(value.storedMilestoneID),+ "rawStatus": value.rawStatus, "effectiveStatus": value.effectiveStatus,+ "rawType": value.rawType, "effectiveType": value.effectiveType,+ "rawPriority": value.rawPriority, "effectivePriority": value.effectivePriority,+ "metadata": value.metadata, "metadataJSON": value.metadataJSON as Any? ?? NSNull(),+ "creationDate": value.creationDate.timeIntervalSinceReferenceDate,+ "lastStatusChangeDate": value.lastStatusChangeDate.timeIntervalSinceReferenceDate,+ "completionDate": optionalDate(value.completionDate), "commentKeys": value.commentKeys.map(key),+ "selectedRecordJSON": value.selectedRecordJSON.base64EncodedString(),+ "revision": value.revision as Any? ?? NSNull(),+ "fullRecordWithoutCommentsJSON": optionalBytes(value.fullRecordWithoutCommentsJSON),+ "requestedCommentRecordsJSON": optionalBytes(value.requestedCommentRecordsJSON)]+ }++ private static func milestone(_ value: ReadMilestone) -> [String: Any] {+ ["physicalKey": key(value.physicalKey), "id": value.id.uuidString,+ "displayId": value.permanentDisplayId as Any? ?? NSNull(), "name": value.name,+ "description": value.milestoneDescription as Any? ?? NSNull(), "projectKey": optionalKey(value.projectKey),+ "storedProjectID": optionalID(value.storedProjectID), "rawStatus": value.rawStatus,+ "effectiveStatus": value.effectiveStatus, "creationDate": value.creationDate.timeIntervalSinceReferenceDate,+ "lastStatusChangeDate": value.lastStatusChangeDate.timeIntervalSinceReferenceDate,+ "completionDate": optionalDate(value.completionDate), "taskKeys": value.taskKeys.map(key),+ "selectedRecordJSON": value.selectedRecordJSON.base64EncodedString()]+ }++ private static func comment(_ value: ReadCommentEvidence) -> [String: Any] {+ ["physicalKey": key(value.physicalKey), "id": value.id.uuidString, "taskKey": optionalKey(value.taskKey),+ "storedTaskID": optionalID(value.storedTaskID),+ "creationDate": value.creationDate.timeIntervalSinceReferenceDate,+ "content": value.content, "authorName": value.authorName, "isAgent": value.isAgent,+ "selectedRecordJSON": value.selectedRecordJSON.base64EncodedString()]+ }+}+#endif
diff --git a/Transit/Transit/MCP/MCPPortfolioProjection.swift b/Transit/Transit/MCP/MCPPortfolioProjection.swiftnew file mode 100644index 0000000..ce831df--- /dev/null+++ b/Transit/Transit/MCP/MCPPortfolioProjection.swift@@ -0,0 +1,159 @@+#if os(macOS)+import Foundation++/// Private page plan; the shared response gate stages its continuation bytes before publication.+nonisolated struct EncodedSnapshotTaskPages: Sendable {+ let firstPage: Data+ let pages: [Data]+ let cursors: [String]+ let frozenMetadataBytes: Data+ let snapshotId: String+ let retentionDeadline: ContinuousClock.Instant+}++nonisolated enum MCPPortfolioProjection {+ private static let summaryKeys: Set<String> = [+ "taskId", "name", "status", "type", "priority", "lastStatusChangeDate",+ "displayId", "projectId", "projectName", "completionDate", "milestone"+ ]++ static func query(root: RetainedView, request: MCPSnapshotTaskQueryRequest) throws -> EncodedSnapshotTaskPages {+ try Task.checkCancellation()+ guard case .initial(let snapshotID, let detail, let limit, let projectID, let statuses) = request,+ root.capture.completeness == .completePortfolio, root.capture.captureScope != .selectedQuery else {+ throw MCPReusableSnapshotError.incompatible+ }+ guard snapshotID == root.capture.metadata.snapshotId else { throw MCPReusableSnapshotError.invalidSnapshot }+ guard (1...100).contains(limit),+ statuses.allSatisfy({ MCPSnapshotTaskQueryRequest.supportedStatuses.contains($0) }) else {+ throw MCPSnapshotTaskQueryError.invalidInput+ }+ let records = try selectedTasks(view: root.capture, projectID: projectID)+ let filtered = statuses.isEmpty ? records : records.filter { statuses.contains(effectiveStatus($0)) }+ let ordered = filtered.sorted {+ ($0.id.uuidString, $0.physicalKey.encodedIdentifier.base64EncodedString())+ < ($1.id.uuidString, $1.physicalKey.encodedIdentifier.base64EncodedString())+ }+ var rows: [[String: Any]] = []+ for (position, record) in ordered.enumerated() {+ if position.isMultiple(of: 256) { try Task.checkCancellation() }+ rows.append(try dictionary(task(record: record, detail: detail).json))+ }+ let encoded = try encodePages(rows, limit: limit, root: root)+ return EncodedSnapshotTaskPages(+ firstPage: encoded.pages[0], pages: Array(encoded.pages.dropFirst()), cursors: encoded.cursors,+ frozenMetadataBytes: root.frozenMetadataBytes, snapshotId: snapshotID,+ retentionDeadline: root.capture.retentionDeadline)+ }++ static func task(record: ReadTask, detail: SnapshotTaskDetail) throws -> EncodedTaskRecord {+ // Decode the retained canonical body; never mint an r1 from a derived status or hidden comments.+ guard let captured = record.fullRecordWithoutCommentsJSON, let revision = record.revision else {+ throw PortfolioSummaryError.incoherentCapture+ }+ var output = try dictionary(captured)+ if detail == .summary { output = output.filter { summaryKeys.contains($0.key) } }+ output.removeValue(forKey: "comments")+ output.removeValue(forKey: "commentKeys")+ output.removeValue(forKey: "storedStatus")+ let status = effectiveStatus(record)+ output["status"] = status+ if status != record.rawStatus { output["storedStatus"] = record.rawStatus }+ if detail == .full { output["revision"] = revision }+ return EncodedTaskRecord(json: try encode(output))+ }++ private static func effectiveStatus(_ task: ReadTask) -> String {+ MCPSnapshotTaskQueryRequest.supportedStatuses.contains(task.rawStatus) ? task.rawStatus : "idea"+ }++ private static func selectedTasks(view: CapturedReadView, projectID: UUID?) throws -> [ReadTask] {+ var projectKeys: Set<LocalRecordKey>+ switch view.captureScope {+ case .wholePortfolio: projectKeys = Set(view.projects.map(\.physicalKey))+ case .projects(let keys):+ projectKeys = Set(keys)+ guard !keys.isEmpty, projectKeys.count == keys.count,+ keys.allSatisfy({ key in view.projects.contains { $0.physicalKey == key } }) else {+ throw MCPReusableSnapshotError.incompatible+ }+ case .selectedQuery: throw MCPReusableSnapshotError.incompatible+ }+ if let projectID {+ let matching = view.projects.filter { $0.id == projectID }+ let permitted = matching.filter { projectKeys.contains($0.physicalKey) }+ guard !permitted.isEmpty else { throw MCPReusableSnapshotError.incompatible }+ guard matching.count == 1 else { throw PortfolioSummaryError.identityAmbiguity }+ projectKeys = Set(permitted.map(\.physicalKey))+ }+ let includeOrphans = view.captureScope == .wholePortfolio && projectID == nil+ let tasks = view.tasks.filter {+ includeOrphans || $0.projectKey.map { projectKeys.contains($0) } == true+ }+ let milestones = view.milestones.filter { $0.projectKey.map { projectKeys.contains($0) } == true }+ // Reuse T-2382 attribution rules before status filtering. Generic canonical capture+ // validation remains the shared provider's responsibility at handler admission.+ try PortfolioSummaryService.validateIdentities(+ view: view, projects: projectKeys, tasks: tasks, milestones: milestones)+ return tasks+ }++ private static func encodePages(_ rows: [[String: Any]], limit: Int, root: RetainedView) throws+ -> (pages: [Data], cursors: [String]) {+ let count = max(1, (rows.count + limit - 1) / limit)+ var allocated: Set<String> = [root.capture.metadata.snapshotId]+ let cursors = (0..<(count - 1)).map { _ -> String in+ var cursor = reusableCursor()+ while !allocated.insert(cursor).inserted { cursor = reusableCursor() }+ return cursor+ }+ let expiry = try expiryText(root)+ var pages: [Data] = []+ var byteCount = 0+ for position in 0..<count {+ try Task.checkCancellation()+ let start = position * limit+ let end = min(start + limit, rows.count)+ let next: Any = position < cursors.count ? cursors[position] : NSNull()+ let page = try encode(["results": Array(rows[start..<end]), "nextCursor": next, "expiresAt": expiry])+ byteCount += page.count+ guard byteCount <= 16 * 1024 * 1024 else { throw PublicationRejection.capacity }+ pages.append(page)+ }+ return (pages, cursors)+ }++ private static func reusableCursor() -> String {+ var bytes = UUID().uuid+ bytes.6 = (bytes.6 & 0x0F) | 0x80+ bytes.8 = (bytes.8 & 0x3F) | 0x80+ return UUID(uuid: bytes).uuidString+ }++ private static func expiryText(_ root: RetainedView) throws -> String {+ let formatter = ISO8601DateFormatter()+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ guard let capturedAt = formatter.date(from: root.capture.metadata.asOf) else {+ throw PortfolioSummaryError.incoherentCapture+ }+ let duration = root.capture.createdAt.duration(to: root.capture.retentionDeadline).components+ let seconds = Double(duration.seconds) + Double(duration.attoseconds) / 1e18+ return formatter.string(from: capturedAt.addingTimeInterval(seconds))+ }++ private static func dictionary(_ data: Data) throws -> [String: Any] {+ do {+ guard let result = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {+ throw MCPReadCaptureError.serializationFailure+ }+ return result+ } catch { throw MCPReadCaptureError.serializationFailure }+ }++ private static func encode(_ dictionary: [String: Any]) throws -> Data {+ do { return try JSONSerialization.data(withJSONObject: dictionary, options: [.sortedKeys]) } catch {+ throw MCPReadCaptureError.serializationFailure+ }+ }+}+#endif
diff --git a/Transit/Transit/MCP/MCPPortfolioReadEncoding.swift b/Transit/Transit/MCP/MCPPortfolioReadEncoding.swiftnew file mode 100644index 0000000..091a8b6--- /dev/null+++ b/Transit/Transit/MCP/MCPPortfolioReadEncoding.swift@@ -0,0 +1,179 @@+#if os(macOS)+import Foundation++/// Own value-only wire encoding. No live data, freshness assessment or publication occurs here.+nonisolated enum MCPPortfolioReadEncoding {+ static let byteLimit = 16 * 1024 * 1024++ static func check(_ operation: MCPReadOperation) throws {+ guard operation.shouldContinue(), !Task.isCancelled else {+ throw MCPTaskQueryError(code: "READ_TIMEOUT", message: "Read exceeded its original admission budget")+ }+ }++ static func publicationDeadline(_ operation: MCPReadOperation) throws -> ContinuousClock.Instant {+ try check(operation)+ // Sampling before remainingBudget produces a conservative original cutoff, not a restarted timer.+ let now = ContinuousClock.now+ let remaining = operation.remainingBudget()+ guard remaining > .zero else {+ throw MCPTaskQueryError(code: "READ_TIMEOUT", message: "Read exceeded its original admission budget")+ }+ return now.advanced(by: remaining)+ }++ static func instant(_ date: Date) -> String {+ let formatter = ISO8601DateFormatter()+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ return formatter.string(from: date)+ }++ static func expiry(_ view: CapturedReadView) throws -> String {+ let formatter = ISO8601DateFormatter()+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ guard let asOf = formatter.date(from: view.metadata.asOf) else { throw MCPReadCaptureError.incoherentCapture }+ let duration = view.createdAt.duration(to: view.retentionDeadline).components+ return instant(asOf.addingTimeInterval(Double(duration.seconds) + Double(duration.attoseconds) / 1e18))+ }++ static func encode(_ value: Any) throws -> Data {+ do { return try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]) } catch {+ throw MCPReadCaptureError.serializationFailure+ }+ }++ static func prepared(_ bytes: Data, metadata: Data) throws -> MCPPreparedToolRead {+ guard let text = String(data: bytes, encoding: .utf8) else { throw MCPReadCaptureError.serializationFailure }+ let prepared = try MCPPreparedToolRead(text: text, frozenMetadataBytes: metadata)+ guard prepared.encodedToolResult.count <= byteLimit else { throw PublicationRejection.capacity }+ return prepared+ }++ static func normalized(_ error: Error, cursor: Bool) throws -> MCPPreparedToolRead? {+ let code: String+ let message: String+ if let retained = retentionFault(error, cursor: cursor) {+ code = retained.code; message = retained.message+ } else {+ switch error {+ case MCPReusableSnapshotError.incompatible, MCPSnapshotTaskQueryError.incompatible:+ code = "SNAPSHOT_INCOMPATIBLE"; message = "Request is incompatible with the retained view"+ case PortfolioSummaryError.identityAmbiguity:+ code = "IDENTITY_AMBIGUITY"; message = "Captured identities are ambiguous in the requested scope"+ case PortfolioSummaryError.incoherentCapture: throw MCPReadCaptureError.incoherentCapture+ case CompletionWindowError.invalidInput, MCPSnapshotTaskQueryError.invalidInput:+ code = "INVALID_INPUT"; message = "Invalid captured-read arguments"+ case MCPSnapshotTaskQueryError.invalidCursor:+ code = "INVALID_CURSOR"; message = "Invalid reusable cursor"+ case let error as MCPPortfolioRequestError: code = error.code; message = error.message+ case let error as MCPTaskQueryError: code = error.code; message = error.message+ default: return nil+ }+ }+ guard let text = String(data: try encode(["error": ["code": code, "message": message]]), encoding: .utf8) else {+ throw MCPReadCaptureError.serializationFailure+ }+ return try MCPPreparedToolRead(text: text, isError: true)+ }++ private static func retentionFault(_ error: Error, cursor: Bool) -> (code: String, message: String)? {+ switch error {+ case PublicationRejection.capacity, MCPResultPreparationError.retentionCapacity:+ return ("QUERY_CAPACITY_EXCEEDED", "Captured read capacity exceeded")+ case PublicationRejection.busy: return ("READ_BUSY", "Read publication changed; retry the request")+ case PublicationRejection.expired:+ return (cursor ? "INVALID_CURSOR" : "INVALID_SNAPSHOT", "Retained view expired; start a new summary")+ case MCPReusableSnapshotError.invalidSnapshot:+ return ("INVALID_SNAPSHOT", "Unknown or expired snapshot; start a new summary")+ case MCPReusableSnapshotError.invalidCursor:+ return ("INVALID_CURSOR", "Unknown or expired cursor; start a new summary")+ default: return nil+ }+ }++ static func cursor() -> String {+ var bytes = UUID().uuid+ bytes.6 = (bytes.6 & 0x0F) | 0x80+ bytes.8 = (bytes.8 & 0x3F) | 0x80+ return UUID(uuid: bytes).uuidString+ }++ static func summaryPages(_ summary: PortfolioSummary, view: CapturedReadView, limit: Int,+ operation: MCPReadOperation) throws -> (pages: [Data], cursors: [String]) {+ guard (1...100).contains(limit) else { throw CompletionWindowError.invalidInput }+ let count = max(1, (summary.projects.count + limit - 1) / limit)+ var allocated: Set<String> = [view.metadata.snapshotId]+ let cursors = (0..<(count - 1)).map { _ -> String in+ var token = cursor()+ while !allocated.insert(token).inserted { token = cursor() }+ return token+ }+ let window = ["start": instant(summary.completionWindow.start), "end": instant(summary.completionWindow.end)]+ let expiresAt = try expiry(view)+ var pages: [Data] = []+ var byteCount = 0+ for position in 0..<count {+ try check(operation)+ let start = position * limit+ let end = min(start + limit, summary.projects.count)+ let next: Any = position < cursors.count ? cursors[position] : NSNull()+ let bytes = try encode([+ "projects": summary.projects[start..<end].map(project),+ "unresolvedProjects": breakdown(summary.unresolvedProjects),+ "diagnostics": summary.diagnostics.map(diagnostic), "completionWindow": window,+ "nextCursor": next, "expiresAt": expiresAt+ ])+ byteCount += bytes.count+ guard byteCount <= byteLimit else { throw PublicationRejection.capacity }+ pages.append(bytes)+ }+ return (pages, cursors)+ }+}++extension MCPPortfolioReadEncoding {+ nonisolated private static func counts(_ value: PortfolioStatusCounts) -> [String: Int] {+ ["idea": value.idea, "planning": value.planning, "spec": value.spec,+ "ready-for-implementation": value.readyForImplementation, "in-progress": value.inProgress,+ "ready-for-review": value.readyForReview, "done": value.done, "abandoned": value.abandoned]+ }+ nonisolated private static func recent(_ value: PortfolioRecentCompletions) -> [String: Int] {+ ["done": value.done, "abandoned": value.abandoned,+ "missingCompletionDateCount": value.missingCompletionDateCount]+ }+ nonisolated private static func breakdown(_ value: PortfolioTaskBreakdown) -> [String: Any] {+ ["countsByStatus": counts(value.countsByStatus), "totalTaskCount": value.totalTaskCount,+ "recentCompletions": recent(value.recentCompletions)]+ }+ nonisolated private static func diagnostic(_ value: PortfolioDiagnostic) -> [String: Any] {+ ["category": value.category, "affectedCount": value.affectedCount, "sampleComplete": value.sampleComplete,+ "samples": value.samples.map { sample in+ ["entityKind": sample.entityKind, "id": sample.id.uuidString,+ "displayId": sample.displayId as Any? ?? NSNull(),+ "discriminator": sample.discriminator as Any? ?? NSNull()] as [String: Any]+ }]+ }+ nonisolated private static func milestone(_ value: PortfolioMilestoneSummary) -> [String: Any] {+ ["milestoneId": value.milestoneId.uuidString, "displayId": value.displayId as Any? ?? NSNull(),+ "name": value.name, "rawStatus": value.rawStatus, "status": value.status, "invalidStatus": value.invalidStatus,+ "countsByStatus": counts(value.countsByStatus), "totalTaskCount": value.totalTaskCount,+ "recentCompletions": recent(value.recentCompletions)]+ }+ nonisolated private static func project(_ value: PortfolioProjectSummary) -> [String: Any] {+ let activity: Any+ if let evidence = value.lastRecordedActivity {+ activity = ["timestamp": instant(evidence.timestamp), "kind": evidence.kind.rawValue,+ "id": evidence.id.uuidString]+ } else { activity = NSNull() }+ return ["projectId": value.projectId.uuidString, "name": value.name,+ "countsByStatus": counts(value.countsByStatus), "totalTaskCount": value.totalTaskCount,+ "ideaCount": value.ideaCount, "inProgressCount": value.inProgressCount,+ "workflowTaskCount": value.workflowTaskCount, "nonterminalTaskCount": value.nonterminalTaskCount,+ "recentCompletions": recent(value.recentCompletions), "lastRecordedActivity": activity,+ "milestones": value.milestones.map(milestone),+ "unassignedMilestone": breakdown(value.unassignedMilestone),+ "invalidMilestoneAssociations": breakdown(value.invalidMilestoneAssociations),+ "diagnostics": value.diagnostics.map(diagnostic)]+ }+}+#endif
diff --git a/Transit/Transit/MCP/MCPPortfolioSummaryRequest.swift b/Transit/Transit/MCP/MCPPortfolioSummaryRequest.swiftnew file mode 100644index 0000000..2e2d0e0--- /dev/null+++ b/Transit/Transit/MCP/MCPPortfolioSummaryRequest.swift@@ -0,0 +1,123 @@+#if os(macOS)+import Foundation++nonisolated struct MCPPortfolioRequestError: Error, Sendable {+ let code: String+ let message: String++ static func invalid(_ message: String) -> Self { Self(code: "INVALID_INPUT", message: message) }+}++nonisolated enum MCPPortfolioSummaryRequest: Sendable {+ case initial(window: CompletionWindow, limit: Int, project: ReadProjectSelector?, policy: MCPReadPolicy)+ case replay(snapshotId: String)+ case continuation(cursor: String, policy: MCPReadPolicy?)++ @MainActor static func parse(_ arguments: [String: Any]) throws -> Self {+ if let raw = arguments["snapshotId"] {+ guard arguments.count == 1 else {+ throw MCPPortfolioRequestError.invalid("Summary replay requires snapshotId only")+ }+ guard let id = raw as? String, UUID(uuidString: id) != nil else {+ throw MCPPortfolioRequestError(+ code: "INVALID_SNAPSHOT", message: "Invalid snapshot; start a new summary")+ }+ return .replay(snapshotId: id)+ }+ if let raw = arguments["cursor"] {+ guard Set(arguments.keys).isSubset(of: ["cursor", "readPolicy"]) else {+ throw MCPPortfolioRequestError.invalid("Continuation permits only cursor and readPolicy")+ }+ guard let policy = MCPReadRefreshPolicy.parse(arguments["readPolicy"]) else {+ throw MCPPortfolioRequestError.invalid("Invalid readPolicy")+ }+ guard let cursor = raw as? String, UUID(uuidString: cursor) != nil else {+ throw MCPPortfolioRequestError(code: "INVALID_CURSOR", message: "Invalid cursor; start a new summary")+ }+ return .continuation(cursor: cursor, policy: arguments["readPolicy"] == nil ? nil : policy)+ }+ guard Set(arguments.keys).isSubset(of: ["start", "end", "limit", "projectId", "project", "readPolicy"]),+ let start = arguments["start"] as? String, let end = arguments["end"] as? String,+ let limit = IntentHelpers.parseIntValue(arguments["limit"]), (1...100).contains(limit),+ let policy = MCPReadRefreshPolicy.parse(arguments["readPolicy"]) else {+ throw MCPPortfolioRequestError.invalid(+ "Supply start, end and integer limit from 1 through 100; use supported fields")+ }+ guard arguments["projectId"] == nil || arguments["project"] == nil else {+ throw MCPPortfolioRequestError.invalid("Use only one project selector")+ }+ let selector = try projectSelector(arguments)+ let window: CompletionWindow+ do { window = try CompletionWindow.parse(start: start, end: end) } catch {+ throw MCPPortfolioRequestError.invalid(+ "Invalid completion window; supply explicit timezone timestamps with start before end")+ }+ return .initial(window: window, limit: limit, project: selector, policy: policy)+ }++ @MainActor private static func projectSelector(_ arguments: [String: Any]) throws -> ReadProjectSelector? {+ if let raw = arguments["projectId"] {+ guard let string = raw as? String, let id = UUID(uuidString: string) else {+ throw MCPPortfolioRequestError.invalid("projectId must be a UUID string")+ }+ return .id(id)+ }+ if let raw = arguments["project"] {+ guard let name = raw as? String, !ProjectNamePolicy.normalized(name).isEmpty else {+ throw MCPPortfolioRequestError.invalid("project must be a nonempty name")+ }+ // Resolution is exclusively the fenced capture provider's responsibility.+ return .name(name)+ }+ return nil+ }+}++extension CompletionWindow {+ nonisolated static func parse(start: String, end: String) throws -> Self {+ let startDate = try instant(start)+ let endDate = try instant(end)+ guard startDate < endDate else { throw CompletionWindowError.invalidInput }+ return Self(start: startDate, end: endDate)+ }++ nonisolated private static func instant(_ string: String) throws -> Date {+ let pattern = "^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})"+ + "(?:\\.([0-9]{1,3}))?(Z|[+-][0-9]{2}:[0-9]{2})$"+ let expression = try NSRegularExpression(pattern: pattern)+ let range = NSRange(string.startIndex..., in: string)+ guard let match = expression.firstMatch(in: string, range: range), match.range == range else {+ throw CompletionWindowError.invalidInput+ }+ func field(_ index: Int) -> String {+ guard let range = Range(match.range(at: index), in: string) else { return "" }+ return String(string[range])+ }+ let numbers = (1...6).compactMap { Int(field($0)) }+ guard numbers.count == 6, (1...9999).contains(numbers[0]), (1...12).contains(numbers[1]),+ (1...31).contains(numbers[2]), (0...23).contains(numbers[3]),+ (0...59).contains(numbers[4]), (0...59).contains(numbers[5]) else {+ throw CompletionWindowError.invalidInput+ }+ let zone = field(8)+ var offset = 0+ if zone != "Z" {+ let hours = Int(zone.dropFirst().prefix(2)) ?? 24+ let minutes = Int(zone.suffix(2)) ?? 60+ guard hours < 24, minutes < 60 else { throw CompletionWindowError.invalidInput }+ offset = (hours * 3600 + minutes * 60) * (zone.first == "-" ? -1 : 1)+ }+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(secondsFromGMT: 0)!+ let components = DateComponents(year: numbers[0], month: numbers[1], day: numbers[2],+ hour: numbers[3], minute: numbers[4], second: numbers[5])+ guard let date = calendar.date(from: components),+ calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date) == components else {+ throw CompletionWindowError.invalidInput+ }+ let fraction = field(7)+ let fractionalSeconds = fraction.isEmpty ? 0 : (Double("0.\(fraction)") ?? 0)+ return date.addingTimeInterval(fractionalSeconds - Double(offset))+ }+}+#endif
diff --git a/Transit/Transit/MCP/MCPPortfolioSummaryTypes.swift b/Transit/Transit/MCP/MCPPortfolioSummaryTypes.swiftnew file mode 100644index 0000000..dcba153--- /dev/null+++ b/Transit/Transit/MCP/MCPPortfolioSummaryTypes.swift@@ -0,0 +1,121 @@+#if os(macOS)+import Foundation++/// Service failures remain distinct from parser validation and diagnosed relationship corruption.+nonisolated enum PortfolioSummaryError: Error, Equatable {+ case identityAmbiguity+ case incoherentCapture+}++nonisolated enum CompletionWindowError: Error, Equatable {+ case invalidInput+}++/// Parsed instants. Strict wire parsing and UTC formatting are supplied by the window parser.+nonisolated struct CompletionWindow: Sendable, Equatable {+ let start: Date+ let end: Date+}++/// Stored independently of app model enums so value-only work can leave MainActor.+/// Values are populated by aggregation, not computed independently from live records.+nonisolated struct PortfolioStatusCounts: Sendable, Equatable {+ let idea: Int+ let planning: Int+ let spec: Int+ let readyForImplementation: Int+ let inProgress: Int+ let readyForReview: Int+ let done: Int+ let abandoned: Int+}++nonisolated struct PortfolioRecentCompletions: Sendable, Equatable {+ let done: Int+ let abandoned: Int+ let missingCompletionDateCount: Int+}++/// Also represents the unassigned, invalid-association and unresolved-project partitions.+nonisolated struct PortfolioTaskBreakdown: Sendable, Equatable {+ let countsByStatus: PortfolioStatusCounts+ let totalTaskCount: Int+ let recentCompletions: PortfolioRecentCompletions+}++nonisolated enum PortfolioActivityKind: String, Sendable {+ case taskCreation = "task_creation"+ case taskStatus = "task_status"+ case commentCreation = "comment_creation"+ case milestoneCreation = "milestone_creation"+ case milestoneStatus = "milestone_status"+}++nonisolated struct PortfolioActivityEvidence: Sendable, Equatable {+ let timestamp: Date+ let kind: PortfolioActivityKind+ let id: UUID+}++/// A discriminator is capture-local diagnostic evidence, never a new persistent identity.+nonisolated struct PortfolioIdentitySample: Sendable, Equatable {+ let entityKind: String+ let id: UUID+ let displayId: Int?+ let discriminator: String?+}++nonisolated struct PortfolioDiagnostic: Sendable, Equatable {+ let category: String+ let affectedCount: Int+ let samples: [PortfolioIdentitySample]+ let sampleComplete: Bool+}++nonisolated struct PortfolioMilestoneSummary: Sendable, Equatable {+ let milestoneId: UUID+ let displayId: Int?+ let name: String+ let rawStatus: String+ let status: String+ let invalidStatus: Bool+ let countsByStatus: PortfolioStatusCounts+ let totalTaskCount: Int+ let recentCompletions: PortfolioRecentCompletions+}++nonisolated struct PortfolioProjectSummary: Sendable, Equatable {+ let projectId: UUID+ let name: String+ let countsByStatus: PortfolioStatusCounts+ let totalTaskCount: Int+ let ideaCount: Int+ let inProgressCount: Int+ let workflowTaskCount: Int+ let nonterminalTaskCount: Int+ let recentCompletions: PortfolioRecentCompletions+ let lastRecordedActivity: PortfolioActivityEvidence?+ let milestones: [PortfolioMilestoneSummary]+ let unassignedMilestone: PortfolioTaskBreakdown+ let invalidMilestoneAssociations: PortfolioTaskBreakdown+ let diagnostics: [PortfolioDiagnostic]+}++/// Pure aggregation output. Shared read metadata and pagination belong to the enclosing result.+nonisolated struct PortfolioSummary: Sendable, Equatable {+ let projects: [PortfolioProjectSummary]+ let unresolvedProjects: PortfolioTaskBreakdown+ let diagnostics: [PortfolioDiagnostic]+ let completionWindow: CompletionWindow+}++nonisolated enum SnapshotTaskDetail: String, Sendable {+ case summary+ case full+}++/// Encoded from an immutable shared ReadTask; no live model is retained by projection.+nonisolated struct EncodedTaskRecord: Sendable, Equatable {+ let json: Data+}+#endif
diff --git a/Transit/Transit/MCP/MCPPortfolioToolDefinitions.swift b/Transit/Transit/MCP/MCPPortfolioToolDefinitions.swiftnew file mode 100644index 0000000..e7ea29b--- /dev/null+++ b/Transit/Transit/MCP/MCPPortfolioToolDefinitions.swift@@ -0,0 +1,185 @@+#if os(macOS)+import Foundation++/// Portfolio-owned descriptors; shared registration and dispatch remain the shared MCP owner's responsibility.+nonisolated enum MCPPortfolioToolDefinitions {+ static let queryProjectSummaries = MCPToolDefinition(+ name: "query_project_summaries",+ description: """+ Read saved project and milestone summaries from one coherent, reusable snapshot. Supply start, end and+ limit (1...100), optionally projectId or project (exclusive selectors). No selector includes the whole+ portfolio, including empty projects. Project names use normalized exact matching; ambiguity fails.+ Pending local edits are excluded. This does not guarantee that every remote change has been imported.++ countsByStatus contains all eight statuses, including zeros; totalTaskCount is their sum. ideaCount+ counts idea; inProgressCount counts only in-progress; workflowTaskCount counts planning, spec,+ ready-for-implementation, in-progress and ready-for-review; nonterminalTaskCount adds idea to workflow.+ These are recorded status counts, not inferred readiness or activity. Legacy get_projects.activeTaskCount+ continues to count all nonterminal tasks, including ideas. Unknown raw task statuses fall back to idea+ and are diagnosed. Project totals partition valid same-project milestone tasks, unassigned tasks and+ invalid milestone links. All captured milestones, including empty and terminal milestones, are included;+ unknown milestone statuses fall back to open and are diagnosed. Task counts do not infer milestone status.++ completionWindow is UTC [start,end): start is inclusive, end exclusive. Counts include currently done+ or abandoned tasks whose recorded completionDate lies in that window; they are not historical events.+ Terminal tasks missing completionDate are diagnosed and excluded from window counts. Nonterminal tasks+ are excluded even when a completionDate remains. Timestamps require seconds and an explicit Z or offset,+ with at most three fractional digits, valid calendar dates and start before end; no local/date-only values.++ lastRecordedActivity is the latest task creation/status change, comment creation or milestone creation/status+ change timestamp, with evidence kind and identity; ties use kind, UUID then physical identity. It is null+ without evidence. Arbitrary edits without an activity timestamp and orphan comments invent no activity.+ Unresolved project ownership is reported separately. Invalid links/statuses and identity collisions have+ exact diagnostic counts and at most ten deterministic identity samples per category, with sampleComplete.+ Names and display IDs never merge records. Ambiguous UUID attribution affecting scope fails explicitly.+ Summaries sort by normalized project name, UUID then physical identity; milestones sort by UUID then+ physical identity. Missing milestone display IDs remain absent.++ The payload contains projects, unresolvedProjects, diagnostics, completionWindow, nextCursor and expiresAt.+ Read evidence is outside text in _meta["me.nore.ig.transit/read"]: asOf, snapshotId, freshness and read.+ asOf is capture time, distinct from import evidence, completion window and expiry. readPolicy defaults to+ refresh_if_needed; cached skips refresh observation. Refresh observation lasts at most two seconds within+ the five-second read budget and considers a relevant import within thirty seconds recent; it does not+ force a pull. Freshness reports recent_import, stale, unknown or not_applicable and active/inactive sync;+ absent import proof stays unknown where applicable.++ Replay with snapshotId only returns the original first page. Continue with cursor only, optionally the+ identical original readPolicy. Both retain original scope, window, options, bytes and freshness metadata;+ they do not recapture or reassess freshness. Snapshots expire five minutes after capture completes,+ without extension; server stop/restart invalidates them. Expired/lost snapshots or cursors require a new+ initial request. Reusable cursors have a separate family from ordinary query_tasks cursors. A retained+ snapshot can also serve restricted query_tasks calls with captured descriptions/metadata and original+ comment-covered revisions, but without comment bodies. Live snapshots are not evicted to admit new ones.+ Retention admits at most eight reusable roots and sixteen MiB of logical encoded data; ordinary query+ retention has its own equal budget. These encoded budgets are not total heap-memory limits.++ The encoded read-only response is available to the transport within five seconds, including queueing,+ capture, aggregation and encoding. Each HTTP POST accepts one JSON-RPC object; JSON-RPC batch arrays+ are rejected. mutate_tasks can carry multiple application-level operations within one tools/call;+ it follows its own write and receipt contract. Eight unfinished physical reads can be admitted;+ timed-out work retains its slot until actually drained. Failures produce typed errors, never partial/empty+ success counts: INVALID_INPUT,+ PROJECT_NOT_FOUND, AMBIGUOUS_PROJECT, IDENTITY_AMBIGUITY, SNAPSHOT_INCOMPATIBLE, INVALID_SNAPSHOT,+ INVALID_CURSOR, QUERY_CAPACITY_EXCEEDED, READ_TIMEOUT or READ_BUSY. Required fetch, coherence and encoding+ failures carry storage_failure, incoherent_capture or serialization_failure read failure categories.+ No failed or expired request silently starts a replacement snapshot.+ """,+ inputSchema: JSONSchema(+ type: "object", properties: nil, required: nil,+ oneOf: initialSummarySchemas + [summaryReplaySchema, reusableContinuationSchema]+ )+ )++ /// Append only this initial branch to query_tasks; preserve its ordinary initial branch unchanged.+ static let snapshotTaskQueryInitialSchema = JSONSchema(+ type: "object",+ properties: [+ "snapshotId": uuid("Retained summary snapshot UUID; never capture a replacement implicitly."),+ "detailLevel": .stringEnum("Captured task detail level.", values: ["summary", "full"]),+ "includeComments": excludedComments,+ "limit": pageLimit("Required integer page size from 1 through 100, inclusive."),+ "projectId": uuid("Optional project UUID within the original captured scope; no scope expansion."),+ "status": .array(+ "Optional effective statuses; empty means unrestricted. Unknown stored statuses match idea.",+ enumValues: [+ "idea", "planning", "spec", "ready-for-implementation", "in-progress",+ "ready-for-review", "done", "abandoned"+ ]+ )+ ],+ required: ["snapshotId", "detailLevel", "includeComments", "limit"],+ additionalProperties: false+ )++ /// Shared query_tasks must replace/merge its cursor branch, not append an overlapping oneOf alternative.+ /// Its ordinary cursor family remains supported there; this fragment describes reusable cursors only.+ static let reusableContinuationSchema = JSONSchema(+ type: "object",+ properties: [+ "cursor": uuid("Opaque continuation cursor; expired or lost cursors require a new initial request."),+ "readPolicy": .stringEnum(+ "Optional identical original policy; omission retains it. No refresh or policy override.",+ values: ["cached", "refresh_if_needed"]+ )+ ],+ required: ["cursor"],+ additionalProperties: false+ )++ static let snapshotTaskQueryDescription = """+ Alternatively query a retained summary snapshot with snapshotId, detailLevel, includeComments:false and+ limit (integer 1...100). Only optional projectId and status are accepted; projectId must stay within the+ original scope. Status uses captured effective status, with unknown raw status treated as idea and+ exposed as storedStatus when different. An empty status array means unrestricted. Other filters, project+ names, comment bodies and a new readPolicy are incompatible. Rows sort by UUID then physical identity.+ Full detail uses captured description and metadata, retaining the original canonical comment-covered+ revision even though comment bodies are omitted. This does not alter ordinary stored-status query+ filtering, ordering or results. Continue with cursor and optionally the identical original readPolicy;+ retain the original snapshot, options, expiry and read metadata without live capture or refresh.+ Reusable cursor routing remains recognizable after expiry; failure never recaptures implicitly.+ """++ private static let summaryReplaySchema = JSONSchema(+ type: "object",+ properties: ["snapshotId": uuid("Replay the original first summary page and its frozen read metadata.")],+ required: ["snapshotId"],+ additionalProperties: false+ )++ private static var initialSummarySchemas: [JSONSchema] {+ let required = ["start", "end", "limit"]+ let properties: [String: JSONSchemaProperty] = [+ "start": timestamp("Inclusive completion-window start; explicit timezone, seconds; start < end."),+ "end": timestamp("Exclusive completion-window end; explicit timezone, seconds; start < end."),+ "limit": pageLimit("Required integer project page size from 1 through 100, inclusive."),+ "readPolicy": initialReadPolicy+ ]+ var byId = properties+ byId["projectId"] = uuid("Exact project UUID; exclusive with project name.")+ var byName = properties+ byName["project"] = .string("Nonempty normalized exact project name; exclusive with projectId.")+ return [+ JSONSchema(type: "object", properties: properties, required: required, additionalProperties: false),+ JSONSchema(type: "object", properties: byId, required: required + ["projectId"],+ additionalProperties: false),+ JSONSchema(type: "object", properties: byName, required: required + ["project"],+ additionalProperties: false)+ ]+ }++ private static var excludedComments: JSONSchemaProperty {+ var property = JSONSchemaProperty.boolean("Must be false; snapshot tasks never return comment bodies.")+ property.const = false+ return property+ }++ private static var initialReadPolicy: JSONSchemaProperty {+ var property = JSONSchemaProperty.stringEnum(+ "Default refresh_if_needed; cached skips import observation. Never guarantees remote completeness.",+ values: ["cached", "refresh_if_needed"]+ )+ property.defaultValue = "refresh_if_needed"+ return property+ }++ private static func pageLimit(_ description: String) -> JSONSchemaProperty {+ var property = JSONSchemaProperty.integer(description)+ property.minimum = 1+ property.maximum = 100+ return property+ }++ private static func uuid(_ description: String) -> JSONSchemaProperty {+ var property = JSONSchemaProperty.string(description)+ property.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 property+ }++ private static func timestamp(_ description: String) -> JSONSchemaProperty {+ var property = JSONSchemaProperty.string(description)+ property.pattern = #"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}"#+ + #"(?:\.[0-9]{1,3})?(Z|[+-][0-9]{2}:[0-9]{2})$"#+ return property+ }+}+#endif
diff --git a/Transit/Transit/MCP/MCPReusableSnapshotIndex.swift b/Transit/Transit/MCP/MCPReusableSnapshotIndex.swiftnew file mode 100644index 0000000..a4b4ab6--- /dev/null+++ b/Transit/Transit/MCP/MCPReusableSnapshotIndex.swift@@ -0,0 +1,99 @@+#if os(macOS)+import Foundation++/// The original bundle remains owned by every replacement entry, including its lifetime probe.+nonisolated struct MCPReusableSnapshotEntry: Sendable {+ let identity: UUID+ let bundle: EncodedViewBundle+ let pages: [String: Data]+ let preparedResultBundle: MCPResultRetainedBundle?+ let preparedResultPages: [String: MCPResultPreparedPage]++ init(identity: UUID = UUID(), bundle: EncodedViewBundle, pages: [String: Data],+ preparedResultPages: [String: MCPResultPreparedPage] = [:],+ preparedResultBundle: MCPResultRetainedBundle? = nil) {+ self.identity = identity+ self.bundle = bundle+ self.pages = pages+ self.preparedResultPages = preparedResultPages+ self.preparedResultBundle = preparedResultBundle+ }++ func descriptor(checkpoint: () throws -> Void = {}) throws -> MCPPublicationRoot {+ try checkpoint()+ let id = bundle.root.capture.metadata.snapshotId+ guard bundle.encodedCaptureByteCount >= 0, pages[id] == nil else {+ throw MCPReusableSnapshotError.incompatible+ }+ let (initialBytes, initialOverflow) = bundle.encodedCaptureByteCount+ .addingReportingOverflow(bundle.root.firstPage.count)+ guard !initialOverflow else { throw PublicationRejection.capacity }+ var legacyBytes = initialBytes+ for data in pages.values {+ try checkpoint()+ let value = data.count+ let sum = legacyBytes+ let (total, overflow) = sum.addingReportingOverflow(value)+ guard !overflow else { throw PublicationRejection.capacity }+ legacyBytes = total+ }+ if let preparedResultBundle {+ guard bundle.preparedResultBundle == nil,+ preparedResultBundle.charge.originalCaptureIndexBytes == legacyBytes,+ let first = bundle.root.preparedResultPage,+ try preparedResultBundle.pages.contains(where: {+ try checkpoint()+ return $0 === first+ }),+ Set(preparedResultPages.keys) == Set(pages.keys),+ try preparedResultPages.values.allSatisfy({ owner in+ try checkpoint()+ return try preparedResultBundle.pages.contains(where: {+ try checkpoint()+ return $0 === owner+ })+ }) else { throw MCPReusableSnapshotError.incompatible }+ } else {+ guard bundle.preparedResultBundle == nil, bundle.root.preparedResultPage == nil,+ preparedResultPages.isEmpty else { throw MCPReusableSnapshotError.incompatible }+ }+ return MCPPublicationRoot(id: id, deadline: bundle.root.capture.retentionDeadline,+ encodedByteCount: preparedResultBundle?.charge.totalBytes ?? legacyBytes,+ tokens: Set(pages.keys).union([id]))+ }+}++/// Built and pinned outside the shared gate; its descriptor contains bounded root bookkeeping.+nonisolated final class MCPReusableSnapshotIndex: MCPPublicationIndex {+ let descriptor: MCPPublicationIndexDescriptor+ let entries: [String: MCPReusableSnapshotEntry]+ let pageRoots: [String: String]++ init(entries: [String: MCPReusableSnapshotEntry] = [:], checkpoint: () throws -> Void = {}) throws {+ self.entries = entries+ self.descriptor = try MCPPublicationIndexDescriptor(roots: entries.values.map {+ try $0.descriptor(checkpoint: checkpoint)+ })+ var mapping: [String: String] = [:]+ var identities: Set<ObjectIdentifier> = []+ for (id, entry) in entries {+ try checkpoint()+ var rootIdentities: Set<ObjectIdentifier> = []+ for page in entry.preparedResultBundle?.pages ?? [] {+ try checkpoint()+ rootIdentities.insert(ObjectIdentifier(page))+ if let metadata = page.metadataOwner { rootIdentities.insert(ObjectIdentifier(metadata)) }+ }+ guard identities.isDisjoint(with: rootIdentities) else { throw PublicationRejection.busy }+ identities.formUnion(rootIdentities)+ guard id == entry.bundle.root.capture.metadata.snapshotId else { throw PublicationRejection.busy }+ for cursor in entry.pages.keys {+ try checkpoint()+ guard mapping[cursor] == nil else { throw PublicationRejection.busy }+ mapping[cursor] = id+ }+ }+ self.pageRoots = mapping+ }+}+#endif
diff --git a/Transit/Transit/MCP/MCPReusableSnapshotPreparedRetention.swift b/Transit/Transit/MCP/MCPReusableSnapshotPreparedRetention.swiftnew file mode 100644index 0000000..4fcee92--- /dev/null+++ b/Transit/Transit/MCP/MCPReusableSnapshotPreparedRetention.swift@@ -0,0 +1,348 @@+#if os(macOS)+import Foundation++extension MCPReusableSnapshotStore {+ nonisolated func preparedResultBudget(originalCaptureIndexBytes: Int, replacingSnapshotID: String? = nil,+ operation: MCPReadOperation) throws -> MCPResultRetentionBudget {+ let base = try preparedObservation(operation)+ return try budget(base, legacyBytes: originalCaptureIndexBytes, replacing: replacingSnapshotID)+ }++ nonisolated func reservePreparedCreate(bundle: EncodedViewBundle, preparedResults: MCPResultRetainedBundle,+ operation: MCPReadOperation, publicationDeadline: ContinuousClock.Instant)+ throws -> RetentionReservation {+ try MCPPortfolioReadEncoding.check(operation)+ guard case .completePortfolio = bundle.root.capture.completeness,+ bundle.root.capture.captureScope != .selectedQuery, case .initial = bundle.root.initialRequest,+ bundle.root.capture.createdAt.duration(to: bundle.root.capture.retentionDeadline) == .seconds(300),+ !bundle.root.capture.metadata.snapshotId.isEmpty,+ preparedResults.pages.count == bundle.pages.count + 1,+ let firstOwner = preparedResults.pages.first else {+ throw MCPReusableSnapshotError.incompatible+ }+ guard bundle.root.preparedResultPage == nil || bundle.root.preparedResultPage === firstOwner else {+ throw MCPReusableSnapshotError.incompatible+ }+ let mapping = try pageMapping(pages: bundle.pages, cursors: bundle.cursors)+ try validateOwners(preparedResults.pages, root: bundle.root,+ bytes: [bundle.root.firstPage] + bundle.pages, operation: operation)+ let root = RetainedView(capture: bundle.root.capture, frozenMetadataBytes: bundle.root.frozenMetadataBytes,+ window: bundle.root.window, initialRequest: bundle.root.initialRequest,+ firstPage: bundle.root.firstPage, preparedResultPage: firstOwner)+ let normalized = EncodedViewBundle(root: root, pages: bundle.pages, cursors: bundle.cursors,+ encodedCaptureByteCount: bundle.encodedCaptureByteCount, lifetimeProbe: bundle.lifetimeProbe)+ let base = try preparedObservation(operation)+ let id = bundle.root.capture.metadata.snapshotId+ guard base.index.entries[id] == nil else { throw PublicationRejection.busy }+ let legacy = try legacyBytes(normalized, pages: mapping, operation: operation)+ let measured = try measure(preparedResults.pages, budget: budget(base, legacyBytes: legacy, replacing: nil),+ operation: operation)+ guard measured.charge.totalBytes == preparedResults.charge.totalBytes else {+ throw MCPReusableSnapshotError.incompatible+ }+ let owners = Dictionary(uniqueKeysWithValues: zip(bundle.cursors, preparedResults.pages.dropFirst()))+ let entry = MCPReusableSnapshotEntry(bundle: normalized, pages: mapping,+ preparedResultPages: owners, preparedResultBundle: measured)+ try rejectForeignOwners(entry, rootID: id, observation: base, operation: operation)+ var entries = base.index.entries+ entries[id] = entry+ let candidate = try MCPReusableSnapshotIndex(entries: entries,+ checkpoint: { try MCPPortfolioReadEncoding.check(operation) })+ try MCPPortfolioReadEncoding.check(operation)+ let deadline = min(publicationDeadline, try MCPPortfolioReadEncoding.publicationDeadline(operation))+ return try reserve(base: base.snapshot, candidate: candidate, deadline: deadline)+ }++ // swiftlint:disable:next function_parameter_count+ nonisolated func reservePreparedAppend(snapshotID: String, pages: [Data], cursors: [String],+ preparedPages: [MCPResultPreparedPage],+ operation: MCPReadOperation,+ publicationDeadline: ContinuousClock.Instant) throws+ -> RetentionReservation {+ let base = try preparedObservation(operation)+ guard let original = base.index.entries[snapshotID] else { throw MCPReusableSnapshotError.invalidSnapshot }+ guard let retained = original.preparedResultBundle, preparedPages.count == pages.count + 1 else {+ throw MCPReusableSnapshotError.incompatible+ }+ let additions = try pageMapping(pages: pages, cursors: cursors)+ // The first projection response is retained even when it has no continuation.+ try validateOwners(preparedPages, root: original.bundle.root, bytes: nil, operation: operation)+ for (page, bytes) in zip(preparedPages.dropFirst(), pages) {+ guard try cooperativelyEqual(page.source.originalText.utf8, bytes, operation: operation) else {+ throw MCPReusableSnapshotError.incompatible+ }+ }+ var mapping = original.pages+ var owners = original.preparedResultPages+ for (cursor, bytes) in additions {+ try MCPPortfolioReadEncoding.check(operation)+ guard mapping[cursor] == nil else { throw PublicationRejection.busy }+ mapping[cursor] = bytes+ }+ for (cursor, owner) in zip(cursors, preparedPages.dropFirst()) { owners[cursor] = owner }+ let union = try ownerUnion(retained.pages + preparedPages, operation: operation)+ let legacy = try legacyBytes(original.bundle, pages: mapping, operation: operation)+ let measured = try measure(union, budget: budget(base, legacyBytes: legacy, replacing: snapshotID),+ operation: operation)+ let entry = MCPReusableSnapshotEntry(identity: original.identity, bundle: original.bundle, pages: mapping,+ preparedResultPages: owners, preparedResultBundle: measured)+ try rejectForeignOwners(entry, rootID: snapshotID, observation: base, operation: operation)+ var entries = base.index.entries+ entries[snapshotID] = entry+ let candidate = try MCPReusableSnapshotIndex(entries: entries,+ checkpoint: { try MCPPortfolioReadEncoding.check(operation) })+ try MCPPortfolioReadEncoding.check(operation)+ let deadline = min(publicationDeadline, try MCPPortfolioReadEncoding.publicationDeadline(operation))+ return try reserve(base: base.snapshot, candidate: candidate, deadline: deadline)+ }++ // swiftlint:disable large_tuple+ nonisolated func preparedResultView(for snapshotID: String, now: ContinuousClock.Instant,+ testingAfterPin: (() throws -> Void)? = nil) throws+ -> (root: RetainedView, firstPage: MCPResultPreparedPage, pin: MCPReusableSnapshotReadPin) {+ let pinned = try preparedRetainedView(for: snapshotID, now: now, testingAfterPin: testingAfterPin)+ guard let owner = pinned.root.preparedResultPage else { throw MCPReusableSnapshotError.incompatible }+ return (pinned.root, owner, pinned.pin)+ }++ nonisolated func preparedResultPage(for cursor: String, now: ContinuousClock.Instant,+ testingAfterPin: (() throws -> Void)? = nil) throws+ -> (page: RetainedPage, preparedPage: MCPResultPreparedPage, pin: MCPReusableSnapshotReadPin) {+ guard MCPCursorFamily.classify(cursor) == .reusable else { throw MCPReusableSnapshotError.invalidCursor }+ let base = try liveSnapshot(now: now)+ guard let index = base.index as? MCPReusableSnapshotIndex, let id = index.pageRoots[cursor],+ let entry = index.entries[id], let bytes = entry.pages[cursor] else {+ throw MCPReusableSnapshotError.invalidCursor+ }+ guard let owner = entry.preparedResultPages[cursor] else { throw MCPReusableSnapshotError.incompatible }+ let pin = MCPReusableSnapshotReadPin(publicationStoreID: publicationStoreID, domain: domain,+ snapshotID: id, identity: entry.identity,+ deadline: entry.bundle.root.capture.retentionDeadline, cursor: cursor)+ try testingAfterPin?()+ guard domain.withLock({ pin.validateLocked(in: domain) == nil }), now < pin.deadline else {+ throw MCPReusableSnapshotError.invalidCursor+ }+ return (RetainedPage(root: entry.bundle.root, encodedPage: bytes, preparedResultPage: owner), owner, pin)+ }+ // swiftlint:enable large_tuple+}++extension MCPReusableSnapshotStore {+ /// Private preparation under the original admitted operation, before shared ownership transfer.+ nonisolated func prepareAggregate(_ publications: [any MCPPreparedPublication], in domain: MCPReadPublicationDomain,+ operation: MCPReadOperation) throws -> any MCPPreparedPublication {+ try MCPPortfolioReadEncoding.check(operation)+ guard domain === self.domain else { throw PublicationRejection.busy }+ let (children, pins) = try publicationParts(publications, in: domain)+ guard children.count > 1 else { return try prepareAggregate(publications, in: domain) }+ let base = try preparedObservation(operation)+ var existingIdentities: Set<ObjectIdentifier> = []+ for entry in base.index.entries.values {+ existingIdentities.formUnion(try ownerIdentities(entry, operation: operation))+ }+ var newIdentities: Set<ObjectIdentifier> = []+ var entries = base.index.entries+ for child in children {+ try MCPPortfolioReadEncoding.check(operation)+ guard child.expectedVersion == base.snapshot.version,+ let candidate = child.index as? MCPReusableSnapshotIndex else { throw PublicationRejection.busy }+ let introduced = try introducedOwners(candidate, excluding: existingIdentities, operation: operation)+ guard introduced.isDisjoint(with: newIdentities) else { throw PublicationRejection.busy }+ newIdentities.formUnion(introduced)+ entries = try mergeCandidate(candidate, original: base.index, combined: entries, operation: operation)+ }+ let candidate = try MCPReusableSnapshotIndex(entries: entries,+ checkpoint: { try MCPPortfolioReadEncoding.check(operation) })+ try MCPPortfolioReadEncoding.check(operation)+ let mutation = try domain.transfer(children, aggregateIndex: candidate, operationID: UUID())+ if pins.isEmpty { return mutation }+ return MCPReusableSnapshotGuardedPublication(publicationStoreID: publicationStoreID,+ domain: domain, pins: pins, mutation: mutation)+ }+}++private extension MCPReusableSnapshotStore {+ nonisolated func mergeCandidate(_ candidate: MCPReusableSnapshotIndex, original: MCPReusableSnapshotIndex,+ combined: [String: MCPReusableSnapshotEntry], operation: MCPReadOperation) throws+ -> [String: MCPReusableSnapshotEntry] {+ var entries = combined+ for (id, entry) in candidate.entries {+ try MCPPortfolioReadEncoding.check(operation)+ guard let initial = original.entries[id] else {+ guard entries[id] == nil else { throw PublicationRejection.busy }+ entries[id] = entry+ continue+ }+ guard let current = entries[id], entry.identity == initial.identity else { throw PublicationRejection.busy }+ entries[id] = try mergedPreparedEntry(original: initial, current: current,+ addition: entry, operation: operation)+ }+ return entries+ }++ nonisolated func introducedOwners(_ index: MCPReusableSnapshotIndex, excluding existing: Set<ObjectIdentifier>,+ operation: MCPReadOperation) throws -> Set<ObjectIdentifier> {+ var introduced: Set<ObjectIdentifier> = []+ for entry in index.entries.values {+ introduced.formUnion(try ownerIdentities(entry, operation: operation))+ }+ introduced.subtract(existing)+ return introduced+ }++ nonisolated func mergedPreparedEntry(original: MCPReusableSnapshotEntry, current: MCPReusableSnapshotEntry,+ addition: MCPReusableSnapshotEntry, operation: MCPReadOperation) throws+ -> MCPReusableSnapshotEntry {+ var pages = current.pages+ var owners = current.preparedResultPages+ for (cursor, bytes) in addition.pages where original.pages[cursor] == nil {+ try MCPPortfolioReadEncoding.check(operation)+ guard pages[cursor] == nil else { throw PublicationRejection.busy }+ pages[cursor] = bytes+ owners[cursor] = addition.preparedResultPages[cursor]+ }+ let combined = try ownerUnion((current.preparedResultBundle?.pages ?? [])+ + (addition.preparedResultBundle?.pages ?? []), operation: operation)+ let prepared: MCPResultRetainedBundle?+ if current.preparedResultBundle != nil || addition.preparedResultBundle != nil {+ guard current.preparedResultBundle != nil, addition.preparedResultBundle != nil else {+ throw MCPReusableSnapshotError.incompatible+ }+ let legacy = try legacyBytes(original.bundle, pages: pages, operation: operation)+ // Children already own exact additive pending deltas; transfer revalidates their sum.+ prepared = try measure(combined, budget: MCPResultRetentionBudget(store: .reusable,+ originalCaptureIndexBytes: legacy, visibleBytes: 0, pendingBytes: 0), operation: operation)+ } else { prepared = nil }+ return MCPReusableSnapshotEntry(identity: original.identity, bundle: original.bundle,+ pages: pages, preparedResultPages: owners, preparedResultBundle: prepared)+ }++ nonisolated struct PreparedObservation {+ let snapshot: MCPPublicationStoreSnapshot+ let index: MCPReusableSnapshotIndex+ let pendingBytes: Int+ let pending: [MCPReusableSnapshotIndex]+ }++ nonisolated func preparedObservation(_ operation: MCPReadOperation) throws -> PreparedObservation {+ try MCPPortfolioReadEncoding.check(operation)+ let snapshot = try liveSnapshot()+ guard let index = snapshot.index as? MCPReusableSnapshotIndex else { throw PublicationRejection.busy }+ let observed = try domain.withLock {+ guard let state = domain.stores[publicationStoreID], state.version == snapshot.version,+ domain.tokenVersion == snapshot.tokenVersion else { throw PublicationRejection.busy }+ return (state.pendingBytes, state.pending.values.compactMap { $0.index as? MCPReusableSnapshotIndex })+ }+ try MCPPortfolioReadEncoding.check(operation)+ return PreparedObservation(snapshot: snapshot, index: index, pendingBytes: observed.0, pending: observed.1)+ }++ nonisolated func budget(_ observed: PreparedObservation, legacyBytes: Int, replacing id: String?) throws+ -> MCPResultRetentionBudget {+ var visible = observed.index.descriptor.encodedByteCount+ if let id {+ guard let root = observed.index.descriptor.roots[id] else { throw MCPReusableSnapshotError.invalidSnapshot }+ visible = try checkedDifference(visible, root.encodedByteCount)+ }+ return MCPResultRetentionBudget(store: .reusable, originalCaptureIndexBytes: legacyBytes,+ visibleBytes: visible, pendingBytes: observed.pendingBytes)+ }++ nonisolated func checkedDifference(_ total: Int, _ original: Int) throws -> Int {+ guard total >= 0, original >= 0 else { throw MCPResultPreparationError.invalidAccounting }+ let (difference, overflow) = total.subtractingReportingOverflow(original)+ guard !overflow, difference >= 0 else { throw MCPResultPreparationError.invalidAccounting }+ return difference+ }++ nonisolated func legacyBytes(_ bundle: EncodedViewBundle, pages: [String: Data],+ operation: MCPReadOperation) throws -> Int {+ var total = try MCPResultRetentionAccounting.add(bundle.encodedCaptureByteCount, bundle.root.firstPage.count)+ for bytes in pages.values {+ try MCPPortfolioReadEncoding.check(operation)+ total = try MCPResultRetentionAccounting.add(total, bytes.count)+ }+ return total+ }++ nonisolated func validateOwners(_ owners: [MCPResultPreparedPage], root: RetainedView, bytes: [Data]?,+ operation: MCPReadOperation) throws {+ let expected = [Data("{\"me.nore.ig.transit/read\":".utf8), root.frozenMetadataBytes, Data("}".utf8)].joined()+ for (position, owner) in owners.enumerated() {+ try MCPPortfolioReadEncoding.check(operation)+ guard let metadata = owner.metadataOwner,+ try cooperativelyEqual(metadata.value.document.originalUTF8, expected, operation: operation) else {+ throw MCPReusableSnapshotError.incompatible+ }+ if let bytes,+ try !cooperativelyEqual(owner.source.originalText.utf8, bytes[position], operation: operation) {+ throw MCPReusableSnapshotError.incompatible+ }+ }+ }++ /// Compare existing backing byte-by-byte; no complete text or metadata copy and no retained checkpoint.+ nonisolated func cooperativelyEqual<Left: Sequence, Right: Sequence>(+ _ left: Left, _ right: Right, operation: MCPReadOperation+ ) throws -> Bool where Left.Element == UInt8, Right.Element == UInt8 {+ var lhs = left.makeIterator()+ var rhs = right.makeIterator()+ var untilCheckpoint = 0+ while let byte = lhs.next() {+ if untilCheckpoint == 0 {+ try MCPPortfolioReadEncoding.check(operation)+ untilCheckpoint = 256+ }+ guard let other = rhs.next(), byte == other else {+ try MCPPortfolioReadEncoding.check(operation)+ return false+ }+ untilCheckpoint -= 1+ }+ try MCPPortfolioReadEncoding.check(operation)+ return rhs.next() == nil+ }++ nonisolated func ownerUnion(_ owners: [MCPResultPreparedPage], operation: MCPReadOperation) throws+ -> [MCPResultPreparedPage] {+ var seen: Set<ObjectIdentifier> = []+ var result: [MCPResultPreparedPage] = []+ for owner in owners {+ try MCPPortfolioReadEncoding.check(operation)+ if seen.insert(ObjectIdentifier(owner)).inserted { result.append(owner) }+ }+ return result+ }++ nonisolated func measure(_ owners: [MCPResultPreparedPage], budget: MCPResultRetentionBudget,+ operation: MCPReadOperation) throws -> MCPResultRetainedBundle {+ try MCPResultPreparation.prepare(pages: owners, budget: budget,+ checkpoint: { try MCPPortfolioReadEncoding.check(operation) })+ }++ nonisolated func rejectForeignOwners(_ entry: MCPReusableSnapshotEntry, rootID: String,+ observation: PreparedObservation, operation: MCPReadOperation) throws {+ let identity = try ownerIdentities(entry, operation: operation)+ for index in [observation.index] + observation.pending {+ for (id, existing) in index.entries where id != rootID {+ try MCPPortfolioReadEncoding.check(operation)+ let existingIdentities = try ownerIdentities(existing, operation: operation)+ guard identity.isDisjoint(with: existingIdentities) else {+ throw PublicationRejection.busy+ }+ }+ }+ }++ nonisolated func ownerIdentities(_ entry: MCPReusableSnapshotEntry, operation: MCPReadOperation) throws+ -> Set<ObjectIdentifier> {+ var result: Set<ObjectIdentifier> = []+ for page in entry.preparedResultBundle?.pages ?? [] {+ try MCPPortfolioReadEncoding.check(operation)+ result.insert(ObjectIdentifier(page))+ if let metadata = page.metadataOwner { result.insert(ObjectIdentifier(metadata)) }+ }+ return result+ }+}+#endif
diff --git a/Transit/Transit/MCP/MCPReusableSnapshotReadPin.swift b/Transit/Transit/MCP/MCPReusableSnapshotReadPin.swiftnew file mode 100644index 0000000..c9f5550--- /dev/null+++ b/Transit/Transit/MCP/MCPReusableSnapshotReadPin.swift@@ -0,0 +1,51 @@+#if os(macOS)+import Foundation++/// Scalar proof of the exact root pinned during value lookup, including its original lifetime.+nonisolated struct MCPReusableSnapshotReadPin: MCPPreparedPublication {+ let publicationStoreID: MCPPublicationStoreID+ let domain: MCPReadPublicationDomain+ let snapshotID: String+ let identity: UUID+ let deadline: ContinuousClock.Instant+ let cursor: String?++ func validateLocked(in domain: MCPReadPublicationDomain) -> PublicationRejection? {+ guard domain === self.domain else { return .busy }+ guard domain.currentInstantLocked < deadline,+ let index = domain.stores[publicationStoreID]?.index as? MCPReusableSnapshotIndex,+ let entry = index.entries[snapshotID], entry.identity == identity,+ entry.bundle.root.capture.retentionDeadline == deadline else { return .expired }+ if let cursor {+ guard index.pageRoots[cursor] == snapshotID, entry.pages[cursor] != nil else { return .expired }+ }+ return nil+ }++ func commitLocked(in domain: MCPReadPublicationDomain) {}+ func discardLocked(in domain: MCPReadPublicationDomain) {}+}++/// One store participant: validate read guards before the optional single mutation swap.+nonisolated struct MCPReusableSnapshotGuardedPublication: MCPPreparedPublication {+ let publicationStoreID: MCPPublicationStoreID+ let domain: MCPReadPublicationDomain+ let pins: [MCPReusableSnapshotReadPin]+ let mutation: MCPPublicationReservation?++ func validateLocked(in domain: MCPReadPublicationDomain) -> PublicationRejection? {+ guard domain === self.domain, pins.count <= 8,+ mutation.map({ $0.publicationStoreID == publicationStoreID && $0.domain === domain }) ?? true else {+ return .busy+ }+ for pin in pins {+ guard pin.publicationStoreID == publicationStoreID else { return .busy }+ if let rejection = pin.validateLocked(in: domain) { return rejection }+ }+ return mutation?.validateLocked(in: domain)+ }++ func commitLocked(in domain: MCPReadPublicationDomain) { mutation?.commitLocked(in: domain) }+ func discardLocked(in domain: MCPReadPublicationDomain) { mutation?.discardLocked(in: domain) }+}+#endif
diff --git a/Transit/Transit/MCP/MCPReusableSnapshotStore.swift b/Transit/Transit/MCP/MCPReusableSnapshotStore.swiftnew file mode 100644index 0000000..150781a--- /dev/null+++ b/Transit/Transit/MCP/MCPReusableSnapshotStore.swift@@ -0,0 +1,363 @@+#if os(macOS)+import Foundation++nonisolated struct RetainedView: Sendable {+ let capture: CapturedReadView+ let frozenMetadataBytes: Data+ let window: CompletionWindow+ let initialRequest: MCPPortfolioSummaryRequest+ let firstPage: Data+ let preparedResultPage: MCPResultPreparedPage?++ init(capture: CapturedReadView, frozenMetadataBytes: Data, window: CompletionWindow,+ initialRequest: MCPPortfolioSummaryRequest, firstPage: Data,+ preparedResultPage: MCPResultPreparedPage? = nil) {+ self.capture = capture+ self.frozenMetadataBytes = frozenMetadataBytes+ self.window = window+ self.initialRequest = initialRequest+ self.firstPage = firstPage+ self.preparedResultPage = preparedResultPage+ }+}++nonisolated struct RetentionReservation: Sendable {+ let publication: MCPPublicationReservation+ var id: UUID { publication.operationID }+}++nonisolated struct EncodedViewBundle: Sendable {+ let root: RetainedView+ let pages: [Data]+ let cursors: [String]+ let encodedCaptureByteCount: Int+ let preparedResultBundle: MCPResultRetainedBundle?+ /// Internal lifetime seam: retain with the actual immutable bundle, never invoke manually.+ let lifetimeProbe: (any MCPReusableSnapshotLifetimeProbe)?++ init(root: RetainedView, pages: [Data], cursors: [String], encodedCaptureByteCount: Int,+ lifetimeProbe: (any MCPReusableSnapshotLifetimeProbe)? = nil,+ preparedResultBundle: MCPResultRetainedBundle? = nil) {+ self.root = root+ self.pages = pages+ self.cursors = cursors+ self.encodedCaptureByteCount = encodedCaptureByteCount+ self.lifetimeProbe = lifetimeProbe+ self.preparedResultBundle = preparedResultBundle+ }+}++nonisolated protocol MCPReusableSnapshotLifetimeProbe: AnyObject, Sendable {}++nonisolated struct RetainedPage: Sendable {+ let root: RetainedView+ let encodedPage: Data+ let preparedResultPage: MCPResultPreparedPage?++ init(root: RetainedView, encodedPage: Data, preparedResultPage: MCPResultPreparedPage? = nil) {+ self.root = root+ self.encodedPage = encodedPage+ self.preparedResultPage = preparedResultPage+ }+}++nonisolated enum MCPReusableSnapshotError: Error, Equatable, Sendable {+ case invalidSnapshot+ case invalidCursor+ case incompatible+}++/// Immutable candidates are prepared outside the sole shared publication lock.+/// Root expiry and store versions are checked again by the enclosing response gate.+nonisolated final class MCPReusableSnapshotStore: MCPRetainedViewSource, MCPReadPublicationParticipant {+ let publicationStoreID: MCPPublicationStoreID+ let domain: MCPReadPublicationDomain++ init(domain: MCPReadPublicationDomain) throws {+ self.domain = domain+ self.publicationStoreID = MCPPublicationStoreID(rawValue: UUID())+ try domain.register(storeID: publicationStoreID, index: MCPReusableSnapshotIndex(),+ maxEntries: 8, maxBytes: 16 * 1024 * 1024)+ }++ func retainedView(for snapshotID: String, now: ContinuousClock.Instant,+ testingAfterPin: (() throws -> Void)? = nil) throws -> RetainedView {+ try preparedRetainedView(for: snapshotID, now: now, testingAfterPin: testingAfterPin).root+ }++ func preparedRetainedView(for snapshotID: String, now: ContinuousClock.Instant,+ testingAfterPin: (() throws -> Void)? = nil) throws+ -> (root: RetainedView, pin: MCPReusableSnapshotReadPin) {+ let base = try liveSnapshot(now: now)+ guard let index = base.index as? MCPReusableSnapshotIndex,+ let entry = index.entries[snapshotID] else { throw MCPReusableSnapshotError.invalidSnapshot }+ let pin = MCPReusableSnapshotReadPin(publicationStoreID: publicationStoreID, domain: domain,+ snapshotID: snapshotID, identity: entry.identity, deadline: entry.bundle.root.capture.retentionDeadline,+ cursor: nil)+ try testingAfterPin?()+ let valid = domain.withLock { pin.validateLocked(in: domain) == nil }+ guard valid, now < pin.deadline else { throw MCPReusableSnapshotError.invalidSnapshot }+ return (entry.bundle.root, pin)+ }++ func page(for cursor: String, now: ContinuousClock.Instant,+ testingAfterPin: (() throws -> Void)? = nil) throws -> RetainedPage {+ try preparedPage(for: cursor, now: now, testingAfterPin: testingAfterPin).page+ }++ func preparedPage(for cursor: String, now: ContinuousClock.Instant,+ testingAfterPin: (() throws -> Void)? = nil) throws+ -> (page: RetainedPage, pin: MCPReusableSnapshotReadPin) {+ guard MCPCursorFamily.classify(cursor) == .reusable else { throw MCPReusableSnapshotError.invalidCursor }+ let base = try liveSnapshot(now: now)+ guard let index = base.index as? MCPReusableSnapshotIndex,+ let snapshotID = index.pageRoots[cursor], let entry = index.entries[snapshotID],+ let bytes = entry.pages[cursor] else { throw MCPReusableSnapshotError.invalidCursor }+ let pin = MCPReusableSnapshotReadPin(publicationStoreID: publicationStoreID, domain: domain,+ snapshotID: snapshotID, identity: entry.identity, deadline: entry.bundle.root.capture.retentionDeadline,+ cursor: cursor)+ try testingAfterPin?()+ let valid = domain.withLock { pin.validateLocked(in: domain) == nil }+ guard valid, now < pin.deadline else { throw MCPReusableSnapshotError.invalidCursor }+ return (RetainedPage(root: entry.bundle.root, encodedPage: bytes), pin)+ }++ func reserveCreate(bundle: EncodedViewBundle, publicationDeadline: ContinuousClock.Instant)+ throws -> RetentionReservation {+ guard bundle.preparedResultBundle == nil, bundle.root.preparedResultPage == nil else {+ throw MCPResultPreparationError.notImplemented+ }+ guard case .completePortfolio = bundle.root.capture.completeness,+ bundle.root.capture.captureScope != .selectedQuery,+ case .initial = bundle.root.initialRequest,+ bundle.root.capture.createdAt.duration(to: bundle.root.capture.retentionDeadline) == .seconds(300),+ !bundle.root.capture.metadata.snapshotId.isEmpty else { throw MCPReusableSnapshotError.incompatible }+ let pages = try pageMapping(pages: bundle.pages, cursors: bundle.cursors)+ let entry = MCPReusableSnapshotEntry(bundle: bundle, pages: pages)+ let rootID = bundle.root.capture.metadata.snapshotId+ let base = try liveSnapshot()+ guard let index = base.index as? MCPReusableSnapshotIndex,+ index.entries[rootID] == nil else { throw PublicationRejection.busy }+ var entries = index.entries+ entries[rootID] = entry+ return try reserve(base: base, candidate: MCPReusableSnapshotIndex(entries: entries),+ deadline: publicationDeadline)+ }++ func reserveAppend(snapshotID: String, pages: [Data], cursors: [String],+ publicationDeadline: ContinuousClock.Instant) throws -> RetentionReservation {+ let additions = try pageMapping(pages: pages, cursors: cursors)+ guard !additions.isEmpty else { throw MCPReusableSnapshotError.incompatible }+ let base = try liveSnapshot()+ guard let index = base.index as? MCPReusableSnapshotIndex,+ let root = index.entries[snapshotID] else { throw MCPReusableSnapshotError.invalidSnapshot }+ guard root.preparedResultBundle == nil else { throw MCPReusableSnapshotError.incompatible }+ var mapping = root.pages+ for (cursor, bytes) in additions {+ guard mapping[cursor] == nil else { throw PublicationRejection.busy }+ mapping[cursor] = bytes+ }+ var entries = index.entries+ entries[snapshotID] = MCPReusableSnapshotEntry(identity: root.identity, bundle: root.bundle, pages: mapping)+ return try reserve(base: base, candidate: MCPReusableSnapshotIndex(entries: entries),+ deadline: publicationDeadline)+ }++ func prepare(reservation: RetentionReservation) throws -> any MCPPreparedPublication {+ let publication = reservation.publication+ guard publication.publicationStoreID == publicationStoreID, publication.domain === domain else {+ throw PublicationRejection.busy+ }+ try domain.withLock {+ if let rejection = publication.validateLocked(in: domain) { throw rejection }+ }+ return publication+ }++ func view(for snapshotID: String, now: ContinuousClock.Instant) throws -> CapturedReadView {+ try retainedView(for: snapshotID, now: now).capture+ }++ func prepareAggregate(+ _ publications: [any MCPPreparedPublication], in domain: MCPReadPublicationDomain+ ) throws -> any MCPPreparedPublication {+ guard domain === self.domain else { throw PublicationRejection.busy }+ let (children, pins) = try publicationParts(publications, in: domain)+ if children.isEmpty {+ guard !pins.isEmpty else { throw PublicationRejection.busy }+ return MCPReusableSnapshotGuardedPublication(publicationStoreID: publicationStoreID,+ domain: domain, pins: pins, mutation: nil)+ }+ if children.count == 1, let child = children.first,+ let candidate = child.index as? MCPReusableSnapshotIndex,+ candidate.entries.values.contains(where: { $0.preparedResultBundle != nil }) {+ if pins.isEmpty { return child }+ return MCPReusableSnapshotGuardedPublication(publicationStoreID: publicationStoreID,+ domain: domain, pins: pins, mutation: child)+ }+ let base = try domain.snapshot(for: publicationStoreID)+ guard let original = base.index as? MCPReusableSnapshotIndex else { throw PublicationRejection.busy }+ var entries = original.entries+ for child in children {+ guard let candidate = child.index as? MCPReusableSnapshotIndex else { throw PublicationRejection.busy }+ entries = try merging(candidate: candidate, original: original, combined: entries)+ }+ let mutation = try domain.transfer(children, aggregateIndex: MCPReusableSnapshotIndex(entries: entries),+ operationID: UUID())+ if pins.isEmpty { return mutation }+ return MCPReusableSnapshotGuardedPublication(publicationStoreID: publicationStoreID,+ domain: domain, pins: pins, mutation: mutation)+ }++ private func merging(candidate: MCPReusableSnapshotIndex, original: MCPReusableSnapshotIndex,+ combined: [String: MCPReusableSnapshotEntry]) throws -> [String: MCPReusableSnapshotEntry] {+ var entries = combined+ for (id, entry) in candidate.entries {+ guard let initial = original.entries[id] else {+ guard entries[id] == nil else { throw PublicationRejection.busy }+ entries[id] = entry+ continue+ }+ guard let current = entries[id] else { throw PublicationRejection.busy }+ guard entry.preparedResultBundle == nil, current.preparedResultBundle == nil,+ initial.preparedResultBundle == nil, entry.preparedResultPages.isEmpty,+ current.preparedResultPages.isEmpty,+ initial.preparedResultPages.isEmpty, entry.bundle.preparedResultBundle == nil,+ current.bundle.preparedResultBundle == nil, initial.bundle.preparedResultBundle == nil,+ entry.bundle.root.preparedResultPage == nil, current.bundle.root.preparedResultPage == nil,+ initial.bundle.root.preparedResultPage == nil else {+ throw MCPResultPreparationError.notImplemented+ }+ var pages = current.pages+ for (token, bytes) in entry.pages where initial.pages[token] == nil {+ guard pages[token] == nil else { throw PublicationRejection.busy }+ pages[token] = bytes+ }+ entries[id] = MCPReusableSnapshotEntry(identity: initial.identity, bundle: initial.bundle, pages: pages)+ }+ return entries+ }++ func rollback(_ reservation: RetentionReservation) throws {+ guard reservation.publication.domain === domain,+ reservation.publication.publicationStoreID == publicationStoreID else {+ throw PublicationRejection.busy+ }+ domain.withLock { reservation.publication.discardLocked(in: domain) }+ }++ func invalidate() throws {+ let empty = try MCPReusableSnapshotIndex()+ // Bounded scalar bookkeeping only; the domain carries old bundles through unlock.+ try domain.withLock {+ guard let state = domain.stores[publicationStoreID] else { throw PublicationRejection.busy }+ domain.retireLocked(state.index)+ state.index = empty+ state.descriptor = empty.descriptor+ state.version &+= 1+ domain.tokenVersion &+= 1+ let pending = Array(state.pending.values)+ for reservation in pending { reservation.discardLocked(in: domain) }+ }+ }++ func pageMapping(pages: [Data], cursors: [String]) throws -> [String: Data] {+ guard pages.count == cursors.count, Set(cursors).count == cursors.count,+ cursors.allSatisfy({ MCPCursorFamily.classify($0) == .reusable }) else {+ throw MCPReusableSnapshotError.incompatible+ }+ return Dictionary(uniqueKeysWithValues: zip(cursors, pages))+ }++ func reserve(base: MCPPublicationStoreSnapshot, candidate: MCPReusableSnapshotIndex,+ deadline: ContinuousClock.Instant) throws -> RetentionReservation {+ let original = base.index.descriptor+ let descriptor = candidate.descriptor+ // Reject oversize candidates as capacity rather than descriptor-shape contention.+ guard descriptor.entryCount <= 8, descriptor.encodedByteCount <= 16 * 1024 * 1024 else {+ throw PublicationRejection.capacity+ }+ let (entryDelta, entryOverflow) = descriptor.entryCount.subtractingReportingOverflow(original.entryCount)+ let (byteDelta, byteOverflow) = descriptor.encodedByteCount+ .subtractingReportingOverflow(original.encodedByteCount)+ guard !entryOverflow, !byteOverflow, entryDelta >= 0, byteDelta >= 0 else { throw PublicationRejection.busy }+ let publication = try domain.reserve(storeID: publicationStoreID, operationID: UUID(),+ expectedVersion: base.version, expectedTokenVersion: base.tokenVersion, index: candidate,+ chargeEntries: entryDelta, chargeBytes: byteDelta,+ newTokens: descriptor.tokens.subtracting(original.tokens), deadline: deadline)+ return RetentionReservation(publication: publication)+ }++ /// Expiry removal is prepared outside the domain; a competing swap produces busy.+ func liveSnapshot(now: ContinuousClock.Instant? = nil) throws -> MCPPublicationStoreSnapshot {+ let instant = now ?? domain.withLock { domain.currentInstantLocked }+ let base = try domain.snapshot(for: publicationStoreID)+ guard let original = base.index as? MCPReusableSnapshotIndex else { throw PublicationRejection.busy }+ let entries = original.entries.filter { instant < $0.value.bundle.root.capture.retentionDeadline }+ guard entries.count != original.entries.count else { return base }+ let replacement = try MCPReusableSnapshotIndex(entries: entries)+ try domain.retire(storeID: publicationStoreID, expectedVersion: base.version, replacementIndex: replacement)+ return try domain.snapshot(for: publicationStoreID)+ }+}++extension MCPReusableSnapshotStore {+ nonisolated func publicationParts(+ _ publications: [any MCPPreparedPublication], in domain: MCPReadPublicationDomain+ ) throws -> ([MCPPublicationReservation], [MCPReusableSnapshotReadPin]) {+ var children: [MCPPublicationReservation] = []+ var pins: [MCPReusableSnapshotReadPin] = []+ for publication in publications {+ guard publication.publicationStoreID == publicationStoreID else { throw PublicationRejection.busy }+ switch publication {+ case let pin as MCPReusableSnapshotReadPin:+ guard pin.domain === domain else { throw PublicationRejection.busy }+ pins.append(pin)+ case let combined as MCPReusableSnapshotGuardedPublication:+ let mutation = try checkedMutation(combined, in: domain)+ pins += combined.pins+ if let mutation { children.append(mutation) }+ case let child as MCPPublicationReservation:+ guard child.domain === domain else { throw PublicationRejection.busy }+ children.append(child)+ default: throw PublicationRejection.busy+ }+ }+ return (children, try compactPins(pins, in: domain))+ }++ nonisolated private func checkedMutation(+ _ combined: MCPReusableSnapshotGuardedPublication, in domain: MCPReadPublicationDomain+ ) throws -> MCPPublicationReservation? {+ guard combined.domain === domain,+ combined.mutation.map({ mutation in+ mutation.domain === domain && mutation.publicationStoreID == publicationStoreID+ }) ?? true else {+ throw PublicationRejection.busy+ }+ return combined.mutation+ }++ nonisolated private func compactPins(_ pins: [MCPReusableSnapshotReadPin], in domain: MCPReadPublicationDomain)+ throws -> [MCPReusableSnapshotReadPin] {+ var roots: [String: MCPReusableSnapshotReadPin] = [:]+ for pin in pins {+ guard pin.domain === domain, pin.publicationStoreID == publicationStoreID else {+ throw PublicationRejection.busy+ }+ if let prior = roots[pin.snapshotID] {+ guard prior.identity == pin.identity, prior.deadline == pin.deadline else {+ throw PublicationRejection.busy+ }+ }+ // Pages are append-only for an immutable root identity. Root identity/lifetime+ // implies preservation of every cursor validated during its atomic lookup.+ roots[pin.snapshotID] = MCPReusableSnapshotReadPin(publicationStoreID: publicationStoreID,+ domain: domain, snapshotID: pin.snapshotID, identity: pin.identity, deadline: pin.deadline, cursor: nil)+ }+ guard roots.count <= 8 else { throw PublicationRejection.busy }+ return roots.keys.sorted().compactMap { roots[$0] }+ }+}++#endif
diff --git a/Transit/Transit/MCP/MCPServer+Responses.swift b/Transit/Transit/MCP/MCPServer+Responses.swiftindex 1789754..bd144cd 100644--- a/Transit/Transit/MCP/MCPServer+Responses.swift+++ b/Transit/Transit/MCP/MCPServer+Responses.swift@@ -6,6 +6,21 @@ import NIOCore import NIOFoundationCompat extension MCPServer {+ nonisolated static func encodedResponse(_ bytes: Data) -> Response {+ Response(status: .ok, headers: [.contentType: "application/json"],+ body: .init(byteBuffer: ByteBuffer(data: bytes)))+ }++ nonisolated static func modernRejection(_ rejection: MCPModernRejection) -> Response {+ let status = HTTPResponse.Status(code: rejection.httpStatus)+ guard rejection.rpcCode != nil else { return Response(status: status) }+ guard let bytes = try? MCPModernWire.error(rejection) else {+ return Response(status: .internalServerError)+ }+ return Response(status: status, headers: [.contentType: "application/json"],+ body: .init(byteBuffer: ByteBuffer(data: bytes)))+ }+ nonisolated static func jsonResponse( _ payload: some Encodable & Sendable, additionalHeaders: HTTPFields = [:]
diff --git a/Transit/Transit/MCP/MCPServer+Routing.swift b/Transit/Transit/MCP/MCPServer+Routing.swiftnew file mode 100644index 0000000..ea116eb--- /dev/null+++ b/Transit/Transit/MCP/MCPServer+Routing.swift@@ -0,0 +1,250 @@+#if os(macOS)+import Foundation+import Hummingbird+import HTTPTypes+import NIOCore+import NIOFoundationCompat++extension MCPServer {++ /// Modern single-request transport. Availability is frozen before covered admission.+ nonisolated static func makeRouter(+ handler: MCPToolHandler, readCoordinator: MCPReadCoordinator? = nil+ ) -> Router<MCPRequestContext> {+ let coordinator = readCoordinator ?? handler.readCoordinator+ let router = Router(context: MCPRequestContext.self)+ let methods: [HTTPRequest.Method] = [.get, .delete, .head, .put, .patch, .options, .trace, .connect]+ for method in methods {+ router.on("mcp", method: method) { request, _ -> Response in+ guard Self.isAllowedMCPRequest(request) else { return forbiddenResponse() }+ return Response(status: .methodNotAllowed, headers: [.allow: "POST"])+ }+ }+ router.post("mcp") { request, context -> Response in+ await modernPost(request, context: context, handler: handler, coordinator: coordinator)+ }+ return router+ }++ nonisolated private static func modernPost(_ request: Request, context: MCPRequestContext, handler: MCPToolHandler,+ coordinator: MCPReadCoordinator) async -> Response {+ guard Self.isAllowedMCPRequest(request) else { return forbiddenResponse() }+ var headers = request.head.headerFields.map {+ MCPModernHeader(name: $0.name.rawName, value: $0.value)+ }+ if !headers.contains(where: { $0.name.lowercased() == "host" }), let authority = request.head.authority {+ headers.append(MCPModernHeader(name: "Host", value: authority))+ }+ do {+ try MCPModernValidator.validateTransport(MCPModernRequestInput(httpMethod: "POST",+ headers: headers, body: Data()))+ let body = try await request.body.collect(upTo: 1_048_576)+ let maintenanceEnabled = handler.modernMaintenanceEnabled+ let modern = try MCPModernValidator.validate(MCPModernRequestInput(httpMethod: "POST",+ headers: headers, body: Data(buffer: body)),+ availability: MCPModernProviderBinding.availability(maintenanceEnabled: maintenanceEnabled))+ let admittedAt = ContinuousClock.now+ return try await dispatchModern(modern, context: context, handler: handler, coordinator: coordinator,+ snapshot: (maintenanceEnabled, admittedAt))+ } catch let rejection as MCPModernRejection {+ return modernRejection(rejection)+ } catch let transport as HTTPError {+ return Response(status: transport.status, headers: transport.headers)+ } catch {+ return Response(status: .internalServerError)+ }+ }++ nonisolated private static func dispatchModern(+ _ modern: MCPModernRequest, context: MCPRequestContext, handler: MCPToolHandler,+ coordinator: MCPReadCoordinator, snapshot: (maintenanceEnabled: Bool, admittedAt: ContinuousClock.Instant)+ ) async throws -> Response {+ let (maintenanceEnabled, admittedAt) = snapshot+ switch modern.method {+ case .discover:+ let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0"+ return encodedResponse(try MCPModernDiscovery.encodeDiscovery(id: modern.id,+ identity: MCPModernServerIdentity(name: "transit", version: version)))+ case .listTools:+ return encodedResponse(try MCPModernDiscovery.encodeTools(id: modern.id,+ tools: MCPToolDefinitions.modernTools(includingMaintenance: maintenanceEnabled)))+ case .callTool(let tool, let execution):+ let rpc = MCPModernWire.request(modern, tool: tool)+ if case .coveredRead = execution {+ guard let read = MCPBoundedReadDispatcher.classify(rpc) else {+ throw MCPResultBoundaryError.unsupportedEvidence+ }+ let bytes = try await MCPBoundedReadDispatcher.response(for: read, rpc: rpc,+ handler: handler, coordinator: coordinator, admittedAt: admittedAt,+ encodeWithOperation: { prepared, id, operation in+ try MCPModernProviderBinding.read(prepared, id: id, tool: tool, operation: operation)+ }, encodeConstantToolFailure: { prepared, id in+ try MCPModernProviderBinding.read(prepared, id: id, tool: tool)+ })+ return encodedResponse(bytes)+ }+ switch try await MCPModernProviderBinding.call(rpc, tool: tool, handler: handler,+ maintenanceEnabled: maintenanceEnabled) {+ case .normal(let bytes), .reconciliation(let bytes): return encodedResponse(bytes)+ case .suppressed: return Response(status: .accepted)+ }+ case .listenSubscriptions:+ do {+ return try await toolListChangeStreamResponse(modern: modern, context: context, handler: handler)+ } catch MCPSubscriptionRegistrationError.closed {+ return modernRejection(MCPModernRejection(httpStatus: 503, rpcCode: -32603,+ message: "Subscriptions are closing", id: modern.id, data: nil))+ }+ }+ }++ /// Dispatches one non-empty JSON-RPC batch and builds its HTTP response.+ private static func batchResponse(+ for elements: [BatchElement],+ handler: MCPToolHandler+ ) async -> Response {+ var responses: [JSONRPCResponse] = []+ responses.reserveCapacity(elements.count)++ // Sequential dispatch is intentional. JSON-RPC permits any processing+ // order, and preserving input order keeps side effects deterministic+ // for Transit's shared model context.+ for element in elements {+ switch element {+ case .invalid:+ responses.append(invalidRequestResponse())+ case .request(let rpcRequest):+ // MCP 2025-03-26 lifecycle: initialize MUST NOT be in a batch.+ // Notifications still never get a response.+ if rpcRequest.method == "initialize" {+ if !rpcRequest.isNotification {+ responses.append(JSONRPCResponse.error(+ id: rpcRequest.id,+ code: JSONRPCErrorCode.invalidRequest,+ message: "Invalid Request: initialize must not be batched"+ ))+ }+ } else if let rpcResponse = await handler.handle(rpcRequest) {+ responses.append(rpcResponse)+ }+ }+ }++ // JSON-RPC forbids an empty response array. Streamable HTTP requires+ // 202 with no body when the input is notifications only.+ guard !responses.isEmpty else {+ return Response(status: .accepted)+ }+ return jsonResponse(responses)+ }++ // MARK: - Helpers++ /// Decode an incoming request body as a single JSON-RPC request or a+ /// non-empty JSON-RPC batch, distinguishing transport-level parse failures+ /// from protocol-level shape failures.+ ///+ /// Per JSON-RPC 2.0 §5.1 and §6:+ /// - Malformed JSON produces one `-32700 Parse error` response.+ /// - An invalid single root or an empty batch produces one `-32600 Invalid+ /// Request` response object.+ /// - A non-empty batch preserves every member. Valid request objects are+ /// dispatched, while each invalid member produces its own `-32600`+ /// response in the eventual response array.+ nonisolated static func decodeIncomingRequest(+ _ data: Data+ ) -> DecodeOutcome {+ // Stage 1: confirm the bytes are well-formed JSON. `.fragmentsAllowed`+ // lets scalar roots through so they become Invalid Request rather than+ // Parse error.+ let parsed: Any+ do {+ parsed = try JSONSerialization.jsonObject(+ with: data, options: [.fragmentsAllowed]+ )+ } catch {+ return .failure(JSONRPCResponse.error(+ id: nil,+ code: JSONRPCErrorCode.parseError,+ message: "Parse error"+ ))+ }++ if let batch = parsed as? [Any] {+ guard !batch.isEmpty else {+ return .failure(invalidRequestResponse())+ }+ return .batch(batch.map { element in+ guard let object = element as? [String: Any],+ let request = decodeRequestObject(object) else {+ return .invalid+ }+ return .request(request)+ })+ }++ guard let object = parsed as? [String: Any],+ isValidRequestObjectShape(object),+ let request = try? JSONDecoder().decode(JSONRPCRequest.self, from: data) else {+ return .failure(invalidRequestResponse())+ }+ return .success(request)+ }++ /// Structural checks that `JSONRPCRequest` intentionally leaves lenient.+ /// A missing `jsonrpc` member decodes to `""` so the handler can preserve+ /// T-1106's detailed version error, but a present non-string member is not+ /// a valid Request object. Likewise, present `params` must be the structured+ /// object or array required by JSON-RPC 2.0 §4.2.+ nonisolated private static func isValidRequestObjectShape(+ _ object: [String: Any]+ ) -> Bool {+ guard object["jsonrpc"] == nil || object["jsonrpc"] is String else {+ return false+ }+ guard let params = object["params"] else {+ return true+ }+ return params is [String: Any] || params is [Any]+ }++ nonisolated private static func decodeRequestObject(+ _ object: [String: Any]+ ) -> JSONRPCRequest? {+ guard isValidRequestObjectShape(object),+ let data = try? JSONSerialization.data(withJSONObject: object) else {+ return nil+ }+ return try? JSONDecoder().decode(JSONRPCRequest.self, from: data)+ }++ nonisolated private static func invalidRequestResponse() -> JSONRPCResponse {+ JSONRPCResponse.error(+ id: nil,+ code: JSONRPCErrorCode.invalidRequest,+ message: "Invalid Request"+ )+ }++ /// Validates Origin and Host/authority before body access or dispatch.+ /// This MCP DNS-rebinding defence must remain first in every MCP route.+ nonisolated private static func isAllowedMCPRequest(_ request: Request) -> Bool {+ let origin = request.head.headerFields[.origin]+ return MCPOriginValidator.rejectionReason(+ origin: origin,+ authority: request.head.authority+ ) == nil+ }++ /// Transport-level rejection, not JSON-RPC: fixed plain text avoids+ /// revealing whether Origin or Host validation failed to a prober.+ nonisolated private static func forbiddenResponse() -> Response {+ Response(+ status: .forbidden,+ headers: [.contentType: "text/plain"],+ body: .init(byteBuffer: ByteBuffer(string: "Forbidden"))+ )+ }++}+#endif
diff --git a/Transit/Transit/MCP/MCPServer+ToolListNotifications.swift b/Transit/Transit/MCP/MCPServer+ToolListNotifications.swiftindex be31c30..d730bcf 100644--- a/Transit/Transit/MCP/MCPServer+ToolListNotifications.swift+++ b/Transit/Transit/MCP/MCPServer+ToolListNotifications.swift@@ -7,39 +7,56 @@ import NIOFoundationCompat extension MCPServer { nonisolated static func toolListChangeStreamResponse(- request: Request,- context: MCPRequestContext,- handler: MCPToolHandler- ) async -> Response {- guard acceptsEventStream(request.head.headerFields[.accept]) else {- return Response(status: .methodNotAllowed, headers: [.allow: "POST"])+ modern: MCPModernRequest, context: MCPRequestContext, handler: MCPToolHandler+ ) async throws -> Response {+ var wantsTools = false+ if case .object(let params) = modern.params,+ case .object(let filters) = params.first(where: { $0.name == "notifications" })?.value,+ case .boolean(true) = filters.first(where: { $0.name == "toolsListChanged" })?.value {+ wantsTools = true }- guard let sessionID = request.head.headerFields[.mcpSessionID] else {- return Response(status: .badRequest)- }- guard let notifications = await handler.toolListChangeNotifications(- sessionID: sessionID,- channelClose: context.channel.closeFuture- ) else {- return Response(status: .notFound)- }-- return Response(- status: .ok,- headers: [- .contentType: "text/event-stream",- .cacheControl: "no-cache"- ],+ let subscription = try await handler.subscribeToToolListChanges(id: modern.id,+ toolsListChanged: wantsTools, channelClose: context.channel.closeFuture)+ return Response(status: .ok, headers: [.contentType: "text/event-stream", .cacheControl: "no-cache"], body: ResponseBody { writer in- for await notification in notifications {- try await writer.write(try Self.serverSentEvent(notification))+ try await withTaskCancellationHandler {+ try await writeSubscription(subscription, writer: &writer, handler: handler)+ } onCancel: {+ subscription.delivery.disconnect()+ Task { @MainActor in+ handler.disconnectToolListSubscription(subscription.registrationID)+ } }- try await writer.finish(nil)+ })+ }++ @concurrent nonisolated private static func writeSubscription(+ _ subscription: MCPToolListSubscription, writer: inout any ResponseBodyWriter, handler: MCPToolHandler+ ) async throws {+ do {+ try Task.checkCancellation()+ if subscription.delivery.isWritable {+ try await writer.write(Self.serverSentEvent(subscription.acknowledgement))+ }+ for await change in subscription.changes {+ try Task.checkCancellation()+ guard subscription.delivery.isWritable else { break }+ try await writer.write(Self.serverSentEvent(change)) }- )+ try Task.checkCancellation()+ if subscription.delivery.completesGracefully {+ try await writer.write(Self.serverSentEvent(subscription.completion))+ }+ try await writer.finish(nil)+ await handler.disconnectToolListSubscription(subscription.registrationID)+ } catch {+ subscription.delivery.disconnect()+ await handler.disconnectToolListSubscription(subscription.registrationID)+ throw error+ } } - /// GET listening streams require an explicit, acceptable+ /// Listening streams require an explicit, acceptable /// `text/event-stream` media range. A zero quality value means the client /// does not accept that representation; substring lookalikes are unrelated /// media types and must not negotiate SSE.@@ -145,12 +162,7 @@ extension MCPServer { return nil } - nonisolated private static func serverSentEvent(- _ notification: MCPServerNotification- ) throws -> ByteBuffer {- let encoder = JSONEncoder()- encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]- let payload = try encoder.encode(notification)+ nonisolated private static func serverSentEvent(_ payload: Data) -> ByteBuffer { var event = Data("data: ".utf8) event.append(payload) event.append(contentsOf: [0x0A, 0x0A])
diff --git a/Transit/Transit/MCP/MCPServer.swift b/Transit/Transit/MCP/MCPServer.swiftindex 0d53cdd..aea22c6 100644--- a/Transit/Transit/MCP/MCPServer.swift+++ b/Transit/Transit/MCP/MCPServer.swift@@ -22,6 +22,8 @@ final class MCPServer { } private let toolHandler: MCPToolHandler+ nonisolated let readCoordinator: MCPReadCoordinator+ var listenerGeneration: Int { serverGeneration } private var desiredState: DesiredState = .stopped private var lifecycleTask: Task<Void, Never>? private var activeServer: ActiveServer?@@ -37,8 +39,10 @@ final class MCPServer { /// instead of a bare "Stopped". private(set) var startError: String? - init(toolHandler: MCPToolHandler) {+ init(toolHandler: MCPToolHandler, readCoordinator: MCPReadCoordinator? = nil) { self.toolHandler = toolHandler+ self.readCoordinator = readCoordinator ?? toolHandler.readCoordinator+ precondition(self.readCoordinator === toolHandler.readCoordinator) } } @@ -129,7 +133,9 @@ extension MCPServer { } private func tearDownCurrentServer() async {+ readCoordinator.stop() toolHandler.setTaskQueryAdmission(open: false)+ toolHandler.finishToolListChangeSessions() guard let currentServer = activeServer else { return } // Task cancellation only cancels ServiceGroup's child tasks; it does@@ -142,7 +148,6 @@ extension MCPServer { // as a start failure for a server the caller just asked to stop. serverGeneration += 1 activeServer = nil- toolHandler.finishToolListChangeSessions() await currentServer.serviceGroup.triggerGracefulShutdown() await currentServer.task.value }@@ -150,8 +155,10 @@ extension MCPServer { /// Ignore completion from a listener replaced by a newer generation. func listenerDidExit(generation: Int, failure: String?) { guard serverGeneration == generation else { return }+ readCoordinator.stop() toolHandler.setTaskQueryAdmission(open: false) activeServer = nil+ toolHandler.finishToolListChangeSessions() if let failure { startError = failure } } @@ -160,13 +167,15 @@ extension MCPServer { let currentGeneration = serverGeneration startError = nil + toolHandler.openToolListSubscriptions() toolHandler.setTaskQueryAdmission(open: true)+ readCoordinator.start() let handler = toolHandler let setNotRunning = { @MainActor [weak self] (failure: String?) in self?.listenerDidExit(generation: currentGeneration, failure: failure) } let app = Application(- router: Self.makeRouter(handler: handler),+ router: Self.makeRouter(handler: handler, readCoordinator: readCoordinator), configuration: .init( address: .hostname("127.0.0.1", port: port) )@@ -197,203 +206,4 @@ extension MCPServer { ) } }--extension MCPServer {-- /// Builds the Hummingbird router for the MCP endpoint.- /// POST carries JSON-RPC; GET offers the optional Streamable HTTP SSE- /// channel used for server-initiated notifications.- /// `nonisolated` keeps transport construction independent of MainActor;- /// route callbacks execute on Hummingbird/NIO and hop to MainActor when dispatching.- nonisolated static func makeRouter(handler: MCPToolHandler) -> Router<MCPRequestContext> {- let router = Router(context: MCPRequestContext.self)- router.get("mcp") { request, context -> Response in- guard Self.isAllowedMCPRequest(request) else { return forbiddenResponse() }- return await Self.toolListChangeStreamResponse(- request: request,- context: context,- handler: handler- )- }- router.post("mcp") { request, _ -> Response in- // Validate origin before reading the body.- guard Self.isAllowedMCPRequest(request) else { return forbiddenResponse() }-- let body = try await request.body.collect(upTo: 1_048_576)- let data = Data(buffer: body)-- switch decodeIncomingRequest(data) {- case .success(let rpcRequest):- // A single notification has no JSON-RPC response body.- guard let rpcResponse = await handler.handle(rpcRequest) else {- return Response(status: .accepted)- }- if rpcRequest.method == "initialize", rpcResponse.error == nil {- let sessionID = await handler.createToolListChangeSession()- return jsonResponse(- rpcResponse,- additionalHeaders: [.mcpSessionID: sessionID]- )- }- return jsonResponse(rpcResponse)-- case .batch(let elements):- return await batchResponse(for: elements, handler: handler)-- case .failure(let errorResponse):- return jsonResponse(errorResponse)- }- }- return router- }-- /// Dispatches one non-empty JSON-RPC batch and builds its HTTP response.- private static func batchResponse(- for elements: [BatchElement],- handler: MCPToolHandler- ) async -> Response {- var responses: [JSONRPCResponse] = []- responses.reserveCapacity(elements.count)-- // Sequential dispatch is intentional. JSON-RPC permits any processing- // order, and preserving input order keeps side effects deterministic- // for Transit's shared model context.- for element in elements {- switch element {- case .invalid:- responses.append(invalidRequestResponse())- case .request(let rpcRequest):- // MCP 2025-03-26 lifecycle: initialize MUST NOT be in a batch.- // Notifications still never get a response.- if rpcRequest.method == "initialize" {- if !rpcRequest.isNotification {- responses.append(JSONRPCResponse.error(- id: rpcRequest.id,- code: JSONRPCErrorCode.invalidRequest,- message: "Invalid Request: initialize must not be batched"- ))- }- } else if let rpcResponse = await handler.handle(rpcRequest) {- responses.append(rpcResponse)- }- }- }-- // JSON-RPC forbids an empty response array. Streamable HTTP requires- // 202 with no body when the input is notifications only.- guard !responses.isEmpty else {- return Response(status: .accepted)- }- return jsonResponse(responses)- }-- // MARK: - Helpers-- /// Decode an incoming request body as a single JSON-RPC request or a- /// non-empty JSON-RPC batch, distinguishing transport-level parse failures- /// from protocol-level shape failures.- ///- /// Per JSON-RPC 2.0 §5.1 and §6:- /// - Malformed JSON produces one `-32700 Parse error` response.- /// - An invalid single root or an empty batch produces one `-32600 Invalid- /// Request` response object.- /// - A non-empty batch preserves every member. Valid request objects are- /// dispatched, while each invalid member produces its own `-32600`- /// response in the eventual response array.- nonisolated static func decodeIncomingRequest(- _ data: Data- ) -> DecodeOutcome {- // Stage 1: confirm the bytes are well-formed JSON. `.fragmentsAllowed`- // lets scalar roots through so they become Invalid Request rather than- // Parse error.- let parsed: Any- do {- parsed = try JSONSerialization.jsonObject(- with: data, options: [.fragmentsAllowed]- )- } catch {- return .failure(JSONRPCResponse.error(- id: nil,- code: JSONRPCErrorCode.parseError,- message: "Parse error"- ))- }-- if let batch = parsed as? [Any] {- guard !batch.isEmpty else {- return .failure(invalidRequestResponse())- }- return .batch(batch.map { element in- guard let object = element as? [String: Any],- let request = decodeRequestObject(object) else {- return .invalid- }- return .request(request)- })- }-- guard let object = parsed as? [String: Any],- isValidRequestObjectShape(object),- let request = try? JSONDecoder().decode(JSONRPCRequest.self, from: data) else {- return .failure(invalidRequestResponse())- }- return .success(request)- }-- /// Structural checks that `JSONRPCRequest` intentionally leaves lenient.- /// A missing `jsonrpc` member decodes to `""` so the handler can preserve- /// T-1106's detailed version error, but a present non-string member is not- /// a valid Request object. Likewise, present `params` must be the structured- /// object or array required by JSON-RPC 2.0 §4.2.- nonisolated private static func isValidRequestObjectShape(- _ object: [String: Any]- ) -> Bool {- guard object["jsonrpc"] == nil || object["jsonrpc"] is String else {- return false- }- guard let params = object["params"] else {- return true- }- return params is [String: Any] || params is [Any]- }-- nonisolated private static func decodeRequestObject(- _ object: [String: Any]- ) -> JSONRPCRequest? {- guard isValidRequestObjectShape(object),- let data = try? JSONSerialization.data(withJSONObject: object) else {- return nil- }- return try? JSONDecoder().decode(JSONRPCRequest.self, from: data)- }-- nonisolated private static func invalidRequestResponse() -> JSONRPCResponse {- JSONRPCResponse.error(- id: nil,- code: JSONRPCErrorCode.invalidRequest,- message: "Invalid Request"- )- }-- /// Validates Origin and Host/authority before body access or dispatch.- /// This MCP DNS-rebinding defence must remain first in every MCP route.- nonisolated private static func isAllowedMCPRequest(_ request: Request) -> Bool {- let origin = request.head.headerFields[.origin]- return MCPOriginValidator.rejectionReason(- origin: origin,- authority: request.head.authority- ) == nil- }-- /// Transport-level rejection, not JSON-RPC: fixed plain text avoids- /// revealing whether Origin or Host validation failed to a prober.- nonisolated private static func forbiddenResponse() -> Response {- Response(- status: .forbidden,- headers: [.contentType: "text/plain"],- body: .init(byteBuffer: ByteBuffer(string: "Forbidden"))- )- }--} #endif
diff --git a/Transit/Transit/MCP/MCPSettings.swift b/Transit/Transit/MCP/MCPSettings.swiftindex 0e4a6c2..dc4be5c 100644--- a/Transit/Transit/MCP/MCPSettings.swift+++ b/Transit/Transit/MCP/MCPSettings.swift@@ -1,6 +1,7 @@ #if os(macOS) import Foundation import NIOCore+import NIOConcurrencyHelpers @Observable final class MCPSettings {@@ -8,7 +9,12 @@ final class MCPSettings { private static let enabledKey = "mcpServerEnabled" private static let portKey = "mcpServerPort" private static let maintenanceToolsKey = "mcpMaintenanceToolsEnabled"+ @ObservationIgnored nonisolated private let maintenanceAvailability = NIOLockedValueBox(false) private let toolListChangeBroadcaster = MCPToolListChangeBroadcaster()++ @MainActor var subscriptionBroadcaster: MCPToolListChangeBroadcaster {+ toolListChangeBroadcaster+ } static let defaultPort = 3141 /// Valid TCP port range. Port 0 means "any available port" to the OS and is@@ -32,28 +38,21 @@ final class MCPSettings { didSet { UserDefaults.standard.set(port, forKey: Self.portKey) } } + /// Availability reads never hop to MainActor or inspect preferences.+ nonisolated var maintenanceToolsEnabledSnapshot: Bool {+ maintenanceAvailability.withLockedValue { $0 }+ }+ var maintenanceToolsEnabled: Bool { didSet {+ let enabled = maintenanceToolsEnabled+ maintenanceAvailability.withLockedValue { $0 = enabled } UserDefaults.standard.set(maintenanceToolsEnabled, forKey: Self.maintenanceToolsKey) guard maintenanceToolsEnabled != oldValue else { return } toolListChangeBroadcaster.notifyToolsListChanged() } } - func createToolListChangeSession() -> String {- toolListChangeBroadcaster.createSession()- }-- func toolListChangeNotifications(- sessionID: String,- channelClose: EventLoopFuture<Void>- ) -> AsyncStream<MCPServerNotification>? {- toolListChangeBroadcaster.stream(- sessionID: sessionID,- channelClose: channelClose- )- }- func finishToolListChangeSessions() { toolListChangeBroadcaster.finishAllSessions() }@@ -66,7 +65,9 @@ final class MCPSettings { self.isEnabled = UserDefaults.standard.bool(forKey: Self.enabledKey) let stored = UserDefaults.standard.integer(forKey: Self.portKey) self.port = stored > 0 ? stored : Self.defaultPort- self.maintenanceToolsEnabled = UserDefaults.standard.bool(forKey: Self.maintenanceToolsKey)+ let maintenanceEnabled = UserDefaults.standard.bool(forKey: Self.maintenanceToolsKey)+ self.maintenanceToolsEnabled = maintenanceEnabled+ maintenanceAvailability.withLockedValue { $0 = maintenanceEnabled } } }
diff --git a/Transit/Transit/MCP/MCPSnapshotTaskQueryRequest.swift b/Transit/Transit/MCP/MCPSnapshotTaskQueryRequest.swiftnew file mode 100644index 0000000..862c5cd--- /dev/null+++ b/Transit/Transit/MCP/MCPSnapshotTaskQueryRequest.swift@@ -0,0 +1,63 @@+#if os(macOS)+import Foundation++nonisolated enum MCPSnapshotTaskQueryError: Error, Equatable, Sendable {+ case invalidInput+ case incompatible+ case invalidCursor+}++nonisolated enum MCPSnapshotTaskQueryRequest: Sendable {+ case initial(snapshotId: String, detail: SnapshotTaskDetail, limit: Int, projectId: UUID?, statuses: [String])+ case continuation(cursor: String, policy: MCPReadPolicy?)++ static let supportedStatuses = [+ "idea", "planning", "spec", "ready-for-implementation", "in-progress",+ "ready-for-review", "done", "abandoned"+ ]++ @MainActor static func parse(_ arguments: [String: Any]) throws -> Self {+ if let raw = arguments["cursor"] { return try continuation(arguments, raw: raw) }+ guard Set(arguments.keys).isSubset(of: [+ "snapshotId", "detailLevel", "includeComments", "limit", "projectId", "status"+ ]) else { throw MCPSnapshotTaskQueryError.incompatible }+ guard let snapshotID = arguments["snapshotId"] as? String, UUID(uuidString: snapshotID) != nil,+ let detailString = arguments["detailLevel"] as? String,+ let detail = SnapshotTaskDetail(rawValue: detailString),+ let comments = IntentHelpers.parseBoolValue(arguments["includeComments"]),+ let limit = IntentHelpers.parseIntValue(arguments["limit"]), (1...100).contains(limit) else {+ throw MCPSnapshotTaskQueryError.invalidInput+ }+ guard !comments else { throw MCPSnapshotTaskQueryError.incompatible }+ let projectID: UUID?+ if let raw = arguments["projectId"] {+ guard let string = raw as? String, let id = UUID(uuidString: string) else {+ throw MCPSnapshotTaskQueryError.invalidInput+ }+ projectID = id+ } else { projectID = nil }+ let statuses: [String]+ if let raw = arguments["status"] {+ guard let array = raw as? [String], array.allSatisfy({ supportedStatuses.contains($0) }) else {+ throw MCPSnapshotTaskQueryError.invalidInput+ }+ let selected = Set(array)+ statuses = supportedStatuses.filter { selected.contains($0) }+ } else { statuses = [] }+ return .initial(snapshotId: snapshotID, detail: detail, limit: limit, projectId: projectID, statuses: statuses)+ }+ @MainActor private static func continuation(_ arguments: [String: Any], raw: Any) throws -> Self {+ guard Set(arguments.keys).isSubset(of: ["cursor", "readPolicy"]) else {+ throw MCPSnapshotTaskQueryError.incompatible+ }+ guard let policy = MCPReadRefreshPolicy.parse(arguments["readPolicy"]) else {+ throw MCPSnapshotTaskQueryError.invalidInput+ }+ guard let cursor = raw as? String, MCPCursorFamily.classify(cursor) == .reusable else {+ throw MCPSnapshotTaskQueryError.invalidCursor+ }+ return .continuation(cursor: cursor, policy: arguments["readPolicy"] == nil ? nil : policy)+ }++}+#endif
diff --git a/Transit/Transit/MCP/MCPTaskQueryRequest.swift b/Transit/Transit/MCP/MCPTaskQueryRequest.swiftindex 7c04b38..36465ab 100644--- a/Transit/Transit/MCP/MCPTaskQueryRequest.swift+++ b/Transit/Transit/MCP/MCPTaskQueryRequest.swift@@ -1,21 +1,22 @@ #if os(macOS) import Foundation -struct MCPTaskQueryError: Error {+nonisolated struct MCPTaskQueryError: Error, Sendable { let code: String let message: String static func invalid(_ message: String) -> Self { Self(code: "INVALID_INPUT", message: message) } } -struct MCPTaskQueryRequest {- enum Selector {+struct MCPTaskQueryRequest: Sendable {+ enum Selector: Sendable { case list case single(Int) case taskIDs([String]) case displayIDs([Int]) } + let readPolicy: MCPReadPolicy? let cursor: String? let detailLevel: String let includeComments: Bool@@ -30,16 +31,18 @@ struct MCPTaskQueryRequest { // swiftlint:disable:next cyclomatic_complexity function_body_length static func parse(_ args: [String: Any]) throws -> Self { if let raw = args["cursor"] {- guard args.count == 1 else {+ let policy = try policy(args["readPolicy"])+ guard Set(args.keys).isSubset(of: ["cursor", "readPolicy"]) else { throw MCPTaskQueryError.invalid("Continuation requires only a cursor") } guard let cursor = raw as? String, UUID(uuidString: cursor) != nil else { throw MCPTaskQueryError(code: "INVALID_CURSOR", message: "Invalid cursor; start a new query") }- return Self(cursor: cursor, detailLevel: "summary", includeComments: false, limit: 1, selector: .list)+ return Self(readPolicy: policy, cursor: cursor, detailLevel: "summary",+ includeComments: false, limit: 1, selector: .list) } let allowed = filterKeys.union([- "detailLevel", "includeComments", "limit", "displayId", "taskIds", "displayIds"+ "detailLevel", "includeComments", "limit", "displayId", "taskIds", "displayIds", "readPolicy" ]) guard Set(args.keys).isSubset(of: allowed) else { throw MCPTaskQueryError.invalid("Unknown query field")@@ -82,7 +85,16 @@ struct MCPTaskQueryRequest { } else { selector = .list }- return Self(cursor: nil, detailLevel: detail, includeComments: comments, limit: limit, selector: selector)+ return Self(readPolicy: try policy(args["readPolicy"]), cursor: nil, detailLevel: detail,+ includeComments: comments, limit: limit, selector: selector)+ }++ private static func policy(_ raw: Any?) throws -> MCPReadPolicy? {+ guard let raw else { return nil }+ guard let value = MCPReadRefreshPolicy.parse(raw) else {+ throw MCPTaskQueryError.invalid("readPolicy must be cached or refresh_if_needed")+ }+ return value } private static func batch(_ raw: Any, key: String) throws -> [Any] {
diff --git a/Transit/Transit/MCP/MCPTaskQuerySnapshotStore+PreparedResults.swift b/Transit/Transit/MCP/MCPTaskQuerySnapshotStore+PreparedResults.swiftnew file mode 100644index 0000000..d0ee097--- /dev/null+++ b/Transit/Transit/MCP/MCPTaskQuerySnapshotStore+PreparedResults.swift@@ -0,0 +1,181 @@+#if os(macOS)+import Foundation++extension MCPTaskQuerySnapshotStore {+ nonisolated struct ModernRoot: Sendable {+ let bundle: MCPResultRetainedBundle+ /// Raw compatibility metadata is excluded from bundle.originalCaptureIndexBytes.+ let rawMetadataBytes: Int+ }++ // Retains all page owners, including the first, before visibility. Bundle base must exclude+ // raw metadata supplied here; its separately retained backing is added exactly once per root.+ // swiftlint:disable function_parameter_count cyclomatic_complexity+ func prepare(preparedBundle: MCPResultRetainedBundle, cursors: [String],+ deadline: ContinuousClock.Instant, operationID: UUID, metadataBytes: Data?,+ policy: MCPReadPolicy?, operation: MCPReadOperation? = nil) throws -> MCPPublicationReservation? {+ try Self.check(operation)+ if let operation, operation.id != operationID { throw PublicationRejection.busy }+ purgeExpired()+ guard now() < deadline else { throw expiryError() }+ let owners = preparedBundle.pages+ guard !owners.isEmpty, cursors.count == owners.count - 1,+ Set(cursors).count == cursors.count,+ cursors.allSatisfy({ MCPCursorFamily.classify($0) == .ordinary }) else {+ throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Could not publish query pages")+ }+ let bytes: Int+ do {+ bytes = try Self.add(preparedBundle.charge.totalBytes, metadataBytes?.count ?? 0)+ } catch PublicationRejection.capacity { throw capacityError() }+ guard bytes <= maxBytes else { throw capacityError() }+ guard owners.count > 1 else { return nil }+ let base = try domain.snapshot(for: publicationStoreID)+ guard let original = base.index as? Index else { throw PublicationRejection.busy }+ let tokens = Set(cursors)+ guard base.allocatedTokenSets.allSatisfy({ tokens.isDisjoint(with: $0) }) else {+ throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Could not publish query pages")+ }+ let id = UUID().uuidString+ let root = MCPPublicationRoot(id: id, deadline: deadline, encodedByteCount: bytes,+ tokens: tokens.union([id]))+ var modernRoots = original.modernRoots+ modernRoots[id] = ModernRoot(bundle: preparedBundle, rawMetadataBytes: metadataBytes?.count ?? 0)+ try Self.validateModernOwners(modernRoots, operation: operation)+ var mapping = original.pages+ for (token, owner) in zip(cursors, owners.dropFirst()) {+ try Self.check(operation)+ mapping[token] = MCPRetainedQueryPage(text: owner.source.originalText,+ metadataBytes: metadataBytes, policy: policy, preparedResultPage: owner)+ }+ let candidate = try Index(roots: Array(original.descriptor.roots.values) + [root],+ pages: mapping, modernRoots: modernRoots)+ try Self.check(operation)+ do {+ return try domain.reserve(storeID: publicationStoreID, operationID: operationID,+ expectedVersion: base.version, expectedTokenVersion: base.tokenVersion, index: candidate,+ chargeEntries: 1, chargeBytes: bytes, newTokens: root.tokens, deadline: deadline)+ } catch PublicationRejection.capacity { throw capacityError() } catch PublicationRejection.expired {+ throw expiryError()+ }+ }+ // swiftlint:enable function_parameter_count cyclomatic_complexity++ nonisolated func prepareAggregate(_ publications: [any MCPPreparedPublication],+ in domain: MCPReadPublicationDomain,+ operation: MCPReadOperation) throws -> any MCPPreparedPublication {+ try prepareAggregate(publications, in: domain, checking: operation)+ }++ // The protocol compatibility path still validates fixed additive root ownership; only the+ // operation-aware path remeasures backing with the caller's original checkpoint.+ // swiftlint:disable:next cyclomatic_complexity function_body_length+ nonisolated func prepareAggregate(_ publications: [any MCPPreparedPublication],+ in domain: MCPReadPublicationDomain,+ checking operation: MCPReadOperation?) throws -> any MCPPreparedPublication {+ try Self.check(operation)+ guard domain === self.domain, !publications.isEmpty, publications.count <= 8 else {+ throw PublicationRejection.busy+ }+ let base = try domain.snapshot(for: publicationStoreID)+ guard let index = base.index as? Index else { throw PublicationRejection.busy }+ var roots = index.descriptor.roots+ var pages = index.pages+ var modernRoots = index.modernRoots+ var children: [MCPPublicationReservation] = []+ var pins: [MCPOrdinaryQueryReadPin] = []+ for publication in publications {+ try Self.check(operation)+ if let pin = publication as? MCPOrdinaryQueryReadPin {+ guard pin.domain === domain, pin.publicationStoreID == publicationStoreID else {+ throw PublicationRejection.busy+ }+ pins.append(pin)+ continue+ }+ guard let child = publication as? MCPPublicationReservation,+ child.publicationStoreID == publicationStoreID, child.domain === domain,+ child.expectedVersion == base.version,+ let candidate = child.index as? Index else { throw PublicationRejection.busy }+ children.append(child)+ for (key, root) in candidate.descriptor.roots where index.descriptor.roots[key] == nil {+ try Self.check(operation)+ guard roots[key] == nil else { throw PublicationRejection.busy }+ roots[key] = root+ if let modern = candidate.modernRoots[key] { modernRoots[key] = modern }+ }+ for (token, page) in candidate.pages where index.pages[token] == nil {+ try Self.check(operation)+ guard pages[token] == nil else { throw PublicationRejection.busy }+ pages[token] = page+ }+ }+ if children.isEmpty {+ return MCPOrdinaryQueryGuardedPublication(publicationStoreID: publicationStoreID,+ domain: domain, pins: pins, mutation: nil)+ }+ try Self.validateModernOwners(modernRoots, operation: operation)+ for (id, modern) in modernRoots {+ try Self.check(operation)+ let bytes: Int+ if let operation {+ let measured = try MCPResultPreparation.prepare(pages: modern.bundle.pages,+ budget: MCPResultRetentionBudget(store: .ordinary,+ originalCaptureIndexBytes: modern.bundle.charge.originalCaptureIndexBytes,+ visibleBytes: 0, pendingBytes: 0), checkpoint: {+ try Self.check(operation)+ })+ bytes = try Self.add(measured.charge.totalBytes, modern.rawMetadataBytes)+ } else {+ bytes = try Self.add(modern.bundle.charge.totalBytes, modern.rawMetadataBytes)+ }+ guard roots[id]?.encodedByteCount == bytes else { throw PublicationRejection.busy }+ }+ let candidate = try Index(roots: Array(roots.values), pages: pages, modernRoots: modernRoots)+ try Self.check(operation)+ if let operation {+ if children.count == 1, let child = children.first {+ guard child.operationID == operation.id else { throw PublicationRejection.busy }+ if pins.isEmpty { return child }+ return MCPOrdinaryQueryGuardedPublication(+ publicationStoreID: publicationStoreID, domain: domain, pins: pins, mutation: child)+ }+ // Transfer cannot replace a live child slot with the same UUID. An aggregate operation+ // owns a distinct ID; children keep their own unique IDs until the gapless transfer.+ guard children.allSatisfy({ $0.operationID != operation.id }) else { throw PublicationRejection.busy }+ }+ let mutation = try domain.transfer(children, aggregateIndex: candidate, operationID: operation?.id ?? UUID())+ if pins.isEmpty { return mutation }+ return MCPOrdinaryQueryGuardedPublication(+ publicationStoreID: publicationStoreID, domain: domain, pins: pins, mutation: mutation)+ }++ /// Sharing inside one bundle is intentional. Different roots must own disjoint new page and+ /// metadata allocations, or fixed root charges/retirement would double-charge a shared owner.+ nonisolated private static func validateModernOwners(_ roots: [String: ModernRoot],+ operation: MCPReadOperation?) throws {+ var previous: Set<ObjectIdentifier> = []+ for root in roots.values {+ try check(operation)+ var owners: Set<ObjectIdentifier> = []+ for page in root.bundle.pages {+ try check(operation)+ owners.insert(ObjectIdentifier(page))+ if let metadata = page.metadataOwner { owners.insert(ObjectIdentifier(metadata)) }+ }+ guard previous.isDisjoint(with: owners) else { throw PublicationRejection.busy }+ previous.formUnion(owners)+ }+ }++ nonisolated private static func check(_ operation: MCPReadOperation?) throws {+ if let operation, !operation.shouldContinue() { throw CancellationError() }+ }++ nonisolated private static func add(_ left: Int, _ right: Int) throws -> Int {+ let (total, overflow) = left.addingReportingOverflow(right)+ guard left >= 0, right >= 0, !overflow else { throw PublicationRejection.capacity }+ return total+ }+}+#endif
diff --git a/Transit/Transit/MCP/MCPTaskQuerySnapshotStore.swift b/Transit/Transit/MCP/MCPTaskQuerySnapshotStore.swiftindex d510a57..8354cfe 100644--- a/Transit/Transit/MCP/MCPTaskQuerySnapshotStore.swift+++ b/Transit/Transit/MCP/MCPTaskQuerySnapshotStore.swift@@ -1,80 +1,190 @@ #if os(macOS) import Foundation +nonisolated struct MCPRetainedQueryPage: Sendable {+ private let legacyText: String?+ var text: String { preparedResultPage?.source.originalText ?? legacyText ?? "" }+ let metadataBytes: Data?+ let policy: MCPReadPolicy?+ let preparedResultPage: MCPResultPreparedPage?++ init(text: String, metadataBytes: Data?, policy: MCPReadPolicy?,+ preparedResultPage: MCPResultPreparedPage? = nil) {+ self.legacyText = preparedResultPage == nil ? text : nil+ self.metadataBytes = metadataBytes+ self.policy = policy+ self.preparedResultPage = preparedResultPage+ }+}++nonisolated enum MCPCursorFamily: Sendable {+ case ordinary, reusable+ static func classify(_ token: String) -> Self? {+ guard let uuid = UUID(uuidString: token) else { return nil }+ switch uuid.uuid.6 >> 4 {+ case 4: return .ordinary+ case 8: return .reusable+ default: return nil+ }+ }+}+ @MainActor-final class MCPTaskQuerySnapshotStore {- private struct Snapshot {- let deadline: ContinuousClock.Instant- let pages: [String: String]- let byteCount: Int+final class MCPTaskQuerySnapshotStore: MCPReadPublicationParticipant {+ nonisolated final class Index: MCPPublicationIndex {+ let descriptor: MCPPublicationIndexDescriptor+ let pages: [String: MCPRetainedQueryPage]+ let modernRoots: [String: ModernRoot]+ init(roots: [MCPPublicationRoot] = [], pages: [String: MCPRetainedQueryPage] = [:],+ modernRoots: [String: ModernRoot] = [:]) throws {+ descriptor = try MCPPublicationIndexDescriptor(roots: roots)+ self.pages = pages+ self.modernRoots = modernRoots+ } } let now: () -> ContinuousClock.Instant let wallNow: () -> Date let makeCursor: () -> String let maxBytes: Int- private let maxSnapshots: Int- private var snapshots: [Snapshot] = []- private(set) var retainedBytes = 0-- init(- now: @escaping () -> ContinuousClock.Instant = { .now },- wallNow: @escaping () -> Date = Date.init,- makeCursor: @escaping () -> String = { UUID().uuidString },- maxSnapshots: Int = 8,- maxBytes: Int = 16 * 1024 * 1024- ) {+ nonisolated let publicationStoreID = MCPPublicationStoreID(rawValue: UUID())+ nonisolated let domain: MCPReadPublicationDomain+ var retainedBytes: Int { (try? domain.accounting(for: publicationStoreID).visibleBytes) ?? 0 }++ init(now: @escaping () -> ContinuousClock.Instant = { .now },+ wallNow: @escaping () -> Date = Date.init,+ makeCursor: @escaping () -> String = { UUID().uuidString },+ maxSnapshots: Int = 8, maxBytes: Int = 16 * 1024 * 1024,+ domain: MCPReadPublicationDomain? = nil) { self.now = now self.wallNow = wallNow self.makeCursor = makeCursor- self.maxSnapshots = maxSnapshots self.maxBytes = maxBytes+ self.domain = domain ?? MCPReadPublicationDomain()+ // Fresh private store identity and an empty index cannot collide.+ do {+ try self.domain.register(storeID: publicationStoreID, index: Index(),+ maxEntries: maxSnapshots, maxBytes: maxBytes)+ } catch {+ preconditionFailure("Invalid ordinary retention store configuration: \(error)")+ } } func purgeExpired() {+ guard let base = try? domain.snapshot(for: publicationStoreID), let index = base.index as? Index else { return } let instant = now()- snapshots.removeAll { instant >= $0.deadline }- retainedBytes = snapshots.reduce(0) { $0 + $1.byteCount }+ let roots = index.descriptor.roots.values.filter { instant < $0.deadline }+ guard roots.count != index.descriptor.entryCount else { return }+ let tokens = roots.reduce(into: Set<String>()) { $0.formUnion($1.tokens) }+ guard let replacement = try? Index(roots: roots, pages: index.pages.filter { tokens.contains($0.key) },+ modernRoots: index.modernRoots.filter { key, _ in+ roots.contains { $0.id == key }+ }) else {+ return+ }+ try? domain.retire(storeID: publicationStoreID, expectedVersion: base.version, replacementIndex: replacement) } - func publish(pages: [String], cursors: [String], deadline: ContinuousClock.Instant) throws {+ /// Builds a complete private index and reserves capacity; visibility waits for the response gate.+ func prepare(pages: [String], cursors: [String], deadline: ContinuousClock.Instant,+ operationID: UUID, metadataBytes: Data? = nil, policy: MCPReadPolicy? = nil)+ throws -> MCPPublicationReservation? { purgeExpired()- guard now() < deadline else {- throw MCPTaskQueryError(code: "QUERY_EXPIRED",- message: "Query expired during preparation; start a new query")- }- let bytes = pages.reduce(0) { $0 + $1.utf8.count }+ guard now() < deadline else { throw expiryError() }+ let bytes = pages.reduce(0) { $0 + $1.utf8.count + (metadataBytes?.count ?? 0) } guard bytes <= maxBytes else { throw capacityError() } guard !pages.isEmpty, cursors.count == pages.count - 1, Set(cursors).count == cursors.count,- cursors.allSatisfy({ token in- UUID(uuidString: token) != nil && !snapshots.contains { $0.pages[token] != nil }- }) else {+ cursors.allSatisfy({ MCPCursorFamily.classify($0) == .ordinary }) else {+ throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Could not publish query pages")+ }+ guard pages.count > 1 else { return nil }+ let base = try domain.snapshot(for: publicationStoreID)+ guard let original = base.index as? Index else { throw PublicationRejection.busy }+ guard base.allocatedTokenSets.allSatisfy({ Set(cursors).isDisjoint(with: $0) }) else { throw MCPTaskQueryError(code: "QUERY_FAILED", message: "Could not publish query pages") }- guard pages.count > 1 else { return }- guard snapshots.count < maxSnapshots, retainedBytes <= maxBytes - bytes else { throw capacityError() }- let mapping = Dictionary(uniqueKeysWithValues: zip(cursors, pages.dropFirst()))- snapshots.append(Snapshot(deadline: deadline, pages: mapping, byteCount: bytes))- retainedBytes += bytes+ let id = UUID().uuidString+ let root = MCPPublicationRoot(id: id, deadline: deadline, encodedByteCount: bytes,+ tokens: Set(cursors).union([id]))+ var mapping = original.pages+ for (token, text) in zip(cursors, pages.dropFirst()) {+ mapping[token] = MCPRetainedQueryPage(text: text, metadataBytes: metadataBytes, policy: policy)+ }+ let candidate = try Index(roots: Array(original.descriptor.roots.values) + [root], pages: mapping,+ modernRoots: original.modernRoots)+ do {+ return try domain.reserve(storeID: publicationStoreID, operationID: operationID,+ expectedVersion: base.version, expectedTokenVersion: base.tokenVersion, index: candidate,+ chargeEntries: 1, chargeBytes: bytes, newTokens: root.tokens, deadline: deadline)+ } catch PublicationRejection.capacity { throw capacityError() } catch PublicationRejection.expired {+ throw expiryError()+ }+ }++ func publish(pages: [String], cursors: [String], deadline: ContinuousClock.Instant) throws {+ guard let reservation = try prepare(pages: pages, cursors: cursors, deadline: deadline,+ operationID: UUID()) else { return }+ let rejection = domain.withLock { () -> PublicationRejection? in+ if let rejection = reservation.validateLocked(in: domain) {+ reservation.discardLocked(in: domain)+ return rejection+ }+ reservation.commitLocked(in: domain)+ return nil+ }+ if let rejection {+ if rejection == .expired { throw expiryError() }+ throw MCPTaskQueryError(code: "READ_BUSY", message: "Query publication changed; retry with backoff")+ }+ }++ func retainedPage(for cursor: String) throws -> MCPRetainedQueryPage {+ try preparedRetainedPage(for: cursor).page } - func page(for cursor: String) throws -> String {+ func preparedRetainedPage(for cursor: String) throws+ -> (page: MCPRetainedQueryPage, pin: MCPOrdinaryQueryReadPin) { purgeExpired()- guard let page = snapshots.lazy.compactMap({ $0.pages[cursor] }).first else {- throw MCPTaskQueryError(code: "INVALID_CURSOR", message: "Unknown or expired cursor; start a new query")+ let base = try domain.snapshot(for: publicationStoreID)+ guard let index = base.index as? Index else { throw PublicationRejection.busy }+ // Lookup and token->root work is outside the gate; pin/version and bounded+ // original root expiry are checked together before returning frozen bytes.+ guard let page = index.pages[cursor],+ let root = index.descriptor.roots.values.first(where: { $0.tokens.contains(cursor) }) else {+ throw cursorError() }- return page+ let pin = MCPOrdinaryQueryReadPin(publicationStoreID: publicationStoreID, domain: domain,+ rootID: root.id, cursor: cursor, deadline: root.deadline)+ let valid = domain.withLock { pin.validateLocked(in: domain) == nil }+ guard valid else { throw cursorError() }+ return (page, pin) } + func page(for cursor: String) throws -> String { try retainedPage(for: cursor).text }+ func clear() {- snapshots.removeAll()- retainedBytes = 0+ guard let base = try? domain.snapshot(for: publicationStoreID), let empty = try? Index() else { return }+ try? domain.retire(storeID: publicationStoreID, expectedVersion: base.version, replacementIndex: empty)+ }++ nonisolated func prepareAggregate(+ _ publications: [any MCPPreparedPublication], in domain: MCPReadPublicationDomain+ ) throws -> any MCPPreparedPublication {+ try prepareAggregate(publications, in: domain, checking: nil) } func capacityError() -> MCPTaskQueryError { MCPTaskQueryError(code: "QUERY_CAPACITY_EXCEEDED", message: "Query capacity exceeded; reduce scope/comments or retry after expiry") }++ func expiryError() -> MCPTaskQueryError {+ MCPTaskQueryError(code: "QUERY_EXPIRED", message: "Query expired during preparation; start a new query")+ }++ private func cursorError() -> MCPTaskQueryError {+ MCPTaskQueryError(code: "INVALID_CURSOR", message: "Unknown or expired cursor; start a new query")+ } } #endif
diff --git a/Transit/Transit/MCP/MCPToolDefinitions.swift b/Transit/Transit/MCP/MCPToolDefinitions.swiftindex ba03298..d312595 100644--- a/Transit/Transit/MCP/MCPToolDefinitions.swift+++ b/Transit/Transit/MCP/MCPToolDefinitions.swift@@ -1,11 +1,13 @@ #if os(macOS)+import Foundation // MARK: - Tool Definitions nonisolated enum MCPToolDefinitions { static let coreTools: [MCPToolDefinition] = [ createTask, updateTaskStatus, queryTasks, addComment, getProjects, createProject,- createMilestone, queryMilestones, updateMilestone, deleteMilestone, updateTask+ createMilestone, queryMilestones, updateMilestone, deleteMilestone, updateTask,+ MCPPortfolioToolDefinitions.queryProjectSummaries ] static let maintenanceTools: [MCPToolDefinition] = [@@ -21,6 +23,18 @@ nonisolated enum MCPToolDefinitions { includingMaintenance ? coreTools + maintenanceTools : coreTools } + /// Uses the same selected definitions without altering their public input contracts.+ static func modernTools(includingMaintenance: Bool) throws -> [MCPModernToolDescriptor] {+ try tools(includingMaintenance: includingMaintenance).map { definition in+ MCPModernToolDescriptor(+ name: definition.name,+ description: definition.description,+ inputSchema: try MCPJSONDocument.parse(JSONEncoder().encode(definition.inputSchema)),+ resultSchema: try MCPResultSchemas.descriptor(+ tool: definition.name, description: definition.description))+ }+ }+ /// Names of tools gated behind `MCPSettings.maintenanceToolsEnabled`, /// derived from `maintenanceTools` so adding a tool there is a single edit. static let maintenanceToolNames: Set<String> = Set(maintenanceTools.map(\.name))@@ -121,7 +135,9 @@ extension MCPToolDefinitions { (TASK_NOT_FOUND/AMBIGUOUS_TASK_ID). Full detail includes nullable description, nonempty metadata and a revision covering complete comment state. Full reads fetch comments even when includeComments=false; that option omits only their payload. Summary reads with includeComments=false do not fetch comments.- Continue with only cursor. Results are frozen for five minutes; replay does not extend expiry.+ A new ordinary query creates a new capture. Continue with cursor and optionally the identical retained readPolicy;+ frozen cursor replay never captures or refreshes again. Results expire five minutes after the original capture;+ replay does not extend expiry. There is no automatic retry. Whole-query errors are {error:{code,message}}: INVALID_INPUT, AMBIGUOUS_TASK_ID, AMBIGUOUS_FILTER, QUERY_FAILED, INVALID_CURSOR (start a new query), QUERY_EXPIRED, QUERY_UNAVAILABLE, or QUERY_CAPACITY_EXCEEDED (reduce scope/comments or retry after expiry). Unknown fields are rejected.@@ -162,12 +178,14 @@ extension MCPToolDefinitions { ] nonisolated static let queryTasks = MCPToolDefinition(- name: "query_tasks", description: queryTasksDescription,+ name: "query_tasks",+ description: queryTasksDescription + "\n\n" + readExecutionDescription+ + "\n\n" + MCPPortfolioToolDefinitions.snapshotTaskQueryDescription, inputSchema: JSONSchema(type: "object", properties: nil, required: nil, oneOf: [ JSONSchema(type: "object", properties: queryTaskProperties, required: ["detailLevel", "includeComments", "limit"], additionalProperties: false),- JSONSchema(type: "object", properties: ["cursor": .string("Opaque next-page cursor; send alone")],- required: ["cursor"], additionalProperties: false)+ MCPPortfolioToolDefinitions.reusableContinuationSchema,+ MCPPortfolioToolDefinitions.snapshotTaskQueryInitialSchema ]) ) @@ -208,7 +226,8 @@ extension MCPToolDefinitions { nonisolated static let getProjects = MCPToolDefinition( name: "get_projects",- description: "List all projects with metadata. Returns an array of project objects sorted by name.",+ description: "List all projects with metadata. Returns an array of project objects sorted by name."+ + "\n\n" + readExecutionDescription, inputSchema: .object(properties: [:], required: []) ) @@ -239,7 +258,7 @@ extension MCPToolDefinitions { nonisolated static let queryMilestones = MCPToolDefinition( name: "query_milestones",- description: queryMilestonesDescription,+ description: queryMilestonesDescription + "\n\n" + readExecutionDescription, inputSchema: .object( properties: [ "displayId": .integer("Milestone display ID for single-milestone lookup (e.g. 3 for M-3)"),
diff --git a/Transit/Transit/MCP/MCPToolHandler+CapturedRead.swift b/Transit/Transit/MCP/MCPToolHandler+CapturedRead.swiftnew file mode 100644index 0000000..d31144d--- /dev/null+++ b/Transit/Transit/MCP/MCPToolHandler+CapturedRead.swift@@ -0,0 +1,34 @@+#if os(macOS)+import Foundation++nonisolated struct MCPReadToolRequest: Sendable {+ let tool: String+ let arguments: [String: AnyCodable]+}++extension MCPToolHandler {+ /// Covered tools prepare privately after independent transport admission.+ func prepareCoveredRead(_ request: MCPReadToolRequest,+ operation: MCPReadOperation) async throws -> MCPPreparedToolRead {+ operation.finishActorQueue()+ guard let readService else {+ let metadata = ReadFailureMetadata(requestId: operation.id.uuidString, category: .storageFailure,+ read: ReadExecutionMetadata(policy: .refreshIfNeeded, refreshOutcome: .unavailable, budgetMs: 5_000))+ return try MCPPreparedToolRead(text: "Saved read capture service is unavailable", isError: true,+ metadata: .failure(metadata),+ providerEvidence: MCPResultProviderEvidence(+ origin: .plainText, evidence: .established))+ }+ let arguments = request.arguments.mapValues(\.value)+ if request.tool == "query_project_summaries" {+ return try await preparePortfolioRead(arguments: arguments, service: readService, operation: operation)+ }+ if request.tool == "query_tasks",+ arguments["snapshotId"] != nil+ || (arguments["cursor"] as? String).map({ MCPCursorFamily.classify($0) == .reusable }) == true {+ return try prepareSnapshotRead(arguments: arguments, service: readService, operation: operation)+ }+ return try await readService.prepare(tool: request.tool, arguments: arguments, operation: operation)+ }+}+#endif
diff --git a/Transit/Transit/MCP/MCPToolHandler+PortfolioReadPreparation.swift b/Transit/Transit/MCP/MCPToolHandler+PortfolioReadPreparation.swiftnew file mode 100644index 0000000..33b4518--- /dev/null+++ b/Transit/Transit/MCP/MCPToolHandler+PortfolioReadPreparation.swift@@ -0,0 +1,76 @@+#if os(macOS)+import Foundation++/// Shared admission/capture binding only. Portfolio-owned helpers supply projection and retention.+extension MCPToolHandler {+ func preparePortfolioRead(arguments: [String: Any], service: MCPReadService,+ operation: MCPReadOperation) async throws -> MCPPreparedToolRead {+ var policy = MCPReadPolicy.refreshIfNeeded+ do {+ let request = try MCPPortfolioSummaryRequest.parse(arguments)+ if case let .initial(_, _, _, requestedPolicy) = request { policy = requestedPolicy }+ if case let .continuation(_, requestedPolicy) = request { policy = requestedPolicy ?? policy }+ try requireReusableReadAvailability()+ switch request {+ case let .initial(_, _, project, requestedPolicy):+ policy = requestedPolicy+ let captureRequest = ReadCaptureRequest(projectSelectors: project.map { [$0] },+ selection: .portfolio, completeness: .completePortfolio, includeComments: false)+ return try await service.prepareCapturedRead(request: captureRequest, policy: policy,+ operation: operation) { [self] capsule, operation in+ // Forward the original capsule, including its exact metadata bytes, without reconstruction.+ try handlePortfolioSummary(request: request, capture: capsule, operation: operation)+ }+ case .replay:+ return try handlePortfolioSummary(request: request, capture: nil, operation: operation)+ case let .continuation(_, requestedPolicy):+ policy = requestedPolicy ?? policy+ return try handlePortfolioSummary(request: request, capture: nil, operation: operation)+ }+ } catch let error as MCPPortfolioRequestError {+ return try portfolioInputFailure(code: error.code, message: error.message)+ } catch MCPReadCaptureError.projectNotFound {+ return try portfolioInputFailure(code: "PROJECT_NOT_FOUND", message: "Project not found")+ } catch MCPReadCaptureError.ambiguousProject {+ return try portfolioInputFailure(code: "AMBIGUOUS_PROJECT", message: "Project selector is ambiguous")+ } catch {+ return try service.prepareFailure(error, tool: "query_project_summaries",+ operation: operation, policy: policy)+ }+ }++ func prepareSnapshotRead(arguments: [String: Any], service: MCPReadService,+ operation: MCPReadOperation) throws -> MCPPreparedToolRead {+ var policy = MCPReadPolicy.refreshIfNeeded+ do {+ let request = try MCPSnapshotTaskQueryRequest.parse(arguments)+ if case let .continuation(_, requestedPolicy) = request { policy = requestedPolicy ?? policy }+ try requireReusableReadAvailability()+ // Retained snapshot/cursor reads never capture or reassess import freshness.+ return try handleSnapshotTaskQuery(request: request, operation: operation)+ } catch let error as MCPSnapshotTaskQueryError {+ switch error {+ case .invalidInput:+ return try portfolioInputFailure(code: "INVALID_INPUT", message: "Invalid snapshot task arguments")+ case .incompatible:+ return try portfolioInputFailure(code: "SNAPSHOT_INCOMPATIBLE",+ message: "Arguments are incompatible with the retained snapshot")+ case .invalidCursor:+ return try portfolioInputFailure(code: "INVALID_CURSOR", message: "Invalid reusable cursor")+ }+ } catch {+ return try service.prepareFailure(error, tool: "query_tasks", operation: operation, policy: policy)+ }+ }++ private func requireReusableReadAvailability() throws {+ if let error = reusableSnapshotLifecycleFailure { throw error }+ _ = try reusableSnapshots.get()+ }++ private func portfolioInputFailure(code: String, message: String) throws -> MCPPreparedToolRead {+ try MCPPreparedToolRead(text: IntentHelpers.encodeJSON(["error": ["code": code, "message": message]]),+ isError: true)+ }+}+#endif
diff --git a/Transit/Transit/MCP/MCPToolHandler+PortfolioSummary.swift b/Transit/Transit/MCP/MCPToolHandler+PortfolioSummary.swiftnew file mode 100644index 0000000..392b50b--- /dev/null+++ b/Transit/Transit/MCP/MCPToolHandler+PortfolioSummary.swift@@ -0,0 +1,86 @@+#if os(macOS)+import Foundation++extension MCPToolHandler {+ nonisolated func handlePortfolioSummary(+ request: MCPPortfolioSummaryRequest, capture: MCPPreparedReadCapture?, operation: MCPReadOperation+ ) throws -> MCPPreparedToolRead {+ let cursorRequest: Bool+ if case .continuation = request { cursorRequest = true } else { cursorRequest = false }+ do {+ try MCPPortfolioReadEncoding.check(operation)+ let store = try reusableSnapshots.get()+ switch request {+ case .initial:+ guard let capture else { throw MCPReadCaptureError.incoherentCapture }+ return try preparePortfolioCapture(capture, request: request, store: store, operation: operation)+ case .replay(let snapshotID):+ let pinned = try store.preparedResultView(for: snapshotID, now: retainedReadInstant(store))+ try MCPPortfolioReadEncoding.check(operation)+ return MCPPreparedToolRead(preparedResultPage: pinned.firstPage,+ frozenMetadataBytes: pinned.root.frozenMetadataBytes, publications: [pinned.pin])+ case .continuation(let cursor, let policy):+ let pinned = try store.preparedResultPage(for: cursor, now: retainedReadInstant(store))+ try requireRetainedPolicy(policy, root: pinned.page.root)+ try MCPPortfolioReadEncoding.check(operation)+ return MCPPreparedToolRead(preparedResultPage: pinned.preparedPage,+ frozenMetadataBytes: pinned.page.root.frozenMetadataBytes, publications: [pinned.pin])+ }+ } catch {+ if let failure = try MCPPortfolioReadEncoding.normalized(error, cursor: cursorRequest) { return failure }+ throw error+ }+ }++ nonisolated private func preparePortfolioCapture(+ _ capture: MCPPreparedReadCapture, request: MCPPortfolioSummaryRequest,+ store: MCPReusableSnapshotStore, operation: MCPReadOperation+ ) throws -> MCPPreparedToolRead {+ guard case .initial(let window, let limit, _, _) = request else {+ throw MCPReadCaptureError.incoherentCapture+ }+ let summary = try PortfolioSummaryService.summarize(view: capture.view, window: window)+ try MCPPortfolioReadEncoding.check(operation)+ let pages = try MCPPortfolioReadEncoding.summaryPages(summary, view: capture.view, limit: limit,+ operation: operation)+ let reads = try pages.pages.map {+ try MCPPortfolioReadEncoding.check(operation)+ return try MCPPortfolioReadEncoding.prepared($0, metadata: capture.frozenMetadataBytes)+ }+ let owners = try MCPModernProviderBinding.prepareReadPages(reads,+ tool: "query_project_summaries", operation: operation)+ guard owners.count == reads.count, let firstOwner = owners.first, let first = reads.first else {+ throw MCPReadCaptureError.serializationFailure+ }+ let root = RetainedView(capture: capture.view, frozenMetadataBytes: capture.frozenMetadataBytes,+ window: window, initialRequest: request, firstPage: pages.pages[0], preparedResultPage: firstOwner)+ let captureBytes = try MCPPortfolioCaptureCharge.bytes(capture, operation: operation)+ let legacyBytes = try pages.pages.reduce(captureBytes) { total, bytes in+ try MCPPortfolioReadEncoding.check(operation)+ return try MCPResultRetentionAccounting.add(total, bytes.count)+ }+ let budget = try store.preparedResultBudget(originalCaptureIndexBytes: legacyBytes, operation: operation)+ let measured = try MCPResultPreparation.prepare(pages: owners, budget: budget,+ checkpoint: { try MCPPortfolioReadEncoding.check(operation) })+ let bundle = EncodedViewBundle(root: root, pages: Array(pages.pages.dropFirst()), cursors: pages.cursors,+ encodedCaptureByteCount: captureBytes, preparedResultBundle: measured)+ try MCPPortfolioReadEncoding.check(operation)+ let reservation = try store.reservePreparedCreate(bundle: bundle, preparedResults: measured,+ operation: operation, publicationDeadline: MCPPortfolioReadEncoding.publicationDeadline(operation))+ var attached = false+ defer { if !attached { try? store.rollback(reservation) } }+ let publication = try store.prepare(reservation: reservation)+ try MCPPortfolioReadEncoding.check(operation)+ attached = true+ return first.attachingPreparedResultPage(firstOwner).attaching([publication])+ }++ nonisolated func retainedReadInstant(_ store: MCPReusableSnapshotStore) -> ContinuousClock.Instant {+ store.domain.withLock { store.domain.currentInstantLocked }+ }++ nonisolated func requireRetainedPolicy(_ policy: MCPReadPolicy?, root: RetainedView) throws {+ if let policy, policy != root.capture.metadata.read.policy { throw MCPReusableSnapshotError.incompatible }+ }+}+#endif
diff --git a/Transit/Transit/MCP/MCPToolHandler+SnapshotTaskQuery.swift b/Transit/Transit/MCP/MCPToolHandler+SnapshotTaskQuery.swiftnew file mode 100644index 0000000..6a349e1--- /dev/null+++ b/Transit/Transit/MCP/MCPToolHandler+SnapshotTaskQuery.swift@@ -0,0 +1,52 @@+#if os(macOS)+import Foundation++extension MCPToolHandler {+ nonisolated func handleSnapshotTaskQuery(+ request: MCPSnapshotTaskQueryRequest, operation: MCPReadOperation+ ) throws -> MCPPreparedToolRead {+ let cursorRequest: Bool+ if case .continuation = request { cursorRequest = true } else { cursorRequest = false }+ do {+ try MCPPortfolioReadEncoding.check(operation)+ let store = try reusableSnapshots.get()+ switch request {+ case .initial(let snapshotID, _, _, _, _):+ let pinned = try store.preparedResultView(for: snapshotID, now: retainedReadInstant(store))+ let plan = try MCPPortfolioProjection.query(root: pinned.root, request: request)+ try MCPPortfolioReadEncoding.check(operation)+ let reads = try ([plan.firstPage] + plan.pages).map {+ try MCPPortfolioReadEncoding.check(operation)+ return try MCPPortfolioReadEncoding.prepared($0, metadata: pinned.root.frozenMetadataBytes)+ }+ let owners = try MCPModernProviderBinding.prepareReadPages(reads,+ tool: "query_tasks", operation: operation)+ guard owners.count == reads.count, let firstOwner = owners.first, let first = reads.first else {+ throw MCPReadCaptureError.serializationFailure+ }+ let reservation = try store.reservePreparedAppend(snapshotID: snapshotID,+ pages: plan.pages, cursors: plan.cursors, preparedPages: owners, operation: operation,+ publicationDeadline: MCPPortfolioReadEncoding.publicationDeadline(operation))+ var attached = false+ defer { if !attached { try? store.rollback(reservation) } }+ _ = try store.prepare(reservation: reservation)+ // The original pin protects against same-ID root recreation during projection.+ let publication = MCPReusableSnapshotGuardedPublication(publicationStoreID: store.publicationStoreID,+ domain: store.domain, pins: [pinned.pin], mutation: reservation.publication)+ try MCPPortfolioReadEncoding.check(operation)+ attached = true+ return first.attachingPreparedResultPage(firstOwner).attaching([publication])+ case .continuation(let cursor, let policy):+ let pinned = try store.preparedResultPage(for: cursor, now: retainedReadInstant(store))+ try requireRetainedPolicy(policy, root: pinned.page.root)+ try MCPPortfolioReadEncoding.check(operation)+ return MCPPreparedToolRead(preparedResultPage: pinned.preparedPage,+ frozenMetadataBytes: pinned.page.root.frozenMetadataBytes, publications: [pinned.pin])+ }+ } catch {+ if let failure = try MCPPortfolioReadEncoding.normalized(error, cursor: cursorRequest) { return failure }+ throw error+ }+ }+}+#endif
diff --git a/Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift b/Transit/Transit/MCP/MCPToolHandler+TaskQuery.swiftindex 39ee35a..be20b2f 100644--- a/Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift+++ b/Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift@@ -23,7 +23,9 @@ extension MCPToolHandler { } private func queryErrorResult(_ error: MCPTaskQueryError) -> MCPToolResult {- errorResult(IntentHelpers.encodeJSON(["error": ["code": error.code, "message": error.message]]))+ let category = MCPResultClassification.category(for: error.code) ?? .unclassifiedHistorical+ return errorResult(IntentHelpers.encodeJSON(["error": ["code": error.code, "message": error.message]]),+ category: category, origin: .generatedJSON) } private func queryResults(_ request: MCPTaskQueryRequest, args: [String: Any]) throws -> [[String: Any]] {
diff --git a/Transit/Transit/MCP/MCPToolHandler.swift b/Transit/Transit/MCP/MCPToolHandler.swiftindex 0c492b5..53827db 100644--- a/Transit/Transit/MCP/MCPToolHandler.swift+++ b/Transit/Transit/MCP/MCPToolHandler.swift@@ -24,23 +24,32 @@ final class MCPToolHandler { let milestoneFetcher: any MilestoneFetching let milestoneDisplayIDFinder: any MilestoneDisplayIDFinding private let maintenanceService: DisplayIDMaintenanceService- private let settings: MCPSettings+ private nonisolated let settings: MCPSettings private let persistence: PersistenceAvailability private let writeCoordinator: MCPWriteCoordinator? + /// Task14 fault seam declaration; task15 binds only the post-effect provider encoding stage.+ let maintenanceReassignmentEncoder: (@Sendable (ReassignmentResult) throws -> String)?++ let readService: MCPReadService? let taskQuerySnapshots: MCPTaskQuerySnapshotStore+ nonisolated let reusableSnapshots: Result<MCPReusableSnapshotStore, Error>+ private(set) var reusableSnapshotLifecycleFailure: Error? private(set) var taskQueryAdmissionOpen = true func setTaskQueryAdmission(open: Bool) { taskQueryAdmissionOpen = open- taskQuerySnapshots.clear()+ clearTaskQuerySnapshots() } - func clearTaskQuerySnapshots() { taskQuerySnapshots.clear() }+ func clearTaskQuerySnapshots() {+ taskQuerySnapshots.clear()+ do { try reusableSnapshots.get().invalidate() } catch { reusableSnapshotLifecycleFailure = error }+ } /// Tools that only read. private static let readOnlyToolNames: Set<String> = [- "query_tasks", "query_milestones", "get_projects", "scan_duplicate_display_ids"+ "query_tasks", "query_milestones", "get_projects", "query_project_summaries", "scan_duplicate_display_ids" ] /// Tools blocked while fallback storage is active. Derived by subtracting the read-only@@ -50,6 +59,8 @@ final class MCPToolHandler { MCPToolDefinitions.tools(includingMaintenance: true).map(\.name) ).subtracting(readOnlyToolNames) + nonisolated let readCoordinator: MCPReadCoordinator+ init( taskService: TaskService, projectService: ProjectService,@@ -63,7 +74,11 @@ final class MCPToolHandler { milestoneFetcher: (any MilestoneFetching)? = nil, milestoneDisplayIDFinder: (any MilestoneDisplayIDFinding)? = nil, taskQuerySnapshots: MCPTaskQuerySnapshotStore? = nil,- writeCoordinator: MCPWriteCoordinator? = nil+ writeCoordinator: MCPWriteCoordinator? = nil,+ readService: MCPReadService? = nil,+ readCoordinator: MCPReadCoordinator? = nil,+ reusableSnapshots: MCPReusableSnapshotStore? = nil,+ maintenanceReassignmentEncoder: (@Sendable (ReassignmentResult) throws -> String)? = nil ) { self.taskService = taskService self.taskFetcher = taskFetcher ?? taskService@@ -75,24 +90,76 @@ final class MCPToolHandler { self.maintenanceService = maintenanceService self.settings = settings self.persistence = persistence ?? .shared- self.taskQuerySnapshots = taskQuerySnapshots ?? MCPTaskQuerySnapshotStore()+ self.taskQuerySnapshots = taskQuerySnapshots ?? readService?.snapshots ?? MCPTaskQuerySnapshotStore()+ let domain = self.taskQuerySnapshots.domain+ let coordinator = readCoordinator ?? MCPReadCoordinator(+ domain: domain, diagnostics: readService?.diagnostics ?? .disabled)+ self.readCoordinator = coordinator+ self.reusableSnapshots = Result {+ guard coordinator.domain === domain,+ readService == nil || readService?.snapshots.domain === domain else {+ throw PublicationRejection.busy+ }+ if let reusableSnapshots {+ guard reusableSnapshots.domain === domain else {+ throw PublicationRejection.busy+ }+ return reusableSnapshots+ }+ return try MCPReusableSnapshotStore(domain: domain)+ } self.writeCoordinator = writeCoordinator+ self.maintenanceReassignmentEncoder = maintenanceReassignmentEncoder+ self.readService = readService+ }++ /// One immutable request snapshot; no MainActor hop or defaults access at admission.+ nonisolated var modernMaintenanceEnabled: Bool { settings.maintenanceToolsEnabledSnapshot }++ /// Delegates pure input validation to the existing write validator. Acceptance, receipts,+ /// persistence and effects remain exclusively owned by the write coordinator.+ func modernPreflight(_ request: JSONRPCRequest, tool: String) -> MCPModernProviderPreflight {+ guard let params = request.params?.value as? [String: Any] else {+ return .requestError(JSONRPCError(code: JSONRPCErrorCode.invalidParams,+ message: "Missing tool name", data: nil))+ }+ let arguments: [String: Any]+ switch parseArgumentsEnvelope(params) {+ case .success(let value): arguments = value+ case .failure(.message(let message)):+ return .requestError(JSONRPCError(code: JSONRPCErrorCode.invalidParams, message: message, data: nil))+ }+ var recovery: MCPMutationRecoveryContext?+ if MCPWriteCommand.protectedTools.contains(tool) {+ do {+ let command = try MCPWriteCommand.validate(tool: tool, arguments: arguments)+ recovery = .protectedWrite(MCPProtectedRecoveryKey(tool: tool, idempotencyKey: command.key))+ } catch {+ let result = MCPWriteOutcome.result(MCPWriteOutcome.failure(tool: tool,+ key: arguments["idempotencyKey"] as? String, failure: MCPWriteFailure.from(error),+ accepted: false), isError: true)+ return .rejected(result)+ }+ } else if tool == "reassign_duplicate_display_ids" {+ recovery = .unprotectedMaintenance(tool: tool)+ }+ return .ready(MCPResultContext(tool: tool, semanticFailure: nil,+ mutationRecovery: recovery, entityPositions: [])) } // MARK: - JSON-RPC Dispatch - func createToolListChangeSession() -> String {- settings.createToolListChangeSession()+ func subscribeToToolListChanges(+ id: JSONRPCId, toolsListChanged: Bool, channelClose: EventLoopFuture<Void>+ ) throws -> MCPToolListSubscription {+ try settings.subscriptionBroadcaster.subscribe(id: id, toolsListChanged: toolsListChanged,+ channelClose: channelClose) } - func toolListChangeNotifications(- sessionID: String,- channelClose: EventLoopFuture<Void>- ) -> AsyncStream<MCPServerNotification>? {- settings.toolListChangeNotifications(- sessionID: sessionID,- channelClose: channelClose- )+ func openToolListSubscriptions() { settings.subscriptionBroadcaster.openRequests() }++ func disconnectToolListSubscription(_ registrationID: UUID) {+ settings.subscriptionBroadcaster.disconnect(registrationID) } func finishToolListChangeSessions() {@@ -104,11 +171,11 @@ final class MCPToolHandler { } /// Returns `nil` for JSON-RPC notifications (no response required).- func handle(_ request: JSONRPCRequest) async -> JSONRPCResponse? {+ func handle(_ request: JSONRPCRequest, maintenanceEnabled: Bool? = nil) async -> JSONRPCResponse? { // MCP 2025-03-26 requires a present request id to be a string or // integer. `JSONRPCRequest` preserves presence separately because an // omitted id is a notification while an explicit null is invalid.- guard request.isNotification || request.id != nil else {+ guard !request.isNotification, request.id != nil else { return JSONRPCResponse.error( id: nil, code: JSONRPCErrorCode.invalidRequest,@@ -134,7 +201,8 @@ final class MCPToolHandler { case "tools/list": response = handleToolsList(id: request.id) case "tools/call":- response = await handleToolCall(id: request.id, params: request.params)+ response = await handleToolCall(id: request.id, params: request.params,+ maintenanceEnabled: maintenanceEnabled ?? settings.maintenanceToolsEnabledSnapshot) default: response = JSONRPCResponse.error( id: request.id,@@ -255,7 +323,8 @@ final class MCPToolHandler { // swiftlint:disable:next cyclomatic_complexity function_body_length private func handleToolCall( id: JSONRPCId?,- params: AnyCodable?+ params: AnyCodable?,+ maintenanceEnabled: Bool ) async -> JSONRPCResponse { guard let dict = params?.value as? [String: Any], let name = dict["name"] as? String@@ -279,7 +348,7 @@ final class MCPToolHandler { // callers can tell a disabled tool from an unknown one (AC 5.5). The // outer tools/call method is supported; only its tool-name parameter is // invalid under the negotiated MCP protocol contract.- if MCPToolDefinitions.maintenanceToolNames.contains(name), !settings.maintenanceToolsEnabled {+ if MCPToolDefinitions.maintenanceToolNames.contains(name), !maintenanceEnabled { return JSONRPCResponse.error( id: id, code: JSONRPCErrorCode.invalidParams,@@ -318,7 +387,7 @@ final class MCPToolHandler { // action that could act on a stale read is blocked by this same gate. if Self.mutatingToolNames.contains(name), persistence.isFallbackStorageActive { return JSONRPCResponse.success(- id: id, result: errorResult(PersistenceAvailability.unavailableHint)+ id: id, result: errorResult(PersistenceAvailability.unavailableHint, category: .storageFailure) ) } @@ -350,18 +419,25 @@ final class MCPToolHandler { private func handleScanDuplicateDisplayIds() -> MCPToolResult { do { let report = try maintenanceService.scanDuplicates()- return textResult(try IntentHelpers.encodeAsJSONString(report))+ do { return textResult(try IntentHelpers.encodeAsJSONString(report)) } catch {+ return errorResult("Failed to encode duplicate report: \(error.localizedDescription)",+ category: .serializationFailure) } } catch {- return errorResult("Failed to scan duplicates: \(error.localizedDescription)")+ return errorResult("Failed to scan duplicates: \(error.localizedDescription)", category: .storageFailure) } } private func handleReassignDuplicateDisplayIds() async -> MCPToolResult { let result = await maintenanceService.reassignDuplicates() do {- return textResult(try IntentHelpers.encodeAsJSONString(result))+ let text = try maintenanceReassignmentEncoder?(result) ?? IntentHelpers.encodeAsJSONString(result)+ return textResult(text) } catch {- return errorResult("Failed to encode reassignment result: \(error.localizedDescription)")+ let message = "Failed to encode reassignment result: \(error.localizedDescription)"+ return MCPToolResult(content: [.text(message)],+ isError: true, providerEvidence: MCPResultProviderEvidence(origin: .plainText,+ evidence: .unestablished, failure: MCPResultFailure(category: .outcomeUncertain, diagnostic: nil),+ requiresPreparedReconciliation: true)) } } @@ -381,7 +457,7 @@ extension MCPToolHandler { switch resolveProjectFilter(args) { case .resolved(let pid): projectFilter = pid case .none: projectFilter = nil- case .error(let message): return errorResult(message)+ case .error(let message, let category): return errorResult(message, category: category) } // Status filter — validate enum values before filtering [T-732]@@ -407,7 +483,7 @@ extension MCPToolHandler { do { allMilestones = try milestoneService.fetchAllMilestones() } catch {- return errorResult("Failed to fetch milestones: \(error)")+ return errorResult("Failed to fetch milestones: \(error)", category: .storageFailure) } let filtered = allMilestones.filter { milestoneMatches($0, args: args, projectFilter: projectFilter) }@@ -415,7 +491,7 @@ extension MCPToolHandler { do { let results = try filtered.map { try milestoneToDict($0, formatter: formatter) } return textResult(IntentHelpers.encodeJSONArray(results))- } catch { return errorResult("Failed to capture milestones: \(error)") }+ } catch { return errorResult("Failed to capture milestones: \(error)", category: .storageFailure) } } /// Returns true when `milestone` satisfies the project/status/search filters in `args`.@@ -454,34 +530,36 @@ extension MCPToolHandler { } catch MilestoneService.Error.milestoneNotFound { return textResult(IntentHelpers.encodeJSONArray([])) } catch MilestoneService.Error.duplicateDisplayID {- return errorResult("Duplicate milestone identifier detected for displayId \(displayId)")+ return errorResult("Duplicate milestone identifier detected for displayId \(displayId)",+ category: .ambiguousIdentity) } catch {- return errorResult("Failed to look up milestone: \(error)")+ return errorResult("Failed to look up milestone: \(error)", category: .storageFailure) } } private enum ProjectFilterResult { case resolved(UUID) case none- case error(String)+ case error(String, MCPResultErrorCategory) } private func resolveProjectFilter(_ args: [String: Any]) -> ProjectFilterResult { // Reject malformed or non-string projectId when the key is present // [T-665, T-788]. switch parseProjectIdArgument(args) {- case .failure(.message(let message)): return .error(message)+ case .failure(.message(let message)): return .error(message, .invalidInput) case .success(let pid?): switch projectService.findProject(id: pid) { case .success(let project): return .resolved(project.id) case .failure(let error):- return .error(IntentHelpers.mapProjectLookupError(error).hint)+ let mapped = IntentHelpers.mapProjectLookupError(error)+ return .error(mapped.hint, MCPResultClassification.category(for: mapped.code) ?? .internalFailure) } case .success(nil): // Reject non-string `project` filter [T-1116]. if args["project"] != nil, !(args["project"] is String) {- return .error("project must be a string")+ return .error("project must be a string", .invalidInput) } if let name = args["project"] as? String, !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {@@ -489,7 +567,8 @@ extension MCPToolHandler { case .success(let found): return .resolved(found.id) case .failure(let err):- return .error(IntentHelpers.mapProjectLookupError(err).hint)+ let mapped = IntentHelpers.mapProjectLookupError(err)+ return .error(mapped.hint, MCPResultClassification.category(for: mapped.code) ?? .internalFailure) } } return .none@@ -512,20 +591,20 @@ extension MCPToolHandler { do { projects = try projectService.fetchAllProjects(sortedByName: true) } catch {- return errorResult("Failed to fetch projects: \(error)")+ return errorResult("Failed to fetch projects: \(error)", category: .storageFailure) } var results: [[String: Any]] = [] for project in projects { var dict: [String: Any] do { dict = try projectMetadataDict(project) } catch {- return errorResult("Failed to capture project: \(error)")+ return errorResult("Failed to capture project: \(error)", category: .storageFailure) } let milestones: [Milestone] do { milestones = try milestoneService.milestonesForProject(project) } catch {- return errorResult("Failed to fetch milestones: \(error)")+ return errorResult("Failed to fetch milestones: \(error)", category: .storageFailure) } if !milestones.isEmpty { dict["milestones"] = milestones.map { milestoneSummaryDict($0) }@@ -547,9 +626,15 @@ extension MCPToolHandler { return "Duplicate task identifier detected for displayId \(displayId)" } - func textResult(_ text: String) -> MCPToolResult { MCPToolResult(content: [.text(text)], isError: nil) }- func errorResult(_ message: String) -> MCPToolResult {- MCPToolResult(content: [.text(message)], isError: true)+ func textResult(_ text: String) -> MCPToolResult {+ MCPToolResult(content: [.text(text)], isError: nil,+ providerEvidence: MCPResultProviderEvidence(origin: .generatedJSON))+ }+ func errorResult(_ message: String, category: MCPResultErrorCategory = .invalidInput,+ origin: MCPResultOrigin = .plainText) -> MCPToolResult {+ MCPToolResult(content: [.text(message)], isError: true,+ providerEvidence: MCPResultProviderEvidence(origin: origin,+ failure: MCPResultFailure(category: category, diagnostic: nil))) } /// Validates the `arguments` envelope of a `tools/call` request. Omitting the
diff --git a/Transit/Transit/MCP/MCPToolListChangeBroadcaster.swift b/Transit/Transit/MCP/MCPToolListChangeBroadcaster.swiftindex 5f40c6b..a8bb820 100644--- a/Transit/Transit/MCP/MCPToolListChangeBroadcaster.swift+++ b/Transit/Transit/MCP/MCPToolListChangeBroadcaster.swift@@ -1,82 +1,133 @@ #if os(macOS) import Foundation+import NIOConcurrencyHelpers import NIOCore -/// Publishes server-wide MCP tool-list invalidations once per active session.-/// A session can own multiple Streamable HTTP listening streams, but MCP-/// requires each JSON-RPC message to be sent on only one of them.-@MainActor-final class MCPToolListChangeBroadcaster {- private struct StreamRegistration {- let sessionID: String- let continuation: AsyncStream<MCPServerNotification>.Continuation- }+/// A request's terminal state is separate from its bounded invalidation queue.+nonisolated final class MCPSubscriptionDelivery: Sendable {+ private enum State { case open, graceful, disconnected }+ private let state = NIOLockedValueBox(State.open) - private var sessionIDs: Set<String> = []- private var registrations: [UUID: StreamRegistration] = [:]+ var isWritable: Bool { state.withLockedValue { $0 != .disconnected } }+ var completesGracefully: Bool { state.withLockedValue { $0 == .graceful } }+ func finish() { state.withLockedValue { if $0 == .open { $0 = .graceful } } }+ func disconnect() { state.withLockedValue { $0 = .disconnected } }+} - var activeStreamCount: Int { registrations.count }+nonisolated struct MCPToolListSubscription: Sendable {+ let registrationID: UUID+ let acknowledgement: Data+ let completion: Data+ let changes: AsyncStream<Data>+ let delivery: MCPSubscriptionDelivery+} - func createSession() -> String {- let sessionID = UUID().uuidString- sessionIDs.insert(sessionID)- return sessionID+/// Each POST owns its own registration, even when RPC IDs are equal.+@MainActor+final class MCPToolListChangeBroadcaster {+ private struct Registration {+ let change: Data?+ let continuation: AsyncStream<Data>.Continuation+ let delivery: MCPSubscriptionDelivery }+ private var registrations: [UUID: Registration] = [:]+ private var acceptingRequests = true - func stream(- sessionID: String,- channelClose: EventLoopFuture<Void>- ) -> AsyncStream<MCPServerNotification>? {- guard sessionIDs.contains(sessionID) else { return nil }+ func openRequests() { acceptingRequests = true }+ var activeStreamCount: Int { registrations.count } - let streamID = UUID()- let (stream, continuation) = AsyncStream.makeStream(- of: MCPServerNotification.self,- bufferingPolicy: .bufferingNewest(1)- )- registrations[streamID] = StreamRegistration(- sessionID: sessionID,- continuation: continuation- )- continuation.onTermination = { @Sendable [weak self] _ in- Task { @MainActor in- self?.removeStream(streamID)- }+ func subscribe(id: JSONRPCId, toolsListChanged: Bool,+ channelClose: EventLoopFuture<Void>) throws -> MCPToolListSubscription {+ guard acceptingRequests else { throw MCPSubscriptionRegistrationError.closed }+ // Freeze all terminal/control frames before exposing the registration.+ let frames = try MCPSubscriptionFrames.make(id: id, toolsListChanged: toolsListChanged)+ let registrationID = UUID()+ let delivery = MCPSubscriptionDelivery()+ let (stream, continuation) = AsyncStream.makeStream(of: Data.self, bufferingPolicy: .bufferingNewest(1))+ registrations[registrationID] = Registration(change: toolsListChanged ? frames.change : nil,+ continuation: continuation, delivery: delivery)+ continuation.onTermination = { @Sendable [weak self] reason in+ guard case .cancelled = reason else { return }+ delivery.disconnect()+ Task { @MainActor in self?.disconnect(registrationID) } } channelClose.whenComplete { @Sendable [weak self] _ in- Task { @MainActor in- self?.finishStream(streamID)- }+ delivery.disconnect()+ Task { @MainActor in self?.disconnect(registrationID) } }- return stream+ return MCPToolListSubscription(registrationID: registrationID, acknowledgement: frames.ack,+ completion: frames.complete, changes: stream, delivery: delivery)+ }++ func disconnect(_ id: UUID) {+ guard let registration = registrations.removeValue(forKey: id) else { return }+ registration.delivery.disconnect()+ registration.continuation.finish() } func notifyToolsListChanged() {- let streamsBySession = Dictionary(grouping: registrations) { $0.value.sessionID }- for streams in streamsBySession.values {- // Dictionary order is intentionally not part of the contract: MCP- // permits any one of a session's concurrently connected streams.- streams.first?.value.continuation.yield(.toolsListChanged)+ for registration in registrations.values {+ if let change = registration.change { registration.continuation.yield(change) } } } + /// Retained Settings calls this name; it now finishes request registrations only. func finishAllSessions() {- sessionIDs.removeAll()- let continuations = registrations.values.map(\.continuation)+ acceptingRequests = false+ let current = Array(registrations.values) registrations.removeAll()- for continuation in continuations {- continuation.finish()+ for registration in current {+ registration.delivery.finish()+ registration.continuation.finish() } }+} - private func finishStream(_ streamID: UUID) {- guard let registration = registrations.removeValue(forKey: streamID) else { return }- registration.continuation.finish()- }+nonisolated enum MCPSubscriptionRegistrationError: Error { case closed } - private func removeStream(_ streamID: UUID) {- registrations.removeValue(forKey: streamID)+nonisolated private struct MCPSubscriptionMetadata: Encodable {+ let subscriptionId: JSONRPCId+ enum CodingKeys: String, CodingKey {+ case subscriptionId = "io.modelcontextprotocol/subscriptionId" } }+nonisolated private struct MCPSubscriptionParams: Encodable {+ let notifications: [String: Bool]?+ let metadata: MCPSubscriptionMetadata+ enum CodingKeys: String, CodingKey { case notifications; case metadata = "_meta" }+}+nonisolated private struct MCPSubscriptionNotification: Encodable {+ let jsonrpc = "2.0"+ let method: String+ let params: MCPSubscriptionParams+}+nonisolated private struct MCPSubscriptionCompleteResult: Encodable {+ let resultType = "complete"+ let metadata: MCPSubscriptionMetadata+ enum CodingKeys: String, CodingKey { case resultType; case metadata = "_meta" }+}+nonisolated private struct MCPSubscriptionComplete: Encodable {+ let jsonrpc = "2.0"+ let id: JSONRPCId+ let result: MCPSubscriptionCompleteResult+}+nonisolated private struct MCPSubscriptionFrames {+ let ack: Data+ let change: Data+ let complete: Data + static func make(id: JSONRPCId, toolsListChanged: Bool) throws -> Self {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]+ let meta = MCPSubscriptionMetadata(subscriptionId: id)+ let ack = try encoder.encode(MCPSubscriptionNotification(method: "notifications/subscriptions/acknowledged",+ params: MCPSubscriptionParams(notifications: toolsListChanged ? ["toolsListChanged": true] : [:],+ metadata: meta)))+ let change = try encoder.encode(MCPSubscriptionNotification(method: "notifications/tools/list_changed",+ params: MCPSubscriptionParams(notifications: nil, metadata: meta)))+ let complete = try encoder.encode(MCPSubscriptionComplete(id: id,+ result: MCPSubscriptionCompleteResult(metadata: meta)))+ return Self(ack: ack, change: change, complete: complete)+ }+} #endif
diff --git a/Transit/Transit/MCP/MCPTypes.swift b/Transit/Transit/MCP/MCPTypes.swiftindex 98c84ee..fcc769f 100644--- a/Transit/Transit/MCP/MCPTypes.swift+++ b/Transit/Transit/MCP/MCPTypes.swift@@ -82,15 +82,11 @@ nonisolated struct JSONRPCResponse: Encodable, Sendable { } func encode(to encoder: Encoder) throws {- // Per JSON-RPC 2.0 §5, the `id` member MUST always be present in a- // response. Use a nil-to-null encoding rather than synthesized- // `encodeIfPresent`, which would omit the key entirely.+ // Modern request errors omit an unavailable identifier; never fabricate null. var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(jsonrpc, forKey: .jsonrpc) if let id { try container.encode(id, forKey: .id)- } else {- try container.encodeNil(forKey: .id) } try container.encodeIfPresent(result, forKey: .result) try container.encodeIfPresent(error, forKey: .error)@@ -189,6 +185,22 @@ nonisolated struct MCPToolsListResult: Encodable, Sendable { nonisolated struct MCPToolResult: Encodable, Sendable { let content: [MCPContent] let isError: Bool?+ let metadata: MCPToolResultMetadata?+ /// Provider declarations are internal evidence, never persisted or added to logical JSON.+ let providerEvidence: MCPResultProviderEvidence?++ init(content: [MCPContent], isError: Bool?, metadata: MCPToolResultMetadata? = nil,+ providerEvidence: MCPResultProviderEvidence? = nil) {+ self.content = content+ self.isError = isError+ self.metadata = metadata+ self.providerEvidence = providerEvidence+ }++ private enum CodingKeys: String, CodingKey {+ case content, isError+ case metadata = "_meta"+ } } nonisolated struct MCPContent: Encodable, Sendable {@@ -233,10 +245,15 @@ nonisolated struct JSONSchemaProperty: Encodable, Sendable { let enumValues: [String]? let items: JSONSchemaItems? var pattern: String?+ var minimum: Int?+ var maximum: Int?+ var const: Bool?+ var defaultValue: String? nonisolated enum CodingKeys: String, CodingKey {- case type, description, items, pattern+ case type, description, items, pattern, minimum, maximum, const case enumValues = "enum"+ case defaultValue = "default" } static func string(_ description: String) -> JSONSchemaProperty {
diff --git a/Transit/Transit/MCP/Protocol/MCPModernDiscovery.swift b/Transit/Transit/MCP/Protocol/MCPModernDiscovery.swiftnew file mode 100644index 0000000..126cef4--- /dev/null+++ b/Transit/Transit/MCP/Protocol/MCPModernDiscovery.swift@@ -0,0 +1,59 @@+#if os(macOS)+import Foundation++nonisolated struct MCPModernServerIdentity: Sendable {+ let name: String+ let version: String+}++nonisolated struct MCPModernToolDescriptor: Sendable {+ let name: String+ let description: String+ let inputSchema: MCPJSONDocument+ let resultSchema: MCPResultSchemaDescriptor+}++/// These complete RPC values are distinct from tool-result/fallback encoding.+/// Schema bytes are inserted only from parser-validated immutable documents.+nonisolated enum MCPModernDiscovery {+ static func encodeDiscovery(id: JSONRPCId, identity: MCPModernServerIdentity) throws -> Data {+ var bytes = try prefix(id: id)+ bytes.append(Data("{\"resultType\":\"complete\",\"supportedVersions\":[\"2026-07-28\"],".utf8))+ bytes.append(Data("\"capabilities\":{\"tools\":{\"listChanged\":true}},".utf8))+ bytes.append(Data("\"_meta\":{\"io.modelcontextprotocol/serverInfo\":{\"name\":".utf8))+ bytes.append(try JSONEncoder().encode(identity.name))+ bytes.append(Data(",\"version\":".utf8))+ bytes.append(try JSONEncoder().encode(identity.version))+ bytes.append(Data("}},\"ttlMs\":0,\"cacheScope\":\"public\"}}".utf8))+ return bytes+ }++ static func encodeTools(id: JSONRPCId, tools: [MCPModernToolDescriptor]) throws -> Data {+ var bytes = try prefix(id: id)+ bytes.append(Data("{\"resultType\":\"complete\",\"tools\":[".utf8))+ for (index, tool) in tools.sorted(by: { $0.name.utf8.lexicographicallyPrecedes($1.name.utf8) }).enumerated() {+ if index > 0 { bytes.append(0x2C) }+ bytes.append(Data("{\"name\":".utf8))+ bytes.append(try JSONEncoder().encode(tool.name))+ bytes.append(Data(",\"description\":".utf8))+ bytes.append(try JSONEncoder().encode(tool.description))+ bytes.append(Data(",\"inputSchema\":".utf8))+ bytes.append(tool.inputSchema.originalUTF8)+ bytes.append(Data(",\"outputSchema\":".utf8))+ bytes.append(tool.resultSchema.outputSchema.originalUTF8)+ bytes.append(0x7D)+ }+ bytes.append(Data("],\"ttlMs\":0,\"cacheScope\":\"public\"}}".utf8))+ return bytes+ }++ // JSONRPCId is a closed string/integer enum and this argument is nonoptional;+ // neither null nor a missing ID can reach these complete-response encoders.+ private static func prefix(id: JSONRPCId) throws -> Data {+ var bytes = Data("{\"jsonrpc\":\"2.0\",\"id\":".utf8)+ bytes.append(try JSONEncoder().encode(id))+ bytes.append(Data(",\"result\":".utf8))+ return bytes+ }+}+#endif
diff --git a/Transit/Transit/MCP/Protocol/MCPModernRequest.swift b/Transit/Transit/MCP/Protocol/MCPModernRequest.swiftnew file mode 100644index 0000000..f93bb19--- /dev/null+++ b/Transit/Transit/MCP/Protocol/MCPModernRequest.swift@@ -0,0 +1,59 @@+#if os(macOS)+import Foundation++/// Ordered headers retain duplicates so validation can reject conflicts.+nonisolated struct MCPModernHeader: Sendable {+ let name: String+ let value: String+}++nonisolated struct MCPModernRequestInput: Sendable {+ let httpMethod: String+ let headers: [MCPModernHeader]+ let body: Data+}++nonisolated enum MCPModernToolExecution: Sendable {+ case coveredRead, ordinaryRead, protectedWrite, applicationBatch, unprotectedMaintenance+}++nonisolated struct MCPModernAvailableTool: Sendable {+ let name: String+ let execution: MCPModernToolExecution+}++/// No storage/actor callbacks occur during pre-admission classification.+nonisolated struct MCPModernAvailability: Sendable {+ let tools: [MCPModernAvailableTool]+}++nonisolated struct MCPModernClientMetadata: Sendable {+ let protocolVersion: String+ let clientCapabilities: MCPJSONValue+ let clientInfo: MCPJSONValue?+}++nonisolated enum MCPModernMethod: Sendable {+ case discover+ case listTools+ case callTool(name: String, execution: MCPModernToolExecution)+ case listenSubscriptions+}++nonisolated struct MCPModernRequest: Sendable {+ let id: JSONRPCId+ let method: MCPModernMethod+ let params: MCPJSONValue?+ let metadata: MCPModernClientMetadata+ let document: MCPJSONDocument+}++/// Pure HTTP/RPC rejection data; notifications do not acquire response IDs.+nonisolated struct MCPModernRejection: Error, Sendable {+ let httpStatus: Int+ let rpcCode: Int?+ let message: String+ let id: JSONRPCId?+ let data: MCPJSONValue?+}+#endif
diff --git a/Transit/Transit/MCP/Protocol/MCPModernValidator.swift b/Transit/Transit/MCP/Protocol/MCPModernValidator.swiftnew file mode 100644index 0000000..892ae02--- /dev/null+++ b/Transit/Transit/MCP/Protocol/MCPModernValidator.swift@@ -0,0 +1,348 @@+#if os(macOS)+import Foundation++/// Performs only protocol validation and immutable availability classification.+nonisolated enum MCPModernValidator {+ static let protocolVersion = "2026-07-28"++ /// Run Origin/Host and content negotiation before the transport reads a request body.+ static func validateTransport(_ input: MCPModernRequestInput) throws {+ try validateHTTP(input)+ }++ static func validate(+ _ input: MCPModernRequestInput,+ availability: MCPModernAvailability+ ) throws -> MCPModernRequest {+ try validateHTTP(input)+ let envelope = try envelope(input)+ let document = envelope.document+ let id = envelope.id+ let method = envelope.method+ let params = envelope.params+ guard let meta = params.field("_meta"), meta.isObject else {+ throw reject(400, -32602, "Required per-request metadata is missing", id: id)+ }+ let metadata = try clientMetadata(meta, id: id)+ try validateHeaders(input, method: method, params: params, metadata: metadata, id: id)+ guard metadata.protocolVersion == protocolVersion else {+ throw reject(400, -32022, "Unsupported protocol version", id: id, data: .object([+ MCPJSONMember(name: "requested", value: .string(metadata.protocolVersion)),+ MCPJSONMember(name: "supported", value: .array([.string(protocolVersion)]))+ ]))+ }+ let classification = try classify(method, params: params, availability: availability, id: id)+ if case .listenSubscriptions = classification {+ guard accepts("text/event-stream", input: input) else {+ throw reject(406, nil, "Subscriptions require text/event-stream", id: id)+ }+ } else {+ guard accepts("application/json", input: input) else {+ throw reject(406, nil, "Complete responses require application/json", id: id)+ }+ }+ return MCPModernRequest(id: id, method: classification, params: params,+ metadata: metadata, document: document)+ }++ private static func validateHTTP(_ input: MCPModernRequestInput) throws {+ try validateOrigin(input)+ guard input.httpMethod == "POST" else { throw reject(405, nil, "Only POST is supported") }+ try validateContentType(input)+ guard accepts("application/json", input: input) || accepts("text/event-stream", input: input) else {+ throw reject(406, nil, "No acceptable response format")+ }+ }++ private struct Envelope {+ let document: MCPJSONDocument+ let id: JSONRPCId+ let method: String+ let params: MCPJSONValue+ }++ private static func envelope(+ _ input: MCPModernRequestInput+ ) throws -> Envelope {+ guard input.body.count <= 1_048_576 else { throw reject(413, nil, "Request body exceeds limit") }+ let document: MCPJSONDocument+ do {+ document = try MCPJSONDocument.parse(input.body)+ } catch MCPResultBoundaryError.resourceLimit {+ throw reject(400, -32600, "Request JSON exceeds the 32-container nesting resource limit")+ } catch {+ throw reject(400, -32700, "Invalid JSON")+ }+ guard case .object = document.value else { throw reject(400, -32600, "Expected one request object") }+ let root = document.value+ let id = requestID(root.field("id"))+ guard root.field("jsonrpc")?.text == "2.0", let method = root.field("method")?.text else {+ throw reject(400, -32600, "Invalid JSON-RPC envelope", id: id)+ }+ guard root.field("id") != nil else {+ throw reject(400, nil, "Client notifications are unsupported over HTTP")+ }+ guard let id else {+ if case .number = root.field("id") {+ throw reject(400, -32600,+ "Numeric request ID must be integral and between \(Int.min) and \(Int.max); "+ + "use a string ID outside this range")+ }+ throw reject(400, -32600, "Request ID must be a string or integer")+ }+ guard let params = root.field("params"), params.isObject else {+ throw reject(400, -32602, "Required request parameters are missing", id: id)+ }+ return Envelope(document: document, id: id, method: method, params: params)+ }++ private static func classify(+ _ method: String, params: MCPJSONValue, availability: MCPModernAvailability, id: JSONRPCId+ ) throws -> MCPModernMethod {+ switch method {+ case "server/discover": return .discover+ case "tools/list": return .listTools+ case "tools/call":+ guard let name = params.field("name")?.text,+ let tool = availability.tools.first(where: { $0.name.utf8.elementsEqual(name.utf8) }) else {+ throw reject(400, -32602, "Tool name is missing or unavailable", id: id)+ }+ // Domain arguments, including their shape, are the admitted worker's responsibility.+ return .callTool(name: name, execution: tool.execution)+ case "subscriptions/listen":+ guard let notifications = params.field("notifications"), case .object(let fields) = notifications else {+ throw reject(400, -32602, "Subscription notifications must be an object", id: id)+ }+ try validateSubscriptionFilters(fields, id: id)+ return .listenSubscriptions+ default: throw reject(404, -32601, "Method is unavailable", id: id)+ }+ }++ private static func validateSubscriptionFilters(_ fields: [MCPJSONMember], id: JSONRPCId) throws {+ for field in fields {+ switch field.name {+ case "toolsListChanged", "promptsListChanged", "resourcesListChanged":+ guard case .boolean = field.value else {+ throw reject(400, -32602, "List-change notification filters must be Boolean", id: id)+ }+ case "resourceSubscriptions":+ guard case .array(let uris) = field.value, uris.allSatisfy({ $0.text != nil }) else {+ throw reject(400, -32602, "Resource subscriptions must be an array of strings", id: id)+ }+ default:+ // The normative SubscriptionFilter JSON Schema leaves additional+ // properties unconstrained. Preserve valid unknown JSON; the stream+ // acknowledges only supported requested filters, never these extras.+ continue+ }+ }+ }++ private static func clientMetadata(_ meta: MCPJSONValue, id: JSONRPCId) throws -> MCPModernClientMetadata {+ guard let version = meta.field("io.modelcontextprotocol/protocolVersion")?.text,+ let capabilities = meta.field("io.modelcontextprotocol/clientCapabilities"), capabilities.isObject else {+ throw reject(400, -32602, "Invalid required per-request metadata", id: id)+ }+ if case .object(let fields) = meta, fields.contains(where: { !validMetaKey($0.name) }) {+ throw reject(400, -32602, "Invalid metadata key", id: id)+ }+ try validateCapabilities(capabilities, id: id)+ let info = meta.field("io.modelcontextprotocol/clientInfo")+ if let info {+ guard info.isObject, info.field("name")?.text != nil, info.field("version")?.text != nil else {+ throw reject(400, -32602, "Invalid client identity", id: id)+ }+ }+ return MCPModernClientMetadata(protocolVersion: version, clientCapabilities: capabilities, clientInfo: info)+ }++ private static func validateCapabilities(_ capabilities: MCPJSONValue, id: JSONRPCId) throws {+ for name in ["roots", "sampling", "elicitation", "experimental", "extensions"] {+ guard let value = capabilities.field(name) else { continue }+ guard value.isObject else { throw reject(400, -32602, "Invalid client capability", id: id) }+ if name == "experimental" || name == "extensions" {+ if case .object(let fields) = value, fields.contains(where: {+ !$0.value.isObject || (name == "extensions" && !validMetaKey($0.name, requiresPrefix: true))+ }) {+ throw reject(400, -32602, "Capability settings must be objects", id: id)+ }+ }+ let children = name == "sampling" ? ["tools", "context"] : name == "elicitation" ? ["form", "url"] : []+ for child in children {+ if let settings = value.field(child), !settings.isObject {+ throw reject(400, -32602, "Capability settings must be objects", id: id)+ }+ }+ }+ }++ private static func validMetaKey(_ key: String, requiresPrefix: Bool = false) -> Bool {+ guard key.utf8.allSatisfy({ (0x20...0x7E).contains($0) }) else { return false }+ let segments = key.split(separator: "/", omittingEmptySubsequences: false)+ guard segments.count <= 2, !requiresPrefix || segments.count == 2 else { return false }+ func matches(_ text: Substring, _ pattern: String) -> Bool {+ text.range(of: pattern, options: .regularExpression) != nil+ }+ if segments.count == 2 {+ let labels = segments[0].split(separator: ".", omittingEmptySubsequences: false)+ guard labels.allSatisfy({ matches($0, "^[A-Za-z](?:[A-Za-z0-9-]*[A-Za-z0-9])?$") }) else {+ return false+ }+ }+ guard let name = segments.last else { return false }+ return name.isEmpty || matches(name, "^[A-Za-z0-9](?:[A-Za-z0-9_.-]*[A-Za-z0-9])?$")+ }++ private static func validateHeaders(+ _ input: MCPModernRequestInput, method: String, params: MCPJSONValue,+ metadata: MCPModernClientMetadata, id: JSONRPCId+ ) throws {+ let version = try requiredHeader("MCP-Protocol-Version", input: input, id: id)+ let mirroredMethod = try requiredHeader("Mcp-Method", input: input, id: id)+ guard version.utf8.elementsEqual(metadata.protocolVersion.utf8),+ mirroredMethod.utf8.elementsEqual(method.utf8) else {+ throw reject(400, -32020, "Header does not match request metadata or method", id: id)+ }+ if method == "tools/call" {+ guard let name = params.field("name")?.text else {+ throw reject(400, -32602, "Tool name must be a string", id: id)+ }+ let mirroredName = try requiredHeader("Mcp-Name", input: input, id: id)+ let decoded = try decodeName(mirroredName, id: id)+ guard decoded.utf8.elementsEqual(name.utf8) else {+ throw reject(400, -32020, "Mcp-Name does not match tool name", id: id)+ }+ }+ }++ private static func decodeName(_ name: String, id: JSONRPCId) throws -> String {+ guard name.utf8.allSatisfy({ (0x20...0x7E).contains($0) }) else {+ throw reject(400, -32020, "Mcp-Name must be printable ASCII or encoded UTF-8", id: id)+ }+ guard name.first != " ", name.last != " " else {+ throw reject(400, -32020, "Padded Mcp-Name values require Base64 encoding", id: id)+ }+ if name.hasPrefix("=?base64?"), name.hasSuffix("?=") {+ let token = String(name.dropFirst(9).dropLast(2))+ guard let data = Data(base64Encoded: token), data.base64EncodedString() == token,+ let decoded = String(data: data, encoding: .utf8) else {+ throw reject(400, -32020, "Invalid encoded Mcp-Name", id: id)+ }+ return decoded+ }+ return name+ }++ private static func requiredHeader(+ _ name: String, input: MCPModernRequestInput, id: JSONRPCId+ ) throws -> String {+ let values = headers(name, input: input)+ guard values.count == 1, let value = values.first, !value.isEmpty,+ value.utf8.allSatisfy({ (0x20...0x7E).contains($0) }) else {+ throw reject(400, -32020, "Missing or conflicting " + name, id: id)+ }+ return value+ }++}++nonisolated private extension MCPModernValidator {+ static func validateOrigin(_ input: MCPModernRequestInput) throws {+ let origins = headers("Origin", input: input)+ let hosts = headers("Host", input: input)+ guard origins.count <= 1, hosts.count <= 1,+ MCPOriginValidator.rejectionReason(origin: origins.first, authority: hosts.first) == nil else {+ throw reject(403, nil, "Origin or Host is not allowed")+ }+ }++ private static func validateContentType(_ input: MCPModernRequestInput) throws {+ let values = headers("Content-Type", input: input)+ guard values.count == 1,+ values.first?.split(separator: ";").first?.trimmingCharacters(in: .whitespaces).lowercased()+ == "application/json" else { throw reject(415, nil, "Content-Type must be application/json") }+ }++ private static func accepts(_ media: String, input: MCPModernRequestInput) -> Bool {+ let ranges = headers("Accept", input: input).joined(separator: ",").split(separator: ",")+ var quality = -1.0+ var specificity = -1+ for range in ranges {+ let parts = range.split(separator: ";", omittingEmptySubsequences: false)+ let type = parts[0].trimmingCharacters(in: .whitespaces).lowercased()+ let score = type == media ? 2 : type == media.split(separator: "/")[0] + "/*" ? 1 : type == "*/*" ? 0 : -1+ guard score >= 0 else { continue }+ var candidate = 1.0+ for parameter in parts.dropFirst() {+ let pair = parameter.split(separator: "=", maxSplits: 1).map {+ $0.trimmingCharacters(in: .whitespaces).lowercased()+ }+ if pair.first == "q" {+ guard pair.count == 2, let parsed = Double(pair[1]), (0...1).contains(parsed) else { return false }+ candidate = parsed+ }+ }+ if score > specificity { specificity = score; quality = candidate } else if score == specificity {+ quality = max(quality, candidate)+ }+ }+ return quality > 0+ }++ private static func headers(_ name: String, input: MCPModernRequestInput) -> [String] {+ input.headers.filter { $0.name.lowercased() == name.lowercased() }.map(\.value)+ }++ private static func requestID(_ value: MCPJSONValue?) -> JSONRPCId? {+ switch value {+ case .string(let text): return .string(text)+ case .number(let number): return exactInteger(number.lexeme).map(JSONRPCId.integer)+ default: return nil+ }+ }++ /// JSON integer semantics include decimal/exponent spellings. Convert exact+ /// decimal digits, never Double/NSNumber, into the existing signed Int domain.+ private static func exactInteger(_ token: String) -> Int? {+ let negative = token.hasPrefix("-")+ let unsigned = negative ? String(token.dropFirst()) : token+ let exponentParts = unsigned.lowercased().split(separator: "e", omittingEmptySubsequences: false)+ let decimal = exponentParts[0].split(separator: ".", omittingEmptySubsequences: false)+ var digits = String(decimal[0]) + (decimal.count == 2 ? String(decimal[1]) : "")+ if digits.allSatisfy({ $0 == "0" }) { return 0 }+ let exponent = exponentParts.count == 2 ? Int(exponentParts[1]) : 0+ guard let exponent, (-1_048_576...1_048_576).contains(exponent) else { return nil }+ let fractionCount = decimal.count == 2 ? decimal[1].count : 0+ let shift = exponent - fractionCount+ if shift < 0 {+ let removed = -shift+ guard removed < digits.count, digits.suffix(removed).allSatisfy({ $0 == "0" }) else { return nil }+ digits.removeLast(removed)+ }+ digits = String(digits.drop(while: { $0 == "0" }))+ if shift > 0 {+ guard digits.count + shift <= 19 else { return nil }+ digits += String(repeating: "0", count: shift)+ }+ guard digits.count <= 19 else { return nil }+ return Int((negative ? "-" : "") + digits)+ }++ private static func reject(+ _ status: Int, _ code: Int?, _ message: String, id: JSONRPCId? = nil, data: MCPJSONValue? = nil+ ) -> MCPModernRejection {+ MCPModernRejection(httpStatus: status, rpcCode: code, message: message, id: id, data: data)+ }+}++nonisolated private extension MCPJSONValue {+ func field(_ name: String) -> MCPJSONValue? {+ guard case .object(let members) = self else { return nil }+ return members.first { $0.name.utf8.elementsEqual(name.utf8) }?.value+ }++ var text: String? { if case .string(let text) = self { text } else { nil } }+ var isObject: Bool { if case .object = self { true } else { false } }+}+#endif
diff --git a/Transit/Transit/MCP/Protocol/MCPModernWire.swift b/Transit/Transit/MCP/Protocol/MCPModernWire.swiftnew file mode 100644index 0000000..5685d79--- /dev/null+++ b/Transit/Transit/MCP/Protocol/MCPModernWire.swift@@ -0,0 +1,84 @@+#if os(macOS)+import Foundation++/// Pure transport values. Logical result sources never pass through this request bridge.+nonisolated enum MCPModernWire {+ static func request(_ modern: MCPModernRequest, tool: String) -> JSONRPCRequest {+ var params: [String: Any] = ["name": tool]+ if case .object(let members) = modern.params,+ let arguments = members.first(where: { $0.name.utf8.elementsEqual("arguments".utf8) }) {+ params["arguments"] = (try? requestValue(arguments.value)) ?? UnsupportedArguments.value+ }+ return JSONRPCRequest(jsonrpc: "2.0", id: modern.id, method: "tools/call", params: AnyCodable(params))+ }++ /// Domain conversion never rejects before read admission. Unsupported numeric representations+ /// and Unicode-key collisions make the entire envelope unsupported; existing domain validation+ /// rejects that envelope inside its worker, without dropping fields or inventing defaults.+ private enum UnsupportedArguments: Error { case value }++ private static func requestValue(_ value: MCPJSONValue) throws -> Any {+ switch value {+ case .null: return NSNull()+ case .boolean(let value): return value+ case .string(let value): return value+ case .number(let value):+ guard let decoded = try? JSONDecoder().decode(AnyCodable.self, from: Data(value.lexeme.utf8)) else {+ throw UnsupportedArguments.value+ }+ return decoded.value+ case .array(let values): return try values.map(requestValue)+ case .object(let members):+ var object: [String: Any] = [:]+ for member in members {+ guard object[member.name] == nil else { throw UnsupportedArguments.value }+ object[member.name] = try requestValue(member.value)+ }+ return object+ }+ }++ static func error(_ rejection: MCPModernRejection) throws -> Data {+ var writer = MCPResultByteWriter(checkpoint: {})+ try writer.literal("{\"jsonrpc\":\"2.0\"")+ if let id = rejection.id {+ try writer.literal(",\"id\":")+ try writer.raw(JSONEncoder().encode(id))+ }+ try writer.literal(",\"error\":{\"code\":")+ try writer.literal(String(rejection.rpcCode ?? JSONRPCErrorCode.internalError))+ try writer.field("message", rejection.message)+ if let data = rejection.data {+ try writer.literal(",\"data\":")+ try write(data, to: &writer)+ }+ try writer.literal("}}")+ return writer.data+ }++ private static func write(_ value: MCPJSONValue, to writer: inout MCPResultByteWriter) throws {+ switch value {+ case .null: try writer.literal("null")+ case .boolean(let value): try writer.literal(value ? "true" : "false")+ case .string(let value): try writer.string(value)+ case .number(let value): try writer.literal(value.lexeme)+ case .array(let values):+ try writer.literal("[")+ for (index, value) in values.enumerated() {+ if index > 0 { try writer.literal(",") }+ try write(value, to: &writer)+ }+ try writer.literal("]")+ case .object(let members):+ try writer.literal("{")+ for (index, member) in members.enumerated() {+ if index > 0 { try writer.literal(",") }+ try writer.string(member.name)+ try writer.literal(":")+ try write(member.value, to: &writer)+ }+ try writer.literal("}")+ }+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPBoundedReadDispatcher.swift b/Transit/Transit/MCP/Reads/MCPBoundedReadDispatcher.swiftnew file mode 100644index 0000000..1231dc5--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPBoundedReadDispatcher.swift@@ -0,0 +1,147 @@+#if os(macOS)+import Foundation++nonisolated struct MCPClassifiedRead: Sendable {+ let request: MCPReadToolRequest+ let malformedArguments: Bool+}++/// Transport-neutral single-read bridge. Modern protocol validation remains the wire owner's layer.+nonisolated enum MCPBoundedReadDispatcher {+ static func classify(_ rpc: JSONRPCRequest) -> MCPClassifiedRead? {+ guard rpc.jsonrpc == "2.0", !rpc.isNotification, rpc.id != nil, rpc.method == "tools/call",+ let params = rpc.params?.value as? [String: Any], let tool = params["name"] as? String,+ ["query_tasks", "query_milestones", "get_projects", "query_project_summaries"].contains(tool)+ else { return nil }+ let arguments = params["arguments"] as? [String: Any]+ return MCPClassifiedRead(request: MCPReadToolRequest(tool: tool,+ arguments: (arguments ?? [:]).mapValues(AnyCodable.init)),+ malformedArguments: params["arguments"] != nil && arguments == nil)+ }++ @concurrent static func response(+ for read: MCPClassifiedRead, rpc: JSONRPCRequest, handler: MCPToolHandler,+ coordinator: MCPReadCoordinator, admittedAt: ContinuousClock.Instant,+ encode: @escaping @Sendable (MCPPreparedToolRead, JSONRPCId) throws -> Data = encodeResult,+ encodeWithOperation: (@Sendable (MCPPreparedToolRead, JSONRPCId, MCPReadOperation) throws -> Data)? = nil,+ encodeConstantToolFailure: (@Sendable (MCPPreparedToolRead, JSONRPCId) throws -> Data)? = nil+ ) async throws -> Data {+ guard let id = rpc.id else { throw MCPReadCaptureError.serializationFailure }+ let constantEncoder = encodeConstantToolFailure ?? encodeResult+ let admission = MCPReadAdmission()+ let policy = (read.request.arguments["readPolicy"]?.value as? String).flatMap(MCPReadPolicy.init(rawValue:))+ ?? .refreshIfNeeded+ let timeout = try failure(id: id, operationID: admission.operationID, policy: policy,+ category: .timeout, code: "READ_TIMEOUT", encode: constantEncoder)+ let busy = try failure(id: id, operationID: admission.operationID, policy: policy,+ category: .busy, code: "READ_BUSY", encode: constantEncoder)+ let serialization = try failure(id: id, operationID: admission.operationID, policy: policy,+ category: .serializationFailure, code: read.request.tool == "query_tasks" ? "QUERY_FAILED" : "READ_FAILED",+ encode: constantEncoder)+ let errors = try publicationErrors(for: read.request, id: id, busy: busy,+ encodeConstantToolFailure: constantEncoder)+ return await coordinator.execute(timeout: timeout, busy: busy, admittedAt: admittedAt,+ admission: admission, diagnosticTool: read.request.tool) { operation in+ var prepared: MCPPreparedToolRead?+ do {+ if read.malformedArguments {+ let bytes = try JSONEncoder().encode(JSONRPCResponse.error(id: id,+ code: JSONRPCErrorCode.invalidParams, message: "Invalid arguments: must be a JSON object"))+ return PreparedReadResult(encodedResponse: bytes, publications: [], publicationErrors: errors,+ diagnosticOutcome: .failure)+ }+ operation.beginActorQueue()+ let tool = try await handler.prepareCoveredRead(read.request, operation: operation)+ prepared = tool+ let bytes = try encodeMeasured(tool, id: id, operation: operation) { tool, id, operation in+ try encodeWithOperation?(tool, id, operation) ?? encode(tool, id)+ }+ return PreparedReadResult(encodedResponse: bytes, publications: tool.publications,+ publicationErrors: errors, diagnosticOutcome: tool.result.isError == true ? .failure : .success)+ } catch {+ if let prepared { discard(prepared.publications, in: coordinator.domain) }+ return PreparedReadResult(encodedResponse: serialization, publications: [],+ publicationErrors: errors, diagnosticOutcome: .failure)+ }+ }+ }++ /// Measures the actual complete RPC encoder outside the publication gate and on the original operation.+ static func encodeMeasured(_ tool: MCPPreparedToolRead, id: JSONRPCId, operation: MCPReadOperation,+ encode: @Sendable (MCPPreparedToolRead, JSONRPCId, MCPReadOperation) throws -> Data)+ throws -> Data {+ let started = ContinuousClock.now+ do {+ let bytes = try encode(tool, id, operation)+ operation.recordDiagnostic(.serialization, startedAt: started)+ return bytes+ } catch {+ operation.recordDiagnostic(.serialization, startedAt: started, outcome: .failure)+ throw error+ }+ }++ static func encodeResult(_ tool: MCPPreparedToolRead, id: JSONRPCId) throws -> Data {+ var result = Data("{\"jsonrpc\":\"2.0\",\"id\":".utf8)+ result.append(try JSONEncoder().encode(id))+ result.append(Data(",\"result\":".utf8))+ result.append(tool.encodedToolResult)+ result.append(Data("}".utf8))+ return result+ }++ /// Prepares transport errors before the terminal gate; retention families own distinct expiry codes.+ static func publicationErrors(for request: MCPReadToolRequest, id: JSONRPCId,+ busy: Data,+ encodeConstantToolFailure:+ (@Sendable (MCPPreparedToolRead, JSONRPCId) throws -> Data)? = nil+ ) throws -> PreencodedPublicationErrors {+ let constantEncoder = encodeConstantToolFailure ?? encodeResult+ let expiryCode: String+ if request.tool == "query_project_summaries" {+ expiryCode = request.arguments["cursor"] == nil ? "INVALID_SNAPSHOT" : "INVALID_CURSOR"+ } else if request.tool == "query_tasks", request.arguments["snapshotId"] != nil {+ expiryCode = "INVALID_SNAPSHOT"+ } else if request.tool == "query_tasks",+ let cursor = request.arguments["cursor"]?.value as? String,+ MCPCursorFamily.classify(cursor) == .reusable {+ expiryCode = "INVALID_CURSOR"+ } else {+ expiryCode = "QUERY_EXPIRED"+ }+ return PreencodedPublicationErrors(busy: busy,+ expired: try queryFailure(id: id, code: expiryCode, encode: constantEncoder),+ capacity: try queryFailure(id: id, code: "QUERY_CAPACITY_EXCEEDED", encode: constantEncoder))+ }++ // The encoder is separate from failure identity/category to keep fallback preparation independent.+ // swiftlint:disable:next function_parameter_count+ private static func failure(id: JSONRPCId, operationID: UUID, policy: MCPReadPolicy,+ category: ReadFailureCategory, code: String,+ encode: @Sendable (MCPPreparedToolRead, JSONRPCId) throws -> Data) throws -> Data {+ let metadata = ReadFailureMetadata(requestId: operationID.uuidString, category: category,+ read: ReadExecutionMetadata(policy: policy, refreshOutcome: .unavailable, budgetMs: 5_000))+ let textBytes = try JSONEncoder().encode(["error": ["code": code, "message": code]])+ guard let text = String(data: textBytes, encoding: .utf8) else {+ throw MCPReadCaptureError.serializationFailure+ }+ return try encode(MCPPreparedToolRead(text: text, isError: true, metadata: .failure(metadata)), id)+ }++ private static func queryFailure(id: JSONRPCId, code: String,+ encode: @Sendable (MCPPreparedToolRead, JSONRPCId) throws -> Data) throws -> Data {+ let bytes = try JSONEncoder().encode(["error": ["code": code, "message": code]])+ guard let text = String(data: bytes, encoding: .utf8) else {+ throw MCPReadCaptureError.serializationFailure+ }+ return try encode(MCPPreparedToolRead(text: text, isError: true), id)+ }++ private static func discard(_ publications: [any MCPPreparedPublication], in domain: MCPReadPublicationDomain) {+ let (_, retired) = domain.withLockRetainingRetirement {+ for publication in publications { publication.discardLocked(in: domain) }+ }+ withExtendedLifetime(retired) {}+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPImportEvidenceMonitor.swift b/Transit/Transit/MCP/Reads/MCPImportEvidenceMonitor.swiftnew file mode 100644index 0000000..d1f005a--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPImportEvidenceMonitor.swift@@ -0,0 +1,232 @@+#if os(macOS)+import CoreData+import Foundation++/// Copied synchronously from the callback; no Core Data event crosses executors.+nonisolated struct MCPImportEvent: Sendable {+ enum Kind: Sendable { case setup, `import`, export }+ let id: UUID+ let storeIdentifier: String+ let kind: Kind+ let startDate: Date+ let endDate: Date?+ let succeeded: Bool+ let failureCategory: String?++ init(id: UUID, storeIdentifier: String, kind: Kind, startDate: Date, endDate: Date?,+ succeeded: Bool, failureCategory: String? = nil) {+ self.id = id+ self.storeIdentifier = storeIdentifier+ self.kind = kind+ self.startDate = startDate+ self.endDate = endDate+ self.succeeded = succeeded+ self.failureCategory = failureCategory+ }+}++/// Only a capture producer with independent import-visible history evidence may supply this.+/// Store equality, notification arrival, heartbeat, or equal history fences alone are insufficient.+nonisolated struct MCPImportCaptureProof: Sendable {+ let storeIdentifier: String+ let visibleImportIDs: Set<UUID>+}++nonisolated struct MCPObservedImport: Sendable {+ let event: MCPImportEvent+ let observedAt: Date+ let monotonicAt: ContinuousClock.Instant+}++nonisolated struct MCPImportMonitorSnapshot: Sendable {+ let syncActive: Bool+ let storeIdentifier: String?+ let generation: UInt64+ let lastSuccess: MCPObservedImport?+ let inFlight: Set<UUID>+ let lastFailureGeneration: UInt64?+ let lastFailureID: UUID?+ let successfulImports: [UUID: MCPObservedImport]+ let failedImports: [UUID: UInt64]+ let observationIsValid: Bool+}++/// The lock serializes callback values and capture fences without a MainActor hop.+/// Reads never wait for a queued observer task to catch up.+nonisolated final class MCPImportEvidenceMonitor: @unchecked Sendable {+ private let lock = NSLock()+ private let syncActive: Bool+ private let storeIdentifier: String?+ private var generation: UInt64 = 0+ private var lastSuccess: MCPObservedImport?+ private var inFlight: Set<UUID> = []+ private var lastFailureGeneration: UInt64?+ private var lastFailureID: UUID?+ private var stopped = false+ private var observerEpoch: UInt64 = 0+ private var observer: (any NSObjectProtocol)?+ private var notificationCenter: NotificationCenter?+ private var observations: [UUID: MCPImportWindowEvidence] = [:]++ init(syncActive: Bool, storeIdentifier: String?) {+ self.syncActive = syncActive+ self.storeIdentifier = storeIdentifier+ }++ /// Subscribe before admission. An unknown public store identity stays fail-closed.+ func start(center: NotificationCenter = .default) {+ lock.lock()+ guard observer == nil, syncActive else { lock.unlock(); return }+ stopped = false+ observerEpoch &+= 1+ let epoch = observerEpoch+ notificationCenter = center+ observer = center.addObserver(+ forName: NSPersistentCloudKitContainer.eventChangedNotification, object: nil, queue: nil+ ) { [weak self] notification in+ guard let event = notification.userInfo?[NSPersistentCloudKitContainer.eventNotificationUserInfoKey]+ as? NSPersistentCloudKitContainer.Event else { return }+ let kind: MCPImportEvent.Kind+ switch event.type {+ case .setup: kind = .setup+ case .import: kind = .import+ case .export: kind = .export+ @unknown default: return+ }+ let copy = MCPImportEvent(id: event.identifier, storeIdentifier: event.storeIdentifier,+ kind: kind, startDate: event.startDate, endDate: event.endDate,+ succeeded: event.succeeded, failureCategory: event.error.map {+ let error = $0 as NSError+ return "\(error.domain):\(error.code)"+ })+ self?.receive(copy, observerEpoch: epoch)+ }+ lock.unlock()+ }++ func stop() {+ lock.lock()+ stopped = true+ observerEpoch &+= 1+ observations.removeAll()+ if !inFlight.isEmpty { generation &+= 1; inFlight.removeAll() }+ let token = observer+ let center = notificationCenter+ observer = nil+ notificationCenter = nil+ lock.unlock()+ if let token { center?.removeObserver(token) }+ }++ deinit { stop() }++ func receive(_ event: MCPImportEvent, observedAt: Date = Date(),+ monotonicNow: ContinuousClock.Instant = .now, observerEpoch expectedEpoch: UInt64? = nil) {+ lock.lock()+ defer { lock.unlock() }+ guard !stopped, expectedEpoch == nil || expectedEpoch == observerEpoch,+ syncActive, event.kind == .import,+ let storeIdentifier, event.storeIdentifier == storeIdentifier else { return }+ generation &+= 1+ guard let end = event.endDate else {+ inFlight.insert(event.id)+ return+ }+ inFlight.remove(event.id)+ guard event.succeeded else {+ lastFailureGeneration = generation+ lastFailureID = event.id+ for id in observations.keys where observations[id]?.applicableImportIDs.contains(event.id) == true {+ observations[id]?.failures[event.id] = generation+ }+ return+ }+ // Invalid completed evidence must never replace the last reliable success.+ guard event.startDate <= end, end <= observedAt else { return }+ let observed = MCPObservedImport(event: event, observedAt: observedAt, monotonicAt: monotonicNow)+ for id in observations.keys where observations[id]?.applicableImportIDs.contains(event.id) == true {+ observations[id]?.successes[event.id] = observed+ }+ if let previous = lastSuccess, let previousEnd = previous.event.endDate, end < previousEnd { return }+ lastSuccess = observed+ }++ /// Register before the decision snapshot to cover completions between decision and polling.+ func beginObservation(applicableImportIDs: Set<UUID>) throws -> MCPImportObservationWindow {+ lock.lock()+ defer { lock.unlock() }+ guard applicableImportIDs.count <= 256 else { throw MCPImportObservationError.tooManyImports }+ guard observations.count < 8, !stopped else { throw MCPImportObservationError.busy }+ let id = UUID()+ var evidence = MCPImportWindowEvidence(applicableImportIDs: applicableImportIDs)+ if let success = lastSuccess, applicableImportIDs.contains(success.event.id) {+ evidence.successes[success.event.id] = success+ }+ observations[id] = evidence+ return MCPImportObservationWindow(id: id, applicableImportIDs: applicableImportIDs, monitor: self)+ }++ func endObservation(_ id: UUID) {+ lock.lock()+ observations.removeValue(forKey: id)+ lock.unlock()+ }++ func snapshot(observation: MCPImportObservationWindow? = nil) -> MCPImportMonitorSnapshot {+ lock.lock()+ defer { lock.unlock() }+ let valid = observation == nil || observation.flatMap { observations[$0.id] } != nil+ var successes = observation.flatMap { observations[$0.id]?.successes } ?? [:]+ var failures = observation.flatMap { observations[$0.id]?.failures } ?? [:]+ if observation == nil, let success = lastSuccess { successes[success.event.id] = success }+ if observation == nil, let failureID = lastFailureID, let failureGeneration = lastFailureGeneration {+ failures[failureID] = failureGeneration+ }+ return MCPImportMonitorSnapshot(syncActive: syncActive, storeIdentifier: storeIdentifier,+ generation: generation, lastSuccess: valid ? lastSuccess : nil,+ inFlight: valid ? inFlight : [], lastFailureGeneration: lastFailureGeneration,+ lastFailureID: valid ? lastFailureID : nil, successfulImports: successes,+ failedImports: failures, observationIsValid: valid)+ }++ func freshness(_ snapshot: MCPImportMonitorSnapshot, proof: MCPImportCaptureProof?,+ asOf: Date, now: ContinuousClock.Instant) -> ReadFreshness {+ let timestamp = Self.timestamp(asOf)+ guard snapshot.syncActive else {+ return ReadFreshness(syncState: .inactive, assessment: .notApplicable, assessedAt: timestamp,+ lastImportedAt: nil, evidence: .none, recentImportThresholdMs: 30_000)+ }+ guard snapshot.observationIsValid, let proof, proof.storeIdentifier == snapshot.storeIdentifier,+ let success = snapshot.successfulImports.values.filter({ proof.visibleImportIDs.contains($0.event.id) })+ .max(by: { ($0.event.endDate ?? .distantPast) < ($1.event.endDate ?? .distantPast) }),+ let end = success.event.endDate, end <= asOf,+ now >= success.monotonicAt else { return Self.unknown(at: timestamp) }+ let monotonicAge = Self.seconds(success.monotonicAt.duration(to: now))+ + success.observedAt.timeIntervalSince(end)+ let wallAge = asOf.timeIntervalSince(end)+ // A changed wall clock cannot make retained evidence younger.+ guard abs(monotonicAge - wallAge) <= 1 else { return Self.unknown(at: timestamp) }+ return ReadFreshness(syncState: .active, assessment: max(monotonicAge, wallAge) <= 30+ ? .recentImport : .stale, assessedAt: timestamp,+ lastImportedAt: Self.timestamp(end), evidence: .completedImport,+ recentImportThresholdMs: 30_000)+ }++ static func timestamp(_ date: Date) -> String {+ let formatter = ISO8601DateFormatter()+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ formatter.timeZone = TimeZone(secondsFromGMT: 0)+ return formatter.string(from: date)+ }++ private static func unknown(at timestamp: String) -> ReadFreshness {+ ReadFreshness(syncState: .active, assessment: .unknown, assessedAt: timestamp,+ lastImportedAt: nil, evidence: .none, recentImportThresholdMs: 30_000)+ }++ private static func seconds(_ duration: Duration) -> Double {+ let value = duration.components+ return Double(value.seconds) + Double(value.attoseconds) / 1e18+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPImportObservationWindow.swift b/Transit/Transit/MCP/Reads/MCPImportObservationWindow.swiftnew file mode 100644index 0000000..2dc5a6b--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPImportObservationWindow.swift@@ -0,0 +1,29 @@+#if os(macOS)+import Foundation++nonisolated enum MCPImportObservationError: Error { case busy, tooManyImports }++/// Hold from refresh decision through capture. At most eight admitted observations exist;+/// each retains at most 256 declared event IDs, never a global event history.+/// Overflow rejects registration; callers use unavailable/unknown fallback.+nonisolated final class MCPImportObservationWindow: @unchecked Sendable {+ let id: UUID+ let applicableImportIDs: Set<UUID>+ private weak var monitor: MCPImportEvidenceMonitor?++ init(id: UUID, applicableImportIDs: Set<UUID>, monitor: MCPImportEvidenceMonitor) {+ self.id = id+ self.applicableImportIDs = applicableImportIDs+ self.monitor = monitor+ }++ func close() { monitor?.endObservation(id) }+ deinit { close() }+}++nonisolated struct MCPImportWindowEvidence: Sendable {+ let applicableImportIDs: Set<UUID>+ var successes: [UUID: MCPObservedImport] = [:]+ var failures: [UUID: UInt64] = [:]+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPOrdinaryQueryReadPin.swift b/Transit/Transit/MCP/Reads/MCPOrdinaryQueryReadPin.swiftnew file mode 100644index 0000000..efb0b71--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPOrdinaryQueryReadPin.swift@@ -0,0 +1,47 @@+#if os(macOS)+import Foundation++/// Scalar proof of an exact immutable ordinary root and cursor, with its original deadline.+nonisolated struct MCPOrdinaryQueryReadPin: MCPPreparedPublication {+ let publicationStoreID: MCPPublicationStoreID+ let domain: MCPReadPublicationDomain+ let rootID: String+ let cursor: String+ let deadline: ContinuousClock.Instant++ func validateLocked(in domain: MCPReadPublicationDomain) -> PublicationRejection? {+ guard domain === self.domain else { return .busy }+ guard domain.currentInstantLocked < deadline,+ let index = domain.stores[publicationStoreID]?.index as? MCPTaskQuerySnapshotStore.Index,+ let root = index.descriptor.roots[rootID], root.deadline == deadline,+ root.tokens.contains(cursor), index.pages[cursor] != nil else { return .expired }+ return nil+ }++ func commitLocked(in domain: MCPReadPublicationDomain) {}+ func discardLocked(in domain: MCPReadPublicationDomain) {}+}++/// Coalesced read pins guard the optional single index mutation before any commit.+nonisolated struct MCPOrdinaryQueryGuardedPublication: MCPPreparedPublication {+ let publicationStoreID: MCPPublicationStoreID+ let domain: MCPReadPublicationDomain+ let pins: [MCPOrdinaryQueryReadPin]+ let mutation: MCPPublicationReservation?++ func validateLocked(in domain: MCPReadPublicationDomain) -> PublicationRejection? {+ guard domain === self.domain, pins.count <= 8,+ mutation.map({ $0.publicationStoreID == publicationStoreID && $0.domain === domain }) ?? true else {+ return .busy+ }+ for pin in pins {+ guard pin.publicationStoreID == publicationStoreID else { return .busy }+ if let rejection = pin.validateLocked(in: domain) { return rejection }+ }+ return mutation?.validateLocked(in: domain)+ }++ func commitLocked(in domain: MCPReadPublicationDomain) { mutation?.commitLocked(in: domain) }+ func discardLocked(in domain: MCPReadPublicationDomain) { mutation?.discardLocked(in: domain) }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPPreparedToolRead.swift b/Transit/Transit/MCP/Reads/MCPPreparedToolRead.swiftnew file mode 100644index 0000000..ee16e74--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPPreparedToolRead.swift@@ -0,0 +1,71 @@+#if os(macOS)+import Foundation++/// Tool-level fragments have no RPC identifier. The transport selects final encoded RPC bytes.+nonisolated struct MCPPreparedToolRead: Sendable {+ let result: MCPToolResult+ let encodedToolResult: Data+ let frozenMetadataBytes: Data?+ let publications: [any MCPPreparedPublication]+ let preparedResultPage: MCPResultPreparedPage?++ private init(result: MCPToolResult, encodedToolResult: Data, frozenMetadataBytes: Data?,+ publications: [any MCPPreparedPublication], preparedResultPage: MCPResultPreparedPage?) {+ self.result = result+ self.encodedToolResult = encodedToolResult+ self.frozenMetadataBytes = frozenMetadataBytes+ self.publications = publications+ self.preparedResultPage = preparedResultPage+ }++ /// Attaching a reservation cannot fail after its ownership has been allocated.+ func attaching(_ publications: [any MCPPreparedPublication]) -> Self {+ Self(result: result, encodedToolResult: encodedToolResult, frozenMetadataBytes: frozenMetadataBytes,+ publications: publications, preparedResultPage: preparedResultPage)+ }++ /// Carries the sealed immutable owner without rebuilding existing tool bytes or metadata.+ func attachingPreparedResultPage(_ page: MCPResultPreparedPage) -> Self {+ Self(result: result, encodedToolResult: encodedToolResult, frozenMetadataBytes: frozenMetadataBytes,+ publications: publications, preparedResultPage: page)+ }++ /// Replays a sealed page without decoding frozen metadata or reparsing/reclassifying its source.+ init(preparedResultPage page: MCPResultPreparedPage, frozenMetadataBytes: Data?,+ publications: [any MCPPreparedPublication] = []) {+ result = MCPToolResult(content: [.text(page.source.originalText)], isError: page.source.originalIsError)+ encodedToolResult = page.fragment.encodedResult+ self.frozenMetadataBytes = frozenMetadataBytes+ self.publications = publications+ preparedResultPage = page+ }++ init(text: String, isError: Bool? = nil, metadata: MCPReadResultMetadata? = nil,+ frozenMetadataBytes: Data? = nil, publications: [any MCPPreparedPublication] = [],+ preparedResultPage: MCPResultPreparedPage? = nil,+ providerEvidence: MCPResultProviderEvidence? = nil) throws {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys]+ let bytes = try frozenMetadataBytes ?? metadata.map { try encoder.encode($0) }+ let resultMetadata: MCPToolResultMetadata?+ if let metadata { resultMetadata = MCPToolResultMetadata(read: metadata) } else if let bytes {+ let original = try JSONDecoder().decode(ReadCaptureMetadata.self, from: bytes)+ resultMetadata = MCPToolResultMetadata(read: .capture(original))+ } else { resultMetadata = nil }+ result = MCPToolResult(content: [.text(text)], isError: isError, metadata: resultMetadata,+ providerEvidence: providerEvidence)+ var encoded = try encoder.encode(MCPToolResult(content: [.text(text)], isError: isError))+ if let bytes {+ // Insert the frozen metadata JSON verbatim; cursor replay does not assess or relabel it.+ encoded.removeLast()+ encoded.append(Data(",\"_meta\":{\"me.nore.ig.transit/read\":".utf8))+ encoded.append(bytes)+ encoded.append(Data("}}".utf8))+ }+ encodedToolResult = encoded+ self.frozenMetadataBytes = bytes+ self.publications = publications+ self.preparedResultPage = preparedResultPage+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPPublicationIndex.swift b/Transit/Transit/MCP/Reads/MCPPublicationIndex.swiftnew file mode 100644index 0000000..ed5e58c--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPPublicationIndex.swift@@ -0,0 +1,95 @@+#if os(macOS)+import Foundation++nonisolated struct MCPPublicationRoot: Sendable {+ let id: String+ let deadline: ContinuousClock.Instant+ let encodedByteCount: Int+ let tokens: Set<String>+}++/// Validated once during preparation; the gate reads only bounded roots and scalars.+nonisolated struct MCPPublicationIndexDescriptor: Sendable {+ let roots: [String: MCPPublicationRoot]+ let entryCount: Int+ let encodedByteCount: Int+ let tokens: Set<String>++ init(roots: [MCPPublicationRoot]) throws {+ var mapping: [String: MCPPublicationRoot] = [:]+ var bytes = 0+ var tokens: Set<String> = []+ for root in roots {+ let (sum, overflow) = bytes.addingReportingOverflow(root.encodedByteCount)+ guard !root.id.isEmpty, root.encodedByteCount >= 0, !overflow,+ mapping[root.id] == nil, tokens.isDisjoint(with: root.tokens) else {+ throw PublicationRejection.busy+ }+ mapping[root.id] = root+ bytes = sum+ tokens.formUnion(root.tokens)+ }+ self.roots = mapping+ self.entryCount = roots.count+ self.encodedByteCount = bytes+ self.tokens = tokens+ }+}++nonisolated protocol MCPPublicationIndex: AnyObject, Sendable {+ var descriptor: MCPPublicationIndexDescriptor { get }+}++nonisolated struct MCPPublicationStoreSnapshot: Sendable {+ let version: UInt64+ let tokenVersion: UInt64+ let index: any MCPPublicationIndex+ let allocatedTokenSets: [Set<String>]+}++nonisolated struct MCPPublicationAccounting: Equatable, Sendable {+ let visibleEntries: Int+ let visibleBytes: Int+ let pendingEntries: Int+ let pendingBytes: Int+}++/// Ownership and status are mutable only in the domain; indices remain immutable.+nonisolated final class MCPPublicationReservation: MCPPreparedPublication, @unchecked Sendable {+ enum Status { case pending, transferred, committed, discarded }+ let publicationStoreID: MCPPublicationStoreID+ let operationID: UUID+ let expectedVersion: UInt64+ let index: any MCPPublicationIndex+ let descriptor: MCPPublicationIndexDescriptor+ let chargeEntries: Int+ let chargeBytes: Int+ let newTokens: Set<String>+ let deadline: ContinuousClock.Instant+ let domain: MCPReadPublicationDomain+ var status = Status.pending++ init(storeID: MCPPublicationStoreID, operationID: UUID, expectedVersion: UInt64,+ index: any MCPPublicationIndex, descriptor: MCPPublicationIndexDescriptor,+ chargeEntries: Int, chargeBytes: Int, newTokens: Set<String>,+ deadline: ContinuousClock.Instant, domain: MCPReadPublicationDomain) {+ publicationStoreID = storeID+ self.operationID = operationID+ self.expectedVersion = expectedVersion+ self.index = index+ self.descriptor = descriptor+ self.chargeEntries = chargeEntries+ self.chargeBytes = chargeBytes+ self.newTokens = newTokens+ self.deadline = deadline+ self.domain = domain+ }++ func validateLocked(in domain: MCPReadPublicationDomain) -> PublicationRejection? {+ domain.validateLocked(self)+ }++ func commitLocked(in domain: MCPReadPublicationDomain) { domain.commitLocked(self) }+ func discardLocked(in domain: MCPReadPublicationDomain) { domain.discardLocked(self) }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadAdmissionContracts.swift b/Transit/Transit/MCP/Reads/MCPReadAdmissionContracts.swiftnew file mode 100644index 0000000..890d5b1--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadAdmissionContracts.swift@@ -0,0 +1,15 @@+#if os(macOS)+import Foundation++/// Caller-owned identity and physical-finalizer receipt. This value does not admit work.+/// A live duplicate identity must be rejected without replacing its operation.+nonisolated struct MCPReadAdmission: Sendable {+ let operationID: UUID+ let physicalCompletion: @Sendable () -> Void++ init(operationID: UUID = UUID(), physicalCompletion: @escaping @Sendable () -> Void = {}) {+ self.operationID = operationID+ self.physicalCompletion = physicalCompletion+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadAppDependencies.swift b/Transit/Transit/MCP/Reads/MCPReadAppDependencies.swiftnew file mode 100644index 0000000..90ad6de--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadAppDependencies.swift@@ -0,0 +1,30 @@+#if os(macOS)+import Foundation+import SwiftData++@MainActor enum MCPReadAppDependencies {+ static func make(container: ModelContainer, syncActive: Bool) -> MCPReadService {+ let domain = MCPReadPublicationDomain()+ let snapshots = MCPTaskQuerySnapshotStore(domain: domain)+ let monitor = MCPImportEvidenceMonitor(syncActive: syncActive, storeIdentifier: storeIdentifier(container))+ monitor.start()+ let source = MCPReadCaptureBuilder(container: container, generation: { monitor.snapshot().generation })+ let service = MCPReadService(source: source, monitor: monitor, snapshots: snapshots,+ diagnostics: .application,+ pagePreparer: { try MCPModernProviderBinding.prepareReadPages($0, tool: $1, operation: $2) })+ return service+ }++ /// Public history identity only; no import applicability or visibility is manufactured.+ private static func storeIdentifier(_ container: ModelContainer) -> String? {+ let context = ModelContext(container)+ context.autosaveEnabled = false+ var descriptor = HistoryDescriptor<DefaultHistoryTransaction>(+ sortBy: [SortDescriptor(\.transactionIdentifier, order: .reverse)])+ descriptor.fetchLimit = 1+ guard let transaction = try? context.fetchHistory(descriptor).first,+ !transaction.storeIdentifier.isEmpty else { return nil }+ return transaction.storeIdentifier+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadBatchTypes.swift b/Transit/Transit/MCP/Reads/MCPReadBatchTypes.swiftnew file mode 100644index 0000000..552e0c6--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadBatchTypes.swift@@ -0,0 +1,68 @@+#if os(macOS)+import Foundation++nonisolated struct MCPReadBatchWork: Sendable {+ let timeout: Data+ let busy: Data+ let responds: Bool+ let worker: @Sendable (MCPReadOperation) async -> PreparedReadResult+}++nonisolated enum MCPReadBatchElement: Sendable {+ case fixed(Data?)+ case read(MCPReadBatchWork)+}++/// Completed captures wait here outside the terminal lock. One physical permit+/// remains held by the designated assembly worker until final assembly finishes.+actor MCPReadBatchCollector {+ private var values: [PreparedReadResult?]+ private var cancelled = false+ private var remaining: Int+ private var waiter: CheckedContinuation<[PreparedReadResult?], Never>?++ init(values: [PreparedReadResult?], remaining: Int) {+ self.values = values+ self.remaining = remaining+ }++ func complete(_ position: Int, value: PreparedReadResult?) -> [any MCPPreparedPublication] {+ if cancelled { return value?.publications ?? [] }+ values[position] = value+ remaining -= 1+ if remaining == 0 {+ waiter?.resume(returning: values)+ waiter = nil+ }+ return []+ }++ func cancel() -> [any MCPPreparedPublication] {+ cancelled = true+ let retired = values+ values = []+ waiter?.resume(returning: [])+ waiter = nil+ return retired.compactMap { $0 }.flatMap(\.publications)+ }++ func all() async -> [PreparedReadResult?] {+ if remaining == 0 { return values }+ return await withCheckedContinuation { waiter = $0 }+ }+}++nonisolated enum MCPReadBatchEncoding {+ static func array(_ values: [Data?]) -> Data? {+ let responses = values.compactMap { $0 }+ guard !responses.isEmpty else { return nil }+ var bytes = Data("[".utf8)+ for (position, response) in responses.enumerated() {+ if position != 0 { bytes.append(contentsOf: ",".utf8) }+ bytes.append(response)+ }+ bytes.append(contentsOf: "]".utf8)+ return bytes+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swift b/Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swiftnew file mode 100644index 0000000..a563669--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadCaptureBuilder.swift@@ -0,0 +1,388 @@+#if os(macOS)+import Foundation+import SwiftData++nonisolated enum MCPReadCaptureError: Error, Equatable {+ case incoherentCapture+ case storageFailure+ case serializationFailure+ case projectNotFound+ case ambiguousProject+}++nonisolated enum MCPReadCaptureFence: Sendable {+ case persistentHistory+ /// Tests only: one nonawaiting actor scope, no external store writers.+ case actorOnlyTestFixture+}++@MainActor+final class MCPReadCaptureBuilder: MCPReadCaptureSource {+ private var keyCache: [PersistentIdentifier: LocalRecordKey] = [:]+ private var isCapturing = false+ private let container: ModelContainer+ private let fence: MCPReadCaptureFence+ private let generation: () -> UInt64+ private let metadata: (Date, MCPReadCaptureBoundary) -> ReadCaptureMetadata+ private let fetchTasks: (ModelContext) throws -> [TransitTask]+ private let fetchMilestones: (ModelContext) throws -> [Milestone]+ private let fetchComments: (ModelContext) throws -> [Comment]+ private let afterProjects: () throws -> Void++ init(+ container: ModelContainer,+ fence: MCPReadCaptureFence = .persistentHistory,+ generation: @escaping () -> UInt64 = { 0 },+ metadata: @escaping (Date, MCPReadCaptureBoundary) -> ReadCaptureMetadata = { date, _ in+ let timestamp = MCPRecordSnapshot.timestamp(date)+ return ReadCaptureMetadata(+ asOf: timestamp, snapshotId: UUID().uuidString,+ freshness: ReadFreshness(syncState: .inactive, assessment: .notApplicable,+ assessedAt: timestamp, lastImportedAt: nil, evidence: .none,+ recentImportThresholdMs: 30_000),+ read: ReadExecutionMetadata(policy: .cached, refreshOutcome: .notRequested, budgetMs: 5_000))+ },+ fetchComments: @escaping (ModelContext) throws -> [Comment] = {+ try $0.fetch(FetchDescriptor<Comment>())+ },+ afterProjects: @escaping () throws -> Void = {},+ fetchTasks: @escaping (ModelContext) throws -> [TransitTask] = {+ try $0.fetch(FetchDescriptor<TransitTask>())+ },+ fetchMilestones: @escaping (ModelContext) throws -> [Milestone] = {+ try $0.fetch(FetchDescriptor<Milestone>())+ }+ ) {+ self.container = container+ self.fence = fence+ self.generation = generation+ self.metadata = metadata+ self.fetchComments = fetchComments+ self.fetchTasks = fetchTasks+ self.fetchMilestones = fetchMilestones+ self.afterProjects = afterProjects+ }++ func capture(_ request: ReadCaptureRequest) throws -> CapturedReadView {+ guard !isCapturing else { throw MCPReadCaptureError.incoherentCapture }+ guard request.completeness != .completePortfolio+ || (request.selectTaskBodies == nil && request.selectMilestoneBodies == nil) else {+ throw MCPReadCaptureError.incoherentCapture+ }+ isCapturing = true+ defer { isCapturing = false; keyCache.removeAll(keepingCapacity: false) }+ let initialGeneration = generation()+ let before = try watermark()+ let context = ModelContext(container)+ context.autosaveEnabled = false+ let copied = try copy(request, in: context)+ 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(+ 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)+ if view.completeness == .completePortfolio { try MCPReadCaptureValidation.validateReusableCapture(view) }+ return view+ }++ private func watermark() throws -> DefaultHistoryTransaction? {+ guard fence == .persistentHistory else { return nil }+ guard container.configurations.count == 1 else { throw MCPReadCaptureError.incoherentCapture }+ let context = ModelContext(container)+ context.autosaveEnabled = false+ do {+ var descriptor = HistoryDescriptor<DefaultHistoryTransaction>(+ sortBy: [SortDescriptor(\.transactionIdentifier, order: .reverse)])+ descriptor.fetchLimit = 1+ if let transaction = try context.fetchHistory(descriptor).first {+ guard !transaction.storeIdentifier.isEmpty else { throw MCPReadCaptureError.incoherentCapture }+ return transaction+ }+ // An empty selection does not prove an empty store. History can have been purged.+ guard try context.fetchCount(FetchDescriptor<Project>()) == 0,+ try context.fetchCount(FetchDescriptor<TransitTask>()) == 0,+ 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 {+ throw MCPReadCaptureError.incoherentCapture+ }+ return nil+ } catch {+ throw MCPReadCaptureError.incoherentCapture+ }+ }++ private struct Copied {+ let scope: ReadCaptureScope+ let projects: [ReadProject]+ let tasks: [ReadTask]+ let milestones: [ReadMilestone]+ let comments: [ReadCommentEvidence]+ }++ private func copy(_ request: ReadCaptureRequest, in context: ModelContext) 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 tasks = try allTasks.filter { task in+ guard request.projectSelectors != nil else { return true }+ return try task.project.map { selectedKeys.contains(try key($0)) } ?? false+ }+ let milestones = try allMilestones.filter { milestone in+ 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 milestoneBodyKeys = try milestoneBodyKeys(request, all: allMilestones, scoped: milestones)+ let bodyTasks = try tasks.filter { bodyKeys.contains(try key($0)) }+ let full = fullRecordSelection(request.selection)+ guard request.completeness != .completePortfolio || full else {+ throw MCPReadCaptureError.incoherentCapture+ }+ let comments = try commentEvidence(request, context: context, bodyTasks: bodyTasks,+ needed: needsTasks && (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.+ let scope: ReadCaptureScope = request.completeness == .completePortfolio+ ? (request.projectSelectors == nil ? .wholePortfolio : .projects(selectedKeys.sorted(by: keyOrder)))+ : .selectedQuery+ 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),+ milestones: (request.completeness == .completePortfolio+ ? allMilestones : milestones).map {+ try milestoneValue($0, canonical: milestoneBodyKeys.contains(try key($0)))+ },+ comments: includedComments.map(commentValue))+ } catch let error as MCPTaskQueryError {+ throw error+ } catch let error as MCPReadCaptureError {+ throw error+ } catch is MCPCanonicalJSON.Error {+ throw MCPReadCaptureError.serializationFailure+ } catch {+ 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+ let matches = projects.filter { project in+ switch selector {+ case .id(let id): project.id == id+ case .name(let name): ProjectNamePolicy.normalized(project.name) == ProjectNamePolicy.normalized(name)+ }+ }+ guard let match = matches.first else { throw MCPReadCaptureError.projectNotFound }+ guard matches.count == 1 else { throw MCPReadCaptureError.ambiguousProject }+ return match+ }+ }++ private func keyOrder(_ lhs: LocalRecordKey, _ rhs: LocalRecordKey) -> Bool {+ lhs.encodedIdentifier.lexicographicallyPrecedes(rhs.encodedIdentifier)+ }++ private func json(_ value: Any) throws -> Data {+ do {+ return try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys])+ } catch {+ throw MCPReadCaptureError.serializationFailure+ }+ }++ private func milestoneValue(_ milestone: Milestone, canonical: Bool) throws -> ReadMilestone {+ try ReadMilestone(physicalKey: key(milestone), id: milestone.id,+ permanentDisplayId: milestone.permanentDisplayId, name: milestone.name,+ milestoneDescription: milestone.milestoneDescription,+ projectKey: milestone.project.map(key), storedProjectID: milestone.project?.id,+ rawStatus: milestone.statusRawValue, effectiveStatus: milestone.status.rawValue,+ creationDate: milestone.creationDate, lastStatusChangeDate: milestone.lastStatusChangeDate,+ completionDate: milestone.completionDate, taskKeys: (milestone.tasks ?? []).map(key),+ selectedRecordJSON: json(canonical ? MCPRecordSnapshot.milestone(milestone).record+ : ["milestoneId": milestone.id.uuidString, "name": milestone.name]))+ }++ private func commentValue(_ comment: Comment) throws -> ReadCommentEvidence {+ try ReadCommentEvidence(physicalKey: key(comment), id: comment.id, taskKey: comment.task.map(key),+ storedTaskID: comment.task?.id, creationDate: comment.creationDate,+ content: comment.content, authorName: comment.authorName, isAgent: comment.isAgent,+ selectedRecordJSON: json(MCPRecordSnapshot.comment(comment).record))+ }++ private func taskValue(+ _ task: TransitTask, comments: TaskComments, full: Bool, includeComments: Bool, identityOnly: Bool+ ) 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+ var noComments = snapshot?.record+ noComments?.removeValue(forKey: "comments")+ var selected = noComments ?? ["taskId": task.id.uuidString, "name": task.name,+ "status": task.status.rawValue, "type": task.type.rawValue,+ "priority": task.priority.rawValue]+ if identityOnly { selected = ["taskId": task.id.uuidString, "name": task.name] }+ if includeComments && !identityOnly {+ selected["comments"] = try coveredComments.map { try MCPRecordSnapshot.comment($0).record }+ }+ return try ReadTask(+ physicalKey: taskKey, id: task.id, permanentDisplayId: task.permanentDisplayId,+ name: task.name, taskDescription: identityOnly ? nil : task.taskDescription,+ projectKey: task.project.map(key),+ milestoneKey: task.milestone.map(key), storedProjectID: task.project?.id,+ storedMilestoneID: task.milestone?.id, rawStatus: task.statusRawValue,+ effectiveStatus: task.status.rawValue, rawType: task.typeRawValue, effectiveType: task.type.rawValue,+ rawPriority: task.priorityRawValue, effectivePriority: task.priority.rawValue,+ metadata: identityOnly ? [:] : task.metadata, metadataJSON: identityOnly ? nil : task.metadataJSON,+ creationDate: task.creationDate,+ lastStatusChangeDate: task.lastStatusChangeDate, completionDate: task.completionDate,+ commentKeys: ownedComments.map(key), selectedRecordJSON: json(selected), revision: snapshot?.revision,+ fullRecordWithoutCommentsJSON: noComments.map(json),+ requestedCommentRecordsJSON: includeComments && !identityOnly+ ? json(coveredComments.map { try MCPRecordSnapshot.comment($0).record }) : nil)+ }+}+private extension MCPReadCaptureBuilder {+ private func projectValue(_ project: Project) throws -> ReadProject {+ try ReadProject(physicalKey: key(project), id: project.id, name: project.name,+ projectDescription: project.projectDescription, gitRepo: project.gitRepo,+ colorHex: project.colorHex, taskKeys: (project.tasks ?? []).map(key),+ milestoneKeys: (project.milestones ?? []).map(key),+ selectedRecordJSON: json(MCPRecordSnapshot.project(project).record))+ }++ private func milestoneBodyKeys(_ request: ReadCaptureRequest, all: [Milestone],+ scoped: [Milestone]) throws -> Set<LocalRecordKey> {+ if let select = request.selectMilestoneBodies {+ return try select(all.map {+ ReadMilestoneSelectionValue(physicalKey: try key($0), identity: milestoneIdentity($0))+ })+ }+ let values = request.completeness == .completePortfolio && request.projectSelectors != nil ? scoped : all+ return try Set(values.map(key))+ }++ private func fullRecordSelection(_ selection: ReadCaptureSelection) -> Bool {+ switch selection {+ case .portfolio, .tasks(detail: .fullRecord): true+ default: false+ }+ }++ private func commentEvidence(_ request: ReadCaptureRequest, context: ModelContext,+ 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 [] }+ return try fetchComments(context)+ }++ private func key(_ model: some PersistentModel) throws -> LocalRecordKey {+ let identifier = model.persistentModelID+ if let cached = keyCache[identifier] { return cached }+ do {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys]+ let encoded = LocalRecordKey(encodedIdentifier: try encoder.encode(identifier))+ keyCache[identifier] = encoded+ return encoded+ } catch {+ throw MCPReadCaptureError.serializationFailure+ }+ }++ private func taskSelectionValue(_ task: TransitTask) throws -> ReadTaskSelectionValue {+ try ReadTaskSelectionValue(physicalKey: key(task), id: task.id, permanentDisplayId: task.permanentDisplayId,+ name: task.name, taskDescription: task.taskDescription, storedProjectID: task.project?.id,+ storedMilestoneID: task.milestone?.id, rawStatus: task.statusRawValue, rawType: task.typeRawValue,+ effectivePriority: task.priority.rawValue)+ }++ private func milestoneIdentity(_ milestone: Milestone) -> ReadMilestoneIdentity {+ ReadMilestoneIdentity(id: milestone.id, permanentDisplayId: milestone.permanentDisplayId, name: milestone.name,+ storedProjectID: milestone.project?.id, rawStatus: milestone.statusRawValue,+ milestoneDescription: milestone.milestoneDescription)+ }++ func fetchEntities(_ request: ReadCaptureRequest, in context: ModelContext)+ throws -> ([TransitTask], [Milestone]) {+ let (needsTasks, needsMilestones) = neededEntities(request.selection)+ 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)+ }++ func commentsForScope(_ comments: [Comment], request: ReadCaptureRequest, tasks: [TransitTask]) -> [Comment] {+ if request.completeness == .completePortfolio && request.projectSelectors == nil { return comments }+ let ids = Set(tasks.map(\.id))+ return comments.filter {+ $0.task.map { ids.contains($0.id) } ?? (request.completeness == .completePortfolio)+ }+ }++ private func copyTaskValues(_ tasks: [TransitTask], selectedKeys: Set<LocalRecordKey>, comments: CommentIndex,+ full: Bool, includeComments: Bool) 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] ?? []),+ full: full, includeComments: includeComments,+ identityOnly: !selectedKeys.contains(taskKey))+ }+ }++ private struct CommentIndex {+ let canonical: [UUID: [Comment]]+ let physical: [LocalRecordKey: [Comment]]+ }++ private func indexComments(_ includedComments: [Comment]) throws -> CommentIndex {+ let canonicalComments = Dictionary(grouping: includedComments.compactMap { comment in+ comment.task.map { ($0.id, comment) }+ }, by: { $0.0 }).mapValues { group in+ group.map(\.1).sorted { ($0.creationDate, $0.id.uuidString) < ($1.creationDate, $1.id.uuidString) }+ }+ var physicalComments: [LocalRecordKey: [Comment]] = [:]+ for comment in includedComments {+ if let owner = comment.task { physicalComments[try key(owner), default: []].append(comment) }+ }+ return CommentIndex(canonical: canonicalComments, physical: physicalComments)+ }++ private struct TaskComments {+ let canonical: [Comment]+ let owned: [Comment]+ }++}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadCaptureTypes.swift b/Transit/Transit/MCP/Reads/MCPReadCaptureTypes.swiftnew file mode 100644index 0000000..996dd72--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadCaptureTypes.swift@@ -0,0 +1,216 @@+#if os(macOS)+import Foundation++/// Canonical encoded PersistentIdentifier; domain UUIDs are not physical identity.+nonisolated struct LocalRecordKey: Hashable, Sendable {+ let encodedIdentifier: Data+}++nonisolated enum ReadCaptureScope: Equatable, Sendable {+ case wholePortfolio+ /// Canonical unique physical project keys. Identity closure cannot expand this scope.+ case projects([LocalRecordKey])+ case selectedQuery+}++nonisolated enum CaptureCompleteness: Sendable {+ case selectedRead+ /// Complete declared scope plus required identity/comment closure.+ case completePortfolio+}++nonisolated struct CapturedReadView: Sendable {+ let completeness: CaptureCompleteness+ let captureScope: ReadCaptureScope+ let metadata: ReadCaptureMetadata+ let createdAt: ContinuousClock.Instant+ let retentionDeadline: ContinuousClock.Instant+ let projects: [ReadProject]+ let tasks: [ReadTask]+ let milestones: [ReadMilestone]+ let comments: [ReadCommentEvidence]+}++nonisolated struct ReadProject: Sendable {+ let physicalKey: LocalRecordKey+ let id: UUID+ let name: String+ let projectDescription: String+ let gitRepo: String?+ let colorHex: String+ let taskKeys: [LocalRecordKey]+ let milestoneKeys: [LocalRecordKey]+ let selectedRecordJSON: Data+}++nonisolated struct ReadTask: Sendable {+ let physicalKey: LocalRecordKey+ let id: UUID+ let permanentDisplayId: Int?+ let name: String+ let taskDescription: String?+ let projectKey: LocalRecordKey?+ let milestoneKey: LocalRecordKey?+ let storedProjectID: UUID?+ let storedMilestoneID: UUID?+ let rawStatus: String+ let effectiveStatus: String+ let rawType: String+ let effectiveType: String+ let rawPriority: String+ let effectivePriority: String+ let metadata: [String: String]+ let metadataJSON: String?+ let creationDate: Date+ let lastStatusChangeDate: Date+ let completionDate: Date?+ let commentKeys: [LocalRecordKey]+ let selectedRecordJSON: Data+ /// Authoritative MCPRecordSnapshot.task r1, minted before removing comments.+ let revision: String?+ /// Mandatory alongside revision for selected tasks in completePortfolio; optional for identity closure.+ /// Selected portfolio tasks require complete commentKeys and canonical UUID comment evidence.+ let fullRecordWithoutCommentsJSON: Data?+ /// Output bodies only; may be nil when includeComments is false, even for a portfolio.+ let requestedCommentRecordsJSON: Data?+}++nonisolated struct ReadMilestone: Sendable {+ let physicalKey: LocalRecordKey+ let id: UUID+ let permanentDisplayId: Int?+ let name: String+ let milestoneDescription: String?+ let projectKey: LocalRecordKey?+ let storedProjectID: UUID?+ let rawStatus: String+ let effectiveStatus: String+ let creationDate: Date+ let lastStatusChangeDate: Date+ let completionDate: Date?+ let taskKeys: [LocalRecordKey]+ let selectedRecordJSON: Data+}++nonisolated struct ReadCommentEvidence: Sendable {+ let physicalKey: LocalRecordKey+ let id: UUID+ let taskKey: LocalRecordKey?+ let storedTaskID: UUID?+ let creationDate: Date+ let content: String+ let authorName: String+ let isAgent: Bool+ let selectedRecordJSON: Data+}++nonisolated protocol MCPRetainedViewSource: Sendable {+ func view(for snapshotID: String, now: ContinuousClock.Instant) throws -> CapturedReadView+}++/// Selectors are resolved by the builder inside its fence, never before capture.+nonisolated enum ReadProjectSelector: Sendable {+ case id(UUID)+ case name(String)+}++nonisolated enum ReadTaskCaptureDetail: Sendable {+ /// Preserve the ordinary summary path: no comment fetch unless requested.+ case summary+ /// Canonical revision covers all comments even when output comments are hidden.+ case fullRecord+}++nonisolated enum ReadCaptureSelection: Sendable {+ case projects+ /// Saved catalog counts and milestone summaries, without comment evidence.+ case projectCatalog+ case milestones+ case tasks(detail: ReadTaskCaptureDetail)+ /// Requires completePortfolio and full revision/comment identity evidence.+ case portfolio+}++nonisolated struct ReadProjectIdentity: Sendable {+ let id: UUID+ let name: String+}++nonisolated struct ReadMilestoneIdentity: Sendable {+ let id: UUID+ let permanentDisplayId: Int?+ let name: String+ let storedProjectID: UUID?+ let rawStatus: String+ let milestoneDescription: String?+}++/// Scalar selector input copied inside the saved fence, before canonical serialization.+nonisolated struct ReadTaskSelectionValue: Sendable {+ let physicalKey: LocalRecordKey+ let id: UUID+ let permanentDisplayId: Int?+ let name: String+ let taskDescription: String?+ let storedProjectID: UUID?+ let storedMilestoneID: UUID?+ let rawStatus: String+ let rawType: String+ let effectivePriority: String+}++nonisolated struct ReadMilestoneSelectionValue: Sendable {+ let physicalKey: LocalRecordKey+ let identity: ReadMilestoneIdentity+}++typealias ReadTaskBodySelection =+ @MainActor @Sendable ([ReadTaskSelectionValue]) throws -> Set<LocalRecordKey>+typealias ReadMilestoneBodySelection =+ @MainActor @Sendable ([ReadMilestoneSelectionValue]) throws -> Set<LocalRecordKey>++nonisolated struct ReadCaptureRequest: Sendable {+ let projectSelectors: [ReadProjectSelector]?+ let selection: ReadCaptureSelection+ let completeness: CaptureCompleteness+ /// Output preference only; fullRecord/portfolio still capture canonical comment coverage.+ let includeComments: Bool+ /// Runs inside the fence before dependent entity fetches; no relationship values escape.+ let validateProjects: (@MainActor @Sendable ([ReadProjectIdentity]) throws -> Void)?++ /// Runs after milestone fetch and before task fetch. False means no task values are needed.+ let validateMilestones: (@MainActor @Sendable ([ReadMilestoneIdentity]) throws -> Bool)?++ /// Optional selectedRead body selection; completePortfolio rejects these narrowing hooks.+ let selectTaskBodies: ReadTaskBodySelection?+ let selectMilestoneBodies: ReadMilestoneBodySelection?++ init(projectSelectors: [ReadProjectSelector]?, selection: ReadCaptureSelection,+ completeness: CaptureCompleteness, includeComments: Bool,+ validateProjects: (@MainActor @Sendable ([ReadProjectIdentity]) throws -> Void)? = nil,+ validateMilestones: (@MainActor @Sendable ([ReadMilestoneIdentity]) throws -> Bool)? = nil,+ selectTaskBodies: ReadTaskBodySelection? = nil,+ selectMilestoneBodies: ReadMilestoneBodySelection? = nil) {+ self.projectSelectors = projectSelectors+ self.selection = selection+ self.completeness = completeness+ self.includeComments = includeComments+ self.validateProjects = validateProjects+ self.validateMilestones = validateMilestones+ self.selectTaskBodies = selectTaskBodies+ self.selectMilestoneBodies = selectMilestoneBodies+ }+}++/// Local fence evidence only. This is not proof that a particular CloudKit import became visible.+nonisolated struct MCPReadCaptureBoundary: Sendable {+ let historyStoreIdentifier: String?+ let generation: UInt64+ let stablePersistentHistory: Bool+}++/// Synchronous actor entry: implementations must not suspend within the capture fence.+nonisolated protocol MCPReadCaptureSource: Sendable {+ @MainActor func capture(_ request: ReadCaptureRequest) throws -> CapturedReadView+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadCaptureValidation.swift b/Transit/Transit/MCP/Reads/MCPReadCaptureValidation.swiftnew file mode 100644index 0000000..2dce057--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadCaptureValidation.swift@@ -0,0 +1,93 @@+#if os(macOS)+import Foundation++/// Provider-side validation only. Public snapshot query/filter behavior belongs to T2382.+nonisolated enum MCPReadCaptureValidation {+ static func validateReusableCapture(_ view: CapturedReadView) throws {+ guard view.completeness == .completePortfolio else { throw MCPReadCaptureError.incoherentCapture }+ let projects = Set(view.projects.map(\.physicalKey))+ let tasks = Set(view.tasks.map(\.physicalKey))+ let milestones = Set(view.milestones.map(\.physicalKey))+ let comments = Set(view.comments.map(\.physicalKey))+ guard projects.count == view.projects.count, tasks.count == view.tasks.count,+ milestones.count == view.milestones.count, comments.count == view.comments.count else {+ throw MCPReadCaptureError.incoherentCapture+ }+ let scope: Set<LocalRecordKey>?+ switch view.captureScope {+ case .wholePortfolio: scope = nil+ case .projects(let keys):+ let selected = Set(keys)+ guard selected.count == keys.count, selected.isSubset(of: projects) else {+ throw MCPReadCaptureError.incoherentCapture+ }+ scope = selected+ case .selectedQuery: throw MCPReadCaptureError.incoherentCapture+ }+ try validateEndpoints(view, projects: projects, tasks: tasks, milestones: milestones)+ try validateTasks(view, projects: projects, milestones: milestones, scope: scope)+ for comment in view.comments {+ guard comment.taskKey.map({ tasks.contains($0) }) ?? true else {+ throw MCPReadCaptureError.incoherentCapture+ }+ }+ }++ private static func validateEndpoints(_ view: CapturedReadView, projects: Set<LocalRecordKey>,+ tasks: Set<LocalRecordKey>, milestones: Set<LocalRecordKey>) throws {+ for project in view.projects {+ guard Set(project.taskKeys).isSubset(of: tasks), Set(project.milestoneKeys).isSubset(of: milestones) else {+ throw MCPReadCaptureError.incoherentCapture+ }+ }+ for milestone in view.milestones {+ guard milestone.projectKey.map({ projects.contains($0) }) ?? true,+ Set(milestone.taskKeys).isSubset(of: tasks) else { throw MCPReadCaptureError.incoherentCapture }+ }+ }++ private static func validateTasks(_ view: CapturedReadView, projects: Set<LocalRecordKey>,+ milestones: Set<LocalRecordKey>, scope: Set<LocalRecordKey>?) throws {+ let owners = Dictionary(grouping: view.comments.compactMap { comment in+ comment.taskKey.map { ($0, comment.physicalKey) }+ }, by: { $0.0 }).mapValues { Set($0.map(\.1)) }+ for task in view.tasks {+ guard task.projectKey.map({ projects.contains($0) }) ?? true,+ task.milestoneKey.map({ milestones.contains($0) }) ?? true,+ Set(task.commentKeys) == owners[task.physicalKey, default: []],+ Set(task.commentKeys).count == task.commentKeys.count else {+ throw MCPReadCaptureError.incoherentCapture+ }+ let selected = scope.map { keys in task.projectKey.map { keys.contains($0) } == true } ?? true+ if selected { try validateCanonicalRecord(task) }+ }+ }++ /// A typed consumer scope check; public query parsing and selection remain with its owner.+ static func requireScope(_ view: CapturedReadView, projectKeys: Set<LocalRecordKey>) throws {+ let allowed: Set<LocalRecordKey>+ switch view.captureScope {+ case .wholePortfolio: allowed = Set(view.projects.map(\.physicalKey))+ case .projects(let keys): allowed = Set(keys)+ case .selectedQuery: throw MCPReadCaptureError.incoherentCapture+ }+ guard projectKeys.isSubset(of: allowed) else {+ throw MCPTaskQueryError(code: "SNAPSHOT_INCOMPATIBLE",+ message: "Requested projects are outside the retained capture scope")+ }+ }++ private static func validateCanonicalRecord(_ task: ReadTask) throws {+ guard let revision = task.revision, let bytes = task.fullRecordWithoutCommentsJSON else {+ throw MCPReadCaptureError.incoherentCapture+ }+ do {+ guard let record = try JSONSerialization.jsonObject(with: bytes) as? [String: Any],+ record["revision"] as? String == revision,+ record["taskId"] as? String == task.id.uuidString else {+ throw MCPReadCaptureError.incoherentCapture+ }+ } catch { throw MCPReadCaptureError.incoherentCapture }+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadCoordinator+Entry.swift b/Transit/Transit/MCP/Reads/MCPReadCoordinator+Entry.swiftnew file mode 100644index 0000000..91c8574--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadCoordinator+Entry.swift@@ -0,0 +1,36 @@+#if os(macOS)+import Foundation++extension MCPReadCoordinator {+ nonisolated final class Entry: @unchecked Sendable {+ let id: UUID+ let generation: UInt64+ let deadline: ContinuousClock.Instant+ let diagnosticContext: MCPReadDiagnosticContext+ var actorQueuedAt: ContinuousClock.Instant?+ var terminalEvent: MCPReadDiagnosticEvent?+ var terminalDelivered = false+ let physicalCompletion: @Sendable () -> Void+ var timeout: Data+ var responseReady = true+ var invalidated = false+ var selected: Data?+ var continuation: CheckedContinuation<Data, Never>?+ var timer: DispatchSourceTimer?++ init(id: UUID, generation: UInt64, deadline: ContinuousClock.Instant, timeout: Data,+ admittedAt: ContinuousClock.Instant, diagnosticTool: String,+ physicalCompletion: @escaping @Sendable () -> Void = {}) {+ self.id = id+ self.generation = generation+ self.deadline = deadline+ self.diagnosticContext = MCPReadDiagnosticContext(operationID: id, tool: diagnosticTool,+ generation: generation, admittedAt: admittedAt, responseDeadline: admittedAt + .seconds(5),+ internalCutoff: deadline)+ self.timeout = timeout+ self.physicalCompletion = physicalCompletion+ }+ }++}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadCoordinator.swift b/Transit/Transit/MCP/Reads/MCPReadCoordinator.swiftnew file mode 100644index 0000000..9bbeadd--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadCoordinator.swift@@ -0,0 +1,400 @@+#if os(macOS)+import Foundation++/// Mutable state is accessed only while holding the injected common publication domain.+nonisolated final class MCPReadCoordinator: @unchecked Sendable {+ let domain: MCPReadPublicationDomain+ let diagnostics: MCPReadDiagnosticSink+ private let cutoff: Duration+ private let maxOperations: Int+ private var entries: [UUID: Entry] = [:]+ private var generation: UInt64 = 1+ private var admissionOpen = true+ private let timerQueue = DispatchQueue(label: "transit.read.deadline", qos: .userInitiated, attributes: .concurrent)++ init(domain: MCPReadPublicationDomain = MCPReadPublicationDomain(), cutoff: Duration = .milliseconds(4_850),+ maxOperations: Int = 8, diagnostics: MCPReadDiagnosticSink = .disabled) {+ self.domain = domain+ self.cutoff = cutoff+ self.maxOperations = maxOperations+ self.diagnostics = diagnostics+ }++ var unfinishedCount: Int { domain.withLock { entries.count } }++ @concurrent func execute(+ timeout: Data, busy: Data, admittedAt: ContinuousClock.Instant = .now,+ admission: MCPReadAdmission = MCPReadAdmission(),+ diagnosticTool: String = "unknown",+ worker: @escaping @Sendable (MCPReadOperation) async -> PreparedReadResult+ ) async -> Data {+ let entry = reserve(timeout: timeout, admittedAt: admittedAt, admission: admission, tool: diagnosticTool)+ guard let entry else { return busy }+ return await executeReserved(entry, worker: worker)+ }++ private func reserve(timeout: Data, admittedAt: ContinuousClock.Instant, admission: MCPReadAdmission,+ tool: String) -> Entry? {+ var rejected: MCPReadDiagnosticContext?+ let entry = domain.withLock { () -> Entry? in+ guard admissionOpen, entries.count < maxOperations, entries[admission.operationID] == nil else {+ if diagnostics.capacity > 0 {+ rejected = MCPReadDiagnosticContext(operationID: admission.operationID, tool: tool,+ generation: generation, admittedAt: admittedAt, responseDeadline: admittedAt + .seconds(5),+ internalCutoff: admittedAt + cutoff)+ }+ return nil+ }+ let entry = Entry(id: admission.operationID, generation: generation, deadline: admittedAt + cutoff,+ timeout: timeout, admittedAt: admittedAt, diagnosticTool: tool,+ physicalCompletion: admission.physicalCompletion)+ entries[entry.id] = entry+ return entry+ }+ if let rejected { recordDiagnostic(context: rejected, phase: .terminal,+ startedAt: admittedAt, outcome: .busy) }+ return entry+ }++ @concurrent private func executeReserved(+ _ entry: Entry, skipped: (@Sendable () async -> Void)? = nil,+ worker: @escaping @Sendable (MCPReadOperation) async -> PreparedReadResult+ ) async -> Data {+ if Task.isCancelled { expire(entry) }+ let operation = MCPReadOperation(id: entry.id, generation: entry.generation,+ context: entry.diagnosticContext, coordinator: self)+ installTimer(entry)+ let operationID = entry.id+ Task.detached(priority: .userInitiated) {+ defer { self.physicalFinished(operationID) }+ await self.prepareAndOffer(operation, skipped: skipped, worker: worker)+ }+ return await withTaskCancellationHandler {+ await withCheckedContinuation { continuation in+ let selected = domain.withLock { () -> Data? in+ if let selected = entry.selected { return selected }+ entry.continuation = continuation+ return nil+ }+ if let selected { continuation.resume(returning: selected) }+ }+ } onCancel: {+ self.expire(entry)+ }+ }++ /// Release the prepared result and its buffers before physical finalization/receipt.+ private func prepareAndOffer(+ _ operation: MCPReadOperation, skipped: (@Sendable () async -> Void)?,+ worker: @escaping @Sendable (MCPReadOperation) async -> PreparedReadResult+ ) async {+ operation.recordDiagnostic(.queue, startedAt: operation.diagnosticContext.admittedAt)+ guard operation.shouldContinue() else {+ let started = ContinuousClock.now+ await skipped?()+ operation.recordDiagnostic(.discard, startedAt: started, outcome: .discarded)+ return+ }+ let prepared = await worker(operation)+ offer(prepared, for: operation.id)+ }++ func stop() {+ let (stopped, completions) = domain.withLock { () -> ([Entry], [(CheckedContinuation<Data, Never>, Data)]) in+ admissionOpen = false+ generation &+= 1+ let stopped = Array(entries.values)+ let completions = stopped.compactMap { entry in+ entry.invalidated = true+ return entry.responseReady ? selectLocked(entry.timeout, entry: entry) : nil+ }+ return (stopped, completions)+ }+ for (continuation, data) in completions { continuation.resume(returning: data) }+ for entry in stopped { flushTerminal(entry) }+ }++ func start() {+ domain.withLock {+ generation &+= 1+ admissionOpen = true+ }+ }++ func canContinue(id: UUID, generation: UInt64) -> Bool {+ domain.withLock {+ guard let entry = entries[id] else { return false }+ return admissionOpen && self.generation == generation && entry.responseReady && !entry.invalidated+ && entry.selected == nil && .now < entry.deadline+ }+ }++ func remainingBudget(id: UUID, generation: UInt64) -> Duration {+ domain.withLock {+ guard let entry = entries[id], admissionOpen, self.generation == generation,+ !entry.invalidated, entry.selected == nil else { return .zero }+ return max(.zero, ContinuousClock.now.duration(to: entry.deadline))+ }+ }++ private func installTimer(_ entry: Entry) {+ let timer = DispatchSource.makeTimerSource(flags: .strict, queue: timerQueue)+ let remaining = max(0, seconds(ContinuousClock.now.duration(to: entry.deadline)))+ timer.schedule(deadline: .now() + remaining, leeway: .nanoseconds(0))+ timer.setEventHandler { [weak self] in self?.expire(entry) }+ domain.withLock {+ if entry.selected == nil { entry.timer = timer } else { timer.cancel() }+ }+ timer.resume()+ }++ private func seconds(_ duration: Duration) -> Double {+ let components = duration.components+ return Double(components.seconds) + Double(components.attoseconds) / 1e18+ }++ private func expire(_ entry: Entry) {+ let completion = domain.withLock { () -> (CheckedContinuation<Data, Never>, Data)? in+ guard entries[entry.id] === entry else { return nil }+ entry.invalidated = true+ return entry.responseReady ? selectLocked(entry.timeout, entry: entry) : nil+ }+ if let (continuation, data) = completion { continuation.resume(returning: data) }+ flushTerminal(entry)+ }++ private func selectLocked(_ data: Data, entry: Entry, outcome: MCPReadDiagnosticOutcome? = .timeout)+ -> (CheckedContinuation<Data, Never>, Data)? {+ guard entry.selected == nil else { return nil }+ entry.selected = data+ if diagnostics.capacity > 0 {+ entry.terminalEvent = MCPReadDiagnosticEvent(context: entry.diagnosticContext, phase: .terminal,+ startedAt: entry.diagnosticContext.admittedAt, finishedAt: .now, outcome: outcome,+ unfinishedPhysicalCount: entries.count)+ }+ entry.timer?.cancel()+ entry.timer = nil+ guard let continuation = entry.continuation else { return nil }+ entry.continuation = nil+ return (continuation, data)+ }++ private func offer(_ prepared: PreparedReadResult, for id: UUID) {+ let distinctStores = Set(prepared.publications.map(\.publicationStoreID))+ let offerStarted = ContinuousClock.now+ var selectedEntry: Entry?+ var late = false+ let (completion, retired) = domain.withLockRetainingRetirement {+ () -> (CheckedContinuation<Data, Never>, Data)? in+ selectedEntry = entries[id]+ guard let entry = selectedEntry, admissionOpen, entry.generation == generation,+ entry.selected == nil, .now < entry.deadline else {+ late = true+ for publication in prepared.publications { publication.discardLocked(in: domain) }+ if let entry = entries[id] { return selectLocked(entry.timeout, entry: entry) }+ return nil+ }+ let rejection = distinctStores.count != prepared.publications.count ? .busy+ : prepared.publications.compactMap { $0.validateLocked(in: domain) }.first+ if let rejection {+ for publication in prepared.publications { publication.discardLocked(in: domain) }+ let bytes: Data+ switch rejection {+ case .busy: bytes = prepared.publicationErrors.busy+ case .expired: bytes = prepared.publicationErrors.expired+ case .capacity: bytes = prepared.publicationErrors.capacity+ }+ return selectLocked(bytes, entry: entry, outcome: rejection == .busy ? .busy : .failure)+ }+ for publication in prepared.publications { publication.commitLocked(in: domain) }+ return selectLocked(prepared.encodedResponse, entry: entry, outcome: prepared.diagnosticOutcome)+ }+ if let (continuation, data) = completion { continuation.resume(returning: data) }+ withExtendedLifetime(retired) {}+ recordOffer(entry: selectedEntry, late: late, startedAt: offerStarted)+ }++ private func recordOffer(entry: Entry?, late: Bool, startedAt: ContinuousClock.Instant) {+ guard let entry else { return }+ flushTerminal(entry)+ if late { recordDiagnostic(context: entry.diagnosticContext, phase: .discard,+ startedAt: startedAt, outcome: .discarded) }+ }++ private func physicalFinished(_ id: UUID) {+ let started = ContinuousClock.now+ let receipt: ((@Sendable () -> Void), MCPReadDiagnosticContext)? = {+ let (retired, completion) = domain.withLock {+ let entry = entries.removeValue(forKey: id)+ let completion = entry.flatMap { selectLocked($0.timeout, entry: $0) }+ return (entry, completion)+ }+ if let (continuation, data) = completion { continuation.resume(returning: data) }+ guard let retired else { return nil }+ flushTerminal(retired)+ return (retired.physicalCompletion, retired.diagnosticContext)+ }()+ // Entry buffers and worker/private cleanup are released before this event and receipt.+ if let (completion, context) = receipt {+ recordDiagnostic(context: context, phase: .physicalFinish, startedAt: started)+ completion()+ }+ }++ private func flushTerminal(_ entry: Entry) {+ guard diagnostics.capacity > 0 else { return }+ let event = domain.withLock { () -> MCPReadDiagnosticEvent? in+ guard !entry.terminalDelivered, let event = entry.terminalEvent else { return nil }+ entry.terminalDelivered = true+ return event+ }+ if let event { diagnostics.enqueue(event) }+ }++ func beginActorQueue(id: UUID) {+ guard diagnostics.capacity > 0 else { return }+ domain.withLock { entries[id]?.actorQueuedAt = .now }+ }++ func finishActorQueue(id: UUID) {+ guard diagnostics.capacity > 0 else { return }+ let interval = domain.withLock { () -> (MCPReadDiagnosticContext, ContinuousClock.Instant)? in+ guard let entry = entries[id], let started = entry.actorQueuedAt else { return nil }+ entry.actorQueuedAt = nil+ return (entry.diagnosticContext, started)+ }+ if let (context, started) = interval { recordDiagnostic(context: context, phase: .queue, startedAt: started) }+ }+}++extension MCPReadCoordinator {+ /// Read-only protocol batch seam. Fixed invalid responses and notifications+ /// retain their positions. Callers coalesce same-store publications while assembling.+ @concurrent func executeBatch(+ _ elements: [MCPReadBatchElement], admittedAt: ContinuousClock.Instant = .now,+ beforeFallbackReady: @escaping @Sendable () async -> Void = {},+ assemble: @escaping @Sendable ([PreparedReadResult?]) async throws -> PreparedReadResult+ ) async -> Data? {+ let admission = admitBatch(elements, admittedAt: admittedAt)+ let admitted = admission.admitted+ await beforeFallbackReady()+ let fallback = MCPReadBatchEncoding.array(admission.fallbackElements)+ guard let first = admitted.first else { return fallback }+ // The complete fallback is ready before any physical dispatch or final assembly.+ readyBatch(first.entry, fallback: fallback ?? Data())+ let collector = MCPReadBatchCollector(values: admission.initial, remaining: admitted.count)+ for admission in admitted.dropFirst() {+ let position = admission.position+ let entry = admission.entry+ let work = admission.work+ Task.detached(priority: .userInitiated) {+ _ = await self.executeReserved(entry, skipped: {+ let discarded = await collector.complete(position, value: work.responds+ ? self.fixedResult(work.timeout) : nil)+ self.discard(discarded)+ }, worker: { operation in+ let result = operation.shouldContinue()+ ? await work.worker(operation) : self.fixedResult(work.timeout)+ if !work.responds { self.discard(result.publications) }+ let discarded = await collector.complete(position, value: work.responds ? result : nil)+ self.discard(discarded)+ return self.fixedResult(result.encodedResponse)+ })+ }+ }+ let selected = await executeReserved(first.entry, skipped: {+ self.discard(await collector.cancel())+ }, worker: { operation in+ let result = operation.shouldContinue()+ ? await first.work.worker(operation) : self.fixedResult(first.work.timeout)+ if !first.work.responds { self.discard(result.publications) }+ let discarded = await collector.complete(first.position, value: first.work.responds ? result : nil)+ self.discard(discarded)+ let completed = await collector.all()+ guard operation.shouldContinue(), fallback != nil else {+ self.discard(completed.compactMap { $0 }.flatMap(\.publications))+ return self.fixedResult(fallback ?? Data())+ }+ let assemblyStarted = ContinuousClock.now+ defer { operation.recordDiagnostic(.aggregation, startedAt: assemblyStarted) }+ do { return try await assemble(completed) } catch {+ self.discard(completed.compactMap { $0 }.flatMap(\.publications))+ return self.fixedResult(fallback ?? Data())+ }+ })+ return fallback == nil ? nil : selected+ }++ private nonisolated struct BatchAdmissions: Sendable {+ let fallbackElements: [Data?]+ let initial: [PreparedReadResult?]+ let admitted: [BatchAdmission]+ }++ private nonisolated struct BatchAdmission: Sendable {+ let position: Int+ let entry: Entry+ let work: MCPReadBatchWork+ }++ private nonisolated func readyBatch(_ entry: Entry, fallback: Data) {+ domain.withLock {+ entry.timeout = fallback+ entry.responseReady = true+ if entry.invalidated || !admissionOpen || entry.generation != generation+ || .now >= entry.deadline {+ _ = selectLocked(entry.timeout, entry: entry)+ }+ }+ }++ private nonisolated func admitBatch(+ _ elements: [MCPReadBatchElement], admittedAt: ContinuousClock.Instant+ ) -> BatchAdmissions {+ let reads = elements.enumerated().compactMap { position, element -> (Int, MCPReadBatchWork)? in+ guard case .read(let work) = element else { return nil }+ return (position, work)+ }+ // Only up to eight compact entries are allocated under the domain; bulk+ // fallback arrays and index construction stay outside this critical section.+ let admitted = domain.withLock { () -> [BatchAdmission] in+ guard admissionOpen else { return [] }+ return reads.prefix(max(0, maxOperations - entries.count)).enumerated().map { index, read in+ let entry = Entry(id: UUID(), generation: generation, deadline: admittedAt + cutoff,+ timeout: read.1.timeout, admittedAt: admittedAt, diagnosticTool: "historical_batch")+ entry.responseReady = index != 0+ entries[entry.id] = entry+ return BatchAdmission(position: read.0, entry: entry, work: read.1)+ }+ }+ let admittedPositions = Set(admitted.map(\.position))+ var fallbackElements: [Data?] = []+ var initial: [PreparedReadResult?] = []+ for (position, element) in elements.enumerated() {+ switch element {+ case .fixed(let bytes):+ fallbackElements.append(bytes)+ initial.append(bytes.map { fixedResult($0) })+ case .read(let work):+ if admittedPositions.contains(position) {+ fallbackElements.append(work.responds ? work.timeout : nil)+ initial.append(nil)+ } else {+ fallbackElements.append(work.responds ? work.busy : nil)+ initial.append(work.responds ? fixedResult(work.busy) : nil)+ }+ }+ }+ return BatchAdmissions(fallbackElements: fallbackElements, initial: initial, admitted: admitted)+ }++ private nonisolated func fixedResult(_ bytes: Data) -> PreparedReadResult {+ PreparedReadResult(encodedResponse: bytes, publications: [],+ publicationErrors: PreencodedPublicationErrors(busy: bytes, expired: bytes, capacity: bytes))+ }++ private nonisolated func discard(_ publications: [any MCPPreparedPublication]) {+ domain.withLock { for publication in publications { publication.discardLocked(in: domain) } }+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadDiagnostics.swift b/Transit/Transit/MCP/Reads/MCPReadDiagnostics.swiftnew file mode 100644index 0000000..407f0b2--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadDiagnostics.swift@@ -0,0 +1,107 @@+#if os(macOS)+import Foundation+import NIOConcurrencyHelpers+import OSLog++nonisolated enum MCPReadDiagnosticPhase: Sendable, Equatable {+ case queue, refresh, capture, transform, serialization, aggregation, terminal, physicalFinish, discard+}++nonisolated enum MCPReadDiagnosticOutcome: Sendable, Equatable {+ case success, timeout, busy, failure, discarded, lateCompletion+}++/// Correlation scalars only: diagnostics never retain a captured view or a result buffer.+nonisolated struct MCPReadDiagnosticContext: Sendable {+ let operationID: UUID+ let tool: String+ let generation: UInt64+ let admittedAt: ContinuousClock.Instant+ /// Original external five-second boundary, distinct from the internal selection cutoff.+ let responseDeadline: ContinuousClock.Instant+ let internalCutoff: ContinuousClock.Instant+}++/// Only actual measured intervals belong here; an unmeasured phase produces no fabricated duration.+nonisolated struct MCPReadDiagnosticEvent: Sendable {+ let context: MCPReadDiagnosticContext+ let phase: MCPReadDiagnosticPhase+ let startedAt: ContinuousClock.Instant+ let finishedAt: ContinuousClock.Instant+ let outcome: MCPReadDiagnosticOutcome?+ let unfinishedPhysicalCount: Int+}++/// Bounded active-plus-queued records. The writer never holds either publication or sink lock.+nonisolated final class MCPReadDiagnosticSink: Sendable {+ static let disabled = MCPReadDiagnosticSink(capacity: 0, writer: { _ in })+ static let application = MCPReadDiagnosticSink(writer: MCPReadDiagnosticLogging.write)+ let capacity: Int+ private let writer: @Sendable (MCPReadDiagnosticEvent) -> Void+ private let state = NIOLockedValueBox(State())+ private let queue: DispatchQueue?++ private struct State: Sendable {+ var events: [MCPReadDiagnosticEvent] = []+ var unfinished = 0+ var draining = false+ }++ init(capacity: Int = 64, writer: @escaping @Sendable (MCPReadDiagnosticEvent) -> Void) {+ self.capacity = max(0, capacity)+ self.writer = writer+ queue = capacity > 0 ? DispatchQueue(label: "transit.read.diagnostics", qos: .utility) : nil+ }++ var pendingCount: Int { state.withLockedValue { $0.unfinished } }++ @discardableResult func enqueue(_ event: MCPReadDiagnosticEvent) -> Bool {+ guard let queue else { return false }+ let admission = state.withLockedValue { state -> (accepted: Bool, start: Bool) in+ guard state.unfinished < capacity else { return (false, false) }+ state.events.append(event)+ state.unfinished += 1+ let start = !state.draining+ state.draining = true+ return (true, start)+ }+ if admission.start { queue.async { self.drain() } }+ return admission.accepted+ }++ private func drain() {+ while true {+ let event = state.withLockedValue { state -> MCPReadDiagnosticEvent? in+ guard !state.events.isEmpty else { state.draining = false; return nil }+ return state.events.removeFirst()+ }+ guard let event else { return }+ writer(event)+ state.withLockedValue { $0.unfinished -= 1 }+ }+ }+}++nonisolated private enum MCPReadDiagnosticLogging {+ private static let logger = Logger(subsystem: "me.nore.ig.Transit", category: "MCP.Read")+ static func write(_ event: MCPReadDiagnosticEvent) {+ let elapsed = event.startedAt.duration(to: event.finishedAt).components+ let milliseconds = Double(elapsed.seconds) * 1_000 + Double(elapsed.attoseconds) / 1e15+ let phase = String(describing: event.phase)+ let outcome = event.outcome.map { String(describing: $0) } ?? "unclassified"+ let offset = event.context.admittedAt.duration(to: event.startedAt).components+ let offsetMs = Double(offset.seconds) * 1_000 + Double(offset.attoseconds) / 1e15+ let external = event.context.admittedAt.duration(to: event.context.responseDeadline).components+ let cutoff = event.context.admittedAt.duration(to: event.context.internalCutoff).components+ let externalMs = Double(external.seconds) * 1_000 + Double(external.attoseconds) / 1e15+ let cutoffMs = Double(cutoff.seconds) * 1_000 + Double(cutoff.attoseconds) / 1e15+ logger.debug("""+ read id=\(event.context.operationID.uuidString, privacy: .public) \+ tool=\(event.context.tool, privacy: .public) generation=\(event.context.generation) \+ phase=\(phase, privacy: .public) admission_offset_ms=\(offsetMs) elapsed_ms=\(milliseconds) \+ budget_ms=\(externalMs) cutoff_ms=\(cutoffMs) \+ outcome=\(outcome, privacy: .public) physical=\(event.unfinishedPhysicalCount)+ """)+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadMetadata.swift b/Transit/Transit/MCP/Reads/MCPReadMetadata.swiftnew file mode 100644index 0000000..710247c--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadMetadata.swift@@ -0,0 +1,103 @@+#if os(macOS)+import Foundation++nonisolated enum MCPReadPolicy: String, Codable, Sendable {+ case cached+ case refreshIfNeeded = "refresh_if_needed"+}++nonisolated enum ReadSyncState: String, Codable, Sendable {+ case active, inactive+}++nonisolated enum ReadFreshnessAssessment: String, Codable, Sendable {+ case recentImport = "recent_import"+ case stale, unknown+ case notApplicable = "not_applicable"+}++nonisolated enum ReadImportEvidence: String, Codable, Sendable {+ case completedImport = "completed_import"+ case none+}++nonisolated enum ReadRefreshOutcome: String, Codable, Sendable {+ case notRequested = "not_requested"+ case recentImport = "recent_import"+ case importObserved = "import_observed"+ case failed, timeout, unavailable+}++/// Timestamp strings are frozen UTC ISO 8601 milliseconds from the capture producer.+nonisolated struct ReadFreshness: Codable, Sendable {+ let syncState: ReadSyncState+ let assessment: ReadFreshnessAssessment+ let assessedAt: String+ let lastImportedAt: String?+ let evidence: ReadImportEvidence+ let recentImportThresholdMs: Int++ private enum CodingKeys: String, CodingKey {+ case syncState, assessment, assessedAt, lastImportedAt, evidence, recentImportThresholdMs+ }++ func encode(to encoder: Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(syncState, forKey: .syncState)+ try container.encode(assessment, forKey: .assessment)+ try container.encode(assessedAt, forKey: .assessedAt)+ // The wire contract requires an explicit nullable import timestamp.+ try container.encode(lastImportedAt, forKey: .lastImportedAt)+ try container.encode(evidence, forKey: .evidence)+ try container.encode(recentImportThresholdMs, forKey: .recentImportThresholdMs)+ }+}++nonisolated struct ReadExecutionMetadata: Codable, Sendable {+ let policy: MCPReadPolicy+ let refreshOutcome: ReadRefreshOutcome+ let budgetMs: Int+}++nonisolated struct ReadCaptureMetadata: Codable, Sendable {+ let asOf: String+ let snapshotId: String+ let freshness: ReadFreshness+ let read: ReadExecutionMetadata+}++nonisolated enum ReadFailureCategory: String, Encodable, Sendable {+ case storageFailure = "storage_failure"+ case serializationFailure = "serialization_failure"+ case incoherentCapture = "incoherent_capture"+ case timeout = "READ_TIMEOUT"+ case busy = "READ_BUSY"+}++/// A failed request has no invented capture identity or capture timestamp.+nonisolated struct ReadFailureMetadata: Encodable, Sendable {+ let requestId: String+ let category: ReadFailureCategory+ let read: ReadExecutionMetadata+}++nonisolated enum MCPReadResultMetadata: Encodable, Sendable {+ case capture(ReadCaptureMetadata)+ case failure(ReadFailureMetadata)++ func encode(to encoder: Encoder) throws {+ switch self {+ case .capture(let metadata): try metadata.encode(to: encoder)+ case .failure(let metadata): try metadata.encode(to: encoder)+ }+ }+}++nonisolated struct MCPToolResultMetadata: Encodable, Sendable {+ let read: MCPReadResultMetadata++ private enum CodingKeys: String, CodingKey {+ case read = "me.nore.ig.transit/read"+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadOperation.swift b/Transit/Transit/MCP/Reads/MCPReadOperation.swiftnew file mode 100644index 0000000..4682d9d--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadOperation.swift@@ -0,0 +1,42 @@+#if os(macOS)+import Foundation++nonisolated struct MCPReadOperation: Sendable {+ let id: UUID+ let generation: UInt64+ let diagnosticContext: MCPReadDiagnosticContext+ private let coordinator: MCPReadCoordinator++ init(id: UUID, generation: UInt64, context: MCPReadDiagnosticContext, coordinator: MCPReadCoordinator) {+ self.id = id+ self.generation = generation+ self.coordinator = coordinator+ self.diagnosticContext = context+ }++ func recordDiagnostic(_ phase: MCPReadDiagnosticPhase, startedAt: ContinuousClock.Instant,+ outcome: MCPReadDiagnosticOutcome? = nil) {+ coordinator.recordDiagnostic(context: diagnosticContext, phase: phase, startedAt: startedAt, outcome: outcome)+ }++ func beginActorQueue() { coordinator.beginActorQueue(id: id) }+ func finishActorQueue() { coordinator.finishActorQueue(id: id) }++ func shouldContinue() -> Bool { coordinator.canContinue(id: id, generation: generation) }++ /// Remaining original admission budget, never a clock restarted by a handler.+ func remainingBudget() -> Duration { coordinator.remainingBudget(id: id, generation: generation) }+}++extension MCPReadCoordinator {+ nonisolated func recordDiagnostic(context: MCPReadDiagnosticContext, phase: MCPReadDiagnosticPhase,+ startedAt: ContinuousClock.Instant, outcome: MCPReadDiagnosticOutcome? = nil) {+ guard diagnostics.capacity > 0 else { return }+ let finished = ContinuousClock.now+ let count = unfinishedCount+ diagnostics.enqueue(MCPReadDiagnosticEvent(context: context, phase: phase, startedAt: startedAt,+ finishedAt: finished, outcome: outcome, unfinishedPhysicalCount: count))+ }++}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadProjection+Catalog.swift b/Transit/Transit/MCP/Reads/MCPReadProjection+Catalog.swiftnew file mode 100644index 0000000..fa54911--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadProjection+Catalog.swift@@ -0,0 +1,114 @@+#if os(macOS)+import Foundation++extension MCPReadProjection {+ static func projects(_ view: CapturedReadView, checkpoint: () throws -> Void = {}) throws -> [[String: Any]] {+ let tasksByKey = try catalogTaskIndex(view, checkpoint: checkpoint)+ var milestonesByProject: [UUID: [ReadMilestone]] = [:]+ for milestone in view.milestones {+ try checkpoint()+ if let projectID = milestone.storedProjectID {+ milestonesByProject[projectID, default: []].append(milestone)+ }+ }+ return try view.projects.sorted { $0.name < $1.name }.map { project in+ try checkpoint()+ var record = try object(project.selectedRecordJSON)+ var activeTaskCount = 0+ for key in project.taskKeys {+ try checkpoint()+ guard let task = tasksByKey[key] else { throw MCPReadCaptureError.incoherentCapture }+ if !["done", "abandoned"].contains(task.effectiveStatus) { activeTaskCount += 1 }+ }+ record["activeTaskCount"] = activeTaskCount+ // Ordinary catalog queries historically select milestones by project UUID.+ let milestones = milestonesByProject[project.id, default: []]+ if !milestones.isEmpty {+ record["milestones"] = try milestones.map { milestone in+ try checkpoint()+ return milestoneSummary(milestone)+ }+ }+ return record+ }+ }++ static func milestones(_ view: CapturedReadView, arguments: [String: Any],+ checkpoint: () throws -> Void = {}) throws -> [[String: Any]] {+ try checkpoint()+ let project = try project(arguments, view: view, validateIgnoredName: false)+ try enumeration(arguments, key: "status", type: MilestoneStatus.self)+ try string(arguments, key: "search")+ try integer(arguments, key: "displayId")+ let id = IntentHelpers.parseIntValue(arguments["displayId"])+ var milestones = view.milestones+ if let id {+ milestones = try milestones.filter { milestone in+ try checkpoint()+ return milestone.permanentDisplayId == id+ }+ guard milestones.count <= 1 else {+ throw MCPTaskQueryError(code: "AMBIGUOUS_FILTER",+ message: "Duplicate milestone identifier detected for displayId \(id)")+ }+ }+ let tasksByKey = id == nil ? [:] : try catalogTaskIndex(view, checkpoint: checkpoint)+ return try milestones.filter { milestone in+ try checkpoint()+ return matchesMilestone(ReadMilestoneIdentity(id: milestone.id,+ permanentDisplayId: milestone.permanentDisplayId, name: milestone.name,+ storedProjectID: milestone.storedProjectID, rawStatus: milestone.rawStatus,+ milestoneDescription: milestone.milestoneDescription), arguments: arguments, projectID: project?.id)+ }.map { milestone in+ try checkpoint()+ var record = try object(milestone.selectedRecordJSON)+ record["taskCount"] = milestone.taskKeys.count+ if id != nil {+ record["tasks"] = try milestone.taskKeys.map { key in+ try checkpoint()+ guard let task = tasksByKey[key] else {+ throw MCPReadCaptureError.incoherentCapture+ }+ var summary: [String: Any] = ["taskId": task.id.uuidString, "name": task.name,+ "status": task.rawStatus, "type": task.rawType, "priority": task.effectivePriority]+ summary["displayId"] = task.permanentDisplayId+ return summary+ }+ }+ return record+ }+ }++ private static func catalogTaskIndex(_ view: CapturedReadView,+ checkpoint: () throws -> Void) throws -> [LocalRecordKey: ReadTask] {+ try checkpoint()+ var index: [LocalRecordKey: ReadTask] = [:]+ for task in view.tasks {+ try checkpoint()+ guard index.updateValue(task, forKey: task.physicalKey) == nil else {+ throw MCPReadCaptureError.incoherentCapture+ }+ }+ return index+ }++ static func matchesMilestone(_ milestone: ReadMilestoneIdentity, arguments: [String: Any],+ projectID: UUID?) -> Bool {+ if let projectID, milestone.storedProjectID != projectID { return false }+ if let values = arguments["status"] as? [String], !values.contains(milestone.rawStatus) { return false }+ if let value = arguments["status"] as? String, value != milestone.rawStatus { return false }+ if let search = arguments["search"] as? String,+ !search.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,+ !milestone.name.localizedCaseInsensitiveContains(search),+ milestone.milestoneDescription?.localizedCaseInsensitiveContains(search) != true { return false }+ return true+ }++ private static func milestoneSummary(_ milestone: ReadMilestone) -> [String: Any] {+ var record: [String: Any] = ["milestoneId": milestone.id.uuidString, "name": milestone.name,+ "status": milestone.rawStatus, "taskCount": milestone.taskKeys.count]+ record["displayId"] = milestone.permanentDisplayId+ return record+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadProjection+Selection.swift b/Transit/Transit/MCP/Reads/MCPReadProjection+Selection.swiftnew file mode 100644index 0000000..7499498--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadProjection+Selection.swift@@ -0,0 +1,45 @@+#if os(macOS)+import Foundation++extension MCPReadProjection {+ /// Preserve identifier ambiguity before filters; only uniquely selected batch records need bodies.+ static func taskBodyKeys(_ values: [ReadTaskSelectionValue], request: MCPTaskQueryRequest,+ filters: MCPQueryFilters?) throws -> Set<LocalRecordKey> {+ switch request.selector {+ case .taskIDs(let ids):+ let wanted = Set(ids.compactMap(UUID.init(uuidString:)))+ let groups = Dictionary(grouping: values.filter { wanted.contains($0.id) }, by: \.id)+ return Set(groups.values.filter { $0.count == 1 }.compactMap { $0.first?.physicalKey })+ case .displayIDs(let ids):+ let wanted = Set(ids)+ let groups = Dictionary(grouping: values.filter {+ $0.permanentDisplayId.map { wanted.contains($0) } == true+ }, by: \.permanentDisplayId)+ return Set(groups.values.filter { $0.count == 1 }.compactMap { $0.first?.physicalKey })+ case .single(let id):+ guard let filters else { return [] }+ let candidates = values.filter { $0.permanentDisplayId == id }+ guard candidates.count <= 1 else {+ throw MCPTaskQueryError(code: "AMBIGUOUS_TASK_ID",+ message: "Duplicate task identifier detected for displayId \(id)")+ }+ return Set(candidates.filter { matches($0, filters: filters) }.map(\.physicalKey))+ case .list:+ guard let filters else { return [] }+ return Set(values.filter { matches($0, filters: filters) }.map(\.physicalKey))+ }+ }+ static func milestoneBodyKeys(_ values: [ReadMilestoneSelectionValue], arguments: [String: Any],+ projectID: UUID?) throws -> Set<LocalRecordKey> {+ let id = IntentHelpers.parseIntValue(arguments["displayId"])+ let candidates = values.filter { id == nil || $0.identity.permanentDisplayId == id }+ if let id, candidates.count > 1 {+ throw MCPTaskQueryError(code: "AMBIGUOUS_FILTER",+ message: "Duplicate milestone identifier detected for displayId \(id)")+ }+ return Set(candidates.filter {+ matchesMilestone($0.identity, arguments: arguments, projectID: projectID)+ }.map(\.physicalKey))+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadProjection.swift b/Transit/Transit/MCP/Reads/MCPReadProjection.swiftnew file mode 100644index 0000000..b49f0f0--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadProjection.swift@@ -0,0 +1,264 @@+#if os(macOS)+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]] {+ 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 })+ 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!)+ })+ case .list, .single:+ guard let filters = try filters(arguments, view: view) else { return [] }+ let keys = try taskBodyKeys(available.map(selectionValue), request: request, filters: filters)+ return try available.filter { keys.contains($0.physicalKey) }+ .sorted { $0.id.uuidString < $1.id.uuidString }.map { try task($0, view: view, request: request) }+ }+ }++ private static func scopedTasks(_ view: CapturedReadView) -> [ReadTask] {+ guard case .projects(let keys) = view.captureScope else { return view.tasks }+ let projects = Set(keys)+ return view.tasks.filter { $0.projectKey.map { projects.contains($0) } == true }+ }++ private static func batch(_ view: CapturedReadView, request: MCPTaskQueryRequest,+ inputs: [(requested: [String: Any], key: String)],+ index: [String: [ReadTask]]) throws -> [[String: Any]] {+ var serialized: [LocalRecordKey: [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 record = matches.first {+ if serialized[record.physicalKey] == nil {+ serialized[record.physicalKey] = try task(record, view: view, request: request)+ }+ outcome["task"] = serialized[record.physicalKey]+ } else {+ let field = input.requested.keys.first ?? "identifier"+ let identifier = input.requested[field] ?? input.key+ outcome["error"] = ["code": matches.isEmpty ? "TASK_NOT_FOUND" : "AMBIGUOUS_TASK_ID",+ "message": matches.isEmpty ? "No task matches \(field) \(identifier)"+ : "Multiple tasks match \(field) \(identifier)"]+ }+ return outcome+ }+ }++ static func task(_ task: ReadTask, view: CapturedReadView,+ request: MCPTaskQueryRequest) throws -> [String: Any] {+ if request.detailLevel == "full" {+ guard task.revision != nil, let bytes = task.fullRecordWithoutCommentsJSON else {+ throw MCPReadCaptureError.incoherentCapture+ }+ var record = try object(bytes)+ if request.includeComments {+ // Canonical r1 covers UUID-based comments, including duplicate physical owners.+ guard let comments = task.requestedCommentRecordsJSON else {+ throw MCPReadCaptureError.incoherentCapture+ }+ record["comments"] = try JSONSerialization.jsonObject(with: comments)+ }+ if (record["metadata"] as? [String: String])?.isEmpty == true { record.removeValue(forKey: "metadata") }+ return record+ }+ let formatter = ISO8601DateFormatter()+ var record: [String: Any] = ["taskId": task.id.uuidString, "name": task.name,+ "status": task.rawStatus, "type": task.rawType, "priority": task.effectivePriority,+ "lastStatusChangeDate": formatter.string(from: task.lastStatusChangeDate)]+ record["displayId"] = task.permanentDisplayId+ if let project = view.projects.first(where: { $0.physicalKey == task.projectKey }) {+ record["projectId"] = project.id.uuidString+ record["projectName"] = project.name+ }+ if let date = task.completionDate { record["completionDate"] = formatter.string(from: date) }+ if let milestone = view.milestones.first(where: { $0.physicalKey == task.milestoneKey }) {+ var info: [String: Any] = ["milestoneId": milestone.id.uuidString, "name": milestone.name]+ info["displayId"] = milestone.permanentDisplayId+ record["milestone"] = info+ }+ if request.includeComments {+ record["comments"] = view.comments.filter { $0.storedTaskID == task.id }.sorted {+ ($0.creationDate, $0.id.uuidString) < ($1.creationDate, $1.id.uuidString)+ }.map { ["id": $0.id.uuidString, "authorName": $0.authorName, "content": $0.content,+ "isAgent": $0.isAgent, "creationDate": formatter.string(from: $0.creationDate)] as [String: Any] }+ }+ return record+ }++ static func object(_ bytes: Data) throws -> [String: Any] {+ do {+ guard let value = try JSONSerialization.jsonObject(with: bytes) as? [String: Any] else {+ throw MCPReadCaptureError.serializationFailure+ }+ return value+ } catch { throw MCPReadCaptureError.serializationFailure }+ }++ static func project(_ args: [String: Any], view: CapturedReadView,+ validateIgnoredName: Bool = true) throws -> ReadProject? {+ let identities = view.projects.map { ReadProjectIdentity(id: $0.id, name: $0.name) }+ guard let identity = try projectIdentity(args, projects: identities,+ validateIgnoredName: validateIgnoredName) else { return nil }+ return view.projects.first { $0.id == identity.id && $0.name == identity.name }+ }++ 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)+ guard id != nil || name?.isEmpty == false else { return nil }+ let matches = projects.filter {+ if let id { return $0.id == id }+ return ProjectNamePolicy.normalized($0.name) == ProjectNamePolicy.normalized(name!)+ }+ guard let project = matches.first else {+ let hint = id.map { "No project with ID \($0.uuidString)" } ?? "No project named \"\(name!)\""+ throw MCPTaskQueryError.invalid(hint)+ }+ guard id != nil || matches.count == 1 else {+ throw MCPTaskQueryError(code: "AMBIGUOUS_FILTER",+ message: "\(matches.count) projects match \"\(name ?? "")\"")+ }+ return project+ }++ // Keep project resolution before remaining-filter validation and milestone resolution afterwards.+ static func filters(_ args: [String: Any], view: CapturedReadView) throws -> MCPQueryFilters? {+ let project = try project(args, view: view)+ try validateTaskScalars(args)+ return try taskFilters(args, project: project.map { ReadProjectIdentity(id: $0.id, name: $0.name) },+ milestones: view.milestones.map { ReadMilestoneIdentity(id: $0.id,+ permanentDisplayId: $0.permanentDisplayId, name: $0.name, storedProjectID: $0.storedProjectID,+ rawStatus: $0.rawStatus, milestoneDescription: $0.milestoneDescription) })+ }++ static func taskFilters(_ args: [String: Any], project: ReadProjectIdentity?,+ milestones: [ReadMilestoneIdentity]) throws -> MCPQueryFilters? {+ let milestoneIDs: Set<UUID>?+ switch try milestoneFilter(args, project: project, milestones: milestones) {+ case .noFilter: milestoneIDs = nil+ case .matched(let ids): milestoneIDs = ids+ case .noMatch: return nil+ }+ let search = (args["search"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)+ return MCPQueryFilters.from(args: args, type: args["type"] as? String, projectId: project?.id,+ search: search?.isEmpty == true ? nil : search, milestoneIds: milestoneIDs)+ }++ enum MilestoneFilter {+ case noFilter, matched(Set<UUID>), noMatch+ }++ static func milestoneFilter(_ args: [String: Any], project: ReadProjectIdentity?,+ milestones: [ReadMilestoneIdentity]) throws -> MilestoneFilter {+ if let id = IntentHelpers.parseIntValue(args["milestoneDisplayId"]) {+ let matches = milestones.filter { $0.permanentDisplayId == id }+ guard matches.count <= 1 else {+ throw MCPTaskQueryError(code: "AMBIGUOUS_FILTER",+ message: "Duplicate milestone identifier detected for displayId \(id)")+ }+ guard let match = matches.first else { return .noMatch }+ return .matched([match.id])+ }+ if let name = args["milestone"] as? String,+ !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ let matches = milestones.filter {+ (project == nil || $0.storedProjectID == project?.id)+ && MilestoneNamePolicy.normalized($0.name) == MilestoneNamePolicy.normalized(name)+ }+ if let project, matches.count > 1 {+ throw MCPTaskQueryError(code: "AMBIGUOUS_FILTER",+ message: "Multiple milestones named '\(name)' exist in project '\(project.name)'")+ }+ return matches.isEmpty ? .noMatch : .matched(Set(matches.map(\.id)))+ }+ return .noFilter+ }++ static func validateTaskScalars(_ args: [String: Any]) throws {+ try integer(args, key: "milestoneDisplayId")+ try string(args, key: "milestone")+ try enumeration(args, key: "status", type: TaskStatus.self)+ try enumeration(args, key: "not_status", type: TaskStatus.self)+ try enumeration(args, key: "type", type: TaskType.self, allowArray: false)+ try enumeration(args, key: "priority", type: TaskPriority.self)+ if let value = args["unfinished"], IntentHelpers.parseBoolValue(value) == nil {+ throw MCPTaskQueryError.invalid("unfinished must be a boolean")+ }+ try string(args, key: "search")+ try integer(args, key: "displayId")+ }++ private static func matches(_ task: ReadTask, filters: MCPQueryFilters) -> Bool {+ matches(selectionValue(task), filters: filters)+ }++ static func selectionValue(_ task: ReadTask) -> ReadTaskSelectionValue {+ ReadTaskSelectionValue(physicalKey: task.physicalKey, id: task.id, permanentDisplayId: task.permanentDisplayId,+ name: task.name, taskDescription: task.taskDescription, storedProjectID: task.storedProjectID,+ storedMilestoneID: task.storedMilestoneID, rawStatus: task.rawStatus, rawType: task.rawType,+ effectivePriority: task.effectivePriority)+ }++ static func matches(_ task: ReadTaskSelectionValue, filters: MCPQueryFilters) -> Bool {+ if let values = filters.statuses, !values.isEmpty, !values.contains(task.rawStatus) { return false }+ if let values = filters.notStatuses, !values.isEmpty, values.contains(task.rawStatus) { return false }+ if let type = filters.type, type != task.rawType { return false }+ if let values = filters.priorities, !values.isEmpty, !values.contains(task.effectivePriority) { return false }+ if let id = filters.projectId, id != task.storedProjectID { return false }+ if let ids = filters.milestoneIds, !ids.isEmpty,+ task.storedMilestoneID.map({ ids.contains($0) }) != true { return false }+ if let search = filters.search, !search.isEmpty,+ !task.name.localizedCaseInsensitiveContains(search),+ task.taskDescription?.localizedCaseInsensitiveContains(search) != true { return false }+ return true+ }++ static func integer(_ args: [String: Any], key: String) throws {+ if args[key] != nil, IntentHelpers.parseIntValue(args[key]) == nil {+ throw MCPTaskQueryError.invalid("\(key) must be an integer")+ }+ }++ static func string(_ args: [String: Any], key: String) throws {+ if args[key] != nil, !(args[key] is String) { throw MCPTaskQueryError.invalid("\(key) must be a string") }+ }++ static func enumeration<E: RawRepresentable & CaseIterable>(+ _ args: [String: Any], key: String, type: E.Type, allowArray: Bool = true+ ) throws where E.RawValue == String {+ guard let raw = args[key] else { return }+ let expectation = allowArray ? "a string or array of strings" : "a string"+ let values: [String]+ if let single = raw as? String { values = [single] } else if allowArray, let array = raw as? [String] {+ values = array+ } else { throw MCPTaskQueryError.invalid("Invalid \(key): expected \(expectation)") }+ let all = E.allCases.map(\.rawValue)+ let invalid = values.filter { !all.contains($0) }+ if !invalid.isEmpty {+ let message = "Invalid \(key): \(invalid.joined(separator: ", ")). "+ + "Must be one of: \(all.joined(separator: ", "))"+ throw MCPTaskQueryError.invalid(message)+ }+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadPublicationDomain+Preparation.swift b/Transit/Transit/MCP/Reads/MCPReadPublicationDomain+Preparation.swiftnew file mode 100644index 0000000..d6e8c3e--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadPublicationDomain+Preparation.swift@@ -0,0 +1,168 @@+#if os(macOS)+import Foundation++extension MCPReadPublicationDomain {+ // swiftlint:disable:next function_parameter_count+ nonisolated func reserve(+ storeID: MCPPublicationStoreID, operationID: UUID, expectedVersion: UInt64,+ expectedTokenVersion: UInt64, index: any MCPPublicationIndex, chargeEntries: Int,+ chargeBytes: Int, newTokens: Set<String>, deadline: ContinuousClock.Instant+ ) throws -> MCPPublicationReservation {+ let base = try snapshot(for: storeID)+ let descriptor = index.descriptor+ guard base.version == expectedVersion, base.tokenVersion == expectedTokenVersion,+ chargeEntries >= 0, chargeBytes >= 0,+ descriptor.entryCount <= 8,+ descriptor.entryCount - base.index.descriptor.entryCount == chargeEntries,+ descriptor.encodedByteCount - base.index.descriptor.encodedByteCount == chargeBytes,+ descriptor.tokens.subtracting(base.index.descriptor.tokens) == newTokens,+ base.allocatedTokenSets.allSatisfy({ newTokens.isDisjoint(with: $0) }) else {+ throw PublicationRejection.busy+ }+ try validateExtension(descriptor, of: base.index.descriptor)+ let reservation = MCPPublicationReservation(storeID: storeID, operationID: operationID,+ expectedVersion: expectedVersion, index: index, descriptor: descriptor,+ chargeEntries: chargeEntries, chargeBytes: chargeBytes, newTokens: newTokens,+ deadline: deadline, domain: self)+ try withLock {+ guard let store = stores[storeID], store.version == expectedVersion,+ tokenVersion == expectedTokenVersion, store.pending[operationID] == nil else {+ throw PublicationRejection.busy+ }+ guard store.pending.count < 8,+ chargeEntries <= store.maxEntries - store.descriptor.entryCount - store.pendingEntries,+ chargeBytes <= store.maxBytes - store.descriptor.encodedByteCount - store.pendingBytes else {+ throw PublicationRejection.capacity+ }+ let instant = currentInstantLocked+ guard instant < deadline, descriptor.roots.values.allSatisfy({ instant < $0.deadline }) else {+ throw PublicationRejection.expired+ }+ store.pending[operationID] = reservation+ store.pendingEntries += chargeEntries+ store.pendingBytes += chargeBytes+ tokenVersion &+= 1+ }+ return reservation+ }++ /// Sibling allocations advance the global token version, so transfer pins a fresh+ /// allocation snapshot rather than requiring each child's historic token version.+ nonisolated func transfer(+ _ children: [MCPPublicationReservation], aggregateIndex: any MCPPublicationIndex, operationID: UUID+ ) throws -> MCPPublicationReservation {+ guard let first = children.first, children.count <= 8,+ Set(children.map(\.operationID)).count == children.count,+ children.allSatisfy({ $0.domain === self && $0.publicationStoreID == first.publicationStoreID+ && $0.expectedVersion == first.expectedVersion }) else { throw PublicationRejection.busy }+ let base = try snapshot(for: first.publicationStoreID)+ guard base.version == first.expectedVersion else { throw PublicationRejection.busy }+ let descriptor = aggregateIndex.descriptor+ let bytes = try checkedSum(children.map(\.chargeBytes))+ let entries = try checkedSum(children.map(\.chargeEntries))+ var tokens: Set<String> = []+ for child in children {+ guard tokens.isDisjoint(with: child.newTokens) else { throw PublicationRejection.busy }+ tokens.formUnion(child.newTokens)+ }+ guard descriptor.entryCount <= 8,+ descriptor.entryCount - base.index.descriptor.entryCount == entries,+ descriptor.encodedByteCount - base.index.descriptor.encodedByteCount == bytes,+ descriptor.tokens == base.index.descriptor.tokens.union(tokens) else { throw PublicationRejection.busy }+ try validateAggregate(descriptor, children: children, base: base.index.descriptor)+ let aggregate = MCPPublicationReservation(storeID: first.publicationStoreID, operationID: operationID,+ expectedVersion: base.version, index: aggregateIndex, descriptor: descriptor,+ chargeEntries: entries, chargeBytes: bytes, newTokens: tokens,+ deadline: children.map(\.deadline).min() ?? first.deadline, domain: self)+ try withLock {+ guard let store = stores[first.publicationStoreID], store.version == base.version,+ tokenVersion == base.tokenVersion,+ store.pending[operationID] == nil,+ children.allSatisfy({ $0.status == .pending && store.pending[$0.operationID] === $0 }) else {+ throw PublicationRejection.busy+ }+ let instant = currentInstantLocked+ guard instant < aggregate.deadline,+ descriptor.roots.values.allSatisfy({ instant < $0.deadline }) else {+ throw PublicationRejection.expired+ }+ // The summed charge remains unchanged throughout this ownership move.+ for child in children {+ retireLocked(child)+ store.pending.removeValue(forKey: child.operationID)+ child.status = .transferred+ }+ store.pending[operationID] = aggregate+ tokenVersion &+= 1+ }+ return aggregate+ }++ nonisolated func retire(+ storeID: MCPPublicationStoreID, expectedVersion: UInt64, replacementIndex: any MCPPublicationIndex+ ) throws {+ let base = try snapshot(for: storeID)+ let old = base.index.descriptor+ let replacement = replacementIndex.descriptor+ guard base.version == expectedVersion,+ replacement.roots.allSatisfy({ key, root in+ guard let original = old.roots[key] else { return false }+ return root.deadline == original.deadline && root.encodedByteCount == original.encodedByteCount+ && root.tokens == original.tokens+ }) else { throw PublicationRejection.busy }+ try withLock {+ guard let store = stores[storeID], store.version == expectedVersion else { throw PublicationRejection.busy }+ retireLocked(store.index)+ store.index = replacementIndex+ store.descriptor = replacement+ store.version &+= 1+ tokenVersion &+= 1+ }+ }++ private nonisolated func checkedSum(_ values: [Int]) throws -> Int {+ try values.reduce(0) { result, value in+ let (sum, overflow) = result.addingReportingOverflow(value)+ guard value >= 0, !overflow else { throw PublicationRejection.busy }+ return sum+ }+ }++ private nonisolated func validateExtension(+ _ candidate: MCPPublicationIndexDescriptor, of base: MCPPublicationIndexDescriptor+ ) throws {+ for (key, original) in base.roots {+ guard let root = candidate.roots[key], root.deadline == original.deadline,+ root.encodedByteCount >= original.encodedByteCount,+ original.tokens.isSubset(of: root.tokens) else { throw PublicationRejection.busy }+ }+ }++ private nonisolated func validateAggregate(+ _ aggregate: MCPPublicationIndexDescriptor,+ children: [MCPPublicationReservation], base: MCPPublicationIndexDescriptor+ ) throws {+ try validateExtension(aggregate, of: base)+ var roots = base.roots+ for child in children {+ for (key, root) in child.descriptor.roots {+ if let original = base.roots[key] {+ guard let combined = roots[key] else { throw PublicationRejection.busy }+ roots[key] = MCPPublicationRoot(id: key, deadline: min(combined.deadline, root.deadline),+ encodedByteCount: try checkedSum([combined.encodedByteCount,+ root.encodedByteCount - original.encodedByteCount]),+ tokens: combined.tokens.union(root.tokens))+ } else {+ guard roots[key] == nil else { throw PublicationRejection.busy }+ roots[key] = root+ }+ }+ }+ guard roots.count == aggregate.entryCount, roots.allSatisfy({ key, root in+ guard let result = aggregate.roots[key] else { return false }+ return result.deadline == root.deadline && result.encodedByteCount == root.encodedByteCount+ && result.tokens == root.tokens+ }) else { throw PublicationRejection.busy }+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadPublicationDomain.swift b/Transit/Transit/MCP/Reads/MCPReadPublicationDomain.swiftnew file mode 100644index 0000000..7ec3193--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadPublicationDomain.swift@@ -0,0 +1,168 @@+#if os(macOS)+import Foundation++/// All mutable coordinator and retention state uses this single short lock domain.+nonisolated final class MCPReadPublicationDomain: @unchecked Sendable {+ final class StoreState {+ var version: UInt64 = 0+ var index: any MCPPublicationIndex+ var descriptor: MCPPublicationIndexDescriptor+ let maxEntries: Int+ let maxBytes: Int+ var pending: [UUID: MCPPublicationReservation] = [:]+ var pendingEntries = 0+ var pendingBytes = 0++ init(index: any MCPPublicationIndex, descriptor: MCPPublicationIndexDescriptor,+ maxEntries: Int, maxBytes: Int) {+ self.index = index+ self.descriptor = descriptor+ self.maxEntries = maxEntries+ self.maxBytes = maxBytes+ }+ }++ /// A linked bundle avoids bulk array copying and destruction inside terminal gates.+ final class Retirement {+ let value: AnyObject+ let next: Retirement?+ init(_ value: AnyObject, next: Retirement?) { self.value = value; self.next = next }+ }++ private let lock = NSLock()+ private var retirement: Retirement?+ var stores: [MCPPublicationStoreID: StoreState] = [:]+ var tokenVersion: UInt64 = 0+ private var testingInstant: ContinuousClock.Instant?++ init(testingInstant: ContinuousClock.Instant? = nil) { self.testingInstant = testingInstant }++ /// Scalar deterministic-clock seam; production uses the system clock directly.+ func setTestingInstant(_ instant: ContinuousClock.Instant) {+ withLock { testingInstant = instant }+ }++ var currentInstantLocked: ContinuousClock.Instant { testingInstant ?? .now }++ func withLock<Value>(_ operation: () throws -> Value) rethrows -> Value {+ lock.lock()+ do {+ let result = try operation()+ let retired = retirement+ retirement = nil+ lock.unlock()+ withExtendedLifetime(retired) {}+ return result+ } catch {+ let retired = retirement+ retirement = nil+ lock.unlock()+ withExtendedLifetime(retired) {}+ throw error+ }+ }++ /// Response selectors resume the continuation before draining this bundle;+ /// physical worker ownership remains held until the outside-lock cleanup ends.+ func withLockRetainingRetirement<Value>(_ operation: () -> Value) -> (Value, Retirement?) {+ lock.lock()+ let result = operation()+ let retired = retirement+ retirement = nil+ lock.unlock()+ return (result, retired)+ }++ func retireLocked(_ value: AnyObject) { retirement = Retirement(value, next: retirement) }++ func register(storeID: MCPPublicationStoreID, index: any MCPPublicationIndex,+ maxEntries: Int, maxBytes: Int) throws {+ let descriptor = index.descriptor+ guard maxEntries >= 0, maxEntries <= 8, maxBytes >= 0,+ descriptor.entryCount <= maxEntries, descriptor.encodedByteCount <= maxBytes else {+ throw PublicationRejection.capacity+ }+ let state = StoreState(index: index, descriptor: descriptor, maxEntries: maxEntries, maxBytes: maxBytes)+ // Registration also pins a token snapshot; no token union is built under the gate.+ if descriptor.tokens.isEmpty {+ try withLock {+ guard stores[storeID] == nil else { throw PublicationRejection.busy }+ stores[storeID] = state+ tokenVersion &+= 1+ }+ return+ }+ let allocation = withLock { (tokenVersion, allocatedTokensLocked()) }+ guard allocation.1.allSatisfy({ descriptor.tokens.isDisjoint(with: $0) }) else {+ throw PublicationRejection.busy+ }+ try withLock {+ guard stores[storeID] == nil, tokenVersion == allocation.0 else { throw PublicationRejection.busy }+ stores[storeID] = state+ tokenVersion &+= 1+ }+ }++ func snapshot(for storeID: MCPPublicationStoreID) throws -> MCPPublicationStoreSnapshot {+ try withLock {+ guard let store = stores[storeID] else { throw PublicationRejection.busy }+ return MCPPublicationStoreSnapshot(version: store.version, tokenVersion: tokenVersion,+ index: store.index, allocatedTokenSets: allocatedTokensLocked())+ }+ }++ private func allocatedTokensLocked() -> [Set<String>] {+ stores.values.flatMap { [$0.descriptor.tokens] + $0.pending.values.map(\.newTokens) }+ }++ func accounting(for storeID: MCPPublicationStoreID) throws -> MCPPublicationAccounting {+ try withLock {+ guard let store = stores[storeID] else { throw PublicationRejection.busy }+ return MCPPublicationAccounting(visibleEntries: store.descriptor.entryCount,+ visibleBytes: store.descriptor.encodedByteCount, pendingEntries: store.pendingEntries,+ pendingBytes: store.pendingBytes)+ }+ }++ func validateLocked(_ reservation: MCPPublicationReservation) -> PublicationRejection? {+ guard reservation.domain === self, reservation.status == .pending,+ let store = stores[reservation.publicationStoreID],+ store.pending[reservation.operationID] === reservation,+ store.version == reservation.expectedVersion else { return .busy }+ let instant = currentInstantLocked+ guard instant < reservation.deadline,+ reservation.descriptor.roots.values.allSatisfy({ instant < $0.deadline }) else { return .expired }+ return nil+ }++ func commitLocked(_ reservation: MCPPublicationReservation) {+ guard reservation.domain === self, reservation.status == .pending,+ let store = stores[reservation.publicationStoreID],+ store.version == reservation.expectedVersion,+ store.pending[reservation.operationID] === reservation else { return }+ retireLocked(store.index)+ store.index = reservation.index+ store.descriptor = reservation.descriptor+ store.version &+= 1+ removeLocked(reservation, from: store)+ reservation.status = .committed+ tokenVersion &+= 1+ }++ func discardLocked(_ reservation: MCPPublicationReservation) {+ guard reservation.domain === self, reservation.status == .pending,+ let store = stores[reservation.publicationStoreID],+ store.pending[reservation.operationID] === reservation else { return }+ removeLocked(reservation, from: store)+ reservation.status = .discarded+ tokenVersion &+= 1+ }++ func removeLocked(_ reservation: MCPPublicationReservation, from store: StoreState) {+ retireLocked(reservation)+ store.pending.removeValue(forKey: reservation.operationID)+ store.pendingEntries -= reservation.chargeEntries+ store.pendingBytes -= reservation.chargeBytes+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadPublicationTypes.swift b/Transit/Transit/MCP/Reads/MCPReadPublicationTypes.swiftnew file mode 100644index 0000000..6fb406e--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadPublicationTypes.swift@@ -0,0 +1,58 @@+#if os(macOS)+import Foundation++/// Stable identity of one retention store sharing the common publication domain.+nonisolated struct MCPPublicationStoreID: Hashable, Sendable {+ let rawValue: UUID+}++nonisolated enum PublicationRejection: Error, Hashable, Sendable {+ case busy+ case expired+ case capacity+}++/// Calls occur only under the shared domain lock. Preparation/coalescing happens outside it.+/// Implementations validate all participants before any commit, and discard idempotently.+nonisolated protocol MCPPreparedPublication: Sendable {+ var publicationStoreID: MCPPublicationStoreID { get }+ func validateLocked(in domain: MCPReadPublicationDomain) -> PublicationRejection?+ func commitLocked(in domain: MCPReadPublicationDomain)+ func discardLocked(in domain: MCPReadPublicationDomain)+}++/// Coalesces selected children into one immutable candidate per store before terminal selection.+/// Preparation runs outside the terminal lock; reservation ownership transfers atomically+/// through the same domain, without an independent store lock or a capacity-charge gap.+/// Concrete lookup, reservation, transfer and retirement hooks are supplied in task 9.+nonisolated protocol MCPReadPublicationParticipant: Sendable {+ var publicationStoreID: MCPPublicationStoreID { get }+ func prepareAggregate(+ _ publications: [any MCPPreparedPublication],+ in domain: MCPReadPublicationDomain+ ) throws -> any MCPPreparedPublication+}++/// All failure bytes must be ready before entering the terminal-selection lock.+nonisolated struct PreencodedPublicationErrors: Sendable {+ let busy: Data+ let expired: Data+ let capacity: Data+}++nonisolated struct PreparedReadResult: Sendable {+ let encodedResponse: Data+ let publications: [any MCPPreparedPublication]+ let publicationErrors: PreencodedPublicationErrors+ /// Known typed tool outcome only. Nil leaves opaque responses unclassified.+ let diagnosticOutcome: MCPReadDiagnosticOutcome?++ init(encodedResponse: Data, publications: [any MCPPreparedPublication],+ publicationErrors: PreencodedPublicationErrors, diagnosticOutcome: MCPReadDiagnosticOutcome? = nil) {+ self.encodedResponse = encodedResponse+ self.publications = publications+ self.publicationErrors = publicationErrors+ self.diagnosticOutcome = diagnosticOutcome+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadRefreshPolicy.swift b/Transit/Transit/MCP/Reads/MCPReadRefreshPolicy.swiftnew file mode 100644index 0000000..2c669a4--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadRefreshPolicy.swift@@ -0,0 +1,75 @@+#if os(macOS)+import Foundation++nonisolated enum MCPRefreshDecision: Equatable, Sendable {+ case skip(ReadRefreshOutcome)+ case wait(Duration)+}++/// Current public SwiftData APIs supply no force-pull trigger. This adapter never writes.+nonisolated struct MCPUnavailableRefreshTrigger: Sendable {+ let isAvailable = false+}++nonisolated enum MCPReadRefreshPolicy {+ /// Use before cursor lookup; caller preserves existing selector-validation precedence.+ static func parse(_ value: Any?) -> MCPReadPolicy? {+ guard let value else { return .refreshIfNeeded }+ guard let string = value as? String else { return nil }+ return MCPReadPolicy(rawValue: string)+ }++ static func decision(policy: MCPReadPolicy, snapshot: MCPImportMonitorSnapshot,+ recent: Bool, remaining: Duration, applicableInFlightIDs: Set<UUID> = [],+ triggerAvailable: Bool = false) -> MCPRefreshDecision {+ guard snapshot.syncActive, policy != .cached else { return .skip(.notRequested) }+ guard snapshot.observationIsValid else { return .skip(.unavailable) }+ if recent { return .skip(.recentImport) }+ guard triggerAvailable || !snapshot.inFlight.isDisjoint(with: applicableInFlightIDs) else {+ return .skip(.unavailable)+ }+ guard remaining > .zero else { return .skip(.timeout) }+ return .wait(min(.seconds(2), remaining))+ }++ /// Capture-time applicability is evaluated again after this bounded wait. A successful+ /// callback alone never produces import_observed or a recent freshness claim.+ @concurrent static func wait(+ monitor: MCPImportEvidenceMonitor, initial: MCPImportMonitorSnapshot, duration: Duration,+ observation: MCPImportObservationWindow,+ now: @Sendable () -> ContinuousClock.Instant = { .now },+ sleep: @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }+ ) async -> MCPImportMonitorSnapshot {+ // Caller owns the window from before decision until metadata is frozen after capture.+ let deadline = now().advanced(by: max(.zero, duration))+ while now() < deadline, !Task.isCancelled {+ let state = monitor.snapshot(observation: observation)+ guard state.observationIsValid else { return state }+ let succeeded = state.successfulImports.contains {+ observation.applicableImportIDs.contains($0.key) && initial.successfulImports[$0.key] == nil+ }+ let failed = state.failedImports.contains {+ observation.applicableImportIDs.contains($0.key) && $0.value > initial.generation+ }+ if succeeded || failed { return state }+ do { try await sleep(min(.milliseconds(10), now().duration(to: deadline))) } catch { break }+ }+ return monitor.snapshot(observation: observation)+ }++ static func outcome(initial: MCPImportMonitorSnapshot, final: MCPImportMonitorSnapshot,+ proof: MCPImportCaptureProof?, applicableInFlightIDs: Set<UUID> = [],+ triggerAvailable: Bool = false) -> ReadRefreshOutcome {+ guard final.observationIsValid else { return .unavailable }+ if let proof, proof.storeIdentifier == final.storeIdentifier,+ final.successfulImports.contains(where: {+ proof.visibleImportIDs.contains($0.key) && initial.successfulImports[$0.key] == nil+ }) { return .importObserved }+ if final.failedImports.contains(where: {+ applicableInFlightIDs.contains($0.key) && $0.value > initial.generation+ }) { return .failed }+ return triggerAvailable || !initial.inFlight.isDisjoint(with: applicableInFlightIDs)+ ? .timeout : .unavailable+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadService+CaptureRequest.swift b/Transit/Transit/MCP/Reads/MCPReadService+CaptureRequest.swiftnew file mode 100644index 0000000..b6e6fde--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadService+CaptureRequest.swift@@ -0,0 +1,59 @@+#if os(macOS)+import Foundation++extension MCPReadService {+ func captureRequest(tool: String, arguments: [String: Any], selection: ReadCaptureSelection,+ includeComments: Bool, query: MCPTaskQueryRequest?) -> ReadCaptureRequest {+ let fields = arguments.mapValues(AnyCodable.init)+ let state = ValidationState()+ return ReadCaptureRequest(projectSelectors: nil, selection: selection,+ completeness: .selectedRead, includeComments: includeComments,+ validateProjects: { projects in+ let args = fields.mapValues(\.value)+ guard tool != "get_projects" else { return }+ state.project = try MCPReadProjection.projectIdentity(args, projects: projects,+ validateIgnoredName: tool == "query_tasks")+ if tool == "query_tasks" {+ try MCPReadProjection.validateTaskScalars(args)+ } else {+ try MCPReadProjection.enumeration(args, key: "status", type: MilestoneStatus.self)+ try MCPReadProjection.string(args, key: "search")+ try MCPReadProjection.integer(args, key: "displayId")+ }+ }, validateMilestones: { milestones in+ let args = fields.mapValues(\.value)+ state.milestones = milestones+ if tool == "query_tasks" {+ if case .noMatch = try MCPReadProjection.milestoneFilter(args, project: state.project,+ milestones: milestones) { return false }+ return true+ }+ guard tool == "query_milestones", let id = IntentHelpers.parseIntValue(args["displayId"]) else {+ return tool == "get_projects"+ }+ let matches = milestones.filter { $0.permanentDisplayId == id }+ guard matches.count <= 1 else {+ throw MCPTaskQueryError(code: "AMBIGUOUS_FILTER",+ message: "Duplicate milestone identifier detected for displayId \(id)")+ }+ guard let match = matches.first else { return false }+ return MCPReadProjection.matchesMilestone(match, arguments: args, projectID: state.project?.id)+ }, selectTaskBodies: { values in+ guard let query else { return Set(values.map(\.physicalKey)) }+ let filters = try MCPReadProjection.taskFilters(fields.mapValues(\.value),+ project: state.project, milestones: state.milestones)+ return try MCPReadProjection.taskBodyKeys(values, request: query, filters: filters)+ }, selectMilestoneBodies: { values in+ guard tool == "query_milestones" else { return [] }+ return try MCPReadProjection.milestoneBodyKeys(values, arguments: fields.mapValues(\.value),+ projectID: state.project?.id)+ })+ }++ private final class ValidationState {+ var project: ReadProjectIdentity?+ var milestones: [ReadMilestoneIdentity] = []+ }++}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadService+PreparedPages.swift b/Transit/Transit/MCP/Reads/MCPReadService+PreparedPages.swiftnew file mode 100644index 0000000..bf6aa35--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadService+PreparedPages.swift@@ -0,0 +1,65 @@+#if os(macOS)+import Foundation++extension MCPReadService {+ func prepareRetainedPage(cursor: String, requestedPolicy: MCPReadPolicy?) throws -> MCPPreparedToolRead {+ let (page, pin) = try snapshots.preparedRetainedPage(for: cursor)+ if let requestedPolicy, let retained = page.policy, requestedPolicy != retained {+ throw MCPTaskQueryError(code: "INVALID_INPUT", message: "readPolicy conflicts with retained query")+ }+ if let owner = page.preparedResultPage {+ return MCPPreparedToolRead(preparedResultPage: owner, frozenMetadataBytes: page.metadataBytes,+ publications: [pin])+ }+ return try MCPPreparedToolRead(text: page.text, frozenMetadataBytes: page.metadataBytes, publications: [pin])+ }++ func preparePages(_ results: [[String: Any]], query: MCPTaskQueryRequest,+ view: CapturedReadView, operation: MCPReadOperation,+ frozenMetadataBytes: Data) throws -> MCPPreparedToolRead {+ let count = max(1, (results.count + query.limit - 1) / query.limit)+ let cursors = (0..<(count - 1)).map { _ in snapshots.makeCursor() }+ let formatter = ISO8601DateFormatter()+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ guard let asOf = formatter.date(from: view.metadata.asOf) else {+ throw MCPReadCaptureError.incoherentCapture+ }+ let expiry = ISO8601DateFormatter().string(from: asOf.addingTimeInterval(300))+ let pages = try (0..<count).map { position in+ guard operation.shouldContinue() else { throw CancellationError() }+ let start = position * query.limit+ let end = min(start + query.limit, results.count)+ let next: Any = position < cursors.count ? cursors[position] : NSNull()+ return try jsonText(["results": Array(results[start..<end]), "nextCursor": next, "expiresAt": expiry])+ }+ guard operation.shouldContinue() else { throw CancellationError() }+ let tools = try pages.map { text in+ guard operation.shouldContinue() else { throw CancellationError() }+ return try MCPPreparedToolRead(text: text, metadata: .capture(view.metadata),+ frozenMetadataBytes: frozenMetadataBytes)+ }+ if let owners = try preparePrivatePages(tools, tool: "query_tasks", operation: operation) {+ guard owners.count == tools.count, let first = owners.first else {+ throw MCPReadCaptureError.incoherentCapture+ }+ let checkpoint: @Sendable () throws -> Void = {+ guard operation.shouldContinue() else { throw CancellationError() }+ }+ let usage = try snapshots.domain.accounting(for: snapshots.publicationStoreID)+ // No model capture is retained in ordinary indexes. Raw metadata is charged by the store.+ let bundle = try MCPResultPreparation.prepare(pages: owners,+ budget: MCPResultRetentionBudget(store: .ordinary, originalCaptureIndexBytes: 0,+ visibleBytes: usage.visibleBytes, pendingBytes: usage.pendingBytes), checkpoint: checkpoint)+ let publication = try snapshots.prepare(preparedBundle: bundle, cursors: cursors,+ deadline: view.retentionDeadline, operationID: operation.id, metadataBytes: frozenMetadataBytes,+ policy: view.metadata.read.policy, operation: operation)+ return tools[0].attachingPreparedResultPage(first).attaching(publication.map { [$0] } ?? [])+ }+ let first = tools[0]+ let reservation = try snapshots.prepare(pages: pages, cursors: cursors, deadline: view.retentionDeadline,+ operationID: operation.id, metadataBytes: first.frozenMetadataBytes, policy: view.metadata.read.policy)+ return first.attaching(reservation.map { [$0] } ?? [])+ }++}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadService.swift b/Transit/Transit/MCP/Reads/MCPReadService.swiftnew file mode 100644index 0000000..22b13af--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadService.swift@@ -0,0 +1,242 @@+#if os(macOS)+import Foundation++/// A Sendable synchronous function value; no actor isolation or checkpoint is added.+typealias MCPReadPagePreparer = @Sendable ([MCPPreparedToolRead], String, MCPReadOperation)+ throws -> [MCPResultPreparedPage]++nonisolated struct MCPReadImportApplicability: Sendable {+ let inFlightImportIDs: Set<UUID>+ /// Independent evidence of saved-store visibility available before the decision.+ let visibleSavedImportProof: MCPImportCaptureProof?+}++/// Captures and prepares tool values. The outer coordinator alone publishes and chooses RPC bytes.+@MainActor+final class MCPReadService: MCPReadCapturedPreparing {+ let source: any MCPReadCaptureSource+ let monitor: MCPImportEvidenceMonitor+ let snapshots: MCPTaskQuerySnapshotStore+ let diagnostics: MCPReadDiagnosticSink+ let pagePreparer: MCPReadPagePreparer?+ private let applicability: () -> MCPReadImportApplicability+ private let proof: (CapturedReadView) -> MCPImportCaptureProof?++ init(source: any MCPReadCaptureSource, monitor: MCPImportEvidenceMonitor,+ snapshots: MCPTaskQuerySnapshotStore,+ applicability: @escaping () -> MCPReadImportApplicability = {+ MCPReadImportApplicability(inFlightImportIDs: [], visibleSavedImportProof: nil)+ },+ proof: @escaping (CapturedReadView) -> MCPImportCaptureProof? = { _ in nil },+ diagnostics: MCPReadDiagnosticSink = .disabled, pagePreparer: MCPReadPagePreparer? = nil) {+ self.source = source+ self.monitor = monitor+ self.snapshots = snapshots+ self.applicability = applicability+ self.proof = proof+ self.diagnostics = diagnostics+ self.pagePreparer = pagePreparer+ }++ /// Pure optional forwarding seam. Existing paged flow stays inactive until verified binding.+ func preparePrivatePages(_ pages: [MCPPreparedToolRead], tool: String,+ operation: MCPReadOperation) throws -> [MCPResultPreparedPage]? {+ guard let pagePreparer else { return nil }+ guard operation.shouldContinue() else { throw CancellationError() }+ let prepared = try pagePreparer(pages, tool, operation)+ guard operation.shouldContinue() else { throw CancellationError() }+ guard prepared.count == pages.count else { throw MCPReadCaptureError.incoherentCapture }+ for (original, owner) in zip(pages, prepared) {+ guard operation.shouldContinue() else { throw CancellationError() }+ guard original.result.content.count == 1,+ let text = original.result.content.first?.text,+ try MCPReadSourceByteValidation.matches(text, owner.source.originalText, checkpoint: {+ guard operation.shouldContinue() else { throw CancellationError() }+ }),+ original.result.isError == owner.source.originalIsError else {+ throw MCPReadCaptureError.incoherentCapture+ }+ }+ return prepared+ }++ func prepare(tool: String, arguments: [String: Any],+ operation: MCPReadOperation) async throws -> MCPPreparedToolRead {+ operation.finishActorQueue()+ var policy = MCPReadPolicy.refreshIfNeeded+ do {+ guard operation.shouldContinue() else { throw ReadExecutionError.timeout }+ let query = tool == "query_tasks" ? try MCPTaskQueryRequest.parse(arguments) : nil+ if let raw = arguments["readPolicy"] {+ guard let parsed = MCPReadRefreshPolicy.parse(raw) else {+ throw MCPTaskQueryError.invalid("readPolicy must be cached or refresh_if_needed")+ }+ policy = parsed+ }+ if let cursor = query?.cursor {+ return try prepareRetainedPage(cursor: cursor, requestedPolicy: query?.readPolicy)+ }+ let selection: ReadCaptureSelection+ switch tool {+ case "query_tasks": selection = .tasks(detail: query?.detailLevel == "full" ? .fullRecord : .summary)+ case "query_milestones":+ selection = arguments["displayId"] == nil ? .milestones : .tasks(detail: .summary)+ case "get_projects": selection = .projectCatalog+ default: throw MCPTaskQueryError.invalid("Unsupported covered read")+ }+ let request = captureRequest(tool: tool, arguments: arguments, selection: selection,+ includeComments: query?.includeComments ?? false, query: query)+ let fields = arguments.mapValues(AnyCodable.init)+ let transform: MCPReadCaptureTransform = { @MainActor [self] capsule, operation in+ try prepareProjection(capsule, tool: tool, arguments: fields.mapValues(\.value),+ query: query, operation: operation)+ }+ return try await prepareCapturedRead(request: request, policy: policy, operation: operation,+ transform: transform)+ } catch {+ return try prepareFailure(error, tool: tool, operation: operation, policy: policy)+ }+ }++ private func prepareProjection(+ _ capsule: MCPPreparedReadCapture, tool: String, arguments: [String: Any],+ query: MCPTaskQueryRequest?, operation: MCPReadOperation+ ) throws -> MCPPreparedToolRead {+ let captured = capsule.view+ let results: [[String: Any]]+ if let query {+ results = try MCPReadProjection.tasks(captured, request: query, arguments: arguments)+ } else {+ let checkpoint = {+ guard operation.shouldContinue() else { throw ReadExecutionError.timeout }+ }+ results = tool == "get_projects" ? try MCPReadProjection.projects(captured, checkpoint: checkpoint)+ : try MCPReadProjection.milestones(captured, arguments: arguments, checkpoint: checkpoint)+ }+ if let query {+ return try preparePages(results, query: query, view: captured, operation: operation,+ frozenMetadataBytes: capsule.frozenMetadataBytes)+ }+ let prepared = try MCPPreparedToolRead(text: jsonText(results),+ frozenMetadataBytes: capsule.frozenMetadataBytes)+ guard let owners = try preparePrivatePages([prepared], tool: tool, operation: operation) else {+ return prepared+ }+ guard owners.count == 1, let owner = owners.first else { throw MCPReadCaptureError.incoherentCapture }+ return prepared.attachingPreparedResultPage(owner)+ }++ func prepareCapturedRead(request: ReadCaptureRequest, policy: MCPReadPolicy,+ operation: MCPReadOperation, transform: @escaping MCPReadCaptureTransform)+ async throws -> MCPPreparedToolRead {+ guard operation.shouldContinue() else { throw ReadExecutionError.timeout }+ let applicable = await MainActor.run { self.applicability() }+ let observation = try? monitor.beginObservation(applicableImportIDs: applicable.inFlightImportIDs)+ defer { observation?.close() }+ let view = try await capture(request: request, policy: policy, operation: operation,+ context: (observation, applicable.visibleSavedImportProof))+ guard operation.shouldContinue() else { throw ReadExecutionError.timeout }+ let transformStarted = ContinuousClock.now+ defer { operation.recordDiagnostic(.transform, startedAt: transformStarted) }+ let metadataBytes = try JSONEncoder().encode(view.metadata)+ return try await transform(MCPPreparedReadCapture(view: view, frozenMetadataBytes: metadataBytes), operation)+ }++ private func capture(request: ReadCaptureRequest,+ policy: MCPReadPolicy, operation: MCPReadOperation,+ context: (MCPImportObservationWindow?, MCPImportCaptureProof?))+ async throws -> CapturedReadView {+ let refreshStarted = ContinuousClock.now+ let (observation, decisionProof) = context+ // The active window starts before the decision snapshot and remains through metadata freezing.+ let applicable = observation?.applicableImportIDs ?? []+ let initial = monitor.snapshot(observation: observation)+ let recent = monitor.freshness(initial, proof: decisionProof, asOf: Date(), now: .now)+ .assessment == .recentImport+ let decision = observation == nil && initial.syncActive && policy != .cached+ ? MCPRefreshDecision.skip(.unavailable)+ : MCPReadRefreshPolicy.decision(policy: policy, snapshot: initial, recent: recent,+ remaining: operation.remainingBudget(), applicableInFlightIDs: applicable)+ let skipped: ReadRefreshOutcome?+ switch decision {+ case .skip(let outcome): skipped = outcome+ case .wait(let duration):+ guard let observation else { throw MCPReadCaptureError.incoherentCapture }+ _ = await MCPReadRefreshPolicy.wait(monitor: monitor, initial: initial,+ duration: duration, observation: observation)+ skipped = nil+ }+ operation.recordDiagnostic(.refresh, startedAt: refreshStarted)+ guard operation.shouldContinue() else { throw ReadExecutionError.timeout }+ let captureStarted = ContinuousClock.now+ let view: CapturedReadView+ do { view = try source.capture(request) } catch {+ operation.recordDiagnostic(.capture, startedAt: captureStarted, outcome: .failure)+ throw error+ }+ operation.recordDiagnostic(.capture, startedAt: captureStarted)+ let formatter = ISO8601DateFormatter()+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ guard let date = formatter.date(from: view.metadata.asOf) else { throw MCPReadCaptureError.incoherentCapture }+ let visibility = observation == nil ? nil : proof(view)+ let snapshot = monitor.snapshot(observation: observation)+ let freshness = monitor.freshness(snapshot, proof: visibility, asOf: date, now: view.createdAt)+ let outcome = skipped ?? MCPReadRefreshPolicy.outcome(initial: initial, final: snapshot, proof: visibility,+ applicableInFlightIDs: applicable)+ let metadata = ReadCaptureMetadata(asOf: view.metadata.asOf, snapshotId: view.metadata.snapshotId,+ 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)+ }++ func jsonText(_ value: Any) throws -> String {+ do {+ let data = try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys])+ guard let text = String(data: data, encoding: .utf8) else { throw MCPReadCaptureError.serializationFailure }+ return text+ } catch { throw MCPReadCaptureError.serializationFailure }+ }++ /// Prepares the existing tool failure shape before outer transport serialization.+ func prepareFailure(_ error: Error, tool: String, operation: MCPReadOperation,+ policy: MCPReadPolicy) throws -> MCPPreparedToolRead {+ let failureCode = tool == "query_tasks" ? "QUERY_FAILED" : "READ_FAILED"+ let category: ReadFailureCategory?+ let code: String+ let message: String+ switch error {+ case let query as MCPTaskQueryError:+ category = nil; code = query.code; message = query.message+ case MCPReadCaptureError.incoherentCapture:+ 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:+ 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:+ category = .timeout; code = "READ_TIMEOUT"; message = "Read exceeded its original admission budget"+ default:+ category = .storageFailure; code = failureCode; message = "Saved read storage failed"+ }+ let metadata = category.map { MCPReadResultMetadata.failure(ReadFailureMetadata(+ requestId: operation.id.uuidString, category: $0,+ read: ReadExecutionMetadata(policy: policy, refreshOutcome: .unavailable, budgetMs: 5_000))) }+ let jsonFailure = tool == "query_tasks" || (code == "READ_FAILED"+ && (tool == "get_projects" || tool == "query_milestones"))+ let text = jsonFailure+ ? IntentHelpers.encodeJSON(["error": ["code": code, "message": message]]) : message+ // This error envelope consists only of valid strings and fixed metadata values.+ let evidence = jsonFailure ? nil+ : MCPResultProviderEvidence(origin: .plainText, evidence: .established,+ failure: MCPResultFailure(category: MCPResultClassification.category(for: code) ?? .internalFailure,+ diagnostic: nil))+ return try MCPPreparedToolRead(text: text, isError: true, metadata: metadata, providerEvidence: evidence)+ }++ private enum ReadExecutionError: Error { case timeout }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadSourceByteValidation.swift b/Transit/Transit/MCP/Reads/MCPReadSourceByteValidation.swiftnew file mode 100644index 0000000..8c21629--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadSourceByteValidation.swift@@ -0,0 +1,23 @@+#if os(macOS)+import Foundation++nonisolated enum MCPReadSourceByteValidation {+ /// Traverse without an unchecked count scan or temporary byte array. The supplied checkpoint+ /// belongs to the original operation and runs at most 256 byte comparisons apart.+ static func matches(_ original: String, _ prepared: String,+ checkpoint: @Sendable () throws -> Void) throws -> Bool {+ try checkpoint()+ var left = original.utf8.makeIterator()+ var right = prepared.utf8.makeIterator()+ var compared = 0+ while true {+ if compared == 256 { try checkpoint(); compared = 0 }+ let lhs = left.next()+ let rhs = right.next()+ guard lhs == rhs else { try checkpoint(); return false }+ guard lhs != nil else { try checkpoint(); return true }+ compared += 1+ }+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadToolPreparationContracts.swift b/Transit/Transit/MCP/Reads/MCPReadToolPreparationContracts.swiftnew file mode 100644index 0000000..20f5b5e--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadToolPreparationContracts.swift@@ -0,0 +1,23 @@+#if os(macOS)+import Foundation++/// Fresh or retained capture identity plus the original complete outer read metadata bytes.+/// A retained query consumes this value without capture, waiting or reassessment.+nonisolated struct MCPPreparedReadCapture: Sendable {+ let view: CapturedReadView+ let frozenMetadataBytes: Data+}++/// Pure value transformation can run off MainActor. Model/store access must explicitly hop.+typealias MCPReadCaptureTransform = @Sendable (MCPPreparedReadCapture, MCPReadOperation)+ async throws -> MCPPreparedToolRead++/// T63 owns the concrete policy/observation implementation. This is an interface-only seam.+/// The observation remains held through transform/encoding/private reservation preparation.+/// The operation always uses its original admission deadline. No helper publishes here.+nonisolated protocol MCPReadCapturedPreparing: Sendable {+ func prepareCapturedRead(request: ReadCaptureRequest, policy: MCPReadPolicy,+ operation: MCPReadOperation, transform: @escaping MCPReadCaptureTransform)+ async throws -> MCPPreparedToolRead+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPReadTransportAdapter.swift b/Transit/Transit/MCP/Reads/MCPReadTransportAdapter.swiftnew file mode 100644index 0000000..c7ddb86--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPReadTransportAdapter.swift@@ -0,0 +1,19 @@+#if os(macOS)+import Foundation+import HTTPTypes+import Hummingbird+import NIOCore+import NIOFoundationCompat++nonisolated enum MCPReadTransportAdapter {+ @concurrent static func response(+ coordinator: MCPReadCoordinator, timeout: Data, busy: Data,+ admittedAt: ContinuousClock.Instant = .now,+ worker: @escaping @Sendable (MCPReadOperation) async -> PreparedReadResult+ ) async -> Response {+ let bytes = await coordinator.execute(timeout: timeout, busy: busy, admittedAt: admittedAt, worker: worker)+ return Response(status: .ok, headers: [.contentType: "application/json"],+ body: .init(byteBuffer: ByteBuffer(data: bytes)))+ }+}+#endif
diff --git a/Transit/Transit/MCP/Reads/MCPToolDefinitions+ReadGuidance.swift b/Transit/Transit/MCP/Reads/MCPToolDefinitions+ReadGuidance.swiftnew file mode 100644index 0000000..00157df--- /dev/null+++ b/Transit/Transit/MCP/Reads/MCPToolDefinitions+ReadGuidance.swift@@ -0,0 +1,20 @@+#if os(macOS)+extension MCPToolDefinitions {+ nonisolated static let readExecutionDescription = """+ Each covered read describes saved local data. Response deadline is five seconds from original admission.+ Optional readPolicy is cached or refresh_if_needed (default). cached never waits for imports;+ refresh_if_needed observes only positively applicable already-running imports for at most two seconds+ within the original budget. Unsupported import visibility reports unknown freshness and null lastImportedAt;+ recent import evidence is not proof of global freshness or a server round trip. Inactive sync skips waiting.+ Read metadata uses asOf for the saved local capture time and an opaque snapshotId.+ freshness.assessedAt equals asOf.+ Cursor pages retain the original metadata and expiry; a cursor request has its own log correlation.+ Task storage/projection errors use QUERY_FAILED. Project/milestone execution failures use READ_FAILED.+ Failure metadata categories are storage_failure, serialization_failure, or incoherent_capture;+ READ_TIMEOUT and READ_BUSY never invent successful asOf or snapshotId metadata.+ No automatic retry occurs. After READ_BUSY or READ_TIMEOUT, use backoff before explicitly retrying;+ timed-out physical work retains its permit until cleanup, so an immediate retry may still be READ_BUSY.+ """++}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPJSONDocument.swift b/Transit/Transit/MCP/Results/MCPJSONDocument.swiftnew file mode 100644index 0000000..422daa0--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPJSONDocument.swift@@ -0,0 +1,293 @@+#if os(macOS)+import Foundation++/// Immutable JSON values retain member order and validated numeric lexemes.+nonisolated indirect enum MCPJSONValue: Sendable, Equatable {+ case object([MCPJSONMember])+ case array([MCPJSONValue])+ case string(String)+ case number(MCPJSONNumber)+ case boolean(Bool)+ case null+}++nonisolated struct MCPJSONMember: Sendable, Equatable {+ let name: String+ let value: MCPJSONValue+}++nonisolated struct MCPJSONNumber: Sendable, Equatable {+ let lexeme: String++ fileprivate init(validatedLexeme: String) {+ lexeme = validatedLexeme+ }+}++/// Only the complete-value parser may construct an insertable raw fragment.+nonisolated struct MCPJSONDocument: Sendable, Equatable {+ let originalUTF8: Data+ let value: MCPJSONValue++ private init(originalUTF8: Data, value: MCPJSONValue) {+ self.originalUTF8 = originalUTF8+ self.value = value+ }++ /// The worker supplies its original deadline/cancellation check.+ static func parse(+ _ utf8: Data,+ checkpoint: @escaping @Sendable () throws -> Void = {}+ ) throws -> MCPJSONDocument {+ try checkpoint()+ guard String(data: utf8, encoding: .utf8) != nil else { throw MCPResultBoundaryError.invalidJSON }+ var scanner = MCPJSONScanner(bytes: Array(utf8), checkpoint: checkpoint)+ let value = try scanner.parse()+ try checkpoint()+ return MCPJSONDocument(originalUTF8: utf8, value: value)+ }++ static func parse(+ _ text: String,+ checkpoint: @escaping @Sendable () throws -> Void = {}+ ) throws -> MCPJSONDocument {+ return try parse(Data(text.utf8), checkpoint: checkpoint)+ }+}++/// Declaration-stage failures are explicit; no source or effect is fabricated.+nonisolated enum MCPResultBoundaryError: Error, Sendable, Equatable {+ case notImplemented+ case invalidJSON+ case resourceLimit+ case unsupportedEvidence+}++/// Iterative assembly bounds both parser stack and the resulting value tree.+nonisolated private struct MCPJSONScanner {+ let bytes: [UInt8]+ let checkpoint: @Sendable () throws -> Void+ private var offset = 0+ private var nextCheckpoint = 256+ private var frames: [MCPJSONFrame] = []+ private var root: MCPJSONValue?++ init(bytes: [UInt8], checkpoint: @escaping @Sendable () throws -> Void) {+ self.bytes = bytes+ self.checkpoint = checkpoint+ }++ mutating func parse() throws -> MCPJSONValue {+ try skipWhitespace()+ try readValue()+ while !frames.isEmpty {+ try skipWhitespace()+ try processTopFrame()+ }+ try skipWhitespace()+ guard offset == bytes.count, let root else { throw MCPResultBoundaryError.invalidJSON }+ return root+ }++ private mutating func processTopFrame() throws {+ let index = frames.count - 1+ switch frames[index].state {+ case .valueOrEnd:+ if peek == 0x5D { try closeContainer() } else { try readValue() }+ case .valueRequired: try readValue()+ case .keyOrEnd:+ if peek == 0x7D { try closeContainer() } else { try readKey() }+ case .keyRequired: try readKey()+ case .colon:+ guard try take() == 0x3A else { throw MCPResultBoundaryError.invalidJSON }+ frames[index].state = .valueRequired+ case .commaOrEnd: try readSeparator()+ }+ }++ private mutating func readSeparator() throws {+ let index = frames.count - 1+ let closing: UInt8 = frames[index].isObject ? 0x7D : 0x5D+ if peek == closing {+ try closeContainer()+ } else {+ guard try take() == 0x2C else { throw MCPResultBoundaryError.invalidJSON }+ frames[index].state = frames[index].isObject ? .keyRequired : .valueRequired+ }+ }++ private mutating func readValue() throws {+ guard let byte = peek else { throw MCPResultBoundaryError.invalidJSON }+ switch byte {+ case 0x7B, 0x5B:+ guard frames.count < 32 else { throw MCPResultBoundaryError.resourceLimit }+ let isObject = try take() == 0x7B+ frames.append(MCPJSONFrame(isObject: isObject, state: isObject ? .keyOrEnd : .valueOrEnd))+ case 0x22: try attach(.string(readString()))+ case 0x74: try readLiteral("true"); attach(.boolean(true))+ case 0x66: try readLiteral("false"); attach(.boolean(false))+ case 0x6E: try readLiteral("null"); attach(.null)+ case 0x2D, 0x30...0x39: try attach(.number(MCPJSONNumber(validatedLexeme: readNumber())))+ default: throw MCPResultBoundaryError.invalidJSON+ }+ }++ private mutating func readKey() throws {+ let key = try readString()+ let index = frames.count - 1+ // Swift String hashing uses canonical equivalence; JSON names do not.+ guard frames[index].keys.insert(key.unicodeScalars.map(\.value)).inserted else {+ throw MCPResultBoundaryError.invalidJSON+ }+ frames[index].pendingKey = key+ frames[index].state = .colon+ }++ private mutating func closeContainer() throws {+ _ = try take()+ let frame = frames.removeLast()+ attach(frame.isObject ? .object(frame.members) : .array(frame.values))+ }++ private mutating func attach(_ value: MCPJSONValue) {+ guard !frames.isEmpty else { root = value; return }+ let index = frames.count - 1+ if frames[index].isObject {+ // Only the colon/value state can reach this path with an object.+ if let key = frames[index].pendingKey {+ frames[index].members.append(MCPJSONMember(name: key, value: value))+ frames[index].pendingKey = nil+ }+ } else {+ frames[index].values.append(value)+ }+ frames[index].state = .commaOrEnd+ }++ private var peek: UInt8? { offset < bytes.count ? bytes[offset] : nil }++ private mutating func take() throws -> UInt8 {+ guard let byte = peek else { throw MCPResultBoundaryError.invalidJSON }+ offset += 1+ if offset >= nextCheckpoint {+ try checkpoint()+ nextCheckpoint = offset + 256+ }+ return byte+ }++ private mutating func skipWhitespace() throws {+ while let byte = peek, [0x20, 0x09, 0x0A, 0x0D].contains(byte) { _ = try take() }+ }+}++nonisolated private extension MCPJSONScanner {+ mutating func readLiteral(_ literal: String) throws {+ for byte in literal.utf8 {+ guard try take() == byte else { throw MCPResultBoundaryError.invalidJSON }+ }+ }++ mutating func readNumber() throws -> String {+ let start = offset+ if peek == 0x2D { _ = try take() }+ if peek == 0x30 {+ _ = try take()+ } else {+ guard let byte = peek, (0x31...0x39).contains(byte) else { throw MCPResultBoundaryError.invalidJSON }+ try digits()+ }+ if peek == 0x2E { _ = try take(); try requiredDigits() }+ if peek == 0x65 || peek == 0x45 {+ _ = try take()+ if peek == 0x2B || peek == 0x2D { _ = try take() }+ try requiredDigits()+ }+ guard let token = String(bytes: bytes[start..<offset], encoding: .utf8) else {+ throw MCPResultBoundaryError.invalidJSON+ }+ return token+ }++ mutating func requiredDigits() throws {+ guard let byte = peek, (0x30...0x39).contains(byte) else { throw MCPResultBoundaryError.invalidJSON }+ try digits()+ }++ mutating func digits() throws {+ while let byte = peek, (0x30...0x39).contains(byte) { _ = try take() }+ }++ mutating func readString() throws -> String {+ guard try take() == 0x22 else { throw MCPResultBoundaryError.invalidJSON }+ var decoded: [UInt8] = []+ while true {+ let byte = try take()+ if byte == 0x22 { break }+ guard byte >= 0x20 else { throw MCPResultBoundaryError.invalidJSON }+ if byte != 0x5C { decoded.append(byte); continue }+ try decoded.append(contentsOf: readEscape())+ }+ guard let text = String(bytes: decoded, encoding: .utf8) else { throw MCPResultBoundaryError.invalidJSON }+ return text+ }++ mutating func readEscape() throws -> [UInt8] {+ switch try take() {+ case 0x22: return [0x22]+ case 0x5C: return [0x5C]+ case 0x2F: return [0x2F]+ case 0x62: return [0x08]+ case 0x66: return [0x0C]+ case 0x6E: return [0x0A]+ case 0x72: return [0x0D]+ case 0x74: return [0x09]+ case 0x75: return try Array(readUnicodeEscape().utf8)+ default: throw MCPResultBoundaryError.invalidJSON+ }+ }++ mutating func readUnicodeEscape() throws -> String {+ var code = try hexQuad()+ if (0xD800...0xDBFF).contains(code) {+ guard try take() == 0x5C, try take() == 0x75 else { throw MCPResultBoundaryError.invalidJSON }+ let low = try hexQuad()+ guard (0xDC00...0xDFFF).contains(low) else { throw MCPResultBoundaryError.invalidJSON }+ code = 0x10000 + (code - 0xD800) * 0x400 + low - 0xDC00+ } else if (0xDC00...0xDFFF).contains(code) {+ throw MCPResultBoundaryError.invalidJSON+ }+ guard let scalar = UnicodeScalar(code) else { throw MCPResultBoundaryError.invalidJSON }+ return String(scalar)+ }++ mutating func hexQuad() throws -> UInt32 {+ var code: UInt32 = 0+ for _ in 0..<4 {+ let byte = try take()+ let digit: UInt8+ switch byte {+ case 0x30...0x39: digit = byte - 0x30+ case 0x41...0x46: digit = byte - 0x41 + 10+ case 0x61...0x66: digit = byte - 0x61 + 10+ default: throw MCPResultBoundaryError.invalidJSON+ }+ code = code * 16 + UInt32(digit)+ }+ return code+ }+}++nonisolated private struct MCPJSONFrame {+ let isObject: Bool+ var state: MCPJSONFrameState+ var values: [MCPJSONValue] = []+ var members: [MCPJSONMember] = []+ var keys: Set<[UInt32]> = []+ var pendingKey: String?+}++nonisolated private enum MCPJSONFrameState {+ case valueOrEnd, valueRequired, keyOrEnd, keyRequired, colon, commaOrEnd+}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPModernProviderBinding.swift b/Transit/Transit/MCP/Results/MCPModernProviderBinding.swiftnew file mode 100644index 0000000..9e13cf0--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPModernProviderBinding.swift@@ -0,0 +1,265 @@+#if os(macOS)+import Foundation++nonisolated enum MCPModernProviderPreflight: Sendable {+ case ready(MCPResultContext)+ case rejected(MCPToolResult)+ case requestError(JSONRPCError)+}++/// Common value-only binding; providers continue to own storage, receipts and publication.+nonisolated enum MCPModernProviderBinding {+ /// Owner callbacks supply every private page before reserving publication.+ /// Fresh sibling pages share one original capture metadata owner, or fail whole.+ static func prepareReadPages(_ pages: [MCPPreparedToolRead], tool: String,+ operation: MCPReadOperation) throws -> [MCPResultPreparedPage] {+ let checkpoint = readCheckpoint(operation)+ try checkpoint()+ var prepared: [MCPResultPreparedPage] = []+ var metadataInitialized = false+ var originalMetadata: Data?+ var metadataOwner: MCPResultPreparedMetadata?+ var hasAttachedMetadata = false+ for page in pages {+ try checkpoint()+ if let attached = page.preparedResultPage {+ metadataOwner = attached.metadataOwner+ hasAttachedMetadata = true+ break+ }+ }+ for page in pages {+ try checkpoint()+ if let attached = page.preparedResultPage {+ prepared.append(attached)+ continue+ }+ if metadataInitialized {+ guard try sameMetadata(originalMetadata, page.frozenMetadataBytes, checkpoint: checkpoint) else {+ throw MCPResultBoundaryError.unsupportedEvidence+ }+ } else {+ originalMetadata = page.frozenMetadataBytes+ let value = try MCPResultProviderAdapters.metadata(result: page.result,+ frozenReadBytes: originalMetadata, checkpoint: checkpoint)+ if hasAttachedMetadata {+ guard try sameMetadata(metadataOwner?.value.document.originalUTF8,+ value?.document.originalUTF8, checkpoint: checkpoint) else {+ throw MCPResultBoundaryError.unsupportedEvidence+ }+ } else if let value {+ try checkpoint()+ metadataOwner = try MCPResultPreparation.metadata(value: value)+ try checkpoint()+ }+ metadataInitialized = true+ }+ let outcome = try readOutcome(page, tool: tool, checkpoint: checkpoint)+ prepared.append(try MCPResultPreparation.page(source: outcome.source, context: outcome.context,+ metadataOwner: metadataOwner, checkpoint: checkpoint))+ }+ try checkpoint()+ return prepared+ }++ private static func sameMetadata(_ left: Data?, _ right: Data?,+ checkpoint: @Sendable () throws -> Void) throws -> Bool {+ try checkpoint()+ guard let left, let right else { return left == nil && right == nil }+ guard left.count == right.count else { return false }+ for (index, pair) in zip(left, right).enumerated() {+ if index % 1_024 == 0 { try checkpoint() }+ if pair.0 != pair.1 { return false }+ }+ try checkpoint()+ return true+ }++ static func availability(maintenanceEnabled: Bool) -> MCPModernAvailability {+ let covered: Set<String> = ["query_tasks", "query_milestones", "get_projects", "query_project_summaries"]+ return MCPModernAvailability(tools: MCPToolDefinitions.tools(includingMaintenance: maintenanceEnabled).map {+ let execution: MCPModernToolExecution+ if covered.contains($0.name) {+ execution = .coveredRead+ } else if $0.name == "scan_duplicate_display_ids" {+ execution = .ordinaryRead+ } else if $0.name == "reassign_duplicate_display_ids" {+ execution = .unprotectedMaintenance+ } else {+ execution = .protectedWrite+ }+ return MCPModernAvailableTool(name: $0.name, execution: execution)+ })+ }++ static func call(_ request: JSONRPCRequest, tool: String, handler: MCPToolHandler,+ maintenanceEnabled: Bool) async throws -> MCPResultResponseSelection {+ guard let id = request.id else { throw MCPResultBoundaryError.unsupportedEvidence }+ switch await handler.modernPreflight(request, tool: tool) {+ case .requestError(let error):+ return .normal(try JSONEncoder().encode(JSONRPCResponse(id: id, result: nil, error: error)))+ case .rejected(let result):+ let context = MCPResultContext(tool: tool, semanticFailure: nil,+ mutationRecovery: nil, entityPositions: [])+ let outcome = try MCPResultProviderAdapters.outcome(result: result, context: context,+ origin: .generatedJSON)+ return .normal(try MCPResultProviderSelection.encode(outcome: outcome, id: id, metadata: nil))+ case .ready(let context):+ if context.mutationRecovery != nil {+ let message: String+ if case .unprotectedMaintenance = context.mutationRecovery {+ message = "Partial effects are possible. Run a fresh scan_duplicate_display_ids "+ + "and inspect before any further reassignment."+ } else {+ message = "Reconcile using the original tool and idempotency key; do not retry with a fresh key."+ }+ guard let encodedMessage = String(data: try JSONEncoder().encode(message), encoding: .utf8) else {+ throw MCPResultBoundaryError.unsupportedEvidence+ }+ let fallbackText = "{\"error\":{\"code\":\"OUTCOME_UNCERTAIN\",\"message\":" + encodedMessage + "}}"+ let fallback = try MCPResultAdapter.source(+ text: fallbackText,+ isError: true, origin: .generatedJSON, evidence: .unestablished)+ return try await MCPResultProviderSelection.mutation(id: id, context: context,+ metadata: nil, fallbackSource: fallback) {+ try await dispatch(request, context: context, handler: handler,+ maintenanceEnabled: maintenanceEnabled)+ }+ }+ let outcome = try await dispatch(request, context: context, handler: handler,+ maintenanceEnabled: maintenanceEnabled)+ return .normal(try MCPResultProviderSelection.encode(outcome: outcome, id: id, metadata: nil))+ }+ }++ private static func dispatch(_ request: JSONRPCRequest, context: MCPResultContext,+ handler: MCPToolHandler,+ maintenanceEnabled: Bool) async throws -> MCPResultProviderOutcome {+ guard let response = await handler.handle(request, maintenanceEnabled: maintenanceEnabled),+ response.error == nil, let result = response.result?.value as? MCPToolResult else {+ throw MCPResultBoundaryError.unsupportedEvidence+ }+ let origin: MCPResultOrigin+ if case .protectedWrite = context.mutationRecovery {+ origin = .retainedJSON+ } else {+ origin = .generatedJSON+ }+ let outcome = try MCPResultProviderAdapters.outcome(result: result, context: context, origin: origin)+ return try declaringPositions(outcome)+ }++ static func read(_ prepared: MCPPreparedToolRead, id: JSONRPCId, tool: String,+ operation: MCPReadOperation? = nil) throws -> Data {+ let checkpoint = readCheckpoint(operation)+ try checkpoint()+ if let attached = prepared.preparedResultPage {+ return try MCPResultEncoder.encode(fragment: attached.fragment, id: id, checkpoint: checkpoint)+ }+ let outcome = try readOutcome(prepared, tool: tool, checkpoint: checkpoint)+ let metadata = try MCPResultProviderAdapters.metadata(result: prepared.result,+ frozenReadBytes: prepared.frozenMetadataBytes, checkpoint: checkpoint)+ let presentation = try MCPResultAdapter.present(outcome.source, context: outcome.context,+ checkpoint: checkpoint)+ return try MCPResultEncoder.encode(source: outcome.source, presentation: presentation, id: id,+ metadata: metadata, checkpoint: checkpoint)+ }++ private static func readCheckpoint(_ operation: MCPReadOperation?) -> @Sendable () throws -> Void {+ {+ if let operation, !operation.shouldContinue() { throw CancellationError() }+ try Task.checkCancellation()+ }+ }++ private static func readOutcome(_ prepared: MCPPreparedToolRead, tool: String,+ checkpoint: @escaping @Sendable () throws -> Void) throws+ -> MCPResultProviderOutcome {+ var failure: MCPResultFailure?+ if case .some(.failure(let value)) = prepared.result.metadata?.read {+ let category: MCPResultErrorCategory+ switch value.category {+ case .storageFailure: category = .storageFailure+ case .serializationFailure: category = .serializationFailure+ case .incoherentCapture: category = .incoherentCapture+ case .timeout: category = .deadlineExceeded+ case .busy: category = .admissionBusy+ }+ failure = MCPResultFailure(category: category, diagnostic: nil)+ }+ let context = MCPResultContext(tool: tool, semanticFailure: failure,+ mutationRecovery: nil, entityPositions: [])+ let outcome = try MCPResultProviderAdapters.outcome(result: prepared.result, context: context,+ origin: .generatedJSON, checkpoint: checkpoint)+ return try declaringPositions(outcome, checkpoint: checkpoint)+ }+ /// Explicit current public shapes only. Historical unknown fields are never traversed for IDs.+ private static func declaringPositions(+ _ outcome: MCPResultProviderOutcome, checkpoint: @Sendable () throws -> Void = {}+ ) throws -> MCPResultProviderOutcome {+ guard let value = outcome.source.document?.value else { return outcome }+ let positions: [MCPResultEntityPosition]+ switch outcome.context.tool {+ case "query_project_summaries": positions = try portfolioPositions(value, checkpoint: checkpoint)+ case "scan_duplicate_display_ids": positions = try scanPositions(value, checkpoint: checkpoint)+ case "reassign_duplicate_display_ids": positions = try reassignmentPositions(value, checkpoint: checkpoint)+ default: positions = []+ }+ let context = outcome.context+ return MCPResultProviderOutcome(source: outcome.source, context: MCPResultContext(tool: context.tool,+ semanticFailure: context.semanticFailure, mutationRecovery: context.mutationRecovery,+ entityPositions: context.entityPositions + positions))+ }++ private static func portfolioPositions(_ value: MCPJSONValue, checkpoint: @Sendable () throws -> Void) throws+ -> [MCPResultEntityPosition] {+ guard case .array(let projects) = try MCPResultInspection.member("projects", in: value,+ checkpoint: checkpoint) else { return [] }+ return try projects.indices.map { index in+ try checkpoint()+ return .init(entityType: .project, sourcePath: "/projects/\(index)")+ }+ }++ private static func scanPositions(_ value: MCPJSONValue, checkpoint: @Sendable () throws -> Void) throws+ -> [MCPResultEntityPosition] {+ guard case .array(let groups) = try MCPResultInspection.member("tasks", in: value,+ checkpoint: checkpoint) else { return [] }+ var positions: [MCPResultEntityPosition] = []+ for (index, group) in groups.enumerated() {+ try checkpoint()+ if case .array(let records) = try MCPResultInspection.member("records", in: group,+ checkpoint: checkpoint) {+ for record in records.indices {+ try checkpoint()+ positions.append(.init(entityType: .task,+ sourcePath: "/tasks/\(index)/records/\(record)/id"))+ }+ }+ }+ return positions+ }++ private static func reassignmentPositions(_ value: MCPJSONValue, checkpoint: @Sendable () throws -> Void) throws+ -> [MCPResultEntityPosition] {+ guard case .array(let groups) = try MCPResultInspection.member("groups", in: value,+ checkpoint: checkpoint) else { return [] }+ var positions: [MCPResultEntityPosition] = []+ for (index, group) in groups.enumerated() {+ try checkpoint()+ guard MCPResultInspection.string(try MCPResultInspection.member("type", in: group,+ checkpoint: checkpoint)) == "task" else { continue }+ positions.append(.init(entityType: .task, sourcePath: "/groups/\(index)/winner/id"))+ if case .array(let records) = try MCPResultInspection.member("reassignments", in: group,+ checkpoint: checkpoint) {+ for record in records.indices {+ try checkpoint()+ positions.append(.init(entityType: .task,+ sourcePath: "/groups/\(index)/reassignments/\(record)/id"))+ }+ }+ }+ return positions+ }+}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPResultAdapter.swift b/Transit/Transit/MCP/Results/MCPResultAdapter.swiftnew file mode 100644index 0000000..13b1f64--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPResultAdapter.swift@@ -0,0 +1,45 @@+#if os(macOS)+import Foundation++nonisolated struct MCPUnavailableLink: Sendable {+ let entityType: MCPResultEntityType+ let entityId: UUID+ let sourcePath: String+ let availability = "unavailable"+ let reason = "navigation_not_supported"+}++nonisolated struct MCPResultPresentation: Sendable {+ let evidence: MCPResultEvidence+ let links: [MCPUnavailableLink]+ let errorCategory: MCPResultErrorCategory?+ let recovery: MCPResultRecovery?+}++nonisolated enum MCPResultAdapter {+ static func source(+ text: String,+ isError: Bool?,+ origin: MCPResultOrigin,+ evidence: MCPResultEvidence,+ checkpoint: @escaping @Sendable () throws -> Void = {}+ ) throws -> MCPResultSource {+ try MCPResultSource.make(text: text, isError: isError, origin: origin,+ evidence: evidence, checkpoint: checkpoint)+ }++ /// Source-only presentation; worker checkpoints preserve the original budget.+ static func present(+ _ source: MCPResultSource,+ context: MCPResultContext,+ checkpoint: @escaping @Sendable () throws -> Void = {}+ ) throws -> MCPResultPresentation {+ try checkpoint()+ let classification = try MCPResultClassification.inspect(source, context: context, checkpoint: checkpoint)+ let links = try MCPResultLinks.build(source, context: context, checkpoint: checkpoint)+ try checkpoint()+ return MCPResultPresentation(evidence: classification.evidence, links: links,+ errorCategory: classification.category, recovery: classification.recovery)+ }+}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPResultByteWriter.swift b/Transit/Transit/MCP/Results/MCPResultByteWriter.swiftnew file mode 100644index 0000000..7707ff5--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPResultByteWriter.swift@@ -0,0 +1,55 @@+#if os(macOS)+import Foundation++/// Worker-local writer. Only validated document/fragment factories insert raw JSON.+/// The callback is discarded with this writer; returned bytes contain no closures.+nonisolated struct MCPResultByteWriter {+ private(set) var data = Data()+ private static let hex = Array("0123456789abcdef".utf8)+ private let checkpoint: @Sendable () throws -> Void++ init(checkpoint: @escaping @Sendable () throws -> Void) {+ self.checkpoint = checkpoint+ }++ mutating func literal(_ text: String) throws {+ try raw(Data(text.utf8))+ }++ mutating func raw(_ bytes: Data) throws {+ try checkpoint()+ var start = bytes.startIndex+ while start < bytes.endIndex {+ let end = bytes.index(start, offsetBy: min(4_096, bytes.distance(from: start, to: bytes.endIndex)))+ data.append(contentsOf: bytes[start..<end])+ start = end+ try checkpoint()+ }+ }++ mutating func string(_ text: String) throws {+ try checkpoint()+ data.append(34)+ for (index, byte) in text.utf8.enumerated() {+ if index.isMultiple(of: 256) { try checkpoint() }+ switch byte {+ case 34: data.append(contentsOf: [92, 34])+ case 92: data.append(contentsOf: [92, 92])+ case 0...31:+ data.append(contentsOf: [92, 117, 48, 48, Self.hex[Int(byte >> 4)], Self.hex[Int(byte & 15)]])+ default: data.append(byte)+ }+ }+ data.append(34)+ try checkpoint()+ }++ mutating func field(_ name: String, _ value: String, first: Bool = false) throws {+ if !first { try literal(",") }+ try string(name)+ try literal(":")+ try string(value)+ }++}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPResultClassification.swift b/Transit/Transit/MCP/Results/MCPResultClassification.swiftnew file mode 100644index 0000000..17c0324--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPResultClassification.swift@@ -0,0 +1,107 @@+#if os(macOS)+import Foundation++/// Supplemental classification never changes acceptance or retry facts in source.+nonisolated struct MCPResultClassification {+ let evidence: MCPResultEvidence+ let category: MCPResultErrorCategory?+ let recovery: MCPResultRecovery?++ static func inspect(_ source: MCPResultSource, context: MCPResultContext,+ checkpoint: @Sendable () throws -> Void) throws -> MCPResultClassification {+ let value = source.document?.value+ let error = try MCPResultInspection.member("error", in: value, checkpoint: checkpoint)+ let code = MCPResultInspection.string(try MCPResultInspection.member("code", in: error, checkpoint: checkpoint))+ let outcome = MCPResultInspection.string(+ try MCPResultInspection.member("outcome", in: value, checkpoint: checkpoint))+ let retry = MCPResultInspection.string(+ try MCPResultInspection.member("retryAction", in: value, checkpoint: checkpoint))+ let accepted = MCPResultInspection.boolean(+ try MCPResultInspection.member("accepted", in: value, checkpoint: checkpoint))+ let contradictory = contradicts(outcome: outcome, accepted: accepted,+ retry: retry, isError: source.originalIsError)+ let unsupportedOutcome = outcome.map { !["committed", "rejected", "in_progress", "uncertain"].contains($0) }+ ?? false+ let evidence: MCPResultEvidence = contradictory || unsupportedOutcome ? .unestablished : source.evidence+ var category = context.semanticFailure?.category ?? code.flatMap { categories[$0] }+ if category == nil, source.originalIsError == true || code != nil { category = .unclassifiedHistorical }+ if evidence == .unestablished {+ category = context.mutationRecovery == nil ? .unclassifiedHistorical : .outcomeUncertain+ }+ if outcome == "uncertain" { category = .outcomeUncertain }+ if context.mutationRecovery != nil, category == .serializationFailure { category = .outcomeUncertain }+ let savedRetry = MCPResultSavedRetryEvidence(code: code, outcome: outcome, retryAction: retry)+ let recovery = recovery(category: category, evidence: evidence, saved: savedRetry,+ mutation: context.mutationRecovery)+ return MCPResultClassification(evidence: evidence, category: category, recovery: recovery)+ }++ /// Consistency of already reported facts, not a receipt acceptance validator.+ private static func contradicts(outcome: String?, accepted: Bool?, retry: String?, isError: Bool?) -> Bool {+ switch outcome {+ case "committed": return accepted == false || isError == true || retry == "new_request_new_key"+ case "in_progress": return accepted == false || retry == "new_request_new_key"+ case "uncertain": return retry == "new_request_new_key"+ case "rejected": return retry == "reconcile"+ default: return false+ }+ }++ private static func recovery(category: MCPResultErrorCategory?, evidence: MCPResultEvidence,+ saved: MCPResultSavedRetryEvidence, mutation: MCPMutationRecoveryContext?)+ -> MCPResultRecovery? {+ guard let category else { return nil }+ if let mutation {+ let knownInternalRejection = saved.outcome == "rejected" &&+ ["INTERNAL_ERROR", "INTERRUPTED_BEFORE_COMMIT"].contains(saved.code ?? "")+ let unknownCode = saved.code.map { categories[$0] == nil } ?? false+ let uncertain = evidence == .unestablished || category == .outcomeUncertain ||+ category == .unclassifiedHistorical || unknownCode ||+ (category == .internalFailure && !knownInternalRejection)+ let sourceRetry = saved.outcome == "rejected" && saved.retryAction == "new_request_new_key" ||+ ["rejected", "in_progress"].contains(saved.outcome ?? "") && saved.retryAction == "retry_same_request"+ if case .protectedWrite = mutation, !uncertain, sourceRetry {+ return MCPResultRecovery(direction: .followSource, mutation: mutation)+ }+ if case .unprotectedMaintenance = mutation {+ return MCPResultRecovery(direction: .reconcileMaintenance, mutation: mutation)+ }+ return MCPResultRecovery(direction: .reconcileOriginalWrite, mutation: mutation)+ }+ switch category {+ case .invalidCursor, .expiredCursor:+ return MCPResultRecovery(direction: .restartRead, mutation: nil)+ case .storageFailure, .incoherentCapture, .admissionBusy, .deadlineExceeded,+ .retentionCapacity, .serializationFailure:+ return MCPResultRecovery(direction: .retryIdenticalRead, mutation: nil)+ default: return nil+ }+ }++ static func category(for code: String) -> MCPResultErrorCategory? { categories[code] }++ private static let categories: [String: MCPResultErrorCategory] = [+ "INVALID_INPUT": .invalidInput, "INVALID_STATUS": .invalidInput, "INVALID_TYPE": .invalidInput,+ "INVALID_PRIORITY": .invalidInput, "MILESTONE_PROJECT_MISMATCH": .invalidInput,+ "TASK_NOT_FOUND": .notFound, "PROJECT_NOT_FOUND": .notFound, "MILESTONE_NOT_FOUND": .notFound,+ "AMBIGUOUS_TASK_ID": .ambiguousIdentity, "AMBIGUOUS_PROJECT": .ambiguousIdentity,+ "AMBIGUOUS_MILESTONE": .ambiguousIdentity, "AMBIGUOUS_FILTER": .ambiguousIdentity,+ "DUPLICATE_MILESTONE_NAME": .ambiguousIdentity, "DUPLICATE_PROJECT_NAME": .ambiguousIdentity,+ "DUPLICATE_TASK_IDENTIFIER": .ambiguousIdentity, "MILESTONE_NOT_OPEN": .invalidInput,+ "REVISION_CONFLICT": .revisionConflict, "IDEMPOTENCY_KEY_REUSED": .keyConflict,+ "PERSISTENCE_UNAVAILABLE": .storageFailure, "QUERY_FAILED": .storageFailure,+ "READ_BUSY": .admissionBusy, "QUERY_UNAVAILABLE": .admissionBusy,+ "STORE_BUSY": .admissionBusy, "OPERATION_IN_PROGRESS": .admissionBusy,+ "READ_TIMEOUT": .deadlineExceeded, "QUERY_CAPACITY_EXCEEDED": .retentionCapacity,+ "INVALID_CURSOR": .invalidCursor, "INVALID_SNAPSHOT": .invalidCursor, "QUERY_EXPIRED": .expiredCursor,+ "SNAPSHOT_INCOMPATIBLE": .invalidInput, "IDENTITY_AMBIGUITY": .ambiguousIdentity,+ "OUTCOME_UNCERTAIN": .outcomeUncertain, "INTERNAL_ERROR": .internalFailure,+ "INTERRUPTED_BEFORE_COMMIT": .internalFailure+ ]+}+nonisolated private struct MCPResultSavedRetryEvidence: Sendable {+ let code: String?+ let outcome: String?+ let retryAction: String?+}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPResultEncoder.swift b/Transit/Transit/MCP/Results/MCPResultEncoder.swiftnew file mode 100644index 0000000..cb0a65c--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPResultEncoder.swift@@ -0,0 +1,167 @@+#if os(macOS)+import Foundation++/// Frozen tool-level fragments never retain the originating JSON-RPC ID.+nonisolated struct MCPResultToolFragment: Sendable {+ let encodedResult: Data++ fileprivate init(encodedResult: Data) {+ self.encodedResult = encodedResult+ }+}++/// Encoder boundaries return complete immutable response bytes, not closures.+nonisolated enum MCPResultEncoder {+ static func encode(+ source: MCPResultSource,+ presentation: MCPResultPresentation,+ id: JSONRPCId,+ metadata: MCPResultMetadata?,+ checkpoint: @escaping @Sendable () throws -> Void = {}+ ) throws -> Data {+ let fragment = try freeze(source: source, presentation: presentation, metadata: metadata,+ checkpoint: checkpoint)+ return try encode(fragment: fragment, id: id, checkpoint: checkpoint)+ }++ /// Providers own the compact logical failure. No effects or delivery selection occur here.+ static func prepareMutationFallback(+ id: JSONRPCId,+ source: MCPResultSource,+ context: MCPResultContext,+ metadata: MCPResultMetadata?,+ checkpoint: @escaping @Sendable () throws -> Void = {}+ ) throws -> Data {+ try checkpoint()+ guard let mutation = context.mutationRecovery else { throw MCPResultBoundaryError.unsupportedEvidence }+ let direction: MCPResultRecoveryDirection+ if case .unprotectedMaintenance = mutation {+ direction = .reconcileMaintenance+ } else {+ direction = .reconcileOriginalWrite+ }+ let presentation = MCPResultPresentation(evidence: .unestablished, links: [], errorCategory: .outcomeUncertain,+ recovery: MCPResultRecovery(direction: direction, mutation: mutation))+ var writer = MCPResultByteWriter(checkpoint: checkpoint)+ try writeTool(source: source, presentation: presentation, metadata: metadata,+ omitBatchItemId: true, to: &writer)+ let fragment = MCPResultToolFragment(encodedResult: writer.data)+ return try encode(fragment: fragment, id: id, checkpoint: checkpoint)+ }++ static func freeze(+ source: MCPResultSource,+ presentation: MCPResultPresentation,+ metadata: MCPResultMetadata?,+ checkpoint: @escaping @Sendable () throws -> Void = {}+ ) throws -> MCPResultToolFragment {+ try checkpoint()+ var writer = MCPResultByteWriter(checkpoint: checkpoint)+ try writeTool(source: source, presentation: presentation, metadata: metadata,+ omitBatchItemId: false, to: &writer)+ try checkpoint()+ return MCPResultToolFragment(encodedResult: writer.data)+ }++ static func encode(+ fragment: MCPResultToolFragment,+ id: JSONRPCId,+ checkpoint: @escaping @Sendable () throws -> Void = {}+ ) throws -> Data {+ try checkpoint()+ var writer = MCPResultByteWriter(checkpoint: checkpoint)+ try writer.literal("{\"jsonrpc\":\"2.0\",\"id\":")+ switch id {+ case .string(let value): try writer.string(value)+ case .integer(let value): try writer.literal(String(value))+ }+ try writer.literal(",\"result\":")+ try writer.raw(fragment.encodedResult)+ try writer.literal("}")+ try checkpoint()+ return writer.data+ }++ private static func writeTool(source: MCPResultSource, presentation: MCPResultPresentation,+ metadata: MCPResultMetadata?, omitBatchItemId: Bool,+ to writer: inout MCPResultByteWriter) throws {+ try writer.literal("{\"resultType\":\"complete\",\"content\":[{\"type\":\"text\",\"text\":")+ try writer.string(source.originalText)+ try writer.literal("}],\"structuredContent\":{\"contractVersion\":1,\"source\":{\"kind\":")+ try writer.string(source.kind.rawValue)+ switch source.kind {+ case .json:+ guard let document = source.document else { throw MCPResultBoundaryError.unsupportedEvidence }+ try writer.literal(",\"payload\":")+ try writer.raw(document.originalUTF8)+ case .text:+ try writer.literal(",\"payload\":")+ try writer.string(source.originalText)+ case .unreadable: break+ }+ try writer.literal("},\"presentation\":")+ try writePresentation(presentation, omitBatchItemId: omitBatchItemId, to: &writer)+ try writer.literal("}")+ if let isError = source.originalIsError {+ try writer.literal(isError ? ",\"isError\":true" : ",\"isError\":false")+ }+ if let metadata {+ try writer.literal(",\"_meta\":")+ try writer.raw(metadata.document.originalUTF8)+ }+ try writer.literal("}")+ }++ private static func writePresentation(_ value: MCPResultPresentation, omitBatchItemId: Bool,+ to writer: inout MCPResultByteWriter) throws {+ try writer.literal("{")+ try writer.field("evidence", value.evidence.rawValue, first: true)+ try writer.literal(",\"links\":[")+ for (index, link) in value.links.enumerated() {+ if index > 0 { try writer.literal(",") }+ try writer.literal("{")+ try writer.field("entityType", link.entityType.rawValue, first: true)+ try writer.field("entityId", link.entityId.uuidString)+ try writer.field("sourcePath", link.sourcePath)+ try writer.field("availability", link.availability)+ try writer.field("reason", link.reason)+ try writer.literal("}")+ }+ try writer.literal("]")+ if let category = value.errorCategory { try writer.field("errorCategory", category.rawValue) }+ if let recovery = value.recovery {+ try writer.literal(",\"recovery\":")+ try writeRecovery(recovery, omitBatchItemId: omitBatchItemId, to: &writer)+ }+ try writer.literal("}")+ }++ private static func writeRecovery(_ recovery: MCPResultRecovery, omitBatchItemId: Bool,+ to writer: inout MCPResultByteWriter) throws {+ try writer.literal("{")+ try writer.field("direction", recovery.direction.rawValue, first: true)+ switch recovery.mutation {+ case .protectedWrite(let key):+ try writer.field("tool", key.tool)+ try writer.field("idempotencyKey", key.idempotencyKey)+ case .unprotectedMaintenance(let tool): try writer.field("tool", tool)+ case .applicationBatch(let items):+ try writer.literal(",\"items\":[")+ for (index, item) in items.enumerated() {+ if index > 0 { try writer.literal(",") }+ try writer.literal("{\"index\":")+ try writer.literal(String(item.index))+ try writer.field("operation", item.operation)+ try writer.field("tool", item.originalKey.tool)+ try writer.field("idempotencyKey", item.originalKey.idempotencyKey)+ if let taskId = item.targetTaskId { try writer.field("targetTaskId", taskId.uuidString) }+ if !omitBatchItemId, let itemId = item.itemId { try writer.field("itemId", itemId) }+ try writer.literal("}")+ }+ try writer.literal("]")+ case nil: break+ }+ try writer.literal("}")+ }+}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPResultInspection.swift b/Transit/Transit/MCP/Results/MCPResultInspection.swiftnew file mode 100644index 0000000..4a93fdc--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPResultInspection.swift@@ -0,0 +1,84 @@+#if os(macOS)+import Foundation++/// Inspected names use decoded scalar identity, never String canonical equivalence.+nonisolated enum MCPResultInspection {+ static func member(_ name: String, in value: MCPJSONValue?,+ checkpoint: @Sendable () throws -> Void) throws -> MCPJSONValue? {+ guard case .object(let members) = value else { return nil }+ for (index, member) in members.enumerated() {+ if index.isMultiple(of: 64) { try checkpoint() }+ if member.name.unicodeScalars.elementsEqual(name.unicodeScalars) { return member.value }+ }+ return nil+ }++ static func string(_ value: MCPJSONValue?) -> String? {+ guard case .string(let string) = value else { return nil }+ return string+ }++ static func boolean(_ value: MCPJSONValue?) -> Bool? {+ guard case .boolean(let boolean) = value else { return nil }+ return boolean+ }++ static func pointer(_ path: String, in root: MCPJSONValue,+ checkpoint: @Sendable () throws -> Void) throws -> MCPResultPointerMatch? {+ if path.isEmpty { return MCPResultPointerMatch(value: root, order: []) }+ guard path.first == "/" else { return nil }+ var value = root+ var order: [MCPResultPointerOrder] = []+ for part in path.split(separator: "/", omittingEmptySubsequences: false).dropFirst() {+ try checkpoint()+ guard let token = try unescape(String(part), checkpoint: checkpoint) else { return nil }+ switch value {+ case .object:+ guard let next = try member(token, in: value, checkpoint: checkpoint) else { return nil }+ value = next+ order.append(.member(Array(token.utf8)))+ case .array(let values):+ guard validIndex(token), let index = Int(token), values.indices.contains(index) else { return nil }+ value = values[index]+ order.append(.element(index))+ default: return nil+ }+ }+ return MCPResultPointerMatch(value: value, order: order)+ }++ private static func validIndex(_ token: String) -> Bool {+ !token.isEmpty && (token == "0" || token.first != "0") && token.utf8.allSatisfy { (48...57).contains($0) }+ }++ private static func unescape(_ token: String, checkpoint: @Sendable () throws -> Void) throws -> String? {+ let scalars = Array(token.unicodeScalars)+ var output = String.UnicodeScalarView()+ var index = 0+ while index < scalars.count {+ if index.isMultiple(of: 64) { try checkpoint() }+ let scalar = scalars[index]+ index += 1+ if scalar.value != 0x7E { output.append(scalar); continue }+ guard index < scalars.count else { return nil }+ switch scalars[index].value {+ case 0x30: output.append("~")+ case 0x31: output.append("/")+ default: return nil+ }+ index += 1+ }+ return String(output)+ }+}++nonisolated struct MCPResultPointerMatch {+ let value: MCPJSONValue+ let order: [MCPResultPointerOrder]+}++nonisolated enum MCPResultPointerOrder: Equatable {+ case member([UInt8])+ case element(Int)+}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPResultLinks.swift b/Transit/Transit/MCP/Results/MCPResultLinks.swiftnew file mode 100644index 0000000..2fe2271--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPResultLinks.swift@@ -0,0 +1,145 @@+#if os(macOS)+import Foundation++/// Positions are explicit public shapes; no recursive search through unknown data.+nonisolated enum MCPResultLinks {+ static func build(_ source: MCPResultSource, context: MCPResultContext,+ checkpoint: @Sendable () throws -> Void) throws -> [MCPUnavailableLink] {+ guard let document = source.document else { return [] }+ var positions = try builtins(tool: context.tool, value: document.value, checkpoint: checkpoint)+ positions.append(contentsOf: context.entityPositions)+ var candidates: [MCPResultLinkCandidate] = []+ var seen: Set<MCPResultLinkKey> = []+ for (index, position) in positions.enumerated() {+ if index.isMultiple(of: 64) { try checkpoint() }+ guard let match = try MCPResultInspection.pointer(position.sourcePath, in: document.value,+ checkpoint: checkpoint),+ let identity = try identity(match.value, type: position.entityType, checkpoint: checkpoint) else {+ continue+ }+ let key = MCPResultLinkKey(path: Array(position.sourcePath.utf8),+ type: position.entityType.rawValue, identity: identity)+ guard seen.insert(key).inserted else { continue }+ let link = MCPUnavailableLink(entityType: position.entityType, entityId: identity,+ sourcePath: position.sourcePath)+ candidates.append(MCPResultLinkCandidate(link: link, order: match.order))+ }+ try checkpoint()+ var comparisons = 0+ try candidates.sort { left, right in+ if comparisons.isMultiple(of: 64) { try checkpoint() }+ comparisons += 1+ return precedes(left, right)+ }+ try checkpoint()+ return candidates.map(\.link)+ }++ private static func identity(_ value: MCPJSONValue, type: MCPResultEntityType,+ checkpoint: @Sendable () throws -> Void) throws -> UUID? {+ let token: String?+ if case .string(let direct) = value {+ token = direct+ } else {+ let field = type == .task ? "taskId" : "projectId"+ token = MCPResultInspection.string(try MCPResultInspection.member(field, in: value, checkpoint: checkpoint))+ }+ return token.flatMap(UUID.init(uuidString:))+ }++ private static func builtins(tool: String, value: MCPJSONValue,+ checkpoint: @Sendable () throws -> Void) throws -> [MCPResultEntityPosition] {+ switch tool {+ case "query_tasks": return try taskQueryPositions(value, checkpoint: checkpoint)+ case "get_projects":+ return try projectArrayPositions(value, suffix: "", checkpoint: checkpoint)+ case "query_milestones":+ return try projectArrayPositions(value, suffix: "/projectId", checkpoint: checkpoint)+ case "create_task", "update_task", "update_task_status":+ return ["/record", "/currentRecord", "/recordBeforeDeletion"].flatMap(taskPositions)+ case "create_project":+ return ["/record", "/currentRecord", "/recordBeforeDeletion"].map {+ .init(entityType: .project, sourcePath: $0)+ }+ case "add_comment": return [.init(entityType: .task, sourcePath: "/record/taskId")]+ case "create_milestone", "update_milestone", "delete_milestone":+ return ["/record", "/currentRecord", "/recordBeforeDeletion"].map {+ .init(entityType: .project, sourcePath: $0 + "/projectId")+ }+ default: return []+ }+ }++ private static func projectArrayPositions(_ value: MCPJSONValue, suffix: String,+ checkpoint: @Sendable () throws -> Void) throws+ -> [MCPResultEntityPosition] {+ guard case .array(let records) = value else { return [] }+ var positions: [MCPResultEntityPosition] = []+ for index in records.indices {+ // Check before allocating the next chunk of positions, including the first.+ if index.isMultiple(of: 64) { try checkpoint() }+ positions.append(.init(entityType: .project, sourcePath: "/\(index)" + suffix))+ }+ return positions+ }++ private static func taskQueryPositions(_ value: MCPJSONValue,+ checkpoint: @Sendable () throws -> Void) throws+ -> [MCPResultEntityPosition] {+ let records: [MCPJSONValue]+ let prefix: String+ if case .array(let rootRecords) = value {+ records = rootRecords+ prefix = ""+ } else if case .array(let pageRecords) = try MCPResultInspection.member("results", in: value,+ checkpoint: checkpoint) {+ records = pageRecords+ prefix = "/results"+ } else { return [] }+ var positions: [MCPResultEntityPosition] = []+ for (index, record) in records.enumerated() {+ if index.isMultiple(of: 64) { try checkpoint() }+ let path = prefix + "/\(index)"+ let task = try MCPResultInspection.member("task", in: record, checkpoint: checkpoint)+ let requested = try MCPResultInspection.member("requested", in: record, checkpoint: checkpoint)+ if task != nil {+ positions.append(contentsOf: taskPositions(path + "/task"))+ } else if requested == nil {+ positions.append(contentsOf: taskPositions(path))+ }+ }+ return positions+ }++ private static func taskPositions(_ path: String) -> [MCPResultEntityPosition] {+ [.init(entityType: .task, sourcePath: path), .init(entityType: .project, sourcePath: path + "/projectId")]+ }++ private static func precedes(_ lhs: MCPResultLinkCandidate, _ rhs: MCPResultLinkCandidate) -> Bool {+ for (left, right) in zip(lhs.order, rhs.order) where left != right {+ switch (left, right) {+ case (.member(let first), .member(let second)): return first.lexicographicallyPrecedes(second)+ case (.element(let first), .element(let second)): return first < second+ case (.member, .element): return true+ case (.element, .member): return false+ }+ }+ if lhs.order.count != rhs.order.count { return lhs.order.count < rhs.order.count }+ if lhs.link.entityType != rhs.link.entityType {+ return lhs.link.entityType.rawValue < rhs.link.entityType.rawValue+ }+ return lhs.link.entityId.uuidString < rhs.link.entityId.uuidString+ }+}++nonisolated private struct MCPResultLinkCandidate {+ let link: MCPUnavailableLink+ let order: [MCPResultPointerOrder]+}++nonisolated private struct MCPResultLinkKey: Hashable {+ let path: [UInt8]+ let type: String+ let identity: UUID+}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPResultPreparation.swift b/Transit/Transit/MCP/Results/MCPResultPreparation.swiftnew file mode 100644index 0000000..774e111--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPResultPreparation.swift@@ -0,0 +1,148 @@+#if os(macOS)+import Foundation++/// Value preparation only. This seam neither reserves capacity nor publishes roots.+/// Logical backing charges are not allocator capacity, RSS or a process peak bound.+nonisolated enum MCPResultPreparationError: Error, Sendable, Equatable {+ case notImplemented, invalidAccounting, arithmeticOverflow, retentionCapacity+}++nonisolated enum MCPResultRetentionStore: Sendable, CaseIterable {+ case ordinary, reusable+}++nonisolated struct MCPResultRetentionBudget: Sendable {+ static let limitBytes = 16 * 1_024 * 1_024+ let store: MCPResultRetentionStore+ /// Original capture/index plus separately retained legacy compatibility backing.+ /// Excludes text/documents/fragments/metadata already measured from prepared owners.+ let originalCaptureIndexBytes: Int+ /// Observations of this store only; the publication owner revalidates races later.+ let visibleBytes: Int+ let pendingBytes: Int+}++/// Factories own reference identities. Equal bytes never establish shared ownership.+nonisolated final class MCPResultPreparedMetadata: Sendable {+ let value: MCPResultMetadata+ fileprivate init(value: MCPResultMetadata) { self.value = value }+}++nonisolated final class MCPResultPreparedPage: Sendable {+ let source: MCPResultSource+ let presentation: MCPResultPresentation+ let fragment: MCPResultToolFragment+ let metadataOwner: MCPResultPreparedMetadata?++ fileprivate init(source: MCPResultSource, presentation: MCPResultPresentation,+ fragment: MCPResultToolFragment, metadataOwner: MCPResultPreparedMetadata?) {+ self.source = source+ self.presentation = presentation+ self.fragment = fragment+ self.metadataOwner = metadataOwner+ }+}++nonisolated struct MCPResultPagePreparationRequest: Sendable {+ let text: String+ let isError: Bool?+ let origin: MCPResultOrigin+ let evidence: MCPResultEvidence+ let context: MCPResultContext+ let metadataOwner: MCPResultPreparedMetadata?+}++/// Normative retained components, measured once per actual immutable owner.+/// Tree root handles embedded in source/metadata are not charged again. Dynamic+/// case payloads include array handles/element slots, object member slots, decoded+/// UTF8 keys/strings and number lexemes. Presentation includes dynamic link/recovery+/// storage and strings. Distinct owners conservatively count despite hidden COW.+nonisolated struct MCPResultRetainedCharge: Sendable {+ let originalCaptureIndexBytes: Int+ let originalTextBytes: Int+ let sourceDocumentBytes: Int+ let sourceValueBytes: Int+ let presentationValueBytes: Int+ let fragmentBytes: Int+ let metadataDocumentBytes: Int+ let metadataValueBytes: Int+ /// Bundle array handle/every reference slot; each unique page's metadata+ /// pointer. Embedded source/presentation/fragment headers are charged above.+ let ownerReferenceBytes: Int+ let totalBytes: Int+ fileprivate init(originalCaptureIndexBytes: Int, originalTextBytes: Int,+ sourceDocumentBytes: Int, sourceValueBytes: Int, presentationValueBytes: Int,+ fragmentBytes: Int, metadataDocumentBytes: Int, metadataValueBytes: Int,+ ownerReferenceBytes: Int, totalBytes: Int) {+ self.originalCaptureIndexBytes = originalCaptureIndexBytes+ self.originalTextBytes = originalTextBytes+ self.sourceDocumentBytes = sourceDocumentBytes+ self.sourceValueBytes = sourceValueBytes+ self.presentationValueBytes = presentationValueBytes+ self.fragmentBytes = fragmentBytes+ self.metadataDocumentBytes = metadataDocumentBytes+ self.metadataValueBytes = metadataValueBytes+ self.ownerReferenceBytes = ownerReferenceBytes+ self.totalBytes = totalBytes+ }+}++nonisolated struct MCPResultRetainedBundle: Sendable {+ let pages: [MCPResultPreparedPage]+ let charge: MCPResultRetainedCharge+ fileprivate init(pages: [MCPResultPreparedPage], charge: MCPResultRetainedCharge) {+ self.pages = pages+ self.charge = charge+ }+}++/// Synchronous immutable preparation. Original checkpoints are used but never retained.+nonisolated enum MCPResultPreparation {+ static func metadata(value: MCPResultMetadata) throws -> MCPResultPreparedMetadata {+ MCPResultPreparedMetadata(value: value)+ }++ static func page(request: MCPResultPagePreparationRequest,+ checkpoint: @escaping @Sendable () throws -> Void = {}) throws -> MCPResultPreparedPage {+ try checkpoint()+ let source = try MCPResultAdapter.source(text: request.text, isError: request.isError,+ origin: request.origin, evidence: request.evidence, checkpoint: checkpoint)+ return try page(source: source, context: request.context,+ metadataOwner: request.metadataOwner, checkpoint: checkpoint)+ }++ /// Reuses a validated immutable source; provider position selection never reparses it.+ static func page(source: MCPResultSource, context: MCPResultContext,+ metadataOwner: MCPResultPreparedMetadata?,+ checkpoint: @escaping @Sendable () throws -> Void = {}) throws -> MCPResultPreparedPage {+ try checkpoint()+ let presentation = try MCPResultAdapter.present(source, context: context, checkpoint: checkpoint)+ let fragment = try MCPResultEncoder.freeze(source: source, presentation: presentation,+ metadata: metadataOwner?.value, checkpoint: checkpoint)+ try checkpoint()+ return MCPResultPreparedPage(source: source, presentation: presentation, fragment: fragment,+ metadataOwner: metadataOwner)+ }++ static func prepare(pages: [MCPResultPreparedPage], budget: MCPResultRetentionBudget,+ checkpoint: @escaping @Sendable () throws -> Void = {}) throws -> MCPResultRetainedBundle {+ try checkpoint()+ let observed = [budget.originalCaptureIndexBytes, budget.visibleBytes, budget.pendingBytes]+ guard observed.allSatisfy({ $0 >= 0 }) else { throw MCPResultPreparationError.invalidAccounting }+ var ledger = MCPResultRetentionAccounting(checkpoint: checkpoint)+ try ledger.measure(pages)+ let total = try ledger.total(originalCaptureIndexBytes: budget.originalCaptureIndexBytes)+ let used = try MCPResultRetentionAccounting.add(+ MCPResultRetentionAccounting.add(budget.visibleBytes, budget.pendingBytes), total)+ guard used <= MCPResultRetentionBudget.limitBytes else { throw MCPResultPreparationError.retentionCapacity }+ try checkpoint()+ let charge = MCPResultRetainedCharge(originalCaptureIndexBytes: budget.originalCaptureIndexBytes,+ originalTextBytes: ledger.originalTextBytes, sourceDocumentBytes: ledger.sourceDocumentBytes,+ sourceValueBytes: ledger.sourceValueBytes, presentationValueBytes: ledger.presentationValueBytes,+ fragmentBytes: ledger.fragmentBytes, metadataDocumentBytes: ledger.metadataDocumentBytes,+ metadataValueBytes: ledger.metadataValueBytes, ownerReferenceBytes: ledger.ownerReferenceBytes,+ totalBytes: total)+ return MCPResultRetainedBundle(pages: pages, charge: charge)+ }+}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPResultProviderAdapters.swift b/Transit/Transit/MCP/Results/MCPResultProviderAdapters.swiftnew file mode 100644index 0000000..179eec1--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPResultProviderAdapters.swift@@ -0,0 +1,65 @@+#if os(macOS)+import Foundation++/// Declarations made where a provider produces its result, not inferred from parsing failure.+/// These values are never encoded into original logical JSON or persisted receipts.+nonisolated struct MCPResultProviderEvidence: Sendable {+ let origin: MCPResultOrigin+ let evidence: MCPResultEvidence+ let failure: MCPResultFailure?+ let requiresPreparedReconciliation: Bool++ init(origin: MCPResultOrigin, evidence: MCPResultEvidence = .established,+ failure: MCPResultFailure? = nil, requiresPreparedReconciliation: Bool = false) {+ self.origin = origin+ self.evidence = evidence+ self.failure = failure+ self.requiresPreparedReconciliation = requiresPreparedReconciliation+ }+}++/// Value-only provider adaptation. This layer does not read storage or decide acceptance.+nonisolated enum MCPResultProviderAdapters {+ static func outcome(+ result: MCPToolResult,+ context: MCPResultContext,+ origin: MCPResultOrigin,+ checkpoint: @escaping @Sendable () throws -> Void = {}+ ) throws -> MCPResultProviderOutcome {+ try checkpoint()+ let declaration = result.providerEvidence+ guard declaration?.requiresPreparedReconciliation != true,+ result.content.count == 1, let content = result.content.first, content.type == "text" else {+ throw MCPResultBoundaryError.unsupportedEvidence+ }+ let source = try MCPResultAdapter.source(text: content.text, isError: result.isError,+ origin: declaration?.origin ?? origin, evidence: declaration?.evidence ?? .established,+ checkpoint: checkpoint)+ let effective = MCPResultContext(tool: context.tool,+ semanticFailure: declaration?.failure ?? context.semanticFailure,+ mutationRecovery: context.mutationRecovery, entityPositions: context.entityPositions)+ return MCPResultProviderOutcome(source: source, context: effective)+ }++ /// Frozen capture metadata remains an opaque value in its existing namespace.+ static func metadata(+ result: MCPToolResult,+ frozenReadBytes: Data? = nil,+ checkpoint: @escaping @Sendable () throws -> Void = {}+ ) throws -> MCPResultMetadata? {+ try checkpoint()+ let bytes: Data+ if let frozenReadBytes {+ var wrapper = MCPResultByteWriter(checkpoint: checkpoint)+ try wrapper.literal("{\"me.nore.ig.transit/read\":")+ try wrapper.raw(frozenReadBytes)+ try wrapper.literal("}")+ bytes = wrapper.data+ } else if let metadata = result.metadata {+ bytes = try JSONEncoder().encode(metadata)+ } else { return nil }+ let document = try MCPJSONDocument.parse(bytes, checkpoint: checkpoint)+ return try MCPResultMetadata.make(document: document, checkpoint: checkpoint)+ }+}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPResultProviderSelection.swift b/Transit/Transit/MCP/Results/MCPResultProviderSelection.swiftnew file mode 100644index 0000000..ccc2212--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPResultProviderSelection.swift@@ -0,0 +1,106 @@+#if os(macOS)+import Foundation++/// Immutable evidence returned by a provider; adaptation never recreates saved outcomes.+nonisolated struct MCPResultProviderOutcome: Sendable {+ let source: MCPResultSource+ let context: MCPResultContext+}++nonisolated enum MCPResultResponseSelection: Sendable {+ case normal(Data)+ case reconciliation(Data)+ /// Delivery suppression says nothing about provider acceptance or commitment.+ case suppressed+}++/// Effect-aware response selection only. Providers retain all transaction/recovery ownership.+nonisolated enum MCPResultProviderSelection {+ typealias PrepareFallback = @Sendable (+ JSONRPCId, MCPResultSource, MCPResultContext, MCPResultMetadata?+ ) throws -> Data+ typealias EncodeOutcome = @Sendable (+ MCPResultProviderOutcome, JSONRPCId, MCPResultMetadata?+ ) throws -> Data++ /// `context` fixes the authentic tool/recovery identities before dispatch. Outcome context+ /// may declare source positions/failure phase, but must not substitute those identities.+ /// `metadata` is authoritative for both responses; its original bytes remain opaque.+ /// Fallback preparation must finish before dispatch. Later failures select ready bytes;+ /// cancellation suppresses delivery independently of effects. No callback is retained.+ static func mutation(+ id: JSONRPCId,+ context: MCPResultContext,+ metadata: MCPResultMetadata?,+ fallbackSource: MCPResultSource,+ prepareFallback: PrepareFallback = prepare,+ encodeOutcome: EncodeOutcome = encode,+ shouldDeliver: @escaping @Sendable () -> Bool = { !Task.isCancelled },+ dispatch: @escaping @Sendable () async throws -> MCPResultProviderOutcome+ ) async throws -> MCPResultResponseSelection {+ guard shouldDeliver() else { return .suppressed }+ let prepared = try prepareFallback(id, fallbackSource, context, metadata)+ guard shouldDeliver() else { return .suppressed }+ do {+ let outcome = try await dispatch()+ guard shouldDeliver() else { return .suppressed }+ guard sameIdentity(context, outcome.context) else {+ throw MCPResultBoundaryError.unsupportedEvidence+ }+ let bytes = try encodeOutcome(outcome, id, metadata)+ return shouldDeliver() ? .normal(bytes) : .suppressed+ } catch {+ return shouldDeliver() ? .reconciliation(prepared) : .suppressed+ }+ }++ /// Compare opaque identities by UTF8, preserving distinct Unicode spellings and item order.+ private static func sameIdentity(_ fixed: MCPResultContext, _ outcome: MCPResultContext) -> Bool {+ guard exact(fixed.tool, outcome.tool) else { return false }+ switch (fixed.mutationRecovery, outcome.mutationRecovery) {+ case (nil, nil): return true+ case (.protectedWrite(let left), .protectedWrite(let right)):+ return sameKey(left, right)+ case (.unprotectedMaintenance(let left), .unprotectedMaintenance(let right)):+ return exact(left, right)+ case (.applicationBatch(let left), .applicationBatch(let right)):+ guard left.count == right.count else { return false }+ return zip(left, right).allSatisfy { first, second in+ first.index == second.index && exact(first.itemId, second.itemId)+ && exact(first.operation, second.operation) && sameKey(first.originalKey, second.originalKey)+ && first.targetTaskId == second.targetTaskId+ }+ default: return false+ }+ }++ private static func sameKey(_ left: MCPProtectedRecoveryKey, _ right: MCPProtectedRecoveryKey) -> Bool {+ exact(left.tool, right.tool) && exact(left.idempotencyKey, right.idempotencyKey)+ }++ private static func exact(_ left: String, _ right: String) -> Bool {+ left.utf8.elementsEqual(right.utf8)+ }++ private static func exact(_ left: String?, _ right: String?) -> Bool {+ switch (left, right) {+ case (nil, nil): return true+ case (.some(let first), .some(let second)): return exact(first, second)+ default: return false+ }+ }++ static func prepare(id: JSONRPCId, source: MCPResultSource, context: MCPResultContext,+ metadata: MCPResultMetadata?) throws -> Data {+ try MCPResultEncoder.prepareMutationFallback(id: id, source: source,+ context: context, metadata: metadata)+ }++ static func encode(outcome: MCPResultProviderOutcome, id: JSONRPCId,+ metadata: MCPResultMetadata?) throws -> Data {+ let presentation = try MCPResultAdapter.present(outcome.source, context: outcome.context)+ return try MCPResultEncoder.encode(source: outcome.source, presentation: presentation,+ id: id, metadata: metadata)+ }+}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPResultRetentionAccounting.swift b/Transit/Transit/MCP/Results/MCPResultRetentionAccounting.swiftnew file mode 100644index 0000000..ea2891a--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPResultRetentionAccounting.swift@@ -0,0 +1,151 @@+#if os(macOS)+import Foundation++/// Private-stage logical accounting. This temporary ledger never reaches a frozen+/// owner and never reserves store capacity. Checkpoints retain original failure types.+nonisolated struct MCPResultRetentionAccounting {+ private let checkpoint: @Sendable () throws -> Void+ private(set) var originalTextBytes = 0+ private(set) var sourceDocumentBytes = 0+ private(set) var sourceValueBytes = 0+ private(set) var presentationValueBytes = 0+ private(set) var fragmentBytes = 0+ private(set) var metadataDocumentBytes = 0+ private(set) var metadataValueBytes = 0+ private(set) var ownerReferenceBytes = 0++ init(checkpoint: @escaping @Sendable () throws -> Void) {+ self.checkpoint = checkpoint+ }++ mutating func measure(_ pages: [MCPResultPreparedPage]) throws {+ try checkpoint()+ ownerReferenceBytes = try Self.add(MemoryLayout<[MCPResultPreparedPage]>.stride,+ Self.slots(pages.count, stride: MemoryLayout<MCPResultPreparedPage>.stride))+ var seenPages: Set<ObjectIdentifier> = []+ var seenMetadata: Set<ObjectIdentifier> = []+ for page in pages {+ try checkpoint()+ guard seenPages.insert(ObjectIdentifier(page)).inserted else { continue }+ ownerReferenceBytes = try Self.add(ownerReferenceBytes, MemoryLayout<MCPResultPreparedMetadata?>.stride)+ originalTextBytes = try Self.add(originalTextBytes, utf8Bytes(page.source.originalText))+ var sourceDynamic = 0+ if let document = page.source.document {+ try checkpoint()+ sourceDocumentBytes = try Self.add(sourceDocumentBytes, document.originalUTF8.count)+ sourceDynamic = try treeDynamicBytes(document.value)+ }+ sourceValueBytes = try Self.add(sourceValueBytes,+ Self.add(MemoryLayout<MCPResultSource>.stride, sourceDynamic))+ presentationValueBytes = try Self.add(presentationValueBytes, presentationBytes(page.presentation))+ try checkpoint()+ fragmentBytes = try Self.add(fragmentBytes,+ Self.add(MemoryLayout<MCPResultToolFragment>.stride, page.fragment.encodedResult.count))+ if let owner = page.metadataOwner, seenMetadata.insert(ObjectIdentifier(owner)).inserted {+ try checkpoint()+ metadataDocumentBytes = try Self.add(metadataDocumentBytes, owner.value.document.originalUTF8.count)+ metadataValueBytes = try Self.add(metadataValueBytes,+ Self.add(MemoryLayout<MCPResultMetadata>.stride, treeDynamicBytes(owner.value.document.value)))+ }+ }+ try checkpoint()+ }++ func total(originalCaptureIndexBytes: Int) throws -> Int {+ var bytes = originalCaptureIndexBytes+ for component in [originalTextBytes, sourceDocumentBytes, sourceValueBytes, presentationValueBytes,+ fragmentBytes, metadataDocumentBytes, metadataValueBytes, ownerReferenceBytes] {+ try checkpoint()+ bytes = try Self.add(bytes, component)+ }+ return bytes+ }++ /// The enclosing source/metadata/member/array slot already contains this enum+ /// handle. Count only its indirect case payload and owned dynamic backing here.+ private func treeDynamicBytes(_ value: MCPJSONValue) throws -> Int {+ try checkpoint()+ switch value {+ case .object(let members):+ var bytes = try Self.add(MemoryLayout<[MCPJSONMember]>.stride,+ Self.slots(members.count, stride: MemoryLayout<MCPJSONMember>.stride))+ for member in members {+ try checkpoint()+ bytes = try Self.add(bytes, utf8Bytes(member.name))+ bytes = try Self.add(bytes, treeDynamicBytes(member.value))+ }+ return bytes+ case .array(let values):+ var bytes = try Self.add(MemoryLayout<[MCPJSONValue]>.stride,+ Self.slots(values.count, stride: MemoryLayout<MCPJSONValue>.stride))+ for value in values {+ try checkpoint()+ bytes = try Self.add(bytes, treeDynamicBytes(value))+ }+ return bytes+ case .string(let text): return try Self.add(MemoryLayout<String>.stride, utf8Bytes(text))+ case .number(let number): return try Self.add(MemoryLayout<MCPJSONNumber>.stride, utf8Bytes(number.lexeme))+ case .boolean: return MemoryLayout<Bool>.stride+ case .null: return 0+ }+ }++ private func presentationBytes(_ value: MCPResultPresentation) throws -> Int {+ try checkpoint()+ var bytes = try Self.add(MemoryLayout<MCPResultPresentation>.stride,+ Self.slots(value.links.count, stride: MemoryLayout<MCPUnavailableLink>.stride))+ for link in value.links {+ try checkpoint()+ for text in [link.sourcePath, link.availability, link.reason] {+ bytes = try Self.add(bytes, utf8Bytes(text))+ }+ }+ // Recovery's enum/optional/array handles are embedded in presentation.+ if let mutation = value.recovery?.mutation {+ switch mutation {+ case .protectedWrite(let key):+ bytes = try Self.add(bytes, utf8Bytes(key.tool))+ bytes = try Self.add(bytes, utf8Bytes(key.idempotencyKey))+ case .unprotectedMaintenance(let tool):+ bytes = try Self.add(bytes, utf8Bytes(tool))+ case .applicationBatch(let items):+ bytes = try Self.add(bytes, Self.slots(items.count, stride: MemoryLayout<MCPBatchRecoveryItem>.stride))+ for item in items {+ try checkpoint()+ for text in [item.operation, item.originalKey.tool, item.originalKey.idempotencyKey] {+ bytes = try Self.add(bytes, utf8Bytes(text))+ }+ if let itemId = item.itemId { bytes = try Self.add(bytes, utf8Bytes(itemId)) }+ }+ }+ }+ return bytes+ }++ /// Traverse instead of an unbounded String.UTF8View.count scan. Callers supply+ /// their original worker budget; this ledger creates no clock or new deadline.+ private func utf8Bytes(_ text: String) throws -> Int {+ var bytes = 0+ for _ in text.utf8 {+ if bytes.isMultiple(of: 256) { try checkpoint() }+ bytes = try Self.add(bytes, 1)+ }+ try checkpoint()+ return bytes+ }++ static func add(_ left: Int, _ right: Int) throws -> Int {+ guard left >= 0, right >= 0 else { throw MCPResultPreparationError.invalidAccounting }+ let (sum, overflow) = left.addingReportingOverflow(right)+ guard !overflow else { throw MCPResultPreparationError.arithmeticOverflow }+ return sum+ }++ private static func slots(_ count: Int, stride: Int) throws -> Int {+ guard count >= 0, stride >= 0 else { throw MCPResultPreparationError.invalidAccounting }+ let (bytes, overflow) = count.multipliedReportingOverflow(by: stride)+ guard !overflow else { throw MCPResultPreparationError.arithmeticOverflow }+ return bytes+ }+}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPResultSchemas.swift b/Transit/Transit/MCP/Results/MCPResultSchemas.swiftnew file mode 100644index 0000000..e46baeb--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPResultSchemas.swift@@ -0,0 +1,133 @@+#if os(macOS)+import Foundation++/// Descriptor data is independent of shared tool-definition registration.+nonisolated struct MCPResultSchemaDescriptor: Sendable {+ let tool: String+ let description: String+ let outputSchema: MCPJSONDocument+}++nonisolated enum MCPResultSchemas {+ static func descriptor(tool: String, description: String) throws -> MCPResultSchemaDescriptor {+ MCPResultSchemaDescriptor(tool: tool, description: description,+ outputSchema: try MCPJSONDocument.parse(schemaJSON))+ }++ /// Only the presentation contract is closed. Historic logical JSON remains+ /// unrestricted, including arbitrary names, nulls and exact numeric tokens.+ /// Provider descriptions document current payload shapes without making+ /// those shapes a restriction on saved outcomes or future batch providers.+ private static let schemaJSON = #"""+ {+ "$schema":"https://json-schema.org/draft/2020-12/schema",+ "title":"Transit structured result contract version 1",+ "description":"Immutable original source and separate presentation; text and isError remain in the tool result.",+ "type":"object",+ "required":["contractVersion","source","presentation"],+ "additionalProperties":false,+ "properties":{+ "contractVersion":{"type":"integer","const":1},+ "source":{"oneOf":[+ {"$ref":"#/$defs/jsonSource"},+ {"$ref":"#/$defs/textSource"},+ {"$ref":"#/$defs/unreadableSource"}+ ]},+ "presentation":{"$ref":"#/$defs/presentation"}+ },+ "if":{"properties":{"source":{"properties":{"kind":{"const":"unreadable"}}}}},+ "then":{"properties":{"presentation":{"properties":{"evidence":{"const":"unestablished"}}}}},+ "$defs":{+ "jsonSource":{+ "type":"object","required":["kind","payload"],"additionalProperties":false,+ "properties":{+ "kind":{"const":"json"},+ "payload":{"description":"Complete original JSON; historical fields and types are unrestricted."}+ }+ },+ "textSource":{+ "type":"object","required":["kind","payload"],"additionalProperties":false,+ "properties":{"kind":{"const":"text"},"payload":{"type":"string"}}+ },+ "unreadableSource":{+ "type":"object","required":["kind"],"additionalProperties":false,+ "properties":{"kind":{"const":"unreadable"}}+ },+ "uuid":{+ "type":"string","format":"uuid",+ "minLength":36,"maxLength":36,+ "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}$"+ },+ "jsonPointer":{+ "type":"string",+ "description":"RFC 6901 pointer to frozen source evidence; empty root or slash-separated escaped tokens.",+ "pattern":"^(?:/(?:[^~/]|~[01])*)*(?![\\s\\S])"+ },+ "link":{+ "type":"object",+ "required":["entityType","entityId","sourcePath","availability","reason"],+ "additionalProperties":false,+ "properties":{+ "entityType":{"type":"string","enum":["task","project"]},+ "entityId":{"$ref":"#/$defs/uuid"},+ "sourcePath":{"$ref":"#/$defs/jsonPointer"},+ "availability":{"const":"unavailable"},+ "reason":{"const":"navigation_not_supported"}+ }+ },+ "presentation":{+ "type":"object","required":["evidence","links"],"additionalProperties":false,+ "properties":{+ "evidence":{"type":"string","enum":["established","unestablished"]},+ "links":{"type":"array","items":{"$ref":"#/$defs/link"}},+ "errorCategory":{"type":"string","enum":[+ "invalid_input","not_found","ambiguous_identity","revision_conflict","key_conflict",+ "storage_failure","incoherent_capture","admission_busy","deadline_exceeded","retention_capacity",+ "invalid_cursor","expired_cursor","serialization_failure","outcome_uncertain",+ "unclassified_historical","internal_failure"+ ]},+ "recovery":{"oneOf":[+ {"$ref":"#/$defs/readRecovery"},+ {"$ref":"#/$defs/protectedRecovery"},+ {"$ref":"#/$defs/batchRecovery"},+ {"$ref":"#/$defs/maintenanceRecovery"}+ ]}+ }+ },+ "readRecovery":{+ "type":"object","required":["direction"],"additionalProperties":false,+ "properties":{"direction":{"type":"string","enum":["retry_identical_read","restart_read"]}}+ },+ "protectedRecovery":{+ "type":"object","required":["direction","tool","idempotencyKey"],"additionalProperties":false,+ "description":"Original protected identity from trusted provider evidence; no newly invented key.",+ "properties":{+ "direction":{"type":"string","enum":["follow_source","reconcile_original_write"]},+ "tool":{"type":"string"},"idempotencyKey":{"type":"string"}+ }+ },+ "batchRecovery":{+ "type":"object","required":["direction","items"],"additionalProperties":false,+ "description":"Ordered original item identities; no aggregate durable key namespace.",+ "properties":{+ "direction":{"const":"reconcile_original_write"},+ "items":{"type":"array","items":{"$ref":"#/$defs/batchRecoveryItem"}}+ }+ },+ "batchRecoveryItem":{+ "type":"object","required":["index","operation","tool","idempotencyKey"],"additionalProperties":false,+ "properties":{+ "index":{"type":"integer","minimum":0},+ "operation":{"type":"string"},"tool":{"type":"string"},"idempotencyKey":{"type":"string"},+ "itemId":{"type":"string"},"targetTaskId":{"$ref":"#/$defs/uuid"}+ }+ },+ "maintenanceRecovery":{+ "type":"object","required":["direction","tool"],"additionalProperties":false,+ "properties":{"direction":{"const":"reconcile_maintenance"},"tool":{"type":"string"}}+ }+ }+ }+ """#+}+#endif
diff --git a/Transit/Transit/MCP/Results/MCPResultSource.swift b/Transit/Transit/MCP/Results/MCPResultSource.swiftnew file mode 100644index 0000000..1989c36--- /dev/null+++ b/Transit/Transit/MCP/Results/MCPResultSource.swift@@ -0,0 +1,223 @@+#if os(macOS)+import Foundation++nonisolated enum MCPResultSourceKind: String, Sendable {+ case json, text, unreadable+}++nonisolated enum MCPResultEvidence: String, Sendable {+ case established, unestablished+}++/// Providers declare origin; a parse failure never guesses plain-text intent.+nonisolated enum MCPResultOrigin: Sendable {+ case generatedJSON+ case retainedJSON+ case plainText+}++nonisolated struct MCPResultSource: Sendable {+ let originalText: String+ let originalIsError: Bool?+ let document: MCPJSONDocument?+ let kind: MCPResultSourceKind+ let evidence: MCPResultEvidence++ private init(+ originalText: String,+ originalIsError: Bool?,+ document: MCPJSONDocument?,+ kind: MCPResultSourceKind,+ evidence: MCPResultEvidence+ ) {+ self.originalText = originalText+ self.originalIsError = originalIsError+ self.document = document+ self.kind = kind+ self.evidence = evidence+ }++ static func make(+ text: String,+ isError: Bool?,+ origin: MCPResultOrigin,+ evidence: MCPResultEvidence,+ checkpoint: @escaping @Sendable () throws -> Void = {}+ ) throws -> MCPResultSource {+ if case .plainText = origin {+ return MCPResultSource(originalText: text, originalIsError: isError, document: nil,+ kind: .text, evidence: evidence)+ }+ do {+ let document = try MCPJSONDocument.parse(text) {+ do { try checkpoint() } catch { throw MCPSourceCheckpointError(underlying: error) }+ }+ return MCPResultSource(originalText: text, originalIsError: isError, document: document,+ kind: .json, evidence: evidence)+ } catch let failure as MCPSourceCheckpointError {+ throw failure.underlying+ } catch MCPResultBoundaryError.invalidJSON where Self.isRetained(origin) {+ return unreadable(text: text, isError: isError)+ } catch MCPResultBoundaryError.resourceLimit where Self.isRetained(origin) {+ return unreadable(text: text, isError: isError)+ }+ }++ private static func isRetained(_ origin: MCPResultOrigin) -> Bool {+ if case .retainedJSON = origin { return true }+ return false+ }++ private static func unreadable(text: String, isError: Bool?) -> MCPResultSource {+ MCPResultSource(originalText: text, originalIsError: isError, document: nil,+ kind: .unreadable, evidence: .unestablished)+ }+}++/// Keeps checkpoint-originated failures distinct even if they share parser codes.+nonisolated private struct MCPSourceCheckpointError: Error {+ let underlying: any Error+}++nonisolated enum MCPResultErrorCategory: String, Sendable {+ case invalidInput = "invalid_input"+ case notFound = "not_found"+ case ambiguousIdentity = "ambiguous_identity"+ case revisionConflict = "revision_conflict"+ case keyConflict = "key_conflict"+ case storageFailure = "storage_failure"+ case incoherentCapture = "incoherent_capture"+ case admissionBusy = "admission_busy"+ case deadlineExceeded = "deadline_exceeded"+ case retentionCapacity = "retention_capacity"+ case invalidCursor = "invalid_cursor"+ case expiredCursor = "expired_cursor"+ case serializationFailure = "serialization_failure"+ case outcomeUncertain = "outcome_uncertain"+ case unclassifiedHistorical = "unclassified_historical"+ case internalFailure = "internal_failure"+}++/// Explicit provider phase, distinct from any original payload code/message.+nonisolated struct MCPResultFailure: Sendable {+ let category: MCPResultErrorCategory+ let diagnostic: String?+}++nonisolated struct MCPProtectedRecoveryKey: Sendable, Equatable {+ let tool: String+ let idempotencyKey: String+}++nonisolated struct MCPBatchRecoveryItem: Sendable {+ let index: Int+ let itemId: String?+ let operation: String+ let originalKey: MCPProtectedRecoveryKey+ let targetTaskId: UUID?+}++/// Recovery evidence only: this type creates no durable key or acceptance state.+nonisolated enum MCPMutationRecoveryContext: Sendable {+ case protectedWrite(MCPProtectedRecoveryKey)+ case applicationBatch(items: [MCPBatchRecoveryItem])+ case unprotectedMaintenance(tool: String)+}++nonisolated enum MCPResultEntityType: String, Sendable {+ case task, project+}++/// JSON Pointer to a typed record object (taskId/projectId) or direct UUID token.+nonisolated struct MCPResultEntityPosition: Sendable {+ let entityType: MCPResultEntityType+ let sourcePath: String+}++nonisolated struct MCPResultContext: Sendable {+ let tool: String+ let semanticFailure: MCPResultFailure?+ let mutationRecovery: MCPMutationRecoveryContext?+ let entityPositions: [MCPResultEntityPosition]+}++nonisolated enum MCPResultRecoveryDirection: String, Sendable {+ case followSource = "follow_source"+ case retryIdenticalRead = "retry_identical_read"+ case restartRead = "restart_read"+ case reconcileOriginalWrite = "reconcile_original_write"+ case reconcileMaintenance = "reconcile_maintenance"+}++nonisolated struct MCPResultRecovery: Sendable {+ let direction: MCPResultRecoveryDirection+ let mutation: MCPMutationRecoveryContext?+}++/// Metadata is an independent namespace, never inserted into original payloads.+nonisolated struct MCPResultMetadata: Sendable {+ let document: MCPJSONDocument++ private init(document: MCPJSONDocument) {+ self.document = document+ }++ static func make(+ document: MCPJSONDocument,+ checkpoint: @escaping @Sendable () throws -> Void = {}+ ) throws -> MCPResultMetadata {+ try checkpoint()+ guard case .object(let members) = document.value else { throw MCPResultBoundaryError.invalidJSON }+ for member in members {+ try checkpoint()+ guard try validKey(member.name, checkpoint: checkpoint) else {+ throw MCPResultBoundaryError.invalidJSON+ }+ }+ try checkpoint()+ return MCPResultMetadata(document: document)+ }++ /// Modern metadata permits an optional DNS prefix followed by an ASCII name.+ /// Nested JSON member names remain unrestricted and are never reconstructed.+ private static func validKey(_ key: String, checkpoint: @Sendable () throws -> Void) throws -> Bool {+ for (index, byte) in key.utf8.enumerated() {+ if index.isMultiple(of: 256) { try checkpoint() }+ guard (0x20...0x7E).contains(byte) else { return false }+ }+ let parts = key.split(separator: "/", omittingEmptySubsequences: false)+ guard parts.count <= 2 else { return false }+ if parts.count == 2 {+ let labels = parts[0].split(separator: ".", omittingEmptySubsequences: false)+ for label in labels {+ try checkpoint()+ guard let first = label.utf8.first, Self.isLetter(first),+ let last = label.utf8.last, Self.isAlphaNumeric(last),+ try allowed(label, punctuation: [45], checkpoint: checkpoint) else { return false }+ }+ }+ guard let name = parts.last else { return false }+ if name.isEmpty { return true }+ guard let first = name.utf8.first, Self.isAlphaNumeric(first),+ let last = name.utf8.last, Self.isAlphaNumeric(last) else { return false }+ return try allowed(name, punctuation: [45, 46, 95], checkpoint: checkpoint)+ }++ private static func allowed(_ text: Substring, punctuation: [UInt8],+ checkpoint: @Sendable () throws -> Void) throws -> Bool {+ for (index, byte) in text.utf8.enumerated() {+ if index.isMultiple(of: 256) { try checkpoint() }+ guard isAlphaNumeric(byte) || punctuation.contains(byte) else { return false }+ }+ return true+ }++ private static func isLetter(_ byte: UInt8) -> Bool {+ (65...90).contains(byte) || (97...122).contains(byte)+ }++ private static func isAlphaNumeric(_ byte: UInt8) -> Bool {+ isLetter(byte) || (48...57).contains(byte)+ }+}+#endif
diff --git a/Transit/Transit/Services/AppDisplayIDAllocators.swift b/Transit/Transit/Services/AppDisplayIDAllocators.swiftnew file mode 100644index 0000000..d923df9--- /dev/null+++ b/Transit/Transit/Services/AppDisplayIDAllocators.swift@@ -0,0 +1,38 @@+import Foundation++/// Selects counter adapters before any CloudKit container is constructed.+enum AppDisplayIDAllocators {+ struct Pair {+ let tasks: DisplayIDAllocator+ let milestones: DisplayIDAllocator+ }++ static func make(+ mode: AppPersistencePolicy.Mode,+ syncActive: Bool,+ cloudFactory: (String) -> DisplayIDAllocator = {+ DisplayIDAllocator(counterRecordName: $0, isCloudSyncActive: true)+ }+ ) -> Pair {+ guard mode.permitsCloudSync && syncActive else {+ return Pair(+ tasks: DisplayIDAllocator(store: DisabledCounterStore(), isCloudSyncActive: false),+ milestones: DisplayIDAllocator(store: DisabledCounterStore(), isCloudSyncActive: false)+ )+ }+ return Pair(tasks: cloudFactory("global-counter"), milestones: cloudFactory("milestone-counter"))+ }+}++/// Fails closed even if a caller bypasses the allocator's inactive-sync guard.+nonisolated struct DisabledCounterStore: DisplayIDAllocator.CounterStore {+ enum Failure: Swift.Error { case unavailable }++ func loadCounter() async throws -> DisplayIDAllocator.CounterSnapshot {+ throw Failure.unavailable+ }++ func saveCounter(nextDisplayID: Int, expectedChangeTag: String?) async throws {+ throw Failure.unavailable+ }+}
diff --git a/Transit/Transit/Services/AppIsolationSmoke.swift b/Transit/Transit/Services/AppIsolationSmoke.swiftnew file mode 100644index 0000000..958ae67--- /dev/null+++ b/Transit/Transit/Services/AppIsolationSmoke.swift@@ -0,0 +1,52 @@+import Foundation+import SwiftData++/// Opt-in test-host attestation; preflight runs before ModelContainer creation.+enum AppIsolationSmoke {+ struct Snapshot {+ let mode: AppPersistencePolicy.Mode+ let storeURL: URL+ let memoryOnly: Bool+ let cloudSyncActive: Bool+ let disabledCounters: Bool+ let sidecar: URL+ }++ static var snapshot: Snapshot?+ static var enabled: Bool {+ ProcessInfo.processInfo.environment["TRANSIT_ISOLATION_SMOKE"] == "1"+ }++ static func preflight(mode: AppPersistencePolicy.Mode, configuration: ModelConfiguration) {+ guard enabled else { return }+ let environment = ProcessInfo.processInfo.environment+ precondition(environment["TRANSIT_PERSISTENCE_MODE"] == "unit-test")+ precondition(mode == .unitTest && Bundle.main.bundleIdentifier == AppPersistencePolicy.developmentBundleID)+ precondition(environment["TRANSIT_SMOKE_HOST_PATH"] == Bundle.main.bundleURL.path)+ precondition(configuration.isStoredInMemoryOnly)+ precondition(configuration.cloudKitContainerIdentifier == nil)+ precondition(configuration.groupAppContainerIdentifier == nil)+ precondition(!configuration.url.path.contains("me.nore.ig.Transit/"))+ }++ static func record(+ mode: AppPersistencePolicy.Mode, container: ModelContainer, cloudSyncActive: Bool,+ allocators: AppDisplayIDAllocators.Pair, sidecar: URL+ ) {+ guard enabled else { return }+ precondition(!cloudSyncActive && !mode.permitsAutomaticMCPStartup)+ precondition(container.configurations.allSatisfy {+ $0.isStoredInMemoryOnly && $0.cloudKitContainerIdentifier == nil+ && $0.groupAppContainerIdentifier == nil+ })+ let disabled = [allocators.tasks, allocators.milestones].allSatisfy {+ !$0.isCloudSyncActive && $0.counterStore is DisabledCounterStore+ }+ precondition(disabled)+ precondition(sidecar.deletingLastPathComponent() == FileManager.default.temporaryDirectory)+ precondition(sidecar.lastPathComponent.hasPrefix("mcp-tests-"))+ snapshot = Snapshot(mode: mode, storeURL: container.configurations.first!.url,+ memoryOnly: true, cloudSyncActive: cloudSyncActive,+ disabledCounters: disabled, sidecar: sidecar)+ }+}
diff --git a/Transit/Transit/Services/AppPersistencePolicy.swift b/Transit/Transit/Services/AppPersistencePolicy.swiftnew file mode 100644index 0000000..c9b972d--- /dev/null+++ b/Transit/Transit/Services/AppPersistencePolicy.swift@@ -0,0 +1,80 @@+import Foundation++/// Decides persistence before any store, sync service or background task is created.+nonisolated enum AppPersistencePolicy {+ static let productionBundleID = "me.nore.ig.Transit"+ static let developmentBundleID = "me.nore.ig.Transit.development"++ enum Mode: Equatable, Sendable {+ case production+ case development+ case unitTest+ case uiTest++ var usesMemoryStore: Bool { self == .unitTest || self == .uiTest }+ var permitsCloudSync: Bool { self == .production }+ var permitsBackgroundServices: Bool { !usesMemoryStore }+ var permitsAutomaticMCPStartup: Bool { self == .production }+ }++ enum Failure: Error, Equatable {+ case invalidLaunchMode+ case developmentUsesProductionIdentity+ case testUsesProductionIdentity+ case unexpectedProductionIdentity+ }++ static func resolve(+ bundleID: String?,+ developmentBuild: Bool,+ environment: [String: String],+ testRuntimeDetected: Bool+ ) throws -> Mode {+ func isolatedTest(_ mode: Mode) throws -> Mode {+ guard bundleID == developmentBundleID else { throw Failure.testUsesProductionIdentity }+ return mode+ }+ // Explicit scheme/runner configuration is primary; runtime detection only+ // provides an additional isolated fallback, never access to live storage.+ if let requested = environment["TRANSIT_PERSISTENCE_MODE"] {+ switch requested {+ case "unit-test": return try isolatedTest(.unitTest)+ case "ui-test": return try isolatedTest(.uiTest)+ default: throw Failure.invalidLaunchMode+ }+ }+ if environment["TRANSIT_UI_TEST_SCENARIO"] != nil { return try isolatedTest(.uiTest) }+ let testKeys = ["XCTestConfigurationFilePath", "XCTestBundlePath", "XCInjectBundleInto"]+ if testRuntimeDetected || testKeys.contains(where: { environment[$0] != nil }) {+ return try isolatedTest(.unitTest)+ }+ if developmentBuild {+ guard bundleID == developmentBundleID else {+ throw Failure.developmentUsesProductionIdentity+ }+ return .development+ }+ guard bundleID == productionBundleID else { throw Failure.unexpectedProductionIdentity }+ return .production+ }++ static var isDevelopmentBuild: Bool {+ #if DEBUG || TRANSIT_DEVELOPMENT+ true+ #else+ false+ #endif+ }++ static var current: Mode {+ do {+ return try resolve(+ bundleID: Bundle.main.bundleIdentifier, developmentBuild: isDevelopmentBuild,+ environment: ProcessInfo.processInfo.environment,+ testRuntimeDetected: NSClassFromString("XCTestCase") != nil+ )+ } catch {+ fatalError("Refusing unsafe Transit persistence configuration: \(error)")+ }+ }+}
diff --git a/Transit/Transit/Services/IsolatedPersistenceConfiguration.swift b/Transit/Transit/Services/IsolatedPersistenceConfiguration.swiftnew file mode 100644index 0000000..f993775--- /dev/null+++ b/Transit/Transit/Services/IsolatedPersistenceConfiguration.swift@@ -0,0 +1,22 @@+import Foundation+import SwiftData++enum IsolatedPersistenceConfiguration {+ enum Failure: Error { case productionModeNotAllowed }+ static func make(+ mode: AppPersistencePolicy.Mode,+ schema: Schema,+ applicationSupportDirectory: URL = .applicationSupportDirectory+ ) throws -> ModelConfiguration {+ guard mode != .production else { throw Failure.productionModeNotAllowed }+ if mode.usesMemoryStore {+ return ModelConfiguration(schema: schema, isStoredInMemoryOnly: true,+ groupContainer: .none, cloudKitDatabase: .none)+ }+ let directory = applicationSupportDirectory.appendingPathComponent("TransitDevelopment", isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ return ModelConfiguration("TransitDevelopment", schema: schema,+ url: directory.appendingPathComponent("development.store"),+ cloudKitDatabase: .none)+ }+}
diff --git a/Transit/Transit/Services/PortfolioSummaryService.swift b/Transit/Transit/Services/PortfolioSummaryService.swiftnew file mode 100644index 0000000..7a8a312--- /dev/null+++ b/Transit/Transit/Services/PortfolioSummaryService.swift@@ -0,0 +1,334 @@+#if os(macOS)+import Foundation++nonisolated enum MCPPortfolioScaffoldError: Error {+ case notImplemented+}++/// Pure saved-value aggregation. Identity closure validates attribution but never expands scope.+nonisolated enum PortfolioSummaryService {+ private static let taskStatuses = [+ "idea", "planning", "spec", "ready-for-implementation", "in-progress",+ "ready-for-review", "done", "abandoned"+ ]++ static func summarize(view: CapturedReadView, window: CompletionWindow) throws -> PortfolioSummary {+ try Task.checkCancellation()+ guard view.completeness == .completePortfolio else { throw PortfolioSummaryError.incoherentCapture }+ guard window.start < window.end else { throw CompletionWindowError.invalidInput }+ let projectIndex = try index(view.projects, key: \.physicalKey)+ let taskIndex = try index(view.tasks, key: \.physicalKey)+ let milestoneIndex = try index(view.milestones, key: \.physicalKey)+ _ = try index(view.comments, key: \.physicalKey)+ let selectedKeys: Set<LocalRecordKey>+ switch view.captureScope {+ case .wholePortfolio: selectedKeys = Set(projectIndex.keys)+ case .projects(let keys):+ selectedKeys = Set(keys)+ guard !keys.isEmpty, selectedKeys.count == keys.count,+ selectedKeys.allSatisfy({ projectIndex[$0] != nil }) else {+ throw PortfolioSummaryError.incoherentCapture+ }+ case .selectedQuery: throw PortfolioSummaryError.incoherentCapture+ }+ let wholePortfolio = view.captureScope == .wholePortfolio+ let tasks = view.tasks.filter { task in+ wholePortfolio || task.projectKey.map { selectedKeys.contains($0) } == true+ }+ let milestones = view.milestones.filter {+ $0.projectKey.map { selectedKeys.contains($0) } == true+ }+ try validateIdentities(view: view, projects: selectedKeys, tasks: tasks, milestones: milestones)+ let projects = selectedKeys.compactMap { projectIndex[$0] }.sorted(by: projectPrecedes)+ var state = Aggregation(+ builders: Dictionary(uniqueKeysWithValues: projects.map { ($0.physicalKey, ProjectBuilder()) }),+ milestoneCounts: Dictionary(uniqueKeysWithValues: milestones.map { ($0.physicalKey, TaskCounts()) }))+ try accumulateTasks(tasks, milestoneIndex: milestoneIndex, window: window, state: &state)+ try accumulateMilestones(milestones, builders: &state.builders)+ try accumulateComments(view.comments, taskIndex: taskIndex, builders: &state.builders)+ let milestonesByProject = Dictionary(grouping: milestones, by: \.projectKey)+ let summaries = projects.map { project in+ projectSummary(project, builder: state.builders[project.physicalKey]!,+ milestones: milestonesByProject[project.physicalKey] ?? [],+ milestoneCounts: state.milestoneCounts)+ }+ var diagnostics = collisionDiagnostics(+ view: view, projectKeys: selectedKeys, tasks: tasks, milestones: milestones)+ if !state.unresolvedSamples.isEmpty {+ diagnostics.append(diagnostic("unresolved_project", state.unresolvedSamples))+ }+ if !state.unresolvedInvalidStatuses.isEmpty {+ diagnostics.append(diagnostic("invalid_task_status", state.unresolvedInvalidStatuses))+ }+ return PortfolioSummary(+ projects: summaries, unresolvedProjects: state.unresolved.breakdown,+ diagnostics: diagnostics.sorted { $0.category < $1.category }, completionWindow: window)+ }+}++extension PortfolioSummaryService {+ nonisolated private static func accumulateTasks(+ _ tasks: [ReadTask], milestoneIndex: [LocalRecordKey: ReadMilestone], window: CompletionWindow,+ state: inout Aggregation+ ) throws {+ for (offset, task) in tasks.enumerated() {+ try checkpoint(offset)+ guard let projectKey = task.projectKey, state.builders[projectKey] != nil else {+ state.unresolved.add(task, window: window)+ state.unresolvedSamples.append(sample(task))+ if !taskStatuses.contains(task.rawStatus) { state.unresolvedInvalidStatuses.append(sample(task)) }+ continue+ }+ var builder = state.builders[projectKey]!+ builder.total.add(task, window: window)+ builder.activity.consider(task.creationDate, kind: .taskCreation, id: task.id, key: task.physicalKey)+ builder.activity.consider(task.lastStatusChangeDate, kind: .taskStatus, id: task.id, key: task.physicalKey)+ if !taskStatuses.contains(task.rawStatus) { builder.invalidStatuses.append(sample(task)) }+ if let key = task.milestoneKey {+ if let milestone = milestoneIndex[key], milestone.projectKey == projectKey {+ state.milestoneCounts[key, default: TaskCounts()].add(task, window: window)+ } else {+ builder.invalidMilestones.add(task, window: window)+ builder.invalidLinks.append(sample(task))+ }+ } else { builder.unassigned.add(task, window: window) }+ state.builders[projectKey] = builder+ }+ }++ nonisolated private static func accumulateMilestones(+ _ milestones: [ReadMilestone], builders: inout [LocalRecordKey: ProjectBuilder]+ ) throws {+ for (offset, milestone) in milestones.enumerated() {+ try checkpoint(offset)+ guard let key = milestone.projectKey else { continue }+ builders[key]?.activity.consider(+ milestone.creationDate, kind: .milestoneCreation, id: milestone.id, key: milestone.physicalKey)+ builders[key]?.activity.consider(+ milestone.lastStatusChangeDate, kind: .milestoneStatus, id: milestone.id, key: milestone.physicalKey)+ if !["open", "done", "abandoned"].contains(milestone.rawStatus) {+ builders[key]?.invalidMilestoneStatuses.append(sample(milestone))+ }+ }+ }++ nonisolated private static func accumulateComments(+ _ comments: [ReadCommentEvidence], taskIndex: [LocalRecordKey: ReadTask],+ builders: inout [LocalRecordKey: ProjectBuilder]+ ) throws {+ for (offset, comment) in comments.enumerated() {+ try checkpoint(offset)+ guard let taskKey = comment.taskKey, let task = taskIndex[taskKey],+ let projectKey = task.projectKey, builders[projectKey] != nil else { continue }+ builders[projectKey]?.activity.consider(+ comment.creationDate, kind: .commentCreation, id: comment.id, key: comment.physicalKey)+ }+ }++ nonisolated private static func checkpoint(_ offset: Int) throws {+ if offset.isMultiple(of: 256) { try Task.checkCancellation() }+ }++ nonisolated private static func index<Record>(_ records: [Record], key: KeyPath<Record, LocalRecordKey>) throws+ -> [LocalRecordKey: Record] {+ var result: [LocalRecordKey: Record] = [:]+ for (offset, record) in records.enumerated() {+ try checkpoint(offset)+ guard result.updateValue(record, forKey: record[keyPath: key]) == nil else {+ throw PortfolioSummaryError.incoherentCapture+ }+ }+ return result+ }++ nonisolated static func validateIdentities(+ view: CapturedReadView, projects: Set<LocalRecordKey>, tasks: [ReadTask], milestones: [ReadMilestone]+ ) throws {+ let selectedTaskKeys = Set(tasks.map(\.physicalKey))+ let relatedMilestoneKeys = Set(milestones.map(\.physicalKey)).union(tasks.compactMap(\.milestoneKey))+ let relatedProjectKeys = projects.union(view.milestones.filter {+ relatedMilestoneKeys.contains($0.physicalKey)+ }.compactMap(\.projectKey))+ try rejectDuplicateUUIDs(view.projects, id: \.id, key: \.physicalKey, relevant: relatedProjectKeys)+ try rejectDuplicateUUIDs(view.tasks, id: \.id, key: \.physicalKey, relevant: selectedTaskKeys)+ try rejectDuplicateUUIDs(view.milestones, id: \.id, key: \.physicalKey, relevant: relatedMilestoneKeys)+ let relevantComments = Set(view.comments.filter {+ $0.taskKey.map { selectedTaskKeys.contains($0) } == true+ }.map(\.physicalKey))+ try rejectDuplicateUUIDs(view.comments, id: \.id, key: \.physicalKey, relevant: relevantComments)+ }++ nonisolated private static func rejectDuplicateUUIDs<Record>(+ _ records: [Record], id: KeyPath<Record, UUID>, key: KeyPath<Record, LocalRecordKey>,+ relevant: Set<LocalRecordKey>+ ) throws {+ let groups = Dictionary(grouping: records) { $0[keyPath: id] }+ for group in groups.values where group.count > 1 {+ if group.contains(where: { relevant.contains($0[keyPath: key]) }) {+ throw PortfolioSummaryError.identityAmbiguity+ }+ }+ }++ nonisolated private static func projectSummary(+ _ project: ReadProject, builder: ProjectBuilder, milestones: [ReadMilestone],+ milestoneCounts: [LocalRecordKey: TaskCounts]+ ) -> PortfolioProjectSummary {+ let counts = builder.total.statuses+ let workflow = counts.planning + counts.spec + counts.readyForImplementation+ + counts.inProgress + counts.readyForReview+ let rows = milestones.sorted {+ ($0.id.uuidString, keyString($0.physicalKey)) < ($1.id.uuidString, keyString($1.physicalKey))+ }.map { milestone in+ let total = milestoneCounts[milestone.physicalKey] ?? TaskCounts()+ let validStatus = ["open", "done", "abandoned"].contains(milestone.rawStatus)+ return PortfolioMilestoneSummary(+ milestoneId: milestone.id, displayId: milestone.permanentDisplayId, name: milestone.name,+ rawStatus: milestone.rawStatus, status: validStatus ? milestone.rawStatus : "open",+ invalidStatus: !validStatus, countsByStatus: total.statuses,+ totalTaskCount: total.count, recentCompletions: total.recent)+ }+ let diagnostics = [+ ("invalid_task_status", builder.invalidStatuses),+ ("invalid_milestone_status", builder.invalidMilestoneStatuses),+ ("invalid_milestone_association", builder.invalidLinks)+ ].filter { !$0.1.isEmpty }.map { diagnostic($0.0, $0.1) }.sorted { $0.category < $1.category }+ return PortfolioProjectSummary(+ projectId: project.id, name: project.name, countsByStatus: counts, totalTaskCount: builder.total.count,+ ideaCount: counts.idea, inProgressCount: counts.inProgress, workflowTaskCount: workflow,+ nonterminalTaskCount: counts.idea + workflow, recentCompletions: builder.total.recent,+ lastRecordedActivity: builder.activity.evidence, milestones: rows,+ unassignedMilestone: builder.unassigned.breakdown,+ invalidMilestoneAssociations: builder.invalidMilestones.breakdown, diagnostics: diagnostics)+ }++ nonisolated private static func normalizedName(_ name: String) -> String {+ // Same POSIX folding as actor-isolated ProjectNamePolicy; no live name resolution.+ name.trimmingCharacters(in: .whitespacesAndNewlines)+ .folding(options: [.caseInsensitive], locale: Locale(identifier: "en_US_POSIX"))+ }++ nonisolated private static func projectPrecedes(_ lhs: ReadProject, _ rhs: ReadProject) -> Bool {+ (normalizedName(lhs.name), lhs.id.uuidString, keyString(lhs.physicalKey))+ < (normalizedName(rhs.name), rhs.id.uuidString, keyString(rhs.physicalKey))+ }++ nonisolated private static func collisionDiagnostics(+ view: CapturedReadView, projectKeys: Set<LocalRecordKey>, tasks: [ReadTask], milestones: [ReadMilestone]+ ) -> [PortfolioDiagnostic] {+ let taskKeys = Set(tasks.map(\.physicalKey))+ let milestoneKeys = Set(milestones.map(\.physicalKey)).union(tasks.compactMap(\.milestoneKey))+ let names = Dictionary(grouping: view.projects) { normalizedName($0.name) }.values.filter {+ $0.count > 1 && $0.contains { projectKeys.contains($0.physicalKey) }+ }.flatMap { $0.map(sample) }+ let taskIDs = Dictionary(grouping: view.tasks.filter { $0.permanentDisplayId != nil }) {+ $0.permanentDisplayId!+ }.values.filter { $0.count > 1 && $0.contains { taskKeys.contains($0.physicalKey) } }.flatMap { $0.map(sample) }+ let milestoneIDs = Dictionary(grouping: view.milestones.filter { $0.permanentDisplayId != nil }) {+ $0.permanentDisplayId!+ }.values.filter {+ $0.count > 1 && $0.contains { milestoneKeys.contains($0.physicalKey) }+ }.flatMap { $0.map(sample) }+ return [+ ("duplicate_project_name", names), ("duplicate_task_display_id", taskIDs),+ ("duplicate_milestone_display_id", milestoneIDs)+ ].filter { !$0.1.isEmpty }.map { diagnostic($0.0, $0.1) }+ }++ nonisolated private static func keyString(_ key: LocalRecordKey) -> String {+ key.encodedIdentifier.base64EncodedString()+ }+ nonisolated private static func sample(_ task: ReadTask) -> Sample {+ Sample(kind: "task", id: task.id, displayID: task.permanentDisplayId, key: task.physicalKey)+ }+ nonisolated private static func sample(_ milestone: ReadMilestone) -> Sample {+ Sample(kind: "milestone", id: milestone.id, displayID: milestone.permanentDisplayId, key: milestone.physicalKey)+ }+ nonisolated private static func sample(_ project: ReadProject) -> Sample {+ Sample(kind: "project", id: project.id, displayID: nil, key: project.physicalKey)+ }+ nonisolated private static func diagnostic(_ category: String, _ samples: [Sample]) -> PortfolioDiagnostic {+ let ordered = samples.sorted {+ if $0.kind != $1.kind { return $0.kind < $1.kind }+ if $0.id != $1.id { return $0.id.uuidString < $1.id.uuidString }+ if $0.displayID != $1.displayID { return ($0.displayID ?? Int.min) < ($1.displayID ?? Int.min) }+ return keyString($0.key) < keyString($1.key)+ }+ return PortfolioDiagnostic(+ category: category, affectedCount: samples.count,+ samples: ordered.prefix(10).map {+ PortfolioIdentitySample(entityKind: $0.kind, id: $0.id, displayId: $0.displayID,+ discriminator: keyString($0.key))+ }, sampleComplete: samples.count <= 10)+ }++}++extension PortfolioSummaryService {+ nonisolated private struct Aggregation {+ var builders: [LocalRecordKey: ProjectBuilder]+ var milestoneCounts: [LocalRecordKey: TaskCounts]+ var unresolved = TaskCounts()+ var unresolvedSamples: [Sample] = []+ var unresolvedInvalidStatuses: [Sample] = []+ }++ nonisolated private struct Sample {+ let kind: String+ let id: UUID+ let displayID: Int?+ let key: LocalRecordKey+ }++ nonisolated private struct ProjectBuilder {+ var total = TaskCounts()+ var unassigned = TaskCounts()+ var invalidMilestones = TaskCounts()+ var activity = Activity()+ var invalidStatuses: [Sample] = []+ var invalidMilestoneStatuses: [Sample] = []+ var invalidLinks: [Sample] = []+ }++ nonisolated private struct TaskCounts {+ var buckets = Array(repeating: 0, count: 8)+ var done = 0+ var abandoned = 0+ var missing = 0+ var count: Int { buckets.reduce(0, +) }+ var statuses: PortfolioStatusCounts {+ PortfolioStatusCounts(idea: buckets[0], planning: buckets[1], spec: buckets[2],+ readyForImplementation: buckets[3], inProgress: buckets[4],+ readyForReview: buckets[5], done: buckets[6], abandoned: buckets[7])+ }+ var recent: PortfolioRecentCompletions {+ PortfolioRecentCompletions(done: done, abandoned: abandoned, missingCompletionDateCount: missing)+ }+ var breakdown: PortfolioTaskBreakdown {+ PortfolioTaskBreakdown(countsByStatus: statuses, totalTaskCount: count, recentCompletions: recent)+ }+ mutating func add(_ task: ReadTask, window: CompletionWindow) {+ let bucket = taskStatuses.firstIndex(of: task.rawStatus) ?? 0+ buckets[bucket] += 1+ guard bucket >= 6 else { return }+ guard let date = task.completionDate else { missing += 1; return }+ guard window.start <= date, date < window.end else { return }+ if bucket == 6 { done += 1 } else { abandoned += 1 }+ }+ }++ nonisolated private struct Activity {+ var evidence: PortfolioActivityEvidence?+ var physicalKey: LocalRecordKey?+ mutating func consider(_ timestamp: Date, kind: PortfolioActivityKind, id: UUID, key: LocalRecordKey) {+ if let previous = evidence, let previousKey = physicalKey {+ guard timestamp > previous.timestamp || (timestamp == previous.timestamp+ && (kind.rawValue, id.uuidString, keyString(key))+ < (previous.kind.rawValue, previous.id.uuidString, keyString(previousKey))) else { return }+ }+ evidence = PortfolioActivityEvidence(timestamp: timestamp, kind: kind, id: id)+ physicalKey = key+ }+ }+}+#endif
diff --git a/Transit/Transit/Services/SyncManager.swift b/Transit/Transit/Services/SyncManager.swiftindex b97324b..fc010a4 100644--- a/Transit/Transit/Services/SyncManager.swift+++ b/Transit/Transit/Services/SyncManager.swift@@ -45,6 +45,8 @@ final class SyncManager { private let heartbeatFetcher: HeartbeatFetcher private let heartbeatSaver: HeartbeatSaver+ /// Development and test bootstrap can prohibit sync regardless of saved preferences.+ let cloudSyncAllowed: Bool /// True when the preference no longer matches the mode the live container runs in, /// i.e. the user changed the toggle and has not relaunched yet.@@ -53,6 +55,7 @@ final class SyncManager { } init(+ cloudSyncAllowed: Bool = true, heartbeatFetcher: @escaping HeartbeatFetcher = { context, descriptor in try context.fetch(descriptor) },@@ -62,10 +65,11 @@ final class SyncManager { ) { // Default to enabled if never set let defaults = UserDefaults.standard- if defaults.object(forKey: Self.syncEnabledKey) == nil {+ if cloudSyncAllowed && defaults.object(forKey: Self.syncEnabledKey) == nil { defaults.set(true, forKey: Self.syncEnabledKey) }- let enabled = defaults.bool(forKey: Self.syncEnabledKey)+ let enabled = cloudSyncAllowed && defaults.bool(forKey: Self.syncEnabledKey)+ self.cloudSyncAllowed = cloudSyncAllowed self.isSyncEnabled = enabled self.isCloudSyncActive = enabled self.heartbeatFetcher = heartbeatFetcher@@ -80,6 +84,7 @@ final class SyncManager { /// container and its heartbeat keep the CloudKit mode they launched with until the /// app is relaunched. Explicit MCP lifecycle operations own heartbeat start/stop. func setSyncEnabled(_ enabled: Bool) {+ guard cloudSyncAllowed else { return } isSyncEnabled = enabled UserDefaults.standard.set(enabled, forKey: Self.syncEnabledKey) }@@ -91,7 +96,7 @@ final class SyncManager { /// in-memory, CloudKit-free container — must call it with `false` so display-ID /// allocation is gated correctly (T-1797). func recordActiveCloudSync(_ active: Bool) {- isCloudSyncActive = active+ isCloudSyncActive = active && cloudSyncAllowed } /// Creates a ModelConfiguration based on the current sync preference, and records
diff --git a/Transit/Transit/TransitApp.swift b/Transit/Transit/TransitApp.swiftindex f288f60..cb5d6b3 100644--- a/Transit/Transit/TransitApp.swift+++ b/Transit/Transit/TransitApp.swift@@ -36,9 +36,8 @@ struct TransitApp: App { private let quickActionService: QuickActionService #endif - /// True when the app is launched as a unit test host (not UI tests, which set their own scenario).- private static let isUnitTestHost: Bool = NSClassFromString("XCTestCase") != nil- && ProcessInfo.processInfo.environment["TRANSIT_UI_TEST_SCENARIO"] == nil+ /// Resolve before constructing SyncManager, a container, or receipt sidecars.+ private static let persistenceMode = AppPersistencePolicy.current private static var uiTestScenario: UITestScenario? { UITestScenario(rawValue: ProcessInfo.processInfo.environment["TRANSIT_UI_TEST_SCENARIO"] ?? "")@@ -46,22 +45,24 @@ struct TransitApp: App { // swiftlint:disable:next function_body_length init() {- let isInert = Self.isUnitTestHost- let syncManager = SyncManager()+ let mode = Self.persistenceMode+ let syncManager = SyncManager(cloudSyncAllowed: mode.permitsCloudSync) self.syncManager = syncManager let schema = Schema([ Project.self, TransitTask.self, Comment.self, Milestone.self, SyncHeartbeat.self, MCPWriteReceipt.self ]) let config: ModelConfiguration- if isInert || Self.uiTestScenario != nil {- config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)- // Test hosts bypass makeModelConfiguration, so record the mode explicitly —- // otherwise the display-ID subsystem would think CloudKit is live [T-1797].- syncManager.recordActiveCloudSync(false)+ if mode != .production {+ do {+ config = try IsolatedPersistenceConfiguration.make(mode: mode, schema: schema)+ } catch {+ fatalError("Unable to create isolated storage: \(error)")+ } } else { config = syncManager.makeModelConfiguration(schema: schema) }+ AppIsolationSmoke.preflight(mode: mode, configuration: config) let containerResult = ContainerFactory.makeContainer(schema: schema, configuration: config) // A fallback container is always CloudKit-free, even if the requested // configuration enabled sync. Derive and record the effective mode only@@ -83,18 +84,16 @@ struct TransitApp: App { let persistence = PersistenceAvailability.shared persistence.update(from: containerResult) - if !isInert && Self.uiTestScenario == nil && containerResult.error == nil {+ if mode.permitsCloudSync && containerResult.error == nil { syncManager.initializeCloudKitSchemaIfNeeded(container: container) } let context = container.mainContext- let allocator = DisplayIDAllocator(isCloudSyncActive: cloudSyncActive)+ let allocators = AppDisplayIDAllocators.make(mode: mode, syncActive: cloudSyncActive)+ let allocator = allocators.tasks self.displayIDAllocator = allocator - let milestoneAllocator = DisplayIDAllocator(- counterRecordName: "milestone-counter",- isCloudSyncActive: cloudSyncActive- )+ let milestoneAllocator = allocators.milestones self.milestoneIDAllocator = milestoneAllocator let taskService = TaskService(modelContext: context, displayIDAllocator: allocator)@@ -108,7 +107,7 @@ struct TransitApp: App { let connectivityMonitor = ConnectivityMonitor() self.connectivityMonitor = connectivityMonitor - if !isInert {+ if mode.permitsCloudSync { // Wire up connectivity restore to trigger display ID promotion. // The closure is @MainActor @Sendable, and context (container.mainContext) // is MainActor-isolated, so it can be captured directly.@@ -154,20 +153,25 @@ struct TransitApp: App { tasks: taskService, projects: projectService, comments: commentService, milestones: milestoneService, context: context) // Own the retry scope and lock for the app lifetime, across listener restarts.- let sidecar = isInert || Self.uiTestScenario != nil+ let sidecar = mode.usesMemoryStore ? FileManager.default.temporaryDirectory.appendingPathComponent("mcp-tests-" + UUID().uuidString) : config.url.appendingPathExtension("mcp-writes")+ AppIsolationSmoke.record(mode: mode, container: container, cloudSyncActive: cloudSyncActive,+ allocators: allocators, sidecar: sidecar) let writeCoordinator = MCPWriteCoordinator(services: writeServices, sidecarDirectory: sidecar, persistence: persistence) self.mcpWriteCoordinator = writeCoordinator try? writeCoordinator.cleanupExpiredOutcomes()+ let reads = MCPReadAppDependencies.make(container: container, syncActive: cloudSyncActive)+ let readCoordinator = MCPReadCoordinator(domain: reads.snapshots.domain, diagnostics: reads.diagnostics) let mcpToolHandler = MCPToolHandler( taskService: taskService, projectService: projectService, commentService: commentService, milestoneService: milestoneService, maintenanceService: maintenanceService, settings: mcpSettings,- persistence: persistence, writeCoordinator: writeCoordinator+ persistence: persistence, taskQuerySnapshots: reads.snapshots, writeCoordinator: writeCoordinator,+ readService: reads, readCoordinator: readCoordinator )- self.mcpServer = MCPServer(toolHandler: mcpToolHandler)+ self.mcpServer = MCPServer(toolHandler: mcpToolHandler, readCoordinator: readCoordinator) #endif }@@ -297,23 +301,26 @@ struct TransitApp: App { .environment(maintenanceService) } + // MARK: - UI Test Support++ private func seedUITestDataIfNeeded() {+ guard let scenario = Self.uiTestScenario else { return }+ scenario.seed(into: container.mainContext)+ }+}++extension TransitApp { // MARK: - MCP Server #if os(macOS) private func startMCPServerIfEnabled() async { // Skip MCP server in unit test host to avoid port conflicts across test runs- guard mcpSettings.isEnabled, !Self.isUnitTestHost else { return }+ guard Self.persistenceMode.permitsAutomaticMCPStartup, mcpSettings.isEnabled else { return } await mcpServer.start(port: mcpSettings.port) syncManager.startHeartbeat(container: container) } #endif - // MARK: - UI Test Support-- private func seedUITestDataIfNeeded() {- guard let scenario = Self.uiTestScenario else { return }- scenario.seed(into: container.mainContext)- } } // MARK: - macOS Commands
diff --git a/Transit/Transit/Views/Settings/SettingsView.swift b/Transit/Transit/Views/Settings/SettingsView.swiftindex 0f8dca6..b0ed91f 100644--- a/Transit/Transit/Views/Settings/SettingsView.swift+++ b/Transit/Transit/Views/Settings/SettingsView.swift@@ -110,7 +110,8 @@ struct SettingsView: View { TextField("Your Name", text: $userDisplayName) LabeledContent("About Transit", value: appVersion) VStack(alignment: .leading, spacing: 4) {- Toggle("iCloud Sync", isOn: $syncEnabled)+ Toggle("iCloud Sync", isOn: syncPreference)+ .disabled(!syncManager.cloudSyncAllowed) .onChange(of: syncEnabled) { _, enabled in syncManager.setSyncEnabled(enabled) }@@ -153,7 +154,15 @@ struct SettingsView: View { } var syncFootnote: String {- Self.syncFootnote(requiresRestart: syncManager.syncChangeRequiresRestart)+ guard syncManager.cloudSyncAllowed else { return "This copy keeps its data on this device." }+ return Self.syncFootnote(requiresRestart: syncManager.syncChangeRequiresRestart)+ }++ private var syncPreference: Binding<Bool> {+ Binding(+ get: { syncManager.cloudSyncAllowed && syncEnabled },+ set: { if syncManager.cloudSyncAllowed { syncEnabled = $0 } }+ ) } private func projectRow(_ project: Project) -> some View {@@ -445,7 +454,8 @@ extension SettingsView { } FormRow("iCloud Sync", labelWidth: Self.labelWidth) { VStack(alignment: .leading, spacing: 4) {- Toggle("", isOn: $syncEnabled)+ Toggle("", isOn: syncPreference)+ .disabled(!syncManager.cloudSyncAllowed) .labelsHidden() .toggleStyle(.switch) .onChange(of: syncEnabled) { _, enabled in
diff --git a/Transit/TransitIsolationSmokeTests/DevelopmentIsolationSmokeTests.swift b/Transit/TransitIsolationSmokeTests/DevelopmentIsolationSmokeTests.swiftnew file mode 100644index 0000000..d441ff8--- /dev/null+++ b/Transit/TransitIsolationSmokeTests/DevelopmentIsolationSmokeTests.swift@@ -0,0 +1,20 @@+import Foundation+import Testing+@testable import Transit++@MainActor+struct DevelopmentIsolationSmokeTests {+ @Test("Actual isolated host bootstrap uses no persistent or CloudKit store",+ .enabled(if: ProcessInfo.processInfo.environment["TRANSIT_ISOLATION_SMOKE"] == "1"))+ func actualHostBootstrap() throws {+ #expect(AppIsolationSmoke.enabled)+ let snapshot = try #require(AppIsolationSmoke.snapshot)+ #expect(Bundle.main.bundleIdentifier == AppPersistencePolicy.developmentBundleID)+ #expect(snapshot.mode == .unitTest)+ #expect(snapshot.memoryOnly && !snapshot.cloudSyncActive && snapshot.disabledCounters)+ #expect(snapshot.sidecar.lastPathComponent.hasPrefix("mcp-tests-"))+ #expect(!snapshot.storeURL.path.contains("me.nore.ig.Transit/"))+ print("Isolated host mode=unit-test memoryOnly=true cloudSync=false disabledCounters=true")+ print("Isolated host configuration URL=\(snapshot.storeURL.path) sidecar=\(snapshot.sidecar.path)")+ }+}
diff --git a/Transit/TransitTests/MCP/MCPImportEvidenceMonitorTests.swift b/Transit/TransitTests/MCP/MCPImportEvidenceMonitorTests.swiftnew file mode 100644index 0000000..04aad58--- /dev/null+++ b/Transit/TransitTests/MCP/MCPImportEvidenceMonitorTests.swift@@ -0,0 +1,134 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++struct MCPImportEvidenceMonitorTests {+ @Test func relevantSuccessNeedsCaptureProofAndPreservesLastSuccess() {+ let now = ContinuousClock.now+ let date = Date(timeIntervalSince1970: 100)+ let monitor = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store")+ let id = UUID()+ monitor.receive(.init(id: id, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: true),+ observedAt: date, monotonicNow: now)+ let state = monitor.snapshot()+ #expect(state.generation == 1)+ #expect(monitor.freshness(state, proof: nil, asOf: date, now: now).assessment == .unknown)+ let proof = MCPImportCaptureProof(storeIdentifier: "store", visibleImportIDs: [id])+ #expect(monitor.freshness(state, proof: proof, asOf: date, now: now).assessment == .recentImport)+ monitor.receive(.init(id: UUID(), storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: false),+ observedAt: date, monotonicNow: now)+ #expect(monitor.snapshot().lastSuccess?.event.id == id)+ }++ @Test func unrelatedEventsAndStoppedCallbacksCannotChangeGeneration() {+ let monitor = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store")+ let date = Date()+ for kind in [MCPImportEvent.Kind.setup, .export, .import] {+ monitor.receive(.init(id: UUID(), storeIdentifier: "other", kind: kind,+ startDate: date, endDate: date, succeeded: true))+ }+ #expect(monitor.snapshot().generation == 0)+ monitor.stop()+ monitor.receive(.init(id: UUID(), storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: true))+ #expect(monitor.snapshot().generation == 0)+ }++ @Test func recencyUsesBothMonotonicAndWallClockBoundaries() {+ let now = ContinuousClock.now+ let date = Date(timeIntervalSince1970: 100)+ let id = UUID()+ let monitor = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store")+ monitor.receive(.init(id: id, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: true),+ observedAt: date, monotonicNow: now)+ let proof = MCPImportCaptureProof(storeIdentifier: "store", visibleImportIDs: [id])+ let snapshot = monitor.snapshot()+ #expect(monitor.freshness(snapshot, proof: proof, asOf: date.addingTimeInterval(30),+ now: now.advanced(by: .seconds(30))).assessment == .recentImport)+ #expect(monitor.freshness(snapshot, proof: proof, asOf: date.addingTimeInterval(31),+ now: now.advanced(by: .seconds(31))).assessment == .stale)+ #expect(monitor.freshness(snapshot, proof: proof, asOf: date.addingTimeInterval(-1),+ now: now).assessment == .unknown)+ }++ @Test func malformedImportAndClockJumpsFailClosed() {+ let date = Date(timeIntervalSince1970: 100)+ let now = ContinuousClock.now+ let id = UUID()+ let monitor = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store")+ monitor.receive(.init(id: id, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date.addingTimeInterval(1), succeeded: true),+ observedAt: date, monotonicNow: now)+ #expect(monitor.snapshot().lastSuccess == nil)+ monitor.receive(.init(id: id, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: true),+ observedAt: date, monotonicNow: now)+ let snapshot = monitor.snapshot()+ let proof = MCPImportCaptureProof(storeIdentifier: "store", visibleImportIDs: [id])+ #expect(monitor.freshness(snapshot, proof: proof, asOf: date.addingTimeInterval(2),+ now: now.advanced(by: .seconds(20))).assessment == .unknown)+ let wrongStore = MCPImportCaptureProof(storeIdentifier: "other", visibleImportIDs: [id])+ #expect(monitor.freshness(snapshot, proof: wrongStore, asOf: date, now: now).lastImportedAt == nil)+ let inactive = MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: "store")+ #expect(inactive.freshness(inactive.snapshot(), proof: proof, asOf: date,+ now: now).assessment == .notApplicable)+ }++ @Test func concurrentCallbackCopiesAreSerializedBeforeFenceRead() {+ let date = Date()+ let monitor = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store")+ DispatchQueue.concurrentPerform(iterations: 100) { _ in+ monitor.receive(.init(id: UUID(), storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: true))+ }+ #expect(monitor.snapshot().generation == 100)+ }++ @Test func boundedWindowsFreezeEvidenceAndCloseFailClosed() throws {+ let monitor = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store")+ let date = Date()+ let id = UUID()+ let window = try monitor.beginObservation(applicableImportIDs: [id])+ monitor.receive(.init(id: id, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: true))+ let frozen = monitor.snapshot(observation: window)+ window.close()+ #expect(frozen.successfulImports[id] != nil)+ let closed = monitor.snapshot(observation: window)+ #expect(!closed.observationIsValid)+ #expect(closed.successfulImports.isEmpty)+ let proof = MCPImportCaptureProof(storeIdentifier: "store", visibleImportIDs: [id])+ #expect(monitor.freshness(closed, proof: proof, asOf: date, now: .now).assessment == .unknown)+ var windows: [MCPImportObservationWindow] = []+ for _ in 0..<8 { windows.append(try monitor.beginObservation(applicableImportIDs: [])) }+ #expect(throws: MCPImportObservationError.self) { try monitor.beginObservation(applicableImportIDs: []) }+ windows.removeLast().close()+ let replacement = try monitor.beginObservation(applicableImportIDs: [])+ replacement.close()+ #expect(throws: MCPImportObservationError.self) {+ try monitor.beginObservation(applicableImportIDs: Set((0..<257).map { _ in UUID() }))+ }+ }++ @Test func restartedObserverRejectsOldEpochCallback() {+ let monitor = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store")+ let center = NotificationCenter()+ let date = Date()+ monitor.start(center: center)+ monitor.stop()+ monitor.start(center: center)+ monitor.receive(.init(id: UUID(), storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: true), observerEpoch: 1)+ #expect(monitor.snapshot().generation == 0)+ monitor.receive(.init(id: UUID(), storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: true), observerEpoch: 3)+ #expect(monitor.snapshot().generation == 1)+ monitor.stop()+ }++}+#endif
diff --git a/Transit/TransitTests/MCP/MCPReadRefreshPolicyTests.swift b/Transit/TransitTests/MCP/MCPReadRefreshPolicyTests.swiftnew file mode 100644index 0000000..cd8617e--- /dev/null+++ b/Transit/TransitTests/MCP/MCPReadRefreshPolicyTests.swift@@ -0,0 +1,152 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++struct MCPReadRefreshPolicyTests {+ @Test func skipAndUnavailableDecisions() {+ let empty = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store").snapshot()+ #expect(MCPReadRefreshPolicy.decision(policy: .cached, snapshot: empty,+ recent: false, remaining: .seconds(5)) == .skip(.notRequested))+ #expect(MCPReadRefreshPolicy.decision(policy: .refreshIfNeeded, snapshot: empty,+ recent: false, remaining: .seconds(5)) == .skip(.unavailable))+ #expect(MCPReadRefreshPolicy.decision(policy: .refreshIfNeeded, snapshot: empty,+ recent: true, remaining: .seconds(5)) == .skip(.recentImport))+ #expect(MCPReadRefreshPolicy.parse(nil) == .refreshIfNeeded)+ #expect(MCPReadRefreshPolicy.parse("cached") == .cached)+ #expect(MCPReadRefreshPolicy.parse(1) == nil)+ #expect(MCPReadRefreshPolicy.parse("invalid") == nil)+ }++ @Test func boundedInflightAndInactive() {+ let monitor = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store")+ monitor.receive(.init(id: UUID(), storeIdentifier: "store", kind: .import,+ startDate: Date(), endDate: nil, succeeded: false))+ let state = monitor.snapshot()+ #expect(MCPReadRefreshPolicy.decision(policy: .refreshIfNeeded, snapshot: state,+ recent: false, remaining: .seconds(5),+ applicableInFlightIDs: state.inFlight) == .wait(.seconds(2)))+ #expect(MCPReadRefreshPolicy.decision(policy: .refreshIfNeeded, snapshot: state,+ recent: false, remaining: .milliseconds(250),+ applicableInFlightIDs: state.inFlight) == .wait(.milliseconds(250)))+ #expect(MCPReadRefreshPolicy.decision(policy: .refreshIfNeeded, snapshot: state,+ recent: false, remaining: .zero,+ applicableInFlightIDs: state.inFlight) == .skip(.timeout))+ let inactive = MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: "store").snapshot()+ #expect(MCPReadRefreshPolicy.decision(policy: .refreshIfNeeded, snapshot: inactive,+ recent: true, remaining: .seconds(5)) == .skip(.notRequested))+ }++ @Test func applicabilityAndOutcomePriority() {+ let date = Date()+ let id = UUID()+ let monitor = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store")+ monitor.receive(.init(id: id, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: nil, succeeded: false))+ let initial = monitor.snapshot()+ #expect(MCPReadRefreshPolicy.decision(policy: .refreshIfNeeded, snapshot: initial,+ recent: false, remaining: .seconds(5)) == .skip(.unavailable))+ monitor.receive(.init(id: id, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: false))+ let failed = monitor.snapshot()+ #expect(MCPReadRefreshPolicy.outcome(initial: initial, final: failed, proof: nil,+ applicableInFlightIDs: [id]) == .failed)+ monitor.receive(.init(id: id, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: true))+ let successful = monitor.snapshot()+ let proof = MCPImportCaptureProof(storeIdentifier: "store", visibleImportIDs: [id])+ #expect(MCPReadRefreshPolicy.outcome(initial: initial, final: successful, proof: proof,+ applicableInFlightIDs: [id]) == .importObserved)+ #expect(MCPReadRefreshPolicy.outcome(initial: initial, final: successful, proof: nil,+ applicableInFlightIDs: [id]) == .failed)+ }++ @Test func waitObservesCompletionWithoutMainActorHop() async throws {+ let date = Date()+ let id = UUID()+ let monitor = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store")+ monitor.receive(.init(id: id, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: nil, succeeded: false))+ let observation = try monitor.beginObservation(applicableImportIDs: [id])+ defer { observation.close() }+ let initial = monitor.snapshot(observation: observation)+ let final = await MCPReadRefreshPolicy.wait(monitor: monitor, initial: initial,+ duration: .milliseconds(50),+ observation: observation, sleep: { _ in+ monitor.receive(.init(id: id, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: true))+ })+ #expect(final.lastSuccess?.event.id == id)+ }++ @Test func waitStopsAtShortenedDeadline() async throws {+ let monitor = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store")+ monitor.receive(.init(id: UUID(), storeIdentifier: "store", kind: .import,+ startDate: Date(), endDate: nil, succeeded: false))+ let initial = monitor.snapshot()+ let observation = try monitor.beginObservation(applicableImportIDs: initial.inFlight)+ defer { observation.close() }+ let start = ContinuousClock.now+ let final = await MCPReadRefreshPolicy.wait(monitor: monitor, initial: initial,+ duration: .milliseconds(20),+ observation: observation)+ #expect(start.duration(to: .now) < .milliseconds(500))+ #expect(final.generation == initial.generation)+ }++ @Test func applicableCompletionSurvivesLaterUnrelatedSameStoreEvents() async throws {+ for succeeds in [true, false] {+ let date = Date()+ let relevant = UUID()+ let unrelated = UUID()+ let monitor = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store")+ monitor.receive(.init(id: relevant, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: nil, succeeded: false))+ let observation = try monitor.beginObservation(applicableImportIDs: [relevant])+ defer { observation.close() }+ let initial = monitor.snapshot(observation: observation)+ let final = await MCPReadRefreshPolicy.wait(monitor: monitor, initial: initial,+ duration: .milliseconds(20),+ observation: observation, sleep: { _ in+ monitor.receive(.init(id: relevant, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: succeeds))+ monitor.receive(.init(id: unrelated, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: succeeds))+ })+ let proof = MCPImportCaptureProof(storeIdentifier: "store", visibleImportIDs: [relevant])+ #expect(MCPReadRefreshPolicy.outcome(initial: initial, final: final, proof: proof,+ applicableInFlightIDs: [relevant])+ == (succeeds ? .importObserved : .failed))+ }+ }++ @Test func windowCaptureKeepsVisibleSuccessAboveRelevantFailure() throws {+ let monitor = MCPImportEvidenceMonitor(syncActive: true, storeIdentifier: "store")+ let date = Date()+ let successID = UUID()+ let failureID = UUID()+ let window = try monitor.beginObservation(applicableImportIDs: [successID, failureID])+ defer { window.close() }+ for id in [successID, failureID] {+ monitor.receive(.init(id: id, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: nil, succeeded: false))+ }+ let initial = monitor.snapshot(observation: window)+ monitor.receive(.init(id: successID, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: true))+ monitor.receive(.init(id: failureID, storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: false))+ monitor.receive(.init(id: UUID(), storeIdentifier: "store", kind: .import,+ startDate: date, endDate: date, succeeded: true))+ let capture = monitor.snapshot(observation: window)+ let proof = MCPImportCaptureProof(storeIdentifier: "store", visibleImportIDs: [successID])+ #expect(MCPReadRefreshPolicy.outcome(initial: initial, final: capture, proof: proof,+ applicableInFlightIDs: [successID, failureID]) == .importObserved)+ #expect(monitor.freshness(capture, proof: proof, asOf: Date(), now: .now).assessment == .recentImport)+ #expect(MCPReadRefreshPolicy.outcome(initial: initial, final: capture, proof: nil,+ applicableInFlightIDs: [successID, failureID]) == .failed)+ #expect(monitor.freshness(capture, proof: nil, asOf: Date(), now: .now).assessment == .unknown)+ }++}+#endif
diff --git a/Transit/TransitTests/MCPBoundedReadRouteTests.swift b/Transit/TransitTests/MCPBoundedReadRouteTests.swiftnew file mode 100644index 0000000..c18a2fc--- /dev/null+++ b/Transit/TransitTests/MCPBoundedReadRouteTests.swift@@ -0,0 +1,153 @@+#if os(macOS)+import Foundation+import HTTPTypes+import SwiftData+import Testing+@testable import Transit++/// Actual router RED, separate from the historical batch transport component fixtures.+@Suite(.serialized)+nonisolated struct MCPBoundedReadRouteTests {+ @MainActor private final class Fixture {+ let owner: TestModelContainer+ let handler: MCPToolHandler+ let service: MCPReadService+ let savedTask: TransitTask+ init(owner: TestModelContainer, handler: MCPToolHandler, service: MCPReadService, savedTask: TransitTask) {+ self.owner = owner; self.handler = handler; self.service = service; self.savedTask = savedTask+ }+ }++ @Test @concurrent func actualRouterReturnsSavedResultAndFullRPCIdentity() async throws {+ let fixture = try await Self.fixture()+ let id = String(repeating: "rpc-id-", count: 128)+ let response = try await MCPTestHelpers.respond(handler: fixture.handler,+ contentType: "application/json", accept: "application/json, text/event-stream",+ protocolVersion: "2026-07-28", body: Self.body(id: id), loggerLabel: "bounded-read-route")+ #expect(response.status == .ok)+ let frame = try #require(response.json as? [String: Any])+ #expect(frame["jsonrpc"] as? String == "2.0" && frame["id"] as? String == id)+ let result = try #require(frame["result"] as? [String: Any])+ let payload = try Self.payload(result)+ let records = try #require(payload["results"] as? [[String: Any]])+ #expect(records.first?["name"] as? String == "Saved task")+ let meta = try #require((result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])+ #expect(meta["snapshotId"] != nil && meta["asOf"] != nil)+ #expect(frame["_meta"] == nil && frame["content"] == nil)+ }++ @Test @concurrent func actualRouterFreezesCursorMetadataAndPublishesOnlySelectedPage() async throws {+ let fixture = try await Self.fixture(twoTasks: true)+ let first = try await MCPTestHelpers.respond(handler: fixture.handler,+ contentType: "application/json", accept: "application/json, text/event-stream",+ protocolVersion: "2026-07-28", body: Self.body(id: "first"), loggerLabel: "bounded-read-cursor")+ let frame = try #require(first.json as? [String: Any])+ let result = try #require(frame["result"] as? [String: Any])+ let payload = try Self.payload(result)+ let cursor = try #require(payload["nextCursor"] as? String)+ let original = try await MainActor.run {+ try #require(fixture.service.snapshots.retainedPage(for: cursor).metadataBytes)+ }+ #expect(first.body.range(of: original) != nil)+ await MainActor.run { fixture.savedTask.name = "Changed after capture" }+ let replay = try await MCPTestHelpers.respond(handler: fixture.handler,+ contentType: "application/json", accept: "application/json, text/event-stream",+ protocolVersion: "2026-07-28", body: Self.body(id: "replay", arguments: ["cursor": cursor]),+ loggerLabel: "bounded-read-cursor")+ let replayFrame = try #require(replay.json as? [String: Any])+ let replayResult = try #require(replayFrame["result"] as? [String: Any])+ #expect(replay.body.range(of: original) != nil)+ #expect(replayResult["_meta"] != nil)+ #expect(replayFrame["id"] as? String == "replay")+ let sameDomain = await MainActor.run {+ fixture.service.snapshots.domain === fixture.handler.taskQuerySnapshots.domain+ }+ #expect(sameDomain)+ }++ @Test(arguments: [false, true]) @concurrent+ func actualRouterDeadlineCoversValidAndInvalidToolArguments(invalid: Bool) async throws {+ let fixture = try await Self.fixture(twoTasks: true)+ let started = DispatchSemaphore(value: 0)+ let blocker = Task { @MainActor in Self.blockMainActor(started) }+ Self.waitForStart(started)+ let start = ContinuousClock.now+ var args: [String: Any] = ["detailLevel": "summary", "includeComments": false, "limit": 1]+ if invalid { args["status"] = true }+ let response: MCPHTTPTestResponse+ do {+ response = try await MCPTestHelpers.respond(handler: fixture.handler,+ contentType: "application/json", accept: "application/json, text/event-stream",+ protocolVersion: "2026-07-28", body: Self.body(id: "bounded", arguments: args),+ loggerLabel: "bounded-read-deadline")+ } catch {+ await blocker.value+ throw error+ }+ let elapsed = start.duration(to: .now)+ print("T63_ROUTE invalid_tool_arguments=\(invalid) encoded_body_elapsed=\(elapsed)")+ #expect(elapsed < .seconds(5))+ await blocker.value+ let accounting = try await MainActor.run {+ let store = fixture.service.snapshots+ return try store.domain.accounting(for: store.publicationStoreID)+ }+ #expect(accounting.visibleEntries == 0 && accounting.visibleBytes == 0)+ let frame = try #require(response.json as? [String: Any])+ #expect(frame["id"] as? String == "bounded")+ let result = try #require(frame["result"] as? [String: Any])+ let meta = try #require((result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])+ #expect(meta["category"] as? String == ReadFailureCategory.timeout.rawValue)+ #expect(meta["snapshotId"] == nil && meta["asOf"] == nil)+ }++ @MainActor private static func blockMainActor(_ signal: DispatchSemaphore) {+ signal.signal()+ Thread.sleep(forTimeInterval: 6)+ }++ private static func waitForStart(_ signal: DispatchSemaphore) { signal.wait() }++ @MainActor private static func fixture(twoTasks: Bool = false) throws -> Fixture {+ let owner = try TestModelContainer()+ owner.context.autosaveEnabled = false+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ let task = TransitTask(name: "Saved task", type: .feature, project: project, displayID: .permanent(1))+ owner.context.insert(project)+ owner.context.insert(task)+ if twoTasks {+ owner.context.insert(TransitTask(name: "Second saved task", type: .feature,+ project: project, displayID: .permanent(2)))+ }+ try owner.context.save()+ task.name = "Unsaved UI task"+ let tasks = DisplayIDAllocator(store: InMemoryCounterStore())+ let milestones = DisplayIDAllocator(store: InMemoryCounterStore())+ let comments = CommentService(modelContext: owner.context)+ let store = MCPTaskQuerySnapshotStore()+ let builder = MCPReadCaptureBuilder(container: owner.container, fence: .actorOnlyTestFixture)+ let service = MCPReadService(source: builder,+ monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil), snapshots: store)+ let handler = MCPToolHandler(taskService: TaskService(modelContext: owner.context, displayIDAllocator: tasks),+ projectService: ProjectService(modelContext: owner.context), commentService: comments,+ milestoneService: MilestoneService(modelContext: owner.context, displayIDAllocator: milestones),+ maintenanceService: DisplayIDMaintenanceService(modelContext: owner.context, taskAllocator: tasks,+ milestoneAllocator: milestones, commentService: comments), settings: MCPSettings(),+ taskQuerySnapshots: store, readService: service)+ return Fixture(owner: owner, handler: handler, service: service, savedTask: task)+ }++ private static func body(id: String, arguments: [String: Any]? = nil) throws -> String {+ let args = arguments ?? ["detailLevel": "summary", "includeComments": false, "limit": 1]+ let bytes = try JSONSerialization.data(withJSONObject: ["jsonrpc": "2.0", "id": id,+ "method": "tools/call", "params": ["name": "query_tasks", "arguments": args]])+ return try #require(String(data: bytes, encoding: .utf8))+ }++ private static func payload(_ result: [String: Any]) throws -> [String: Any] {+ let text = try #require((result["content"] as? [[String: Any]])?.first?["text"] as? String)+ return try #require(JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])+ }++}+#endif
diff --git a/Transit/TransitTests/MCPHTTPTestHelpers.swift b/Transit/TransitTests/MCPHTTPTestHelpers.swiftindex 5b19bdb..648591e 100644--- a/Transit/TransitTests/MCPHTTPTestHelpers.swift+++ b/Transit/TransitTests/MCPHTTPTestHelpers.swift@@ -20,7 +20,7 @@ extension MCPTestHelpers { return try #require(try JSONSerialization.jsonObject(with: bytes) as? [String: Any]) } - static func respond(+ nonisolated static func respond( handler: MCPToolHandler, method: HTTPRequest.Method = .post, path: String = "/mcp",@@ -29,10 +29,11 @@ extension MCPTestHelpers { contentType: String? = nil, accept: String? = nil, sessionID: String? = nil,+ protocolVersion: String? = nil,+ orderedHeaders: [HTTPField] = [], body: String = "", loggerLabel: String ) async throws -> MCPHTTPTestResponse {- let responder = MCPServer.makeRouter(handler: handler).buildResponder() var headers = HTTPFields() if let origin { headers[.origin] = origin@@ -46,6 +47,12 @@ extension MCPTestHelpers { if let sessionID { headers[.mcpSessionID] = sessionID }+ if let protocolVersion {+ headers[HTTPField.Name("MCP-Protocol-Version")!] = protocolVersion+ }+ for field in orderedHeaders {+ headers.append(field)+ } let request = Request( head: HTTPRequest( method: method,@@ -57,28 +64,44 @@ extension MCPTestHelpers { body: RequestBody(buffer: ByteBuffer(string: body)) ) - let channel = EmbeddedChannel()- defer { _ = try? channel.finish() }- let context = MCPRequestContext(- source: ApplicationRequestContextSource(- channel: channel,- logger: Logger(label: loggerLabel)- )- )+ return try await respondToRequest(request, handler: handler, loggerLabel: loggerLabel)+ } - let response = try await responder.respond(to: request, context: context)- let writer = MCPHTTPTestResponseWriter()- try await response.body.write(writer)- let data = Data(buffer: writer.collated.withLockedValue { $0 })- return MCPHTTPTestResponse(- status: response.status,- headers: response.headers,- body: data- )+ nonisolated private static func respondToRequest(+ _ request: Request, handler: MCPToolHandler, loggerLabel: String+ ) async throws -> MCPHTTPTestResponse {+ let responder = MCPServer.makeRouter(handler: handler).buildResponder()+ let loop = NIOAsyncTestingEventLoop()+ var ownedChannel: NIOAsyncTestingChannel?+ do {+ let channel = try await NIOAsyncTestingChannel(loop: loop) { _ in }+ ownedChannel = channel+ let context = MCPRequestContext(source: ApplicationRequestContextSource(+ channel: channel, logger: Logger(label: loggerLabel)))+ let response = try await responder.respond(to: request, context: context)+ let writer = MCPHTTPTestResponseWriter()+ try await response.body.write(writer)+ let data = Data(buffer: writer.collated.withLockedValue { $0 })+ let leftovers = try await channel.finish(acceptAlreadyClosed: true)+ #expect(leftovers.isClean)+ await loop.shutdownGracefully()+ return MCPHTTPTestResponse(status: response.status, headers: response.headers, body: data)+ } catch {+ if let channel = ownedChannel {+ do {+ let leftovers = try await channel.finish(acceptAlreadyClosed: true)+ #expect(leftovers.isClean)+ } catch {+ Issue.record("HTTP fixture channel cleanup failed: \(error)")+ }+ }+ await loop.shutdownGracefully()+ throw error+ } } } -nonisolated struct MCPHTTPTestResponse {+nonisolated struct MCPHTTPTestResponse: Sendable { let status: HTTPResponse.Status let headers: HTTPFields let body: Data
diff --git a/Transit/TransitTests/MCPInitializeHandshakeTests.swift b/Transit/TransitTests/MCPInitializeHandshakeTests.swiftindex 81e9e5b..32f0c06 100644--- a/Transit/TransitTests/MCPInitializeHandshakeTests.swift+++ b/Transit/TransitTests/MCPInitializeHandshakeTests.swift@@ -1,124 +1,105 @@ #if os(macOS)- import Foundation import Testing @testable import Transit +/// Legacy handshake regressions now apply to each modern request's metadata.+/// Initialize is unavailable; an absent optional clientInfo is valid. @MainActor @Suite(.serialized) struct MCPInitializeHandshakeTests {-- @Test func initializeWithoutParamsReturnsInvalidParams() async throws {- let env = try MCPTestHelpers.makeEnv()- let response = await env.handler.handle(MCPTestHelpers.request(method: "initialize"))-- let error = try MCPTestHelpers.jsonRPCError(response)- #expect(error["code"] as? Int == JSONRPCErrorCode.invalidParams)+ @Test func initializeIsUnavailableInsteadOfNegotiatingSession() throws {+ let rejection = try reject(method: "initialize", params: ["_meta": validMetadata()])+ #expect(rejection.httpStatus == 404)+ #expect(rejection.rpcCode == -32601) } - @Test func initializeWithNonObjectParamsReturnsInvalidParams() async throws {- let env = try MCPTestHelpers.makeEnv()- let request = JSONRPCRequest(- jsonrpc: "2.0",- id: .integer(1),- method: "initialize",- params: AnyCodable(["2025-03-26"])- )-- let error = try MCPTestHelpers.jsonRPCError(await env.handler.handle(request))- #expect(error["code"] as? Int == JSONRPCErrorCode.invalidParams)+ @Test func discoverWithoutParamsReturnsInvalidParams() throws {+ let rejection = try reject(params: nil)+ #expect(rejection.rpcCode == -32602) } - @Test func initializeWithScalarParamsReturnsInvalidRequest() throws {- for params in ["42", "true", "null", "\"invalid\""] {- let data = Data("""- {"jsonrpc":"2.0","id":1,"method":"initialize","params":\(params)}- """.utf8)+ @Test func discoverWithNonObjectParamsReturnsInvalidParams() throws {+ let rejection = try reject(params: ["2026-07-28"])+ #expect(rejection.rpcCode == -32602)+ } - let response: JSONRPCResponse- switch MCPServer.decodeIncomingRequest(data) {- case .failure(let errorResponse):- response = errorResponse- case .success, .batch:- Issue.record("Scalar initialize params must be an invalid request")- continue- }- let error = try MCPTestHelpers.jsonRPCError(response)- #expect(error["code"] as? Int == JSONRPCErrorCode.invalidRequest)+ @Test func scalarParamsRemainInvalid() throws {+ for value in [42, true, NSNull(), "invalid"] as [Any] {+ #expect(try reject(params: value).rpcCode == -32602) } } - @Test func initializeRequiresEveryHandshakeField() async throws {- let env = try MCPTestHelpers.makeEnv()-- for field in ["protocolVersion", "capabilities", "clientInfo"] {- var params = validInitializeParams()- params.removeValue(forKey: field)-- let request = MCPTestHelpers.request(method: "initialize", params: params)- let error = try MCPTestHelpers.jsonRPCError(await env.handler.handle(request))- #expect(error["code"] as? Int == JSONRPCErrorCode.invalidParams)+ @Test func everyRequiredMetadataFieldRemainsRequired() throws {+ for field in ["io.modelcontextprotocol/protocolVersion", "io.modelcontextprotocol/clientCapabilities"] {+ var meta = validMetadata()+ meta.removeValue(forKey: field)+ #expect(try reject(params: ["_meta": meta]).rpcCode == -32602) }+ #expect(try reject(params: [:] as [String: Any]).rpcCode == -32602) } - @Test func initializeRejectsWrongRequiredFieldTypes() async throws {- let env = try MCPTestHelpers.makeEnv()- let malformedFields: [(String, Any)] = [- ("protocolVersion", 20250326),- ("capabilities", []),- ("clientInfo", "Transit Tests")- ]-- for (field, value) in malformedFields {- var params = validInitializeParams()- params[field] = value-- let request = MCPTestHelpers.request(method: "initialize", params: params)- let error = try MCPTestHelpers.jsonRPCError(await env.handler.handle(request))- #expect(error["code"] as? Int == JSONRPCErrorCode.invalidParams)+ @Test func wrongRequiredFieldTypesRemainRejected() throws {+ let invalidFields: [(String, Any)] = [("io.modelcontextprotocol/protocolVersion", 20260728),+ ("io.modelcontextprotocol/clientCapabilities", [])]+ for (field, value) in invalidFields {+ var meta = validMetadata()+ meta[field] = value+ #expect(try reject(params: ["_meta": meta]).rpcCode == -32602) } } - @Test func initializeRejectsMalformedClientInfo() async throws {- let env = try MCPTestHelpers.makeEnv()- let malformedClientInfo: [[String: Any]] = [- ["version": "1.0"],- ["name": "Transit Tests"],- ["name": 42, "version": "1.0"],- ["name": "Transit Tests", "version": 1],- ["name": "Transit Tests", "version": "1.0", "title": false]- ]-- for clientInfo in malformedClientInfo {- var params = validInitializeParams()- params["clientInfo"] = clientInfo-- let request = MCPTestHelpers.request(method: "initialize", params: params)- let error = try MCPTestHelpers.jsonRPCError(await env.handler.handle(request))- #expect(error["code"] as? Int == JSONRPCErrorCode.invalidParams)+ @Test func malformedClientInfoRemainsRejectedWhenProvided() throws {+ for clientInfo in [+ ["version": "1.0"], ["name": "Transit Tests"], ["name": 42, "version": "1.0"],+ ["name": "Transit Tests", "version": 1]+ ] as [[String: Any]] {+ var meta = validMetadata()+ meta["io.modelcontextprotocol/clientInfo"] = clientInfo+ #expect(try reject(params: ["_meta": meta]).rpcCode == -32602) } } - @Test func initializeFallsBackToSupportedProtocolVersion() async throws {- let env = try MCPTestHelpers.makeEnv()- var params = validInitializeParams()- params["protocolVersion"] = "2099-01-01"+ @Test func optionalClientInfoAndUnknownMetadataDoNotRequireSession() throws {+ _ = try MCPModernValidator.validate(input(method: "server/discover", params: ["_meta": validMetadata()]),+ availability: MCPModernAvailability(tools: []))+ var meta = validMetadata()+ meta["example.test/extension"] = ["unknown": NSNull()]+ meta["io.modelcontextprotocol/clientInfo"] = ["name": "Transit Tests", "version": "1.0", "title": false]+ _ = try MCPModernValidator.validate(input(method: "server/discover", params: ["_meta": meta]),+ availability: MCPModernAvailability(tools: []))+ }++ @Test func unsupportedVersionRejectsWithoutLegacyFallback() throws {+ var meta = validMetadata()+ meta["io.modelcontextprotocol/protocolVersion"] = "2099-01-01"+ let rejection = try reject(params: ["_meta": meta], version: "2099-01-01")+ #expect(rejection.rpcCode == -32022)+ } - let request = MCPTestHelpers.request(method: "initialize", params: params)- let response = try #require(await env.handler.handle(request))- let data = try JSONEncoder().encode(response)- let json = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any])- let result = try #require(json["result"] as? [String: Any])+ private func validMetadata() -> [String: Any] {+ ["io.modelcontextprotocol/protocolVersion": "2026-07-28",+ "io.modelcontextprotocol/clientCapabilities": [:] as [String: Any]]+ } - #expect(result["protocolVersion"] as? String == "2025-03-26")+ private func input(method: String, params: Any?, version: String = "2026-07-28") throws -> MCPModernRequestInput {+ var object: [String: Any] = ["jsonrpc": "2.0", "id": 1, "method": method]+ if let params { object["params"] = params }+ return MCPModernRequestInput(httpMethod: "POST", headers: [+ .init(name: "Content-Type", value: "application/json"), .init(name: "Accept", value: "application/json"),+ .init(name: "MCP-Protocol-Version", value: version), .init(name: "Mcp-Method", value: method)+ ], body: try JSONSerialization.data(withJSONObject: object)) } - private func validInitializeParams() -> [String: Any] {- [- "protocolVersion": "2025-03-26",- "capabilities": [:] as [String: Any],- "clientInfo": ["name": "Transit Tests", "version": "1.0"]- ]+ private func reject(method: String = "server/discover", params: Any?,+ version: String = "2026-07-28") throws -> MCPModernRejection {+ do {+ _ = try MCPModernValidator.validate(input(method: method, params: params, version: version),+ availability: MCPModernAvailability(tools: []))+ Issue.record("Expected modern metadata rejection")+ throw FixtureFailure.expectedRejection+ } catch let rejection as MCPModernRejection { return rejection } }-} + private enum FixtureFailure: Error { case expectedRejection }+} #endif
diff --git a/Transit/TransitTests/MCPJSONDocumentTests.swift b/Transit/TransitTests/MCPJSONDocumentTests.swiftnew file mode 100644index 0000000..a7b2345--- /dev/null+++ b/Transit/TransitTests/MCPJSONDocumentTests.swift@@ -0,0 +1,182 @@+#if os(macOS)+import Foundation+import Synchronization+import Testing+@testable import Transit++@MainActor struct MCPJSONDocumentTests {+ @Test func completeValuesPreserveWhitespaceAndNumberLexemes() throws {+ let text = " \n{\"huge\":18446744073709551616,\"fraction\":1.00000000000000000001," ++ "\"exp\":-2.300e+400,\"negativeZero\":-0,\"bool\":true,\"null\":null}\t "+ let document = try MCPJSONDocument.parse(text)+ #expect(document.originalUTF8 == Data(text.utf8))+ let expected = MCPJSONFixtureValue.object([+ .init(name: "huge", value: .number("18446744073709551616")),+ .init(name: "fraction", value: .number("1.00000000000000000001")),+ .init(name: "exp", value: .number("-2.300e+400")),+ .init(name: "negativeZero", value: .number("-0")),+ .init(name: "bool", value: .boolean(true)),+ .init(name: "null", value: .null)+ ])+ #expect(expected.matches(document.value))+ }++ @Test func escapedStringsDecodeWithoutChangingOriginalBytes() throws {+ let text = #"{"\u0061":"\uD83D\uDE80\n\t\"\\\/","東京":"e\u0301"}"#+ let document = try MCPJSONDocument.parse(Data(text.utf8))+ #expect(document.originalUTF8 == Data(text.utf8))+ let expected = MCPJSONFixtureValue.object([+ .init(name: "a", value: .string("🚀\n\t\"\\/")),+ .init(name: "東京", value: .string("e\u{0301}"))+ ])+ #expect(expected.matches(document.value))+ }++ @Test func canonicallyEquivalentButScalarDistinctObjectKeysRemainDistinct() throws {+ let text = #"{"\u00e9":1,"e\u0301":2}"#+ let document = try MCPJSONDocument.parse(text)+ #expect(document.originalUTF8 == Data(text.utf8))+ guard case .object(let members) = document.value else {+ Issue.record("Expected two distinct JSON object keys")+ return+ }+ #expect(members.count == 2)+ #expect(members.map { $0.name.unicodeScalars.map(\.value) } == [[0xE9], [0x65, 0x301]])+ let expected = MCPJSONFixtureValue.object([+ .init(name: "\u{E9}", value: .number("1")),+ .init(name: "e\u{301}", value: .number("2"))+ ])+ #expect(expected.matches(document.value))+ }++ @Test func seededCompleteValuesRetainTypedTreeAndExactFragment() throws {+ for seed in UInt64(0)..<128 {+ var generator = MCPJSONFixtureGenerator(seed: seed)+ let expected = generator.value()+ let text = " \n" + (try expected.json()) + "\t"+ do {+ let document = try MCPJSONDocument.parse(text)+ if expected.matches(document.value), document.originalUTF8 == Data(text.utf8) { continue }+ } catch {+ // A valid-value parse error is a property failure, not invalid-input success.+ }+ let minimal = MCPJSONFixtureValue.minimizedFailure(expected) { candidate in+ guard let text = try? candidate.json(), let parsed = try? MCPJSONDocument.parse(text) else {+ return true+ }+ return !candidate.matches(parsed.value) || parsed.originalUTF8 != Data(text.utf8)+ }+ let counterexample = try minimal.json()+ Issue.record("Valid JSON property failed; seed=\(seed), minimal=\(counterexample)")+ return+ }+ }++ @Test(arguments: [+ "", " ", "{}[]", "true false", "{\"a\":1,\"a\":2}", #"{"a":1,"\u0061":2}"#,+ #"{"é":1,"\u00e9":2}"#,+ "[1,]", "{\"a\":}", "{\"a\":1,}", "01", "-", "+1", "1.", "1e", "1e+", "NaN",+ #""\x20""#, #""\uD800""#, #""\uDC00""#, #""\uD800\u0041""#, "\"line\nfeed\""+ ])+ func rejectsAmbiguousOrMalformedJSON(text: String) {+ #expect(throws: MCPResultBoundaryError.invalidJSON) { try MCPJSONDocument.parse(text) }+ }++ @Test func rejectsInvalidUTF8RatherThanReplacingBytes() {+ for bytes: [UInt8] in [[0x22, 0xC3, 0x28, 0x22], [0x22, 0xED, 0xA0, 0x80, 0x22], [0xFF]] {+ #expect(throws: MCPResultBoundaryError.invalidJSON) { try MCPJSONDocument.parse(Data(bytes)) }+ }+ }++ @Test func injectedWorkerCheckpointFailurePropagates() {+ #expect(throws: MCPJSONCheckpointFailure.cancelled) {+ try MCPJSONDocument.parse("[0,1,2]") { throw MCPJSONCheckpointFailure.cancelled }+ }+ }++ @Test(arguments: [31, 32])+ func admittedContainerDepthPreservesCompleteValue(depth: Int) throws {+ let text = Self.nestedContainers(depth: depth)+ let document = try MCPJSONDocument.parse(text)+ #expect(document.originalUTF8 == Data(text.utf8))+ var current = document.value+ for level in 0..<depth {+ if level.isMultiple(of: 2), case .array(let values) = current, values.count == 1 {+ current = values[0]+ } else if !level.isMultiple(of: 2), case .object(let members) = current,+ members.count == 1, members[0].name == "value" {+ current = members[0].value+ } else {+ Issue.record("Container depth or shape changed at level \(level)")+ return+ }+ }+ #expect(current == .null)+ }++ @Test func depth33IsAResourceLimitRatherThanMalformedJSON() {+ #expect(throws: MCPResultBoundaryError.resourceLimit) {+ try MCPJSONDocument.parse(Self.nestedContainers(depth: 33))+ }+ }++ @Test func wide2000RecordArrayIsNotAContainerDepthFailure() throws {+ let records = (0..<2_000).map { "{\"index\":\($0),\"nullable\":null}" }+ let text = "[" + records.joined(separator: ",") + "]"+ let document = try MCPJSONDocument.parse(text)+ #expect(document.originalUTF8 == Data(text.utf8))+ guard case .array(let values) = document.value else {+ Issue.record("Expected wide record array")+ return+ }+ #expect(values.count == 2_000)+ for (index, value) in values.enumerated() {+ let expected = MCPJSONFixtureValue.object([+ .init(name: "index", value: .number(String(index))),+ .init(name: "nullable", value: .null)+ ])+ #expect(expected.matches(value))+ }+ }++ @Test func depthLimitDoesNotReplaceOriginalWorkerCheckpointFailure() {+ #expect(throws: MCPJSONCheckpointFailure.cancelled) {+ try MCPJSONDocument.parse(Self.nestedContainers(depth: 33)) {+ throw MCPJSONCheckpointFailure.cancelled+ }+ }+ }++ @Test func largeStringParsingChecksOriginalWorkerRepeatedly() {+ let checks = Mutex(0)+ let text = "\"" + String(repeating: "東京🛰️", count: 8_000) + "\""+ #expect(throws: MCPJSONCheckpointFailure.cancelled) {+ try MCPJSONDocument.parse(text) {+ let count = checks.withLock { value in value += 1; return value }+ if count == 2 { throw MCPJSONCheckpointFailure.cancelled }+ }+ }+ #expect(checks.withLock { $0 } == 2)+ }++ @Test func shrinkerKeepsValidCandidatesAndFindsSmallCounterexample() throws {+ let original = MCPJSONFixtureValue.array([.string("long"), .number("18446744073709551616")])+ let minimal = MCPJSONFixtureValue.minimizedFailure(original) { _ in true }+ #expect(minimal == .array([]))+ #expect(try minimal.json() == "[]")+ #expect(original.shrinks().allSatisfy { (try? $0.json()) != nil })+ }++ private static func nestedContainers(depth: Int) -> String {+ var text = "null"+ for level in (0..<depth).reversed() {+ text = level.isMultiple(of: 2) ? "[" + text + "]" : "{\"value\":" + text + "}"+ }+ return " \n" + text + "\t"+ }+}++nonisolated enum MCPJSONCheckpointFailure: Error, Equatable {+ case cancelled+}+#endif
diff --git a/Transit/TransitTests/MCPJSONEnvelopeFixtureValidation.swift b/Transit/TransitTests/MCPJSONEnvelopeFixtureValidation.swiftnew file mode 100644index 0000000..be97006--- /dev/null+++ b/Transit/TransitTests/MCPJSONEnvelopeFixtureValidation.swift@@ -0,0 +1,72 @@+#if os(macOS)+import Foundation++/// Test-only complete-envelope structure oracle, independent of Transit parsing.+/// Foundation's numeric range cannot validate lossless JSON number tokens. Strictly+/// validate those tokens first, then replace them only in a disposable copy. The+/// decoded tree is discarded; raw-fragment assertions always use original bytes.+nonisolated enum MCPJSONEnvelopeFixtureValidation {+ static func validate(_ data: Data) throws {+ let bytes = Array(data)+ var disposable = Data()+ var offset = 0+ while offset < bytes.count {+ let byte = bytes[offset]+ if byte == 34 {+ let end = try stringEnd(bytes, offset)+ disposable.append(contentsOf: bytes[offset..<end])+ offset = end+ } else if byte == 45 || (48...57).contains(byte) {+ offset = try numberEnd(bytes, offset)+ disposable.append(48)+ } else {+ guard byte != 43, byte != 46 else { throw ValidationError.invalidNumber }+ disposable.append(byte)+ offset += 1+ }+ }+ _ = try JSONSerialization.jsonObject(with: disposable, options: [.fragmentsAllowed])+ }++ private static func stringEnd(_ bytes: [UInt8], _ start: Int) throws -> Int {+ var offset = start + 1+ while offset < bytes.count {+ if bytes[offset] == 92 { offset += 2; continue }+ if bytes[offset] == 34 { return offset + 1 }+ offset += 1+ }+ throw ValidationError.unterminatedString+ }++ private static func numberEnd(_ bytes: [UInt8], _ start: Int) throws -> Int {+ var offset = start+ func peek() -> UInt8? { offset < bytes.count ? bytes[offset] : nil }+ func digits() {+ while let byte = peek(), (48...57).contains(byte) { offset += 1 }+ }+ func requiredDigits() throws {+ guard let byte = peek(), (48...57).contains(byte) else { throw ValidationError.invalidNumber }+ digits()+ }+ if peek() == 45 { offset += 1 }+ if peek() == 48 {+ offset += 1+ } else {+ guard let byte = peek(), (49...57).contains(byte) else { throw ValidationError.invalidNumber }+ digits()+ }+ if peek() == 46 { offset += 1; try requiredDigits() }+ if peek() == 69 || peek() == 101 {+ offset += 1+ if peek() == 43 || peek() == 45 { offset += 1 }+ try requiredDigits()+ }+ if let next = peek(), ![9, 10, 13, 32, 44, 93, 125].contains(next) {+ throw ValidationError.invalidNumber+ }+ return offset+ }++ private enum ValidationError: Error { case invalidNumber, unterminatedString }+}+#endif
diff --git a/Transit/TransitTests/MCPJSONPropertyFixtures.swift b/Transit/TransitTests/MCPJSONPropertyFixtures.swiftnew file mode 100644index 0000000..3be0647--- /dev/null+++ b/Transit/TransitTests/MCPJSONPropertyFixtures.swift@@ -0,0 +1,115 @@+#if os(macOS)+import Foundation+@testable import Transit++/// Independent fixture model: numbers are tokens, never Foundation numbers.+nonisolated indirect enum MCPJSONFixtureValue: Equatable, Sendable {+ case object([MCPJSONFixtureMember])+ case array([MCPJSONFixtureValue])+ case string(String)+ case number(String)+ case boolean(Bool)+ case null++ func json() throws -> String {+ switch self {+ case .object(let members):+ let entries = try members.map { try Self.quote($0.name) + ":" + $0.value.json() }+ return "{" + entries.joined(separator: ",") + "}"+ case .array(let values): return "[" + (try values.map { try $0.json() }).joined(separator: ",") + "]"+ case .string(let value): return try Self.quote(value)+ case .number(let token): return token+ case .boolean(let value): return value ? "true" : "false"+ case .null: return "null"+ }+ }++ func matches(_ actual: MCPJSONValue) -> Bool {+ switch (self, actual) {+ case (.object(let expected), .object(let members)):+ return expected.count == members.count && zip(expected, members).allSatisfy {+ Array($0.name.unicodeScalars) == Array($1.name.unicodeScalars) && $0.value.matches($1.value)+ }+ case (.array(let expected), .array(let values)):+ return expected.count == values.count && zip(expected, values).allSatisfy { $0.matches($1) }+ case (.string(let expected), .string(let value)): return expected == value+ case (.number(let expected), .number(let value)): return expected == value.lexeme+ case (.boolean(let expected), .boolean(let value)): return expected == value+ case (.null, .null): return true+ default: return false+ }+ }++ /// Every candidate remains valid JSON and has less structure or simpler data.+ func shrinks() -> [MCPJSONFixtureValue] {+ switch self {+ case .object(let members) where !members.isEmpty:+ return [.object([]), .object(Array(members.dropLast())), members[0].value]+ case .array(let values) where !values.isEmpty:+ return [.array([]), .array(Array(values.dropLast())), values[0]]+ case .string(let value) where !value.isEmpty: return [.string(""), .string(String(value.prefix(1)))]+ case .number(let token) where token != "0": return [.number("0")]+ case .boolean(true): return [.boolean(false)]+ default: return []+ }+ }++ static func minimizedFailure(+ _ value: MCPJSONFixtureValue,+ fails: (MCPJSONFixtureValue) -> Bool+ ) -> MCPJSONFixtureValue {+ var current = value+ while let smaller = current.shrinks().first(where: { $0 != current && fails($0) }) {+ current = smaller+ }+ return current+ }++ private static func quote(_ value: String) throws -> String {+ guard let result = String(data: try JSONEncoder().encode(value), encoding: .utf8) else {+ throw CocoaError(.coderReadCorrupt)+ }+ return result+ }+}++nonisolated struct MCPJSONFixtureMember: Equatable, Sendable {+ let name: String+ let value: MCPJSONFixtureValue+}++nonisolated struct MCPJSONFixtureGenerator {+ private var state: UInt64++ init(seed: UInt64) { state = seed }++ mutating func value(depth: Int = 3) -> MCPJSONFixtureValue {+ let selection = next() % (depth > 0 ? 6 : 4)+ switch selection {+ case 0: return .null+ case 1: return .boolean(next() % 2 == 0)+ case 2:+ let tokens = ["0", "-0", "9007199254740993", "18446744073709551616", "-9223372036854775809",+ "1.00000000000000000001", "-2.300e+400", "1E-9999"]+ return .number(tokens[Int(next() % UInt64(tokens.count))])+ case 3:+ let strings = ["", "hello", "東京🛰️", "quote\"\\\n\t\u{0000}", "e\u{0301}", "/~"]+ return .string(strings[Int(next() % UInt64(strings.count))])+ case 4:+ let count = Int(next() % 4)+ return .array((0..<count).map { _ in value(depth: depth - 1) })+ default:+ let count = Int(next() % 4)+ let names = ["source", "presentation", "unknown/~\"", "contractVersion"]+ return .object((0..<count).map {+ MCPJSONFixtureMember(name: names[$0], value: value(depth: depth - 1))+ })+ }+ }++ private mutating func next() -> UInt64 {+ state = state &* 6364136223846793005 &+ 1442695040888963407+ return state >> 32+ }+}+#endif
diff --git a/Transit/TransitTests/MCPModernBindingTests.swift b/Transit/TransitTests/MCPModernBindingTests.swiftnew file mode 100644index 0000000..dcb5425--- /dev/null+++ b/Transit/TransitTests/MCPModernBindingTests.swift@@ -0,0 +1,215 @@+#if os(macOS)+import Foundation+import HTTPTypes+import HummingbirdCore+import NIOConcurrencyHelpers+import NIOCore+import NIOEmbedded+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPModernBindingTests {+ @Test func unsupportedNestedArgumentsNeverCollapseOrBecomeAbsent() throws {+ for arguments in [+ #"{"metadata":{"é":"first","e\u0301":"second"}}"#,+ #"{"metadata":[{"é":"first","e\u0301":"second"}]}"#,+ #"{"limit":1E+9999}"#+ ] {+ let modern = try request(tool: "query_tasks", arguments: arguments)+ let rpc = MCPModernWire.request(modern, tool: "query_tasks")+ let read = try #require(MCPBoundedReadDispatcher.classify(rpc))+ #expect(read.malformedArguments)+ let params = try #require(rpc.params?.value as? [String: Any])+ #expect(params["arguments"] != nil)+ #expect(params["arguments"] as? [String: Any] == nil)+ }+ }++ @Test func unsupportedProtectedArgumentsRejectBeforeAnyEffect() async throws {+ let env = try MCPTestHelpers.makeEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let modern = try request(tool: "create_project", arguments:+ """+ {"name":"Must not exist","colorHex":"#334455","idempotencyKey":"collision",+ "metadata":{"é":1,"e\\u0301":2}}+ """)+ let rpc = MCPModernWire.request(modern, tool: "create_project")+ let selected = try await MCPModernProviderBinding.call(rpc, tool: "create_project",+ handler: env.handler, maintenanceEnabled: false)+ guard case .normal(let bytes) = selected else {+ Issue.record("Unsupported argument envelope must return a request error without dispatch")+ return+ }+ let document = try MCPJSONDocument.parse(bytes)+ let error = try #require(MCPResultEncoderFixtures.field("error", in: document.value))+ #expect(MCPResultEncoderFixtures.field("result", in: document.value) == nil)+ #expect(MCPResultEncoderFixtures.field("code", in: error) != nil)+ #expect(try env.context.fetchCount(FetchDescriptor<Project>()) == 0)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0)+ }++ @Test func availabilitySnapshotReflectsStoredInitialAndImmediateAssignments() async throws {+ let key = "mcpMaintenanceToolsEnabled"+ let previous = UserDefaults.standard.object(forKey: key)+ defer {+ if let previous {+ UserDefaults.standard.set(previous, forKey: key)+ } else {+ UserDefaults.standard.removeObject(forKey: key)+ }+ }+ UserDefaults.standard.set(true, forKey: key)+ let settings = MCPSettings()+ #expect(settings.maintenanceToolsEnabledSnapshot)+ #expect(await Task.detached { settings.maintenanceToolsEnabledSnapshot }.value)+ settings.maintenanceToolsEnabled = false+ #expect(!settings.maintenanceToolsEnabledSnapshot)+ #expect(!(await Task.detached { settings.maintenanceToolsEnabledSnapshot }.value))+ let off = MCPModernProviderBinding.availability(maintenanceEnabled: settings.maintenanceToolsEnabledSnapshot)+ #expect(!off.tools.contains { $0.name == "reassign_duplicate_display_ids" })+ settings.maintenanceToolsEnabled = true+ #expect(settings.maintenanceToolsEnabledSnapshot)+ #expect(MCPModernProviderBinding.availability(maintenanceEnabled: true).tools.contains {+ $0.name == "reassign_duplicate_display_ids"+ })+ }++ @Test func snapshotAssignmentsKeepExistingChangeNotificationSemantics() async throws {+ let env = try MCPTestHelpers.makeEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let settings = env.mcpSettings+ settings.maintenanceToolsEnabled = false+ let loop = NIOAsyncTestingEventLoop()+ let closed = loop.makePromise(of: Void.self)+ do {+ let subscription = try settings.subscriptionBroadcaster.subscribe(id: .string("availability"),+ toolsListChanged: true, channelClose: closed.futureResult)+ settings.maintenanceToolsEnabled = false+ settings.maintenanceToolsEnabled = true+ #expect(settings.maintenanceToolsEnabledSnapshot)+ settings.finishToolListChangeSessions()+ let ack = try #require(try JSONSerialization.jsonObject(+ with: subscription.acknowledgement) as? [String: Any])+ #expect(ack["method"] as? String == "notifications/subscriptions/acknowledged")+ var methods: [String] = []+ for await frame in subscription.changes {+ let notification = try #require(try JSONSerialization.jsonObject(with: frame) as? [String: Any])+ methods.append(try #require(notification["method"] as? String))+ }+ #expect(methods == ["notifications/tools/list_changed"])+ #expect(subscription.delivery.completesGracefully)+ let complete = try #require(try JSONSerialization.jsonObject(+ with: subscription.completion) as? [String: Any])+ let result = try #require(complete["result"] as? [String: Any])+ #expect(result["resultType"] as? String == "complete")+ #expect(complete["id"] as? String == "availability")+ closed.succeed(())+ await loop.shutdownGracefully()+ } catch {+ settings.finishToolListChangeSessions()+ closed.succeed(())+ await loop.shutdownGracefully()+ throw error+ }+ }++ @Test func cancellationDuringBlockedAcknowledgementUnregistersBeforeWriterReturns() async throws {+ let env = try MCPTestHelpers.makeEnv()+ let stream = try await MCPSubscriptionFixture.open(handler: env.handler)+ do {+ try #require(stream.response.status == .ok)+ stream.writer.blockNextWrite()+ stream.startBody()+ try #require(await MCPSubscriptionFixture.wait {+ stream.writer.blockedWriteEntered.withLockedValue { $0 }+ })+ stream.cancelBodyOnly()+ try #require(await MCPSubscriptionFixture.wait { env.handler.activeToolListChangeStreamCount == 0 })+ #expect(!stream.writer.bodyCompleted.withLockedValue { $0 })+ stream.writer.releaseBlockedWrite()+ try #require(await MCPSubscriptionFixture.wait { stream.writer.bodyCompleted.withLockedValue { $0 } })+ #expect(try stream.messages().count == 1)+ await stream.close()+ } catch {+ stream.writer.releaseBlockedWrite()+ await stream.close()+ throw error+ }+ }++ @Test func shutdownFenceRejectsLateRegistrationAndReopenOwnsReplacement() async throws {+ let env = try MCPTestHelpers.makeEnv()+ let old = try await MCPSubscriptionFixture.open(handler: env.handler, id: "old")+ var replacement: MCPSubscriptionFixture?+ var lateRequest: MCPSubscriptionFixture?+ do {+ try #require(old.response.status == .ok)+ env.handler.finishToolListChangeSessions()+ let late = try await MCPSubscriptionFixture.open(handler: env.handler, id: "late")+ lateRequest = late+ #expect(late.response.status == .serviceUnavailable)+ late.startBody()+ try #require(await MCPSubscriptionFixture.wait { late.writer.bodyCompleted.withLockedValue { $0 } })+ let rejected = try #require(try JSONSerialization.jsonObject(+ with: Data(late.writer.bytes.withLockedValue { $0.readableBytesView })) as? [String: Any])+ #expect(rejected["id"] as? String == "late")+ #expect((rejected["error"] as? [String: Any])?["code"] as? Int == -32603)+ #expect(env.handler.activeToolListChangeStreamCount == 0)+ await late.close()+ env.handler.openToolListSubscriptions()+ let next = try await MCPSubscriptionFixture.open(handler: env.handler, id: "new")+ replacement = next+ try #require(next.response.status == .ok)+ #expect(env.handler.activeToolListChangeStreamCount == 1)+ old.startBody()+ try #require(await MCPSubscriptionFixture.wait { old.writer.bodyCompleted.withLockedValue { $0 } })+ let messages = try old.messages()+ try #require(messages.count == 2)+ try MCPToolListChangeNotificationTests.assertComplete(messages[1], id: "old")+ #expect(env.handler.activeToolListChangeStreamCount == 1)+ await old.close()+ await next.close()+ } catch {+ await lateRequest?.close()+ await replacement?.close()+ await old.close()+ throw error+ }+ }++ @Test func unsupportedHTTPMethodsReturn405AndNeverDispatch() async throws {+ let env = try MCPTestHelpers.makeEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let methods: [HTTPRequest.Method] = [.get, .delete, .head, .put, .patch, .options, .trace, .connect]+ for method in methods {+ let response = try await MCPModernResultFixture.transport(handler: env.handler, method: method,+ body: "{not parsed", loggerLabel: "t2383-modern-method-rejection")+ #expect(response.status == .methodNotAllowed)+ #expect(response.headers[.allow] == "POST")+ let forbidden = try await MCPModernResultFixture.transport(handler: env.handler, method: method,+ origin: "https://untrusted.example", body: "{not parsed", loggerLabel: "t2383-modern-origin-first")+ #expect(forbidden.status == .forbidden)+ }+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0)+ }++ private func request(tool: String, arguments: String) throws -> MCPModernRequest {+ let text = """+ {"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"\(tool)","arguments":\(arguments),+ "_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28",+ "io.modelcontextprotocol/clientCapabilities":{}}}}+ """+ let input = MCPModernRequestInput(httpMethod: "POST", headers: [+ .init(name: "Host", value: "127.0.0.1:3141"),+ .init(name: "Content-Type", value: "application/json"),+ .init(name: "Accept", value: "application/json, text/event-stream"),+ .init(name: "MCP-Protocol-Version", value: "2026-07-28"),+ .init(name: "Mcp-Method", value: "tools/call"), .init(name: "Mcp-Name", value: tool)+ ], body: Data(text.utf8))+ return try MCPModernValidator.validate(input,+ availability: MCPModernProviderBinding.availability(maintenanceEnabled: false))+ }+}+#endif
diff --git a/Transit/TransitTests/MCPModernDiscoveryTests.swift b/Transit/TransitTests/MCPModernDiscoveryTests.swiftnew file mode 100644index 0000000..e52cd5a--- /dev/null+++ b/Transit/TransitTests/MCPModernDiscoveryTests.swift@@ -0,0 +1,51 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor+struct MCPModernDiscoveryTests {+ private func result(_ bytes: Data, id: Any) throws -> [String: Any] {+ let envelope = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any])+ #expect(envelope["jsonrpc"] as? String == "2.0")+ let responseID = try #require(envelope["id"])+ #expect(String(describing: responseID) == String(describing: id))+ let result = try #require(envelope["result"] as? [String: Any])+ #expect(result["resultType"] as? String == "complete")+ #expect(result["ttlMs"] as? Int == 0)+ #expect(result["cacheScope"] as? String == "public")+ return result+ }++ @Test func discoveryAdvertisesOnlyImplementedCapabilitiesAndModernVersion() throws {+ let result = try result(MCPModernDiscovery.encodeDiscovery(id: .string("discover"),+ identity: MCPModernServerIdentity(name: "Transit", version: "fixture")), id: "discover")+ #expect(result["supportedVersions"] as? [String] == ["2026-07-28"])+ let capabilities = try #require(result["capabilities"] as? [String: Any])+ #expect(capabilities["tools"] is [String: Any])+ #expect(capabilities["resources"] == nil)+ #expect(capabilities["sampling"] == nil)+ let meta = try #require(result["_meta"] as? [String: Any])+ let identity = try #require(meta["io.modelcontextprotocol/serverInfo"] as? [String: Any])+ #expect(identity["name"] as? String == "Transit")+ #expect(identity["version"] as? String == "fixture")+ }++ @Test func toolsAreSortedAndEveryDefinitionRetainsOutputSchema() throws {+ let schema = try MCPJSONDocument.parse("{\"type\":\"object\"}")+ let tools = ["zeta", "alpha", "middle"].map {+ MCPModernToolDescriptor(name: $0, description: "fixture " + $0, inputSchema: schema,+ resultSchema: MCPResultSchemaDescriptor(tool: $0, description: "fixture", outputSchema: schema))+ }+ let result = try result(MCPModernDiscovery.encodeTools(id: .integer(7), tools: tools), id: 7)+ let definitions = try #require(result["tools"] as? [[String: Any]])+ #expect(definitions.compactMap { $0["name"] as? String } == ["alpha", "middle", "zeta"])+ for definition in definitions {+ #expect((definition["outputSchema"] as? [String: Any])?["type"] as? String == "object")+ #expect((definition["inputSchema"] as? [String: Any])?["type"] as? String == "object")+ }+ let empty = try self.result(MCPModernDiscovery.encodeTools(id: .integer(8), tools: []), id: 8)+ #expect((empty["tools"] as? [Any])?.isEmpty == true)+ }+}+#endif
diff --git a/Transit/TransitTests/MCPModernOrdinaryRetentionTests.swift b/Transit/TransitTests/MCPModernOrdinaryRetentionTests.swiftnew file mode 100644index 0000000..6bd6959--- /dev/null+++ b/Transit/TransitTests/MCPModernOrdinaryRetentionTests.swift@@ -0,0 +1,180 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPModernOrdinaryRetentionTests {+ @Test func omittedCommentsKeepSavedCanonicalRevisionAfterLaterEditsAndNewIDs() throws {+ let models = try TestModelContainer()+ models.context.autosaveEnabled = false+ let project = Project(name: "Original parent", description: "", gitRepo: nil, colorHex: "blue")+ let task = TransitTask(name: "Original task", type: .feature, project: project, displayID: .permanent(16))+ let comment = Comment(content: "Original comment", authorName: "Fixture", isAgent: true, task: task)+ models.context.insert(project)+ models.context.insert(task)+ models.context.insert(comment)+ try models.context.save()+ let savedRevision = try MCPRecordSnapshot.task(task, in: models.context).revision+ let capture = try MCPReadCaptureBuilder(container: models.container, fence: .actorOnlyTestFixture)+ .capture(ReadCaptureRequest(projectSelectors: nil, selection: .tasks(detail: .fullRecord),+ completeness: .selectedRead, includeComments: false))+ let capturedTask = try #require(capture.tasks.first)+ #expect(capturedTask.revision == savedRevision)+ #expect(capturedTask.requestedCommentRecordsJSON == nil)+ #expect(capture.comments.count == 1)+ let recordBytes = try #require(capturedTask.fullRecordWithoutCommentsJSON)+ let text = try #require(String(data: recordBytes, encoding: .utf8))+ let metadata = try JSONEncoder().encode(capture.metadata)+ let pages = try preparedPages([text, text], metadata: metadata)+ let bundle = try retainedBundle(pages)+ let clock = Clock()+ clock.instant = capture.createdAt+ let domain = MCPReadPublicationDomain(testingInstant: clock.instant)+ let store = MCPTaskQuerySnapshotStore(now: { clock.instant }, domain: domain)+ let cursor = UUID().uuidString+ let reservation = try #require(try store.prepare(preparedBundle: bundle, cursors: [cursor],+ deadline: capture.retentionDeadline, operationID: UUID(), metadataBytes: metadata, policy: .cached))+ try commit(reservation, domain: domain)+ try saveLaterEdits(comment: comment, task: task, project: project, context: models.context)+ #expect(try MCPRecordSnapshot.task(task, in: models.context).revision != savedRevision)+ let retained = try store.retainedPage(for: cursor)+ let owner = try #require(retained.preparedResultPage)+ #expect(owner === pages[1])+ #expect(retained.text.utf8.elementsEqual(text.utf8))+ #expect(retained.metadataBytes == metadata && retained.policy == .cached)+ let frozen = try #require(owner.source.document?.value)+ #expect(MCPResultEncoderFixtures.field("revision", in: frozen) == .string(savedRevision))+ #expect(MCPResultEncoderFixtures.field("comments", in: frozen) == nil)+ for id in [JSONRPCId.string("after-edit"), .integer(16)] {+ let prepared = try MCPPreparedToolRead(text: retained.text, frozenMetadataBytes: retained.metadataBytes,+ preparedResultPage: owner)+ let actual = try MCPModernProviderBinding.read(prepared, id: id, tool: "query_tasks")+ let expected = try MCPResultEncoder.encode(fragment: pages[1].fragment, id: id)+ #expect(actual == expected)+ }+ clock.instant += .seconds(300)+ domain.setTestingInstant(clock.instant)+ #expect(throws: (any Error).self) { try store.retainedPage(for: cursor) }+ }++ @Test func expandedOwnersStayPrivateAndDiscardClearsAllPendingBytes() throws {+ let clock = Clock()+ let domain = MCPReadPublicationDomain(testingInstant: clock.instant)+ let store = MCPTaskQuerySnapshotStore(now: { clock.instant }, domain: domain)+ let pages = try preparedPages(["[]", #"{"future":1E-9999}"#])+ let bundle = try retainedBundle(pages)+ let cursor = UUID().uuidString+ let reservation = try #require(try store.prepare(preparedBundle: bundle, cursors: [cursor],+ deadline: clock.instant + .seconds(300), operationID: UUID(), metadataBytes: nil, policy: .cached))+ defer { domain.withLock { reservation.discardLocked(in: domain) } }+ let pending = try domain.accounting(for: store.publicationStoreID)+ #expect(pending.visibleBytes == 0 && pending.pendingBytes == bundle.charge.totalBytes)+ #expect(throws: (any Error).self) { try store.retainedPage(for: cursor) }+ domain.withLock { reservation.discardLocked(in: domain); reservation.discardLocked(in: domain) }+ let empty = try domain.accounting(for: store.publicationStoreID)+ #expect(empty.pendingBytes == 0 && empty.visibleBytes == 0)+ #expect(throws: (any Error).self) { try store.retainedPage(for: cursor) }+ }++ @Test func expandedCapacityRejectsWholeWhileReusableBudgetIsIndependent() throws {+ let pages = try preparedPages(["[]", #"{"future":null}"#])+ let bundle = try retainedBundle(pages)+ let domain = MCPReadPublicationDomain()+ let store = MCPTaskQuerySnapshotStore(maxBytes: bundle.charge.totalBytes - 1, domain: domain)+ let reusable = try MCPReusableSnapshotStore(domain: domain)+ do {+ _ = try store.prepare(preparedBundle: bundle, cursors: [UUID().uuidString],+ deadline: .now + .seconds(300), operationID: UUID(), metadataBytes: nil, policy: .cached)+ Issue.record("Expanded ordinary capacity unexpectedly accepted")+ } catch let error as MCPTaskQueryError {+ #expect(error.code == "QUERY_CAPACITY_EXCEEDED")+ }+ #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+ #expect(try domain.accounting(for: reusable.publicationStoreID).visibleBytes == 0)+ #expect(try domain.accounting(for: reusable.publicationStoreID).pendingBytes == 0)+ }++ @Test func pagePreparerGetsAllPrivatePagesAndExactOriginalOperationBeforeFailure() async throws {+ let models = try TestModelContainer()+ let snapshots = MCPTaskQuerySnapshotStore()+ let service = MCPReadService(source: MCPReadCaptureBuilder(container: models.container,+ fence: .actorOnlyTestFixture), monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil),+ snapshots: snapshots, pagePreparer: { pages, tool, original in+ #expect(pages.map { $0.result.content.first?.text } == ["[]", "null", "false"])+ #expect(tool == "query_tasks" && original.shouldContinue())+ throw PreparationFault.blockedParser+ })+ let coordinator = MCPReadCoordinator(domain: snapshots.domain)+ let bytes = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { operation in+ await MainActor.run {+ do {+ let reads = try ["[]", "null", "false"].map { try MCPPreparedToolRead(text: $0) }+ #expect(throws: PreparationFault.blockedParser) {+ try service.preparePrivatePages(reads, tool: "query_tasks", operation: operation)+ }+ return Self.response(Data("observed".utf8))+ } catch {+ Issue.record("Page-preparer control failed: \(error)")+ return Self.response(Data("failed".utf8))+ }+ }+ }+ #expect(bytes == Data("observed".utf8))+ #expect(snapshots.retainedBytes == 0)+ for _ in 0..<100 where coordinator.unfinishedCount != 0 { try? await Task.sleep(for: .milliseconds(5)) }+ #expect(coordinator.unfinishedCount == 0)+ }++ @Test func laterParserFailureLeavesNoPreparedPublicationOrCursor() throws {+ let store = MCPTaskQuerySnapshotStore()+ #expect(throws: MCPResultBoundaryError.invalidJSON) { try preparedPages(["[]", "{broken"]) }+ #expect(store.retainedBytes == 0)+ }++ private func preparedPages(_ texts: [String], metadata: Data? = nil) throws -> [MCPResultPreparedPage] {+ let owner: MCPResultPreparedMetadata?+ if let metadata {+ let tool = try MCPPreparedToolRead(text: "null", frozenMetadataBytes: metadata)+ let value = try #require(try MCPResultProviderAdapters.metadata(+ result: tool.result, frozenReadBytes: metadata))+ owner = try MCPResultPreparation.metadata(value: value)+ } else { owner = nil }+ return try texts.map { text in+ try MCPResultPreparation.page(request: MCPResultPagePreparationRequest(text: text, isError: nil,+ origin: .generatedJSON, evidence: .established,+ context: MCPResultContext(tool: "query_tasks", semanticFailure: nil,+ mutationRecovery: nil, entityPositions: []), metadataOwner: owner))+ }+ }++ private func saveLaterEdits(comment: Transit.Comment, task: TransitTask, project: Project,+ context: ModelContext) throws {+ comment.content = "Later saved comment"+ task.name = "Later saved task"+ project.name = "Later parent"+ try context.save()+ }++ private func retainedBundle(_ pages: [MCPResultPreparedPage]) throws -> MCPResultRetainedBundle {+ try MCPResultPreparation.prepare(pages: pages, budget: MCPResultRetentionBudget(store: .ordinary,+ originalCaptureIndexBytes: 0, visibleBytes: 0, pendingBytes: 0))+ }++ private func commit(_ publication: MCPPublicationReservation, domain: MCPReadPublicationDomain) throws {+ try domain.withLock {+ if let rejection = publication.validateLocked(in: domain) { throw rejection }+ publication.commitLocked(in: domain)+ }+ }++ nonisolated private static func response(_ bytes: Data) -> PreparedReadResult {+ PreparedReadResult(encodedResponse: bytes, publications: [],+ publicationErrors: .init(busy: Data(), expired: Data(), capacity: Data()))+ }++ private final class Clock { var instant = ContinuousClock.now }+ private enum PreparationFault: Error { case blockedParser }+}+#endif
diff --git a/Transit/TransitTests/MCPModernProtocolTests.swift b/Transit/TransitTests/MCPModernProtocolTests.swiftnew file mode 100644index 0000000..8fd9de6--- /dev/null+++ b/Transit/TransitTests/MCPModernProtocolTests.swift@@ -0,0 +1,397 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++/// Pure protocol fixtures never construct services, capture storage or execute tools.+@MainActor+struct MCPModernProtocolTests {+ private let version = "2026-07-28"+ private let availability = MCPModernAvailability(tools: [+ MCPModernAvailableTool(name: "query_tasks", execution: .coveredRead),+ MCPModernAvailableTool(name: "update_task", execution: .protectedWrite),+ MCPModernAvailableTool(name: "café", execution: .ordinaryRead)+ ])++ private func envelope(+ method: String = "tools/call", id: Any = "request-1", name: Any = "query_tasks",+ version: Any = "2026-07-28", capabilities: Any = [String: Any](),+ arguments: Any = [String: Any]()+ ) -> [String: Any] {+ var params: [String: Any] = ["_meta": [+ "io.modelcontextprotocol/protocolVersion": version,+ "io.modelcontextprotocol/clientCapabilities": capabilities+ ]]+ if method == "tools/call" { params["name"] = name; params["arguments"] = arguments }+ return ["jsonrpc": "2.0", "id": id, "method": method, "params": params]+ }++ private func input(+ _ body: Any, method: String = "tools/call", name: String? = "query_tasks",+ version: String = "2026-07-28", httpMethod: String = "POST",+ overrides: [String: String] = [:], extra: [MCPModernHeader] = []+ ) throws -> MCPModernRequestInput {+ var headers = ["Content-Type": "application/json",+ "Accept": "application/json, text/event-stream",+ "MCP-Protocol-Version": version, "Mcp-Method": method]+ if let name { headers["Mcp-Name"] = name }+ for (key, value) in overrides { headers[key] = value }+ return MCPModernRequestInput(httpMethod: httpMethod,+ headers: headers.map { MCPModernHeader(name: $0.key, value: $0.value) } + extra,+ body: try JSONSerialization.data(withJSONObject: body,+ options: [.fragmentsAllowed, .withoutEscapingSlashes]))+ }++ private func rejection(_ input: MCPModernRequestInput) throws -> MCPModernRejection {+ do {+ _ = try MCPModernValidator.validate(input, availability: availability)+ Issue.record("Invalid protocol input was accepted")+ throw FixtureFailure.expectedRejection+ } catch let error as MCPModernRejection { return error }+ }++ private enum FixtureFailure: Error { case expectedRejection }++ @Test func validRequestUsesImmutableAvailabilityAndLeavesDomainArgumentsForAdmission() throws {+ let request = try MCPModernValidator.validate(+ input(envelope(arguments: ["limit": -1, "displayId": "invalid"])),+ availability: availability)+ #expect(request.id == .string("request-1"))+ #expect(request.metadata.protocolVersion == version)+ #expect(request.metadata.clientInfo == nil)+ if case .callTool(let name, .coveredRead) = request.method {+ #expect(name == "query_tasks")+ } else { Issue.record("Expected covered-read classification") }+ #expect(request.params != nil)+ }++ @Test(arguments: ["server/discover", "tools/list", "subscriptions/listen"])+ func requestOnlyMethodsAreStateless(method: String) throws {+ var body = envelope(method: method, id: 17)+ if method == "subscriptions/listen" {+ var params = try #require(body["params"] as? [String: Any])+ params["notifications"] = ["toolsListChanged": true]+ body["params"] = params+ }+ let request = try MCPModernValidator.validate(input(body, method: method, name: nil),+ availability: availability)+ #expect(request.id == .integer(17))+ switch request.method {+ case .discover: #expect(method == "server/discover")+ case .listTools: #expect(method == "tools/list")+ case .listenSubscriptions: #expect(method == "subscriptions/listen")+ case .callTool: Issue.record("Unexpected tool call")+ }+ }++ @Test(arguments: ["protocolVersion", "clientCapabilities"])+ func missingMetadataHasStandardError(field: String) throws {+ var body = envelope()+ var params = try #require(body["params"] as? [String: Any])+ var meta = try #require(params["_meta"] as? [String: Any])+ meta.removeValue(forKey: "io.modelcontextprotocol/" + field)+ params["_meta"] = meta; body["params"] = params+ let error = try rejection(input(body))+ #expect(error.httpStatus == 400)+ #expect(error.rpcCode == -32602)+ #expect(error.id == .string("request-1"))+ }++ @Test func metadataShapePrecedesHeaderComparison() throws {+ let error = try rejection(input(envelope(capabilities: []),+ overrides: ["Mcp-Method": "tools/list"]))+ #expect(error.rpcCode == -32602)+ }++ @Test(arguments: ["roots", "sampling", "elicitation", "extensions", "experimental"])+ func knownCapabilitiesRequireObjects(field: String) throws {+ let error = try rejection(input(envelope(capabilities: [field: true])))+ #expect(error.rpcCode == -32602)+ }++ @Test func unknownExtensionMetadataAndEmptyCapabilitiesDoNotRequireOptionalFeatures() throws {+ var body = envelope()+ var params = try #require(body["params"] as? [String: Any])+ var meta = try #require(params["_meta"] as? [String: Any])+ meta["com.example/context"] = ["unknown": NSNull()]+ params["_meta"] = meta; body["params"] = params+ _ = try MCPModernValidator.validate(input(body), availability: availability)+ let second = try MCPModernValidator.validate(input(envelope(id: "fresh")),+ availability: availability)+ #expect(second.metadata.clientCapabilities == .object([]))+ }++ @Test(arguments: ["MCP-Protocol-Version", "Mcp-Method", "Mcp-Name"])+ func requiredHeaderMissingConflictingOrDuplicatedIsRejected(header: String) throws {+ let original = try input(envelope())+ let missing = MCPModernRequestInput(httpMethod: "POST",+ headers: original.headers.filter { $0.name != header }, body: original.body)+ #expect(try rejection(missing).rpcCode == -32020)+ #expect(try rejection(input(envelope(), overrides: [header: "mismatch"])).rpcCode == -32020)+ let duplicate = try input(envelope(), extra: [MCPModernHeader(name: header.lowercased(), value: "other")])+ #expect(try rejection(duplicate).rpcCode == -32020)+ }++ @Test func headerNamesAreCaseInsensitiveButValuesAreExact() throws {+ let original = try input(envelope())+ let lowered = MCPModernRequestInput(httpMethod: "POST", headers: original.headers.map {+ MCPModernHeader(name: $0.name.lowercased(), value: $0.value)+ }, body: original.body)+ _ = try MCPModernValidator.validate(lowered, availability: availability)+ #expect(try rejection(input(envelope(), overrides: ["Mcp-Method": "TOOLS/CALL"])).rpcCode == -32020)+ }++ @Test func matchingUnsupportedVersionReportsSupportedAndMismatchWins() throws {+ let error = try rejection(input(envelope(version: "2025-11-25"), version: "2025-11-25"))+ #expect(error.httpStatus == 400)+ #expect(error.rpcCode == -32022)+ guard case .object(let fields) = error.data else {+ Issue.record("Unsupported version must supply structured negotiation evidence")+ return+ }+ #expect(fields.first { $0.name == "requested" }?.value == .string("2025-11-25"))+ #expect(fields.first { $0.name == "supported" }?.value == .array([.string(version)]))+ let mismatch = try rejection(input(envelope(version: "2025-11-25")))+ #expect(mismatch.rpcCode == -32020)+ }++ @Test func base64NameDecodesUTF8AndRejectsMalformedTokens() throws {+ let name = "café"+ let encoded = "=?base64?" + Data(name.utf8).base64EncodedString() + "?="+ _ = try MCPModernValidator.validate(input(envelope(name: name), name: encoded), availability: availability)+ for invalid in ["=?base64?%%%?=", "=?base64?/w==?=", "=?base64?Y2Fmw6k=", name] {+ #expect(try rejection(input(envelope(name: name), name: invalid)).rpcCode == -32020)+ }+ }++ @Test(arguments: ["initialize", "ping", "resources/list", "unknown/method"])+ func unsupportedMethodsHaveNoLegacyDispatch(method: String) throws {+ let error = try rejection(input(envelope(method: method), method: method, name: nil))+ #expect(error.httpStatus == 404)+ #expect(error.rpcCode == -32601)+ }++ @Test func unavailableToolAndMalformedNameAreProtocolErrors() throws {+ #expect(try rejection(input(envelope(name: "disabled_tool"), name: "disabled_tool")).rpcCode == -32602)+ #expect(try rejection(input(envelope(name: 42))).rpcCode == -32602)+ }++ @Test func arraysNullAndInvalidIDsNeverBecomeDispatchableRequests() throws {+ let arrayError = try rejection(input([envelope(), envelope(id: "second")]))+ #expect(arrayError.rpcCode == -32600)+ #expect(arrayError.id == nil)+ for invalid: Any in [NSNull(), true, 1.5, ["nested": "id"]] {+ let error = try rejection(input(envelope(id: invalid)))+ #expect(error.httpStatus == 400)+ #expect(error.rpcCode == -32600)+ #expect(error.id == nil)+ }+ var wrongEnvelope = envelope(id: 9)+ wrongEnvelope["jsonrpc"] = "1.0"+ #expect(try rejection(input(wrongEnvelope)).id == .integer(9))+ }++ @Test func notificationsRejectWithoutFabricatedRPCResponse() throws {+ for method in ["tools/call", "notifications/initialized", "notifications/cancelled"] {+ var body = envelope(method: method)+ body.removeValue(forKey: "id")+ let error = try rejection(input(body, method: method, name: method == "tools/call" ? "query_tasks" : nil))+ #expect(error.httpStatus == 400)+ #expect(error.rpcCode == nil)+ #expect(error.id == nil)+ }+ }++ @Test func duplicateMetadataKeysAreNotSilentlyCollapsed() throws {+ let original = try input(envelope())+ let text = try #require(String(data: original.body, encoding: .utf8))+ let field = "\"io.modelcontextprotocol/protocolVersion\""+ let malformed = text.replacingOccurrences(of: field + ":\"2026-07-28\"",+ with: field + ":\"2026-07-28\"," + field + ":\"2025-11-25\"")+ #expect(malformed != text)+ let error = try rejection(MCPModernRequestInput(httpMethod: "POST", headers: original.headers,+ body: Data(malformed.utf8)))+ #expect(error.httpStatus == 400)+ #expect(error.rpcCode == -32700)+ }++ @Test func knownNestedCapabilityAndClientInfoShapesAreValidated() throws {+ for capabilities: Any in [["sampling": ["tools": true]], ["elicitation": ["form": []]],+ ["extensions": ["com.example/feature": false]]] {+ #expect(try rejection(input(envelope(capabilities: capabilities))).rpcCode == -32602)+ }+ var body = envelope()+ var params = try #require(body["params"] as? [String: Any])+ var meta = try #require(params["_meta"] as? [String: Any])+ meta["io.modelcontextprotocol/clientInfo"] = ["name": "fixture"]+ params["_meta"] = meta; body["params"] = params+ #expect(try rejection(input(body)).rpcCode == -32602)+ }++ @Test func deterministicHostileHeaderCorpusNeverProducesValidClassification() throws {+ // Enumerate rather than randomize so every hostile byte is reproducible.+ for byte in [UInt8(0), 10, 13, 31, 127, 128, 255] {+ let value = "query_tasks" + String(UnicodeScalar(byte))+ let error = try rejection(input(envelope(), name: value))+ #expect(error.httpStatus == 400)+ #expect(error.rpcCode == -32020)+ }+ }++ @Test func malformedJSONHasNoInventedID() throws {+ let original = try input(envelope())+ let error = try rejection(MCPModernRequestInput(httpMethod: "POST", headers: original.headers,+ body: Data("{invalid".utf8)))+ #expect(error.httpStatus == 400)+ #expect(error.rpcCode == -32700)+ #expect(error.id == nil)+ }++ @Test(arguments: ["GET", "DELETE", "PATCH"])+ func unsupportedHTTPMethodsCannotOpenLegacyStreams(method: String) throws {+ #expect(try rejection(input(envelope(), httpMethod: method)).httpStatus == 405)+ }++ @Test func contentAndAcceptNegotiationFailBeforeClassification() throws {+ #expect(try rejection(input(envelope(), overrides: ["Content-Type": "text/plain"])).httpStatus == 415)+ #expect(try rejection(input(envelope(), overrides: ["Accept": "text/html"])).httpStatus == 406)+ var body = envelope(method: "subscriptions/listen")+ var params = try #require(body["params"] as? [String: Any])+ params["notifications"] = ["toolsListChanged": true]; body["params"] = params+ #expect(try rejection(input(body, method: "subscriptions/listen", name: nil,+ overrides: ["Accept": "application/json"])).httpStatus == 406)+ }+}++extension MCPModernProtocolTests {+ // Supplemental boundary coverage added after the original declaration-stage RED.+ private func rawInput(id: String = "1", padding: String = "0") throws -> MCPModernRequestInput {+ let template = try input(envelope())+ let body = """+ {"jsonrpc":"2.0","id":\(id),"method":"tools/call","params":{+ "name":"query_tasks","arguments":{},"padding":\(padding),"_meta":{+ "io.modelcontextprotocol/protocolVersion":"2026-07-28",+ "io.modelcontextprotocol/clientCapabilities":{}}}}+ """+ return MCPModernRequestInput(httpMethod: "POST", headers: template.headers, body: Data(body.utf8))+ }++ @Test func numericIDsUseExactIntegralSemanticsWithinSignedIntResourceBound() throws {+ let cases: [(String, Int)] = [+ (String(Int.min), Int.min), (String(Int.max), Int.max),+ ("1.0", 1), ("1e0", 1), ("1000e-3", 1), ("0.01e2", 1),+ ("-1000.00e-2", -10), ("0e999999", 0), ("-0.000e-999999", 0)+ ]+ for (token, value) in cases {+ let request = try MCPModernValidator.validate(rawInput(id: token), availability: availability)+ #expect(request.id == .integer(value))+ }+ }++ @Test func outOfRangeAndNonIntegralNumericIDsNeverBecomeDispatchable() throws {+ for token in ["9223372036854775808", "-9223372036854775809", "1e999999", "1.5", "1e-1"] {+ let error = try rejection(rawInput(id: token))+ #expect(error.httpStatus == 400)+ #expect(error.rpcCode == -32600)+ #expect(error.id == nil)+ #expect(error.message.contains("use a string ID"))+ }+ #expect(try rejection(rawInput(id: "true")).rpcCode == -32600)+ }++ @Test func validJSONDepthLimitIsDistinctFromParseFailure() throws {+ // Root and params consume two containers; thirty arrays reaches exactly 32.+ let atLimit = String(repeating: "[", count: 30) + "0" + String(repeating: "]", count: 30)+ _ = try MCPModernValidator.validate(rawInput(padding: atLimit), availability: availability)+ let beyondLimit = "[" + atLimit + "]"+ let error = try rejection(rawInput(padding: beyondLimit))+ #expect(error.httpStatus == 400)+ #expect(error.rpcCode == -32600)+ #expect(error.message.contains("32-container nesting resource limit"))+ #expect(error.id == nil)+ }++ @Test func bodyAndWidthBoundsAreIndependentOfNestingLimit() throws {+ let wide = "{" + (0..<128).map { "\"field\($0)\":0" }.joined(separator: ",") + "}"+ _ = try MCPModernValidator.validate(rawInput(padding: wide), availability: availability)+ let original = try rawInput()+ var oversized = Data(repeating: 0x20, count: 1_048_576)+ oversized.append(original.body)+ let error = try rejection(MCPModernRequestInput(httpMethod: "POST", headers: original.headers,+ body: oversized))+ #expect(error.httpStatus == 413)+ }++}++// Critic supplemental RED: the production validator remains at 3cfd28a.+extension MCPModernProtocolTests {+ private func subscriptionInput(_ filters: [String: Any]) throws -> MCPModernRequestInput {+ var body = envelope(method: "subscriptions/listen")+ var params = try #require(body["params"] as? [String: Any])+ params["notifications"] = filters+ body["params"] = params+ return try input(body, method: "subscriptions/listen", name: nil)+ }++ @Test func validUnsupportedResourceSubscriptionsDoNotRejectMixedFilters() throws {+ let request = try MCPModernValidator.validate(subscriptionInput([+ "toolsListChanged": true, "resourcesListChanged": true,+ "resourceSubscriptions": ["file:///synthetic/one", "file:///synthetic/two"]+ ]), availability: availability)+ guard case .listenSubscriptions = request.method else {+ Issue.record("Expected subscription classification")+ return+ }+ // A future stream acknowledges only toolsListChanged; unsupported valid+ // filters must survive protocol validation without acquiring resources.+ #expect(request.params != nil)+ }++ @Test func malformedResourceSubscriptionsStillRejectBeforeDispatch() throws {+ for invalid: Any in ["file:///synthetic/one", [true], ["valid", NSNull()]] {+ let error = try rejection(subscriptionInput(["toolsListChanged": true,+ "resourceSubscriptions": invalid]))+ #expect(error.httpStatus == 400)+ #expect(error.rpcCode == -32602)+ }+ }++ private func classifySyntheticName(_ name: String, header: String) throws -> MCPModernRequest {+ let available = MCPModernAvailability(tools: [+ MCPModernAvailableTool(name: name, execution: .ordinaryRead)+ ])+ return try MCPModernValidator.validate(input(envelope(name: name), name: header), availability: available)+ }++ private func encodedName(_ name: String) -> String {+ "=?base64?" + Data(name.utf8).base64EncodedString() + "?="+ }++ @Test func paddedPlainNamesRequireEncodingEvenWhenTheyMatchBody() throws {+ for name in [" padded", "padded ", " padded "] {+ #expect(throws: MCPModernRejection.self) {+ _ = try classifySyntheticName(name, header: name)+ }+ let request = try classifySyntheticName(name, header: encodedName(name))+ guard case .callTool(let actual, .ordinaryRead) = request.method else {+ Issue.record("Expected synthetic name classification")+ continue+ }+ #expect(actual.utf8.elementsEqual(name.utf8))+ }+ }++ @Test func sentinelRequiresBothExactMarkersAndLiteralSentinelIsOuterEncoded() throws {+ for name in ["=?base64?prefix-only", "suffix-only?=", "=?BASE64?literal?="] {+ _ = try classifySyntheticName(name, header: name)+ }+ let literal = "=?base64?YQ==?="+ _ = try classifySyntheticName(literal, header: encodedName(literal))+ #expect(throws: MCPModernRejection.self) {+ _ = try classifySyntheticName(literal, header: literal)+ }+ }+}++#endif
diff --git a/Transit/TransitTests/MCPModernReadBoundaryTests.swift b/Transit/TransitTests/MCPModernReadBoundaryTests.swiftnew file mode 100644index 0000000..5e20ad9--- /dev/null+++ b/Transit/TransitTests/MCPModernReadBoundaryTests.swift@@ -0,0 +1,177 @@+#if os(macOS)+import Foundation+import NIOConcurrencyHelpers+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPModernReadBoundaryTests {+ @Test func actualPagedServiceCallsPrivatePreparerBeforeAnyReservation() async throws {+ let models = try makeModelsWithTwoTasks()+ let snapshots = MCPTaskQuerySnapshotStore()+ let count = NIOLockedValueBox(0)+ let service = MCPReadService(source: MCPReadCaptureBuilder(container: models.container,+ fence: .actorOnlyTestFixture), monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil),+ snapshots: snapshots, pagePreparer: { pages, tool, operation in+ count.withLockedValue { $0 += 1 }+ #expect(pages.count == 2 && tool == "query_tasks" && operation.shouldContinue())+ throw MCPReadCaptureError.serializationFailure+ })+ let coordinator = MCPReadCoordinator(domain: snapshots.domain)+ let output = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { operation in+ do {+ let result = try await service.prepare(tool: "query_tasks", arguments: [+ "limit": 1, "detailLevel": "full", "includeComments": false, "readPolicy": "cached"+ ], operation: operation)+ return await MainActor.run {+ defer { snapshots.domain.withLock {+ for publication in result.publications { publication.discardLocked(in: snapshots.domain) }+ } }+ #expect(count.withLockedValue { $0 } == 1)+ #expect(result.publications.isEmpty)+ guard case .some(.failure(let failure)) = result.result.metadata?.read else {+ Issue.record("Private whole-page encoder fault escaped as a capture success")+ return Self.response(Data("failed".utf8))+ }+ #expect(failure.category == .serializationFailure)+ do {+ let accounting = try snapshots.domain.accounting(for: snapshots.publicationStoreID)+ #expect(accounting.pendingBytes == 0)+ } catch {+ Issue.record("Private-page accounting failed: \(error)")+ return Self.response(Data("failed".utf8))+ }+ return Self.response(Data("failed-whole".utf8))+ }+ } catch {+ Issue.record("Actual paged service unexpectedly threw: \(error)")+ return Self.response(Data("failed".utf8))+ }+ }+ #expect(output == Data("failed-whole".utf8))+ for _ in 0..<100 where coordinator.unfinishedCount != 0 { try? await Task.sleep(for: .milliseconds(5)) }+ #expect(coordinator.unfinishedCount == 0 && snapshots.retainedBytes == 0)+ }++ @Test func explicitMissingSelectorAndStorageFaultNeverProducePrivatePages() throws {+ let models = try TestModelContainer()+ let store = MCPTaskQuerySnapshotStore()+ let source = MCPReadCaptureBuilder(container: models.container, fence: .actorOnlyTestFixture)+ #expect(throws: MCPReadCaptureError.projectNotFound) {+ try source.capture(ReadCaptureRequest(projectSelectors: [.name("Absent")], selection: .portfolio,+ completeness: .completePortfolio, includeComments: false))+ }+ let failing = MCPReadCaptureBuilder(container: models.container, fence: .actorOnlyTestFixture,+ fetchTasks: { _ in throw StorageFault.unavailable })+ #expect(throws: MCPReadCaptureError.storageFailure) {+ try failing.capture(ReadCaptureRequest(projectSelectors: nil, selection: .portfolio,+ completeness: .completePortfolio, includeComments: false))+ }+ #expect(store.retainedBytes == 0)+ }++ @Test func stopInsidePrivatePreparationPropagatesOriginalCancellationWithoutPublication() async throws {+ let models = try TestModelContainer()+ let store = MCPTaskQuerySnapshotStore()+ let coordinator = MCPReadCoordinator(domain: store.domain)+ let service = MCPReadService(source: MCPReadCaptureBuilder(container: models.container,+ fence: .actorOnlyTestFixture), monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil),+ snapshots: store, pagePreparer: { _, tool, operation in+ let page = try MCPResultPreparation.page(request: MCPResultPagePreparationRequest(text: "[]",+ isError: nil, origin: .generatedJSON, evidence: .established,+ context: MCPResultContext(tool: tool, semanticFailure: nil,+ mutationRecovery: nil, entityPositions: []), metadataOwner: nil)) {+ guard operation.shouldContinue() else { throw CancellationError() }+ }+ coordinator.stop()+ return [page]+ })+ let output = await coordinator.execute(timeout: Data("stopped".utf8), busy: Data("busy".utf8)) { operation in+ await MainActor.run {+ do {+ let read = try MCPPreparedToolRead(text: "[]")+ #expect(throws: CancellationError.self) {+ try service.preparePrivatePages([read], tool: "query_tasks", operation: operation)+ }+ } catch { Issue.record("Cancellation fixture setup failed: \(error)") }+ return Self.response(Data("must-not-deliver".utf8))+ }+ }+ #expect(output == Data("stopped".utf8))+ #expect(store.retainedBytes == 0)+ for _ in 0..<100 where coordinator.unfinishedCount != 0 { try? await Task.sleep(for: .milliseconds(5)) }+ #expect(coordinator.unfinishedCount == 0)+ }++ @Test func expiredPublicationSelectsReadyWholeModernFailureAndDiscardsAllOwners() async throws {+ let instant = ContinuousClock.now+ let domain = MCPReadPublicationDomain(testingInstant: instant)+ let store = MCPTaskQuerySnapshotStore(now: { instant }, domain: domain)+ let coordinator = MCPReadCoordinator(domain: domain)+ let errors = try failureBytes("QUERY_EXPIRED")+ let timeout = try failureBytes("READ_TIMEOUT")+ let busy = try failureBytes("READ_BUSY")+ let output = await coordinator.execute(timeout: timeout, busy: busy) { operation in+ await MainActor.run {+ do {+ let pages = try ["[]", "null"].map { text in+ try MCPResultPreparation.page(request: MCPResultPagePreparationRequest(text: text,+ isError: nil, origin: .generatedJSON, evidence: .established,+ context: MCPResultContext(tool: "query_tasks", semanticFailure: nil,+ mutationRecovery: nil, entityPositions: []), metadataOwner: nil))+ }+ let bundle = try MCPResultPreparation.prepare(pages: pages, budget: MCPResultRetentionBudget(+ store: .ordinary, originalCaptureIndexBytes: 0, visibleBytes: 0, pendingBytes: 0))+ let reservation = try #require(try store.prepare(preparedBundle: bundle,+ cursors: [UUID().uuidString], deadline: instant + .milliseconds(200),+ operationID: operation.id, metadataBytes: nil, policy: .cached))+ let bytes = try MCPResultEncoder.encode(fragment: pages[0].fragment, id: .integer(16))+ // A root near its original expiry can expire during a still-admitted read.+ domain.setTestingInstant(instant + .milliseconds(201))+ #expect(operation.shouldContinue())+ return PreparedReadResult(encodedResponse: bytes, publications: [reservation],+ publicationErrors: .init(busy: busy, expired: errors, capacity: errors))+ } catch {+ Issue.record("Modern offered-page preparation failed: \(error)")+ return Self.response(Data("failed".utf8))+ }+ }+ }+ #expect(output == errors)+ #expect(output != timeout && output != busy)+ #expect(try domain.accounting(for: store.publicationStoreID).visibleBytes == 0)+ #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+ for _ in 0..<100 where coordinator.unfinishedCount != 0 { try? await Task.sleep(for: .milliseconds(5)) }+ #expect(coordinator.unfinishedCount == 0)+ }++ nonisolated private static func response(_ bytes: Data) -> PreparedReadResult {+ PreparedReadResult(encodedResponse: bytes, publications: [],+ publicationErrors: .init(busy: Data(), expired: Data(), capacity: Data()))+ }++ private func failureBytes(_ code: String) throws -> Data {+ let source = try MCPResultAdapter.source(text: "{\"error\":{\"code\":\"\(code)\"}}",+ isError: true, origin: .generatedJSON, evidence: .established)+ let context = MCPResultContext(tool: "query_tasks", semanticFailure: nil,+ mutationRecovery: nil, entityPositions: [])+ return try MCPResultEncoder.encode(source: source, presentation: MCPResultAdapter.present(source,+ context: context), id: .integer(16), metadata: nil)+ }++ private func makeModelsWithTwoTasks() throws -> TestModelContainer {+ let models = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ models.context.insert(project)+ for index in 1...2 {+ models.context.insert(TransitTask(name: "Saved \(index)", type: .feature, project: project,+ displayID: .permanent(index)))+ }+ try models.context.save()+ return models+ }++ private enum StorageFault: Error { case unavailable }+}+#endif
diff --git a/Transit/TransitTests/MCPModernReadPagePreparationTests.swift b/Transit/TransitTests/MCPModernReadPagePreparationTests.swiftnew file mode 100644index 0000000..4152eec--- /dev/null+++ b/Transit/TransitTests/MCPModernReadPagePreparationTests.swift@@ -0,0 +1,127 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++/// Value-side task16 RED. Actual retained-store publication needs the owner bindings.+@MainActor @Suite(.serialized)+struct MCPModernReadPagePreparationTests {+ @Test func everyPrivatePageSharesFrozenCaptureOwnerAndExactText() async {+ await withOperation { operation in+ let texts = [#"{"future":-0.00E+0,"flag":false,"nullable":null}"#, "[]", "null"]+ let reads = try texts.map { try MCPPreparedToolRead(text: $0, metadata: .capture(Self.capture)) }+ let pages = try MCPModernProviderBinding.prepareReadPages(reads, tool: "query_tasks", operation: operation)+ try #require(pages.count == reads.count)+ let first = try #require(pages.first)+ let metadata = try #require(first.metadataOwner)+ for (index, page) in pages.enumerated() {+ #expect(page.source.originalText.utf8.elementsEqual(texts[index].utf8))+ #expect(page.source.document?.originalUTF8 == Data(texts[index].utf8))+ #expect(page.metadataOwner === metadata)+ #expect(page.fragment.encodedResult.range(of: try #require(reads[index].frozenMetadataBytes)) != nil)+ }+ }+ }++ @Test func malformedGeneratedLaterPageFailsWholePreparation() async {+ await withOperation { operation in+ let reads = try ["[]", "{broken"].map { try MCPPreparedToolRead(text: $0) }+ #expect(throws: MCPResultBoundaryError.invalidJSON) {+ try MCPModernProviderBinding.prepareReadPages(reads, tool: "query_tasks", operation: operation)+ }+ }+ }++ @Test func generatedFailureKeepsFlagCategoryAndOriginalMetadata() async {+ await withOperation { operation in+ let read = try MCPPreparedToolRead(text: #"{"error":{"code":"READ_BUSY","message":"busy"}}"#,+ isError: true, metadata: .failure(ReadFailureMetadata(requestId: "original-request",+ category: .busy, read: ReadExecutionMetadata(policy: .cached,+ refreshOutcome: .notRequested, budgetMs: 5_000))))+ let pages = try MCPModernProviderBinding.prepareReadPages([read], tool: "query_tasks", operation: operation)+ let page = try #require(pages.first)+ #expect(page.source.originalIsError == true)+ #expect(page.presentation.errorCategory == .admissionBusy)+ #expect(page.fragment.encodedResult.range(of: try #require(read.frozenMetadataBytes)) != nil)+ }+ }++ @Test func attachedOwnerSurvivesBothCarrierAttachingPaths() throws {+ let page = try Self.page(#"{"saved":true}"#)+ let read = try MCPPreparedToolRead(text: "[]").attachingPreparedResultPage(page).attaching([])+ #expect(read.preparedResultPage === page)+ #expect(read.result.content.first?.text == "[]")+ #expect(read.encodedToolResult == (try MCPPreparedToolRead(text: "[]")).encodedToolResult)+ }++ @Test func attachedFrozenFragmentRewrapsNewIDsWithoutLegacyReparse() async {+ await withOperation { operation in+ // An intentionally unusable legacy text distinguishes carrier consumption+ // from parsing/reclassifying the immutable saved owner a second time.+ let page = try Self.page(#"{"future":1E+9999,"nullable":null}"#)+ let read = try MCPPreparedToolRead(text: "unusable legacy text")+ .attachingPreparedResultPage(page).attaching([])+ for id in [JSONRPCId.string("first"), .integer(2383)] {+ let actual = try MCPModernProviderBinding.read(read, id: id, tool: "query_tasks", operation: operation)+ let expected = try MCPResultEncoder.encode(fragment: page.fragment, id: id)+ #expect(actual == expected)+ }+ }+ }++ @Test func expiredOriginalOperationRejectsPreparationWithoutNewBudget() async throws {+ let saved = OperationCapture()+ await withOperation { operation in saved.operation = operation }+ let operation = try #require(saved.operation)+ let read = try MCPPreparedToolRead(text: "[]")+ #expect(!operation.shouldContinue())+ #expect(throws: CancellationError.self) {+ try MCPModernProviderBinding.prepareReadPages([read], tool: "query_tasks", operation: operation)+ }+ }++ private func withOperation(_ body: @escaping @MainActor @Sendable (MCPReadOperation) throws -> Void) async {+ let coordinator = MCPReadCoordinator()+ let bytes = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { operation in+ await MainActor.run {+ do {+ try body(operation)+ return Self.result(Data("completed".utf8))+ } catch {+ Issue.record("Modern private-page preparation failed: \(error)")+ return Self.result(Data("failed".utf8))+ }+ }+ }+ #expect(bytes == Data("completed".utf8))+ for _ in 0..<100 where coordinator.unfinishedCount != 0 {+ try? await Task.sleep(for: .milliseconds(5))+ }+ #expect(coordinator.unfinishedCount == 0)+ }++ private static func page(_ text: String) throws -> MCPResultPreparedPage {+ try MCPResultPreparation.page(request: MCPResultPagePreparationRequest(text: text, isError: nil,+ origin: .generatedJSON, evidence: .established,+ context: MCPResultContext(tool: "query_tasks", semanticFailure: nil,+ mutationRecovery: nil, entityPositions: []), metadataOwner: nil))+ }++ private static var capture: ReadCaptureMetadata {+ ReadCaptureMetadata(asOf: "2026-10-04T09:00:00.000Z", snapshotId: "original-capture",+ freshness: ReadFreshness(syncState: .inactive, assessment: .notApplicable,+ assessedAt: "2026-10-04T09:00:00.000Z", lastImportedAt: nil,+ evidence: .none, recentImportThresholdMs: 60_000),+ read: ReadExecutionMetadata(policy: .cached, refreshOutcome: .notRequested, budgetMs: 5_000))+ }++ nonisolated private static func result(_ bytes: Data) -> PreparedReadResult {+ PreparedReadResult(encodedResponse: bytes, publications: [],+ publicationErrors: .init(busy: Data(), expired: Data(), capacity: Data()))+ }++ private final class OperationCapture {+ var operation: MCPReadOperation?+ }+}+#endif
diff --git a/Transit/TransitTests/MCPModernReadinessFixture.swift b/Transit/TransitTests/MCPModernReadinessFixture.swiftnew file mode 100644index 0000000..7fe0303--- /dev/null+++ b/Transit/TransitTests/MCPModernReadinessFixture.swift@@ -0,0 +1,183 @@+#if os(macOS)+import Foundation+import HTTPTypes+import Hummingbird+import NIOConcurrencyHelpers+import ServiceLifecycle+import SwiftData+import Testing+@testable import Transit++nonisolated enum MCPReadinessFixtureError: Error { case unsafeEndpoint, invalidTrace }+@MainActor enum MCPModernReadinessFixture {+ static func validateEndpoint(_ endpoint: URL) throws {+ guard endpoint.scheme == "http", endpoint.host == "127.0.0.1", let port = endpoint.port,+ port > 1024, port != MCPSettings.defaultPort, endpoint.path == "/mcp",+ endpoint.user == nil, endpoint.password == nil, endpoint.query == nil, endpoint.fragment == nil else {+ throw MCPReadinessFixtureError.unsafeEndpoint+ }+ }++ static func capture() async throws -> [String: Any] {+ let env = try MCPModernResultFixture.makeEnvWithReads()+ let project = MCPTestHelpers.makeProject(in: env.context)+ _ = try await env.taskService.createTask(name: "Synthetic readiness record", description: nil,+ type: .feature, project: project)+ let boundPort = NIOLockedValueBox<Int?>(nil)+ let underlying = MCPServer.makeRouter(handler: env.handler).buildResponder()+ let allowedNames = ["query_tasks", "get_projects"].flatMap {+ [$0, "=?base64?" + Data($0.utf8).base64EncodedString() + "?="]+ }+ let responder = CallbackResponder<MCPRequestContext> { request, context in+ // Mirrored header and body must match in the actual validator. A forged read header+ // cannot authorize a write; its body is rejected by that validator before effects.+ if request.head.headerFields[HTTPField.Name("Mcp-Method")!] == "tools/call",+ !allowedNames.contains(request.head.headerFields[HTTPField.Name("Mcp-Name")!] ?? "") {+ return Response(status: .forbidden)+ }+ return try await underlying.respond(to: request, context: context)+ }+ let app = Application(responder: responder,+ configuration: .init(address: .hostname("127.0.0.1", port: 0)),+ onServerRunning: { channel in boundPort.withLockedValue { $0 = channel.localAddress?.port } })+ let configuration = MCPServerLifecycleConfiguration.make(services: [app], logger: app.logger)+ let group = ServiceGroup(configuration: configuration)+ let listener = Task.detached { try await group.run() }+ do {+ let cutoff = ContinuousClock.now.advanced(by: .seconds(5))+ while boundPort.withLockedValue({ $0 }) == nil && ContinuousClock.now < cutoff {+ try await Task.sleep(for: .milliseconds(10))+ }+ let port = try #require(boundPort.withLockedValue { $0 })+ let endpoint = try #require(URL(string: "http://127.0.0.1:\(port)/mcp"))+ try validateEndpoint(endpoint)+ let descriptor = try exportDescriptor(endpoint)+ let trace = try await collect(endpoint: endpoint, env: env, group: group, descriptor: descriptor)+ await group.triggerGracefulShutdown()+ try await listener.value+ return trace+ } catch {+ env.handler.finishToolListChangeSessions()+ await group.triggerGracefulShutdown()+ _ = try? await listener.value+ throw error+ }+ }++ private static func exportDescriptor(_ endpoint: URL) throws -> URL {+ let requestedHold = ProcessInfo.processInfo.environment["TRANSIT_READINESS_HOLD_SECONDS"] ?? "0"+ let hold = min(120, max(0, Int(requestedHold) ?? 0))+ let descriptor: [String: Any] = ["formatVersion": 1, "endpoint": endpoint.absoluteString,+ "synthetic": true, "persistentStore": false, "allowedTools": ["query_tasks", "get_projects"],+ "catalog": "Actual full catalog; all other tool calls denied before dispatch",+ "bundleID": "me.nore.ig.Transit.development", "holdSeconds": hold,+ "shutdown": "Graceful shutdown after ACK and bounded hold; fixture listener only"]+ let path = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + "-endpoint.json")+ try JSONSerialization.data(withJSONObject: descriptor, options: [.sortedKeys]).write(to: path)+ print("T2383_MODERN_READINESS_ENDPOINT=\(path.path)")+ return path+ }++ private static func collect(endpoint: URL, env: MCPTestEnv, group: ServiceGroup,+ descriptor: URL) async throws -> [String: Any] {+ let config = URLSessionConfiguration.ephemeral+ let requestedHold = ProcessInfo.processInfo.environment["TRANSIT_READINESS_HOLD_SECONDS"] ?? "0"+ let hold = min(120, max(0, Int(requestedHold) ?? 0))+ config.timeoutIntervalForRequest = Double(hold + 10)+ config.timeoutIntervalForResource = Double(hold + 15)+ let session = URLSession(configuration: config)+ defer { session.invalidateAndCancel() }+ var exchanges = [[String: Any]]()+ exchanges.append(try await exchange(session, endpoint, kind: "discovery",+ method: "server/discover", id: "discover"))+ exchanges.append(try await exchange(session, endpoint, kind: "list", method: "tools/list", id: 2))+ exchanges.append(try await exchange(session, endpoint, kind: "read", method: "tools/call", id: "read",+ params: ["name": "query_tasks", "arguments": ["detailLevel": "full", "includeComments": false,+ "limit": 1, "readPolicy": "cached"]]))+ exchanges.append(try await exchange(session, endpoint, kind: "wrong-version", method: "server/discover",+ id: 4, version: "2025-03-26"))+ exchanges.append(try await exchange(session, endpoint, kind: "legacy-method", method: "initialize", id: 5))+ exchanges.append(try await exchange(session, endpoint, kind: "notification", method: "tools/list", id: nil))+ let deniedWrite = try await exchange(session, endpoint, kind: "denied-write", method: "tools/call", id: 6,+ params: ["name": "create_project", "arguments": ["name": "Forbidden fixture mutation",+ "colorHex": "#123456", "idempotencyKey": "readiness-denied-write"]])+ try #require(deniedWrite["status"] as? Int == 403)+ let read = try #require(exchanges[2]["response"] as? [String: Any])+ let result = try #require(read["result"] as? [String: Any])+ let structured = try #require(result["structuredContent"] as? [String: Any])+ let subscription = try await subscription(session, endpoint: endpoint, group: group, env: env)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0)+ return ["formatVersion": 1, "synthetic": true, "persistentStore": false,+ "endpoint": endpoint.absoluteString, "descriptorPath": descriptor.path, "endpointClosed": true,+ "exchanges": exchanges, "writeDenied": deniedWrite, "structuredConsumption": structured,+ "subscriptionRequest": ["id": "readiness-subscription", "notifications": ["toolsListChanged": true]],+ "subscriptionFrames": subscription.frames, "sessionHeader": subscription.sessionHeader ?? NSNull(),+ "eventIDs": subscription.eventIDs,+ "provenance": ["producer": "actual-app-test", "bundleID": "me.nore.ig.Transit.development",+ "path": "Actual app router/validator/encoder over separate loopback URLSession"]]+ }++ private static func request(_ endpoint: URL, method: String, id: Any?, params: [String: Any] = [:],+ version: String = "2026-07-28",+ accept: String = "application/json") throws -> URLRequest {+ var metadata = MCPModernResultFixture.meta+ metadata["io.modelcontextprotocol/protocolVersion"] = version+ var parameters = params; parameters["_meta"] = metadata+ var object: [String: Any] = ["jsonrpc": "2.0", "method": method, "params": parameters]+ if let id { object["id"] = id }+ var request = URLRequest(url: endpoint); request.httpMethod = "POST"+ request.timeoutInterval = 5+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")+ request.setValue(accept, forHTTPHeaderField: "Accept")+ request.setValue(version, forHTTPHeaderField: "MCP-Protocol-Version")+ request.setValue(method, forHTTPHeaderField: "Mcp-Method")+ if let tool = params["name"] as? String { request.setValue(tool, forHTTPHeaderField: "Mcp-Name") }+ request.httpBody = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])+ return request+ }++ private static func exchange(_ session: URLSession, _ endpoint: URL, kind: String, method: String,+ id: Any?, params: [String: Any] = [:], version: String = "2026-07-28") async throws+ -> [String: Any] {+ let outgoing = try request(endpoint, method: method, id: id, params: params, version: version)+ let (data, response) = try await session.data(for: outgoing)+ let http = try #require(response as? HTTPURLResponse)+ let body: Any = data.isEmpty ? NSNull() : try JSONSerialization.jsonObject(with: data)+ return ["kind": kind, "request": try JSONSerialization.jsonObject(with: try #require(outgoing.httpBody)),+ "headers": outgoing.allHTTPHeaderFields ?? [:], "status": http.statusCode, "response": body]+ }++ private struct SubscriptionEvidence {+ let frames: [[String: Any]]+ let sessionHeader: String?+ let eventIDs: [String]+ }++ private static func subscription(_ session: URLSession, endpoint: URL, group: ServiceGroup,+ env: MCPTestEnv) async throws -> SubscriptionEvidence {+ var outgoing = try request(endpoint, method: "subscriptions/listen", id: "readiness-subscription",+ params: ["notifications": ["toolsListChanged": true]], accept: "text/event-stream")+ let requestedHold = ProcessInfo.processInfo.environment["TRANSIT_READINESS_HOLD_SECONDS"] ?? "0"+ outgoing.timeoutInterval = Double(min(120, max(0, Int(requestedHold) ?? 0)) + 10)+ let (bytes, response) = try await session.bytes(for: outgoing)+ let http = try #require(response as? HTTPURLResponse); try #require(http.statusCode == 200)+ var frames = [[String: Any]](); var eventIDs = [String]()+ for try await line in bytes.lines {+ if line.hasPrefix("id:") { eventIDs.append(line) }+ if line.hasPrefix("data:") {+ let data = Data(line.dropFirst(5).trimmingCharacters(in: .whitespaces).utf8)+ frames.append(try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]))+ if frames.count == 1 {+ let requestedHold = ProcessInfo.processInfo.environment["TRANSIT_READINESS_HOLD_SECONDS"] ?? "0"+ let hold = min(120, max(0, Int(requestedHold) ?? 0))+ if hold > 0 { try await Task.sleep(for: .seconds(hold)) }+ env.handler.finishToolListChangeSessions()+ await group.triggerGracefulShutdown()+ }+ }+ }+ return SubscriptionEvidence(frames: frames,+ sessionHeader: http.value(forHTTPHeaderField: "Mcp-Session-Id"), eventIDs: eventIDs)+ }+}+#endif
diff --git a/Transit/TransitTests/MCPModernReadinessTests.swift b/Transit/TransitTests/MCPModernReadinessTests.swiftnew file mode 100644index 0000000..e5c7ea2--- /dev/null+++ b/Transit/TransitTests/MCPModernReadinessTests.swift@@ -0,0 +1,108 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++/// Separate synthetic fixture, never the installed listener or a persistent store.+@MainActor @Suite(.serialized)+struct MCPModernReadinessTests {+ @Test func isolatedLoopbackNegotiatesDiscoveryListReadAndSubscription() async throws {+ let trace = try await MCPModernReadinessFixture.capture()+ try assertNegotiation(trace)+ try #require(trace["synthetic"] as? Bool == true)+ try #require(trace["persistentStore"] as? Bool == false)+ let exchanges = try #require(trace["exchanges"] as? [[String: Any]])+ try #require(exchanges.count == 6)+ #expect(exchanges.compactMap { $0["kind"] as? String } == [+ "discovery", "list", "read", "wrong-version", "legacy-method", "notification"+ ])+ let discovery = try #require(exchanges[0]["response"] as? [String: Any])+ let discoveryResult = try #require(discovery["result"] as? [String: Any])+ #expect(discoveryResult["supportedVersions"] as? [String] == ["2026-07-28"])+ let listed = try #require(exchanges[1]["response"] as? [String: Any])+ let listedResult = try #require(listed["result"] as? [String: Any])+ let tools = try #require(listedResult["tools"] as? [[String: Any]])+ #expect(tools.contains { $0["name"] as? String == "query_tasks" && $0["outputSchema"] != nil })+ let read = try #require(exchanges[2]["response"] as? [String: Any])+ let result = try #require(read["result"] as? [String: Any])+ let structured = try #require(result["structuredContent"] as? [String: Any])+ #expect(structured["contractVersion"] as? Int == 1)+ #expect(structured["source"] != nil && structured["presentation"] != nil)+ for negative in exchanges.suffix(3) {+ #expect((negative["status"] as? Int ?? 0) >= 400)+ }+ let frames = try #require(trace["subscriptionFrames"] as? [[String: Any]])+ try #require(frames.count == 2)+ #expect(frames[0]["method"] as? String == "notifications/subscriptions/acknowledged")+ #expect((frames[0]["params"] as? [String: Any])?["notifications"] as? [String: Bool]+ == ["toolsListChanged": true])+ #expect((frames[1]["result"] as? [String: Any])?["resultType"] as? String == "complete")+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ let file = directory.appendingPathComponent("modern-readiness-trace.json")+ try JSONSerialization.data(withJSONObject: trace, options: [.sortedKeys]).write(to: file)+ print("T2383_MODERN_READINESS_EXPORT=\(file.path)")+ }++ private func assertNegotiation(_ trace: [String: Any]) throws {+ let exchanges = try #require(trace["exchanges"] as? [[String: Any]])+ for exchange in exchanges.prefix(3) {+ let request = try #require(exchange["request"] as? [String: Any])+ let response = try #require(exchange["response"] as? [String: Any])+ let headers = try #require(exchange["headers"] as? [String: String])+ let params = try #require(request["params"] as? [String: Any])+ let meta = try #require(params["_meta"] as? [String: Any])+ #expect(meta["io.modelcontextprotocol/protocolVersion"] as? String == "2026-07-28")+ #expect(meta["io.modelcontextprotocol/clientCapabilities"] is [String: Any])+ #expect(headers["MCP-Protocol-Version"] == "2026-07-28")+ #expect(headers["Mcp-Method"] == request["method"] as? String)+ #expect(response["jsonrpc"] as? String == "2.0")+ #expect(exchange["status"] as? Int == 200)+ if request["method"] as? String == "tools/call" { #expect(headers["Mcp-Name"] == "query_tasks") }+ let requestValue = try #require(request["id"])+ let responseValue = try #require(response["id"])+ let requestedID = try JSONSerialization.data(withJSONObject: requestValue, options: [.fragmentsAllowed])+ let responseID = try JSONSerialization.data(withJSONObject: responseValue, options: [.fragmentsAllowed])+ #expect(requestedID == responseID)+ }+ let read = try #require(exchanges[2]["response"] as? [String: Any])+ let result = try #require(read["result"] as? [String: Any])+ let structured = try #require(result["structuredContent"] as? [String: Any])+ let consumed = try #require(trace["structuredConsumption"] as? [String: Any])+ let source = try #require(structured["source"] as? NSDictionary)+ let consumedSource = try #require(consumed["source"])+ #expect(source.isEqual(consumedSource))+ let frames = try #require(trace["subscriptionFrames"] as? [[String: Any]])+ try #require(frames.count == 2)+ let subscription = try #require(trace["subscriptionRequest"] as? [String: Any])+ let subscriptionID = try #require(subscription["id"] as? String)+ let ackParams = try #require(frames[0]["params"] as? [String: Any])+ let ackMeta = try #require(ackParams["_meta"] as? [String: Any])+ let completion = try #require(frames[1]["result"] as? [String: Any])+ let completionMeta = try #require(completion["_meta"] as? [String: Any])+ #expect(ackMeta["io.modelcontextprotocol/subscriptionId"] as? String == subscriptionID)+ #expect(completionMeta["io.modelcontextprotocol/subscriptionId"] as? String == subscriptionID)+ #expect(frames[1]["id"] as? String == subscriptionID)+ #expect(trace["eventIDs"] as? [String] == [])+ #expect(trace["sessionHeader"] is NSNull)+ let discovery = try #require(exchanges[0]["response"] as? [String: Any])+ let discoveryResult = try #require(discovery["result"] as? [String: Any])+ let meta = try #require(discoveryResult["_meta"] as? [String: Any])+ let identity = try #require(meta["io.modelcontextprotocol/serverInfo"] as? [String: Any])+ #expect(identity["name"] as? String == "transit")+ #expect(discoveryResult["capabilities"] != nil)+ }++ @Test func fixtureRefusesProductionAndNonLoopbackEndpoints() throws {+ for endpoint in ["http://127.0.0.1:3141/mcp", "http://example.com:9876/mcp",+ "https://127.0.0.1:9876/mcp", "http://127.0.0.1:9876/other",+ "http://user@127.0.0.1:9876/mcp", "http://127.0.0.1:9876/mcp?alias=1",+ "http://127.0.0.1:9876/mcp#alias"] {+ #expect(throws: MCPReadinessFixtureError.unsafeEndpoint) {+ try MCPModernReadinessFixture.validateEndpoint(URL(string: endpoint)!)+ }+ }+ }+}++#endif
diff --git a/Transit/TransitTests/MCPModernResultFixture.swift b/Transit/TransitTests/MCPModernResultFixture.swiftnew file mode 100644index 0000000..eee56d3--- /dev/null+++ b/Transit/TransitTests/MCPModernResultFixture.swift@@ -0,0 +1,179 @@+#if os(macOS)+import Foundation+import HTTPTypes+import Hummingbird+import Logging+import NIOConcurrencyHelpers+import NIOCore+import NIOEmbedded+import NIOFoundationCompat+import SwiftData+import Testing+@testable import Transit++/// App-test-owned in-memory providers; no production store, listener or client activation.+@MainActor enum MCPModernResultFixture {+ static let meta: [String: Any] = [+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",+ "io.modelcontextprotocol/clientCapabilities": [:] as [String: Any]+ ]++ static func makeEnvWithReads() throws -> MCPTestEnv {+ let env = try MCPTestHelpers.makeEnv()+ let snapshots = env.handler.taskQuerySnapshots+ let source = MCPReadCaptureBuilder(container: env.context.container, fence: .actorOnlyTestFixture)+ let service = MCPReadService(source: source,+ monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil), snapshots: snapshots)+ let handler = MCPToolHandler(taskService: env.taskService, projectService: env.projectService,+ commentService: env.commentService, milestoneService: env.milestoneService,+ maintenanceService: env.maintenanceService, settings: env.mcpSettings,+ taskQuerySnapshots: snapshots, writeCoordinator: env.writeCoordinator, readService: service,+ readCoordinator: env.handler.readCoordinator)+ return MCPTestEnv(handler: handler, taskService: env.taskService, projectService: env.projectService,+ commentService: env.commentService, milestoneService: env.milestoneService,+ maintenanceService: env.maintenanceService, mcpSettings: env.mcpSettings, context: env.context,+ writeCoordinator: env.writeCoordinator, sidecarDirectory: env.sidecarDirectory)+ }++ // swiftlint:disable:next cyclomatic_complexity+ static func validArguments(tool: String, env: MCPTestEnv, project: Project,+ task: TransitTask, milestone: Milestone) throws -> [String: Any] {+ var args: [String: Any] = [:]+ switch tool {+ case "create_project": args = ["name": "New Project", "colorHex": "#334455"]+ case "create_task": args = ["name": "New Task", "type": "feature", "projectId": project.id.uuidString]+ case "create_milestone": args = ["name": "New Milestone", "projectId": project.id.uuidString]+ case "update_task": args = ["taskId": task.id.uuidString, "name": "Updated Task"]+ case "update_task_status": args = ["taskId": task.id.uuidString, "status": "in-progress"]+ case "add_comment": args = ["taskId": task.id.uuidString, "content": "Saved Comment", "authorName": "Fixture"]+ case "update_milestone": args = ["milestoneId": milestone.id.uuidString, "name": "Updated Milestone"]+ case "delete_milestone": args = ["milestoneId": milestone.id.uuidString]+ case "query_tasks":+ args = ["detailLevel": "full", "includeComments": false, "readPolicy": "cached", "limit": 100]+ case "query_milestones", "get_projects": args = ["readPolicy": "cached"]+ case "query_project_summaries": args = [+ "start": "2026-01-01T00:00:00Z", "end": "2026-12-31T00:00:00Z",+ "limit": 100, "readPolicy": "cached"+ ]+ default: break+ }+ if MCPWriteCommand.protectedTools.contains(tool) { args["idempotencyKey"] = "all-tools-" + tool }+ if ["update_task", "update_task_status"].contains(tool) {+ args["expectedRevision"] = try MCPTestHelpers.readRevision(task, in: env.context)+ }+ if ["update_milestone", "delete_milestone"].contains(tool) {+ args["expectedRevision"] = try MCPTestHelpers.readRevision(milestone)+ }+ return args+ }++ static func body(method: String, id: Any = 1, parameters: [String: Any] = [:]) throws -> String {+ var params = parameters+ params["_meta"] = meta+ let bytes = try JSONSerialization.data(withJSONObject: [+ "jsonrpc": "2.0", "id": id, "method": method, "params": params+ ], options: [.sortedKeys])+ return try #require(String(data: bytes, encoding: .utf8))+ }++ static func respond(_ env: MCPTestEnv, method: String, id: Any = 1,+ parameters: [String: Any] = [:], headers: [HTTPField] = [],+ origin: String? = nil) async throws -> MCPHTTPTestResponse {+ var fields = [HTTPField(name: HTTPField.Name("Mcp-Method")!, value: method)]+ if let name = parameters["name"] as? String {+ fields.append(HTTPField(name: HTTPField.Name("Mcp-Name")!, value: name))+ }+ fields.append(contentsOf: headers)+ return try await transport(handler: env.handler, origin: origin,+ contentType: "application/json", accept: "application/json, text/event-stream",+ protocolVersion: "2026-07-28", orderedHeaders: fields,+ body: body(method: method, id: id, parameters: parameters), loggerLabel: "t2383-modern-result-fixture")+ }++ /// Supported asynchronous test transport; no socket/listener or retained helper changes.+ nonisolated static func transport(+ handler: MCPToolHandler, method: HTTPRequest.Method = .post, path: String = "/mcp",+ origin: String? = nil, authority: String = "127.0.0.1:3141", contentType: String? = nil,+ accept: String? = nil, protocolVersion: String? = nil, orderedHeaders: [HTTPField] = [],+ body: String = "", loggerLabel: String+ ) async throws -> MCPHTTPTestResponse {+ let responder = MCPServer.makeRouter(handler: handler).buildResponder()+ var headers = HTTPFields()+ if let origin { headers[.origin] = origin }+ if let contentType { headers[.contentType] = contentType }+ if let accept { headers[.accept] = accept }+ if let protocolVersion { headers[HTTPField.Name("MCP-Protocol-Version")!] = protocolVersion }+ for field in orderedHeaders { headers.append(field) }+ let request = Request(head: HTTPRequest(method: method, scheme: "http", authority: authority,+ path: path, headerFields: headers), body: RequestBody(buffer: ByteBuffer(string: body)))+ let loop = NIOAsyncTestingEventLoop()+ var ownedChannel: NIOAsyncTestingChannel?+ do {+ let channel = try await NIOAsyncTestingChannel(loop: loop) { _ in }+ ownedChannel = channel+ let context = MCPRequestContext(source: ApplicationRequestContextSource(+ channel: channel, logger: Logger(label: loggerLabel)))+ let response = try await responder.respond(to: request, context: context)+ let writer = Writer()+ try await response.body.write(writer)+ let result = MCPHTTPTestResponse(status: response.status, headers: response.headers,+ body: Data(buffer: writer.bytes.withLockedValue { $0 }))+ // Clear the owned reference before finishing so a cleanup failure cannot finish twice.+ ownedChannel = nil+ let leftovers = try await channel.finish(acceptAlreadyClosed: true)+ #expect(leftovers.isClean)+ await loop.shutdownGracefully()+ return result+ } catch {+ if let channel = ownedChannel {+ do {+ let leftovers = try await channel.finish(acceptAlreadyClosed: true)+ #expect(leftovers.isClean)+ } catch { Issue.record("Async testing channel cleanup failed: \(error)") }+ }+ await loop.shutdownGracefully()+ throw error+ }+ }++ private nonisolated final class Writer: ResponseBodyWriter, Sendable {+ let bytes = NIOLockedValueBox(ByteBuffer())+ func write(_ buffer: ByteBuffer) async throws {+ _ = bytes.withLockedValue { $0.writeImmutableBuffer(buffer) }+ }+ func finish(_: HTTPFields?) async throws {}+ }++ static func call(_ env: MCPTestEnv, tool: String, arguments: [String: Any],+ id: Any = 1) async throws -> MCPHTTPTestResponse {+ try await respond(env, method: "tools/call", id: id, parameters: ["name": tool, "arguments": arguments])+ }++ static func text(_ response: MCPHTTPTestResponse) throws -> String {+ let root = try MCPJSONDocument.parse(response.body).value+ let result = try #require(MCPResultEncoderFixtures.field("result", in: root))+ #expect(MCPResultEncoderFixtures.field("resultType", in: result) == .string("complete"))+ return try MCPResultEncoderFixtures.originalText(result)+ }++ static func assertSource(_ response: MCPHTTPTestResponse, id: JSONRPCId) throws -> MCPJSONValue {+ let result = try MCPResultEncoderFixtures.result(response.body, id: id)+ let original = try MCPResultEncoderFixtures.originalText(result)+ let structured = try MCPResultEncoderFixtures.structured(result)+ let source = try #require(MCPResultEncoderFixtures.field("source", in: structured))+ switch MCPResultEncoderFixtures.field("kind", in: source) {+ case .string("json"):+ #expect(try MCPResultEncoderFixtures.rawFragment(response.body,+ path: ["result", "structuredContent", "source", "payload"]) == Data(original.utf8))+ case .string("text"):+ #expect(MCPResultEncoderFixtures.field("payload", in: source) == .string(original))+ case .string("unreadable"):+ #expect(MCPResultEncoderFixtures.field("payload", in: source) == nil)+ let presentation = MCPResultEncoderFixtures.field("presentation", in: structured)+ #expect(MCPResultEncoderFixtures.field("evidence", in: presentation) == .string("unestablished"))+ default: Issue.record("Missing declared source kind")+ }+ return result+ }+}+#endif
diff --git a/Transit/TransitTests/MCPModernReusableRetentionTests.swift b/Transit/TransitTests/MCPModernReusableRetentionTests.swiftnew file mode 100644index 0000000..05c7f3e--- /dev/null+++ b/Transit/TransitTests/MCPModernReusableRetentionTests.swift@@ -0,0 +1,362 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// Owner-supplied reusable ABI; actual saved capture/comment closure has separate task16 coverage.+@MainActor @Suite(.serialized)+struct MCPModernReusableRetentionTests {+ @Test func reusableCaptureKeepsCommentCoveredRevisionAfterLaterSavedChanges() async throws {+ let models = try TestModelContainer()+ models.context.autosaveEnabled = false+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ let task = TransitTask(name: "Saved", type: .feature, project: project, displayID: .permanent(16))+ let comment = Comment(content: "First", authorName: "Fixture", isAgent: true, task: task)+ models.context.insert(project)+ models.context.insert(task)+ models.context.insert(comment)+ try models.context.save()+ let revision = try MCPRecordSnapshot.task(task, in: models.context).revision+ let capture = try MCPReadCaptureBuilder(container: models.container, fence: .actorOnlyTestFixture)+ .capture(ReadCaptureRequest(projectSelectors: nil, selection: .portfolio,+ completeness: .completePortfolio, includeComments: false))+ await withOperation { operation in+ let fixture = try Fixture(capture: capture)+ let results = try fixture.results(fixture.pages())+ try fixture.commit(fixture.store.reservePreparedCreate(bundle: fixture.bundle,+ preparedResults: results, operation: operation, publicationDeadline: fixture.deadline))+ comment.content = "Second saved comment"+ task.name = "Second saved task"+ try models.context.save()+ #expect(try MCPRecordSnapshot.task(task, in: models.context).revision != revision)+ let retained = try fixture.store.preparedResultView(for: fixture.id, now: fixture.instant)+ let frozenTask = try #require(retained.root.capture.tasks.first)+ #expect(frozenTask.revision == revision && frozenTask.name == "Saved")+ #expect(frozenTask.requestedCommentRecordsJSON == nil)+ #expect(retained.root.capture.comments.first?.content == "First")+ #expect(retained.pin.deadline == capture.retentionDeadline)+ #expect(retained.root.frozenMetadataBytes == fixture.bundle.root.frozenMetadataBytes)+ }+ }++ @Test func legacyDefaultsRemainUsableAndModernCarrierCannotUseLegacyCharge() throws {+ let fixture = try Fixture()+ #expect(fixture.bundle.root.preparedResultPage == nil)+ #expect(fixture.bundle.preparedResultBundle == nil)+ let legacy = try fixture.store.reserveCreate(bundle: fixture.bundle, publicationDeadline: fixture.deadline)+ try fixture.commit(legacy)+ let root = try fixture.store.retainedView(for: fixture.id, now: fixture.instant)+ #expect(root.firstPage == fixture.bundle.root.firstPage)+ #expect(root.preparedResultPage == nil)+ #expect(throws: MCPReusableSnapshotError.incompatible) {+ try fixture.store.reserveAppend(snapshotID: fixture.id, pages: [], cursors: [],+ publicationDeadline: fixture.deadline)+ }+ let page = try fixture.pages()[0]+ let modernRoot = RetainedView(capture: root.capture, frozenMetadataBytes: root.frozenMetadataBytes,+ window: root.window, initialRequest: root.initialRequest, firstPage: root.firstPage,+ preparedResultPage: page)+ let guarded = EncodedViewBundle(root: modernRoot, pages: [], cursors: [], encodedCaptureByteCount: 128)+ #expect(throws: MCPResultPreparationError.notImplemented) {+ try fixture.store.reserveCreate(bundle: guarded, publicationDeadline: fixture.deadline)+ }+ }++ @Test func budgetObservesVisibleAndPendingWithoutCombiningOrdinaryStore() async {+ await withOperation { operation in+ let fixture = try Fixture()+ try fixture.commit(fixture.store.reserveCreate(bundle: fixture.bundle,+ publicationDeadline: fixture.deadline))+ let pendingFixture = try Fixture()+ let reservation = try fixture.store.reserveCreate(bundle: pendingFixture.bundle,+ publicationDeadline: fixture.deadline)+ defer { fixture.domain.withLock { reservation.publication.discardLocked(in: fixture.domain) } }+ let ordinary = MCPTaskQuerySnapshotStore(now: { fixture.instant }, domain: fixture.domain)+ try ordinary.publish(pages: ["ordinary-first", "ordinary-next"], cursors: [UUID().uuidString],+ deadline: fixture.deadline)+ let observed = try fixture.domain.accounting(for: fixture.store.publicationStoreID)+ let budget = try fixture.store.preparedResultBudget(originalCaptureIndexBytes: 257, operation: operation)+ #expect(budget.store == .reusable)+ #expect(budget.originalCaptureIndexBytes == 257)+ #expect(budget.visibleBytes == observed.visibleBytes)+ #expect(budget.visibleBytes > 0)+ #expect(budget.pendingBytes == observed.pendingBytes && budget.pendingBytes > 0)+ fixture.domain.withLock { reservation.publication.discardLocked(in: fixture.domain) }+ let clean = try fixture.store.preparedResultBudget(originalCaptureIndexBytes: 257, operation: operation)+ #expect(clean.pendingBytes == 0 && clean.visibleBytes == observed.visibleBytes)+ }+ }++ @Test func preparedCreateIsPrivateUntilGateWithExactExpandedChargeAndFrozenLookups() async {+ await withOperation { operation in+ let fixture = try Fixture()+ let pages = try fixture.pages()+ let results = try fixture.results(pages)+ let reservation = try fixture.store.reservePreparedCreate(bundle: fixture.bundle,+ preparedResults: results, operation: operation, publicationDeadline: fixture.deadline)+ defer { fixture.domain.withLock { reservation.publication.discardLocked(in: fixture.domain) } }+ #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+ try fixture.store.retainedView(for: fixture.id, now: fixture.instant)+ }+ let pending = try fixture.domain.accounting(for: fixture.store.publicationStoreID)+ #expect(pending.visibleEntries == 0 && pending.pendingEntries == 1)+ #expect(pending.pendingBytes == results.charge.totalBytes)+ try fixture.commit(reservation)+ let root = try fixture.store.preparedResultView(for: fixture.id, now: fixture.instant)+ let next = try fixture.store.preparedResultPage(for: fixture.cursor, now: fixture.instant)+ #expect(root.firstPage === pages[0])+ #expect(next.preparedPage === pages[1])+ #expect(next.page.preparedResultPage === pages[1])+ #expect(root.root.preparedResultPage === pages[0])+ #expect(root.pin.identity == next.pin.identity)+ #expect(root.pin.deadline == fixture.bundle.root.capture.retentionDeadline)+ #expect(next.page.root.frozenMetadataBytes == fixture.bundle.root.frozenMetadataBytes)+ #expect(root.firstPage.metadataOwner === next.preparedPage.metadataOwner)+ let visible = try fixture.domain.accounting(for: fixture.store.publicationStoreID)+ #expect(visible.visibleBytes == results.charge.totalBytes && visible.pendingBytes == 0)+ for id in [JSONRPCId.string("replay-new-id"), .integer(16)] {+ let first = try MCPResultEncoder.encode(fragment: next.preparedPage.fragment, id: id)+ #expect(first == (try MCPResultEncoder.encode(fragment: pages[1].fragment, id: id)))+ }+ }+ }++ @Test func zeroCursorAppendRetainsNewResponseOwnerAndSharedMetadataOnce() async {+ await withOperation { operation in+ let fixture = try Fixture()+ let pages = try fixture.pages()+ let first = try fixture.results(pages)+ try fixture.commit(fixture.store.reservePreparedCreate(bundle: fixture.bundle,+ preparedResults: first, operation: operation, publicationDeadline: fixture.deadline))+ let newPage = try fixture.page(#"{"projects":[],"later":true}"#, metadata: pages[0].metadataOwner)+ let expected = try fixture.results(pages + [newPage])+ let append = try fixture.store.reservePreparedAppend(snapshotID: fixture.id,+ pages: [], cursors: [], preparedPages: [newPage], operation: operation,+ publicationDeadline: fixture.deadline)+ try fixture.commit(append)+ let accounting = try fixture.domain.accounting(for: fixture.store.publicationStoreID)+ #expect(accounting.visibleBytes == expected.charge.totalBytes)+ let root = try fixture.store.preparedResultView(for: fixture.id, now: fixture.instant)+ #expect(root.firstPage === pages[0])+ #expect(root.pin.deadline == fixture.bundle.root.capture.retentionDeadline)+ #expect(newPage.metadataOwner === root.firstPage.metadataOwner)+ }+ }++ @Test func discardedPreparedCandidateReleasesPendingAndNeverPublishesTokens() async {+ await withOperation { operation in+ let fixture = try Fixture()+ let prepared = try fixture.results(fixture.pages())+ let reservation = try fixture.store.reservePreparedCreate(bundle: fixture.bundle,+ preparedResults: prepared, operation: operation, publicationDeadline: fixture.deadline)+ let before = try fixture.domain.accounting(for: fixture.store.publicationStoreID)+ #expect(before.pendingBytes == prepared.charge.totalBytes)+ fixture.domain.withLock {+ reservation.publication.discardLocked(in: fixture.domain)+ reservation.publication.discardLocked(in: fixture.domain)+ }+ let after = try fixture.domain.accounting(for: fixture.store.publicationStoreID)+ #expect(after.pendingBytes == 0 && after.pendingEntries == 0 && after.visibleEntries == 0)+ #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+ try fixture.store.retainedView(for: fixture.id, now: fixture.instant)+ }+ #expect(throws: MCPReusableSnapshotError.invalidCursor) {+ try fixture.store.page(for: fixture.cursor, now: fixture.instant)+ }+ }+ }++ @Test func expiredPreparedCandidateCannotPublishOrExtendOriginalFiveMinuteRoot() async {+ await withOperation { operation in+ let fixture = try Fixture()+ let results = try fixture.results(fixture.pages())+ let reservation = try fixture.store.reservePreparedCreate(bundle: fixture.bundle,+ preparedResults: results, operation: operation, publicationDeadline: fixture.deadline)+ defer { fixture.domain.withLock { reservation.publication.discardLocked(in: fixture.domain) } }+ fixture.domain.setTestingInstant(fixture.bundle.root.capture.retentionDeadline)+ #expect(fixture.domain.withLock {+ reservation.publication.validateLocked(in: fixture.domain)+ } == .expired)+ #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+ try fixture.store.retainedView(for: fixture.id, now: fixture.bundle.root.capture.retentionDeadline)+ }+ #expect(try fixture.domain.accounting(for: fixture.store.publicationStoreID).visibleEntries == 0)+ }+ }++ @Test func expandedPreparationFailsWholeAtReusableCapacityWithoutReservation() async throws {+ let largeFixture = try Fixture()+ // Build the immutable value outside the admission clock. Capacity measurement+ // below still uses the actual original operation and never widens its budget.+ let text = "{\"padding\":\"" + String(repeating: "x", count: 5 * 1_024 * 1_024) + "\"}"+ let page = try largeFixture.page(text, metadata: nil)+ await withOperation { operation in+ let fixture = try Fixture()+ // Raw text fits legacy Data accounting; tree/document/text/fragment together exceed 16MiB.+ let budget = try fixture.store.preparedResultBudget(originalCaptureIndexBytes: 128, operation: operation)+ #expect(throws: MCPResultPreparationError.retentionCapacity) {+ try MCPResultPreparation.prepare(pages: [page], budget: budget) {+ guard operation.shouldContinue() else { throw CancellationError() }+ }+ }+ let accounting = try fixture.domain.accounting(for: fixture.store.publicationStoreID)+ #expect(accounting.pendingBytes == 0 && accounting.visibleBytes == 0)+ }+ }++ @Test(arguments: [false, true])+ func siblingAppendsShareExistingBaseButRejectNewSharedOwnerBeforeTransfer(sharedNew: Bool) async {+ await withOperation { operation in+ let fixture = try Fixture()+ let pages = try fixture.pages()+ try fixture.commit(fixture.store.reservePreparedCreate(bundle: fixture.bundle,+ preparedResults: fixture.results(pages), operation: operation, publicationDeadline: fixture.deadline))+ let existing = try #require(pages[0].metadataOwner)+ let metadata = sharedNew ? try MCPResultPreparation.metadata(value: existing.value) : existing+ let firstPage = try fixture.page(#"{"projects":[],"sibling":1}"#, metadata: metadata)+ let secondPage = try fixture.page(#"{"projects":[],"sibling":2}"#, metadata: metadata)+ let first = try fixture.store.reservePreparedAppend(snapshotID: fixture.id, pages: [], cursors: [],+ preparedPages: [firstPage], operation: operation, publicationDeadline: fixture.deadline)+ defer { fixture.domain.withLock { first.publication.discardLocked(in: fixture.domain) } }+ let second: RetentionReservation+ let beforeSecond = try fixture.domain.accounting(for: fixture.store.publicationStoreID)+ do {+ second = try fixture.store.reservePreparedAppend(snapshotID: fixture.id, pages: [], cursors: [],+ preparedPages: [secondPage], operation: operation, publicationDeadline: fixture.deadline)+ } catch {+ guard sharedNew, Self.isOwnerMisuse(error) else { throw error }+ #expect(operation.shouldContinue())+ #expect(try fixture.domain.accounting(for: fixture.store.publicationStoreID) == beforeSecond)+ #expect(first.publication.status == .pending)+ return+ }+ defer { fixture.domain.withLock { second.publication.discardLocked(in: fixture.domain) } }+ let before = try fixture.domain.accounting(for: fixture.store.publicationStoreID)+ if sharedNew {+ try self.requireAggregateMisuse(fixture: fixture, first: first, second: second, operation: operation)+ #expect(try fixture.domain.accounting(for: fixture.store.publicationStoreID) == before)+ #expect(first.publication.status == .pending && second.publication.status == .pending)+ } else {+ let expected = try fixture.results(pages + [firstPage, secondPage])+ #expect(before.pendingBytes == expected.charge.totalBytes - before.visibleBytes)+ let aggregate = try fixture.store.prepareAggregate([first.publication, second.publication],+ in: fixture.domain, operation: operation)+ try fixture.domain.withLock {+ if let rejection = aggregate.validateLocked(in: fixture.domain) { throw rejection }+ aggregate.commitLocked(in: fixture.domain)+ }+ let after = try fixture.domain.accounting(for: fixture.store.publicationStoreID)+ #expect(after.visibleBytes == expected.charge.totalBytes && after.pendingBytes == 0)+ #expect(firstPage.metadataOwner === secondPage.metadataOwner)+ }+ }+ }++}++extension MCPModernReusableRetentionTests {+ private static func isOwnerMisuse(_ error: any Error) -> Bool {+ (error as? MCPReusableSnapshotError) == .incompatible || (error as? PublicationRejection) == .busy+ }++ private func requireAggregateMisuse(fixture: Fixture, first: RetentionReservation,+ second: RetentionReservation, operation: MCPReadOperation) throws {+ do {+ _ = try fixture.store.prepareAggregate([first.publication, second.publication],+ in: fixture.domain, operation: operation)+ Issue.record("New shared sibling owner unexpectedly transferred")+ } catch { #expect(Self.isOwnerMisuse(error)) }+ }++ private func withOperation(_ body: @escaping @MainActor @Sendable (MCPReadOperation) throws -> Void) async {+ let coordinator = MCPReadCoordinator()+ let bytes = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { operation in+ await MainActor.run {+ do { try body(operation); return Self.result(Data("completed".utf8)) } catch {+ Issue.record("Modern reusable retention failed: \(error)")+ return Self.result(Data("failed".utf8))+ }+ }+ }+ #expect(bytes == Data("completed".utf8))+ for _ in 0..<100 where coordinator.unfinishedCount != 0 { try? await Task.sleep(for: .milliseconds(5)) }+ #expect(coordinator.unfinishedCount == 0)+ }++ nonisolated private static func result(_ bytes: Data) -> PreparedReadResult {+ PreparedReadResult(encodedResponse: bytes, publications: [],+ publicationErrors: .init(busy: Data(), expired: Data(), capacity: Data()))+ }+}++@MainActor+private struct Fixture {+ let instant: ContinuousClock.Instant+ let deadline: ContinuousClock.Instant+ let domain: MCPReadPublicationDomain+ let store: MCPReusableSnapshotStore+ let id: String+ let cursor: String+ let bundle: EncodedViewBundle++ init(capture savedCapture: CapturedReadView? = nil) throws {+ instant = savedCapture?.createdAt ?? .now+ deadline = savedCapture?.retentionDeadline ?? instant.advanced(by: .seconds(300))+ domain = MCPReadPublicationDomain(testingInstant: instant)+ store = try MCPReusableSnapshotStore(domain: domain)+ id = savedCapture?.metadata.snapshotId ?? UUID().uuidString+ cursor = "00000000-0000-8000-8000-" + UUID().uuidString.suffix(12)+ let metadata = ReadCaptureMetadata(asOf: "2026-10-04T09:00:00.000Z", snapshotId: id,+ freshness: ReadFreshness(syncState: .inactive, assessment: .notApplicable,+ assessedAt: "2026-10-04T09:00:00.000Z", lastImportedAt: nil,+ evidence: .none, recentImportThresholdMs: 60_000),+ read: ReadExecutionMetadata(policy: .cached, refreshOutcome: .notRequested, budgetMs: 5_000))+ let capture = savedCapture ?? CapturedReadView(completeness: .completePortfolio, captureScope: .wholePortfolio,+ metadata: metadata, createdAt: instant, retentionDeadline: deadline,+ projects: [], tasks: [], milestones: [], comments: [])+ let window = try CompletionWindow.parse(start: "2026-10-01T00:00:00Z", end: "2026-10-04T00:00:00Z")+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys]+ let root = RetainedView(capture: capture, frozenMetadataBytes: try encoder.encode(capture.metadata),+ window: window,+ initialRequest: .initial(window: window, limit: 1, project: nil, policy: .cached),+ firstPage: Data(#"{"projects":[],"first":true}"#.utf8))+ bundle = EncodedViewBundle(root: root, pages: [Data(#"{"projects":[],"next":true}"#.utf8)],+ cursors: [cursor], encodedCaptureByteCount: 128 + root.frozenMetadataBytes.count)+ }++ func pages() throws -> [MCPResultPreparedPage] {+ let read = try MCPPreparedToolRead(text: "null", frozenMetadataBytes: bundle.root.frozenMetadataBytes)+ let value = try #require(try MCPResultProviderAdapters.metadata(result: read.result,+ frozenReadBytes: bundle.root.frozenMetadataBytes))+ let metadata = try MCPResultPreparation.metadata(value: value)+ return try ([bundle.root.firstPage] + bundle.pages).map {+ try page(try #require(String(data: $0, encoding: .utf8)), metadata: metadata)+ }+ }++ func page(_ text: String, metadata: MCPResultPreparedMetadata?) throws -> MCPResultPreparedPage {+ try MCPResultPreparation.page(request: MCPResultPagePreparationRequest(text: text, isError: nil,+ origin: .generatedJSON, evidence: .established,+ context: MCPResultContext(tool: "query_project_summaries", semanticFailure: nil,+ mutationRecovery: nil, entityPositions: []), metadataOwner: metadata))+ }++ func results(_ pages: [MCPResultPreparedPage]) throws -> MCPResultRetainedBundle {+ // Existing legacy copies remain retained alongside frozen modern owners.+ let original = bundle.encodedCaptureByteCount + bundle.root.firstPage.count+ + bundle.pages.reduce(0) { $0 + $1.count }+ return try MCPResultPreparation.prepare(pages: pages, budget: MCPResultRetentionBudget(store: .reusable,+ originalCaptureIndexBytes: original, visibleBytes: 0, pendingBytes: 0))+ }++ func commit(_ reservation: RetentionReservation) throws {+ let publication = try store.prepare(reservation: reservation)+ try domain.withLock {+ if let rejection = publication.validateLocked(in: domain) { throw rejection }+ publication.commitLocked(in: domain)+ }+ }+}+#endif
diff --git a/Transit/TransitTests/MCPModernRouterIntegrationTests.swift b/Transit/TransitTests/MCPModernRouterIntegrationTests.swiftnew file mode 100644index 0000000..eb14dea--- /dev/null+++ b/Transit/TransitTests/MCPModernRouterIntegrationTests.swift@@ -0,0 +1,213 @@+#if os(macOS)+import Foundation+import HTTPTypes+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPModernRouterIntegrationTests {+ @Test func discoverAndSortedToolListPublishCompleteOutputSchemas() async throws {+ let env = try MCPTestHelpers.makeEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ env.mcpSettings.maintenanceToolsEnabled = true+ for method in ["server/discover", "tools/list"] {+ let response = try await MCPModernResultFixture.respond(env, method: method)+ #expect(response.status == .ok)+ let object = try #require(response.json as? [String: Any])+ let result = try #require(object["result"] as? [String: Any])+ #expect(result["resultType"] as? String == "complete")+ #expect(result["ttlMs"] as? Int == 0)+ #expect(result["cacheScope"] as? String == "public")+ if method == "tools/list" {+ let tools = try #require(result["tools"] as? [[String: Any]])+ let names = tools.compactMap { $0["name"] as? String }+ #expect(names == names.sorted())+ #expect(Set(names) == Set(MCPToolDefinitions.tools(includingMaintenance: true).map(\.name)))+ for tool in tools {+ let schema = try #require(tool["outputSchema"] as? [String: Any])+ #expect(schema["$schema"] as? String == "https://json-schema.org/draft/2020-12/schema")+ #expect(schema["$defs"] is [String: Any])+ }+ }+ }+ }++ @Test func everyEnabledCurrentToolReturnsDeclaredCompleteSource() async throws {+ let env = try MCPModernResultFixture.makeEnvWithReads()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ env.mcpSettings.maintenanceToolsEnabled = true+ let project = try env.projectService.createProject(name: "Existing", description: "", gitRepo: nil,+ colorHex: "#112233")+ let task = try await env.taskService.createTask(name: "Existing Task", description: "Description",+ type: .feature, project: project)+ let milestone = try await env.milestoneService.createMilestone(name: "Existing Milestone",+ description: nil, project: project)+ for definition in MCPToolDefinitions.tools(includingMaintenance: true) {+ let args = try MCPModernResultFixture.validArguments(tool: definition.name, env: env,+ project: project, task: task, milestone: milestone)+ let response = try await MCPModernResultFixture.call(env, tool: definition.name, arguments: args)+ #expect(response.status == .ok)+ let result = try MCPModernResultFixture.assertSource(response, id: .integer(1))+ #expect(MCPResultEncoderFixtures.field("isError", in: result) != .boolean(true))+ let covered = ["query_tasks", "query_milestones", "get_projects", "query_project_summaries"]+ if covered.contains(definition.name) {+ #expect(MCPResultEncoderFixtures.field("_meta", in: result) != nil)+ }+ }+ }++ private actor ReadHold {+ private var entered = false+ private var entryWaiter: CheckedContinuation<Void, Never>?+ private var releaseWaiter: CheckedContinuation<Void, Never>?+ func block() async {+ entered = true+ entryWaiter?.resume()+ entryWaiter = nil+ await withCheckedContinuation { releaseWaiter = $0 }+ }+ func waitForEntry() async {+ if entered { return }+ await withCheckedContinuation { entryWaiter = $0 }+ }+ func release() { releaseWaiter?.resume(); releaseWaiter = nil }+ }++ @Test func coveredInvalidArgumentsRespectSaturatedAdmissionBeforeDomainValidation() async throws {+ let env = try MCPModernResultFixture.makeEnvWithReads()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let domain = env.handler.taskQuerySnapshots.domain+ let coordinator = MCPReadCoordinator(domain: domain, maxOperations: 1)+ let handler = MCPToolHandler(taskService: env.taskService, projectService: env.projectService,+ commentService: env.commentService, milestoneService: env.milestoneService,+ maintenanceService: env.maintenanceService, settings: env.mcpSettings,+ taskQuerySnapshots: env.handler.taskQuerySnapshots, writeCoordinator: env.writeCoordinator,+ readService: env.handler.readService, readCoordinator: coordinator)+ let hold = ReadHold()+ let runner = Task.detached {+ await coordinator.execute(timeout: Data("held-timeout".utf8), busy: Data("held-busy".utf8)) { _ in+ await hold.block()+ return PreparedReadResult(encodedResponse: Data("held-done".utf8), publications: [],+ publicationErrors: PreencodedPublicationErrors(busy: Data(), expired: Data(), capacity: Data()))+ }+ }+ await hold.waitForEntry()+ do {+ let body = try MCPModernResultFixture.body(method: "tools/call",+ parameters: ["name": "query_tasks", "arguments": "invalid-object-shape"])+ let response = try await MCPModernResultFixture.transport(+ handler: handler, contentType: "application/json",+ accept: "application/json, text/event-stream", protocolVersion: "2026-07-28", orderedHeaders: [+ HTTPField(name: HTTPField.Name("Mcp-Method")!, value: "tools/call"),+ HTTPField(name: HTTPField.Name("Mcp-Name")!, value: "query_tasks")+ ], body: body, loggerLabel: "t2383-covered-admission")+ let text = try MCPModernResultFixture.text(response)+ #expect(text.contains("READ_BUSY"))+ _ = try MCPModernResultFixture.assertSource(response, id: .integer(1))+ } catch {+ await hold.release()+ _ = await runner.value+ throw error+ }+ await hold.release()+ _ = await runner.value+ }++ private nonisolated final class MainActorHold: @unchecked Sendable {+ private let entered = DispatchSemaphore(value: 0)+ private let released = DispatchSemaphore(value: 0)+ private let lock = NSLock()+ private var blocked = false+ private var explicitlyReleased = false+ @MainActor func block() {+ lock.lock(); blocked = true; lock.unlock()+ entered.signal()+ let result = released.wait(timeout: .now() + .seconds(2))+ lock.lock(); explicitlyReleased = result == .success; lock.unlock()+ lock.lock(); blocked = false; lock.unlock()+ }+ func waitForEntry() -> Bool { entered.wait(timeout: .now() + .seconds(2)) == .success }+ func release() { released.signal() }+ var isBlocked: Bool { lock.lock(); defer { lock.unlock() }; return blocked }+ var completedByRelease: Bool { lock.lock(); defer { lock.unlock() }; return explicitlyReleased }+ }++ @Test func immutableUnavailableToolClassificationDoesNotWaitForMainActor() async throws {+ let env = try MCPModernResultFixture.makeEnvWithReads()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let handler = env.handler+ let body = try MCPModernResultFixture.body(method: "tools/call",+ parameters: ["name": "unavailable_tool", "arguments": [:] as [String: Any]])+ let hold = MainActorHold()+ let scenario = Task.detached {+ let blocker = Task { @MainActor in hold.block() }+ guard hold.waitForEntry() else {+ hold.release()+ await blocker.value+ throw FixtureFailure.barrier+ }+ do {+ let response = try await MCPModernResultFixture.transport(+ handler: handler, contentType: "application/json",+ accept: "application/json, text/event-stream", protocolVersion: "2026-07-28", orderedHeaders: [+ HTTPField(name: HTTPField.Name("Mcp-Method")!, value: "tools/call"),+ HTTPField(name: HTTPField.Name("Mcp-Name")!, value: "unavailable_tool")+ ], body: body, loggerLabel: "t2383-immutable-classification")+ let beforeRelease = hold.isBlocked+ hold.release()+ await blocker.value+ return (response, beforeRelease, hold.completedByRelease)+ } catch {+ hold.release()+ await blocker.value+ throw error+ }+ }+ let (response, beforeRelease, completedByRelease) = try await scenario.value+ #expect(completedByRelease)+ #expect(beforeRelease)+ #expect(response.status == .badRequest)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0)+ }++ private enum FixtureFailure: Error { case barrier }++ @Test func originAndDuplicateRequiredHeadersRejectBeforeAcceptance() async throws {+ let env = try MCPTestHelpers.makeEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let parameters: [String: Any] = ["name": "create_project", "arguments": [+ "name": "Blocked", "colorHex": "#112233", "idempotencyKey": "blocked-key"+ ]]+ let origin = try await MCPModernResultFixture.respond(env, method: "tools/call",+ parameters: parameters, origin: "https://untrusted.invalid")+ #expect(origin.status == .forbidden)+ let duplicated = try await MCPModernResultFixture.respond(env, method: "tools/call",+ parameters: parameters, headers: [HTTPField(name: HTTPField.Name("Mcp-Name")!, value: "create_project")])+ #expect(duplicated.status == .badRequest)+ #expect(try env.context.fetchCount(FetchDescriptor<Project>()) == 0)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0)+ }++ @Test func notificationMutationRejectsWithoutAcceptanceOrFabricatedID() async throws {+ let env = try MCPTestHelpers.makeEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let body = ##"""+ {"jsonrpc":"2.0","method":"tools/call","params":{"name":"create_project",+ "arguments":{"name":"Blocked","colorHex":"#112233","idempotencyKey":"notify-key"},+ "_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28",+ "io.modelcontextprotocol/clientCapabilities":{}}}}+ """##+ let response = try await MCPModernResultFixture.transport(handler: env.handler,+ contentType: "application/json", accept: "application/json, text/event-stream",+ protocolVersion: "2026-07-28", orderedHeaders: [+ HTTPField(name: HTTPField.Name("Mcp-Method")!, value: "tools/call"),+ HTTPField(name: HTTPField.Name("Mcp-Name")!, value: "create_project")+ ], body: body, loggerLabel: "t2383-notification")+ #expect(response.status == .badRequest)+ if let object = response.json as? [String: Any] { #expect(object["id"] == nil) }+ #expect(try env.context.fetchCount(FetchDescriptor<Project>()) == 0)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0)+ }+}+#endif
diff --git a/Transit/TransitTests/MCPNotificationDispatchTests.swift b/Transit/TransitTests/MCPNotificationDispatchTests.swiftindex 7f0992e..c019640 100644--- a/Transit/TransitTests/MCPNotificationDispatchTests.swift+++ b/Transit/TransitTests/MCPNotificationDispatchTests.swift@@ -5,181 +5,101 @@ import SwiftData import Testing @testable import Transit -/// T-1820: a JSON-RPC notification executes its method normally and only-/// suppresses its JSON-RPC response. These cases cover the direct handler and-/// Streamable HTTP transport paths for mutating tools.+/// Modern HTTP rejects client notifications before effects; ordered valid+/// request objects retain their own correlation and mutation/read ordering. @MainActor @Suite(.serialized) struct MCPNotificationDispatchTests {-- @Test func directToolCallNotificationExecutesMutationButSuppressesResponse() async throws {+ @Test func directNotificationIsRejectedBeforeMutation() async throws { let env = try MCPTestHelpers.makeEnv() let project = MCPTestHelpers.makeProject(in: env.context)- let request = try JSONDecoder().decode(- JSONRPCRequest.self,- from: Data(- """- {- "jsonrpc":"2.0",- "method":"tools/call",- "params":{- "name":"create_task",- "arguments":{- "idempotencyKey":"direct-notification",- "name":"Direct notification task",- "type":"bug",- "projectId":"\(project.id.uuidString)"- }- }- }- """.utf8- )- )-+ let body = try notification(tool: "create_task", arguments: ["idempotencyKey": "direct-notification",+ "name": "Direct notification task", "type": "bug", "projectId": project.id.uuidString])+ let request = try JSONDecoder().decode(JSONRPCRequest.self, from: Data(body.utf8)) #expect(request.isNotification)- #expect(await env.handler.handle(request) == nil)-- let tasks = try env.context.fetch(FetchDescriptor<TransitTask>())- #expect(tasks.map(\.name) == ["Direct notification task"])+ let response = try #require(await env.handler.handle(request))+ #expect(response.error?.code == JSONRPCErrorCode.invalidRequest)+ #expect(response.id == nil && response.result == nil)+ #expect(try env.context.fetchCount(FetchDescriptor<TransitTask>()) == 0)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0) } - @Test func singleToolCallNotificationOverHTTPExecutesMutationWithAcceptedNoBody() async throws {+ @Test func HTTPNotificationIsRejectedWithoutCommentOrReceipt() async throws { let env = try MCPTestHelpers.makeEnv() let project = MCPTestHelpers.makeProject(in: env.context) let task = try await env.taskService.createTask(- name: "Task", description: nil, type: .feature, project: project- )- let displayId = try #require(task.permanentDisplayId)-- let response = try await respond(handler: env.handler, body: """- {- "jsonrpc":"2.0",- "method":"tools/call",- "params":{- "name":"add_comment",- "arguments":{- "displayId":\(displayId),- "idempotencyKey":"http-comment",- "content":"Created over HTTP",- "authorName":"TestBot"- }- }- }- """)-- #expect(response.status == .accepted)- #expect(response.body.isEmpty)- let comments = try env.commentService.fetchComments(for: task.id)- #expect(comments.map(\.content) == ["Created over HTTP"])+ name: "Task", description: nil, type: .feature, project: project)+ let response = try await respond(env.handler, body: notification(tool: "add_comment",+ arguments: ["taskId": task.id.uuidString, "idempotencyKey": "http-comment",+ "content": "Created over HTTP", "authorName": "TestBot"]), tool: "add_comment")+ #expect(response.status == .badRequest && response.body.isEmpty)+ #expect(try env.commentService.fetchComments(for: task.id).isEmpty)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0) } - @Test func singleToolCallFailureNotificationOverHTTPIsAcceptedWithNoBody() async throws {+ @Test func unknownToolNotificationNeverProducesRPCResponseOrEffects() async throws { let env = try MCPTestHelpers.makeEnv()-- let response = try await respond(handler: env.handler, body: """- {- "jsonrpc":"2.0",- "method":"tools/call",- "params":{"name":"not_a_real_tool","arguments":{}}- }- """)-- #expect(response.status == .accepted)- #expect(response.body.isEmpty, "Notification errors must not produce a JSON-RPC response")+ let response = try await respond(env.handler, body: notification(tool: "not_a_real_tool", arguments: [:]),+ tool: "not_a_real_tool")+ #expect(response.status == .badRequest && response.body.isEmpty)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0) } - @Test func mixedBatchExecutesNotificationBeforeRequestAndSuppressesNotificationFailures() async throws {- let env = try MCPTestHelpers.makeEnv()+ @Test func rejectedArrayHasNoEffectsAndSequentialObjectsPreserveMutationReadOrder() async throws {+ let env = try MCPModernResultFixture.makeEnvWithReads() let project = MCPTestHelpers.makeProject(in: env.context) let task = try await env.taskService.createTask(- name: "Task", description: nil, type: .feature, project: project- )- let displayId = try #require(task.permanentDisplayId)-- let response = try await respond(handler: env.handler, body: """- [- {- "jsonrpc":"2.0",- "method":"tools/call",- "params":{- "name":"update_task_status",- "arguments":{"displayId":\(displayId),"status":"planning",- "idempotencyKey":"notification-status",- "expectedRevision":"\(try MCPTestHelpers.readRevision(task, in: env.context))"}- }- },- {- "jsonrpc":"2.0",- "id":"after-mutation",- "method":"tools/call",- "params":{- "name":"query_tasks",- "arguments":{"displayId":\(displayId),"detailLevel":"full","includeComments":false,"limit":100}- }- },- {- "jsonrpc":"2.0",- "method":"tools/call",- "params":{"name":"not_a_real_tool","arguments":{}}- }- ]- """)-- #expect(response.status == .ok)- let objects = try #require(response.json as? [[String: Any]])- #expect(- objects.count == 1,- "Notification success and failure responses must both be suppressed"- )- let object = try #require(objects.first)- #expect(object["id"] as? String == "after-mutation")-- let result = try #require(object["result"] as? [String: Any])- let content = try #require(result["content"] as? [[String: Any]])- let text = try #require(content.first?["text"] as? String)- let returnedTasks = try #require(- (try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])?["results"] as? [[String: Any]]- )- #expect(returnedTasks.map { $0["status"] as? String } == ["planning"])+ name: "Task", description: nil, type: .feature, project: project)+ let arguments: [String: Any] = ["taskId": task.id.uuidString, "status": "planning",+ "idempotencyKey": "ordered-status",+ "expectedRevision": try MCPTestHelpers.readRevision(task, in: env.context)]+ let mutation = try MCPModernResultFixture.body(method: "tools/call", id: "mutation",+ parameters: ["name": "update_task_status", "arguments": arguments])+ let response = try await respond(env.handler,+ body: "[\(try notification(tool: "update_task_status", arguments: arguments)),\(mutation)]",+ tool: "update_task_status")+ #expect(response.status == .badRequest)+ #expect(task.status != .planning)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0)+ let committed = try await MCPModernResultFixture.respond(env, method: "tools/call", id: "mutation",+ parameters: ["name": "update_task_status", "arguments": arguments])+ #expect((committed.json as? [String: Any])?["id"] as? String == "mutation") #expect(task.status == .planning)+ let read = try await MCPModernResultFixture.respond(env, method: "tools/call", id: 17,+ parameters: ["name": "query_tasks", "arguments": ["taskIds": [task.id.uuidString],+ "detailLevel": "full", "includeComments": false, "limit": 100]])+ #expect((read.json as? [String: Any])?["id"] as? Int == 17)+ let payload = try MCPTestHelpers.decodeHTTPToolResult(try #require(read.json as? [String: Any]))+ let results = try #require(payload["results"] as? [[String: Any]])+ let saved = try #require(results.first?["task"] as? [String: Any])+ #expect(saved["status"] as? String == "planning")+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 1) } - @Test func batchedInitializeNotificationIsSuppressedAndDoesNotBlockFollowingRequest() async throws {+ @Test func rejectedLifecycleNotificationArrayDoesNotPreventLaterValidRequest() async throws { let env = try MCPTestHelpers.makeEnv()-- let response = try await respond(handler: env.handler, body: """- [- {- "jsonrpc":"2.0",- "method":"initialize",- "params":{- "protocolVersion":"2025-03-26",- "capabilities":{},- "clientInfo":{"name":"Test Client","version":"1.0"}- }- },- {"jsonrpc":"2.0","id":"after-initialize","method":"ping"}- ]- """)-- #expect(response.status == .ok)- let objects = try #require(response.json as? [[String: Any]])- #expect(objects.count == 1, "The initialize notification must not produce a response")- let object = try #require(objects.first)- #expect(object["id"] as? String == "after-initialize")- #expect(object["result"] != nil, "A rejected lifecycle notification must not block requests after it")+ let rejected = try await respond(env.handler,+ body: #"[{"jsonrpc":"2.0","method":"initialize"},{"jsonrpc":"2.0","id":1,"method":"ping"}]"#,+ tool: nil, method: "initialize")+ #expect(rejected.status == .badRequest)+ #expect(env.handler.activeToolListChangeStreamCount == 0)+ let valid = try await MCPModernResultFixture.respond(env, method: "tools/list", id: "after-initialize")+ let object = try #require(valid.json as? [String: Any])+ #expect(valid.status == .ok && object["id"] as? String == "after-initialize")+ #expect(object["result"] != nil) } - private func respond(- handler: MCPToolHandler,- body: String- ) async throws -> MCPHTTPTestResponse {- try await MCPTestHelpers.respond(- handler: handler,- contentType: "application/json",- body: body,- loggerLabel: "mcp-notification-dispatch-tests"- )+ private func notification(tool: String, arguments: [String: Any]) throws -> String {+ let bytes = try JSONSerialization.data(withJSONObject: ["jsonrpc": "2.0", "method": "tools/call",+ "params": ["name": tool, "arguments": arguments, "_meta": MCPModernResultFixture.meta]])+ return try #require(String(data: bytes, encoding: .utf8))+ }+ private func respond(_ handler: MCPToolHandler, body: String, tool: String?,+ method: String = "tools/call") async throws -> MCPHTTPTestResponse {+ var headers = [HTTPField(name: HTTPField.Name("Mcp-Method")!, value: method)]+ if let tool { headers.append(HTTPField(name: HTTPField.Name("Mcp-Name")!, value: tool)) }+ return try await MCPTestHelpers.respond(handler: handler, contentType: "application/json",+ accept: "application/json, text/event-stream", protocolVersion: "2026-07-28", orderedHeaders: headers,+ body: body, loggerLabel: "mcp-notification-dispatch-tests") } }- #endif
diff --git a/Transit/TransitTests/MCPNullIdTests.swift b/Transit/TransitTests/MCPNullIdTests.swiftindex 11360df..34c8834 100644--- a/Transit/TransitTests/MCPNullIdTests.swift+++ b/Transit/TransitTests/MCPNullIdTests.swift@@ -1,21 +1,21 @@ #if os(macOS) import Foundation+import SwiftData import Testing @testable import Transit -/// Regression tests for T-1863: MCP 2025-03-26 rejects an explicit JSON `null`-/// request id as Invalid Request. Requests with the id member omitted remain-/// notifications, while string and integer ids remain valid.+/// Modern requests require a string/integer ID. Preserve omitted/null presence+/// for rejection, and omit unreadable IDs from encoded request errors. @MainActor @Suite(.serialized) struct MCPNullIdTests { // MARK: - Decoding and presence @Test func decodingPreservesOmittedIdAndExplicitNullPresence() throws {- let omittedJSON = Data(#"{"jsonrpc":"2.0","method":"ping"}"#.utf8)- let nullJSON = Data(#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#.utf8)- let stringJSON = Data(#"{"jsonrpc":"2.0","id":"request-1","method":"ping"}"#.utf8)- let integerJSON = Data(#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#.utf8)+ let omittedJSON = Data(#"{"jsonrpc":"2.0","method":"tools/list"}"#.utf8)+ let nullJSON = Data(#"{"jsonrpc":"2.0","id":null,"method":"tools/list"}"#.utf8)+ let stringJSON = Data(#"{"jsonrpc":"2.0","id":"request-1","method":"tools/list"}"#.utf8)+ let integerJSON = Data(#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#.utf8) let omitted = try JSONDecoder().decode(JSONRPCRequest.self, from: omittedJSON) let explicitNull = try JSONDecoder().decode(JSONRPCRequest.self, from: nullJSON)@@ -33,23 +33,26 @@ struct MCPNullIdTests { @Test func handlerRejectsExplicitNullIdAsInvalidRequest() async throws { let env = try MCPTestHelpers.makeEnv()- let json = Data(#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#.utf8)+ let json = Data(#"{"jsonrpc":"2.0","id":null,"method":"tools/list"}"#.utf8) let request = try JSONDecoder().decode(JSONRPCRequest.self, from: json) let response = try #require(await env.handler.handle(request)) let error = try #require(response.error) #expect(error.code == JSONRPCErrorCode.invalidRequest) #expect(response.result == nil)- #expect(response.id == nil, "Invalid requests use a JSON null response id")+ #expect(response.id == nil, "Invalid requests have no readable response identifier") } - @Test func handlerOmitsResponseForMissingId() async throws {+ @Test func handlerRejectsMissingIdWithoutEffects() async throws { let env = try MCPTestHelpers.makeEnv()- let json = Data(#"{"jsonrpc":"2.0","method":"ping"}"#.utf8)+ let json = Data(#"{"jsonrpc":"2.0","method":"tools/list"}"#.utf8) let request = try JSONDecoder().decode(JSONRPCRequest.self, from: json) let response = await env.handler.handle(request)- #expect(response == nil, "Notifications (omitted id) must not produce a response")+ #expect(response?.error?.code == JSONRPCErrorCode.invalidRequest)+ #expect(response?.id == nil && response?.result == nil)+ #expect(try env.context.fetchCount(FetchDescriptor<TransitTask>()) == 0)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0) } @Test(arguments: [@@ -72,24 +75,27 @@ struct MCPNullIdTests { "initialize", "ping", "tools/list", "tools/call", "notifications/initialized", "unknown/method" ])- func handlerOmitsResponseForMissingIdAcrossMethodPaths(method: String) async throws {+ func handlerRejectsMissingIdBeforeEveryMethodPath(method: String) async throws { let env = try MCPTestHelpers.makeEnv() let json = Data(#"{"jsonrpc":"2.0","method":"\#(method)"}"#.utf8) let request = try JSONDecoder().decode(JSONRPCRequest.self, from: json) let response = await env.handler.handle(request)- #expect(response == nil, "Notifications must not produce a response")+ #expect(response?.error?.code == JSONRPCErrorCode.invalidRequest)+ #expect(response?.id == nil && response?.result == nil)+ #expect(try env.context.fetchCount(FetchDescriptor<TransitTask>()) == 0)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0) } @Test func handlerReturnsResponsesForStringAndIntegerIds() async throws { let env = try MCPTestHelpers.makeEnv() let stringRequest = try JSONDecoder().decode( JSONRPCRequest.self,- from: Data(#"{"jsonrpc":"2.0","id":"request-1","method":"ping"}"#.utf8)+ from: Data(#"{"jsonrpc":"2.0","id":"request-1","method":"tools/list"}"#.utf8) ) let integerRequest = try JSONDecoder().decode( JSONRPCRequest.self,- from: Data(#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#.utf8)+ from: Data(#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#.utf8) ) let stringResponse = try #require(await env.handler.handle(stringRequest))@@ -102,11 +108,11 @@ struct MCPNullIdTests { // MARK: - Error envelope encoding - @Test func invalidNullIdResponseEncodesErrorWithNullId() async throws {+ @Test func invalidNullIdResponseOmitsUnavailableId() async throws { let env = try MCPTestHelpers.makeEnv() let request = try JSONDecoder().decode( JSONRPCRequest.self,- from: Data(#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#.utf8)+ from: Data(#"{"jsonrpc":"2.0","id":null,"method":"tools/list"}"#.utf8) ) let response = try #require(await env.handler.handle(request))@@ -116,8 +122,7 @@ struct MCPNullIdTests { ) let error = try #require(object["error"] as? [String: Any]) - #expect(object.keys.contains("id"))- #expect(object["id"] is NSNull)+ #expect(!object.keys.contains("id")) #expect(error["code"] as? Int == JSONRPCErrorCode.invalidRequest) #expect(object["result"] == nil) }
diff --git a/Transit/TransitTests/MCPPortfolioFixture.swift b/Transit/TransitTests/MCPPortfolioFixture.swiftnew file mode 100644index 0000000..20d32eb--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioFixture.swift@@ -0,0 +1,109 @@+#if os(macOS)+import Foundation+import SwiftData+@testable import Transit++/// Deterministic fixture inputs and independently specified expectations.+/// Captures use the actual shared builder, never duplicate DTOs or fabricated revisions.+nonisolated enum MCPPortfolioFixture {+ static let populatedProjectID = UUID(uuidString: "00000000-0000-4000-8000-000000000001")!+ static let emptyProjectID = UUID(uuidString: "00000000-0000-4000-8000-000000000002")!+ static let openMilestoneID = UUID(uuidString: "00000000-0000-4000-8000-000000000003")!+ static let emptyDoneMilestoneID = UUID(uuidString: "00000000-0000-4000-8000-000000000004")!+ static let commentID = UUID(uuidString: "00000000-0000-4000-8000-000000000005")!++ // 2026-10-03 00:00:00Z to 01:00:00Z; no locale-dependent formatter or wall clock.+ static let window = CompletionWindow(+ start: Date(timeIntervalSince1970: 1_790_985_600),+ end: Date(timeIntervalSince1970: 1_790_989_200)+ )++ // Nine physical task records: each legal status once and one unknown raw status.+ // Both idea and unknown records belong to the open milestone; all others are unassigned.+ static let expectedCounts = PortfolioStatusCounts(+ idea: 2, planning: 1, spec: 1, readyForImplementation: 1,+ inProgress: 1, readyForReview: 1, done: 1, abandoned: 1+ )+ static let expectedTaskCount = 9+ static let expectedWorkflowCount = 5+ static let expectedNonterminalCount = 7++ // Done lies exactly at start; abandoned lies exactly at end and must be excluded.+ static let expectedCompletions = PortfolioRecentCompletions(+ done: 1, abandoned: 0, missingCompletionDateCount: 0+ )+}++@MainActor+struct MCPPortfolioSavedFixture {+ enum FixtureError: Error { case invalidTaskCount }+ let owner: TestModelContainer+ let tasks: [TransitTask]+ let project: Project+ let comment: Comment++ // swiftlint:disable:next function_body_length+ init(taskCount: Int = 9, commentOnEveryTask: Bool = false) throws {+ guard taskCount > 0 else { throw FixtureError.invalidTaskCount }+ owner = try TestModelContainer()+ owner.context.autosaveEnabled = false+ project = Project(name: "Populated", description: "", gitRepo: nil, colorHex: "blue")+ project.id = MCPPortfolioFixture.populatedProjectID+ let empty = Project(name: "Empty", description: "", gitRepo: nil, colorHex: "green")+ empty.id = MCPPortfolioFixture.emptyProjectID+ let open = Milestone(name: "Open", project: project, displayID: .permanent(1))+ open.id = MCPPortfolioFixture.openMilestoneID+ let done = Milestone(name: "Empty done", project: project, displayID: .permanent(2))+ done.id = MCPPortfolioFixture.emptyDoneMilestoneID+ done.statusRawValue = "done"+ for milestone in [open, done] {+ milestone.creationDate = MCPPortfolioFixture.window.start.addingTimeInterval(-120)+ milestone.lastStatusChangeDate = milestone.creationDate+ }+ owner.context.insert(project)+ owner.context.insert(empty)+ owner.context.insert(open)+ owner.context.insert(done)+ var records: [TransitTask] = []+ let statuses = ["idea", "planning", "spec", "ready-for-implementation", "in-progress",+ "ready-for-review", "done", "abandoned", "unknown"]+ for index in 0..<taskCount {+ let task = TransitTask(name: "Task \(index)", type: .feature, project: project,+ displayID: .permanent(index + 1))+ task.id = UUID(uuidString: String(format: "00000000-0000-4001-8000-%012d", index + 1))!+ task.statusRawValue = statuses[index % statuses.count]+ task.creationDate = MCPPortfolioFixture.window.start.addingTimeInterval(-60)+ task.lastStatusChangeDate = task.creationDate+ if task.statusRawValue == "done" { task.completionDate = MCPPortfolioFixture.window.start }+ if task.statusRawValue == "abandoned" { task.completionDate = MCPPortfolioFixture.window.end }+ if index % 9 == 0 || index % 9 == 8 { task.milestone = open }+ task.taskDescription = "Captured description \(index)"+ task.metadata = ["fixture": "\(index)"]+ owner.context.insert(task)+ if commentOnEveryTask {+ let evidence = Comment(content: "Revision evidence \(index)", authorName: "Agent",+ isAgent: true, task: task)+ evidence.creationDate = task.creationDate+ owner.context.insert(evidence)+ }+ records.append(task)+ }+ tasks = records+ comment = Comment(content: "Canonical comment coverage", authorName: "Agent", isAgent: true,+ task: records[min(6, records.count - 1)])+ comment.id = MCPPortfolioFixture.commentID+ comment.creationDate = MCPPortfolioFixture.window.end.addingTimeInterval(60)+ owner.context.insert(comment)+ try owner.context.save()+ }++ func capture() throws -> CapturedReadView {+ try MCPReadCaptureBuilder(container: owner.container, fence: .actorOnlyTestFixture).capture(Self.request)+ }++ static var request: ReadCaptureRequest {+ ReadCaptureRequest(projectSelectors: nil, selection: .portfolio,+ completeness: .completePortfolio, includeComments: false)+ }+}+#endif
diff --git a/Transit/TransitTests/MCPPortfolioIntegrationTests.swift b/Transit/TransitTests/MCPPortfolioIntegrationTests.swiftnew file mode 100644index 0000000..9499d81--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioIntegrationTests.swift@@ -0,0 +1,266 @@+#if os(macOS)+import Foundation+import HTTPTypes+import Hummingbird+import SwiftData+import Testing+@testable import Transit++/// Actual router/body-writer acceptance preparation. Final API-15 transport negotiation remains separate.+@MainActor @Suite(.serialized)+struct MCPPortfolioIntegrationTests {+ @Test func routerCaptureExcludesPendingEditsWithoutSavingThem() async throws {+ let env = try Environment()+ try await withDrainedEnvironment(env) {+ let captured = try env.fixture.capture()+ env.fixture.project.name = "Unsaved project"+ env.fixture.tasks[0].taskDescription = "Unsaved description"+ env.fixture.comment.content = "Unsaved comment"+ let summary = try success(try await request(env, tool: "query_project_summaries", arguments: initial))+ let projects = try #require(summary.payload["projects"] as? [[String: Any]])+ #expect(projects.contains { $0["name"] as? String == "Populated" })+ #expect(!projects.contains { $0["name"] as? String == "Unsaved project" })+ let snapshot = try #require(summary.metadata["snapshotId"] as? String)+ let rows = try #require(try await taskPages(+ env, snapshot: snapshot, metadata: summary.metadata, limit: 100))+ let row = try #require(rows.first { $0["taskId"] as? String == env.fixture.tasks[0].id.uuidString })+ #expect(row["revision"] as? String == captured.tasks.first { $0.id == env.fixture.tasks[0].id }?.revision)+ #expect(row["description"] as? String != "Unsaved description")+ #expect(env.fixture.owner.context.hasChanges)+ #expect(env.fixture.tasks[0].taskDescription == "Unsaved description")+ #expect(env.fixture.project.name == "Unsaved project" && env.fixture.comment.content == "Unsaved comment")+ }+ }++ @Test func routerPagesReconcileEveryEffectiveStatusAndFreezeCanonicalRecordsAfterSavedChanges() async throws {+ let env = try Environment()+ try await withDrainedEnvironment(env) {+ let capture = try env.fixture.capture()+ let summary = try success(try await request(env, tool: "query_project_summaries", arguments: initial))+ let snapshot = try #require(summary.metadata["snapshotId"] as? String)+ let original = try #require(try await taskPages(+ env, snapshot: snapshot, metadata: summary.metadata, limit: 2))+ try reconcile(summary, rows: original, expected: capture)+ env.fixture.tasks[0].statusRawValue = "done"+ env.fixture.tasks[0].taskDescription = "Saved changed body"+ env.fixture.comment.content = "Saved changed comment"+ try env.fixture.owner.context.save()+ let replay = try success(try await request(+ env, tool: "query_project_summaries", arguments: ["snapshotId": snapshot]))+ #expect(try canonical(replay.payload) == canonical(summary.payload))+ #expect(try canonical(replay.metadata) == canonical(summary.metadata))+ let frozen = try #require(try await taskPages(+ env, snapshot: snapshot, metadata: summary.metadata, limit: 2))+ #expect(try canonical(frozen) == canonical(original))+ }+ }++ @Test func admissionLifecycleInvalidatesPublishedRootAndCursorWithoutAppendPublication() async throws {+ let env = try Environment()+ try await withDrainedEnvironment(env) {+ let summary = try success(try await request(env, tool: "query_project_summaries", arguments: initial))+ let snapshot = try #require(summary.metadata["snapshotId"] as? String)+ let page = try success(try await request(+ env, tool: "query_tasks", arguments: taskArguments(snapshot, limit: 1)))+ let cursor = try #require(page.payload["nextCursor"] as? String)+ env.handler.setTaskQueryAdmission(open: false)+ env.handler.setTaskQueryAdmission(open: false)+ try expectError(try await request(+ env, tool: "query_project_summaries", arguments: ["snapshotId": snapshot]),+ code: "INVALID_SNAPSHOT")+ try expectError(try await request(env, tool: "query_tasks", arguments: ["cursor": cursor]),+ code: "INVALID_CURSOR")+ let store = try env.handler.reusableSnapshots.get()+ let accounting = try store.domain.accounting(for: store.publicationStoreID)+ #expect(accounting.visibleEntries == 0 && accounting.pendingEntries == 0 && accounting.pendingBytes == 0)+ }+ }++ @Test func router2375CommentCoveredTasksReturnsCompleteSummaryAndReconciledPagesOrTypedFailure() async throws {+ let env = try Environment(taskCount: 2_375, commentOnEveryTask: true)+ try await withDrainedEnvironment(env) {+ let capture = try env.fixture.capture()+ let result = try await request(env, tool: "query_project_summaries", arguments: initial)+ if result["isError"] as? Bool == true {+ try expectVolumeFailure(result)+ } else {+ let summary = try success(result)+ let snapshot = try #require(summary.metadata["snapshotId"] as? String)+ if let rows = try await taskPages(+ env, snapshot: snapshot, metadata: summary.metadata, limit: 100, allowVolumeFailure: true+ ) {+ try reconcile(summary, rows: rows, expected: capture)+ #expect(rows.count == 2_375)+ }+ }+ await drain(env)+ let store = try env.handler.reusableSnapshots.get()+ let accounting = try store.domain.accounting(for: store.publicationStoreID)+ #expect(accounting.pendingEntries == 0 && accounting.pendingBytes == 0)+ if result["isError"] as? Bool == true { #expect(accounting.visibleEntries == 0) }+ }+ }+}++private extension MCPPortfolioIntegrationTests {+ @MainActor struct Environment {+ let fixture: MCPPortfolioSavedFixture+ let handler: MCPToolHandler++ init(taskCount: Int = 9, commentOnEveryTask: Bool = false) throws {+ fixture = try MCPPortfolioSavedFixture(taskCount: taskCount, commentOnEveryTask: commentOnEveryTask)+ let context = fixture.owner.context+ let taskAllocator = DisplayIDAllocator(store: InMemoryCounterStore())+ let milestoneAllocator = DisplayIDAllocator(store: InMemoryCounterStore())+ let tasks = TaskService(modelContext: context, displayIDAllocator: taskAllocator)+ let projects = ProjectService(modelContext: context)+ let comments = CommentService(modelContext: context)+ let milestones = MilestoneService(modelContext: context, displayIDAllocator: milestoneAllocator)+ let maintenance = DisplayIDMaintenanceService(modelContext: context, taskAllocator: taskAllocator,+ milestoneAllocator: milestoneAllocator, commentService: comments)+ let domain = MCPReadPublicationDomain()+ let snapshots = MCPTaskQuerySnapshotStore(domain: domain)+ let service = MCPReadService(source: MCPReadCaptureBuilder(container: fixture.owner.container,+ fence: .actorOnlyTestFixture),+ monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil),+ snapshots: snapshots, pagePreparer: {+ try MCPModernProviderBinding.prepareReadPages($0, tool: $1, operation: $2)+ })+ handler = MCPToolHandler(taskService: tasks, projectService: projects, commentService: comments,+ milestoneService: milestones, maintenanceService: maintenance, settings: MCPSettings(),+ persistence: FallbackOutcomeFixture.makeHealthy(), taskQuerySnapshots: snapshots,+ readService: service, readCoordinator: MCPReadCoordinator(domain: domain))+ }+ }++ struct Result {+ let payload: [String: Any]+ let metadata: [String: Any]+ }++ var initial: [String: Any] {+ ["start": "2026-10-03T00:00:00Z", "end": "2026-10-03T01:00:00Z", "limit": 100, "readPolicy": "cached"]+ }++ func taskArguments(_ snapshot: String, limit: Int) -> [String: Any] {+ ["snapshotId": snapshot, "detailLevel": "full", "includeComments": false, "limit": limit]+ }++ func request(_ env: Environment, tool: String, arguments: [String: Any]) async throws -> [String: Any] {+ let body = try MCPPortfolioModernHTTPHarness.request(tool: tool, arguments: arguments)+ let response = try await MCPPortfolioModernHTTPHarness.post(+ responder: MCPServer.makeRouter(handler: env.handler).buildResponder(), body: body, tool: tool)+ #expect(response.elapsed <= .seconds(5))+ #expect(response.status == .ok)+ let envelope = try #require(response.json as? [String: Any])+ #expect(envelope["id"] as? Int == 2382 && envelope["error"] == nil)+ let result = try #require(envelope["result"] as? [String: Any])+ #expect(result["resultType"] as? String == "complete" && result["structuredContent"] is [String: Any])+ return result+ }++ func success(_ result: [String: Any]) throws -> Result {+ try #require(result["isError"] as? Bool != true)+ let content = try #require(result["content"] as? [[String: Any]])+ let text = try #require(content.first?["text"] as? String)+ let payload = try #require(try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])+ let metadata = try #require((result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])+ return Result(payload: payload, metadata: metadata)+ }++ func taskPages(+ _ env: Environment, snapshot: String, metadata: [String: Any], limit: Int, allowVolumeFailure: Bool = false+ ) async throws -> [[String: Any]]? {+ var arguments = taskArguments(snapshot, limit: limit)+ var rows: [[String: Any]] = []+ var cursors = Set<String>()+ var expiresAt: String?+ repeat {+ let result = try await request(env, tool: "query_tasks", arguments: arguments)+ if allowVolumeFailure && result["isError"] as? Bool == true {+ try expectVolumeFailure(result)+ return nil // No partial page set is asserted as complete reconciliation.+ }+ let page = try success(result)+ #expect(try canonical(page.metadata) == canonical(metadata))+ let expiry = try #require(page.payload["expiresAt"] as? String)+ if let expiresAt { #expect(expiry == expiresAt) } else { expiresAt = expiry }+ rows += try #require(page.payload["results"] as? [[String: Any]])+ guard let cursor = page.payload["nextCursor"] as? String else {+ #expect(page.payload["nextCursor"] is NSNull)+ break+ }+ try #require(cursors.insert(cursor).inserted, "Continuation must make progress")+ arguments = ["cursor": cursor]+ } while true+ return rows+ }++ func reconcile(_ summary: Result, rows: [[String: Any]], expected: CapturedReadView) throws {+ let projects = try #require(summary.payload["projects"] as? [[String: Any]])+ let project = try #require(projects.first {+ $0["projectId"] as? String == MCPPortfolioFixture.populatedProjectID.uuidString+ })+ let counts = try #require(project["countsByStatus"] as? [String: Int])+ #expect(project["totalTaskCount"] as? Int == expected.tasks.count && rows.count == expected.tasks.count)+ for status in MCPSnapshotTaskQueryRequest.supportedStatuses {+ #expect(counts[status] == expected.tasks.filter { $0.effectiveStatus == status }.count)+ #expect(counts[status] == rows.filter { $0["status"] as? String == status }.count)+ }+ #expect(Set(rows.compactMap { $0["taskId"] as? String }).count == rows.count)+ for task in expected.tasks {+ let row = try #require(rows.first { $0["taskId"] as? String == task.id.uuidString })+ #expect(row["revision"] as? String == task.revision && row["comments"] == nil)+ #expect(row["description"] as? String == task.taskDescription)+ }+ }++ func expectError(_ result: [String: Any], code: String) throws {+ #expect(result["isError"] as? Bool == true)+ let content = try #require(result["content"] as? [[String: Any]])+ let text = try #require(content.first?["text"] as? String)+ let payload = try #require(try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])+ #expect((payload["error"] as? [String: Any])?["code"] as? String == code)+ }++ func expectVolumeFailure(_ result: [String: Any]) throws {+ let content = try #require(result["content"] as? [[String: Any]])+ let text = try #require(content.first?["text"] as? String)+ let payload = try #require(try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])+ let code = try #require((payload["error"] as? [String: Any])?["code"] as? String)+ #expect(["READ_TIMEOUT", "QUERY_CAPACITY_EXCEEDED"].contains(code))+ #expect(payload["projects"] == nil && payload["results"] == nil && payload["nextCursor"] == nil)+ let read = (result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any]+ if code == "READ_TIMEOUT" {+ #expect(read?["category"] as? String == "READ_TIMEOUT")+ #expect(read?["requestId"] is String && read?["read"] is [String: Any])+ }+ // Owner capacity errors carry no invented capture evidence; timeout metadata is failure evidence only.+ #expect(read?["snapshotId"] == nil && read?["asOf"] == nil && read?["freshness"] == nil)+ }++ func canonical(_ value: Any) throws -> Data {+ try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys])+ }++ func withDrainedEnvironment(_ env: Environment, body: () async throws -> Void) async throws {+ do {+ try await body()+ await drain(env)+ } catch {+ await drain(env)+ throw error+ }+ }++ func drain(_ env: Environment) async {+ let deadline = ContinuousClock.now.advanced(by: .seconds(8))+ while env.handler.readCoordinator.unfinishedCount != 0 && ContinuousClock.now < deadline {+ // Independent sleep still waits when the test task has been cancelled.+ await Task.detached { try? await Task.sleep(for: .milliseconds(25)) }.value+ }+ #expect(env.handler.readCoordinator.unfinishedCount == 0, "Physical workers must drain before fixture release")+ withExtendedLifetime(env.fixture) {}+ }+}+#endif
diff --git a/Transit/TransitTests/MCPPortfolioModernAcceptanceTests.swift b/Transit/TransitTests/MCPPortfolioModernAcceptanceTests.swiftnew file mode 100644index 0000000..67c8916--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioModernAcceptanceTests.swift@@ -0,0 +1,309 @@+#if os(macOS)+import Foundation+import HTTPTypes+import Hummingbird+import SwiftData+import Testing+@testable import Transit++/// Combined modern consumer acceptance; common adapters and retained-fragment ownership stay external.+@MainActor @Suite(.serialized)+struct MCPPortfolioModernAcceptanceTests {+ @Test func discoverySchemasAndStatelessValidationRejectBeforeCapture() async throws {+ let env = try Environment()+ try await withDrainedEnvironment(env) {+ let discovery = try await send(env, method: "server/discover")+ let discovered = try result(discovery)+ #expect(discovered["supportedVersions"] as? [String] == ["2026-07-28"])+ #expect(discovered["resultType"] as? String == "complete")+ let listed = try result(try await send(env, method: "tools/list"))+ let tools = try #require(listed["tools"] as? [[String: Any]])+ for name in ["query_project_summaries", "query_tasks"] {+ let tool = try #require(tools.first { $0["name"] as? String == name })+ let output = try #require(tool["outputSchema"] as? [String: Any])+ let properties = try #require(output["properties"] as? [String: Any])+ #expect(properties["contractVersion"] != nil && properties["source"] != nil+ && properties["presentation"] != nil)+ let required = try #require(output["required"] as? [String])+ #expect(Set(required) == ["contractVersion", "source", "presentation"])+ #expect(output["additionalProperties"] as? Bool == false)+ let version = try #require(properties["contractVersion"] as? [String: Any])+ #expect(version["const"] as? Int == 1)+ #expect(tool["inputSchema"] is [String: Any])+ }+ let valid = try MCPPortfolioModernHTTPHarness.request(tool: "query_project_summaries", arguments: initial)+ let missing = Data("""+ {"jsonrpc":"2.0","id":2382,"method":"tools/call",+ "params":{"name":"query_project_summaries","arguments":{}}}+ """.utf8)+ let oldVersion = Data(try #require(String(data: valid, encoding: .utf8))+ .replacingOccurrences(of: "2026-07-28", with: "2025-03-26").utf8)+ let cases = [+ Rejected(body: Data("[".utf8) + valid + Data("]".utf8), code: -32600),+ Rejected(body: missing, code: -32602),+ Rejected(body: valid, method: "tools/list", code: -32020),+ Rejected(body: valid, tool: "query_tasks", code: -32020),+ Rejected(body: valid, version: "2025-03-26", code: -32020),+ Rejected(body: oldVersion, version: "2025-03-26", code: -32022)+ ]+ for invalid in cases {+ let rejected = try await MCPPortfolioModernHTTPHarness.post(+ responder: MCPServer.makeRouter(handler: env.handler).buildResponder(), body: invalid.body,+ tool: invalid.tool, method: invalid.method, version: invalid.version)+ #expect(rejected.status == .badRequest)+ let envelope = try #require(rejected.json as? [String: Any])+ #expect((envelope["error"] as? [String: Any])?["code"] as? Int == invalid.code)+ #expect(envelope["result"] == nil)+ }+ #expect(env.fetchCount.value == 0)+ let accounting = try env.handler.reusableSnapshots.get().domain.accounting(+ for: env.handler.reusableSnapshots.get().publicationStoreID)+ #expect(accounting.visibleEntries == 0 && accounting.pendingEntries == 0)+ }+ }++ @Test func structuredSourcePreservesLargeDisplayIDAndExactFrozenMetadataBytes() async throws {+ let env = try Environment()+ try await withDrainedEnvironment(env) {+ env.fixture.tasks[0].permanentDisplayId = 9_007_199_254_740_993+ try env.fixture.owner.context.save()+ let summaryResponse = try await send(env, tool: "query_project_summaries", arguments: initial)+ let summary = try checkedSource(summaryResponse)+ let snapshot = try #require(summary.metadata["snapshotId"] as? String)+ let root = try env.handler.reusableSnapshots.get().retainedView(for: snapshot, now: .now)+ try exactMetadata(summaryResponse, bytes: root.frozenMetadataBytes)+ let response = try await send(env, tool: "query_tasks", arguments: taskArguments(snapshot, limit: 100))+ let source = try checkedSource(response)+ try exactMetadata(response, bytes: root.frozenMetadataBytes)+ let rows = try #require(source.payload["results"] as? [[String: Any]])+ #expect(rows.count == 9 && rows.allSatisfy { $0["comments"] == nil && $0["revision"] is String })+ let values = try array(member("results", source.value))+ let row = try #require(values.first {+ string(member("taskId", $0)) == env.fixture.tasks[0].id.uuidString+ })+ guard case .number(let displayID) = member("displayId", row) else {+ throw MCPResultBoundaryError.unsupportedEvidence+ }+ #expect(displayID.lexeme == "9007199254740993")+ #expect(root.capture.tasks.first { $0.id == env.fixture.tasks[0].id }?.revision+ == rows.first {+ $0["taskId"] as? String == env.fixture.tasks[0].id.uuidString+ }?["revision"] as? String)+ }+ }++ @Test func modernFrozenPagesReconcileAllStatusesAfterSavedMutationWithoutRecapture() async throws {+ let env = try Environment()+ try await withDrainedEnvironment(env) {+ let response = try await send(env, tool: "query_project_summaries", arguments: initial)+ let summary = try checkedSource(response)+ let snapshot = try #require(summary.metadata["snapshotId"] as? String)+ let root = try env.handler.reusableSnapshots.get().retainedView(for: snapshot, now: .now)+ let projects = try #require(summary.payload["projects"] as? [[String: Any]])+ let project = try #require(projects.first {+ $0["projectId"] as? String == MCPPortfolioFixture.populatedProjectID.uuidString+ })+ let counts = try #require(project["countsByStatus"] as? [String: Int])+ env.fixture.tasks[0].statusRawValue = "done"+ env.fixture.comment.content = "Later saved comment"+ try env.fixture.owner.context.save()+ for status in MCPSnapshotTaskQueryRequest.supportedStatuses {+ var arguments = taskArguments(snapshot, limit: 1)+ arguments["status"] = [status]+ var rows: [[String: Any]] = []+ var cursors = Set<String>()+ repeat {+ let pageResponse = try await send(env, tool: "query_tasks", arguments: arguments)+ let page = try checkedSource(pageResponse)+ try exactMetadata(pageResponse, bytes: root.frozenMetadataBytes)+ #expect(page.payload["expiresAt"] as? String == summary.payload["expiresAt"] as? String)+ rows += try #require(page.payload["results"] as? [[String: Any]])+ guard let cursor = page.payload["nextCursor"] as? String else { break }+ try #require(cursors.insert(cursor).inserted)+ #expect(MCPCursorFamily.classify(cursor) == .reusable)+ arguments = ["cursor": cursor]+ } while true+ #expect(rows.count == counts[status] && rows.allSatisfy { $0["status"] as? String == status })+ }+ #expect(env.fetchCount.value == 1)+ let replayResponse = try await send(+ env, tool: "query_project_summaries", arguments: ["snapshotId": snapshot], id: 2383)+ let replay = try checkedSource(replayResponse, id: 2383)+ #expect(replay.text == summary.text && replay.value == summary.value)+ try exactMetadata(replayResponse, bytes: root.frozenMetadataBytes)+ #expect(env.fetchCount.value == 1)+ }+ }++ @Test func modernOrdinaryV4PagesKeepRawStatusFieldsAndOriginalMetadataAfterSavedChanges() async throws {+ let env = try Environment()+ try await withDrainedEnvironment(env) {+ let firstResponse = try await send(env, tool: "query_tasks", arguments: [+ "detailLevel": "summary", "includeComments": false, "limit": 1, "readPolicy": "cached"])+ let first = try checkedSource(firstResponse)+ var cursor = try #require(first.payload["nextCursor"] as? String)+ #expect(MCPCursorFamily.classify(cursor) == .ordinary)+ let retained = try env.handler.taskQuerySnapshots.retainedPage(for: cursor)+ let metadata = try #require(retained.metadataBytes)+ try exactMetadata(firstResponse, bytes: metadata)+ var rows = try #require(first.payload["results"] as? [[String: Any]])+ env.fixture.tasks[8].statusRawValue = "done"+ try env.fixture.owner.context.save()+ var cursors = Set<String>()+ while true {+ try #require(cursors.insert(cursor).inserted)+ let response = try await send(env, tool: "query_tasks", arguments: ["cursor": cursor])+ let page = try checkedSource(response)+ try exactMetadata(response, bytes: metadata)+ #expect(page.payload["expiresAt"] as? String == first.payload["expiresAt"] as? String)+ rows += try #require(page.payload["results"] as? [[String: Any]])+ guard let next = page.payload["nextCursor"] as? String else { break }+ #expect(MCPCursorFamily.classify(next) == .ordinary)+ cursor = next+ }+ #expect(rows.count == 9 && rows.contains { $0["status"] as? String == "unknown" })+ #expect(rows.allSatisfy { $0["revision"] == nil && $0["description"] == nil && $0["comments"] == nil })+ #expect(env.fetchCount.value == 1)+ }+ }+}++private extension MCPPortfolioModernAcceptanceTests {+ struct Rejected {+ let body: Data+ var method = "tools/call"+ var tool = "query_project_summaries"+ var version = "2026-07-28"+ let code: Int+ }++ @MainActor final class FetchCount { var value = 0 }+ @MainActor struct Environment {+ let fixture: MCPPortfolioSavedFixture+ let handler: MCPToolHandler+ let fetchCount: FetchCount++ init(taskCount: Int = 9, commentOnEveryTask: Bool = false) throws {+ fixture = try MCPPortfolioSavedFixture(taskCount: taskCount, commentOnEveryTask: commentOnEveryTask)+ let counter = FetchCount()+ fetchCount = counter+ let context = fixture.owner.context+ let taskAllocator = DisplayIDAllocator(store: InMemoryCounterStore())+ let milestoneAllocator = DisplayIDAllocator(store: InMemoryCounterStore())+ let tasks = TaskService(modelContext: context, displayIDAllocator: taskAllocator)+ let projects = ProjectService(modelContext: context)+ let comments = CommentService(modelContext: context)+ let milestones = MilestoneService(modelContext: context, displayIDAllocator: milestoneAllocator)+ let maintenance = DisplayIDMaintenanceService(modelContext: context, taskAllocator: taskAllocator,+ milestoneAllocator: milestoneAllocator, commentService: comments)+ let domain = MCPReadPublicationDomain()+ let snapshots = MCPTaskQuerySnapshotStore(domain: domain)+ let service = MCPReadService(source: MCPReadCaptureBuilder(container: fixture.owner.container,+ fence: .actorOnlyTestFixture, fetchTasks: { context in+ counter.value += 1+ return try context.fetch(FetchDescriptor<TransitTask>())+ }),+ monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil),+ snapshots: snapshots, pagePreparer: {+ try MCPModernProviderBinding.prepareReadPages($0, tool: $1, operation: $2)+ })+ handler = MCPToolHandler(taskService: tasks, projectService: projects, commentService: comments,+ milestoneService: milestones, maintenanceService: maintenance, settings: MCPSettings(),+ persistence: FallbackOutcomeFixture.makeHealthy(), taskQuerySnapshots: snapshots,+ readService: service, readCoordinator: MCPReadCoordinator(domain: domain))+ }+ }++ struct Source {+ let text: String+ let value: MCPJSONValue+ let payload: [String: Any]+ let metadata: [String: Any]+ }++ var initial: [String: Any] {+ ["start": "2026-10-03T00:00:00Z", "end": "2026-10-03T01:00:00Z", "limit": 100, "readPolicy": "cached"]+ }++ func taskArguments(_ snapshot: String, limit: Int) -> [String: Any] {+ ["snapshotId": snapshot, "detailLevel": "full", "includeComments": false, "limit": limit]+ }++ func send(_ env: Environment, tool: String? = nil, arguments: [String: Any] = [:],+ method: String = "tools/call", id: Int = 2382) async throws -> MCPPortfolioModernHTTPHarness.Response {+ let body = try MCPPortfolioModernHTTPHarness.request(tool: tool, arguments: arguments, method: method, id: id)+ let response = try await MCPPortfolioModernHTTPHarness.post(+ responder: MCPServer.makeRouter(handler: env.handler).buildResponder(),+ body: body, tool: tool, method: method)+ #expect(response.status == .ok && response.elapsed <= .seconds(5))+ return response+ }++ func result(_ response: MCPPortfolioModernHTTPHarness.Response, id: Int = 2382) throws -> [String: Any] {+ let envelope = try #require(response.json as? [String: Any])+ #expect(envelope["id"] as? Int == id && envelope["error"] == nil)+ return try #require(envelope["result"] as? [String: Any])+ }++ func checkedSource(_ response: MCPPortfolioModernHTTPHarness.Response, id: Int = 2382) throws -> Source {+ let result = try result(response, id: id)+ try #require(result["isError"] as? Bool != true)+ #expect(result["resultType"] as? String == "complete")+ let content = try #require(result["content"] as? [[String: Any]])+ #expect(content.count == 1 && content.first?["type"] as? String == "text")+ let text = try #require(content.first?["text"] as? String)+ let document = try MCPJSONDocument.parse(response.body)+ let structured = member("structuredContent", member("result", document.value))+ guard case .number(let version) = member("contractVersion", structured) else {+ throw MCPResultBoundaryError.unsupportedEvidence+ }+ #expect(version.lexeme == "1" && string(member("kind", member("source", structured))) == "json")+ let value = try #require(member("payload", member("source", structured)))+ #expect(try value == MCPJSONDocument.parse(text).value)+ let payload = try #require(try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])+ let metadata = try #require((result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])+ return Source(text: text, value: value, payload: payload, metadata: metadata)+ }++ func member(_ name: String, _ value: MCPJSONValue?) -> MCPJSONValue? {+ guard case .object(let fields) = value else { return nil }+ return fields.first { $0.name == name }?.value+ }++ func string(_ value: MCPJSONValue?) -> String? {+ guard case .string(let value) = value else { return nil }+ return value+ }++ func array(_ value: MCPJSONValue?) throws -> [MCPJSONValue] {+ guard case .array(let values) = value else { throw MCPResultBoundaryError.unsupportedEvidence }+ return values+ }++ func exactMetadata(_ response: MCPPortfolioModernHTTPHarness.Response, bytes: Data) throws {+ let namespace = Data("\"me.nore.ig.transit/read\":".utf8) + bytes+ #expect(response.body.range(of: namespace) != nil, "Retained metadata bytes must be inserted unchanged")+ _ = try MCPJSONDocument.parse(bytes)+ }++ func withDrainedEnvironment(_ env: Environment, body: () async throws -> Void) async throws {+ do {+ try await body()+ await drain(env)+ } catch {+ await drain(env)+ throw error+ }+ }++ func drain(_ env: Environment) async {+ let deadline = ContinuousClock.now.advanced(by: .seconds(8))+ while env.handler.readCoordinator.unfinishedCount != 0 && ContinuousClock.now < deadline {+ // Independent sleep still waits when the test task has been cancelled.+ await Task.detached { try? await Task.sleep(for: .milliseconds(25)) }.value+ }+ #expect(env.handler.readCoordinator.unfinishedCount == 0, "Physical workers must drain before fixture release")+ withExtendedLifetime(env.fixture) {}+ }+}+#endif
diff --git a/Transit/TransitTests/MCPPortfolioModernHTTPHarness.swift b/Transit/TransitTests/MCPPortfolioModernHTTPHarness.swiftnew file mode 100644index 0000000..9ec75b7--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioModernHTTPHarness.swift@@ -0,0 +1,77 @@+#if os(macOS)+import Foundation+import HTTPTypes+import Hummingbird+import Logging+import NIOConcurrencyHelpers+import NIOCore+import NIOEmbedded+import NIOFoundationCompat+import Testing+@testable import Transit++/// Test transport only: the delivered validator/provider remain the protocol/result owners.+nonisolated enum MCPPortfolioModernHTTPHarness {+ struct Response: Sendable {+ let status: HTTPResponse.Status+ let body: Data+ let elapsed: Duration+ var json: Any? { try? JSONSerialization.jsonObject(with: body) }+ }++ static func request(tool: String? = nil, arguments: [String: Any] = [:],+ method: String = "tools/call", id: Int = 2382) throws -> Data {+ var params: [String: Any] = ["_meta": [+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",+ "io.modelcontextprotocol/clientCapabilities": [:] as [String: Any]]]+ if let tool { params["name"] = tool; params["arguments"] = arguments }+ return try JSONSerialization.data(withJSONObject: ["jsonrpc": "2.0", "id": id,+ "method": method, "params": params])+ }++ @concurrent static func post(responder: RouterResponder<MCPRequestContext>, body: Data,+ tool: String? = nil, method: String = "tools/call",+ version: String = "2026-07-28") async throws -> Response {+ let loop = NIOAsyncTestingEventLoop()+ var ownedChannel: NIOAsyncTestingChannel?+ do {+ let channel = try await NIOAsyncTestingChannel(loop: loop) { _ in }+ ownedChannel = channel+ var headers: HTTPFields = [.contentType: "application/json", .accept: "application/json"]+ headers[HTTPField.Name("MCP-Protocol-Version")!] = version+ headers[HTTPField.Name("Mcp-Method")!] = method+ if let tool { headers[HTTPField.Name("Mcp-Name")!] = tool }+ let context = MCPRequestContext(source: ApplicationRequestContextSource(+ channel: channel, logger: Logger(label: "portfolio-modern-router")))+ let request = Request(head: HTTPRequest(method: .post, scheme: "http", authority: "127.0.0.1:3141",+ path: "/mcp", headerFields: headers), body: RequestBody(buffer: ByteBuffer(data: body)))+ let start = ContinuousClock.now+ let response = try await responder.respond(to: request, context: context)+ let writer = Writer()+ try await response.body.write(writer)+ let elapsed = start.duration(to: .now)+ let result = Response(status: response.status,+ body: Data(buffer: writer.bytes.withLockedValue { $0 }), elapsed: elapsed)+ let leftovers = try await channel.finish(acceptAlreadyClosed: true)+ #expect(leftovers.isClean)+ await loop.shutdownGracefully()+ return result+ } catch {+ if let channel = ownedChannel {+ do {+ let leftovers = try await channel.finish(acceptAlreadyClosed: true)+ #expect(leftovers.isClean)+ } catch { Issue.record("Modern test channel cleanup failed: \(error)") }+ }+ await loop.shutdownGracefully()+ throw error+ }+ }++ private final class Writer: ResponseBodyWriter, Sendable {+ let bytes = NIOLockedValueBox(ByteBuffer())+ func write(_ buffer: ByteBuffer) async throws { _ = bytes.withLockedValue { $0.writeImmutableBuffer(buffer) } }+ func finish(_: HTTPFields?) async throws {}+ }+}+#endif
diff --git a/Transit/TransitTests/MCPPortfolioRouterDeadlineTests.swift b/Transit/TransitTests/MCPPortfolioRouterDeadlineTests.swiftnew file mode 100644index 0000000..ea1d828--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioRouterDeadlineTests.swift@@ -0,0 +1,216 @@+#if os(macOS)+import Foundation+import HTTPTypes+import Hummingbird+import Logging+import NIOConcurrencyHelpers+import NIOCore+import NIOEmbedded+import NIOFoundationCompat+import SwiftData+import Testing+@testable import Transit++/// Real individual POSTs; coordinator stop/start is not a full MCPServer restart assertion.+@Suite(.serialized)+nonisolated struct MCPPortfolioRouterDeadlineTests {+ @Test @concurrent func blockedRegisteredSummaryReturnsTimeoutBeforePhysicalCaptureFinishes() async throws {+ try await Self.withPrepared { prepared in+ let response = try await Self.post(prepared, id: 2382)+ try Self.failure(response, code: "READ_TIMEOUT")+ #expect(prepared.latch.started && !prepared.latch.finished)+ #expect(prepared.coordinator.unfinishedCount == 1)+ let accounting = try prepared.store.domain.accounting(for: prepared.store.publicationStoreID)+ #expect(accounting.visibleEntries == 0 && accounting.pendingEntries == 0)+ }+ }++ @Test @concurrent func eightActualPostsRetainPhysicalChargeAcrossCoordinatorRestartAndNinthIsBusy() async throws {+ try await Self.withPrepared { prepared in+ let responses = try await withThrowingTaskGroup(of: WireResponse.self) { group in+ for id in 1...8 { group.addTask { try await Self.post(prepared, id: id) } }+ var results: [WireResponse] = []+ for try await response in group { results.append(response) }+ return results+ }+ #expect(responses.count == 8 && Set(responses.map(\.id)).count == 8)+ var requestIDs = Set<String>()+ for response in responses { requestIDs.insert(try Self.failure(response, code: "READ_TIMEOUT")) }+ #expect(requestIDs.count == 8)+ #expect(prepared.latch.started && !prepared.latch.finished)+ #expect(prepared.coordinator.unfinishedCount == 8)+ prepared.coordinator.stop()+ prepared.coordinator.start()+ #expect(prepared.coordinator.unfinishedCount == 8)+ try Self.failure(try await Self.post(prepared, id: 9), code: "READ_BUSY")+ #expect(prepared.coordinator.unfinishedCount == 8)+ }+ }+}++private extension MCPPortfolioRouterDeadlineTests {+ struct Prepared: Sendable {+ let owner: Owner+ let responder: RouterResponder<MCPRequestContext>+ let coordinator: MCPReadCoordinator+ let store: MCPReusableSnapshotStore+ let latch: CaptureLatch+ }++ struct LatchSnapshot {+ let released: Bool+ let entries: Int+ let completions: Int+ let expirations: Int+ }++ final class CaptureLatch: @unchecked Sendable {+ private let condition = NSCondition()+ private var released = false+ private var entries = 0+ private var completions = 0+ private var failSafeExpirations = 0+ private var snapshot: LatchSnapshot {+ condition.lock()+ defer { condition.unlock() }+ return LatchSnapshot(released: released, entries: entries, completions: completions,+ expirations: failSafeExpirations)+ }+ var started: Bool { snapshot.entries > 0 }+ var finished: Bool { let value = snapshot; return value.entries > 0 && value.completions == value.entries }+ var explicitlyReleased: Bool { let value = snapshot; return value.released && value.expirations == 0 }+ var entryCount: Int { snapshot.entries }+ var completionCount: Int { snapshot.completions }+ func block() {+ condition.lock()+ entries += 1+ let deadline = ContinuousClock.now.advanced(by: .seconds(12))+ while !released && ContinuousClock.now < deadline {+ _ = condition.wait(until: Date().addingTimeInterval(0.1))+ }+ if !released { failSafeExpirations += 1 }+ completions += 1+ condition.unlock()+ }+ func unblock() {+ condition.lock()+ released = true+ condition.broadcast() // Idempotent release also lets unexpected later entries return immediately.+ condition.unlock()+ }+ }++ @MainActor final class Owner {+ let fixture: MCPPortfolioSavedFixture+ let handler: MCPToolHandler++ init(latch: CaptureLatch) throws {+ fixture = try MCPPortfolioSavedFixture()+ let context = fixture.owner.context+ let taskAllocator = DisplayIDAllocator(store: InMemoryCounterStore())+ let milestoneAllocator = DisplayIDAllocator(store: InMemoryCounterStore())+ let tasks = TaskService(modelContext: context, displayIDAllocator: taskAllocator)+ let projects = ProjectService(modelContext: context)+ let comments = CommentService(modelContext: context)+ let milestones = MilestoneService(modelContext: context, displayIDAllocator: milestoneAllocator)+ let maintenance = DisplayIDMaintenanceService(modelContext: context, taskAllocator: taskAllocator,+ milestoneAllocator: milestoneAllocator, commentService: comments)+ let domain = MCPReadPublicationDomain()+ let snapshots = MCPTaskQuerySnapshotStore(domain: domain)+ let service = MCPReadService(source: MCPReadCaptureBuilder(container: fixture.owner.container,+ fence: .actorOnlyTestFixture, fetchTasks: { context in+ latch.block()+ return try context.fetch(FetchDescriptor<TransitTask>())+ }),+ monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil),+ snapshots: snapshots, pagePreparer: {+ try MCPModernProviderBinding.prepareReadPages($0, tool: $1, operation: $2)+ })+ handler = MCPToolHandler(taskService: tasks, projectService: projects, commentService: comments,+ milestoneService: milestones, maintenanceService: maintenance, settings: MCPSettings(),+ persistence: FallbackOutcomeFixture.makeHealthy(), taskQuerySnapshots: snapshots,+ readService: service, readCoordinator: MCPReadCoordinator(domain: domain))+ }+ }++ struct WireResponse: Sendable {+ let id: Int+ let bytes: Data+ let elapsed: Duration+ }++ @MainActor static func prepare() throws -> Prepared {+ let latch = CaptureLatch()+ let owner = try Owner(latch: latch)+ return Prepared(owner: owner, responder: MCPServer.makeRouter(handler: owner.handler).buildResponder(),+ coordinator: owner.handler.readCoordinator, store: try owner.handler.reusableSnapshots.get(), latch: latch)+ }++ @concurrent static func post(_ prepared: Prepared, id: Int) async throws -> WireResponse {+ let body = try MCPPortfolioModernHTTPHarness.request(tool: "query_project_summaries", arguments: [+ "start": "2026-10-03T00:00:00Z", "end": "2026-10-03T01:00:00Z", "limit": 100,+ "readPolicy": "cached"], id: id)+ let response = try await MCPPortfolioModernHTTPHarness.post(+ responder: prepared.responder, body: body, tool: "query_project_summaries")+ #expect(response.status == .ok && response.elapsed <= .seconds(5))+ return WireResponse(id: id, bytes: response.body, elapsed: response.elapsed)+ }++ @discardableResult static func failure(_ response: WireResponse, code: String) throws -> String {+ let envelope = try #require(try JSONSerialization.jsonObject(with: response.bytes) as? [String: Any])+ #expect(envelope["id"] as? Int == response.id && envelope["error"] == nil)+ let result = try #require(envelope["result"] as? [String: Any])+ #expect(result["isError"] as? Bool == true && result["resultType"] as? String == "complete")+ let content = try #require(result["content"] as? [[String: Any]])+ let text = try #require(content.first?["text"] as? String)+ let payload = try #require(try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])+ #expect((payload["error"] as? [String: Any])?["code"] as? String == code)+ let wireValue = try MCPJSONDocument.parse(response.bytes).value+ guard case .object(let root) = wireValue,+ case .object(let toolResult) = root.first(where: { $0.name == "result" })?.value,+ case .object(let structured) = toolResult.first(where: { $0.name == "structuredContent" })?.value,+ case .object(let source) = structured.first(where: { $0.name == "source" })?.value else {+ Issue.record("Missing modern source wrapper")+ throw MCPResultBoundaryError.unsupportedEvidence+ }+ #expect(try source.first(where: { $0.name == "payload" })?.value == MCPJSONDocument.parse(text).value)+ #expect(payload["snapshotId"] == nil && payload["nextCursor"] == nil && payload["projects"] == nil)+ let metadata = try #require((result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])+ #expect(metadata["category"] as? String == code)+ #expect(metadata["snapshotId"] == nil && metadata["asOf"] == nil && metadata["freshness"] == nil)+ let read = try #require(metadata["read"] as? [String: Any])+ #expect(read["policy"] as? String == "cached" && read["budgetMs"] as? Int == 5_000)+ let requestID = try #require(metadata["requestId"] as? String)+ #expect(UUID(uuidString: requestID) != nil)+ return requestID+ }++ @concurrent static func withPrepared(_ body: @Sendable (Prepared) async throws -> Void) async throws {+ let prepared = try await prepare()+ do {+ try await body(prepared)+ await cleanup(prepared)+ } catch {+ await cleanup(prepared)+ throw error+ }+ }++ @concurrent static func cleanup(_ prepared: Prepared) async {+ prepared.latch.unblock() // Always release before any actor hop, including assertion/parser throws.+ let deadline = ContinuousClock.now.advanced(by: .seconds(8))+ while prepared.coordinator.unfinishedCount != 0 && ContinuousClock.now < deadline {+ await Task.detached { try? await Task.sleep(for: .milliseconds(25)) }.value+ }+ #expect(prepared.coordinator.unfinishedCount == 0)+ #expect(prepared.latch.finished && prepared.latch.explicitlyReleased)+ #expect(prepared.latch.entryCount == 1 && prepared.latch.completionCount == 1)+ do {+ let accounting = try prepared.store.domain.accounting(for: prepared.store.publicationStoreID)+ #expect(accounting.visibleEntries == 0 && accounting.visibleBytes == 0)+ #expect(accounting.pendingEntries == 0 && accounting.pendingBytes == 0)+ } catch { Issue.record("Could not inspect drained publication accounting: \(error)") }+ withExtendedLifetime(prepared.owner) {}+ }+}+#endif
diff --git a/Transit/TransitTests/MCPPortfolioRouterExpiryTests.swift b/Transit/TransitTests/MCPPortfolioRouterExpiryTests.swiftnew file mode 100644index 0000000..6cb78cc--- /dev/null+++ b/Transit/TransitTests/MCPPortfolioRouterExpiryTests.swift@@ -0,0 +1,169 @@+#if os(macOS)+import Foundation+import HTTPTypes+import Hummingbird+import SwiftData+import Testing+@testable import Transit++/// Retention clock boundaries through real registered single-object router requests.+@MainActor @Suite(.serialized)+struct MCPPortfolioRouterExpiryTests {+ @Test func summaryReplayKeepsOriginalExpiryUntilExactDeadline() async throws {+ try await verifyBoundary(cursorMode: false)+ }++ @Test func publishedTaskCursorKeepsOriginalExpiryUntilExactDeadline() async throws {+ try await verifyBoundary(cursorMode: true)+ }+}++private extension MCPPortfolioRouterExpiryTests {+ @MainActor final class FetchCount { var value = 0 }++ func verifyBoundary(cursorMode: Bool) async throws {+ let env = try Environment()+ try await withDrainedEnvironment(env) {+ let summary = try success(try await request(env, tool: "query_project_summaries", arguments: initial))+ let snapshot = try #require(summary.metadata["snapshotId"] as? String)+ let first = try success(try await request(+ env, tool: "query_tasks", arguments: taskArguments(snapshot, limit: 1)))+ let cursor = try #require(first.payload["nextCursor"] as? String)+ let tool = cursorMode ? "query_tasks" : "query_project_summaries"+ let arguments: [String: Any] = cursorMode ? ["cursor": cursor] : ["snapshotId": snapshot]+ let original = try success(try await request(env, tool: tool, arguments: arguments))+ let expiry = try #require(original.payload["expiresAt"] as? String)+ #expect(first.payload["expiresAt"] as? String == expiry)+ #expect(try canonical(original.metadata) == canonical(summary.metadata))+ let store = try env.handler.reusableSnapshots.get()+ let root = try store.retainedView(for: snapshot, now: .now)+ #expect(root.capture.createdAt.duration(to: root.capture.retentionDeadline) == .seconds(300))+ let fetches = env.fetchCount.value+ #expect(fetches == 1)+ // These are pin-only reads of existing bytes, never new projection/reservation at a future clock.+ store.domain.setTestingInstant(root.capture.retentionDeadline - .milliseconds(1))+ let near = try success(try await request(env, tool: tool, arguments: arguments))+ #expect(try canonical(near.payload) == canonical(original.payload))+ #expect(try canonical(near.metadata) == canonical(original.metadata))+ #expect(near.payload["expiresAt"] as? String == expiry)+ #expect(env.fetchCount.value == fetches)+ await drain(env)+ let before = try store.domain.accounting(for: store.publicationStoreID)+ store.domain.setTestingInstant(root.capture.retentionDeadline)+ let expired = try await request(env, tool: tool, arguments: arguments)+ try expectFamilyError(expired, code: cursorMode ? "INVALID_CURSOR" : "INVALID_SNAPSHOT")+ #expect(env.fetchCount.value == fetches)+ await drain(env)+ let after = try store.domain.accounting(for: store.publicationStoreID)+ #expect(after.pendingEntries == 0 && after.pendingBytes == 0)+ #expect(after.visibleEntries <= before.visibleEntries && after.visibleBytes <= before.visibleBytes)+ }+ }++ func expectFamilyError(_ result: [String: Any], code: String) throws {+ #expect(result["isError"] as? Bool == true)+ let content = try #require(result["content"] as? [[String: Any]])+ let text = try #require(content.first?["text"] as? String)+ let payload = try #require(try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])+ #expect((payload["error"] as? [String: Any])?["code"] as? String == code)+ #expect(payload["snapshotId"] == nil && payload["nextCursor"] == nil && payload["results"] == nil)+ let metadata = (result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any]+ #expect(metadata?["snapshotId"] == nil && metadata?["asOf"] == nil && metadata?["freshness"] == nil)+ }++ @MainActor struct Environment {+ let fixture: MCPPortfolioSavedFixture+ let handler: MCPToolHandler+ let fetchCount: FetchCount++ init(taskCount: Int = 9, commentOnEveryTask: Bool = false) throws {+ fixture = try MCPPortfolioSavedFixture(taskCount: taskCount, commentOnEveryTask: commentOnEveryTask)+ let counter = FetchCount()+ fetchCount = counter+ let context = fixture.owner.context+ let taskAllocator = DisplayIDAllocator(store: InMemoryCounterStore())+ let milestoneAllocator = DisplayIDAllocator(store: InMemoryCounterStore())+ let tasks = TaskService(modelContext: context, displayIDAllocator: taskAllocator)+ let projects = ProjectService(modelContext: context)+ let comments = CommentService(modelContext: context)+ let milestones = MilestoneService(modelContext: context, displayIDAllocator: milestoneAllocator)+ let maintenance = DisplayIDMaintenanceService(modelContext: context, taskAllocator: taskAllocator,+ milestoneAllocator: milestoneAllocator, commentService: comments)+ let domain = MCPReadPublicationDomain()+ let snapshots = MCPTaskQuerySnapshotStore(domain: domain)+ let service = MCPReadService(source: MCPReadCaptureBuilder(container: fixture.owner.container,+ fence: .actorOnlyTestFixture, fetchTasks: { context in+ counter.value += 1+ return try context.fetch(FetchDescriptor<TransitTask>())+ }),+ monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil),+ snapshots: snapshots, pagePreparer: {+ try MCPModernProviderBinding.prepareReadPages($0, tool: $1, operation: $2)+ })+ handler = MCPToolHandler(taskService: tasks, projectService: projects, commentService: comments,+ milestoneService: milestones, maintenanceService: maintenance, settings: MCPSettings(),+ persistence: FallbackOutcomeFixture.makeHealthy(), taskQuerySnapshots: snapshots,+ readService: service, readCoordinator: MCPReadCoordinator(domain: domain))+ }+ }++ struct Result {+ let payload: [String: Any]+ let metadata: [String: Any]+ }++ var initial: [String: Any] {+ ["start": "2026-10-03T00:00:00Z", "end": "2026-10-03T01:00:00Z", "limit": 100, "readPolicy": "cached"]+ }++ func taskArguments(_ snapshot: String, limit: Int) -> [String: Any] {+ ["snapshotId": snapshot, "detailLevel": "full", "includeComments": false, "limit": limit]+ }++ func request(_ env: Environment, tool: String, arguments: [String: Any]) async throws -> [String: Any] {+ let body = try MCPPortfolioModernHTTPHarness.request(tool: tool, arguments: arguments)+ let response = try await MCPPortfolioModernHTTPHarness.post(+ responder: MCPServer.makeRouter(handler: env.handler).buildResponder(), body: body, tool: tool)+ #expect(response.elapsed <= .seconds(5))+ #expect(response.status == .ok)+ let envelope = try #require(response.json as? [String: Any])+ #expect(envelope["id"] as? Int == 2382 && envelope["error"] == nil)+ let result = try #require(envelope["result"] as? [String: Any])+ #expect(result["resultType"] as? String == "complete" && result["structuredContent"] is [String: Any])+ return result+ }++ func success(_ result: [String: Any]) throws -> Result {+ try #require(result["isError"] as? Bool != true)+ let content = try #require(result["content"] as? [[String: Any]])+ let text = try #require(content.first?["text"] as? String)+ let payload = try #require(try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])+ let metadata = try #require((result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])+ return Result(payload: payload, metadata: metadata)+ }++ func canonical(_ value: Any) throws -> Data {+ try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys])+ }++ func withDrainedEnvironment(_ env: Environment, body: () async throws -> Void) async throws {+ do {+ try await body()+ await drain(env)+ } catch {+ await drain(env)+ throw error+ }+ }++ func drain(_ env: Environment) async {+ let deadline = ContinuousClock.now.advanced(by: .seconds(8))+ while env.handler.readCoordinator.unfinishedCount != 0 && ContinuousClock.now < deadline {+ // Independent sleep still waits when the test task has been cancelled.+ await Task.detached { try? await Task.sleep(for: .milliseconds(25)) }.value+ }+ #expect(env.handler.readCoordinator.unfinishedCount == 0, "Physical workers must drain before fixture release")+ withExtendedLifetime(env.fixture) {}+ }+}+#endif
diff --git a/Transit/TransitTests/MCPProtocolVersionTests.swift b/Transit/TransitTests/MCPProtocolVersionTests.swiftindex 8cbbc1f..7577e56 100644--- a/Transit/TransitTests/MCPProtocolVersionTests.swift+++ b/Transit/TransitTests/MCPProtocolVersionTests.swift@@ -39,7 +39,7 @@ struct MCPProtocolVersionTests { @Test func handlerRejectsJsonRpcVersion1() async throws { let env = try MCPTestHelpers.makeEnv() - let json = Data(#"{"jsonrpc":"1.0","id":1,"method":"ping"}"#.utf8)+ let json = Data(#"{"jsonrpc":"1.0","id":1,"method":"tools/list"}"#.utf8) let request = try JSONDecoder().decode(JSONRPCRequest.self, from: json) let response = try #require(await env.handler.handle(request))@@ -61,7 +61,7 @@ struct MCPProtocolVersionTests { @Test func handlerRejectsEmptyJsonRpcVersion() async throws { let env = try MCPTestHelpers.makeEnv() - let json = Data(#"{"jsonrpc":"","id":1,"method":"ping"}"#.utf8)+ let json = Data(#"{"jsonrpc":"","id":1,"method":"tools/list"}"#.utf8) let request = try JSONDecoder().decode(JSONRPCRequest.self, from: json) let response = try #require(await env.handler.handle(request))@@ -75,7 +75,7 @@ struct MCPProtocolVersionTests { // Some broken clients send a JSON number rather than the required string. // `decodeIfPresent(String.self, ...)` returns nil for a non-string, so it // surfaces as "" and must be rejected with -32600 like any other bad version.- let json = Data(#"{"jsonrpc":2,"id":1,"method":"ping"}"#.utf8)+ let json = Data(#"{"jsonrpc":2,"id":1,"method":"tools/list"}"#.utf8) let request = try JSONDecoder().decode(JSONRPCRequest.self, from: json) let response = try #require(await env.handler.handle(request))@@ -90,7 +90,7 @@ struct MCPProtocolVersionTests { // No jsonrpc member at all — must still be parseable and rejected by the // handler with -32600 rather than silently dispatched.- let json = Data(#"{"id":1,"method":"ping"}"#.utf8)+ let json = Data(#"{"id":1,"method":"tools/list"}"#.utf8) let request = try JSONDecoder().decode(JSONRPCRequest.self, from: json) let response = try #require(await env.handler.handle(request))@@ -103,7 +103,7 @@ struct MCPProtocolVersionTests { @Test func errorResponseEchoesRequestId() async throws { let env = try MCPTestHelpers.makeEnv() - let json = Data(#"{"jsonrpc":"1.0","id":42,"method":"ping"}"#.utf8)+ let json = Data(#"{"jsonrpc":"1.0","id":42,"method":"tools/list"}"#.utf8) let request = try JSONDecoder().decode(JSONRPCRequest.self, from: json) let response = try #require(await env.handler.handle(request))@@ -114,17 +114,17 @@ struct MCPProtocolVersionTests { #expect(object["id"] as? Int == 42) } - @Test func errorResponseForMissingIdUsesNull() async throws {+ @Test func errorResponseForMissingIdOmitsUnavailableIdentifier() async throws { let env = try MCPTestHelpers.makeEnv() - // No id member and bad jsonrpc — JSON-RPC §5 requires id: null in errors.- let json = Data(#"{"jsonrpc":"1.0","method":"ping"}"#.utf8)+ // No readable ID is fabricated for an invalid modern envelope.+ let json = Data(#"{"jsonrpc":"1.0","method":"tools/list"}"#.utf8) let request = try JSONDecoder().decode(JSONRPCRequest.self, from: json) let response = try #require(await env.handler.handle(request)) let fields = try Self.errorFields(response)- #expect(fields.idKeyPresent)- #expect(fields.idIsNull)+ #expect(!fields.idKeyPresent)+ #expect(!fields.idIsNull) } // MARK: - Valid jsonrpc value still dispatches normally@@ -132,7 +132,7 @@ struct MCPProtocolVersionTests { @Test func handlerAcceptsValidJsonRpcVersion() async throws { let env = try MCPTestHelpers.makeEnv() - let json = Data(#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#.utf8)+ let json = Data(#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#.utf8) let request = try JSONDecoder().decode(JSONRPCRequest.self, from: json) let response = try #require(await env.handler.handle(request))
diff --git a/Transit/TransitTests/MCPReadAdmissionContractTests.swift b/Transit/TransitTests/MCPReadAdmissionContractTests.swiftnew file mode 100644index 0000000..d3f1d58--- /dev/null+++ b/Transit/TransitTests/MCPReadAdmissionContractTests.swift@@ -0,0 +1,108 @@+#if os(macOS)+import Foundation+import NIOConcurrencyHelpers+import Testing+@testable import Transit++/// Calls the actual admission API; receipts follow cleanup and permit removal.+@Suite(.serialized)+nonisolated struct MCPReadAdmissionContractTests {+ @Test @concurrent func duplicateLiveIdentityCannotStartOrReplaceAnotherWorker() async {+ let coordinator = MCPReadCoordinator(maxOperations: 2)+ let gate = AdmissionGate()+ let admission = MCPReadAdmission()+ let first = Task {+ await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8),+ admission: admission) { _ in+ await gate.started()+ await gate.wait()+ return Self.result("first")+ }+ }+ await gate.waitUntilStarted()+ let duplicateStarted = NIOLockedValueBox(false)+ let duplicate = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8),+ admission: admission) { _ in+ duplicateStarted.withLockedValue { $0 = true }+ return Self.result("duplicate")+ }+ #expect(duplicate == Data("busy".utf8))+ #expect(!duplicateStarted.withLockedValue { $0 })+ #expect(coordinator.unfinishedCount == 1)+ await gate.release()+ #expect(await first.value == Data("first".utf8))+ await Self.drain(coordinator)+ }++ @Test @concurrent func physicalReceiptFollowsCleanupAndPermitRemoval() async {+ let coordinator = MCPReadCoordinator(maxOperations: 1)+ let gate = AdmissionGate()+ let cleaned = NIOLockedValueBox(false)+ let receiptState = NIOLockedValueBox<[Bool]>([])+ let admission = MCPReadAdmission(physicalCompletion: {+ receiptState.withLockedValue { $0 = [cleaned.withLockedValue { $0 }, coordinator.unfinishedCount == 0] }+ })+ let call = Task {+ await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8),+ admission: admission) { _ in+ await gate.started()+ await gate.wait()+ defer { cleaned.withLockedValue { $0 = true } }+ return Self.result("late")+ }+ }+ await gate.waitUntilStarted()+ coordinator.stop()+ #expect(await call.value == Data("timeout".utf8))+ #expect(receiptState.withLockedValue { $0 }.isEmpty)+ #expect(coordinator.unfinishedCount == 1)+ coordinator.start()+ await gate.release()+ await Self.drain(coordinator)+ // Permit removal precedes the outside-lock receipt callback; await each independently.+ let receiptDeadline = ContinuousClock.now + .seconds(1)+ while receiptState.withLockedValue({ $0.isEmpty }) && .now < receiptDeadline { await Task.yield() }+ #expect(receiptState.withLockedValue { $0 } == [true, true])+ }++ private static func result(_ value: String) -> PreparedReadResult {+ PreparedReadResult(encodedResponse: Data(value.utf8), publications: [],+ publicationErrors: .init(busy: Data("busy".utf8), expired: Data("expired".utf8),+ capacity: Data("capacity".utf8)))+ }++ private static func drain(_ coordinator: MCPReadCoordinator) async {+ let deadline = ContinuousClock.now + .seconds(1)+ while coordinator.unfinishedCount != 0 && .now < deadline { await Task.yield() }+ #expect(coordinator.unfinishedCount == 0)+ }+}++private actor AdmissionGate {+ private var didStart = false+ private var open = false+ private var starters: [CheckedContinuation<Void, Never>] = []+ private var waiters: [CheckedContinuation<Void, Never>] = []++ func started() {+ didStart = true+ let pending = starters+ starters.removeAll()+ for continuation in pending { continuation.resume() }+ }+ func waitUntilStarted() async {+ if didStart { return }+ await withCheckedContinuation { starters.append($0) }+ }+ func wait() async {+ if open { return }+ await withCheckedContinuation { waiters.append($0) }+ }+ func release() {+ open = true+ let pending = waiters+ waiters.removeAll()+ for continuation in pending { continuation.resume() }+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadCaptureBuilderTests.swift b/Transit/TransitTests/MCPReadCaptureBuilderTests.swiftnew file mode 100644index 0000000..b8ad1d6--- /dev/null+++ b/Transit/TransitTests/MCPReadCaptureBuilderTests.swift@@ -0,0 +1,201 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPReadCaptureBuilderTests {+ @Test func savedCaptureExcludesPendingUIEditsAndFreezesCanonicalRevision() throws {+ let fixture = try TestModelContainer()+ fixture.context.autosaveEnabled = false+ let project = Project(name: "Saved", description: "", gitRepo: nil, colorHex: "blue")+ let task = TransitTask(name: "Saved task", type: .feature, project: project, displayID: .permanent(63))+ let comment = Comment(content: "Saved comment", authorName: "Agent", isAgent: true, task: task)+ fixture.context.insert(project)+ fixture.context.insert(task)+ fixture.context.insert(comment)+ try fixture.context.save()+ let revision = try MCPRecordSnapshot.task(task, in: fixture.context).revision+ project.name = "Unsaved"+ task.name = "Unsaved task"+ comment.content = "Unsaved comment"+ let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture)+ let view = try builder.capture(portfolioRequest())+ #expect(view.projects.first?.name == "Saved")+ #expect(view.tasks.first?.name == "Saved task")+ #expect(view.tasks.first?.revision == revision)+ #expect(view.tasks.first?.requestedCommentRecordsJSON == nil)+ #expect(view.comments.first?.content == "Saved comment")+ #expect(view.tasks.first?.commentKeys == view.comments.map(\.physicalKey))+ #expect(view.tasks.first?.projectKey == view.projects.first?.physicalKey)+ #expect(fixture.context.hasChanges)+ }++ @Test func persistentHistoryRejectsSaveBetweenEntityFetches() throws {+ let fixture = try diskFixture()+ let project = Project(name: "Old", description: "", gitRepo: nil, colorHex: "blue")+ fixture.context.insert(project)+ try fixture.context.save()+ let builder = MCPReadCaptureBuilder(container: fixture.container, afterProjects: {+ project.name = "New"+ try fixture.context.save()+ })+ #expect(throws: MCPReadCaptureError.incoherentCapture) {+ try builder.capture(portfolioRequest())+ }+ let fresh = try MCPReadCaptureBuilder(container: fixture.container).capture(portfolioRequest())+ #expect(fresh.projects.first?.name == "New")+ }++ @Test func emptySelectionWithPurgedHistoryFailsClosed() throws {+ let fixture = try diskFixture()+ let project = Project(name: "Saved", description: "", gitRepo: nil, colorHex: "blue")+ fixture.context.insert(project)+ try fixture.context.save()+ try fixture.context.deleteHistory(HistoryDescriptor<DefaultHistoryTransaction>())+ #expect(throws: MCPReadCaptureError.incoherentCapture) {+ try MCPReadCaptureBuilder(container: fixture.container).capture(+ ReadCaptureRequest(projectSelectors: [.name("Missing")], selection: .portfolio,+ completeness: .completePortfolio, includeComments: false))+ }+ }++ @Test func trulyEmptyPersistentDomainCapturesEmptySuccessfully() throws {+ let fixture = try diskFixture()+ let view = try MCPReadCaptureBuilder(container: fixture.container).capture(portfolioRequest())+ #expect(view.projects.isEmpty && view.tasks.isEmpty && view.comments.isEmpty)+ #expect(!view.metadata.snapshotId.isEmpty)+ #expect(view.metadata.asOf == view.metadata.freshness.assessedAt)+ }++ @Test func duplicateTaskUUIDsKeepPhysicalCommentOwnership() throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ let first = TransitTask(name: "First", type: .feature, project: project, displayID: .permanent(1))+ let second = TransitTask(name: "Second", type: .feature, project: project, displayID: .permanent(2))+ second.id = first.id+ let firstComment = Comment(content: "First", authorName: "A", isAgent: true, task: first)+ let secondComment = Comment(content: "Second", authorName: "A", isAgent: true, task: second)+ fixture.context.insert(project)+ fixture.context.insert(first)+ fixture.context.insert(second)+ fixture.context.insert(firstComment)+ fixture.context.insert(secondComment)+ try fixture.context.save()+ let view = try MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture)+ .capture(portfolioRequest())+ for task in view.tasks {+ #expect(task.commentKeys == view.comments.filter { $0.taskKey == task.physicalKey }.map(\.physicalKey))+ #expect(task.commentKeys.count == 1)+ let model = task.name == "First" ? first : second+ #expect(task.revision == (try MCPRecordSnapshot.task(model, in: fixture.context).revision))+ }+ }++ @Test func importGenerationChangeRejectsCapture() throws {+ let fixture = try TestModelContainer()+ var generation: UInt64 = 0+ let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,+ generation: { generation }, afterProjects: { generation += 1 })+ #expect(throws: MCPReadCaptureError.incoherentCapture) { try builder.capture(portfolioRequest()) }+ }++ @Test func scopedPortfolioRetainsForeignMilestoneAndOrphanIdentityClosure() throws {+ let fixture = try TestModelContainer()+ let selected = Project(name: "Selected", description: "", gitRepo: nil, colorHex: "blue")+ let foreign = Project(name: "Foreign", description: "", gitRepo: nil, colorHex: "green")+ let milestone = Milestone(name: "Foreign milestone", project: foreign, displayID: .permanent(1))+ let task = TransitTask(name: "Selected task", type: .feature, project: selected, displayID: .permanent(1))+ task.milestone = milestone+ let orphan = Comment(content: "Orphan", authorName: "A", isAgent: true, task: task)+ orphan.task = nil+ fixture.context.insert(selected)+ fixture.context.insert(foreign)+ fixture.context.insert(milestone)+ fixture.context.insert(task)+ fixture.context.insert(orphan)+ try fixture.context.save()+ let view = try MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture)+ .capture(ReadCaptureRequest(projectSelectors: [.id(selected.id)], selection: .portfolio,+ completeness: .completePortfolio, includeComments: false))+ let selectedKey = try #require(view.projects.first { $0.id == selected.id }?.physicalKey)+ #expect(view.captureScope == .projects([selectedKey]))+ #expect(view.tasks.first?.milestoneKey == view.milestones.first?.physicalKey)+ #expect(view.milestones.first?.storedProjectID == foreign.id)+ #expect(view.comments.first?.taskKey == nil)+ #expect(view.comments.first?.content == "Orphan")+ }++ @Test func savedMultiEntityChangeCannotEscapeAsMixedSuccess() throws {+ let fixture = try diskFixture()+ let project = Project(name: "Old", description: "", gitRepo: nil, colorHex: "blue")+ let task = TransitTask(name: "Old", type: .feature, project: project, displayID: .permanent(1))+ let milestone = Milestone(name: "Old", project: project, displayID: .permanent(1))+ let comment = Comment(content: "Old", authorName: "A", isAgent: true, task: task)+ fixture.context.insert(project)+ fixture.context.insert(task)+ fixture.context.insert(milestone)+ fixture.context.insert(comment)+ try fixture.context.save()+ let builder = MCPReadCaptureBuilder(container: fixture.container, afterProjects: {+ project.name = "New"+ task.name = "New"+ milestone.name = "New"+ comment.content = "New"+ try fixture.context.save()+ })+ #expect(throws: MCPReadCaptureError.incoherentCapture) { try builder.capture(portfolioRequest()) }+ let coherent = try MCPReadCaptureBuilder(container: fixture.container).capture(portfolioRequest())+ #expect(coherent.projects.first?.name == "New")+ #expect(coherent.tasks.first?.name == "New")+ #expect(coherent.milestones.first?.name == "New")+ #expect(coherent.comments.first?.content == "New")+ }++ @Test func requiredCommentFailureIsNotAnEmptySuccess() throws {+ let fixture = try TestModelContainer()+ let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,+ fetchComments: { _ in throw CaptureFixtureError.fetchFailed })+ #expect(throws: MCPReadCaptureError.storageFailure) { try builder.capture(portfolioRequest()) }+ let projects = try builder.capture(ReadCaptureRequest(projectSelectors: nil, selection: .projects,+ completeness: .selectedRead, includeComments: true))+ #expect(projects.projects.isEmpty && projects.comments.isEmpty)+ }++ @Test func canonicalSerializationFailureKeepsItsCategory() throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ let task = TransitTask(name: "T", type: .feature, project: project, displayID: .permanent(1))+ let comment = Comment(content: "C", authorName: "A", isAgent: true, task: task)+ fixture.context.insert(project)+ fixture.context.insert(task)+ fixture.context.insert(comment)+ try fixture.context.save()+ let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,+ fetchComments: { context in+ let comments = try context.fetch(FetchDescriptor<Transit.Comment>())+ comments.first?.creationDate = Date(timeIntervalSince1970: .infinity)+ return comments+ })+ #expect(throws: MCPReadCaptureError.serializationFailure) { try builder.capture(portfolioRequest()) }+ }++ private enum CaptureFixtureError: Error { case fetchFailed }++ private func portfolioRequest() -> ReadCaptureRequest {+ ReadCaptureRequest(projectSelectors: nil, selection: .portfolio,+ completeness: .completePortfolio, includeComments: false)+ }++ private func diskFixture() throws -> TestModelContainer {+ let schema = Schema([Project.self, TransitTask.self, Comment.self, Milestone.self,+ SyncHeartbeat.self, MCPWriteReceipt.self])+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ let config = ModelConfiguration(schema: schema, url: directory.appendingPathComponent("fixture.store"),+ cloudKitDatabase: .none)+ return try TestModelContainer(schema: schema, configurations: [config])+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadCaptureScopeTests.swift b/Transit/TransitTests/MCPReadCaptureScopeTests.swiftnew file mode 100644index 0000000..f5b6271--- /dev/null+++ b/Transit/TransitTests/MCPReadCaptureScopeTests.swift@@ -0,0 +1,120 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPReadCaptureScopeTests {+ @Test func scopedCaptureKeepsCanonicalSelectedBodiesAndMinimalForeignIdentity() throws {+ let fixture = try TestModelContainer()+ let selected = Project(name: "Selected", description: "", gitRepo: nil, colorHex: "blue")+ let foreign = Project(name: "Foreign", description: "", gitRepo: nil, colorHex: "red")+ let task = TransitTask(name: "Selected task", type: .feature, project: selected, displayID: .permanent(1))+ let unrelated = TransitTask(name: "Foreign identity", type: .bug, project: foreign, displayID: .permanent(2))+ unrelated.id = task.id+ unrelated.taskDescription = "Unrelated full body must not be retained"+ unrelated.metadata = ["secret": "Unrelated metadata"]+ let ownComment = Comment(content: "Own", authorName: "A", isAgent: true, task: task)+ let foreignComment = Comment(content: "UUID canonical coverage", authorName: "B",+ isAgent: true, task: unrelated)+ fixture.context.insert(selected)+ fixture.context.insert(foreign)+ fixture.context.insert(task)+ fixture.context.insert(unrelated)+ fixture.context.insert(ownComment)+ fixture.context.insert(foreignComment)+ try fixture.context.save()+ let revision = try MCPRecordSnapshot.task(task, in: fixture.context).revision+ let view = try MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture)+ .capture(ReadCaptureRequest(projectSelectors: [.id(selected.id)], selection: .portfolio,+ completeness: .completePortfolio, includeComments: false))+ let selectedKey = try #require(view.projects.first { $0.id == selected.id }?.physicalKey)+ #expect(view.captureScope == .projects([selectedKey]))+ let captured = try #require(view.tasks.first { $0.projectKey == selectedKey })+ #expect(captured.revision == revision)+ #expect(captured.fullRecordWithoutCommentsJSON != nil)+ #expect(captured.commentKeys.count == 1)+ #expect(view.comments.count == 2)+ let closure = try #require(view.tasks.first { $0.projectKey != selectedKey })+ #expect(closure.revision == nil && closure.fullRecordWithoutCommentsJSON == nil)+ #expect(closure.requestedCommentRecordsJSON == nil)+ #expect(closure.taskDescription == nil && closure.metadata.isEmpty && closure.metadataJSON == nil)+ let identity = try #require(JSONSerialization.jsonObject(with: closure.selectedRecordJSON) as? [String: Any])+ #expect(identity["description"] == nil && identity["metadata"] == nil && identity["comments"] == nil)+ }++ @Test func scopedForeignMilestoneKeepsClosureWithoutCanonicalDateSerialization() throws {+ let fixture = try TestModelContainer()+ let selected = Project(name: "Selected", description: "", gitRepo: nil, colorHex: "blue")+ let foreign = Project(name: "Foreign", description: "", gitRepo: nil, colorHex: "red")+ let milestone = Milestone(name: "Foreign milestone", project: foreign, displayID: .permanent(9))+ let task = TransitTask(name: "Selected task", type: .feature, project: selected, displayID: .permanent(1))+ task.milestone = milestone+ fixture.context.insert(selected)+ fixture.context.insert(foreign)+ fixture.context.insert(milestone)+ fixture.context.insert(task)+ try fixture.context.save()+ let revision = try MCPRecordSnapshot.task(task, in: fixture.context).revision+ let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,+ fetchMilestones: { context in+ let values = try context.fetch(FetchDescriptor<Milestone>())+ let corrupt = try #require(values.first)+ corrupt.creationDate = Date(timeIntervalSinceReferenceDate: .nan)+ #expect(throws: (any Error).self) { try MCPRecordSnapshot.milestone(corrupt) }+ return values+ })+ let view = try builder.capture(ReadCaptureRequest(projectSelectors: [.id(selected.id)], selection: .portfolio,+ completeness: .completePortfolio, includeComments: false))+ let captured = try #require(view.tasks.first { $0.id == task.id })+ let closure = try #require(view.milestones.first { $0.id == milestone.id })+ let foreignKey = try #require(view.projects.first { $0.id == foreign.id }?.physicalKey)+ #expect(captured.revision == revision && captured.fullRecordWithoutCommentsJSON != nil)+ #expect(captured.milestoneKey == closure.physicalKey)+ #expect(closure.projectKey == foreignKey && closure.taskKeys == [captured.physicalKey])+ #expect(closure.permanentDisplayId == 9 && closure.name == "Foreign milestone")+ #expect(closure.rawStatus == "open" && closure.effectiveStatus == "open")+ #expect(closure.creationDate.timeIntervalSinceReferenceDate.isNaN)+ let record = try #require(JSONSerialization.jsonObject(with: closure.selectedRecordJSON) as? [String: String])+ #expect(record == ["milestoneId": milestone.id.uuidString, "name": "Foreign milestone"])+ try MCPReadCaptureValidation.validateReusableCapture(view)+ #expect(throws: MCPReadCaptureError.serializationFailure) {+ try builder.capture(ReadCaptureRequest(projectSelectors: nil, selection: .portfolio,+ completeness: .completePortfolio, includeComments: false))+ }+ }++ @Test func volumeCaptureReportsPhysicalAndEncodingCostsSeparately() throws {+ let setupStart = ContinuousClock.now+ let fixture = try TestModelContainer()+ let project = Project(name: "Volume", description: "", gitRepo: nil, colorHex: "blue")+ fixture.context.insert(project)+ var tasks: [TransitTask] = []+ for number in 0..<2_375 {+ let task = TransitTask(name: "Task \(number)", type: .feature, project: project,+ displayID: .permanent(number + 1))+ fixture.context.insert(task)+ fixture.context.insert(Comment(content: "Comment \(number)", authorName: "A", isAgent: true, task: task))+ tasks.append(task)+ }+ fixture.context.insert(Comment(content: "Extra", authorName: "A", isAgent: true, task: tasks[0]))+ try fixture.context.save()+ print("T63_PROVIDER setup=\(setupStart.duration(to: .now))")+ let captureStart = ContinuousClock.now+ let view = try MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture)+ .capture(ReadCaptureRequest(projectSelectors: nil, selection: .portfolio,+ completeness: .completePortfolio, includeComments: false))+ print("T63_PROVIDER physical_capture=\(captureStart.duration(to: .now))")+ let encodingStart = ContinuousClock.now+ let bytes = try JSONEncoder().encode(view.tasks.map(\.fullRecordWithoutCommentsJSON))+ print("T63_PROVIDER frozen_record_encoding=\(encodingStart.duration(to: .now)) bytes=\(bytes.count)")+ #expect(view.tasks.count == 2_375 && view.comments.count == 2_376)+ #expect(view.tasks.allSatisfy { $0.revision != nil && $0.fullRecordWithoutCommentsJSON != nil })+ for model in [tasks[0], tasks[2_374]] {+ #expect(view.tasks.first { $0.id == model.id }?.revision+ == (try MCPRecordSnapshot.task(model, in: fixture.context).revision))+ }+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadCaptureValidationTests.swift b/Transit/TransitTests/MCPReadCaptureValidationTests.swiftnew file mode 100644index 0000000..bf65bbb--- /dev/null+++ b/Transit/TransitTests/MCPReadCaptureValidationTests.swift@@ -0,0 +1,86 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPReadCaptureValidationTests {+ nonisolated private struct Retained: MCPRetainedViewSource {+ let captured: CapturedReadView+ func view(for snapshotID: String, now: ContinuousClock.Instant) throws -> CapturedReadView {+ guard snapshotID == captured.metadata.snapshotId, now < captured.retentionDeadline else {+ throw MCPTaskQueryError(code: "SNAPSHOT_EXPIRED", message: "Retained capture expired")+ }+ return captured+ }+ }++ @Test func retainedSourceKeepsIdentityAndScopeWithoutDroppingForeignClosure() throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "Selected", description: "", gitRepo: nil, colorHex: "blue")+ let foreign = Project(name: "Foreign", description: "", gitRepo: nil, colorHex: "red")+ let task = TransitTask(name: "Saved", type: .feature, project: project, displayID: .permanent(63))+ let endpoint = TransitTask(name: "Identity", type: .bug, project: foreign, displayID: .permanent(64))+ let comment = Comment(content: "Evidence", authorName: "A", isAgent: true, task: task)+ fixture.context.insert(project)+ fixture.context.insert(foreign)+ fixture.context.insert(task)+ fixture.context.insert(endpoint)+ fixture.context.insert(comment)+ try fixture.context.save()+ let captured = try MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture)+ .capture(ReadCaptureRequest(projectSelectors: [.id(project.id)], selection: .portfolio,+ completeness: .completePortfolio, includeComments: false))+ let source = Retained(captured: captured)+ task.name = "After"+ comment.content = "After"+ try fixture.context.save()+ let view = try source.view(for: captured.metadata.snapshotId, now: .now)+ try MCPReadCaptureValidation.validateReusableCapture(view)+ #expect(view.metadata.snapshotId == captured.metadata.snapshotId)+ #expect(view.metadata.asOf == captured.metadata.asOf)+ #expect(view.tasks.count == 2)+ let ownKey = try #require(view.projects.first { $0.id == project.id }?.physicalKey)+ let foreignKey = try #require(view.projects.first { $0.id == foreign.id }?.physicalKey)+ try MCPReadCaptureValidation.requireScope(view, projectKeys: [ownKey])+ #expect(throws: MCPTaskQueryError.self) {+ try MCPReadCaptureValidation.requireScope(view, projectKeys: [foreignKey])+ }+ let request = try MCPTaskQueryRequest.parse(["detailLevel": "full", "includeComments": false, "limit": 100])+ let records = try MCPReadProjection.tasks(view, request: request, arguments: [:])+ #expect(records.count == 1 && records[0]["name"] as? String == "Saved")+ #expect(records[0]["revision"] as? String == captured.tasks.first { $0.id == task.id }?.revision)+ let noEvidence = replacing(view, tasks: view.tasks, comments: [])+ #expect(throws: MCPReadCaptureError.incoherentCapture) {+ try MCPReadCaptureValidation.validateReusableCapture(noEvidence)+ }+ }++ @Test func selectedSummaryCannotPretendToBeCompleteCanonicalPortfolio() throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ fixture.context.insert(project)+ fixture.context.insert(TransitTask(name: "Task", type: .feature, project: project, displayID: .permanent(63)))+ try fixture.context.save()+ let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture)+ let complete = try builder.capture(ReadCaptureRequest(projectSelectors: nil, selection: .portfolio,+ completeness: .completePortfolio, includeComments: false))+ let summary = try builder.capture(ReadCaptureRequest(projectSelectors: nil,+ selection: .tasks(detail: .summary),+ completeness: .selectedRead,+ includeComments: false))+ let inadequate = replacing(complete, tasks: summary.tasks, comments: [])+ #expect(throws: MCPReadCaptureError.incoherentCapture) {+ try MCPReadCaptureValidation.validateReusableCapture(inadequate)+ }+ }++ private func replacing(_ view: CapturedReadView, tasks: [ReadTask],+ comments: [ReadCommentEvidence]) -> CapturedReadView {+ CapturedReadView(completeness: view.completeness, captureScope: view.captureScope, metadata: view.metadata,+ createdAt: view.createdAt, retentionDeadline: view.retentionDeadline, projects: view.projects,+ tasks: tasks, milestones: view.milestones, comments: comments)+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadCoordinatorTests.swift b/Transit/TransitTests/MCPReadCoordinatorTests.swiftnew file mode 100644index 0000000..0344f8c--- /dev/null+++ b/Transit/TransitTests/MCPReadCoordinatorTests.swift@@ -0,0 +1,292 @@+#if os(macOS)+import Foundation+import Hummingbird+import HTTPTypes+import Logging+import NIOConcurrencyHelpers+import NIOCore+import NIOEmbedded+import NIOFoundationCompat+import Testing+@testable import Transit++@Suite(.serialized)+nonisolated struct MCPReadCoordinatorTests {+ @Test @concurrent func actualRouterReturnsTimeoutWhileMainActorIsBlocked() async throws {+ let coordinator = MCPReadCoordinator()+ let started = DispatchSemaphore(value: 0)+ let blocker = Task { @MainActor in+ Self.blockMainActor(started)+ }+ Self.waitForStart(started)+ let router = Router(context: MCPRequestContext.self)+ router.post("/read") { _, _ in+ await MCPReadTransportAdapter.response(coordinator: coordinator,+ timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { _ in+ await MainActor.run { Self.result("success") }+ }+ }+ let channel = EmbeddedChannel()+ defer { _ = try? channel.finish() }+ let context = MCPRequestContext(source: ApplicationRequestContextSource(+ channel: channel, logger: Logger(label: "read-deadline-fixture")))+ let request = Request(head: HTTPRequest(method: .post, scheme: "http", authority: "localhost", path: "/read"),+ body: RequestBody(buffer: ByteBuffer()))+ let start = ContinuousClock.now+ let response = try await router.buildResponder().respond(to: request, context: context)+ let writer = ReadResponseWriter()+ try await response.body.write(writer)+ let elapsed = start.duration(to: .now)+ #expect(Data(buffer: writer.bytes.withLockedValue { $0 }) == Data("timeout".utf8))+ print("READ_DEADLINE router_and_body_elapsed=\(elapsed) blocked_main_actor=6s")+ #expect(elapsed < .seconds(5))+ #expect(response.status == .ok)+ #expect(coordinator.unfinishedCount == 1)+ await blocker.value+ try await Task.sleep(for: .milliseconds(30))+ #expect(coordinator.unfinishedCount == 0)+ }++ @Test @concurrent func timeoutAndRestartNeverReleasePhysicalPermits() async throws {+ let coordinator = MCPReadCoordinator(cutoff: .milliseconds(40))+ let latch = ReadWorkerLatch()+ let calls = (0..<8).map { _ in Task {+ await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { _ in+ await latch.wait()+ return Self.result("late")+ }+ } }+ for call in calls { #expect(await call.value == Data("timeout".utf8)) }+ #expect(coordinator.unfinishedCount == 8)+ coordinator.stop()+ coordinator.start()+ let ninth = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { _ in+ Issue.record("busy request launched a worker")+ return Self.result("unexpected")+ }+ #expect(ninth == Data("busy".utf8))+ await latch.release()+ for _ in 0..<100 where coordinator.unfinishedCount != 0 {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(coordinator.unfinishedCount == 0)+ }++ @Test @concurrent func wholeBatchFallbackWinsBlockedAssemblyAndRetainsOnePermit() async throws {+ let coordinator = MCPReadCoordinator(cutoff: .milliseconds(50))+ let publication = ReadRecordingPublication(domain: coordinator.domain)+ let work = MCPReadBatchWork(timeout: Data("0".utf8), busy: Data("-1".utf8), responds: true) { _ in+ Self.result("1")+ }+ let elements = (0..<8).map { _ in MCPReadBatchElement.read(work) }+ let started = ContinuousClock.now+ let bytes = await coordinator.executeBatch(elements) { values in+ Self.blockAssembly()+ let encoded = MCPReadBatchEncoding.array(values.map { $0?.encodedResponse }) ?? Data()+ return PreparedReadResult(encodedResponse: encoded, publications: [publication],+ publicationErrors: Self.result("rejected").publicationErrors)+ }+ #expect(started.duration(to: .now) < .milliseconds(200))+ #expect(bytes == Data("[0,0,0,0,0,0,0,0]".utf8))+ #expect(coordinator.unfinishedCount == 1)+ try await Task.sleep(for: .milliseconds(550))+ #expect(coordinator.unfinishedCount == 0)+ #expect(publication.counts() == [0, 1])+ }++ @Test @concurrent func stoppedBeforeDispatchDoesNotLeaveAssemblyPermit() async throws {+ let coordinator = MCPReadCoordinator(cutoff: .milliseconds(20))+ let work = MCPReadBatchWork(timeout: Data("0".utf8), busy: Data("-1".utf8), responds: true) { _ in+ Issue.record("expired undispatched read started physical work")+ return Self.result("1")+ }+ let bytes = await coordinator.executeBatch([.read(work), .read(work)],+ admittedAt: .now - .seconds(1), assemble: { _ in+ Issue.record("expired batch assembled success")+ return Self.result("unexpected")+ })+ #expect(bytes == Data("[0,0]".utf8))+ try await Task.sleep(for: .milliseconds(30))+ #expect(coordinator.unfinishedCount == 0)+ }++ @Test @concurrent func seededTerminalRacesNeverPublishAfterTimeoutOrStop() async throws {+ var seed: UInt64 = 63+ for _ in 0..<120 {+ seed = seed &* 6_364_136_223_846_793_005 &+ 1+ let coordinator = MCPReadCoordinator(cutoff: .milliseconds(4))+ let publication = ReadRecordingPublication(domain: coordinator.domain)+ let delay = Int(seed % 8)+ let stop = seed & 16 != 0+ let response = Task {+ await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { _ in+ try? await Task.sleep(for: .milliseconds(delay))+ return PreparedReadResult(encodedResponse: Data("success".utf8), publications: [publication],+ publicationErrors: Self.result("busy").publicationErrors)+ }+ }+ if stop {+ try await Task.sleep(for: .milliseconds(1))+ coordinator.stop()+ coordinator.start()+ }+ let bytes = await response.value+ #expect(["success", "timeout", "busy"].contains(String(bytes: bytes, encoding: .utf8) ?? "invalid"))+ try await Task.sleep(for: .milliseconds(10))+ #expect(coordinator.unfinishedCount == 0)+ #expect(publication.counts()[0] == (bytes == Data("success".utf8) ? 1 : 0))+ #expect(publication.counts().reduce(0, +) <= 1)+ }+ }++ @Test @concurrent func nearBodyCeilingRouterBatchAccountsForFallbackPreparation() async throws {+ let coordinator = MCPReadCoordinator()+ let input = try Self.largeBatchInput()+ #expect(input.count > 950_000 && input.count < 1_048_576)+ let router = Router(context: MCPRequestContext.self)+ router.post("/read") { request, _ in+ let body = try await request.body.collect(upTo: 1_048_576)+ let decoded = try JSONSerialization.jsonObject(with: Data(buffer: body)) as? [[String: String]] ?? []+ let admittedAt = ContinuousClock.now+ let elements = try decoded.map { value -> MCPReadBatchElement in+ let id = value["id"]+ if value["method"] == "invalid" {+ return .fixed(try Self.frame(id: id, outcome: "invalid"))+ }+ return .read(MCPReadBatchWork(timeout: try Self.frame(id: id, outcome: "timeout"),+ busy: try Self.frame(id: id, outcome: "busy"), responds: id != nil) { _ in+ try? await Task.sleep(for: .seconds(6))+ return Self.result("1")+ })+ }+ let response = await coordinator.executeBatch(elements, admittedAt: admittedAt) { values in+ Self.result(String(bytes: MCPReadBatchEncoding.array(values.map { $0?.encodedResponse }) ?? Data(),+ encoding: .utf8) ?? "[]")+ }+ let elapsed = admittedAt.duration(to: .now)+ print("READ_BATCH admission_to_encoded=\(elapsed) request_bytes=\(input.count)")+ return Response(status: .ok, body: .init(byteBuffer: ByteBuffer(data: response ?? Data())))+ }+ let channel = EmbeddedChannel()+ defer { _ = try? channel.finish() }+ let context = MCPRequestContext(source: ApplicationRequestContextSource(+ channel: channel, logger: Logger(label: "large-read-batch-fixture")))+ let request = Request(head: HTTPRequest(method: .post, scheme: "http", authority: "localhost", path: "/read"),+ body: RequestBody(buffer: ByteBuffer(data: input)))+ let start = ContinuousClock.now+ let response = try await router.buildResponder().respond(to: request, context: context)+ let writer = ReadResponseWriter()+ try await response.body.write(writer)+ let elapsed = start.duration(to: .now)+ let bytes = Data(buffer: writer.bytes.withLockedValue { $0 })+ let outcomes = try #require(try JSONSerialization.jsonObject(with: bytes) as? [[String: String]])+ #expect(elapsed < .seconds(5))+ #expect(outcomes.count == 80)+ #expect(outcomes.filter { $0["outcome"] == "timeout" }.count == 8)+ #expect(outcomes.filter { $0["outcome"] == "busy" }.count == 24)+ #expect(outcomes.filter { $0["outcome"] == "invalid" }.count == 48)+ #expect(coordinator.unfinishedCount == 8)+ print("READ_BATCH router_and_body_elapsed=\(elapsed) response_bytes=\(bytes.count)")+ try await Task.sleep(for: .milliseconds(1_300))+ #expect(coordinator.unfinishedCount == 0)+ }++ @Test @concurrent func stopDuringFallbackPreparationSelectsOnlyWholeArray() async throws {+ let coordinator = MCPReadCoordinator(cutoff: .milliseconds(50), maxOperations: 2)+ let work = MCPReadBatchWork(timeout: Data("0".utf8), busy: Data("-1".utf8), responds: true) { _ in+ Issue.record("invalidated batch dispatched a read")+ return Self.result("1")+ }+ let bytes = await coordinator.executeBatch([.read(work), .read(work)], beforeFallbackReady: {+ coordinator.stop()+ coordinator.start()+ #expect(coordinator.unfinishedCount == 2)+ let ninth = await coordinator.execute(timeout: Data("0".utf8), busy: Data("-1".utf8)) { _ in+ Issue.record("restart released pending physical slots")+ return Self.result("1")+ }+ #expect(ninth == Data("-1".utf8))+ }, assemble: { _ in+ Issue.record("invalidated batch assembled success")+ return Self.result("unexpected")+ })+ #expect(bytes == Data("[0,0]".utf8))+ try await Task.sleep(for: .milliseconds(20))+ #expect(coordinator.unfinishedCount == 0)+ }++ @Test @concurrent func cutoffDuringFallbackPreparationNeverDispatchesExpiredWork() async throws {+ let coordinator = MCPReadCoordinator(cutoff: .milliseconds(10))+ let work = MCPReadBatchWork(timeout: Data("0".utf8), busy: Data("-1".utf8), responds: true) { _ in+ Issue.record("expired pending batch dispatched")+ return Self.result("1")+ }+ let bytes = await coordinator.executeBatch([.read(work), .read(work)], beforeFallbackReady: {+ try? await Task.sleep(for: .milliseconds(20))+ }, assemble: { _ in Self.result("unexpected") })+ #expect(bytes == Data("[0,0]".utf8))+ try await Task.sleep(for: .milliseconds(20))+ #expect(coordinator.unfinishedCount == 0)+ }++ private static func largeBatchInput() throws -> Data {+ let longID = String(repeating: "x", count: 30_000)+ let requests = (0..<32).map { ["jsonrpc": "2.0", "id": "\($0)-\(longID)", "method": "read"] }+ + (0..<48).map { ["jsonrpc": "wrong", "id": "bad-\($0)", "method": "invalid"] }+ + (0..<16).map { _ in ["jsonrpc": "2.0", "method": "notification"] }+ return try JSONSerialization.data(withJSONObject: requests)+ }++ private static func frame(id: String?, outcome: String) throws -> Data {+ try JSONSerialization.data(withJSONObject: ["id": id ?? "notification", "outcome": outcome])+ }++ private static func blockAssembly() { Thread.sleep(forTimeInterval: 0.5) }++ @MainActor private static func blockMainActor(_ semaphore: DispatchSemaphore) {+ semaphore.signal()+ Thread.sleep(forTimeInterval: 6)+ }++ private static func waitForStart(_ semaphore: DispatchSemaphore) { semaphore.wait() }++ private static func result(_ text: String) -> PreparedReadResult {+ PreparedReadResult(encodedResponse: Data(text.utf8), publications: [],+ publicationErrors: PreencodedPublicationErrors(+ busy: Data("busy".utf8), expired: Data("expired".utf8), capacity: Data("capacity".utf8)))+ }+}++private nonisolated final class ReadRecordingPublication: MCPPreparedPublication, @unchecked Sendable {+ let publicationStoreID = MCPPublicationStoreID(rawValue: UUID())+ private let domain: MCPReadPublicationDomain+ private var commits = 0+ private var discards = 0+ init(domain: MCPReadPublicationDomain) { self.domain = domain }+ func validateLocked(in domain: MCPReadPublicationDomain) -> PublicationRejection? { nil }+ func commitLocked(in domain: MCPReadPublicationDomain) { if commits + discards == 0 { commits += 1 } }+ func discardLocked(in domain: MCPReadPublicationDomain) { if commits + discards == 0 { discards += 1 } }+ func counts() -> [Int] { domain.withLock { [commits, discards] } }+}++private nonisolated final class ReadResponseWriter: ResponseBodyWriter {+ let bytes = NIOLockedValueBox(ByteBuffer())+ func write(_ buffer: ByteBuffer) async throws { _ = bytes.withLockedValue { $0.writeImmutableBuffer(buffer) } }+ func finish(_: HTTPFields?) async throws {}+}++private actor ReadWorkerLatch {+ private var released = false+ private var continuations: [CheckedContinuation<Void, Never>] = []+ func wait() async {+ if released { return }+ await withCheckedContinuation { continuations.append($0) }+ }+ func release() {+ released = true+ let waiting = continuations+ continuations = []+ for continuation in waiting { continuation.resume() }+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadFrozenCursorGateTests.swift b/Transit/TransitTests/MCPReadFrozenCursorGateTests.swiftnew file mode 100644index 0000000..985ae58--- /dev/null+++ b/Transit/TransitTests/MCPReadFrozenCursorGateTests.swift@@ -0,0 +1,104 @@+#if os(macOS)+import Foundation+import NIOConcurrencyHelpers+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPReadFrozenCursorGateTests {+ @Test(arguments: [false, true], [false, true])+ func cursorLookupCannotPublishAfterRootExpiryOrRetirement(modern: Bool, retire: Bool) async throws {+ let start = ContinuousClock.now+ // Original root began 299 seconds earlier; only its final second remains.+ let deadline = (start - .seconds(299)) + .seconds(300)+ let domain = MCPReadPublicationDomain(testingInstant: start)+ let store = MCPTaskQuerySnapshotStore(domain: domain)+ let cursor = store.makeCursor()+ let candidate = try prepareRoot(store: store, cursor: cursor, deadline: deadline, modern: modern)+ let publication = try #require(candidate)+ let (_, retired) = domain.withLockRetainingRetirement {+ #expect(publication.validateLocked(in: domain) == nil)+ publication.commitLocked(in: domain)+ }+ withExtendedLifetime(retired) {}+ let source = NoCapture()+ let service = MCPReadService(source: source,+ monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil), snapshots: store)+ let coordinator = MCPReadCoordinator(domain: domain)+ let id = JSONRPCId.string("frozen-cursor")+ let errors = try MCPBoundedReadDispatcher.publicationErrors(+ for: MCPReadToolRequest(tool: "query_tasks", arguments: ["cursor": AnyCodable(cursor)]),+ id: id, busy: Data("busy".utf8))+ let bytes = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { operation in+ do {+ let prepared = try await service.prepareRetainedPage(cursor: cursor, requestedPolicy: nil)+ #expect(prepared.publications.count == 1 && operation.shouldContinue())+ let guardPublication = try store.prepareAggregate(prepared.publications,+ in: domain, operation: operation)+ let success = try MCPModernProviderBinding.read(prepared, id: id,+ tool: "query_tasks", operation: operation)+ if retire { await store.clear() } else { domain.setTestingInstant(deadline) }+ #expect(operation.shouldContinue())+ return PreparedReadResult(encodedResponse: success, publications: [guardPublication],+ publicationErrors: errors)+ } catch {+ Issue.record("Unexpected cursor fixture error: \(error)")+ return PreparedReadResult(encodedResponse: Data("fixture-error".utf8), publications: [],+ publicationErrors: errors)+ }+ }+ let drainDeadline = ContinuousClock.now + .seconds(1)+ while coordinator.unfinishedCount != 0 && .now < drainDeadline { await Task.yield() }+ #expect(coordinator.unfinishedCount == 0)+ #expect(bytes == errors.expired && bytes != Data("timeout".utf8))+ #expect(source.calls == 0)+ store.clear()+ let accounting = try domain.accounting(for: store.publicationStoreID)+ #expect(accounting.pendingBytes == 0 && accounting.visibleBytes == 0)+ }++ private func prepareRoot(store: MCPTaskQuerySnapshotStore, cursor: String,+ deadline: ContinuousClock.Instant, modern: Bool) throws -> MCPPublicationReservation? {+ if modern {+ let pages = try ["[]", "null"].map { text in+ try MCPResultPreparation.page(request: MCPResultPagePreparationRequest(text: text,+ isError: false, origin: .generatedJSON, evidence: .established,+ context: MCPResultContext(tool: "query_tasks", semanticFailure: nil,+ mutationRecovery: nil, entityPositions: []), metadataOwner: nil))+ }+ let bundle = try MCPResultPreparation.prepare(pages: pages,+ budget: MCPResultRetentionBudget(store: .ordinary, originalCaptureIndexBytes: 0,+ visibleBytes: 0, pendingBytes: 0))+ return try store.prepare(preparedBundle: bundle, cursors: [cursor],+ deadline: deadline, operationID: UUID(), metadataBytes: nil, policy: nil)+ } else {+ return try store.prepare(pages: ["[]", "null"], cursors: [cursor],+ deadline: deadline, operationID: UUID())+ }+ }++ @Test func byteComparisonChecksCancellationDuringTraversal() throws {+ let calls = NIOLockedValueBox(0)+ let text = String(repeating: "é", count: 10_000)+ #expect(throws: CancellationError.self) {+ try MCPReadSourceByteValidation.matches(text, text) {+ let count = calls.withLockedValue { $0 += 1; return $0 }+ if count == 3 { throw CancellationError() }+ }+ }+ #expect(calls.withLockedValue { $0 } == 3)+ #expect(try MCPReadSourceByteValidation.matches("", "", checkpoint: {}))+ #expect(try MCPReadSourceByteValidation.matches("é", "é", checkpoint: {}))+ #expect(try !MCPReadSourceByteValidation.matches("é", "e\u{301}", checkpoint: {}))+ #expect(try !MCPReadSourceByteValidation.matches("a", "ab", checkpoint: {}))+ }++ @MainActor private final class NoCapture: MCPReadCaptureSource {+ var calls = 0+ func capture(_ request: ReadCaptureRequest) throws -> CapturedReadView {+ calls += 1+ throw MCPReadCaptureError.storageFailure+ }+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadHelperContractTests.swift b/Transit/TransitTests/MCPReadHelperContractTests.swiftnew file mode 100644index 0000000..b55fb3c--- /dev/null+++ b/Transit/TransitTests/MCPReadHelperContractTests.swift@@ -0,0 +1,74 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// Generic preparation acceptance only. Actual portfolio modules have separate delivery gates.+@MainActor @Suite(.serialized)+struct MCPReadHelperContractTests {+ @Test func savedCapsulePreservesMetadataAndObservationThroughHelperTransform() async throws {+ let fixture = try TestModelContainer()+ fixture.context.autosaveEnabled = false+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ let task = TransitTask(name: "Saved", type: .feature, project: project, displayID: .permanent(63))+ fixture.context.insert(project)+ fixture.context.insert(task)+ try fixture.context.save()+ task.name = "Unsaved UI edit"+ let monitor = MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil)+ let store = MCPTaskQuerySnapshotStore()+ let service = MCPReadService(source: MCPReadCaptureBuilder(container: fixture.container,+ fence: .actorOnlyTestFixture), monitor: monitor, snapshots: store)+ // Runtime baseline RED, rather than missing-method compile RED. No fake service implementation.+ guard let preparer = (service as Any) as? any MCPReadCapturedPreparing else {+ Issue.record("MCPReadService has not bound the generic captured preparation contract")+ return+ }+ let coordinator = MCPReadCoordinator(domain: store.domain)+ let request = ReadCaptureRequest(projectSelectors: nil, selection: .tasks(detail: .summary),+ completeness: .selectedRead, includeComments: false)+ let bytes = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { operation in+ do {+ let prepared = try await preparer.prepareCapturedRead(request: request, policy: .cached,+ operation: operation) { capsule, originalOperation in+ #expect(capsule.view.tasks.map(\.name) == ["Saved"])+ #expect(originalOperation.id == operation.id)+ #expect(originalOperation.remainingBudget() > .zero)+ let metadata = try JSONDecoder().decode(ReadCaptureMetadata.self,+ from: capsule.frozenMetadataBytes)+ #expect(metadata.snapshotId == capsule.view.metadata.snapshotId)+ #expect(metadata.asOf == capsule.view.metadata.asOf)+ try Self.checkObservationCapacity(monitor, available: 7)+ let tool = try MCPPreparedToolRead(text: "fixture helper",+ frozenMetadataBytes: capsule.frozenMetadataBytes)+ #expect(tool.frozenMetadataBytes == capsule.frozenMetadataBytes)+ return tool+ }+ return Self.result(prepared.encodedToolResult)+ } catch {+ Issue.record("Generic captured preparation failed: \(error)")+ return Self.result(Data("failed".utf8))+ }+ }+ let object = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any])+ #expect(object["id"] == nil && object["jsonrpc"] == nil)+ #expect((object["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] != nil)+ try Self.checkObservationCapacity(monitor, available: 8)+ }++ nonisolated private static func checkObservationCapacity(+ _ monitor: MCPImportEvidenceMonitor, available: Int+ ) throws {+ var windows: [MCPImportObservationWindow] = []+ defer { for window in windows { window.close() } }+ for _ in 0..<available { windows.append(try monitor.beginObservation(applicableImportIDs: [])) }+ #expect(throws: MCPImportObservationError.busy) { try monitor.beginObservation(applicableImportIDs: []) }+ }++ nonisolated private static func result(_ bytes: Data) -> PreparedReadResult {+ PreparedReadResult(encodedResponse: bytes, publications: [],+ publicationErrors: .init(busy: Data(), expired: Data(), capacity: Data()))+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadModernPageBindingTests.swift b/Transit/TransitTests/MCPReadModernPageBindingTests.swiftnew file mode 100644index 0000000..75cabd7--- /dev/null+++ b/Transit/TransitTests/MCPReadModernPageBindingTests.swift@@ -0,0 +1,184 @@+#if os(macOS)+import Foundation+import NIOConcurrencyHelpers+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPReadModernPageBindingTests {+ @Test func allPrivatePagesPrepareBeforeReservationAndReplayUsesSameSealedOwner() async throws {+ let fixture = try Fixture()+ let observed = NIOLockedValueBox<[MCPResultPreparedPage]>([])+ let domain = fixture.store.domain+ let storeID = fixture.store.publicationStoreID+ let service = fixture.service { pages, tool, operation in+ #expect(tool == "query_tasks" && pages.count == 2 && operation.shouldContinue())+ let state = try domain.accounting(for: storeID)+ #expect(state.pendingBytes == 0 && state.visibleBytes == 0)+ let owners = try Self.prepare(pages)+ observed.withLockedValue { $0 = owners }+ return owners+ }+ let first = try await fixture.execute(service, arguments: ["detailLevel": "summary",+ "includeComments": false, "limit": 1], id: .string("initial"))+ await fixture.drain()+ let frameValue = try JSONSerialization.jsonObject(with: first)+ let frame = try #require(frameValue as? [String: Any])+ let payload = try MCPTestHelpers.decodeHTTPToolResult(frame)+ let cursor = try #require(payload["nextCursor"] as? String)+ let retained = try fixture.store.retainedPage(for: cursor)+ let owner = try #require(retained.preparedResultPage)+ let prepared = observed.withLockedValue { $0 }+ #expect(prepared.count == 2 && owner === prepared[1])+ #expect(prepared[0].metadataOwner === prepared[1].metadataOwner)+ let raw = retained.metadataBytes+ let tasks = try fixture.models.context.fetch(FetchDescriptor<TransitTask>())+ tasks.first?.name = "Saved later edit"+ try fixture.models.context.save()+ fixture.source.failure = .storageFailure+ let replay = try await fixture.execute(service, arguments: ["cursor": cursor])+ await fixture.drain()+ #expect(fixture.source.calls == 1)+ #expect(try fixture.store.retainedPage(for: cursor).preparedResultPage === owner)+ #expect(try fixture.store.retainedPage(for: cursor).metadataBytes == raw)+ let expected = try MCPResultEncoder.encode(fragment: owner.fragment, id: .string("fixture"))+ #expect(replay == expected)+ // Direct replay trusts the sealed fragment, even when raw metadata cannot be typed-decoded.+ let opaque = MCPPreparedToolRead(preparedResultPage: owner, frozenMetadataBytes: Data("not-json".utf8))+ #expect(opaque.encodedToolResult == owner.fragment.encodedResult)+ #expect(opaque.frozenMetadataBytes == Data("not-json".utf8) && opaque.result.metadata == nil)+ }++ @Test(arguments: [false, true])+ func failedModernPreparationNeverReservesOrInventsSuccess(capacity: Bool) async throws {+ let fixture = try Fixture()+ let service = fixture.service { _, _, _ in+ if capacity { throw MCPResultPreparationError.retentionCapacity }+ return []+ }+ let bytes = try await fixture.execute(service, arguments: ["detailLevel": "summary",+ "includeComments": false, "limit": 1])+ await fixture.drain()+ let value = try JSONSerialization.jsonObject(with: bytes)+ let frame = try #require(value as? [String: Any])+ let payload = try MCPTestHelpers.decodeHTTPToolResult(frame)+ #expect((payload["error"] as? [String: Any])?["code"] as? String+ == (capacity ? "QUERY_CAPACITY_EXCEEDED" : "QUERY_FAILED"))+ let state = try fixture.store.domain.accounting(for: fixture.store.publicationStoreID)+ #expect(state.pendingBytes == 0 && state.visibleBytes == 0)+ #expect(fixture.source.calls == 1)+ }++ @Test func siblingNewRootsSharingFreshOwnersRejectBeforeTransfer() throws {+ let fixture = try Fixture()+ let tools = try ["[]", "null"].map { try MCPPreparedToolRead(text: $0) }+ let pages = try Self.prepare(tools)+ let bundle = try MCPResultPreparation.prepare(pages: pages,+ budget: MCPResultRetentionBudget(store: .ordinary, originalCaptureIndexBytes: 0,+ visibleBytes: 0, pendingBytes: 0))+ let deadline = ContinuousClock.now + .seconds(300)+ let firstCandidate = try fixture.store.prepare(preparedBundle: bundle, cursors: [UUID().uuidString],+ deadline: deadline, operationID: UUID(), metadataBytes: nil, policy: .cached)+ let first = try #require(firstCandidate)+ let secondCandidate = try fixture.store.prepare(preparedBundle: bundle, cursors: [UUID().uuidString],+ deadline: deadline, operationID: UUID(), metadataBytes: nil, policy: .cached)+ let second = try #require(secondCandidate)+ #expect(throws: PublicationRejection.busy) {+ try fixture.store.prepareAggregate([first, second], in: fixture.store.domain)+ }+ let state = try fixture.store.domain.accounting(for: fixture.store.publicationStoreID)+ #expect(state.pendingBytes == bundle.charge.totalBytes * 2 && state.visibleBytes == 0)+ let (_, retired) = fixture.store.domain.withLockRetainingRetirement {+ first.discardLocked(in: fixture.store.domain)+ second.discardLocked(in: fixture.store.domain)+ }+ withExtendedLifetime(retired) {}+ #expect(try fixture.store.domain.accounting(for: fixture.store.publicationStoreID).pendingBytes == 0)+ }++ nonisolated private static func prepare(_ tools: [MCPPreparedToolRead]) throws -> [MCPResultPreparedPage] {+ let metadata: MCPResultPreparedMetadata?+ if let first = tools.first,+ let value = try MCPResultProviderAdapters.metadata(result: first.result,+ frozenReadBytes: first.frozenMetadataBytes) {+ metadata = try MCPResultPreparation.metadata(value: value)+ } else { metadata = nil }+ return try tools.map { tool in+ guard let text = tool.result.content.first?.text else { throw MCPReadCaptureError.serializationFailure }+ return try MCPResultPreparation.page(request: MCPResultPagePreparationRequest(text: text,+ isError: tool.result.isError, origin: .generatedJSON, evidence: .established,+ context: MCPResultContext(tool: "query_tasks", semanticFailure: nil,+ mutationRecovery: nil, entityPositions: []), metadataOwner: metadata))+ }+ }++ @MainActor private struct Fixture {+ let models: TestModelContainer+ let source: Source+ let store: MCPTaskQuerySnapshotStore+ let coordinator: MCPReadCoordinator+ init() throws {+ models = try TestModelContainer()+ models.context.autosaveEnabled = false+ let project = Project(name: "Frozen", description: "", gitRepo: nil, colorHex: "blue")+ models.context.insert(project)+ for number in 1...2 {+ models.context.insert(TransitTask(name: "Saved \(number)", type: .feature,+ project: project, displayID: .permanent(number)))+ }+ try models.context.save()+ source = Source(models)+ store = MCPTaskQuerySnapshotStore()+ coordinator = MCPReadCoordinator(domain: store.domain)+ }+ func service(_ preparer: @escaping MCPReadPagePreparer) -> MCPReadService {+ MCPReadService(source: source, monitor: MCPImportEvidenceMonitor(syncActive: false,+ storeIdentifier: nil), snapshots: store, pagePreparer: preparer)+ }+ func execute(_ service: MCPReadService, arguments: [String: Any],+ id: JSONRPCId = .string("fixture")) async throws -> Data {+ let fields = arguments.mapValues(AnyCodable.init)+ return await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { operation in+ do {+ let tool = try await self.prepare(service, fields: fields, operation: operation)+ let bytes: Data+ if let page = tool.preparedResultPage {+ bytes = try MCPResultEncoder.encode(fragment: page.fragment, id: id)+ } else { bytes = try MCPBoundedReadDispatcher.encodeResult(tool, id: id) }+ return PreparedReadResult(encodedResponse: bytes, publications: tool.publications,+ publicationErrors: .init(busy: Data(), expired: Data(), capacity: Data()))+ } catch {+ Issue.record("Unexpected fixture failure: \(error)")+ return PreparedReadResult(encodedResponse: Data(), publications: [],+ publicationErrors: .init(busy: Data(), expired: Data(), capacity: Data()))+ }+ }+ }+ private func prepare(_ service: MCPReadService, fields: [String: AnyCodable],+ operation: MCPReadOperation) async throws -> MCPPreparedToolRead {+ try await service.prepare(tool: "query_tasks", arguments: fields.mapValues(\.value), operation: operation)+ }+ func drain() async {+ let deadline = ContinuousClock.now + .seconds(1)+ while coordinator.unfinishedCount != 0 && .now < deadline { await Task.yield() }+ #expect(coordinator.unfinishedCount == 0)+ withExtendedLifetime(models) {}+ }+ }++ @MainActor private final class Source: MCPReadCaptureSource {+ let builder: MCPReadCaptureBuilder+ var failure: MCPReadCaptureError?+ var calls = 0+ init(_ models: TestModelContainer) {+ builder = MCPReadCaptureBuilder(container: models.container, fence: .actorOnlyTestFixture)+ }+ func capture(_ request: ReadCaptureRequest) throws -> CapturedReadView {+ calls += 1+ if let failure { throw failure }+ return try builder.capture(request)+ }+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadProjectionTests.swift b/Transit/TransitTests/MCPReadProjectionTests.swiftnew file mode 100644index 0000000..92caf56--- /dev/null+++ b/Transit/TransitTests/MCPReadProjectionTests.swift@@ -0,0 +1,208 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPReadProjectionTests {+ @Test func summaryUsesSavedValuesAndDoesNotFetchComments() throws {+ let fixture = try TestModelContainer()+ fixture.context.autosaveEnabled = false+ let project = Project(name: "Saved project", description: "", gitRepo: nil, colorHex: "blue")+ let task = TransitTask(name: "Saved task", type: .feature, project: project, displayID: .permanent(63))+ fixture.context.insert(project)+ fixture.context.insert(task)+ try fixture.context.save()+ let expected = IntentHelpers.taskToDict(task, formatter: ISO8601DateFormatter())+ task.name = "Unsaved task"+ project.name = "Unsaved project"+ let source = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,+ fetchComments: { _ in throw CocoaError(.fileReadUnknown) })+ let view = try source.capture(request(full: false))+ let results = try MCPReadProjection.tasks(view, request: query(), arguments: [:])+ #expect(try bytes(results[0]) == bytes(expected))+ #expect(fixture.context.hasChanges)+ }++ @Test func fullHiddenCommentsPreserveAuthoritativeRevision() throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ let task = TransitTask(name: "Task", type: .bug, project: project, displayID: .permanent(63))+ let comment = Comment(content: "Before", authorName: "A", isAgent: true, task: task)+ fixture.context.insert(project)+ fixture.context.insert(task)+ fixture.context.insert(comment)+ try fixture.context.save()+ let expected = try MCPRecordSnapshot.task(task, in: fixture.context).revision+ let view = try MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture)+ .capture(request(full: true))+ comment.content = "After"+ try fixture.context.save()+ let results = try MCPReadProjection.tasks(view, request: query(full: true), arguments: [:])+ #expect(results[0]["revision"] as? String == expected)+ #expect(results[0]["comments"] == nil)+ #expect(results[0]["metadata"] == nil)+ #expect(results[0]["description"] is NSNull)+ }++ @Test func duplicateUUIDSelectorRemainsAmbiguousDespitePhysicalKeys() throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ let first = TransitTask(name: "First", type: .feature, project: project, displayID: .permanent(1))+ let second = TransitTask(name: "Second", type: .feature, project: project, displayID: .permanent(2))+ second.id = first.id+ fixture.context.insert(project)+ fixture.context.insert(first)+ fixture.context.insert(second)+ try fixture.context.save()+ let view = try MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture)+ .capture(request(full: false))+ let args: [String: Any] = ["taskIds": [first.id.uuidString.lowercased(), UUID().uuidString],+ "detailLevel": "summary", "includeComments": false, "limit": 100]+ let results = try MCPReadProjection.tasks(view, request: MCPTaskQueryRequest.parse(args), arguments: args)+ #expect((results[0]["error"] as? [String: String])?["code"] == "AMBIGUOUS_TASK_ID")+ #expect((results[1]["error"] as? [String: String])?["code"] == "TASK_NOT_FOUND")+ #expect(results.map { $0["index"] as? Int } == [0, 1])+ }++ @Test func malformedPolicyPrecedesCursorLookupAndMatchingPolicyIsAccepted() throws {+ let cursor = UUID().uuidString+ #expect(throws: MCPTaskQueryError.self) {+ try MCPTaskQueryRequest.parse(["cursor": cursor, "readPolicy": 1])+ }+ #expect(try MCPTaskQueryRequest.parse(["cursor": cursor, "readPolicy": "cached"]).readPolicy == .cached)+ #expect(try MCPTaskQueryRequest.parse(["cursor": cursor]).readPolicy == nil)+ }++ @Test func catalogRejectsMissingAndDuplicatePhysicalTaskMatches() throws {+ let view = try catalogView()+ for tasks in [Array(view.tasks.dropFirst()), view.tasks + [view.tasks[0]]] {+ let malformed = replacingTasks(view, tasks: tasks)+ #expect(throws: MCPReadCaptureError.incoherentCapture) {+ try MCPReadProjection.projects(malformed)+ }+ #expect(throws: MCPReadCaptureError.incoherentCapture) {+ try MCPReadProjection.milestones(malformed, arguments: ["displayId": 7])+ }+ }+ }++ @Test func catalogIndexPreservesRelationshipOrderAndActiveCount() throws {+ let view = try catalogView()+ let reordered = replacingTasks(view, tasks: Array(view.tasks.reversed()))+ let projects = try MCPReadProjection.projects(reordered)+ #expect(projects[0]["activeTaskCount"] as? Int == 2)+ let milestones = try MCPReadProjection.milestones(reordered, arguments: ["displayId": 7])+ let summaries = try #require(milestones[0]["tasks"] as? [[String: Any]])+ let expected = try view.milestones[0].taskKeys.map { key in+ try #require(view.tasks.first { $0.physicalKey == key }).id.uuidString+ }+ #expect(summaries.compactMap { $0["taskId"] as? String } == expected)+ }++ @Test func catalogCancellationInterruptsIndexingAndRelationshipTraversal() throws {+ let view = try catalogView()+ for stopAfter in [3, 7] {+ var checkpoints = 0+ #expect(throws: CancellationError.self) {+ try MCPReadProjection.projects(view, checkpoint: {+ checkpoints += 1+ if checkpoints == stopAfter { throw CancellationError() }+ })+ }+ #expect(checkpoints == stopAfter)+ }+ for stopAfter in [3, 9] {+ var checkpoints = 0+ #expect(throws: CancellationError.self) {+ try MCPReadProjection.milestones(view, arguments: ["displayId": 7], checkpoint: {+ checkpoints += 1+ if checkpoints == stopAfter { throw CancellationError() }+ })+ }+ #expect(checkpoints == stopAfter)+ }+ }++ @Test(arguments: ["milestoneInput", "projectPolicy", "capacity"])+ func freshPlainTextReadFailuresPreserveSemanticCategory(scenario: String) async throws {+ let fixture = try TestModelContainer()+ let store = MCPTaskQuerySnapshotStore()+ let service = MCPReadService(source: MCPReadCaptureBuilder(container: fixture.container,+ fence: .actorOnlyTestFixture), monitor: MCPImportEvidenceMonitor(syncActive: false,+ storeIdentifier: nil), snapshots: store)+ let coordinator = MCPReadCoordinator(domain: store.domain)+ let tool = scenario == "milestoneInput" ? "query_milestones" : "get_projects"+ let bytes = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { operation in+ do {+ let prepared: MCPPreparedToolRead+ if scenario == "capacity" {+ prepared = try await service.prepareFailure(MCPResultPreparationError.retentionCapacity,+ tool: tool, operation: operation, policy: .cached)+ } else {+ let arguments: [String: Any] = scenario == "milestoneInput"+ ? ["status": 17, "readPolicy": "cached"] : ["readPolicy": true]+ prepared = try await service.prepare(tool: tool, arguments: arguments, operation: operation)+ }+ let context = MCPResultContext(tool: tool, semanticFailure: nil, mutationRecovery: nil,+ entityPositions: [])+ let outcome = try MCPResultProviderAdapters.outcome(result: prepared.result, context: context,+ origin: .generatedJSON)+ let presentation = try MCPResultAdapter.present(outcome.source, context: outcome.context)+ #expect(presentation.errorCategory == (scenario == "capacity" ? .retentionCapacity : .invalidInput))+ #expect(outcome.source.originalText == prepared.result.content[0].text)+ #expect(outcome.source.originalIsError == true)+ #expect(outcome.source.kind == .text)+ #expect(prepared.result.providerEvidence?.failure?.diagnostic == nil)+ return PreparedReadResult(encodedResponse: prepared.encodedToolResult, publications: [],+ publicationErrors: .init(busy: Data(), expired: Data(), capacity: Data()))+ } catch {+ Issue.record("Read failure classification failed: \(error)")+ return PreparedReadResult(encodedResponse: Data(), publications: [],+ publicationErrors: .init(busy: Data(), expired: Data(), capacity: Data()))+ }+ }+ #expect(!bytes.isEmpty)+ }++ private func catalogView() throws -> CapturedReadView {+ let fixture = try TestModelContainer()+ let project = Project(name: "Catalog", description: "", gitRepo: nil, colorHex: "blue")+ let milestone = Milestone(name: "Milestone", project: project, displayID: .permanent(7))+ fixture.context.insert(project)+ fixture.context.insert(milestone)+ for index in 0..<3 {+ let task = TransitTask(name: "Task \(index)", type: .feature, project: project,+ displayID: .permanent(index + 1))+ task.milestone = milestone+ if index == 0 { task.status = .done }+ fixture.context.insert(task)+ }+ try fixture.context.save()+ return try MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture)+ .capture(ReadCaptureRequest(projectSelectors: nil, selection: .tasks(detail: .summary),+ completeness: .selectedRead, includeComments: false))+ }++ private func replacingTasks(_ view: CapturedReadView, tasks: [ReadTask]) -> CapturedReadView {+ CapturedReadView(completeness: view.completeness, captureScope: view.captureScope, metadata: view.metadata,+ createdAt: view.createdAt, retentionDeadline: view.retentionDeadline, projects: view.projects,+ tasks: tasks, milestones: view.milestones, comments: view.comments)+ }++ private func request(full: Bool) -> ReadCaptureRequest {+ ReadCaptureRequest(projectSelectors: nil, selection: .tasks(detail: full ? .fullRecord : .summary),+ completeness: .selectedRead, includeComments: false)+ }++ private func query(full: Bool = false) throws -> MCPTaskQueryRequest {+ try MCPTaskQueryRequest.parse(["detailLevel": full ? "full" : "summary",+ "includeComments": false, "limit": 100])+ }++ private func bytes(_ value: [String: Any]) throws -> Data {+ try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys])+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadProviderEvidenceTests.swift b/Transit/TransitTests/MCPReadProviderEvidenceTests.swiftnew file mode 100644index 0000000..2edafc8--- /dev/null+++ b/Transit/TransitTests/MCPReadProviderEvidenceTests.swift@@ -0,0 +1,36 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPReadProviderEvidenceTests {+ @Test(arguments: [false, true])+ func providerSidecarPreservesWireAndPublicationAttachment(declared: Bool) throws {+ let text = "Saved read capture service is unavailable"+ let evidence = declared ? MCPResultProviderEvidence(origin: .plainText, evidence: .established) : nil+ let original = try MCPPreparedToolRead(text: text, isError: true)+ let annotated = try MCPPreparedToolRead(text: text, isError: true, providerEvidence: evidence)+ let attached = annotated.attaching([])+ #expect(attached.encodedToolResult == original.encodedToolResult)+ #expect(attached.result.content.first?.text == text && attached.result.isError == true)+ #expect((attached.result.providerEvidence != nil) == declared)+ let decoded = try JSONSerialization.jsonObject(with: JSONEncoder().encode(attached.result))+ let wire = try #require(decoded as? [String: Any])+ #expect(wire["providerEvidence"] == nil && wire["origin"] == nil)+ }++ @Test func explicitPlainTextEvidenceOverridesGeneratedJSONAdapterDefault() throws {+ let text = "Saved read storage failed"+ let tool = try MCPPreparedToolRead(text: text, isError: true,+ providerEvidence: MCPResultProviderEvidence(origin: .plainText, evidence: .established))+ let context = MCPResultContext(tool: "get_projects", semanticFailure: nil,+ mutationRecovery: nil, entityPositions: [])+ let outcome = try MCPResultProviderAdapters.outcome(result: tool.result, context: context,+ origin: .generatedJSON)+ #expect(outcome.source.kind == .text && outcome.source.evidence == .established)+ #expect(outcome.source.originalText == text && outcome.source.originalIsError == true)+ #expect(outcome.source.document == nil)+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadPublicationDomainTests.swift b/Transit/TransitTests/MCPReadPublicationDomainTests.swiftnew file mode 100644index 0000000..2773cd7--- /dev/null+++ b/Transit/TransitTests/MCPReadPublicationDomainTests.swift@@ -0,0 +1,360 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@Suite(.serialized)+nonisolated struct MCPReadPublicationDomainTests {+ private let deadline = ContinuousClock.now + .seconds(300)++ private func index(_ roots: [MCPPublicationRoot] = []) throws -> PublicationTestIndex {+ PublicationTestIndex(descriptor: try MCPPublicationIndexDescriptor(roots: roots))+ }++ // swiftlint:disable:next function_parameter_count+ private func reserve(_ domain: MCPReadPublicationDomain, _ store: MCPPublicationStoreID,+ _ candidate: PublicationTestIndex, entries: Int, bytes: Int,+ tokens: Set<String>) throws -> MCPPublicationReservation {+ let base = try domain.snapshot(for: store)+ return try domain.reserve(storeID: store, operationID: UUID(), expectedVersion: base.version,+ expectedTokenVersion: base.tokenVersion, index: candidate,+ chargeEntries: entries, chargeBytes: bytes, newTokens: tokens,+ deadline: deadline)+ }++ private func wait(_ semaphore: DispatchSemaphore) -> DispatchTimeoutResult {+ semaphore.wait(timeout: .now() + 2)+ }++ @Test func capacityTransferAndExactlyOnceRollback() throws {+ let domain = MCPReadPublicationDomain()+ let store = MCPPublicationStoreID(rawValue: UUID())+ try domain.register(storeID: store, index: index(), maxEntries: 2, maxBytes: 10)+ let rootA = MCPPublicationRoot(id: "a", deadline: deadline, encodedByteCount: 4, tokens: ["a"])+ let rootB = MCPPublicationRoot(id: "b", deadline: deadline, encodedByteCount: 6, tokens: ["b"])+ let first = try reserve(domain, store, index([rootA]), entries: 1, bytes: 4, tokens: ["a"])+ let second = try reserve(domain, store, index([rootB]), entries: 1, bytes: 6, tokens: ["b"])+ #expect(try domain.accounting(for: store) == MCPPublicationAccounting(visibleEntries: 0, visibleBytes: 0,+ pendingEntries: 2, pendingBytes: 10))+ #expect(throws: PublicationRejection.capacity) {+ try reserve(domain, store, index([MCPPublicationRoot(id: "c", deadline: deadline,+ encodedByteCount: 1, tokens: ["c"])]),+ entries: 1, bytes: 1, tokens: ["c"])+ }+ let unrelated = MCPPublicationStoreID(rawValue: UUID())+ try domain.register(storeID: unrelated, index: index(), maxEntries: 8, maxBytes: 100)+ let other = try reserve(domain, unrelated, index([MCPPublicationRoot(id: "x", deadline: deadline,+ encodedByteCount: 1, tokens: ["x"])]),+ entries: 1, bytes: 1, tokens: ["x"])+ let aggregate = try domain.transfer([first, second], aggregateIndex: index([rootA, rootB]), operationID: UUID())+ #expect(try domain.accounting(for: store).pendingBytes == 10)+ domain.withLock { first.discardLocked(in: domain); second.discardLocked(in: domain) }+ #expect(try domain.accounting(for: store).pendingBytes == 10)+ domain.withLock { aggregate.discardLocked(in: domain); aggregate.discardLocked(in: domain) }+ #expect(try domain.accounting(for: store).pendingBytes == 0)+ domain.withLock { other.discardLocked(in: domain) }+ }++ @Test func staleCASAndGlobalTokenCollisions() throws {+ let domain = MCPReadPublicationDomain()+ let store = MCPPublicationStoreID(rawValue: UUID())+ try domain.register(storeID: store, index: index(), maxEntries: 8, maxBytes: 100)+ let root = MCPPublicationRoot(id: "a", deadline: deadline, encodedByteCount: 3, tokens: ["token"])+ let candidate = try reserve(domain, store, index([root]), entries: 1, bytes: 3, tokens: ["token"])+ #expect(throws: PublicationRejection.busy) {+ try reserve(domain, store, index([root]), entries: 1, bytes: 3, tokens: ["token"])+ }+ let sibling = try reserve(domain, store, index([MCPPublicationRoot(id: "b", deadline: deadline,+ encodedByteCount: 4, tokens: ["b"])]),+ entries: 1, bytes: 4, tokens: ["b"])+ domain.withLock { candidate.commitLocked(in: domain) }+ #expect(domain.withLock { sibling.validateLocked(in: domain) } == .busy)+ domain.withLock { sibling.discardLocked(in: domain) }+ #expect(try domain.snapshot(for: store).version == 1)+ #expect(try domain.accounting(for: store).visibleBytes == 3)+ #expect(try domain.accounting(for: store).pendingBytes == 0)+ }++ @Test func unrelatedStoreAllocationInvalidatesPinnedTokenVersion() throws {+ let domain = MCPReadPublicationDomain()+ let first = MCPPublicationStoreID(rawValue: UUID())+ let second = MCPPublicationStoreID(rawValue: UUID())+ try domain.register(storeID: first, index: index(), maxEntries: 8, maxBytes: 100)+ try domain.register(storeID: second, index: index(), maxEntries: 8, maxBytes: 100)+ let pinned = try domain.snapshot(for: first)+ let root = MCPPublicationRoot(id: "a", deadline: deadline, encodedByteCount: 1, tokens: ["shared"])+ let pending = try reserve(domain, second, index([root]), entries: 1, bytes: 1, tokens: ["shared"])+ #expect(throws: PublicationRejection.busy) {+ try domain.reserve(storeID: first, operationID: UUID(), expectedVersion: pinned.version,+ expectedTokenVersion: pinned.tokenVersion, index: index([root]),+ chargeEntries: 1, chargeBytes: 1, newTokens: ["shared"], deadline: deadline)+ }+ #expect(throws: PublicationRejection.busy) {+ try reserve(domain, first, index([root]), entries: 1, bytes: 1, tokens: ["shared"])+ }+ #expect(try domain.accounting(for: first).pendingBytes == 0)+ domain.withLock { pending.discardLocked(in: domain) }+ #expect(throws: PublicationRejection.busy) {+ try reserve(domain, first, index([root]), entries: -1, bytes: 1, tokens: ["shared"])+ }+ }++ @Test func appendExpiryAndExactNetCharges() throws {+ var now = ContinuousClock.now+ let domain = MCPReadPublicationDomain(testingInstant: now)+ let store = MCPPublicationStoreID(rawValue: UUID())+ let original = MCPPublicationRoot(id: "a", deadline: now + .seconds(1), encodedByteCount: 2, tokens: ["a"])+ try domain.register(storeID: store, index: index([original]), maxEntries: 8, maxBytes: 100)+ let appended = MCPPublicationRoot(id: "a", deadline: original.deadline, encodedByteCount: 5, tokens: ["a", "b"])+ #expect(throws: PublicationRejection.busy) {+ try reserve(domain, store, index([appended]), entries: 0, bytes: 2, tokens: ["b"])+ }+ let shortened = MCPPublicationRoot(id: "a", deadline: original.deadline - .milliseconds(100),+ encodedByteCount: 5, tokens: ["a", "b"])+ #expect(throws: PublicationRejection.busy) {+ try reserve(domain, store, index([shortened]), entries: 0, bytes: 3, tokens: ["b"])+ }+ let pending = try reserve(domain, store, index([appended]), entries: 0, bytes: 3, tokens: ["b"])+ now = original.deadline+ domain.setTestingInstant(now)+ #expect(domain.withLock { pending.validateLocked(in: domain) } == .expired)+ domain.withLock { pending.discardLocked(in: domain) }+ #expect(try domain.accounting(for: store).visibleBytes == 2)+ let extended = MCPPublicationRoot(id: "a", deadline: deadline, encodedByteCount: 5, tokens: ["a", "b"])+ #expect(throws: PublicationRejection.busy) {+ try reserve(domain, store, index([extended]), entries: 0, bytes: 3, tokens: ["b"])+ }+ }++ @Test func twoAppendsAndCreateAppendTransferOneSwap() throws {+ for includeCreate in [false, true] {+ let domain = MCPReadPublicationDomain()+ let store = MCPPublicationStoreID(rawValue: UUID())+ let original = MCPPublicationRoot(id: "a", deadline: deadline, encodedByteCount: 2, tokens: ["a"])+ try domain.register(storeID: store, index: index([original]), maxEntries: 8, maxBytes: 100)+ let appended = MCPPublicationRoot(id: "a", deadline: deadline, encodedByteCount: 5, tokens: ["a", "b"])+ let other = includeCreate+ ? MCPPublicationRoot(id: "c", deadline: deadline, encodedByteCount: 4, tokens: ["c"])+ : MCPPublicationRoot(id: "a", deadline: deadline, encodedByteCount: 6, tokens: ["a", "c"])+ let first = try reserve(domain, store, index([appended]), entries: 0, bytes: 3, tokens: ["b"])+ let second = try reserve(domain, store, index(includeCreate ? [original, other] : [other]),+ entries: includeCreate ? 1 : 0, bytes: 4, tokens: ["c"])+ let combined = includeCreate ? [appended, other]+ : [MCPPublicationRoot(id: "a", deadline: deadline, encodedByteCount: 9, tokens: ["a", "b", "c"])]+ let aggregate = try domain.transfer([first, second], aggregateIndex: index(combined), operationID: UUID())+ #expect(try domain.accounting(for: store).pendingBytes == 7)+ domain.withLock {+ #expect(aggregate.validateLocked(in: domain) == nil)+ aggregate.commitLocked(in: domain)+ first.discardLocked(in: domain)+ second.discardLocked(in: domain)+ aggregate.discardLocked(in: domain)+ }+ #expect(try domain.accounting(for: store).visibleBytes == 9)+ #expect(try domain.accounting(for: store).pendingBytes == 0)+ #expect(try domain.snapshot(for: store).version == 1)+ }+ }++}++extension MCPReadPublicationDomainTests {+ @Test func descriptorGetterNeverRunsInsideGate() throws {+ let domain = MCPReadPublicationDomain()+ let store = MCPPublicationStoreID(rawValue: UUID())+ try domain.register(storeID: store,+ index: PublicationReentrantIndex(descriptor: try MCPPublicationIndexDescriptor(roots: []), domain: domain),+ maxEntries: 8, maxBytes: 100)+ let root = MCPPublicationRoot(id: "a", deadline: deadline, encodedByteCount: 1, tokens: ["a"])+ let candidate = PublicationReentrantIndex(descriptor: try MCPPublicationIndexDescriptor(roots: [root]),+ domain: domain)+ let snapshot = try domain.snapshot(for: store)+ let pending = try domain.reserve(storeID: store, operationID: UUID(), expectedVersion: snapshot.version,+ expectedTokenVersion: snapshot.tokenVersion, index: candidate,+ chargeEntries: 1, chargeBytes: 1, newTokens: ["a"], deadline: deadline)+ domain.withLock {+ #expect(pending.validateLocked(in: domain) == nil)+ pending.commitLocked(in: domain)+ pending.discardLocked(in: domain)+ }+ #expect(try domain.accounting(for: store).visibleBytes == 1)+ _ = try domain.snapshot(for: store)+ try domain.retire(storeID: store, expectedVersion: 1, replacementIndex: index())+ }++ @Test @concurrent func commitAndDiscardDestructionAllowConcurrentGate() async throws {+ for commit in [false, true] {+ let domain = MCPReadPublicationDomain()+ let store = MCPPublicationStoreID(rawValue: UUID())+ let started = DispatchSemaphore(value: 0)+ let release = DispatchSemaphore(value: 0)+ if commit {+ try domain.register(storeID: store,+ index: PublicationDestructionIndex(descriptor: try MCPPublicationIndexDescriptor(roots: []),+ started: started, release: release), maxEntries: 8, maxBytes: 100)+ _ = try reserve(domain, store,+ index([MCPPublicationRoot(id: "a", deadline: deadline, encodedByteCount: 1, tokens: ["a"])]),+ entries: 1, bytes: 1, tokens: ["a"])+ } else {+ try domain.register(storeID: store, index: index(), maxEntries: 8, maxBytes: 100)+ let base = try domain.snapshot(for: store)+ _ = try domain.reserve(storeID: store, operationID: UUID(), expectedVersion: base.version,+ expectedTokenVersion: base.tokenVersion,+ index: PublicationDestructionIndex(descriptor: try MCPPublicationIndexDescriptor(roots: [+ MCPPublicationRoot(id: "a", deadline: deadline, encodedByteCount: 1, tokens: ["a"])]),+ started: started, release: release),+ chargeEntries: 1, chargeBytes: 1, newTokens: ["a"], deadline: deadline)+ }+ let finalizer = Task.detached {+ domain.withLock {+ if let pending = domain.stores[store]?.pending.values.first {+ if commit { pending.commitLocked(in: domain) } else { pending.discardLocked(in: domain) }+ }+ }+ }+ #expect(wait(started) == .success)+ let gateStart = ContinuousClock.now+ let gate = Task.detached { domain.withLock { 42 } }+ #expect(await gate.value == 42)+ #expect(gateStart.duration(to: .now) < .seconds(1))+ release.signal()+ await finalizer.value+ }+ }++ @Test @concurrent func responseSelectionPrecedesLargeRetirementCleanup() async throws {+ let domain = MCPReadPublicationDomain()+ let coordinator = MCPReadCoordinator(domain: domain, cutoff: .milliseconds(100))+ let store = MCPPublicationStoreID(rawValue: UUID())+ let started = DispatchSemaphore(value: 0)+ let release = DispatchSemaphore(value: 0)+ try domain.register(storeID: store,+ index: PublicationDestructionIndex(descriptor: try MCPPublicationIndexDescriptor(roots: []),+ started: started, release: release), maxEntries: 8, maxBytes: 100)+ let pending = try reserve(domain, store,+ index([MCPPublicationRoot(id: "a", deadline: deadline, encodedByteCount: 1, tokens: ["a"])]),+ entries: 1, bytes: 1, tokens: ["a"])+ let start = ContinuousClock.now+ let bytes = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { _ in+ PreparedReadResult(encodedResponse: Data("success:a".utf8), publications: [pending],+ publicationErrors: PreencodedPublicationErrors(busy: Data("busy".utf8),+ expired: Data("expired".utf8), capacity: Data("capacity".utf8)))+ }+ #expect(bytes == Data("success:a".utf8))+ #expect(start.duration(to: .now) < .seconds(1))+ #expect(wait(started) == .success)+ #expect(coordinator.unfinishedCount == 1)+ release.signal()+ for _ in 0..<100 where coordinator.unfinishedCount > 0 {+ try await Task.sleep(for: .milliseconds(1))+ }+ #expect(coordinator.unfinishedCount == 0)+ }++ @Test @concurrent func largeIndexDestructionAllowsConcurrentGate() async throws {+ let domain = MCPReadPublicationDomain()+ let store = MCPPublicationStoreID(rawValue: UUID())+ let started = DispatchSemaphore(value: 0)+ let release = DispatchSemaphore(value: 0)+ try domain.register(storeID: store,+ index: PublicationDestructionIndex(descriptor: try MCPPublicationIndexDescriptor(roots: []),+ started: started, release: release), maxEntries: 8, maxBytes: 100)+ let empty = try index()+ let retirement = Task.detached {+ try domain.retire(storeID: store, expectedVersion: 0, replacementIndex: empty)+ }+ #expect(wait(started) == .success)+ let gate = Task.detached { domain.withLock { 42 } }+ #expect(await gate.value == 42)+ release.signal()+ try await retirement.value+ }++ @Test @concurrent func seededTerminalRacesDiscardRealReservations() async throws {+ for seed in 0..<24 {+ let domain = MCPReadPublicationDomain()+ let store = MCPPublicationStoreID(rawValue: UUID())+ let coordinator = MCPReadCoordinator(domain: domain, cutoff: .milliseconds(4))+ try domain.register(storeID: store, index: index(), maxEntries: 8, maxBytes: 100)+ let pending = try reserve(domain, store, index([MCPPublicationRoot(id: "a", deadline: deadline,+ encodedByteCount: 3, tokens: ["a"])]),+ entries: 1, bytes: 3, tokens: ["a"])+ let started = DispatchSemaphore(value: 0)+ let work = Task {+ await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { _ in+ started.signal()+ try? await Task.sleep(for: .milliseconds(seed % 7))+ return PreparedReadResult(encodedResponse: Data("success:a".utf8), publications: [pending],+ publicationErrors: PreencodedPublicationErrors(busy: Data("busy".utf8),+ expired: Data("expired".utf8), capacity: Data("capacity".utf8)))+ }+ }+ #expect(wait(started) == .success)+ if seed % 3 == 0 { try await Task.sleep(for: .milliseconds(1)); coordinator.stop() }+ if seed % 5 == 0 { work.cancel() }+ let bytes = await work.value+ for _ in 0..<100 where coordinator.unfinishedCount > 0 {+ try await Task.sleep(for: .milliseconds(1))+ }+ let expected = bytes == Data("success:a".utf8) ? 3 : 0+ #expect(try domain.accounting(for: store).visibleBytes == expected)+ #expect(try domain.accounting(for: store).pendingBytes == 0)+ #expect(coordinator.unfinishedCount == 0)+ domain.withLock { pending.discardLocked(in: domain) }+ #expect(try domain.accounting(for: store).pendingBytes == 0)+ }+ }++ @Test @concurrent func validatesAllStoresBeforeAnyCommitAndChoosesPreencodedError() async throws {+ let domain = MCPReadPublicationDomain()+ let coordinator = MCPReadCoordinator(domain: domain)+ let firstStore = MCPPublicationStoreID(rawValue: UUID())+ let secondStore = MCPPublicationStoreID(rawValue: UUID())+ try domain.register(storeID: firstStore, index: index(), maxEntries: 8, maxBytes: 100)+ try domain.register(storeID: secondStore, index: index(), maxEntries: 8, maxBytes: 100)+ let first = try reserve(domain, firstStore, index([MCPPublicationRoot(id: "a", deadline: deadline,+ encodedByteCount: 1, tokens: ["a"])]),+ entries: 1, bytes: 1, tokens: ["a"])+ let second = try reserve(domain, secondStore, index([MCPPublicationRoot(id: "b", deadline: deadline,+ encodedByteCount: 1, tokens: ["b"])]),+ entries: 1, bytes: 1, tokens: ["b"])+ try domain.retire(storeID: secondStore, expectedVersion: 0, replacementIndex: index())+ let result = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { _ in+ PreparedReadResult(encodedResponse: Data("success:a,b".utf8), publications: [first, second],+ publicationErrors: PreencodedPublicationErrors(busy: Data("cas".utf8),+ expired: Data("expired".utf8), capacity: Data("capacity".utf8)))+ }+ #expect(result == Data("cas".utf8))+ #expect(try domain.accounting(for: firstStore).visibleBytes == 0)+ #expect(try domain.accounting(for: firstStore).pendingBytes == 0)+ #expect(try domain.accounting(for: secondStore).pendingBytes == 0)+ }+}++nonisolated private final class PublicationTestIndex: MCPPublicationIndex {+ let descriptor: MCPPublicationIndexDescriptor+ init(descriptor: MCPPublicationIndexDescriptor) { self.descriptor = descriptor }+}+nonisolated private final class PublicationReentrantIndex: MCPPublicationIndex {+ private let value: MCPPublicationIndexDescriptor+ private unowned let domain: MCPReadPublicationDomain+ var descriptor: MCPPublicationIndexDescriptor { domain.withLock { value } }+ init(descriptor: MCPPublicationIndexDescriptor, domain: MCPReadPublicationDomain) {+ value = descriptor+ self.domain = domain+ }+}++nonisolated private final class PublicationDestructionIndex: MCPPublicationIndex {+ let descriptor: MCPPublicationIndexDescriptor+ let payload = Data(repeating: 1, count: 16 * 1024 * 1024)+ let started: DispatchSemaphore+ let release: DispatchSemaphore+ init(descriptor: MCPPublicationIndexDescriptor, started: DispatchSemaphore, release: DispatchSemaphore) {+ self.descriptor = descriptor+ self.started = started+ self.release = release+ }+ deinit { started.signal(); _ = release.wait(timeout: .now() + 2) }+}+#endif
diff --git a/Transit/TransitTests/MCPReadPublicationFailureTests.swift b/Transit/TransitTests/MCPReadPublicationFailureTests.swiftnew file mode 100644index 0000000..9e1c28e--- /dev/null+++ b/Transit/TransitTests/MCPReadPublicationFailureTests.swift@@ -0,0 +1,58 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPReadPublicationFailureTests {+ nonisolated private enum EncodingFailure: Error { case injected }++ @Test func outerEncodingFailureDiscardsActualPrivateOrdinaryCandidate() async throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ fixture.context.insert(project)+ for number in 1...2 {+ fixture.context.insert(TransitTask(name: "Task \(number)", type: .feature,+ project: project, displayID: .permanent(number)))+ }+ try fixture.context.save()+ let env = try MCPTestHelpers.makeEnv()+ let store = MCPTaskQuerySnapshotStore()+ let service = MCPReadService(source: MCPReadCaptureBuilder(container: fixture.container,+ fence: .actorOnlyTestFixture), monitor: MCPImportEvidenceMonitor(syncActive: false,+ storeIdentifier: nil), snapshots: store)+ let handler = MCPToolHandler(taskService: env.taskService, projectService: env.projectService,+ commentService: env.commentService, milestoneService: env.milestoneService,+ maintenanceService: env.maintenanceService, settings: env.mcpSettings, readService: service)+ let rpc = JSONRPCRequest(jsonrpc: "2.0", id: .string("outer-encoding-\"\\failure"), method: "tools/call",+ params: AnyCodable(["name": "query_tasks", "arguments": ["detailLevel": "summary",+ "includeComments": false, "limit": 1]] as [String: Any]))+ let read = try #require(MCPBoundedReadDispatcher.classify(rpc))+ let domain = store.domain+ let storeID = store.publicationStoreID+ let bytes = try await MCPBoundedReadDispatcher.response(for: read, rpc: rpc, handler: handler,+ coordinator: handler.readCoordinator, admittedAt: .now, encode: { tool, _ in+ #expect(tool.publications.count == 1)+ let privateState = try domain.accounting(for: storeID)+ #expect(privateState.visibleEntries == 0 && privateState.pendingEntries == 1)+ #expect(privateState.pendingBytes > 0)+ throw EncodingFailure.injected+ })+ let deadline = ContinuousClock.now + .seconds(1)+ while handler.readCoordinator.unfinishedCount != 0 && .now < deadline { await Task.yield() }+ #expect(handler.readCoordinator.unfinishedCount == 0)+ let after = try domain.accounting(for: storeID)+ #expect(after.visibleEntries == 0 && after.visibleBytes == 0)+ #expect(after.pendingEntries == 0 && after.pendingBytes == 0)+ let response = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any])+ #expect(response["id"] as? String == "outer-encoding-\"\\failure")+ let tool = try #require(response["result"] as? [String: Any])+ let metadata = try #require((tool["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])+ #expect(metadata["category"] as? String == "serialization_failure")+ #expect(metadata["snapshotId"] == nil && metadata["asOf"] == nil)+ #expect(try MCPTestHelpers.decodeHTTPToolResult(response)["error"] as? [String: String]+ == ["code": "QUERY_FAILED", "message": "QUERY_FAILED"])+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadServerCoordinatorLifecycleTests.swift b/Transit/TransitTests/MCPReadServerCoordinatorLifecycleTests.swiftnew file mode 100644index 0000000..76a5724--- /dev/null+++ b/Transit/TransitTests/MCPReadServerCoordinatorLifecycleTests.swift@@ -0,0 +1,96 @@+#if os(macOS)+import Foundation+import NIOConcurrencyHelpers+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPReadServerCoordinatorLifecycleTests {+ @Test func actualListenerRestartKeepsCoordinatorAndOldPhysicalWorkers() async throws {+ let env = try MCPTestHelpers.makeEnv()+ let coordinator = env.handler.readCoordinator+ let server = MCPServer(toolHandler: env.handler, readCoordinator: coordinator)+ let listener = MCPServerLifecycleTests()+ let port = try listener.availableLoopbackPort()+ await server.start(port: port)+ guard await listener.waitUntilListening(port: port) else {+ await server.stop()+ Issue.record("Initial actual listener did not start")+ return+ }+ let oldGeneration = server.listenerGeneration+ let gate = LifecycleReadGate()+ let receipts = NIOLockedValueBox<[UUID]>([])+ let calls = startWorkers(coordinator, gate: gate, receipts: receipts)+ let startDeadline = ContinuousClock.now + .seconds(1)+ while await gate.count < 8 && .now < startDeadline { await Task.yield() }+ #expect(await gate.count == 8)+ await server.restart(port: port)+ #expect(await listener.waitUntilListening(port: port))+ for call in calls { #expect(await call.value == Data("timeout".utf8)) }+ #expect(server.readCoordinator === coordinator && env.handler.readCoordinator === coordinator)+ #expect(coordinator.unfinishedCount == 8 && receipts.withLockedValue { $0 }.isEmpty)+ server.listenerDidExit(generation: oldGeneration, failure: "old listener completion")+ #expect(server.isRunning && env.handler.taskQueryAdmissionOpen && server.startError == nil)+ let ninth = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { _ in+ Issue.record("Replacement listener forgot old physical permits")+ return Self.result("unexpected")+ }+ #expect(ninth == Data("busy".utf8))+ await gate.release()+ let drainDeadline = ContinuousClock.now + .seconds(1)+ while (coordinator.unfinishedCount != 0 || receipts.withLockedValue({ $0.count }) != 8)+ && .now < drainDeadline { await Task.yield() }+ #expect(coordinator.unfinishedCount == 0)+ #expect(Set(receipts.withLockedValue { $0 }).count == 8)+ #expect(receipts.withLockedValue { $0.count } == 8)+ let current = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { _ in+ Self.result("current")+ }+ #expect(current == Data("current".utf8))+ await server.stop()+ let finalDeadline = ContinuousClock.now + .seconds(1)+ while coordinator.unfinishedCount != 0 && .now < finalDeadline { await Task.yield() }+ #expect(coordinator.unfinishedCount == 0)+ }++ private func startWorkers(_ coordinator: MCPReadCoordinator, gate: LifecycleReadGate,+ receipts: NIOLockedValueBox<[UUID]>) -> [Task<Data, Never>] {+ (0..<8).map { _ in+ let id = UUID()+ let admission = MCPReadAdmission(operationID: id, physicalCompletion: {+ receipts.withLockedValue { $0.append(id) }+ })+ return Task {+ await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8),+ admission: admission) { _ in+ await gate.wait()+ return Self.result("late")+ }+ }+ }+ }++ nonisolated private static func result(_ value: String) -> PreparedReadResult {+ PreparedReadResult(encodedResponse: Data(value.utf8), publications: [],+ publicationErrors: .init(busy: Data(), expired: Data(), capacity: Data()))+ }+}++private actor LifecycleReadGate {+ private(set) var count = 0+ private var open = false+ private var waiters: [CheckedContinuation<Void, Never>] = []+ func wait() async {+ count += 1+ if open { return }+ await withCheckedContinuation { waiters.append($0) }+ }+ func release() {+ open = true+ let pending = waiters+ waiters.removeAll()+ for continuation in pending { continuation.resume() }+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadServerPreservationTests.swift b/Transit/TransitTests/MCPReadServerPreservationTests.swiftnew file mode 100644index 0000000..69bf304--- /dev/null+++ b/Transit/TransitTests/MCPReadServerPreservationTests.swift@@ -0,0 +1,116 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// Actual existing router/lifecycle APIs. No substitute for process-lifetime injection tests.+@MainActor @Suite(.serialized)+struct MCPReadServerPreservationTests {+ @Test(arguments: ["query_tasks", "query_milestones", "get_projects"])+ func stoppedServerRejectsEveryCoveredReadWithoutCaptureIdentity(tool: String) async throws {+ let env = try MCPTestHelpers.makeEnv()+ let server = MCPServer(toolHandler: env.handler)+ await server.stop()+ let response = try await call(env.handler, tool: tool, args: [:])+ let result = try #require(response["result"] as? [String: Any])+ let meta = try #require((result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])+ #expect(meta["category"] as? String == "READ_BUSY")+ #expect(meta["snapshotId"] == nil && meta["asOf"] == nil)+ #expect(result["isError"] as? Bool == true)+ }++ @Test func staleListenerExitDoesNotCloseCurrentAdmission() async throws {+ let env = try MCPTestHelpers.makeEnv()+ let server = MCPServer(toolHandler: env.handler)+ #expect(env.handler.taskQueryAdmissionOpen)+ server.listenerDidExit(generation: -1, failure: "stale failure")+ #expect(env.handler.taskQueryAdmissionOpen)+ #expect(server.startError == nil)+ let response = try await call(env.handler, tool: "get_projects", args: [:])+ #expect(response["error"] == nil)+ }++ @Test func protectedWriteReplayKeepsOriginalProjectionAndReceiptOutsideReadMetadata() async throws {+ let env = try MCPTestHelpers.makeEnv()+ let args: [String: Any] = ["name": "Original", "colorHex": "#112233", "idempotencyKey": "read-preservation"]+ let first = try await call(env.handler, tool: "create_project", args: args)+ let saved = try #require(try env.context.fetch(FetchDescriptor<Project>()).first)+ saved.name = "Later UI name"+ try env.context.save()+ let replay = try await call(env.handler, tool: "create_project", args: args)+ let firstTool = try #require(first["result"] as? [String: Any])+ let replayTool = try #require(replay["result"] as? [String: Any])+ #expect(firstTool["_meta"] == nil && replayTool["_meta"] == nil)+ let firstText = try #require((firstTool["content"] as? [[String: Any]])?.first?["text"] as? String)+ #expect((replayTool["content"] as? [[String: Any]])?.first?["text"] as? String == firstText)+ let logical = try MCPTestHelpers.decodeHTTPToolResult(first)+ #expect(logical["outcome"] as? String == "committed")+ #expect(logical["replayExpiresAt"] is String)+ #expect(try env.context.fetch(FetchDescriptor<MCPWriteReceipt>()).count == 1)+ #expect(try env.context.fetch(FetchDescriptor<Project>()).count == 1)+ }++ @Test func maintenanceScanRemainsOutsideFreshnessAndStoppedReadAdmission() async throws {+ let env = try MCPTestHelpers.makeEnv()+ env.mcpSettings.maintenanceToolsEnabled = true+ let server = MCPServer(toolHandler: env.handler)+ await server.stop()+ let response = try await call(env.handler, tool: "scan_duplicate_display_ids", args: [:])+ let tool = try #require(response["result"] as? [String: Any])+ #expect(tool["_meta"] == nil)+ #expect(tool["isError"] == nil)+ _ = try MCPTestHelpers.decodeHTTPToolResult(response)+ }++ @Test func staleWriteRevisionPreservesInterveningTaskAndCommentState() async throws {+ let env = try MCPTestHelpers.makeEnv()+ let project = MCPTestHelpers.makeProject(in: env.context)+ let task = TransitTask(name: "Original", type: .feature, project: project, displayID: .permanent(63))+ env.context.insert(task)+ try env.context.save()+ let revision = try MCPRecordSnapshot.task(task, in: env.context).revision+ task.name = "Intervening edit"+ try env.context.save()+ let args: [String: Any] = ["taskId": task.id.uuidString, "status": "done", "comment": "not committed",+ "authorName": "A", "expectedRevision": revision, "idempotencyKey": "preserve-stale-revision"]+ let response = try await call(env.handler, tool: "update_task_status", args: args)+ let logical = try MCPTestHelpers.decodeHTTPToolResult(response)+ #expect((logical["error"] as? [String: Any])?["code"] as? String == "REVISION_CONFLICT")+ #expect((response["result"] as? [String: Any])?["_meta"] == nil)+ #expect(task.name == "Intervening edit" && task.status == .idea)+ #expect(try env.context.fetch(FetchDescriptor<Transit.Comment>()).isEmpty)+ #expect(try MCPRecordSnapshot.task(task, in: env.context).revision != revision)+ }++ @Test func fallbackStorageKeepsMaintenanceReadAndRejectsMutations() async throws {+ let env = try MCPTestHelpers.makeEnv(persistence: PersistenceAvailability(isFallbackStorageActive: true))+ env.mcpSettings.maintenanceToolsEnabled = true+ let scan = try await call(env.handler, tool: "scan_duplicate_display_ids", args: [:])+ #expect((scan["result"] as? [String: Any])?["isError"] == nil)+ let write = try await call(env.handler, tool: "create_project", args: [+ "name": "Rejected", "colorHex": "#112233", "idempotencyKey": "fallback-preservation"+ ])+ let logical = try MCPTestHelpers.decodeHTTPToolResult(write)+ #expect((logical["error"] as? [String: Any])?["code"] as? String == "PERSISTENCE_UNAVAILABLE")+ let maintenance = try await call(env.handler, tool: "reassign_duplicate_display_ids", args: [:])+ let tool = try #require(maintenance["result"] as? [String: Any])+ #expect(tool["isError"] as? Bool == true && tool["_meta"] == nil)+ #expect(try env.context.fetch(FetchDescriptor<Project>()).isEmpty)+ #expect(try env.context.fetch(FetchDescriptor<MCPWriteReceipt>()).isEmpty)+ }++ private func call(_ handler: MCPToolHandler, tool: String, args: [String: Any]) async throws -> [String: Any] {+ let envelope: [String: Any] = ["jsonrpc": "2.0", "id": "preservation-id", "method": "tools/call",+ "params": ["name": tool, "arguments": args]]+ let data = try JSONSerialization.data(withJSONObject: envelope)+ let response = try await MCPTestHelpers.respond(handler: handler,+ contentType: "application/json", accept: "application/json", protocolVersion: "2026-07-28",+ body: try #require(String(data: data, encoding: .utf8)), loggerLabel: "read-server-preservation")+ let object = try #require(response.json as? [String: Any])+ #expect(object["id"] as? String == "preservation-id")+ #expect(object["jsonrpc"] as? String == "2.0")+ return object+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReadServiceTests.swift b/Transit/TransitTests/MCPReadServiceTests.swiftnew file mode 100644index 0000000..5e14205--- /dev/null+++ b/Transit/TransitTests/MCPReadServiceTests.swift@@ -0,0 +1,355 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPReadServiceTests {+ @MainActor private final class Source: MCPReadCaptureSource {+ let builder: MCPReadCaptureBuilder+ var calls = 0+ var failure: MCPReadCaptureError?+ init(_ fixture: TestModelContainer, builder: MCPReadCaptureBuilder? = nil) {+ self.builder = builder ?? MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture)+ }+ func capture(_ request: ReadCaptureRequest) throws -> CapturedReadView {+ calls += 1+ if let failure { throw failure }+ return try builder.capture(request)+ }+ }++ @Test func frozenCursorMetadataPolicyAndPayloadSurviveLocalEdit() async throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ fixture.context.insert(project)+ for number in 1...2 {+ fixture.context.insert(TransitTask(name: "Task \(number)", type: .feature,+ project: project, displayID: .permanent(number)))+ }+ try fixture.context.save()+ let source = Source(fixture)+ let store = MCPTaskQuerySnapshotStore()+ let service = MCPReadService(source: source, monitor: MCPImportEvidenceMonitor(+ syncActive: true, storeIdentifier: "fixture"), snapshots: store)+ let first = try await execute(service, arguments: ["detailLevel": "summary", "includeComments": false,+ "limit": 1, "readPolicy": "cached"])+ let payload = try object(try #require((first["content"] as? [[String: Any]])?.first?["text"] as? String))+ let cursor = try #require(payload["nextCursor"] as? String)+ let page = try store.retainedPage(for: cursor)+ let originalBytes = try #require(page.metadataBytes)+ project.name = "After"+ try fixture.context.save()+ source.failure = .storageFailure+ for policy in [nil, "cached"] as [String?] {+ var args: [String: Any] = ["cursor": cursor]+ args["readPolicy"] = policy+ let replay = try await execute(service, arguments: args)+ #expect(try metadata(replay) == metadata(first))+ #expect(try store.retainedPage(for: cursor).metadataBytes == originalBytes)+ }+ let conflict = try await execute(service, arguments: ["cursor": cursor, "readPolicy": "refresh_if_needed"])+ #expect(try errorCode(conflict) == "INVALID_INPUT")+ let invalid = try await execute(service, arguments: ["cursor": UUID().uuidString, "readPolicy": true])+ #expect(try errorCode(invalid) == "INVALID_INPUT")+ #expect(source.calls == 1)+ let meta = try object(try #require(String(data: originalBytes, encoding: .utf8)))+ let freshness = try #require(meta["freshness"] as? [String: Any])+ #expect(freshness["assessment"] as? String == "unknown")+ #expect(freshness["lastImportedAt"] is NSNull)+ #expect(meta["asOf"] as? String == freshness["assessedAt"] as? String)+ }++ @Test(arguments: [MCPReadCaptureError.storageFailure, .serializationFailure, .incoherentCapture])+ func requiredCaptureFailureNeverLooksEmpty(failure: MCPReadCaptureError) async throws {+ let fixture = try TestModelContainer()+ let source = Source(fixture)+ source.failure = failure+ let service = MCPReadService(source: source, monitor: MCPImportEvidenceMonitor(+ syncActive: false, storeIdentifier: nil), snapshots: MCPTaskQuerySnapshotStore())+ let result = try await execute(service, arguments: ["detailLevel": "summary", "includeComments": false,+ "limit": 100])+ #expect(result["isError"] as? Bool == true)+ #expect(try errorCode(result) == "QUERY_FAILED")+ let meta = try metadataObject(result)+ #expect(meta["snapshotId"] == nil && meta["asOf"] == nil)+ let expected = failure == .storageFailure ? "storage_failure"+ : failure == .serializationFailure ? "serialization_failure" : "incoherent_capture"+ #expect(meta["category"] as? String == expected)+ }++ @Test func catalogCountsAndMilestoneDetailsUseSavedValuesWithoutComments() async throws {+ let fixture = try TestModelContainer()+ fixture.context.autosaveEnabled = false+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ let task = TransitTask(name: "Saved", type: .feature, project: project, displayID: .permanent(63))+ fixture.context.insert(project)+ fixture.context.insert(task)+ try fixture.context.save()+ task.name = "Unsaved"+ let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,+ fetchComments: { _ in throw CocoaError(.fileReadUnknown) })+ let view = try builder.capture(ReadCaptureRequest(projectSelectors: nil, selection: .projectCatalog,+ completeness: .selectedRead, includeComments: false))+ let projects = try MCPReadProjection.projects(view)+ #expect(projects[0]["activeTaskCount"] as? Int == 1)+ #expect(view.tasks[0].name == "Saved")+ #expect(view.comments.isEmpty)+ }++ @Test(arguments: ["query_tasks", "query_milestones"])+ func projectThenScalarValidationPrecedesDependentFetchFailure(tool: String) async throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ fixture.context.insert(project)+ try fixture.context.save()+ var fetched = false+ let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,+ fetchTasks: { _ in fetched = true; throw CocoaError(.fileReadUnknown) },+ fetchMilestones: { _ in fetched = true; throw CocoaError(.fileReadUnknown) })+ let service = MCPReadService(source: Source(fixture, builder: builder),+ monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil),+ snapshots: MCPTaskQuerySnapshotStore())+ var args: [String: Any] = ["project": "Missing", "status": 123]+ if tool == "query_tasks" {+ args.merge(["detailLevel": "summary", "includeComments": false, "limit": 100]) { _, new in new }+ }+ let missing = try await execute(service, arguments: args, tool: tool)+ let missingText = try #require((missing["content"] as? [[String: Any]])?.first?["text"] as? String)+ #expect(missingText.contains("No project named"))+ #expect(!fetched)+ args["project"] = "P"+ let malformed = try await execute(service, arguments: args, tool: tool)+ let malformedText = try #require((malformed["content"] as? [[String: Any]])?.first?["text"] as? String)+ #expect(malformedText.contains("Invalid status"))+ #expect(!fetched)+ args["status"] = tool == "query_tasks" ? "idea" : "open"+ let failed = try await execute(service, arguments: args, tool: tool)+ #expect(try metadataObject(failed)["category"] as? String == "storage_failure")+ #expect(fetched)+ }++ @Test(arguments: ["query_tasks", "query_milestones"])+ func milestoneResolutionPrecedesDependentTaskFetch(tool: String) async throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ let first = Milestone(name: "M", project: project, displayID: .permanent(9))+ let duplicate = Milestone(name: "M", project: project, displayID: .permanent(9))+ let task = TransitTask(name: "Task", type: .feature, project: project, displayID: .permanent(63))+ task.milestone = first+ fixture.context.insert(project)+ fixture.context.insert(first)+ fixture.context.insert(duplicate)+ fixture.context.insert(task)+ try fixture.context.save()+ var fetched = false+ let source = Source(fixture, builder: MCPReadCaptureBuilder(container: fixture.container,+ fence: .actorOnlyTestFixture, fetchTasks: { _ in fetched = true; throw CocoaError(.fileReadUnknown) }))+ let service = MCPReadService(source: source, monitor: MCPImportEvidenceMonitor(+ syncActive: false, storeIdentifier: nil), snapshots: MCPTaskQuerySnapshotStore())+ var args: [String: Any] = ["project": "P"]+ if tool == "query_tasks" {+ args.merge(["detailLevel": "summary", "includeComments": false, "limit": 100]) { _, new in new }+ }+ let key = tool == "query_tasks" ? "milestoneDisplayId" : "displayId"+ args[key] = 9+ let ambiguous = try await execute(service, arguments: args, tool: tool)+ let ambiguousText = try #require((ambiguous["content"] as? [[String: Any]])?.first?["text"] as? String)+ #expect(ambiguousText.contains("Duplicate milestone identifier"))+ #expect(!fetched)+ args[key] = 77+ let absent = try await execute(service, arguments: args, tool: tool)+ #expect(absent["isError"] == nil)+ #expect(!fetched)+ fixture.context.delete(duplicate)+ try fixture.context.save()+ args[key] = 9+ if tool == "query_milestones" {+ args["status"] = "done"+ let filtered = try await execute(service, arguments: args, tool: tool)+ #expect(filtered["isError"] == nil && !fetched)+ args.removeValue(forKey: "status")+ }+ let failed = try await execute(service, arguments: args, tool: tool)+ #expect(try metadataObject(failed)["category"] as? String == "storage_failure")+ #expect(fetched)+ }++ @Test(arguments: [true, false])+ func emptyFullTaskReadDoesNotRequireUnrelatedComments(missingMilestone: Bool) async throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ fixture.context.insert(project)+ if missingMilestone {+ fixture.context.insert(TransitTask(name: "Unrelated", type: .feature,+ project: project, displayID: .permanent(63)))+ }+ try fixture.context.save()+ var commentsFetched = false+ let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,+ fetchComments: { _ in commentsFetched = true; throw CocoaError(.fileReadUnknown) })+ let service = MCPReadService(source: Source(fixture, builder: builder), monitor: MCPImportEvidenceMonitor(+ syncActive: false, storeIdentifier: nil), snapshots: MCPTaskQuerySnapshotStore())+ var arguments: [String: Any] = ["project": "P", "detailLevel": "full", "includeComments": true, "limit": 100]+ if missingMilestone { arguments["milestoneDisplayId"] = 77 }+ let result = try await execute(service, arguments: arguments)+ #expect(result["isError"] == nil)+ #expect(!commentsFetched)+ let text = try #require((result["content"] as? [[String: Any]])?.first?["text"] as? String)+ let payload = try object(text)+ #expect((payload["results"] as? [[String: Any]])?.isEmpty == true)+ #expect(try metadataObject(result)["snapshotId"] != nil)+ }++ @Test func validEmptyInactiveReadHasCaptureMetadata() async throws {+ let fixture = try TestModelContainer()+ let service = MCPReadService(source: Source(fixture), monitor: MCPImportEvidenceMonitor(+ syncActive: false, storeIdentifier: nil), snapshots: MCPTaskQuerySnapshotStore())+ let result = try await execute(service, arguments: ["detailLevel": "summary", "includeComments": false,+ "limit": 100])+ #expect(result["isError"] == nil)+ let meta = try metadataObject(result)+ #expect(meta["snapshotId"] is String && meta["asOf"] is String)+ #expect((meta["freshness"] as? [String: Any])?["assessment"] as? String == "not_applicable")+ #expect((meta["read"] as? [String: Any])?["refreshOutcome"] as? String == "not_requested")+ }++ private func execute(_ service: MCPReadService, arguments: [String: Any],+ tool: String = "query_tasks") async throws -> [String: Any] {+ let env = try MCPTestHelpers.makeEnv()+ let handler = MCPToolHandler(taskService: env.taskService, projectService: env.projectService,+ commentService: env.commentService, milestoneService: env.milestoneService,+ maintenanceService: env.maintenanceService, settings: env.mcpSettings, readService: service)+ let coordinator = MCPReadCoordinator(domain: service.snapshots.domain)+ let fields = arguments.mapValues(AnyCodable.init)+ let bytes = await coordinator.execute(timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { operation in+ do {+ let prepared = try await handler.prepareCoveredRead(+ MCPReadToolRequest(tool: tool, arguments: fields), operation: operation)+ let rejection = Data("rejected".utf8)+ return PreparedReadResult(encodedResponse: prepared.encodedToolResult,+ publications: prepared.publications,+ publicationErrors: PreencodedPublicationErrors(busy: rejection, expired: rejection,+ capacity: rejection))+ } catch {+ return PreparedReadResult(encodedResponse: Data("unexpected".utf8), publications: [],+ publicationErrors: PreencodedPublicationErrors(busy: Data(), expired: Data(), capacity: Data()))+ }+ }+ return try object(try #require(String(data: bytes, encoding: .utf8)))+ }++ private func object(_ text: String) throws -> [String: Any] {+ try #require(JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])+ }++ private func metadataObject(_ result: [String: Any]) throws -> [String: Any] {+ try #require((result["_meta"] as? [String: Any])?["me.nore.ig.transit/read"] as? [String: Any])+ }++ private func metadata(_ result: [String: Any]) throws -> Data {+ try JSONSerialization.data(withJSONObject: metadataObject(result), options: [.sortedKeys])+ }++ private func errorCode(_ result: [String: Any]) throws -> String {+ let text = try #require((result["content"] as? [[String: Any]])?.first?["text"] as? String)+ return try #require((try object(text)["error"] as? [String: Any])?["code"] as? String)+ }+}+extension MCPReadServiceTests {+ @Test(arguments: [false, true])+ func emptyPortfolioStillRequiresOrphanCommentEvidence(scoped: Bool) throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ fixture.context.insert(project)+ try fixture.context.save()+ var commentsFetched = false+ let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,+ fetchComments: { _ in commentsFetched = true; throw CocoaError(.fileReadUnknown) })+ let request = ReadCaptureRequest(projectSelectors: scoped ? [.id(project.id)] : nil,+ selection: .portfolio, completeness: .completePortfolio, includeComments: false)+ #expect(throws: MCPReadCaptureError.storageFailure) { try builder.capture(request) }+ #expect(commentsFetched)+ }++}+extension MCPReadServiceTests {+ @Test(arguments: ["filtered", "batch", "selected"])+ func taskCanonicalSerializationFollowsTypedSelection(mode: String) async throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ let good = TransitTask(name: "Good", type: .feature, project: project, displayID: .permanent(1))+ good.statusRawValue = "done"+ let bad = TransitTask(name: "Bad", type: .feature, project: project, displayID: .permanent(2))+ fixture.context.insert(project)+ fixture.context.insert(good)+ fixture.context.insert(bad)+ try fixture.context.save()+ // Inject corrupt read evidence into the fresh capture context, never into persisted data.+ let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,+ fetchTasks: { context in+ 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 [] } }+ return values+ })+ let service = MCPReadService(source: Source(fixture, builder: builder), monitor: MCPImportEvidenceMonitor(+ syncActive: false, storeIdentifier: nil), snapshots: MCPTaskQuerySnapshotStore())+ var args: [String: Any] = ["detailLevel": "full", "includeComments": false, "limit": 100]+ if mode == "filtered" { args["status"] = "done" }+ if mode == "batch" { args["displayIds"] = [1] }+ if mode == "selected" { args["displayId"] = 2 }+ let result = try await execute(service, arguments: args)+ if mode == "selected" {+ #expect(try errorCode(result) == "QUERY_FAILED")+ #expect(try metadataObject(result)["category"] as? String == "serialization_failure")+ } else {+ #expect(result["isError"] == nil)+ let text = try #require((result["content"] as? [[String: Any]])?.first?["text"] as? String)+ #expect((try object(text)["results"] as? [[String: Any]])?.count == 1)+ }+ }++ @Test(arguments: ["query_tasks", "query_milestones", "get_projects", "selected_milestone"])+ func unrelatedMilestoneCanonicalDatesDoNotPoisonSelectedOutput(tool: String) async throws {+ let fixture = try TestModelContainer()+ let project = Project(name: "P", description: "", gitRepo: nil, colorHex: "blue")+ let good = Milestone(name: "Good", project: project, displayID: .permanent(1))+ let bad = Milestone(name: "Bad", project: project, displayID: .permanent(2))+ bad.statusRawValue = "done"+ let task = TransitTask(name: "Task", type: .feature, project: project, displayID: .permanent(63))+ task.milestone = bad+ fixture.context.insert(project)+ fixture.context.insert(good)+ fixture.context.insert(bad)+ fixture.context.insert(task)+ try fixture.context.save()+ let builder = MCPReadCaptureBuilder(container: fixture.container, fence: .actorOnlyTestFixture,+ fetchMilestones: { context in+ let values = try context.fetch(FetchDescriptor<Milestone>())+ let corrupt = try #require(values.first { $0.permanentDisplayId == 2 })+ corrupt.creationDate = Date(timeIntervalSinceReferenceDate: .nan)+ #expect(throws: (any Error).self) { try MCPRecordSnapshot.milestone(corrupt) }+ return values+ })+ let service = MCPReadService(source: Source(fixture, builder: builder), monitor: MCPImportEvidenceMonitor(+ syncActive: false, storeIdentifier: nil), snapshots: MCPTaskQuerySnapshotStore())+ var args: [String: Any] = [:]+ if tool == "query_milestones" { args["status"] = "open" }+ if tool == "query_tasks" {+ args = ["detailLevel": "full", "includeComments": false, "limit": 100]+ }+ if tool == "selected_milestone" { args["status"] = "done" }+ let actualTool = tool == "selected_milestone" ? "query_milestones" : tool+ let result = try await execute(service, arguments: args, tool: actualTool)+ if tool == "selected_milestone" {+ #expect(result["isError"] as? Bool == true)+ #expect(try metadataObject(result)["category"] as? String == "serialization_failure")+ } else {+ #expect(result["isError"] == nil)+ }+ }+}+#endif
diff --git a/Transit/TransitTests/MCPRequestDecodeErrorClassificationTests.swift b/Transit/TransitTests/MCPRequestDecodeErrorClassificationTests.swiftindex 5c099cc..a4359ad 100644--- a/Transit/TransitTests/MCPRequestDecodeErrorClassificationTests.swift+++ b/Transit/TransitTests/MCPRequestDecodeErrorClassificationTests.swift@@ -6,6 +6,7 @@ import Testing /// Regression tests for T-1128: the MCP route handler must distinguish /// JSON-RPC parse errors (-32700) from invalid-request shape errors (-32600). ///+/// Modern request validation retains the original parse-versus-shape regression. /// Per JSON-RPC 2.0 §5.1: /// - `-32700 Parse error` is for input that is not well-formed JSON. /// - `-32600 Invalid Request` is for valid JSON that is not a well-formed@@ -23,22 +24,22 @@ struct MCPRequestDecodeErrorClassificationTests { @Test func malformedJSONReturnsParseError() throws { let data = Data("{not json".utf8) let response = try unwrapErrorResponse(for: data)- #expect(response.code == JSONRPCErrorCode.parseError)- #expect(response.message == "Parse error")+ #expect(response.rpcCode == JSONRPCErrorCode.parseError)+ #expect(response.httpStatus == 400) } @Test func emptyBodyReturnsParseError() throws { let data = Data() let response = try unwrapErrorResponse(for: data)- #expect(response.code == JSONRPCErrorCode.parseError)- #expect(response.message == "Parse error")+ #expect(response.rpcCode == JSONRPCErrorCode.parseError)+ #expect(response.httpStatus == 400) } @Test func unterminatedStringReturnsParseError() throws { // Lexically broken JSON: a quoted string that never closes. let data = Data(#"{"jsonrpc":"2.0,"method":"ping"}"#.utf8) let response = try unwrapErrorResponse(for: data)- #expect(response.code == JSONRPCErrorCode.parseError)+ #expect(response.rpcCode == JSONRPCErrorCode.parseError) } // MARK: - Invalid request errors (-32600)@@ -47,92 +48,79 @@ struct MCPRequestDecodeErrorClassificationTests { // Valid JSON, but missing the required `method` member. let data = Data(#"{"jsonrpc":"2.0","id":1}"#.utf8) let response = try unwrapErrorResponse(for: data)- #expect(response.code == JSONRPCErrorCode.invalidRequest)- #expect(response.message == "Invalid Request")+ #expect(response.rpcCode == JSONRPCErrorCode.invalidRequest)+ #expect(response.httpStatus == 400) } @Test func nonStringJSONRPCMemberReturnsInvalidRequest() throws { // `jsonrpc` must be a string per the spec; a number is structurally wrong. let data = Data(#"{"jsonrpc":2.0,"id":1,"method":"ping"}"#.utf8) let response = try unwrapErrorResponse(for: data)- #expect(response.code == JSONRPCErrorCode.invalidRequest)+ #expect(response.rpcCode == JSONRPCErrorCode.invalidRequest) } @Test func booleanIdReturnsInvalidRequest() throws { // `id` must be string, number, or null. Boolean is not allowed. let data = Data(#"{"jsonrpc":"2.0","id":true,"method":"ping"}"#.utf8) let response = try unwrapErrorResponse(for: data)- #expect(response.code == JSONRPCErrorCode.invalidRequest)+ #expect(response.rpcCode == JSONRPCErrorCode.invalidRequest) } @Test func objectIdReturnsInvalidRequest() throws { // `id` must be string, number, or null. Object is not allowed. let data = Data(#"{"jsonrpc":"2.0","id":{"x":1},"method":"ping"}"#.utf8) let response = try unwrapErrorResponse(for: data)- #expect(response.code == JSONRPCErrorCode.invalidRequest)+ #expect(response.rpcCode == JSONRPCErrorCode.invalidRequest) } @Test func scalarRootReturnsInvalidRequest() throws { // Valid JSON, but the root is a scalar — not a Request object. let data = Data("42".utf8) let response = try unwrapErrorResponse(for: data)- #expect(response.code == JSONRPCErrorCode.invalidRequest)+ #expect(response.rpcCode == JSONRPCErrorCode.invalidRequest) } - @Test func errorResponseIdIsNull() throws {- // For both error categories, `id` in the response must be null when it- // cannot be reliably extracted from the request.- let data = Data(#"{"jsonrpc":"2.0","id":true,"method":"ping"}"#.utf8)- let response = MCPServer.decodeIncomingRequest(data)- switch response {- case .success:- Issue.record("Expected error response for invalid id type")- case .batch:- Issue.record("Expected single-request decode failure, not a batch")- case .failure(let errorResponse):- let encoded = try JSONEncoder().encode(errorResponse)- let parsed = try JSONSerialization.jsonObject(with: encoded) as? [String: Any]- let dict = try #require(parsed)- #expect(dict.keys.contains("id"))- #expect(dict["id"] is NSNull)+ @Test func invalidIDRemainsUnavailableForModernErrorCorrelation() throws {+ for token in ["true", "null", "{}", "[]", "1.5"] {+ let data = Data("{\"jsonrpc\":\"2.0\",\"id\":\(token),\"method\":\"server/discover\"}".utf8)+ let rejection = try unwrapErrorResponse(for: data)+ #expect(rejection.rpcCode == JSONRPCErrorCode.invalidRequest)+ #expect(rejection.id == nil) } } // MARK: - Happy path (sanity) @Test func wellFormedRequestDecodes() throws {- let data = Data(#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#.utf8)- let result = MCPServer.decodeIncomingRequest(data)- switch result {- case .success(let req):- #expect(req.method == "ping")- #expect(req.jsonrpc == "2.0")- #expect(!req.isNotification)- case .batch:- Issue.record("Single request must not decode as a batch")- case .failure:- Issue.record("Well-formed request must decode successfully")- }+ let body = Data("""+ {"jsonrpc":"2.0","id":1,"method":"server/discover",+ "params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28",+ "io.modelcontextprotocol/clientCapabilities":{}}}}+ """.utf8)+ let result = try MCPModernValidator.validate(input(body), availability: MCPModernAvailability(tools: []))+ if case .discover = result.method {} else { Issue.record("Expected discover classification") }+ if case .integer(1) = result.id {} else { Issue.record("Expected original ID") } } - // MARK: - Helpers+ private func input(_ body: Data) -> MCPModernRequestInput {+ MCPModernRequestInput(httpMethod: "POST", headers: [+ .init(name: "Content-Type", value: "application/json"),+ .init(name: "Accept", value: "application/json, text/event-stream"),+ .init(name: "MCP-Protocol-Version", value: "2026-07-28"),+ .init(name: "Mcp-Method", value: "server/discover")+ ], body: body)+ } - private func unwrapErrorResponse(for data: Data) throws -> JSONRPCError {- let result = MCPServer.decodeIncomingRequest(data)- switch result {- case .success:- Issue.record("Expected decode failure but request decoded successfully")+ private func unwrapErrorResponse(for data: Data) throws -> MCPModernRejection {+ do {+ _ = try MCPModernValidator.validate(input(data), availability: MCPModernAvailability(tools: []))+ Issue.record("Expected modern rejection") throw DecodeUnwrapError.unexpectedSuccess- case .batch:- Issue.record("Expected single-request decode failure, not a batch")- throw DecodeUnwrapError.unexpectedSuccess- case .failure(let response):- let error = try #require(response.error, "Error response must carry a JSONRPCError")- return error+ } catch let rejection as MCPModernRejection {+ return rejection } } private enum DecodeUnwrapError: Error { case unexpectedSuccess } }- #endif
diff --git a/Transit/TransitTests/MCPResultEncoderFallbackTests.swift b/Transit/TransitTests/MCPResultEncoderFallbackTests.swiftnew file mode 100644index 0000000..260911e--- /dev/null+++ b/Transit/TransitTests/MCPResultEncoderFallbackTests.swift@@ -0,0 +1,200 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++/// This synthetic driver proves readiness/selection of actual encoder bytes.+/// It does not prove production dispatch, receipt atomicity or transport delivery;+/// real provider/response selection integration is task14's separate obligation.+@MainActor+struct MCPResultEncoderFallbackTests {+ private typealias Fixture = MCPResultEncoderFixtures++ private func selectAfterSyntheticEffect(+ prepare: () throws -> Data, effect: () -> Void, finalEncoding: () throws -> Data+ ) throws -> Data {+ let completeFallback = try prepare()+ effect()+ do { return try finalEncoding() } catch { return completeFallback }+ }++ private func protectedContext() -> MCPMutationRecoveryContext {+ .protectedWrite(MCPProtectedRecoveryKey(tool: "update_task", idempotencyKey: "original-\"\\\n-key"))+ }++ private func failureSource() throws -> MCPResultSource {+ try Fixture.source("{\"outcome\":\"uncertain\",\"accepted\":null,\"retryAction\":\"reconcile\"}",+ isError: true, evidence: .unestablished)+ }++ @Test func protectedFallbackIsCompleteBeforeEffectsAndSelectedWithoutReencoding() throws {+ let id = JSONRPCId.string("protected-\"\\\n")+ let source = try failureSource()+ let context = Fixture.context(protectedContext())+ let metadata = try MCPResultMetadata.make(document: MCPJSONDocument.parse(+ "{\"com.example/request\":\"original\",\"com.example/number\":-0}"))+ var effects = 0+ var preparationCalls = 0+ var failedEncoderCalls = 0+ var prepared: Data?+ let selected = try selectAfterSyntheticEffect(prepare: {+ preparationCalls += 1+ let bytes = try MCPResultEncoder.prepareMutationFallback(id: id, source: source,+ context: context, metadata: metadata)+ let result = try Fixture.result(bytes, id: id)+ #expect(try Fixture.originalText(result) == source.originalText)+ #expect(Fixture.field("isError", in: result) == .boolean(true))+ #expect(Fixture.field("_meta", in: result) == metadata.document.value)+ #expect(effects == 0)+ prepared = bytes+ return bytes+ }, effect: { effects += 1 }, finalEncoding: {+ failedEncoderCalls += 1+ throw Fixture.FixtureError.injectedEncodingFailure+ })+ #expect(effects == 1)+ #expect(preparationCalls == 1)+ #expect(failedEncoderCalls == 1)+ #expect(selected == prepared)+ let result = try Fixture.result(selected, id: id)+ let presentation = Fixture.field("presentation", in: try Fixture.structured(result))+ let recovery = try #require(Fixture.field("recovery", in: presentation))+ let leaves = Fixture.leaves(recovery)+ #expect(leaves.contains("original-\"\\\n-key"))+ #expect(leaves.contains("update_task"))+ #expect(leaves.contains("reconcile_original_write"))+ #expect(!leaves.contains("new_request_new_key"))+ }++ @Test func typedPreparationCancellationPreventsAllSyntheticEffects() throws {+ let counter = MCPEncoderCheckpointCounter(failAt: 1)+ let source = try failureSource()+ var effects = 0+ var finalCalls = 0+ #expect(throws: Fixture.FixtureError.cancelled) {+ _ = try selectAfterSyntheticEffect(prepare: {+ try MCPResultEncoder.prepareMutationFallback(id: .integer(7), source: source,+ context: Fixture.context(protectedContext()), metadata: nil,+ checkpoint: { try counter.check() })+ }, effect: { effects += 1 }, finalEncoding: {+ finalCalls += 1+ return Data()+ })+ }+ #expect(effects == 0)+ #expect(finalCalls == 0)+ #expect(counter.value() == 1)+ }++ @Test func maintenanceFallbackRequiresReconciliationWithoutInventedKeyOrAcceptance() throws {+ let source = try Fixture.source("{\"error\":{\"code\":\"OUTCOME_UNCERTAIN\"}}", isError: true,+ evidence: .unestablished)+ let context = Fixture.context(.unprotectedMaintenance(tool: "reassign_duplicate_display_ids"))+ let bytes = try MCPResultEncoder.prepareMutationFallback(id: .integer(19), source: source,+ context: context, metadata: nil)+ let result = try Fixture.result(bytes, id: .integer(19))+ #expect(try Fixture.originalText(result) == source.originalText)+ let structured = try Fixture.structured(result)+ let payload = Fixture.field("payload", in: Fixture.field("source", in: structured))+ #expect(payload == source.document?.value)+ #expect(Fixture.field("accepted", in: payload) == nil)+ let presentation = try #require(Fixture.field("presentation", in: structured))+ let leaves = Fixture.leaves(presentation)+ #expect(leaves.contains("reconcile_maintenance"))+ #expect(leaves.contains("reassign_duplicate_display_ids"))+ #expect(!leaves.contains("idempotencyKey"))+ #expect(!leaves.contains("new_request_new_key"))+ }++ @Test func batchFallbackOmitsUnboundedCorrelationOnlyFromFallbackPresentation() throws {+ let giantID = String(repeating: "giant-correlation-🛰️", count: 4_096)+ let normalFixture = MCPJSONFixtureValue.object([+ MCPJSONFixtureMember(name: "items", value: .array([.object([+ MCPJSONFixtureMember(name: "itemId", value: .string(giantID)),+ MCPJSONFixtureMember(name: "originalResult", value: .object([+ MCPJSONFixtureMember(name: "unknown", value: .number("9007199254740993"))+ ]))+ ])]))+ ])+ let normalSource = try Fixture.source(normalFixture.json())+ let normalPresentation = try MCPResultAdapter.present(normalSource, context: Fixture.context())+ let normalResult = try Fixture.result(MCPResultEncoder.encode(source: normalSource,+ presentation: normalPresentation, id: .string("normal"), metadata: nil), id: .string("normal"))+ let payload = try #require(Fixture.field("payload", in: Fixture.field("source",+ in: try Fixture.structured(normalResult))))+ #expect(normalFixture.matches(payload))+ #expect(try Fixture.originalText(normalResult) == normalSource.originalText)++ let taskId = try #require(UUID(uuidString: "E46FCBBA-31BA-4C53-AD13-C3A4E3209819"))+ let item = MCPBatchRecoveryItem(index: 3, itemId: giantID, operation: "update_task",+ originalKey: MCPProtectedRecoveryKey(tool: "update_task", idempotencyKey: "batch-original-key"),+ targetTaskId: taskId)+ // This synthetic provider owns its compact logical failure shape.+ let compactSource = try Fixture.source(+ "{\"summary\":\"serialization_failed\",\"retryAction\":\"reconcile\"}",+ isError: true, evidence: .unestablished)+ let context = Fixture.context(.applicationBatch(items: [item]))+ let bytes = try MCPResultEncoder.prepareMutationFallback(id: .string("batch"), source: compactSource,+ context: context, metadata: nil)+ let result = try Fixture.result(bytes, id: .string("batch"))+ #expect(try Fixture.originalText(result) == compactSource.originalText)+ let structured = try Fixture.structured(result)+ #expect(Fixture.field("payload", in: Fixture.field("source", in: structured)) == compactSource.document?.value)+ let presentation = try #require(Fixture.field("presentation", in: structured))+ #expect(Fixture.field("evidence", in: presentation) == .string("unestablished"))+ let leaves = Fixture.leaves(presentation)+ #expect(leaves.contains("3"))+ #expect(leaves.contains("update_task"))+ #expect(leaves.contains("batch-original-key"))+ #expect(leaves.contains(taskId.uuidString))+ #expect(!leaves.contains(giantID))+ #expect(!leaves.contains("itemId"))+ #expect(bytes.count < 4_096)+ }++ @Test func postEffectDepthFailureSelectsAlreadyEncodedShallowFallback() throws {+ let source = try Fixture.source("{\"summary\":\"serialization_failed\"}", isError: true,+ evidence: .unestablished)+ let mutation = MCPMutationRecoveryContext.applicationBatch(items: [MCPBatchRecoveryItem(+ index: 0, itemId: nil, operation: "update_task",+ originalKey: MCPProtectedRecoveryKey(tool: "update_task", idempotencyKey: "depth-original-key"),+ targetTaskId: nil)])+ let id = JSONRPCId.integer(31)+ var effects = 0+ var preparations = 0+ var finalCalls = 0+ var finalFailure: MCPResultBoundaryError?+ let selected = try selectAfterSyntheticEffect(prepare: {+ preparations += 1+ let bytes = try MCPResultEncoder.prepareMutationFallback(id: id, source: source,+ context: Fixture.context(mutation), metadata: nil)+ _ = try Fixture.result(bytes, id: id)+ #expect(effects == 0)+ return bytes+ }, effect: { effects += 1 }, finalEncoding: {+ finalCalls += 1+ let deep = String(repeating: "[", count: 33) + "0" + String(repeating: "]", count: 33)+ let aggregate: MCPResultSource+ do { aggregate = try Fixture.source(deep) } catch let failure as MCPResultBoundaryError {+ finalFailure = failure+ throw failure+ }+ let presentation = try MCPResultAdapter.present(aggregate, context: Fixture.context())+ return try MCPResultEncoder.encode(source: aggregate, presentation: presentation, id: id, metadata: nil)+ })+ #expect(effects == 1)+ #expect(preparations == 1)+ #expect(finalCalls == 1)+ #expect(finalFailure == .resourceLimit)+ let result = try Fixture.result(selected, id: id)+ let structured = try Fixture.structured(result)+ let retained = Fixture.field("payload", in: Fixture.field("source", in: structured))+ #expect(Fixture.field("summary", in: retained) == .string("serialization_failed"))+ #expect(Fixture.field("accepted", in: retained) != .boolean(false))+ #expect(Fixture.field("outcome", in: retained) != .string("rejected"))+ let presentation = try #require(Fixture.field("presentation", in: structured))+ #expect(Fixture.field("evidence", in: presentation) == .string("unestablished"))+ #expect(Fixture.leaves(presentation).contains("depth-original-key"))+ }+}+#endif
diff --git a/Transit/TransitTests/MCPResultEncoderFixtures.swift b/Transit/TransitTests/MCPResultEncoderFixtures.swiftnew file mode 100644index 0000000..6d711c2--- /dev/null+++ b/Transit/TransitTests/MCPResultEncoderFixtures.swift@@ -0,0 +1,153 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor+enum MCPResultEncoderFixtures {+ static func context(_ mutation: MCPMutationRecoveryContext? = nil) -> MCPResultContext {+ MCPResultContext(tool: "fixture", semanticFailure: nil, mutationRecovery: mutation, entityPositions: [])+ }++ static func source(_ text: String, isError: Bool? = nil, origin: MCPResultOrigin = .generatedJSON,+ evidence: MCPResultEvidence = .established) throws -> MCPResultSource {+ try MCPResultAdapter.source(text: text, isError: isError, origin: origin, evidence: evidence)+ }++ static func field(_ name: String, in value: MCPJSONValue?) -> MCPJSONValue? {+ guard case .object(let members) = value else { return nil }+ return members.first { $0.name.utf8.elementsEqual(name.utf8) }?.value+ }++ static func text(_ value: MCPJSONValue?) -> String? {+ guard case .string(let text) = value else { return nil }+ return text+ }++ static func result(_ bytes: Data, id: JSONRPCId) throws -> MCPJSONValue {+ let root = try MCPJSONDocument.parse(bytes).value+ #expect(field("jsonrpc", in: root) == .string("2.0"))+ switch id {+ case .string(let expected): #expect(field("id", in: root) == .string(expected))+ case .integer(let expected):+ guard case .number(let number) = field("id", in: root) else {+ Issue.record("Missing integer correlation ID")+ throw FixtureError.invalidFixture+ }+ #expect(number.lexeme == String(expected))+ }+ #expect(field("error", in: root) == nil)+ let result = try #require(field("result", in: root))+ #expect(field("resultType", in: result) == .string("complete"))+ return result+ }++ static func originalText(_ result: MCPJSONValue) throws -> String {+ guard case .array(let content) = field("content", in: result) else {+ throw FixtureError.invalidFixture+ }+ #expect(content.count == 1)+ let first = try #require(content.first)+ #expect(field("type", in: first) == .string("text"))+ return try #require(text(field("text", in: first)))+ }++ static func structured(_ result: MCPJSONValue) throws -> MCPJSONValue {+ let value = try #require(field("structuredContent", in: result))+ #expect(try field("contractVersion", in: value) == MCPJSONDocument.parse("1").value)+ return value+ }++ private static func stringEnd(_ bytes: [UInt8], _ start: Int) throws -> Int {+ var offset = start + 1+ while offset < bytes.count {+ if bytes[offset] == 92 { offset += 2; continue }+ if bytes[offset] == 34 { return offset + 1 }+ offset += 1+ }+ throw FixtureError.invalidFixture+ }++ /// Independent envelope-only parser. Never rebuilds or compares original payload numbers.+ static func rawFragment(_ data: Data, path: [String]) throws -> Data {+ try MCPJSONEnvelopeFixtureValidation.validate(data)+ let bytes = Array(data)+ func whitespace(_ offset: inout Int) {+ while offset < bytes.count, [9, 10, 13, 32].contains(bytes[offset]) { offset += 1 }+ }+ func valueEnd(_ start: Int) throws -> Int {+ if bytes[start] == 34 { return try stringEnd(bytes, start) }+ if bytes[start] == 123 || bytes[start] == 91 {+ var offset = start + 1+ while offset < bytes.count {+ whitespace(&offset)+ if bytes[offset] == 125 || bytes[offset] == 93 { return offset + 1 }+ if bytes[offset] == 44 || bytes[offset] == 58 { offset += 1; continue }+ offset = try valueEnd(offset)+ }+ throw FixtureError.invalidFixture+ }+ var offset = start+ while offset < bytes.count, ![9, 10, 13, 32, 44, 125, 93].contains(bytes[offset]) { offset += 1 }+ return offset+ }+ var offset = 0+ whitespace(&offset)+ for component in path {+ guard bytes[offset] == 123 else { throw FixtureError.invalidFixture }+ offset += 1+ var found: Int?+ while offset < bytes.count {+ whitespace(&offset)+ if bytes[offset] == 125 { break }+ if bytes[offset] == 44 { offset += 1; continue }+ guard bytes[offset] == 34 else { throw FixtureError.invalidFixture }+ let end = try stringEnd(bytes, offset)+ let key = try JSONSerialization.jsonObject(with: Data(bytes[offset..<end]),+ options: [.fragmentsAllowed]) as? String+ offset = end+ whitespace(&offset)+ guard bytes[offset] == 58 else { throw FixtureError.invalidFixture }+ offset += 1+ whitespace(&offset)+ if key?.utf8.elementsEqual(component.utf8) == true { found = offset; break }+ offset = try valueEnd(offset)+ }+ guard let found else { throw FixtureError.invalidFixture }+ offset = found+ }+ return Data(bytes[offset..<(try valueEnd(offset))])+ }++ static func leaves(_ value: MCPJSONValue) -> [String] {+ switch value {+ case .object(let members): return members.flatMap { [$0.name] + leaves($0.value) }+ case .array(let values): return values.flatMap(leaves)+ case .string(let text): return [text]+ case .number(let number): return [number.lexeme]+ case .boolean(let flag): return [flag ? "true" : "false"]+ case .null: return ["null"]+ }+ }++ nonisolated enum FixtureError: Error { case invalidFixture, injectedEncodingFailure, cancelled }+}++/// Test-only count is protected because checkpoints execute outside actor isolation.+nonisolated final class MCPEncoderCheckpointCounter: @unchecked Sendable {+ private let lock = NSLock()+ private var count = 0+ let failAt: Int?++ init(failAt: Int? = nil) { self.failAt = failAt }++ func check() throws {+ try lock.withLock {+ count += 1+ if let failAt, count >= failAt { throw MCPResultEncoderFixtures.FixtureError.cancelled }+ }+ }++ func value() -> Int { lock.withLock { count } }+}+#endif
diff --git a/Transit/TransitTests/MCPResultEncoderTests.swift b/Transit/TransitTests/MCPResultEncoderTests.swiftnew file mode 100644index 0000000..769eca4--- /dev/null+++ b/Transit/TransitTests/MCPResultEncoderTests.swift@@ -0,0 +1,192 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor+struct MCPResultEncoderTests {+ private typealias Fixture = MCPResultEncoderFixtures++ @Test func completeResponsesPreserveSourceTextAndOptionalErrorPresence() throws {+ let values = ["null", "true", "1E-9999", "\"東京\\nquote\\\"\"", "[false,null,9007199254740993]",+ " {\"source\":null,\"presentation\":false,\"contractVersion\":99} \n"]+ let errors: [Bool?] = [nil, false, true]+ for value in values {+ for error in errors {+ let source = try Fixture.source(value, isError: error)+ let presentation = try MCPResultAdapter.present(source, context: Fixture.context())+ let bytes = try MCPResultEncoder.encode(source: source, presentation: presentation,+ id: .string("new-\"\\\n🛰️"), metadata: nil)+ let result = try Fixture.result(bytes, id: .string("new-\"\\\n🛰️"))+ #expect(try Fixture.originalText(result) == value)+ #expect(Fixture.field("isError", in: result) == error.map(MCPJSONValue.boolean))+ #expect(Fixture.field("_meta", in: result) == nil)+ let structured = try Fixture.structured(result)+ let retained = Fixture.field("source", in: structured)+ #expect(Fixture.field("kind", in: retained) == .string("json"))+ #expect(Fixture.field("payload", in: retained) == source.document?.value)+ #expect(Fixture.field("evidence", in: Fixture.field("presentation", in: structured)) != nil)+ }+ }+ }++ @Test func plainAndUnreadableSourcesKeepRawEvidenceWithoutInventedPayload() throws {+ for origin: MCPResultOrigin in [.plainText, .retainedJSON] {+ let raw = "unreadable \"\\\n\u{0000} 東京"+ let source = try Fixture.source(raw, isError: false, origin: origin)+ let presentation = try MCPResultAdapter.present(source, context: Fixture.context())+ let result = try Fixture.result(MCPResultEncoder.encode(source: source, presentation: presentation,+ id: .integer(Int.min), metadata: nil),+ id: .integer(Int.min))+ #expect(try Fixture.originalText(result) == raw)+ #expect(Fixture.field("isError", in: result) == .boolean(false))+ let structured = try Fixture.structured(result)+ let retained = Fixture.field("source", in: structured)+ if case .plainText = origin {+ #expect(Fixture.field("kind", in: retained) == .string("text"))+ #expect(Fixture.field("payload", in: retained) == .string(raw))+ } else {+ #expect(Fixture.field("kind", in: retained) == .string("unreadable"))+ #expect(Fixture.field("payload", in: retained) == nil)+ #expect(Fixture.field("evidence", in: Fixture.field("presentation", in: structured))+ == .string("unestablished"))+ }+ }+ }++ @Test func seededLosslessSourcesSurviveCompleteEnvelopeAndSafeEscaping() throws {+ var generator = MCPJSONFixtureGenerator(seed: 0x2383_0607)+ for index in 0..<64 {+ let fixture = generator.value(depth: 3)+ let source = try Fixture.source(fixture.json())+ let presentation = try MCPResultAdapter.present(source, context: Fixture.context())+ let bytes = try MCPResultEncoder.encode(source: source, presentation: presentation,+ id: .integer(index), metadata: nil)+ let result = try Fixture.result(bytes, id: .integer(index))+ #expect(try Fixture.originalText(result) == fixture.json())+ let structured = try Fixture.structured(result)+ let payload = try #require(Fixture.field("payload", in: Fixture.field("source", in: structured)))+ #expect(fixture.matches(payload), "Seed2383_0607 index\(index) must preserve exact tokens and identities")+ }+ }++ @Test func metadataUsesOwnedLosslessObjectAndIndependentNamespace() throws {+ let raw = """+ {"com.example/capture":{"é":9007199254740993,"e\u{0301}":1E-9999,"missing":null},+ "com.example/policy":{"source":"collides","presentation":false}}+ """+ let document = try MCPJSONDocument.parse(raw)+ let metadata = try MCPResultMetadata.make(document: document)+ let source = try Fixture.source("{\"_meta\":null,\"source\":\"original\"}")+ let presentation = try MCPResultAdapter.present(source, context: Fixture.context())+ let result = try Fixture.result(MCPResultEncoder.encode(source: source, presentation: presentation,+ id: .integer(Int.max), metadata: metadata),+ id: .integer(Int.max))+ let actual = try #require(Fixture.field("_meta", in: result))+ let fixture = MCPJSONFixtureValue.object([+ MCPJSONFixtureMember(name: "com.example/capture", value: .object([+ MCPJSONFixtureMember(name: "é", value: .number("9007199254740993")),+ MCPJSONFixtureMember(name: "e\u{0301}", value: .number("1E-9999")),+ MCPJSONFixtureMember(name: "missing", value: .null)+ ])),+ MCPJSONFixtureMember(name: "com.example/policy", value: .object([+ MCPJSONFixtureMember(name: "source", value: .string("collides")),+ MCPJSONFixtureMember(name: "presentation", value: .boolean(false))+ ]))+ ])+ #expect(fixture.matches(actual))+ #expect(metadata.document.originalUTF8 == document.originalUTF8)+ let payload = Fixture.field("payload", in: Fixture.field("source", in: try Fixture.structured(result)))+ #expect(payload == source.document?.value)+ #expect(Fixture.field("com.example/capture", in: payload) == nil)+ }++ @Test func metadataRejectsNonObjectAndInvalidNamespaceBeforeEncoding() throws {+ for raw in ["null", "[]", "3", "{\"bad key\":true}"] {+ let document = try MCPJSONDocument.parse(raw)+ #expect(throws: MCPResultBoundaryError.invalidJSON) {+ _ = try MCPResultMetadata.make(document: document)+ }+ }+ }++ @Test func frozenFragmentsAreIDIndependentAndReuseExactToolBytes() throws {+ let source = try Fixture.source("{\"revision\":\"r1:frozen\",\"record\":null}")+ let presentation = try MCPResultAdapter.present(source, context: Fixture.context())+ let metadata = try MCPResultMetadata.make(document: MCPJSONDocument.parse(+ "{\"com.example/capturedAt\":\"original\",\"com.example/expiry\":\"fixed\"}"))+ let fragment = try MCPResultEncoder.freeze(source: source, presentation: presentation, metadata: metadata)+ let frozen = try MCPJSONDocument.parse(fragment.encodedResult).value+ #expect(Fixture.field("id", in: frozen) == nil)+ #expect(Fixture.field("jsonrpc", in: frozen) == nil)+ for id: JSONRPCId in [.string("continuation-2"), .integer(3)] {+ let bytes = try MCPResultEncoder.encode(fragment: fragment, id: id)+ #expect(try Fixture.result(bytes, id: id) == frozen)+ #expect(bytes.range(of: fragment.encodedResult) != nil)+ }+ }++ @Test func rawPayloadAndFrozenMetadataPreserveExactOwnedFragments() throws {+ let raw = #"{"z": -0,"escaped":"\u0061\/","é":9007199254740993,"e\u0301":1E-9999,"first":null}"#+ let source = try Fixture.source(raw)+ let metadata = try MCPResultMetadata.make(document: MCPJSONDocument.parse(+ #"{"com.example/raw":{"z":-0,"é":1E-9999,"e\u0301":"\u0061\/"}}"#))+ let presentation = try MCPResultAdapter.present(source, context: Fixture.context())+ let fragment = try MCPResultEncoder.freeze(source: source, presentation: presentation, metadata: metadata)+ #expect(try Fixture.rawFragment(fragment.encodedResult, path: ["structuredContent", "source", "payload"])+ == source.document?.originalUTF8)+ #expect(try Fixture.rawFragment(fragment.encodedResult, path: ["_meta"]) == metadata.document.originalUTF8)+ let wire = try MCPResultEncoder.encode(fragment: fragment, id: .string("fresh"))+ #expect(try Fixture.rawFragment(wire, path: ["result"]) == fragment.encodedResult)+ #expect(try Fixture.rawFragment(wire, path: ["result", "structuredContent", "source", "payload"])+ == source.document?.originalUTF8)+ }++ @Test func depth32InputsRemainValidWhenEnvelopeAddsNesting() throws {+ let raw = String(repeating: "[", count: 32) + "-0" + String(repeating: "]", count: 32)+ let source = try Fixture.source(raw)+ let nested = String(repeating: "[", count: 31) + "1E-9999" + String(repeating: "]", count: 31)+ let metadata = try MCPResultMetadata.make(document: MCPJSONDocument.parse(+ "{\"com.example/deep\":\(nested)}"))+ let presentation = try MCPResultAdapter.present(source, context: Fixture.context())+ let bytes = try MCPResultEncoder.encode(source: source, presentation: presentation,+ id: .integer(32), metadata: metadata)+ // Full wire has greater depth than the separately validated source cap.+ #expect(try Fixture.rawFragment(bytes, path: ["result", "structuredContent", "source", "payload"])+ == source.document?.originalUTF8)+ #expect(try Fixture.rawFragment(bytes, path: ["result", "_meta"]) == metadata.document.originalUTF8)+ #expect(try Fixture.rawFragment(bytes, path: ["id"]) == Data("32".utf8))+ #expect(try Fixture.rawFragment(bytes, path: ["result", "resultType"]) == Data("\"complete\"".utf8))+ }++ @Test func encodingHonoursOriginalCheckpointAndNeverRetainsIt() throws {+ let source = try Fixture.source("[\"safe\"]")+ let presentation = try MCPResultAdapter.present(source, context: Fixture.context())+ let counter = MCPEncoderCheckpointCounter()+ let fragment = try MCPResultEncoder.freeze(source: source, presentation: presentation, metadata: nil,+ checkpoint: { try counter.check() })+ let finished = counter.value()+ #expect(finished > 0)+ _ = try MCPResultEncoder.encode(fragment: fragment, id: .integer(1))+ #expect(counter.value() == finished)+ let cancelled = MCPEncoderCheckpointCounter(failAt: 1)+ #expect(throws: MCPResultEncoderFixtures.FixtureError.cancelled) {+ _ = try MCPResultEncoder.encode(source: source, presentation: presentation, id: .integer(1),+ metadata: nil, checkpoint: { try cancelled.check() })+ }+ #expect(cancelled.value() == 1)+ let metadataCancelled = MCPEncoderCheckpointCounter(failAt: 1)+ let document = try MCPJSONDocument.parse("{\"com.example/check\":true}")+ #expect(throws: MCPResultEncoderFixtures.FixtureError.cancelled) {+ _ = try MCPResultMetadata.make(document: document, checkpoint: { try metadataCancelled.check() })+ }+ #expect(metadataCancelled.value() == 1)+ let wrapCancelled = MCPEncoderCheckpointCounter(failAt: 1)+ #expect(throws: MCPResultEncoderFixtures.FixtureError.cancelled) {+ _ = try MCPResultEncoder.encode(fragment: fragment, id: .integer(2),+ checkpoint: { try wrapCancelled.check() })+ }+ #expect(wrapCancelled.value() == 1)+ }+}+#endif
diff --git a/Transit/TransitTests/MCPResultMaintenanceIntegrationTests.swift b/Transit/TransitTests/MCPResultMaintenanceIntegrationTests.swiftnew file mode 100644index 0000000..edc6c25--- /dev/null+++ b/Transit/TransitTests/MCPResultMaintenanceIntegrationTests.swift@@ -0,0 +1,155 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++@MainActor @Suite(.serialized)+struct MCPResultMaintenanceIntegrationTests {+ private enum Fault: Error { case inner, outer, preparation }+ private nonisolated final class Counts: @unchecked Sendable {+ private let lock = NSLock()+ private var value = 0+ func record() { lock.lock(); defer { lock.unlock() }; value += 1 }+ var count: Int { lock.lock(); defer { lock.unlock() }; return value }+ }++ @Test func actualInnerEncodingFailureAfterSavedReassignmentUsesNoKeyReconciliation() async throws {+ let env = try await duplicateEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let calls = Counts()+ let handler = MCPToolHandler(taskService: env.taskService, projectService: env.projectService,+ commentService: env.commentService, milestoneService: env.milestoneService,+ maintenanceService: env.maintenanceService, settings: env.mcpSettings,+ writeCoordinator: env.writeCoordinator, maintenanceReassignmentEncoder: { _ in+ calls.record()+ throw Fault.inner+ })+ let faultEnv = MCPTestEnv(handler: handler, taskService: env.taskService, projectService: env.projectService,+ commentService: env.commentService, milestoneService: env.milestoneService,+ maintenanceService: env.maintenanceService, mcpSettings: env.mcpSettings, context: env.context,+ writeCoordinator: env.writeCoordinator, sidecarDirectory: env.sidecarDirectory)+ let response = try await MCPModernResultFixture.call(faultEnv, tool: "reassign_duplicate_display_ids",+ arguments: [:], id: "inner-fault")+ #expect(calls.count == 1)+ try assertSavedReassignment(env)+ let result = try MCPModernResultFixture.assertSource(response, id: .string("inner-fault"))+ try assertMaintenanceRecovery(result)+ }++ @Test func actualSavedMaintenanceThenFinalEnvelopeFailureSelectsReadyBytesOnce() async throws {+ let env = try await duplicateEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let handler = env.handler+ let calls = Counts()+ let fixed = context()+ let fallback = try fallbackSource()+ let id = JSONRPCId.string("outer-fault")+ let ready = try MCPResultProviderSelection.prepare(id: id, source: fallback, context: fixed, metadata: nil)+ let selected = try await MCPResultProviderSelection.mutation(id: id, context: fixed,+ metadata: nil, fallbackSource: fallback, encodeOutcome: { _, _, _ in+ calls.record(); throw Fault.outer+ }, dispatch: { try await Self.actualOutcome(handler, context: fixed) })+ guard case .reconciliation(let bytes) = selected else {+ Issue.record("Expected already prepared post-effect response"); throw Fault.outer+ }+ #expect(bytes == ready)+ #expect(calls.count == 1)+ try assertSavedReassignment(env)+ try assertMaintenanceRecovery(MCPResultEncoderFixtures.result(bytes, id: id))+ }++ @Test func actualMaintenanceDeliverySuppressionRetainsSavedEffects() async throws {+ let env = try await duplicateEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let handler = env.handler+ let fixed = context()+ let completed = Counts()+ let selected = try await MCPResultProviderSelection.mutation(id: .string("delivery-fault"), context: fixed,+ metadata: nil, fallbackSource: fallbackSource(), shouldDeliver: { completed.count == 0 }, dispatch: {+ let outcome = try await Self.actualOutcome(handler, context: fixed)+ completed.record()+ return outcome+ })+ if case .suppressed = selected {} else { Issue.record("Expected delivery suppression") }+ #expect(completed.count == 1)+ try assertSavedReassignment(env)+ }++ @Test func preparationFailureNeverInvokesActualMaintenanceEffects() async throws {+ let env = try await duplicateEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let handler = env.handler+ let fixed = context()+ let calls = Counts()+ do {+ _ = try await MCPResultProviderSelection.mutation(id: .string("prep-fault"), context: fixed,+ metadata: nil, fallbackSource: fallbackSource(),+ prepareFallback: { _, _, _, _ in throw Fault.preparation },+ dispatch: { calls.record(); return try await Self.actualOutcome(handler, context: fixed) })+ Issue.record("Expected original preparation failure")+ } catch Fault.preparation {}+ #expect(calls.count == 0)+ let fresh = ModelContext(env.context.container)+ fresh.autosaveEnabled = false+ #expect(try fresh.fetch(FetchDescriptor<TransitTask>()).compactMap(\.permanentDisplayId) == [99, 99])+ }++ private func duplicateEnv() async throws -> MCPTestEnv {+ let env = try MCPTestHelpers.makeEnv()+ env.mcpSettings.maintenanceToolsEnabled = true+ let project = try env.projectService.createProject(name: "Maintenance Fixture", description: "",+ gitRepo: nil, colorHex: "#112233")+ let first = try await env.taskService.createTask(name: "First", description: nil,+ type: .feature, project: project)+ let second = try await env.taskService.createTask(name: "Second", description: nil,+ type: .feature, project: project)+ first.permanentDisplayId = 99+ second.permanentDisplayId = 99+ try env.context.save()+ return env+ }++ private func context() -> MCPResultContext {+ MCPResultContext(tool: "reassign_duplicate_display_ids", semanticFailure: nil,+ mutationRecovery: .unprotectedMaintenance(tool: "reassign_duplicate_display_ids"), entityPositions: [])+ }++ private func fallbackSource() throws -> MCPResultSource {+ try MCPResultAdapter.source(text: #"{"error":{"code":"OUTCOME_UNKNOWN"}}"#, isError: true,+ origin: .generatedJSON, evidence: .unestablished)+ }++ private static func actualOutcome(_ handler: MCPToolHandler,+ context: MCPResultContext) async throws -> MCPResultProviderOutcome {+ let request = MCPTestHelpers.toolCallRequest(tool: "reassign_duplicate_display_ids", arguments: [:])+ let response = try #require(await handler.handle(request))+ let tool = try #require(response.result?.value as? MCPToolResult)+ let text = try #require(tool.content.first?.text)+ let source = try MCPResultAdapter.source(text: text, isError: tool.isError,+ origin: .generatedJSON, evidence: .established)+ return MCPResultProviderOutcome(source: source, context: context)+ }++ private func assertSavedReassignment(_ env: MCPTestEnv) throws {+ let fresh = ModelContext(env.context.container)+ fresh.autosaveEnabled = false+ let tasks = try fresh.fetch(FetchDescriptor<TransitTask>())+ let values = tasks.compactMap(\.permanentDisplayId)+ #expect(values.count == 2)+ #expect(Set(values).count == 2)+ #expect(values.contains(99))+ #expect(try fresh.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0)+ }++ private func assertMaintenanceRecovery(_ result: MCPJSONValue) throws {+ let structured = try MCPResultEncoderFixtures.structured(result)+ let presentation = MCPResultEncoderFixtures.field("presentation", in: structured)+ #expect(MCPResultEncoderFixtures.field("evidence", in: presentation) == .string("unestablished"))+ let recovery = MCPResultEncoderFixtures.field("recovery", in: presentation)+ #expect(MCPResultEncoderFixtures.field("direction", in: recovery) == .string("reconcile_maintenance"))+ #expect(MCPResultEncoderFixtures.field("tool", in: recovery) == .string("reassign_duplicate_display_ids"))+ #expect(MCPResultEncoderFixtures.field("idempotencyKey", in: recovery) == nil)+ }+}+#endif
diff --git a/Transit/TransitTests/MCPResultPreparationBudgetTests.swift b/Transit/TransitTests/MCPResultPreparationBudgetTests.swiftnew file mode 100644index 0000000..55cb58b--- /dev/null+++ b/Transit/TransitTests/MCPResultPreparationBudgetTests.swift@@ -0,0 +1,356 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++/// Pure value preparation: actual domain reservation/publication is task17 coverage.+@MainActor+struct MCPResultPreparationBudgetTests {+ @Test func normativeComponentBreakdownPreservesOriginalBacking() throws {+ let text = #"{"a":"é","b":[false,1E-9,null]}"#+ let page = try makePage(text)+ let bundle = try prepare([page], base: 137)+ let charge = bundle.charge+ // Hand-computed tree dynamic payload; embedded root enum handle is excluded.+ let treeDynamic = MemoryLayout<[MCPJSONMember]>.stride + 2 * MemoryLayout<MCPJSONMember>.stride+ + 2 + MemoryLayout<String>.stride + 2 + MemoryLayout<[MCPJSONValue]>.stride+ + 3 * MemoryLayout<MCPJSONValue>.stride + MemoryLayout<Bool>.stride+ + MemoryLayout<MCPJSONNumber>.stride + 4+ #expect(charge.originalCaptureIndexBytes == 137)+ #expect(charge.originalTextBytes == text.utf8.count)+ #expect(charge.sourceDocumentBytes == text.utf8.count)+ #expect(charge.sourceValueBytes == MemoryLayout<MCPResultSource>.stride + treeDynamic)+ #expect(charge.presentationValueBytes == MemoryLayout<MCPResultPresentation>.stride)+ #expect(charge.fragmentBytes == page.fragment.encodedResult.count + MemoryLayout<MCPResultToolFragment>.stride)+ #expect(charge.metadataDocumentBytes == 0)+ #expect(charge.metadataValueBytes == 0)+ // Page array header and every reference slot, plus each unique page's+ // metadata pointer. Source/presentation/fragment headers are above.+ #expect(charge.ownerReferenceBytes == MemoryLayout<[MCPResultPreparedPage]>.stride+ + MemoryLayout<MCPResultPreparedPage>.stride + MemoryLayout<MCPResultPreparedMetadata?>.stride)+ #expect(charge.totalBytes == components(charge))+ #expect(page.source.originalText == text)+ #expect(page.source.document?.originalUTF8 == Data(text.utf8))+ #expect(page.source.originalIsError == false)+ #expect(bundle.pages[0] === page)+ #expect(page.fragment.encodedResult.range(of: Data(text.utf8)) != nil)+ }++ @Test func metadataHasIndependentNonzeroDecodedValueCharge() throws {+ let text = #"{"x":"é","b":[false,1E-9,null]}"#+ let value = try MCPResultMetadata.make(document: MCPJSONDocument.parse(text))+ let metadata = try MCPResultPreparation.metadata(value: value)+ let page = try makePage("null", metadata: metadata)+ let charge = try prepare([page]).charge+ let dynamic = MemoryLayout<[MCPJSONMember]>.stride + 2 * MemoryLayout<MCPJSONMember>.stride+ + 2 + MemoryLayout<String>.stride + 2 + MemoryLayout<[MCPJSONValue]>.stride+ + 3 * MemoryLayout<MCPJSONValue>.stride + MemoryLayout<Bool>.stride+ + MemoryLayout<MCPJSONNumber>.stride + 4+ #expect(charge.metadataDocumentBytes == text.utf8.count)+ #expect(charge.metadataValueBytes == MemoryLayout<MCPResultMetadata>.stride + dynamic)+ #expect(metadata.value.document.originalUTF8 == Data(text.utf8))+ #expect(charge.totalBytes == components(charge))+ }++ @Test func sharedOwnersAreCountedOnceButEqualBytesDistinctOwnersAreNot() throws {+ let value = try MCPResultMetadata.make(+ document: MCPJSONDocument.parse(MCPResultPreparationFixtures.metadataText))+ let shared = try MCPResultPreparation.metadata(value: value)+ let first = try makePage(#"{"future":null}"#, metadata: shared)+ let second = try makePage(#"{"future":null}"#, metadata: shared)+ let unique = try prepare([first])+ let aliased = try prepare([first, first])+ let distinct = try prepare([first, second])+ #expect(aliased.charge.originalTextBytes == unique.charge.originalTextBytes)+ #expect(aliased.charge.sourceValueBytes == unique.charge.sourceValueBytes)+ #expect(aliased.charge.fragmentBytes == unique.charge.fragmentBytes)+ #expect(distinct.charge.originalTextBytes == 2 * unique.charge.originalTextBytes)+ #expect(distinct.charge.sourceValueBytes == 2 * unique.charge.sourceValueBytes)+ #expect(distinct.charge.fragmentBytes == 2 * unique.charge.fragmentBytes)+ #expect(distinct.charge.metadataDocumentBytes == value.document.originalUTF8.count)+ #expect(distinct.charge.metadataValueBytes == unique.charge.metadataValueBytes)+ #expect(first.metadataOwner === second.metadataOwner)+ let separate = try MCPResultPreparation.metadata(value: value)+ let third = try makePage(#"{"future":null}"#, metadata: separate)+ let separateBundle = try prepare([first, third])+ #expect(separateBundle.charge.metadataDocumentBytes == 2 * unique.charge.metadataDocumentBytes)+ #expect(separateBundle.charge.metadataValueBytes == 2 * unique.charge.metadataValueBytes)+ #expect(first.metadataOwner !== third.metadataOwner)+ #expect(aliased.charge.ownerReferenceBytes == unique.charge.ownerReferenceBytes+ + MemoryLayout<MCPResultPreparedPage>.stride)+ #expect(distinct.charge.ownerReferenceBytes == aliased.charge.ownerReferenceBytes+ + MemoryLayout<MCPResultPreparedMetadata?>.stride)+ #expect(aliased.charge.totalBytes == components(aliased.charge))+ #expect(distinct.charge.totalBytes == components(distinct.charge))+ }++ @Test func twoThousandSeededRecordsFourPagesRetainExactFrozenEvidence() throws {+ let texts = try MCPResultPreparationFixtures.pages()+ #expect(texts.count == 4)+ #expect(texts == (try MCPResultPreparationFixtures.pages()))+ let metadata = try MCPResultPreparation.metadata(value: MCPResultMetadata.make(+ document: MCPJSONDocument.parse(MCPResultPreparationFixtures.metadataText)))+ let checks = Checkpoints()+ let pages = try texts.map { try makePage($0, metadata: metadata, checkpoint: { try checks.check() }) }+ let bundle = try MCPResultPreparation.prepare(pages: pages, budget: budget(base: 8_192),+ checkpoint: { try checks.check() })+ #expect(bundle.pages.count == 4)+ #expect(bundle.charge.originalCaptureIndexBytes == 8_192)+ #expect(bundle.charge.originalTextBytes == texts.reduce(0) { $0 + $1.utf8.count })+ #expect(bundle.charge.sourceDocumentBytes == bundle.charge.originalTextBytes)+ #expect(bundle.charge.metadataDocumentBytes == MCPResultPreparationFixtures.metadataText.utf8.count)+ #expect(bundle.charge.totalBytes == components(bundle.charge))+ #expect(checks.count > 100)+ for (index, page) in bundle.pages.enumerated() {+ #expect(page.source.originalText == texts[index])+ #expect(page.source.document?.originalUTF8 == Data(texts[index].utf8))+ #expect(page.metadataOwner === metadata)+ #expect(page.fragment.encodedResult.range(of: Data(texts[index].utf8)) != nil)+ #expect(page.fragment.encodedResult.range(of: metadata.value.document.originalUTF8) != nil)+ guard case .array(let records) = page.source.document?.value else {+ Issue.record("Original decoded array missing"); continue+ }+ #expect(records.count == 500)+ }+ }++ @Test func fixedSeparateStoreBoundariesIncludeVisibleAndPendingBytes() throws {+ let page = try makePage("null")+ let measured = try prepare([page]).charge.totalBytes+ for store in MCPResultRetentionStore.allCases {+ let limit = MCPResultRetentionBudget.limitBytes+ let exact = try MCPResultPreparation.prepare(pages: [page],+ budget: budget(store: store, base: 23, visible: limit - measured - 30, pending: 7))+ #expect(exact.charge.totalBytes == measured + 23)+ #expect(throwsPreparation(.retentionCapacity) {+ _ = try MCPResultPreparation.prepare(pages: [page],+ budget: budget(store: store, base: 23, visible: limit - measured - 30, pending: 8))+ })+ #expect(throwsPreparation(.retentionCapacity) {+ _ = try MCPResultPreparation.prepare(pages: [page], budget: budget(store: store, base: limit))+ })+ }+ // One store's observed usage is never added to the other's budget.+ #expect(try MCPResultPreparation.prepare(+ pages: [page], budget: budget(store: .ordinary)).charge.totalBytes == measured)+ #expect(try MCPResultPreparation.prepare(+ pages: [page], budget: budget(store: .reusable)).charge.totalBytes == measured)+ }++ @Test func invalidAndOverflowAccountingFailWithoutPartialBundle() throws {+ let page = try makePage("false")+ for value in [budget(base: -1), budget(visible: -1), budget(pending: -1)] {+ #expect(throwsPreparation(.invalidAccounting) {+ _ = try MCPResultPreparation.prepare(pages: [page], budget: value)+ })+ }+ for value in [budget(base: Int.max), budget(visible: Int.max, pending: 1)] {+ var returned: MCPResultRetainedBundle?+ #expect(throwsPreparation(.arithmeticOverflow) {+ returned = try MCPResultPreparation.prepare(pages: [page], budget: value)+ })+ #expect(returned == nil)+ }+ }++ @Test func originalTypedCancellationAndDeadlineSurviveAllPreparationStages() throws {+ let page = try makePage("null")+ for failure in [Cutoff.cancelled, .deadline] {+ #expect(throwsCutoff(failure) {+ _ = try makePage(try MCPResultPreparationFixtures.pages()[0], origin: .retainedJSON,+ checkpoint: { throw failure })+ })+ var returned: MCPResultRetainedBundle?+ #expect(throwsCutoff(failure) {+ returned = try MCPResultPreparation.prepare(pages: [page], budget: budget(),+ checkpoint: { throw failure })+ })+ #expect(returned == nil)+ }+ let checks = Checkpoints(cutoff: 5)+ #expect(throwsCutoff(.deadline) {+ _ = try makePage(try MCPResultPreparationFixtures.pages()[0], checkpoint: { try checks.check() })+ })+ #expect(checks.count == 5)+ }++ @Test func lateMeasurementAndPlainTextEncodingCutoffsReturnNoPartialValue() throws {+ let texts = try MCPResultPreparationFixtures.pages()+ let pages = try texts.map { try makePage($0) }+ let measurement = Checkpoints()+ _ = try MCPResultPreparation.prepare(pages: pages, budget: budget(),+ checkpoint: { try measurement.check() })+ #expect(measurement.count > 10)+ let late = Checkpoints(cutoff: max(2, measurement.count / 2))+ var bundle: MCPResultRetainedBundle?+ #expect(throwsCutoff(.deadline) {+ bundle = try MCPResultPreparation.prepare(pages: pages, budget: budget(),+ checkpoint: { try late.check() })+ })+ #expect(late.count == max(2, measurement.count / 2))+ #expect(bundle == nil)+ // Plain text bypasses JSON scanning and record selection; late work here+ // is the frozen writer over escaped source text, not a parser callback.+ let text = String(repeating: "é\n\"\\", count: 100_000)+ let encoding = Checkpoints()+ _ = try makePage(text, origin: .plainText, checkpoint: { try encoding.check() })+ #expect(encoding.count > 100)+ let encodingCutoff = Checkpoints(cutoff: max(50, encoding.count - 5), failure: .cancelled)+ var page: MCPResultPreparedPage?+ #expect(throwsCutoff(.cancelled) {+ page = try makePage(text, origin: .plainText, checkpoint: { try encodingCutoff.check() })+ })+ #expect(encodingCutoff.count == max(50, encoding.count - 5))+ #expect(page == nil)+ }++ @Test func presentationLinkAndRecoveryBackingIsIncluded() throws {+ let uuid = UUID(uuidString: "AA000000-0000-0000-0000-000000000001")!+ let context = MCPResultContext(tool: "update_task", semanticFailure: nil,+ mutationRecovery: .protectedWrite(.init(tool: "update_task", idempotencyKey: "original-key-é")),+ entityPositions: [.init(entityType: .task, sourcePath: "/record")])+ let text = "{\"record\":{\"taskId\":\"\(uuid)\"},\"accepted\":true}"+ let page = try makePage(text, context: context, evidence: .unestablished)+ let link = try #require(page.presentation.links.first)+ #expect(link.entityId == uuid)+ let charge = try prepare([page]).charge+ let dynamic = MemoryLayout<MCPUnavailableLink>.stride + link.sourcePath.utf8.count+ + link.availability.utf8.count + link.reason.utf8.count+ + "update_task".utf8.count + "original-key-é".utf8.count+ #expect(charge.presentationValueBytes == MemoryLayout<MCPResultPresentation>.stride + dynamic)+ }++}++extension MCPResultPreparationBudgetTests {+ @Test func batchAndMaintenanceRecoveryHaveIndependentDynamicCharges() throws {+ let items = [+ MCPBatchRecoveryItem(index: 0, itemId: "first-é", operation: "update_task",+ originalKey: .init(tool: "update_task", idempotencyKey: "original-one"),+ targetTaskId: UUID(uuidString: "AA000000-0000-0000-0000-000000000001")),+ MCPBatchRecoveryItem(index: 1, itemId: nil, operation: "delete_task",+ originalKey: .init(tool: "delete_task", idempotencyKey: "original-two"), targetTaskId: nil)+ ]+ let context = MCPResultContext(tool: "mutate_tasks", semanticFailure: nil,+ mutationRecovery: .applicationBatch(items: items), entityPositions: [])+ let page = try makePage("null", context: context, evidence: .unestablished)+ let charge = try prepare([page]).charge+ let dynamic = 2 * MemoryLayout<MCPBatchRecoveryItem>.stride + "first-é".utf8.count+ + 2 * "update_task".utf8.count + "original-one".utf8.count+ + 2 * "delete_task".utf8.count + "original-two".utf8.count+ #expect(charge.presentationValueBytes == MemoryLayout<MCPResultPresentation>.stride + dynamic)+ guard case .applicationBatch(let retained) = page.presentation.recovery?.mutation else {+ Issue.record("Original batch recovery missing"); return+ }+ try #require(retained.count == 2)+ #expect(retained.map(\.index) == [0, 1])+ #expect(retained.map(\.originalKey) == items.map(\.originalKey))+ #expect(retained[0].itemId == items[0].itemId)+ #expect(retained[0].targetTaskId == items[0].targetTaskId)+ #expect(retained[1].itemId == nil)+ #expect(retained[1].targetTaskId == nil)+ let maintenance = try makePage("null", context: .init(tool: "repair_links", semanticFailure: nil,+ mutationRecovery: .unprotectedMaintenance(tool: "repair_links"), entityPositions: []),+ evidence: .unestablished)+ #expect(try prepare([maintenance]).charge.presentationValueBytes+ == MemoryLayout<MCPResultPresentation>.stride + "repair_links".utf8.count)+ }++ @Test func blockedParserAndEncoderObserveOriginalFakeCutoff() async throws {+ let text = try MCPResultPreparationFixtures.pages()[0]+ let source = try MCPResultSource.make(text: text, isError: false, origin: .generatedJSON,+ evidence: .established)+ let presentation = MCPResultPresentation(evidence: .established, links: [], errorCategory: nil, recovery: nil)+ for encode in [false, true] {+ for cutoff in [Cutoff.cancelled, .deadline] {+ let barrier = Barrier(cutoff: cutoff)+ let worker = Task.detached {+ do {+ if encode {+ _ = try MCPResultEncoder.freeze(source: source, presentation: presentation, metadata: nil,+ checkpoint: { try barrier.check() })+ } else {+ _ = try MCPResultSource.make(text: text, isError: false, origin: .retainedJSON,+ evidence: .established, checkpoint: { try barrier.check() })+ }+ return false+ } catch { return (error as? Cutoff) == cutoff }+ }+ let started = await Task.detached { barrier.waitForEntry() }.value+ // Deterministic fake deadline/cancellation changes only at this boundary.+ barrier.release.signal()+ #expect(started)+ #expect(await worker.value)+ }+ }+ }++}++private extension MCPResultPreparationBudgetTests {+ func makePage(_ text: String, metadata: MCPResultPreparedMetadata? = nil,+ context: MCPResultContext? = nil, origin: MCPResultOrigin = .generatedJSON,+ evidence: MCPResultEvidence = .established,+ checkpoint: @escaping @Sendable () throws -> Void = {}) throws -> MCPResultPreparedPage {+ try MCPResultPreparation.page(request: .init(text: text, isError: false, origin: origin,+ evidence: evidence, context: context ?? MCPResultContext(tool: "query_tasks", semanticFailure: nil,+ mutationRecovery: nil, entityPositions: []), metadataOwner: metadata), checkpoint: checkpoint)+ }++ func prepare(_ pages: [MCPResultPreparedPage], base: Int = 0) throws -> MCPResultRetainedBundle {+ try MCPResultPreparation.prepare(pages: pages, budget: budget(base: base))+ }++ func budget(store: MCPResultRetentionStore = .ordinary, base: Int = 0,+ visible: Int = 0, pending: Int = 0) -> MCPResultRetentionBudget {+ .init(store: store, originalCaptureIndexBytes: base, visibleBytes: visible, pendingBytes: pending)+ }++ func components(_ charge: MCPResultRetainedCharge) -> Int {+ charge.originalCaptureIndexBytes + charge.originalTextBytes + charge.sourceDocumentBytes+ + charge.sourceValueBytes + charge.presentationValueBytes + charge.fragmentBytes+ + charge.metadataDocumentBytes + charge.metadataValueBytes + charge.ownerReferenceBytes+ }++ func throwsPreparation(_ expected: MCPResultPreparationError, body: () throws -> Void) -> Bool {+ do { try body(); return false } catch { return (error as? MCPResultPreparationError) == expected }+ }++ private func throwsCutoff(_ expected: Cutoff, body: () throws -> Void) -> Bool {+ do { try body(); return false } catch { return (error as? Cutoff) == expected }+ }++ nonisolated private enum Cutoff: Error, Sendable { case cancelled, deadline }++ nonisolated private final class Barrier: @unchecked Sendable {+ let entered = DispatchSemaphore(value: 0)+ let release = DispatchSemaphore(value: 0)+ let cutoff: Cutoff+ init(cutoff: Cutoff) { self.cutoff = cutoff }+ func waitForEntry() -> Bool { entered.wait(timeout: .now() + 2) == .success }+ func check() throws {+ entered.signal()+ guard release.wait(timeout: .now() + 2) == .success else { throw Cutoff.deadline }+ throw cutoff+ }+ }++ nonisolated private final class Checkpoints: @unchecked Sendable {+ private let lock = NSLock()+ private var checks = 0+ private let cutoff: Int?+ private let failure: Cutoff+ init(cutoff: Int? = nil, failure: Cutoff = .deadline) {+ self.cutoff = cutoff+ self.failure = failure+ }+ var count: Int { lock.withLock { checks } }+ func check() throws {+ try lock.withLock {+ checks += 1+ if checks == cutoff { throw failure }+ }+ }+ }+}+#endif
diff --git a/Transit/TransitTests/MCPResultPreparationFixtures.swift b/Transit/TransitTests/MCPResultPreparationFixtures.swiftnew file mode 100644index 0000000..b754f07--- /dev/null+++ b/Transit/TransitTests/MCPResultPreparationFixtures.swift@@ -0,0 +1,49 @@+#if os(macOS)+import Foundation++/// Synthetic immutable values only: no model, store, clock or capture dependency.+@MainActor+enum MCPResultPreparationFixtures {+ static func pages(recordCount: Int = 2_000, pageSize: Int = 500, padding: Int = 512) throws -> [String] {+ var generator = Generator(seed: 0x2383_2012_05BD_000A)+ var pages: [String] = []+ for start in stride(from: 0, to: recordCount, by: pageSize) {+ var records: [String] = []+ for index in start..<min(start + pageSize, recordCount) {+ let uuid = String(format: "AA000000-0000-0000-0000-%012llX", UInt64(index + 1))+ let name = "T-\(index) 🛰 \"saved\"\n" + String(generator.next(), radix: 16)+ let detail = String(repeating: "x", count: padding) + "\n é / é ~ \\"+ let number = index.isMultiple(of: 2) ? "1E-9999" : "999999999999999999999999999999999999999"+ records.append("{\"taskId\":\(try quoted(uuid)),\"displayId\":\(index),"+ + "\"name\":\(try quoted(name)),\"description\":\(try quoted(detail)),"+ + "\"revision\":\(try quoted("r1:" + String(repeating: "a", count: 64))),"+ + "\"future\":{\"number\":\(number),\"flag\":false,\"nullable\":null}}")+ }+ pages.append("[" + records.joined(separator: ",\n") + "]")+ }+ return pages+ }++ static let metadataText = #"""+ {"me.nore.ig.transit/read":{"asOf":"2026-10-03T09:00:00.000Z",+ "snapshotId":"frozen-original-capture","freshness":{"assessment":"unknown"},+ "read":{"policy":"cached","budgetMs":5000},"future":{"value":1E-9999,"flag":false,"nullable":null}}}+ """#++ private static func quoted(_ text: String) throws -> String {+ let bytes = try JSONSerialization.data(withJSONObject: text, options: [.fragmentsAllowed])+ guard let encoded = String(bytes: bytes, encoding: .utf8) else {+ throw CocoaError(.fileReadInapplicableStringEncoding)+ }+ return encoded+ }++ private struct Generator {+ var seed: UInt64+ mutating func next() -> UInt64 {+ seed = seed &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407+ return seed+ }+ }+}+#endif
diff --git a/Transit/TransitTests/MCPResultPresentationRejectionFixtures.swift b/Transit/TransitTests/MCPResultPresentationRejectionFixtures.swiftnew file mode 100644index 0000000..0eebe01--- /dev/null+++ b/Transit/TransitTests/MCPResultPresentationRejectionFixtures.swift@@ -0,0 +1,36 @@+#if os(macOS)+@testable import Transit+nonisolated struct MCPPresentationRejectionFixture: Sendable {+ let code: String+ let accepted: Bool++ static let all: [MCPPresentationRejectionFixture] = [+ .init(code: "INTERRUPTED_BEFORE_COMMIT", accepted: true),+ .init(code: "INTERNAL_ERROR", accepted: true),+ .init(code: "INTERNAL_ERROR", accepted: false)+ ]+}++nonisolated struct MCPPresentationCodeFixture: Sendable {+ let code: String+ let category: MCPResultErrorCategory++ static let all: [MCPPresentationCodeFixture] = [+ .init(code: "INVALID_INPUT", category: .invalidInput),+ .init(code: "TASK_NOT_FOUND", category: .notFound),+ .init(code: "AMBIGUOUS_TASK_ID", category: .ambiguousIdentity),+ .init(code: "REVISION_CONFLICT", category: .revisionConflict),+ .init(code: "IDEMPOTENCY_KEY_REUSED", category: .keyConflict),+ .init(code: "PERSISTENCE_UNAVAILABLE", category: .storageFailure),+ .init(code: "READ_BUSY", category: .admissionBusy),+ .init(code: "READ_TIMEOUT", category: .deadlineExceeded),+ .init(code: "QUERY_CAPACITY_EXCEEDED", category: .retentionCapacity),+ .init(code: "INVALID_CURSOR", category: .invalidCursor),+ .init(code: "INVALID_SNAPSHOT", category: .invalidCursor),+ .init(code: "SNAPSHOT_INCOMPATIBLE", category: .invalidInput),+ .init(code: "IDENTITY_AMBIGUITY", category: .ambiguousIdentity),+ .init(code: "QUERY_EXPIRED", category: .expiredCursor),+ .init(code: "OUTCOME_UNCERTAIN", category: .outcomeUncertain)+ ]+}+#endif
diff --git a/Transit/TransitTests/MCPResultPresentationTests.swift b/Transit/TransitTests/MCPResultPresentationTests.swiftnew file mode 100644index 0000000..1b64179--- /dev/null+++ b/Transit/TransitTests/MCPResultPresentationTests.swift@@ -0,0 +1,385 @@+#if os(macOS)+import Foundation+import Synchronization+import Testing+@testable import Transit++@MainActor struct MCPResultPresentationTests {+ @Test func protectedTaskRecordAndRelationshipHaveDistinctUnavailablePointers() throws {+ let text = "{\"record\":{\"taskId\":\"\(Self.taskID)\",\"displayId\":7," ++ "\"projectId\":\"\(Self.projectID)\",\"comments\":[{\"id\":\"\(Self.otherID)\"}]} }"+ let source = try Self.source(text)+ let presentation = try MCPResultAdapter.present(source, context: Self.context("update_task"))+ #expect(Self.links(presentation) == ["/record|task|\(Self.taskID)",+ "/record/projectId|project|\(Self.projectID)"])+ #expect(presentation.evidence == .established)+ #expect(presentation.errorCategory == nil)+ #expect(presentation.links.allSatisfy {+ $0.availability == "unavailable" && $0.reason == "navigation_not_supported"+ })+ #expect(source.originalText == text)+ }++ @Test func queryArrayOrderAndUUIDsSurviveDuplicateDisplayIDs() throws {+ let records = (0..<12).map { index in+ "{\"taskId\":\"\(Self.numberedID(index))\",\"displayId\":9}"+ }+ let source = try Self.source("{\"results\":[" + records.joined(separator: ",") + "]}")+ let presentation = try MCPResultAdapter.present(source, context: Self.context("query_tasks"))+ #expect(Self.links(presentation) == (0..<12).map { "/results/\($0)|task|\(Self.numberedID($0))" })+ }++ @Test func selectorSuccessUsesNestedTaskAndSavedProjectWithoutLinkingRequestedFailures() throws {+ let text = "{\"results\":[{\"index\":0,\"requested\":{\"displayId\":9},\"task\":{" ++ "\"taskId\":\"\(Self.taskID)\",\"displayId\":9,\"projectId\":\"\(Self.projectID)\"}}," ++ "{\"index\":1,\"requested\":{\"taskId\":\"\(Self.otherID)\"}," ++ "\"error\":{\"code\":\"TASK_NOT_FOUND\",\"message\":\"Absent selector\"}}],\"nextCursor\":null}"+ let source = try Self.source(text)+ let presentation = try MCPResultAdapter.present(source, context: Self.context("query_tasks"))+ #expect(Self.links(presentation) == ["/results/0/task|task|\(Self.taskID)",+ "/results/0/task/projectId|project|\(Self.projectID)"])+ #expect(presentation.evidence == .established)+ #expect(presentation.errorCategory == nil)+ #expect(source.originalText == text)+ }++ @Test func historicalRootTaskArrayPreservesSavedProjectReferencesAndArrayOrder() throws {+ let text = "[{\"taskId\":\"\(Self.taskID)\",\"displayId\":9,\"projectId\":\"\(Self.projectID)\"}," ++ "{\"taskId\":\"\(Self.otherID)\",\"displayId\":9,\"projectId\":\"\(Self.projectID)\"}]"+ let source = try Self.source(text, origin: .retainedJSON)+ let presentation = try MCPResultAdapter.present(source, context: Self.context("query_tasks"))+ #expect(Self.links(presentation) == ["/0|task|\(Self.taskID)", "/0/projectId|project|\(Self.projectID)",+ "/1|task|\(Self.otherID)", "/1/projectId|project|\(Self.projectID)"])+ #expect(source.document?.originalUTF8 == Data(text.utf8))+ }++ @Test func projectsArrayUsesProjectIdentityAndDoesNotSearchUnknownNestedIDs() throws {+ let text = "[{\"projectId\":\"\(Self.projectID)\"," ++ "\"extra\":{\"taskId\":\"\(Self.taskID)\"}}]"+ let source = try Self.source(text)+ let presentation = try MCPResultAdapter.present(source, context: Self.context("get_projects"))+ #expect(Self.links(presentation) == ["/0|project|\(Self.projectID)"])+ }++ @Test(arguments: ["record", "currentRecord", "recordBeforeDeletion"])+ func documentedTaskEvidencePositionsUseTheirOwnPointer(field: String) throws {+ let source = try Self.source("{\"\(field)\":{\"taskId\":\"\(Self.taskID)\"}}")+ let presentation = try MCPResultAdapter.present(source, context: Self.context("update_task"))+ #expect(Self.links(presentation) == ["/\(field)|task|\(Self.taskID)"])+ }++ @Test func missingMalformedAndUndeclaredIdentitiesNeverInventLinks() throws {+ let text = "{\"results\":[{}, {\"taskId\":null}, {\"taskId\":9}, {\"taskId\":\"not-a-uuid\"}]," ++ "\"unknown\":{\"taskId\":\"\(Self.taskID)\"}}"+ let source = try Self.source(text)+ let presentation = try MCPResultAdapter.present(source, context: Self.context("query_tasks"))+ #expect(presentation.links.isEmpty)+ let milestone = try Self.source("{\"record\":{\"id\":\"\(Self.otherID)\"}}")+ #expect(try MCPResultAdapter.present(milestone, context: Self.context("create_milestone")).links.isEmpty)+ let wrongTaskField = try Self.source("{\"record\":{\"id\":\"\(Self.taskID)\"}}")+ #expect(try MCPResultAdapter.present(wrongTaskField, context: Self.context("update_task")).links.isEmpty)+ }++ @Test func milestoneQueryLinksOnlySavedProjectReferencesInRootArrayOrder() throws {+ let text = "[{\"milestoneId\":\"\(Self.taskID)\",\"projectId\":\"\(Self.projectID)\"}," ++ "{\"milestoneId\":\"\(Self.projectID)\",\"projectId\":\"\(Self.otherID)\"}," ++ "{\"milestoneId\":\"\(Self.otherID)\",\"projectId\":null}," ++ "{\"milestoneId\":\"\(Self.taskID)\",\"projectId\":\"not-a-uuid\"}]"+ let source = try Self.source(text, origin: .retainedJSON)+ let presentation = try MCPResultAdapter.present(source, context: Self.context("query_milestones"))+ #expect(Self.links(presentation) == ["/0/projectId|project|\(Self.projectID)",+ "/1/projectId|project|\(Self.otherID)"])+ #expect(presentation.links.allSatisfy { $0.entityType == .project })+ #expect(presentation.errorCategory == nil)+ #expect(source.originalText == text)+ }++ @Test func providerPositionsAreValidatedAgainstSameSourceAndSortedDeterministically() throws {+ let source = try Self.source("{\"z\":\"\(Self.projectID)\",\"a\":{\"taskId\":\"\(Self.taskID)\"}}")+ let positions: [MCPResultEntityPosition] = [+ .init(entityType: .project, sourcePath: "/z"),+ .init(entityType: .task, sourcePath: "/a"),+ .init(entityType: .task, sourcePath: "/missing")+ ]+ let context = Self.context("future_provider", positions: positions)+ let presentation = try MCPResultAdapter.present(source, context: context)+ #expect(Self.links(presentation) == ["/a|task|\(Self.taskID)", "/z|project|\(Self.projectID)"])+ #expect(Self.signature(presentation) == Self.signature(try MCPResultAdapter.present(source, context: context)))+ }++ @Test func pointersUnescapeTokensAndCompareDecodedUnicodeScalarsExactly() throws {+ let source = try Self.source("{\"é\":\"\(Self.taskID)\",\"e\\u0301\":\"\(Self.projectID)\"," ++ "\"a/b~c\":\"\(Self.otherID)\"}")+ let positions: [MCPResultEntityPosition] = [+ .init(entityType: .task, sourcePath: "/é"),+ .init(entityType: .project, sourcePath: "/e\u{301}"),+ .init(entityType: .task, sourcePath: "/a~1b~0c")+ ]+ let presentation = try MCPResultAdapter.present(source, context: Self.context("future", positions: positions))+ #expect(presentation.links.count == 3)+ #expect(presentation.links.first { Array($0.sourcePath.unicodeScalars) == Array("/é".unicodeScalars) }?+ .entityId.uuidString == Self.taskID)+ #expect(presentation.links.first { Array($0.sourcePath.unicodeScalars) == Array("/e\u{301}".unicodeScalars) }?+ .entityId.uuidString == Self.projectID)+ #expect(presentation.links.first { $0.sourcePath == "/a~1b~0c" }?.entityId.uuidString == Self.otherID)+ }++ @Test func seededUnknownFieldsAndCollisionsPreserveEvidenceAndDeterministicLinkSelection() throws {+ for seed in UInt64(0)..<64 {+ var generator = MCPJSONFixtureGenerator(seed: seed)+ let unknown = generator.value()+ if try Self.collisionInvariant(unknown) { continue }+ let minimal = MCPJSONFixtureValue.minimizedFailure(unknown) {+ (try? Self.collisionInvariant($0)) != true+ }+ Issue.record("Presentation invariant failed seed=\(seed); unknown=\(try minimal.json())")+ return+ }+ }++ @Test(arguments: [MCPResultErrorCategory.invalidInput, .notFound, .ambiguousIdentity, .revisionConflict,+ .keyConflict, .storageFailure, .incoherentCapture, .admissionBusy, .deadlineExceeded,+ .retentionCapacity, .invalidCursor, .expiredCursor, .serializationFailure,+ .outcomeUncertain, .unclassifiedHistorical, .internalFailure])+ func explicitProviderFailurePhaseHasFiniteCategory(category: MCPResultErrorCategory) throws {+ let source = try MCPResultAdapter.source(text: "Message deliberately gives no category", isError: true,+ origin: .plainText, evidence: .established)+ let context = Self.context("query_tasks", failure: .init(category: category, diagnostic: "phase"))+ let presentation = try MCPResultAdapter.present(source, context: context)+ #expect(presentation.errorCategory == category)+ }++ @Test func invalidSnapshotRestartsReadWithoutChangingSavedFailure() throws {+ let text = #"{"error":{"code":"INVALID_SNAPSHOT","message":"Start a new summary"}}"#+ let source = try Self.source(text, isError: true, origin: .retainedJSON)+ let presentation = try MCPResultAdapter.present(source, context: Self.context("query_project_summaries"))+ #expect(presentation.errorCategory == .invalidCursor)+ #expect(presentation.recovery?.direction == .restartRead)+ #expect(source.originalText == text)+ }++ @Test(arguments: MCPPresentationCodeFixture.all)+ func knownHistoricCodesMapWithoutChangingOriginalFields(fixture: MCPPresentationCodeFixture) throws {+ let text = "{\"error\":{\"code\":\"\(fixture.code)\",\"message\":\"saved message\"},\"extra\":null}"+ let source = try Self.source(text, isError: true, origin: .retainedJSON)+ let presentation = try MCPResultAdapter.present(source, context: Self.context("query_tasks"))+ #expect(presentation.errorCategory == fixture.category)+ #expect(source.originalText == text)+ #expect(source.originalIsError == true)+ #expect(source.document?.originalUTF8 == Data(text.utf8))+ }+}++@MainActor extension MCPResultPresentationTests {+ @Test func acceptedUncertainWriteCannotAcquireNoEffectRetryFromItsErrorCode() throws {+ let text = #"{"outcome":"uncertain","accepted":true,"retryAction":"reconcile","# ++ #""error":{"code":"INVALID_INPUT"}}"#+ let source = try Self.source(text, isError: true, origin: .retainedJSON)+ let presentation = try MCPResultAdapter.present(source, context: Self.protectedContext())+ #expect(presentation.errorCategory == .outcomeUncertain)+ #expect(presentation.recovery?.direction == .reconcileOriginalWrite)+ guard case .protectedWrite(let key) = presentation.recovery?.mutation else {+ Issue.record("Lost original protected recovery key")+ return+ }+ #expect(key == Self.key)+ #expect(source.originalText == text)+ }++ @Test func contradictorySavedRetryEvidenceBecomesUnestablishedWithoutRewritingIt() throws {+ let text = #"{"outcome":"committed","accepted":true,"retryAction":"new_request_new_key","# ++ #""error":{"code":"INVALID_INPUT"}}"#+ let source = try Self.source(text, isError: true, origin: .retainedJSON)+ let presentation = try MCPResultAdapter.present(source, context: Self.protectedContext())+ #expect(presentation.evidence == .unestablished)+ #expect(presentation.errorCategory == .outcomeUncertain)+ #expect(presentation.recovery?.direction == .reconcileOriginalWrite)+ #expect(source.originalText == text)+ }++ @Test func unsupportedUnestablishedAndUnreadableWritesRequireOriginalEvidenceReconciliation() throws {+ for text in ["{broken", #"{"contractVersion":999,"outcome":"future","accepted":null}"#] {+ let source = try MCPResultAdapter.source(text: text, isError: false, origin: .retainedJSON,+ evidence: .unestablished)+ let presentation = try MCPResultAdapter.present(source, context: Self.protectedContext())+ #expect(presentation.evidence == .unestablished)+ #expect(presentation.errorCategory == .outcomeUncertain)+ #expect(presentation.recovery?.direction == .reconcileOriginalWrite)+ #expect(source.originalText == text)+ #expect(source.originalIsError == false)+ }+ }++ @Test func unknownHistoricCodeIsExplicitAndDoesNotPromiseReadRetrySafety() throws {+ let source = try Self.source(#"{"error":{"code":"FUTURE_UNKNOWN","message":"READ_TIMEOUT"}}"#,+ isError: true, origin: .retainedJSON)+ let presentation = try MCPResultAdapter.present(source, context: Self.context("query_tasks"))+ #expect(presentation.errorCategory == .unclassifiedHistorical)+ #expect(presentation.recovery?.direction != .retryIdenticalRead)+ }++ @Test func protectedRejectedSourceRetryDirectionRemainsAuthoritative() throws {+ let text = #"{"outcome":"rejected","accepted":false,"retryAction":"new_request_new_key","# ++ #""error":{"code":"REVISION_CONFLICT"}}"#+ let source = try Self.source(text, isError: true, origin: .retainedJSON)+ let presentation = try MCPResultAdapter.present(source, context: Self.protectedContext())+ #expect(presentation.errorCategory == .revisionConflict)+ #expect(presentation.recovery?.direction == .followSource)+ #expect(source.originalText == text)+ }++ @Test(arguments: MCPPresentationRejectionFixture.all)+ func establishedV1InternalRejectionsFollowOriginalRetryEvidence(+ fixture: MCPPresentationRejectionFixture+ ) throws {+ let text = Self.v1WriteEvidence(code: fixture.code, accepted: fixture.accepted)+ let source = try Self.source(text, isError: true, origin: .retainedJSON)+ let presentation = try MCPResultAdapter.present(source, context: Self.protectedContext())+ #expect(presentation.evidence == .established)+ #expect(presentation.errorCategory == .internalFailure)+ #expect(presentation.recovery?.direction == .followSource)+ guard case .protectedWrite(let key) = presentation.recovery?.mutation else {+ Issue.record("Lost original key from known rejected outcome")+ return+ }+ #expect(key == Self.key)+ #expect(source.originalText == text)+ #expect(source.originalIsError == true)+ #expect(source.document?.originalUTF8 == Data(text.utf8))+ }++ @Test func unknownV1RejectedCodeDoesNotAcquireSafeRetryFromKnownOutcome() throws {+ let text = Self.v1WriteEvidence(code: "FUTURE_UNKNOWN", accepted: true)+ let source = try Self.source(text, isError: true, origin: .retainedJSON)+ let presentation = try MCPResultAdapter.present(source, context: Self.protectedContext())+ #expect(presentation.errorCategory == .unclassifiedHistorical)+ #expect(presentation.recovery?.direction == .reconcileOriginalWrite)+ #expect(source.originalText == text)+ }++ @Test func uncertainV1InternalFailureOverridesNewKeyLookingCategory() throws {+ let text = Self.v1WriteEvidence(code: "INTERNAL_ERROR", accepted: true,+ outcome: "uncertain", retry: "reconcile")+ let source = try Self.source(text, isError: true, origin: .retainedJSON)+ let presentation = try MCPResultAdapter.present(source, context: Self.protectedContext())+ #expect(presentation.errorCategory == .outcomeUncertain)+ #expect(presentation.recovery?.direction == .reconcileOriginalWrite)+ #expect(source.originalText == text)+ }++ @Test func unestablishedV1KnownRejectionCannotGainFollowSourceRetry() throws {+ let text = Self.v1WriteEvidence(code: "INTERRUPTED_BEFORE_COMMIT", accepted: true)+ let source = try MCPResultAdapter.source(text: text, isError: true, origin: .retainedJSON,+ evidence: .unestablished)+ let presentation = try MCPResultAdapter.present(source, context: Self.protectedContext())+ #expect(presentation.evidence == .unestablished)+ #expect(presentation.errorCategory == .outcomeUncertain)+ #expect(presentation.recovery?.direction == .reconcileOriginalWrite)+ #expect(source.originalText == text)+ }++ @Test func readAndMaintenanceRecoveryDirectionsStaySeparate() throws {+ let source = try Self.source(#"{"error":{"code":"READ_TIMEOUT"}}"#, isError: true)+ #expect(try MCPResultAdapter.present(source, context: Self.context("query_tasks"))+ .recovery?.direction == .retryIdenticalRead)+ let expired = try Self.source(#"{"error":{"code":"QUERY_EXPIRED"}}"#, isError: true)+ #expect(try MCPResultAdapter.present(expired, context: Self.context("query_tasks"))+ .recovery?.direction == .restartRead)+ let maintenance = Self.context("reassign_duplicate_display_ids",+ failure: .init(category: .outcomeUncertain, diagnostic: "may have effects"),+ mutation: .unprotectedMaintenance(tool: "reassign_duplicate_display_ids"))+ let presentation = try MCPResultAdapter.present(source, context: maintenance)+ #expect(presentation.recovery?.direction == .reconcileMaintenance)+ guard case .unprotectedMaintenance(let tool) = presentation.recovery?.mutation else {+ Issue.record("Maintenance acquired an invented protected key")+ return+ }+ #expect(tool == "reassign_duplicate_display_ids")+ }++ @Test func presentationPropagatesOriginalCheckpointAndBoundaryTypedFailure() throws {+ let source = try Self.source("{}")+ #expect(throws: MCPJSONCheckpointFailure.cancelled) {+ try MCPResultAdapter.present(source, context: Self.context("query_tasks")) {+ throw MCPJSONCheckpointFailure.cancelled+ }+ }+ #expect(throws: MCPResultBoundaryError.resourceLimit) {+ try MCPResultAdapter.present(source, context: Self.context("query_tasks")) {+ throw MCPResultBoundaryError.resourceLimit+ }+ }+ }++ @Test func largePresentationTraversalChecksWorkerRepeatedly() throws {+ let records = (0..<2_000).map { "{\"taskId\":\"\(Self.numberedID($0))\"}" }+ let source = try Self.source("{\"results\":[" + records.joined(separator: ",") + "]}")+ let count = Mutex(0)+ #expect(throws: MCPJSONCheckpointFailure.cancelled) {+ try MCPResultAdapter.present(source, context: Self.context("query_tasks")) {+ if count.withLock({ $0 += 1; return $0 }) == 2 { throw MCPJSONCheckpointFailure.cancelled }+ }+ }+ #expect(count.withLock { $0 } == 2)+ }+}++@MainActor private extension MCPResultPresentationTests {+ static var taskID: String { "11111111-1111-1111-1111-111111111111" }+ static var projectID: String { "22222222-2222-2222-2222-222222222222" }+ static var otherID: String { "33333333-3333-3333-3333-333333333333" }+ static var key: MCPProtectedRecoveryKey { .init(tool: "update_task", idempotencyKey: "original-key") }++ static func numberedID(_ index: Int) -> String {+ "00000000-0000-0000-0000-" + String(format: "%012d", index)+ }++ static func source(_ text: String, isError: Bool? = nil,+ origin: MCPResultOrigin = .generatedJSON) throws -> MCPResultSource {+ try MCPResultAdapter.source(text: text, isError: isError, origin: origin, evidence: .established)+ }++ static func context(_ tool: String, failure: MCPResultFailure? = nil,+ mutation: MCPMutationRecoveryContext? = nil,+ positions: [MCPResultEntityPosition] = []) -> MCPResultContext {+ .init(tool: tool, semanticFailure: failure, mutationRecovery: mutation, entityPositions: positions)+ }++ static func protectedContext() -> MCPResultContext {+ context("update_task", mutation: .protectedWrite(key))+ }++ static func v1WriteEvidence(code: String, accepted: Bool, outcome: String = "rejected",+ retry: String = "new_request_new_key") -> String {+ // accepted=true records key binding; a validated terminal rejection still establishes no commit.+ let terminal = accepted && outcome == "rejected" ?+ #","completedAt":"2026-10-03T00:00:00Z","replayExpiresAt":"2026-10-10T00:00:00Z""# : ""+ return #"{"contractVersion":1,"tool":"update_task","idempotencyKey":"original-key","# ++ "\"outcome\":\"\(outcome)\",\"accepted\":\(accepted),\"retryAction\":\"\(retry)\"," ++ "\"error\":{\"code\":\"\(code)\",\"message\":\"Saved failure\"},\"unknown\":null" + terminal + "}"+ }++ static func links(_ presentation: MCPResultPresentation) -> [String] {+ presentation.links.map { "\($0.sourcePath)|\($0.entityType.rawValue)|\($0.entityId.uuidString)" }+ }++ static func signature(_ presentation: MCPResultPresentation) -> [String] {+ [presentation.evidence.rawValue, presentation.errorCategory?.rawValue ?? "absent",+ presentation.recovery?.direction.rawValue ?? "absent"] + links(presentation)+ }++ static func collisionInvariant(_ unknown: MCPJSONFixtureValue) throws -> Bool {+ let text = "{\"record\":{\"taskId\":\"\(taskID)\"},\"source\":" + (try unknown.json()) ++ ",\"presentation\":null,\"links\":[],\"errorCategory\":\"collision\"}"+ let source = try Self.source(text)+ let context = Self.context("update_task")+ let before = source.document?.originalUTF8+ let first = try MCPResultAdapter.present(source, context: context)+ let second = try MCPResultAdapter.present(source, context: context)+ return signature(first) == signature(second) && links(first) == ["/record|task|\(taskID)"] &&+ first.evidence == .established && first.errorCategory == nil && source.originalText == text &&+ source.document?.originalUTF8 == before+ }+}++#endif
diff --git a/Transit/TransitTests/MCPResultProviderIntegrationTests.swift b/Transit/TransitTests/MCPResultProviderIntegrationTests.swiftnew file mode 100644index 0000000..5a4dd7e--- /dev/null+++ b/Transit/TransitTests/MCPResultProviderIntegrationTests.swift@@ -0,0 +1,325 @@+#if os(macOS)+import Foundation+import SwiftData+import Testing+@testable import Transit++/// Consumers of real protected providers; coordinator policy remains owned by T2384.+@MainActor @Suite(.serialized)+struct MCPResultProviderIntegrationTests {+ @Test func savedReceiptReplayAfterEditAndDeletionUsesOriginalTextAndNewRPCID() async throws {+ let env = try MCPTestHelpers.makeEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let args: [String: Any] = ["name": " Original Project\n", "colorHex": "#112233",+ "description": "\nSaved description\n", "idempotencyKey": "replay-project-key"]+ let initial = try await MCPModernResultFixture.call(env, tool: "create_project", arguments: args, id: "first")+ let original = try MCPModernResultFixture.text(initial)+ let initialResult = try MCPModernResultFixture.assertSource(initial, id: .string("first"))+ let receipt = try #require(try env.context.fetch(FetchDescriptor<MCPWriteReceipt>()).first)+ let stored = try #require(receipt.resultJSON)+ #expect(original == stored)+ let request = receipt.requestJSON+ let expiry = receipt.expiresAt+ let completed = receipt.completedAt+ let receiptID = receipt.id+ let errorFlag = receipt.resultIsError+ let project = try #require(try env.context.fetch(FetchDescriptor<Project>()).first)+ project.name = "Edited after receipt"+ try env.context.save()+ let edited = try await MCPModernResultFixture.call(env, tool: "create_project", arguments: args, id: "edited")+ #expect(try MCPModernResultFixture.text(edited) == stored)+ let editedResult = try MCPModernResultFixture.assertSource(edited, id: .string("edited"))+ env.context.delete(project)+ try env.context.save()+ let deleted = try await MCPModernResultFixture.call(env, tool: "create_project", arguments: args, id: "deleted")+ #expect(try MCPModernResultFixture.text(deleted) == stored)+ let deletedResult = try MCPModernResultFixture.assertSource(deleted, id: .string("deleted"))+ for result in [initialResult, editedResult, deletedResult] {+ #expect(MCPResultEncoderFixtures.field("isError", in: result)+ == (errorFlag == true ? .boolean(true) : nil))+ }+ #expect(try env.context.fetchCount(FetchDescriptor<Project>()) == 0)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 1)+ #expect(receipt.id == receiptID)+ #expect(receipt.resultJSON == stored)+ #expect(receipt.resultIsError == errorFlag)+ #expect(receipt.requestJSON == request)+ #expect(receipt.expiresAt == expiry)+ #expect(receipt.completedAt == completed)+ }++ @Test func actualProtectedUpdateTrimClearAndCommentRevisionRemainSavedEvidence() async throws {+ let env = try MCPModernResultFixture.makeEnvWithReads()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let project = try env.projectService.createProject(+ name: "Fixture", description: "", gitRepo: nil, colorHex: "#112233")+ let create = try await MCPModernResultFixture.call(env, tool: "create_task", arguments: [+ "name": " First Task\n", "description": "\nCreate description\n", "type": "feature",+ "projectId": project.id.uuidString, "idempotencyKey": "normalize-create"+ ])+ _ = try MCPModernResultFixture.assertSource(create, id: .integer(1))+ let task = try #require(try env.context.fetch(FetchDescriptor<TransitTask>()).first)+ let update = try await MCPModernResultFixture.call(env, tool: "update_task", arguments: [+ "taskId": task.id.uuidString, "name": " Saved Task\n", "description": "\n Body\nwith newline \n",+ "expectedRevision": try MCPTestHelpers.readRevision(task, in: env.context),+ "idempotencyKey": "normalize-update"+ ], id: "update")+ let updateRecord = try savedRecord(update)+ #expect(task.name == "Saved Task")+ #expect(task.taskDescription == "Body\nwith newline")+ #expect(updateRecord["name"] as? String == task.name)+ #expect(updateRecord["description"] as? String == task.taskDescription)+ #expect(try updateRecord["revision"] as? String == MCPTestHelpers.readRevision(task, in: env.context))+ _ = try MCPModernResultFixture.assertSource(update, id: .string("update"))+ let beforeComment = try MCPTestHelpers.readRevision(task, in: env.context)+ let comment = try await MCPModernResultFixture.call(env, tool: "add_comment", arguments: [+ "taskId": task.id.uuidString, "content": " Comment\nsecond line \n", "authorName": " Agent \n",+ "idempotencyKey": "normalize-comment"+ ], id: "comment")+ let commentRecord = try savedRecord(comment)+ #expect(commentRecord["content"] as? String == "Comment\nsecond line")+ #expect(commentRecord["authorName"] as? String == "Agent")+ _ = try MCPModernResultFixture.assertSource(comment, id: .string("comment"))+ #expect(try MCPTestHelpers.readRevision(task, in: env.context) != beforeComment)+ let clear = try await MCPModernResultFixture.call(env, tool: "update_task", arguments: [+ "taskId": task.id.uuidString, "description": " \n\t ",+ "expectedRevision": try MCPTestHelpers.readRevision(task, in: env.context),+ "idempotencyKey": "normalize-clear"+ ], id: "clear")+ let cleared = try savedRecord(clear)+ #expect(task.taskDescription == nil)+ #expect(cleared.keys.contains("description"))+ #expect(cleared["description"] is NSNull)+ #expect(try cleared["revision"] as? String == MCPTestHelpers.readRevision(task, in: env.context))+ _ = try MCPModernResultFixture.assertSource(clear, id: .string("clear"))+ try await assertReadParity(env, task: task, project: project,+ savedRevision: #require(cleared["revision"] as? String))+ }++ @Test func dirtyUIContextIsUntouchedBySavedEvidenceAdapter() async throws {+ let env = try MCPTestHelpers.makeEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let response = await env.handler.handle(MCPTestHelpers.toolCallRequest(tool: "create_project", arguments: [+ "name": "Saved", "colorHex": "#112233", "idempotencyKey": "dirty-source-key"+ ]))+ let object = try #require(response)+ _ = try JSONEncoder().encode(object)+ let receipt = try #require(try env.context.fetch(FetchDescriptor<MCPWriteReceipt>()).first)+ let saved = try #require(receipt.resultJSON)+ let expiry = receipt.expiresAt+ let project = try #require(try env.context.fetch(FetchDescriptor<Project>()).first)+ project.name = "Unsaved UI edit"+ #expect(env.context.hasChanges)+ let source = try MCPResultAdapter.source(text: saved, isError: receipt.resultIsError == true ? true : nil,+ origin: .retainedJSON, evidence: .established)+ let fixed = MCPResultContext(tool: "create_project", semanticFailure: nil,+ mutationRecovery: .protectedWrite(.init(tool: "create_project", idempotencyKey: "dirty-source-key")),+ entityPositions: [.init(entityType: .project, sourcePath: "/record")])+ let presentation = try MCPResultAdapter.present(source, context: fixed)+ let bytes = try MCPResultEncoder.encode(source: source, presentation: presentation,+ id: .string("dirty-evidence"), metadata: nil)+ let modern = try MCPResultEncoderFixtures.result(bytes, id: .string("dirty-evidence"))+ #expect(try MCPResultEncoderFixtures.originalText(modern) == saved)+ #expect(try MCPResultEncoderFixtures.rawFragment(bytes,+ path: ["result", "structuredContent", "source", "payload"]) == Data(saved.utf8))+ #expect(env.context.hasChanges)+ #expect(project.name == "Unsaved UI edit")+ #expect(receipt.resultJSON == saved)+ #expect(receipt.expiresAt == expiry)+ #expect(presentation.links.first?.entityId == project.id)+ }++ @Test func seededHistoricalReceiptVariantsReplayWithoutRewritingEvidence() async throws {+ let env = try MCPTestHelpers.makeEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let args: [String: Any] = ["name": "History", "colorHex": "#112233", "idempotencyKey": "historical-key"]+ _ = await env.handler.handle(MCPTestHelpers.toolCallRequest(tool: "create_project", arguments: args))+ let receipt = try #require(try env.context.fetch(FetchDescriptor<MCPWriteReceipt>()).first)+ let expiry = receipt.expiresAt+ let request = receipt.requestJSON+ let original = try #require(receipt.resultJSON)+ try #require(original.last == "}")+ let variants = [+ #", "historical":{"presentation":null,"false":false,"adjacentNull":null,"n":-0.00E+0}"#,+ #", "historical":[false,null,{"unknown":true}],"source":"opaque historic field""#,+ #", "historical":null,"largeInteger":9007199254740993"#+ ]+ for (index, additions) in variants.enumerated() {+ // Add unknown members to a complete valid v1 receipt; never replace its known outcome fields.+ let seeded = String(original.dropLast()) + additions + "}"+ receipt.resultJSON = seeded+ try MCPWriteReceiptStore(context: env.context, scopeID: receipt.localScopeID).validate(receipt)+ try env.context.save()+ let id = "historical-" + String(index)+ let replay = try await MCPModernResultFixture.call(env, tool: "create_project", arguments: args, id: id)+ #expect(try MCPModernResultFixture.text(replay) == seeded)+ let result = try MCPModernResultFixture.assertSource(replay, id: .string(id))+ #expect(MCPResultEncoderFixtures.field("isError", in: result) == nil)+ #expect(receipt.resultJSON == seeded && receipt.resultIsError == false)+ #expect(receipt.expiresAt == expiry && receipt.requestJSON == request)+ }+ // A rejected historic receipt retains its complete rejection evidence and delivered true flag.+ let rejectedArgs: [String: Any] = ["name": "History", "colorHex": "#112233",+ "idempotencyKey": "historical-rejected"]+ _ = await env.handler.handle(MCPTestHelpers.toolCallRequest(tool: "create_project", arguments: rejectedArgs))+ let rejected = try #require(try env.context.fetch(FetchDescriptor<MCPWriteReceipt>())+ .first { $0.key == "historical-rejected" })+ try #require(rejected.stateRawValue == "rejected" && rejected.resultIsError == true)+ let rejectedOriginal = try #require(rejected.resultJSON)+ try #require(rejectedOriginal.last == "}")+ let rejectedExpiry = rejected.expiresAt+ let rejectedRequest = rejected.requestJSON+ let rejectedSeed = String(rejectedOriginal.dropLast()) + #", "historical":{"retryAction":null,"n":-0.00E+0}}"#+ rejected.resultJSON = rejectedSeed+ try MCPWriteReceiptStore(context: env.context, scopeID: rejected.localScopeID).validate(rejected)+ try env.context.save()+ let replay = try await MCPModernResultFixture.call(env, tool: "create_project",+ arguments: rejectedArgs, id: "rejected-history")+ #expect(try MCPModernResultFixture.text(replay) == rejectedSeed)+ let result = try MCPModernResultFixture.assertSource(replay, id: .string("rejected-history"))+ #expect(MCPResultEncoderFixtures.field("isError", in: result) == .boolean(true))+ #expect(rejected.resultJSON == rejectedSeed && rejected.resultIsError == true)+ #expect(rejected.expiresAt == rejectedExpiry && rejected.requestJSON == rejectedRequest)+ }++ @Test func missingHistoricReceiptFlagUsesExistingUncertaintyWithoutSourceBypass() async throws {+ // Receipt validation remains authoritative: unavailable flags and invalid payloads cannot be replayed.+ let invalidVariants: [(String?, Bool?)] = [(nil, nil), ("null", false),+ (#"{"unknown":1E+9999}"#, false), ("{unreadable retained evidence", false)]+ for (index, variant) in invalidVariants.enumerated() {+ let env = try MCPTestHelpers.makeEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let args: [String: Any] = ["name": "Unknown Evidence", "colorHex": "#112233",+ "idempotencyKey": "invalid-history-" + String(index)]+ _ = await env.handler.handle(MCPTestHelpers.toolCallRequest(tool: "create_project", arguments: args))+ let receipt = try #require(try env.context.fetch(FetchDescriptor<MCPWriteReceipt>()).first)+ let original = try #require(receipt.resultJSON)+ let saved = variant.0 ?? original+ let expiry = receipt.expiresAt+ let request = receipt.requestJSON+ receipt.resultJSON = saved+ receipt.resultIsError = variant.1+ try env.context.save()+ let id = "invalid-history-" + String(index)+ let response = try await MCPModernResultFixture.call(env, tool: "create_project", arguments: args, id: id)+ let text = try MCPModernResultFixture.text(response)+ #expect(text != saved && text.contains("OUTCOME_UNCERTAIN"))+ _ = try MCPModernResultFixture.assertSource(response, id: .string(id))+ #expect(receipt.resultJSON == saved && receipt.resultIsError == variant.1)+ #expect(receipt.expiresAt == expiry && receipt.requestJSON == request)+ }+ }++ @Test func actualProtectedPostcommitOuterFailurePreservesReceiptAndReplay() async throws {+ let env = try MCPTestHelpers.makeEnv()+ defer { try? FileManager.default.removeItem(at: env.sidecarDirectory) }+ let handler = env.handler+ let args: [String: Any] = ["name": " Post Commit\n", "colorHex": "#112233", "idempotencyKey": "postcommit-key"]+ let request = MCPTestHelpers.toolCallRequest(tool: "create_project", arguments: args)+ let fixed = MCPResultContext(tool: "create_project", semanticFailure: nil,+ mutationRecovery: .protectedWrite(.init(tool: "create_project", idempotencyKey: "postcommit-key")),+ entityPositions: [.init(entityType: .project, sourcePath: "/record")])+ let fallback = try MCPResultAdapter.source(text: #"{"error":{"code":"OUTCOME_UNKNOWN"}}"#,+ isError: true, origin: .generatedJSON, evidence: .unestablished)+ let calls = EncoderCount()+ let id = JSONRPCId.string("postcommit-rpc")+ let ready = try MCPResultProviderSelection.prepare(id: id, source: fallback, context: fixed, metadata: nil)+ let selected = try await MCPResultProviderSelection.mutation(id: id, context: fixed,+ metadata: nil, fallbackSource: fallback, encodeOutcome: { _, _, _ in+ calls.record(); throw OuterFailure.encoding+ },+ dispatch: { try await Self.protectedOutcome(handler, request: request, context: fixed) })+ guard case .reconciliation(let bytes) = selected else {+ Issue.record("Expected ready postcommit recovery bytes"); throw OuterFailure.encoding+ }+ #expect(bytes == ready)+ #expect(calls.count == 1)+ let result = try MCPResultEncoderFixtures.result(bytes, id: id)+ let structured = try MCPResultEncoderFixtures.structured(result)+ let presentation = MCPResultEncoderFixtures.field("presentation", in: structured)+ let recovery = MCPResultEncoderFixtures.field("recovery", in: presentation)+ #expect(MCPResultEncoderFixtures.field("idempotencyKey", in: recovery) == .string("postcommit-key"))+ let fresh = ModelContext(env.context.container)+ fresh.autosaveEnabled = false+ let project = try #require(try fresh.fetch(FetchDescriptor<Project>()).first)+ #expect(project.name == "Post Commit")+ let receipt = try #require(try fresh.fetch(FetchDescriptor<MCPWriteReceipt>()).first)+ #expect(receipt.stateRawValue == "committed")+ let stored = try #require(receipt.resultJSON)+ let expiry = receipt.expiresAt+ let replay = try await MCPModernResultFixture.call(env, tool: "create_project",+ arguments: args, id: "reconcile-new-id")+ #expect(try MCPModernResultFixture.text(replay) == stored)+ _ = try MCPModernResultFixture.assertSource(replay, id: .string("reconcile-new-id"))+ let after = ModelContext(env.context.container)+ after.autosaveEnabled = false+ let recovered = try #require(try after.fetch(FetchDescriptor<MCPWriteReceipt>()).first)+ #expect(recovered.resultJSON == stored)+ #expect(recovered.expiresAt == expiry)+ #expect(recovered.id == receipt.id)+ #expect(try after.fetchCount(FetchDescriptor<Project>()) == 1)+ }++}++extension MCPResultProviderIntegrationTests {+ private enum OuterFailure: Error { case encoding }+ private nonisolated final class EncoderCount: @unchecked Sendable {+ private let lock = NSLock()+ private var value = 0+ func record() { lock.lock(); defer { lock.unlock() }; value += 1 }+ var count: Int { lock.lock(); defer { lock.unlock() }; return value }+ }++ private func assertReadParity(_ env: MCPTestEnv, task: TransitTask, project: Project,+ savedRevision: String) async throws {+ project.name = "Relabeled Parent"+ try env.context.save()+ #expect(try MCPTestHelpers.readRevision(task, in: env.context) == savedRevision)+ for includeComments in [false, true] {+ let read = try await MCPModernResultFixture.call(env, tool: "query_tasks", arguments: [+ "taskIds": [task.id.uuidString], "detailLevel": "full", "includeComments": includeComments,+ "readPolicy": "cached", "limit": 100+ ], id: includeComments ? "with-comments" : "without-comments")+ let text = try MCPModernResultFixture.text(read)+ let payload = try MCPJSONDocument.parse(text).value+ guard case .array(let results) = MCPResultEncoderFixtures.field("results", in: payload) else {+ Issue.record("Missing full saved read records"); throw OuterFailure.encoding+ }+ let entry = try #require(results.first)+ let record = try #require(MCPResultEncoderFixtures.field("task", in: entry))+ #expect(MCPResultEncoderFixtures.field("taskId", in: record) == .string(task.id.uuidString))+ #expect(MCPResultEncoderFixtures.field("revision", in: record) == .string(savedRevision))+ #expect(MCPResultEncoderFixtures.field("projectName", in: record) == .string("Relabeled Parent"))+ if includeComments {+ guard case .array(let comments) = MCPResultEncoderFixtures.field("comments", in: record) else {+ Issue.record("Missing requested comment bodies"); throw OuterFailure.encoding+ }+ #expect(comments.count == 1)+ } else {+ #expect(MCPResultEncoderFixtures.field("comments", in: record) == nil)+ }+ _ = try MCPModernResultFixture.assertSource(read,+ id: .string(includeComments ? "with-comments" : "without-comments"))+ }+ }++ private static func protectedOutcome(_ handler: MCPToolHandler, request: JSONRPCRequest,+ context: MCPResultContext) async throws -> MCPResultProviderOutcome {+ let response = try #require(await handler.handle(request))+ let tool = try #require(response.result?.value as? MCPToolResult)+ let text = try #require(tool.content.first?.text)+ let source = try MCPResultAdapter.source(text: text, isError: tool.isError,+ origin: .retainedJSON, evidence: .established)+ return MCPResultProviderOutcome(source: source, context: context)+ }++ private func savedRecord(_ response: MCPHTTPTestResponse) throws -> [String: Any] {+ let text = try MCPModernResultFixture.text(response)+ let payload = try #require(JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])+ #expect(payload["outcome"] as? String == "committed")+ #expect(payload["accepted"] as? Bool == true)+ return try #require(payload["record"] as? [String: Any])+ }+}+#endif
diff --git a/Transit/TransitTests/MCPResultProviderSelectionTests.swift b/Transit/TransitTests/MCPResultProviderSelectionTests.swiftnew file mode 100644index 0000000..895bcd9--- /dev/null+++ b/Transit/TransitTests/MCPResultProviderSelectionTests.swift@@ -0,0 +1,245 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++/// Synthetic providers exercise common response selection without a second write engine.+nonisolated struct MCPResultProviderSelectionTests: Sendable {+ private enum Fault: Error { case preparation, afterEffect, encoding }++ private nonisolated final class Counts: @unchecked Sendable {+ private let lock = NSLock()+ private var values: [String: Int] = [:]+ func increment(_ name: String) { lock.lock(); defer { lock.unlock() }; values[name, default: 0] += 1 }+ func count(_ name: String) -> Int { lock.lock(); defer { lock.unlock() }; return values[name, default: 0] }+ }++ private func context(_ recovery: MCPMutationRecoveryContext? = nil) -> MCPResultContext {+ MCPResultContext(tool: "update_task", semanticFailure: nil,+ mutationRecovery: recovery ?? .protectedWrite(.init(tool: "update_task",+ idempotencyKey: "original-key")),+ entityPositions: [])+ }++ private func source(_ text: String, origin: MCPResultOrigin = .retainedJSON,+ isError: Bool? = false) throws -> MCPResultSource {+ try MCPResultAdapter.source(text: text, isError: isError, origin: origin, evidence: .established)+ }++ private func fallback() throws -> MCPResultSource {+ try source(#"{"error":{"code":"OUTCOME_UNKNOWN"}}"#, origin: .generatedJSON, isError: true)+ }++ private func bytes(_ selection: MCPResultResponseSelection, reconciliation: Bool = false) throws -> Data {+ switch selection {+ case .normal(let data): #expect(!reconciliation); return data+ case .reconciliation(let data): #expect(reconciliation); return data+ case .suppressed: Issue.record("Expected complete response, got suppression"); throw Fault.encoding+ }+ }++ private func object(_ data: Data) throws -> [String: Any] {+ try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+ }++ @Test func preparationFailureDispatchesNothing() async throws {+ let counts = Counts()+ do {+ _ = try await MCPResultProviderSelection.mutation(id: .string("prepare-rpc"), context: context(),+ metadata: nil, fallbackSource: fallback(), prepareFallback: { _, _, _, _ in throw Fault.preparation },+ dispatch: { counts.increment("dispatch"); throw Fault.afterEffect })+ Issue.record("Expected original preparation error")+ } catch Fault.preparation {}+ #expect(counts.count("dispatch") == 0)+ }++ @Test func postEffectEncodingFailureSelectsCompleteReadyBytesOnce() async throws {+ let counts = Counts()+ let fixed = context()+ let failed = try fallback()+ let id = JSONRPCId.string("new-rpc")+ let metadata = try MCPResultMetadata.make(document: MCPJSONDocument.parse(+ #"{"example.test/opaque":{"n":1E+9999,"missing":null}}"#))+ let ready = try MCPResultProviderSelection.prepare(id: id, source: failed, context: fixed, metadata: metadata)+ let selection = try await MCPResultProviderSelection.mutation(id: id, context: fixed,+ metadata: metadata, fallbackSource: failed,+ prepareFallback: { _, _, _, _ in counts.increment("prepare"); return ready },+ encodeOutcome: { _, _, _ in counts.increment("encode"); throw Fault.encoding },+ dispatch: {+ #expect(counts.count("prepare") == 1)+ counts.increment("effect")+ return MCPResultProviderOutcome(source: try self.source(#"{"accepted":true,"outcome":"committed"}"#),+ context: fixed)+ })+ #expect(try bytes(selection, reconciliation: true) == ready)+ #expect(counts.count("prepare") == 1)+ #expect(counts.count("effect") == 1)+ #expect(counts.count("encode") == 1)+ let wire = try #require(String(data: ready, encoding: .utf8))+ #expect(wire.contains(#""id":"new-rpc""#))+ #expect(wire.contains(#""idempotencyKey":"original-key""#))+ #expect(wire.contains(#""_meta":{"example.test/opaque":{"n":1E+9999,"missing":null}}"#))+ }++ @Test func providerFailureAfterEffectUsesPreparedReconciliation() async throws {+ let counts = Counts()+ let fixed = context()+ let failed = try fallback()+ let ready = try MCPResultProviderSelection.prepare(id: .integer(31), source: failed, context: fixed,+ metadata: nil)+ let selected = try await MCPResultProviderSelection.mutation(id: .integer(31), context: fixed,+ metadata: nil, fallbackSource: failed, encodeOutcome: { _, _, _ in+ counts.increment("encode"); throw Fault.encoding+ }, dispatch: { counts.increment("effect"); throw Fault.afterEffect })+ #expect(try bytes(selected, reconciliation: true) == ready)+ #expect(counts.count("effect") == 1)+ #expect(counts.count("encode") == 0)+ }++ @Test func cancellationSuppressesDeliveryWithoutReinterpretingEffect() async throws {+ let counts = Counts()+ let fixed = context()+ let retained = try source(#"{"outcome":"committed","accepted":true,"retryAction":null}"#)+ let selected = try await MCPResultProviderSelection.mutation(id: .string("cancel-rpc"), context: fixed,+ metadata: nil, fallbackSource: fallback(), shouldDeliver: { counts.count("effect") == 0 }, dispatch: {+ counts.increment("effect")+ return MCPResultProviderOutcome(source: retained, context: fixed)+ })+ if case .suppressed = selected {} else { Issue.record("Cancellation must suppress delivery") }+ #expect(counts.count("effect") == 1)+ #expect(retained.originalText == #"{"outcome":"committed","accepted":true,"retryAction":null}"#)+ #expect(retained.originalIsError == false)+ }++ @Test func historicalSourceAndOpaqueMetadataKeepExactBytesWithNewRPCID() async throws {+ let fixed = context()+ let text = #" {"unknown":{"presentation":null,"contractVersion":false},"#+ + #""retryAction":null,"n":-0.00E+0,"accepted":true} "#+ let retained = try source(text, isError: nil)+ let metadata = try MCPResultMetadata.make(document: MCPJSONDocument.parse(+ #" {"example.test/opaque":{"a":null,"n":1E+9999}} "#))+ let outcome = MCPResultProviderOutcome(source: retained, context: fixed)+ let expected = try MCPResultProviderSelection.encode(outcome: outcome, id: .string("replay-new-id"),+ metadata: metadata)+ let selection = try await MCPResultProviderSelection.mutation(id: .string("replay-new-id"), context: fixed,+ metadata: metadata, fallbackSource: fallback(), dispatch: { outcome })+ #expect(try bytes(selection) == expected)+ #expect(retained.originalText == text)+ #expect(retained.originalIsError == nil)+ let wire = try #require(String(data: expected, encoding: .utf8))+ #expect(wire.contains(#""payload":"# + text))+ #expect(wire.contains(#""_meta": {"example.test/opaque":{"a":null,"n":1E+9999}} "#))+ }++ @Test func forgedOutcomeRecoveryNeverReplacesOriginalIdentity() async throws {+ let fixed = context()+ let substitutions = [+ context(.protectedWrite(.init(tool: "update_task", idempotencyKey: "different-key"))),+ MCPResultContext(tool: "other_tool", semanticFailure: nil,+ mutationRecovery: fixed.mutationRecovery, entityPositions: []),+ context(.unprotectedMaintenance(tool: "update_task"))+ ]+ for substituted in substitutions {+ let counts = Counts()+ let failed = try fallback()+ let ready = try MCPResultProviderSelection.prepare(id: .integer(42), source: failed, context: fixed,+ metadata: nil)+ let selected = try await MCPResultProviderSelection.mutation(id: .integer(42), context: fixed,+ metadata: nil, fallbackSource: failed, encodeOutcome: { _, _, _ in+ counts.increment("encode"); throw Fault.encoding+ }, dispatch: { MCPResultProviderOutcome(source: try self.source("null"), context: substituted) })+ #expect(try bytes(selected, reconciliation: true) == ready)+ #expect(counts.count("encode") == 0)+ }+ }++ @Test func originalTextJSONAndUnreadableEvidenceNeverBecomeInventedOutcomes() async throws {+ let fixed = context()+ for (text, origin, flag) in [+ ("Plain original error", MCPResultOrigin.plainText, true),+ (#"{"error":{"unknown":null},"accepted":false}"#, .retainedJSON, false),+ ("{unreadable retained original", .retainedJSON, true)+ ] {+ let retained = try source(text, origin: origin, isError: flag)+ let outcome = MCPResultProviderOutcome(source: retained, context: fixed)+ let expected = try MCPResultProviderSelection.encode(outcome: outcome, id: .integer(8), metadata: nil)+ let selected = try await MCPResultProviderSelection.mutation(id: .integer(8), context: fixed,+ metadata: nil, fallbackSource: fallback(), dispatch: { outcome })+ #expect(try bytes(selected) == expected)+ #expect(retained.originalText == text)+ #expect(retained.originalIsError == flag)+ if retained.kind == .unreadable { #expect(retained.evidence == .unestablished) }+ }+ }++ @Test func cancellationBeforeDispatchSuppressesWithoutCallingProvider() async throws {+ let counts = Counts()+ let selected = try await MCPResultProviderSelection.mutation(id: .integer(9), context: context(),+ metadata: nil, fallbackSource: fallback(), shouldDeliver: { false }, dispatch: {+ counts.increment("dispatch"); throw Fault.afterEffect+ })+ if case .suppressed = selected {} else { Issue.record("Expected suppressed pre-dispatch delivery") }+ #expect(counts.count("dispatch") == 0)+ }++ @Test func cancellationAfterEffectAndEncodingFailureStillSuppressesDelivery() async throws {+ let counts = Counts()+ let fixed = context()+ let selected = try await MCPResultProviderSelection.mutation(id: .integer(10), context: fixed,+ metadata: nil, fallbackSource: fallback(), encodeOutcome: { _, _, _ in+ counts.increment("cancel"); throw Fault.encoding+ }, shouldDeliver: { counts.count("cancel") == 0 }, dispatch: {+ counts.increment("effect")+ return MCPResultProviderOutcome(source: try self.source("null"), context: fixed)+ })+ if case .suppressed = selected {} else { Issue.record("Expected suppressed post-effect failure response") }+ #expect(counts.count("effect") == 1)+ #expect(counts.count("cancel") == 1)+ }++ @Test func batchFallbackOmitsUnboundedItemIDAndKeepsOrderedOriginalKeys() async throws {+ let taskID = UUID(uuidString: "00000000-0000-0000-0000-000000000001")!+ let items = [+ MCPBatchRecoveryItem(index: 0, itemId: String(repeating: "huge", count: 100_000), operation: "update",+ originalKey: .init(tool: "update_task", idempotencyKey: "first-key"),+ targetTaskId: taskID),+ MCPBatchRecoveryItem(index: 1, itemId: nil, operation: "comment",+ originalKey: .init(tool: "add_comment", idempotencyKey: "second-key"),+ targetTaskId: nil)+ ]+ let fixed = MCPResultContext(tool: "mutate_tasks", semanticFailure: nil,+ mutationRecovery: .applicationBatch(items: items), entityPositions: [])+ let selected = try await MCPResultProviderSelection.mutation(id: .string("batch-id"), context: fixed,+ metadata: nil, fallbackSource: source(#"{"summary":"serialization_failed"}"#,+ origin: .generatedJSON, isError: true),+ encodeOutcome: { _, _, _ in throw Fault.encoding }, dispatch: {+ MCPResultProviderOutcome(source: try self.source(#"{"items":[],"summary":"all_committed"}"#),+ context: fixed)+ })+ let response = try object(bytes(selected, reconciliation: true))+ let result = try #require(response["result"] as? [String: Any])+ let structured = try #require(result["structuredContent"] as? [String: Any])+ let presentation = try #require(structured["presentation"] as? [String: Any])+ let recovery = try #require(presentation["recovery"] as? [String: Any])+ let retained = try #require(recovery["items"] as? [[String: Any]])+ try #require(retained.count == 2)+ #expect(retained[0]["itemId"] == nil)+ #expect(retained[0]["idempotencyKey"] as? String == "first-key")+ #expect(retained[1]["idempotencyKey"] as? String == "second-key")+ #expect(retained[0]["targetTaskId"] as? String == taskID.uuidString)+ #expect(retained[0]["index"] as? Int == 0)+ #expect(retained[1]["index"] as? Int == 1)+ }++ @Test func maintenanceFallbackHasNoInventedProtectedKey() async throws {+ let fixed = MCPResultContext(tool: "reassign_duplicate_display_ids", semanticFailure: nil,+ mutationRecovery: .unprotectedMaintenance(tool: "reassign_duplicate_display_ids"), entityPositions: [])+ let selected = try await MCPResultProviderSelection.mutation(id: .string("maintenance-id"), context: fixed,+ metadata: nil, fallbackSource: fallback(), dispatch: { throw Fault.afterEffect })+ let wire = try #require(String(data: bytes(selected, reconciliation: true), encoding: .utf8))+ #expect(wire.contains(#""direction":"reconcile_maintenance""#))+ #expect(wire.contains(#""tool":"reassign_duplicate_display_ids""#))+ #expect(!wire.contains("idempotencyKey"))+ }+}+#endif
diff --git a/Transit/TransitTests/MCPResultSchemaRecoveryTests.swift b/Transit/TransitTests/MCPResultSchemaRecoveryTests.swiftnew file mode 100644index 0000000..c531a63--- /dev/null+++ b/Transit/TransitTests/MCPResultSchemaRecoveryTests.swift@@ -0,0 +1,93 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor+@Suite(.serialized)+struct MCPResultSchemaRecoveryTests {+ @Test func receiptLikeBatchPreservesOriginalItemKeyReconciliation() throws {+ let mutation = MCPMutationRecoveryContext.applicationBatch(items: [MCPBatchRecoveryItem(+ index: 0, itemId: "saved item", operation: "update_task",+ originalKey: MCPProtectedRecoveryKey(tool: "update_task", idempotencyKey: "original-item-key"),+ targetTaskId: UUID(uuidString: "AA000000-0000-0000-0000-000000000001"))])+ try Self.exportAndCheck("batch", mutation: mutation, expected: .reconcileOriginalWrite)+ }++ @Test func receiptLikeMaintenanceReconcilesWithoutInventingKey() throws {+ try Self.exportAndCheck("maintenance", mutation: .unprotectedMaintenance(tool: "maintenance_fixture"),+ expected: .reconcileMaintenance)+ }++ @Test func protectedReceiptKeepsAuthoritativeFollowSourceDirection() throws {+ let key = MCPProtectedRecoveryKey(tool: "update_task", idempotencyKey: "original-protected-key")+ try Self.exportAndCheck("protected", mutation: .protectedWrite(key), expected: .followSource)+ }++ private static func exportAndCheck(_ name: String, mutation: MCPMutationRecoveryContext,+ expected: MCPResultRecoveryDirection) throws {+ let text = #"""+ {"contractVersion":1,"outcome":"rejected","accepted":false,+ "retryAction":"new_request_new_key","error":{"code":"INVALID_INPUT"},+ "unknown":{"flag":false,"value":null,"exponent":1E-9999}}+ """#+ let source = try MCPResultAdapter.source(text: text, isError: true,+ origin: .retainedJSON, evidence: .established)+ let context = MCPResultContext(tool: "recovery_fixture", semanticFailure: nil,+ mutationRecovery: mutation, entityPositions: [])+ let presentation = try MCPResultAdapter.present(source, context: context)+ let bytes = try MCPResultEncoder.encode(source: source, presentation: presentation,+ id: .string(name), metadata: nil)+ let descriptor = try MCPResultSchemas.descriptor(tool: "recovery_fixture",+ description: "Recovery source fixture")+ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("transit-mcp-schema-recovery-" + name + "-" + UUID().uuidString)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)+ try bytes.write(to: directory.appendingPathComponent("result.json"))+ try descriptor.outputSchema.originalUTF8.write(to: directory.appendingPathComponent("schema.json"))+ print("TRANSIT_MCP_SCHEMA_RECOVERY_EXPORT=" + name + " " + directory.path)+ #expect(presentation.evidence == .established)+ #expect(presentation.errorCategory == .invalidInput)+ let result = try MCPResultEncoderFixtures.result(bytes, id: .string(name))+ #expect(try MCPResultEncoderFixtures.originalText(result) == text)+ #expect(MCPResultEncoderFixtures.field("isError", in: result) == .boolean(true))+ #expect(try MCPResultEncoderFixtures.rawFragment(bytes,+ path: ["result", "structuredContent", "source", "payload"]) == Data(text.utf8))+ let structured = try MCPResultEncoderFixtures.structured(result)+ let recovery = MCPResultEncoderFixtures.field("recovery",+ in: MCPResultEncoderFixtures.field("presentation", in: structured))+ #expect(MCPResultEncoderFixtures.field("direction", in: recovery) == .string(expected.rawValue))+ try checkOriginalIdentity(mutation, recovery: recovery)+ #expect(presentation.recovery?.direction == expected)+ }++ private static func checkOriginalIdentity(_ mutation: MCPMutationRecoveryContext,+ recovery: MCPJSONValue?) throws {+ switch mutation {+ case .protectedWrite(let key):+ #expect(MCPResultEncoderFixtures.field("tool", in: recovery) == .string(key.tool))+ #expect(MCPResultEncoderFixtures.field("idempotencyKey", in: recovery) == .string(key.idempotencyKey))+ case .unprotectedMaintenance(let tool):+ #expect(MCPResultEncoderFixtures.field("tool", in: recovery) == .string(tool))+ #expect(MCPResultEncoderFixtures.field("idempotencyKey", in: recovery) == nil)+ case .applicationBatch(let items):+ guard case .array(let saved) = MCPResultEncoderFixtures.field("items", in: recovery) else {+ throw MCPResultEncoderFixtures.FixtureError.invalidFixture+ }+ #expect(saved.count == items.count)+ for (index, item) in items.enumerated() {+ let actual = try #require(saved.indices.contains(index) ? saved[index] : nil)+ #expect(try MCPResultEncoderFixtures.field("index", in: actual)+ == MCPJSONDocument.parse(String(item.index)).value)+ #expect(MCPResultEncoderFixtures.field("tool", in: actual) == .string(item.originalKey.tool))+ #expect(MCPResultEncoderFixtures.field("operation", in: actual) == .string(item.operation))+ #expect(MCPResultEncoderFixtures.field("idempotencyKey", in: actual)+ == .string(item.originalKey.idempotencyKey))+ #expect(MCPResultEncoderFixtures.field("itemId", in: actual) == item.itemId.map { .string($0) })+ #expect(MCPResultEncoderFixtures.field("targetTaskId", in: actual)+ == item.targetTaskId.map { .string($0.uuidString) })+ }+ }+ }+}+#endif
diff --git a/Transit/TransitTests/MCPResultSchemaTests.swift b/Transit/TransitTests/MCPResultSchemaTests.swiftnew file mode 100644index 0000000..6e0203e--- /dev/null+++ b/Transit/TransitTests/MCPResultSchemaTests.swift@@ -0,0 +1,242 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++/// Export is app-test-owned. The host validator reads it only after the runner exits.+@MainActor+@Suite(.serialized)+struct MCPResultSchemaTests {+ @Test func descriptorsAdvertiseSelfContainedDraft202012() throws {+ let descriptor = try MCPResultSchemas.descriptor(tool: "query_tasks", description: "Schema fixture")+ #expect(descriptor.tool == "query_tasks")+ #expect(!descriptor.description.isEmpty)+ #expect(MCPResultEncoderFixtures.field("$schema", in: descriptor.outputSchema.value)+ == .string("https://json-schema.org/draft/2020-12/schema"))+ }++ @Test func exportActualStructuredSourceAndPresentationCorpus() throws {+ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("transit-mcp-schema-" + UUID().uuidString, isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)+ print("TRANSIT_MCP_SCHEMA_EXPORT=" + directory.path)+ var fixtures = try Self.exportSources(to: directory)+ fixtures += try Self.exportCategories(to: directory)+ let names = ["query_tasks", "get_projects", "query_milestones", "create_task", "update_task",+ "update_task_status", "add_comment", "create_project", "create_milestone",+ "update_milestone", "delete_milestone", "synthetic_mutate_tasks"]+ var manifest: [String: Any] = ["exportVersion": 1, "status": "incomplete",+ "fixtures": fixtures, "schemas": [], "negativeCases": Self.negativeCases]+ let manifestURL = directory.appendingPathComponent("manifest.json")+ try Self.writeManifest(manifest, to: manifestURL)+ do {+ var schemas: [[String: String]] = []+ for name in names {+ let descriptor = try MCPResultSchemas.descriptor(tool: name, description: "Synthetic schema consumer")+ let filename = name + "-schema.json"+ try descriptor.outputSchema.originalUTF8.write(to: directory.appendingPathComponent(filename))+ schemas.append(["tool": name, "file": filename])+ }+ manifest["schemas"] = schemas+ manifest["status"] = "complete"+ try Self.writeManifest(manifest, to: manifestURL)+ } catch {+ manifest["failure"] = String(describing: error)+ try Self.writeManifest(manifest, to: manifestURL)+ throw error // Expected RED is the real descriptor boundary, not missing test types.+ }+ }++ private static func exportSources(to directory: URL) throws -> [[String: Any]] {+ var fixtures: [[String: Any]] = []+ for sample in Self.samples {+ let source = try MCPResultAdapter.source(text: sample.text, isError: sample.isError,+ origin: sample.origin, evidence: sample.evidence)+ let presentation = try MCPResultAdapter.present(source, context: Self.context(sample))+ if sample.name == "escaped_pointer" {+ #expect(presentation.links.count == 1)+ let link = try #require(presentation.links.first)+ #expect(link.sourcePath == "/records~1group/records~0group")+ #expect(link.entityId.uuidString == "AA000000-0000-0000-0000-000000000001")+ }+ if sample.name == "linked_record" { #expect(presentation.links.count == 2) }+ let bytes = try MCPResultEncoder.encode(source: source, presentation: presentation,+ id: .string(sample.name), metadata: nil)+ try bytes.write(to: directory.appendingPathComponent(sample.name + ".json"), options: .atomic)+ let result = try MCPResultEncoderFixtures.result(bytes, id: .string(sample.name))+ #expect(try MCPResultEncoderFixtures.originalText(result) == sample.text)+ #expect(MCPResultEncoderFixtures.field("isError", in: result)+ == sample.isError.map { .boolean($0) })+ fixtures.append(["name": sample.name, "file": sample.name + ".json"])+ }+ let fallbackSource = try MCPResultAdapter.source(+ text: #"{"summary":"serialization_failed","effectEvidence":"unestablished"}"#,+ isError: true, origin: .generatedJSON, evidence: .unestablished)+ let batchSample = try #require(Self.samples.first { $0.name == "batch" })+ let fallback = try MCPResultEncoder.prepareMutationFallback(+ id: .string("batch_fallback"), source: fallbackSource,+ context: Self.context(batchSample), metadata: nil)+ try fallback.write(to: directory.appendingPathComponent("batch_fallback.json"))+ fixtures.append(["name": "batch_fallback", "file": "batch_fallback.json"])+ return fixtures+ }++ private static func exportCategories(to directory: URL) throws -> [[String: Any]] {+ var fixtures: [[String: Any]] = []+ for category in Self.categories {+ let source = try MCPResultAdapter.source(text: "{}", isError: true,+ origin: .generatedJSON, evidence: .established)+ let context = MCPResultContext(tool: "query_tasks",+ semanticFailure: MCPResultFailure(category: category, diagnostic: nil),+ mutationRecovery: nil, entityPositions: [])+ let presentation = try MCPResultAdapter.present(source, context: context)+ #expect(presentation.errorCategory == category)+ let name = "category_" + category.rawValue+ let bytes = try MCPResultEncoder.encode(source: source, presentation: presentation,+ id: .string(name), metadata: nil)+ try bytes.write(to: directory.appendingPathComponent(name + ".json"))+ fixtures.append(["name": name, "file": name + ".json"])+ }+ return fixtures+ }++ private static func writeManifest(_ value: [String: Any], to url: URL) throws {+ try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]).write(to: url, options: .atomic)+ }++ private struct Sample {+ let name: String+ let text: String+ var isError: Bool?+ var origin: MCPResultOrigin = .generatedJSON+ var evidence: MCPResultEvidence = .established+ }++ private static let samples: [Sample] = [+ Sample(name: "object", text: "{}"),+ Sample(name: "array", text: "[{},null,false,1,\"saved\"]", isError: false),+ Sample(name: "null", text: "null"),+ Sample(name: "boolean", text: "false"),+ Sample(name: "string", text: "\"\""),+ Sample(name: "number", text: "1E-9999"),+ Sample(name: "huge_number", text: "99999999999999999999999999999999999999999999999999"),+ Sample(name: "historical", text: #"""+ {"contractVersion":99,"source":null,"presentation":false,"é":1,"é":2,+ "unknown":{"absentSibling":null,"flag":false,"decimal":1.234567890123456789,+ "exponent":1E9999},"outcome":"future","retryAction":null}+ """#,+ isError: false, origin: .retainedJSON, evidence: .unestablished),+ Sample(name: "retained_error", text: #"""+ {"code":"FUTURE_ERROR","message":"saved","accepted":true,"unknown":null}+ """#,+ isError: true, origin: .retainedJSON, evidence: .unestablished),+ Sample(name: "text", text: "Invalid input\n", isError: true, origin: .plainText),+ Sample(name: "empty_text", text: "", origin: .plainText),+ Sample(name: "unreadable", text: "{broken saved evidence", isError: true, origin: .retainedJSON),+ Sample(name: "retry_read", text: #"{"error":{"code":"READ_TIMEOUT"}}"#, isError: true),+ Sample(name: "restart_read", text: #"{"error":{"code":"QUERY_EXPIRED"}}"#, isError: true),+ Sample(name: "maintenance", text: "maintenance original evidence", isError: true,+ origin: .plainText, evidence: .unestablished),+ Sample(name: "follow_source", text: #"""+ {"contractVersion":1,"outcome":"rejected","accepted":false,+ "retryAction":"new_request_new_key","error":{"code":"INVALID_INPUT"}}+ """#,+ isError: true, origin: .retainedJSON),+ Sample(name: "linked_record", text: #"""+ {"record":{"taskId":"AA000000-0000-0000-0000-000000000001",+ "projectId":"BB000000-0000-0000-0000-000000000002","revision":"r1:saved","unknown":false}}+ """#),+ Sample(name: "escaped_pointer",+ text: #"{"records/group":{"records~group":"AA000000-0000-0000-0000-000000000001"}}"#),+ Sample(name: "batch", text: #"""+ {"contractVersion":1,"mode":"execute","atomicity":"per_item","summary":"stopped",+ "items":[{"index":0,"originalResult":{"logicalJSON":{"contractVersion":99,+ "outcome":"future","unknown":null},"text":" original saved bytes ","isError":false}},+ {"index":1,"originalResult":{"logicalJSON":null,"text":"null"}},{"index":2,+ "originalResult":{"logicalJSON":false,"text":"false","isError":null}},{"index":3,+ "originalResult":{"logicalJSON":{"error":"saved"},"text":"saved error","isError":true}}]}+ """#,+ isError: true, evidence: .unestablished)+ ]++ private static func context(_ sample: Sample) -> MCPResultContext {+ var positions: [MCPResultEntityPosition] = []+ var mutation: MCPMutationRecoveryContext?+ if sample.name == "linked_record" {+ positions = [MCPResultEntityPosition(entityType: .task, sourcePath: "/record"),+ MCPResultEntityPosition(entityType: .project, sourcePath: "/record/projectId")]+ }+ if sample.name == "escaped_pointer" {+ positions = [MCPResultEntityPosition(entityType: .task, sourcePath: "/records~1group/records~0group")]+ }+ if ["unreadable", "historical", "retained_error", "follow_source"].contains(sample.name) {+ mutation = .protectedWrite(MCPProtectedRecoveryKey(tool: "update_task", idempotencyKey: "original-key"))+ }+ if sample.name == "maintenance" { mutation = .unprotectedMaintenance(tool: "maintenance_fixture") }+ if sample.name == "batch" {+ mutation = .applicationBatch(items: [MCPBatchRecoveryItem(+ index: 0, itemId: "first", operation: "update_task",+ originalKey: MCPProtectedRecoveryKey(tool: "update_task", idempotencyKey: "original-batch-key"),+ targetTaskId: UUID(uuidString: "AA000000-0000-0000-0000-000000000001"))])+ }+ return MCPResultContext(tool: sample.name == "linked_record" ? "update_task" : "fixture",+ semanticFailure: nil, mutationRecovery: mutation, entityPositions: positions)+ }++ /// Host-only mutations start from actual emitted structuredContent, never a golden descriptor.+ private static let negativeCases: [[String: Any]] = [+ invalid("missing_version", "object", ["contractVersion"], remove: true),+ invalid("wrong_version", "object", ["contractVersion"], value: 2),+ invalid("boolean_version", "object", ["contractVersion"], value: true),+ invalid("missing_source", "object", ["source"], remove: true),+ invalid("missing_presentation", "object", ["presentation"], remove: true),+ invalid("unknown_kind", "object", ["source", "kind"], value: "future"),+ invalid("missing_kind", "object", ["source", "kind"], remove: true),+ invalid("json_missing_payload", "object", ["source", "payload"], remove: true),+ invalid("text_missing_payload", "text", ["source", "payload"], remove: true),+ invalid("text_nonstring_payload", "text", ["source", "payload"], value: NSNull()),+ invalid("unreadable_payload", "unreadable", ["source", "payload"], value: NSNull()),+ invalid("unreadable_established", "unreadable", ["presentation", "evidence"], value: "established"),+ invalid("missing_evidence", "object", ["presentation", "evidence"], remove: true),+ invalid("invalid_evidence", "object", ["presentation", "evidence"], value: "future"),+ invalid("missing_links", "object", ["presentation", "links"], remove: true),+ invalid("links_nonarray", "object", ["presentation", "links"], value: NSNull()),+ invalid("invalid_category", "object", ["presentation", "errorCategory"], value: "future"),+ invalid("category_null", "object", ["presentation", "errorCategory"], value: NSNull()),+ invalid("invalid_recovery", "object", ["presentation", "recovery"], value: ["direction": "fresh_key"]),+ invalid("recovery_missing_direction", "object", ["presentation", "recovery"], value: [String: String]()),+ invalid("recovery_invalid_tool", "unreadable", ["presentation", "recovery", "tool"], value: false),+ invalid("recovery_invalid_key", "unreadable", ["presentation", "recovery", "idempotencyKey"], value: NSNull()),+ invalid("invalid_entity", "linked_record", ["presentation", "links", "0", "entityType"], value: "milestone"),+ invalid("invalid_uuid", "linked_record", ["presentation", "links", "0", "entityId"], value: "T-1"),+ invalid("invalid_pointer", "linked_record", ["presentation", "links", "0", "sourcePath"], value: "record"),+ invalid("invalid_pointer_escape", "linked_record", ["presentation", "links", "0", "sourcePath"],+ value: "/record~2name"),+ invalid("guessed_available", "linked_record", ["presentation", "links", "0", "availability"],+ value: "available"),+ invalid("guessed_uri", "linked_record", ["presentation", "links", "0", "uri"], value: "transit://task/1"),+ invalid("missing_link_reason", "linked_record", ["presentation", "links", "0", "reason"], remove: true),+ invalid("wrong_link_reason", "linked_record", ["presentation", "links", "0", "reason"], value: "guess"),+ invalid("missing_entity_id", "linked_record", ["presentation", "links", "0", "entityId"], remove: true),+ invalid("missing_entity_type", "linked_record", ["presentation", "links", "0", "entityType"], remove: true),+ invalid("batch_negative_index", "batch", ["presentation", "recovery", "items", "0", "index"], value: -1),+ invalid("batch_boolean_index", "batch", ["presentation", "recovery", "items", "0", "index"], value: false),+ invalid("batch_fraction_index", "batch", ["presentation", "recovery", "items", "0", "index"], value: 0.5),+ invalid("batch_invalid_target", "batch", ["presentation", "recovery", "items", "0", "targetTaskId"],+ value: "T-1"),+ invalid("batch_missing_original_key", "batch", ["presentation", "recovery", "items", "0", "idempotencyKey"],+ remove: true)+ ]++ private static let categories: [MCPResultErrorCategory] = [+ .invalidInput, .notFound, .ambiguousIdentity, .revisionConflict, .keyConflict, .storageFailure,+ .incoherentCapture, .admissionBusy, .deadlineExceeded, .retentionCapacity, .invalidCursor,+ .expiredCursor, .serializationFailure, .outcomeUncertain, .unclassifiedHistorical, .internalFailure+ ]++ private static func invalid(_ name: String, _ base: String, _ path: [String],+ value: Any = NSNull(), remove: Bool = false) -> [String: Any] {+ ["name": name, "base": base, "path": path, "value": value, "remove": remove]+ }+}+#endif
diff --git a/Transit/TransitTests/MCPResultSourceTests.swift b/Transit/TransitTests/MCPResultSourceTests.swiftnew file mode 100644index 0000000..89b3d44--- /dev/null+++ b/Transit/TransitTests/MCPResultSourceTests.swift@@ -0,0 +1,114 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++@MainActor struct MCPResultSourceTests {+ @Test func generatedJSONRetainsUnknownFieldsNullAndAllErrorPresenceVariants() throws {+ let text = " \n{\"source\":{\"presentation\":true},\"unknown\":18446744073709551616,\"explicit\":null}\t"+ for isError: Bool? in [nil, false, true] {+ let source = try MCPResultAdapter.source(text: text, isError: isError, origin: .generatedJSON,+ evidence: .established)+ #expect(source.originalText == text)+ #expect(source.originalIsError == isError)+ #expect(source.kind == .json)+ #expect(source.evidence == .established)+ let document = try #require(source.document)+ #expect(document.originalUTF8 == Data(text.utf8))+ guard case .object(let members) = document.value else { Issue.record("Expected source object"); return }+ #expect(members.map(\.name) == ["source", "unknown", "explicit"])+ #expect(!members.contains { $0.name == "absent" })+ #expect(members.last?.value == .null)+ }+ }++ @Test(arguments: ["[]", "[false,1,null]", "null", "true", "9007199254740993", #""plain JSON string""#])+ func anyCompleteJSONValueIsAJSONSource(text: String) throws {+ let source = try MCPResultAdapter.source(text: text, isError: nil, origin: .generatedJSON,+ evidence: .established)+ #expect(source.kind == .json)+ #expect(source.document?.originalUTF8 == Data(text.utf8))+ #expect(source.originalText == text)+ }++ @Test func malformedGeneratedJSONFailsInsteadOfBecomingSuccessEvidence() {+ #expect(throws: MCPResultBoundaryError.invalidJSON) {+ try MCPResultAdapter.source(text: "{broken", isError: false, origin: .generatedJSON,+ evidence: .established)+ }+ }++ @Test func malformedRetainedJSONKeepsOriginalEvidenceAndDoesNotThrow() throws {+ for text in ["{broken", "", "{\"a\":1,\"a\":2}"] {+ for isError: Bool? in [nil, false, true] {+ let source = try MCPResultAdapter.source(text: text, isError: isError, origin: .retainedJSON,+ evidence: .established)+ #expect(source.originalText == text)+ #expect(source.originalIsError == isError)+ #expect(source.kind == .unreadable)+ #expect(source.evidence == .unestablished)+ #expect(source.document == nil)+ }+ }+ }++ @Test func parseableUnsupportedRetainedOutcomeKeepsItsWholePayload() throws {+ let text = #"{"contractVersion":999,"outcome":"future","accepted":null,"extra":1e999}"#+ let source = try MCPResultAdapter.source(text: text, isError: false, origin: .retainedJSON,+ evidence: .unestablished)+ #expect(source.kind == .json)+ #expect(source.evidence == .unestablished)+ #expect(source.originalIsError == false)+ #expect(source.originalText == text)+ #expect(source.document?.originalUTF8 == Data(text.utf8))+ }++ @Test func declaredPlainErrorNeverGuessesJSONOrUnreadableOrigin() throws {+ for text in ["", "null", "{broken", "Storage unavailable\nTry again"] {+ let source = try MCPResultAdapter.source(text: text, isError: true, origin: .plainText,+ evidence: .established)+ #expect(source.originalText == text)+ #expect(source.originalIsError == true)+ #expect(source.kind == .text)+ #expect(source.evidence == .established)+ #expect(source.document == nil)+ }+ }++ @Test func retainedOriginDoesNotSwallowWorkerCancellationAsUnreadableEvidence() {+ #expect(throws: MCPJSONCheckpointFailure.cancelled) {+ try MCPResultAdapter.source(text: "{\"a\":1}", isError: false, origin: .retainedJSON,+ evidence: .established) { throw MCPJSONCheckpointFailure.cancelled }+ }+ }++ @Test func generatedDepth33ThrowsDistinctResourceLimit() {+ let text = String(repeating: "[", count: 33) + "null" + String(repeating: "]", count: 33)+ #expect(throws: MCPResultBoundaryError.resourceLimit) {+ try MCPResultAdapter.source(text: text, isError: false, origin: .generatedJSON,+ evidence: .established)+ }+ }++ @Test func retainedDepth33PreservesRawEvidenceAndAllErrorPresenceVariants() throws {+ let text = " \n" + String(repeating: "[", count: 33) + "null" + String(repeating: "]", count: 33) + "\t"+ for isError: Bool? in [nil, false, true] {+ let source = try MCPResultAdapter.source(text: text, isError: isError, origin: .retainedJSON,+ evidence: .established)+ #expect(source.originalText == text)+ #expect(source.originalIsError == isError)+ #expect(source.kind == .unreadable)+ #expect(source.evidence == .unestablished)+ #expect(source.document == nil)+ }+ }++ @Test func retainedDepth33StillPropagatesOriginalWorkerCancellation() {+ let text = String(repeating: "[", count: 33) + "null" + String(repeating: "]", count: 33)+ #expect(throws: MCPJSONCheckpointFailure.cancelled) {+ try MCPResultAdapter.source(text: text, isError: true, origin: .retainedJSON,+ evidence: .established) { throw MCPJSONCheckpointFailure.cancelled }+ }+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReusableSnapshotPreparedOwnerTests.swift b/Transit/TransitTests/MCPReusableSnapshotPreparedOwnerTests.swiftnew file mode 100644index 0000000..b9e4228--- /dev/null+++ b/Transit/TransitTests/MCPReusableSnapshotPreparedOwnerTests.swift@@ -0,0 +1,344 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++/// RED preparation: successful retention is required; notImplemented is a behavioral failure.+@MainActor @Suite(.serialized)+struct MCPReusableSnapshotPreparedOwnerTests {+ @Test func sharedBaseMetadataAndPagesRemainOneOwnerAcrossAppend() async throws {+ let env = try Environment()+ await withOperation(env) { operation in+ let root = try self.create(env, operation: operation)+ let base = try env.store.domain.accounting(for: env.store.publicationStoreID)+ let metadata = try #require(root.owners.first?.metadataOwner)+ let left = try self.pages(metadata: metadata, operation: operation)+ let right = try self.pages(metadata: metadata, operation: operation)+ #expect(left[0] !== right[0] && left[0].metadataOwner === right[0].metadataOwner)+ let firstCursor = self.cursor()+ let secondCursor = self.cursor()+ let first = try self.append(env, root: root, pages: left, cursor: firstCursor, operation: operation)+ defer { try? env.store.rollback(first) }+ let second = try self.append(env, root: root, pages: right, cursor: secondCursor, operation: operation)+ defer { try? env.store.rollback(second) }+ let children = try [env.store.prepare(reservation: first), env.store.prepare(reservation: second)]+ let pending = try env.store.domain.accounting(for: env.store.publicationStoreID)+ let legacy = root.legacyBytes + left[1].source.originalText.utf8.count+ + right[1].source.originalText.utf8.count+ let expected = try self.measure(root.owners + left + right, legacyBytes: legacy, operation: operation)+ #expect(pending.pendingBytes == expected.charge.totalBytes - base.visibleBytes)+ let aggregate = try env.store.prepareAggregate(children, in: env.store.domain, operation: operation)+ try self.commit(aggregate, env: env)+ let accounting = try env.store.domain.accounting(for: env.store.publicationStoreID)+ #expect(accounting.visibleBytes == expected.charge.totalBytes && accounting.pendingBytes == 0)+ let pinned = try env.store.preparedResultView(for: root.id, now: .now)+ let firstPage = try env.store.preparedResultPage(for: firstCursor, now: .now)+ let secondPage = try env.store.preparedResultPage(for: secondCursor, now: .now)+ #expect(pinned.firstPage === root.owners[0] && firstPage.preparedPage === left[1])+ #expect(secondPage.preparedPage === right[1] && pinned.firstPage.metadataOwner === metadata)+ #expect(firstPage.preparedPage.metadataOwner === metadata+ && secondPage.preparedPage.metadataOwner === metadata)+ #expect(firstPage.page.root.capture.retentionDeadline == root.bundle.root.capture.retentionDeadline)+ }+ }++ @Test func equalBytesWithDistinctNewSiblingOwnersPublishBothChanges() async throws {+ let env = try Environment()+ await withOperation(env) { operation in+ let root = try self.create(env, operation: operation)+ let left = try self.pages(metadata: self.metadata(root.bundle.root), operation: operation)+ let right = try self.pages(metadata: self.metadata(root.bundle.root), operation: operation)+ #expect(left[0] !== right[0] && left[0].metadataOwner !== right[0].metadataOwner)+ #expect(left[0].fragment.encodedResult == right[0].fragment.encodedResult)+ let firstCursor = self.cursor()+ let secondCursor = self.cursor()+ let first = try self.append(env, root: root, pages: left, cursor: firstCursor, operation: operation)+ defer { try? env.store.rollback(first) }+ let second = try self.append(env, root: root, pages: right, cursor: secondCursor, operation: operation)+ defer { try? env.store.rollback(second) }+ let children = try [env.store.prepare(reservation: first), env.store.prepare(reservation: second)]+ let aggregate = try env.store.prepareAggregate(children, in: env.store.domain, operation: operation)+ try self.commit(aggregate, env: env)+ #expect(try env.store.preparedResultPage(for: firstCursor, now: .now).preparedPage === left[1])+ #expect(try env.store.preparedResultPage(for: secondCursor, now: .now).preparedPage === right[1])+ let legacy = root.legacyBytes + left[1].source.originalText.utf8.count+ + right[1].source.originalText.utf8.count+ let expected = try self.measure(root.owners + left + right, legacyBytes: legacy, operation: operation)+ let accounting = try env.store.domain.accounting(for: env.store.publicationStoreID)+ #expect(accounting.visibleBytes == expected.charge.totalBytes && accounting.pendingBytes == 0)+ }+ }++ @Test(arguments: ["page", "metadata"])+ func sharedNewSiblingOwnerRejectsWithoutMutatingReservations(kind: String) async throws {+ let env = try Environment()+ await withOperation(env) { operation in+ let root = try self.create(env, operation: operation)+ let newMetadata = try self.metadata(root.bundle.root)+ let left = try self.pages(metadata: newMetadata, operation: operation)+ let right = kind == "page" ? left : try self.pages(metadata: newMetadata, operation: operation)+ #expect(left[0].metadataOwner === right[0].metadataOwner)+ #expect((left[0] === right[0]) == (kind == "page"))+ let first = try self.append(env, root: root, pages: left, cursor: self.cursor(), operation: operation)+ defer { try? env.store.rollback(first) }+ let firstChild = try env.store.prepare(reservation: first)+ let beforeReserve = try env.store.domain.snapshot(for: env.store.publicationStoreID)+ let beforeAccounting = try env.store.domain.accounting(for: env.store.publicationStoreID)+ let second: RetentionReservation+ do {+ second = try self.append(env, root: root, pages: right, cursor: self.cursor(), operation: operation)+ } catch {+ #expect((error as? PublicationRejection) == .busy)+ let after = try env.store.domain.snapshot(for: env.store.publicationStoreID)+ #expect(after.version == beforeReserve.version && after.tokenVersion == beforeReserve.tokenVersion)+ #expect(ObjectIdentifier(after.index) == ObjectIdentifier(beforeReserve.index))+ #expect(after.allocatedTokenSets == beforeReserve.allocatedTokenSets)+ #expect(try env.store.domain.accounting(for: env.store.publicationStoreID) == beforeAccounting)+ #expect(env.store.domain.withLock { firstChild.validateLocked(in: env.store.domain) } == nil)+ return+ }+ defer { try? env.store.rollback(second) }+ let children = try [firstChild, env.store.prepare(reservation: second)]+ let before = try env.store.domain.snapshot(for: env.store.publicationStoreID)+ let accounting = try env.store.domain.accounting(for: env.store.publicationStoreID)+ #expect(throws: PublicationRejection.busy) {+ try env.store.prepareAggregate(children, in: env.store.domain, operation: operation)+ }+ let after = try env.store.domain.snapshot(for: env.store.publicationStoreID)+ #expect(after.version == before.version && after.tokenVersion == before.tokenVersion)+ #expect(ObjectIdentifier(after.index) == ObjectIdentifier(before.index))+ #expect(after.allocatedTokenSets == before.allocatedTokenSets)+ #expect(try env.store.domain.accounting(for: env.store.publicationStoreID) == accounting)+ for child in children {+ #expect(env.store.domain.withLock { child.validateLocked(in: env.store.domain) } == nil)+ }+ }+ }++ /// Cross-root owners also violate provenance; this does not isolate overlap-detection precedence.+ @Test func crossRootOwnerMisuseRejectsWithoutChangingPendingState() async throws {+ let env = try Environment()+ await withOperation(env) { operation in+ let firstRoot = try self.create(env, operation: operation)+ let secondRoot = try self.create(env, operation: operation)+ let shared = try self.pages(metadata: self.metadata(firstRoot.bundle.root), operation: operation)+ let first = try self.append(env, root: firstRoot, pages: shared,+ cursor: self.cursor(), operation: operation)+ defer { try? env.store.rollback(first) }+ let firstChild = try env.store.prepare(reservation: first)+ var before = try env.store.domain.snapshot(for: env.store.publicationStoreID)+ var accounting = try env.store.domain.accounting(for: env.store.publicationStoreID)+ var children = [firstChild]+ var unexpected: (any MCPPreparedPublication)?+ do {+ let second = try self.append(env, root: secondRoot, pages: shared,+ cursor: self.cursor(), operation: operation)+ defer { try? env.store.rollback(second) }+ children.append(try env.store.prepare(reservation: second))+ before = try env.store.domain.snapshot(for: env.store.publicationStoreID)+ accounting = try env.store.domain.accounting(for: env.store.publicationStoreID)+ do {+ unexpected = try env.store.prepareAggregate(children, in: env.store.domain, operation: operation)+ Issue.record("Cross-root owner misuse unexpectedly produced an aggregate")+ } catch {+ #expect(self.isOwnerMisuseRejection(error))+ }+ let after = try env.store.domain.snapshot(for: env.store.publicationStoreID)+ #expect(after.version == before.version && after.tokenVersion == before.tokenVersion)+ #expect(ObjectIdentifier(after.index) == ObjectIdentifier(before.index))+ #expect(after.allocatedTokenSets == before.allocatedTokenSets)+ #expect(try env.store.domain.accounting(for: env.store.publicationStoreID) == accounting)+ for child in children {+ #expect(env.store.domain.withLock { child.validateLocked(in: env.store.domain) } == nil)+ }+ if let unexpected {+ env.store.domain.withLock { unexpected.discardLocked(in: env.store.domain) }+ }+ } catch {+ #expect(self.isOwnerMisuseRejection(error))+ let after = try env.store.domain.snapshot(for: env.store.publicationStoreID)+ #expect(after.version == before.version && after.tokenVersion == before.tokenVersion)+ #expect(ObjectIdentifier(after.index) == ObjectIdentifier(before.index))+ #expect(after.allocatedTokenSets == before.allocatedTokenSets)+ #expect(try env.store.domain.accounting(for: env.store.publicationStoreID) == accounting)+ #expect(env.store.domain.withLock { firstChild.validateLocked(in: env.store.domain) } == nil)+ }+ }+ }++ @Test func firstOnlyAppendIsChargedAndDoesNotReplaceOriginalSummaryOwner() async throws {+ let env = try Environment()+ await withOperation(env) { operation in+ let root = try self.create(env, operation: operation)+ let added = try self.pages(metadata: self.metadata(root.bundle.root), operation: operation)[0]+ let reservation = try env.store.reservePreparedAppend(snapshotID: root.id, pages: [], cursors: [],+ preparedPages: [added], operation: operation, publicationDeadline: .now + operation.remainingBudget())+ defer { try? env.store.rollback(reservation) }+ try self.commit(env.store.prepare(reservation: reservation), env: env)+ let expected = try self.measure(root.owners + [added], legacyBytes: root.legacyBytes, operation: operation)+ #expect(try env.store.domain.accounting(for: env.store.publicationStoreID).visibleBytes+ == expected.charge.totalBytes)+ #expect(try env.store.preparedResultView(for: root.id, now: .now).firstPage === root.owners[0])+ }+ }++ @Test func retiringOneRootPreservesIndependentlyMeasuredSurvivorCharge() async throws {+ let env = try Environment()+ await withOperation(env) { operation in+ let earlier = try self.create(env, operation: operation)+ let later = try self.create(env, operation: operation)+ #expect(later.bundle.root.capture.retentionDeadline > earlier.bundle.root.capture.retentionDeadline)+ #expect(later.owners[0] !== earlier.owners[0])+ #expect(later.owners[0].metadataOwner !== earlier.owners[0].metadataOwner)+ env.retirement = Retirement(earlier: earlier, later: later)+ }+ let roots = try #require(env.retirement)+ env.store.domain.setTestingInstant(roots.earlier.bundle.root.capture.retentionDeadline)+ let surviving = try env.store.preparedResultView(for: roots.later.id,+ now: roots.earlier.bundle.root.capture.retentionDeadline)+ #expect(surviving.firstPage === roots.later.owners[0])+ let accounting = try env.store.domain.accounting(for: env.store.publicationStoreID)+ #expect(accounting.visibleEntries == 1 && accounting.visibleBytes == roots.later.measured.charge.totalBytes)+ #expect(accounting.pendingEntries == 0 && accounting.pendingBytes == 0)+ #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+ try env.store.preparedResultView(for: roots.earlier.id,+ now: roots.earlier.bundle.root.capture.retentionDeadline)+ }+ try env.store.invalidate()+ #expect(try env.store.domain.accounting(for: env.store.publicationStoreID).visibleBytes == 0)+ }+}++private extension MCPReusableSnapshotPreparedOwnerTests {+ struct Root {+ let bundle: EncodedViewBundle+ let owners: [MCPResultPreparedPage]+ let measured: MCPResultRetainedBundle+ let legacyBytes: Int+ var id: String { bundle.root.capture.metadata.snapshotId }+ }+ struct Retirement { let earlier: Root; let later: Root }++ @MainActor final class Environment {+ let fixture: MCPPortfolioSavedFixture+ let store: MCPReusableSnapshotStore+ let coordinator: MCPReadCoordinator+ var retirement: Retirement?+ init() throws {+ fixture = try MCPPortfolioSavedFixture()+ let domain = MCPReadPublicationDomain()+ store = try MCPReusableSnapshotStore(domain: domain)+ coordinator = MCPReadCoordinator(domain: domain)+ }+ }++ func isOwnerMisuseRejection(_ error: Error) -> Bool {+ (error as? MCPReusableSnapshotError) == .incompatible || (error as? PublicationRejection) == .busy+ }++ func cursor() -> String { MCPReusableSnapshotStoreTests().cursorToken() }++ func metadata(_ root: RetainedView) throws -> MCPResultPreparedMetadata {+ let read = try MCPPreparedToolRead(text: "{}", frozenMetadataBytes: root.frozenMetadataBytes)+ let value = try #require(try MCPResultProviderAdapters.metadata(result: read.result,+ frozenReadBytes: root.frozenMetadataBytes))+ return try MCPResultPreparation.metadata(value: value)+ }++ func pages(metadata: MCPResultPreparedMetadata, operation: MCPReadOperation) throws -> [MCPResultPreparedPage] {+ try [0, 1].map { number in+ try MCPResultPreparation.page(request: MCPResultPagePreparationRequest(text: "{\"page\":\(number)}",+ isError: false, origin: .generatedJSON, evidence: .established,+ context: MCPResultContext(tool: "query_tasks", semanticFailure: nil,+ mutationRecovery: nil, entityPositions: []), metadataOwner: metadata),+ checkpoint: { try MCPPortfolioReadEncoding.check(operation) })+ }+ }++ func measure(_ owners: [MCPResultPreparedPage], legacyBytes: Int,+ operation: MCPReadOperation) throws -> MCPResultRetainedBundle {+ try MCPResultPreparation.prepare(pages: owners, budget: MCPResultRetentionBudget(store: .reusable,+ originalCaptureIndexBytes: legacyBytes, visibleBytes: 0, pendingBytes: 0),+ checkpoint: { try MCPPortfolioReadEncoding.check(operation) })+ }++ func create(_ env: Environment, operation: MCPReadOperation) throws -> Root {+ let capture = try env.fixture.capture()+ let encoder = JSONEncoder()+ encoder.outputFormatting = .sortedKeys+ let bytes = try encoder.encode(capture.metadata)+ let capsule = MCPPreparedReadCapture(view: capture, frozenMetadataBytes: bytes)+ let captureBytes = try MCPPortfolioCaptureCharge.bytes(capsule, operation: operation)+ let initial = RetainedView(capture: capture, frozenMetadataBytes: bytes, window: MCPPortfolioFixture.window,+ initialRequest: .initial(window: MCPPortfolioFixture.window, limit: 1, project: nil, policy: .cached),+ firstPage: Data("{\"page\":0}".utf8))+ let owners = try pages(metadata: metadata(initial), operation: operation)+ let cursor = cursor()+ let continuation = Data(owners[1].source.originalText.utf8)+ let legacyBytes = try MCPResultRetentionAccounting.add(captureBytes,+ MCPResultRetentionAccounting.add(initial.firstPage.count, continuation.count))+ let budget = try env.store.preparedResultBudget(originalCaptureIndexBytes: legacyBytes, operation: operation)+ let measured = try MCPResultPreparation.prepare(pages: owners, budget: budget,+ checkpoint: { try MCPPortfolioReadEncoding.check(operation) })+ let root = RetainedView(capture: capture, frozenMetadataBytes: bytes, window: initial.window,+ initialRequest: initial.initialRequest, firstPage: initial.firstPage, preparedResultPage: owners[0])+ let bundle = EncodedViewBundle(root: root, pages: [continuation], cursors: [cursor],+ encodedCaptureByteCount: captureBytes, preparedResultBundle: measured)+ let reservation = try env.store.reservePreparedCreate(bundle: bundle, preparedResults: measured,+ operation: operation, publicationDeadline: .now + operation.remainingBudget())+ defer { try? env.store.rollback(reservation) }+ try commit(env.store.prepare(reservation: reservation), env: env)+ #expect(try env.store.preparedResultPage(for: cursor, now: .now).preparedPage === owners[1])+ return Root(bundle: bundle, owners: owners, measured: measured, legacyBytes: legacyBytes)+ }++ func append(_ env: Environment, root: Root, pages: [MCPResultPreparedPage], cursor: String,+ operation: MCPReadOperation) throws -> RetentionReservation {+ try env.store.reservePreparedAppend(snapshotID: root.id,+ pages: [Data(pages[1].source.originalText.utf8)], cursors: [cursor], preparedPages: pages,+ operation: operation, publicationDeadline: .now + operation.remainingBudget())+ }++ func commit(_ publication: any MCPPreparedPublication, env: Environment) throws {+ try MCPReusableSnapshotStoreTests().commit(publication, in: env.store.domain)+ }++ func withOperation(_ env: Environment,+ body: @escaping @MainActor @Sendable (MCPReadOperation) throws -> Void) async {+ let success = Data("finished".utf8)+ let (operations, offerOperation) = AsyncStream<MCPReadOperation>.makeStream()+ let (completion, finishBody) = AsyncStream<Void>.makeStream()+ let worker = Task {+ let response = await env.coordinator.execute(+ timeout: Data("timeout".utf8), busy: Data("busy".utf8)) { operation in+ offerOperation.yield(operation)+ offerOperation.finish()+ for await _ in completion { break }+ return PreparedReadResult(encodedResponse: success, publications: [],+ publicationErrors: PreencodedPublicationErrors(busy: Data(), expired: Data(), capacity: Data()))+ }+ offerOperation.finish()+ return response+ }+ // Execute assertions in the original test task, not the coordinator's detached worker.+ for await operation in operations {+ do {+ try body(operation)+ } catch {+ Issue.record("Required prepared-retention behavior failed: \(error)")+ }+ break+ }+ finishBody.yield(())+ finishBody.finish()+ let response = await worker.value+ #expect(response == success)+ let deadline = ContinuousClock.now.advanced(by: .seconds(8))+ while env.coordinator.unfinishedCount != 0 && ContinuousClock.now < deadline {+ await Task.detached { try? await Task.sleep(for: .milliseconds(25)) }.value+ }+ #expect(env.coordinator.unfinishedCount == 0)+ withExtendedLifetime(env.fixture) {}+ }+}+#endif
diff --git a/Transit/TransitTests/MCPReusableSnapshotStoreTests.swift b/Transit/TransitTests/MCPReusableSnapshotStoreTests.swiftnew file mode 100644index 0000000..57e3c90--- /dev/null+++ b/Transit/TransitTests/MCPReusableSnapshotStoreTests.swift@@ -0,0 +1,332 @@+#if os(macOS)+import Foundation+import Testing+@testable import Transit++/// Behavior-first coverage. Until task 7, operational scaffold throws are test failures,+/// not expected outcomes. Clock advances never sleep or extend the original capture.+@MainActor @Suite(.serialized)+struct MCPReusableSnapshotStoreTests {+ private let maxBytes = 16 * 1024 * 1024++ func cursorToken() -> String { "00000000-0000-8000-8000-" + UUID().uuidString.suffix(12) }++ func bundle(_ capture: CapturedReadView, id: String = UUID().uuidString,+ captureBytes: Int = 100, pages: [Data] = [], cursors: [String] = []) throws -> EncodedViewBundle {+ let metadata = ReadCaptureMetadata(asOf: capture.metadata.asOf, snapshotId: id,+ freshness: capture.metadata.freshness, read: capture.metadata.read)+ let copied = CapturedReadView(completeness: capture.completeness, captureScope: capture.captureScope,+ metadata: metadata, createdAt: capture.createdAt, retentionDeadline: capture.retentionDeadline,+ projects: capture.projects, tasks: capture.tasks, milestones: capture.milestones,+ comments: capture.comments)+ let encoder = JSONEncoder()+ encoder.outputFormatting = .sortedKeys+ let root = RetainedView(capture: copied, frozenMetadataBytes: try encoder.encode(metadata),+ window: MCPPortfolioFixture.window,+ initialRequest: .initial(window: MCPPortfolioFixture.window, limit: 1, project: nil, policy: .cached),+ firstPage: Data("original first page".utf8))+ return EncodedViewBundle(root: root, pages: pages, cursors: cursors,+ encodedCaptureByteCount: captureBytes)+ }++ func stage(_ bundle: EncodedViewBundle, store: MCPReusableSnapshotStore,+ deadline: ContinuousClock.Instant? = nil) throws -> any MCPPreparedPublication {+ let reservation = try store.reserveCreate(bundle: bundle,+ publicationDeadline: deadline ?? bundle.root.capture.retentionDeadline)+ return try store.prepare(reservation: reservation)+ }++ func commit(_ publication: any MCPPreparedPublication, in domain: MCPReadPublicationDomain) throws {+ try domain.withLock {+ if let rejection = publication.validateLocked(in: domain) { throw rejection }+ publication.commitLocked(in: domain)+ }+ }++ func metadataBytes(_ root: RetainedView) throws -> Data {+ let encoder = JSONEncoder()+ encoder.outputFormatting = .sortedKeys+ return try encoder.encode(root.capture.metadata)+ }++ @Test func privateReservationPublishesOnlyAtGateAndPreservesCapture() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ let candidate = try bundle(capture)+ let publication = try stage(candidate, store: store)+ #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+ try store.view(for: candidate.root.capture.metadata.snapshotId, now: capture.createdAt)+ }+ #expect(try domain.accounting(for: store.publicationStoreID).pendingEntries == 1)+ try commit(publication, in: domain)+ let root = try store.retainedView(for: candidate.root.capture.metadata.snapshotId, now: capture.createdAt)+ #expect(try metadataBytes(root) == metadataBytes(candidate.root))+ #expect(root.capture.retentionDeadline == capture.retentionDeadline)+ #expect(root.capture.captureScope == capture.captureScope)+ #expect(root.capture.tasks.map(\.revision) == capture.tasks.map(\.revision))+ #expect(root.capture.tasks.map(\.fullRecordWithoutCommentsJSON)+ == capture.tasks.map(\.fullRecordWithoutCommentsJSON))+ #expect(root.frozenMetadataBytes == candidate.root.frozenMetadataBytes)+ #expect(root.firstPage == candidate.root.firstPage)+ #expect(root.window.start == candidate.root.window.start && root.window.end == candidate.root.window.end)+ guard case .initial(_, let limit, _, let policy) = root.initialRequest else {+ Issue.record("Stored initial summary request changed branch")+ return+ }+ #expect(limit == 1 && policy == .cached)+ }++ @Test func eightViewsAreRetainedWithoutEvictionAndNinthFails() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ var ids: [String] = []+ for _ in 0..<8 {+ let candidate = try bundle(capture)+ try commit(stage(candidate, store: store), in: domain)+ ids.append(candidate.root.capture.metadata.snapshotId)+ }+ #expect(throws: PublicationRejection.capacity) { try stage(bundle(capture), store: store) }+ for id in ids { #expect(try store.view(for: id, now: capture.createdAt).metadata.snapshotId == id) }+ #expect(try domain.accounting(for: store.publicationStoreID).visibleEntries == 8)+ }++ @Test func pendingReservationsConsumeCapacityAndRollbackExactlyOnce() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ let candidate = try bundle(capture, captureBytes: maxBytes - 32)+ let reservation = try store.reserveCreate(bundle: candidate, publicationDeadline: capture.retentionDeadline)+ // First summary page is charged in addition to encoded capture, even without cursors.+ #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes+ == candidate.encodedCaptureByteCount + candidate.root.firstPage.count)+ #expect(throws: PublicationRejection.capacity) { try stage(bundle(capture, captureBytes: 33), store: store) }+ try store.rollback(reservation)+ try store.rollback(reservation)+ #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+ #expect(try domain.accounting(for: store.publicationStoreID).visibleEntries == 0)+ }++ @Test func captureFirstPageAndAllContinuationBytesShareSixteenMiBLimit() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ let page = Data(repeating: 7, count: 80)+ let firstPageBytes = Data("original first page".utf8).count+ let candidate = try bundle(capture, captureBytes: maxBytes - firstPageBytes - page.count,+ pages: [page], cursors: [cursorToken()])+ try commit(stage(candidate, store: store), in: domain)+ #expect(try domain.accounting(for: store.publicationStoreID).visibleBytes == maxBytes)+ #expect(throws: PublicationRejection.capacity) {+ try store.reserveAppend(snapshotID: candidate.root.capture.metadata.snapshotId,+ pages: [Data([1])], cursors: [cursorToken()], publicationDeadline: capture.retentionDeadline)+ }+ }++ @Test func appendChargesOnlyNewPagesAndReplaysFrozenRoot() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ let candidate = try bundle(capture)+ try commit(stage(candidate, store: store), in: domain)+ let initial = try domain.accounting(for: store.publicationStoreID)+ let cursor = cursorToken()+ let bytes = Data("frozen task page".utf8)+ let reservation = try store.reserveAppend(snapshotID: candidate.root.capture.metadata.snapshotId,+ pages: [bytes], cursors: [cursor], publicationDeadline: capture.retentionDeadline)+ let pending = try domain.accounting(for: store.publicationStoreID)+ #expect(pending.pendingEntries == 0 && pending.pendingBytes == bytes.count)+ try commit(store.prepare(reservation: reservation), in: domain)+ #expect(try domain.accounting(for: store.publicationStoreID).visibleBytes == initial.visibleBytes + bytes.count)+ let page = try store.page(for: cursor, now: capture.createdAt + .seconds(200))+ #expect(page.encodedPage == bytes)+ #expect(try metadataBytes(page.root) == metadataBytes(candidate.root))+ #expect(page.root.capture.retentionDeadline == capture.retentionDeadline)+ }++ @Test func originalFiveMinuteBoundaryExpiresRootAndPagesTogether() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ #expect(capture.createdAt.duration(to: capture.retentionDeadline) == .seconds(300))+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ let cursor = cursorToken()+ let candidate = try bundle(capture, pages: [Data([1])], cursors: [cursor])+ try commit(stage(candidate, store: store), in: domain)+ let before = capture.retentionDeadline - .nanoseconds(1)+ #expect(try store.page(for: cursor, now: before).root.capture.retentionDeadline == capture.retentionDeadline)+ domain.setTestingInstant(capture.retentionDeadline)+ #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+ try store.view(for: candidate.root.capture.metadata.snapshotId, now: capture.retentionDeadline)+ }+ #expect(throws: MCPReusableSnapshotError.invalidCursor) {+ try store.page(for: cursor, now: capture.retentionDeadline)+ }+ #expect(try domain.accounting(for: store.publicationStoreID).visibleBytes == 0)+ }++}++extension MCPReusableSnapshotStoreTests {+ @Test func aggregateTwoCreatesUsesOneSwapAndPreservesBoth() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ let first = try bundle(capture)+ let second = try bundle(capture)+ let version = try domain.snapshot(for: store.publicationStoreID).version+ let left = try stage(first, store: store)+ let right = try stage(second, store: store)+ let aggregate = try store.prepareAggregate([left, right], in: domain)+ #expect(try domain.accounting(for: store.publicationStoreID).pendingEntries == 2)+ domain.withLock { left.discardLocked(in: domain); right.discardLocked(in: domain) }+ #expect(try domain.accounting(for: store.publicationStoreID).pendingEntries == 2)+ try commit(aggregate, in: domain)+ #expect(try domain.snapshot(for: store.publicationStoreID).version == version + 1)+ for candidate in [first, second] {+ #expect(try store.view(for: candidate.root.capture.metadata.snapshotId,+ now: capture.createdAt).tasks.count == 9)+ }+ #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+ }++ @Test func aggregateTwoAppendsRetainsBothWithoutReplacingOriginal() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ let candidate = try bundle(capture)+ try commit(stage(candidate, store: store), in: domain)+ let cursors = [cursorToken(), cursorToken()]+ let pages = [Data([1, 2]), Data([3, 4, 5])]+ var publications: [any MCPPreparedPublication] = []+ for index in 0..<2 {+ let reservation = try store.reserveAppend(snapshotID: candidate.root.capture.metadata.snapshotId,+ pages: [pages[index]], cursors: [cursors[index]], publicationDeadline: capture.retentionDeadline)+ publications.append(try store.prepare(reservation: reservation))+ }+ let version = try domain.snapshot(for: store.publicationStoreID).version+ try commit(store.prepareAggregate(publications, in: domain), in: domain)+ #expect(try domain.snapshot(for: store.publicationStoreID).version == version + 1)+ for index in 0..<2 {+ #expect(try store.page(for: cursors[index], now: capture.createdAt).encodedPage == pages[index])+ }+ }++ @Test func staleCandidateCannotOverwriteConcurrentPublication() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ let winner = try bundle(capture)+ let loser = try bundle(capture)+ let first = try stage(winner, store: store)+ let stale = try stage(loser, store: store)+ try commit(first, in: domain)+ #expect(domain.withLock { stale.validateLocked(in: domain) } == .busy)+ domain.withLock { stale.discardLocked(in: domain); stale.discardLocked(in: domain) }+ #expect(try domain.accounting(for: store.publicationStoreID).pendingEntries == 0)+ #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+ try store.view(for: loser.root.capture.metadata.snapshotId, now: capture.createdAt)+ }+ #expect(try store.view(for: winner.root.capture.metadata.snapshotId, now: capture.createdAt).tasks.count == 9)+ }++ @Test func lifecycleInvalidatesPublishedRootAndPendingAppend() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ let candidate = try bundle(capture)+ try commit(stage(candidate, store: store), in: domain)+ let cursor = cursorToken()+ let append = try store.reserveAppend(snapshotID: candidate.root.capture.metadata.snapshotId,+ pages: [Data([1])], cursors: [cursor], publicationDeadline: capture.retentionDeadline)+ let publication = try store.prepare(reservation: append)+ try store.invalidate()+ #expect(domain.withLock { publication.validateLocked(in: domain) } != nil)+ domain.withLock { publication.discardLocked(in: domain) }+ #expect(throws: MCPReusableSnapshotError.invalidSnapshot) {+ try store.view(for: candidate.root.capture.metadata.snapshotId, now: capture.createdAt)+ }+ #expect(throws: MCPReusableSnapshotError.invalidCursor) { try store.page(for: cursor, now: capture.createdAt) }+ #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+ }++ @Test func expiryDuringPreparedAppendRejectsWithoutExtendingRoot() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ let candidate = try bundle(capture)+ try commit(stage(candidate, store: store), in: domain)+ let reservation = try store.reserveAppend(snapshotID: candidate.root.capture.metadata.snapshotId,+ pages: [Data([1])], cursors: [cursorToken()],+ publicationDeadline: capture.retentionDeadline + .seconds(10))+ let publication = try store.prepare(reservation: reservation)+ domain.setTestingInstant(capture.retentionDeadline)+ #expect(domain.withLock { publication.validateLocked(in: domain) } == .expired)+ domain.withLock { publication.discardLocked(in: domain) }+ #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+ }++ @Test func cursorTokensCannotCollideAcrossStores() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let first = try MCPReusableSnapshotStore(domain: domain)+ let second = try MCPReusableSnapshotStore(domain: domain)+ let cursor = cursorToken()+ let publication = try stage(bundle(capture, pages: [Data([1])], cursors: [cursor]), store: first)+ #expect(throws: PublicationRejection.busy) {+ try stage(bundle(capture, pages: [Data([2])], cursors: [cursor]), store: second)+ }+ domain.withLock { publication.discardLocked(in: domain) }+ #expect(try domain.accounting(for: second.publicationStoreID).pendingEntries == 0)+ }++ @Test func reservedAndPublishedCursorCollisionsAreRejected() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ let cursor = "00000000-0000-8000-8000-000000000001"+ let first = try stage(bundle(capture, pages: [Data([1])], cursors: [cursor]), store: store)+ #expect(throws: PublicationRejection.busy) {+ try stage(bundle(capture, pages: [Data([2])], cursors: [cursor]), store: store)+ }+ try commit(first, in: domain)+ #expect(throws: PublicationRejection.busy) {+ try stage(bundle(capture, pages: [Data([3])], cursors: [cursor]), store: store)+ }+ }++ @Test func malformedPagePairsAndSelectedQueryAreRejectedWithoutReservation() throws {+ let capture = try MCPPortfolioSavedFixture().capture()+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ #expect(throws: MCPReusableSnapshotError.incompatible) {+ try stage(bundle(capture, pages: [Data([1])], cursors: []), store: store)+ }+ let selected = CapturedReadView(completeness: .completePortfolio, captureScope: .selectedQuery,+ metadata: capture.metadata, createdAt: capture.createdAt, retentionDeadline: capture.retentionDeadline,+ projects: capture.projects, tasks: capture.tasks, milestones: capture.milestones,+ comments: capture.comments)+ #expect(throws: MCPReusableSnapshotError.incompatible) { try stage(bundle(selected), store: store) }+ #expect(try domain.accounting(for: store.publicationStoreID).pendingEntries == 0)+ }++ @Test func scopedViewDoesNotTurnIdentityClosureIntoPortfolioScope() throws {+ let fixture = try MCPPortfolioSavedFixture()+ let capture = try MCPReadCaptureBuilder(container: fixture.owner.container, fence: .actorOnlyTestFixture)+ .capture(ReadCaptureRequest(projectSelectors: [.id(MCPPortfolioFixture.populatedProjectID)],+ selection: .portfolio, completeness: .completePortfolio, includeComments: false))+ let domain = MCPReadPublicationDomain(testingInstant: capture.createdAt)+ let store = try MCPReusableSnapshotStore(domain: domain)+ let candidate = try bundle(capture)+ try commit(stage(candidate, store: store), in: domain)+ let retained = try store.view(for: candidate.root.capture.metadata.snapshotId, now: capture.createdAt)+ #expect(retained.captureScope == capture.captureScope)+ guard case .projects(let keys) = retained.captureScope else {+ Issue.record("Scoped retained view widened to portfolio")+ return+ }+ #expect(keys.count == 1)+ }+}++#endif
diff --git a/Transit/TransitTests/MCPServerBatchRequestTests.swift b/Transit/TransitTests/MCPServerBatchRequestTests.swiftindex 1a476e3..ade287f 100644--- a/Transit/TransitTests/MCPServerBatchRequestTests.swift+++ b/Transit/TransitTests/MCPServerBatchRequestTests.swift@@ -5,212 +5,150 @@ import SwiftData import Testing @testable import Transit -/// Regression tests for T-1834: the MCP Streamable HTTP endpoint advertises-/// protocol 2025-03-26, so POST bodies may be JSON-RPC request batches.-///-/// Before the fix, `MCPServer.decodeIncomingRequest` decoded only one-/// `JSONRPCRequest`. Every array therefore became a single -32600 response,-/// including valid batches and all-notification batches that require HTTP 202.+/// One modern request object per POST. Rejected arrays never execute any member;+/// separate ordered objects retain independent correlation and partial commits. @MainActor @Suite(.serialized) struct MCPServerBatchRequestTests {-- @Test func mixedRequestAndNotificationBatchReturnsOnlyRequestResponses() async throws {- let response = try await respond(body: """- [- {"jsonrpc":"2.0","id":1,"method":"ping"},- {"jsonrpc":"2.0","method":"ping"},- {"jsonrpc":"2.0","id":"missing","method":"unknown/method"}- ]- """)-- #expect(response.status == .ok)- #expect(response.contentType == "application/json")- let objects = try #require(response.json as? [[String: Any]])- #expect(objects.count == 2)- #expect(objects.contains { $0["id"] as? Int == 1 && $0["result"] != nil })- #expect(objects.contains { object in- object["id"] as? String == "missing"- && (object["error"] as? [String: Any])?["code"] as? Int- == JSONRPCErrorCode.methodNotFound- })+ @Test func rejectedArrayAndSequentialObjectsPreserveFirstCommit() async throws {+ let env = try MCPTestHelpers.makeEnv()+ let project = MCPTestHelpers.makeProject(in: env.context)+ try env.context.save()+ let first: [String: Any] = ["name": "First commit", "type": "bug", "projectId": project.id.uuidString,+ "idempotencyKey": "sequential-create"]+ var second = first+ second["name"] = "Must reject conflicting key"+ let firstBody = try MCPModernResultFixture.body(method: "tools/call", id: "first",+ parameters: ["name": "create_task", "arguments": first])+ let secondBody = try MCPModernResultFixture.body(method: "tools/call", id: 2,+ parameters: ["name": "create_task", "arguments": second])+ let rejected = try await respond(env.handler, body: "[\(firstBody),\(secondBody)]",+ method: "tools/call", tool: "create_task")+ try assertArrayRejection(rejected)+ #expect(try env.context.fetchCount(FetchDescriptor<TransitTask>()) == 0)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0)+ let committed = try await MCPModernResultFixture.respond(env, method: "tools/call", id: "first",+ parameters: ["name": "create_task", "arguments": first])+ let conflict = try await MCPModernResultFixture.respond(env, method: "tools/call", id: 2,+ parameters: ["name": "create_task", "arguments": second])+ let firstRPC = try #require(committed.json as? [String: Any])+ let secondRPC = try #require(conflict.json as? [String: Any])+ #expect(firstRPC["id"] as? String == "first" && secondRPC["id"] as? Int == 2)+ #expect(try MCPTestHelpers.decodeHTTPToolResult(firstRPC)["outcome"] as? String == "committed")+ let failed = try MCPTestHelpers.decodeHTTPToolResult(secondRPC)+ #expect(failed["outcome"] as? String == "rejected")+ #expect((failed["error"] as? [String: Any])?["code"] as? String == "IDEMPOTENCY_KEY_REUSED")+ #expect(try env.context.fetch(FetchDescriptor<TransitTask>()).map(\.name) == ["First commit"])+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 1) } - @Test func allNotificationBatchReturnsAcceptedWithNoBody() async throws {- let response = try await respond(body: """- [- {"jsonrpc":"2.0","method":"ping"},- {"jsonrpc":"2.0","method":"notifications/initialized"}- ]- """)-- #expect(response.status == .accepted)- #expect(response.body.isEmpty)+ @Test func allNotificationArrayIsRejectedAsOneInvalidEnvelope() async throws {+ try assertArrayRejection(try await respond(+ body: #"[{"jsonrpc":"2.0","method":"ping"},{"jsonrpc":"2.0","method":"notifications/initialized"}]"#)) } - @Test func toolCallNotificationIsDispatchedButGetsNoResponse() async throws {+ @Test func notificationMutationArrayHasZeroEffects() async throws { let env = try MCPTestHelpers.makeEnv() let project = MCPTestHelpers.makeProject(in: env.context)- let response = try await respond(handler: env.handler, body: """- [{- "jsonrpc":"2.0",- "method":"tools/call",- "params":{- "name":"create_task",- "arguments":{- "idempotencyKey":"batch-notification",- "name":"Notification task",- "type":"bug",- "projectId":"\(project.id.uuidString)"- }- }- }]- """)-- #expect(response.status == .accepted)- #expect(response.body.isEmpty)- let tasks = try env.context.fetch(FetchDescriptor<TransitTask>())- #expect(tasks.map(\.name) == ["Notification task"])+ let body = """+ [{"jsonrpc":"2.0","method":"tools/call","params":{"name":"create_task",\+ "arguments":{"idempotencyKey":"batch-notification","name":"Notification task","type":"bug",\+ "projectId":"\(project.id.uuidString)"},"_meta":\(try metadata())}}]+ """+ try assertArrayRejection(try await respond(env.handler, body: body, method: "tools/call", tool: "create_task"))+ #expect(try env.context.fetchCount(FetchDescriptor<TransitTask>()) == 0)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0) } - @Test func emptyBatchReturnsSingleInvalidRequestObject() async throws {- let response = try await respond(body: "[]")-- #expect(response.status == .ok)- let object = try #require(response.json as? [String: Any])- let error = try #require(object["error"] as? [String: Any])- #expect(error["code"] as? Int == JSONRPCErrorCode.invalidRequest)- #expect(object["id"] is NSNull)+ @Test func emptyArrayReturnsOneInvalidRequestWithoutFabricatedId() async throws {+ try assertArrayRejection(try await respond(body: "[]")) } - @Test func invalidBatchMembersEachProduceAnErrorResponse() async throws {- let response = try await respond(body: """- [- 17,- {"jsonrpc":"2.0","id":2,"method":"ping"},- {"jsonrpc":"2.0","id":false,"method":"ping"}- ]- """)-- #expect(response.status == .ok)- let objects = try #require(response.json as? [[String: Any]])- #expect(objects.count == 3)- #expect(objects.filter { object in- (object["error"] as? [String: Any])?["code"] as? Int- == JSONRPCErrorCode.invalidRequest- }.count == 2)- #expect(objects.contains { $0["id"] as? Int == 2 && $0["result"] != nil })+ @Test func invalidArrayMembersNeverProducePerMemberDispatch() async throws {+ try assertArrayRejection(try await respond(+ body: """+ [17,{"jsonrpc":"2.0","id":2,"method":"tools/list"},+ {"jsonrpc":"2.0","id":false,"method":"tools/list"}]+ """)) } - @Test func singleExplicitNullIdReturnsInvalidRequestWithNullId() async throws {- let response = try await respond(- body: #"{"jsonrpc":"2.0","id":null,"method":"ping"}"#- )-- #expect(response.status == .ok)- let object = try #require(response.json as? [String: Any])- let error = try #require(object["error"] as? [String: Any])- #expect(error["code"] as? Int == JSONRPCErrorCode.invalidRequest)- #expect(object["id"] is NSNull)- #expect(object["result"] == nil)+ @Test func singleExplicitNullIdReturnsInvalidRequestWithoutId() async throws {+ let env = try MCPTestHelpers.makeEnv()+ try assertNullRejection(try await MCPModernResultFixture.respond(env, method: "tools/list", id: NSNull())) } - @Test(arguments: [- "initialize", "ping", "tools/list", "tools/call",- "notifications/initialized", "unknown/method"- ])- func singleExplicitNullIdIsReturnedForEveryMethodPath(method: String) async throws {- let response = try await respond(- body: #"{"jsonrpc":"2.0","id":null,"method":"\#(method)"}"#- )-- #expect(response.status == .ok)- let object = try #require(response.json as? [String: Any])- let error = try #require(object["error"] as? [String: Any])- #expect(error["code"] as? Int == JSONRPCErrorCode.invalidRequest)- #expect(object["id"] is NSNull)- #expect(object["result"] == nil)+ @Test(arguments: ["initialize", "ping", "tools/list", "tools/call", "notifications/initialized", "unknown/method"])+ func singleNullIdRejectsBeforeAnyMethodPath(method: String) async throws {+ let env = try MCPTestHelpers.makeEnv()+ try assertNullRejection(try await MCPModernResultFixture.respond(env, method: method, id: NSNull()))+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0) } - @Test func batchExplicitNullIdIsInvalidWhileStringAndIntegerIdsRemainValid() async throws {- let response = try await respond(body: """- [- {"jsonrpc":"2.0","id":null,"method":"ping"},- {"jsonrpc":"2.0","id":7,"method":"ping"},- {"jsonrpc":"2.0","id":"request-1","method":"ping"},- {"jsonrpc":"2.0","method":"ping"}- ]- """)-- #expect(response.status == .ok)- let objects = try #require(response.json as? [[String: Any]])- #expect(objects.count == 3, "The omitted-id notification must have no response")-- let nullResponse = try #require(objects.first { $0["id"] is NSNull })- let nullError = try #require(nullResponse["error"] as? [String: Any])- #expect(nullError["code"] as? Int == JSONRPCErrorCode.invalidRequest)- #expect(nullResponse["result"] == nil)- #expect(objects.contains { $0["id"] as? Int == 7 && $0["result"] != nil })- #expect(objects.contains { $0["id"] as? String == "request-1" && $0["result"] != nil })+ @Test func mixedIdArrayRejectsWholeButSeparateReadableIdsCorrelate() async throws {+ try assertArrayRejection(try await respond(body:+ """+ [{"jsonrpc":"2.0","id":null,"method":"tools/list"},+ {"jsonrpc":"2.0","id":7,"method":"tools/list"},+ {"jsonrpc":"2.0","id":"request-1","method":"tools/list"}]+ """))+ let env = try MCPTestHelpers.makeEnv()+ for id in [7, "request-1"] as [Any] {+ let response = try await MCPModernResultFixture.respond(env, method: "tools/list", id: id)+ let object = try #require(response.json as? [String: Any])+ #expect(response.status == .ok && object["result"] != nil)+ let actualID = try #require(object["id"])+ let actualBytes = try JSONSerialization.data(withJSONObject: [actualID])+ let expectedBytes = try JSONSerialization.data(withJSONObject: [id])+ #expect(actualBytes == expectedBytes)+ } } - @Test func initializeInsideBatchIsRejectedWithoutRejectingOtherRequests() async throws {- let response = try await respond(body: """- [- {"jsonrpc":"2.0","id":1,"method":"initialize"},- {"jsonrpc":"2.0","id":2,"method":"ping"}- ]- """)-- #expect(response.status == .ok)- let objects = try #require(response.json as? [[String: Any]])- #expect(objects.count == 2)- let initializeResponse = try #require(objects.first { $0["id"] as? Int == 1 })- let error = try #require(initializeResponse["error"] as? [String: Any])- #expect(error["code"] as? Int == JSONRPCErrorCode.invalidRequest)- #expect(objects.contains { $0["id"] as? Int == 2 && $0["result"] != nil })+ @Test func initializeArrayRejectsWholeAndFollowingObjectStillWorks() async throws {+ try assertArrayRejection(try await respond(+ body: #"[{"jsonrpc":"2.0","id":1,"method":"initialize"},{"jsonrpc":"2.0","id":2,"method":"ping"}]"#))+ let env = try MCPTestHelpers.makeEnv()+ let response = try await MCPModernResultFixture.respond(env, method: "tools/list", id: 2)+ #expect(response.status == .ok && (response.json as? [String: Any])?["id"] as? Int == 2) } @Test func singleRequestStillReturnsAResponseObject() async throws {- let response = try await respond(- body: #"{"jsonrpc":"2.0","id":1,"method":"ping"}"#- )-- #expect(response.status == .ok)+ let env = try MCPTestHelpers.makeEnv()+ let response = try await MCPModernResultFixture.respond(env, method: "tools/list", id: 1) let object = try #require(response.json as? [String: Any])- #expect(object["id"] as? Int == 1)+ #expect(response.status == .ok && object["id"] as? Int == 1) #expect(object["result"] != nil) } @Test func unknownToolCallOverRouteReturnsInvalidParams() async throws {- let response = try await respond(- body: #"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"not_a_real_tool","arguments":{}}}"#- )-- #expect(response.status == .ok)+ let env = try MCPTestHelpers.makeEnv()+ let response = try await MCPModernResultFixture.respond(env, method: "tools/call", id: 1,+ parameters: ["name": "not_a_real_tool", "arguments": [:] as [String: Any]]) let object = try #require(response.json as? [String: Any])- let error = try #require(object["error"] as? [String: Any])- #expect(error["code"] as? Int == JSONRPCErrorCode.invalidParams)- #expect(error["message"] as? String == "Unknown tool: not_a_real_tool")+ #expect(response.status == .badRequest && object["id"] as? Int == 1)+ #expect((object["error"] as? [String: Any])?["code"] as? Int == JSONRPCErrorCode.invalidParams) } - // MARK: - Helpers-+ private func assertArrayRejection(_ response: MCPHTTPTestResponse) throws {+ #expect(response.status == .badRequest && response.contentType == "application/json")+ let object = try #require(response.json as? [String: Any])+ #expect((object["error"] as? [String: Any])?["code"] as? Int == JSONRPCErrorCode.invalidRequest)+ #expect(!object.keys.contains("id") && object["result"] == nil)+ }+ private func assertNullRejection(_ response: MCPHTTPTestResponse) throws { try assertArrayRejection(response) }+ private func metadata() throws -> String {+ let data = try JSONSerialization.data(withJSONObject: MCPModernResultFixture.meta)+ return try #require(String(data: data, encoding: .utf8))+ } private func respond(body: String) async throws -> MCPHTTPTestResponse { let env = try MCPTestHelpers.makeEnv()- return try await respond(handler: env.handler, body: body)+ return try await respond(env.handler, body: body) }-- private func respond(- handler: MCPToolHandler,- body: String- ) async throws -> MCPHTTPTestResponse {- try await MCPTestHelpers.respond(- handler: handler,- contentType: "application/json",- body: body,- loggerLabel: "mcp-batch-tests"- )+ private func respond(_ handler: MCPToolHandler, body: String, method: String = "tools/list",+ tool: String? = nil) async throws -> MCPHTTPTestResponse {+ var headers = [HTTPField(name: HTTPField.Name("Mcp-Method")!, value: method)]+ if let tool { headers.append(HTTPField(name: HTTPField.Name("Mcp-Name")!, value: tool)) }+ return try await MCPTestHelpers.respond(handler: handler, contentType: "application/json",+ accept: "application/json, text/event-stream", protocolVersion: "2026-07-28", orderedHeaders: headers,+ body: body, loggerLabel: "mcp-batch-tests") } }- #endif
diff --git a/Transit/TransitTests/MCPServerOriginValidationTests.swift b/Transit/TransitTests/MCPServerOriginValidationTests.swiftindex 6af6ed9..6837161 100644--- a/Transit/TransitTests/MCPServerOriginValidationTests.swift+++ b/Transit/TransitTests/MCPServerOriginValidationTests.swift@@ -55,6 +55,7 @@ struct MCPServerOriginValidationTests { // The state-changing tool must never have run. let tasks = try env.context.fetch(FetchDescriptor<TransitTask>()) #expect(tasks.isEmpty)+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 0) } @Test func httpAttackerOriginIsRejected() async throws {@@ -131,6 +132,7 @@ struct MCPServerOriginValidationTests { let tasks = try env.context.fetch(FetchDescriptor<TransitTask>()) #expect(tasks.count == 1) #expect(tasks.first?.name == "Origin test task")+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 1) } @Test func loopbackIPOriginIsAccepted() async throws {@@ -214,10 +216,16 @@ struct MCPServerOriginValidationTests { // MARK: - Helpers - private static let toolsListBody = #"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#+ private static let toolsListBody = """+ {"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{+ "io.modelcontextprotocol/protocolVersion":"2026-07-28",+ "io.modelcontextprotocol/clientCapabilities":{}}}}+ """ private static let createTaskBody = """- {"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_task",\+ {"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"_meta":{\+ "io.modelcontextprotocol/protocolVersion":"2026-07-28",\+ "io.modelcontextprotocol/clientCapabilities":{}},"name":"create_task",\ "arguments":{"project":"Transit","name":"Origin test task","type":"bug",\ "idempotencyKey":"origin-test"}}} """@@ -232,6 +240,10 @@ struct MCPServerOriginValidationTests { var headerFields = HTTPFields() headerFields[.contentType] = "application/json"+ headerFields[.accept] = "application/json, text/event-stream"+ headerFields[HTTPField.Name("MCP-Protocol-Version")!] = "2026-07-28"+ headerFields[HTTPField.Name("Mcp-Method")!] = body == Self.createTaskBody ? "tools/call" : "tools/list"+ if body == Self.createTaskBody { headerFields[HTTPField.Name("Mcp-Name")!] = "create_task" } if let origin { headerFields[.origin] = origin }@@ -259,7 +271,10 @@ struct MCPServerOriginValidationTests { version: .http1_1, method: .POST, uri: "/mcp",- headers: HTTPHeaders(headers)+ headers: HTTPHeaders(headers + [+ ("Accept", "application/json, text/event-stream"),+ ("MCP-Protocol-Version", "2026-07-28"), ("Mcp-Method", "tools/list")+ ]) ) let head = try HTTPRequest(http1Head, secure: false, splitCookie: false) return try await dispatch(responder: responder, head: head, body: body)@@ -272,16 +287,28 @@ struct MCPServerOriginValidationTests { ) async throws -> HTTPResponse.Status { let request = Request(head: head, body: RequestBody(buffer: ByteBuffer(string: body))) - let channel = EmbeddedChannel()- defer { _ = try? channel.finish() }- let context = MCPRequestContext(- source: ApplicationRequestContextSource(- channel: channel, logger: Logger(label: "mcp-origin-tests")- )- )-- let response = try await responder.respond(to: request, context: context)- return response.status+ let loop = NIOAsyncTestingEventLoop()+ var ownedChannel: NIOAsyncTestingChannel?+ do {+ let channel = try await NIOAsyncTestingChannel(loop: loop) { _ in }+ ownedChannel = channel+ let context = MCPRequestContext(source: ApplicationRequestContextSource(+ channel: channel, logger: Logger(label: "mcp-origin-tests")))+ let response = try await responder.respond(to: request, context: context)+ let leftovers = try await channel.finish(acceptAlreadyClosed: true)+ #expect(leftovers.isClean)+ await loop.shutdownGracefully()+ return response.status+ } catch {+ if let channel = ownedChannel {+ do {+ let leftovers = try await channel.finish(acceptAlreadyClosed: true)+ #expect(leftovers.isClean)+ } catch { Issue.record("Origin fixture channel cleanup failed: \(error)") }+ }+ await loop.shutdownGracefully()+ throw error+ } } }
diff --git a/Transit/TransitTests/MCPServerRouteTests.swift b/Transit/TransitTests/MCPServerRouteTests.swiftindex 959948d..9514a33 100644--- a/Transit/TransitTests/MCPServerRouteTests.swift+++ b/Transit/TransitTests/MCPServerRouteTests.swift@@ -4,190 +4,130 @@ import HTTPTypes import Testing @testable import Transit -/// Regression tests for the MCP Streamable HTTP endpoint routes.-///-/// MCP 2025-03-26 permits GET to open an SSE listening stream when the client-/// accepts `text/event-stream`. A GET without that required negotiation remains-/// unsupported, while POST dispatch, origin validation, and unrelated routes-/// keep their existing behavior.+/// Latest-only POST negotiation; no GET SSE/session compatibility. @MainActor @Suite(.serialized) struct MCPServerRouteTests {-- @Test func getMcpWithoutEventStreamAcceptReturnsMethodNotAllowed() async throws {+ @Test(arguments: ["GET", "DELETE", "HEAD", "OPTIONS"])+ func allLegacyListeningMethodsRejectEvenWithSessionAndSSE(method: String) async throws { let env = try MCPTestHelpers.makeEnv()- let response = try await respond(- handler: env.handler,- method: .get,- path: "/mcp"- )-+ let verb = try #require(HTTPRequest.Method(rawValue: method))+ let response = try await MCPModernResultFixture.transport(handler: env.handler,+ method: verb, accept: "text/event-stream",+ orderedHeaders: [HTTPField(name: .mcpSessionID, value: "obsolete")], loggerLabel: "subscription-method") #expect(response.status == .methodNotAllowed) #expect(response.allow == "POST")+ #expect(response.sessionID == nil)+ #expect(env.handler.activeToolListChangeStreamCount == 0) } - @Test func eventStreamAcceptParsingRequiresExactPositiveQualityMediaRange() {- #expect(MCPServer.acceptsEventStream("text/event-stream"))- #expect(MCPServer.acceptsEventStream(- "application/json, TEXT/EVENT-STREAM; charset=utf-8; q=0.5"- ))- #expect(MCPServer.acceptsEventStream(- "text/event-stream;q=0, text/event-stream;q=0.001"- ))-- #expect(!MCPServer.acceptsEventStream(nil))- #expect(!MCPServer.acceptsEventStream("application/x-text/event-stream"))- #expect(!MCPServer.acceptsEventStream("text/event-streaming"))- #expect(!MCPServer.acceptsEventStream("text/event-stream;q=0"))- #expect(!MCPServer.acceptsEventStream("text/event-stream;q=1.1"))- #expect(!MCPServer.acceptsEventStream("text/event-stream;q=.5"))- #expect(!MCPServer.acceptsEventStream("text/event-stream;note=\"a,b\";q=0"))- }-- @Test func getMcpRejectsEventStreamWithZeroQuality() async throws {+ @Test func unrelatedPathIsStillNotFoundAndOriginPrecedesMethodRejection() async throws { let env = try MCPTestHelpers.makeEnv()- let response = try await respond(- handler: env.handler,- method: .get,- path: "/mcp",- accept: "application/json, text/event-stream;q=0"- )-- #expect(response.status == .methodNotAllowed)- #expect(response.allow == "POST")+ let unrelated = try await MCPModernResultFixture.transport(handler: env.handler, method: .get,+ path: "/not-mcp", loggerLabel: "subscription-unrelated")+ #expect(unrelated.status == .notFound)+ let forbidden = try await MCPModernResultFixture.transport(handler: env.handler, method: .get,+ origin: "https://evil.example.com", loggerLabel: "subscription-origin")+ #expect(forbidden.status == .forbidden)+ #expect(forbidden.body == Data("Forbidden".utf8))+ #expect(forbidden.json == nil && forbidden.sessionID == nil)+ #expect(env.handler.activeToolListChangeStreamCount == 0) } - @Test func getMcpRejectsEventStreamMediaTypeSuperstring() async throws {+ @Test func modernPOSTSubscriptionRequiresSSEAccept() async throws { let env = try MCPTestHelpers.makeEnv()- let response = try await respond(- handler: env.handler,- method: .get,- path: "/mcp",- accept: "application/x-text/event-stream"- )-- #expect(response.status == .methodNotAllowed)- #expect(response.allow == "POST")- }-- @Test func getMcpWithEventStreamAcceptRequiresSession() async throws {- let env = try MCPTestHelpers.makeEnv()- let response = try await respond(- handler: env.handler,- method: .get,- path: "/mcp",- accept: "text/event-stream; charset=utf-8; q=0.5"- )-- #expect(response.status == .badRequest)+ let response = try await rejected(env, accept: "application/json")+ #expect(response.status == .notAcceptable)+ #expect(env.handler.activeToolListChangeStreamCount == 0) } - @Test func getMcpRejectsUnknownSession() async throws {+ @Test(arguments: ["application/x-text/event-stream", "text/event-stream;q=0", "text/event-streaming"])+ func unacceptableSSEMediaRangesNeverRegister(accept: String) async throws { let env = try MCPTestHelpers.makeEnv()- let response = try await respond(- handler: env.handler,- method: .get,- path: "/mcp",- accept: "text/event-stream",- sessionID: "unknown-session"- )-- #expect(response.status == .notFound)+ let response = try await rejected(env, accept: accept)+ #expect(response.status == .notAcceptable)+ #expect(env.handler.activeToolListChangeStreamCount == 0) } - @Test func postMcpStillDispatchesNormally() async throws {+ @Test(arguments: [0, 1, 2, 3, 4, 5, 6]) func malformedModernSubscriptionDoesNotRegister(variant: Int) async throws { let env = try MCPTestHelpers.makeEnv()- let response = try await respond(- handler: env.handler,- method: .post,- path: "/mcp",- body: #"{"jsonrpc":"2.0","id":1,"method":"ping"}"#- )-- #expect(response.status == .ok)- }-- @Test func getMcpStillValidatesUntrustedOrigins() async throws {- let env = try MCPTestHelpers.makeEnv()- let response = try await respond(- handler: env.handler,- method: .get,- path: "/mcp",- origin: "https://evil.example.com"- )-- #expect(response.status == .forbidden)- }-- @Test func getMcpStillValidatesNonLoopbackHost() async throws {- let env = try MCPTestHelpers.makeEnv()- let response = try await respond(- handler: env.handler,- method: .get,- path: "/mcp",- host: "rebind.example.com:3141"- )-- #expect(response.status == .forbidden)+ let valid = try MCPModernResultFixture.body(method: "subscriptions/listen",+ parameters: ["notifications": ["toolsListChanged": true]])+ var body = valid+ var version: String? = "2026-07-28"+ var mirrored = "subscriptions/listen"+ switch variant {+ case 0:+ var json = try #require(try JSONSerialization.jsonObject(with: Data(valid.utf8)) as? [String: Any])+ json.removeValue(forKey: "id")+ body = try #require(String(data: try JSONSerialization.data(withJSONObject: json), encoding: .utf8))+ case 1:+ body = try MCPModernResultFixture.body(method: "subscriptions/listen", id: NSNull(),+ parameters: ["notifications": [:]])+ case 2: version = nil+ case 3: mirrored = "tools/list"+ case 4:+ body = try MCPModernResultFixture.body(method: "subscriptions/listen", parameters: ["notifications": []])+ case 5:+ body = try MCPModernResultFixture.body(method: "subscriptions/listen",+ parameters: ["notifications": ["toolsListChanged": "true"]])+ default:+ body = #"{"jsonrpc":"2.0","id":1,"method":"subscriptions/listen","params":{"notifications":{}}}"#+ }+ let response = try await rejected(env, body: body, version: version, mirrored: mirrored)+ #expect(response.status == .badRequest)+ #expect(response.sessionID == nil)+ #expect(env.handler.activeToolListChangeStreamCount == 0) } - @Test func headMcpRemainsNotFoundWithoutAutoGeneratedHeadRoute() async throws {+ @Test func invalidKnownResourceFilterRejectsWhileUnknownExtensionsRemainValid() async throws { let env = try MCPTestHelpers.makeEnv()- let response = try await respond(- handler: env.handler,- method: .head,- path: "/mcp"- )-- #expect(response.status == .notFound)- #expect(response.allow == nil)+ let invalid = try MCPModernResultFixture.body(method: "subscriptions/listen",+ parameters: ["notifications": ["resourceSubscriptions": [1]]])+ let response = try await rejected(env, body: invalid)+ #expect(response.status == .badRequest)+ #expect(env.handler.activeToolListChangeStreamCount == 0)+ let stream = try await MCPSubscriptionFixture.open(handler: env.handler,+ filters: ["unknown": ["nested": NSNull()]])+ do { try MCPToolListChangeNotificationTests.requireStream(stream) } catch {+ await stream.close(); throw error+ }+ await stream.close() } - @Test func optionsMcpRemainsNotFoundWithoutExplicitOptionsRoute() async throws {+ @Test func duplicateMirroredHeadersNeverCreateSubscription() async throws { let env = try MCPTestHelpers.makeEnv()- let response = try await respond(- handler: env.handler,- method: .options,- path: "/mcp"- )-- #expect(response.status == .notFound)- #expect(response.allow == nil)+ let body = try MCPModernResultFixture.body(method: "subscriptions/listen", parameters: ["notifications": [:]])+ let response = try await MCPModernResultFixture.transport(handler: env.handler,+ contentType: "application/json", accept: "text/event-stream", protocolVersion: "2026-07-28",+ orderedHeaders: [HTTPField(name: HTTPField.Name("Mcp-Method")!, value: "subscriptions/listen"),+ HTTPField(name: HTTPField.Name("Mcp-Method")!, value: "subscriptions/listen")],+ body: body, loggerLabel: "subscription-duplicate-header")+ #expect(response.status == .badRequest)+ #expect(env.handler.activeToolListChangeStreamCount == 0) } - @Test func getOnUnrelatedPathRemainsNotFound() async throws {+ @Test func invalidContentTypeAndHostRejectBeforeRegistration() async throws { let env = try MCPTestHelpers.makeEnv()- let response = try await respond(- handler: env.handler,- method: .get,- path: "/not-mcp"- )-- #expect(response.status == .notFound)- #expect(response.allow == nil)+ let body = try MCPModernResultFixture.body(method: "subscriptions/listen", parameters: ["notifications": [:]])+ let unsupported = try await MCPModernResultFixture.transport(handler: env.handler,+ contentType: "text/plain", accept: "text/event-stream", body: body, loggerLabel: "subscription-content")+ #expect(unsupported.status == .unsupportedMediaType)+ let forbidden = try await MCPModernResultFixture.transport(handler: env.handler,+ authority: "rebind.example:3141", contentType: "application/json", accept: "text/event-stream",+ body: body, loggerLabel: "subscription-host")+ #expect(forbidden.status == .forbidden)+ #expect(env.handler.activeToolListChangeStreamCount == 0) } - private func respond(- handler: MCPToolHandler,- method: HTTPRequest.Method,- path: String,- origin: String? = nil,- host: String = "127.0.0.1:3141",- accept: String? = nil,- sessionID: String? = nil,- body: String = ""- ) async throws -> MCPHTTPTestResponse {- try await MCPTestHelpers.respond(- handler: handler,- method: method,- path: path,- origin: origin,- authority: host,- accept: accept,- sessionID: sessionID,- body: body,- loggerLabel: "mcp-route-tests"- )+ private func rejected(_ env: MCPTestEnv, body: String? = nil, accept: String = "text/event-stream",+ version: String? = "2026-07-28", mirrored: String = "subscriptions/listen") async throws+ -> MCPHTTPTestResponse {+ let requestBody = try body ?? MCPModernResultFixture.body(method: "subscriptions/listen",+ parameters: ["notifications": ["toolsListChanged": true]])+ return try await MCPModernResultFixture.transport(handler: env.handler,+ contentType: "application/json", accept: accept, protocolVersion: version,+ orderedHeaders: [HTTPField(name: HTTPField.Name("Mcp-Method")!, value: mirrored)],+ body: requestBody, loggerLabel: "subscription-rejection") } }- #endif
diff --git a/Transit/TransitTests/MCPSubscriptionFixture.swift b/Transit/TransitTests/MCPSubscriptionFixture.swiftnew file mode 100644index 0000000..16fc799--- /dev/null+++ b/Transit/TransitTests/MCPSubscriptionFixture.swift@@ -0,0 +1,168 @@+#if os(macOS)+import Foundation+import HTTPTypes+import Hummingbird+import Logging+import NIOConcurrencyHelpers+import NIOCore+import NIOEmbedded+import Testing+@testable import Transit++/// Request-scoped asynchronous transport; owns and drains its channel, writer and loop.+@MainActor final class MCPSubscriptionFixture {+ let response: Response+ let writer = Writer()+ private let loop: NIOAsyncTestingEventLoop+ private let handler: MCPToolHandler+ private let channel: NIOAsyncTestingChannel+ private var bodyTask: Task<Void, any Error>?+ private var closed = false++ private init(response: Response, loop: NIOAsyncTestingEventLoop, channel: NIOAsyncTestingChannel,+ handler: MCPToolHandler) {+ self.response = response+ self.loop = loop+ self.channel = channel+ self.handler = handler+ }++ static func open(handler: MCPToolHandler, id: Any = 7,+ filters: [String: Any] = ["toolsListChanged": true]) async throws -> MCPSubscriptionFixture {+ let loop = NIOAsyncTestingEventLoop()+ var ownedChannel: NIOAsyncTestingChannel?+ do {+ let channel = try await NIOAsyncTestingChannel(loop: loop) { _ in }+ ownedChannel = channel+ let body = try MCPModernResultFixture.body(method: "subscriptions/listen", id: id,+ parameters: ["notifications": filters])+ let headers: HTTPFields = [+ .contentType: "application/json", .accept: "text/event-stream",+ HTTPField.Name("MCP-Protocol-Version")!: "2026-07-28",+ HTTPField.Name("Mcp-Method")!: "subscriptions/listen"+ ]+ let request = Request(head: HTTPRequest(method: .post, scheme: "http", authority: "127.0.0.1:3141",+ path: "/mcp", headerFields: headers), body: RequestBody(buffer: ByteBuffer(string: body)))+ let context = MCPRequestContext(source: ApplicationRequestContextSource(channel: channel,+ logger: Logger(label: "t2383-subscription-fixture")))+ let response = try await MCPServer.makeRouter(handler: handler).buildResponder()+ .respond(to: request, context: context)+ return MCPSubscriptionFixture(response: response, loop: loop, channel: channel, handler: handler)+ } catch {+ if let channel = ownedChannel {+ do { _ = try await channel.finish(acceptAlreadyClosed: true) } catch {+ Issue.record("Subscription setup channel cleanup failed: \(error)")+ }+ }+ await loop.shutdownGracefully()+ throw error+ }+ }++ /// Delaying body consumption proves registration/ack staging without relying on timing.+ func startBody() {+ precondition(bodyTask == nil)+ let response = response, writer = writer+ bodyTask = Task {+ defer { writer.bodyCompleted.withLockedValue { $0 = true } }+ try await response.body.write(writer)+ }+ }++ func cancelBodyOnly() { bodyTask?.cancel() }++ func close(cancelBody: Bool = false) async {+ guard !closed else { return }+ closed = true+ if cancelBody { bodyTask?.cancel() }+ do {+ let leftovers = try await channel.finish(acceptAlreadyClosed: true)+ #expect(leftovers.isClean)+ } catch { Issue.record("Owned subscription channel cleanup failed: \(error)") }+ if bodyTask != nil {+ let completed = await Self.wait { writer.bodyCompleted.withLockedValue { $0 } }+ #expect(completed, "Channel close/cancellation must finish the body without cleanup cancellation")+ if !completed {+ handler.finishToolListChangeSessions() // Cleanup only after the disconnect oracle has failed.+ bodyTask?.cancel()+ let drained = await Self.wait { writer.bodyCompleted.withLockedValue { $0 } }+ #expect(drained, "Cleanup cancellation did not drain owned subscription body")+ }+ }+ if let bodyTask, writer.bodyCompleted.withLockedValue({ $0 }) {+ do { try await bodyTask.value } catch is CancellationError { } catch {+ if !(error is SubscriptionWriterFailure) { Issue.record("Subscription body failed: \(error)") }+ }+ }+ await loop.shutdownGracefully()+ }++ func messages() throws -> [[String: Any]] {+ let text = writer.bytes.withLockedValue { String(buffer: $0) }+ var result: [[String: Any]] = []+ for frame in text.components(separatedBy: "\n\n") where !frame.isEmpty {+ #expect(!frame.split(separator: "\n").contains { $0.hasPrefix("id:") },+ "SSE has no event ID/resume token")+ if frame.hasPrefix(":") { continue }+ let data = try #require(frame.split(separator: "\n").first { $0.hasPrefix("data:") })+ let json = data.dropFirst(5).trimmingCharacters(in: .whitespaces)+ result.append(try #require(try JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any]))+ }+ return result+ }++ static func wait(_ predicate: @MainActor () throws -> Bool) async rethrows -> Bool {+ let end = ContinuousClock.now + .seconds(2)+ while ContinuousClock.now < end {+ if try predicate() { return true }+ try? await Task.sleep(for: .milliseconds(5))+ }+ return try predicate()+ }++ static func assertID(_ message: [String: Any], expected: Any) throws {+ let params = try #require(message["params"] as? [String: Any])+ let meta = try #require(params["_meta"] as? [String: Any])+ let actual = try #require(meta["io.modelcontextprotocol/subscriptionId"])+ #expect(try JSONSerialization.data(withJSONObject: [actual])+ == JSONSerialization.data(withJSONObject: [expected]))+ }++ nonisolated final class Writer: ResponseBodyWriter, Sendable {+ let bytes = NIOLockedValueBox(ByteBuffer())+ let failWrites = NIOLockedValueBox(false)+ let finished = NIOLockedValueBox(false)+ let bodyCompleted = NIOLockedValueBox(false)+ let blockedWriteEntered = NIOLockedValueBox(false)+ private let blockedWrite = NIOLockedValueBox(SubscriptionBlockedWriteState())+ func blockNextWrite() { blockedWrite.withLockedValue { $0.enabled = true } }+ func releaseBlockedWrite() {+ let continuation = blockedWrite.withLockedValue { stored in+ stored.enabled = false+ let value = stored.continuation+ stored.continuation = nil+ return value+ }+ continuation?.resume()+ }+ func write(_ buffer: ByteBuffer) async throws {+ await withCheckedContinuation { continuation in+ let blocked = blockedWrite.withLockedValue { stored in+ guard stored.enabled else { return false }+ stored.continuation = continuation+ return true+ }+ if blocked { blockedWriteEntered.withLockedValue { $0 = true } } else { continuation.resume() }+ }+ if failWrites.withLockedValue({ $0 }) { throw SubscriptionWriterFailure.injected }+ _ = bytes.withLockedValue { $0.writeImmutableBuffer(buffer) }+ }+ func finish(_: HTTPFields?) async throws { finished.withLockedValue { $0 = true } }+ }+}+private nonisolated struct SubscriptionBlockedWriteState {+ var enabled = false+ var continuation: CheckedContinuation<Void, Never>?+}+private nonisolated enum SubscriptionWriterFailure: Error { case injected }+#endif
diff --git a/Transit/TransitTests/MCPSubscriptionLifecycleTests.swift b/Transit/TransitTests/MCPSubscriptionLifecycleTests.swiftnew file mode 100644index 0000000..d71e876--- /dev/null+++ b/Transit/TransitTests/MCPSubscriptionLifecycleTests.swift@@ -0,0 +1,72 @@+#if os(macOS)+import Foundation+import NIOConcurrencyHelpers+import Testing+@testable import Transit++/// Synthetic store/listeners on ephemeral loopback ports; never the production/default listener.+@MainActor @Suite(.serialized)+struct MCPSubscriptionLifecycleTests {+ @Test(arguments: ["stop", "restart", "port-change"])+ func lifecycleClosesOldRequestWithCorrelatedCompleteBeforeEnding(action: String) async throws {+ let env = try MCPTestHelpers.makeEnv()+ let server = MCPServer(toolHandler: env.handler)+ let helpers = MCPServerLifecycleTests()+ var firstPort = try helpers.availableLoopbackPort()+ while firstPort == MCPSettings.defaultPort { firstPort = try helpers.availableLoopbackPort() }+ var nextPort = try helpers.availableLoopbackPort()+ while nextPort == firstPort || nextPort == MCPSettings.defaultPort {+ nextPort = try helpers.availableLoopbackPort()+ }+ try #require(firstPort != MCPSettings.defaultPort)+ var ownedStream: MCPSubscriptionFixture?+ do {+ await server.start(port: firstPort)+ try #require(await helpers.waitUntilListening(port: firstPort))+ let stream = try await MCPSubscriptionFixture.open(handler: env.handler, id: action)+ ownedStream = stream+ try MCPToolListChangeNotificationTests.requireStream(stream); stream.startBody()+ try #require(try await MCPSubscriptionFixture.wait { try stream.messages().count == 1 })+ let previousGeneration = server.listenerGeneration+ switch action {+ case "stop": await server.stop()+ case "restart": await server.restart(port: firstPort)+ default: await server.start(port: nextPort)+ }+ try #require(await MCPSubscriptionFixture.wait { stream.writer.finished.withLockedValue { $0 } })+ let messages = try stream.messages(); try #require(messages.count == 2)+ try MCPToolListChangeNotificationTests.assertComplete(messages[1], id: action)+ #expect(env.handler.activeToolListChangeStreamCount == 0)+ if action != "stop" {+ let replacement = try await MCPSubscriptionFixture.open(handler: env.handler, id: "replacement")+ do {+ try MCPToolListChangeNotificationTests.requireStream(replacement); replacement.startBody()+ try #require(try await MCPSubscriptionFixture.wait { try replacement.messages().count == 1 })+ server.listenerDidExit(generation: previousGeneration, failure: "stale synthetic completion")+ #expect(env.handler.activeToolListChangeStreamCount == 1)+ } catch { await replacement.close(); throw error }+ await replacement.close()+ }+ } catch { await ownedStream?.close(); await server.stop(); throw error }+ await ownedStream?.close(); await server.stop()+ #expect(!server.isRunning)+ }++ @Test func currentGenerationListenerFailureClearsRegistrationsEvenWithoutActiveListener() async throws {+ let env = try MCPTestHelpers.makeEnv()+ let server = MCPServer(toolHandler: env.handler)+ let stream = try await MCPSubscriptionFixture.open(handler: env.handler, id: "listener-failure")+ do {+ try MCPToolListChangeNotificationTests.requireStream(stream); stream.startBody()+ try #require(try await MCPSubscriptionFixture.wait { try stream.messages().count == 1 })+ server.listenerDidExit(generation: server.listenerGeneration, failure: "synthetic listener failure")+ try #require(await MCPSubscriptionFixture.wait { env.handler.activeToolListChangeStreamCount == 0 })+ try #require(await MCPSubscriptionFixture.wait { stream.writer.finished.withLockedValue { $0 } })+ let messages = try stream.messages(); try #require(messages.count == 2)+ try MCPToolListChangeNotificationTests.assertComplete(messages[1], id: "listener-failure")+ #expect(server.startError == "synthetic listener failure")+ } catch { await stream.close(); await server.stop(); throw error }+ await stream.close(); await server.stop()+ }+}+#endif
diff --git a/Transit/TransitTests/MCPTaskQuerySnapshotStoreTests.swift b/Transit/TransitTests/MCPTaskQuerySnapshotStoreTests.swiftindex efb910c..fbc8c8c 100644--- a/Transit/TransitTests/MCPTaskQuerySnapshotStoreTests.swift+++ b/Transit/TransitTests/MCPTaskQuerySnapshotStoreTests.swift@@ -3,7 +3,7 @@ import Foundation import Testing @testable import Transit -@MainActor+@MainActor @Suite(.serialized) struct MCPTaskQuerySnapshotStoreTests { @Test func replayExpiryAndCapacity() throws { var now = ContinuousClock.now@@ -40,6 +40,59 @@ struct MCPTaskQuerySnapshotStoreTests { #expect(throws: (any Error).self) { try store.page(for: token) } } + @Test func frozenMetadataAndCursorFamilySurviveExpiry() throws {+ var now = ContinuousClock.now+ let store = MCPTaskQuerySnapshotStore(now: { now })+ let token = UUID().uuidString+ let reusable = "00000000-0000-8000-8000-000000000001"+ let metadata = Data("original metadata bytes".utf8)+ let deadline = now + .seconds(300)+ let reservation = try #require(try store.prepare(pages: ["first", "second"], cursors: [token],+ deadline: deadline, operationID: UUID(), metadataBytes: metadata, policy: .cached))+ #expect(throws: (any Error).self) { try store.page(for: token) }+ store.domain.withLock { reservation.commitLocked(in: store.domain) }+ #expect(try store.retainedPage(for: token).metadataBytes == metadata)+ #expect(try store.retainedPage(for: token).policy == .cached)+ now = deadline+ #expect(throws: (any Error).self) { try store.page(for: token) }+ #expect(MCPCursorFamily.classify(token) == .ordinary)+ #expect(MCPCursorFamily.classify(reusable) == .reusable)+ #expect(store.retainedBytes == 0)+ }++ @Test func wholeBatchPublishesBothOrdinaryCreatesOnlyAfterAssembly() async throws {+ let domain = MCPReadPublicationDomain()+ let coordinator = MCPReadCoordinator(domain: domain)+ let store = MCPTaskQuerySnapshotStore(domain: domain)+ let tokens = [UUID().uuidString, UUID().uuidString]+ let deadline = ContinuousClock.now + .seconds(300)+ let first = try #require(try store.prepare(pages: ["first", "a"], cursors: [tokens[0]],+ deadline: deadline, operationID: UUID()))+ let second = try #require(try store.prepare(pages: ["second", "b"], cursors: [tokens[1]],+ deadline: deadline, operationID: UUID()))+ let errors = PreencodedPublicationErrors(busy: Data("busy".utf8), expired: Data("expired".utf8),+ capacity: Data("capacity".utf8))+ let elements = [first, second].map { reservation in+ MCPReadBatchElement.read(MCPReadBatchWork(timeout: Data("timeout".utf8), busy: Data("busy".utf8),+ responds: true) { _ in+ PreparedReadResult(encodedResponse: Data("success".utf8), publications: [reservation],+ publicationErrors: errors)+ })+ }+ let bytes = await coordinator.executeBatch(elements) { results in+ #expect(try domain.accounting(for: store.publicationStoreID).visibleBytes == 0)+ let aggregate = try store.prepareAggregate(results.compactMap { $0 }.flatMap(\.publications), in: domain)+ #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 13)+ return PreparedReadResult(encodedResponse: Data("[success:a,success:b]".utf8), publications: [aggregate],+ publicationErrors: errors)+ }+ #expect(bytes == Data("[success:a,success:b]".utf8))+ #expect(try store.page(for: tokens[0]) == "a")+ #expect(try store.page(for: tokens[1]) == "b")+ #expect(try domain.snapshot(for: store.publicationStoreID).version == 1)+ #expect(try domain.accounting(for: store.publicationStoreID).pendingBytes == 0)+ }+ @Test func staleListenerExitPreservesPagesButCurrentExitInvalidatesThem() throws { let env = try MCPTestHelpers.makeEnv() let server = MCPServer(toolHandler: env.handler)
diff --git a/Transit/TransitTests/MCPToolListChangeNotificationTests.swift b/Transit/TransitTests/MCPToolListChangeNotificationTests.swiftindex 9e6e222..4a34e73 100644--- a/Transit/TransitTests/MCPToolListChangeNotificationTests.swift+++ b/Transit/TransitTests/MCPToolListChangeNotificationTests.swift@@ -1,222 +1,223 @@ #if os(macOS) import Foundation import HTTPTypes-import Hummingbird-import Logging+import HummingbirdCore import NIOConcurrencyHelpers-import NIOCore-import NIOEmbedded import Testing @testable import Transit -/// Regression coverage for T-2169: clients initialized before the maintenance-/// setting changes must be told that their cached tool list is stale without-/// broadcasting one JSON-RPC message across a session's concurrent streams.+/// Modern request registrations; IDs correlate messages and never group concurrent streams. @MainActor @Suite(.serialized) struct MCPToolListChangeNotificationTests {-- @Test func maintenanceToggleNotifiesEachSessionOnOnlyOneConnectedStream() async throws {+ @Test func burstBeforeConsumptionNeverEvictsAcknowledgementAndCoalescesChanges() async throws { let env = try MCPTestHelpers.makeEnv()- env.mcpSettings.maintenanceToolsEnabled = false- defer { env.mcpSettings.maintenanceToolsEnabled = false }-- let firstSessionID = try await initializeSession(handler: env.handler)- let secondSessionID = try await initializeSession(handler: env.handler)- #expect(firstSessionID != secondSessionID)- let firstStream = try await notificationResponse(- handler: env.handler,- sessionID: firstSessionID- )- let firstConcurrentStream = try await notificationResponse(- handler: env.handler,- sessionID: firstSessionID- )- let secondStream = try await notificationResponse(- handler: env.handler,- sessionID: secondSessionID- )-- let firstWriter = RecordingEventWriter()- let firstConcurrentWriter = RecordingEventWriter()- let secondWriter = RecordingEventWriter()- let bodyTasks = [- bodyTask(response: firstStream.response, writer: firstWriter),- bodyTask(response: firstConcurrentStream.response, writer: firstConcurrentWriter),- bodyTask(response: secondStream.response, writer: secondWriter)- ]-- env.mcpSettings.maintenanceToolsEnabled = true- try #require(await waitForEventCount(2, writers: [- firstWriter, firstConcurrentWriter, secondWriter- ]))-- env.handler.finishToolListChangeSessions()- for task in bodyTasks {- try await task.value+ let original = env.mcpSettings.maintenanceToolsEnabled+ let stream = try await MCPSubscriptionFixture.open(handler: env.handler, id: "burst")+ do {+ try requireStream(stream)+ for _ in 0..<512 { env.mcpSettings.maintenanceToolsEnabled.toggle() }+ stream.startBody()+ try #require(try await MCPSubscriptionFixture.wait { try stream.messages().count >= 2 })+ let messages = try stream.messages()+ try #require(messages.count == 2)+ #expect(messages.count == 2, "512 queued invalidations coalesce to one after the protected ack")+ try assertAck(messages[0], id: "burst", accepted: ["toolsListChanged": true])+ try assertChange(messages[1], id: "burst")+ env.mcpSettings.maintenanceToolsEnabled.toggle()+ try #require(try await MCPSubscriptionFixture.wait { try stream.messages().count == 3 })+ try assertChange(try stream.messages()[2], id: "burst")+ } catch {+ await stream.close(); env.mcpSettings.maintenanceToolsEnabled = original; throw error }- try await firstStream.channel.close()- try await firstConcurrentStream.channel.close()- try await secondStream.channel.close()-- let expected = "data: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/tools/list_changed\"}\n\n"- let firstSessionEvents = firstWriter.events.withLockedValue(\.count)- + firstConcurrentWriter.events.withLockedValue(\.count)- #expect(firstSessionEvents == 1)- #expect(secondWriter.events.withLockedValue { $0 } == [expected])- #expect(- firstWriter.events.withLockedValue { $0 } == [expected]- || firstConcurrentWriter.events.withLockedValue { $0 } == [expected]- )+ await stream.close(); env.mcpSettings.maintenanceToolsEnabled = original #expect(env.handler.activeToolListChangeStreamCount == 0) } - @Test func assigningExistingMaintenanceValueDoesNotNotify() async throws {+ @Test func parallelStringIntegerAndRepeatedIDsOwnIndependentFilteredStreams() async throws { let env = try MCPTestHelpers.makeEnv()- env.mcpSettings.maintenanceToolsEnabled = false- let sessionID = env.handler.createToolListChangeSession()- let channel = EmbeddedChannel()- let notifications = try #require(env.handler.toolListChangeNotifications(- sessionID: sessionID,- channelClose: channel.closeFuture- ))-- env.mcpSettings.maintenanceToolsEnabled = false-- let notification = await firstNotification(in: notifications, timeout: .milliseconds(50))- #expect(notification?.method == nil)- try await channel.close()+ let original = env.mcpSettings.maintenanceToolsEnabled+ var streams: [MCPSubscriptionFixture] = []+ let ids: [Any] = ["17", 17, "17"]+ do {+ for id in ids {+ let stream = try await MCPSubscriptionFixture.open(handler: env.handler, id: id)+ streams.append(stream); try requireStream(stream); stream.startBody()+ }+ try #require(await MCPSubscriptionFixture.wait { env.handler.activeToolListChangeStreamCount == 3 })+ env.mcpSettings.maintenanceToolsEnabled.toggle()+ for (index, stream) in streams.enumerated() {+ try #require(try await MCPSubscriptionFixture.wait { try stream.messages().count == 2 })+ let messages = try stream.messages()+ try assertAck(messages[0], id: ids[index], accepted: ["toolsListChanged": true])+ try assertChange(messages[1], id: ids[index])+ }+ } catch {+ for stream in streams { await stream.close() }+ env.mcpSettings.maintenanceToolsEnabled = original; throw error+ }+ for stream in streams { await stream.close() }+ env.mcpSettings.maintenanceToolsEnabled = original+ #expect(env.handler.activeToolListChangeStreamCount == 0) } - @Test func closingIdleChannelImmediatelyUnregistersStream() async throws {+ @Test(arguments: [0, 1, 2])+ func unsupportedEmptyAndFalseFiltersNeverOptIntoNotifications(variant: Int) async throws {+ let filters: [[String: Any]] = [[:], ["toolsListChanged": false],+ ["promptsListChanged": true, "resourcesListChanged": true, "resourceSubscriptions": ["fixture://only"]]] let env = try MCPTestHelpers.makeEnv()- let sessionID = env.handler.createToolListChangeSession()- let channel = EmbeddedChannel()- _ = try #require(env.handler.toolListChangeNotifications(- sessionID: sessionID,- channelClose: channel.closeFuture- ))- #expect(env.handler.activeToolListChangeStreamCount == 1)-- try await channel.close()-- #expect(await waitForStreamCount(0, handler: env.handler))+ let original = env.mcpSettings.maintenanceToolsEnabled+ let stream = try await MCPSubscriptionFixture.open(handler: env.handler, filters: filters[variant])+ do {+ try requireStream(stream); stream.startBody()+ try #require(try await MCPSubscriptionFixture.wait { try stream.messages().count == 1 })+ try assertAck(try stream.messages()[0], id: 7, accepted: [:])+ env.mcpSettings.maintenanceToolsEnabled.toggle()+ env.handler.finishToolListChangeSessions()+ try #require(await MCPSubscriptionFixture.wait { stream.writer.finished.withLockedValue { $0 } })+ let messages = try stream.messages()+ #expect(messages.count == 2)+ try assertComplete(messages[1], id: 7)+ } catch { await stream.close(); env.mcpSettings.maintenanceToolsEnabled = original; throw error }+ await stream.close(); env.mcpSettings.maintenanceToolsEnabled = original } - private func initializeSession(handler: MCPToolHandler) async throws -> String {- let body = """- {"jsonrpc":"2.0","id":1,"method":"initialize","params":{- "protocolVersion":"2025-03-26","capabilities":{},- "clientInfo":{"name":"Transit Tests","version":"1.0"}}}- """- let response = try await MCPTestHelpers.respond(- handler: handler,- contentType: "application/json",- accept: "application/json, text/event-stream",- body: body,- loggerLabel: "mcp-tool-list-change-initialize"- )- #expect(response.status == .ok)- let result = try #require(response.json as? [String: Any])- let resultObject = try #require(result["result"] as? [String: Any])- let capabilities = try #require(resultObject["capabilities"] as? [String: Any])- let tools = try #require(capabilities["tools"] as? [String: Any])- #expect(tools["listChanged"] as? Bool == true)- return try #require(response.sessionID)+ @Test func supportedSubsetOnlyAndSameValueAssignmentDoesNotInvalidate() async throws {+ let env = try MCPTestHelpers.makeEnv()+ let stream = try await MCPSubscriptionFixture.open(handler: env.handler,+ filters: ["toolsListChanged": true, "promptsListChanged": true, "extension": ["unknown": true]])+ do {+ try requireStream(stream); stream.startBody()+ try #require(try await MCPSubscriptionFixture.wait { try stream.messages().count == 1 })+ try assertAck(try stream.messages()[0], id: 7, accepted: ["toolsListChanged": true])+ let unchanged = env.mcpSettings.maintenanceToolsEnabled+ env.mcpSettings.maintenanceToolsEnabled = unchanged+ env.handler.finishToolListChangeSessions()+ try #require(await MCPSubscriptionFixture.wait { stream.writer.finished.withLockedValue { $0 } })+ let messages = try stream.messages(); #expect(messages.count == 2)+ try assertComplete(messages[1], id: 7)+ } catch { await stream.close(); throw error }+ await stream.close(); #expect(env.handler.activeToolListChangeStreamCount == 0) } - private func bodyTask(- response: Response,- writer: RecordingEventWriter- ) -> Task<Void, any Error> {- Task {- try await response.body.write(writer)- }+ @Test(arguments: [false, true]) func disconnectAndTaskCancellationUnregisterExactlyOnce(cancel: Bool) async throws {+ let env = try MCPTestHelpers.makeEnv()+ let original = env.mcpSettings.maintenanceToolsEnabled+ let stream = try await MCPSubscriptionFixture.open(handler: env.handler)+ do {+ try requireStream(stream); stream.startBody()+ try #require(try await MCPSubscriptionFixture.wait { try stream.messages().count == 1 })+ if cancel {+ stream.cancelBodyOnly()+ try #require(await MCPSubscriptionFixture.wait { stream.writer.bodyCompleted.withLockedValue { $0 } })+ try #require(await MCPSubscriptionFixture.wait { env.handler.activeToolListChangeStreamCount == 0 })+ }+ await stream.close(cancelBody: false)+ #expect(stream.writer.bodyCompleted.withLockedValue { $0 })+ try #require(await MCPSubscriptionFixture.wait { env.handler.activeToolListChangeStreamCount == 0 })+ let bytes = stream.writer.bytes.withLockedValue { $0 }+ env.mcpSettings.maintenanceToolsEnabled.toggle()+ env.handler.finishToolListChangeSessions()+ #expect(stream.writer.bytes.withLockedValue { $0 } == bytes)+ await stream.close(cancelBody: cancel)+ } catch { await stream.close(); env.mcpSettings.maintenanceToolsEnabled = original; throw error }+ env.mcpSettings.maintenanceToolsEnabled = original } - private func firstNotification(- in notifications: AsyncStream<MCPServerNotification>,- timeout: Duration- ) async -> MCPServerNotification? {- await withTaskGroup(of: MCPServerNotification?.self) { group in- group.addTask {- await notifications.first { _ in true }- }- group.addTask {- try? await Task.sleep(for: timeout)- return nil- }- let first = await group.next() ?? nil- group.cancelAll()- return first- }+ @Test func writerFailureUnregistersWithoutWaitingForChannelDisconnect() async throws {+ let env = try MCPTestHelpers.makeEnv()+ let stream = try await MCPSubscriptionFixture.open(handler: env.handler)+ do {+ try requireStream(stream); stream.writer.failWrites.withLockedValue { $0 = true }; stream.startBody()+ try #require(await MCPSubscriptionFixture.wait { env.handler.activeToolListChangeStreamCount == 0 })+ let bytes = stream.writer.bytes.withLockedValue { $0 }+ env.handler.finishToolListChangeSessions()+ #expect(stream.writer.bytes.withLockedValue { $0 } == bytes)+ } catch { await stream.close(); throw error }+ await stream.close() } - private func notificationResponse(- handler: MCPToolHandler,- sessionID: String- ) async throws -> (response: Response, channel: EmbeddedChannel) {- let responder = MCPServer.makeRouter(handler: handler).buildResponder()- var headers = HTTPFields()- headers[.accept] = "text/event-stream"- headers[.mcpSessionID] = sessionID- let request = Request(- head: HTTPRequest(- method: .get,- scheme: "http",- authority: "127.0.0.1:3141",- path: "/mcp",- headerFields: headers- ),- body: RequestBody(buffer: ByteBuffer())- )- let channel = EmbeddedChannel()- let context = MCPRequestContext(- source: ApplicationRequestContextSource(- channel: channel,- logger: Logger(label: "mcp-tool-list-change-tests")- )- )- return (try await responder.respond(to: request, context: context), channel)+ @Test func stopWithoutListenerClosesRegisteredRequestWithCompleteResult() async throws {+ let env = try MCPTestHelpers.makeEnv()+ let server = MCPServer(toolHandler: env.handler)+ let stream = try await MCPSubscriptionFixture.open(handler: env.handler, id: "no-listener")+ do {+ try requireStream(stream); stream.startBody()+ try #require(try await MCPSubscriptionFixture.wait { try stream.messages().count == 1 })+ await server.stop()+ try #require(await MCPSubscriptionFixture.wait { stream.writer.finished.withLockedValue { $0 } })+ let messages = try stream.messages(); #expect(messages.count == 2)+ try assertComplete(messages[1], id: "no-listener")+ #expect(env.handler.activeToolListChangeStreamCount == 0)+ } catch { await stream.close(); await server.stop(); throw error }+ await stream.close(); await server.stop() } - private func waitForEventCount(- _ expected: Int,- writers: [RecordingEventWriter],- timeout: Duration = .seconds(1)- ) async -> Bool {- let deadline = ContinuousClock.now + timeout- while ContinuousClock.now < deadline {- let count = writers.reduce(0) { result, writer in- result + writer.events.withLockedValue(\.count)- }- if count == expected { return true }- try? await Task.sleep(for: .milliseconds(10))- }- return false+ @Test func openSubscriptionNeverConsumesCoveredReadAdmission() async throws {+ let env = try MCPTestHelpers.makeEnv()+ let source = NoCapture()+ let service = MCPReadService(source: source,+ monitor: MCPImportEvidenceMonitor(syncActive: false, storeIdentifier: nil),+ snapshots: env.handler.taskQuerySnapshots)+ let handler = MCPToolHandler(taskService: env.taskService, projectService: env.projectService,+ commentService: env.commentService, milestoneService: env.milestoneService,+ maintenanceService: env.maintenanceService, settings: env.mcpSettings,+ taskQuerySnapshots: env.handler.taskQuerySnapshots, writeCoordinator: env.writeCoordinator,+ readService: service, readCoordinator: env.handler.readCoordinator)+ let stream = try await MCPSubscriptionFixture.open(handler: handler)+ do {+ try requireStream(stream); stream.startBody()+ try #require(try await MCPSubscriptionFixture.wait { try stream.messages().count == 1 })+ #expect(env.handler.readCoordinator.unfinishedCount == 0 && source.calls == 0)+ #expect(env.handler.activeToolListChangeStreamCount == 1)+ env.handler.finishToolListChangeSessions()+ try #require(await MCPSubscriptionFixture.wait { stream.writer.finished.withLockedValue { $0 } })+ #expect(env.handler.readCoordinator.unfinishedCount == 0 && source.calls == 0)+ } catch { await stream.close(); throw error }+ await stream.close() } - private func waitForStreamCount(- _ expected: Int,- handler: MCPToolHandler,- timeout: Duration = .seconds(1)- ) async -> Bool {- let deadline = ContinuousClock.now + timeout- while ContinuousClock.now < deadline {- if handler.activeToolListChangeStreamCount == expected { return true }- try? await Task.sleep(for: .milliseconds(10))+ @MainActor private final class NoCapture: MCPReadCaptureSource {+ var calls = 0+ func capture(_ request: ReadCaptureRequest) throws -> CapturedReadView {+ calls += 1+ throw MCPReadCaptureError.storageFailure }- return false }-} -private nonisolated final class RecordingEventWriter: ResponseBodyWriter, @unchecked Sendable {- let events = NIOLockedValueBox<[String]>([])-- func write(_ buffer: ByteBuffer) async throws {- events.withLockedValue { $0.append(String(buffer: buffer)) }+ static func requireStream(_ stream: MCPSubscriptionFixture) throws {+ try #require(stream.response.status == .ok)+ #expect(stream.response.headers[.contentType] == "text/event-stream")+ #expect(stream.response.headers[.cacheControl] == "no-cache")+ #expect(stream.response.headers[.mcpSessionID] == nil) }-- func finish(_: HTTPFields?) async throws {}+ private func requireStream(_ stream: MCPSubscriptionFixture) throws { try Self.requireStream(stream) }+ private func assertAck(_ message: [String: Any], id: Any, accepted: [String: Bool]) throws {+ #expect(message["jsonrpc"] as? String == "2.0")+ #expect(message["method"] as? String == "notifications/subscriptions/acknowledged")+ let params = try #require(message["params"] as? [String: Any])+ #expect(params["notifications"] as? [String: Bool] == accepted)+ #expect(message["id"] == nil && message["result"] == nil)+ try MCPSubscriptionFixture.assertID(message, expected: id)+ }+ private func assertChange(_ message: [String: Any], id: Any) throws {+ #expect(message["jsonrpc"] as? String == "2.0")+ #expect(message["method"] as? String == "notifications/tools/list_changed")+ #expect(message["id"] == nil && message["result"] == nil)+ try MCPSubscriptionFixture.assertID(message, expected: id)+ }+ static func assertComplete(_ message: [String: Any], id: Any) throws {+ #expect(message["jsonrpc"] as? String == "2.0")+ #expect(message["method"] == nil)+ #expect(try JSONSerialization.data(withJSONObject: [try #require(message["id"])])+ == JSONSerialization.data(withJSONObject: [id]))+ let result = try #require(message["result"] as? [String: Any])+ #expect(result["resultType"] as? String == "complete")+ #expect(message["error"] == nil)+ let meta = try #require(result["_meta"] as? [String: Any])+ let subscriptionID = try #require(meta["io.modelcontextprotocol/subscriptionId"])+ #expect(try JSONSerialization.data(withJSONObject: [subscriptionID])+ == JSONSerialization.data(withJSONObject: [id]))+ }+ private func assertComplete(_ message: [String: Any], id: Any) throws { try Self.assertComplete(message, id: id) } }- #endif
diff --git a/Transit/TransitTests/MCPWriteLifecycleTests.swift b/Transit/TransitTests/MCPWriteLifecycleTests.swiftindex 5e00e54..6076e26 100644--- a/Transit/TransitTests/MCPWriteLifecycleTests.swift+++ b/Transit/TransitTests/MCPWriteLifecycleTests.swift@@ -7,47 +7,57 @@ import Testing @MainActor @Suite(.serialized) struct MCPWriteLifecycleTests {- @Test func protectedNotificationPersistsAndReplaysAcrossResponderReplacement() async throws {+ @Test func protectedRequestPersistsAndReplaysAcrossResponderReplacement() async throws { let env = try MCPTestHelpers.makeEnv() let key = MCPTestHelpers.freshWriteKey()- let args: [String: Any] = ["name": "notification", "colorHex": "#123456", "idempotencyKey": key]- let notification: [String: Any] = ["jsonrpc": "2.0", "method": "tools/call",- "params": ["name": "create_project", "arguments": args]]- let data = try JSONSerialization.data(withJSONObject: notification)- let body = try #require(String(data: data, encoding: .utf8))- let response = try await MCPTestHelpers.respond(handler: env.handler, contentType: "application/json",- body: body, loggerLabel: "write.notification")- #expect(response.status == .accepted)- #expect(response.body.isEmpty)- let retry: [String: Any] = ["jsonrpc": "2.0", "id": 7, "method": "tools/call",- "params": ["name": "create_project", "arguments": args]]- let retryData = try JSONSerialization.data(withJSONObject: retry)- let retryBody = try #require(String(data: retryData, encoding: .utf8))- let replay = try await MCPTestHelpers.respond(handler: env.handler, contentType: "application/json",- body: retryBody, loggerLabel: "write.notification.replay")- let envelope = try MCPTestHelpers.decodeHTTPToolResult(try #require(replay.json as? [String: Any]))+ let args: [String: Any] = ["name": "request", "colorHex": "#123456", "idempotencyKey": key]+ let initial = try await MCPModernResultFixture.respond(env, method: "tools/call", id: "original",+ parameters: ["name": "create_project", "arguments": args])+ let initialRPC = try #require(initial.json as? [String: Any])+ #expect(initial.status == .ok && initialRPC["id"] as? String == "original")+ #expect(try MCPTestHelpers.decodeHTTPToolResult(initialRPC)["outcome"] as? String == "committed")+ // Each transport call constructs a new responder while retaining the app-owned retry store.+ let replay = try await MCPModernResultFixture.respond(env, method: "tools/call", id: 7,+ parameters: ["name": "create_project", "arguments": args])+ let replayRPC = try #require(replay.json as? [String: Any])+ let envelope = try MCPTestHelpers.decodeHTTPToolResult(replayRPC)+ #expect(replay.status == .ok && replayRPC["id"] as? Int == 7) #expect(envelope["outcome"] as? String == "committed")- #expect(try env.context.fetch(FetchDescriptor<Project>()).count == 1)- #expect(try env.context.fetch(FetchDescriptor<MCPWriteReceipt>()).count == 1)+ #expect(envelope["accepted"] as? Bool == true)+ let originalText = try MCPModernResultFixture.text(initial)+ let replayText = try MCPModernResultFixture.text(replay)+ #expect(originalText.utf8.elementsEqual(replayText.utf8))+ #expect(try env.context.fetchCount(FetchDescriptor<Project>()) == 1)+ let receipts = try env.context.fetch(FetchDescriptor<MCPWriteReceipt>())+ try #require(receipts.count == 1)+ #expect(receipts[0].resultJSON == originalText) } - @Test func orderedBatchRetainsFirstCommitWhenSecondWriteRejects() async throws {+ @Test(arguments: [false, true])+ func orderedRequestsRetainFirstCommitWhenSecondWriteRejects(distinctKey: Bool) async throws { let env = try MCPTestHelpers.makeEnv()- let body = """- [- {"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_project",- "arguments":{"name":"first","colorHex":"#123456","idempotencyKey":"batch-first"}}},- {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"create_project",- "arguments":{"name":"first","colorHex":"#123456","idempotencyKey":"batch-second"}}}- ]- """- let response = try await MCPTestHelpers.respond(handler: env.handler, contentType: "application/json",- body: body, loggerLabel: "write.batch")- let objects = try #require(response.json as? [[String: Any]])- #expect(objects.count == 2)- #expect(try MCPTestHelpers.decodeHTTPToolResult(objects[0])["outcome"] as? String == "committed")- #expect(try MCPTestHelpers.decodeHTTPToolResult(objects[1])["outcome"] as? String == "rejected")- #expect(try env.context.fetch(FetchDescriptor<Project>()).map(\.name) == ["first"])+ let key = MCPTestHelpers.freshWriteKey()+ let first = try await MCPModernResultFixture.respond(env, method: "tools/call", id: 1,+ parameters: ["name": "create_project", "arguments": ["name": "first", "colorHex": "#123456",+ "idempotencyKey": key]])+ let second = try await MCPModernResultFixture.respond(env, method: "tools/call", id: 2,+ parameters: ["name": "create_project", "arguments": ["name": "first", "colorHex": "#654321",+ "idempotencyKey": distinctKey ? MCPTestHelpers.freshWriteKey() : key]])+ let firstRPC = try #require(first.json as? [String: Any])+ let secondRPC = try #require(second.json as? [String: Any])+ #expect(first.status == .ok && second.status == .ok)+ #expect(firstRPC["id"] as? Int == 1 && secondRPC["id"] as? Int == 2)+ let committed = try MCPTestHelpers.decodeHTTPToolResult(firstRPC)+ let rejected = try MCPTestHelpers.decodeHTTPToolResult(secondRPC)+ #expect(committed["outcome"] as? String == "committed" && committed["accepted"] as? Bool == true)+ #expect(rejected["outcome"] as? String == "rejected")+ #expect(rejected["accepted"] as? Bool == distinctKey)+ #expect((rejected["error"] as? [String: Any])?["code"] as? String+ == (distinctKey ? "DUPLICATE_PROJECT_NAME" : "IDEMPOTENCY_KEY_REUSED"))+ let projects = try env.context.fetch(FetchDescriptor<Project>())+ #expect(projects.map(\.name) == ["first"])+ #expect(projects.first?.colorHex == "#123456")+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == (distinctKey ? 2 : 1)) } @Test func localAndSeparatelySavedChangesInvalidateObservedRevision() async throws {@@ -74,27 +84,72 @@ struct MCPWriteLifecycleTests { let counter = MCPWriteLifecycleCounter() let env = try MCPTestHelpers.makeEnv(taskCounterStore: counter) let project = MCPTestHelpers.makeProject(in: env.context)+ try env.context.save() let args: [String: Any] = ["name": "disconnect", "type": "feature",- "projectId": project.id.uuidString, "idempotencyKey": "disconnect"]- let request = MCPTestHelpers.toolCallRequest(tool: "create_task", arguments: args)- let object: [String: Any] = ["jsonrpc": "2.0", "id": 1, "method": "tools/call",- "params": ["name": "create_task", "arguments": args]]- let data = try JSONSerialization.data(withJSONObject: object)- let body = try #require(String(data: data, encoding: .utf8))- let connection = Task {- try await MCPTestHelpers.respond(handler: env.handler, contentType: "application/json",- body: body, loggerLabel: "write.disconnect")+ "projectId": project.id.uuidString, "idempotencyKey": "disconnect"]+ let observation = MCPWriteConnectionObservation()+ let connection = Task { @MainActor in+ do {+ observation.response = try await MCPModernResultFixture.respond(env, method: "tools/call", id: 1,+ parameters: ["name": "create_task", "arguments": args])+ } catch { observation.failure = String(describing: error) }+ observation.finished = true+ }+ do {+ try await waitForAcceptance(counter, observation: observation)+ // The real allocator suspension occurs only after durable acceptance.+ #expect(try env.context.fetchCount(FetchDescriptor<MCPWriteReceipt>()) == 1)+ connection.cancel()+ await counter.release()+ try #require(await waitForCompletion(observation), "Accepted cancelled request did not drain")+ await connection.value+ let replay = try await MCPModernResultFixture.respond(env, method: "tools/call", id: "replay",+ parameters: ["name": "create_task", "arguments": args])+ let rpc = try #require(replay.json as? [String: Any])+ #expect(rpc["id"] as? String == "replay")+ let result = try MCPTestHelpers.decodeHTTPToolResult(rpc)+ #expect(result["outcome"] as? String == "rejected")+ #expect(result["accepted"] as? Bool == true)+ #expect((result["error"] as? [String: Any])?["code"] as? String == "CANCELLED")+ #expect(try env.context.fetch(FetchDescriptor<TransitTask>()).isEmpty)+ let receipts = try env.context.fetch(FetchDescriptor<MCPWriteReceipt>())+ try #require(receipts.count == 1)+ let stored = try #require(receipts[0].resultJSON)+ let replayText = try MCPModernResultFixture.text(replay)+ #expect(stored.utf8.elementsEqual(replayText.utf8))+ #expect(await counter.loadCount() == 1)+ } catch {+ connection.cancel()+ await counter.release()+ let drained = await waitForCompletion(observation)+ #expect(drained, "Failed cancellation fixture must drain its released connection")+ if drained { await connection.value }+ throw error+ }+ }++ private func waitForAcceptance(_ counter: MCPWriteLifecycleCounter,+ observation: MCPWriteConnectionObservation) async throws {+ let cutoff = ContinuousClock.now.advanced(by: .seconds(2))+ while ContinuousClock.now < cutoff {+ if await counter.hasStarted() { return }+ if observation.finished {+ Issue.record("Request completed before allocator acceptance: \(observation.evidence)")+ throw MCPWriteLifecycleFixtureError.notAccepted+ }+ try await Task.sleep(for: .milliseconds(10))+ }+ Issue.record("Allocator acceptance deadline expired: \(observation.evidence)")+ throw MCPWriteLifecycleFixtureError.notAccepted+ }++ private func waitForCompletion(_ observation: MCPWriteConnectionObservation) async -> Bool {+ let cutoff = ContinuousClock.now.advanced(by: .seconds(2))+ while ContinuousClock.now < cutoff {+ if observation.finished { return true }+ do { try await Task.sleep(for: .milliseconds(10)) } catch { return observation.finished } }- await counter.waitForLoad()- connection.cancel()- await counter.release()- _ = try? await connection.value- let replay = await env.handler.handle(request)- let result = try MCPTestHelpers.decodeResult(replay)- #expect(result["accepted"] as? Bool == true)- #expect(try MCPTestHelpers.errorCode(replay) == "CANCELLED")- #expect(try env.context.fetch(FetchDescriptor<TransitTask>()).isEmpty)- #expect(try env.context.fetch(FetchDescriptor<MCPWriteReceipt>()).count == 1)+ return observation.finished } @Test func missingSafetyIsRejectedWithoutReservingAKey() async throws {@@ -108,26 +163,48 @@ struct MCPWriteLifecycleTests { #expect(try env.context.fetch(FetchDescriptor<MCPWriteReceipt>()).isEmpty) } }+@MainActor private final class MCPWriteConnectionObservation {+ var response: MCPHTTPTestResponse?+ var failure: String?+ var finished = false+ var evidence: String {+ if let response {+ let body = String(data: response.body.prefix(1024), encoding: .utf8) ?? "<non-UTF8>"+ return "HTTP \(response.status), body \(body)"+ }+ return failure ?? "request still running"+ }+}+private enum MCPWriteLifecycleFixtureError: Error { case notAccepted }+ actor MCPWriteLifecycleCounter: DisplayIDAllocator.CounterStore { private var continuation: CheckedContinuation<Void, Never>?- private var observer: CheckedContinuation<Void, Never>?- private var started = false+ private var loads = 0+ private var released = false func waitForLoad() async {- if started { return }- await withCheckedContinuation { observer = $0 }+ let cutoff = ContinuousClock.now.advanced(by: .seconds(2))+ while loads == 0 && ContinuousClock.now < cutoff {+ do { try await Task.sleep(for: .milliseconds(10)) } catch {+ Issue.record("Allocator rendezvous cancelled before entry")+ return+ }+ }+ if loads == 0 { Issue.record("Allocator rendezvous expired before entry") } } - func release() { continuation?.resume(); continuation = nil }-+ func hasStarted() -> Bool { loads > 0 }+ func loadCount() -> Int { loads }+ func release() {+ released = true+ continuation?.resume()+ continuation = nil+ } func loadCounter() async throws -> DisplayIDAllocator.CounterSnapshot {- started = true- observer?.resume()- observer = nil- await withCheckedContinuation { continuation = $0 }+ loads += 1+ if !released { await withCheckedContinuation { continuation = $0 } } return .init(nextDisplayID: 1, changeTag: nil) }- func saveCounter(nextDisplayID: Int, expectedChangeTag: String?) async throws { } } #endif
diff --git a/Transit/TransitUITests/DataMaintenanceUITests.swift b/Transit/TransitUITests/DataMaintenanceUITests.swiftindex 5584a12..5c7fdf3 100644--- a/Transit/TransitUITests/DataMaintenanceUITests.swift+++ b/Transit/TransitUITests/DataMaintenanceUITests.swift@@ -20,6 +20,7 @@ final class DataMaintenanceUITests: XCTestCase { private func launchApp(scenario: String) -> XCUIApplication { let app = XCUIApplication()+ app.launchEnvironment["TRANSIT_PERSISTENCE_MODE"] = "ui-test" app.launchEnvironment["TRANSIT_UI_TEST_SCENARIO"] = scenario app.launch() return app
diff --git a/Transit/TransitUITests/SearchEmptyStateUITests.swift b/Transit/TransitUITests/SearchEmptyStateUITests.swiftindex 8b74df7..2fd7e46 100644--- a/Transit/TransitUITests/SearchEmptyStateUITests.swift+++ b/Transit/TransitUITests/SearchEmptyStateUITests.swift@@ -9,6 +9,7 @@ final class SearchEmptyStateUITests: XCTestCase { private func launchBoardApp() -> XCUIApplication { let app = XCUIApplication()+ app.launchEnvironment["TRANSIT_PERSISTENCE_MODE"] = "ui-test" app.launchEnvironment["TRANSIT_UI_TEST_SCENARIO"] = "board" app.launch() return app
diff --git a/Transit/TransitUITests/TransitUITests.swift b/Transit/TransitUITests/TransitUITests.swiftindex 89be586..6cd3020 100644--- a/Transit/TransitUITests/TransitUITests.swift+++ b/Transit/TransitUITests/TransitUITests.swift@@ -6,19 +6,6 @@ final class TransitUITests: XCTestCase { continueAfterFailure = false } - // MARK: - Helpers-- private func launchApp(scenario: String? = nil) -> XCUIApplication {- let app = XCUIApplication()- if let scenario {- app.launchEnvironment["TRANSIT_UI_TEST_SCENARIO"] = scenario- } else {- app.launchEnvironment["TRANSIT_UI_TEST_SCENARIO"] = "empty"- }- app.launch()- return app- }- // MARK: - Empty States @MainActor@@ -354,3 +341,19 @@ final class TransitUITests: XCTestCase { XCTAssertTrue(abandonedTask.waitForExistence(timeout: 5)) } }++private extension TransitUITests {+ // MARK: - Helpers++ private func launchApp(scenario: String? = nil) -> XCUIApplication {+ let app = XCUIApplication()+ app.launchEnvironment["TRANSIT_PERSISTENCE_MODE"] = "ui-test"+ if let scenario {+ app.launchEnvironment["TRANSIT_UI_TEST_SCENARIO"] = scenario+ } else {+ app.launchEnvironment["TRANSIT_UI_TEST_SCENARIO"] = "empty"+ }+ app.launch()+ return app+ }+}
diff --git a/Transit/TransitUITests/TransitUITestsLaunchTests.swift b/Transit/TransitUITests/TransitUITestsLaunchTests.swiftindex 1f5ccb3..4e2a96c 100644--- a/Transit/TransitUITests/TransitUITestsLaunchTests.swift+++ b/Transit/TransitUITests/TransitUITestsLaunchTests.swift@@ -20,6 +20,7 @@ final class TransitUITestsLaunchTests: XCTestCase { @MainActor func testLaunch() throws { let app = XCUIApplication()+ app.launchEnvironment["TRANSIT_PERSISTENCE_MODE"] = "ui-test" app.launch() // Insert steps here to perform after app launch but before taking a screenshot,
diff --git a/scripts/mcp-modern-readiness/launch.py b/scripts/mcp-modern-readiness/launch.pynew file mode 100644index 0000000..00dd9e8--- /dev/null+++ b/scripts/mcp-modern-readiness/launch.py@@ -0,0 +1,142 @@+#!/usr/bin/env python3+"""Run a reviewed signed-unit fixture packet; never production Transit or clients."""+import argparse+import hashlib+import json+import pathlib+import plistlib+import re+import shutil+import os+import signal+import subprocess+import time+from verify import verify+++def bounded_cleanup(packet, host, directory):+ """Timeout diagnostics precede identity-scoped runner-first termination."""+ def owned(marker, executable):+ rows = subprocess.check_output(["ps", "-axo", "pid=,comm=,args="], text=True).splitlines()+ matches = []+ for row in rows:+ parts = row.strip().split(None, 2)+ if len(parts) == 3 and parts[1].endswith(executable) and marker in parts[2]:+ matches.append(int(parts[0]))+ if len(matches) > 1:+ raise RuntimeError("Cannot establish unique owned timeout identity: " + marker)+ return matches[0] if matches else None+ plist = re.search(r"-xctestrun (\S+)", packet["test"])[1]+ runner = owned(plist, "xcodebuild")+ guarded_host = owned(host, "/Transit")+ proof = []+ for label, pid in (("runner", runner), ("host", guarded_host)):+ if pid is None:+ proof.append({"identity": label, "state": "already absent", "sample": None})+ continue+ subprocess.run(["sample", str(pid), "3", "1", "-file", str(directory / (label + "-sample.txt"))], check=True)+ proof.append({"identity": label, "pid": pid, "sampleExit": 0})+ (directory / "timeout-identities-and-samples.json").write_text(json.dumps(proof, indent=2))+ for pid, marker in ((runner, plist), (guarded_host, host)):+ if pid is None:+ continue+ identity = subprocess.run(["ps", "-p", str(pid), "-o", "args="], capture_output=True, text=True)+ if identity.returncode:+ continue+ if marker not in identity.stdout:+ raise RuntimeError("Owned timeout identity changed")+ os.kill(pid, signal.SIGTERM)+ for _ in range(40):+ if subprocess.run(["ps", "-p", str(pid)], capture_output=True).returncode:+ break+ time.sleep(.25)+ else:+ raise RuntimeError("Owned timeout process did not drain")+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("--packet", required=True)+ parser.add_argument("--packet-sha256", required=True)+ parser.add_argument("--hold-seconds", type=int, default=0)+ args = parser.parse_args()+ if not 0 <= args.hold_seconds <= 120:+ raise ValueError("Isolated hold must be between zero and 120 seconds")+ path = pathlib.Path(args.packet).resolve()+ raw = path.read_bytes()+ if hashlib.sha256(raw).hexdigest() != args.packet_sha256:+ raise ValueError("Reviewed packet hash changed")+ packet = json.loads(raw)+ if set(packet["expectedTestDeclarations"]) != {"MCPModernReadinessTests"}:+ raise ValueError("Launcher requires only the isolated readiness fixture suite")+ cwd = pathlib.Path(packet["cwd"])+ outputs = []+ for key in ("build", "preflight", "enumerate", "test"):+ command = packet[key]+ for pattern in (r"> (\S+)", r"-resultBundlePath (\S+)", r"-test-enumeration-output-path (\S+)"):+ match = re.search(pattern, command)+ if match:+ output = pathlib.Path(match[1])+ outputs.append(output if output.is_absolute() else cwd / output)+ match = re.search(r"-xctestrun (\S+)", packet["test"])+ outputs.append(pathlib.Path(match[1]))+ outputs.extend(path.parent / name for name in ("actual-readiness-trace.json", "timeout-identities-and-samples.json", "stage-results.json"))+ if any(output.exists() for output in outputs):+ raise ValueError("Fresh packet outputs required; prior evidence must never be overwritten")+ stages = {}+ stage_path = path.parent / "stage-results.json"+ for key in ("sourceReady", "setup", "build", "preflight", "enumerate", "inventoryCheck"):+ result = subprocess.run(packet[key], shell=True, cwd=packet["cwd"])+ stages[key] = result.returncode+ stage_path.write_text(json.dumps(stages, indent=2))+ print(json.dumps({"stage": key, "actualExit": result.returncode}), flush=True)+ if result.returncode:+ raise subprocess.CalledProcessError(result.returncode, packet[key])+ # A hold is unit-target-only; persistence/smoke/host guards remain mandatory.+ match = re.search(r"-xctestrun (\S+)", packet["test"])+ plist_path = pathlib.Path(match[1])+ configuration = plistlib.loads(plist_path.read_bytes())+ if "TestConfigurations" in configuration:+ targets = configuration["TestConfigurations"][0]["TestTargets"]+ else:+ targets = [value for key, value in configuration.items()+ if not key.startswith("__") and isinstance(value, dict)]+ if len(targets) != 1 or targets[0]["BlueprintName"] != "TransitTests":+ raise ValueError("Only inspected unit target is eligible")+ environment = targets[0]["EnvironmentVariables"]+ if environment.get("TRANSIT_PERSISTENCE_MODE") != "unit-test" or environment.get("TRANSIT_ISOLATION_SMOKE") != "1":+ raise ValueError("Isolation guards missing")+ environment["TRANSIT_READINESS_HOLD_SECONDS"] = str(args.hold_seconds)+ plist_path.write_bytes(plistlib.dumps(configuration))+ log = pathlib.Path(packet["cwd"]) / re.search(r"> (\S+) 2>&1", packet["test"])[1]+ print(json.dumps({"testLog": str(log), "boundedHoldSeconds": args.hold_seconds,+ "clientActivation": False}), flush=True)+ process = subprocess.Popen(packet["test"], shell=True, cwd=packet["cwd"])+ advertised = False+ cutoff = time.monotonic() + args.hold_seconds + 180+ while process.poll() is None:+ if log.exists() and not advertised:+ match = re.search(r"T2383_MODERN_READINESS_ENDPOINT=(.+)", log.read_text())+ if match:+ print(pathlib.Path(match[1]).read_text(), flush=True)+ advertised = True+ if time.monotonic() >= cutoff:+ bounded_cleanup(packet, environment["TRANSIT_SMOKE_HOST_PATH"], path.parent)+ process.wait(timeout=10)+ raise RuntimeError("Fixture exceeded bounded runtime; diagnostics preserved, no proof accepted")+ time.sleep(.25)+ stages["test"] = process.returncode+ stage_path.write_text(json.dumps(stages, indent=2))+ if process.returncode:+ raise RuntimeError("Actual app fixture failed; no negotiation evidence accepted")+ match = re.search(r"T2383_MODERN_READINESS_EXPORT=(.+)", log.read_text())+ if not match:+ raise ValueError("Actual app export absent")+ source = pathlib.Path(match[1])+ destination = path.parent / "actual-readiness-trace.json"+ shutil.copyfile(source, destination)+ print(json.dumps(verify(json.loads(destination.read_text())), sort_keys=True))+++if __name__ == "__main__":+ main()
diff --git a/scripts/mcp-modern-readiness/test_verify.py b/scripts/mcp-modern-readiness/test_verify.pynew file mode 100644index 0000000..61a5255--- /dev/null+++ b/scripts/mcp-modern-readiness/test_verify.py@@ -0,0 +1,85 @@+#!/usr/bin/env python3+"""Near-valid evidence doubles test verifier sensitivity; never runtime/client proof."""+import copy+import unittest+from verify import verify+++def specimen():+ meta = {"io.modelcontextprotocol/protocolVersion": "2026-07-28",+ "io.modelcontextprotocol/clientCapabilities": {}}+ source = {"kind": "json", "payload": {"records": [{"id": "synthetic"}]}}+ structured = {"contractVersion": 1, "source": source, "presentation": {}}+ results = [{"supportedVersions": ["2026-07-28"], "capabilities": {"tools": {"listChanged": True}},+ "_meta": {"io.modelcontextprotocol/serverInfo": {"name": "transit", "version": "test"}}},+ {"tools": [{"name": "query_tasks", "inputSchema": {}, "outputSchema": {"type": "object"}}]},+ {"structuredContent": structured, "content": [{"type": "text", "text": "original"}]}]+ exchanges = []+ for index, (kind, method) in enumerate(zip(["discovery", "list", "read"],+ ["server/discover", "tools/list", "tools/call"])):+ params = {"_meta": copy.deepcopy(meta)}+ headers = {"MCP-Protocol-Version": "2026-07-28", "Mcp-Method": method,+ "Content-Type": "application/json", "Accept": "application/json"}+ if kind == "read":+ params.update(name="query_tasks", arguments={"limit": 1})+ headers["Mcp-Name"] = "query_tasks"+ exchanges.append({"kind": kind, "request": {"jsonrpc": "2.0", "id": index,+ "method": method, "params": params}, "headers": headers, "status": 200,+ "response": {"jsonrpc": "2.0", "id": index, "result": results[index]}})+ exchanges.extend([+ {"kind": "wrong-version", "status": 400, "response": {"error": {"code": -32022}}},+ {"kind": "legacy-method", "status": 404, "response": {"error": {"code": -32601}}},+ {"kind": "notification", "status": 400, "response": None}])+ return {"formatVersion": 1, "synthetic": True, "persistentStore": False,+ "endpoint": "http://127.0.0.1:9876/mcp", "exchanges": exchanges,+ "structuredConsumption": {"contractVersion": 1, "source": source},+ "subscriptionRequest": {"id": "subscription", "notifications": {"toolsListChanged": True}},+ "subscriptionFrames": [+ {"jsonrpc": "2.0", "method": "notifications/subscriptions/acknowledged", "params": {+ "notifications": {"toolsListChanged": True}, "_meta": {"io.modelcontextprotocol/subscriptionId": "subscription"}}},+ {"jsonrpc": "2.0", "id": "subscription", "result": {"resultType": "complete",+ "_meta": {"io.modelcontextprotocol/subscriptionId": "subscription"}}}],+ "sessionHeader": None, "eventIDs": [],+ "provenance": {"producer": "actual-app-test", "bundleID": "me.nore.ig.Transit.development"}}+++class EvidenceTests(unittest.TestCase):+ def test_complete_conforming_fixture_is_accepted(self):+ verify(specimen())++ def test_single_field_negotiation_mutations_reject(self):+ for field in ("protocol", "metadata", "discovery", "schema", "consumption", "correlation", "ack", "wrong-version", "legacy-method", "notification", "method", "producer", "read-error", "text"):+ trace = specimen()+ if field == "protocol": trace["exchanges"][0]["headers"]["MCP-Protocol-Version"] = "legacy"+ if field == "metadata": trace["exchanges"][0]["request"]["params"]["_meta"] = {}+ if field == "discovery": trace["exchanges"][0]["response"]["result"]["supportedVersions"] = []+ if field == "schema": del trace["exchanges"][1]["response"]["result"]["tools"][0]["outputSchema"]+ if field == "consumption": del trace["structuredConsumption"]+ if field == "correlation": trace["exchanges"][2]["response"]["id"] = "different"+ if field == "ack": trace["subscriptionFrames"].reverse()+ if field == "wrong-version": trace["exchanges"][3]["status"] = 200+ if field == "legacy-method": trace["exchanges"][4]["status"] = 200+ if field == "notification": trace["exchanges"][5]["response"] = {"id": None}+ if field == "method": trace["exchanges"][0]["request"]["method"] = "initialize"+ if field == "producer": trace["provenance"]["producer"] = "installed-client-runtime"+ if field == "read-error": trace["exchanges"][2]["response"]["result"]["isError"] = True+ if field == "text": trace["exchanges"][2]["response"]["result"]["content"] = []+ with self.subTest(field=field), self.assertRaises(ValueError): verify(trace)++ def test_binary_version_or_legacy_success_is_not_negotiation(self):+ for evidence in ({"binarySymbols": ["2026-07-28"]}, {"version": "latest"}, {"initialize": "succeeded"}):+ with self.assertRaises(ValueError): verify(evidence, installed=True, required_surfaces=("codex-cli",))++ def test_missing_intended_surface_rejects_near_valid_client_evidence(self):+ trace = specimen()+ trace["synthetic"] = False+ trace["surfaces"] = [{"surface": "codex-cli", "trace": specimen()}]+ with self.assertRaises(ValueError):+ verify(trace, installed=True, required_surfaces=("codex-cli", "codex-desktop", "claude-code", "claude-desktop"))++ def test_fixture_cannot_be_installed_client_evidence(self):+ with self.assertRaises(ValueError): verify(specimen(), installed=True, required_surfaces=("codex-cli",))+++if __name__ == "__main__":+ unittest.main()
diff --git a/scripts/mcp-modern-readiness/verify.py b/scripts/mcp-modern-readiness/verify.pynew file mode 100644index 0000000..88fbd87--- /dev/null+++ b/scripts/mcp-modern-readiness/verify.py@@ -0,0 +1,120 @@+#!/usr/bin/env python3+"""Fail closed on actual modern negotiation traces; no version/symbol inference."""+import argparse+import json+import urllib.parse++VERSION = "2026-07-28"+SUBSCRIPTION_ID = "io.modelcontextprotocol/subscriptionId"+++def require(condition, reason):+ if not condition:+ raise ValueError(reason)+++def verify(trace, *, installed=False, required_surfaces=()):+ require(isinstance(trace, dict) and trace.get("formatVersion") == 1, "Missing trace format")+ if installed:+ require(trace.get("synthetic") is False, "Synthetic fixture is not installed-client evidence")+ surfaces = trace.get("surfaces", [])+ names = [entry.get("surface") for entry in surfaces]+ require(len(names) == len(set(names)), "Duplicate client surface")+ require(set(names) == set(required_surfaces) and bool(names), "Missing intended client surface")+ for entry in surfaces:+ require(entry.get("runtimeVersion") and entry.get("captureContext"), "Missing actual runtime provenance")+ child = entry.get("trace", {})+ require(child.get("synthetic") is False, "Client trace cannot be fixture evidence")+ verify(child)+ if entry.get("subscriptionOptIn"):+ require(bool(child.get("subscriptionFrames")), "Opted-in client subscription missing")+ return {"verifiedSurfaces": names, "externalEvidence": True}+ endpoint = urllib.parse.urlsplit(trace.get("endpoint", ""))+ require(endpoint.scheme == "http" and endpoint.hostname == "127.0.0.1"+ and endpoint.port and endpoint.port > 1024 and endpoint.port != 3141+ and endpoint.path == "/mcp" and not endpoint.query and not endpoint.fragment+ and not endpoint.username and not endpoint.password, "Unsafe isolated endpoint")+ require(trace.get("persistentStore") is False, "Fixture must not address a persistent store")+ provenance = trace.get("provenance", {})+ require((trace.get("synthetic") is True and provenance.get("producer") == "actual-app-test")+ or (trace.get("synthetic") is False and provenance.get("producer") == "installed-client-runtime"),+ "Fixture/client provenance mismatch")+ require(provenance.get("producer") in ("actual-app-test", "installed-client-runtime")+ and provenance.get("bundleID") == "me.nore.ig.Transit.development", "Missing app/runtime provenance")+ exchanges = trace.get("exchanges", [])+ kinds = [entry.get("kind") for entry in exchanges]+ require(kinds[:3] == ["discovery", "list", "read"], "Missing intended negotiation exchanges")+ if trace.get("synthetic"):+ require(kinds == ["discovery", "list", "read", "wrong-version", "legacy-method", "notification"],+ "Synthetic protocol-negative evidence missing")+ wrong, legacy, notification = exchanges[3:]+ require(wrong.get("status") == 400 and wrong.get("response", {}).get("error", {}).get("code") == -32022,+ "Wrong-version rejection missing")+ require(legacy.get("status") == 404 and legacy.get("response", {}).get("error", {}).get("code") == -32601,+ "Legacy-method rejection missing")+ require(notification.get("status") == 400 and notification.get("response") is None,+ "Notification must be bodyless and rejected")+ for entry in exchanges[:3]:+ request, response, headers = entry.get("request", {}), entry.get("response", {}), entry.get("headers", {})+ require(entry.get("status") == 200 and request.get("jsonrpc") == "2.0"+ and response.get("jsonrpc") == "2.0", "Failed modern exchange")+ require(type(request.get("id")) in (str, int) and type(response.get("id")) is type(request["id"])+ and response.get("id") == request["id"], "Readable ID correlation missing")+ meta = request.get("params", {}).get("_meta", {})+ require(meta.get("io.modelcontextprotocol/protocolVersion") == VERSION+ and isinstance(meta.get("io.modelcontextprotocol/clientCapabilities"), dict), "Missing modern metadata")+ require(headers.get("MCP-Protocol-Version") == VERSION+ and headers.get("Mcp-Method") == request.get("method")+ and headers.get("Content-Type") == "application/json", "Header negotiation mismatch")+ require("application/json" in headers.get("Accept", ""), "JSON acceptance missing")+ require(exchanges[0]["request"].get("method") == "server/discover"+ and exchanges[1]["request"].get("method") == "tools/list", "Negotiation method mismatch")+ discovery = exchanges[0]["response"].get("result", {})+ require(discovery.get("supportedVersions") == [VERSION], "Modern discovery missing")+ identity = discovery.get("_meta", {}).get("io.modelcontextprotocol/serverInfo", {})+ require(identity.get("name") == "transit" and identity.get("version"), "Discovery identity missing")+ require(discovery.get("capabilities", {}).get("tools", {}).get("listChanged") is True, "Subscription capability missing")+ tools = exchanges[1]["response"].get("result", {}).get("tools", [])+ require(tools and all(isinstance(t.get("inputSchema"), dict) and isinstance(t.get("outputSchema"), dict)+ for t in tools), "Actual tool schemas missing")+ require(any(tool.get("name") == "query_tasks" for tool in tools), "Read tool missing")+ read = exchanges[2]+ require(read["request"].get("method") == "tools/call" and read["headers"].get("Mcp-Name") == "query_tasks"+ and read["request"].get("params", {}).get("name") == "query_tasks", "Read-only tool negotiation missing")+ result = read["response"].get("result", {})+ require(result.get("isError") is not True, "Read failed")+ require(any(item.get("type") == "text" and isinstance(item.get("text"), str)+ for item in result.get("content", [])), "Original text not consumable")+ structured = result.get("structuredContent", {})+ require(structured.get("contractVersion") == 1 and structured.get("source", {}).get("kind") == "json"+ and isinstance(structured.get("presentation"), dict), "Structured result missing")+ consumed = trace.get("structuredConsumption", {})+ require(consumed.get("contractVersion") == 1 and consumed.get("source") == structured["source"],+ "Native parsed structured consumption missing")+ require(isinstance(result.get("content"), list) and bool(result["content"]), "Original text missing")+ frames = trace.get("subscriptionFrames", [])+ if trace.get("synthetic") or frames:+ request = trace.get("subscriptionRequest", {})+ require(len(frames) == 2 and request.get("notifications") == {"toolsListChanged": True}, "Filter evidence missing")+ ack, complete = frames+ require(ack.get("jsonrpc") == "2.0" and ack.get("method") == "notifications/subscriptions/acknowledged",+ "Acknowledgement is not first")+ require(ack.get("params", {}).get("notifications") == request["notifications"]+ and ack.get("params", {}).get("_meta", {}).get(SUBSCRIPTION_ID) == request.get("id"), "ACK correlation/filter mismatch")+ require(complete.get("jsonrpc") == "2.0" and complete.get("id") == request.get("id")+ and complete.get("result", {}).get("resultType") == "complete"+ and complete.get("result", {}).get("_meta", {}).get(SUBSCRIPTION_ID) == request.get("id"), "Completion correlation missing")+ require(trace.get("sessionHeader") is None and trace.get("eventIDs") == [], "Legacy session/event-ID transport")+ return {"verifiedExchanges": len(exchanges), "structuredConsumption": True,+ "synthetic": trace.get("synthetic"), "installedEvidence": False}+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument("trace")+ parser.add_argument("--installed", action="store_true")+ parser.add_argument("--surfaces", nargs="*", default=[])+ args = parser.parse_args()+ with open(args.trace, encoding="utf-8") as stream:+ result = verify(json.load(stream), installed=args.installed, required_surfaces=args.surfaces)+ print(json.dumps(result, sort_keys=True))
diff --git a/specs/bounded-read-freshness/prototype/CaptureProbe.swift b/specs/bounded-read-freshness/prototype/CaptureProbe.swiftnew file mode 100644index 0000000..96e97d8--- /dev/null+++ b/specs/bounded-read-freshness/prototype/CaptureProbe.swift@@ -0,0 +1,51 @@+// DESIGN PROTOTYPE ONLY: isolated on-disk store, CloudKit disabled, no Transit models.+import Foundation+import SwiftData++@Model final class ProbeProject {+ var name: String = ""+ init(name: String) { self.name = name }+}+@Model final class ProbeTask {+ var projectName: String = ""+ init(projectName: String) { self.projectName = projectName }+}++@main struct CaptureProbe {+ @MainActor static func main() throws {+ let url = URL(fileURLWithPath: CommandLine.arguments[1])+ let schema = Schema([ProbeProject.self, ProbeTask.self])+ let config = ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none)+ let container = try ModelContainer(for: schema, configurations: [config])+ let writer = ModelContext(container)+ writer.autosaveEnabled = false+ let project = ProbeProject(name: "old")+ let task = ProbeTask(projectName: "old")+ writer.insert(project); writer.insert(task)+ try writer.save()+ func watermark(_ context: ModelContext) throws -> DefaultHistoryTransaction? {+ var d = HistoryDescriptor<DefaultHistoryTransaction>(sortBy: [SortDescriptor(\.transactionIdentifier, order: .reverse)])+ d.fetchLimit = 1+ return try context.fetchHistory(d).first+ }+ func capture(injectWrite: Bool) throws -> (consistent: Bool, names: [String], store: String) {+ let before = try watermark(ModelContext(container))+ let reader = ModelContext(container)+ reader.autosaveEnabled = false+ let projects = try reader.fetch(FetchDescriptor<ProbeProject>()).map(\.name)+ if injectWrite {+ project.name = "new"; task.projectName = "new"+ try writer.save()+ }+ let tasks = try reader.fetch(FetchDescriptor<ProbeTask>()).map(\.projectName)+ let after = try watermark(ModelContext(container))+ let coherent = before?.token == after?.token && before?.storeIdentifier == after?.storeIdentifier+ return (coherent, projects + tasks, after?.storeIdentifier ?? "unknown")+ }+ let mixed = try capture(injectWrite: true)+ precondition(!mixed.consistent, "a saved change spanning selected tables must invalidate capture")+ let stable = try capture(injectWrite: false)+ precondition(stable.consistent && stable.names == ["new", "new"])+ print("PASS mixed_capture_rejected=true fresh_saved_write_visible=true stable_history_watermark=true store_identifier_known=\(!stable.store.isEmpty && stable.store != "unknown") mixed_values=\(mixed.names) stable_values=\(stable.names)")+ }+}
diff --git a/specs/bounded-read-freshness/prototype/DeadlineProbe.swift b/specs/bounded-read-freshness/prototype/DeadlineProbe.swiftnew file mode 100644index 0000000..2bf69c8--- /dev/null+++ b/specs/bounded-read-freshness/prototype/DeadlineProbe.swift@@ -0,0 +1,112 @@+// DESIGN PROTOTYPE ONLY: not part of Transit app or production implementation.+import Foundation+import Dispatch++nonisolated final class Admission: @unchecked Sendable {+ private let lock = NSLock()+ private var count = 0+ private var generation = 0+ func reserve() -> Bool {+ lock.lock(); defer { lock.unlock() }+ guard count < 8 else { return false }+ count += 1+ return true+ }+ func finishPhysicalWork() { lock.lock(); count -= 1; lock.unlock() }+ func restart() { lock.lock(); generation += 1; lock.unlock() }+ func unfinished() -> Int { lock.lock(); defer { lock.unlock() }; return count }+}++nonisolated final class ResultGate: @unchecked Sendable {+ private let lock = NSLock()+ private var result: Data?+ private var waiter: CheckedContinuation<Data, Never>?+ private(set) var published = false+ let deadline: UInt64+ let timeout: Data+ init(id: Int, admitted: UInt64) {+ // Reserve encoding/delivery headroom inside the five-second contract.+ deadline = admitted + 4_850_000_000+ timeout = Data("{\"jsonrpc\":\"2.0\",\"id\":\(id),\"result\":{\"isError\":true,\"content\":[{\"type\":\"text\",\"text\":\"READ_TIMEOUT\"}]}}".utf8)+ }+ func offer(_ bytes: Data, publish: Bool) {+ lock.lock()+ guard result == nil else { lock.unlock(); return }+ let inTime = DispatchTime.now().uptimeNanoseconds < deadline+ result = inTime ? bytes : timeout+ published = publish && inTime+ let saved = result!+ let continuation = waiter+ waiter = nil+ lock.unlock()+ continuation?.resume(returning: saved)+ }+ func expire() { offer(timeout, publish: false) }+ @concurrent func value() async -> Data {+ await withCheckedContinuation { continuation in+ lock.lock()+ if let saved = result { lock.unlock(); continuation.resume(returning: saved) }+ else { waiter = continuation; lock.unlock() }+ }+ }+ func didPublish() -> Bool { lock.lock(); defer { lock.unlock() }; return published }+}++@MainActor func nonCooperativeCapture(id: Int, gate: ResultGate) {+ if id == 0 { Thread.sleep(forTimeInterval: 6.0) }+ gate.offer(Data("{\"result\":\"captured\"}".utf8), publish: true)+}++@concurrent nonisolated func runProbe() async {+ let admission = Admission()+ let timers = DispatchQueue(label: "t63.design.deadline", qos: .userInitiated, attributes: .concurrent)+ let start = DispatchTime.now().uptimeNanoseconds+ var gates: [ResultGate] = []+ var sources: [DispatchSourceTimer] = []+ for id in 0..<8 {+ precondition(admission.reserve())+ let gate = ResultGate(id: id, admitted: start)+ gates.append(gate)+ let source = DispatchSource.makeTimerSource(flags: .strict, queue: timers)+ source.setEventHandler { gate.expire() }+ source.schedule(deadline: DispatchTime(uptimeNanoseconds: gate.deadline), leeway: .nanoseconds(0))+ source.resume()+ sources.append(source)+ Task.detached {+ await nonCooperativeCapture(id: id, gate: gate)+ admission.finishPhysicalWork()+ }+ // Ensure the blocked read enters MainActor before scheduling queued reads.+ if id == 0 { try! await Task.sleep(for: .milliseconds(100)) }+ }+ admission.restart()+ precondition(!admission.reserve(), "restart must not reset physical capacity")+ var times: [Double] = []+ var responses: [Data] = []+ for gate in gates {+ responses.append(await gate.value())+ times.append(Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000)+ }+ let encodedBatch = Data(([UInt8]("[".utf8) + responses.enumerated().flatMap {+ ($0.offset == 0 ? [] : [UInt8](",".utf8)) + [UInt8]($0.element)+ } + [UInt8]("]".utf8)))+ precondition((try! JSONSerialization.jsonObject(with: encodedBatch)) is [Any])+ let batchMs = Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000+ let unfinishedAtTimeout = admission.unfinished()+ sources.forEach { $0.cancel() }+ FileHandle.standardOutput.write(Data("MEASURE batch_ms=\(batchMs) response_ms=\(times) unfinished=\(unfinishedAtTimeout)\n".utf8))+ precondition(times.max()! < 5_000 && batchMs < 5_000)+ precondition(unfinishedAtTimeout == 8, "timed-out work must retain its slots")+ precondition(gates.allSatisfy { !$0.didPublish() })+ try! await Task.sleep(for: .milliseconds(1_500))+ precondition(admission.unfinished() == 0)+ precondition(gates.allSatisfy { !$0.didPublish() }, "late capture must not publish")+ print("PASS blocked_mainactor_ms=6000 encoded_batch_ms=\(String(format: "%.2f", batchMs)) max_response_ms=\(String(format: "%.2f", times.max()!)) unfinished_at_timeout=\(unfinishedAtTimeout) unfinished_after_completion=\(admission.unfinished()) late_publications=0 restart_busy=true bytes=\(encodedBatch.count)")+}++@main struct Probe {+ static func main() async {+ // Detached driver is independent of the deliberately blocked MainActor.+ await Task.detached { await runProbe() }.value+ }+}
diff --git a/specs/development-isolation/source-checkpoint.json b/specs/development-isolation/source-checkpoint.jsonnew file mode 100644index 0000000..dc396a3--- /dev/null+++ b/specs/development-isolation/source-checkpoint.json@@ -0,0 +1,53 @@+{+ "base": "36f7ee328f53250413beff825af3ae826e25d3d0",+ "branch": "fix/development-store-isolation",+ "capturedAtUTC": "2026-10-03T16:29:36.863910+00:00",+ "standaloneRuntimeVerified": true,+ "fullAppBuildVerified": true,+ "appHostTestsExecuted": true,+ "fileSHA256": {+ "Makefile": "b820f4365bcd368424b5e1b6a0970a59c5e57075f68ae35ab7a756a200ddde53",+ "Transit/Configuration/Development.entitlements": "113894d862d16acfe98a0f6ac1e66ee1dea26d011f8364077200a7eaa7bd2e8b",+ "Transit/Configuration/DevelopmentInfo.plist": "8f127347ad7e45f9965ac45f83c2fe59465702b55ca3bbce744020576bfbbd35",+ "Transit/Transit.xcodeproj/project.pbxproj": "207934daaf68fae13c31519b428b8100e552a0a99353b0a8525ae6a4e2bd79cd",+ "Transit/Transit.xcodeproj/xcshareddata/xcschemes/Transit.xcscheme": "122e6f8c1316fcd094b39d0accdf9057c3cc36211b748326debd3335d4b9f136",+ "Transit/Transit.xcodeproj/xcshareddata/xcschemes/TransitDevelopment.xcscheme": "95470af1b11951dbab18d30d6de00b32ca46c288901fcd92f922ca8582ef2d8b",+ "Transit/Transit/MCP/Reads/MCPReadService.swift": "c331be9a98b2017e9d68b9488ed64104b9ce6ef8db343a2acef42da653ba07c5",+ "Transit/Transit/Services/AppPersistencePolicy.swift": "c35e81fc7e0aae2e32d6d4ee9eecc9455b6af689c3d478dae32c97fbe71b2e78",+ "Transit/Transit/Services/IsolatedPersistenceConfiguration.swift": "910c39003c4588514896739cae477aa5a81d267121aa0322034f86c4fd873e8b",+ "Transit/Transit/Services/SyncManager.swift": "1eaa400257ccb6fc0004ce974922d05992666e2cd0902504ae1fb34fd51459d4",+ "Transit/Transit/TransitApp.swift": "e36b89ab0f652a8972196f610408ed7fdad5c32471cf19beddd61053947a3eb1",+ "Transit/Transit/Views/Settings/SettingsView.swift": "85d64469fe1e48c1b8fff9fcc7959a0dd5ffb9ae4c82fb7a1be0478828eb7a16",+ "Transit/TransitUITests/DataMaintenanceUITests.swift": "b63c85ad4dcd39b338a00f102d998ca7120c3c0aab1b22df6ea38d36621e5dc6",+ "Transit/TransitUITests/SearchEmptyStateUITests.swift": "ee2f95a1e7cd1c7d743eaff5ec3430c41f803b4d0b9c2812076f3d43de984e61",+ "Transit/TransitUITests/TransitUITests.swift": "c6941d52a12fb07a42d09c6445c5bb2f1fb605f164b0c4d96f2b1393ce724341",+ "Transit/TransitUITests/TransitUITestsLaunchTests.swift": "80520f13cd9573852ba6ca1f665a92fd2c454f73598c7a5b3a7a7dc3cc19e50a",+ "specs/development-isolation/component-handoff.md": "295065256eb8ec8a3c1adf844a03b68cea32bf2b708a226d660662508dc93be0",+ "specs/development-isolation/implementation.md": "6edf47056db31e2688f7e455b033e9be90348902ec2b687020514031ed003bd2",+ "specs/development-isolation/source-review.md": "8afef007621ca805bf343f645b43c9662a6f0cdda32ce36e4ca00ef242036dd1",+ "specs/development-isolation/verification/build-after-t63-fix.json": "17fead1ed37d06587fdeb5bc874705c8ebfbc18562d9b541bfd899d3de8cddaf",+ "specs/development-isolation/verification/build-diagnostics.json": "16142b2bf67ae2f683be9d4f536acfa98efe123b76993670aa32fa7d5d2df42f",+ "specs/development-isolation/verification/isolation-verification.json": "dc93dcae4c5337aafd169fa135d4c68d6bcf5a056ce94794390f5615a0174cd4",+ "tests/development-isolation/MigrationProbe.swift": "5faeb34ded8911af6d455892f1c343ecd51591c108d78643764b1f000b4e08da",+ "tests/development-isolation/PolicyProbe.swift": "990b76373dc6fce5ffdac5f9838e9b79e9782e4f87932769cb400c15be92856d",+ "tests/development-isolation/configuration_guard.py": "6d77011b5c42383fa8f0c4298cbb6f66046f04c3881043040e984c61a675adfb",+ "tests/development-isolation/run.py": "006d6336a9ca40842b7a470eb432f99d0f5ba87ed36894bdcde0332f337296ce",+ "Transit/Transit/Services/AppDisplayIDAllocators.swift": "2d78db6a13b7c391930a58a67c9d135b9801b7489ebbee5b591ef4092f3b8561",+ "tests/development-isolation/BootstrapProbe.swift": "b4b7e73dc4b12f66561fa35dd21418b095a12ccb8e17864e721bfc3eb986a7ad",+ "specs/development-isolation/verification/build-after-bootstrap.json": "657bbc615f92165cd8520d007061f6dea88ae3e4522b51c6ecd9b537dd83ed4b",+ "Transit/Transit/Services/AppIsolationSmoke.swift": "0a25b4350075c0587f816226c690952bc91b8647cd4e5514c9968da02ea7f981",+ "Transit/TransitIsolationSmokeTests/DevelopmentIsolationSmokeTests.swift": "46adefadceb2daecf7accff820d2a3f44bd8e2cf4117dcfae62a959d926a96be",+ "Transit/Transit.xcodeproj/xcshareddata/xcschemes/TransitIsolationSmoke.xcscheme": "021e9cdeeac83d08e5bd1e37c585f947ca9e9772235ad635c557f24fa030637e",+ "tests/development-isolation/host_smoke.py": "e51e09e3876ec7fbacad6d128e27180cbfb297ea039a93398f44736be3440e0e",+ "specs/development-isolation/verification/host-smoke.json": "ba930f8ea99cb1f1be388c7a56fb3bb3e1f3031a4d5fe27f46b916d33ac3c309",+ "specs/development-isolation/verification/host-smoke.log": "86aa462d9659316920a6c393eeeb771ef536f5b2526cb6ece0f13ac6dc1d2432"+ },+ "appHostIsolationReleased": false,+ "T63FixApplied": "46bec7c386624ce755c11940ef58bf046999cb02",+ "reviewBlocker": null,+ "bootstrapFindingResolved": true,+ "remainingReviewFinding": null,+ "focusedHostSmokeVerified": true,+ "focusedHostTestsExecuted": 1,+ "broaderAppHostIsolationReleased": false+}
diff --git a/specs/development-isolation/verification/build-after-bootstrap.json b/specs/development-isolation/verification/build-after-bootstrap.jsonnew file mode 100644index 0000000..e4dec0a--- /dev/null+++ b/specs/development-isolation/verification/build-after-bootstrap.json@@ -0,0 +1,25 @@+{+ "command": "make build-development-macos > DerivedData/isolation-build-after-bootstrap.log 2>&1",+ "completedAtUTC": "2026-10-03T16:15:03.819947+00:00",+ "exit": 0,+ "target": "TransitDevelopment",+ "configuration": "Debug",+ "bundleID": "me.nore.ig.Transit.development",+ "signingAllowed": false,+ "install": false,+ "appLaunch": false,+ "appHostTests": false,+ "compilerSandboxDisabled": false,+ "runtimeNetwork": "denied by sandbox-exec",+ "runtimeLiveContainers": "denied by sandbox-exec",+ "bootstrapFactoryInvocationsInIsolatedModes": 0,+ "activeProductionCounterNames": [+ "global-counter",+ "milestone-counter"+ ],+ "lint": {+ "files": 443,+ "violations": 0+ },+ "testIsolationReleased": false+}
diff --git a/specs/development-isolation/verification/build-after-t63-fix.json b/specs/development-isolation/verification/build-after-t63-fix.jsonnew file mode 100644index 0000000..cbe9c08--- /dev/null+++ b/specs/development-isolation/verification/build-after-t63-fix.json@@ -0,0 +1,17 @@+{+ "command": "make build-development-macos > DerivedData/isolation-build-after-t63-fix.log 2>&1",+ "completedAtUTC": "2026-10-03T16:02:36.034704+00:00",+ "exit": 0,+ "target": "TransitDevelopment",+ "configuration": "Debug",+ "bundleID": "me.nore.ig.Transit.development",+ "displayName": "Transit Development",+ "executable": "TransitDevelopment",+ "signingAllowed": false,+ "install": false,+ "appLaunch": false,+ "appHostTests": false,+ "T63SourceMatchesCommit": "46bec7c386624ce755c11940ef58bf046999cb02",+ "testIsolationReleased": false,+ "remainingReviewFinding": "Inactive DisplayIDAllocator convenience initializer constructs default CloudKit container/database handles"+}
diff --git a/specs/development-isolation/verification/build-diagnostics.json b/specs/development-isolation/verification/build-diagnostics.jsonnew file mode 100644index 0000000..faf2773--- /dev/null+++ b/specs/development-isolation/verification/build-diagnostics.json@@ -0,0 +1,12 @@+{+ "command": "make build-development-macos",+ "makeExit": 2,+ "xcodebuildExit": 65,+ "activityLog": "DerivedData/Logs/Build/A9DFCFAF-4788-4CF4-8D39-5CDA6ADB9AAE.xcactivitylog",+ "errors": [+ "/Users/arjen/Documents/Codex/2026-10-02/task/transit-isolation/Transit/Transit/MCP/Reads/MCPReadService.swift:97:26: error: non-Sendable type '() -> MCPReadImportApplicability' of property 'applicability' cannot exit main actor-isolated context [#NonSendableExitingActor]",+ "/Users/arjen/Documents/Codex/2026-10-02/task/transit-isolation/Transit/Transit/MCP/Reads/MCPReadService.swift:97:26: error: main actor-isolated property 'applicability' cannot be accessed from outside of the actor"+ ],+ "appLaunch": false,+ "appHostTests": false+}
diff --git a/specs/development-isolation/verification/host-smoke.json b/specs/development-isolation/verification/host-smoke.jsonnew file mode 100644index 0000000..5b8de77--- /dev/null+++ b/specs/development-isolation/verification/host-smoke.json@@ -0,0 +1,38 @@+{+ "bundleID": "me.nore.ig.Transit.development",+ "host": "/Users/arjen/Documents/Codex/2026-10-02/task/transit-isolation/DerivedData/isolation-host/Build/Products/Debug/TransitDevelopment.app",+ "entitlements": {+ "com.apple.security.app-sandbox": true,+ "com.apple.security.files.user-selected.read-only": true,+ "com.apple.security.get-task-allow": true,+ "com.apple.security.network.client": true,+ "com.apple.security.network.server": true,+ "com.apple.security.temporary-exception.files.absolute-path.read-only": [+ "/"+ ],+ "com.apple.security.temporary-exception.mach-lookup.global-name": [+ "com.apple.testmanagerd",+ "com.apple.dt.testmanagerd.runner",+ "com.apple.coresymbolicationd"+ ]+ },+ "mode": "unit-test",+ "fixture": "TransitIsolationSmokeTests/DevelopmentIsolationSmokeTests",+ "parallel": false,+ "completedAtUTC": "2026-10-03T16:29:36.863910+00:00",+ "testsPassed": 1,+ "suitesPassed": 1,+ "exit": 0,+ "effectiveStoreURL": "/dev/null",+ "memoryOnly": true,+ "cloudSyncActive": false,+ "disabledCounterAdapters": true,+ "sidecarScope": "me.nore.ig.Transit.development/Data/tmp/mcp-tests-*",+ "preflightBeforeModelContainer": true,+ "installedProductionAppLaunched": false,+ "MCPEnabled": false,+ "broaderSuitesRun": false,+ "workersDrained": true,+ "liveStoreEvidence": "Preflight requires memory-only/no CloudKit/no App Group before the app container factory; actual effective configuration is /dev/null. No independent system-wide file-open trace was taken.",+ "initialSharedTestBuild": "Blocked by existing MCP read-test compile errors; no launch. Dedicated target compiles only the smoke fixture."+}
diff --git a/specs/development-isolation/verification/host-smoke.log b/specs/development-isolation/verification/host-smoke.lognew file mode 100644index 0000000..4be1803--- /dev/null+++ b/specs/development-isolation/verification/host-smoke.log@@ -0,0 +1,69 @@+{+ "bundleID": "me.nore.ig.Transit.development",+ "host": "/Users/arjen/Documents/Codex/2026-10-02/task/transit-isolation/DerivedData/isolation-host/Build/Products/Debug/TransitDevelopment.app",+ "entitlements": {+ "com.apple.security.app-sandbox": true,+ "com.apple.security.files.user-selected.read-only": true,+ "com.apple.security.get-task-allow": true,+ "com.apple.security.network.client": true,+ "com.apple.security.network.server": true,+ "com.apple.security.temporary-exception.files.absolute-path.read-only": [+ "/"+ ],+ "com.apple.security.temporary-exception.mach-lookup.global-name": [+ "com.apple.testmanagerd",+ "com.apple.dt.testmanagerd.runner",+ "com.apple.coresymbolicationd"+ ]+ },+ "mode": "unit-test",+ "fixture": "TransitIsolationSmokeTests/DevelopmentIsolationSmokeTests",+ "parallel": false+}+Command line invocation:+ /Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild test-without-building -xctestrun /Users/arjen/Documents/Codex/2026-10-02/task/transit-isolation/DerivedData/isolation-host/Build/Products/IsolationSmoke.xctestrun -destination platform=macOS,arch=arm64 -parallel-testing-enabled NO "-only-testing:TransitIsolationSmokeTests/DevelopmentIsolationSmokeTests" -resultBundlePath /Users/arjen/Documents/Codex/2026-10-02/task/transit-isolation/DerivedData/isolation-host/Build/Products/IsolationSmoke.xcresult++Writing result bundle at path:+ /Users/arjen/Documents/Codex/2026-10-02/task/transit-isolation/DerivedData/isolation-host/Build/Products/IsolationSmoke.xcresult++--- xcodebuild: WARNING: Using the first of multiple matching destinations:+{ platform:macOS, arch:arm64, id:00006001-001011E20C45801E, name:My Mac }+{ platform:macOS, arch:arm64, variant:Mac Catalyst, id:00006001-001011E20C45801E, name:My Mac }+{ platform:macOS, arch:arm64, variant:DriverKit, id:00006001-001011E20C45801E, name:My Mac }+{ platform:macOS, arch:arm64, variant:Designed for [iPad,iPhone], id:00006001-001011E20C45801E, name:My Mac }+2026-10-04 03:26:21.981929+1100 TransitDevelopment[28383:41332880] [Connection] Unable to get synchronousRemoteObjectProxy, error: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.linkd.autoShortcut" UserInfo={NSDebugDescription=connection to service named com.apple.linkd.autoShortcut}+2026-10-04 03:26:21.982449+1100 TransitDevelopment[28383:41332880] [Application] Error registering app with intents framework: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.linkd.autoShortcut" UserInfo={NSDebugDescription=connection to service named com.apple.linkd.autoShortcut}+2026-10-04 03:26:21.982738+1100 TransitDevelopment[28383:41332897] [Connection] Unable to get synchronousRemoteObjectProxy, error: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.linkd.autoShortcut" UserInfo={NSDebugDescription=connection to service named com.apple.linkd.autoShortcut}+2026-10-04 03:26:21.982756+1100 TransitDevelopment[28383:41332897] [Connection] Unable to re-register with Process Instance Registry, error: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.linkd.autoShortcut" UserInfo={NSDebugDescription=connection to service named com.apple.linkd.autoShortcut}+2026-10-04 03:26:21.983374+1100 TransitDevelopment[28383:41332880] [Connection] Unable to get synchronousRemoteObjectProxy, error: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.linkd.autoShortcut" UserInfo={NSDebugDescription=connection to service named com.apple.linkd.autoShortcut}+2026-10-04 03:26:21.983409+1100 TransitDevelopment[28383:41332880] [Connection] Unable to re-register with Process Instance Registry, error: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.linkd.autoShortcut" UserInfo={NSDebugDescription=connection to service named com.apple.linkd.autoShortcut}+2026-10-04 03:26:21.983969+1100 TransitDevelopment[28383:41332880] [Connection] Will NOT re-try to establish the connection+2026-10-04 03:26:21.983999+1100 TransitDevelopment[28383:41332935] [Connection] Unable to get synchronousRemoteObjectProxy, error: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.linkd.autoShortcut" UserInfo={NSDebugDescription=connection to service named com.apple.linkd.autoShortcut}+2026-10-04 03:26:21.984015+1100 TransitDevelopment[28383:41332935] [Connection] Unable to re-register with Process Instance Registry, error: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.linkd.autoShortcut" UserInfo={NSDebugDescription=connection to service named com.apple.linkd.autoShortcut}+2026-10-04 03:26:22.208034+1100 TransitDevelopment[28383:41332738] ApplePersistenceIgnoreState: Existing state will not be touched. New state will be written to /Users/arjen/Library/Containers/me.nore.ig.Transit.development/Data/tmp/me.nore.ig.Transit.development.savedState+Test Suite 'Selected tests' started at 2026-10-04 03:26:23.161.+Test Suite 'TransitIsolationSmokeTests.xctest' started at 2026-10-04 03:26:23.162.+Test Suite 'TransitIsolationSmokeTests.xctest' passed at 2026-10-04 03:26:23.162.+ Executed 0 tests, with 0 failures (0 unexpected) in 0.000 (0.000) seconds+Test Suite 'Selected tests' passed at 2026-10-04 03:26:23.162.+ Executed 0 tests, with 0 failures (0 unexpected) in 0.000 (0.001) seconds+◇ Test run started.+↳ Testing Library Version: 2084+↳ Target Platform: arm64e-apple-macos14.0+◇ Suite DevelopmentIsolationSmokeTests started.+◇ Test "Actual isolated host bootstrap uses no persistent or CloudKit store" started.+Isolated host mode=unit-test memoryOnly=true cloudSync=false disabledCounters=true+Isolated host configuration URL=/dev/null sidecar=/Users/arjen/Library/Containers/me.nore.ig.Transit.development/Data/tmp/mcp-tests-DAB4F472-FB5B-4149-9AAA-8B328E99C9C6+✔ Test "Actual isolated host bootstrap uses no persistent or CloudKit store" passed after 0.001 seconds.+✔ Suite DevelopmentIsolationSmokeTests passed after 0.001 seconds.+✔ Test run with 1 test in 1 suite passed after 0.001 seconds.+2026-10-04 03:26:23.444 xcodebuild[28374:41332629] [MT] IDETestOperationsObserverDebug: 2.894 elapsed -- Testing started completed.+2026-10-04 03:26:23.444 xcodebuild[28374:41332629] [MT] IDETestOperationsObserverDebug: 0.000 sec, +0.000 sec -- start+2026-10-04 03:26:23.444 xcodebuild[28374:41332629] [MT] IDETestOperationsObserverDebug: 2.894 sec, +2.894 sec -- end++Test session results, code coverage, and logs:+ /Users/arjen/Documents/Codex/2026-10-02/task/transit-isolation/DerivedData/isolation-host/Build/Products/IsolationSmoke.xcresult++** TEST EXECUTE SUCCEEDED **++Testing started
diff --git a/specs/development-isolation/verification/isolation-verification.json b/specs/development-isolation/verification/isolation-verification.jsonnew file mode 100644index 0000000..e1f2e9c--- /dev/null+++ b/specs/development-isolation/verification/isolation-verification.json@@ -0,0 +1,234 @@+{+ "cloudKit": "none",+ "network": "denied by sandbox-exec",+ "liveContainer": "denied by sandbox-exec",+ "cases": [+ {+ "name": "sequential",+ "seed": {+ "mode": "seed-old",+ "exit": 0,+ "stdout": "{\"linkedProjectNames\":[\"Synthetic\"],\"phase\":\"seed-old\",\"projectCount\":1,\"projectionRevisions\":[\"r1:f6872c051509fa5d883f828e3944806a10808cabdf992bec848719120d1151fb\"],\"projectNames\":[\"Synthetic\"],\"taskCount\":1,\"taskIDs\":[\"84589B3C-C9EB-48BC-9894-1957326A7DC5\"],\"taskRecords\":[{\"displayID\":1,\"id\":\"84589B3C-C9EB-48BC-9894-1957326A7DC5\",\"projectID\":\"8249C061-AE29-42CF-A713-2EE7BF24BEAA\",\"status\":\"idea\"}]}\n",+ "stderr": ""+ },+ "before": {+ "entities": [+ [+ 1,+ "Comment"+ ],+ [+ 2,+ "Milestone"+ ],+ [+ 3,+ "Project"+ ],+ [+ 4,+ "SyncHeartbeat"+ ],+ [+ 5,+ "TransitTask"+ ],+ [+ 16001,+ "CHANGE"+ ],+ [+ 16002,+ "TRANSACTION"+ ],+ [+ 16003,+ "TRANSACTIONSTRING"+ ]+ ],+ "taskEntityCounts": [+ [+ 5,+ 1+ ]+ ],+ "taskUUIDDuplicates": 0,+ "quickCheck": "ok"+ },+ "new": {+ "mode": "open-new",+ "exit": 0,+ "stdout": "{\"linkedProjectNames\":[\"Synthetic\"],\"phase\":\"before-new-save\",\"projectCount\":1,\"projectionRevisions\":[\"r1:f6872c051509fa5d883f828e3944806a10808cabdf992bec848719120d1151fb\"],\"projectNames\":[\"Synthetic\"],\"taskCount\":1,\"taskIDs\":[\"84589B3C-C9EB-48BC-9894-1957326A7DC5\"],\"taskRecords\":[{\"displayID\":1,\"id\":\"84589B3C-C9EB-48BC-9894-1957326A7DC5\",\"projectID\":\"8249C061-AE29-42CF-A713-2EE7BF24BEAA\",\"status\":\"idea\"}]}\n{\"linkedProjectNames\":[\"Synthetic\"],\"phase\":\"open-new\",\"projectCount\":1,\"projectionRevisions\":[\"r1:f6872c051509fa5d883f828e3944806a10808cabdf992bec848719120d1151fb\"],\"projectNames\":[\"Synthetic\"],\"receipt\":{\"id\":\"FE6D20F5-E8CD-4C7E-84E4-BB68D7D81649\",\"key\":\"synthetic-key\",\"state\":\"accepted\"},\"taskCount\":1,\"taskIDs\":[\"84589B3C-C9EB-48BC-9894-1957326A7DC5\"],\"taskRecords\":[{\"displayID\":1,\"id\":\"84589B3C-C9EB-48BC-9894-1957326A7DC5\",\"projectID\":\"8249C061-AE29-42CF-A713-2EE7BF24BEAA\",\"status\":\"idea\"}]}\n",+ "stderr": ""+ },+ "after": {+ "entities": [+ [+ 1,+ "Comment"+ ],+ [+ 2,+ "MCPWriteReceipt"+ ],+ [+ 3,+ "Milestone"+ ],+ [+ 4,+ "Project"+ ],+ [+ 5,+ "SyncHeartbeat"+ ],+ [+ 6,+ "TransitTask"+ ],+ [+ 16001,+ "CHANGE"+ ],+ [+ 16002,+ "TRANSACTION"+ ],+ [+ 16003,+ "TRANSACTIONSTRING"+ ]+ ],+ "taskEntityCounts": [+ [+ 6,+ 1+ ]+ ],+ "taskUUIDDuplicates": 0,+ "quickCheck": "ok"+ }+ },+ {+ "name": "concurrent",+ "seed": {+ "mode": "seed-old",+ "exit": 0,+ "stdout": "{\"linkedProjectNames\":[\"Synthetic\"],\"phase\":\"seed-old\",\"projectCount\":1,\"projectionRevisions\":[\"r1:16a9261fe6f4841a5c7698cedbe343a97c81f937c970b4db86b1ab1a909792cb\"],\"projectNames\":[\"Synthetic\"],\"taskCount\":1,\"taskIDs\":[\"BF55C870-1169-4EAB-9F7E-67E70F9FC56B\"],\"taskRecords\":[{\"displayID\":1,\"id\":\"BF55C870-1169-4EAB-9F7E-67E70F9FC56B\",\"projectID\":\"F216AA77-B606-4613-859B-4EF6526FE6B0\",\"status\":\"idea\"}]}\n",+ "stderr": ""+ },+ "before": {+ "entities": [+ [+ 1,+ "Comment"+ ],+ [+ 2,+ "Milestone"+ ],+ [+ 3,+ "Project"+ ],+ [+ 4,+ "SyncHeartbeat"+ ],+ [+ 5,+ "TransitTask"+ ],+ [+ 16001,+ "CHANGE"+ ],+ [+ 16002,+ "TRANSACTION"+ ],+ [+ 16003,+ "TRANSACTIONSTRING"+ ]+ ],+ "taskEntityCounts": [+ [+ 5,+ 1+ ]+ ],+ "taskUUIDDuplicates": 0,+ "quickCheck": "ok"+ },+ "oldReady": "{\"linkedProjectNames\":[\"Synthetic\"],\"phase\":\"READY\",\"projectCount\":1,\"projectionRevisions\":[\"r1:16a9261fe6f4841a5c7698cedbe343a97c81f937c970b4db86b1ab1a909792cb\"],\"projectNames\":[\"Synthetic\"],\"taskCount\":1,\"taskIDs\":[\"BF55C870-1169-4EAB-9F7E-67E70F9FC56B\"],\"taskRecords\":[{\"displayID\":1,\"id\":\"BF55C870-1169-4EAB-9F7E-67E70F9FC56B\",\"projectID\":\"F216AA77-B606-4613-859B-4EF6526FE6B0\",\"status\":\"idea\"}]}",+ "new": {+ "mode": "open-new",+ "exit": 0,+ "stdout": "{\"linkedProjectNames\":[\"Synthetic\"],\"phase\":\"before-new-save\",\"projectCount\":1,\"projectionRevisions\":[\"r1:16a9261fe6f4841a5c7698cedbe343a97c81f937c970b4db86b1ab1a909792cb\"],\"projectNames\":[\"Synthetic\"],\"taskCount\":1,\"taskIDs\":[\"BF55C870-1169-4EAB-9F7E-67E70F9FC56B\"],\"taskRecords\":[{\"displayID\":1,\"id\":\"BF55C870-1169-4EAB-9F7E-67E70F9FC56B\",\"projectID\":\"F216AA77-B606-4613-859B-4EF6526FE6B0\",\"status\":\"idea\"}]}\n{\"linkedProjectNames\":[\"Synthetic\"],\"phase\":\"open-new\",\"projectCount\":1,\"projectionRevisions\":[\"r1:16a9261fe6f4841a5c7698cedbe343a97c81f937c970b4db86b1ab1a909792cb\"],\"projectNames\":[\"Synthetic\"],\"receipt\":{\"id\":\"5DF046C9-8B3A-4960-B72E-EA17694B3FEC\",\"key\":\"synthetic-key\",\"state\":\"accepted\"},\"taskCount\":1,\"taskIDs\":[\"BF55C870-1169-4EAB-9F7E-67E70F9FC56B\"],\"taskRecords\":[{\"displayID\":1,\"id\":\"BF55C870-1169-4EAB-9F7E-67E70F9FC56B\",\"projectID\":\"F216AA77-B606-4613-859B-4EF6526FE6B0\",\"status\":\"idea\"}]}\n",+ "stderr": ""+ },+ "oldRead": "{\"linkedProjectNames\":[\"Synthetic\"],\"phase\":\"READ\",\"projectCount\":1,\"projectionRevisions\":[\"r1:16a9261fe6f4841a5c7698cedbe343a97c81f937c970b4db86b1ab1a909792cb\"],\"projectNames\":[\"Synthetic\"],\"taskCount\":1,\"taskIDs\":[\"BF55C870-1169-4EAB-9F7E-67E70F9FC56B\"],\"taskRecords\":[{\"displayID\":1,\"id\":\"BF55C870-1169-4EAB-9F7E-67E70F9FC56B\",\"projectID\":\"F216AA77-B606-4613-859B-4EF6526FE6B0\",\"status\":\"idea\"}]}",+ "oldExit": 0,+ "oldStderr": "",+ "after": {+ "entities": [+ [+ 1,+ "Comment"+ ],+ [+ 2,+ "MCPWriteReceipt"+ ],+ [+ 3,+ "Milestone"+ ],+ [+ 4,+ "Project"+ ],+ [+ 5,+ "SyncHeartbeat"+ ],+ [+ 6,+ "TransitTask"+ ],+ [+ 16001,+ "CHANGE"+ ],+ [+ 16002,+ "TRANSACTION"+ ],+ [+ 16003,+ "TRANSACTIONSTRING"+ ]+ ],+ "taskEntityCounts": [+ [+ 6,+ 1+ ]+ ],+ "taskUUIDDuplicates": 0,+ "quickCheck": "ok"+ }+ }+ ],+ "policy": "Persistence policy checks passed",+ "bootstrap": "Bootstrap passed: isolated factory calls=0; active production counter names preserved",+ "configuration": {+ "mode": "configuration",+ "exit": 0,+ "stdout": "Actual isolated configuration checks passed\n",+ "stderr": ""+ },+ "sequentialInvariantPassed": true+}
diff --git a/specs/structured-mcp-results/api15-runtime-dependency-manifest.json b/specs/structured-mcp-results/api15-runtime-dependency-manifest.jsonnew file mode 100644index 0000000..b9c0d12--- /dev/null+++ b/specs/structured-mcp-results/api15-runtime-dependency-manifest.json@@ -0,0 +1,349 @@+{+ "sourceCommit": "543c4a757e4cb7f9f73c973d7cb1be5725c8f342",+ "componentHistory": {+ "ownedBinding": "a8fcc71506ff61ee5b6f0e320ace5a064e30c915",+ "firstSelectionAdaptersTypes": "fb776a03c366c7f1bed447eaeb98a8bfcaf06508",+ "fixtureImport": "d29fdaa7bb5f60830674cb32df39903b06f487d3",+ "twoMandatoryLimits": "543c4a757e4cb7f9f73c973d7cb1be5725c8f342",+ "baselineImport": "1a19dfd",+ "ownerReadHooks": "6a39611",+ "ownerDefinitionsFactory": "8be5d55",+ "ownerSettingsSnapshot": "b51ab96"+ },+ "ownedCommonResultsProtocolAndAcceptedTen": [+ {+ "path": "Transit/Transit/MCP/MCPServer+Responses.swift",+ "sha256": "fd3ba7a841bc04d46653f9ce598092c8082d13a4060506ad30f4100ff355a049"+ },+ {+ "path": "Transit/Transit/MCP/MCPServer+Routing.swift",+ "sha256": "279dc9ebbdea1845acf7652ad7f4a86b8bc2c667668a343c382177aa788968a1"+ },+ {+ "path": "Transit/Transit/MCP/MCPServer+ToolListNotifications.swift",+ "sha256": "0a6ea616cb23d54f325f1ab82c7338ea46e8c6ae303dd5f7b65f1120ae25e3cc"+ },+ {+ "path": "Transit/Transit/MCP/MCPServer.swift",+ "sha256": "204b78bc0d3d49a41b9b6ce422cd367b0e1b4d02f613cd7266946021c276ec11"+ },+ {+ "path": "Transit/Transit/MCP/MCPServerDecodeTypes.swift",+ "sha256": "7d8243ee4e14ec1d4e8c4b7af5c29691ac3af9c592950fb43e696ba323d0edab"+ },+ {+ "path": "Transit/Transit/MCP/MCPServerLifecycleConfiguration.swift",+ "sha256": "6cc4fddb83d78e9c6e86eb54ee074a7ba35f2473337212b7e017c50bb5057d86"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift",+ "sha256": "e76888dd73a21d6ba4bed090347d90ee9e4a6cef20415b9e1b38698f11374681"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler.swift",+ "sha256": "bc486833e26a3913309650c9c81e78f980c02bef784bbd087f526a53dd9467eb"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolListChangeBroadcaster.swift",+ "sha256": "8afa54367af4ded22a43acaca5f4692882d37511030a5d1430c4fe0c39dd4f66"+ },+ {+ "path": "Transit/Transit/MCP/MCPTypes.swift",+ "sha256": "e1246d36a5838369d9b98116f1779cb5705b0fe8c8a0bd19d4c5a5b6cf4c7793"+ },+ {+ "path": "Transit/Transit/MCP/Protocol/MCPModernDiscovery.swift",+ "sha256": "a857a6ba430723053bb306ec70512e3841e081b58213a0ec75c6fc03b68d144e"+ },+ {+ "path": "Transit/Transit/MCP/Protocol/MCPModernRequest.swift",+ "sha256": "d6b0d60edddfcb1a2ae1dc33991f3d80e71b4c0f4ed87e550ebe64e1ab643b3d"+ },+ {+ "path": "Transit/Transit/MCP/Protocol/MCPModernValidator.swift",+ "sha256": "b54268a66b12f03140bd9fb57fb072d214197db36d427eba90d48bc2f6a42bdb"+ },+ {+ "path": "Transit/Transit/MCP/Protocol/MCPModernWire.swift",+ "sha256": "00cf6febe0dee3d7d04d6d2a714d3bcccfd47a1c17984ba901a084206a1c630a"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPJSONDocument.swift",+ "sha256": "7efd3387f8b262d2a253343ce976f562dab830fe7aa2954832c6a11e1fae725c"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPModernProviderBinding.swift",+ "sha256": "f79ccb4b623dc573732b96786c463605634701fcf8386fc893dfc10b7dfd2a01"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultAdapter.swift",+ "sha256": "b27522345f88c6a28a2a5ccc5d339bb89859bcecf794ced5e7f20314d3802254"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultByteWriter.swift",+ "sha256": "2aae6f485a5648c38bb83df76a2f7f5320d387d1e0b9ad66867c16020d6760c0"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultClassification.swift",+ "sha256": "8d3664f62cce2e142174235e060a00bfb02d92cfc4b4f3b1b81c8b26968a7380"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultEncoder.swift",+ "sha256": "177abf4f9b5b6158047de2c0ff0ad179565d8a1d1c50027403a902d3aaa77127"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultInspection.swift",+ "sha256": "5202d57c29a946a6e64ebb26ce5512f19aa1d5460a766141d30789af5c7fc2f1"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultLinks.swift",+ "sha256": "c31ec2298e3d90d56f71ba79a430eec94184a71876350e4b4ed0a7d277cf0036"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultPreparation.swift",+ "sha256": "f3f1fcc0f4b836e254498c53fc117a5d8757fcb61ddb4d36cf5aba9bf3d12112"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultProviderAdapters.swift",+ "sha256": "7e9028ea2c9e9195863c38493137bec56565de1471e8340596b511f68979d75c"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultProviderSelection.swift",+ "sha256": "49d54b6e3591c5e8eb37bb7c9d2779aa4d6309de055447a42ffb161e16dbdc62"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultRetentionAccounting.swift",+ "sha256": "b76ea01a468d590160ff4b2d6391752f3754482ea0394d7fa2d720cf7b4f8a34"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultSchemas.swift",+ "sha256": "ebb3af861af669af946f0b94eb3b3c68fd276e4be9416b180545ba383cf20338"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultSource.swift",+ "sha256": "524fe680c37db3670d283bb1e02d8a48a15195dc9ffc8aaa8ff5712e62337068"+ }+ ],+ "retainedOwnerDependencies": [+ {+ "path": "Transit/Transit/MCP/MCPPortfolioCaptureCharge.swift",+ "sha256": "ee800ad9c30d71473648c91f76c381c65fa0ac19b5c51aacf24919711bf7e9df",+ "owner": "T2382",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "ee800ad9c30d71473648c91f76c381c65fa0ac19b5c51aacf24919711bf7e9df",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPPortfolioProjection.swift",+ "sha256": "c0dd664e0b6165d4d28716e0e456d9688888c1ef8d3972b16ba9bb859f5e31a1",+ "owner": "T2382",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "c0dd664e0b6165d4d28716e0e456d9688888c1ef8d3972b16ba9bb859f5e31a1",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPPortfolioReadEncoding.swift",+ "sha256": "45117778c9b1f1b9bca13cde8fafec19e37456a8f50baa34c2576bc25e664f0c",+ "owner": "T2382",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "45117778c9b1f1b9bca13cde8fafec19e37456a8f50baa34c2576bc25e664f0c",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPPortfolioSummaryRequest.swift",+ "sha256": "1a2b3ef24f059ec9852018ae03bf16d66a4e5313a53007baf1346aff5f880320",+ "owner": "T2382",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "1a2b3ef24f059ec9852018ae03bf16d66a4e5313a53007baf1346aff5f880320",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPPortfolioSummaryTypes.swift",+ "sha256": "8fca6b967a8bf4fa8fe70492e0e27e52eae66e04f50c6608561fd79cc603371c",+ "owner": "T2382",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "8fca6b967a8bf4fa8fe70492e0e27e52eae66e04f50c6608561fd79cc603371c",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPPortfolioToolDefinitions.swift",+ "sha256": "80b942df914211b7229576b2334efd1026924bf4be681e460fcf60253290d1e9",+ "owner": "T2382",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "80b942df914211b7229576b2334efd1026924bf4be681e460fcf60253290d1e9",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPReusableSnapshotIndex.swift",+ "sha256": "3ece2a9a32de2d6b6032568fff472db1d4980a4c86f8442492d27c1e2ddaceca",+ "owner": "T2382",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "3ece2a9a32de2d6b6032568fff472db1d4980a4c86f8442492d27c1e2ddaceca",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPReusableSnapshotReadPin.swift",+ "sha256": "180e0cc690db0a453ece931825eb07a5d64d6c308a11a7388f59eb57dd2c82d2",+ "owner": "T2382",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "180e0cc690db0a453ece931825eb07a5d64d6c308a11a7388f59eb57dd2c82d2",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPReusableSnapshotStore.swift",+ "sha256": "43cb4128af0fdf73ceca6ae69a0415e924d7365e733277e3316ce37611a85d87",+ "owner": "T2382",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "43cb4128af0fdf73ceca6ae69a0415e924d7365e733277e3316ce37611a85d87",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPSnapshotTaskQueryRequest.swift",+ "sha256": "e809a8c97808807476df24522b0961be7b7427ed6af600034181a5fa7dbdb890",+ "owner": "T2382",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "e809a8c97808807476df24522b0961be7b7427ed6af600034181a5fa7dbdb890",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPToolDefinitions.swift",+ "sha256": "879d1094658ad9840a86ce20839bbae048a4936540c169fa985a1d1df7c132dd",+ "owner": "T63",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "decfde58b4728ace41b4c83f5b32f24a46ef397a001927843d90e279ab53d45a",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler+CapturedRead.swift",+ "sha256": "e57963b7384f3baca19b0d0b46fcc377dab584016fb8b45efd5cd4fa6b6a0d7e",+ "owner": "T63",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "e57963b7384f3baca19b0d0b46fcc377dab584016fb8b45efd5cd4fa6b6a0d7e",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler+PortfolioReadPreparation.swift",+ "sha256": "e714aef4acd3eff8cbc9f143d4edad80136b2e7c8242823ba58c44c4cf7a513e",+ "owner": "T63",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "e714aef4acd3eff8cbc9f143d4edad80136b2e7c8242823ba58c44c4cf7a513e",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler+PortfolioSummary.swift",+ "sha256": "c2d2ceeddc8daeabea4fc1e4db07a119d9f4509841f3055bf362d8e10b696da2",+ "owner": "T2382",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "c2d2ceeddc8daeabea4fc1e4db07a119d9f4509841f3055bf362d8e10b696da2",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler+SnapshotTaskQuery.swift",+ "sha256": "78d8c5ae99676e5778354ea3a0fc103cedd20747c51c6f629a1a05855205a4a9",+ "owner": "T2382",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "78d8c5ae99676e5778354ea3a0fc103cedd20747c51c6f629a1a05855205a4a9",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/Reads/MCPBoundedReadDispatcher.swift",+ "sha256": "7ccc496f65c99db34c4ae913bdfab96380a6b67ad55f76c98dfc36c32e6cab25",+ "owner": "T63",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "0df7cbeb9ae535b16499257814225cebb3fc0643021eab2614fa01232eb4f506",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/Reads/MCPReadService.swift",+ "sha256": "2cbebce6a0107b2b3532c639b08fb40471c18060e686f354192108bf6e21a87d",+ "owner": "T63",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "2cbebce6a0107b2b3532c639b08fb40471c18060e686f354192108bf6e21a87d",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/Services/PortfolioSummaryService.swift",+ "sha256": "0f5ecc8d5601d7b7669610f442650f3a0de69fd9e545d4524e59367b9c0f5945",+ "owner": "T2382",+ "originalBaseline": "b1f30256b4fb33270809188131d047a29807f162",+ "originalBaselineSHA256": "0f5ecc8d5601d7b7669610f442650f3a0de69fd9e545d4524e59367b9c0f5945",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/MCPSettings.swift",+ "sha256": "c2fe9f43e2283c792a98691d349da34ff7fe5dcb3545e5fb23e2c5a40d1cf062",+ "owner": "T63",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/Reads/MCPPreparedToolRead.swift",+ "sha256": "ecc1c541dec9d1fa4059de556deeb163687b80de7b41b6effd4e5648fc39ca69",+ "owner": "T63",+ "editOwnershipRetained": true+ },+ {+ "path": "Transit/Transit/MCP/Reads/MCPReadCoordinator.swift",+ "sha256": "34bbb3710f8ba9d665eb5259f4b6443e63140794c7d21b51f87097077b8b7fb8",+ "owner": "T63",+ "editOwnershipRetained": true+ }+ ],+ "ownerHooks": {+ "T63Definitions": "MCPToolDefinitions.modernTools(includingMaintenance: Bool) throws -> [MCPModernToolDescriptor]",+ "T63Settings": "nonisolated var maintenanceToolsEnabledSnapshot: Bool",+ "T63ReadNormal": "encodeWithOperation: (@Sendable (MCPPreparedToolRead, JSONRPCId, MCPReadOperation) throws -> Data)?",+ "T63ReadConstants": "encodeConstantToolFailure: (@Sendable (MCPPreparedToolRead, JSONRPCId) throws -> Data)?",+ "readPolicy": "Original operation/checkpoint/admittedAt and independent constant failure encoder; no clock/reset/admission/publication engine added"+ },+ "commonAPI": {+ "source": "MCPResultAdapter.source(text:isError:origin:evidence:checkpoint:) throws -> MCPResultSource (original text/optional flag/owned JSON unchanged)",+ "context": "MCPResultContext(tool:semanticFailure:mutationRecovery:entityPositions:) immutable Sendable; protected originalkey, ordered applicationBatch original itemkeys/indices/optionalitemIds/UUIDs, or no-key maintenance",+ "provider": "MCPResultProviderAdapters.outcome(result:context:origin:checkpoint:) throws -> MCPResultProviderOutcome; optional MCPToolResult.providerEvidence excluded wire CodingKeys",+ "metadata": "MCPResultProviderAdapters.metadata(result:frozenReadBytes:checkpoint:) throws -> MCPResultMetadata?; exact frozen namespace bytes, separate from original source",+ "normalEncoder": "MCPResultEncoder.encode(source:presentation:id:metadata:checkpoint:) throws -> Data; or freeze then encode(fragment:id:checkpoint:)",+ "preparedFallback": "MCPResultEncoder.prepareMutationFallback(id:source:context:metadata:checkpoint:) throws -> Data; complete request-correlated response before effects; no links/unbounded batch itemId presentation, original indexes/tool/keys/UUIDs retained; provider owns compact logical fallback source",+ "selector": "MCPResultProviderSelection.mutation(id:context:metadata:fallbackSource:prepareFallback:encodeOutcome:shouldDeliver:dispatch:) async throws -> MCPResultResponseSelection; normal/reconciliation prepared Data or suppressed, no retry encoder/receipt rewrite",+ "schema": "MCPResultSchemas.descriptor(tool:description:) throws -> MCPResultSchemaDescriptor with immutable owned outputSchema Draft2020-12; logical source payload unrestricted",+ "valuePreparation": "MCPResultPreparation.metadata/page/prepare and sealed immutable owners; checked logical charge/capacity preflight only, originalcapturebase, independent16MiB perstore; real reserve/publication binding task17"+ },+ "consumerConstraints": [+ "No live reread/result reconstruction or receipt rewrite; original text/isError/unknown fields/numeric lexemes/missing-null preserved.",+ "Batch provider owns logical aggregate and compact serialization_failed source; prepare complete fallback before first effect, select stored bytes after failure; cancellation only suppresses delivery.",+ "No provider callback retained; original read checkpoint forwarded during source/links/meta/encoding.",+ "DELIVERED15 synthetic/common consumer is independent of real batch registration and later store17/subscription19 integration."+ ],+ "verification": {+ "sourceCommit": "543c4a757e4cb7f9f73c973d7cb1be5725c8f342",+ "productionBindingCommit": "a8fcc71506ff61ee5b6f0e320ace5a064e30c915",+ "fixtureImportCommit": "d29fdaa7bb5f60830674cb32df39903b06f487d3",+ "head": "160181e0259d67333693e8cfc237ba58dd324539",+ "buildExit": 0,+ "preflightExit": 0,+ "enumerationExit": 0,+ "inventoryExit": 0,+ "testExit": 0,+ "summaryExtractionExit": 0,+ "expectedEnabledMethods": 2,+ "actualEnabledMethods": 2,+ "actualExecutedMethods": [+ "everyEnabledCurrentToolReturnsDeclaredCompleteSource()",+ "actualProtectedUpdateTrimClearAndCommentRevisionRemainSavedEvidence()"+ ],+ "finalizedResult": "Passed",+ "passedTests": 2,+ "failedTests": 0,+ "skippedTests": 0,+ "issues": 0,+ "runtimeWarnings": [],+ "NIOMisuseWarnings": 0,+ "runnerPID": 49902,+ "host": "Exact guarded private development host; no matching owned process after normal finish",+ "ownedDrained": true,+ "releaseBeforeExtraction": true,+ "cleanup": "None required; no signals/samples/replay",+ "combinedEvidence": "98 PASS in preserved100-declaration run plus corrected2 PASS; full100 earlier test143/unfinalizedsummary64 remains explicit. No full100 repeat.",+ "staticAndRuntimeCritic": "CLEAR approved15 source, source-only fixture corrections, actual finalized2 and preserved98",+ "API15": "Ready for root DELIVERED15 review/bookkeeping; no later17/19/batch production gate."+ },+ "ownership": "Baseline imports and owner seams do not transfer retained T63/T2382/T2384 editing ownership; coordinator/App/project unchanged."+}
diff --git a/specs/structured-mcp-results/api15-source-manifest.json b/specs/structured-mcp-results/api15-source-manifest.jsonnew file mode 100644index 0000000..bea26aa--- /dev/null+++ b/specs/structured-mcp-results/api15-source-manifest.json@@ -0,0 +1,147 @@+{+ "runeTask": "15/gpzncvz",+ "sourceCheckpoint": "543c4a757e4cb7f9f73c973d7cb1be5725c8f342",+ "repository": "/Users/arjen/Documents/Codex/2026-10-03/task-3/transit",+ "branch": "T-2383/structured-mcp-results",+ "pureConsumerSeam": [+ {+ "path": "Transit/Transit/MCP/Results/MCPJSONDocument.swift",+ "sha256": "7efd3387f8b262d2a253343ce976f562dab830fe7aa2954832c6a11e1fae725c",+ "lastSourceCommit": "31bc425ba3a066497c6a9dcdedb1ed9dcdffdf03"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultSource.swift",+ "sha256": "524fe680c37db3670d283bb1e02d8a48a15195dc9ffc8aaa8ff5712e62337068",+ "lastSourceCommit": "3ba1cfbc157a0682dbdec211b4cbcd9ac269aea1"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultInspection.swift",+ "sha256": "5202d57c29a946a6e64ebb26ce5512f19aa1d5460a766141d30789af5c7fc2f1",+ "lastSourceCommit": "1652913db72bd2a5bf00dd109fca547d8477db3a"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultAdapter.swift",+ "sha256": "b27522345f88c6a28a2a5ccc5d339bb89859bcecf794ced5e7f20314d3802254",+ "lastSourceCommit": "1652913db72bd2a5bf00dd109fca547d8477db3a"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultClassification.swift",+ "sha256": "8d3664f62cce2e142174235e060a00bfb02d92cfc4b4f3b1b81c8b26968a7380",+ "lastSourceCommit": "a8fcc71506ff61ee5b6f0e320ace5a064e30c915"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultLinks.swift",+ "sha256": "c31ec2298e3d90d56f71ba79a430eec94184a71876350e4b4ed0a7d277cf0036",+ "lastSourceCommit": "f4bd03a638dbdb0c56c04c4506a5aaaf864fb054"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultByteWriter.swift",+ "sha256": "2aae6f485a5648c38bb83df76a2f7f5320d387d1e0b9ad66867c16020d6760c0",+ "lastSourceCommit": "3ba1cfbc157a0682dbdec211b4cbcd9ac269aea1"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultEncoder.swift",+ "sha256": "177abf4f9b5b6158047de2c0ff0ad179565d8a1d1c50027403a902d3aaa77127",+ "lastSourceCommit": "3ba1cfbc157a0682dbdec211b4cbcd9ac269aea1"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultSchemas.swift",+ "sha256": "ebb3af861af669af946f0b94eb3b3c68fd276e4be9416b180545ba383cf20338",+ "lastSourceCommit": "a25bf996a8e73edb7972cc85780248df9c83e654"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultProviderSelection.swift",+ "sha256": "49d54b6e3591c5e8eb37bb7c9d2779aa4d6309de055447a42ffb161e16dbdc62",+ "lastSourceCommit": "fb776a03c366c7f1bed447eaeb98a8bfcaf06508"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPResultProviderAdapters.swift",+ "sha256": "7e9028ea2c9e9195863c38493137bec56565de1471e8340596b511f68979d75c",+ "lastSourceCommit": "fb776a03c366c7f1bed447eaeb98a8bfcaf06508"+ }+ ],+ "integratedBinding": [+ {+ "path": "Transit/Transit/MCP/MCPTypes.swift",+ "sha256": "e1246d36a5838369d9b98116f1779cb5705b0fe8c8a0bd19d4c5a5b6cf4c7793",+ "lastSourceCommit": "a8fcc71506ff61ee5b6f0e320ace5a064e30c915"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler.swift",+ "sha256": "bc486833e26a3913309650c9c81e78f980c02bef784bbd087f526a53dd9467eb",+ "lastSourceCommit": "a8fcc71506ff61ee5b6f0e320ace5a064e30c915"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift",+ "sha256": "e76888dd73a21d6ba4bed090347d90ee9e4a6cef20415b9e1b38698f11374681",+ "lastSourceCommit": "a8fcc71506ff61ee5b6f0e320ace5a064e30c915"+ },+ {+ "path": "Transit/Transit/MCP/MCPServer+Routing.swift",+ "sha256": "279dc9ebbdea1845acf7652ad7f4a86b8bc2c667668a343c382177aa788968a1",+ "lastSourceCommit": "a8fcc71506ff61ee5b6f0e320ace5a064e30c915"+ },+ {+ "path": "Transit/Transit/MCP/MCPServer+Responses.swift",+ "sha256": "fd3ba7a841bc04d46653f9ce598092c8082d13a4060506ad30f4100ff355a049",+ "lastSourceCommit": "a8fcc71506ff61ee5b6f0e320ace5a064e30c915"+ },+ {+ "path": "Transit/Transit/MCP/Protocol/MCPModernRequest.swift",+ "sha256": "d6b0d60edddfcb1a2ae1dc33991f3d80e71b4c0f4ed87e550ebe64e1ab643b3d",+ "lastSourceCommit": "8ea94ce0b3b9a3b73fcee330aed0c9883a08e92f"+ },+ {+ "path": "Transit/Transit/MCP/Protocol/MCPModernValidator.swift",+ "sha256": "b54268a66b12f03140bd9fb57fb072d214197db36d427eba90d48bc2f6a42bdb",+ "lastSourceCommit": "a8fcc71506ff61ee5b6f0e320ace5a064e30c915"+ },+ {+ "path": "Transit/Transit/MCP/Protocol/MCPModernDiscovery.swift",+ "sha256": "a857a6ba430723053bb306ec70512e3841e081b58213a0ec75c6fc03b68d144e",+ "lastSourceCommit": "3cfd28a8a8f7d707f9a03ca4bcdd0aed4e4f71b9"+ },+ {+ "path": "Transit/Transit/MCP/Protocol/MCPModernWire.swift",+ "sha256": "00cf6febe0dee3d7d04d6d2a714d3bcccfd47a1c17984ba901a084206a1c630a",+ "lastSourceCommit": "a8fcc71506ff61ee5b6f0e320ace5a064e30c915"+ },+ {+ "path": "Transit/Transit/MCP/Results/MCPModernProviderBinding.swift",+ "sha256": "f79ccb4b623dc573732b96786c463605634701fcf8386fc893dfc10b7dfd2a01",+ "lastSourceCommit": "a8fcc71506ff61ee5b6f0e320ace5a064e30c915"+ }+ ],+ "retainedOwnerDependencies": [+ {+ "path": "Transit/Transit/MCP/MCPToolDefinitions.swift",+ "sha256": "879d1094658ad9840a86ce20839bbae048a4936540c169fa985a1d1df7c132dd",+ "lastSourceCommit": "8be5d55579a703b4e64eac46f4e528ea191bf61d",+ "owner": "T63",+ "localImportCommit": "8be5d55",+ "ownerCommit": "6a748928ccb6b91e6cebaf1538997e50d664b9da"+ },+ {+ "path": "Transit/Transit/MCP/MCPSettings.swift",+ "sha256": "c2fe9f43e2283c792a98691d349da34ff7fe5dcb3545e5fb23e2c5a40d1cf062",+ "lastSourceCommit": "b51ab962018f34d12fda220a1b115af384526de9",+ "owner": "T63",+ "localImportCommit": "b51ab96",+ "ownerCommit": "105ba8fdfc9323d08248d615b1620232ae6bc687"+ },+ {+ "path": "Transit/Transit/MCP/Reads/MCPBoundedReadDispatcher.swift",+ "sha256": "7ccc496f65c99db34c4ae913bdfab96380a6b67ad55f76c98dfc36c32e6cab25",+ "lastSourceCommit": "6a39611292aba4646f23d32fae574ddffdea2bd7",+ "owner": "T63",+ "localImportCommit": "6a39611",+ "ownerCommit": "5a57896422e9aee4e31c0530e86f09fc9bc1fd83"+ }+ ],+ "baselineDependencyManifest": "specs/structured-mcp-results/task14-baseline-import.json",+ "coordination": "Hashes identify source; do not overwrite T2384-owned write coordinator or T63-retained modules. Transfer these owner dependencies through coordinated imports, not a wholesale checkout.",+ "verification": [+ ".codex-cache/task15-binding-green-import-fixed/results.md",+ ".codex-cache/task15-binding-green-limit-fixed/xcresult-summary.json"+ ]+}
diff --git a/specs/structured-mcp-results/modern-transfer-acceptance.json b/specs/structured-mcp-results/modern-transfer-acceptance.jsonnew file mode 100644index 0000000..2fe96d4--- /dev/null+++ b/specs/structured-mcp-results/modern-transfer-acceptance.json@@ -0,0 +1,155 @@+{+ "status": "accepted_sole_writer_for_named_production_files",+ "authorization": "explicit parent delegation authorizing staged modern-file ownership transfer",+ "manifest_commit": "557b4c2cbd91bcb82f61f91d16e4bf7297511e16",+ "manifest_path": "/Users/arjen/Documents/Codex/2026-10-03/task/transit-t63/specs/bounded-read-freshness/modern-transfer-manifest.json",+ "manifest_sha256": "989b69f969b2c35f75460f3740a5074813ac606a18b75bdef67677aef0822352",+ "source_base": "b1f30256b4fb33270809188131d047a29807f162",+ "accepted_production_files": [+ {+ "path": "Transit/Transit/MCP/MCPServer.swift",+ "sha256": "204b78bc0d3d49a41b9b6ce422cd367b0e1b4d02f613cd7266946021c276ec11",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPServer+Routing.swift",+ "sha256": "a61923728971c1d1bf8c687884ea7e46213ad8d64e167c3ffb90f95ae00b2dde",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPServer+Responses.swift",+ "sha256": "c1da3a62420439cb6b7007a8871ff9ad2f45f4c06cabf4e7c7933a981b0e8bfb",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPServer+ToolListNotifications.swift",+ "sha256": "0a6ea616cb23d54f325f1ab82c7338ea46e8c6ae303dd5f7b65f1120ae25e3cc",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPServerDecodeTypes.swift",+ "sha256": "7d8243ee4e14ec1d4e8c4b7af5c29691ac3af9c592950fb43e696ba323d0edab",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPServerLifecycleConfiguration.swift",+ "sha256": "6cc4fddb83d78e9c6e86eb54ee074a7ba35f2473337212b7e017c50bb5057d86",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolListChangeBroadcaster.swift",+ "sha256": "8afa54367af4ded22a43acaca5f4692882d37511030a5d1430c4fe0c39dd4f66",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPTypes.swift",+ "sha256": "ed9a44ffb38bcbe98a37cc742a52850ecab3ab9334f395e2a70a30a1423e7f06",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler.swift",+ "sha256": "0749918c933b89f3e2aa4e1757bfd5243584ca1f559af54d7ac76cbc701581e2",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift",+ "sha256": "f46e9ca6386c3d7740654ac7d38ddb82a33c8dcde4a17ec569727ad3413ceb16",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ }+ ],+ "optional_fixture_files": "recorded only; separately authorized optional transfer not assumed",+ "optional_fixture_candidates": [+ {+ "path": "Transit/TransitTests/MCPServerRouteTests.swift",+ "sha256": "dec881e0639a6aa982bcc2278af9b4d7fbaee32b42cd5d29f133b3be2ab1385b",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/TransitTests/MCPServerBatchRequestTests.swift",+ "sha256": "7829d17fd5cc64847ad99bc35cf9c800311fa62bb433a1c77acddc8acc47c3b6",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/TransitTests/MCPNotificationDispatchTests.swift",+ "sha256": "f76bf880acf144bbb72532640932d796ee8884f34bba5b808931073e74b3cb35",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/TransitTests/MCPToolListChangeNotificationTests.swift",+ "sha256": "ad451dda60e897143490a180e29654b2f560b2c76895c7e7e929f1bd1b8e9ab6",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/TransitTests/MCPServerOriginValidationTests.swift",+ "sha256": "bc6707ddde5869a796946e7703e4a30aee68239bc9aa034ae991876888202a89",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/TransitTests/MCPServerLifecycleTests.swift",+ "sha256": "dd2930d0dd5957ea30d3a507283e9987e5560be9679b57c6119db8d99b9525c5",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ },+ {+ "path": "Transit/TransitTests/MCPServerStartFailureTests.swift",+ "sha256": "19aaa3f72882cf85fadc2b33e70a1e7a6d559f5fea9fe2ca915eedd20abe39f8",+ "current_owner": "T63",+ "proposed_owner_after_explicit_parent_record": "T2383"+ }+ ],+ "verified_source_and_current_hash_count": 17,+ "retained_owners": {+ "T63": [+ "Transit/Transit/MCP/Reads/",+ "Transit/Transit/MCP/MCPTaskQuerySnapshotStore.swift",+ "Transit/Transit/MCP/MCPToolHandler+CapturedRead.swift",+ "Transit/Transit/MCP/MCPToolHandler+PortfolioReadPreparation.swift",+ "Transit/Transit/MCP/MCPToolDefinitions.swift",+ "Transit/TransitTests/MCPHTTPTestHelpers.swift",+ "Transit/TransitTests/MCPTestHelpers.swift",+ "read-specific tests"+ ],+ "T2382": [+ "portfolio/reusable source modules",+ "portfolio-owned tests"+ ],+ "T2384": [+ "MCP/Writes/MCPWriteCoordinator.swift",+ "write-specific tests"+ ],+ "containment_build_owner": [+ "App/project/signing/isolation/Makefile"+ ]+ },+ "source_imported": false,+ "production_files_edited": false,+ "task10": "in progress; exact build and unchanged retry denied; awaiting direct user/tool-supported resolution",+ "task11": "blocked by meaningful task10 RED",+ "task14": "blocked by task11; ownership gate alone is now satisfied for named production files",+ "api15_delivered": false,+ "heavy_slot_held": false,+ "verification_obligations": [+ "real fragment/schema ABI and owner-applied read/ordinary/reusable bindings",+ "complete actual-ID encoded bytes before publication; exact frozen metadata and retention accounting",+ "modern single-object POST and wire-array rejection",+ "portfolio request-header alignment and source/presentation/opaque-metadata assertions",+ "current HTTP-helper focused router verification with modern adapter",+ "include two verified owner router-expiry fixtures with current helper and modern adapter"+ ],+ "external_runtime_evidence": "manifest reports owner router4/4 atb4c104e7 and expiry2/2 atee053269 separately; no combined/local runtime proof claimed"+}
diff --git a/specs/structured-mcp-results/task14-baseline-import.json b/specs/structured-mcp-results/task14-baseline-import.jsonnew file mode 100644index 0000000..c131294--- /dev/null+++ b/specs/structured-mcp-results/task14-baseline-import.json@@ -0,0 +1,167 @@+{+ "recipient": "38ad6631b35be9ca95c7a936861ef7cf3d39385e",+ "stageA": "b500543",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sourceFileCount": 20,+ "entries": [+ {+ "path": "Transit/Transit/MCP/MCPPortfolioCaptureCharge.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "ee800ad9c30d71473648c91f76c381c65fa0ac19b5c51aacf24919711bf7e9df",+ "owner": "T2382",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPPortfolioProjection.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "c0dd664e0b6165d4d28716e0e456d9688888c1ef8d3972b16ba9bb859f5e31a1",+ "owner": "T2382",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPPortfolioReadEncoding.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "45117778c9b1f1b9bca13cde8fafec19e37456a8f50baa34c2576bc25e664f0c",+ "owner": "T2382",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPPortfolioSummaryRequest.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "1a2b3ef24f059ec9852018ae03bf16d66a4e5313a53007baf1346aff5f880320",+ "owner": "T2382",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPPortfolioSummaryTypes.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "8fca6b967a8bf4fa8fe70492e0e27e52eae66e04f50c6608561fd79cc603371c",+ "owner": "T2382",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPPortfolioToolDefinitions.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "80b942df914211b7229576b2334efd1026924bf4be681e460fcf60253290d1e9",+ "owner": "T2382",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPReusableSnapshotIndex.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "3ece2a9a32de2d6b6032568fff472db1d4980a4c86f8442492d27c1e2ddaceca",+ "owner": "T2382",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPReusableSnapshotReadPin.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "180e0cc690db0a453ece931825eb07a5d64d6c308a11a7388f59eb57dd2c82d2",+ "owner": "T2382",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPReusableSnapshotStore.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "43cb4128af0fdf73ceca6ae69a0415e924d7365e733277e3316ce37611a85d87",+ "owner": "T2382",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPSnapshotTaskQueryRequest.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "e809a8c97808807476df24522b0961be7b7427ed6af600034181a5fa7dbdb890",+ "owner": "T2382",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolDefinitions.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "decfde58b4728ace41b4c83f5b32f24a46ef397a001927843d90e279ab53d45a",+ "owner": "T63",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler+CapturedRead.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "e57963b7384f3baca19b0d0b46fcc377dab584016fb8b45efd5cd4fa6b6a0d7e",+ "owner": "T63",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler+PortfolioReadPreparation.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "e714aef4acd3eff8cbc9f143d4edad80136b2e7c8242823ba58c44c4cf7a513e",+ "owner": "T63",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler+PortfolioSummary.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "c2d2ceeddc8daeabea4fc1e4db07a119d9f4509841f3055bf362d8e10b696da2",+ "owner": "T2382",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler+SnapshotTaskQuery.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "78d8c5ae99676e5778354ea3a0fc103cedd20747c51c6f629a1a05855205a4a9",+ "owner": "T2382",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/MCPToolHandler.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "0749918c933b89f3e2aa4e1757bfd5243584ca1f559af54d7ac76cbc701581e2",+ "owner": "T2383",+ "state": "accepted sole writer baseline reconciled"+ },+ {+ "path": "Transit/Transit/MCP/MCPTypes.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "ed9a44ffb38bcbe98a37cc742a52850ecab3ab9334f395e2a70a30a1423e7f06",+ "owner": "T2383",+ "state": "accepted sole writer baseline reconciled"+ },+ {+ "path": "Transit/Transit/MCP/Reads/MCPBoundedReadDispatcher.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "0df7cbeb9ae535b16499257814225cebb3fc0643021eab2614fa01232eb4f506",+ "owner": "T63",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/MCP/Reads/MCPReadService.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "2cbebce6a0107b2b3532c639b08fb40471c18060e686f354192108bf6e21a87d",+ "owner": "T63",+ "state": "imported byte-identical; edit owner retained"+ },+ {+ "path": "Transit/Transit/Services/PortfolioSummaryService.swift",+ "source": "b1f30256b4fb33270809188131d047a29807f162",+ "sha256": "0f5ecc8d5601d7b7669610f442650f3a0de69fd9e545d4524e59367b9c0f5945",+ "owner": "T2382",+ "state": "imported byte-identical; edit owner retained"+ }+ ],+ "T63Patch": "/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/stage-b-retained-owner-handoff/retained-owner-baseline.patch",+ "T63PatchSHA256": "b1bffff5a9e25e441d14991aa2cc0ebe2b3a47b13bdb598f1f14013f8175ab5e",+ "currentHTTPHelperSHA256": "6ab7df966537972871c75b5cb390574ee2087e57d640d5cc61c4c5c85beebf97",+ "optionalFixturesTransferred": false,+ "appProjectChanged": false,+ "productionImportsSoFar": true,+ "APIDelivery15": false,+ "T63AndTransferredBaselineCommit": "36030cf",+ "T2382OwnerConfirmation": "explicit parent forwarded owner confirmation;13 exact import authorised",+ "editingOwnershipTransferred": false,+ "combinedCompileOrAcceptance": false,+ "T2382BaselineCommit": "1a19dfda6761ac788db47821a838fb14f7de3e4b",+ "review": "read-only internal critic clear; exact20 paths/no extras and all hashes match",+ "current_helper_followup": "T63-owned respond needs ordered extra HTTP fields for Mcp-Method/Mcp-Name and duplicate-header tests; current signature supports protocolVersion only",+ "additional_legacy_fixture_coordination": [+ "Transit/TransitTests/MCPRequestDecodeErrorClassificationTests.swift",+ "Transit/TransitTests/MCPInitializeHandshakeTests.swift"+ ],+ "diagnostics_checkpoint_excluded": "ce0f1a98d874d53f2c607d47e197ae7c64c0f2d3"+}
diff --git a/specs/structured-mcp-results/task16-owner-request.json b/specs/structured-mcp-results/task16-owner-request.jsonnew file mode 100644index 0000000..681d6de--- /dev/null+++ b/specs/structured-mcp-results/task16-owner-request.json@@ -0,0 +1,161 @@+{+ "phase": "Task16 owner coordination; source-only RED preparation, no runtime readiness claim",+ "recipientHead": "18a3483",+ "paths": [+ {+ "owner": "T63",+ "path": "Transit/Transit/MCP/Reads/MCPPreparedToolRead.swift",+ "sha256": "1394537f348260d9022c5c2defa8fbaab744c06cf4cef4446b3e3cab9e5ff462"+ },+ {+ "owner": "T63",+ "path": "Transit/Transit/MCP/Reads/MCPReadService.swift",+ "sha256": "2cbebce6a0107b2b3532c639b08fb40471c18060e686f354192108bf6e21a87d"+ },+ {+ "owner": "T63",+ "path": "Transit/Transit/MCP/MCPTaskQuerySnapshotStore.swift",+ "sha256": "7095df9b81b3b4db8e468d405454478a4b640058ff9b0a0c05fa370b2f2657eb"+ },+ {+ "owner": "T63",+ "path": "Transit/Transit/MCP/MCPToolHandler+CapturedRead.swift",+ "sha256": "e57963b7384f3baca19b0d0b46fcc377dab584016fb8b45efd5cd4fa6b6a0d7e"+ },+ {+ "owner": "T63",+ "path": "Transit/Transit/MCP/MCPToolHandler+PortfolioReadPreparation.swift",+ "sha256": "e714aef4acd3eff8cbc9f143d4edad80136b2e7c8242823ba58c44c4cf7a513e"+ },+ {+ "owner": "T2382",+ "path": "Transit/Transit/MCP/MCPReusableSnapshotStore.swift",+ "sha256": "43cb4128af0fdf73ceca6ae69a0415e924d7365e733277e3316ce37611a85d87"+ },+ {+ "owner": "T2382",+ "path": "Transit/Transit/MCP/MCPReusableSnapshotIndex.swift",+ "sha256": "3ece2a9a32de2d6b6032568fff472db1d4980a4c86f8442492d27c1e2ddaceca"+ },+ {+ "owner": "T2382",+ "path": "Transit/Transit/MCP/MCPReusableSnapshotReadPin.swift",+ "sha256": "180e0cc690db0a453ece931825eb07a5d64d6c308a11a7388f59eb57dd2c82d2"+ },+ {+ "owner": "T2383 reference only",+ "path": "Transit/Transit/MCP/Results/MCPResultPreparation.swift",+ "sha256": "f3f1fcc0f4b836e254498c53fc117a5d8757fcb61ddb4d36cf5aba9bf3d12112"+ },+ {+ "owner": "T2383 reference only",+ "path": "Transit/Transit/MCP/Results/MCPModernProviderBinding.swift",+ "sha256": "f79ccb4b623dc573732b96786c463605634701fcf8386fc893dfc10b7dfd2a01"+ },+ {+ "owner": "T63 unchanged gate reference",+ "path": "Transit/Transit/MCP/Reads/MCPReadCoordinator.swift",+ "sha256": "34bbb3710f8ba9d665eb5259f4b6443e63140794c7d21b51f87097077b8b7fb8"+ },+ {+ "owner": "T63 unchanged gate reference",+ "path": "Transit/Transit/MCP/Reads/MCPReadPublicationDomain.swift",+ "sha256": "5862e034aa120d99beb0c11a6ad28bd4fff90019f3b52284e09e4b66939901a0"+ },+ {+ "owner": "T63 unchanged gate reference",+ "path": "Transit/Transit/MCP/Reads/MCPReadPublicationDomain+Preparation.swift",+ "sha256": "c97b489b274220bd9090c9e91c31a099b2be1ff1c0cdd777bb229f1a418f1942"+ }+ ],+ "existingDeliveredTypes": [+ "MCPResultPreparedPage",+ "MCPResultPreparedMetadata",+ "MCPResultRetainedBundle",+ "MCPResultRetentionBudget",+ "MCPResultPagePreparationRequest"+ ],+ "ownerRequests": [+ {+ "owner": "T63",+ "scope": "Ordinary prepared read and snapshot retention",+ "current": "Supplied ce4d0af prepared-read carrier consumed exactly as18a3483. Ordinary retained pages/store and all-private-page hook still lack modern owners/expanded accounting.",+ "change": "Preserve supplied preparedResultPage carrier through ordinary retained-page lookup. Before reservation, prepare ALL private pages including first with the original operation and retain existing MCPResultPreparedPage/MCPResultRetainedBundle owners. Charge measured expanded owners plus all remaining original capture/index or compatibility backing; avoid unmeasured retained legacy copies and double charging actual shared owners. Expose exact owner-selected all-page hook and store declaration for task16 fixtures; original domain reserve remains authoritative.",+ "paths": [+ "Transit/Transit/MCP/Reads/MCPPreparedToolRead.swift",+ "Transit/Transit/MCP/Reads/MCPReadService.swift",+ "Transit/Transit/MCP/MCPTaskQuerySnapshotStore.swift",+ "Transit/Transit/MCP/MCPToolHandler+CapturedRead.swift",+ "Transit/Transit/MCP/MCPToolHandler+PortfolioReadPreparation.swift"+ ]+ },+ {+ "owner": "T2382",+ "scope": "Reusable portfolio retention",+ "current": "RetainedView/EncodedViewBundle/RetainedPage retain Data/capture; index charge uses capture byte count and page Data only.",+ "change": "Carry existing immutable prepared page/bundle owners through root, create, append, and pinned lookups. Prepare every private page before reservation using the original operation. Integrate expanded measured charges preserving original capture/index cost and shared owner identity, original root expiry, pins, and atomic publication. Append accounting must avoid charging shared owners twice or subtracting unchecked estimates; real domain reserve revalidates races.",+ "paths": [+ "Transit/Transit/MCP/MCPReusableSnapshotStore.swift",+ "Transit/Transit/MCP/MCPReusableSnapshotIndex.swift",+ "Transit/Transit/MCP/MCPReusableSnapshotReadPin.swift"+ ]+ },+ {+ "owner": "T63",+ "scope": "Explicit prepared-read source origin",+ "current": "CapturedRead no-readService branch emits actual plain text; current modern read adapter defaults fresh prepared reads to generated JSON.",+ "change": "Add optional providerEvidence/source-origin declaration to existing MCPPreparedToolRead initializer/result sidecar, with compatibility default for generated JSON. Explicitly declare no-service plainText and audit other plain read failure producers. Preserve wire CodingKeys/text/isError and attaching. Do not infer origin from parse failure or localized message."+ }+ ],+ "preparerSemanticSketch": {+ "notLockedProductionSignature": true,+ "inputs": [+ "all MCPResultPagePreparationRequest values",+ "MCPResultRetentionBudget for the specific store",+ "the SAME MCPReadOperation"+ ],+ "output": "Common factory returns frozen page owners. Existing MCPResultPreparation.prepare(pages:budget:checkpoint:) measures retained bundle/charge for store reservation; original capture/index and compatibility backing must remain accounted.",+ "implementation": "Consume MCPResultPreparation.metadata/page/prepare with original operation checkpoint; one actual immutable metadata owner shared across pages. Owner chooses callback names and final signatures; no parallel carrier/descriptor type.",+ "budget": "Fixed independent 16MiB per store; checked logical retained charge, not RSS. Original capture/index base excludes page text/document/tree/fragment/meta measured by new ledger. Visible and pending observations come from existing domain. Preflight does not reserve.",+ "lookup": "Stored page.fragment plus frozen original metadata/source/presentation; no live reread/reparse/reclassification or regenerated links/policy/expiry.",+ "suppliedCommonSignature": "T63 requested common MCPModernProviderBinding.prepareReadPages(_ pages: [MCPPreparedToolRead], tool: String, operation: MCPReadOperation) throws -> [MCPResultPreparedPage]; T2383 delivers through tasks16/17, with no new deadline/guard/retention engine."+ },+ "unchangedInvariants": [+ "Original five-second operation and eight physical unfinished workers across stop/start",+ "Existing shared domain reserve/validate-all-before-commit and discard semantics",+ "Independent ordinary/reusable five-minute/eight-snapshot/16MiB limits",+ "Canonical comment-covered r1 even when comments omitted",+ "Frozen text/payload/metadata/presentation/policy/expiry with new request IDs",+ "No encoding under publication gate; large destruction remains outside lock"+ ],+ "fixturePreparation": {+ "status": "Read-only seam inventory completed; no new Task16 fixture file or owner declaration added yet.",+ "existingSeamsSufficient": [+ "coordinator fake clock/cutoff/maxOperations and stop/start",+ "domain accounting/reserve/atomic publication tests",+ "builder capture/fence/source faults",+ "reusable pins/testingAfterPin/lifetimeProbe"+ ],+ "plannedOwnedTests": [+ "ordinary and reusable frozen continuation after saved record/comment edits, new IDs and includeComments false canonical r1",+ "whole capture/parser/selector/storage failure and no private partial publication",+ "expanded budget boundary using actual modern private-page preparation, independent store caps and pending costs",+ "original deadline/cancellation through preparation/offer; stale/expired publication and physical workers across restart"+ ],+ "blockingExactBindings": "Common factory signature and prepared-read carrier are supplied. Ordinary/reusable all-private-page create/append/lookup and charge declarations remain owner-selected; new owned RED fixtures will consume those declared seams, not guess names.",+ "runtime": "No heavy command, app run, publication guarantee or Task16 RED/GREEN claim at this checkpoint."+ },+ "nextSafeAction": "Parent forwards bundled request to retained owners. Worker resumes owned fixtures using existing fakes and supplied declarations, then prepares reviewed focused RED command for a separately coordinated heavy slot.",+ "suppliedABI": {+ "owner": "T63",+ "ownerCommit": "ce4d0af",+ "localImportCommit": "18a3483",+ "patchSHA256": "22fec83828cbaa7e415c786e675186b52943324bf74d607fc7cca3ffa8a3b726",+ "fileSHA256": "1394537f348260d9022c5c2defa8fbaab744c06cf4cef4446b3e3cab9e5ff462",+ "symbols": [+ "MCPPreparedToolRead.preparedResultPage: MCPResultPreparedPage?",+ "MCPPreparedToolRead.attachingPreparedResultPage(_:) -> Self"+ ],+ "ownership": "T63 retained; exact byte-matching owner import, no runtime proof."+ }+}
diff --git a/tests/development-isolation/BootstrapProbe.swift b/tests/development-isolation/BootstrapProbe.swiftnew file mode 100644index 0000000..7ab67c7--- /dev/null+++ b/tests/development-isolation/BootstrapProbe.swift@@ -0,0 +1,57 @@+import Foundation+import SwiftData++@main+struct BootstrapProbe {+ @MainActor static func main() async throws {+ let schema = Schema([Project.self, TransitTask.self, Comment.self, Milestone.self,+ SyncHeartbeat.self, MCPWriteReceipt.self])+ let configuration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true,+ cloudKitDatabase: .none)+ let container = try ModelContainer(for: schema, configurations: configuration)+ let context = container.mainContext+ let project = Project(name: "Synthetic", description: "Bootstrap probe",+ gitRepo: nil, colorHex: "#123456")+ let task = TransitTask(name: "Provisional", type: .feature, project: project,+ displayID: .provisional)+ context.insert(project)+ context.insert(task)+ try context.save()+ var calls: [String] = []+ let factory: (String) -> DisplayIDAllocator = { name in+ calls.append(name)+ return DisplayIDAllocator(store: DisabledCounterStore(), isCloudSyncActive: true)+ }+ for mode in [AppPersistencePolicy.Mode.development, .unitTest, .uiTest, .production] {+ for active in [false, true] where mode != .production || !active {+ let pair = AppDisplayIDAllocators.make(mode: mode, syncActive: active, cloudFactory: factory)+ for allocator in [pair.tasks, pair.milestones] {+ precondition(!allocator.isCloudSyncActive)+ precondition(allocator.counterStore is DisabledCounterStore)+ do {+ _ = try await allocator.allocateNextID()+ fatalError("Inactive allocation succeeded")+ } catch DisplayIDAllocator.Error.cloudSyncInactive {} catch { throw error }+ do {+ _ = try await allocator.counterStore.loadCounter()+ fatalError("Disabled counter read succeeded")+ } catch DisabledCounterStore.Failure.unavailable {} catch { throw error }+ do {+ try await allocator.counterStore.saveCounter(nextDisplayID: 2, expectedChangeTag: nil)+ fatalError("Disabled counter write succeeded")+ } catch DisabledCounterStore.Failure.unavailable {} catch { throw error }+ await allocator.promoteProvisionalTasks(in: context, save: { _ in+ fatalError("Inactive promotion tried to save")+ })+ precondition(task.permanentDisplayId == nil)+ }+ precondition(calls.isEmpty)+ }+ }+ let production = AppDisplayIDAllocators.make(mode: .production, syncActive: true,+ cloudFactory: factory)+ precondition(production.tasks.isCloudSyncActive && production.milestones.isCloudSyncActive)+ precondition(calls == ["global-counter", "milestone-counter"])+ print("Bootstrap passed: isolated factory calls=0; active production counter names preserved")+ }+}
diff --git a/tests/development-isolation/MigrationProbe.swift b/tests/development-isolation/MigrationProbe.swiftnew file mode 100644index 0000000..398cecc--- /dev/null+++ b/tests/development-isolation/MigrationProbe.swift@@ -0,0 +1,106 @@+import Foundation+import SwiftData++/// A standalone executable with no app lifecycle, entitlement or CloudKit connection.+@main+struct MigrationProbe {+ @MainActor static func main() throws {+ let arguments = CommandLine.arguments+ precondition(arguments.count == 3)+ let mode = arguments[1]+ let root = ProcessInfo.processInfo.environment["TRANSIT_DISPOSABLE_ROOT"]!+ let url = URL(fileURLWithPath: arguments[2]).standardizedFileURL.resolvingSymlinksInPath()+ let allowed = URL(fileURLWithPath: root).standardizedFileURL.resolvingSymlinksInPath().path + "/"+ precondition(url.path.hasPrefix(allowed) && url.lastPathComponent == "synthetic.store")+ var models: [any PersistentModel.Type] = [+ Project.self, TransitTask.self, Comment.self, Milestone.self, SyncHeartbeat.self+ ]+ if mode == "open-new" || mode == "configuration" { models.append(MCPWriteReceipt.self) }+ let schema = Schema(models)+ let configuration = mode == "configuration"+ ? try IsolatedPersistenceConfiguration.make(mode: .development, schema: schema,+ applicationSupportDirectory: url.deletingLastPathComponent())+ : ModelConfiguration(schema: schema, url: url, cloudKitDatabase: .none)+ let container = try ModelContainer(for: schema, configurations: configuration)+ let context = container.mainContext+ context.autosaveEnabled = false+ switch mode {+ case "configuration":+ try verifyConfiguration(schema: schema, configuration: configuration, url: url)+ case "seed-old":+ let project = Project(name: "Synthetic", description: "Disposable verification",+ gitRepo: nil, colorHex: "#123456")+ let task = TransitTask(name: "Synthetic task", type: .feature,+ project: project, displayID: .permanent(1))+ context.insert(project)+ context.insert(task)+ try context.save()+ try report(context, phase: mode)+ case "hold-old":+ try report(context, phase: "READY")+ while let command = readLine() {+ if command == "read" { try report(ModelContext(container), phase: "READ") }+ if command == "quit" { break }+ }+ case "open-new":+ try report(context, phase: "before-new-save")+ context.insert(MCPWriteReceipt(localScopeID: "synthetic", tool: "probe", key: "synthetic-key",+ requestJSON: "{}", acceptedAt: Date()))+ try context.save()+ let receipt = try context.fetch(FetchDescriptor<MCPWriteReceipt>()).first!+ precondition(receipt.key == "synthetic-key" && receipt.stateRawValue == "accepted")+ try report(context, phase: mode, receipt: receipt)+ default: fatalError("Unsupported probe mode")+ }+ }++ @MainActor static func verifyConfiguration(+ schema: Schema, configuration: ModelConfiguration, url: URL+ ) throws {+ let expected = url.deletingLastPathComponent()+ .appendingPathComponent("TransitDevelopment/development.store")+ precondition(configuration.url == expected && !configuration.isStoredInMemoryOnly)+ for mode in [AppPersistencePolicy.Mode.unitTest, .uiTest] {+ let memory = try IsolatedPersistenceConfiguration.make(mode: mode, schema: schema)+ precondition(memory.isStoredInMemoryOnly)+ let isolated = try ModelContainer(for: schema, configurations: memory)+ let project = Project(name: "Memory synthetic", description: "", gitRepo: nil, colorHex: "#123456")+ isolated.mainContext.insert(project)+ try isolated.mainContext.save()+ let count = try isolated.mainContext.fetchCount(FetchDescriptor<Project>())+ precondition(count == 1)+ }+ print("Actual isolated configuration checks passed")+ }++ @MainActor static func report(_ context: ModelContext, phase: String, receipt: MCPWriteReceipt? = nil) throws {+ let tasks = try context.fetch(FetchDescriptor<TransitTask>())+ let projects = try context.fetch(FetchDescriptor<Project>())+ var result: [String: Any] = [+ "phase": phase, "taskCount": tasks.count, "projectCount": projects.count,+ "taskIDs": tasks.map { $0.id.uuidString }, "projectNames": projects.map(\.name),+ "linkedProjectNames": tasks.map { $0.project?.name ?? "missing" },+ "taskRecords": tasks.map { ["id": $0.id.uuidString,+ "displayID": $0.permanentDisplayId as Any? ?? NSNull(),+ "status": $0.statusRawValue,+ "projectID": $0.project?.id.uuidString as Any? ?? NSNull()] }+ ]+ // A named synthetic projection uses the production revision algorithm;+ // it is not advertised as a complete task revision from a live tool.+ result["projectionRevisions"] = try tasks.map { task in+ try MCPRecordRevision.token(entity: "syntheticTaskProjection", fields: [+ "id": MCPRecordRevision.uuid(task.id), "name": task.name,+ "displayID": task.permanentDisplayId as Any? ?? NSNull(),+ "status": task.statusRawValue, "projectID": MCPRecordRevision.uuid(task.project?.id),+ "creationDate": try MCPRecordRevision.exactDate(task.creationDate),+ "lastStatusChangeDate": try MCPRecordRevision.exactDate(task.lastStatusChangeDate)+ ])+ }+ if let receipt {+ result["receipt"] = ["id": receipt.id.uuidString, "key": receipt.key, "state": receipt.stateRawValue]+ }+ let data = try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys])+ print(String(data: data, encoding: .utf8)!)+ fflush(stdout)+ }+}
diff --git a/tests/development-isolation/PolicyProbe.swift b/tests/development-isolation/PolicyProbe.swiftnew file mode 100644index 0000000..4c91d40--- /dev/null+++ b/tests/development-isolation/PolicyProbe.swift@@ -0,0 +1,40 @@+import Foundation++@main+struct PolicyProbe {+ static func main() throws {+ typealias Policy = AppPersistencePolicy+ func mode(_ development: Bool, _ bundle: String?, _ environment: [String: String] = [:],+ runtime: Bool = false) throws -> Policy.Mode {+ try Policy.resolve(bundleID: bundle, developmentBuild: development,+ environment: environment, testRuntimeDetected: runtime)+ }+ func expect(_ actual: Policy.Mode, _ expected: Policy.Mode) {+ precondition(actual == expected)+ }+ func rejects(_ operation: () throws -> Policy.Mode) {+ do { _ = try operation(); fatalError("Unsafe launch accepted") } catch {}+ }+ try expect(mode(false, Policy.productionBundleID), .production)+ try expect(mode(true, Policy.developmentBundleID), .development)+ rejects { try mode(true, Policy.productionBundleID) }+ rejects { try mode(false, Policy.developmentBundleID) }+ rejects { try mode(false, nil) }+ rejects { try mode(true, Policy.developmentBundleID, ["TRANSIT_PERSISTENCE_MODE": "production"]) }+ rejects { try mode(false, Policy.productionBundleID, ["TRANSIT_PERSISTENCE_MODE": "invalid"]) }+ rejects { try mode(false, Policy.productionBundleID, ["TRANSIT_PERSISTENCE_MODE": "unit-test"]) }+ for development in [false, true] {+ try expect(mode(development, Policy.developmentBundleID,+ ["TRANSIT_PERSISTENCE_MODE": "unit-test"]), .unitTest)+ try expect(mode(development, Policy.developmentBundleID,+ ["TRANSIT_PERSISTENCE_MODE": "ui-test"]), .uiTest)+ try expect(mode(development, Policy.developmentBundleID, runtime: true), .unitTest)+ try expect(mode(development, Policy.developmentBundleID,+ ["XCTestConfigurationFilePath": "/synthetic/test-config"]), .unitTest)+ }+ precondition(!Policy.Mode.development.permitsCloudSync)+ precondition(!Policy.Mode.unitTest.permitsBackgroundServices)+ precondition(Policy.Mode.uiTest.usesMemoryStore)+ print("Persistence policy checks passed")+ }+}
diff --git a/tests/development-isolation/configuration_guard.py b/tests/development-isolation/configuration_guard.pynew file mode 100644index 0000000..98e29f8--- /dev/null+++ b/tests/development-isolation/configuration_guard.py@@ -0,0 +1,62 @@+"""Reject development/test build configuration that can share production identity."""+import json+import pathlib+import plistlib+import subprocess+import xml.etree.ElementTree as ET++root = pathlib.Path(__file__).resolve().parents[2]+project = root / "Transit/Transit.xcodeproj/project.pbxproj"+objects = json.loads(subprocess.check_output(+ ["/usr/bin/plutil", "-convert", "json", "-o", "-", str(project)]+))["objects"]+found = set()+for target in objects.values():+ if target.get("isa") != "PBXNativeTarget" or target.get("productType") != "com.apple.product-type.application":+ continue+ name = target["name"]+ found.add(name)+ configurations = objects[target["buildConfigurationList"]]["buildConfigurations"]+ for identifier in configurations:+ configuration = objects[identifier]+ settings = configuration["buildSettings"]+ isolated = name == "TransitDevelopment" or configuration["name"] == "Debug"+ if isolated:+ assert settings["PRODUCT_BUNDLE_IDENTIFIER"] == "me.nore.ig.Transit.development"+ entitlements = plistlib.loads((root / "Transit" / settings["CODE_SIGN_ENTITLEMENTS"]).read_bytes())+ assert not any("icloud" in key or "aps-environment" in key or "application-groups" in key+ for key in entitlements), entitlements+ assert settings["REGISTER_APP_GROUPS"] == "NO"+ if name == "TransitDevelopment":+ assert "TRANSIT_DEVELOPMENT" in settings["SWIFT_ACTIVE_COMPILATION_CONDITIONS"]+ else:+ assert settings["PRODUCT_BUNDLE_IDENTIFIER"] == "me.nore.ig.Transit"+ assert settings["CODE_SIGN_ENTITLEMENTS"] == "Transit/Transit.entitlements"+assert {"Transit", "TransitDevelopment"}.issubset(found)+scheme = ET.parse(root / "Transit/Transit.xcodeproj/xcshareddata/xcschemes/Transit.xcscheme")+test_action = scheme.find("TestAction")+assert test_action.attrib["buildConfiguration"] == "Debug"+variables = test_action.findall("EnvironmentVariables/EnvironmentVariable")+assert any(v.attrib == {"key": "TRANSIT_PERSISTENCE_MODE", "value": "unit-test", "isEnabled": "YES"}+ for v in variables)+for file in (root / "Transit/TransitUITests").glob("*.swift"):+ source = file.read_text()+ if "let app = XCUIApplication()" in source:+ assert 'app.launchEnvironment["TRANSIT_PERSISTENCE_MODE"] = "ui-test"' in source, file+app = (root / "Transit/Transit/TransitApp.swift").read_text()+assert "AppDisplayIDAllocators.make(mode: mode, syncActive: cloudSyncActive)" in app+assert "DisplayIDAllocator(" not in app, "App bootstrap must use the guarded allocator factory"+smoke_scheme = ET.parse(root / "Transit/Transit.xcodeproj/xcshareddata/xcschemes/TransitIsolationSmoke.xcscheme")+smoke_action = smoke_scheme.find("TestAction")+assert smoke_action.attrib["buildConfiguration"] == "Debug"+assert any(v.attrib == {"key": "TRANSIT_PERSISTENCE_MODE", "value": "unit-test", "isEnabled": "YES"}+ for v in smoke_action.findall("EnvironmentVariables/EnvironmentVariable"))+smoke = next(t for t in objects.values() if t.get("name") == "TransitIsolationSmokeTests"+ and t.get("isa") == "PBXNativeTarget")+assert len(smoke["fileSystemSynchronizedGroups"]) == 1+assert objects[smoke["fileSystemSynchronizedGroups"][0]]["path"] == "TransitIsolationSmokeTests"+for identifier in objects[smoke["buildConfigurationList"]]["buildConfigurations"]:+ settings = objects[identifier]["buildSettings"]+ assert settings["PRODUCT_BUNDLE_IDENTIFIER"] == "me.nore.ig.Transit.development.smoke-tests"+ assert "TransitDevelopment.app/" in settings["TEST_HOST"]+print("Development identity, entitlements, test launch configuration and guarded allocator wiring passed")
diff --git a/tests/development-isolation/host_smoke.py b/tests/development-isolation/host_smoke.pynew file mode 100644index 0000000..47d897c--- /dev/null+++ b/tests/development-isolation/host_smoke.py@@ -0,0 +1,52 @@+"""Verify the built isolated host before a single, serial test-without-building run."""+import json+import pathlib+import plistlib+import subprocess+import sys++products = pathlib.Path(sys.argv[1]).resolve()+host = products / "Debug/TransitDevelopment.app"+info = plistlib.loads((host / "Contents/Info.plist").read_bytes())+assert info["CFBundleIdentifier"] == "me.nore.ig.Transit.development"+assert info["CFBundleExecutable"] == "TransitDevelopment"+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)+assert not any("icloud" in key or "aps-environment" in key or "application-groups" in key+ for key in entitlements), entitlements+assert entitlements.get("com.apple.security.get-task-allow") is True+files = list(products.glob("TransitIsolationSmoke_*.xctestrun"))+assert len(files) == 1, files+configuration = plistlib.loads(files[0].read_bytes())+targets = []+if "TestConfigurations" in configuration:+ for test_configuration in configuration["TestConfigurations"]:+ targets.extend(test_configuration["TestTargets"])+else:+ targets = [value for key, value in configuration.items()+ if not key.startswith("__") and isinstance(value, dict)]+unit = [target for target in targets if target.get("BlueprintName") == "TransitIsolationSmokeTests"]+assert len(unit) == 1, targets+unit = unit[0]+host_path = unit["TestHostPath"].replace("__TESTROOT__", str(products))+assert pathlib.Path(host_path).resolve() == host+assert unit.get("IsUITestBundle", False) is False+variables = unit.setdefault("EnvironmentVariables", {})+assert variables.get("TRANSIT_PERSISTENCE_MODE") == "unit-test", variables+variables.update(TRANSIT_ISOLATION_SMOKE="1", TRANSIT_SMOKE_HOST_PATH=str(host))+unit["OnlyTestIdentifiers"] = ["DevelopmentIsolationSmokeTests"]+launch = products / "IsolationSmoke.xctestrun"+launch.write_bytes(plistlib.dumps(configuration))+evidence = {"bundleID": info["CFBundleIdentifier"], "host": str(host),+ "entitlements": entitlements, "mode": variables["TRANSIT_PERSISTENCE_MODE"],+ "fixture": "TransitIsolationSmokeTests/DevelopmentIsolationSmokeTests", "parallel": False}+(products / "smoke-preflight.json").write_text(json.dumps(evidence, indent=2) + "\n")+print(json.dumps(evidence, indent=2), flush=True)+result = products / "IsolationSmoke.xcresult"+assert not result.exists(), "Use fresh result/DerivedData paths for a repeat smoke"+subprocess.run(["xcodebuild", "test-without-building", "-xctestrun", str(launch),+ "-destination", "platform=macOS,arch=arm64", "-parallel-testing-enabled", "NO",+ "-only-testing:" + evidence["fixture"],+ "-resultBundlePath", str(result)], check=True, timeout=180)
diff --git a/tests/development-isolation/run.py b/tests/development-isolation/run.pynew file mode 100644index 0000000..8d2650e--- /dev/null+++ b/tests/development-isolation/run.py@@ -0,0 +1,127 @@+"""Bounded offline verification; production files are denied to every child."""+import json+import os+import pathlib+import selectors+import sqlite3+import subprocess+import sys+import tempfile+++def main():+ policy, migration, bootstrap, output = map(lambda p: pathlib.Path(p).resolve(), sys.argv[1:])+ cache_root = output.parent+ temporary = cache_root / "tmp"+ temporary.mkdir(parents=True, exist_ok=True)+ production = pathlib.Path.home() / "Library/Containers/me.nore.ig.Transit"+ groups = pathlib.Path.home() / "Library/Group Containers"+ profile = '(version 1)(allow default)(deny network*)' + ''.join(+ '(deny file-read* file-write* (subpath ' + json.dumps(str(p)) + '))'+ for p in (production, groups)+ )+ prefix = ["/usr/bin/sandbox-exec", "-p", profile]+ subprocess.run(prefix + ["/usr/bin/true"], check=True, timeout=5)+ results = {"cloudKit": "none", "network": "denied by sandbox-exec",+ "liveContainer": "denied by sandbox-exec", "cases": []}+ results["policy"] = subprocess.check_output(prefix + [str(policy)], text=True, timeout=10).strip()+ results["bootstrap"] = subprocess.check_output(prefix + [str(bootstrap)], text=True, timeout=15).strip()+ with tempfile.TemporaryDirectory(prefix="transit-synthetic-", dir=temporary) as disposable:+ root = pathlib.Path(disposable).resolve()+ environment = dict(os.environ, TRANSIT_DISPOSABLE_ROOT=str(root))++ def execute(mode, store):+ run = subprocess.run(prefix + [str(migration), mode, str(store)],+ env=environment, capture_output=True, text=True, timeout=15)+ return {"mode": mode, "exit": run.returncode,+ "stdout": run.stdout, "stderr": run.stderr[-8000:]}++ configuration_root = root / "configuration"+ configuration_root.mkdir()+ results["configuration"] = execute("configuration", configuration_root / "synthetic.store")++ def metadata(store):+ connection = sqlite3.connect(store.as_uri() + "?mode=ro", uri=True)+ try:+ return {+ "entities": connection.execute("SELECT Z_ENT,Z_NAME FROM Z_PRIMARYKEY").fetchall(),+ "taskEntityCounts": connection.execute(+ "SELECT Z_ENT,count(*) FROM ZTRANSITTASK GROUP BY Z_ENT").fetchall(),+ "taskUUIDDuplicates": connection.execute(+ "SELECT count(*) FROM (SELECT ZID FROM ZTRANSITTASK GROUP BY ZID HAVING count(*)>1)"+ ).fetchone()[0],+ "quickCheck": connection.execute("PRAGMA quick_check").fetchone()[0],+ }+ finally:+ connection.close()++ for concurrent in (False, True):+ case_root = root / ("concurrent" if concurrent else "sequential")+ case_root.mkdir()+ store = case_root / "synthetic.store"+ case = {"name": case_root.name, "seed": execute("seed-old", store)}+ if case["seed"]["exit"]:+ raise RuntimeError(case["seed"])+ case["before"] = metadata(store)+ old = None+ try:+ if concurrent:+ # Stderr is a file, so diagnostic output cannot fill a pipe+ # and prevent bounded completion of the held process.+ with (case_root / "old-stderr.txt").open("w+") as errors:+ old = subprocess.Popen(prefix + [str(migration), "hold-old", str(store)],+ env=environment, stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=errors,+ text=True, bufsize=1)+ case["oldReady"] = read_line(old)+ case["new"] = execute("open-new", store)+ old.stdin.write("read\nquit\n")+ old.stdin.flush()+ case["oldRead"] = read_line(old)+ old.wait(timeout=10)+ errors.seek(0)+ case["oldExit"] = old.returncode+ case["oldStderr"] = errors.read()[-8000:]+ else:+ case["new"] = execute("open-new", store)+ case["after"] = metadata(store)+ except (OSError, subprocess.SubprocessError, TimeoutError) as error:+ case["error"] = str(error)+ finally:+ if old is not None:+ if old.poll() is None:+ old.terminate()+ old.wait(timeout=5)+ old.stdin.close()+ old.stdout.close()+ results["cases"].append(case)+ baseline = results["cases"][0]+ baseline_ok = baseline.get("new", {}).get("exit") == 0 and "error" not in baseline+ if baseline_ok:+ seed = json.loads(baseline["seed"]["stdout"].strip().splitlines()[-1])+ saved = json.loads(baseline["new"]["stdout"].strip().splitlines()[-1])+ baseline_ok = (saved["taskCount"] == 1 and saved["projectCount"] == 1+ and seed["taskRecords"] == saved["taskRecords"]+ and seed["projectionRevisions"] == saved["projectionRevisions"]+ and saved["receipt"]["key"] == "synthetic-key"+ and saved["receipt"]["state"] == "accepted"+ and saved["linkedProjectNames"] == ["Synthetic"])+ results["sequentialInvariantPassed"] = baseline_ok+ output.write_text(json.dumps(results, indent=2) + "\n")+ print(json.dumps(results, indent=2))+ if results["configuration"]["exit"] != 0:+ raise RuntimeError("Actual isolated configuration checks failed; see saved evidence")+ if not results["sequentialInvariantPassed"]:+ raise RuntimeError("Sequential migration baseline failed; see saved evidence")+++def read_line(process):+ with selectors.DefaultSelector() as selector:+ selector.register(process.stdout, selectors.EVENT_READ)+ if not selector.select(timeout=10):+ raise TimeoutError("Disposable probe did not respond within 10 seconds")+ return process.stdout.readline().strip()+++if __name__ == "__main__":+ main()
diff --git a/tests/validation/bootstrap_mcp_result_schema_tests.sh b/tests/validation/bootstrap_mcp_result_schema_tests.shnew file mode 100755index 0000000..33ef8ea--- /dev/null+++ b/tests/validation/bootstrap_mcp_result_schema_tests.sh@@ -0,0 +1,10 @@+#!/bin/sh+# Isolated test-only dependencies; no changes to global Python or Transit runtime.+set -eu+script_directory=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+repository_directory=$(CDPATH= cd -- "$script_directory/../.." && pwd)+environment_directory="$repository_directory/.codex-cache/schema-tests/venv"+python3 -m venv "$environment_directory"+"$environment_directory/bin/python" -m pip --isolated install --disable-pip-version-check --no-cache-dir \+ -r "$script_directory/mcp-result-schema-requirements.txt"+"$environment_directory/bin/python" "$script_directory/validate_mcp_result_schemas.py" --self-test
diff --git a/tests/validation/mcp-result-schema-requirements.txt b/tests/validation/mcp-result-schema-requirements.txtnew file mode 100644index 0000000..30442aa--- /dev/null+++ b/tests/validation/mcp-result-schema-requirements.txt@@ -0,0 +1,7 @@+# Test-only isolated environment; never a Transit runtime dependency.+attrs==26.1.0+jsonschema==4.25.1+jsonschema-specifications==2025.9.1+referencing==0.36.2+rpds-py==0.27.1+typing_extensions==4.16.0
diff --git a/tests/validation/validate_mcp_result_schema_recovery.py b/tests/validation/validate_mcp_result_schema_recovery.pynew file mode 100644index 0000000..c99f574--- /dev/null+++ b/tests/validation/validate_mcp_result_schema_recovery.py@@ -0,0 +1,78 @@+#!/usr/bin/env python3+"""Host-only supplemental conformance after copying three app-owned exports.++The directory must contain batch/, maintenance/ and protected/, each with the+actual result.json and schema.json exported by MCPResultSchemaRecoveryTests.+Use the pinned schema-tests venv and the actual process exit code. Pure source+exports can exercise this checker, but are not app Swift Testing GREEN evidence.+"""++import argparse+from pathlib import Path++from validate_mcp_result_schemas import decode, read_artifact, validator++EXPECTED = {+ "batch": "reconcile_original_write",+ "maintenance": "reconcile_maintenance",+ "protected": "follow_source",+}+++def validate_recovery_exports(directory, app_exit_code):+ if app_exit_code != 0:+ raise ValueError("App test did not exit successfully; recovery export is not GREEN evidence")+ if {path.name for path in directory.iterdir() if path.is_dir()} != set(EXPECTED):+ raise ValueError("Recovery export must contain exactly batch, maintenance and protected")+ for name, direction in EXPECTED.items():+ artifact_directory = directory / name+ wire = read_artifact(artifact_directory, "result.json")+ schema = read_artifact(artifact_directory, "schema.json")+ if wire.get("jsonrpc") != "2.0" or wire.get("id") != name:+ raise ValueError("Wrong recovery fixture correlation: " + name)+ result = wire["result"]+ structured = result["structuredContent"]+ if result.get("resultType") != "complete" or result.get("isError") is not True:+ raise ValueError("Recovery fixture lost original result facts: " + name)+ content = result["content"]+ if len(content) != 1 or content[0].get("type") != "text":+ raise ValueError("Recovery fixture lost original text: " + name)+ payload = structured["source"]["payload"]+ if structured["source"]["kind"] != "json" or payload != decode(content[0]["text"]):+ raise ValueError("Recovery fixture altered original logical evidence: " + name)+ if payload.get("outcome") != "rejected" or payload.get("accepted") is not False \+ or payload.get("retryAction") != "new_request_new_key":+ raise ValueError("Recovery fixture altered saved acceptance/retry facts: " + name)+ presentation = structured["presentation"]+ recovery = presentation["recovery"]+ if presentation.get("evidence") != "established" or presentation.get("errorCategory") != "invalid_input" \+ or recovery.get("direction") != direction:+ raise ValueError("Unexpected recovery presentation: " + name)+ if name == "batch":+ expected_item = {"index": 0, "operation": "update_task", "tool": "update_task",+ "idempotencyKey": "original-item-key", "itemId": "saved item",+ "targetTaskId": "AA000000-0000-0000-0000-000000000001"}+ if recovery.get("items") != [expected_item]:+ raise ValueError("Batch recovery lost original ordered item identity")+ elif name == "maintenance":+ if recovery != {"direction": direction, "tool": "maintenance_fixture"}:+ raise ValueError("Maintenance recovery invented a key or changed its original tool")+ elif recovery != {"direction": direction, "tool": "update_task",+ "idempotencyKey": "original-protected-key"}:+ raise ValueError("Protected recovery lost original tool/key")+ errors = list(validator(schema).iter_errors(structured))+ if errors:+ raise ValueError("Actual schema rejects " + name + ": " + errors[0].message)+ print("PASS: 3 actual recovery descriptors/results; original identities and saved evidence preserved")+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("directory", type=Path)+ parser.add_argument("--app-exit-code", type=int, required=True)+ args = parser.parse_args()+ validate_recovery_exports(args.directory, args.app_exit_code)+++if __name__ == "__main__":+ main()
diff --git a/tests/validation/validate_mcp_result_schemas.py b/tests/validation/validate_mcp_result_schemas.pynew file mode 100644index 0000000..fd5bfd9--- /dev/null+++ b/tests/validation/validate_mcp_result_schemas.py@@ -0,0 +1,239 @@+#!/usr/bin/env python3+"""Host-only Draft 2020-12 checks of app-owned exports; never fetch references.++Run with the isolated schema-tests venv. A successful test process exit code must+be supplied explicitly. --self-test exercises only validator plumbing, not Transit.+"""++import argparse+import copy+import json+import tempfile+from decimal import Decimal+from pathlib import Path++from jsonschema import Draft202012Validator, FormatChecker+from referencing import Registry++DRAFT = "https://json-schema.org/draft/2020-12/schema"+EXPECTED_TOOLS = frozenset("query_tasks get_projects query_milestones create_task update_task "+ "update_task_status add_comment create_project create_milestone "+ "update_milestone delete_milestone synthetic_mutate_tasks".split())+EXPECTED_CATEGORIES = "invalid_input not_found ambiguous_identity revision_conflict key_conflict storage_failure " \+ "incoherent_capture admission_busy deadline_exceeded retention_capacity invalid_cursor expired_cursor " \+ "serialization_failure outcome_uncertain unclassified_historical internal_failure"+EXPECTED_FIXTURES = frozenset("object array null boolean string number huge_number historical retained_error text "+ "empty_text unreadable retry_read restart_read maintenance follow_source linked_record "+ "escaped_pointer batch batch_fallback".split()) | frozenset(+ "category_" + value for value in EXPECTED_CATEGORIES.split())+EXPECTED_NEGATIVES = frozenset("missing_version wrong_version boolean_version missing_source missing_presentation "+ "unknown_kind missing_kind json_missing_payload text_missing_payload "+ "text_nonstring_payload unreadable_payload unreadable_established missing_evidence "+ "invalid_evidence missing_links links_nonarray invalid_category category_null "+ "invalid_recovery recovery_missing_direction recovery_invalid_tool recovery_invalid_key "+ "invalid_entity invalid_uuid invalid_pointer invalid_pointer_escape guessed_available "+ "guessed_uri missing_link_reason wrong_link_reason missing_entity_id missing_entity_type "+ "batch_negative_index batch_boolean_index batch_fraction_index batch_invalid_target "+ "batch_missing_original_key".split())+++def reject_constant(value):+ raise ValueError("Non-JSON constant: " + value)+++def exact_members(pairs):+ result = {}+ for name, value in pairs:+ if name in result:+ raise ValueError("Duplicate JSON member: " + name)+ result[name] = value+ return result+++def decode(text):+ return json.loads(text, parse_float=Decimal, parse_int=int,+ parse_constant=reject_constant, object_pairs_hook=exact_members)+++def read_artifact(directory, filename):+ path = (directory / filename).resolve()+ if path.parent != directory.resolve() or not path.is_file():+ raise ValueError("Missing or nonlocal export artifact: " + filename)+ return decode(path.read_text(encoding="utf-8"))+++def refuse_retrieval(uri):+ raise ValueError("External schema retrieval prohibited: " + uri)+++def check_references(schema):+ # Walk every member, including extension keywords. A future validator must+ # never make those references a route to the network either.+ stack = [schema]+ while stack:+ value = stack.pop()+ if isinstance(value, dict):+ for keyword in ("$ref", "$dynamicRef"):+ if keyword in value:+ reference = value[keyword]+ if not isinstance(reference, str) or not reference.startswith("#"):+ raise ValueError("Only local schema references permitted")+ stack.extend(value.values())+ elif isinstance(value, list):+ stack.extend(value)+++def validator(schema):+ if not isinstance(schema, dict) or schema.get("$schema") != DRAFT:+ raise ValueError("Descriptor must explicitly advertise Draft 2020-12")+ check_references(schema)+ Draft202012Validator.check_schema(schema)+ return Draft202012Validator(schema, format_checker=FormatChecker(),+ registry=Registry(retrieve=refuse_retrieval))+++def mutate(original, case):+ value = copy.deepcopy(original)+ parent = value+ for component in case["path"][:-1]:+ parent = parent[int(component)] if isinstance(parent, list) else parent[component]+ final = case["path"][-1]+ if isinstance(parent, list):+ final = int(final)+ if case["remove"]:+ del parent[final]+ else:+ parent[final] = case["value"]+ return value+++def coverage(items, identity, expected, files=False):+ names = [item[identity] for item in items]+ if len(names) != len(expected) or set(names) != expected:+ raise ValueError("Truncated, unexpected or duplicate export coverage: " + identity)+ if files and len({item["file"] for item in items}) != len(items):+ raise ValueError("Duplicate export artifact mapping")+++def validate_exports(directory, app_exit_code):+ if app_exit_code != 0:+ raise ValueError("App test did not exit successfully; export is not GREEN evidence")+ manifest = read_artifact(directory, "manifest.json")+ if type(manifest.get("exportVersion")) is not int or manifest["exportVersion"] != 1 \+ or manifest.get("status") != "complete":+ raise ValueError("Incomplete source-generated schema export")+ fixtures, schemas, negatives = (manifest[key] for key in ("fixtures", "schemas", "negativeCases"))+ coverage(fixtures, "name", EXPECTED_FIXTURES, files=True)+ coverage(schemas, "tool", EXPECTED_TOOLS, files=True)+ coverage(negatives, "name", EXPECTED_NEGATIVES)+ instances = {}+ for item in fixtures:+ wire = read_artifact(directory, item["file"])+ if wire.get("jsonrpc") != "2.0" or wire["result"].get("resultType") != "complete":+ raise ValueError("Fixture is not an actual complete RPC result")+ instances[item["name"]] = wire["result"]["structuredContent"]+ count = 0+ for item in schemas:+ check = validator(read_artifact(directory, item["file"]))+ for name, instance in instances.items():+ errors = list(check.iter_errors(instance))+ if errors:+ raise ValueError(item["tool"] + " rejects emitted " + name + ": " + errors[0].message)+ count += 1+ for case in negatives:+ if check.is_valid(mutate(instances[case["base"]], case)):+ raise ValueError(item["tool"] + " accepts malformed " + case["name"])+ count += 1+ print(f"PASS: {len(schemas)} actual descriptors, {len(fixtures)} emitted source cases, "+ f"{len(negatives)} malformed variants; {count} schema assertions")+++def self_test():+ # Deliberately tiny nonproduction schema. These controls cannot complete task8/9.+ schema = {"$schema": DRAFT, "type": "object", "required": ["flag", "number"],+ "properties": {"flag": {"type": "boolean"}, "number": {"type": "number"}},+ "additionalProperties": False}+ check = validator(schema)+ for text in ('{"flag":false,"number":1E-9999}', '{"flag":true,"number":1E9999}',+ '{"flag":false,"number":99999999999999999999999999999999999999}'):+ assert check.is_valid(decode(text)), text+ for text in ('{"flag":0,"number":1}', '{"flag":null,"number":1}',+ '{"number":1}', '{"flag":false,"number":"1"}'):+ assert not check.is_valid(decode(text)), text+ unicode_keys = decode('{"é":1,"é":2}')+ assert len(unicode_keys) == 2 and unicode_keys["é"] != unicode_keys["é"]+ for text in ('{"same":1,"same":2}', 'NaN', 'Infinity', '-Infinity', '01', '1.'):+ try:+ decode(text)+ except ValueError:+ continue+ raise AssertionError("Accepted invalid JSON: " + text)+ for keyword in ("$ref", "$dynamicRef"):+ for placement in ({keyword: "https://example.invalid/schema"},+ {"unknownExtension": {keyword: "https://example.invalid/schema"}}):+ try:+ validator({"$schema": DRAFT, **placement})+ except ValueError:+ continue+ raise AssertionError("Accepted external reference")+ local = {"$schema": DRAFT, "$defs": {"flag": {"type": "boolean"}}, "$ref": "#/$defs/flag"}+ assert validator(local).is_valid(False) and not validator(local).is_valid(0)+ # Stock jsonschema treats Decimal as number, but integral Decimal is not its+ # integer type. Owned wrapper/index integers are Int lexemes; arbitrary+ # source.payload numbers remain unconstrained. Never rebuild them to fit this.+ integer = Draft202012Validator({"type": "integer"})+ assert integer.is_valid(decode("1")) and not integer.is_valid(decode("1.0"))+ # Exercise the registry denial independently of the static scanner.+ blocked = Draft202012Validator({"$ref": "https://example.invalid/schema"},+ registry=Registry(retrieve=refuse_retrieval))+ try:+ blocked.is_valid({})+ except Exception as error:+ assert "Unresolvable" in str(error), error+ else:+ raise AssertionError("External retrieval registry did not reject")+ with tempfile.TemporaryDirectory(prefix="transit-schema-validator-controls-") as temporary:+ directory = Path(temporary)+ fixtures = [{"name": value, "file": value + ".json"} for value in sorted(EXPECTED_FIXTURES)]+ schemas = [{"tool": value, "file": value + "-schema.json"} for value in sorted(EXPECTED_TOOLS)]+ negatives = [{"name": value} for value in sorted(EXPECTED_NEGATIVES)]+ complete = {"exportVersion": 1, "status": "complete", "fixtures": fixtures,+ "schemas": schemas, "negativeCases": negatives}+ cases = [(complete, 65, "App test did not exit successfully"),+ ({**complete, "status": "incomplete"}, 0, "Incomplete source-generated schema export"),+ (complete, 0, "Missing or nonlocal export artifact"),+ ({**complete, "fixtures": fixtures[:1]}, 0, "export coverage: name"),+ ({**complete, "schemas": schemas[:1]}, 0, "export coverage: tool"),+ ({**complete, "negativeCases": negatives[:1]}, 0, "export coverage: name")]+ duplicate_tools = copy.deepcopy(schemas)+ duplicate_tools[-1] = duplicate_tools[0]+ duplicate_files = [{**item, "file": "shared.json"} for item in schemas]+ cases.extend([({**complete, "schemas": duplicate_tools}, 0, "export coverage: tool"),+ ({**complete, "schemas": duplicate_files}, 0, "Duplicate export artifact mapping")])+ for manifest, exit_code, reason in cases:+ (directory / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")+ try:+ validate_exports(directory, exit_code)+ except ValueError as error:+ assert reason in str(error), (reason, str(error))+ continue+ raise AssertionError("Accepted incomplete/truncated/missing/failed export")+ print("PASS: validator-only JSON/Decimal/scalar-key/offline/fail-closed controls; no Transit schema claim")+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("directory", type=Path, nargs="?")+ parser.add_argument("--app-exit-code", type=int)+ parser.add_argument("--self-test", action="store_true")+ args = parser.parse_args()+ if args.self_test:+ self_test()+ elif args.directory is not None and args.app_exit_code is not None:+ validate_exports(args.directory, args.app_exit_code)+ else:+ parser.error("Supply an export directory and --app-exit-code, or --self-test")+++if __name__ == "__main__":+ main()
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b67edd3..c992abc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,11 +8,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- T-2383: MCP tool results expose a versioned structured source/presentation envelope while preserving original text, saved receipt outcomes and retry evidence. Tool output schemas and a synthetic read-only loopback readiness harness cover the contract; navigable links remain unavailable pending T-572. - T-2380: Eight standard MCP writes require retry keys, and task/milestone updates require revision preconditions. Local receipts retain saved outcomes for seven days, durable guards protect uncertain requests across restart, and full-record reads return content revisions for conflict detection. - T-2377: MCP `create_project` accepts a required name and six-digit colour, validates optional description/repository fields and case-insensitive name uniqueness, persists through `ProjectService`, and returns project ID and metadata for subsequent task creation. Regression tests cover discovery, validation, storage failures, fallback write rejection, and project-to-task creation. ### Changed +- T-2383: Replace legacy MCP initialization, session groups and GET streams with latest-only request validation, stateless discovery and request-scoped POST subscriptions. Acknowledgements and completion frames remain separate from coalesced invalidations, and cancellation/lifecycle cleanup preserves bounded read ownership. Local isolated tests pass; production activation remains held for actual installed-client readiness. - T-2380: Full bounded task queries now capture complete comment-covered revisions even when comments are omitted from the response. Duplicate batch references share one capture and continuation pages retain frozen revisions; summary reads without comments still skip comment retrieval. - T-2379: MCP `query_tasks` requires explicit detail, comments, and page-size options and returns bounded pages over five-minute frozen results. Batch UUID/display-ID lookup reports ordered per-input outcomes, comments are optional, and opaque cursors expire or invalidate on server restart. Existing filters are preserved; the query response changes from an array to an object containing results, next cursor, and expiry. Task serialization shares one date formatter per query, and regression coverage verifies frozen comment values after edits, removal, and creation.
diff --git a/CLAUDE.md b/CLAUDE.mdindex dd655eb..13fa2cf 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -138,21 +138,23 @@ Shared intent infrastructure lives in `Intents/Shared/`: entities (`ProjectEntit ### MCP Server (macOS only) -HTTP-based JSON-RPC 2.0 server using **Hummingbird**, gated behind `#if os(macOS)`. Configured via `MCPSettings` (UserDefaults-backed toggle and port). Exposes 11 tools:+HTTP-based JSON-RPC 2.0 server using **Hummingbird**, gated behind `#if os(macOS)`. Configured via `MCPSettings` (UserDefaults-backed toggle and port). Exposes 12 normal tools: -`create_task`, `update_task_status`, `query_tasks`, `update_task`, `add_comment`, `get_projects`, `create_project`, `create_milestone`, `query_milestones`, `update_milestone`, `delete_milestone`+`create_task`, `update_task_status`, `query_tasks`, `update_task`, `add_comment`, `get_projects`, `create_project`, `create_milestone`, `query_milestones`, `update_milestone`, `delete_milestone`, `query_project_summaries` Key implementation files: - `MCP/MCPServer.swift` — Hummingbird router, lifecycle management - `MCP/MCPToolHandler.swift` — dispatches `tools/call` to service layer - `MCP/MCPToolDefinitions.swift` — tool schemas with input validation-- `MCP/MCPTypes.swift` — JSON-RPC request/response types+- `MCP/MCPTypes.swift` — shared JSON-RPC types; exposed transport is latest-only `2026-07-28` via `MCP/Protocol` and `MCPServer+Routing.swift`+- `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`) - `MCP/Writes/MCPWriteCoordinator.swift` — key acceptance, revision checks, atomic domain/result saves, and replay/recovery - `MCP/Writes/MCPWriteReceiptStore.swift` and `MCPLocalReservationStore.swift` — synced receipts and local durable payload guards - `MCP/Writes/MCPRecordSnapshot.swift` — normalized records and content revision coverage -The MCP server reuses the same service instances as the UI (shared `mainContext`), so changes from MCP calls appear immediately in the app. `TransitApp` retains one write coordinator and store-scoped sidecar for its lifetime; listener restarts do not release accepted operations or their lock. Protected writes require keys, and updates/deletion require revision preconditions; MCP results wrap full saved records rather than matching App Intent response envelopes. See [docs/mcp-write-contract.md](docs/mcp-write-contract.md) before changing schemas or examples. Domain changes and their terminal receipt share one synchronous save; guards remain durable when outcome recovery is uncertain.+The MCP server reuses the same service instances as the UI (shared `mainContext`), so changes from MCP calls appear immediately in the app. `TransitApp` retains one write coordinator and store-scoped sidecar for its lifetime; listener restarts do not release accepted operations or their lock. Protected writes require keys, and updates/deletion require revision preconditions; MCP results wrap full saved records rather than matching App Intent response envelopes. See [docs/mcp-write-contract.md](docs/mcp-write-contract.md) and [docs/mcp-result-contract.md](docs/mcp-result-contract.md) before changing schemas or examples. Domain changes and their terminal receipt share one synchronous save; guards remain durable when outcome recovery is uncertain. ### Reports
diff --git a/README.md b/README.mdindex cc4ba47..8783ce7 100644--- a/README.md+++ b/README.md@@ -16,7 +16,7 @@ Transit sits alongside the existing tool ecosystem: [Orbit](https://github.com/A - **Reports** — generate summary reports of completed/abandoned tasks by date range - **Cross-device sync** via CloudKit private database - **CLI automation** through App Intents — create tasks, update statuses, manage milestones, add comments, generate reports-- **MCP server** (macOS) — HTTP JSON-RPC server for AI agent integration with 11 tools+- **MCP server** (macOS) — HTTP JSON-RPC server for AI agent integration with 12 normal tools - **Agent handoff statuses** (Ready for Implementation, Ready for Review) for AI/human workflow integration - **Adaptive layout**: width-based multi-column Kanban on iPhone/iPad/Mac, with a segmented single-column fallback only when one column fits - **Drag and drop** between columns to change task status@@ -64,11 +64,11 @@ All intents accept a JSON string input and return a JSON string response, includ ## MCP Server (macOS) -Transit includes a built-in MCP server on macOS for AI agent integration. Enable it in Settings and configure the port (default: 3141). The server exposes 11 tools over HTTP JSON-RPC 2.0:+Transit includes a built-in MCP server on macOS for AI agent integration. Enable it in Settings and configure the port (default: 3141). The server exposes 12 normal tools over latest-only MCP `2026-07-28` HTTP JSON-RPC 2.0: -`create_task`, `update_task_status`, `query_tasks`, `update_task`, `add_comment`, `get_projects`, `create_project`, `create_milestone`, `query_milestones`, `update_milestone`, `delete_milestone`+`create_task`, `update_task_status`, `query_tasks`, `update_task`, `add_comment`, `get_projects`, `create_project`, `create_milestone`, `query_milestones`, `update_milestone`, `delete_milestone`, `query_project_summaries` -The eight write tools require an `idempotencyKey`. Task/milestone updates and milestone deletion also require the target's current `expectedRevision`. Read a revision before updating, and retry an interrupted request with the same key and arguments. Responses use structured saved-record outcomes; see the [MCP write contract](docs/mcp-write-contract.md) for examples, seven-day replay retention, conflicts, and local-store limits. App Intent inputs are unchanged.+The eight write tools require an `idempotencyKey`. Task/milestone updates and milestone deletion also require the target's current `expectedRevision`. Read a revision before updating, and retry an interrupted request with the same key and arguments. Responses use structured saved-record outcomes; see the [MCP write contract](docs/mcp-write-contract.md) for examples, seven-day replay retention, conflicts, and local-store limits. See the [MCP result contract](docs/mcp-result-contract.md) for structuredContent, modern request headers and recovery. Actual installed-client compatibility is deferred to post-merge MacBook validation and remains unverified. App Intent inputs are unchanged. ## Documentation
diff --git a/docs/agent-notes/mcp-server.md b/docs/agent-notes/mcp-server.mdindex 1e57855..cdefaaf 100644--- a/docs/agent-notes/mcp-server.md+++ b/docs/agent-notes/mcp-server.md@@ -7,10 +7,10 @@ Embedded MCP server in the Transit macOS app using Hummingbird HTTP server. Expo ## Architecture ```-Claude Code ←→ HTTP POST + session GET/SSE /mcp (localhost:3141) ←→ MCPServer ←→ MCPToolHandler ←→ read services / MCPWriteCoordinator ←→ SwiftData+Claude Code ←→ HTTP POST + request-scoped POST/SSE /mcp (localhost:3141) ←→ MCPServer ←→ MCPToolHandler ←→ read services / MCPWriteCoordinator ←→ SwiftData ``` -- **Transport**: Streamable HTTP at `/mcp`. `POST /mcp` carries JSON-RPC requests and client notifications; a successful standalone `initialize` returns an `Mcp-Session-Id`. A GET with that session ID and an exact acceptable `text/event-stream` media range opens the optional SSE channel for server-initiated notifications. Missing session IDs return 400, unknown IDs return 404, and GET without SSE negotiation remains HTTP 405 with `Allow: POST`.+- **Transport**: Latest-only MCP `2026-07-28` at `POST /mcp`: server/discover, tools/list, tools/call and request-scoped subscriptions/listen SSE. No initialize, session ID, GET listener or wire arrays. Required metadata/headers and result schemas are documented in [the result contract](../mcp-result-contract.md). - **HTTP server**: Hummingbird 2.x (SwiftNIO-based), binds to `127.0.0.1` only - **Lifecycle**: Opt-in via Settings toggle. Default port 3141. @@ -21,10 +21,10 @@ Claude Code ←→ HTTP POST + session GET/SSE /mcp (localhost:3141) ←→ MCPS - `Transit/Transit/MCP/MCPToolListChangeBroadcaster.swift` — active SSE stream registration and list-change broadcasting - `Transit/Transit/MCP/MCPToolHandler.swift` — Tool dispatch, handler methods, helpers - `Transit/Transit/MCP/MCPToolDefinitions.swift` — Tool schema definitions (extracted for file length)-- `Transit/Transit/MCP/MCPServer.swift` — Hummingbird server lifecycle, session creation, and HTTP routing+- `Transit/Transit/MCP/MCPServer.swift` — Hummingbird server lifecycle and modern HTTP routing - `Transit/Transit/MCP/MCPServer+Responses.swift` — shared JSON response encoding and header construction - `Transit/Transit/MCP/MCPRequestContext.swift` — request context retaining the NIO channel for disconnect observation-- `Transit/Transit/MCP/MCPServer+ToolListNotifications.swift` — session validation, Streamable HTTP GET negotiation, and SSE framing+- `Transit/Transit/MCP/MCPServer+ToolListNotifications.swift` — request-scoped POST subscription negotiation and SSE framing - `Transit/Transit/MCP/MCPServerLifecycleConfiguration.swift` — bounded shutdown and no-signal `ServiceGroup` policy - `Transit/Transit/MCP/MCPServerDecodeTypes.swift` — request decode outcome types shared by the route and decoder - `Transit/Transit/MCP/MCPOriginValidator.swift` — transport-level `Origin`/`Host` validation@@ -50,28 +50,22 @@ All eight write tools require `idempotencyKey`; updates and milestone deletion a | `create_task` | Create a new task (name and type required; at least one of project / projectId required to identify the project; description, metadata, and priority optional — priority defaults to medium, invalid priority rejects with no task created) | | `update_task_status` | Change task status (by displayId or taskId) | | `update_task` | Update a task's mutable fields — any combination of `name`, `description`, `type`, `priority`, `metadata`, and milestone assignment (`milestone` / `milestoneDisplayId` / `clearMilestone`) — in a single atomic call. Priority is non-clearable: omit to leave unchanged. Identify task by displayId or taskId. |-| `query_tasks` | Required detailLevel, includeComments, and limit (1–100); returns frozen {results,nextCursor,expiresAt} pages. Existing filters or single displayId; taskIds/displayIds batches reject filters. Continuations send only cursor. |+| `query_tasks` | Required detailLevel, includeComments, and limit (1–100); returns frozen {results,nextCursor,expiresAt} pages. Existing filters or single displayId; taskIds/displayIds batches reject filters. Continuations send cursor and optional identical retained readPolicy. | | `add_comment` | Add a comment to a task (by displayId or taskId); always sets `isAgent: true` | ### Task query snapshots (T-2379) -`MCPTaskQueryRequest` validates initial options and cursor-only continuation.-`MCPToolHandler+TaskQuery` copies all selected task/comment values into JSON pages-synchronously on MainActor before publication. Full queries fetch child-side comments once per unique task for a complete revision, even when `includeComments: false` omits their payload; summary queries with that option skip the fetch. Repeated batch IDs reuse one snapshot, and continuations retain frozen revisions without fetching. `MCPTaskQuerySnapshotStore` retains-encoded pages for five minutes with monotonic expiry, at most eight multi-page-snapshots and 16 MiB. Capacity rejection preserves existing cursors; reads do not-extend lifetime. One-page results are byte-limited but need no retained snapshot.-The listener closes query admission and clears snapshots before shutdown awaits,-on generation-checked current-listener exit, and before reopening on launch.-Whole-query tool errors contain a structured `{error:{code,message}}` object.+`MCPTaskQueryRequest` validates initial options and cursor continuation (cursor plus optional identical retained readPolicy). The admitted `MCPReadService` captures saved values, then prepares projected pages, frozen tool fragments and capture metadata through the common result seam before atomic publication. Full queries fetch child-side comments for a complete revision even when bodies are omitted; summary queries without comments can skip that fetch. Repeated selector IDs reuse captured evidence. Continuations retain frozen revisions/text/metadata and add only a newly correlated RPC wrapper, without fetching live records.++`MCPTaskQuerySnapshotStore` retains encoded pages for five minutes with monotonic expiry, at most eight multi-page snapshots and16MiB charged retained data. Capacity rejection preserves existing cursors; reads do not extend lifetime. One-page results are byte-limited but need no retained snapshot. Listener shutdown closes admission and clears indexes before awaiting listener teardown; unfinished physical read workers retain their slots until finalizers complete; canceled or failed publication cannot expose cursor success. The bounded coordinator retains unfinished physical slots across restart. ### Maintenance tools (gated, default off) `scan_duplicate_display_ids` and `reassign_duplicate_display_ids` are exposed only when `MCPSettings.maintenanceToolsEnabled` is true. The toggle is persisted under UserDefaults key `mcpMaintenanceToolsEnabled`. - `MCPToolDefinitions` is split into `coreTools` and `maintenanceTools`; `tools(includingMaintenance:)` returns the right subset. The legacy `all` alias still resolves to `coreTools` only — anything in production should use the helper.-- When the toggle is off, `tools/list` excludes both maintenance tools and `tools/call` for either name returns JSON-RPC `invalidParams` (-32602) with the literal message `Tool '<name>' is disabled. Enable maintenance tools in Transit Settings.` — distinct from the "Unknown tool" message used for genuinely unknown names.-- The toggle takes effect on the next `tools/list` without restart. Initialization advertises `tools.listChanged: true` and returns a unique session ID; each initialized session with one or more negotiated GET/SSE streams receives exactly one `notifications/tools/list_changed` on each real toggle change. `MCPToolListChangeBroadcaster` is scoped to the shared `MCPSettings` instance, deduplicates across concurrent streams in the same session, and retains only the newest pending invalidation because the notification is idempotent. The request context observes each NIO channel's close future so even an idle disconnected stream is promptly finished and unregistered.+- When the toggle is off, tools/list excludes both maintenance tools. Exposed modern tools/call validation rejects unknown or disabled tool names with HTTP400/-32602, `Tool name is missing or unavailable`, before handler dispatch.+- The toggle takes effect on the next tools/list without restart. Discovery advertises tools.listChanged; subscriptions/listen acknowledges supported requested filters before any change. Each opted-in request stream receives correlated availability changes with bounded coalescing. Disconnect/cancellation/server teardown releases its registration; there are no sessions. - Dispatch handlers (`handleScanDuplicateDisplayIds`, `handleReassignDuplicateDisplayIds`) encode `DisplayIDMaintenanceTypes` (Codable structs) via a shared `encodedTextResult(_:)` helper that JSON-encodes any `Encodable` and wraps it in the `MCPToolResult.content[text]` envelope. ## Origin / Host Validation (T-1833)@@ -95,7 +89,7 @@ Gotchas: - **Never reject a missing `Origin`.** Claude Code and CLI callers send no `Origin` header at all; rejecting absence breaks the entire agent integration. - **Rejections are plain HTTP 403, not JSON-RPC errors.** The request never- entered a JSON-RPC session, and a `200` with an error object would confirm to+ passed protocol validation, and a `200` with an error object would confirm to an attacker's page that the endpoint is live. The body is a fixed `"Forbidden"` rather than the specific reason, so a prober cannot tell whether the `Origin` or the `Host` check tripped.@@ -115,19 +109,10 @@ Gotchas: - `MCPSettings.validPortRange` is `nonisolated` so the validator (which runs on NIO threads) can reuse it. -## JSON-RPC Methods Handled--`initialize`, `notifications/initialized`, `ping`, `tools/list`, `tools/call`--### Initialize handshake validation (T-1778)--`initialize` requires an object `params` containing string `protocolVersion`, object `capabilities`, and object `clientInfo`. `clientInfo.name` and `clientInfo.version` are required strings; optional `clientInfo.title` must also be a string. Missing fields and object/array method-parameter mismatches return JSON-RPC `invalidParams` (`-32602`); scalar or null top-level `params` violate the JSON-RPC request shape and return `invalidRequest` (`-32600`). Transit currently supports only `2025-03-26`: that version is echoed when requested, while any unsupported requested version receives the latest advertised supported version (`2025-03-26`) per the MCP lifecycle negotiation rule.--## JSON-RPC Batch Envelopes (T-1834)--`POST /mcp` accepts either one `JSONRPCRequest` or a non-empty JSON-RPC batch. `MCPServer.decodeIncomingRequest` preserves invalid batch members so each produces its own `-32600` response, while an empty batch produces one standalone `-32600` object as required by JSON-RPC 2.0.+## Modern request validation -Batch dispatch is sequential on the MainActor to keep mutations against the shared SwiftData context deterministic. Responses to request members remain inside an array even when notifications are omitted. A batch containing only notifications returns HTTP 202 with no body; notifications still execute their method/tool path before the result is discarded. Batched `initialize` requests are rejected with `-32600` because MCP 2025-03-26 requires initialization to be a standalone request. Single requests continue to return one response object.+Supported methods: `server/discover`, `tools/list`, `tools/call`, `subscriptions/listen`.+The route validates Origin/Host before collecting at most1MiB, then validates one request object, ID, required per-request metadata and matching protocol/method/name headers before dispatch. Unsupported versions return the supported revision; unknown methods return404. Arrays, initialize, GET listeners, null/missing IDs and unsupported client notifications reject without effects. See [the result contract](../mcp-result-contract.md) for exact fields, response schemas and rejection behavior. ## Dependencies @@ -142,25 +127,11 @@ Batch dispatch is sequential on the MainActor to keep mutations against the shar Added `com.apple.security.network.server` and `com.apple.security.network.client` to `Transit.entitlements`. -## Testing with curl+## Client usage and compatibility -Protected calls follow the [MCP write contract](../mcp-write-contract.md): supply a fresh key for a new logical request and reuse it unchanged for retries. Updates and milestone deletion also need the current revision from a read. The create example assumes an existing project named `Agent Work`.+Use the request examples and header requirements in [the result contract](../mcp-result-contract.md). Protected effects additionally require the original key/revision evidence from [the write contract](../mcp-write-contract.md). Do not send legacy headerless curl calls or assume a client supports the latest-only endpoint from its version. -```bash-# List tools-curl -X POST http://localhost:3141/mcp -H 'Content-Type: application/json' \- -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'--# Create task-curl -X POST http://localhost:3141/mcp -H 'Content-Type: application/json' \- -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"create_task","arguments":{"name":"Test","type":"feature","project":"Agent Work","idempotencyKey":"curl-create-task-001"}}}'-```--## Claude Code Integration--```bash-claude mcp add transit --transport http http://localhost:3141/mcp-```+Actual Codex/Claude installed-client compatibility is unverified and owner-approved deferred to post-merge MacBook validation. No client configuration or activation is performed by this branch's tests. Validate each intended surface against an isolated synthetic endpoint before relying on it. ## Task Resolution @@ -173,7 +144,7 @@ MCPToolHandler, App Intents, and IntentHelpers all delegate to these methods rat ## Gotchas - `nonisolated` on struct/enum declarations is essential in this project due to `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`. Without it, all types inherit MainActor isolation, breaking Codable conformance on NIO threads.-- `JSONRPCRequest` preserves the distinction between an omitted `id` member and an explicit JSON `null` using `isNotification`. MCP 2025-03-26 requires present IDs to be strings or integers, so `MCPToolHandler.handle(_:)` rejects the `id == nil && !isNotification` state with `-32600 Invalid Request`; omitted-id notifications still execute and return no response. T-847 established the presence flag, but its expectation that explicit null should be accepted is superseded by T-1863.+- Modern request IDs are nonnull strings or signed64-bit integral numbers. Missing IDs/client notifications are rejected without dispatch; a tools/call notification cannot mutate data. Internal legacy decoder types do not define the exposed route. - `ByteBuffer(data:)` requires explicit `import NIOFoundationCompat` — not available from just `import Hummingbird`. - Don't reference `self` in `Task.detached` closures on `MCPServer` — causes "sending 'self' risks data races" error. Capture dependencies explicitly. - **Name-based filters must handle cross-project duplicates.** Milestone names (and potentially other name-resolved entities) can be duplicated across projects. When filtering by name without a project scope, use `Set<UUID>` to collect all matching IDs rather than taking just the first match (T-292).
diff --git a/docs/mcp-result-contract.md b/docs/mcp-result-contract.mdnew file mode 100644index 0000000..4808b65--- /dev/null+++ b/docs/mcp-result-contract.md@@ -0,0 +1,103 @@+# MCP result contract version 1++Transit's macOS endpoint supports MCP `2026-07-28` only. A tool result keeps the original text and optional `isError` and adds an independent structured wrapper. Output schemas advertised by `tools/list` validate `structuredContent`, not the entire JSON-RPC response.++```json+{+ "jsonrpc": "2.0",+ "id": "read-1",+ "result": {+ "resultType": "complete",+ "content": [{"type": "text", "text": "{\"results\":[],\"nextCursor\":null,\"expiresAt\":\"2026-10-04T00:05:00Z\"}"}],+ "structuredContent": {+ "contractVersion": 1,+ "source": {"kind": "json", "payload": {"results": [], "nextCursor": null, "expiresAt": "2026-10-04T00:05:00Z"}},+ "presentation": {"evidence": "established", "links": []}+ }+ }+}+```++This illustrative empty frozen-page result omits `isError` and capture metadata. Actual covered reads also carry their original `_meta` capture/freshness data outside `structuredContent`. Use the advertised schema and actual result rather than assuming metadata is absent.++## Original source and presentation++| Source kind | Payload | Meaning |+| --- | --- | --- |+| `json` | Complete original JSON value, including scalar/array roots | Parseable provider evidence; preserve unknown fields and original types. |+| `text` | Original string | Provider explicitly declared plain text. Do not guess JSON intent. |+| `unreadable` | Absent | Retained JSON cannot be interpreted; exact raw text remains in `content[0].text`. |++`presentation.evidence` is `established` or `unestablished`. A syntactically readable source can still have contradictory or unsupported outcome evidence; do not infer commitment from readability. Supplemental `errorCategory`, `recovery` and `links` never overwrite original payload fields. Unknown saved fields named `presentation`, `source` or `contractVersion` stay inside `source.payload`.++Preserve absent versus null, Boolean versus number, unknown fields and exact numeric tokens. The optional result-level `isError` preserves its original absent/false/true state. Text is the unchanged original string, including whitespace/newlines; JSON string escaping in the outer transport does not change that string. Native consumers can round numbers, so retain raw text when exact numeric identity matters.++Parser inputs allow at most 32 nested object/array containers (root container counts one; scalar counts zero). Generated JSON over this limit fails with a resource-limit error. Retained over-limit or malformed JSON becomes unreadable with unestablished evidence; it is not rewritten or reparsed from live records. The complete modern wrapper is not subject to a claimed 32-level output limit.++## Replay, frozen pages and saved fields++[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.++| Protected path | Existing normalization authority |+| --- | --- |+| `create_task`, `create_milestone` | Services trim names; provided descriptions pass through, including surrounding whitespace/newlines. |+| `create_project` | ProjectService trims name; description passes through, with the existing empty-string default when omitted. |+| `update_task` | TaskUpdateValidator trims name/description using whitespacesAndNewlines. Omitted description is unchanged; empty after trimming clears it. Internal newlines survive. Metadata replaces/clears under the validator. |+| `update_milestone` | MCPWriteCommand trims name/description. Omission leaves description unchanged; empty after trimming clears it. |+| `add_comment`, status update with comment | CommentService trims content and author; existing status-command validation applies. |++The serializer adds no second normalizer. Historical absence/null distinctions remain intact.++## Errors and recovery++Original `error.code`, message, `outcome`, `accepted` and `retryAction` remain authoritative evidence. Category is supplemental, not a new outcome namespace or a retry guarantee. Protocol-invalid requests produce HTTP/JSON-RPC failures rather than tool errors.++| Category | Read recovery / caller action |+| --- | --- |+| `invalid_input`, `not_found`, `ambiguous_identity`, `revision_conflict`, `key_conflict` | Correct input or inspect evidence; no automatic read retry promised. |+| `storage_failure`, `incoherent_capture`, `admission_busy`, `deadline_exceeded`, `retention_capacity`, `serialization_failure` | `retry_identical_read` for reads; failure publishes no successful records/cursor/snapshot. |+| `invalid_cursor`, `expired_cursor` | `restart_read`; start a fresh read rather than reusing the invalid retained view. |+| `outcome_uncertain` | Reconcile the original mutation and protected key; never assume no effect or use a fresh key automatically. |+| `unclassified_historical`, `internal_failure` | Inspect source and provider evidence; no blanket retry promise. |++For protected writes, `recovery.direction:follow_source` means obey the preserved known `retryAction`; `reconcile_original_write` includes the original tool and key. Unsupported/contradictory evidence requires reconciliation even if it resembles rejection. Unprotected maintenance uses `reconcile_maintenance` and its original tool, without an invented protected key; inspect current state with a fresh `scan_duplicate_display_ids` before deciding further effects.++A mutation's complete request-correlated fallback bytes must be prepared before effects. If final encoding fails after effects, selection uses those bytes without calling the failed encoder again; effect evidence is unestablished. Application-batch recovery can retain ordered original indexes/tool/keys/UUIDs, while compact fallback omits unbounded itemIds, raw records and links. This common seam does not claim T2384 production integration or define its batch outcomes.++## Links++Task/project entries in `presentation.links` associate `entityType`, UUID `entityId` and RFC6901 `sourcePath` with frozen source evidence. Each currently has `availability:unavailable` and `reason:navigation_not_supported`. No guessed URI is emitted. T572 entity-opening navigation is a separate feature; unavailable links remain deterministic on replay.++## Latest-only request contract++Use one JSON-RPC object per `POST /mcp`, with `Content-Type: application/json`. Requests require non-null string or signed 64-bit integral IDs, object `params` and:++```json+{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}+```++Optional clientInfo, if supplied, must include string name/version. Send `MCP-Protocol-Version: 2026-07-28` and `Mcp-Method` matching the body method. `tools/call` additionally requires `Mcp-Name` matching the tool name. Ordinary responses require acceptable `application/json`; subscriptions require acceptable `text/event-stream`. Header name matching is case-insensitive, values remain validated. Request bodies are limited to 1 MiB.++Methods are `server/discover`, `tools/list`, `tools/call` and `subscriptions/listen`. Discovery and sorted tool lists include `resultType:complete`, `ttlMs:0` and `cacheScope:public`. Maintenance availability changes are reflected in the next list. There is no initialization handshake, session ID, GET listener or wire-level JSON-RPC batch. An application batch is one `tools/call` under its owner's separate feature contract.++| Rejected input | HTTP behavior |+| --- | --- |+| Disallowed Origin/Host | 403 before body capture/dispatch |+| Non-POST method | 405, Allow POST |+| Unsupported content type / response negotiation | 415 / 406 |+| Malformed JSON, nesting/range/shape errors, missing/mismatched metadata/headers, unavailable tool, client notification | 400, no effects |+| Unsupported protocol version | 400 with supported version list |+| Unknown RPC method, including legacy initialize, after valid modern metadata/headers | 404, method-not-found; an invalid envelope rejects earlier |+| Oversized body | 413 |++Loopback-only listening remains `127.0.0.1`; missing Origin is permitted, non-loopback Origin/Host is rejected. The transport expands no remote access.++`subscriptions/listen` uses `params.notifications:{toolsListChanged:true}` plus request metadata, ID and matching headers. The first SSE message is `notifications/subscriptions/acknowledged`; changes carry the original subscription ID and only acknowledged supported filters. Pending invalidations coalesce without evicting the first acknowledgement. Disconnect/cancellation removes the request registration; graceful server closure may finish with a complete result. No session IDs, event IDs or resumability are issued.++## Bounds and readiness++Covered reads retain the five-second deadline and eight unfinished physical-read admission slots across listener restarts. Cancellation suppresses late delivery/publication but does not free a physical slot until work completes. Ordinary/reusable retained data retains its own five-minute, eight-snapshot and 16-MiB contracts; structured/text/envelope duplication is charged. Capacity/deadline failure does not publish partial success or invalidate existing retained entries.++Actual installed Codex surfaces, Claude Code and Claude Desktop compatibility remains **unverified**. The owner explicitly deferred AC6.3 to post-merge MacBook testing at Sentinel_c0dbfe3212888191bc01744c855f67bb. Synthetic loopback evidence proves local protocol behavior only. Later validation must record modern discovery/list/call and native parsed structured consumption per intended surface, and subscriptions for surfaces opting in. This deferral permits merge after required review/checks; it does not authorise client setup or deployment here.
diff --git a/docs/mcp-write-contract.md b/docs/mcp-write-contract.mdindex 89ca82b..3b93248 100644--- a/docs/mcp-write-contract.md+++ b/docs/mcp-write-contract.md@@ -8,7 +8,7 @@ Intents retain their existing input contracts. Keys are case-sensitive and match `[A-Za-z0-9._:-]{1,128}`. Generate a fresh UUID for each logical write. The namespace is one local store plus tool name, independent of JSON-RPC request ID, connection and-MCP session. Request identity includes every argument except the key, including the original revision.+protocol session (the modern endpoint uses none). Request identity includes every argument except the key, including the original revision. Object order is ignored; array order, Boolean versus number, absence versus null and explicit versus omitted defaults remain significant. JSON numbers are compared by value. @@ -28,7 +28,7 @@ If the response is lost, repeat those exact arguments with that same key. A reta replays the original saved record, revision and metadata even after editing or deleting the target. Reusing a retained key with different arguments returns `IDEMPOTENCY_KEY_REUSED` without mutation. -Protected responses are JSON in MCP `content[0].text`. Committed responses include `contractVersion:1`,+Protected responses retain JSON in MCP `content[0].text` and expose the same complete logical JSON, when interpretable, at `structuredContent.source.payload`. Retained malformed or over-limit JSON preserves raw text with unreadable structured evidence. Supplemental presentation lives separately; see the [versioned result contract](mcp-result-contract.md). Committed responses include `contractVersion:1`, `tool`, `idempotencyKey`, `outcome:"committed"`, `accepted:true`, `entityId`, the full saved `record`, `completedAt` and `replayExpiresAt`. The record contains its `revision`. Status with a comment also returns the full saved `comment`; both persist together. Milestone deletion returns `deleted:true`@@ -62,7 +62,7 @@ the same token. Tokens are neither timestamps nor monotonic counters. Edits not CloudKit cannot be detected, and later sync merges can still conflict. These outcome and revision semantics are shared vocabulary for T-2384. They introduce no batch-mutation application or dry-run behavior; existing ordered JSON-RPC batches remain non-atomic.+mutation application or dry-run behavior. Wire-level JSON-RPC arrays are rejected. A T-2384 application batch, when delivered by its owner, is one tools/call with its separate per-item effect policy. ## Recovery when local retry storage is unreadable
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex 9f9f531..f9f33b0 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -36,6 +36,8 @@ | [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 |+| [Structured MCP Results](#structured-mcp-results) | 2026-10-03 | Ready for Review | Structured/text results and latest-only transport locally verified; client compatibility explicitly deferred post-merge |+| [Bounded Read Freshness](#bounded-read-freshness) | 2026-10-03 | In Progress | Bound MCP read completion and report immutable saved capture/import evidence | --- @@ -351,3 +353,51 @@ All 18 coding tasks are implemented and review findings are resolved. Verificati - [tasks.md](mcp-write-safety/tasks.md) - [prerequisites.md](mcp-write-safety/prerequisites.md) - [implementation.md](mcp-write-safety/implementation.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.++**Status:** In Progress++- [Scope](structured-mcp-results/scope.md)+- [Requirements](structured-mcp-results/requirements.md)+- [Requirements review](structured-mcp-results/requirements-review.md)+- [Design](structured-mcp-results/design.md)+- [Design review](structured-mcp-results/design-review.md)+- [Tasks](structured-mcp-results/tasks.md)+- [Task review](structured-mcp-results/tasks-review.md)+- [Prerequisites](structured-mcp-results/prerequisites.md)+- [Decision log](structured-mcp-results/decision_log.md)+- [Implementation evidence](structured-mcp-results/implementation.md)+- [Local verification handoff](structured-mcp-results/local-verification-handoff.md)+- [Bounded client approval request](structured-mcp-results/client-readiness-next-approval.md)+- [Source RED evidence](structured-mcp-results/source-red.md)+- [Source cap RED evidence](structured-mcp-results/source-cap-red.md)+- [Source GREEN evidence](structured-mcp-results/source-green.md)+- [Presentation GREEN evidence](structured-mcp-results/presentation-green.md)+- [Protocol GREEN evidence](structured-mcp-results/protocol-green.md)+- [Encoder implementation draft](structured-mcp-results/encoder-green.md)+- [Encoder RED preparation](structured-mcp-results/encoder-red.md)+- [Encoder fixture review](structured-mcp-results/encoder-review.md)+- [Schema RED preparation](structured-mcp-results/schema-red.md)+- [Schema implementation readiness](structured-mcp-results/schema-green.md)+- [Isolation integration](structured-mcp-results/isolation-integration-plan.md)+- [Presentation RED evidence](structured-mcp-results/presentation-red.md)+- [Presentation supplemental RED evidence](structured-mcp-results/presentation-supplemental-red.md)+- [Pending common interface coordination](structured-mcp-results/interface-coordination.md)+- [Protocol RED evidence](structured-mcp-results/protocol-red.md)++## Bounded Read Freshness++**Created:** 2026-10-03 · **Status:** In Progress++T-63 bounds MCP reads with saved-only coherent capture, explicit import evidence, independent deadlines and frozen pagination metadata. Shared capture/publication contracts support T2382 reusable portfolio views.++- [Requirements](bounded-read-freshness/requirements.md)+- [Design](bounded-read-freshness/design.md)+- [Tasks](bounded-read-freshness/tasks.md)+- [Decisions](bounded-read-freshness/decision_log.md)+- [Task review](bounded-read-freshness/tasks-review.md)+- [Foundation handoff](bounded-read-freshness/foundation-handoff.md)
diff --git a/specs/bounded-read-freshness/contract-proposal.md b/specs/bounded-read-freshness/contract-proposal.mdnew file mode 100644index 0000000..02e3d7a--- /dev/null+++ b/specs/bounded-read-freshness/contract-proposal.md@@ -0,0 +1,75 @@+# Shared read contract proposal — T-63 and T2382++Status: draft for parent and user review. The user approved preserving existing payloads with additive metadata, refresh_if_needed default, five-second total/two-second refresh limits, the mixed-batch delivery exception, same-snapshot summary/task-query reuse, and deferring a separate refresh tool and maintenance reads. The parent assigned T2382 external snapshot API/lifecycle and T-63 compatible shared capture/freshness. Remaining fields, 30-second import threshold, admission bounds, and exact schema/integration are not approved requirements or design.++## Meaning of a captured view++`asOf` is the UTC timestamp assigned when local immutable data capture completes. It describes the data returned, not the most recent server response, latest remote write, or global CloudKit convergence. `snapshotId` is an opaque identity for that captured view; equal timestamps do not establish equal snapshots.++Every page of a captured result keeps exactly the same `asOf`, `snapshotId`, and freshness evidence. A cursor continuation may have a new request latency or response time, but these do not replace the captured metadata. Snapshot retention expiry stays distinct from the per-request read deadline.++## Proposed logical shape++```json+{+ "asOf": "2026-10-03T15:00:00.000Z",+ "snapshotId": "opaque-view-id",+ "freshness": {+ "syncState": "active",+ "assessment": "recent_import",+ "assessedAt": "2026-10-03T15:00:00.000Z",+ "lastImportedAt": "2026-10-03T14:59:55.000Z",+ "evidence": "local_import_observation",+ "recentImportThresholdMs": 30000+ },+ "read": {+ "policy": "refresh_if_needed",+ "refreshOutcome": "recent_import",+ "budgetMs": 5000+ }+}+```++This shape is logical metadata. Placement in existing array responses versus query envelopes is an open compatibility decision; do not change shared schemas before that decision is approved.++| Field/state | Meaning |+| --- | --- |+| `syncState: active` | The running store was configured with CloudKit. |+| `syncState: inactive` | The running store has no CloudKit sync; no import wait applies. |+| `lastImportedAt: null` | No successful, relevant import is known; never substitute heartbeat or response time. |+| `assessment: recent_import` | A successfully observed relevant import ended within the disclosed threshold before capture; it is not proof all remote changes are visible. |+| `assessment: stale` | Last known successful import is older than the disclosed threshold. |+| `assessment: unknown` | No trustworthy relevant import evidence exists, including observer unavailability or process-start uncertainty. |+| `assessment: not_applicable` | Cloud sync is inactive; the data is a local view. |+| `evidence: local_import_observation` | The endpoint observed a relevant completed successful import, subject to verification that the evidence applies to the captured context. |+| `evidence: none` | No trustworthy import evidence. |++Use UTC ISO 8601 with a documented precision for wire dates, and a monotonic clock for durations/deadlines. Freshness age is assessed once at capture; retained pages do not gain newer import evidence. A caller can compute the view's current age from fixed dates. A later failed import must not erase the last successful timestamp or turn the captured view into a fresh one.++## Policy, deadlines, and errors++`cached` captures the local view without import waiting. It does not mean bypassing the local store, and still has a fetch/encoding deadline. `refresh_if_needed` skips waiting if evidence meets the configured recency threshold; otherwise it attempts or observes refresh activity within the remaining total budget. Absence of a supported trigger yields `unavailable` only when there is also no relevant import already in flight. An existing relevant import can instead complete, fail, or time out during the bounded observation interval.++Proposed refresh outcomes: `not_requested`, `recent_import`, `import_observed`, `timeout`, `unavailable`, `failed`. These describe refresh handling separately from freshness assessment and local fetch success. An observed failed import can coexist with valid cached data and a prior successful import timestamp. No outcome claims guaranteed CloudKit force-pull.++Approved limits are a five-second total server read budget and at most two seconds of import waiting. A 30-second recent-import threshold remains proposed. Admission queueing, capture, transformation, and serialization share one deadline; the refresh wait is not extra time on top of it. Individual/read-only batch responses have that deadline; mixed batches produce read results within it but may await write completion for combined delivery, as the user approved.++If the deadline leaves no usable captured result, return a machine-readable `READ_TIMEOUT`, indicating the exhausted phase when known. A fetch or encode failure returns `READ_FAILED` with a stable failure category, or the existing tool error code if compatibility requires it. Keep validation/cursor/capacity errors distinct. Never return empty results to disguise failure. Both names remain proposals until the error compatibility decision is made.++Retries start a new bounded read and a new capture, except cursor retries replay the same retained page until its existing expiry. A refresh timeout does not warrant an automatic unbounded retry loop. Explicitly document a caller backoff recommendation and admission limits during design.++## T2382 integration boundary++Portfolio totals and milestone breakdowns must be derived from one coherent immutable capture and carry this same metadata. Import evidence applies only after the completed import is visible to that selected view. T-63 owns the shared deadline, policy, and import-evidence service proposal; T2382 owns summary aggregation and identity/status semantics. Parent coordinates MCPToolHandler, MCPToolDefinitions, server deadline wiring, and any cross-ticket snapshot storage changes.++Two independent captures cannot be promised to reconcile merely because both say `asOf`. T2382's approved same-snapshot behavior needs a shared retained view supporting both summaries and filtered queries. Existing task cursors remain opaque page tokens, not automatically general-purpose snapshot selectors; the reusable snapshot selector is T2382's API/lifecycle scope.++The user approved summary and detailed task queries using the same saved snapshot. The parent assigned T2382 the externally reusable summary/task-query snapshot API and lifecycle; T-63 shared capture/freshness must preserve retained capture identity. When that mechanism reuses a view, summary and query preserve its identity, capture time, and import evidence. Exact API/storage integration remains a design gate.++## Verification needed in the design phase++- Confirm the import event source actually represents the SwiftData store and context used to capture reads, including unfocused/headless execution, failures, and multiple store events.+- Establish what supported refresh trigger exists, if any. Preserve an honest unavailable path.+- Prove a slow synchronous MainActor fetch does not prevent deadline response, and bound lingering work after timeout.+- Decide whether preserving the shared UI context is essential to read-your-local-writes behavior before considering an isolated read context.+- Preserve exact original metadata in serialized cursor pages and validate summary/query reconciliation using an identical snapshot.
diff --git a/specs/bounded-read-freshness/deadline-feasibility-note.md b/specs/bounded-read-freshness/deadline-feasibility-note.mdnew file mode 100644index 0000000..78889ef--- /dev/null+++ b/specs/bounded-read-freshness/deadline-feasibility-note.md@@ -0,0 +1,22 @@+# Deadline feasibility assessment for requirements review++The approved requirement remains a five-second encoded response available to transport for individual reads and read-only JSON-RPC batches. Mixed read/write batches retain the user-approved exception: read result production is bounded but combined delivery may await writes. Checking a timeout only after a blocked MainActor resumes does not satisfy the approved response requirement.++## Source evidence at base 0db453b++- `Transit/Transit/MCP/MCPServer.swift`: `makeRouter` is explicitly nonisolated; its comment states Hummingbird/NIO route callbacks hop to MainActor for dispatch. The POST callback currently awaits `handler.handle`, which is the boundary to coordinate independently.+- `Transit/Transit/MCP/MCPServer+Responses.swift`: `jsonResponse` is explicitly nonisolated and accepts `Encodable & Sendable`, so response construction does not require MainActor.+- `Transit/Transit/MCP/MCPTypes.swift`: request, response, request ID, and MCP tool result are explicitly nonisolated Sendable value types for the NIO/MainActor boundary.+- `Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift`: current query handling fetches synchronously and publishes serialized pages before returning. Adding a timer there cannot bound a blocked MainActor read; the publication path also needs terminal-state checks before retained snapshots become visible.++## Credible architecture to validate during design++A transport-side coordinator can admit a decoded read, establish its deadline and prebuild a small timeout response, then launch an unstructured read worker that awaits MainActor. A one-shot terminal gate chooses the encoded success or timeout. The transport must return the chosen response without waiting for the underlying non-cooperative fetch to finish. A structured task-group race that waits for canceled work at scope exit is insufficient.++The physical unfinished worker remains counted against the proposed eight-operation admission bound until it actually finishes. Queued or running work must not escape accounting during server stop/restart. If timeout wins, the late worker cannot emit another response or publish a caller-visible retained snapshot. Snapshot publication must consult the shared terminal state, not merely a timer on MainActor.++Deadline delivery, fallback encoding, and read-only batch aggregation must stay independent of a blocked MainActor and of any expensive success encoding. The design should assess prebuilt timeout bytes and a short critical section/independent timer executor rather than placing timeout work behind the fetch or encoding task it bounds.++This assessment shows a plausible route supported by existing source isolation, not a completed design or verified implementation. Xcode 27 validation must demonstrate a blocked MainActor still permits the bounded transport response, late work remains accounted for, no late snapshot is published, and read-only batch output meets the shared deadline. There is no source evidence establishing that the approved deadline is impossible.++T2382 must consume the same deadline and capture metadata semantics. Its reusable summary/task-query API/lifecycle is separately owned, but it must not silently weaken the response deadline to a success-admission cutoff.
diff --git a/specs/bounded-read-freshness/decision_log.md b/specs/bounded-read-freshness/decision_log.mdnew file mode 100644index 0000000..e4bbc70--- /dev/null+++ b/specs/bounded-read-freshness/decision_log.md@@ -0,0 +1,87 @@+# T-63 decision log++## Quick decisions++| Date | Decision | Rationale / authority |+| --- | --- | --- |+| 2026-10-03 | Work on dedicated `T-63/bounded-read-freshness` branch/worktree from `0db453b` | Delegation explicitly requested isolation and allows branch commits; scoped Git administration escalation succeeded. |+| 2026-10-03 | Preserve all other work, including T2380 | Explicit delegation; inspected separate branch/worktree without editing it. |+| 2026-10-03 | Keep feature name, wire shape, budgets, default policy, refresh tool scope, and cross-ticket snapshot ownership pending | These affect caller behavior and shared T2382 contracts; no approval of unseen proposals was supplied. |+| 2026-10-03 | Do not implement or change ticket status before first approval | Actual creating-spec phase gate; requirements skill also requires a name answer. |++## Approval record++| Date | Decision | Rationale / authority |+| --- | --- | --- |+| 2026-10-03 | Full scope, full spec type, and `bounded-read-freshness` name approved | Parent conveyed direct user statement: “Both tickets scope, spec type, and name are approved” (Sentinel_3ccdbb1152c88191b673f3dde9f76e60). |+| 2026-10-03 | Ticket moved to `spec` | Actual creating-spec transition after scope approval; committed Transit revision `r1:aaaffbb389d4c805f835e3b64bb78731f83e85030897c8e7956c8154b42f31ea`. |++| 2026-10-03 | Preserve existing data payloads with additive freshness metadata; default refresh_if_needed; 5,000 ms total / at most 2,000 ms refresh limits; defer separate refresh tool and maintenance reads | Parent conveyed direct user reply “That's fine” (Sentinel_6b71cb52cf10819190043fb6ad347713 replying to Sentinel_c62cd3e9da0c8191aedc90e0eb304f6e). This reply did not approve the 30-second recency threshold or complete requirements. |++| 2026-10-03 | Summary and detailed task queries may use the same saved snapshot; T2382 owns its external API/lifecycle, T-63 shared capture/freshness supports retained identity | Parent conveyed direct user “Sounds good” (Sentinel_5479ed38c0cc8191a7c47a6487b6c0a1) to same-snapshot reconciliation proposal, and assigned ownership. The same reply approved T2382 legacy count preservation/separate counts; those count requirements belong to T2382. |++| 2026-10-03 | Individual reads/read-only batches have a five-second response limit; mixed read/write batches produce the read result within five seconds but delivery may wait on writes | Parent conveyed direct user “That's acceptable” (Sentinel_a44f8dbe8f1c8191a055e45169b5e685) replying to that exact distinction. Preserves write behavior without claiming an overall mixed-batch delivery deadline. |++## Requirements choices (now approved)++The requirements draft recommended a 30,000 ms recency threshold, eight unfinished reads as an operation-count admission bound, and server phase/late-completion diagnostics. Those requirements decisions are now approved as recorded below. Exact design mechanisms and tasks retain their separate approval gates.++## Requirements approval++| Date | Decision | Rationale / authority |+| --- | --- | --- |+| 2026-10-03 | Both final requirements packets and all decisions within them approved, including 30-second threshold, eight physical unfinished reads, and latency diagnostics | Parent conveyed direct user “Both are approved for all decisions, including the ones in the requirements review” (Sentinel_fa39017e21a08191abdcd0b7ae6c9e8e). Design, tasks, and production implementation are not approved. |+| 2026-10-03 | T-63 is single writer for shared MCPServer, MCPToolHandler init/dispatch/read-only registration, MCPToolDefinitions wiring, and shared metadata DTOs | Parent coordination; T2382 supplies separate summary/snapshot query/schema modules and owns reusable snapshot lifecycle/API. Coordination is not user design approval. |+| 2026-10-03 | Return saved data only for MCP reads/summaries | Parent conveyed direct user “If something isn't saved, it shouldn't be returned” (Sentinel_bb00a4d9d8688191a33a0e6a34ea38db). Requirement 2.6 and fresh-context design follow this explicit clarification; no need to ask again about pending UI edits. |++## Design ADR 1 — independent physical work and response completion++Use transport-side one-shot completion with an independent strict deadline timer. Keep each underlying worker admitted until it physically finishes, including after timeout and server generation changes. A structured task-group race waits for non-cooperative children at scope exit; a MainActor timer cannot run during a blocked fetch. Neither satisfies the approved response deadline.++The standalone Swift6.4 prototype measured the default asyncAfter timer returning at 5,164 ms despite a 4,850 ms schedule. A strict DispatchSourceTimer with zero leeway, userInitiated queue, and explicit @concurrent entry produced eight encoded timeouts by 4,850.49 ms and their batch by 4,851.15 ms while MainActor was blocked for six seconds. Eight unfinished slots persisted until work actually completed; restart did not reset them; no late publication occurred. This validates the isolated mechanism, not complete production transport performance.++## Design ADR 2 — fresh capture plus persistent history fence++Capture saved state from a fresh autosave-disabled ModelContext in one nonawaiting MainActor turn. Read the latest public persistent-history token/storeIdentifier before capture and again through a fresh validation context afterwards; reject unequal/unavailable/invalid fencing. Copy only immutable DTOs and bytes across executors. Do not transact, save, or roll back the UI's shared context.++The isolated SwiftData probe injected a saved project/task change between selected fetches. It observed old/new values but detected a changed history token and rejected that view; a stable fresh context returned saved new/new values. MainActor serialization alone excludes local actor reentrancy but not CloudKit/background store commits. History fencing supplies a measurable consistency check without private Core Data context access. CloudKit import/history identifier and visible-history completeness still need live signed-app verification; freshness remains unknown if association cannot be proved.++## Merged foundation verification++PR249 is merged at `201205bd4e786c7f152d8f99006b37da7da888c7`, also current remote main. Its tree is identical to previously inspected T2380 head `b618acf9e3d66a4a1ce493eea94091c058721731`; canonical r1/comment behavior needs no design change. Align the dedicated branch before production implementation, preserving this spec work and all other worktrees.++## Design ADR 3 — shared publication transaction++T-63 and T2382 agreed one common publication lock domain with pre-encoded success/rejection bytes, pending-plus-published capacity, same-store batch coalescing into one immutable index candidate, atomic child-reservation transfer, validate-all-before-any-commit, and one index swap per store. Read-only batch selection publishes all selected children together or discards all. Stale append CAS returns READ_BUSY rather than overwriting another index. Internal peer review identified the same-store lost-update gap and the design adopted this correction. These mechanisms remain proposed until final design approval.++## Shared scope clarification before design gate++`CapturedReadView.captureScope` is typed as whole portfolio, selected resolved physical project keys, or ordinary selected query. `completePortfolio` means complete declared reusable scope plus identity/comment closure, not necessarily every global record. Closure records do not enlarge selected counts; reusable queries outside declared scope fail. T2382 requested this explicit DTO contract and T-63 confirmed it before design approval.++## Design approval++The user approved both designs unchanged: “Both 63 and 2382 are approved without required changes” (Sentinel_541ceb19e7c8819193d04d23c5263041), conveyed by the parent. Approval covers T-63 `5639c40` and T2382 `3932e88`, including final typed scope and publication amendments. Task planning is authorized; the task list and production implementation still require the next explicit approval.++## Tasks approval and implementation start++The user approved both task lists: “Tasks approved, but why so many explicit mentions of xcode27 in there?” (Sentinel_c2e9343628948191b921868234aaf409), conveyed by parent. Implementation is authorized with the approved DAG/red-green evidence. The toolchain constraint remains recorded once in repository guidance; routine reports should avoid repeating it. The dedicated branch was rebased cleanly to merged `201205bd4e786c7f152d8f99006b37da7da888c7`, preserving five spec commits and all other worktrees. T-63 has the initial exclusive heavy build/test slot for foundation tasks 3/7/9 and must tell parent when released. No merge/deployment is authorized.++## Verified interface-only foundation++Commits `1b34efb` and `52e4882` define actual shared interfaces; focused typechecking and lint passed. T2382 confirmed the DTO fields satisfy its handoff. Requested comment-body JSON is optional with includeComments=false; complete portfolio canonical revision/full no-comment record/comment identity evidence remain mandatory. Stable MCPPublicationStoreID and MCPReadPublicationParticipant.prepareAggregate provide same-store grouping before terminal selection; task 9 owns concrete single-domain registry/lookup/reservation/retirement behavior. This is an interface handoff, not runtime risk verification.++## Foundation implementation review checkpoints++The import/refresh stream passed ten focused app tests at local `8d69d65`. Independent internal design review subsequently found that a non-applicable same-store completion could replace an applicable completion before polling or capture. Requirement 3.6 requires retaining that outcome. The repair adds bounded active observation windows and A/B ordering regressions; production nil-proof unknown/null behavior remains unchanged. The earlier passing suite is not treated as final verification of the repaired stream.++The capture/coordinator stream passed twelve focused app tests before the remaining large-input and initialization-race cases: seven actual SwiftData capture cases and five transport/permit/batch/terminal-race cases. Live signed-store import applicability is not established. Stable local persistent history is a capture boundary, not proof that a specific remote import is visible.++Read-only review identified a batch initialization race: stop could select an individual timeout before the complete array fallback was installed. The approved whole-array contract requires atomic same-generation admission with terminal selection deferred until the prebuilt full fallback is ready. The worker is adding forced stop/cutoff interleavings. Bulk fallback preparation remains outside the common publication lock; the original admission timestamp does not reset.++Parent's separately approved latest-protocol T2383 migration does not alter the currently approved T-63 foundation work. Keep the coordinator transport-neutral and the current batch adapter separable; do not add dual-era behavior or remove approved batch tests before coordinated integration.++## Fixture foundation verified++Tasks 2/3/6/7 passed 17 focused actual app tests, including saved-only SwiftData/canonical revision and real Hummingbird encoded availability. Large fallback admission/stop/cutoff races were corrected before handoff. Exact measured values, preserved result paths, observation-hook limitations and the coordinated task 9 registry contract are recorded in foundation-handoff.md. No signed-store import-visible proof is claimed; approved unknown/null/unavailable and incoherent_capture fallbacks remain binding. Tasks 8/9 are handed to a fresh parent-coordinated implementation delegate; no competing heavy job remains.++Both completed streams were integrated locally on the dedicated branch at `7f5d7ce`. The repaired import stream passed fourteen actual app tests at `e11979c`; independent review confirmed the A/B evidence correction and found no new lifecycle/bounding issue. Register its observation window before the decision snapshot and hold it until capture metadata is frozen. Evidence is preserved outside Git under `t63-review-evidence/foundation/` and `t63-review-evidence/import/`; only the two completed stream worktrees were removed. Tasks 1–7 are complete; publication task 9 still gates the verified T2382 runtime handoff. These local integrations are part of the authorized implementation workflow; upstream merge/deployment remains unauthorized.
diff --git a/specs/bounded-read-freshness/design-critic.md b/specs/bounded-read-freshness/design-critic.mdnew file mode 100644index 0000000..dd9bc5b--- /dev/null+++ b/specs/bounded-read-freshness/design-critic.md@@ -0,0 +1,33 @@+# T-63 design critic review++Reviewed the proposed design against the approved requirements, decision log, explanation, and isolated prototype sources using the local design-critic skill. This is an internal document review, not design approval or production validation. No tests, external review calls, ticket changes, or production edits were performed by this reviewer.++## Original findings and revalidation++| Priority | Original finding | Revised disposition |+| --- | --- | --- |+| Blocker | Individual timeout bytes did not establish a complete batch fallback; large candidate-array assembly could delay timeout or outlive physical admission accounting (requirements 1.1, 1.3, 1.5). | Addressed in design: a whole valid fallback array is prepared at decoded admission and held by an independent batch terminal gate. Candidate assembly is private; it retains a participating element permit until physically finished. Timeout selects complete fallback without waiting for assembly. Verify the reserved permit transfers atomically and cannot be released between element completion and assembly ownership. |+| Blocker | `MCPRetainedViewSource` exposed lookup but omitted the transaction contract needed to combine T-63 response selection and T2382 retention publication (requirements 1.4, 5.3). | Addressed in design: `MCPReadPublicationDomain`, `MCPPreparedPublication`, and `PreparedReadResult` define a shared lock domain, pending reservations, nonthrowing commit/discard, generation checks, and atomic batch publication. Large destruction is outside the lock. Verify every visibility/capacity/expiry transition follows this domain and that stale append CAS is checked in the same critical section as terminal selection. |+| Blocker | Optional task revision/full-record/comment fields allowed a portfolio consumer to accept an inadequate capture as complete evidence (requirements 4.2, 5.3). | Addressed in design: `CaptureCompleteness.completePortfolio` is required at the aggregation/retention boundary, with mandatory canonical task revision/full-record and complete comment-evidence validation; inadequate capture fails before counting or publishing. Missing required fetches remain storage failures. Verify these invariants are enforced at construction and consumption rather than only documented. |++No remaining design blocker was identified in this revalidation. The revised project-selector fence also closes the separate pre-capture identity-resolution race. Pending-plus-published create/append capacity, immutable index versions, and UUIDv4/v8 routing provide explicit integration rules; they still need implementation tests.++The final publication correction was also re-read: every selected reservation runs `validateLocked` before any commit in the same domain; `PreencodedPublicationErrors` supplies rejection bytes, and rejection discards the entire selected publication set and returns the matching error or batch fallback. No child success publishes before whole-batch selection. This explicitly prevents returning a staged success with an unpublished snapshot/cursor ID and clarifies the atomic CAS/terminal-selection requirement.++## Residual verification risks++1. **Persistent history is not yet proven as a CloudKit coherence fence.** The probe rejects one intervening saved local change, but does not prove remote-import history completeness, concurrent purge handling, or the empty-history sentinel. Test a genuinely empty store separately from nonempty/purged/unavailable history. A store for which the invariant cannot be established must fail with `incoherent_capture`; an alternative mechanism requires the stated design gate.+2. **Import applicability remains conditional.** Verify actual SwiftData history and CloudKit event store identifiers and evidence that the completed import is visible to the selected fresh context. Define/test the monitor's serialized observation boundary so queued event processing is not confused with proof that all earlier callbacks have been incorporated. Until supported, retain `unknown`/null import time and unavailable refresh rather than asserting recency.+3. **The deadline headroom is empirical.** The independent strict timer is supported by isolated evidence; router-return availability and batch fallback preparation are not yet measured in production. Test the maximum permitted request body, large IDs, slow result encoding/aggregation, blocked MainActor, cancellation, and stop/restart. Fallback preparation is included in the admission budget, and no fallback assembly may depend on a timed-out candidate worker.+4. **Shared publication is a concurrency integration gate.** Exercise timeout/success/stop/disconnect races, pending reservation rollback, concurrent append CAS, expiry, and batch commit/discard. Ensure no store lock nests under the domain and no large copy or final destruction runs inside it. Verify unfinished capture/encoding/assembly stays within eight physical operations, including after timeout/restart.+5. **T2380 parity must be checked on the aligned implementation base.** The revised document records PR249 merge `201205bd4e786c7f152d8f99006b37da7da888c7` with the same tree as inspected `b618acf9e3d66a4a1ce493eea94091c058721731`; this reviewer did not independently inspect that merged tree. Preserve its canonical comment-covered r1 in full task views, including omitted public comments and normalized status, and retain its ordinary summary no-comment-fetch behavior.++## Required answers and evidence before implementation completion++- Which atomic ownership transition retains the assembly permit, and do generated race tests prove it is never released early or twice?+- Do append version validation and terminal/publication selection occur under the same domain lock, with reservation discard exactly once?+- Do complete-portfolio construction and consumer validation reject every missing required revision/record/comment dependency?+- What live saved-state/import/history evidence establishes the fence, or demonstrates the documented fail-closed/unknown fallback?+- Do real router-return measurements meet the approved five-second availability contract under the named blocked-actor and large-batch cases?++These are implementation verification gates, not claims that the isolated probes have already answered them. User design approval remains separate.
diff --git a/specs/bounded-read-freshness/design-peer-review.md b/specs/bounded-read-freshness/design-peer-review.mdnew file mode 100644index 0000000..9eee232--- /dev/null+++ b/specs/bounded-read-freshness/design-peer-review.md@@ -0,0 +1,23 @@+# T-63 final design peer synthesis++Reviewed the approved requirements and proposed design after the local design-critic gate. `PERSONAL_PROJECTS=1` selects external-model mode in the actual peer-review-validator instructions, but its named external MCP reviewers are unavailable. The parent instructed us to respect the external review retry denial and use the documented fallback, so this design used two independent internal subagents with distinct correctness/feasibility and architecture/integration lenses. No new external review transmission occurred. This is internal peer validation, not cross-model validation or user approval.++## Findings and dispositions++Both peers validated the critic's three original concerns: whole-batch timeout selection must be independent of candidate serialization; unfinished aggregation must retain physical admission; successful response IDs and retained publication must commit together; and complete portfolio captures must reject missing canonical task/comment evidence. The revised mechanisms address those concerns.++Both independently identified a further intra-batch lost-update risk: two prepared whole-index versions for the same store could pass validation and then overwrite each other. Adopted correction: coalesce all selected creates/appends per store into one aggregate immutable candidate and combined reservation outside the gate; atomically transfer child reservations without a gap or double count; validate every aggregate before any commit; swap each store once. T2382's design already required an aggregate candidate and now the shared interface makes it explicit.++Architecture review confirmed `MCPRetainedViewSource` is compatible with immutable capture lookup while T2382 owns frozen scope/index/lifetime. Clarified completeness means the entire resolved portfolio/project scope plus required identity/comment closure, and forbids expanding a retained scope. Correctness review directly inspected merged `201205bd4e786c7f152d8f99006b37da7da888c7`: authoritative UUID-based comment coverage in `MCPRecordSnapshot.task` must remain unchanged even when portfolio attribution uses physical relationships. Admission/cutoff now explicitly precedes fallback preparation.++## Consensus and judgment++All three reviewers find no remaining design blocker. They agree that the isolated probes establish only timer independence, retained physical accounting, and one local history-fence case. Real HTTP/router availability, large payloads, live CloudKit history/import applicability, shared publication races, and empty-versus-purged history remain early implementation verification gates.++No substantive disagreement remains. A stronger complete-portfolio type could remove optional evidence fields internally; both peers consider validated construction/consumption adequate for design approval. A separate retention actor would simplify ownership but could schedule behind timeout delivery; short common-lock commits over prepared immutable candidates better fit the approved contract.++## Approval and next gate++The reviewed design proposes the `me.nore.ig.transit/read` metadata namespace, 4,850 ms internal cutoff plus 150 ms response headroom, supported saved-state history fencing with `incoherent_capture` fallback, explicit unknown freshness when import evidence is unavailable, and shared prepared publication machinery. T2382 separately proposes eight reusable views/16 MiB encoded retention alongside the ordinary eight/16 MiB store; their combined logical encoded ceiling is not a heap bound.++Does the design look good? User approval must be surfaced in the parent conversation. Do not create tasks or production implementation before that approval. After approval, the actual tasks skill has its own review and user approval gate; only then can production implementation begin. Align the dedicated branch to the merged foundation while preserving all other work. Coordinate heavy Xcode27/simulator gates through the parent.
diff --git a/specs/bounded-read-freshness/design.md b/specs/bounded-read-freshness/design.mdnew file mode 100644index 0000000..9da10da--- /dev/null+++ b/specs/bounded-read-freshness/design.md@@ -0,0 +1,179 @@+# Bounded read freshness — design++Review status: approved unchanged by the user in the parent conversation (Sentinel_541ceb19e7c8819193d04d23c5263041), including final scope/publication amendments at 5639c40. Tasks and implementation are also approved (Sentinel_c2e9343628948191b921868234aaf409).++## Architecture++Place deadline/admission coordination between decoded Hummingbird requests and MainActor read dispatch. Store access remains MainActor isolated; encoded bytes, immutable captures, freshness evidence, and retention are safe to handle outside it. A caller timeout ends response delivery, not the physical operation's admission lifetime.++### Deadline and publication++`MCPReadCoordinator` is process-lifetime, nonisolated, Sendable, lock-protected state. It reserves at most eight physical workers in decoded element order before hopping to MainActor. A JSON-RPC batch has one admission instant; an identifier batch inside `query_tasks` consumes one worker. Read notifications consume physical capacity but emit no response. Invalid protocol elements retain existing validation behavior; a classified covered read gets the deadline even if its tool arguments are invalid.++Record the absolute admission instant and cutoff before fallback preparation; preparation is inside the budget and never resets the clock. At admission, pre-encode the request-specific timeout/busy tool result without store access. Start a strict DispatchSourceTimer on a userInitiated concurrent queue with zero leeway at admission +4,850 ms, reserving the remaining 150 ms of the 5,000 ms contract for compact response completion. Use explicit `@concurrent` async transport helpers; the timer completes the continuation directly. Do not create a task inheriting MainActor from the timer or use a task group whose exit waits for the canceled physical worker.++Run the physical worker as an unstructured task with one admitted operation ID. It checks the terminal/generation token before starting store work and between bounded stages. The route awaits the single-winner response gate, not the worker. The worker's finalizer alone releases its physical permit. Timeout, canceled clients, stopped service, and restarted service never reset unfinished counts. Service generations close admission and invalidate unpublished work; the same coordinator survives stop/start within the process.++Success requires final JSON-RPC bytes ready before the internal cutoff. Prepare cursor/snapshot publications privately, including capacity reservations, before offering success. A short synchronized commit chooses success and transfers prepared immutable retention entries together; if timeout or generation change wins, cancel reservations and discard the staged data. The synchronized commit performs no fetch, filesystem operation, encoding, await, or MainActor hop. Existing retained task-query limits remain eight snapshots, 16 MiB, and 300 seconds; temporary worker captures remain subject to physical admission and deadline, not a promised total-byte bound.++For read-only JSON-RPC batches, pre-encode a complete valid fallback array at decoded admission, preserving known invalid/busy entries and giving each admitted read its timeout result; omit notifications. Keep that Data ready in an independent batch terminal gate before dispatch. Assemble candidate success bytes privately outside MainActor. The strict timer can select the already complete fallback without waiting for/canceling an in-progress large array copy. Only a complete candidate selected before cutoff can atomically commit its prepared publications. If final assembly misses cutoff, no candidate success/retention is exposed. All-notification batches retain HTTP 202.++An admitted element permit stays held until its physical capture/transformation/encoding finishes. Batch assembly additionally retains one participating element's permit until assembly physically finishes; its capture/encoding must have finished before assembly starts, so the same permit never covers concurrent workers. Other completed element permits can release. At cutoff, lingering assembly remains counted even though the fallback was returned. Batches with no admitted elements return their prebuilt invalid/busy bytes without launching assembly. Timer/short terminal commits do not launch uncounted long work.++Mixed batches preserve write order and behavior; covered reads keep the common admission deadline and pre-encoded per-read errors, while combined delivery may await writes. When a preceding write occupies MainActor beyond the read cutoff, select its following read's timeout without dispatching a store fetch. Do not commit a covered result's retention unless its encoded bytes won that read's terminal gate; mixed delivery does not authorize late capture/publication.++### Coherent capture++`MCPReadCaptureBuilder.capture` runs synchronously in one nonawaiting MainActor scope. Use a new `ModelContext(container)` with autosave disabled for saved data; never transact, save, or roll back `container.mainContext`. Shared UI/MCP write services keep their contexts. A saved write is visible to the fresh capture, while uncommitted UI edits are not promoted into saved-state evidence.++Fence a persisted capture with the latest `DefaultHistoryTransaction` token/storeIdentifier, read with `HistoryDescriptor` sorted by descending transactionIdentifier and fetchLimit 1. Read the initial watermark through a fresh context, create the capture context after that watermark, copy all selected data/relationships, then read the final watermark through another fresh context. Require equal valid watermarks plus a stable import-monitor generation. Detect changed/expired/unavailable history or incomparable store scope as `incoherent_capture`; return no partial view and perform no unbounded retry. An empty persisted store uses an explicit empty-history sentinel, validated again after capture. The container has one configured domain store; foreign store history is rejected. In-memory CloudKit-free fixtures use a nonawaiting actor-only fence with no external writers, explicitly injected in tests.++Resolve project selectors inside the fenced capture and freeze their physical project identity; do not resolve a selector against a separate pre-capture store view. Copy relationship physical identifiers while models are live on MainActor. Every selected property and revision is frozen before leaving that scope. No live `@Model`, `ModelContext`, `[String: Any]`, or unchecked model wrapper crosses the actor boundary. Filtering, aggregation, projection, and output serialization operate on DTOs. History/import evidence is internal and does not replace the opaque public snapshot ID.++### Freshness++`MCPImportEvidenceMonitor` subscribes to `NSPersistentCloudKitContainer.eventChangedNotification` before the server admits reads. Its callback copies type, event identifier, store identifier, start/end dates, success and failure category into Sendable values; process them on a non-MainActor serialized queue. Ignore setup/export events and unrelated stores; every relevant transition advances a generation fence. Retain the last relevant completed successful import separately from in-flight/failed outcomes.++Associate the running SwiftData store with import events only when its public history storeIdentifier and the event's storeIdentifier can be positively matched. Fresh-context capture, equal history fencing, and import generation fencing must establish that the completed import is applicable to the chosen view. If matching or visible-history evidence is unavailable, emit `unknown`, nullable lastImportedAt, and evidence `none`; never infer a match from arrival time, bundle name, heartbeat, or a local save. The monitor records unsuccessful events without replacing the last successful import. Active mode comes from launch-fixed `SyncManager.isCloudSyncActive`.++Use no synthetic writes, app focusing, App Nap setting changes, private context access, or guessed force-pull API. The refresh trigger adapter is explicitly unavailable for the current SwiftData API. `refresh_if_needed` skips waiting for a positively applicable recent import; otherwise observes an already relevant in-flight import for at most two seconds within the remaining budget. With neither trigger nor relevant in-flight import, return local capture with `unavailable` immediately. Apply requirement 3.6's success/failure/timeout precedence. Inactive sync always skips waiting with `not_requested`/`not_applicable`/null import time. Capture-time evidence stays immutable even when newer events occur.++## Components and shared interfaces++New common code belongs in `Transit/Transit/MCP/Reads/`, macOS gated. All boundary data types are explicitly `nonisolated`, Codable as required, and Sendable; control state uses bounded locks and strict timer queues.++```swift+enum ReadCaptureScope: Sendable {+ case wholePortfolio+ case projects([LocalRecordKey]) // canonical unique physical-key set; closure is separate+ case selectedQuery // ordinary narrow read, not a reusable portfolio+}+enum CaptureCompleteness: Sendable {+ case selectedRead+ case completePortfolio // complete resolved portfolio/project scope and required identity/comment closure+}+struct CapturedReadView: Sendable {+ let completeness: CaptureCompleteness+ let captureScope: ReadCaptureScope+ let metadata: ReadCaptureMetadata+ let createdAt: ContinuousClock.Instant+ let retentionDeadline: ContinuousClock.Instant+ let projects: [ReadProject]+ let tasks: [ReadTask]+ let milestones: [ReadMilestone]+ let comments: [ReadCommentEvidence]+}+struct ReadTask: Sendable {+ let physicalKey: LocalRecordKey // encoded persistentModelID; opaque, local only+ let id: UUID+ let projectKey, milestoneKey: LocalRecordKey?+ let storedProjectID, storedMilestoneID: UUID?+ let rawStatus, effectiveStatus: String+ let creationDate, lastStatusChangeDate: Date+ let completionDate: Date?+ let revision: String? // authoritative stored-content r1 when full capture is selected+ let fullRecordWithoutCommentsJSON: Data?+ let requestedCommentRecordsJSON: Data?+}+protocol MCPRetainedViewSource: Sendable {+ func view(for snapshotID: String, now: ContinuousClock.Instant) throws -> CapturedReadView+}+struct MCPPublicationStoreID: Hashable, Sendable { let rawValue: UUID }+protocol MCPReadPublicationParticipant: Sendable {+ var publicationStoreID: MCPPublicationStoreID { get }+ func prepareAggregate(_ publications: [any MCPPreparedPublication],+ in domain: MCPReadPublicationDomain) throws -> any MCPPreparedPublication+}+protocol MCPPreparedPublication: Sendable {+ var publicationStoreID: MCPPublicationStoreID { get }+ // Prepared/private capacity already reserved; all validation precedes every commit.+ func validateLocked(in domain: MCPReadPublicationDomain) -> PublicationRejection?+ func commitLocked(in domain: MCPReadPublicationDomain)+ func discardLocked(in domain: MCPReadPublicationDomain)+}+struct PreparedReadResult: Sendable {+ let encodedResponse: Data+ let publications: [any MCPPreparedPublication]+ let publicationErrors: PreencodedPublicationErrors // busy/expiry/capacity failure bytes+}+```++`MCPReadPublicationDomain` is one common nonisolated lock domain owned by T-63 and injected into ordinary cursor and T2382 retention stores. It owns terminal/generation state and store capacity/visibility transitions; store prepare/lookup locks never nest inside a domain commit. `prepare` reserves immutable private entries and returns an idempotent prepared-publication object; its capacity counts pending reservations as well as visible entries. `finishSuccess(operationID,generation,encodedBytes,publications)` acquires the domain once, validates time/open terminal/generation and every selected publication before committing any, inserts prepared references with nonthrowing commitLocked, and selects bytes. Prepare PreencodedPublicationErrors for busy/expiry/capacity failures outside the gate. If any publication validation fails, discard all selected reservations and select matching pre-encoded error bytes (or the read-only batch fallback), never the staged success containing an unpublished ID. No child success publishes before the complete read-only batch array is selected. The batch version selects one complete encoded array and its whole publication set. Timeout/stop/disconnect discard each prepared reservation once under the same domain. No separately locked portfolio-store commit can run after response selection. Before offering read-only batch success, coalesce every selected create/append for the same store into one aggregate immutable candidate/index version outside the gate, including the combined capacity reservation, transferred atomically from child reservations with neither double-counting nor an unreserved gap; two independently prepared whole-index swaps for one store are forbidden. Shared preparation detects duplicate operation/token ownership and excludes overwritten or unselected candidates. Validate all aggregate store candidates before any commit, then swap each store index once. Create and append reservations both count pending plus published capacity. Append prepares a complete immutable index version privately; stale-version compare-and-swap fails with READ_BUSY before terminal selection, avoiding concurrent overwrite. Ordinary cursor tokens remain UUIDv4 and reusable portfolio cursors use UUIDv8 routing even after expiry; token allocation and collision checks are atomic within the publication domain. Lookup/expiry sees only committed entries through the domain. Destruction of large discarded values occurs after unlocking. The physical worker finalizer releases permits independently of publication discard.++`LocalRecordKey` is canonical encoded `PersistentIdentifier` data, stable within one local store/capture lifecycle, independent of potentially duplicated domain UUIDs. Project/milestone DTOs carry physical key, UUID, name, raw/effective status where relevant, creation/status/completion timestamps, actual relationship physical keys, and their frozen selected wire record bytes. Comment evidence carries physical key, UUID, actual task physical key, stored task UUID, and creation timestamp. T2382 derives identity attribution from physical relationships and leaves unresolved UUID references explicit. CapturedReadView explicitly carries typed ReadCaptureScope: wholePortfolio, projects with resolved physical project keys, or selectedQuery for ordinary narrow reads. CompletePortfolio means complete declared scope plus required identity closure; it never labels a scoped capture as wholePortfolio. Closure records outside declared project keys support attribution only and cannot enlarge selected totals. T2382 retains the same typed scope in its wrapper and rejects reusable queries outside it with SNAPSHOT_INCOMPATIBLE, prohibiting later scope expansion; completeness covers every selected task and required identity/relationship/comment closure for that scope. Its aggregator/retention entry point accepts only completePortfolio captures after validating each task's required canonical revision/full record and complete comment evidence; an inadequate capture is incoherent_capture before counting or publishing, never an empty/partial success. Revision/fullRecordWithoutCommentsJSON and complete commentKeys/evidence are mandatory for completePortfolio. requestedCommentRecordsJSON represents output bodies and can be nil when includeComments is false; omission never weakens canonical revision or complete comment evidence.++The full task capture invokes T2380's authoritative `MCPRecordSnapshot.task` on all comment-covered content before comment fields are removed from output. Preserve that r1 verbatim through summary projection and snapshot queries; effective status normalization never remints revision. Summary-only ordinary task reads preserve T2380's no-comment-fetch path when comments are not requested. Portfolio capture requests the richer full/revision evidence because its reusable task view depends on it. Required comment capture failures are storage failures, never partial totals. T2382 owns its summary aggregation, projection, completion windows, reusable lifetime/capacity policy, and frozen query API; it consumes `CapturedReadView` and the same terminal publication gate.++### Wire metadata++Add optional `_meta` to `MCPToolResult`, using the key `me.nore.ig.transit/read`. Existing `content[0].text` values keep their current array/envelope shape. MCP 2025-03-26's base Result explicitly allows extension metadata; no protocol-version change is needed.++```json+{+ "_meta": {+ "me.nore.ig.transit/read": {+ "asOf": "2026-10-03T15:00:00.000Z",+ "snapshotId": "opaque-view-id",+ "freshness": {+ "syncState": "active", "assessment": "unknown",+ "assessedAt": "2026-10-03T15:00:00.000Z",+ "lastImportedAt": null, "evidence": "none",+ "recentImportThresholdMs": 30000+ },+ "read": {"policy": "refresh_if_needed", "refreshOutcome": "unavailable", "budgetMs": 5000}+ }+ }+}+```++Dates use UTC ISO 8601 milliseconds. Recency/deadlines use monotonic elapsed time to avoid wall-clock adjustment falsely improving freshness; inconsistent event clocks yield unknown. `assessedAt` equals asOf. Cursor pages retain the original complete metadata bytes and data; continuation request diagnostics use a separate request correlation ID in server logs. Snapshot expiry is a retention deadline, not the response deadline. Reused T2382 views retain exactly the same identity/evidence. Failure before a complete capture omits asOf/snapshotId and reports request/error metadata only.++## Integration and parity audit++| Existing/new site | Owner | Needs equivalent | Integration |+| --- | --- | --- | --- |+| MCPServer.makeRouter POST single route | T-63 | yes | Classify covered read before MainActor; coordinator returns encoded response bytes. Writes retain handler dispatch. |+| MCPServer.batchResponse | T-63 | yes | Common admission instant, physical element slots, read-only batch commit gate, mixed write order preserved. |+| MCPServer start/stop/tearDown | T-63 | yes | Close generation admission, invalidate unpublished work, keep process-lifetime unfinished accounting. |+| MCPToolHandler init/handleToolCall/readOnlyToolNames | T-63 | yes | Inject capture/evidence/retained sources; recognize new portfolio read; maintain fallback write protection. |+| query_tasks ordinary selectors and cursor | T-63 | yes | DTO projection, original validation precedence, frozen metadata retention; preserve T2380 revision/comment behavior. |+| query_milestones and get_projects | T-63 | yes | Selected DTO capture, outer metadata, existing filters/order/data shape. |+| scan_duplicate_display_ids/maintenance mutations | T-63 | no | Outside approved freshness scope; existing maintenance behavior remains. |+| MCPToolDefinitions common wiring/existing schemas | T-63 | yes | Optional readPolicy enum, cursor policy rules, include T2382 descriptor provider. |+| MCPTypes/MCPToolResult | T-63 | yes | Typed optional _meta and common DTO/error value types. |+| TransitApp service construction | T-63 | yes | One process-lifetime read coordinator and launch-fixed mode monitor; container supplied only to capture builder. |+| MCPToolHandler+PortfolioSummary/+SnapshotTaskQuery | T2382 | yes | New separate modules consume shared DTO/source; query_tasks snapshotId dispatch wired by T-63. |+| MCPPortfolioToolDefinitions/snapshot store | T2382 | yes | Supplies descriptor and retained source/transaction hooks; no concurrent edits to shared files. |+| Write coordinator/receipt/revision implementation | T2380 | no | Depend on current authoritative snapshot routine; no duplicate write safeguards or receipt schema deployment. |+| App Intent reads/UI services | — | no | Outside covered MCP transport contract. |++T2382 submits interfaces/helper files before shared-file wiring. PR249 merged as 201205bd4e786c7f152d8f99006b37da7da888c7; its tree equals inspected head b618acf9e3d66a4a1ce493eea94091c058721731. Parent coordinates foundation alignment before implementation; do not alter the T2380 working branch. T2382 proposes a separate eight-view/16 MiB encoded retention budget alongside ordinary eight/16 MiB retention, subject to this design approval. The 32 MiB combined logical encoded ceiling is not a bound on heap use or temporary admitted captures. The new MCPWriteReceipt production schema remains an owner release prerequisite.++## Errors and diagnostics++Keep protocol validation/unknown-method errors unchanged. Covered execution failures use tool results with isError true. Task-query errors retain their existing codes; additional category is metadata. For project/milestone execution errors use READ_FAILED with category `storage_failure`, `serialization_failure`, or `incoherent_capture`. `READ_TIMEOUT` and `READ_BUSY` have no successful capture metadata. Cursor/input/capacity errors retain existing precedence. Timeout wins once selected; late failures are diagnostics only.++Log request correlation, tool, generation, monotonic admission/deadline, outcome, and measured queue/refresh/capture/transform/serialize/batch durations. The worker finalizer logs correlated late completion/discard and retained physical count. Timer response uses precomputed small bytes and a bounded diagnostic enqueue; logging cannot perform synchronous filesystem work on the timer or keep a response gate locked. Document backoff after busy/timeout, cursor replay until expiry, and mixed-batch delivery limitations.++## Risks and assumptions++- Risk: SwiftData/CloudKit may not expose matching store identifiers or import-visible history in unfocused signed execution | Verify: early live import/history correlation probe on the configured store | If wrong: unknown freshness/null import time and unavailable refresh; never assert recency.+- Risk: persistent history may not fully fence a concurrent CloudKit commit or may be unavailable/purged for a supported store | Verify: early saved local/cross-context/live-import and empty-versus-purged history probes | If wrong: incoherent_capture failure for that store; bring any alternative capture mechanism back for design approval before depending on it.+- Risk: end-to-end scheduling/encoding at production volume exceeds internal headroom | Verify: transport load and blocked-MainActor/batch probes before implementation completion | If wrong: return pre-encoded timeout earlier within the approved budget; retain physical accounting and defer success.++## Testing strategy and traceability++The isolated Xcode27/Swift6.4 prototypes under this spec establish timer independence, retained physical permits, late-publication suppression, and basic fresh-context/history fencing. They are not production integration tests. Use Swift Testing and the repository's owning TestModelContainer fixtures for app tests; serialize SwiftData suites. Coordinate simulator/full build gates with the parent.++| Requirements | Design/test evidence |+| --- | --- |+| 1.1–1.6 | Strict coordinator one-shot race, physical cap/stop-restart, pre-encoded errors, shared batch admission/aggregation; test blocked MainActor, slow encoding, canceled request, eight lingering/ninth busy, invalid/both notification modes, and late completion. |+| 2.1–2.6 | DTO capture/history/import fences, physical relationship attribution, `_meta`; test saved multi-entity changes, empty/scoped views, unknown/unrelated/failed events, wrong store, date inconsistency, and asOf/assessedAt equality. |+| 3.1–3.6 | Optional readPolicy parser + evidence observation; test cached/default/inactive, recent import, in-flight success/failure/timeout, no trigger, zero wait, and input precedence. |+| 4.1–4.4 | Error categories/unchanged writes; test fetch/comment/history/serialization failures, legitimate empty result, existing identifier outcomes, and T2380 input/output/revision parity. |+| 5.1–5.4 | Encoded retention + shared view identity; test import/edit between pages, byte-identical metadata replay, cursor policies/expiry, and T2382 same-view query projection without r1 reminting. |+| 6.1–6.3 | Caller guide and diagnostic correlation; validate phase durations/late discard, mixed delivery documentation, backoff examples, and no timer-path logging delay. |++Use seeded generated event sequences in Swift Testing for terminal race/permit invariants and cursor replay: one response per ID, no publication after terminal timeout, unfinished count never above eight or below zero, and immutable metadata across randomized import/local-edit sequences. No external property-testing dependency is required.++Research informing the design: [MCP Result metadata schema](https://raw.githubusercontent.com/modelcontextprotocol/specification/main/schema/2025-03-26/schema.ts), [Apple ModelContext](https://developer.apple.com/documentation/swiftdata/modelcontext), [Apple history fetching](https://developer.apple.com/documentation/swiftdata/fetching-and-filtering-time-based-model-changes), [Apple CloudKit events](https://developer.apple.com/documentation/coredata/nspersistentcloudkitcontainer/event), and [Swift SE-0461 executor isolation](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0461-async-function-isolation.md). Installed Xcode27 SDK interfaces confirm history sorting/fetchLimit and event properties for the target platform.
diff --git a/specs/bounded-read-freshness/explanation.md b/specs/bounded-read-freshness/explanation.mdnew file mode 100644index 0000000..4961e29--- /dev/null+++ b/specs/bounded-read-freshness/explanation.md@@ -0,0 +1,41 @@+# Design explanation and self-validation++## Beginner level++### What this does++A read has two lifetimes: how long the caller waits and how long the computer keeps doing the underlying work. The caller gets a result or timeout within five seconds; a slow read continues to occupy one of eight places until it actually stops. This prevents repeated retries from filling an unlimited queue.++### Why it matters++A timeout means the server could not finish the selected read in time. It does not mean there are no tasks, the work was canceled, or the endpoint caught up with every other device. The answer carries the time its local data was captured and only the import evidence the server can support.++### Key concepts++A captured view is an immutable copy of the selected local data. A history fence checks whether a saved change happened while that copy was being made. A freshness caveat tells the caller when remote import evidence is missing; it is separate from whether local data could be read.++## Intermediate level++### Implementation approach++The transport coordinator reserves capacity before queueing MainActor work. A strict timer and one-shot gate live outside MainActor; the physical worker and deadline race over prepared encoded bytes. Store and model access stays in a synchronous MainActor capture; projection uses typed Sendable values afterwards. Publication and the chosen result share the terminal gate so an old worker cannot expose a snapshot after timeout.++### Trade-offs++A fresh autosave-disabled context reads saved state and avoids cached model values or accidentally saving UI edits. Persistent-history token/storeID fences detect a save crossing selected fetches. The user explicitly requires saved data only, so unsaved UI state is excluded. A failed/unsupported fence produces a visible read failure; unsupported import proof produces unknown freshness and valid local data when a coherent capture is available.++## Expert level++### Architecture implications++Physical admission is process-scoped; server generation is a publication/admission epoch, not a reset of active permits. Success bytes and retention capacity are prepared outside the commit lock. For read-only batches the final combined bytes and their publication set commit together; per-element successes cannot publish before selection into the final batch. Mixed batches retain write ordering and the approved delivery exception.++### Edge cases++Default Dispatch asyncAfter timer coalescing exceeded the five-second limit in the isolated experiment; strict timers still need internal response headroom. @concurrent entry and direct continuation completion keep result delivery off MainActor. A saved-store history fence must also cover CloudKit/background changes, while import storeID equality and context visibility need live verification. Same-view T2382 queries preserve canonical r1 from stored/comment-covered content, even when the public status projection is normalized.++## Validation findings++The beginner pass exposed the need to distinguish incomplete physical work from a completed timeout response and the saved-versus-unsaved context choice. Both are explicit in the design. The expert pass exposed batch publication, stop/restart permit accounting, timer coalescing, and import/history applicability; the design records the first three as invariants and the last as an early verification risk with fail-closed/unknown outcomes. No mechanism claims global remote convergence or cancellation of a synchronous fetch.++Outstanding user technical choices are the proposed metadata namespace, internal timer/encoding reserve, fail-closed history fence, and shared separate portfolio retention budget. Saved-only data is explicitly approved. Final design approval must include the design choices; production feasibility remains subject to the named integration checks.
diff --git a/specs/bounded-read-freshness/foundation-handoff.md b/specs/bounded-read-freshness/foundation-handoff.mdnew file mode 100644index 0000000..8e981dd--- /dev/null+++ b/specs/bounded-read-freshness/foundation-handoff.md@@ -0,0 +1,162 @@+# T-63 fixture foundation handoff++Tasks 2/3/6/7/8/9 are verified. The publication registry and ordinary retention are implemented and locally tested. T2382 may consume this shared API after parent review; actual cross-ticket routing acceptance remains tasks 13/16.++## Verified evidence++`make test-quick TEST_TARGETS='TransitTests/MCPReadCaptureBuilderTests TransitTests/MCPReadCoordinatorTests'` passed 17 tests: nine capture and eight coordinator cases. `make lint` passed with zero violations. RED checkpoints reproduced missing capture/coordinator/batch seams and duplicate-UUID attribution before their corrections.++The preserved result is `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/foundation/expanded.xcresult`; build/test, lint, RED logs and extracted timing lines are in that same directory. These files live outside Git and survive stream-worktree cleanup.++| Measurement | Observed |+| --- | --- |+| Hummingbird router and encoded body while MainActor blocks six seconds | 4.850738667 seconds |+| Large batch, admission through encoded selection (fallback preparation included) | 4.850275917 seconds |+| Large batch, router through encoded body | 4.857904584 seconds |+| Large request / response | 964,637 / 962,693 bytes |+| Large batch results | 8 timeout, 24 busy, 48 fixed invalid, 16 omitted notifications |++The batch harness obeys the actual Hummingbird 1 MiB body collection ceiling. It uses fixture response records, not final MCP protocol dispatch. It measures encoded transport availability, not network delivery. Scheduling evidence is empirical. Production MCPServer/handler wiring and mixed-write acceptance remain later tasks.++Capture fixtures prove saved-only fresh contexts, authoritative comment-covered r1 while output comment bodies are omitted, physical relationship identity despite duplicate UUIDs, multi-entity save rejection, empty versus purged history, import-generation invalidation, foreign milestone/orphan identity closure with unchanged declared scope, and required comment-fetch failure without empty success.++Deadline fixtures prove eight lingering physical permits/ninth busy across restart, whole-array fallback despite blocked final assembly with one retained permit, expired undispatched cleanup, 120 seeded terminal races, and forced stop/start or cutoff between admission and full-fallback readiness.++## Capture interfaces and live limitations++`MCPReadCaptureBuilder` takes the owning ModelContainer, explicit fence mode, synchronous generation closure, metadata closure `(Date, MCPReadCaptureBoundary) -> ReadCaptureMetadata`, and test injection seams. `MCPReadCaptureBoundary` contains `historyStoreIdentifier`, `generation`, and `stablePersistentHistory`. It is local fence evidence only; it cannot prove a particular CloudKit event became visible.++The metadata callback is the read-only observation hook for a signed app that owns the configured container: capture emits the boundary without saving, rolling back, publishing retention, triggering refresh, or making synthetic writes. No invocation against the signed production store was available in this execution. All disk fixtures disable CloudKit. Therefore no positive live import/history correlation is claimed. The approved production fallback is nil import applicability proof, unknown/null freshness, and unavailable refresh. Unavailable, purged, changed or incomparable local history fails closed as incoherent_capture.++Full portfolio DTOs retain complete identity closure, including foreign milestones and orphan comments; `captureScope.projects` alone controls selected totals/query scope. Canonical r1 covers comments by authoritative UUID semantics; task `commentKeys` use actual physical task ownership. Requested comment-body JSON remains optional.++## Coordinator assumptions for task 9++Coordinator, timer, admission/generation and publication terminal selection share `MCPReadPublicationDomain.withLock`. A prepared success validates every candidate before any commit and chooses response bytes atomically with swaps. Same-store children must already be coalesced; duplicate store candidates select preencoded busy errors. Physical entry removal happens only in worker finalizers.++Batch admission reserves at most eight compact entries from one generation atomically. Bulk fixed/fallback construction stays outside the domain. The assembly entry remains pending until its complete fallback is ready; stop marks it invalidated without selecting individual bytes. Original admittedAt never resets. Workers dispatch only after readiness. One completed-capture permit remains held through final assembly. No child result publishes before the selected full array.++Task 9 must extend the common lock domain without a second store lock. Displaced/discarded large indices and reservations must remain alive through unlock, including commitLocked/discardLocked paths.++## Agreed publication contract to implement++The following field/signature shape is coordinated with parent/T2382 and implemented locally, with acceptance evidence below.++- Immutable `MCPPublicationRoot`: id:String, deadline:ContinuousClock.Instant, encodedByteCount:Int, tokens:Set<String>.+- Precomputed validated `MCPPublicationIndexDescriptor`: roots:[String:MCPPublicationRoot], entryCount:Int, encodedByteCount:Int, tokens:Set<String>.+- `MCPPublicationIndex`: descriptor:MCPPublicationIndexDescriptor.+- `MCPPublicationStoreSnapshot`: version:UInt64, tokenVersion:UInt64, index:any MCPPublicationIndex, allocatedTokenSets:[Set<String>].+- Domain register(storeID,index,maxEntries,maxBytes), snapshot(for:), reserve(storeID,operationID,expectedVersion,expectedTokenVersion,index,chargeEntries,chargeBytes,newTokens,deadline), transfer(children,aggregateIndex,operationID), and retire(storeID,expectedVersion,replacementIndex).++Descriptors, counts, token unions/collision indices and net-delta validation are built outside the domain. The short gate rechecks pinned store/token versions, at most eight root expiries, scalar capacity and ownership, then swaps prepared references. Charges must be exact nonnegative net additions; published plus pending remains bounded. Never mutate/copy a large global token Set under the gate: use version-pinned immutable token-set/index references. Register once per store; no live eviction.++Existing root expiry never extends: append keeps exactly the original deadline. Transfer accepts only live same-store/same-base children with unique operation ownership, moves their exact summed charges once without gap/double count, and changes nothing on failure. It pins a fresh aggregate tokenVersion; each child's original tokenVersion need not remain current because sibling reservations advance it. Test sibling aggregation with intervening allocations and unrelated-store token races. Final validation rechecks store/base version, root existence and expiry. CAS conflicts choose preencoded READ_BUSY, never overwrite another index.++Ordinary retention keeps eight snapshots, 16 MiB encoded bytes, 300 seconds and frozen metadata. Ordinary cursor UUIDv4 versus reusable UUIDv8 routing remains recognizable after expiry, with atomic allocation/collision checks. Preserve existing selector/input/cursor error precedence. T2382 owns its separate retained store; do not implement it here. Tests must cover creates/appends/create+append coalescing, charged ownership transfer and exactly-once rollback, stale CAS, collisions, expiry, all-candidate validation and no success referencing unpublished IDs.++## Task 9 verified API and evidence++The implemented registry lives in `MCPReadPublicationDomain`, its preparation extension, and `MCPPublicationIndex.swift`. Register one immutable index per store. Capture `snapshot(for:)`, build descriptor/token unions and exact nonnegative net additions outside the lock, and call `reserve` with both captured `expectedVersion` and global `expectedTokenVersion`. `PublicationRejection` is an Error (`busy`, `expired`, `capacity`). `accounting(for:)` exposes numerical visible/pending entry and encoded-byte totals for acceptance fixtures.++`transfer([MCPPublicationReservation], aggregateIndex:operationID:)` pins a fresh global token version. It accepts only same-store/same-base uniquely owned live children, validates the aggregate's per-root bytes/tokens and exact original deadlines, transfers summed charges without a gap, and leaves children with no cleanup ownership. Releasing transferred children is idempotent. Commit advances the store index version once; stale candidates cannot overwrite the index. Explicit lifecycle retirement is separate from expiry purge; preparation never evicts live roots.++All descriptor getters, set unions, descriptor/root validation and index copies run outside the lock. Final gates read cached scalar/descriptor values and at most eight root deadlines. Production time comes directly from ContinuousClock; deterministic tests use a scalar `testingInstant` seam. `withLockRetainingRetirement` lets the coordinator resume selected response bytes before draining large displaced/discarded values outside the gate. The physical permit remains owned through this cleanup.++Ordinary `MCPTaskQuerySnapshotStore` implements the participant protocol and shares the injected domain. `prepare(pages:cursors:deadline:operationID:metadataBytes:policy:)` returns an optional private reservation (one page needs no retention). `prepareAggregate` combines ordinary creates; `retainedPage(for:)` returns immutable text/metadata bytes/policy, while the existing `page(for:)` compatibility wrapper returns text. Default retention is eight roots, 16 MiB encoded bytes and the caller's original 300-second capture deadline. Metadata bytes count in the logical encoded-byte charge. `MCPCursorFamily.classify` recognizes ordinary UUIDv4 and reusable UUIDv8 without consulting retained entries, including after expiry. No T2382 retention/helper module was required or edited.++Actual macOS app verification: `make test-quick TEST_TARGETS='TransitTests/MCPReadPublicationDomainTests TransitTests/MCPTaskQuerySnapshotStoreTests TransitTests/MCPReadCaptureBuilderTests TransitTests/MCPReadCoordinatorTests'` passed 34 cases (11 publication, five ordinary retention, ten capture, eight coordinator). These include two-create selected wholebatch/no early publication, two-appends/create+append, fresh sibling token pinning and unrelated-store allocation conflicts, exact capacity/rollback counters, stale CAS, root shortening/extension rejection, expiry, reentrant descriptor getters, 16 MiB blocked destruction during commit/discard/retirement, response selection before cleanup, 24 real-reservation terminal races, and validate-all before any multi-store commit. The parent-requested canonical serialization-category repair has a RED runtime failure and GREEN test; required comment fetch remains storageFailure and history fencing remains incoherentCapture.++Evidence is preserved outside Git under `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/publication/`: `red.log`, `capture-red.log`, `verified-green.log`, `lint.log` and `verified.xcresult`. No upstream push, merge or deployment occurred. Tasks 10–16 and real cross-ticket integration are outstanding; this foundation does not claim final handler/server wiring or live CloudKit applicability proof.++## Scoped provider correction and capture cost follow-up++A compiled runtime RED (`MCPReadCaptureScopeTests.scopedCaptureKeepsCanonicalSelectedBodiesAndMinimalForeignIdentity`) reproduced copying unrelated task descriptions, metadata and canonical full records into a scoped portfolio. The provider now keeps full authoritative r1 records only for tasks in the declared physical project scope. Unrelated task endpoints remain identity closure with no description, metadata or canonical/output body. Canonical comments remain grouped by domain UUID, including duplicate-UUID owners outside scope; physical ownership keys remain independent. Required scoped orphan diagnostic evidence and cross-project milestone endpoints are preserved.++Capture-local physical-key caching and preindexed UUID/physical comment ownership replace per-task whole-comment scans and repeated physical-identifier encoding. The authoritative MCPRecordSnapshot r1 routine remains unchanged, including its comment ordering and hashing. History/import fencing and reentrancy rejection remain in place.++The first GREEN run passed the new scope/volume cases but failed the existing scoped orphan-evidence case after over-filtering orphan comments. That filtering was corrected. The subsequent actual macOS app run passed all 12 provider/capture cases; final lint passed. Evidence is retained outside Git at `../t63-review-evidence/provider/`, including RED, first GREEN and clean GREEN xcresults/logs and extracted timing output.++The volume fixture contains 2,375 tasks and 2,376 comments. Timing separates setup, physical saved capture and JSONEncoder encoding of `[Data?]` full-record bytes. This adapter is not T2382's full frozen-evidence envelope; these totals must not be directly compared with its earlier 83.393-second capture-plus-envelope measurement. This is provider evidence, not final production routing/deadline acceptance.++Clean GREEN measured setup 2.584662958 seconds, physical capture 3.287930667 seconds, and frozen record-byte encoding 0.007581875 seconds for 1,332,730 encoded bytes. The physical worker completed synchronously before the test finished. No positive CloudKit applicability/visibility evidence was invented by this optimization.+++## Tasks 10–11 prepared saved-read handoff++`MCPToolHandler.prepareCoveredRead(MCPReadToolRequest, operation: MCPReadOperation)` is the async prepared-read entry. `MCPReadService.prepare(tool:arguments:operation:)` captures saved immutable DTOs, projects task single/batch/list and project/milestone values, freezes additive outer metadata, and returns private ordinary cursor reservations. Task 13 must route admitted production reads here and provide the final fully encoded transport result to the common terminal/publication gate. The old direct dispatch remains the explicit pre-integration baseline; this component checkpoint does not claim production deadline/routing acceptance.++`MCPPreparedToolRead` contains logical result convenience, authoritative `encodedToolResult` (no RPC ID), original `frozenMetadataBytes`, and private `publications`. Its encoding embeds the complete original metadata JSON bytes verbatim. Later modern transport must consume the frozen fragment rather than decode/reencode the convenience value. `attaching` does not throw after allocating reservations. Ordinary retained pages preserve original metadata, policy, payload and original capture deadline. Cursor replay performs no capture/import wait; omitted or matching policy succeeds, malformed policy is checked before lookup, and a typed conflict is checked after valid lookup.++`MCPReadOperation.remainingBudget()` uses the same publication-domain gate and original admission deadline, returning zero for expired/invalidated/selected operations. Refresh observation windows begin before the decision snapshot and remain open through capture, projection, metadata freezing and page preparation. Capture-time observation evidence determines final refresh outcome; production applicability/visibility proof remains nil, so active production freshness is unknown/null and refresh unavailable, while inactive reads are not_requested. Positive observation/policy behavior is covered by the separately verified import component suites; this service run establishes the supported nil-proof production fallback and frozen replay, not signed CloudKit visibility.++The capture request adds narrowly typed synchronous MainActor project/milestone validation hooks. Minimal identity DTOs preserve project resolution, scalar validation, milestone lookup and dependent task-fetch precedence inside one capture fence. `projectCatalog` captures task/milestone values without comments; ordinary milestone lists need no task fetch, while detailed milestone and task-filter paths use the milestone hook before dependent task capture. Ordinary UUID selector semantics remain unchanged despite physical closure attribution.++`MCPReadCaptureValidation.validateReusableCapture(_:)` validates complete typed scope, unique physical identities, required relationship/comment-owner closure, and full canonical records only for physically selected tasks. Minimal foreign task identity and orphan comment evidence remain allowed. `requireScope(_:projectKeys:)` accepts typed physical project keys and returns SNAPSHOT_INCOMPATIBLE outside declared scope. It does not narrow identity closure or implement T2382 public query parsing/filtering. T2382 continues to own reusable query dispatch and retention modules.++RED was an actual baseline compile failure for the intentionally absent new APIs, with zero runtime cases; the independent scoped provider regression has its separate compiled runtime RED. Source-only reset/restoration used enumerated SHA-pinned backups and preserved the corrected provider commit. The first GREEN failed compilation because a helper with a private nested parameter type needed explicit private access; that narrow repair was followed by a passing retry.++Actual command: `make test-quick TEST_TARGETS='TransitTests/MCPReadProjectionTests TransitTests/MCPReadServiceTests TransitTests/MCPReadCaptureValidationTests TransitTests/MCPReadCaptureBuilderTests TransitTests/MCPTaskQueryRequestTests'`. xcresult reports Passed, top-level passedTests/totalTestCount 28, device passedTests 32, zero failures/skips, and three parameterized tests with seven runs. The log lists 25 methods; the device count includes parameter executions. Cases cover saved summary/full canonical parity, duplicate UUID outcomes, frozen metadata/policy/cursor retry, machine capture failure categories, project/scalar/milestone precedence with injected fetch failures, valid empty inactive reads, retained identity/typed scope and missing canonical/comment evidence, plus directly affected capture/request regressions. Strict lint passed with zero violations in 425 files.++Evidence is retained outside Git at `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/projection/`: red.log, first-green-compile.log, green.log, lint.log, summary.json and green.xcresult. No further app jobs run after the exclusive slot was released. Tasks 12 onward remain pending. Modern source/presentation fragments, full final RPC encoding and cross-ticket server/lifecycle binding remain coordinated later integration work; no write coordinator, modern wire, push, merge or deployment was changed here.+++## Adjacent tasks 10–11 compatibility and selection repair++Parent review validated four compatibility/selection defects at 0ff9876. The task read capture/storage/serialization error code is now the established QUERY_FAILED; project/milestone preparation keeps READ_FAILED behavior and failure metadata categories are unchanged. A well-typed conflicting policy after valid cursor lookup returns INVALID_INPUT per requirement 5.4. Conclusively empty selected reads no longer require unrelated comments; whole and scoped completePortfolio still require the orphan/comment diagnostic domain, even with no tasks.++Additive scalar inputs `ReadTaskSelectionValue` and `ReadMilestoneSelectionValue` plus optional synchronous MainActor `selectTaskBodies`/`selectMilestoneBodies` hooks select body keys inside the saved fence before comment/canonical serialization. They carry no models, dates, metadata or canonical records across the hook. Shared pure selection uses raw status/type, effective priority and ordinary UUID/global duplicate-ID semantics. Nonselected records remain identity closure. Filtered or unrequested corrupt task/milestone canonical dates cannot poison an otherwise valid result; selected corrupt records still return serialization_failure. Ordinary task/catalog milestone identity and summary paths do not serialize unnecessary milestone canonical dates.++CompletePortfolio rejects either public narrowing hook. Scoped portfolio automatically canonicalizes milestones within its declared physical project scope; foreign milestone endpoint closure retains physical relationships, UUID/display ID/name, raw/effective status and timestamps, with exactly minimal milestoneId/name selectedRecordJSON. T2382 explicitly confirmed no diagnostic/reconciliation consumer needs full foreign milestone JSON. Whole portfolio still canonicalizes all milestones. The foreign bad-date fixture verifies preserved selected-task authoritative r1 and physical closure, generic validation acceptance, and whole-portfolio failure for the required bad canonical record.++Runtime RED compiled and ran against HEAD22abd9d baseline sources, preserving all committed fixtures. xcresult reports Failed: 13 top-level entries, seven passed/six failed; device counts 11 passed/13 failed; seven parameterized tests with 18 runs. Failure entries reproduce empty comments, policy conflict, legacy QUERY_FAILED, task canonical selection, milestone canonical selection and foreign milestone scope. No incidental compile failure was counted as behavioral RED. The five enumerated implementation source paths were restored with exact SHA verification before GREEN.++GREEN command: `make test-quick TEST_TARGETS='TransitTests/MCPReadServiceTests TransitTests/MCPReadProjectionTests TransitTests/MCPReadCaptureBuilderTests TransitTests/MCPReadCaptureScopeTests TransitTests/MCPReadCaptureValidationTests TransitTests/MCPTaskQueryRequestTests'`. It passed: 35 top-level tests, 46 device executions, zero failures/skips, seven parameterized tests with 18 runs. Strict lint passed with zero violations in 426 files. Parent-coordinated read-only source review confirmed the four findings repaired and reported no additional issue in this repair. Production routing/deadline integration remains task 13; positive live CloudKit visibility remains unclaimed.++Evidence and source-only patch are retained outside Git at `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/projection-compatibility/`: red.log/red.xcresult/red-summary.json/red-tests.json, green.log/green.xcresult/green-summary.json, lint.log, prepared-source/sha256.json, and repair-source.patch. The exclusive app slot was released after the job and capture workers completed; no app job runs after release. A separate preexisting Transit process in another checkout was observed and left untouched. No modern wire, write coordinator, push, merge or deployment was changed. Stop before task 12 remains in effect.+++## Task 12 routing RED and task 13 preparation boundary++Task 12 is in progress. `MCPBoundedReadRouteTests` exercises the actual existing MCPServer router with a correctly typed shared saved-read service, one owning saved SwiftData fixture and explicit 2026-07-28 header. These are single-request tests; no new legacy batch/notification production behavior was added. The tests require saved values, full RPC identifier/envelope, additive tool-level outer read metadata and exact retained metadata bytes inside final RPC data. Timed valid and invalid tool-domain calls both block MainActor for six seconds; the valid case has two tasks/limit one so it can detect actual late ordinary cursor publication. Both blockers are awaited even when HTTP response throws; no arbitrary cleanup sleep is used.++The first app attempt failed fixture compilation because snapshot-store inspections needed explicit MainActor hops. This is retained separately and is not behavioral RED. Only those inspections were moved onto MainActor; elapsed router/body time is recorded before any inspection hop. Application routing/source was unchanged.++Actual command: `make test-quick TEST_TARGETS='TransitTests/MCPBoundedReadRouteTests'`. The retry compiled and ran: three top-level failed methods/four failed device executions, zero passed/skipped, one parameterized method with two runs. Valid encoded response/body took 6.015106334 seconds and invalid arguments took 6.005007875 seconds, both exceeding five seconds. The valid call also left a visible ordinary retained root after the cutoff. The saved read returned Unsaved UI task, and the retained page lacked metadataBytes; tool-level read metadata was absent. This proves the current direct route still needs bounded saved preparation and final encoded publication binding; it is not routing GREEN.++Types-only `MCPPreparedReadCapture` contains immutable view plus original frozenMetadataBytes. `MCPReadCapturedPreparing.prepareCapturedRead(request:policy:operation:transform:)` returns tool-level MCPPreparedToolRead and accepts a Sendable async transform without forced MainActor, permitting pure DTO work off actor. This interface has no concrete implementation or service conformance yet. Concrete task 13 preparation must retain the observation window through transformation/encoding/private reservations and preserve the original operation deadline. Retained query replay bypasses capture, waiting and reassessment.++Parent confirmed T2382 helper signatures: handlePortfolioSummary(request:MCPPortfolioSummaryRequest, view:CapturedReadView, operation:MCPReadOperation) throws -> MCPPreparedToolRead and handleSnapshotTaskQuery(request:MCPSnapshotTaskQueryRequest, view:CapturedReadView, operation:MCPReadOperation) throws -> MCPPreparedToolRead. T63 owns outer RPC encoding using the actual JSONRPCId and full final Data before the terminal gate. PreparedReadResult is exclusively that transport-level result; a helper's tool-only fragment must not be mislabeled final RPC bytes. Exact frozen metadata and private reservation ownership survive the bridge. Actual module delivery/registration, remaining lifecycle/physical-permit/shared-helper tests and final module acceptance are still outstanding; fixture evidence must remain separate, with no circular foundation gate.++Evidence is outside Git at `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/routing/`: compile-failure.log/.xcresult, red.log/.xcresult, red-summary.json, red-tests.json and lint.log. Final strict lint passed with zero violations in 428 files. App processes and six-second blockers drained; the exclusive slot was released, and no further app job runs without a grant. MCPServer, write coordinator and modern wire implementation were not edited. Task 13 source implementation/GREEN remains paused for the precise ownership/module handoff.+# Task 12 admission/helper fixture preparation++The caller-owned `MCPReadAdmission` value carries a preallocated operation UUID and a completion callback. It does not admit work and has no production coordinator binding yet. Two new admission fixtures deliberately use an explicitly labeled test-only baseline adapter over current `execute`: duplicate requested identities must not launch or replace a live worker, and the caller receipt must observe cleanup complete and physical permit removed. This is interface-capability RED only: existing production has no such caller identity/receipt API. It is not evidence that production ignores an API it supports. Task 13 must remove the adapter and invoke the actual admission overload directly before final acceptance. No completed-receipt registry or coordinator runtime change is supplied in this checkpoint.++`MCPReadHelperContractTests` checks runtime service conformance to the declared generic preparation protocol before exercising saved DTO identity, exact capsule metadata, original operation identity/budget and an observation window held through transformation. Observation capacity is checked inside the transform and after preparation to prove release. This is generic preparation acceptance, not actual T2382 module acceptance or proof of CloudKit import visibility. Current missing conformance is an intended runtime RED rather than an absent-method compile failure.++These three methods compiled and ran under the exclusive slot. Actual xcresult reports three top-level/device executions, zero passed, three failed, zero skipped, and no compile failure. Duplicate requested identity returned the test adapter's second-worker bytes instead of busy; caller completion remained absent after bounded drain/receipt waits; the service recorded its missing protocol conformance. These are interface-capability RED results, not evidence that production supports and ignores caller identity/receipt. Exact command:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPReadAdmissionContractTests TransitTests/MCPReadHelperContractTests'+```++Evidence is retained outside Git at `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/capability/`: `red.log`, `red.xcresult`, `red-summary.json`, `red-tests.json` and strict `lint.log` (zero violations across 431 files). Source checkpoint was `cb3aeefb9d131934150e7211dc832062da7148fd`, including the receipt-order correction `a9553bc`. App process and physical latch workers drained; the heavy slot was released. No further app job is authorized. For task 13 acceptance, remove the baseline admission adapter and call the implemented API directly; then run the complete helper assertions beyond the conformance guard.++The existing actual-router RED evidence remains separate. Remaining actual-server lifecycle, write-preservation and real helper registration/replay acceptance follows the staged `routing-integration-plan.md`; task 12 is still in progress and task 13 has no runtime implementation.++The separate `MCPReadServerPreservationTests` baseline compiled and ran on `e3812b1`: six top-level methods/eight device executions, five passed controls and three failed stopped-read runs, zero skips. All stopped reads lacked the required failure metadata namespace. The five passing controls preserve stale-callback admission, original protected-write receipt replay, revision conflict/comment atomicity, stopped maintenance dispatch, and fallback-storage mutation exclusion. Exact focused command was `make test-quick TEST_TARGETS='TransitTests/MCPReadServerPreservationTests'`. Evidence is retained at `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/server-preservation/` (`red.log`, `red.xcresult`, summary/tests JSON, strict lint zero violations/432 files). The slot was released after process drain. The stale callback uses an unmatched generation against an unlaunched server; it does not establish replacement-listener or unfinished-worker lifecycle acceptance. That acceptance still needs one injected coordinator lifetime and the real admission/physical receipt API. No WriteCoordinator-owned source or tests are changed.+++## Stage A generic routing GREEN on the isolated development host++Stage A source is implemented at 36f7ee3, with the narrow applicability MainActor closure fix at 46bec7c. The inspected development-isolation component was integrated at 6806262; c614a9b adds the missing SwiftData fixture import. This checkpoint supersedes the earlier missing generic conformance/admission/router statements above. It does not complete task 13 or actual T2382/modern adapter acceptance.++One direct process-lifetime MCPReadCoordinator is injected into the handler and every listener generation. Caller admission UUIDs reject live duplicates without replacement. Caller-owned physical completion runs outside the common domain lock after private cleanup and permit removal; no completed receipt registry is retained. prepareCapturedRead conforms to the generic tool-level capsule contract, holds the import observation window through transformation/private preparation and preserves the original deadline. The dispatcher prepares the actual-ID full RPC bytes before terminal publication, discarding private candidates on outer encoding failure. Ordinary saved reads and frozen cursor replay use the prepared service; stopped reads have READ_BUSY metadata. Production applicability remains nil, so no positive CloudKit visibility claim is introduced.++The final configuration first passed the dedicated isolated host smoke (one test), then build-for-testing under the shared Transit Debug scheme. Signature/entitlement preflight verified me.nore.ig.Transit.development, no CloudKit/push/App Group entitlement, unit-test persistence, TRANSIT_ISOLATION_SMOKE=1 and the exact signed host path. The dedicated smoke separately verified memory-only /dev/null persistence, disabled cloud sync/counters and a private sidecar. No legacy production scheme or TransitDevelopment shared unit-test scheme was used.++Six test-without-building invocations ran sequentially against the same guarded shared build: admission two methods/two executions; helper one/one; corrected route three/four; server preservation six/eight; actual listener lifecycle one/one; outer-encoding/private-publication failure one/one. Final xcresult totals are 14 methods and 17 device executions passed, zero failures/skips. The actual network listener test verifies restart with eight unfinished physical workers, stale actual-generation completion, duplicate-safe caller receipts and capacity recovery. Write/receipt/revision/maintenance/fallback controls remain intact. Corrected route valid/invalid tool-domain fallback body times were 4.855503625 and 4.851150625 seconds; six-second blockers completed and no late ordinary retained root appeared.++The initial route run had two console parameter failures from the fixture expecting category timeout instead of the established READ_TIMEOUT enum value. Only that assertion was corrected to ReadFailureCategory.timeout.rawValue; source metadata was unchanged. The initial host did not exit after reported test bodies. After a bounded wait, only that exact isolated host was terminated; Xcode finalized with exit 65 and retried zero tests. Its summary coalesces the two parameter failures into one failed method/device entry, so the initial result is not presented as an ordinary clean drain. The corrected run exited normally. The initial hang cause is unproved. EmbeddedEventLoop thread-affinity warnings originate in the test-only EmbeddedChannel responder harness crossing async executors; they were preserved, not suppressed, and are not evidence of the hang cause or of actual network listener misuse.++Evidence is outside Git at /Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence/stage-a-isolated/: dedicated smoke/initial and corrected preflight, guarded xctestrun files, shared build and individual run logs, seven xcresults with extracted summaries and counts.json. The exclusive slot was released after an elevated exact process check found no owned Xcode/test host processes. No additional app job is authorized. Actual T2382 helper registration/snapshot dispatch/coalescing and T2383 modern final adapter remain Stage B/C prerequisites; tasks 12/13 stay incomplete. No live MCP mutations, production launch, push, merge or deployment occurred.
diff --git a/specs/bounded-read-freshness/integration-ownership.md b/specs/bounded-read-freshness/integration-ownership.mdnew file mode 100644index 0000000..02ae1b7--- /dev/null+++ b/specs/bounded-read-freshness/integration-ownership.md@@ -0,0 +1,58 @@+# Shared read integration ownership++Status: coordination proposal before task 13 GREEN. No shared-file handoff has occurred. The verified T63 component baseline is `dc85eabb5b35a6bd6b9ee16908d72aeb2c55bf15`; it does not enable production bounded routing. Task 12 routing fixtures reached actual app RED at `099415e832afc312a94e9521e3704eba729e441d`: saved reads leaked UI changes, frozen metadata was absent, valid and invalid reads exceeded five seconds, and a late cursor root became visible. Lifecycle/helper fixtures may proceed independently of actual T2382 delivery. Actual-module acceptance cannot pass on fixtures alone.++## Integration layers++1. T63 admits a classified read on the non-MainActor transport path using the original decoded admission instant. Protocol/header/envelope validation and availability classification use immutable transport state. Tool-domain validation, saved project/milestone resolution, policy decisions and capture run inside the bounded operation; they cannot add an unbounded MainActor hop before admission.+2. T63's policy-bound capture preparation starts the import observation window before the decision, preserves the original remaining budget, captures saved values inside the history/generation fence, and freezes metadata. T2382 receives that same complete declared-scope view for aggregation and reusable retention. A generic preparation callback must preserve observation lifetime and private reservation ownership.+3. Ordinary reads and T2382 helpers prepare tool-level results without an originating RPC ID. `MCPPreparedToolRead.encodedToolResult` is authoritative at the current baseline; its logical result is not a replay encoder. T2383's approved `MCPResultEncoder.freeze(...) -> MCPResultToolFragment` is the later modern representation. Cursor replay retains the original fragment, metadata, policy and expiry.+4. The transport prepares the complete RPC response bytes, with the current ID, before offering `PreparedReadResult` to the common publication domain. Candidate grouping and all-store validation precede one terminal selection. No response serializer runs after publication, and a timeout never releases an unfinished physical worker's permit.+5. T2383 takes the modern wire adapter after a verified T63 integration commit and explicit ownership transfer. Modern production rejects wire arrays. Existing coordinator batch tests may remain historical component evidence; T63 adds no dual-era protocol support. Final routing acceptance uses the modern adapter.++The parent and T2382 confirmed these tool-level helper signatures before delivery:++```swift+handlePortfolioSummary(request: MCPPortfolioSummaryRequest,+ view: CapturedReadView,+ operation: MCPReadOperation) throws -> MCPPreparedToolRead+handleSnapshotTaskQuery(request: MCPSnapshotTaskQueryRequest,+ view: CapturedReadView,+ operation: MCPReadOperation) throws -> MCPPreparedToolRead+```++The earlier no-ID `PreparedReadResult` scaffold is not a valid final-response boundary. T63 owns the one outer RPC encoder, including fallback response bytes and the original budget. The confirmed helper return composes with T2383 frozen fragments.++The types-only capture seam is `MCPReadCapturedPreparing.prepareCapturedRead(request:policy:operation:transform:)`. Its `MCPPreparedReadCapture` capsule carries `view` and `frozenMetadataBytes`. The Sendable async transform may use pure DTO work off MainActor and explicitly hop for handler/store work. Capture remains synchronous on MainActor inside the fence. The observation window remains held through transformation and private result/reservation preparation. This seam's implementation belongs to task 13; declarations do not establish delivery.++## File ownership++| Files or surface | Current owner | Later handoff |+| --- | --- | --- |+| `MCPServer.swift`, `MCPServer+Responses.swift`, `MCPServer+ToolListNotifications.swift` | T63 through verified bounded integration | T2383 becomes the sole writer for modern wire validation, discovery, subscriptions and response adaptation after explicit transfer. |+| `MCPToolListChangeBroadcaster.swift` | T63 retains current shared ownership; no new edits planned for read preparation | T2383 transport/subscription ownership with the same explicit transfer. |+| `MCPTypes.swift` | T63 preserves the existing metadata/result contract | T2383 modern envelope/result encoding after verified baseline; preserve T63's independent read metadata namespace. |+| `MCPToolHandler.swift`, `MCPToolHandler+TaskQuery.swift` | T63 common construction, classification and dispatch; actual T2382 registration | T2383 becomes the sole writer after verified integration. Later T63 diagnostic/read patches are narrow patches coordinated through that owner. |+| `MCPToolDefinitions.swift` | T63 through task 15 caller descriptions and common registration | T2383 supplies a narrow output-schema/discovery patch for T63 to apply; full transfer follows the verified description checkpoint. |+| All `MCP/Reads` files | T63 | Retain ownership. T2383 supplies narrow fragment/preparation changes for T63 to apply. Public physical-scope and freshness contracts remain shared. |+| `MCPTaskQuerySnapshotStore.swift` and ordinary retained-page hooks | T63 | Retain ownership for modern fragment retention and exact accounting. Never extend a retained root's original expiry. |+| Portfolio aggregation, request parsing, projection, separate handler/schema modules and reusable store | T2382 | T2382 delivers clean verified modules; T63 wires shared entrypoints. T2383 coordinates its reusable-fragment change through T2382. |+| `MCP/Writes/MCPWriteCoordinator.swift` and coordinator-specific write tests | T2384 | Remain T2384-owned. T63 uses separate read/server write-preservation tests and requests any overlap through the parent. |+| Capture, read coordinator, policy, publication and ordinary-retention fixtures | T63 | Retain ownership. |+| Modern transport fixtures | T2383 after transfer | T63 retains bounded-operation assertions through agreed test injection seams; no concurrent test-file edits. |++No blanket handoff is implied by this table. The parent records the exact clean revision and final file list before each transfer. Separate approved modules may progress independently while shared files remain with their current owner.++## Actual-module delivery dependencies++T2382 delivers its separate portfolio summary and snapshot query handlers, descriptors/tool definitions, reusable-store lifecycle hooks, participant aggregation, and tests from a clean verified revision. It confirms the helper return layer described above. T63 supplies the generic policy-bound capture preparation and shared dispatch registration; portfolio aggregation and reusable lifecycle logic remain in T2382 modules.++T2383's interface-only `8ea94ce0b3b9a3b73fcee330aed0c9883a08e92f` declares `freeze(source:presentation:metadata:)`, `encode(fragment:id:)` and `prepareMutationFallback(...)`. These methods are placeholders, not completed delivery. Its GREEN encoder must preserve original text/isError/source/presentation and frozen `_meta` values without renewed assessment or lossy numeric conversion. Retention charges expanded `encodedResult.count` plus uniquely retained backing once, retaining original policy and expiry. Complete response bytes must be ready before terminal publication.++Foundation tasks 1–11 and task 12's fixture draft do not depend on those later modules. Task 13 actual-module acceptance and final modern routing do. This separates preparation from delivery without making T2382/T2383 foundations wait for final T63 production routing.++## Verification and release++Each shared integration is a clean local ticket-branch commit with explicit source paths. The user approved local implementation sub-branch merges into ticket branches in `Sentinel_eafda56391a48191a3c414fef34d1307`; main/PR merges and deployment remain unauthorized. T2380 worktrees are not modified.++Heavy app/build/simulator jobs run only under an explicit exclusive slot from the parent. A worker releases the slot after app processes and physical fixture workers drain. T63 currently has no slot. Remaining task 12 preparation and light lint/type checks may proceed; further actual RED/GREEN jobs wait for a new grant. Final macOS/iOS validation and the full pre-push-review/Pulsar step follow actual-module integration.
diff --git a/specs/bounded-read-freshness/peer-codex.md b/specs/bounded-read-freshness/peer-codex.mdnew file mode 100644index 0000000..96b86ca--- /dev/null+++ b/specs/bounded-read-freshness/peer-codex.md@@ -0,0 +1,25 @@+The critic responses address most concerns, but batch deadlines and several observable states still need clarification before requirements approval. The supplied documents do not establish design feasibility.++1. **High — requirements blocker: batch completion remains ambiguous (1.1, 1.2, 1.5, 6.2).** + The critic correctly separates read-only batch delivery from mixed-batch result production. However, 1.1 still universally promises an encoded result available to transport within five seconds, while 1.5 allows mixed-batch delivery to wait. Read-only batches also lack a defined outcome when individual results finish but combined encoding misses the deadline. + **Suggested edit:** explicitly qualify 1.1 for mixed batches; define whether “produced” includes individual encoding; specify the observable aggregate timeout behavior, including handling of already-completed results. Keep the mixed-batch caveat pending user approval.++2. **Medium — requirements gap: refresh outcome is undefined for inactive sync (3.1, 3.3, 3.4, 3.6).** + The critic’s competing-outcome rules substantially resolve overlap. But an inactive store using the default policy has no specified `refreshOutcome`. The contract proposal also says lack of a trigger means `unavailable`, overlooking a relevant in-flight import that can instead produce `import_observed`, `failed`, or `timeout`. + **Suggested edit:** define the inactive-sync outcome and align the proposal with 3.6. Define `assessedAt` explicitly as the fixed assessment time associated with capture.++3. **Medium — approval-record contradiction (5.3; proposal status/integration boundary; decision log).** + Shared saved-snapshot use and T2382 API/lifecycle ownership are approved. Earlier proposal paragraphs still call ownership unresolved. The proposal also says the five-/two-second defaults require approval, although those limits are approved. Approved decisions appear under “Pending approval” in the log. + **Suggested edit:** reconcile these statements with the supplied approval record. Scope/name/full-spec **type** approval must remain distinct from final requirements approval.++4. **Medium — decision needed: latency diagnostics are only partially observable (1.2, 6.1, 6.2).** + “Exhausted phase when known” supplies a timeout label, but does not establish stage-duration diagnostics or distinguish queueing, refresh, capture, transformation, and encoding costs. It cannot by itself explain the reported unknown 30–50-second delays. + **Suggested edit:** ask whether diagnosing those delays is an acceptance objective. If so, require bounded per-phase elapsed-time diagnostics and specify their audience—caller metadata or server diagnostics. Otherwise, state that causal latency diagnosis is outside this requirement. This is a scope decision, not an automatic blocker.++5. **High — design feasibility gate, not a missing consistency requirement (1.4, 2.4, 2.6, 3.4, 6.2).** + The critic’s coherent-view response is adequate at requirements level. Design must demonstrate deadline response despite blocked MainActor work, establish import visibility for the captured view, and preserve saved-write visibility. Choosing an isolated context or asserting that an import event proves visibility would not establish these properties. No supplied document proves feasibility.++6. **Medium — design risk: operation count does not bound transient memory (1.3, 1.6).** + The critic response accurately adds disposal and retained-slot behavior without claiming a byte bound. Eight unfinished operations can still retain substantial capture data, and blocked operations can occupy all slots indefinitely. Design should disclose these consequences and demonstrate disposal. A transient-byte limit or further recovery guarantee would need user approval.++The cursor response is adequately resolved by 5.1, 5.2, and 5.4, including policy conflicts and validation precedence. The 30,000 ms threshold, eight-operation limit, mixed-batch caveat, and final requirements remain approval gates; exact metadata placement and implementation mechanisms remain design questions.
diff --git a/specs/bounded-read-freshness/peer-design-architecture.md b/specs/bounded-read-freshness/peer-design-architecture.mdnew file mode 100644index 0000000..749d654--- /dev/null+++ b/specs/bounded-read-freshness/peer-design-architecture.md@@ -0,0 +1,35 @@+# T-63 design peer review — architecture and integration++Reviewed the complete requirements, design, design-critic report, explanation, decision log, and both prototype sources/README. This is the architecture/integration/maintainability perspective in the root reviewer's two-peer fallback. The named external MCP reviewers are unavailable and the parent instructed reviewers to respect the external retry denial; this review made no external calls. It is an independent internal peer perspective, not cross-model external validation.++Also inspected existing MCP routing, task-query selection/page retention, T2382's current portfolio design, and `MCPToolHandler+TaskQuery.swift` from merged foundation `201205bd4e786c7f152d8f99006b37da7da888c7`. No production edits, builds, tests, publication, or commits were performed.++## Conclusion++The revised design is suitable for the user design gate. No remaining architecture blocker was found after revalidation of the correction below. Production feasibility remains conditional on the explicitly named history/import, transport, and publication integration checks; the isolated probes do not satisfy those checks.++## Finding resolved during this review++**High: validate-all-before-commit alone did not prevent same-store index overwrite.** Two children in a read-only batch could prepare whole immutable indexes from the same store version. Both would validate before any commit, then the second swap could erase the first child's newly published entries. Atomic response selection would still return IDs from both successes.++The revised shared-publication paragraph explicitly requires coalescing every selected same-store create/append into one aggregate immutable index candidate and combined reservation outside the gate. Independent same-store index swaps are forbidden; validate all aggregate store candidates before any commit, then swap each store once. I re-read that change and consider the blocker resolved. T2382's batch design already calls for an aggregate candidate; the common contract now states why it is mandatory. Verify batching across two creates, two appends to one root, and creates/appends to different roots in the same store, including competing independent requests.++## Critic findings assessed++- **Whole-batch fallback and physical admission:** valid concerns, adequately addressed in design. The small-error deadline probe rebuilds its array after child completion, so it does not validate the revised prebuilt batch gate or assembly-permit transfer. The README accurately limits its evidence. Require real large-candidate/timeout tests and atomic permit transfer; do not reopen this as a design blocker solely because production tests are not implemented yet.+- **Shared transaction domain:** valid concern. A single common lock, staged capacity, validate-all, nonthrowing commits, preencoded rejection responses, and destruction after unlocking form a coherent contract. The correction above was necessary beyond the critic's original revalidation. Each selected store candidate must be composable before the gate; arbitrary publication objects must not introduce hidden independent locking or overwrite behavior.+- **Complete capture evidence:** valid concern. `.completePortfolio` plus canonical revision/full-record/comment validation prevents selected-read DTOs from silently becoming complete summaries. T2382's retained source can return the same immutable capture without fetching live models; its private retained wrapper holds query scope, indexes and publication state. This is compatible with `MCPRetainedViewSource` as a capture-read interface.++## Integration checks and clarifications++1. **Make completeness relative to resolved scope explicit in tasks.** T-63's enum comment says “all domain records”; T2382 supports both portfolio and project captures. For a project capture, completeness means all selected tasks and required relationship/identity/comment closure under the same fence, not every record in every project. Keep the scope frozen in T2382's retained wrapper and prohibit scope expansion. Project selection inside the capture fence closes the identity-resolution race.+2. **Preserve ordinary query behavior during DTO migration.** Current ordinary task filtering and ambiguity/error precedence are established independently of T2382's physical-identity attribution. Physical keys should support the new consumer without silently changing ordinary UUID-based selection, milestone-name matching, identifier outcomes, or no-comment-fetch summary paths. The merged full-task path obtains canonical `MCPRecordSnapshot.task` over comments before stripping public comments; preserve that revision verbatim.+3. **Strong retained ownership must not extend publication validity.** Returning an immutable capture can keep its bytes alive after logical expiry. Root expiry, lifecycle generation, capacity ownership and index version must still be validated under the shared domain at publication. Lookup/replay must observe committed entries only. Test timeout/expiry between lookup and append.+4. **Measure lock work as well as timer work.** Eight root entries bound one dimension, but cursor indexes can be much larger. Preparing/copying indexes, token allocation and discarded-buffer destruction must remain outside terminal critical sections; the final CAS/reference swaps must stay short. The separate 16 MiB stores are logical encoded retention budgets, not heap bounds.+5. **History/import proof is still an early feasibility gate.** Neither probe demonstrates CloudKit transaction completeness or empty-versus-purged history discrimination. Failing closed for capture and reporting unknown freshness are sound fallbacks, but may leave useful reads unavailable on an unsupported store. Surface that measured result before extending implementation around an unproven fence.++## Alternatives and judgment++Prefer a validated portfolio-capture constructor or stronger internal type to eliminate optional full-record evidence after the boundary; retaining one general DTO is acceptable if construction and consumption both enforce completeness. Keep ordinary and reusable retention stores separate to preserve their approved lifecycles, but share publication-domain machinery. A fully serialized retention actor would simplify ownership while risking executor scheduling behind timeout selection; the prepared immutable candidate and short common lock better match the approved independent deadline.++The shared architecture is justified by the requested deadline, frozen pagination and same-view summary/query behavior. Avoid adding a second capture DTO, refresh implementation, revision encoder, or store commit lock. User design approval remains a separate gate; these observations do not authorize tasks or production implementation.
diff --git a/specs/bounded-read-freshness/peer-design-correctness.md b/specs/bounded-read-freshness/peer-design-correctness.mdnew file mode 100644index 0000000..3e2adee--- /dev/null+++ b/specs/bounded-read-freshness/peer-design-correctness.md@@ -0,0 +1,35 @@+# T-63 design peer — correctness and feasibility++Reviewed the complete requirements, revised design, critic report, explanation, decision log, and both isolated prototype sources. Also inspected the existing server's batch dispatch/body limit and the canonical task snapshot implementation directly from merged revision `201205bd4e786c7f152d8f99006b37da7da888c7`. This is one independent internal peer perspective in the documented two-peer fallback; no external-model calls, builds, production edits, or approval actions were performed.++## Verdict++No remaining design blocker in the revised document. The design can proceed to user review with its explicit implementation verification gates. The probes establish narrower facts than the complete production contract: they do not establish live CloudKit coherence, large-batch response availability, actual retained-store transactions, or a hard real-time scheduler guarantee.++## Critic findings independently assessed++- **Whole-batch fallback and physical accounting:** the original blocker was valid. A small array assembled after individual timeouts cannot establish a deadline for arbitrary candidate aggregation. Preparing the complete fallback before worker dispatch and selecting it through an independent batch gate removes the dependency on candidate serialization. Retaining one completed element's physical permit through aggregation prevents repeated timed-out assemblies escaping the eight-operation bound. The ownership transition must be atomic; the current prototype does not exercise that transition or a blocked large aggregate.+- **Publication transaction:** the original blocker was valid. Prepared success bytes can contain snapshot/cursor IDs, so response selection and publication must share one critical section and reject the entire selected set before any commit. The revised pre-encoded rejection/fallback rule prevents returning IDs that were never published. Validation, nonthrowing commit, and discard must be effect-free with respect to arbitrary work: no callbacks, nested store locks, encoding, or final destruction of large values inside the domain.+- **Complete portfolio evidence:** the original blocker was valid. Optional task evidence alone cannot distinguish an intentionally narrow read from an incomplete portfolio. The explicit completeness discriminator plus construction/consumer validation addresses this. Empty comments are valid complete evidence only after a successful required fetch; absent required evidence must never become an empty list.++## Additional concurrency finding and disposition++I independently identified the same-store batch hazard reported by the architecture peer: validating two independently prepared whole-index replacements against version V before committing either would let both pass, then the second swap could overwrite the first. A lock and validation-before-commit alone do not prevent this intra-batch lost update.++The latest design addresses it by coalescing selected create/append operations into one aggregate candidate, version, and capacity reservation per store outside the gate, then validating every aggregate before swapping each store index once. This is sufficient at design level. Implementation tests must cover multiple creates, multiple appends, and create-plus-append in one read-only batch. Transfer ownership from child pending reservations to the aggregate atomically so capacity is neither double-counted nor briefly freed; each discarded/unselected reservation is released exactly once. Concurrent operations changing the base version must select the documented pre-encoded rejection rather than partially publish the batch.++## Early verification priorities++1. **Saved capture/history fence:** equal valid persistent-history watermarks are a defensible optimistic fence only if all relevant saved changes contribute visible history and the validation context observes the latest watermark. Test concurrent imports, history purge/expiry, genuinely empty stores, and fresh contexts with pending UI changes. An empty selected result is not proof that the entire persisted domain store has no history. Unsupported fencing must fail with `incoherent_capture`, including inactive sync, rather than quietly weaken the saved observation boundary. The current local probe proves rejection of one intervening save, not the full assumption.+2. **Import applicability:** positive store-ID association and actual visibility of the completed import remain necessary. A callback's receipt time or an unchanged monitor generation does not by itself prove that the selected context includes that import. Define the monitor's serialized boundary and test queued callbacks; preserve `unknown`/null import time whenever association or visibility cannot be supported. Reject future/inconsistent event clocks rather than giving them zero age. This uncertainty concerns freshness separately from local capture completeness.+3. **Admission-to-router deadline:** measure fallback preparation, strict timer selection, continuation scheduling, and router return with the existing 1,048,576-byte body limit, long request IDs, many invalid/busy elements, and large candidate result arrays. Preparing fallback is inside the approved budget; starting a timer after expensive preparation cannot reset admission time. Reserve the absolute cutoff first and test preparation finishing close to it. The isolated six-second blocked-MainActor result supports timer independence but does not prove these cases.+4. **Permit/lifecycle races:** test timeout before worker starts, capture-to-assembly transfer, stop/restart, disconnect during preparation, and late physical completion. Every physical operation must retain exactly one permit until its actual final stage ends. Requirement 1.6's stop wording should be interpreted with the approved unfinished-work bound: stopping invalidates response/publication state but does not make unfinished physical work disappear.+5. **Publication visibility/capacity:** test stale append versions, expiry during preparation, capacity rejection, token collision, canceled batches, and lookups racing a commit. Capture capacity usage before, during, and after aggregate reservation transfer. Pre-encode all selectable error bytes before the gate; after rejection, no successful response may retain a staged ID and no lookup may expose an uncommitted entry.++## Merged foundation and alternatives++Merged `MCPRecordSnapshot.task` fetches comments through the task UUID descriptor and includes their full covered fields in canonical r1. Public comment omission or effective-status projection must preserve that revision verbatim. Portfolio relationship attribution can use physical keys without substituting a different comment set into the authoritative revision routine. The design correctly keeps ordinary summary reads without requested comments on their no-fetch path.++A typed complete-portfolio wrapper with mandatory revision/record/comment evidence would make invalid states harder to construct than an enum plus optional properties; this is a worthwhile implementation choice rather than a design blocker because both construction and consumption already require validation. If persistent-history fencing cannot be established, do not invent a substitute query-generation guarantee: use the documented failure and return an alternative capture mechanism to the design gate. A structured timeout race or MainActor timer is not a viable substitute for the independent completion mechanism because synchronous store work can prevent timely cancellation or actor execution.++User design approval remains separate. These findings do not authorize tasks or production implementation.
diff --git a/specs/bounded-read-freshness/peer-kiro.md b/specs/bounded-read-freshness/peer-kiro.mdnew file mode 100644index 0000000..13d0697--- /dev/null+++ b/specs/bounded-read-freshness/peer-kiro.md@@ -0,0 +1,57 @@+## Overall assessment++The critic’s six findings were valid and the draft responses are directionally correct. Findings 3 and 5 are substantially resolved at the requirements level; findings 1, 2, 4, and 6 still leave approval or observable-contract blockers. The requirements should not advance to final approval yet.++## Requirements blockers++1. **P0 — Batch deadline semantics remain incomplete and the mixed-batch exception is unapproved** (`1.1`, `1.3`, `1.5`, `6.1`, `6.2`). + - For read-only JSON-RPC batches, “complete encoded batch response” is appropriately stronger than per-read production, but admission is underspecified: whether elements are admitted atomically, how the eight-slot limit applies to a batch, and when rejected elements’ clocks begin.+ - “Batch” also ambiguously refers to both JSON-RPC batches and `query_tasks` batch mode.+ - For mixed batches, producing a read result internally is not caller-observable if HTTP delivery waits 30–50 seconds for a write. It therefore does not provide the bounded endpoint response promised by Story 1.+ - **Suggested edit:** distinguish “JSON-RPC batch” from “task-query batch mode”; define one decoded-batch timestamp, per-element capacity handling, and whether aggregation/envelope serialization is included. Present the mixed-batch choices for approval: accept unbounded combined delivery with explicit documentation, reject mixed batches, or define another transport behavior. Do not make the current caveat final without approval.++2. **P0 — Additive metadata may contradict preservation of existing payload shapes** (`2.1`, `4.3`, compatibility contract). + Every success, including an empty array, must carry one result-level metadata object. The supplied documents identify no backward-compatible extension point for existing top-level arrays. Wrapping an array changes its shape; attaching metadata to elements fails for empty results and duplicates view-level evidence.+ - **Suggested edit:** clarify that “preserve payload shape” means preserving the existing data value within an approved outer MCP result extension, or explicitly approve an envelope/schema change. Exact field placement may remain design work, but the permitted compatibility boundary must be settled in requirements.++3. **P0 — “Coherent,” “relevant,” and “visible to the selected view” are not yet observable invariants** (`2.1`–`2.6`, `3.2`, `5.1`, `5.3`). + The critic correctly caught import relabeling, and `2.6` improves the draft, but it does not define what proves a multi-entity capture is one view. Nor does it define which store/import event is “relevant” or how an import is shown to precede the captured store version.+ - **Suggested edit:** require all selected entities, relationships, and totals to derive from one immutable store/context version or equivalent capture boundary, and require import evidence to be associated with a version no later than that boundary. Leave the SwiftData mechanism to design.++4. **P1 — Failure and latency diagnostics are insufficiently defined** (`1.2`, `2.6`, `4.1`, `6.1`, `6.2`). + `READ_FAILED` versus an existing error remains open, while `2.6` merely says “defined read failure.” Acceptance cannot be tested until a stable category or compatibility mapping is selected.+ + Stage-level diagnostics are also a missing observable requirement **if explaining the existing 30–50-second delays remains an objective**. “Exhausted phase when known” has no phase taxonomy and permits no useful evidence. A response emitted at five seconds also cannot reveal when lingering work eventually completed.+ - **Suggested edit:** define stable phases such as admission/queue, refresh wait, capture/fetch, transformation, serialization, and batch aggregation. Require the timeout error to identify the active phase and monotonic elapsed time when determinable. If root-cause diagnosis is in scope, separately require correlated structured diagnostics for late completion/discard; this needs user approval because it adds an observability requirement. It need not change successful payloads.++5. **P1 — The eight-operation rule is not a complete resource contract** (`1.3`, `1.6`, `6.2`). + The critic response correctly adds disposal and retained-slot tests, but eight operations do not bound per-operation fetch/result memory. Permanently blocked work can also leave the endpoint permanently returning `READ_BUSY`.+ - **Suggested edit:** call this an “admission/concurrency bound,” not a general resource bound. Define JSON-RPC batch slot allocation and shutdown behavior. Ask the user whether operation-only bounding is acceptable or whether transient-byte/result-size limits are required. The value eight remains unapproved.++6. **P1 — Refresh precedence is improved but the observation window remains ambiguous** (`2.5`, `3.2`, `3.3`, `3.6`). + The success/failure/timeout/unavailable priority is useful, but the contract does not say when observation begins, whether a pre-existing in-flight import qualifies, which of multiple store events is relevant, or what happens when no refresh wait time remains.+ - **Suggested edit:** define the refresh-attempt observation interval and store identity. State that zero remaining refresh budget yields `timeout` only when a supported trigger or relevant in-flight import exists; otherwise `unavailable`. Event-source feasibility remains a design gate.++## Design and feasibility questions—not requirements blockers once semantics are fixed++- **Independent deadline path:** `1.4` cannot be met if a synchronous MainActor/SwiftData fetch blocks the executor needed to encode and transport the timeout. Design must prove an independent response timer/path and suppression of late publication.+- **Immutable capture feasibility:** prove SwiftData can provide the required cross-entity captured view while preserving saved local-write visibility (`2.6`, `3.4`).+- **Import evidence:** verify CloudKit events identify the running store/context in headless operation and distinguish success, failure, unrelated imports, and process-start uncertainty (`2.3`–`2.5`).+- **Cursor retention:** prove exact metadata and frozen page data can be replayed under existing byte, capacity, and expiry limits (`5.1`, `5.2`).+- **T2382 integration:** API/lifecycle and storage mechanics remain design work owned by T2382; T-63 only needs to preserve shared capture identity and freshness semantics (`5.3`).++## Critic-response validation++1. **Batch boundary:** partially resolved; read-only behavior is stronger, but mixed delivery and batch admission still block approval. +2. **Consistency invariant:** partially resolved; correct intent, insufficient observable definition. +3. **T2382 ownership:** resolved by the approved allocation and `5.3`. +4. **Resources:** partially resolved; disposal/testing added, transient memory and permanently lingering work remain risks. +5. **Cursor policy:** resolved well in `5.4`, including malformed-policy and cursor-resolution precedence. +6. **Refresh outcomes:** mostly resolved; temporal/store relevance still needs definition.++## Document contradictions and approvals needed++- `contract-proposal.md` first says the **5,000/2,000 ms limits and shared capture ownership are unapproved**, but later sections and the decision log correctly record them as approved. Update the stale statements; only the 30,000 ms threshold, detailed integration, and remaining semantics are pending.+- Normative `1.5`, `2.2`–`2.3`, and `1.3` currently embed proposals explicitly marked unapproved. That is acceptable in a draft, but they must not be represented as final.+- User approval is still needed for: **30,000 ms recency**, **eight-operation admission limit and whether operation-only resource bounding is acceptable**, **mixed-batch delivery caveat**, **final error/metadata compatibility semantics**, **whether stage/late-completion diagnostics are required**, and **the final requirements as a whole**.+- Do **not** reopen the already approved scope/name/full-spec type, additive metadata, `refresh_if_needed`, 5,000/2,000 ms budgets, deferred refresh/maintenance tools, or shared saved-snapshot ownership split.
diff --git a/specs/bounded-read-freshness/prototype/README.md b/specs/bounded-read-freshness/prototype/README.mdnew file mode 100644index 0000000..852d132--- /dev/null+++ b/specs/bounded-read-freshness/prototype/README.md@@ -0,0 +1,27 @@+# Isolated Xcode 27 design probes++These files are under the spec directory and are not included in Transit app targets. They are experiments for design approval, not authorized production implementation. Compile with installed Xcode27's Swift6.4 and SDK; build products/stores remain outside Git in the workspace's `t63-design-prototype` directory.++```sh+/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc -swift-version 6 -default-isolation MainActor -parse-as-library -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk -module-cache-path /Users/arjen/Documents/Codex/2026-10-03/task/t63-design-prototype/module-cache specs/bounded-read-freshness/prototype/DeadlineProbe.swift -o /Users/arjen/Documents/Codex/2026-10-03/task/t63-design-prototype/deadline-probe+/Users/arjen/Documents/Codex/2026-10-03/task/t63-design-prototype/deadline-probe+```++Final measured output (exit 0):++```text+MEASURE batch_ms=4851.153 response_ms=[4850.438959, 4850.478667, 4850.48225, 4850.484125, 4850.486459, 4850.488209, 4850.489584, 4850.490917] unfinished=8+PASS blocked_mainactor_ms=6000 encoded_batch_ms=4851.15 max_response_ms=4850.49 unfinished_at_timeout=8 unfinished_after_completion=0 late_publications=0 restart_busy=true bytes=809+```++An initial generic asyncAfter timer failed the five-second assertion at 5163.999 ms despite a 4850 ms deadline. Strict DispatchSourceTimer, zero leeway, userInitiated queue, explicit @concurrent async helpers, direct gate completion, and internal headroom produced the measured pass. macOS scheduling is not hard real-time; the app/transport load checks must measure encoded response availability at router return. This experiment does not validate real HTTP delivery, SwiftData fetches, lifecycle integration, actual retained store transactions, or arbitrary payload sizes. Publication and restart are modeled counters/gates, not production stores.++CaptureProbe uses two isolated on-disk SwiftData models with CloudKit disabled. The same compile command applies with `CaptureProbe.swift` and output `capture-probe`; run it with a fresh `probe.store` path. SwiftData compiler macro initialization required supported scoped per-command escalation; no compiler safeguards were disabled. Its successful run printed:++```text+PASS mixed_capture_rejected=true fresh_saved_write_visible=true stable_history_watermark=true store_identifier_known=true mixed_values=["old", "new"] stable_values=["new", "new"]+```++Two Core Data store-notification registration diagnostics appeared in the restricted runtime; the probe exited 0. It verifies public persistent-history tokens can reject a saved change across two selected fetches and fresh context sees saved state. It does not prove live CloudKit history/event-store correlation, history completeness during remote imports, or shared UI pending-edit behavior. Those remain early design verification gates.++The parallel T2382 worker independently measured a strict 4.95-second timer selecting timeout bytes at 4.950227 seconds with six-second MainActor blocking, eight retained permits, and 120 single-winner race cases. Its original exact-five-second strict timer measured 5.000345 seconds; its generic asyncAfter timer measured 5.333136 seconds. Both prototypes support independent coordination with internal headroom, not a hard-real-time scheduler claim.
diff --git a/specs/bounded-read-freshness/requirements-critic.md b/specs/bounded-read-freshness/requirements-critic.mdnew file mode 100644index 0000000..58864d6--- /dev/null+++ b/specs/bounded-read-freshness/requirements-critic.md@@ -0,0 +1,29 @@+# T-63 requirements critic — first review++Reviewer: independent design-critic subagent applying the actual local design-critic skill. Reviewed the initial requirements draft and contract proposal, read-only.++1. High: per-read production versus complete HTTP batch response is ambiguous. A mixed write can delay delivery despite a produced read result. Define the boundary without changing write behavior.+2. High: multi-entity capture lacks a consistency invariant. An import observed during capture must not relabel previously fetched data as recent.+3. High: excluding a reusable snapshot API may conflict with T2382 acceptance. State pending ownership and compatible common capture semantics.+4. Medium: eight unfinished operations do not bound transient bytes. Define disposal, distinguish transient capture from existing retained-page limits, and test blocked MainActor and slots retained after timeout.+5. Medium: cursor policy omission/conflicts and invalid-input precedence need definition.+6. Medium: refresh outcomes overlap when trigger is unavailable, imports are in flight, failures/successes compete, or little total budget remains.++Questions before design: What response boundary does five seconds cover for batches? What makes the selected multi-entity view coherent? Which ticket owns reusable capture? What bounds lingering work and transient memory? What cursor validation precedence and competing refresh outcome rules apply?++## Draft response for peer validation++- Added separate read-only combined-batch and mixed-batch production/delivery requirements; mixed-batch delivery caveat is an explicit pending user choice.+- Added coherent immutable selected-view requirement and restriction that import evidence must be visible to that view.+- Clarified T2382 shared view compatibility while leaving API/lifecycle ownership to the parent.+- Added slot/data disposal requirement and tests for blocked MainActor and lingering slots. Retained pages keep their existing limits; no transient-byte limit has been approved. The design must disclose that operation-count admission does not alone bound store fetch memory.+- Defined omitted/same/conflicting cursor policy behavior and validation precedence.+- Defined competing refresh outcome priority and shortened wait within remaining deadline.++These edits are draft requirements, not user approval or a claim of proven design feasibility.++## Final critic validation++The same independent critic re-read the final revised requirements after external Codex/Kiro findings were incorporated. It found no new requirements blocker: per-element JSON-RPC admission, outer MCP metadata preserving text payloads, capture boundary, refresh precedence, stable failure categories, and latency evidence are now explicit.++The remaining risks belong at design approval: demonstrate deadline delivery and batch encoding while MainActor is blocked; preserve admission accounting across stop/restart with unfinished work; establish a supported immutable observation boundary and applicable import evidence; keep diagnostics from delaying the bounded response. The 30-second threshold, eight-operation limit, diagnostics, and final requirements remain user approval choices.
diff --git a/specs/bounded-read-freshness/requirements-peer-review.md b/specs/bounded-read-freshness/requirements-peer-review.mdnew file mode 100644index 0000000..443df2e--- /dev/null+++ b/specs/bounded-read-freshness/requirements-peer-review.md@@ -0,0 +1,33 @@+# T-63 requirements peer validation — final synthesis++The required external Codex and Kiro consultations both completed successfully (exit 0) after the first design-critic review. Successful raw reports are [Codex](peer-codex.md) and [Kiro](peer-kiro.md). They reviewed the supplied launch packet, not the later revisions. After the parent’s final critic reported no new requirements blockers, this peer reviewer read the revised requirements and validated the dispositions below locally; no external consultations were repeated.++## Finding dispositions++| Finding | Final disposition |+| --- | --- |+| Universal transport promise conflicted with mixed-batch exception | Resolved by 1.1 qualification and 1.5; direct user approval permits mixed reads’ production within five seconds while combined delivery waits for writes. External reports’ pending-approval language predates that approval. |+| Combined encoding deadline and batch admission undefined | Resolved at requirements level: 1.5 includes aggregate serialization and affected-read timeout fallback; proposed contract distinguishes JSON-RPC batch elements from one task-query batch operation and defines received-order slot admission with a common decoded-batch timestamp. Design must prove fallback encoding meets the same deadline. |+| Inactive-sync refresh outcome and assessment timestamp undefined | Resolved by 3.4’s not_requested under either policy and 2.2’s assessedAt fixed to original asOf. |+| Additive metadata could change array payload shapes | Resolved by 2.1: outer MCP result metadata preserves existing text-content data value and shape, including empty results. Exact field placement remains design work within the approved compatibility boundary. |+| Coherent/relevant view lacked observable meaning | Resolved by 2.6’s immutable local observation boundary with each completed saved change wholly represented or absent; inability to establish it yields incoherent_capture. 2.4 and 3.6 require import applicability to the running store and capture. Supported SwiftData/CloudKit proof remains a design gate. |+| Storage/encoding/coherence failures lacked stable categories | Resolved by 4.1’s storage_failure/serialization_failure versus incoherent_capture, timeout, busy, and input/cursor categories; caller documentation maps categories to compatible tool error codes. |+| Refresh interval, in-flight events and zero wait unclear | Resolved by 3.6: decision-through-bounded-wait observation, relevant pre-existing imports, explicit zero-wait outcome, and total READ_TIMEOUT precedence. |+| Eight operations described as broad resource bound | Resolved wording: admission bound explicitly excludes total transient-memory bound. Design must disclose large captures and indefinitely occupied slots rather than invent further unapproved limits. Eight remains proposed. |+| Unknown 30–50 second latency lacked useful evidence | Addressed by proposed 6.3 server stage-duration diagnostics with correlated late completion/discard. This is an explicit pending requirements recommendation, not approved instrumentation or a claim that CloudKit caused the incident. |+| Stale approval/ownership records | Resolved in current proposal and decision log, whose headings now distinguish Approval record and Pending requirements choices. Full-spec type approval remains separate from final requirements approval. |+| Cursor policy/precedence and T2382 ownership | Both external reviews found these resolved. 5.1–5.4 preserve original view metadata; T2382 owns reusable external API/lifecycle while T-63 preserves shared capture identity. |++## Final assessment and remaining gates++No additional requirements wording blocker was found in this final local validation. The 30,000 ms import threshold, eight unfinished-operation admission limit, diagnostics recommendation, and complete requirements still need user approval in the parent conversation. The previously approved budgets, additive metadata, default policy, deferred tools, mixed-batch exception and saved-snapshot sharing must not be reopened as unresolved choices.++The final critic’s remaining design risks are valid: independent deadline/batch error encoding despite a blocked MainActor; slot accounting across service stop/restart while old work remains unfinished; a supported immutable capture/import visibility boundary preserving saved local-write visibility; diagnostics that cannot delay bounded results. Current requirements describe required outcomes, not proof of feasibility. These must be resolved with design evidence before implementation.++## Consultation evidence and safeguards++Both initial restricted attempts failed before analysis (Codex app-server initialization; Kiro auth portal). Supported scoped per-command escalation allowed actual consultation without changing global permissions. Codex retained read-only sandboxing; Kiro used zero trusted tools; neither reviewer used tools. The parent supplied direct user approval to share both tickets’ spec documents, findings and relevant repository excerpts with Codex/Kiro (Sentinel_7ba5dca061b4819183c1d6066aa1e949).++Raw CLI logs, failed reports and the exact launch prompt are preserved outside Git/specs in `/Users/arjen/Documents/Codex/2026-10-03/task/t63-review-evidence`: `peer-codex-initial-failed.log`, `peer-kiro-initial-failed.md`, `peer-codex-escalated.log`, and `peer-prompt.txt`. They contain local auth/session initialization details and must not be committed, published or sent to the phone. Only successful external reports and this synthesis remain review deliverables in the spec folder.++This reviewer made no source changes, builds/tests, ticket changes, commits, phone sends or publication. There is no remaining external-consultation blocker. Parent owns user synthesis, phone delivery and the final approval request.
diff --git a/specs/bounded-read-freshness/requirements-review.md b/specs/bounded-read-freshness/requirements-review.mdnew file mode 100644index 0000000..5f039f3--- /dev/null+++ b/specs/bounded-read-freshness/requirements-review.md@@ -0,0 +1,27 @@+# T-63 requirements approval packet++Read `requirements.md` for the six user stories and 29 testable acceptance criteria. Scope/name and the recorded behavioral decisions are approved; this packet requests final requirements approval before design begins.++## Review synthesis++The design-critic and external Codex/Kiro reviews exposed ambiguous batch delivery, capture/import applicability, refresh outcomes, cursor policy, failure categories, and admission accounting. The revised requirements make each explicit. Final internal critic and peer validation found no remaining requirements wording blocker; successful external raw reports and the finding-by-finding synthesis are included.++The five-second response guarantee is preserved. Source inspection shows transport/response value types already separated from MainActor, so an independent timeout coordinator is a credible design direction; merely returning after MainActor resumes is insufficient. `deadline-feasibility-note.md` explains the evidence and the proof still required during design.++## Choices still proposed++1. **Import recency: 30 seconds.** A completed relevant import within this age is `recent_import`, not proof every remote edit arrived. Unknown evidence stays unknown.+2. **Admission: eight unfinished reads.** Includes queued/running work that outlives its timeout. An occupied capacity yields `READ_BUSY`; this does not promise a transient-memory limit or automatic recovery from permanently blocked work.+3. **Latency diagnostics.** Server diagnostics record phase durations and correlate late completion/discard so the reported 30–50 second incident can be investigated without assuming CloudKit caused it.++Do the requirements look good or do you want additional changes? Approval should explicitly cover the complete EARS document, including these three recommendations. Design, tasks, and implementation are separate gates.++## Design evidence required next++- Independent deadline delivery and complete read-only batch encoding while MainActor is blocked.+- Correct unfinished-work accounting across timeout and service stop/restart.+- Supported coherent multi-entity capture, saved-write visibility, and import evidence applicable to that capture.+- Compatibility with T2382's retained summary/task-query identity and lifecycle.+- Diagnostics that do not delay a bounded response.++No implementation, push, merge, deployment, or Pulsar publication has occurred. The local requirements skill requires final requirements approval before moving to design; the parent conversation owns the approval request.
diff --git a/specs/bounded-read-freshness/requirements.md b/specs/bounded-read-freshness/requirements.mdnew file mode 100644index 0000000..a811339--- /dev/null+++ b/specs/bounded-read-freshness/requirements.md@@ -0,0 +1,95 @@+# Bounded read freshness — requirements++Transit agents need to know when a read describes only the endpoint's local view and when that view was captured. Headless CloudKit imports may lag, and read latency has exceeded client deadlines without an established cause. This feature makes those limits visible and gives callers a bounded success or failure response.++Review status: approved in full by the user in the parent conversation on 2026-10-03, including the 30,000 ms threshold, eight unfinished-read admission limit, diagnostics, and all decisions in the requirements review. Design, tasks and implementation are also approved by the user; approved scope and contracts remain binding.++## Proposed observable contract++- Covered tools: `query_tasks` (single, batch, list, and cursor), `query_milestones`, and `get_projects`, including related comments/milestones required by their selected output.+- Default policy: `refresh_if_needed`; optional `cached` policy skips import waiting. No separate refresh tool is required.+- Total read budget: 5,000 ms, measured from decoded read admission before executor queueing to an encoded success/error available to transport. Read-only JSON-RPC batches share their admission timestamp and must have a combined encoded response within this budget. For mixed read/write batches each read result's production is bounded while existing writes are preserved; combined HTTP delivery can wait on writes. The user approved this mixed-batch exception. Network upload/download and whole-process suspension are outside the server response guarantee.+- Freshness wait limit: 2,000 ms within the total budget. A relevant successful import is recent when its age at capture is at most 30,000 ms.+- Compatibility: keep existing data payload shapes, selection semantics, and query cursor expiry/capacity behavior; add read metadata to the MCP result. Success data are the selected local view, not a claim of remote convergence.+- Admission bound: at most eight unfinished covered read operations, including timed-out work still running; return `READ_BUSY` when that capacity is unavailable. This is an operation-count limit, not a total transient-memory limit.+- Recommended latency evidence: server diagnostics distinguish queueing, refresh wait, capture/fetch, transformation, serialization, and batch aggregation, including correlated late completion/discard after a caller timeout. This diagnostics detail is approved.++The import recency threshold, admission bound, and latency diagnostics are approved requirements decisions. Exact metadata placement and supported import observation/refresh mechanisms are design decisions, constrained by compatibility and the behavior below. “JSON-RPC batch” means several protocol request elements; `query_tasks` batch mode is one read operation selecting multiple identifiers. Each covered request element is admitted separately in received order against the global available slots; excess elements receive `READ_BUSY`, while all elements keep the common decoded-batch admission timestamp.++## Non-Goals++- Guaranteed force-pull, global CloudKit convergence, or proof that every remote edit has arrived.+- Changes to writes, persisted model schemas, UI sync behavior, or unrelated App Intent reads.+- A separate refresh tool or optional maintenance-tool reads.+- T2382 portfolio aggregation, completion-window definitions, and its externally reusable summary/task-query snapshot API/lifecycle; T-63 supplies compatible shared capture/freshness semantics.++### 1. Bounded read completion++**User Story:** As an agent, I want every read to finish within a known server budget, so that I can recover from a slow endpoint.++**Acceptance Criteria:**++1. <a name="1.1"></a>WHEN a covered read is admitted, the server SHALL produce its encoded success or defined error within 5,000 ms, including queueing, freshness waiting, local fetches, related-data capture, transformation, and serialization; for individual reads and read-only batches this includes making the response available to transport, while mixed-batch delivery follows the approved exception in 1.5. +2. <a name="1.2"></a>IF a complete selected result cannot be returned within that budget, the server SHALL return `READ_TIMEOUT` with the exhausted phase when known and SHALL NOT later emit a second result for that request. +3. <a name="1.3"></a>WHEN eight unfinished covered reads already exist, the server SHALL reject additional covered reads with `READ_BUSY` within their total budget; timed-out work SHALL continue to count against capacity until it finishes. +4. <a name="1.4"></a>WHEN a response deadline expires while a local fetch is slow or blocked, the server SHALL still return the timeout within the total budget; a late result SHALL NOT create or replace a caller-visible snapshot. +5. <a name="1.5"></a>WHEN a batch contains only covered reads, the server SHALL make its complete encoded batch response available within 5,000 ms of batch admission, including aggregate serialization; IF successful-result encoding cannot finish within that deadline, the affected reads SHALL receive defined timeout results within the same deadline. WHEN a batch also contains writes, the server SHALL produce each covered read result within that deadline and disclose that combined delivery may wait for writes. +6. <a name="1.6"></a>WHEN timed-out work finishes or the read service stops, the server SHALL release its admission slot and discard unneeded capture/page data without publishing a late response or snapshot; retained valid pages SHALL keep existing byte and expiry limits. ++### 2. Explicit local capture and freshness evidence++**User Story:** As an agent, I want capture time and import evidence, so that I can judge whether local data are adequate for my decision.++**Acceptance Criteria:**++1. <a name="2.1"></a>WHEN a covered read succeeds, including an empty or scoped result, the outer MCP tool result SHALL carry an opaque `snapshotId`, UTC ISO 8601 `asOf` with millisecond precision identifying completed local capture, and one freshness assessment for all task/project/milestone/comment evidence used by that result, while preserving the existing data value and shape inside its text content. +2. <a name="2.2"></a>The freshness metadata SHALL disclose the running store's `syncState` (`active` or `inactive`), nullable `lastImportedAt`, `assessedAt` fixed to the capture's `asOf`, and the 30,000 ms recent-import threshold; it SHALL classify evidence at capture as `recent_import`, `stale`, `unknown`, or `not_applicable`. +3. <a name="2.3"></a>WHEN cloud sync is active, the server SHALL classify a known relevant successful import of age 0–30,000 ms as `recent_import`, an older known import as `stale`, and absent, unreliable, or temporally inconsistent evidence as `unknown`; import recency SHALL NOT imply all remote edits are visible in the local view. +4. <a name="2.4"></a>IF successful import evidence cannot be tied to the running store and captured local view, the server SHALL report `unknown` rather than confirmed recency; heartbeat writes, failed/incomplete imports, and response timestamps SHALL NOT substitute for successful import evidence. +5. <a name="2.5"></a>WHEN a later import fails, the server SHALL preserve any valid last successful import timestamp and disclose the failed refresh outcome separately from local fetch success. +6. <a name="2.6"></a>WHEN a result includes task, project, milestone, or comment evidence, all selected records and relationships SHALL correspond to one immutable local observation boundary containing saved data only, with each completed saved change wholly represented or wholly absent from that selected view; unsaved UI/context changes SHALL NOT be returned. IF that boundary cannot be established, the server SHALL return an `incoherent_capture` failure category. Import evidence SHALL NOT label data captured before that import became visible to the selected view as recent.++### 3. Cached and bounded refresh policy++**User Story:** As an agent, I want to choose whether to wait briefly for import evidence, so that I can balance latency against freshness needs.++**Acceptance Criteria:**++1. <a name="3.1"></a>WHEN a new read omits policy, the server SHALL apply `refresh_if_needed`; WHEN it specifies `cached`, the server SHALL capture the local view without import waiting and report `not_requested` as its refresh outcome. +2. <a name="3.2"></a>WHEN `refresh_if_needed` is selected and cloud sync is active, the server SHALL skip import waiting if evidence is recent; otherwise it SHALL attempt a supported refresh if available and wait for relevant completed import evidence for at most 2,000 ms within the remaining total budget. +3. <a name="3.3"></a>WHEN refresh finishes, times out, is unsupported, or fails, the server SHALL distinguish `import_observed`, `timeout`, `unavailable`, or `failed` respectively from a skipped `recent_import` outcome, and SHALL return complete selected local data with freshness metadata if these remain obtainable within the total budget. +4. <a name="3.4"></a>WHEN the running store's cloud sync is inactive, the server SHALL skip import waiting under either policy, report `syncState: inactive`, `assessment: not_applicable`, `lastImportedAt: null`, and `refreshOutcome: not_requested`, and preserve the existing local read selection and saved-write visibility semantics. +5. <a name="3.5"></a>WHEN a caller supplies an unsupported or incorrectly typed policy, the server SHALL return the existing invalid-input category within the total budget without changing stored data. +6. <a name="3.6"></a>WHEN refresh outcomes compete, a relevant successful import visible to capture SHALL yield `import_observed`; otherwise an observed failed import SHALL yield `failed`, an available trigger or relevant in-flight import that does not complete within the wait SHALL yield `timeout`, and absence of both a supported trigger and relevant in-flight import SHALL yield `unavailable`. Observation SHALL cover the refresh decision through the end of the bounded wait, including a relevant import already in flight at that decision; relevance SHALL require the running store and applicability to the selected capture. The wait SHALL be shortened to the remaining total budget, and zero remaining wait SHALL yield `timeout` if a trigger or relevant in-flight import exists, otherwise `unavailable`; IF no complete local result can then be returned within the total deadline, `READ_TIMEOUT` SHALL take precedence. ++### 4. Complete results and distinguishable failure++**User Story:** As an agent, I want storage errors distinguished from freshness limits, so that I do not interpret a failed read as an empty project or task list.++**Acceptance Criteria:**++1. <a name="4.1"></a>IF any local fetch or serialization required by the selected result fails, the server SHALL return the stable machine-readable category `storage_failure` or `serialization_failure` respectively, distinguishable from `incoherent_capture`, `READ_TIMEOUT`, `READ_BUSY`, input/cursor/capacity errors, and a successful read with stale or unknown freshness; caller documentation SHALL map these categories to the retained or extended tool error codes. +2. <a name="4.2"></a>IF the selected result is incomplete, the server SHALL NOT present omitted related data, empty fallback data, or partial totals as a complete success; existing per-identifier not-found/ambiguous outcomes in batch task queries SHALL remain valid complete results. +3. <a name="4.3"></a>WHEN no capture completes, the response SHALL NOT fabricate an `asOf`, import timestamp, or successful snapshot identity; a legitimate empty success SHALL retain the same metadata contract as a populated result. +4. <a name="4.4"></a>WHEN covered reads use these policies, the server SHALL preserve existing write tool inputs, outputs, side effects, and error behavior. ++### 5. Frozen pages and shared contract semantics++**User Story:** As an agent, I want later pages to describe the original view, so that pagination does not make old data appear newly captured.++**Acceptance Criteria:**++1. <a name="5.1"></a>WHEN a cursor continues a captured task query, every page SHALL retain the original `snapshotId`, `asOf`, freshness assessment, import evidence, and capture policy/outcome even if imports or local edits occur between page requests. +2. <a name="5.2"></a>WHEN a valid cursor is retried, the server SHALL return the same retained page and captured metadata without a new import wait or local data capture; cursor validity and snapshot expiry SHALL preserve existing behavior. +3. <a name="5.3"></a>The shared capture metadata contract SHALL define the same meanings for covered read results and T2382 summary results; timestamps alone SHALL NOT establish that independently captured results share a view, and `asOf` SHALL remain distinct from completion-window endpoints. WHERE T2382 exposes the same reusable captured view, its query/summary results SHALL preserve that view's identical snapshot identity, capture time, and import evidence; T-63 SHALL NOT substitute unrelated capture identities for that view. +4. <a name="5.4"></a>WHEN a cursor continuation omits policy, it SHALL preserve the retained capture policy; WHEN it explicitly supplies that same policy, it SHALL return the same page; WHEN it supplies a different policy, it SHALL return invalid input without relabeling the view. Existing selector/argument validation SHALL retain its precedence; malformed policy SHALL be rejected before cursor lookup, and a well-typed conflicting policy SHALL be rejected only after resolving a valid cursor. ++### 6. Caller guidance and validation++**User Story:** As an agent, I want documented limits and retry rules, so that I can recover without turning a freshness caveat into a retry loop.++**Acceptance Criteria:**++1. <a name="6.1"></a>The caller documentation SHALL define metadata meanings, error categories, policy defaults, the server deadline boundary, import-evidence limitations, and retry rules: a new query creates a new capture; a cursor retry retains its capture; timeout/busy retries use backoff; no read performs an unbounded automatic retry. +2. <a name="6.2"></a>Validation SHALL demonstrate normal and empty reads, single/batch/list/cursor task reads, scoped milestone/project reads, inactive sync, unknown/delayed/failed imports, unavailable refresh, slow/failing local reads including a blocked MainActor, late completion, retained admission slots after timeout, and read-only/mixed batch behavior returning the required data/error and metadata within the defined budgets. +3. <a name="6.3"></a>WHEN read latency is inspected, server diagnostics SHALL identify the request, outcome, and measured elapsed times for queueing, refresh waiting, capture/fetch, transformation, serialization, and batch aggregation; WHEN work completes after its caller timeout, its completion/discard SHALL be correlatable with the original request. The validation evidence SHALL use those measurements to distinguish slow stages without attributing unexplained delay to CloudKit.
diff --git a/specs/bounded-read-freshness/routing-integration-plan.md b/specs/bounded-read-freshness/routing-integration-plan.mdnew file mode 100644index 0000000..2657f65--- /dev/null+++ b/specs/bounded-read-freshness/routing-integration-plan.md@@ -0,0 +1,74 @@+# Task 12 remainder and staged task 13 integration++Prepared against `54bfe98`, with capability/server RED evidence on `e3812b1`. The parent authorized Stage A source implementation after actual routing/capability RED; no new product approval or T2382 delivery is required for generic routing repair. This document does not claim task 13 GREEN. Actual single-router RED remains `099415e`: four device executions failed after successful compilation. Capability RED ran three failing executions; stopped-server baseline ran eight executions with three failures and five preservation controls passing. Both exclusive test slots were released after drain. Further app jobs require a new grant.++## Stage A: independent bounded routing and lifecycle++The three ordinary covered reads can be integrated without waiting for portfolio modules. Inject one process-lifetime coordinator and its publication domain into `MCPServer`, retaining the existing desired-state reconciliation, graceful `ServiceGroup` shutdown, listener task completion fence and stale-listener generation check. A replacement listener reuses that coordinator. Stop closes read admission and selects terminal fallbacks before listener teardown; generation changes never clear unfinished physical permits. A stale listener callback must not stop a newer generation. Repeated starts on the active port must not invalidate current operations.++The single-read transport seam records the original decoded admission instant and uses an immutable availability/classification snapshot. Prepare timeout, busy and publication-error RPC bytes with the actual request ID outside the common domain. Admit before tool-domain validation or any MainActor hop. The worker calls saved-read preparation, wraps the authoritative tool fragment in the complete RPC response, and offers those final bytes and private publication candidates together. No serialization follows successful publication. Writes and maintenance retain their existing dispatch and receipts; neither receives read freshness metadata.++Implement the already declared `MCPReadCapturedPreparing` on the existing service. Begin the observation window before the policy decision and hold it through saved capture, metadata freeze, async DTO transformation and private reservation preparation. Preserve the operation's original remaining budget. Capture stays synchronous on MainActor inside its history/generation fence; no models escape. Production missing applicability/visibility proof remains unknown/null with refresh unavailable. Retained replay bypasses this fresh-capture path.++The concrete server injection seam should pass the same coordinator to construction and every router generation; constructing a new coordinator in `makeRouter` or `launchServer` would lose the physical-work bound. Existing listener fences remain authoritative for socket release.++Two small interfaces were confirmed as routine task 13 integration choices; neither has runtime binding yet:++- Preallocated operation UUID accepted by single-read admission, with a default UUID for existing callers, to encode machine fallback correlation before admission. Reject an already-live UUID without replacing its entry. The actual JSON-RPC ID remains a separate value.+- An operation-specific physical-completion receipt for deterministic tests. It completes only after worker finalization and private publication cleanup, resumes outside the common lock, and does not turn terminal selection into permit release. Completed-receipt storage must be bounded or caller-owned.++`MCPReadAdmission(operationID:physicalCompletion:)` now declares those caller-owned values. Capability RED at `e3812b1` compiled and ran three failing methods; final acceptance must remove its test-only baseline adapter and call the real coordinator admission overload directly. The callback may run after `unfinishedCount` reaches zero, so tests await both independently with bounded waits. There is no completed-receipt registry.++### Exact direct-coordinator lifecycle fixture plan++Use the existing `MCPReadCoordinator` directly, not a new runtime wrapper. Proposed task 13 plumbing is `MCPServer(toolHandler:readCoordinator:)` and `MCPServer.makeRouter(handler:readCoordinator:)`, both retaining the same injected instance. `TransitApp` constructs one coordinator/domain/launch-fixed monitor/service. Existing `DesiredState`, `serverGeneration`, `ActiveServer`, `ServiceGroup.triggerGracefulShutdown()` and listener-task completion remain responsible for listener reconciliation/socket release.++The additional fixture file is `MCPReadServerCoordinatorLifecycleTests.swift`; it is not supplied or run yet because the injection plumbing is absent. Use existing loopback-port/lifecycle test helpers rather than replacing shutdown fences:++1. Start the actual listener with the injected coordinator and matching ordinary-store domain. Start eight direct admitted workers with unique preallocated IDs and caller-owned physical receipts; each signals start and awaits a release latch. Stop the server, await all eight terminal fallbacks, restart the same listener port, and assert a new operation is busy while old workers remain physical. Release the old latch, await each receipt plus count drain, then assert new-generation work succeeds. Also assert the server/router retained the same coordinator reference, rather than constructing a replacement.+2. Observe the actual first listener generation, restart, then invoke `listenerDidExit` with that recorded old generation. Assert the replacement remains running with admission open; admit and finish current work. The existing unmatched `-1` callback fixture is only a preservation control and cannot satisfy this assertion. A narrow read-only generation inspection seam is sufficient if needed; do not replace lifecycle state or add an independent generation owner.+3. Prepare an ordinary private cursor candidate with the operation ID, signal its prepared state and latch before full RPC encoding. Stop selects preencoded ID-correct fallback; release late preparation and assert candidate never becomes visible, private charge clears exactly once, and the physical receipt follows cleanup. Success counterpart must preserve exact frozen metadata bytes and actual escaped RPC ID in the complete selected response before the common gate.+4. Force outer encoding failure after private reservation ownership exists. Invoke the dispatcher's actual failure-cleanup path, assert its complete preencoded failure has the original RPC ID, zero visible/pending retained charge, and one physical receipt. A fixture encoder may inject this failure; it must not implement a different publication gate or duplicate T2382 retention logic.++These tests must call the actual injected server and real admission overload once implementation exists. An interface-only compile/capability RED is labeled separately; it cannot substitute compiled behavioral lifecycle or final helper acceptance. No sockets/tests are launched without the exclusive slot.++## Remaining task 12 fixtures++These tests use the real coordinator, domain and ordinary retention participant. A fixture helper implements only the tool-level contract; it does not copy portfolio aggregation or reusable-store logic.++| Fixture | Forced ordering and assertion | Acceptance limit |+| --- | --- | --- |+| Captured preparation capsule | Saved fixture with pending UI edit; transform receives one saved view and the exact frozen metadata bytes; its returned fragment has no originating RPC ID. Hold transform while checking original remaining budget declines. | Requires concrete generic preparer for GREEN; fixture helper cannot establish import proof. |+| Private publication and outer encoding | Reserve an ordinary cursor root, latch before full RPC preparation, assert zero visible roots, then encode an escaped/long actual ID and offer. Success bytes reference only the now-published root and contain the original metadata fragment verbatim. | Establishes common foundation boundary, not modern structured encoding. |+| Failure after private preparation | Force outer encoding/preparation failure after reservation creation. Return a preencoded ID-correct failure; no cursor becomes visible, pending accounting clears exactly once, physical receipt completes afterward. | Requires a dispatcher failure/cleanup seam; must not leave unattached reservations. |+| Stop/restart with unfinished work | Latch a prepared worker, stop and restart the same server/coordinator lifetime. Old caller receives fallback; a full set of old physical workers keeps a new caller busy. Release workers, await physical receipts, then admit new-generation work. | Server lifecycle injection needed; existing graceful listener tests still run. |+| Stale listener completion | Replace listener generation, deliver the old completion callback while current read is pending, assert current admission remains open and current result can publish. | Actual server lifecycle acceptance, not standalone coordinator stop/start. |+| Helper rejection/scope | Test helper receives the capsule's same view identity/evidence and exact metadata; typed outside-scope request fails without publishing; selected valid request returns tool-level bytes and private candidates. | Fixture contract only until real T2382 handlers run. |+| Read/write preservation | Separate server/read fixtures exercise existing mutation safety input/output/receipt/revision behavior and maintenance dispatch. Assert no read metadata is added to these responses. | Do not edit T2384 coordinator or its tests. |++Use latches and physical-completion receipts rather than arbitrary cleanup sleeps. Keep each expected compile failure distinct from a compiled behavioral RED. The next focused command and exact suite list will be reported before requesting the exclusive app slot. During the coordinated quiet measurement window, no build, test, typecheck, lint or review CLI runs.++## Stage B: actual T2382 modules++After clean module delivery, wire the confirmed signatures returning `MCPPreparedToolRead`:++```swift+handlePortfolioSummary(request: MCPPortfolioSummaryRequest,+ view: CapturedReadView,+ operation: MCPReadOperation) throws -> MCPPreparedToolRead+handleSnapshotTaskQuery(request: MCPSnapshotTaskQueryRequest,+ view: CapturedReadView,+ operation: MCPReadOperation) throws -> MCPPreparedToolRead+```++T2382 supplies requests, definitions/descriptors, aggregation, projection, reusable retention and lifecycle hooks. T63 supplies common construction, generic policy-bound preparation, shared registration and outer encoding. Fresh helpers consume the same capsule and original frozen metadata; snapshot replay uses retained view/policy/fragments without recapture or import wait. Do not add RPC IDs to helper interfaces.++Final actual-module assertions include portfolio read classification and descriptor registration, `query_tasks` snapshot dispatch, declared physical-scope rejection, retained metadata/policy/expiry replay, actual reusable/ordinary participant coalescing and all-or-none publication, and lifecycle invalidation. Fixture GREEN cannot satisfy these assertions. Missing module delivery blocks Stage B acceptance only, not Stage A generic routing repair.++## Stage C: modern wire ownership and final acceptance++After a stable bounded integration revision and explicit shared-file transfer, T2383 is the sole modern adapter writer. Modern protocol/header/envelope/availability validation precedes read admission; tool-domain validation stays bounded. Its frozen result encoder preserves original text, `isError`, source/presentation and exact `_meta`, then adds the current RPC ID before the same terminal gate. Expanded fragments and retained backing are charged without duplicate ownership.++Modern production rejects arrays. Mixed/all-notification legacy task text is superseded by the approved modern protocol; existing batch coordinator fixtures remain historical component evidence. T63 adds no dual-era production path. Modern discovery/subscriptions, array rejection and final wire contract are T2383 acceptance. Final combined bounded routing and actual-module tests run after that adapter delivery.++Task 13 is complete only after the required actual-module and final adapter acceptance. Intermediate Stage A GREEN must be labeled accordingly. Ownership remains the committed `integration-ownership.md`; this plan changes no file owner and authorizes no source handoff.
diff --git a/specs/bounded-read-freshness/scope-assessment.md b/specs/bounded-read-freshness/scope-assessment.mdnew file mode 100644index 0000000..81b863f--- /dev/null+++ b/specs/bounded-read-freshness/scope-assessment.md@@ -0,0 +1,56 @@+# T-63 — Bounded reads and explicit freshness++Review state: scope, full spec type, and name approved by the user in the parent conversation on 2026-10-03. Requirements, design, tasks, and implementation are not approved.++## Scope and workflow++Transit MCP reads can return an old local view without disclosing its limitations. The live ticket also records 30–50 second client timeouts whose cause remains unknown. This feature must bound completion across the whole server read path and expose honest local capture and import evidence.++The requested full spec workflow is appropriate: this changes a public MCP response contract used by other agents, and both the default refresh policy and compatibility envelope need user decisions. The approach to bounding synchronous SwiftData reads also needs design work. The user approved the full spec route and feature name `bounded-read-freshness`.++## Evidence from this checkout++- Canonical repository: `/Users/arjen/projects/personal/transit`, origin `git@github.com:ArjenSchwarz/transit.git`.+- Base: `0db453bba3b1da3b8958723947dc41c165ecf0dd`; local main and origin/main agree. It contains merged T2379, bounded batch task queries.+- T2380: separate branch `T-2380/mcp-write-safety`, head `ef29b2baabbaa8a4886e63a03a267d6d7db86519`. T2379 is not an ancestor of that branch. This work does not change it.+- No repository AGENTS.md or .agents directory found. Repository CLAUDE.md and the actual local Transit, creating-spec, and requirements skills were read.+- `MCPToolHandler` is MainActor isolated. Task, milestone, and project fetches are synchronous; reads currently share UI services and context.+- `MCPTaskQuerySnapshotStore` retains serialized cursor pages, bounded by eight snapshots and 16 MiB. The 300-second snapshot expiry is a retention lifetime, not a response deadline.+- Cursor continuation returns the retained serialized page without a new store fetch. This behavior must preserve the original capture time and import evidence.+- `SyncManager.isCloudSyncActive` describes launch-fixed store sync mode; the preference may differ until restart. Freshness must use the active mode.+- Existing heartbeat writes do not establish that remote changes have arrived. No import tracking or documented force-pull facility was established in this scope inspection.++## Proposed requirements to develop after the first gate++1. Cover `query_tasks`, `query_milestones`, and `get_projects`, including single/batch task reads and cursor continuations. Agree whether optional maintenance reads belong in this change.+2. Bound read admission/queueing, store capture, optional import wait, transformation, and response serialization under one elapsed-time budget; return a defined timeout if no result can be produced in time.+3. Preserve successful local results even when remote freshness is unknown, stale, or a refresh wait expires; disclose those states separately from storage failure.+4. Describe the immutable local view with `asOf`, a snapshot identity, active sync mode, nullable last successful import time, and the scope of that evidence.+5. Preserve the original metadata on all retained cursor pages. Do not relabel old pages after an import or a later page request.+6. When active sync is disabled, skip import waiting and retain existing local data semantics. Additive metadata remains a proposed compatibility change for approval.+7. Preserve write behavior and existing explicit store failure results. Do not turn a failing fetch into an empty success.+8. Document retry behavior and exercise unknown/delayed/failed imports, inactive sync, slow/failing fetches, concurrent requests, and snapshot pagination.++## Behavioral decision record++- Full spec route and name: approved.+- Compatibility: approved preserving current text data payloads with additive outer MCP result metadata, including array/empty results.+- Default policy: approved `refresh_if_needed` with optional `cached`, and at most two seconds of freshness waiting. A 30-second recent-import threshold remains proposed.+- Total server budget: approved five seconds including queueing/capture/encoding; individual and read-only batch responses meet it, while mixed write batches may delay combined delivery after bounded read result production.+- Scope: approved deferring a separate refresh tool and maintenance reads.+- T2382 reconciliation: approved using the same saved snapshot for summaries and detailed task queries. Parent assigned T2382 external API/lifecycle and T-63 compatible shared capture/freshness.+- Pending requirements approval: 30-second threshold, eight unfinished read admission bound, latency diagnostics, and final EARS document.++## Technical risk for design++A timeout task on MainActor cannot run while a synchronous fetch blocks that actor. A structured task group can also wait for a non-cooperative operation even after cancellation. The design must show an independent response deadline, immutable Sendable capture boundaries, bounded pending work, and late-result disposal. It must not move live SwiftData models across actors, create an unlimited queue of abandoned fetches, or claim a stronger timeout guarantee than the runtime can support.++## Capabilities++The session uses workspace-write with automatic approval review. Supported per-command `require_escalated` was successfully used to create the dedicated branch/worktree because Git administration is outside the writable workspace. No permission settings were changed. Xcode 27.0 (27A266a) is installed; no Xcode MCP tools are exposed in this session. `/Users/arjen/bin/send-md-to-phone` is available and copies Markdown to `iphone181` through Tailscale; it does not generate web links. No heavy build or simulator work was run. No `memory_summary.md` was found in the local Codex file inventory.++## Approval sequence++Scope/name approval is now recorded and the ticket is in `spec`. The user also approved additive metadata, refresh_if_needed default, the five-second total and two-second refresh limits, and deferring the separate refresh tool and maintenance reads. The local creating-spec skill still requires requirements approval before design, design approval before tasks, and tasks approval before implementation. Remaining requirements choices stay pending and are surfaced through the parent.++Implementation and pre-push-review, including its Pulsar step, are later phases. Coordinate shared MCP wiring and any heavy tests through the parent. No merge or deployment is authorized.
diff --git a/specs/bounded-read-freshness/tasks-architecture-review.md b/specs/bounded-read-freshness/tasks-architecture-review.mdnew file mode 100644index 0000000..8a01c42--- /dev/null+++ b/specs/bounded-read-freshness/tasks-architecture-review.md@@ -0,0 +1,38 @@+# T-63 tasks review — architecture and sequencing++Reviewed `tasks.md` against the actual local `starwave-tasks/SKILL.md`, approved requirements/design and recorded design approval `Sentinel_541ceb19e7c8819193d04d23c5263041`. This is planning review only. No implementation, external calls, builds, tests, commits or changes to the task/design/source files were performed.++## Conclusion++No planning blocker found. The 16 flat tasks form meaningful coding/test units, preserve single-writer integration ownership, and defer production work until the task gate. The explicit T2382 delivery gate must remain enforced during implementation; fixture-only integration is not acceptance.++## Skill and dependency checks++- Ran `rune list specs/bounded-read-freshness/tasks.md`: all 16 tasks render as pending with stream and valid dependency references; no parsing warnings appeared. The rendered dependency graph is acyclic and every task joins the implementation chain.+- Adjacent red/green pairs are 2–3, 4–5, 6–7, 8–9, 10–11, 12–13 and 14–15. Task 1 explicitly limits itself to types/interfaces and injection seams, qualifying for the skill exemption. Task 16 is testing only; behavioral repairs return to the owning pair rather than bypassing red tests.+- Stream 2's evidence monitor/policy files and test doubles can run independently after shared contracts. Capture, coordinator, publication and shared routing stay in stream 1. The plan does not invent separate streams for edits to the same shared files; heavy test execution remains serialized even when file work is parallel.+- Risk verification is early: history feasibility is tasks 2–3 before publication/projection; independent deadline feasibility is tasks 6–7 before publication/full routing; import matching uses injected proof and the approved unknown fallback in tasks 4–5, with actual capture integration waiting for both streams in task 10. Final integrated task 16 checks the live/unsupported outcomes without claiming prototypes prove them.+- All 29 granular acceptance criteria appear in the task references. Requirement 6.1 has executable caller examples and code-level advertised limits in tasks 14–15; the ancillary caller guide remains an explicit delivery obligation outside the skill's coding-only checklist.++## Architecture and integration assessment++Task 1 aligns the dedicated branch with merged foundation `201205bd4e786c7f152d8f99006b37da7da888c7` while preserving spec commits and other worktrees. Tasks 3 and 10–11 preserve the merged canonical comment-covered r1, saved-only capture and ordinary UUID selector behavior. Scope completeness and identity/comment closure are enforced at construction and consumption, with no totals expansion by attribution-only closure.++Tasks 8–9 directly cover the peer review's same-store lost-update correction: aggregate immutable candidates, atomic reservation transfer, validate-all-before-commit, one store swap and preencoded rejection selection. These are substantial coherent units, not file/stub/wiring fragments. The ordinary cursor store migrates under T-63 ownership; T2382's reusable store stays with its worker.++Tasks 12–13 explicitly gate actual shared wiring on parent-delivered T2382 helper/schema/store modules. T-63 remains the only editor for routing, handler/common schema/types and app construction. The external dependency cannot be represented as a local completed task: task 13 must remain blocked in practice until those actual approved modules are available and their contract tests pass. The described parent-selected clean dependency commit prevents duplicate implementation or foreign-worktree edits.++Task 16 requires Xcode27, parent coordination for an exclusive heavy build/simulator slot, serialized SwiftData suites and the Xcode MCP fallback only when available. The later full pre-push-review/Pulsar workflow is acknowledged separately and does not authorize merge/deployment or an otherwise unauthorized publication.++## Concrete execution refinements++1. Keep task 1 genuinely interface-only: metadata encoding behavior or publication behavior belongs in its corresponding tested pair; interface exemption must not absorb runtime code.+2. Preserve task 2's signed-store harness as executable observation/assertion code. A missing import or inability to prove history applicability must produce the recorded unsupported/inconclusive result, not a passing claim of remote coherence. If it requires human remote edits or signing changes, surface that actual prerequisite to the parent before dependent verification.+3. Record the accepted T2382 dependency commit at task 13 and run against actual helpers before marking it complete. Avoid a mutually blocking handoff: T-63 publishes contracts first; T2382 builds separate modules from those contracts; T-63 performs common-file integration last.+4. Treat the caller guide and full pre-push-review as ancillary completion obligations, despite their intentional absence as noncoding checklist tasks. Task 16 alone cannot declare complete feature delivery while those obligations remain outstanding.++These are execution clarifications rather than required changes to the approved design or new implementation scope. The parent should present the task packet for its separate explicit approval and stop at that gate.++## Foundation handoff revalidation++Re-read the clarified tasks 3, 7, 9 and 12. The two-way dependency is now explicit and acyclic: actual SwiftData saved/canonical capture verification (3), actual Hummingbird router/encoded-response verification using fixture read work (7), and shared publication/ordinary-retention verification (9) need no T2382 modules. Their verified local foundation commit and evidence go through the parent to T2382, which can implement its separate modules while T-63 advances the later local work. Actual helper integration at 13 and integrated acceptance at 16 still require those modules. The handoff authorizes no remote publication. This clarification adequately resolves the cross-ticket circular-gate concern; no new planning blocker found.
diff --git a/specs/bounded-read-freshness/tasks-correctness-review.md b/specs/bounded-read-freshness/tasks-correctness-review.mdnew file mode 100644index 0000000..753be72--- /dev/null+++ b/specs/bounded-read-freshness/tasks-correctness-review.md@@ -0,0 +1,33 @@+# T-63 task-plan correctness review++Reviewed `tasks.md` against approved requirements/design, the decision log, and the actual local `starwave-tasks/SKILL.md`. This is planning review only; it does not approve tasks or authorize implementation.++## Verdict and checks++No task-plan blocker identified. The sixteen flat tasks form a coherent incremental implementation chain. Seven behavior-changing green tasks (3, 5, 7, 9, 11, 13, 15) each immediately follow their corresponding red test task and depend on it. Task 1 qualifies for the skill's types/interfaces exemption; task 16 is testing-only. No unnecessary setup/function/wiring fragmentation is present beyond the required red/green pairs.++`rune list specs/bounded-read-freshness/tasks.md` succeeded without parsing warnings: sixteen level-one tasks, streams 1/2, all dependency references resolved. The dependency graph is acyclic: every dependency points to an earlier task. Automated anchor comparison found all 29 acceptance criteria referenced, with no missing or nonexistent IDs. This is syntactic coverage; the behavioral details also cover the important cases below.++## Correctness coverage++- **Saved-only capture:** tasks 2–3 cover saved visibility, excluded pending edits, fenced selector resolution, relationship/physical identity, empty domain versus empty selection, unavailable/purged history, incomplete related evidence, canonical comment-covered r1, and fail-closed coherence. Their early live/store feasibility gate is explicit. Downstream capture/projection work depends on task 3.+- **Freshness:** tasks 4–5 cover positive applicability, queued observations, preserved successful import evidence, unrelated/failed/in-flight events, monotonic recency and inconsistent clocks, default/cached/inactive policy, remaining wait budget, and outcome precedence. These can proceed independently against injected contracts; task 10 joins verified capture and monitor work.+- **Deadline/physical bound:** tasks 6–7 include admission before fallback preparation, real router-return availability, blocked MainActor, large aggregate serialization, long IDs/body ceiling, notifications, eight lingering workers/ninth busy, stop/restart and generated single-winner/permit sequences. Publication/routing work explicitly waits for this early verification outcome.+- **Atomic publication:** tasks 8–9 cover pending plus visible capacity, stale CAS, pre-encoded rejection, same-store aggregate changes, child reservation transfer, validate-all-before-any-commit, one swap per store, collision/routing, exactly-once discard and absence of unpublished IDs in selected success bytes. These directly cover the design-review lost-update correction.+- **Frozen pages/compatibility:** tasks 10–13 cover existing selection/order/errors, unchanged text shapes, metadata identity and precision, no cursor refetch/refresh, canonical r1 preservation and no-comment summary parity, actual T2382 helper integration, read-only/mixed batch behavior, write/fallback/maintenance regressions.+- **Diagnostics/caller contract:** tasks 14–15 test slow logging and late correlation as executable code, validate caller examples and update code-level tool descriptions. The caller guide remains a stated ancillary delivery requirement, correctly outside the skill's coding-only checklist; it must still be delivered to satisfy requirement 6.1.++The three design risk entries map to tasks 2–3 (capture/import-history proof), 4–5 plus integration (event applicability), and 6–7 (transport scheduling/encoding). Dependent work is gated by their green verification outcomes. The second stream owns separate import-monitor code and test doubles, so parallel work is meaningful; heavy signed-store/build/simulator checks remain coordinated through the parent.++T-63/T2382 ownership is consistent throughout. Shared types and publication hooks can be delivered before the final integration task; task 13 explicitly waits for parent-delivered T2382 modules and task 12 cannot pass integrated acceptance on fixtures alone. No portfolio aggregation, separately owned reusable-store implementation, refresh force-pull, persisted schema change, merge, or deployment is introduced.++## Refinements for execution++These are test-case clarifications, not changes needed to the approved design or blockers to task approval:++1. In task 10, explicitly enumerate omitted cursor policy and explicitly matching cursor policy as successful replay cases alongside malformed/conflicting policy. Both must retain the same bytes and bypass new capture/wait.+2. In tasks 2–3, distinguish an unavailable live signed-store test environment from evidence that the history/import invariant holds. Record unavailable/unsupported evidence and exercise the documented `incoherent_capture`/unknown outcomes; do not count a skipped live test as positive verification. If actual signing/account access requires human setup, capture that concrete prerequisite before dependent testing rather than inventing it now.+3. In tasks 8–9, assert that aggregate reservation transfer changes ownership without changing the total charged capacity, then prove rollback restores the original charge exactly once. The existing details already require this behavior; make the assertion numerical in tests.+4. Preserve the requirement-1.6 stop interpretation from the approved design: stop invalidates terminal/publication state, while unfinished physical work remains charged until it actually completes. The task plan correctly prohibits generation changes from clearing physical counts.++The user task approval gate remains outstanding. No implementation, builds, external calls, or commits were performed in this review.
diff --git a/specs/bounded-read-freshness/tasks-review.md b/specs/bounded-read-freshness/tasks-review.mdnew file mode 100644index 0000000..e4e4e02--- /dev/null+++ b/specs/bounded-read-freshness/tasks-review.md@@ -0,0 +1,33 @@+# T-63 task approval packet++Approval received: both task lists approved by user (Sentinel_c2e9343628948191b921868234aaf409). The review/gate text below records the prepared packet; implementation is now authorized.++The user approved requirements and design, including final T-63 `5639c40` / T2382 `3932e88` scope/publication contracts (Sentinel_541ceb19e7c8819193d04d23c5263041). This packet proposes implementation tasks; none have started. The dedicated branch remains spec-only and must align to merged main `201205bd4e786c7f152d8f99006b37da7da888c7` before code changes.++## Self-check and independent review++Created/updated tasks through the actual local rune skill and CLI. `rune list` renders 16 pending level-one tasks with two streams and valid dependencies, without parse warnings. All 29 acceptance criteria are referenced; the dependency graph has no cycles; every task connects to final validation. Seven adjacent red/green pairs cover capture, import policy, deadline, publication, projection, routing and diagnostics. Task 1 is types/interfaces-only; task 16 tests the integrated result. No decorative phases or trivial setup fragments were added.++The three approved design risks have early coded verification: saved/history/import-visible capture in tasks 2–3, evidence applicability/unknown fallback in 4–5, and actual router/encoding deadline mechanics in 6–7. Dependent publication/projection/routing waits for those outcomes. A failed history mechanism cannot be silently replaced: use approved incoherent_capture failure or return a changed mechanism for design approval. Unavailable live evidence is recorded honestly rather than counted as positive proof.++Independent correctness and architecture reviewers found no planning blockers. Adopted refinements explicitly test matching/omitted cursor policy, numerical reservation charge transfer/rollback, and unsupported live evidence. Architecture revalidated the final two-way handoff without a cycle. See tasks-correctness-review.md and tasks-architecture-review.md.++## Cross-ticket handoff and ownership++1. T-63 defines common types, then proves saved capture/canonical r1 (task 3), actual Hummingbird transport mechanics (task 7), and shared publication (task 9) with fixture adapters/participants. These have no T2382 module dependency.+2. Parent receives a verified local foundation commit/interface/test evidence after those gates. T2382 consumes it and implements its separate portfolio aggregation, reusable store, snapshot query and schema modules while T-63 completes the remaining covered read paths. The local handoff does not imply a remote push or publication.+3. Actual cross-ticket modules are required for task 13 integration and task 16 acceptance. Fixture-only tests cannot mark either complete. Parent records and chooses the clean dependency commit; no foreign-worktree edits or duplicated modules.++T-63 alone edits shared server routing/lifecycle, handler init/common dispatch/read-only registration, existing/common schema wiring, metadata DTOs and app construction. T2382 retains its separate helper/store/API ownership. Saved-only capture, typed declared scope plus closure, canonical T2380 r1, frozen metadata and coalesced same-store publication remain unchanged.++Import monitor files/test doubles are the only separate T-63 stream. Parallel code work does not authorize concurrent heavy Xcode/simulator execution: parent allocates exclusive heavy gates, SwiftData suites serialize, and Xcode27 is mandatory. Use Xcode MCP on Makefile failure when available; an unavailable capability must be reported, never replaced by a downgrade.++## Ancillary completion obligations++The local tasks skill excludes noncoding documentation/publication work from its checklist. Requirement 6.1 still requires an updated caller guide based on the executable examples in tasks 14–15: metadata, error mapping, default/cached policies, deadline boundary, import limitations, new-query versus cursor replay, and bounded backoff. Deliver that guide under the later implementation workflow before claiming feature completion.++The user's full pre-push-review skill, including Pulsar publication, is also a later mandatory workflow. Inspect its actual instructions then; ask the parent before any otherwise unauthorized publishing action. Frequent local commits remain authorized. No merge or deployment is authorized. No new manual prerequisite is presently known; if signing/account setup is actually needed for live evidence, surface the concrete prerequisite to parent before dependent testing.++## Next gate++Do the tasks look good? Surface this question in the parent conversation and wait for explicit task-list approval. Do not start production implementation, mark the ticket ready, or update specs overview before this gate. After approval, complete the remaining actual creating-spec steps, honoring the already approved dedicated branch and preserving all other work.
diff --git a/specs/bounded-read-freshness/tasks.md b/specs/bounded-read-freshness/tasks.mdnew file mode 100644index 0000000..3482942--- /dev/null+++ b/specs/bounded-read-freshness/tasks.md@@ -0,0 +1,172 @@+---+references:+ - specs/bounded-read-freshness/requirements.md+ - specs/bounded-read-freshness/design.md+ - specs/bounded-read-freshness/decision_log.md+---+# T-63 bounded read freshness implementation++- [x] 1. Define shared read contracts and injection seams on the merged foundation <!-- id:vh146y0 -->+ - Types/interfaces-only exemption. Before these edits, align only this clean dedicated branch to merged foundation 201205bd4e786c7f152d8f99006b37da7da888c7; preserve all other worktrees and the approved spec commits. Do not modify T2380.+ - Create macOS-gated explicitly nonisolated Sendable DTO/protocol definitions in Transit/Transit/MCP/Reads and optional MCPToolResult metadata. Define typed ReadCaptureScope, CaptureCompleteness, LocalRecordKey, CapturedReadView, MCPRetainedViewSource, MCPPreparedPublication validation/commit/discard, PreparedReadResult and PreencodedPublicationErrors.+ - T-63 alone owns MCPServer, shared handler init/dispatch/readOnlyToolNames, existing/common schema wiring and MCPTypes. Confirm these interfaces with T2382; it supplies separate summary/query/schema/store modules. No portfolio aggregation or reusable lifecycle implementation here.+ - Stream: 1+ - Owner: t63-foundation-types+ - Requirements: [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.6](requirements.md#2.6), [5.3](requirements.md#5.3)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [x] 2. Red: add saved-capture and persistent-history feasibility tests <!-- id:vh146y1 -->+ - Add MCPReadCaptureBuilderTests using owning TestModelContainer fixtures and disposable on-disk CloudKit-free stores. Fail for missing fresh-context capture: saved writes visible, pending UI edits absent, project selector resolved inside fence, frozen relationships/physical keys, mixed save between fetches rejected.+ - Add history-fence tests for empty domain versus empty selection, purged/expired/unavailable history, mismatched store IDs and multi-entity saves; missing required comment/revision evidence fails rather than empty success.+ - Add a signed-store observation test harness for real CloudKit import/history visibility using existing configured storage without synthetic production writes. Record supported proof versus documented incoherent_capture outcome; do not claim the isolated local probe establishes remote coherence.+ - Blocked-by: vh146y0 (Define shared read contracts and injection seams on the merged foundation)+ - Stream: 1+ - Owner: t63-foundation-runtime+ - Requirements: [2.1](requirements.md#2.1), [2.6](requirements.md#2.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [5.3](requirements.md#5.3)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [x] 3. Green: implement and verify the fenced saved capture builder <!-- id:vh146y2 -->+ - Implement MCPReadCaptureBuilder and history fence: initial fresh-context latest history watermark, fresh autosave-disabled capture context, synchronous nonawaiting MainActor DTO copy, final fresh-context watermark and import generation check. Never save/rollback UI mainContext; no unbounded retries.+ - Validate complete declared portfolio/project scope plus identity/comment closure at construction and consumption; closure cannot expand totals/query scope. Preserve canonical MCPRecordSnapshot.task r1 with its authoritative UUID-based comment coverage before stripping output comments.+ - Run task 2 evidence with Xcode 27. Unsupported capture fencing fails incoherent_capture; unavailable import applicability stays unknown. If a different coherence mechanism is needed, stop dependent work and return that design change to parent. Dependent capture/projection tasks wait for this verified outcome.+ - Foundation risk gate A: establish saved capture/canonical revision behavior using actual SwiftData and merged MCPRecordSnapshot, with a minimal fixture adapter; no T2382 aggregation/store/helper code is required. Unknown/unavailable live evidence must be recorded honestly and use the approved fallback, not a fabricated proof.+ - Blocked-by: vh146y1 (Red: add saved-capture and persistent-history feasibility tests)+ - Stream: 1+ - Owner: t63-foundation-runtime+ - Requirements: [2.1](requirements.md#2.1), [2.6](requirements.md#2.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [5.3](requirements.md#5.3)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [x] 4. Red: add import-evidence and bounded-refresh policy tests <!-- id:vh146y3 -->+ - Add MCPImportEvidenceMonitorTests and MCPReadRefreshPolicyTests with injected clocks, event source, store matching and capture-applicability proof. Cover unrelated/setup/export, queued callbacks, in-flight success/failure, retained last success, future/inconsistent wall clocks and30-second boundary.+ - Fail for missing policy: cached/default/inactive, invalid enum/type precedence, recent-import skip, unsupported trigger/no in-flight immediate unavailable,two-second/remaining/zero wait, observed success>failed>timeout>unavailable and total timeout precedence.+ - Use synthetic evidence only in tests; production must never infer store match/import visibility from heartbeat, local save or notification arrival time.+ - Blocked-by: vh146y0 (Define shared read contracts and injection seams on the merged foundation)+ - Stream: 2+ - Owner: t63-import-runtime+ - Requirements: [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [x] 5. Green: implement import monitoring and the bounded refresh decision <!-- id:vh146y4 -->+ - Implement serialized non-MainActor MCPImportEvidenceMonitor callback-value copying and monotonic freshness classifier, plus refresh adapter explicitly unavailable for current SwiftData API. Use launch-fixed SyncManager mode; observe only positively relevant already-in-flight imports.+ - Wire capture-applicability seam to task 1 contracts and validate with task 4. Unknown/null evidence is the supported fallback when matching or visibility cannot be proved; inactive skips waiting. Stop observer cleanly without letting delayed callbacks relabel frozen capture metadata.+ - This module can run in parallel with tasks2–3 because it owns separate files/test doubles; live signed-store verification is coordinated through parent and final integration requires task 3.+ - Evidence: focused actual macOS app suites passed 14/14 (seven import-monitor and seven refresh-policy tests), including applicable A/unrelated B outcome preservation, success/failure priority, bounded observation windows, closed-window fail-closed behavior and observer restart epochs; fourteen standalone behavioral cases and focused default-isolation typecheck also passed. Production event-visible applicability remains unavailable and uses unknown/null plus unavailable refresh; shared capture/router integration is validated in later tasks.+ - Blocked-by: vh146y3 (Red: add import-evidence and bounded-refresh policy tests)+ - Stream: 2+ - Owner: t63-import-runtime+ - Requirements: [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [x] 6. Red: add deadline, physical permit and transport feasibility tests <!-- id:vh146y5 -->+ - Add MCPReadCoordinatorTests and a minimal router-return test harness using controllable physical workers. Require encoded timeout availability withinfive seconds duringsix-second MainActor blocking;eight lingering permits/ninth busy; single winner on cancellation/timeout/success/stop/restart.+ - Add seeded generated event-sequence tests for response count, generation, no late publication, unfinished count0–8 and atomic capture-to-assembly permit transfer. Distinguish notification/no-response from admission accounting.+ - Fail for missing independent timer/batch gate: long IDs and existing1 MiB body ceiling, many invalid/busy elements, prebuilt whole-array fallback and blocked large candidate serialization. Admission time precedes fallback preparation; measure router-return availability, not just timer firing.+ - Blocked-by: vh146y0 (Define shared read contracts and injection seams on the merged foundation)+ - Stream: 1+ - Owner: t63-foundation-runtime+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [6.2](requirements.md#6.2)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [x] 7. Green: implement independent deadline and physical admission coordination <!-- id:vh146y6 -->+ - Implement process-lifetime lock-based MCPReadCoordinator,8physical permits, generation/terminal gates, explicit@concurrent continuation path and strict zero-leeway timer at admission+4,850 ms. Route awaits response gate; worker finalizer alone releases its permit.+ - Implement whole read-only batch preencoded fallback, common admission timestamp, private candidate aggregation and retained assembly permit. Mixed delivery preserves write order/approved exception; expired undispatched reads must not start fetches.+ - Pass task 6 early transport/load harness before building dependent publication/routing. Scheduling evidence is empirical; tune internal cutoff earlier within approvedfive seconds if necessary without weakening the guarantee or resetting admission time. No structured cleanup await or MainActor timeout.+ - Foundation risk gate B: test the actual Hummingbird router/encoded-response adapter with fixture read work, blocked MainActor and large fallback preparation before T2382 modules exist. This independently proves transport mechanics; cross-ticket handlers are only a final acceptance dependency.+ - Blocked-by: vh146y5 (Red: add deadline, physical permit and transport feasibility tests)+ - Stream: 1+ - Owner: t63-foundation-runtime+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [6.2](requirements.md#6.2)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [x] 8. Red: add atomic publication and ordinary-cursor race tests <!-- id:vh146y7 -->+ - Add MCPReadPublicationDomainTests with test retention participants and ordinary MCPTaskQuerySnapshotStore. Cover pending+visible capacity, expiry between lookup/append, stale CAS=>READ_BUSY, collision allocation, v4 ordinary/v8 reusable routing after expiry.+ - Fail for missing aggregate transaction: two creates, two appends and create+append in the same store/batch, concurrent independent requests, child-to-aggregate reservation transfer without gap/double count; validate all candidates before any commit and swap each store once.+ - Generated timeout/stop/disconnect/success races require exactly-once discard, no IDs in chosen success without publication, no child publication before selected whole batch, preencoded rejection selection and large-copy/destruction outside domain lock.+ - Assert charged capacity numerically: child-to-aggregate transfer preserves the total charge, and each rollback returns the original charge exactly once.+ - Blocked-by: vh146y2 (Green: implement and verify the fenced saved capture builder), vh146y6 (Green: implement independent deadline and physical admission coordination)+ - Stream: 1+ - Owner: t63-publication-runtime+ - Requirements: [1.4](requirements.md#1.4), [1.6](requirements.md#1.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)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [x] 9. Green: implement shared publication domain and migrate ordinary retention <!-- id:vh146y8 -->+ - Implement common T63-owned MCPReadPublicationDomain and immutable prepared reservation/candidate machinery. Coalesce selected same-store changes outside gate, atomically transfer reservation ownership, validate complete selected set and terminal/generation/cutoff, then nonthrowing swaps plus encoded-response selection.+ - On validation rejection choose prepared matching error or whole-batch fallback; discard all unselected reservations exactly once. No fetch/encoding/callback/nestedstorelock/bulkindexcopy or final large destruction under gate.+ - Migrate ordinary task-query retention to the domain while preservingeight snapshots/16 MiB/300 seconds and original metadata bytes. T2382 owns its separate8views/16 MiB store and hooks; do not implement or edit that store independently. Run task 8.+ - Two-way handoff: after task 3 saved/canonical risk proof, task 7 transport risk proof and task 9 shared publication tests pass, give parent the verified local foundation commit and interface/test evidence for T2382 to consume. This handoff has NO T2382 module dependency. T2382 then implements separate modules while T63 continues tasks 10–15; actual cross-ticket acceptance waits until tasks 13/16. No remote push/publication is implied by this local handoff.+ - Blocked-by: vh146y7 (Red: add atomic publication and ordinary-cursor race tests)+ - Stream: 1+ - Owner: t63-publication-runtime+ - Requirements: [1.4](requirements.md#1.4), [1.6](requirements.md#1.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)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [x] 10. Red: add read projection, wire parity and frozen metadata tests <!-- id:vh146y9 -->+ - Add focused handler tests for task single/batch/list/cursor and project/milestone scoped/empty/detail reads. Assert existing text payload/filter/order/identifier-error precedence, metadata namespace/UTCms/asOf=assessedAt, full record canonical r1 with comments hidden, and summary no-comment-fetch parity.+ - Inject required fetch/history/comment/serialization failure, incomplete captures, unknown/stale/failing imports and valid empty success; assert machine categories and no fabricated identity/time.+ - Test frozen metadata byte-for-byte across imports/local edits/cursor retries, no new wait/refetch, malformed policy before lookup and typed conflict after valid lookup. Add shared-view source fixture proving identical snapshot identity/evidence and SNAPSHOT_INCOMPATIBLE outside declared scope.+ - Cursor policy fixtures explicitly cover omitted policy, an explicit matching retained policy, malformed policy before lookup, and a well-typed conflict after valid lookup.+ - Blocked-by: vh146y2 (Green: implement and verify the fenced saved capture builder), vh146y4 (Green: implement import monitoring and the bounded refresh decision), vh146y8 (Green: implement shared publication domain and migrate ordinary retention)+ - Stream: 1+ - Owner: t63-foundation-runtime+ - Requirements: [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [2.6](requirements.md#2.6), [3.1](requirements.md#3.1), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [x] 11. Green: migrate covered handler reads onto captured DTO projection <!-- id:vh146ya -->+ - Update MCPToolHandler+TaskQuery and query_milestones/get_projects paths to capture/project immutable DTOs, typed policy parsing, prepared encoded results and additive outer metadata. Preserve ordinary UUID selector semantics and T2380 writes/canonical r1; physical attribution is for shared capture, not a query semantic rewrite.+ - Freeze complete original metadata in ordinary retained pages; replay without capture/wait. Map read execution errors to approved existing/extended codes and metadata categories; input/cursor/capacity precedence stays unchanged.+ - Use injected MCPRetainedViewSource for reusable views and keep T2382 snapshot-query implementation separate. Integrate minimum code and task 10 tests together; no fallback empty arrays.+ - Evidence: Prepared saved-read component and frozen ordinary cursor integration passed focused actual app suites (xcresult top-level 28 tests; device 32 executions; zero failures/skips) and strict lint. Production admission/dispatch and T2382 reusable-query binding remain tasks 12–13; see foundation-handoff.md for exact API and limits.+ - Blocked-by: vh146y9 (Red: add read projection, wire parity and frozen metadata tests)+ - Stream: 1+ - Owner: t63-foundation-runtime+ - Requirements: [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [2.6](requirements.md#2.6), [3.1](requirements.md#3.1), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [-] 12. Red: add full routing, lifecycle and T2382 integration tests <!-- id:vh146yb -->+ - Extend MCPServer tests for single/read-only/mixed JSONRPC, invalid arguments, notifications/all-notification HTTP 202, stopped service and restart with unfinished work; assert final encoded bytes and publication match terminal selection.+ - Add shared helper contract tests for T2382 descriptor registration, portfolio read classification, snapshotId dispatch, same view identity/evidence, scoped rejection and per-store batch aggregation. Use fixtures until parent supplies approved T2382 modules; integrated acceptance cannot pass on fixtures alone.+ - Write preservation regressions for merged write safety inputs/outputs/receipts/revisions, fallback-storage mutating allow-list and maintenance tools outside freshness scope.+ - Foundation tasks 1–9 never depend on these integration tests or on T2382 modules. Keep fixture-based red tests separate from actual-module final acceptance to avoid a circular cross-ticket gate.+ - Evidence: Actual single-route RED compiled and ran (three methods/four device executions failed); saved-only/frozen metadata, five-second valid+invalid tool-domain availability and no late cursor-root publication are unwired. Additional admission/helper capability RED compiled and ran three methods/three device executions, all failed with zero skips; this proves missing interface binding only. Stage A generic admission/helper/router/lifecycle/private-publication/write-preservation fixtures are now implemented and verified GREEN on the isolated host (14 methods/17 executions). Actual T2382 module fixtures/final acceptance remain outstanding, so this mixed integration task remains in progress; see foundation-handoff.md.+ - Blocked-by: vh146y6 (Green: implement independent deadline and physical admission coordination), vh146y8 (Green: implement shared publication domain and migrate ordinary retention), vh146ya (Green: migrate covered handler reads onto captured DTO projection)+ - Stream: 1+ - Owner: t63-foundation-runtime+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [4.4](requirements.md#4.4), [5.3](requirements.md#5.3), [6.2](requirements.md#6.2)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [-] 13. Green: wire server lifecycle, common schemas and T2382 helpers <!-- id:vh146yc -->+ - T63 alone edits MCPServer routes/batch/start/stop, TransitApp construction, handler init/common dispatch/readOnlyToolNames, MCPToolDefinitions existing readPolicy/common provider wiring and shared MCPTypes. Inject one process-lifetime coordinator/monitor/publication domain and capture builder.+ - External prerequisite: parent delivers T2382 separate MCPToolHandler+PortfolioSummary, +SnapshotTaskQuery, MCPPortfolioToolDefinitions and retained-store hook modules matching approved interface. Wire query_tasks snapshotId dispatch to those helpers; do not duplicate their code or touch their worktree. Parent chooses clean dependency commit/cherry-pick after both task gates.+ - Run task 12 with actual modules. Keep write behavior/order, maintenance exclusion, encoded availability and atomic publication intact; never clear physical counts on generation changes.+ - Partial evidence: Stage A generic routing/lifecycle/private-publication/write-preservation passed on the preflight-verified isolated development host: six sequential suites, 14 methods/17 device executions, zero failures/skips. Dedicated isolated bootstrap smoke passed separately (one test). Actual T2382 helpers and final T2383 modern adapter remain unverified Stage B/C prerequisites; this task is not complete. See foundation-handoff.md and external stage-a-isolated evidence.+ - Blocked-by: vh146yb (Red: add full routing, lifecycle and T2382 integration tests)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [4.4](requirements.md#4.4), [5.3](requirements.md#5.3), [6.2](requirements.md#6.2)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [ ] 14. Red: add nonblocking diagnostics and executable caller-contract tests <!-- id:vh146yd -->+ - Add diagnostic sink tests covering correlation and monotonic queue/refresh/capture/transform/serialization/batch durations, late completion/discard, bounded enqueue and simulated slow logging that cannot delay timeout/hold domain lock.+ - Add executable caller-example tests for new-query/new-capture versus cursor/same-capture, cached/default semantics, busy/timeout backoff, error mapping, no unbounded retry and mixed delivery caveat. Assert advertised MCP read descriptions expose these limits without changing payload shape.+ - Caller documentation creation remains an ancillary delivery requirement outside the skill's coding-only checklist; tests validate examples used in that guide.+ - Blocked-by: vh146yc (Green: wire server lifecycle, common schemas and T2382 helpers)+ - Stream: 1+ - Requirements: [4.1](requirements.md#4.1), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [ ] 15. Green: implement bounded phase diagnostics and caller-facing tool descriptions <!-- id:vh146ye -->+ - Implement bounded nonblocking diagnostic sink/event values with original operation correlation retained through late finalizer; measure actual elapsed stages without synchronous timer-path filesystem work or speculative CloudKit attribution.+ - Update code-level MCPToolDefinitions read descriptions/error guidance to match approved metadata/policy/deadline/import/backoff contracts and task 14 examples. Run task 14, including blocked logging.+ - Caller-guide creation and publication follow-up are tracked outside this coding-only checklist; pass the validated executable examples to that separate delivery step.+ - Blocked-by: vh146yd (Red: add nonblocking diagnostics and executable caller-contract tests)+ - Stream: 1+ - Requirements: [4.1](requirements.md#4.1), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md++- [ ] 16. Validate the integrated read contract and merged write parity with Xcode27 <!-- id:vh146yf -->+ - Test task 2–15 suites with actual T2382 integration and saved-only/whole-versus-scoped capture. Include real router-return timing under blocked MainActor/slow large encoding, frozen pages, event/import faults, process-lifetime accounting and atomic same-store batch cases; retain precise supported/unsupported live-history result.+ - Coordinate exclusive heavy build/simulator slot with parent before make lint/full macOS and required iOS gates; serialize SwiftData suites using owning fixtures. Xcode 27 only. If Makefile builds fail, use Xcode MCP when available and report exact unavailable capability; no downgrade or concurrent heavy worker.+ - Testing-only task; repairs reuse the adjacent red/green unit pair for the affected component before rerunning targeted acceptance. Full pre-push-review including Pulsar is mandatory afterwards under its separate skill; parent approval controls otherwise unauthorized publication, with no merge/deploy.+ - Blocked-by: vh146ye (Green: implement bounded phase diagnostics and caller-facing tool descriptions)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [2.6](requirements.md#2.6), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3)+ - References: specs/bounded-read-freshness/design.md, specs/bounded-read-freshness/decision_log.md
diff --git a/specs/development-isolation/component-handoff.md b/specs/development-isolation/component-handoff.mdnew file mode 100644index 0000000..80ca09f--- /dev/null+++ b/specs/development-isolation/component-handoff.md@@ -0,0 +1,61 @@+# Conditional component handoff++Status: verified isolation component; one dedicated smoke exception completed. Broader ticket app-host holds remain in effect. Baseline isolation commit fd3650c alone is incomplete. The follow-up AppDisplayIDAllocators correction resolves the constructor gap and its exact offline bootstrap probe passed. T63's exact 46bec7c fix has now been applied and the development build passed. The parent must announce the final verified isolation/fix commits before branches run hosts.++## Integration sequence++1. T63 supplies its narrow owned service patch; containment applies it without replacing TransitApp or read wiring. Containment owns App/project/target/scheme/entitlement selection. T63 retains read-service, routing, publication-domain and coordinator ownership.+2. Containment closes inactive allocator construction and verifies that exact bootstrap helper offline. Preserve the production allocator branch and all domain/write behavior.+3. Run configuration_guard.py, standalone offline isolation harness and build-development-macos in the parent's exclusive slot. Preserve the evidence and report actual results. Passing these gates does not automatically clear app-host holds.+4. Parent publishes the final commit set and explicitly releases each branch's focused host suite. Only then may workers consume the configuration and request their own non-overlapping slot.++For a branch already containing the agreed T63 foundation, the isolation component can be reviewed with:++```sh+git show --stat fd3650c+git cherry-pick fd3650c+```++The cherry-pick is a future authorised integration instruction, not executed by this handoff. Use the final follow-up commit set too; fd3650c alone leaves the review gap. Older branches must first receive the parent-selected foundation. Do not pull the whole containment branch into an older branch blindly or restore complete files from fd3650c. Stop conflicts in App/project files for the containment owner. Preserve branch-specific schema models and handler/server interfaces through a narrow merge.++## Components to preserve++- AppPersistencePolicy and IsolatedPersistenceConfiguration, plus AppDisplayIDAllocators and DisabledCounterStore.+- App mode resolution before any persistence/sync/sidecar construction; selected container plus effective sync false passed into allocators and T63 reads.+- SyncManager cloudSyncAllowed behavior; production Release behavior unchanged.+- Native TransitDevelopment target, its always-isolated identity/flag and CloudKit/push/App-Group-free entitlements. Transit Debug is isolated too. Shared filesystem source groups include new branch files automatically.+- Shared Transit test scheme in Debug with explicit unit-test mode. Every UI launch supplies ui-test; do not rely solely on XCTest class detection.+- Isolated persistent/temporary receipt sidecars and suppressed automatic MCP startup.+- Configuration guard in lint preflight and offline standalone harness. Build commands never install, launch or provision.++## Branch-specific merge boundaries++T63: preserve MCPReadAppDependencies.make, one coordinator from reads.snapshots.domain, and that same coordinator in handler and server. Later constructor changes come through the App owner.++T2382: preserve its portfolio adapters/services and the agreed T63 publication domain. Do not substitute an older handler or App blob to resolve a constructor conflict.++T2383: preserve structured result/protocol changes while retaining isolated startup and the shared read coordinator. New response types are not permission to use a live host.++T2384: retain new batch commands, revision/receipt semantics and schema inputs while keeping sidecars tied to isolated config.url. Never point synthetic probes at historical or current live snapshots.++T1734/T2381: App owner integrates new link/consolidation model additions into the schema list. Do not replace the six-model receipt schema or accidentally omit MCPWriteReceipt. Use synthetic fixtures for graph/canonical/undo scenarios.++## Host-run acceptance boundary++After explicit parent release, use the shared Transit scheme with configuration Debug and the named focused suite, serial execution, a private DerivedData/result bundle and locally resolved packages. The test host must identify as me.nore.ig.Transit.development. Do not use TransitDevelopment as the unit-test scheme: it intentionally contains no test targets. Do not override production identity, entitlements, launch mode or switch to Release to make a failed test invocation work. No install/run targets, app activation, live MCP calls or production store repair are authorised by this component handoff.++Each branch reports its exact command, host identity, suite count, outcome and remaining limits; the parent controls concurrency and Asterism quiet windows. The historical database snapshot is not a current mutation map: the user renumbered some live records afterward.++## Current gate result++T63 immutable fix 46bec7c386624ce755c11940ef58bf046999cb02 is integrated as an exact one-line patch and the development-target build passed. Baseline branches need both fd3650c and that exact T63 fix, plus the verified allocator-bootstrap correction. Do not release app-host holds or copy old App blobs merely because the target now compiles. The correction checkpoint includes BootstrapProbe, refreshed verification evidence and the guarded app wiring. Parent release remains required before any host runs.++## Dedicated smoke command and final component++The focused host smoke now passed: one test, store URL /dev/null, memory-only, effective CloudKit sync disabled, both counter adapters disabled, temporary development-container sidecar. The dedicated TransitIsolationSmoke scheme uses TransitDevelopment directly and compiles only TransitIsolationSmokeTests; it does not compile or run ticket suites. This avoids existing MCP read-test compilation failures in the shared test target, which remain for their owner.++```sh+make test-isolated-host-smoke SMOKE_DERIVED_DATA=DerivedData/isolation-host-fresh+```++Use a fresh unused directory; the runner refuses to overwrite a previous result bundle. Before launch it checks signed identity/entitlements and generated environment/path; app preflight rejects any unsafe configuration before storage construction. No installed app activation, MCP enablement or broad-suite release accompanies this command. The cumulative isolation component patch excludes T63's owned MCPReadService compiler fix; retain that exact fix separately. Integrators T63/2382/2383/2384 must merge narrow App/project wiring while preserving their read domain/coordinator and branch-specific handler/schema behavior.
diff --git a/specs/development-isolation/implementation.md b/specs/development-isolation/implementation.mdnew file mode 100644index 0000000..12828eb--- /dev/null+++ b/specs/development-isolation/implementation.md@@ -0,0 +1,83 @@+# Development and test storage isolation++Status: standalone isolation verification and development-target build passed; app-host acceptance blocked by the allocator-construction finding in source-review.md. Branch fix/development-store-isolation is based on the T63 ownership checkpoint 36f7ee328f53250413beff825af3ae826e25d3d0. The containment owner preserves T63 read construction and owns only the narrow isolation changes.++## Resulting policy++TransitDevelopment is a separate native target and shared scheme, using me.nore.ig.Transit.development for Debug and Release. Its entitlements contain neither CloudKit/push nor App Groups. Existing Transit Debug builds and their test hosts also use the isolated identity. Transit production Release configuration and entitlement source are unchanged.++Launch mode resolves before SyncManager, a container, or sidecar creation. Debug/development builds with production identity fail closed. Test requests with production identity also fail closed. The test scheme explicitly supplies TRANSIT_PERSISTENCE_MODE=unit-test; every UI launch explicitly supplies ui-test. Runtime XCTest detection is only an additional isolated fallback. Invalid launch modes never fall through to production.++IsolatedPersistenceConfiguration returns a named development.store below TransitDevelopment in the development app support directory, or an in-memory test container. Both use cloudKitDatabase.none. Production mode is rejected by this factory. Isolated SyncManager ignores saved sync preferences, rejects enabling sync and clamps active sync false. Development/test automatic MCP startup and sync connectivity callbacks are suppressed. Receipt sidecars use the isolated persistent URL or a unique temporary test directory. T63's one shared publication domain/read coordinator is retained.++## Checks already completed++- Project/entitlement/Info plist syntax and shared scheme XML parsing.+- Source configuration guard for bundle identity, entitlements and explicit test launch mode.+- Exact equality of production Release build configuration and production entitlement file against T63 base.+- Strict focused SwiftLint: no violations in changed app/policy/configuration/probe Swift files.+- Whitespace diff check.++Standalone compilation and synthetic harness verification passed. Full make lint passed across 441 Swift files. No app-host test, activation, deployment or live-data mutation occurred.++## Requested exclusive verification commands++Run from /Users/arjen/Documents/Codex/2026-10-02/task/transit-isolation:++```sh+make test-development-isolation+```++This compiles two standalone executables only. Compiler subprocess sandboxing is retained. Swift help describes -disable-sandbox as disabling sandbox use for subprocesses; it is not a SwiftPM-only option. The approved invocation explicitly supplied an empty flag variable, and the isolation target now always omits that optional legacy compiler flag. Normal per-command escalation was approved; no approval was bypassed. Runtime children use sandbox-exec to deny network and access to the production Transit container and Group Containers. Synthetic stores are confined to a fresh DerivedData/tmp/transit-synthetic-* directory; the probe rejects other paths. No app main, listener, allocator or sync service is launched. Each child operation is bounded; results go to DerivedData/isolation-verification.json. The actual isolated configuration is exercised before sequential and overlapping old/new schema cases. Projection revision tokens use the production revision algorithm under a synthetic projection name, not a claimed complete task revision.++A second, build-only gate needs locally staged resolved packages:++```sh+mkdir -p DerivedData/SourcePackages+ditto /Users/arjen/Documents/Codex/2026-10-03/task/transit-t63/DerivedData/SourcePackages DerivedData/SourcePackages+make build-development-macos+```++The target uses two build jobs, offline resolved package flags and CODE_SIGNING_ALLOWED=NO. It does not install or launch an app. App-host tests remain separately held. If dependencies cannot resolve offline, report the failure rather than enabling downloads or provisioning. Do not edit T63-owned read files to solve unrelated baseline errors.++## Interpretation boundaries++The historical snapshot proves seven duplicate rows were inserted by a CloudKit import at 13:23:41 UTC. The failed matching import was logged by the installed process. Mixed entity numbering and binary receipt markers support concurrent model generations sharing the live store, but do not prove the full causal chain. Offline synthetic verification can prove local compatibility outcomes only; it cannot reproduce a remote CloudKit import. Live repair and any separate development CloudKit provisioning remain separate decisions.++The phone renumbered some duplicates after the snapshot. Current live IDs must be re-read through supported installed-app access; do not use historical display IDs as mutation targets. At the last access check, the installed app was running, the console was locked, MCP had no listener on 3141, and this session exposed no UI-control tool.++## Verified results++The standalone harness exited 0 without -disable-sandbox. Launch policy checks passed. The actual development configuration created its explicit isolated store; actual unit/UI test configurations saved synthetic records in memory. Sequential migration preserved task/project UUIDs, display ID, status, relationships and synthetic projection revision; the new receipt was saved and read back. The overlapping old/new process case also retained one task and the relationship with zero UUID duplicates. Both disposable databases passed quick_check. This offline case did not reproduce the live CloudKit duplication; import-specific behavior remains unverified.++The build-development-macos gate used staged local resolved packages, two jobs and signing disabled. It reached app compilation but xcodebuild exited 65 on MCPReadService.swift:97:26: the applicability closure is non-Sendable and main actor-isolated in an outside-actor call. This file is T63-owned and unchanged by this patch. No isolation-specific compiler diagnostic was observed, but the target build remains failed, not verified complete. Parent/T63 must provide an owned fix before a fresh build gate; do not release app-host tests on the strength of the standalone gate alone.++Evidence is in verification/isolation-verification.json and verification/build-diagnostics.json. The original live snapshot remains separate historical evidence, and current renumbered live tasks are outside this implementation's mutation scope.++## Build after T63 compiler handoff++Applied the exact one-line source from T63 commit 46bec7c386624ce755c11940ef58bf046999cb02, verified byte equality with that commit, then ran build-development-macos. Exit 0 / Build Succeeded. Generated app Info identifies me.nore.ig.Transit.development, Transit Development, executable TransitDevelopment. No install, launch or app-host test occurred. Earlier failure diagnostics are retained as historical evidence.++Independent local read-only review then identified an isolated-bootstrap CloudKit handle-construction gap in DisplayIDAllocator's default convenience initializer. Counter RPC guards are present, but this constructor path was not covered by the persistence harness. App-host holds stay in place pending a disabled-store allocator path and exact offline bootstrap verification. The conditional component-handoff.md must not be read as a host-run release.++## Inactive allocator bootstrap correction++Resolved the reviewed constructor gap after 4f1a81f: AppDisplayIDAllocators checks launch mode and effective sync before selecting adapters. Inactive modes use DisabledCounterStore through the designated initializer, so CKContainer.default/privateCloudDatabase is never constructed on that branch. Active production retains the original CloudKit convenience initializer and global-counter/milestone-counter names. T63 source and shared coordinator wiring are untouched.++Added an exact-source offline bootstrap executable covering both sync inputs for every isolated mode, production sync-off, fail-closed direct counter access, allocation rejection and provisional-task promotion no-op. Production dispatch is tested with a spy factory, without constructing a CloudKit handle. Every executable runs under the existing network/live-container-denying sandbox; swiftc subprocess sandbox is retained. The complete isolation harness passed; development build-only gate passed; lint passed with zero violations across 443 files. No app-host tests, launches, live reads/writes or server actions ran during this correction. Source review resolves the bootstrap finding, with app-host release still controlled by the parent.++## Minimal isolated test-host smoke++The parent explicitly released one isolated smoke exception while retaining all broader host holds. Added a dedicated TransitIsolationSmokeTests target and TransitIsolationSmoke scheme hosted only by TransitDevelopment; it builds a single opt-in fixture. The original shared test target could not build because of existing ticket-owned MCP read-test import errors, so those tests were left unchanged. Isolated memory configuration now explicitly disables App Group selection as well as CloudKit.++The host_smoke.py runner verifies the actual signed development bundle ID, absence of CloudKit/push/App Group entitlements, exact generated host path and explicit unit-test environment before test-without-building. It sets opt-in attestation and exact host path in a derived xctestrun; no global settings or permission changes occur. App preflight rejects wrong identity/mode/path or persistent/CloudKit/App Group configuration before ContainerFactory invocation. Post-bootstrap attestation checks actual container configurations, disabled counter adapters and the temporary sidecar before its coordinator is created.++One test in one suite passed. The actual configuration URL was /dev/null; memory-only true, effective cloud sync false, both counters disabled, sidecar in the development app container's tmp directory. This proves the app bootstrap selected no live/default persistent store; no system-wide file-open trace was captured. Xcode adds its standard test-driver sandbox/debug entitlements to the ad-hoc test host, with no CloudKit/push/groups; production entitlements are untouched. No installed app launch, MCP enablement or broader test suite ran. All smoke build/test workers exited. The refreshed offline harness and lint also passed.++Reusable command (a fresh, unused result directory is required):++```sh+make test-isolated-host-smoke SMOKE_DERIVED_DATA=DerivedData/isolation-host-fresh+```++This target builds Debug/arm64 with two jobs, locked package resolution, local ad-hoc signing and no provisioning, verifies the generated artifacts, then runs only TransitIsolationSmokeTests/DevelopmentIsolationSmokeTests serially. The shared Transit scheme remains the separate future route for ticket suites after explicit parent release.
diff --git a/specs/development-isolation/source-review.md b/specs/development-isolation/source-review.mdnew file mode 100644index 0000000..caffaea--- /dev/null+++ b/specs/development-isolation/source-review.md@@ -0,0 +1,39 @@+# Read-only isolation source review++Reviewed checkpoint: fd3650c65b0e9861fd5c0844ff7cda5d8ea6098b. This review used local source reads only; no source was disclosed externally and no app, test host or CloudKit operation was run.++## Historical blocking finding: isolated bootstrap constructed a CloudKit handle++TransitApp constructs both DisplayIDAllocator instances using the convenience initializer with isCloudSyncActive=false in development/test modes. DisplayIDAllocator.swift:99-106 evaluates its default CKContainer.default() parameter and reads privateCloudDatabase before passing the inactive flag to the designated initializer. Guarded allocation/promotion paths prevent counter RPCs, but do not prevent construction of the production CloudKit adapter. The new target has no CloudKit entitlement, so initialization failure or entitlement handling remains unverified. The standalone persistence harness never constructs the app allocators and does not close this gap.++Before releasing app-host holds, construct inactive allocators with a disabled CounterStore through the designated init(store:isCloudSyncActive:), without constructing CKContainer or CloudKitCounterStore. Keep the production constructor in the sync-active branch only. Extend the standalone bootstrap probe to exercise the exact inactive allocator factory without CloudKit entitlements and with network/live-container denial. This is a narrow app-bootstrap fix, not a change to allocation semantics or T63 reads.++## Paths examined++- Launch resolution runs before SyncManager, store selection and receipt sidecar selection; a development/test production bundle identity is rejected. Debug builds have a distinct identity; test scheme modes are explicit.+- IsolatedPersistenceConfiguration rejects production and returns only cloudKitDatabase.none, explicit development storage or in-memory tests. ContainerFactory fallback is also memory/CloudKit-none.+- SyncManager false allowance short-circuits saved preference loading/default creation, refuses enabling sync and clamps active sync false. CloudSyncBootstrap cannot make isolated sync active.+- App connectivity callbacks and schema initialization are production-only. Counter allocation, promotion and maintenance RPC entry points gate on active sync. The constructor gap above remains material.+- App Intents and entity queries obtain the app's injected services; no separate live ModelContainer constructor was found in those paths.+- T63 reads use the selected container and its single shared domain/coordinator. Its import observer declines subscription when syncActive=false.+- Persistent receipt sidecars derive from selected config.url; test sidecars are unique temporary directories.+- Automatic MCP startup is production-only. Settings still supports explicit manual MCP startup against the selected store; this does not select live storage, but automatic-start isolation is not a global ban on every UI server action. App-host holds continue.+- Production Release remains a deliberate live-storage path. Do not run Release test/profile/archive or reuse stale production xctestrun artifacts as an isolation check.++## Historical conclusion++At the initial checkpoint, do not declare app-host/test isolation ready yet. Resolve the allocator-construction gap, consume T63's owned service-closure fix, pass the build-only gate, and obtain the parent's explicit release of the relevant focused app-host hold. Offline migration cases passed and did not reproduce the CloudKit duplication; root cause remains an inference.++## Bootstrap correction review++The follow-up source review resolves the constructor finding. TransitApp now calls AppDisplayIDAllocators.make with both the resolved mode and effective sync state. Its guard requires production cloud permission and active sync before invoking the CloudKit factory. All other paths construct DisabledCounterStore through the allocator designated initializer. That adapter imports only Foundation, contains no CKContainer/privateCloudDatabase access, and throws on direct reads and writes. The default factory closure constructs the existing production adapter only when invoked in the guarded branch; both production counter record names and allocator behavior are preserved. No read coordinator, domain, schema, receipt or production entitlement changes occur in this correction.++The standalone BootstrapProbe compiles the exact app helper, allocator and production adapter sources. Under network and live-container denial it verifies zero factory invocations for development, unit-test and UI-test with both sync inputs, plus production with sync disabled. It checks both allocator guards, direct disabled-store failure and no promotion/save of a synthetic provisional task. Active production uses a spy factory and verifies both counter names; it does not contact CloudKit. Configuration preflight additionally rejects direct allocator construction in TransitApp.++Offline policy, actual persistence configuration, sequential/concurrent synthetic migration and bootstrap checks passed. The development build-only gate passed with signing disabled, and lint passed (443 files, zero violations). Compiler sandbox remains enabled; every runtime harness child retains network/live-container denial. This review is a local source review, not an independent external review. The original CloudKit duplication remains unreproduced offline. App-host tests and all launches remain held pending explicit parent release.++## Focused host smoke follow-up++A single smoke exception was authorized after the bootstrap correction review. The dedicated target depends on TransitDevelopment, contains only its smoke fixture, and uses the new Debug scheme with explicit unit-test environment. The runner examines built signed artifacts before launch; the exact host path is also checked in-process. AppIsolationSmoke.preflight sits before ContainerFactory and requires memory-only/no CloudKit/no App Group configuration. record inspects the effective container configuration and disabled counter-store types, and validates the sidecar before coordinator construction. Production operation sees these hooks disabled unless the explicit smoke flag is set, in which case mismatched identity/mode fails closed. Memory tests now explicitly use groupContainer.none.++The signed host and runtime smoke passed (one test). Actual store URL /dev/null and memory-only configuration exclude a default or live persistent store through the app's container path. This is configuration/actual-host evidence, not an independent system-wide file-open trace. The exact helper offline spy test remains the evidence for zero CloudKit factory invocations. Installed production application and production entitlements were not changed. Source review and smoke acceptance do not release the broader ticket suites; parent still controls those holds.
diff --git a/specs/structured-mcp-results/api15-handoff.md b/specs/structured-mcp-results/api15-handoff.mdnew file mode 100644index 0000000..b7366fb--- /dev/null+++ b/specs/structured-mcp-results/api15-handoff.md@@ -0,0 +1,29 @@+# DELIVERED15 / gpzncvz: common result contract++The approved common seam is delivered from T2383 source checkpoint `543c4a757e4cb7f9f73c973d7cb1be5725c8f342`. Production integration is `a8fcc71506ff61ee5b6f0e320ace5a064e30c915`; selector/provider evidence is `fb776a0`. The exact file hashes, last source commits and retained-owner imports are in [api15-source-manifest.json](api15-source-manifest.json). The final handoff commit containing these documents is the consumer delivery reference.++Verification combines the preserved 98 passing bodies from the 100-test run with the finalized two corrected-method passes. It does not claim a single finalized clean 100-test run. The 100-test run had four issues caused by two missing mandatory query limits, test143 and an unfinalized result bundle; both processes were sampled before runner cleanup and drained. The two-method correction result is finalized Passed, 2/2, zero failures/skips/runtime warnings, with normal drain and no cleanup signals. Both runs verified their exact compiled inventory before bodies and preserved signed isolated unit-host guards. Final internal integration critic cleared delivery. Evidence remains local in `.codex-cache/task15-binding-green-import-fixed/` and `.codex-cache/task15-binding-green-limit-fixed/`.++## Consumer interfaces++All types are project-internal Swift values. Consume the delivered declarations directly; do not define a parallel envelope, receipt adapter or acceptance engine.++- `MCPResultAdapter.source(text:isError:origin:evidence:checkpoint:) throws -> MCPResultSource` owns original text, optional error flag and lossless JSON. Declare `.retainedJSON` for historical receipts, `.generatedJSON` for newly generated logical batch JSON, and `.plainText` for actual textual evidence. Malformed/depth-limited historical input retains raw text as `.unreadable`/unestablished; malformed generated input throws. Checkpoint failures propagate.+- `MCPResultAdapter.present(_:context:checkpoint:) throws -> MCPResultPresentation` derives supplemental classification, recovery and source-backed link pointers without changing the source. Context carries tool, typed failure, mutation recovery and explicit entity positions. Navigation links remain unavailable with `navigation_not_supported`; this does not implement T572 navigation.+- `MCPResultEncoder.encode(source:presentation:id:metadata:checkpoint:) throws -> Data` returns complete modern response bytes. `freeze(source:presentation:metadata:checkpoint:)` creates an ID-independent `MCPResultToolFragment`; `encode(fragment:id:checkpoint:)` applies a new request ID.+- `MCPResultEncoder.prepareMutationFallback(id:source:context:metadata:checkpoint:) throws -> Data` prepares complete correlated bytes before effects. The provider supplies its compact logical failure source. Batch fallback presentation omits itemId, links and diagnostic expansion while retaining original index/operation/tool/key/target UUID recovery identities. No acceptance or durable key is invented.+- `MCPResultProviderSelection.mutation(id:context:metadata:fallbackSource:prepareFallback:encodeOutcome:shouldDeliver:dispatch:) async throws -> MCPResultResponseSelection` prepares before dispatch, dispatches once and returns `.normal(Data)`, `.reconciliation(Data)` or `.suppressed`. Post-dispatch provider/adapter/encoding failure selects already prepared bytes without a second encoder call. Preparation failure dispatches nothing; cancellation suppresses delivery without reinterpreting effects. Dispatch returns immutable `MCPResultProviderOutcome(source:context:)`; original recovery identity must match.+- `MCPResultProviderAdapters.outcome(result:context:origin:checkpoint:)` bridges exactly one existing text content block using optional non-wire `MCPResultProviderEvidence`. `metadata(result:frozenReadBytes:checkpoint:)` preserves frozen read metadata bytes in their existing namespace. `MCPToolResult.providerEvidence` is excluded from CodingKeys and persisted outcomes.+- `MCPResultSchemas.descriptor(tool:description:)` supplies the common immutable output descriptor. Retained `MCPToolDefinitions.modernTools(includingMaintenance:)` maps existing definitions through that descriptor once. Real `mutate_tasks` registration remains T2384-owned and requires coordinated owner integration.++## T2384 binding++Build one new logical aggregate with its own compatible original text and aggregate isError. Keep nested original result evidence (complete historic payload, raw text and optional isError) separate from batch diagnostics; do not flatten, normalize or rewrite receipts. The structured wrapper is `{contractVersion:1,source:{kind,payload?},presentation:...}` under `structuredContent`; compatible text and optional outer isError remain present independently. Unknown fields, null/missing distinctions and original numeric lexemes remain source-owned.++Use `.applicationBatch(items:)` with ordered `MCPBatchRecoveryItem(index:itemId:operation:originalKey:targetTaskId:)`, original protected tool/key, and immutable context fixed before effects. Supply the batch-owned compact `serialization_failed` logical source to fallback preparation. Keep unbounded itemIds/raw records/link data out of that logical fallback itself; the common encoder also strips itemId from supplemental fallback presentation. Preparation must complete before the first effect. After effects or depth-limit failure, select ready bytes and reconcile using original item keys; never create a new key or label effects absent. Aggregate isError remains separate from nested original flags. No production batch dependency was used to verify this seam.++## Ownership and later obligations++T63 retains definitions, settings, admission/capture/retention/publication and read dispatcher ownership. The manifest records the exact supplied factory, synchronous availability snapshot and original-operation/separate constant encoder imports. T2384 retains write-coordinator ownership; this handoff authorizes no overwrite of that file. Use the baseline dependency manifest and exact file hashes for coordinated imports, preserving other workers' changes.++DELIVERED15 unblocks T2384 consumer tasks. T2383 tasks16–17 still cover real frozen fragment retention/accounting and atomic publication; tasks18–19 cover request-scoped POST subscriptions; tasks20–22 cover isolated client readiness and final validation. These are later ticket obligations, not reverse dependencies on the common seam. No live activation, settings changes, push, merge or deployment occurred.
diff --git a/specs/structured-mcp-results/client-readiness-approval-bundle.md b/specs/structured-mcp-results/client-readiness-approval-bundle.mdnew file mode 100644index 0000000..8eb1f12--- /dev/null+++ b/specs/structured-mcp-results/client-readiness-approval-bundle.md@@ -0,0 +1,40 @@+# Client-readiness approval bundle for parent++Prepared scope only; no client probe, feature override, configuration change, model turn or activation has run. Ask once after implementation/fixture delivery and the unresolved target details below are concrete. This is separate from the authorised subscription RED run.++## Verified read-only targets++| Installed target | Exact identity | What is established |+| --- | --- | --- |+| Standalone Codex CLI | `/Users/arjen/.local/bin/codex` → executable under `/Users/arjen/.codex/packages/standalone/releases/` | Installed CLI help supports invocation overrides. `mcp_2026_07_28` is disabled. |+| Codex desktop host | `/Applications/ChatGPT.app`, bundle ID `com.openai.codex` | Installed native desktop app. Its bundled CLI at `Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex` also reports the modern flag disabled; that does not establish the host's effective settings. |+| Claude Code | `/Users/arjen/.local/bin/claude` | Installed help supports disposable `--mcp-config` and `--strict-mcp-config`. |+| Claude Desktop | `/Applications/Claude.app`, bundle ID `com.anthropic.claudefordesktop` | Installed vendor code has a native HTTP MCP host/caller; user-registration path, active negotiation and consumption remain unproved. |++The bundled Codex CLI is a diagnostic executable, not a substitute proof for the desktop host. Parent must name intended Codex surfaces; standalone CLI and native desktop host are distinct candidates. Claude Code and Claude Desktop are required by approved scope.++## Actions requiring approval, once exact values are ready++Use one task21-delivered synthetic read-only fixture, bound to its descriptor's exact ephemeral `http://127.0.0.1:<PORT>/mcp` URL excluding3141, and a new empty working directory. Replace all placeholders with the actual descriptor before asking. No real store or existing Transit listener is connected.++1. **Standalone Codex, if selected:** run an invocation-only `--enable mcp_2026_07_28` plus `-c 'mcp_servers={transit_structured_readiness={url="<URL>",enabled_tools=["get_projects","query_tasks"]}}'`. First inspect the same invocation's `mcp list --json`; establish that its effective enabled providers, including plugin providers, are only the fixture. Stop if this is not established. Then start one synthetic client session in the empty directory. No persistent `config.toml` or feature edits.+2. **Claude Code:** supply one disposable JSON file containing `{"mcpServers":{"transit_structured_readiness":{"type":"http","url":"<URL>"}}}` and start one session with `--bare --mcp-config <FILE> --strict-mcp-config` in the empty directory. Installed help confirms bare mode skips automatically discovered hooks/plugins/memory while accepting explicit MCP configuration; this is invocation-scoped context minimisation, not a permissions override. No `claude mcp add` or normal user/project configuration edit.+3. **Desktop hosts:** do not include a generic host/settings permission. First establish each selected host's exact native temporary entry/feature delta, actual storage path or UI action, reload needs and removal step; then add only that concrete action to this same approval bundle. CLI flags are not assumed to affect the Codex desktop host. Claude Desktop's native loopback registration is still unresolved.+4. **Calls/consumption:** connect, collect actual modern discovery/list traces, and make one synthetic `query_tasks` call with `readPolicy:"cached", detailLevel:"full", includeComments:false, limit:100`; verify native parsed structured consumption. If a model turn is necessary, explicitly include one bounded synthetic-only turn and its exact provider/context exposure in approval. Otherwise no model turn is authorised. Subscription probes apply only to clients that opt in; the conforming fixture always supplies subscription proof.++## Configuration and data exposure++CLI configuration can avoid persistent server/feature changes through invocation overrides and a disposable Claude configuration file. This does not imply clients create no ordinary session/auth/cache/history files; preserve existing configuration and remove only newly created fixture artifacts/entries. Native Desktop/host persistence and temporary registration remain to establish, so no claim that their setup is configuration-free is made.++Local endpoint exposure is the exact probe prompt/arguments, synthetic project/task UUIDs and records/revisions/read metadata, request IDs and native client capabilities/version/identity. Evidence stays in the task workspace. No user record, production store, repository source/spec, arbitrary filesystem content or real mutation belongs to the probe. Normal installed-client authentication/feature fetching may contact its service; do not export credentials or request full unrelated logs.++A model turn would additionally send the synthetic prompt/tool results and that client's native context to its configured model provider. The provider and context isolation must be established before that turn is included in approval; an empty working directory alone does not prove that global instructions/memory/plugins cannot enter model context. Connection/discovery approval does not silently authorise external inference. No external peer review is requested.++## Open details before the single ask++- Delivered fixture descriptor/verifier and exact URL, file paths, prompt/expected result, shutdown action and evidence destination.+- Intended Codex surfaces, effective CLI provider isolation, and native desktop-host configuration deltas.+- Claude Desktop supported native loopback entry. If unavailable, report AC6.3 prerequisite unmet rather than introduce a proxy or legacy endpoint.+- Actual provider/context bounds for any necessary single synthetic model turn.++These are client-readiness prerequisites, not blockers for coding tasks18–21 or the delivered API15. No new client permission is being requested at this preparation checkpoint.
diff --git a/specs/structured-mcp-results/client-readiness-next-approval.md b/specs/structured-mcp-results/client-readiness-next-approval.mdnew file mode 100644index 0000000..18ec63a--- /dev/null+++ b/specs/structured-mcp-results/client-readiness-next-approval.md@@ -0,0 +1,31 @@+# Deferred client validation: historical probe proposal++Current status: the owner deferred actual compatibility checks to post-merge MacBook validation. This preserved proposal is unexecuted and is no longer a premerge approval request. It grants no client setup or runtime action here.++Local implementation and tests are complete. Actual client actions remain parked. No client settings/feature activation, app-server start, native client connection or model turn has been performed. Historical synthetic endpoint61985 is closed and must not be reused as a live target.++## Requested action++Approve one standalone installed Codex CLI probe against a newly launched, reviewed synthetic fixture, bounded to120seconds after its owned descriptor is ready. Use the committed scripts/mcp-modern-readiness/launch.py with a fresh guarded packet, signed isolated unit-host preflight, hold120 and the exact OS-assigned127.0.0.1 URL published in that descriptor, excluding3141. Verify descriptor synthetic=true, persistentStore=false and the two-read-tool allowlist before connecting. Never connect to an existing Transit endpoint.++Run `/Users/arjen/.local/bin/codex app-server --stdio` with invocation-only `--enable mcp_2026_07_28` and a fixture-only mcp_servers map restricted to get_projects/query_tasks. No persistent config.toml or feature edits. First inspect the effective enabled server/provider inventory, including plugin providers; stop if fixture-only isolation cannot be established.++Negotiate app-server experimentalApi, create an ephemeral thread in a newly created empty directory under the task workspace, inspect `mcpServerStatus/list` for that thread, and make one direct `mcpServer/tool/call` to query_tasks with `{readPolicy:"cached",detailLevel:"full",includeComments:false,limit:100}`. Capture the native parsed structuredContent and bounded negotiation evidence. Do not call turn/start or start an external model turn; stop rather than substitute a model-based fallback if the direct API is unsupported. Close only the owned app-server/fixture processes and newly created probe artifacts, preserving existing client state.++This is a prospective runtime check, not a claim that the schema-defined API will work. Exact runtime descriptor and fresh packet hash must be verified before executing. The local schema export establishes a possible direct no-model path, not negotiated readiness or native desktop behavior.++## Evidence supporting the proposal++Read-only installed CLI help/schema generation succeeded without starting app-server or enabling a feature. Generated ClientRequest defines `mcpServer/tool/call` with threadId/server/tool/arguments; McpServerToolCallResponse exposes structuredContent; ThreadStartParams supports ephemeral/cwd/baseInstructions/developerInstructions, and mcpServerStatus/list can use threadId. Metadata is retained in `.codex-cache/client-native-protocol-inspection/`. This is standalone CLI evidence only; it does not prove `/Applications/ChatGPT.app` bundlecom.openai.codex has the same effective settings.++## Exposure and limits++MCP payloads are synthetic UUIDs/records/revisions/read metadata plus request IDs, client identity/capabilities and the explicit read arguments. Capture no credentials, repository content, arbitrary files or unrelated logs. Ordinary installed-client authentication/feature fetching may contact its service and create normal auth/cache/history files; no model inference is authorised, and temporary invocation configuration does not promise zero ordinary client persistence.++Claude Code and both native desktop hosts remain parked until their supported modern runtime/setup and exact scoped actions are established. This single CLI approval would not close all of AC6.3, authorise another client or permit a production cutover. No external peer-review disclosure is requested.++## Owner-approved post-merge client compatibility deferral++On 2026-10-04 the owner explicitly accepted that T2383 actual client compatibility tests may take place after merge, when they pull and deploy Transit on the MacBook (parent-verified Sentinel_c0dbfe3212888191bc01744c855f67bb). AC6.3 remains unverified and is deferred to that post-merge validation; it no longer blocks this authorised merge. Synthetic fixture checks do not establish installed-client compatibility. This amendment does not authorise client setup, persistent settings/feature changes, model turns, MacBook work or deployment here. Local checks, pre-push review and PR Pilot readiness criteria remain required.++Post-merge checklist: verify modern discovery and tool list/call with parsed structuredContent for each intended Codex surface, Claude Code and Claude Desktop against an isolated latest-only endpoint; validate subscriptions for installed clients that opt into them; record unsupported modes and exact negotiation evidence. Preserve original text/replay/cursor evidence during checks.
diff --git a/specs/structured-mcp-results/client-readiness-setup-proposal.md b/specs/structured-mcp-results/client-readiness-setup-proposal.mdnew file mode 100644index 0000000..7d23152--- /dev/null+++ b/specs/structured-mcp-results/client-readiness-setup-proposal.md@@ -0,0 +1,77 @@+# Minimal isolated client-readiness setup proposal++This is a staged setup proposal for parent review. It does not authorise or execute a client connection, feature override, settings edit, model turn, upgrade or production cutover. Subscription tasks18/19 and fixture/verifier tasks20/21 can proceed independently. Actual client evidence is required for task22/AC6.3. The current subscription RED checkpoint4366824/f40dfb3 and its guarded packet remain unchanged.++## Minimal scope and fixture prerequisites++Use one delivered task21 fixture process on `127.0.0.1`, an OS-assigned ephemeral port excluding3141, and a separate empty working directory. It serves only synthetic read-only records through the approved encoder/validator and has no reference to a real ModelContainer, production listener, durable write coordinator or original user data. Readiness discovery lists only synthetic `get_projects` and `query_tasks`; writes and unrelated tools are unavailable. A conforming fixture client always verifies subscription behavior; actual installed clients need it only when they opt in.++Before proposing execution, the delivered launcher must provide an exact descriptor with bound URL, fixture PID/lifetime, source commit, synthetic marker/expected values, selected read-only tools, evidence destination, and an awaited shutdown procedure. `<PORT>` and `<EMPTY_DIR>` below are descriptor substitutions, not a request to reserve a guessed port or run an unavailable script now. Update this proposal with those actual values before parent approval of the probes. Stop and report if the fixture isolation or modern-only proof is unavailable.++Required installed surfaces: Claude Code and Claude Desktop, plus the actual Codex surfaces named by parent. Installed candidates observed locally are the standalone Codex CLI and the ChatGPT app's bundled Codex CLI/host. Running its bundled executable does not prove the desktop-host surface. Parent must specify whether standalone CLI, desktop-host or both are intended. Run probes serially against the same synthetic fixture with distinct surface/run labels.++## Codex CLI: invocation-only delta++Read-only installed help confirms `--enable`, `-c` TOML overrides and streamable HTTP configuration. Its current `features list` reports `mcp_2026_07_28` under development and false. Thus propose only this feature override and a temporary fixture server map for the approved CLI invocation; no `codex mcp add`, config file rewrite or persistent feature enable. The separate `codex_apps_mcp_2026_07_28` feature is not proposed for this ordinary external server.++```text+/Users/arjen/.local/bin/codex --enable mcp_2026_07_28 \+ -c 'mcp_servers={transit_structured_readiness={url="http://127.0.0.1:<PORT>/mcp",enabled_tools=["get_projects","query_tasks"]}}' \+ -C '<EMPTY_DIR>'+```++The installed CLI help verifies invocation overrides; the official [MCP configuration documentation](https://learn.chatgpt.com/docs/extend/mcp?surface=cli) verifies the HTTP URL and tool-selection keys. Installed `codex mcp list --help` confirms `--json` reports configured servers. The first proposed post-approval inspection, before a session, is:++```text+/Users/arjen/.local/bin/codex --enable mcp_2026_07_28 \+ -c 'mcp_servers={transit_structured_readiness={url="http://127.0.0.1:<PORT>/mcp",enabled_tools=["get_projects","query_tasks"]}}' \+ mcp list --json+```++Check the resulting enabled server selection is exactly the synthetic entry and descriptor URL. This command itself has not run with overrides. Its help establishes a proposed inspection mechanism, not the actual map-replacement behavior. Verify plugin-supplied providers are included in this inventory or separately disabled/absent using native read-only configuration evidence; a partial server list cannot prove full isolation. If inherited entries remain, or plugin coverage cannot be established before launch, stop and present the exact additional invocation-scoped isolation change through parent. Do not enable broad permissions or apply unrelated flags. Feature presence or enabling it is not modern interoperability evidence.++For an intended ChatGPT desktop-host surface, this CLI command is only a starting reference. Do not change its host flag, connector registry or shared settings by analogy. Obtain that host's actual one-entry native registration/configuration delta and the supported modern override from its runtime before proposing the host action. A standalone or bundled CLI trace cannot substitute for a host trace.++## Claude Code: separate configuration input++Installed help confirms `--mcp-config` accepts a JSON string/file and `--strict-mcp-config` selects only those servers. Current installed help additionally confirms `--bare` skips automatically discovered hooks/plugins/memory and permits explicit MCP configuration; propose that invocation-only context minimisation for this synthetic session. Propose the following JSON as a disposable fixture input outside the repository and normal user configuration:++```json+{"mcpServers":{"transit_structured_readiness":{"type":"http","url":"http://127.0.0.1:<PORT>/mcp"}}}+```++```text+cd '<EMPTY_DIR>'+/Users/arjen/.local/bin/claude \+ --bare --mcp-config '<EXACT_DISPOSABLE_JSON_PATH>' --strict-mcp-config+```++The official [Claude Code MCP runtime documentation](https://code.claude.com/docs/en/mcp#mcp-client-runtimes) identifies the v2 runtime as the modern protocol path and documents strict fixture configuration. Do not change telemetry, cached feature flags or persistent server configuration to force it. Record the actual native negotiation. If the installed session uses an unsupported runtime, retain that evidence and propose its exact minimal correction separately; do not infer success from version or embedded symbols.++## Claude Desktop: exact native delta still to establish++The required target is installed `/Applications/Claude.app`. The proposed endpoint identity is `transit_structured_readiness`, with exactly the descriptor's native loopback HTTP URL and synthetic read-only tool set; it must be separate from any existing Transit entry. Read-only installed vendor-source inspection locates `.vite/build/mcp-runtime/directMcpHost.js` and its actual main-bundle caller: they pass a URL/HTTP transport to a native MCP client, and negotiation setup depends on runtime feature state. This is more specific than SDK-symbol presence but still does not establish the supported local user-registration path, active runtime, or parsed structured-result consumption. No hidden managed-settings field or runtime flag is proposed. The official [local Desktop setup guidance](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop) documents local extensions, and does not establish this specific loopback HTTP negotiation path.++Continue read-only source/configuration-path inspection to establish the native user-registration mechanism; actual app activation or a settings UI change remains held. Once established, present the precise temporary entry/diff, reload requirement and removal action before applying it. No guessed `claude_desktop_config.json` URL entry, extension install, stdio proxy or cloud tunnel is part of the minimal proposal. If Desktop lacks a native modern connection to the isolated loopback fixture, report that installed-client prerequisite as unavailable and keep AC6.3 open. Coding and API delivery proceed.++## Exact probe and acceptance++The first action proposed for approval is connection/discovery only. Capture actual native `server/discover`, `tools/list` and request metadata/headers at the synthetic fixture. Then, only with separate approval for one bounded synthetic-data client turn if it is necessary, request one `query_tasks` call using synthetic read-only arguments `readPolicy:"cached", detailLevel:"full", includeComments:false, limit:100`. No repository, spec, source, local file content or user record enters the client prompt or returned fixture data. A model turn is a client-consumption probe, not a peer review, and requires its own explicit approval here.++For each named surface retain actual request/response correlation, modern version/header/meta checks, complete discovery/list/call results and schema, plus client-side evidence that it consumed `structuredContent.contractVersion`, `structuredContent.source.kind` and the nested synthetic payload/presentation. A server log showing delivered structured JSON alone does not prove native consumption. A printed version, embedded symbol, successful registration, legacy negotiation or copied fixture-client response also cannot substitute. Where the native client cannot supply consumption evidence, report the limitation rather than certify it. If a surface opts into tools-list subscriptions, additionally capture its native acknowledged filter, first ack, original request-ID correlation and one synthetic availability invalidation; otherwise the conforming fixture supplies that coverage.++The future task21 verifier validates the collected actual evidence and rejects missing surfaces, legacy versions, missing consumption or fabricated subscription claims. No manual fixed Mcp-Method/protocol headers are added to client configuration to disguise a nonconforming runtime.++## Approval and cleanup boundary++Parent first names intended Codex surfaces. After task21 delivers the isolated launcher/verifier and this document has exact descriptor values, parent obtains approval for the exact invocation-only Codex feature/connection, Claude Code disposable configuration/connection, and the separately established Desktop/host entry if available. Any bounded model turn is explicitly included or remains held. No approvals are inferred from this proposal.++After probes, close the synthetic sessions, await fixture shutdown, remove only newly created disposable files/entries, and preserve the captured evidence locally. No persistent endpoint replacement, existing entry deletion, client upgrade or production activation is proposed.++## Observed capability evidence++Read-only commands performed during proposal preparation: standalone `codex features list`, Codex/Claude CLI help, MCP-add help, and `codex mcp list --help` only. The configured-server list with proposed overrides was not run. No add command was executed; no client session, endpoint or model agent was started. Codex help/list succeeded with an incidental PATH-alias permission warning; no retry or permission change was made to repair that warning. Saved relevant help/list output and hashes of the inspected Desktop vendor-source files are in `.codex-cache/client-readiness-setup-proposal/`; these artifacts prove available controls/code paths, not runtime negotiation.++## Verified installed target clarification++Read-only app identity inspection verifies `/Applications/ChatGPT.app` is bundle `com.openai.codex`: the installed Codex desktop host despite its directory/display name. Its supporting executable is `/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex`; a read-only feature list also reports `mcp_2026_07_28` disabled. This is a distinct target from `/Users/arjen/.local/bin/codex`; probing that supporting CLI alone cannot establish host readiness. The concise action/configuration/data-exposure bundle is [client-readiness-approval-bundle.md](client-readiness-approval-bundle.md). Actual model-provider/context isolation remains to establish before proposing a model turn; synthetic endpoint data alone does not bound native global context.
diff --git a/specs/structured-mcp-results/decision_log.md b/specs/structured-mcp-results/decision_log.mdnew file mode 100644index 0000000..ec6c18d--- /dev/null+++ b/specs/structured-mcp-results/decision_log.md@@ -0,0 +1,116 @@+# Structured MCP results: decision log++## Quick decisions++| ID | Date | Decision | Evidence / reason |+| --- | --- | --- | --- |+| Q1 | 2026-10-03 | Full spec; name `structured-mcp-results`. | User explicitly approved scope/name through parent Sentinel_efe537c782f88191b8865711b92ade59; public result contract and persisted replay warrant full workflow. |+| Q2 | 2026-10-03 | Explicit unavailable task/project links until supported navigation exists; T-572 implementation stays separate. | Live T-572 is Idea, scheme undecided; no URL registration/open handler in current source. |+| Q3 | 2026-10-03 | T-63 owns existing common files; coordinate serialization adapter and transport handoff. | User's parallel coordination instruction; approved read deadlines/publication must survive migration. |+| Q4 | 2026-10-03 | Use internal design critic followed by two independent internal peer perspectives. | External disclosure is not authorised; local peer-review-validator supplies two-peer fallback. No external AI service will receive repository/spec data. |+| Q5 | 2026-10-03 | Preserve historic T-2380 JSON/text/isError as outcome evidence; common result additions are presentation, not receipt rewrite. | Coordinator replay reads saved resultJSON/resultIsError; T-2384 requirements 4.3,5.2–5.4 align on missing/null, unknown fields, revision/retryAction and no-effect distinctions. |+| Q6 | 2026-10-03 | Move T-2383 Idea → Spec after scope approval. | Committed live update key `T2383.scope-approved.spec.20261003`, comment records approval and remaining gates. |+| Q7 | 2026-10-03 | Preserve subscription opt-in while requiring installed-client tool readiness and a conforming subscription test. | Internal API peer distinguished optional client participation from server subscription conformance; avoids blocking usable tool clients on an unrequested filter. |+| Q8 | 2026-10-03 | Request-only methods never execute notification-shaped requests. | Correctness peer identified legacy handler mutation notification dispatch; modern transport must reject that shape without effects. |+| Q9 | 2026-10-03 | Historical variants must conform to advertised output schemas; supplement names cannot overwrite source fields. | Critic and both peer perspectives confirmed preservation alone is insufficient if schema validation rejects original fields. |+| Q10 | 2026-10-03 | Both Claude Code and Claude Desktop are required readiness surfaces, alongside actual intended Codex surfaces. | User clarification “Both” through parent Sentinel_e3dcebb74f288191a3d42559f563ab5c. This clarifies 6.3, does not approve all requirements or settings changes. |++## ADR 1: Latest-only MCP protocol++**Status:** approved scope decision, 2026-10-03.++**Context:** current source supports `2025-03-26`; structured results require a reviewed protocol change. Latest official stable/current revision is `2026-07-28`, which changes transport/lifecycle substantially. Alternatives were latest with legacy compatibility and interim `2025-11-25`.++**Decision:** target `2026-07-28` only. User declined legacy support because Transit is used by Codex and Claude, and otherwise approved the expanded scope (parent Sentinel_efe537c782f88191b8865711b92ade59). Do not serve old initialization/session/GET or JSON-RPC array batches through a permissive compatibility path.++**Consequences:** modern metadata/header validation, discovery, POST subscription stream and result/cache envelopes need coordinated design with T-63. Application idempotency/snapshots remain server-minted explicit handles. Existing text JSON payloads and saved records survive protocol migration. Implementation and cutover need proof that the actual clients can use modern-only Transit; old-protocol clients receive actionable rejection.++**Client evidence and blocker:** standalone Codex `0.160.0`, bundled `0.159.2`, both read-only feature lists report `mcp_2026_07_28` false. The [exact 0.160.0 protocol-mode source](https://raw.githubusercontent.com/openai/codex/rust-v0.160.0/codex-rs/rmcp-client/src/protocol_mode.rs) includes modern lifecycle but defaults to Legacy. Binary marker inspection confirms modern methods, not enabled negotiation. [Official OpenAI MCP docs](https://learn.chatgpt.com/docs/extend/mcp?surface=cli) establish HTTP support but do not document latest-version activation. Actual desktop host overrides are unverified. Claude Code `2.1.288` has SDK2 modern symbols; cached `tengu_mcp_protocol_negotiation_http` is true, with no environment/settings override observed for MCP_SDK_GENERATION or MCP_PROTOCOL_NEGOTIATION. [Official Claude runtime docs](https://code.claude.com/docs/en/mcp#mcp-client-runtimes) describe conditional runtime selection and feature flags; this supports readiness but does not prove an active modern-only connection. Claude Desktop `2.19675.0` was inspected read-only: its `app.asar` has modern `2026-07-28` version selection, `server/discover`, `subscriptions/listen` and per-request metadata in the bundled `.vite/build/mcp-runtime/directMcpHost.js`/main SDK code. This is installed implementation evidence, not proof its active runtime/Transit connector chooses modern mode. The conventional Desktop config and MCP log show no identifiable Transit negotiation; alternate connector routes were not inferred. Official [Desktop local MCP guide](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop) establishes local MCP support but does not state the protocol revision. Both Code and Desktop remain live-negotiation verification prerequisites. No configs/server modified. Existing successful tool calls against legacy Transit prove only old-server connectivity.++**Verification path:** design/task plan must validate actual Codex/Claude surfaces against an isolated modern protocol fixture before enabling a production migration. If modern mode is disabled/unavailable, stop at the migration gate and report required approved client activation/upgrade; do not add legacy support or change client settings silently. This is a prerequisite, not permission to run an external-model agent.++## Quick decisions: design++| ID | Date | Decision | Evidence / reason |+| --- | --- | --- | --- |+| Q11 | 2026-10-03 | Requirements approved; proceed design only. | Parent verified owner message 2026-10-03T09:51:37.926279Z Sentinel_39b0ca45b1b8819180ac6d9600578f0b, “Structured MCP results requirements also approved”. |+| Q12 | 2026-10-03 | ttlMs zero/public for discovery and tool lists; deterministic name order. | Definitions depend on local availability; no personalised responses, no stale settings cache required. |+| Q13 | 2026-10-03 | Unavailable UUID-and-source-pointer link sidecar; explicit tool selector tables. | Avoid guessing IDs in unknown historical fields and preserve replay determinism. |+| Q14 | 2026-10-03 | Generated plain error text and malformed retained JSON have separate declared origins. | JSON parse failure alone cannot establish that saved evidence is an ordinary message. |+| Q15 | 2026-10-03 | Effectful maintenance prepares no-key uncertainty fallback and reconciles with scan/inspection. | Internal design critic identified post-save serialization gap in reassign_duplicate_display_ids; AC3.4 applies beyond protected writes. |+| Q16 | 2026-10-03 | Generated JSON parse failure throws; malformed retained evidence preserves text/unestablished. | Correctness peer separated capture serialization failure from historical evidence presentation. |+| Q17 | 2026-10-03 | Maintenance provider encoding failures propagate may-have-effects evidence to prepared fallback selection. | Existing inner errorResult catch could otherwise bypass the complete uncertainty fallback. |++## ADR 2: Immutable source and separate presentation envelope++**Status:** approved in T2383 design 7970a9c by Sentinel_717be95229c48191a7c41b6e5e467e4c.++**Context:** historic JSON may contain arbitrary unknown field names. Flattening category/links into that object would either overwrite saved evidence or silently change the supplemental contract. Reads also use arrays and scalar JSON values. T2384 needs nested original JSON/text/optional isError independent of aggregate diagnostics.++**Decision:** common structured contract version1 uses source.kind/payload and a separate presentation containing evidence, links, category and recovery. Text and optional isError are retained independently. A lossless immutable JSON document validates/inserts the whole original JSON fragment without a Double roundtrip; presentation never rewrites the original payload.++**Consequences:** consumers follow source.payload rather than consuming a flat structured record. Common schema constrains wrapper/source variants but intentionally permits any original JSON value/unknown historic fields. Current tool shapes are documented separately. Raw fragment insertion requires a validated complete document and targeted parser/encoder property checks. This adds parser work but avoids lossy generic AnyCodable conversion across actor boundaries. No receipt format migration or alternate canonicalizer is introduced.++**Alternatives:** flat original JSON plus reserved fields cannot satisfy collision safety; metadata-only supplements separate fields but do not supply a self-contained versioned structured contract. Re-encoding Foundation numeric values risks changing unknown historical numbers. A new persisted presentation receipt would change storage/replay semantics and create migration work outside scope.++## ADR 3: Complete response preparation before publication or write effects++**Status:** approved in T2383 design 7970a9c by Sentinel_717be95229c48191a7c41b6e5e467e4c.++**Context:** T63 can publish retained views only with a winning complete response; T2380/T2384 can commit before a response encoder fails. Calling a generic encoder again while handling its failure can hide the outcome or lose request correlation.++**Decision:** covered reads finish all text/structured/meta/modern envelope bytes before the existing atomic publication gate. Protected single/batch writes prepare a complete compact modern uncertainty/reconcile response before effects, correlated to the RPC ID and original keys, then select those ready bytes on post-effect encoding failure without invoking the failed encoder again. Fallback preparation failure blocks dispatch. Cancellation suppresses delivery but never rewrites commitment evidence.++**Consequences:** expanded retained fragments count toward existing store budgets; unsafe generic response fallbacks are excluded from may-commit paths. The common encoder offers complete-byte preparation; T2384 supplies its compact aggregate and preserves per-item effects/keys. Read physical finalizers and write durable transactions remain owned by their approved components.++## Quick decisions: task planning++| ID | Date | Decision | Evidence / reason |+| --- | --- | --- | --- |+| Q18 | 2026-10-03 | Design approved; proceed Rune task planning only. | Owner “2383 and 2384 are approved”, parent-verified Sentinel_717be95229c48191a7c41b6e5e467e4c; T2383 7970a9c, T2384 a5950e99. |+| Q19 | 2026-10-03 | Deliver synthetic-provider-tested common API before real T2384 integration. | T2384 accepts noncircular T63 handoff → common seam → batch consumer sequence; T2383 has no production batch dependency. |+| Q20 | 2026-10-03 | Keep caller-doc deliverables outside coding-only Rune tasks, with T2383 owner and final completion gate. | Task critic found schema fixtures alone do not discharge promised docs; task-review tracks exact documents/commits after15 without blocking common API delivery. |+| Q21 | 2026-10-03 | Interface1 must compile so RED fixtures fail behavior. | API task peer clarification; no task/DAG/scope change. |+| Q22 | 2026-10-03 | Task plan b58298a and implementation approved. | Parent-verified owner “Approved”, Sentinel_ba4c6123288881918042d6aeb8ba6dc5; start independent make-it-so DAG, shared ownership/test-slot gates remain. |+| Q23 | 2026-10-03 | T2384 owns write coordinator/coordinator-specific tests; defer those edits to coordinated owner. | Direct coordination confirms parent ownership grant. T2383 common result consumers remain independent; no second acceptance/recovery engine. |+++### Implementation sequencing correction: protocol parser dependency++Parent confirmed task13/gpzncvx additionally depends on delivered parser3/gpzncvn. Compiler-valid declaration task1 makes protocol RED drafting parallel, but successful protocol validation must return owned lossless MCPJSONDocument and discovery must consume validated schema fragments. GREEN13 cannot pass honestly against parser placeholders; the added Rune edge prevents a duplicate parser or fabricated success. Scope/task count remain unchanged. Source3 passes and integrates before protocol GREEN13; exact shared test slots remain separately gated.+++### Owner-approved32-level parser interpretation bound++Owner rejected excessive512 headroom after review of representative shapes (ordinary fullRPC7–10; prospective full-receipt batch12, constructed from actual source shapes). Parent proposed32 and owner explicitly agreed at Sentinel_9536d4df532c81919792e70801f128fb: “Yes, sounds much better”. Requirements/design now explicitly qualify whole-payload interpretation: parser-input object/array containers root1/scalars0; generateddepth>32 throws distinctresourceLimit; retaineddepth>32 keeps exacttext/originalisError but unreadable/unestablished evidence. This is an approved resource/preservation amendment, not silent implementation narrowing. Verify31/32/33 and width independently; emitted modern wrappers/schema documents are measured separately. Source baselineRED2 remains valid; added cap assertions need meaningful RED refinement beforeGREEN3.+++### Verified source delivery and next pure streams++Source3/gpzncvn finalcomponent0a93930 integrateddf3c23b. App GREEN31bc425 passed23declarations/50expandedruns; final access-only private initializer proved by positive puremodule/fixture typecheck and negative external construction compile. No app test at the access-only finalcommit is claimed. Expected tasks.md merge conflict preserved verified completion3 and earlier12 plus13->3 edge. New isolated streams fromdf3c23b own presentation RED4 and modern protocol GREEN13; source drafting holds no heavy slot. Earlier worktrees retain ignored test artifacts.++Parent confirmed presentation throwing original-checkpoint API and exact documented object/relationship pointer semantics, and approved ordered/validated metadata representation as lossless contract fulfillment without new user policy. Future stable signatures and regression evidence must be sent to T63 before encoder7/runtime delivery15.+++### Protocol request-ID bound and supplemental resource diagnostics++Parent preferred the existing signedInt request-ID domain as a documented resource bound rather than speculative sharedMCPTypes expansion. Verified primary MCP basic/index requires string/integer nonnull IDs, while RFC8259 sections6/9 explicitly permit number range limits. Preserve exact in-range integral decimal/exponent forms and unchanged arbitrary source/metadata lexemes. New tests cover bounds/overflow/fractions/Boolean/string advice.++Review caught valid33-level input incorrectly mapped to parse-error-32700 by blanket catch. Supplemental testscf900ad exercise clear resource-limit400/-32600 and preserve syntax-32700. The prepared fix is safely retained by SHA outsideGit while only this worker's validator is restored exactly to817a80a for meaningful supplementary RED; original tests and unrelated work remain intact. No heavy invocation without the next exact grant.+### Presentation RED source-shape correction++Before task4 execution, auditing MCPRecordSnapshot and MCPToolHandler+TaskQuery found public task records identify entities with taskId, whereas covered revision fields use id; project records use projectId. Corrected fixture/design wording to the actual public schema. Selector successes nest their record at results[index].task; failed requested identifiers cannot establish entity evidence. Retained pre-pagination root task arrays remain source-compatible. This corrects the selector implementation contract without changing payloads, receipts, revisions or navigation scope.++### Recovery-context conformance correction during task9 review++Review of actual descriptor source `a25bf99` found a representation mismatch: receipt-like known rejection fields could cause follow_source on an applicationBatch or unprotectedMaintenance context, while the approved schema requires their distinct reconciliation shapes. Actual source-only pre-fix exports reproduce both schema rejections and accept the protected control. Source fix `1f20e11` adds only a protectedWrite condition to saved-retry presentation; batch retains ordered original-item keys and maintenance its original tool without an invented key. Whole source/retryAction/text/isError/evidence/category are preserved, protected bytes unchanged, and original 876 schema checks plus three supplemental results pass. This fulfils the approved recovery separation rather than broadening schema/retry policy. App GREEN/task9 completion and API15 delivery remain pending their existing verification/integration edges.++## Owner-approved post-merge client compatibility deferral++On 2026-10-04 the owner explicitly accepted that T2383 actual client compatibility tests may take place after merge, when they pull and deploy Transit on the MacBook (parent-verified Sentinel_c0dbfe3212888191bc01744c855f67bb). AC6.3 remains unverified and is deferred to that post-merge validation; it no longer blocks this authorised merge. Synthetic fixture checks do not establish installed-client compatibility. This amendment does not authorise client setup, persistent settings/feature changes, model turns, MacBook work or deployment here. Local checks, pre-push review and PR Pilot readiness criteria remain required.++Post-merge checklist: verify modern discovery and tool list/call with parsed structuredContent for each intended Codex surface, Claude Code and Claude Desktop against an isolated latest-only endpoint; validate subscriptions for installed clients that opt into them; record unsupported modes and exact negotiation evidence. Preserve original text/replay/cursor evidence during checks.++## Pre-push findings resolved++Four internal pre-push reviewers identified available fresh read categories being lost, missing portfolio snapshot/identity mappings, quadratic catalog relationship scans without operation checkpoints, and missing/stale caller contract documentation. Source fix9c41be6 uses existing provider failure evidence and original-operation checks, preserves text/ordering, and fails closed on duplicate/missing physical identities. Final scoped macOS44 declarations/90 expanded cases, signed-host/inventory checks and lint527/0violations passed. Optional portfolio helper reuse was deferred as a nonblocking unrelated refactor. Required full iOS/UI verification remains separately recorded from these focused macOS results. No external peer-review service was used.
diff --git a/specs/structured-mcp-results/design-review.md b/specs/structured-mcp-results/design-review.mdnew file mode 100644index 0000000..5530df3--- /dev/null+++ b/specs/structured-mcp-results/design-review.md@@ -0,0 +1,47 @@+# Structured MCP results: design review++Status: draft self-validation complete; critic complete; two independent peers complete; final targeted rechecks by critic and both peers found no remaining blockers. Internal mode only; no external-model disclosure.++## Explanation self-validation (explain-like)++Beginner: Transit keeps the saved answer exactly as evidence, then puts readable fields in a separate structured box. Extra labels cannot overwrite the saved answer. A retry asks for the same saved write, not a fresh write. The server first checks that clients speak the approved modern protocol; it cannot switch production until actual clients prove they can use it. The load-bearing assumptions are explicit: the original evidence is authoritative, navigation is unavailable, and installed modern code is not proof of active support.++Intermediate: Each provider declares generated JSON, retained JSON or plain text. A lossless immutable document preserves source tokens and optional error presence; a pure adapter adds deterministic links/categories. Captured pages retain this tool-level evidence and metadata without an RPC ID. Whole modern bytes are assembled inside T63's admitted worker before its publication domain selects response and retained handles together. Single/batch writes preencode a correlated uncertainty fallback before effects; response failures leave saved receipts unchanged.++Expert: Acceptance-state authority remains T2380 validation/transaction; JSON syntactic validity alone does not establish commitment. Unsupported/malformed evidence is a presentation-level unestablished status with no fabricated no-effect classification. Typed value boundaries prevent live models/unchecked Any crossing actors; complete validated raw-fragment insertion avoids numeric coercion. Publication and response selection have no encoding under the lock, and cancellation does not release physical permits early. Modern per-request metadata and HTTP mirrored-header checks precede semantic dispatch; subscription correlation is request-scoped, not session state.++Gaps resolved by explanation: source origin must be declared to distinguish old prose errors from corrupt receipt JSON; source syntactic validity is distinct from established outcome evidence; fallback preparation failure must stop before effects. No unstated activation assumption remains. Production-volume encoding/capacity is the sole measurement risk, with explicit failure/verification paths in design.++## Critic++The internal critic found one blocker: effectful `reassign_duplicate_display_ids` saves before serialization but has no protected key. Adopted: preencode a complete maintenance-specific uncertainty result before effects; preparation failure blocks dispatch; later encoding failure selects bytes directly. Recovery requires fresh scan/inspection and admits possible partial effects, with no invented key or guaranteed retry. Added the parity/test obligations. The critic found no other blocking receipt/schema/publication/subscription contradiction.++## Self-check++All 27 criteria map to components and targeted proof in the design verification table. Every added module serves approved results, recovery, modern lifecycle or frozen-read compatibility. No URL-opening framework, batch execution policy, receipt rewrite, read freshness algorithm, client settings change or source implementation is introduced. The parity audit covers all result constructors/helpers, common dispatch, maintenance, retention, fallback, schemas, notifications and lifecycle consumers. New shared edits require T63 handoff.++## Independent peer validation++Internal subagent mode, as required by the authorised peer fallback; no external model services. Technical correctness/replay/transport and API/maintainability/scope perspectives reviewed the complete design after the critic.++| Perspective | Finding / rationale | Disposition |+| --- | --- | --- |+| Correctness | Nonthrowing generated-JSON parse failure could publish unreadable source with original success flag. | source factory throws for malformed generated JSON; covered reads choose serialization_failure/isError with no publication; retained malformed evidence alone uses unreadable/unestablished. Injected parser-failure proof added. |+| Correctness | Existing maintenance inner encode catch returns ordinary prose error, bypassing outer failure selection. | Inner and final encoding faults both propagate effect-phase evidence to preencoded no-key uncertainty; separate fault tests required. |+| API/maintainability | Lossless fragment handling warranted; full tree must stay private/small. | Keep document private, iterative and cancellation-aware. Optimising inspection must preserve duplicate-key detection, number tokens and deterministic selectors. No alternative lossy Foundation conversion adopted. |+| API/maintainability | Historic permissive schema and current-shape examples are appropriate trade-off. | Preserve arbitrary source values/unknown fields; constrain presentation only and document current variants. |+| Critic recheck | Protected atomic domain/result phrasing must not imply receipt guarantees for maintenance. | Split protected transactions/same-key replay from maintenance existing effects/partial-effect reconciliation. |++Consensus: source/presentation separation, original replay and frozen r1/meta, complete preeffect fallback, latest-only client readiness and T63 handoff are consistent with approved requirements. No reviewer disagreement remains. Measurement and live negotiation prerequisites are explicit; no tests or settings changes run in this phase.++## Shared-owner coordination++Parent relayed T63 confirmation: PreparedReadResult carries full modern/text/structured/_meta/RPC bytes; parsing/presentation/encoding stays outside gate inside original admission/physical lifetime. Frozen tool-level fragments retain original metadata/policy/expiry and charge additional backing before reservation, shared backing once. Continuation wraps only new RPC ID without storage reread/reclassification. No seam blocker and no shared-writer handoff yet. Adopted clarification: protocol validation/immutable availability classification precedes admission; covered tool-domain argument validation stays inside bounded path, with no preadmission MainActor/storage/availability callbacks. Expanded-byte and blocked-encoding tests remain required.++Final protocol audit: primary modern base schema makes error ID optional when unreadable rather than nullable; design explicitly omits such IDs and retains valid correlation. HTTP format/Origin rejection is before dispatch. Primary sources were used because no callable Context7/library-doc lookup was available; no external peer service received project data.++T2384 final semantic alignment: batch owns summary `serialization_failed` with effect evidence unestablished and original item key/index recovery. The common adapter preserves that payload; outcome uncertainty describes its meaning and is not an added public batch receipt-outcome field. Preview saved-context/dirty-write safeguards remain batch-owner decisions, outside this serializer design.++## Design approval++Parent verified owner “2383 and 2384 are approved” at Sentinel_717be95229c48191a7c41b6e5e467e4c, covering T2383 7970a9c and T2384 a5950e99. Proceed task planning only; no implementation/settings/activation/push/merge/deployment authorised. T63 retains common-file ownership/heavy-test slot while fixing the provider regression identified by T2382.
diff --git a/specs/structured-mcp-results/design.md b/specs/structured-mcp-results/design.mdnew file mode 100644index 0000000..d1c6d16--- /dev/null+++ b/specs/structured-mcp-results/design.md@@ -0,0 +1,244 @@+# Structured MCP results: design++Status: approved by owner “2383 and 2384 are approved” (parent-verified Sentinel_717be95229c48191a7c41b6e5e467e4c), covering T2383 design commit 7970a9c. Requirements approved at Sentinel_39b0ca45b1b8819180ac6d9600578f0b. Task plan b58298a and implementation approved by parent-verified Sentinel_ba4c6123288881918042d6aeb8ba6dc5; common-file edits wait for handoff and heavy builds/tests for the shared slot.++## Architecture++One immutable source supplies both compatible text and a versioned structured wrapper. Presentation derives only from that source and explicit execution evidence. The modern HTTP boundary validates before dispatch, and T-63 selects fully encoded read results together with retention publication.++```mermaid+flowchart LR+ HTTP[Modern request validation] --> Dispatch[Validated dispatch]+ Dispatch --> Read[T63 capture or frozen page]+ Dispatch --> Write[T2380 receipt or write outcome]+ Dispatch --> Batch[T2384 application batch]+ Read --> Source[Immutable source evidence]+ Write --> Source+ Batch --> Source+ Source --> Encode[Source and presentation encoder]+ Encode --> Gate[T63 read publication gate or write response selection]+ Gate --> Bytes[Complete HTTP bytes]+```++### Result boundary++`structuredContent` has the following contract. `contractVersion` identifies this presentation contract; a protected write's own `contractVersion` remains inside `source.payload`. The source can be an object, array, scalar or null. `content` retains the existing text string; outer `isError` retains its optional presence and value. `_meta` remains the existing independent T-63 metadata boundary.++```json+{+ "resultType": "complete",+ "content": [{"type": "text", "text": "<original text string>"}],+ "structuredContent": {+ "contractVersion": 1,+ "source": {"kind": "json", "payload": "<original JSON value, not a JSON string copy>"},+ "presentation": {+ "evidence": "established",+ "links": [{"entityType": "task", "entityId": "<UUID>",+ "sourcePath": "/record", "availability": "unavailable",+ "reason": "navigation_not_supported"}]+ }+ }+}+```++The example's payload marker is illustrative; an actual write embeds its original object and a query embeds its original page object/array. `source.kind` is `json`, `text`, or `unreadable`. `json` requires `payload`; `text` requires the original plain message as a JSON string payload. `unreadable` prohibits `payload` and leaves available raw evidence in `content`. Empty strings and JSON null are distinct from missing payload. `presentation.evidence` is `established` when the provider has established its result, or `unestablished` when retained evidence cannot establish an outcome. It is not a fresh storage-validity check and does not assert that an uncertain write committed.++For parseable but unsupported retained outcomes, preserve their whole JSON payload and use `evidence:unestablished`; for malformed retained JSON preserve raw text and original optional `isError`, use `kind:unreadable`, and put diagnostics in presentation. Malformed generated JSON throws a source-adaptation failure: covered reads select T-63's preencoded serialization_failure with isError true and publish no records/cursor/snapshot; effectful writes select their prepared effect-aware fallback. The retained-JSON unreadable branch never substitutes for a generated-success failure. Known plain-text tool errors use `kind:text`, not unreadable evidence. Never classify by attempting JSON parse and then assuming any failure is an ordinary message: the provider declares its source origin. Receipt lookup failure without accessible original bytes uses the existing uncertainty result; the adapter does not bypass receipt validation to retrieve corrupt records.++Unknown source field names are unconstrained and cannot collide with presentation. Do not insert link/category fields into records or receipt JSON. Do not create a new durable result store, acceptance state, namespace, or replay expiry.++### Approved nesting resource limit++Owner amendment Sentinel_9536d4df532c81919792e70801f128fb sets maximum parser-input container nesting32. Count root object/array1 and each contained object/array another level; scalar roots/children add0. Use a distinct resourceLimit failure, not invalidJSON for syntactically valid deeper data. Generated source depth>32 throws before successful publication and follows the existing generated-serialization/effect-aware failure path. Retained depth>32 preserves exact raw text and optional isError but returns unreadable/unestablished evidence; it does not rewrite receipts, reread entities or fabricate acceptance/outcome. Checkpoints still propagate and are never swallowed as unreadable evidence.++Test31/32 accepted,33 resourceLimit, wide2000-record arrays accepted subject to existing byte/admission budgets. Iterative parsing plus this cap bounds recursive value equality/destruction. The cap applies separately to each parser input, including logical sources, protocol request documents and schema documents; modern result nesting gains wrapper levels, so verify full wire response and schema depths separately rather than claiming an output-depth32 guarantee. Unknown historical JSON deeper than32 is an explicit interpretation exception to whole-payload structured access, with exact original text preservation.++### Immutable source and encoding interfaces++New macOS modules live in `Transit/Transit/MCP/Results/`. These are design-level names and contracts; shared-file signatures are installed only after the T-63 handoff.++```swift+nonisolated struct MCPResultSource: Sendable {+ let originalText: String+ let originalIsError: Bool? // nil, false, true preserved distinctly+ let document: MCPJSONDocument? // owned UTF-8 and lossless parsed value+ let kind: MCPResultSourceKind // json / text / unreadable+ let evidence: MCPResultEvidence // established / unestablished+}+nonisolated struct MCPResultContext: Sendable {+ let tool: String+ let semanticFailure: MCPResultFailure? // explicit provider evidence, not message matching+ let mutationRecovery: MCPMutationRecoveryContext? // protected, batch or maintenance evidence+ let entityPositions: [MCPResultEntityPosition] // provider-declared source pointers for its own shapes+}+nonisolated struct MCPResultPresentation: Sendable {+ let evidence: MCPResultEvidence+ let links: [MCPUnavailableLink]+ let errorCategory: MCPResultErrorCategory?+ let recovery: MCPResultRecovery? // supplement only; never replaces original retryAction+}+nonisolated enum MCPResultAdapter {+ static func source(text: String, isError: Bool?, origin: MCPResultOrigin,+ evidence: MCPResultEvidence) throws -> MCPResultSource+ static func present(_ source: MCPResultSource,+ context: MCPResultContext) -> MCPResultPresentation+}+nonisolated enum MCPResultEncoder {+ static func encode(source: MCPResultSource, presentation: MCPResultPresentation,+ id: JSONRPCId, metadata: MCPResultMetadata?) throws -> Data+ static func prepareMutationFallback(id: JSONRPCId, source: MCPResultSource,+ context: MCPResultContext, metadata: MCPResultMetadata?) throws -> Data+}+```++`MCPJSONDocument.swift` validates one complete UTF-8 JSON value and owns a lossless value tree with number tokens retained as validated decimal lexemes. The scanner preserves object members, nulls, array order, strings and unknown fields; rejects duplicate object keys, invalid escapes/UTF-8, trailing tokens and malformed numbers as ambiguous/unreadable evidence. Parsing is iterative with periodic cancellation/deadline checks in covered-read workers; no model objects or unchecked `Any` cross the actor boundary. Preserve large integers/exponents and Boolean versus number without a Double conversion. Encoding inserts only the validated original JSON fragment as `source.payload`; all surrounding strings/keys/metadata are safely JSON-encoded. The document's inspected tree and inserted fragment must represent the same complete value. The writer does not accept an arbitrary raw string as a JSON fragment. Existing `MCPCanonicalJSON` request/revision algorithms remain untouched.++`MCPMutationRecoveryContext` distinguishes protected(tool/key), applicationBatch(provider-supplied original item keys), and unprotectedMaintenance(tool), without introducing a maintenance key. `prepareMutationFallback` accepts the provider's compact logical failure source and produces final immutable bytes before dispatch; it does not execute the provider. `MCPResultSource.swift` contains origin/evidence/recovery value types and factories. `MCPResultAdapter.swift` owns presentation and source selectors; `MCPResultEncoder.swift` owns complete response bytes and preencoded recovery failures; `MCPResultSchemas.swift` owns output-schema descriptors. Provider adapters attach declared source origin and semantic error evidence at construction, rather than inferring intent from localized prose. Parsing/inspection/encoding run once per newly produced logical result; retained pages store the frozen derived form. Large destruction happens outside T-63's publication lock.++`MCPToolResult` gains structured content and `resultType` in T-63-owned wiring. Every tool result passes through this adapter exactly once, including maintenance tools and persistence-unavailable failures. Provider-level results stay logical values until the outer RPC ID/metadata is known; retaining a tool result never retains an old JSON-RPC ID. A raw JSON fragment is encoded by the new result byte writer, not through `AnyCodable`'s Double fallback.++T-2384 supplies its own versioned aggregate logical JSON plus compatible generated text and aggregate optional `isError`. The adapter treats it as one source; it does not flatten or reconstruct nested original item results. T-2384's per-item JSON/text/optional isError/evidence remain batch-owned. A missing/null/false `isError` in original evidence must remain distinct. The common factory returns explicit unreadable/unestablished evidence, permitting T-2384 to stop its prefix without fabricating an item outcome. The common encoder can preencode T-2384's compact logical fallback (`summary:serialization_failed`, effect evidence unestablished, original item keys/indexes for recovery) before effects with original item keys; it does not decide batch execution/continuation semantics or invent a durable batch key.++### Replay, normalization and link selection++`MCPWriteCoordinator.stageTerminal` continues saving the original result JSON and Boolean before the atomic domain/result save; `replay` returns those saved bytes and mapped optional isError. The adapter is downstream of terminal receipt validation and never rereads an entity. For generated writes it uses the saved-record snapshot, not request arguments. Failure to present a retained result never reruns that write or rewrites its receipt.++Ordinary and reusable cursor stores retain original text, validated source/presentation fragments, and the original capture metadata with each frozen page. They retain tool-result bytes independent of request IDs and encode only the new outer RPC envelope on continuation. Link/category construction uses frozen evidence once, not current model reads or wall time. Add retained UTF-8/encoded fragment bytes and metadata to each store's existing 16-MiB accounting, preserving its existing capture/index charges, including all privately prepared pages before publication; avoid double-counting shared immutable backing. Ordinary and reusable stores retain their separate eight-snapshot/five-minute bounds. If expanded bytes do not fit, fail capacity before exposing any cursor/snapshot; no eviction or truncation added.++Link selector tables recognize only documented entity positions for each tool: task/project record, currentRecord, recordBeforeDeletion, query `results`, project-list records, and T-2382/T-2384 provider-supplied typed entity positions. Provider entity positions carry source pointers/entity type for their own documented shapes; the adapter checks the indicated identity token against the same immutable document. Each link identifies the source JSON Pointer, UUID and entity type; traversal order follows source arrays, with source-pointer/entity-type/UUID ordering for object positions. Relationship references use their own pointer (for example /record/projectId), avoiding pointer ambiguity with the task record itself. No recursive guess that every `id` or unknown field is an entity. Task project references use the saved `projectId`, including on omitted-comment records. Missing/malformed identity yields no invented entry. Every identified task/project position has an `unavailable` entry and no URI. Milestones/comments have no fabricated task/project identity. T-572 URL opening and registration remain outside this design.++Saved-field normalization is path-specific and documented in `docs/mcp-result-contract.md` from the actual protected write path:++| Protected path | Existing normalization authority |+| --- | --- |+| create_task / create_milestone | Service creation trims name; description is passed through, preserving surrounding/internal whitespace and newlines when provided. |+| create_project | ProjectService trims name; description is passed through (omitted becomes the existing empty string default). |+| update_task | TaskUpdateValidator trims name and description with whitespacesAndNewlines; omitted description is unchanged, empty-after-trim clears it; internal newlines survive. Metadata remains strict replacement/clear under the validator. |+| update_milestone | MCPWriteCommand.applyMilestone trims name/description; omitted description unchanged, empty-after-trim clears it; internal newlines survive. |+| add_comment / update_task_status with comment | CommentService trims stored content and author; status command's existing empty-comment/author validation remains authoritative. |++Do not project create/direct-service normalization onto update paths. Responses use `MCPRecordSnapshot`, not a second normalizer. Parent display labels (`projectName`, `milestoneName`) are associated display data outside task revision coverage. Revision-covered field comparison excludes those labels, keeps comment-covered r1 when bodies are omitted, and uses the captured/readback saved fields at the same covered revision. Historical source absent/null distinctions are never changed to satisfy a newer shape.++### Error and recovery rules++The presentation category is finite and separate from original code/message/outcome/accepted/retryAction. Prefer explicit provider failure phase; retained writes can use their validated known code/outcome. Unknown historic codes map to `unclassified_historical`, not to a retry promise. Source uncertainty or unestablished evidence takes precedence over a superficially no-effect-looking code. Source retryAction remains authoritative; contradictory or unsupported evidence becomes unestablished/reconcile rather than silently normalized.++| Category | Evidence / examples | Supplemental recovery constraint |+| --- | --- | --- |+| invalid_input | INVALID_INPUT, invalid tool fields | Correct input; new key only if original write evidence establishes no effect and directs it. |+| not_found / ambiguous_identity | TASK_NOT_FOUND, PROJECT_NOT_FOUND, duplicate selector identifiers | Correct selector; never infer prior write effect from current absence. |+| revision_conflict / key_conflict | REVISION_CONFLICT / IDEMPOTENCY_KEY_REUSED | Preserve currentRecord/revision and original retryAction; changed arguments do not reuse a bound key. |+| storage_failure / incoherent_capture | T-63 explicit capture phase, PERSISTENCE_UNAVAILABLE | Identical read retry; writes follow original acceptance/retry evidence. |+| admission_busy / deadline_exceeded / retention_capacity | T-63 READ_BUSY/READ_TIMEOUT; ordinary QUERY_CAPACITY_EXCEEDED and reusable equivalents | No publication. Retry read under provider policy; unchanged write recovery only. |+| invalid_cursor / expired_cursor | INVALID_CURSOR; QUERY_EXPIRED or explicit retained-view expiry | Start a new read; unknown/expired token ambiguity is documented under invalid_cursor. |+| serialization_failure | explicit parser/encoder phase before a complete read | No partial read/publication. For writes possibly committed, use uncertain recovery instead. |+| outcome_uncertain | OUTCOME_UNCERTAIN, may-commit delivery/encoding failure | Original tool/key evidence and reconciliation; never fresh-key advice. |+| unclassified_historical / internal_failure | unknown retained code / explicit unclassified new internal failure | No safe retry inferred; inspect source and reconcile uncertain writes. |++`recovery` describes `follow_source`, `retry_identical_read`, `restart_read`, or `reconcile_original_write`, or `reconcile_maintenance`; original protected tool/key may be included only from trusted request/receipt evidence. It cannot rewrite `source.payload.retryAction`. Failures required for a complete read return the established provider error alone, with no successful records/cursor/snapshot; explicit missing-selector result entries remain successful defined data. No swallowing comment/capture errors as empty collections.++Before dispatching a protected write, prepare a compact modern tool-error response correlated to the current RPC ID and original key with outcome uncertainty/reconcile guidance. If final presentation/encoding fails after possible commitment, select that preencoded fallback rather than the generic `MCPServer.jsonResponse` internal-error path. The fallback reports unavailable delivery evidence rather than claiming the saved receipt is corrupt; the unchanged receipt remains replayable with its original key. Never modify the saved receipt to record presentation failure. If fallback preparation fails before dispatch, return a protocol internal error and execute no write. Actual delivery failure sends nothing further; the caller recovers using the original key. Batch fallback is prepared before its first effect using T-2384's compact aggregate supplied to this encoder; a later failure selects that complete aggregate and preserves known original keys without guessing which unreported item committed.++The effectful maintenance tool `reassign_duplicate_display_ids` prepares a complete correlated modern uncertainty fallback before dispatch. It contains no invented key/accepted binding and reports possible partial effects with `reconcile_maintenance`; recovery requires a fresh `scan_duplicate_display_ids` and inspection of changed identifiers before any further reassignment. `handleReassignDuplicateDisplayIds` must surface its inner encodeAsJSONString failure with may-have-effects evidence to response selection, instead of converting it to an ordinary plain errorResult; both that provider-level failure and final envelope encoding failure select those already encoded bytes; fallback preparation failure prevents reassignment. Delivery loss carries no safe repeat guarantee. The scan itself remains a read outside T-63 freshness/admission scope. The same effect-aware rule covers every future enabled unprotected mutation added to this result boundary.++## Modern protocol boundary++Use [MCP 2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28/basic/index), [discovery](https://modelcontextprotocol.io/specification/2026-07-28/server/discover), [HTTP](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http), and [subscriptions](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/subscriptions) as normative wire definitions. New pure types/validation live in `MCP/Protocol/MCPModernRequest.swift`, `MCPModernValidator.swift` and `MCPModernDiscovery.swift`; existing router/handler/notification hooks remain T-63 owned until handoff. Do not negotiate optional features from prior requests, connection identity or session state.++POST processing order: loopback Origin/Host validation → JSON content-type/response-format negotiation → bounded body read (existing 1 MiB) → single-object JSON-RPC structural validation → request ID/method classification → metadata/header validation → immutable method/tool-name availability classification → T-63 covered-read admission → covered tool-domain argument validation and dispatch. Noncovered tools use normal effect-aware dispatch after protocol validation. Covered argument checks remain inside their bounded worker even when invalid; do not hop to MainActor or call live storage/availability callbacks before admission. Use a frozen availability snapshot for transport classification. Invalid requests never reserve write keys or capture storage. HTTP fixtures send the standard Accept listing application/json and text/event-stream. Reject unsupported request Content-Type with 415 and an unacceptable response format with 406 before dispatch; ordinary results use application/json and subscriptions require acceptable SSE. Modern error responses echo a readable valid request ID; when no valid ID can be read, omit id instead of fabricating null. An Origin rejection is 403 before decoding, without a fabricated RPC ID. Case-insensitive header names have case-sensitive values; duplicated/conflicting required headers are rejected. Decode the standard `=?base64?...?=` Mcp-Name sentinel before comparing it to the body tool name; validate UTF-8/ASCII rules. Transit adds no custom mirrored parameter headers. `params._meta` requires protocolVersion and clientCapabilities object, permits absent clientInfo, and validates supplied known capability fields; unknown extension metadata remains tolerated. The server requires no optional client capability for its ordinary complete tool results.++| Boundary | HTTP / RPC disposition |+| --- | --- |+| Malformed JSON / non-object or array / invalid JSON-RPC envelope or ID | 400; -32700 parse error or -32600 invalid request; use readable valid ID where available. No array dispatch. |+| Missing/malformed required per-request metadata | 400; -32602. |+| Missing/malformed/mismatched required version/method/name headers | 400; -32020 HeaderMismatch. |+| Valid matching version values other than 2026-07-28 | 400; -32022, data `{requested, supported:["2026-07-28"]}`. |+| A genuinely required optional capability absent | 400; -32021 with requiredCapabilities; ordinary Transit methods do not manufacture such a requirement. |+| Unknown method, including initialize/ping legacy methods | 404; -32601 after modern boundary validation. |+| tools/call missing/disabled name or malformed params | Defined -32602 protocol error; no tool effects. Tool-domain failures use complete tool result + isError. |+| GET/DELETE / unacceptable method | 405; Allow: POST; no session header and no SSE GET. |+| Notification-shaped request-only method or unsupported client notification | 400 with no JSON-RPC response to a notification; no dispatch/effects. Current core HTTP methods accept no client notifications. |+| Valid ordinary request | 200 application/json complete result or defined JSON-RPC error. |++Header/body mismatch takes precedence over unsupported-version negotiation when both present disagree. Metadata shape is checked before comparing headers; remaining tool argument-validation precedence is the existing contract inside the covered worker; admission never waits on argument validation. Removing legacy transport does not alter application batch semantics: T-2384 remains one tools/call, not a wire array. Do not add session state, Last-Event-ID resumption, sampling/elicitation, resource/prompt tools, or progress channels.++`server/discover` returns resultType complete, supportedVersions `["2026-07-28"]`, tools capability, and serverInfo under `_meta["io.modelcontextprotocol/serverInfo"]`. `tools/list` returns resultType complete, current enabled definitions sorted by stable tool name, and each outputSchema. Both advertise `ttlMs:0`, `cacheScope:"public"`: local metadata is not client-personalized and clients must refresh rather than retain stale settings-dependent definitions. Tool availability changes still publish subscribed invalidation. Do not mix serverInfo with T-63 read metadata.++`MCPResultSchemas` provides a common self-contained JSON Schema 2020-12 wrapper (`$schema` explicit, local `$defs` only). Its `oneOf` constrains json/text/unreadable source variants, presence of payload and presentation enums/links/recovery; `source.payload` for JSON accepts any JSON value and unknown historic fields. Per-tool descriptions and examples document current record/write shapes without narrowing a historic replay into an incompatible success-only schema. T-2384 can describe its current aggregate payload within its provider descriptor, while the common retained-source branch stays permissive. No network $ref dereferencing or production general-purpose schema validator is added; schema conformance is checked in targeted test fixtures with a standards-compliant 2020-12 validator available in the test environment.++### POST subscription stream++`subscriptions/listen` requires a valid request ID, modern metadata/headers, and an Accept value permitting text/event-stream. Validate notification filter types, acknowledge only supported `toolsListChanged:true`; other valid unsupported filter fields are omitted. An empty supported subset is allowed. Register one request-scoped stream, with an acknowledgement queued before making it eligible for availability notifications. Ack uses `notifications/subscriptions/acknowledged`, params.notifications containing the accepted subset, and params._meta[`io.modelcontextprotocol/subscriptionId`] equal to the original RPC ID. All list-change notifications carry the same ID. Multiple streams receive their own filtered notification; remove the old once-per-session grouping.++A bounded stream queue protects the first acknowledgement from replacement by list invalidation; repeated list invalidations can coalesce after acknowledgement because they instruct refresh, not data replay. SSE uses `data:` JSON messages with immediate flush and no event IDs. Existing tool availability observer calls feed the broadcaster. Disconnect removes its registration exactly once and sends no further messages. Server-initiated shutdown sends the original request's complete result with subscription metadata when the stream can still accept it, then closes; teardown releases all registrations even if that final send fails. Optional keep-alive comments carry no protocol data. No read permit is assigned to this long-lived subscription; it captures no store view and does not change T-63's covered-read capacity.++## Shared ownership and parity audit++T-63 completes its approved capture/admission/publication work first. T-2383 integrates only after a coordinated common-file handoff against that landed interface; if common ownership remains active, implement isolated modules/tests after implementation approval and defer shared wiring. The handoff records symbols/files, base commit, owner and retained concurrency invariants. T-2382 retains aggregation/store policy; T-2384 retains batch operation/effect/fallback policy. This spec does not edit their approved documents or widen T-63's read deadline to batch dry-run.++| Call site or consumer | Equivalent needed | Owner / hook |+| --- | --- | --- |+| MCPToolHandler.textResult/errorResult; validation and persistence-unavailable paths | yes | T-63 hook declares source origin/failure; T-2383 adapter handles both JSON and plain text. |+| MCPWriteOutcome.result; coordinator.stageTerminal/replay | yes | T-2383 downstream adaptation; T-2380 save/replay JSON stays original, no receipt/schema rewrite. |+| query_tasks initial/ordinary cursor, encodeQueryPages | yes | T-63 hook; freeze derived fragments/metadata; complete modern bytes before publication. |+| get_projects/query_milestones including [] and one-record lookup | yes | T-63 capture projection hook; preserve arrays, distinct failure semantics, typed link positions. |+| scan_duplicate_display_ids / reassign_duplicate_display_ids | yes | Common wrapper; effectful reassignment preencodes maintenance reconciliation fallback, outside protected-key/bounded-read scope. |+| MCPToolHandler.handle/handleToolCall request ID and availability checks | yes | T-63 handoff; modern request-only validation eliminates notification dispatch side effects. |+| MCPToolDefinitions.definition factory + tools list | yes | T-63-owned common wiring installs output schemas and T2382/T2384 provider descriptors. |+| MCPTypes result/request/tool/error/notification wrappers | yes | T-63 handoff; omit unreadable error ID (replace legacy nil-to-null), complete/structured/schema/metadata fields without unchecked source cross-actor. |+| MCPServer.makeRouter POST / batchResponse / GET listener | yes | T-63 handoff; single modern validation then admission, reject arrays; replace GET with POST subscription. |+| MCPServer.jsonResponse encoder fallback | yes | T-63 handoff; prepared modern bytes; unsafe generic fallback never receives may-commit protected/batch/maintenance writes. |+| MCPTaskQuerySnapshotStore / T2382 retained pages and prepared publications | yes | Store owners consume complete frozen tool fragments; charge expanded retained bytes; same publication domain. |+| T63 timer/busy/publication-rejection preencoded responses | yes | T-63 hook receives modern encoder/fallback builder; no encoding under gate, unchanged physical finalizers. |+| MCPToolListChangeBroadcaster and +ToolListNotifications | yes | T-63 handoff; request-scoped filtering/ack/correlation replacing session grouping. |+| MCPSettings availability observer; lifecycle stop/start; port changes | yes | Existing events retained; subscriptions torn down, read generations cancel unpublished work, permits survive restart. |+| TransitApp service construction | yes | Inject common pure result encoder and modern adapters into T-63 wiring; one lifetime read coordinator. |+| MCPRecordSnapshot / MCPRecordRevision / MCPCanonicalJSON | no | Existing saved normalization/r1/request identity authority; no equivalent normalizer or revision algorithm. |+| App Intents / UI entity navigation | no | Outside scope; no URL scheme/registration/open handlers. |+| Existing protocol/batch/notification/GET tests and docs/mcp-write-contract.md | yes | Replace legacy expectations with modern single-request fixtures, retain write effects/replay assertions; remove obsolete wire-batch documentation. |++## Read publication and write selection++For covered reads, source inspection, link/category construction, text duplication, metadata encoding and outer RPC assembly all happen in the admitted physical worker before offering `PreparedReadResult`. New copies/encoding remain inside the five-second admission budget, with T-63's existing internal cutoff. Privately reserve expanded retained entries before offering success, using T-63's retainedPage seam with frozen tool-level source/presentation fragments and original metadata/policy/expiry independent of RPC ID; T-63 validates and atomically selects all encoded bytes/publications, or selects its preencoded timeout/busy/capacity failure. There is no post-gate serializer. Cancellation, stopped generation, expiry, capacity or late encoding discard private candidates; unfinished physical workers retain permits until their actual finalizers. Envelope encoding cannot remint page metadata or publish only part of a result. Modern protocol removes wire batch array assembly; it retains the individual terminal/admission gate and store participant contracts.++Protected and effectful maintenance writes remain outside T-63 read admission. Only protected writes retain atomic domain/result receipt transactions and same-key replay; maintenance retains its existing effect semantics and may require partial-effect reconciliation. Preencoded recovery fallback is response selection only, not a durable receipt. A cancellation/disconnect suppresses delivery but cannot reinterpret an already accepted/committed operation as rejected. A new RPC ID with exact original tool/key/arguments finds the same saved receipt. Readiness testing and activation cannot waive these semantics.++## Verification and activation++Use the existing Swift Testing target and HTTP fixture helpers; no test/build runs during this spec phase. Implementation checks run after T-63 releases the heavy-test slot. Add result/protocol fixtures under `Transit/TransitTests/` and a loopback-only, separate-port modern readiness fixture under `scripts/` using the approved encoder/validator. It uses synthetic data/no real writes and cannot replace the running Transit endpoint.++| Acceptance criteria | Design / targeted proof |+| --- | --- |+| 1.1–1.4 | Source wrapper/schema: every enabled tool success/error, arrays/scalars/null, colliding unknown contract/presentation fields, exact text/isError presence; schema accepts all branches. |+| 2.1,2.4,2.5 | Historical receipt fixture replay after entity edit/deletion; unsupported/malformed evidence remains explicit; no writes/expiry changes; retry new RPC ID/same original key. |+| 2.2–2.3 | Ordinary/reusable multi-page frozen text/payload/meta/link equality after edits; omitted comment bodies keep r1; no continuation current-model fetch. |+| 3.1–3.2,3.5 | Table-driven known/unknown codes/phase categories and safe recovery directions; conflicting source evidence never gains safe retry; protocol errors stay outside tool results. |+| 3.3 | Inject required comment/history/capture/storage failures, malformed generated JSON/parser failures and explicit selector absence; whole read has no successful records or publication. |+| 3.4 | Inject postcommit adapter/encoding/delivery faults; durable saved outcome unchanged, modern compact uncertainty with original keys, replay recovers original. T2384 aggregate fallback tested by its owner; maintenance inner provider-encoder and final envelope post-save faults independently select prepared no-key uncertainty and directs fresh reconciliation scan. |+| 4.1 | Name/comment trims and description newline/clear semantics; full read same-covered-revision field parity; parent rename excluded; revision unchanged by wrapper. |+| 4.2–4.4 | Duplicate display IDs/distinct UUIDs, missing/invalid IDs, unknown nested IDs, terminal deletion/edit replay; deterministic unavailable entries with correct source pointers, no URI. |+| 5.1–5.4 | Modern discovery/list/call, metadata/header/base64 mismatch/error HTTP matrix, unknown/legacy method, arrays/null IDs/notification mutations no effects, complete/cache fields and sorted tools. |+| 5.5 | POST SSE first acknowledgement cannot coalesce away; accepted filter only, multiple request IDs, availability changes, disconnect/shutdown/port-change cleanup. |+| 5.6 | Existing Origin/Host/loopback negative tests across every POST/GET/DELETE route, no captures/effects before rejection. |+| 6.1–6.2 | T63 fake-clock/barrier tests block parser/large encoding beyond cutoff, cancel during preparation/publication; eight physical workers across restart, 16-MiB expanded-page boundary for both stores; no partial IDs. |+| 6.3 | Actual intended Codex CLI/desktop-host surfaces, Claude Code and Desktop isolated endpoint evidence: request metadata/headers/discover/list/call parsed structured result; conforming subscription fixture and opted-in surfaces. |++Property checks use Swift Testing with a deterministic seeded generator, avoiding a new runtime dependency. Generate nested valid JSON with UTF-8 strings/escapes, unknown keys, missing/null pairs, Boolean/numeric alternatives, integer boundaries and decimal/exponent tokens; assert exact text preservation, inserted payload token preservation, no namespace collision, deterministic presentation and roundtrip parser/writer. Shrink failures by removing fields/elements and reducing strings/tokens; invalid mutation corpus verifies rejection of duplicate keys/trailing tokens/malformed escapes. These checks complement hand-built historic receipt and lifecycle/transaction fixtures; they cannot establish store atomicity alone.++Actual installed-client modern activation is a prerequisite, not inferred from embedded symbols. The read-only evidence is in ADR1. First prove the isolated endpoint with a conforming client; then record live discovery/list/call negotiation for each intended installed surface. If a runtime requires a feature flag, connector edit or upgrade, stop and request that exact change through parent with evidence; this design approves no client settings edits or external model service probes. Keep production on its existing endpoint until modern readiness and a separately authorised activation/cutover are satisfied; do not supply a legacy compatibility endpoint.++Risk: duplicated source/text/metadata may exceed existing retained-page budgets or five-second encoding cutoff at production-shaped volumes | Verify: early synthetic 2,000-record/multi-page measurement after implementation approval and T63 test-slot release | If wrong: fail defined capacity/deadline without publication; optimise shared immutable backing/streamed private byte assembly without reducing evidence or extending limits.+++### Implementation interface clarifications++Parent confirmed throwing presentation checkpoint API before RED4: `present(_:context:checkpoint:) throws`, with a default original-worker Sendable checkpoint. Expensive traversal propagates deadline/cancellation rather than inventing a presentation category; callback lifetime is synchronous and never retained in a frozen result. Known provider positions may identify a documented record object (read its public `taskId` or `projectId` according to entity type, report /record) or a relationship UUID token (report /record/projectId). The revision-covered internal `id` field is not the public task-record identity field. Selector query successes identify /results/index/task and its projectId relationship; requested identifiers in failed selector entries do not establish entity evidence. Retained pre-pagination task arrays identify /index using the same public taskId field. Link sourcePath remains that declared/documented position; no recursive UUID-field guessing.++Parent confirmed metadata must use ordered members or a validated owned document before encoder7/delivery15, avoiding dictionary reconstruction/canonical-key collapse and preserving unknown fields, nulls and numeric lexemes. Exact metadata declaration is coordinated with T63 before runtime binding; Reads remain T63-owned. Discovery/list may assemble their own complete envelope with bounded encoded scalars plus raw validated schema UTF8, without copying the common tool-result/fallback serializer or introducing a reverse dependency on7.+++### Request correlation numeric resource bound++Retain existing JSONRPCId signed Swift Int representation on macOS (64-bit), without new shared-type cases. Parse decimal digits/exponents exactly without Double; mathematically integral1.0/1e0 and other in-range spellings map to their exact integer value. Out-of-range numeric IDs reject clearly before dispatch and can be replaced by a string ID within the1-MiB body bound. Fractional/Boolean/null/object IDs remain invalid. This bound does not limit source/metadata number tokens. Primary normative references: MCP2026-07-28 basic/index requires string/integer request IDs; RFC8259 sections6/9 permit numeric range/resource bounds.++Resource-depth failure in a protocol request is distinct from malformed JSON: validdepth>32 returns HTTP400/-32600 with a clear parser resource-limit diagnostic, while malformed syntax/UTF8 remains HTTP400/-32700. Neither path classifies a tool, captures storage or accepts write keys. Supplemental RED compares new bounds/depth fixtures against earlier817a80a before applying the prepared narrow GREEN refinement.
diff --git a/specs/structured-mcp-results/encoder-green.md b/specs/structured-mcp-results/encoder-green.mdnew file mode 100644index 0000000..9fd5647--- /dev/null+++ b/specs/structured-mcp-results/encoder-green.md@@ -0,0 +1,51 @@+# Encoder implementation draft++Status: task7/gpzncvr is complete after corrected guarded GREEN14/14, clean exit0 and finalised xcresult. Earlier oracle failures and teardown limits remain recorded below. API15 remains undelivered.++MCPResultEncoder now freezes complete tool-level bytes and wraps them with fresh current string/integer RPC IDs, preserving resultType, original text, structured source kind/payload/evidence, optional isError and independent metadata. Original source and metadata documents are inserted as their validated raw UTF8 fragments; member ordering, numeric lexemes, escapes, scalar-distinct nested keys and null/presence survive. The sealed fragment initializer remains local to the encoder; fragments retain Data only and never originating IDs or callbacks.++MCPResultMetadata.make validates object-root documents and modern ASCII top-level namespace keys, retains the exact owned document and preserves unknown nested values. A worker-local writer escapes text byte-safely and checks the original throwing callback at entry, bounded strings/keys and raw4KiB copy stages. Typed cancellation/deadline errors propagate without becoming serialization/unreadable outcomes. Returned bytes retain no callbacks. Parser input depth32 stays distinct from valid higher-depth complete response wrappers.++Provider-owned mutation fallback preparation returns full current-ID modern bytes before effects. Presentation forces unestablished/outcome_uncertain supplemental reconciliation, preserves provider source/text/isError/metadata, and uses links:[]. Protected recovery retains original tool/key; maintenance adds no invented durable key/acceptance; batch recovery keeps ordered index/operation/tool/key/target UUID while omitting itemId only from fallback presentation. Normal payload/itemId data is not clipped or rewritten. No new receipt namespace or batch logical outcome is added.++All14 task6 fixtures remain byte-identical to a480d06. Parse, targeted no-cache lint and pure full Results/test typechecks pass. Evidence .codex-cache/encoder-green-typecheck/manifest.json, SHA256 f68dcafc8381bcaf40a4b3dfa73606c09b378aabf209c6168cfd2edaa58e886a. Internal read-only critic found no blocking source defect. These light checks and review are not runtime GREEN.++Next requested selection is unchanged: TransitTests/MCPResultEncoderTests TransitTests/MCPResultEncoderFallbackTests. A new exclusive parent grant is required for guarded build-for-testing, inspected signed development host/xctestrun and restricted serial test-without-building. No app job follows the prior RED grant. Task11 retains preparation accounting/capacity proof; task14 retains actual production response selection/effect guarantees. Shared MCPTypes/server/handler/Reads/snapshots/WriteCoordinator/App/project source remains unchanged by task7. No live/client-setting/production activity occurred.++## First guarded GREEN attempt++Parent granted the same14 unchanged fixtures on3ba1cfb (observed HEADdd4a89b differed only in documentation). Shared Debug rebuild and actual signed-host/xctestrun preflight passed exit0, with explicit unit-test/smoke/exact-host guards. Prior RED artifact hashes were preserved when reusing only the private DerivedData dependency products; fresh GreenBuild/EncoderGreen result paths were used.++The original console reports14 methods:12 passed,2 failed,2 issues. rawPayloadAndFrozenMetadataPreserveExactOwnedFragments and depth32InputsRemainValidWhenEnvelopeAddsNesting fail inside the independent helper's Foundation JSONSerialization whole-wire validation with NSCocoaError3840 Number wound up as NaN on valid1E-9999. Internal read-only critic confirmed a fixture-oracle defect: the production encoder inserts validated raw numeric fragments without conversion. The two methods' exact-byte/depth assertions remain unverified. No production semantic change is justified by Foundation's numeric limitation.++A post-body hang recurred. Both exact owned processes were sampled before any termination. The guarded host61003 main chain included XCTestDriver→XCTTestRunSession→XCTAsyncEnumerateWithWaiter→XCTWaiter._performWait; runner60967 showed CFRunLoop waitForBuild. No collectSimulatorDiagnostics frames were observed and the underlying cause remains unproved. After bounded5m11s, only the identity-verified runner first and then guarded host were terminated. Actual command exit143; summary extraction exit64 because the unfinalized bundle lacked Info.plist. No clean exit or final xcresult counts are claimed. No automatic replay or second command occurred. Owned pipelines/hosts drained and parent received immediate slot RELEASE.++Evidence .codex-cache/t2383-encoder-green-3ba1cfb/results.md includes manifests, commands, console-method classifications, source/fixture hashes, both samples and scoped cleanup. Prior RED logs/raw bundle remain unchanged.++Parent authorised a narrow helper correction after drain: lexically validate number tokens outside strings, reject malformed spelling/junk, substitute0 only in a disposable Foundation structural-validation copy, discard the decoded tree, and keep raw locating/equality on original bytes. Preserve all14 method files/inputs/assertions and the production parser cap/semantics. Source-only correction and helper controls are delegated; critic review and a fresh focused guarded grant are required before rerun. No app/GREEN retry, production/live/client-setting change follows this attempt.++## Narrow oracle correction readiness++Parent-approved fixture-only correction ffe2c33 changes rawFragment's validation call and adds MCPJSONEnvelopeFixtureValidation. It strictly validates numeric spellings/token boundaries outside quoted strings before substituting valid numbers with0 in a disposable Foundation structural-validation copy. Escaped strings remain intact; Foundation checks complete structure/escapes/trailing input and its decoded tree is ignored. Raw locating and exact equality use original bytes exclusively.++Actual-helper standalone controls passed11 valid/20 malformed cases, including underflow/huge exponents, exact integer/-0, escaped quotes/numeric-looking strings, wrapped depth32, bad leading zero/fraction/exponent/adjacent junk/trailing input/escapes. Parse, targeted lint and pure module/test typechecks pass. Production Results source is byte-identical to3ba1cfb and both14-method test files to a480d06; no assertion/input was weakened. Evidence .codex-cache/encoder-oracle-correction/manifest.json, SHA2565c04988715f0bc5b7e8f5d40a3a99cdc51898961fdb66687dbb78b0005cc7fa0.++Internal critic cleared the correction with no rerun blocker. The parent received the same focused two-suite guarded GREEN request. No app rerun has occurred under the correction; task7 remains in progress and API15 undelivered.++## Corrected rerun approval restriction++Parent delegated a new exclusive guarded rerun on ffe2c33 (observed49f18ba documentation only). Before any process launch, per-command require_escalated automatic review rejected the whole build/preparation command: it treated the delegated grant as untrusted assistant context and could not establish a trusted-owner exception to the original heavy-test prohibition. No build/test/preparation session, process or new run artifact was created. The command was not retried through default permissions, another worker or wrapper; no global permission/configuration change occurred.++Parent received the exact restriction and a request for explicit owner transcript/approval evidence supporting a reviewed retry of the same command. The unused reservation was released; fresh parent slot confirmation is required before any future retry. Task7 remains runtime-blocked, source/fixture identities unchanged, and API15 undelivered. The prior12/2 attempt remains the latest runtime evidence. This is an approval provenance restriction, not a new source defect.++## Corrected guarded GREEN acceptance++Owner approval Sentinel_10e284fb472881918fb01fad1bde10d2 explicitly approved all testing and necessary fix reruns, in response to Sentinel_5b0aef7ba7508191ac141c72ac13cde3 (local isolated development builds/lint/unit/simulator tests and per-command escalation; live data/client activation/deployment separate). The original runner had become unavailable. Parent explicitly authorised one replacement after this fresh approval, preserving the action and ordinary review. Before replacement, escalated process inspection found no former owned encoder pipeline.++The replacement submitted the SAME preserved command exactly once through normal per-command review; SHA25608ee54389a2da2f87c8878b90bba9d81cf50c0aeb2f46d42652230d7b66ce4db. Review accepted and the guarded build started. No command alteration, permission change or alternate approval route occurred. Observed source7547294 differs49f18ba only in blocker documentation; production Results remains3ba1cfb, both14-method filesa480d06 and corrected helperffe2c33.++Build-for-testing and new actual signed-development-host/xctestrun preflight exited0. The same two restricted suites ran serially under unit-test/smoke/exact-host guards with fresh result paths. Both completed cleanly:14 methods/14 executions passed, zero failures/skips and no runtime warnings, test commandexit0. The finalised xcresult confirms these counts. This executes the earlier unreachable exact raw-source/_meta and depth32 assertions as well as all64 seeded/18 optional-error loop samples and synthetic fallback/checkpoint cases. No teardown hang, sampling or cleanup intervention was needed on this corrected run.++Read-only escalated process inspection found no owned build/test pipeline or guarded host; the slot was released immediately before extraction. Prior RED and failed GREEN hashes were checked unchanged. Evidence .codex-cache/t2383-encoder-oracle-green-ffe2c33/results.md, commands.json, xcresult-summary.json, source-fixture-sha256.json and artifact-sha256.json; final result DerivedData/t2383-encoder-red-a480d06/EncoderOracleGreen.xcresult. Initial summary extraction encountered a sandbox cache restriction; the same read-only extraction succeeded under normal per-command escalation, without test replay.++Rune7/gpzncvr is complete. Next ready task8/gpzncvs is schema RED preparation; schema/provider/preparation-budget and production selection gates remain ahead. API15 is not delivered. No production/live/client-setting activity occurred and subsequent heavy slots still require parent coordination.
diff --git a/specs/structured-mcp-results/encoder-red.md b/specs/structured-mcp-results/encoder-red.mdnew file mode 100644index 0000000..12bd25e--- /dev/null+++ b/specs/structured-mcp-results/encoder-red.md@@ -0,0 +1,27 @@+# Encoder RED fixture preparation++Status: task6/gpzncvq completed after meaningful guarded runtime RED and read-only review, with abnormal report finalization documented below. Encoder GREEN7 and API15 delivery remain pending.++Draft source a480d06 contains14 declared test methods (9 in MCPResultEncoderTests,5 in MCPResultEncoderFallbackTests), including64 seeded immutable source cases and18 optional-isError/source samples. Tests specify complete current-ID RPC envelopes, original text, source payload numbers/member identities/fragment bytes, plain/unreadable source differences, owned independent metadata, exact frozen tool/_meta bytes and new IDs, depth32 inputs with independently inspected complete wire envelopes, and original typed cancellation checkpoints without retained closures.++Five explicitly synthetic effect-harness tests specify fully deliverable prepared protected/batch/maintenance fallback bytes before effects, zero effects on preparation failure, failed post-effect encoding selecting previously prepared bytes without re-encoding, batch recovery excluding giant itemId only from fallback presentation, and depth33 aggregate failure after effects retaining original recovery evidence. This is synthetic encoder/selection verification; it does not establish production provider dispatch, transaction or transport selection, which remains later task14 and owned integration.++The minimal declaration refinement gives metadata a private constructor and validated object-document backing, seals frozen-fragment construction at the encoder file boundary, and adds default operation checkpoint parameters. Metadata.make and all encoder methods still throw notImplemented. No shared MCPTypes/server/handler/read/coordinator or App/project source was edited for this fixture package.++Light checks passed: parse, targeted no-cache lint, pure Results plus fixture typecheck using actual read-only MCPTypes/MCPReadMetadata, and external constructor negative probes. Evidence .codex-cache/encoder-red-typecheck/manifest.json (SHA256 ac60a2dcd26ce0b7b3f9b88ddfbd5b6f167f44e14bd0becf36faf29e9ca16fea) and adjacent logs. These are source/light checks, not application behavioral RED. Final read-only critic cleared a480d06 with no blocking fixture/interface gap; earlier raw-fragment and depth32 findings are addressed. The later guarded runtime RED and its report-finalization limitation are recorded below.++Exact next suite selection: TransitTests/MCPResultEncoderTests TransitTests/MCPResultEncoderFallbackTests. Parent receives a request for an exclusive slot after critic clearance and T2382 drain. Use build-for-testing, signed development-host/xctestrun preflight with explicit unit-test/startup guard, and restricted serial test-without-building. A direct make test invocation is not granted by this note. No app launch follows during T2382's slot; live MCP/client settings/production activity remain held.++## Actual guarded runtime RED++The parent granted exactly these two suites on7a3a740/a480d06. A fresh private shared Transit Debug build-for-testing succeeded exit0. Signed host and generated launch preflight passed: development identity, no CloudKit/push/App Group entitlement, explicit unit-test mode, TRANSIT_ISOLATION_SMOKE=1, exact host path and restricted unit-test selection. Application compilation, launch and isolation were successful.++The original console reports14 methods/2 suites failed,0 passed, with18 issues. Every issue is attributable to declaration-stage notImplemented boundaries: metadata construction6 methods (including all4 negative-input expectations), direct encoding4 methods, fallback preparation3 methods (including missing typed checkpoint invocation), and frozen preparation1 method. Runtime critic found no fixture/oracle/environment blocker. Early throws prevented later loop variants, exact-byte/depth-envelope and post-effect-selection assertions. The64 generated samples and all18 optional-error combinations were not fully executed; these remain GREEN acceptance obligations.++## Report-finalization limitation and drain++After test bodies completed, the exact owned guarded host54550 and Xcode54536 remained asleep for a bounded4m15s. The worker terminated only54550 before a crossed parent sample instruction arrived; no pre-termination host sample exists. Xcode automatically replayed13 tests with17 stub issues inside the same single command; this was not a requested second run and is preserved separately.++A bounded sample of still-owned Xcode54536 was captured before its termination. It showed main CFRunLoop waitForBuild and idle SwiftPM/work queues; no collectSimulatorDiagnostics frames were observed. Neither this nor Linkd messages establish the hang cause. No diagnostics suppression was introduced. At bounded7m, only the identity-verified runner54536 and its guarded replay host55974 were terminated. The actual command exited143; this is not an ordinary clean RED exit65. The xcresult summary extraction exited64 because the unfinalized bundle lacked Info.plist; no final bundle counts are fabricated and the raw bundle remains untouched.++Read-only process inspection confirmed all owned pipelines/hosts drained; parent received immediate RELEASE before extraction/bookkeeping. Parent explicitly authorised no repeat solely for teardown if meaningful failures and limitations are recorded. Internal runtime critic confirmed meaningful RED with no fixture blocker. Rune6 is complete; task7 source work is authorised, but no task7 application GREEN run follows this grant. Evidence: .codex-cache/t2383-encoder-red-a480d06/ (build/red logs, signed preflight, per-method failure-classification.json, sample, attempted summary extraction and manifests). No live/production/client-setting activity occurred.
diff --git a/specs/structured-mcp-results/encoder-review.md b/specs/structured-mcp-results/encoder-review.mdnew file mode 100644index 0000000..4daf2e6--- /dev/null+++ b/specs/structured-mcp-results/encoder-review.md@@ -0,0 +1,33 @@+# Encoder fixture review++Reviewed source a480d06 read-only after parse/lint/pure typecheck and constructor-negative checks. Final critic found no blocking fixture or interface gap.++Earlier review required structurally located exact raw source/_meta fragment bytes rather than tree equality alone, and accepted depth32 source/metadata with a separate full-envelope oracle because wrapping adds nesting. Both are addressed.++The synthetic fallback driver makes appropriately limited claims: prepared bytes/current IDs/error presence/metadata/recovery, no synthetic effects after failed preparation, and shallow ready fallback selection after post-effect depth failure without re-encoding. It does not claim production dispatch, receipt atomicity or network delivery.++Task6 is source-ready for a parent-granted guarded focused RED run. No runtime RED was performed; task7 is unimplemented, common API15 undelivered. No reviewer source edits, test/build or live calls occurred.++## Runtime RED review++Original guarded console evidence establishes14 failed methods/18 declaration-stage issues, all attributable to notImplemented boundaries. No fixture/oracle/environment blocker was found. Early throws left later sample combinations, fragment/depth assertions and post-effect fallback selection unexecuted; source inventory is not complete runtime coverage.++Review accepts task6 RED completion under the parent's explicit no-repeat-for-teardown instruction while retaining scoped termination, automatic replay, actual exit143, unavailable final xcresult counts and unproved hang cause as separate limits. Task7 is still pending actual implementation/GREEN verification; no API15 delivery follows.++## Task7 source draft review++Exact draft3ba1cfb is source-ready with no blocking defect found. Review confirmed raw source/metadata/optional isError/current IDs/higher-depth envelopes, sealed frozen bytes and typed checkpoints without retained closures. Complete mutation fallback bytes preserve provider data and separate original protected-key recovery from no-key maintenance reconciliation; batch itemId is omitted only from fallback presentation.++This review establishes neither application GREEN nor API15 delivery. Preparation accounting/capacity remains task11; production selection/effect integration remains task14. No source edits, app tests, heavy commands or live calls were performed by the reviewer.++## First GREEN oracle diagnosis++The two failed methods are fixture-oracle defects, not evidence of encoder corruption: Foundation JSONSerialization rejects valid1E-9999 before raw byte extraction. The encoder's raw insertion does not convert these numbers. Review approves a narrow validation-only surrogate copy after strict numeric lexical validation, using Foundation only for complete structure/escape/trailing validation and ignoring its decoded tree. Raw extraction/equality must remain on original bytes; preserve all14 methods/inputs/assertions and production depth32 semantics. Add standalone helper controls for malformed numeric spelling, escaped strings and trailing junk. The attempt remains12 passes/2 failures and task7 requires a new authorised rerun. No source edits or tests were performed by the critic.++## Oracle correction review++Reviewed exact ffe2c33. Strict grammar rejects malformed numbers before validation-only substitution; quoted strings remain intact, and Foundation validates the full disposable structure. Original bytes alone supply extraction/equality. Production files and all14 test methods remain unchanged. No blocker to requesting the same-suite guarded rerun; task7 is pending application GREEN and API15 undelivered. No reviewer source edits or tests occurred.++## Corrected runtime GREEN++Finalised xcresult confirms all14 methods/executions passed,0failures/0skips; build/preflight/test exit0 with no hang/intervention. Production source and all14 method assertions remain unchanged; only the previously reviewed independent validation helper was corrected. Earlier exact-fragment/depth assertions and all source/error samples now execute. Source critic and oracle critic were already clear; no new code change or test failure justifies repeating verification. Preparation accounting/capacity and real production selection remain separate later obligations.
diff --git a/specs/structured-mcp-results/fixture-coordination.md b/specs/structured-mcp-results/fixture-coordination.mdnew file mode 100644index 0000000..a3068a5--- /dev/null+++ b/specs/structured-mcp-results/fixture-coordination.md@@ -0,0 +1,28 @@+# Shared fixture coordination after T2382 partial full run++Read-only reviewed evidence: task-2/t2382-review-evidence/final-verification/green-6abe659f4ae2fdd9aa7ff95adb85667cfd9169fe/results.md and root-actual-partial-results.json. Actual build0,2248 compiled declarations, partial execution with90 assertion issue lines and176 NIO misuse lines. These are line counts, not complete failed-body counts; no finalized result or full PASS. Existing logs and limitations remain untouched.++Common MCPHTTPTestHelpers.respond currently crosses async suspension with EmbeddedChannel and synchronous defer finish. Parent requested a separate narrow ownership repair: use supported owned async testing channel/loop and explicit success/error teardown; preserve every input/default/header duplicate/body/authority/signature and response collation. Do not automatically add modern metadata or mirrored headers, since that would conceal malformed/security negatives. No warning suppression or assertion removal. Subscription tests retain their explicit long-lived body ownership instead of collecting an infinite SSE body through this ordinary-response helper.++T2382 owns its restored MCPPortfolioFoundationHarness migration. The first observed NIO warning cluster follows mixedFixtureWaitsForProtectedWriteAndPreservesSavedReceipt, which belongs to MCPPortfolioReadFoundationTests in that worktree. T63 owns the separate MCPReadCoordinatorTests EmbeddedChannel usages at29/170; preserve deadline, pre-admission, saved receipt, timeout/busy/invalid and physical-worker assertions when repairing their ownership. T2383 does not rewrite those retained fixtures.++Legacy protocol/transport/null-ID/notification/batch fixtures and fixed tool/schema counts need explicit owner migration to approved latest-only behavior while preserving security and effect evidence. The stalled MCPWriteLifecycleTests request lacks required modern metadata and waits indefinitely for an allocator never admitted. Migrate the caller explicitly and bound its gate wait; preserve accepted cancellation, receipt transaction and exact-key replay assertions. Do not classify unexercised obligations as harmless or remove them. WriteCoordinator-specific sources remain T2384-owned.++Task19 independently migrates the owned availability notification fixture and uses explicit async channels. Its static source review or later focused GREEN cannot establish closure of the full-run failures. Each exact owner patch and focused verification must be recorded separately before another broad run. No source change was made in other worktrees by this review.++## Delivered T2383 source fixes++Shared ordinary HTTP helper4ddbfc8 and five modern protocol fixture ports405ffc7 are independently reviewed and committed. The latter preserves47 declarations/62 expected cases; root verifies all5 committed bytes and original/current declaration counts. Producer source868ed04 remains separate. See modern-fixture-handoff.md for exact scope and focused proposals. No actual compilation, GREEN or full-unit acceptance was performed. Historical write lifecycle was subsequently assigned and delivered as recorded below.++## Subsequent parent assignments++The parent explicitly assigned historical MCPWriteLifecycleTests.swift solely to T2383 for transport fixtures, without write coordinator ownership. Its bounded acceptance/cancellation/receipt replay migration proceeds separately. The preserved duplicate-name rejection with distinct keys has two accepted receipts; a separate same-key/different-valid-arguments control proves IDEMPOTENCY_KEY_REUSED/accepted=false with one receipt. This preserves both domain and key-conflict coverage without changing coordinator logic; T2384 coordination is routed through the parent. Latest parent report identifies T1734 as active heavy-slot owner.++The parent accepted T63's meaningful six-case catalog READ_FAILED RED with its unfinalized limitation and authorised exact source consumption. Owner d2648f6 was imported21356d5, both posthashes verified. Six fault cases and13 diagnostic bodies still await owner runtime GREEN.+++## Historical write lifecycle source delivery++Parent-assigned transport-only migration committed e00e9a0e28ecfb5f40f9c140ae22d24840693f55. Five declarations/six expected cases retain first commit, distinct-key duplicate-name rejection (accepted=true/two receipts), same-key argument conflict (accepted=false/one receipt), revision and missing-safety controls. Cancellation waits for actual allocator entry after durable acceptance using a bounded rendezvous; release/drain covers every path. New-responder replay checks rejected/accepted=true/CANCELLED, no created task, one receipt and exact saved resultJSON UTF-8 bytes. Coordinator and production sources are unchanged. Final source SHA2561017a043d588081d5bb9381b8b51215b1ce7d3017093be41ffdc2734b18d5ec5; parse0/strict no-cache lint0/diff0/internal critic SOURCE CLEAR. Root matched source bytes and retained five declarations. Evidence: `.codex-cache/task19-write-lifecycle-port/` and `.codex-cache/task19-root-review/write-lifecycle-verification.json`. No compile/runtime GREEN.++Historical focused selection is five declarations/six expected cases. Including it with the existing proposals yields ten suites/77 declarations/109 expected cases; actual compiled inventory must establish those counts. T63 Settings two-method owner cleanup remains missing, so guarded build preparation stays fail-closed. Parent schedules focused verification; latest reported heavy-slot owner is T1734. No new full run before focused cases pass.
diff --git a/specs/structured-mcp-results/implementation.md b/specs/structured-mcp-results/implementation.mdnew file mode 100644index 0000000..d046a23--- /dev/null+++ b/specs/structured-mcp-results/implementation.md@@ -0,0 +1,509 @@+# Structured MCP results: implementation evidence++## Authorisation and ownership++Task plan b58298a/implementation approved by parent-verified Sentinel_ba4c6123288881918042d6aeb8ba6dc5. make-it-so delegates all coding; the main worker owns bookkeeping, coordination and review. Single ready stream1 begins interface1 in place; once1 completes, pure Results/Protocol streams may use isolated worktrees.++T63 retains common handler/types/router/definitions/lifecycle ownership pending exact verified handoff manifest. Reads foundation remains shared with T2382; no blanket transfer assumed. T2384 owns MCPWriteCoordinator.swift/coordinator-specific tests; T2383 modifies only downstream consumers unless a coordinated owner patch is agreed. T2382 currently holds heavy-test slot, then T63 focused10/11, then requested short T2383/T2384 RED/GREEN slots. Source drafting holds no test slot.++Transit ticket moved to in-progress with protected committed outcome, key T2383.implementation-approved.20261003 and revision r1:98d5c0bb10c440984383379166f4c98391519018e7c1bc694a12fcc8af04bd62. Source main/origin remain verified201205bd at implementation start.++## Isolated schema test tool++Owner approved recognised-PyPI disposable local install at Sentinel_5afe0d1e8fe081919db67f470430fb2a. Created ignored `.codex-cache/schema-tests/venv`; pip isolated install from https://pypi.org/simple succeeded, Draft202012Validator import confirmed. No global packages/settings or app runtime dependency. Resolved versions:++| Package | Version |+| --- | --- |+| jsonschema | 4.25.1 |+| jsonschema-specifications | 2025.9.1 |+| referencing | 0.36.2 |+| rpds-py | 0.27.1 |+| attrs | 26.1.0 |+| typing_extensions | 4.16.0 |++Schema tasks8–9 must commit test-only pinned dependency/bootstrap instructions/code using these resolved versions for repeatable local/CI environments. Availability alone is not schema-validation completion. No production schema fixture validated yet.++## Pending execution evidence++Interface1/gpzncvl completed at `8ea94ce0b3b9a3b73fcee330aed0c9883a08e92f`: eight new Results/Protocol declaration files, throwing runtime placeholders. Targeted parse, strict no-cache SwiftLint, and standalone Swift6/default-MainActor typecheck of only new modules plus read-only MCPTypes all passed. No application build/test or shared source edit at this checkpoint. RED/GREEN evidence will name exact focused commands/results and slot ownership. Common API delivery15 requires verified local revision; no reverse dependency on production T2384. Client negotiation/activation, full pre-push/Pulsar completion review and push/merge/deployment boundaries remain explicit.+++## Parallel RED preparation++Rune phase/streams retrieval after task1 reports stream1 task2 and stream2 task12 ready. Created isolated worktrees from8ea94ce under `.claude/worktrees/results-stream-{1,2}`, branches `stream/structured-results-{1,2}`. Stream1 owns lossless/source RED fixtures; stream2 owns pure modern-protocol RED fixtures. Both may draft/parse/lint only while the parent schedules exact heavy test slots. No GREEN/completion claim before meaningful RED evidence. Their task statuses are isolated until integration; the root task list remains authoritative for merged completion.++Concrete declaration-only interface sent to T63/parent and T2384: `MCPResultAdapter.source` preserves text/optional isError/origin/evidence; `present` derives separate presentation; `MCPResultEncoder.freeze` returns immutable encoded tool-result Data without RPCID, and `encode(fragment:id:)` wraps a fresh ID. `prepareMutationFallback(id:source:context:metadata:)` returns complete immutable response Data prepared before effects. T63 retains retention/publication hooks and charging; T2384 retains coordinator policy. Runtime delivery gate15 remains pending.+++## Declaration review and lint++Root `make lint` passed both host ownership/schema preflights and SwiftLint: zero violations across405 discovered Swift files. This command runs no application build/tests. Internal design critic found no task1 declaration blocker, with required downstream checks: encoder accepts only valid immutable source/frozen fragments; expensive presentation/freeze/encoding honor original-operation checkpoints; recursive value equality/destruction must be stack-safe or nesting explicitly bounded. These are implementation verification obligations, not delivered runtime capabilities.+++Parent confirmed mechanical dependency correction: task13 also blocked by task3. Protocol RED drafting remains parallel; its GREEN waits parser delivery/integration. Final review must reflect this corrected DAG rather than claim independently executable protocol implementation.+++## RED draft readiness++Isolated stream1 draft `498d515` (afterd255562) contains JSON document/source properties plus seeded fixture/shrinker; stream2 draft `a928cb7` (after26f4dda) contains protocol/discovery fixtures. Both pass parse, targeted no-cache lint and standalone Swift Testing typecheck against pure declarations. Neither focused app test has run; task2/task12 remain in progress on their own branches. Commands queued through parent:++```sh+# results-stream-1+make test-quick TEST_TARGETS='TransitTests/MCPJSONDocumentTests TransitTests/MCPResultSourceTests'+# results-stream-2+make test-quick TEST_TARGETS='TransitTests/MCPModernProtocolTests TransitTests/MCPModernDiscoveryTests'+```++Source fixture review distinguishes decoded Unicode scalar key sequences from Swift canonical-equivalence; same-scalar escaped/literal duplicate keys still reject. Protocol duplicate metadata fixture uses withoutEscapingSlashes so its mutation actually creates duplicate keys. Depth resource-cap decision is pending owner; no assertion/production limit assumed.++T2384 identified a compact-fallback constraint: recovery context must not reintroduce giant itemId/raw records/link data into the provider's prepared serialization_failed fallback. Encoder RED6 must include synthetic giant itemId and enforce only original indexes/tool/key/UUID plus bounded diagnostics in prepared fallback presentation. Normal aggregate evidence remains complete. API delivery15 remains pending.+++## Nesting measurement for owner decision++Read-only review counts JSON objects/arrays with rootcontainer1; scalars and JSON inside strings count0. Source-defined constructed shapes (not captured live responses):++| Shape | Logical source | Structured wrapper | Full RPC |+| --- | --- | --- | --- |+| Full task/comments | 3 | 5 | 7 |+| Protected full-task receipt | 4 | 6 | 8 |+| Ordinary query page | 5 | 7 | 9 |+| Selector page results/task | 6 | 8 | 10 |+| Prospective batch original receipt | 8 | 10 | 12 |++Shape authorities: MCPRecordSnapshot.swift97, MCPWriteCommand.swift261, MCPToolHandler+TaskQuery.swift86/144, TransitTask.swift49, T2384 approved design89. An independent scan parsed54 noninterpolated literals in existing MCP test sources, maximum4 (mostly requests, not a response maximum). Generated schema module remains declaration-only, so actual output schema depth is not yet measurable. Task metadata is a String:String map; arbitrary historical fields/extensions can nest without a semantic maximum. Proposed parser-input cap64 gives headroom, but remains an owner decision with explicit retained-source preservation amendment. No limit adopted at this checkpoint.+++Owner approved32 (not512/64) at Sentinel_9536d4df532c81919792e70801f128fb; requirements/design/decision log amended explicitly. Source baselineRED2 complete8f9c4ce integrated locally with root task13->3 dependency preserved. Added31/32/33/wide-array cap assertions are being drafted for a separately granted RED refinement; no capGREEN claim. Protocol initial invocation failed before compile at package-resolution DNS (xcode74); same focused command is retrying once via per-command escalation for normal dependencies. That environmental failure is not RED evidence.+++## Baseline RED integration++Local sub-branch integration explicitly approved at Sentinel_eafda56391a48191a3c414fef34d1307. Source baseline2 integrated from8f9c4ce: build/launch succeeded,16 declarations15failed1passed (42 expandedruns), all implementation failures notImplemented or exactexpectederror mismatch; independent shrinker passed. Protocol12 integrated fromdb8173c:22 functions/36 runs all failed solelynotImplemented, no fixture/compiler failures. Its initial sandbox-DNS invocation ranzero tests; the single escalated same-command retry produced actual behavioral evidence. Both focused pipelines drained and the exclusive short slot was released. Parent has both classifications. Rune now has1/2/12 complete;3 is the only ready stream task,13 correctly waits3.++Cap RED amendment128823d remains in isolated stream1 pending exactshortslot grant; no GREEN app run. Source/parser3 and commonAPI15 remain undelivered. No shared MCP/coordinator/Reads edits, client activation, push, main merge or deployment occurred.+++Integrated `make lint` passed host guards and409 Swift files with0 violations; log `/tmp/t2383-integrated-red-lint.log`. User-requested phone helper ran from the clean ticket worktree and exited0, transferring13 changed Markdown documents including the approved nesting amendment and source/protocol RED evidence; log `/tmp/t2383-implementation-phone.log`. Transfer success does not establish that the user opened/read them. Cap RED refinement128823d is ready in stream1 awaiting an explicit next shortslot grant; no heavy process or GREEN runtime implementation is active.+++## Approved cap RED execution++Parent granted exclusive source CAPRED128823d after T2384 GREEN drained. Exact same focused source command compiled and executed; make2/xcode65,23 declarations22failed1passed (50 expandedruns49failed1passed). New31/32/33/wide/retained/checkpoint cases fail against notImplemented as expected; independent shrinker passes. Evidenceed9f2fb integrated into the ticket branch, preserving owner requirements amendment and corrected task dependency. Heavy pipeline drained/released promptly to T63 repair; no GREEN app run in that grant.++Parent authorised source/parser3 GREEN source drafting while its focused GREEN test slot remains pending. Compiler-required escaping Sendable checkpoint facade may retain the callback only within synchronous parser lifetime, never within returned document/source/fragments; no renewal of original deadline. Task3 remains incomplete and API15 undelivered until their actual gates pass.+++## Source GREEN3 delivered++Focused31bc425 source command firstattempt passed23declarations/50expandedruns, make0; unchanged baseline/cap RED fixtures. Pipeline/testhost drained and slot released. Critic found no grammar blocker, but required private source initializer. Final0a93930 access-only change passed negativeexternalconstructor compile (expectedprivate-access diagnostic) and full puremodule/unchangedTestingfixture typecheck/lint; it changes construction access, not runtime factory logic. No app run at0a93930 is claimed. Integrateddf3c23b, resolving expected task-status conflict to verified3complete while preserving12complete and13->3 edge.++Next ready streams4/13 drafted in fresh isolated worktrees `presentation-stream-1`/`protocol-green-stream-2` fromdf3c23b. Prior worktrees/artifacts retained for review. No heavy slot held while drafting, no commonAPI15 delivery.++## Presentation RED4 verified++Source-shape audit before execution corrected fixtures to public taskId/projectId rather than internal covered id, and added actual selector results[index].task plus retained pre-pagination root-array cases. Readiness99f8cbc passed parse/lint/pure fixture typecheck. First reservation was released unstarted for the parent's Asterism baseline; no app job ran during that quiet window. After pause ended and both suites were confirmed ready, parent granted sequential presentation/protocol RED only.++Presentation command at99f8cbc compiled/launched and produced meaningful RED:20 declarations/48 expanded runs all failed against notImplemented, make2/underlying65, no malformed fixture/build/launch failure. Seeded invariant/shrinking remains unexercised because the placeholder throws before those assertions; unchanged GREEN must execute it. Final evidence55116ca integrated into the ticket branch; task4 complete, task5 not implemented. Pipeline drained before protocol supplemental RED started; no GREEN or extra app run in this grant. See presentation-red.md for preserved artifacts/classification.++## Protocol supplemental RED and next source work++Atcf900ad the validator was restored exactly to817a80a, with the prepared correction preserved separately by SHA. Focused supplemental RED compiled/launched:26 functions24passed/2failed,40 runs38passed/2failed, no skips; all22 original functions passed. Depth32 passes, valid depth33 is wrongly classified as invalid JSON (-32700) instead of an invalid request/resource bound (-32600). Out-of-range/nonintegral numeric IDs reject but omit required string-ID guidance. Exact numeric bounds, decimal/exponent/giant-zero cases and width/body cases pass. Evidence9b2cef3 was integrated as documentation only; unverified protocol source remains isolated and task13 incomplete.++Both app pipelines drained; slot released promptly before Asterism after measurement. All CPU-heavy work paused until the parent confirmed quiet completion. Source-only task5 drafting and task13 correction now resume in existing isolated streams; lightweight parse/lint/typecheck are permitted, but no application build/test grant follows from the quiet pause ending. CommonAPI15 remains undelivered.++Protocol3cfd28a fixes the demonstrated resource/ID diagnostic failures and passes lightweight checks, but its GREEN readiness was withdrawn after internal critic found subscription filter and Mcp-Name validation defects. Current primary specification confirms resourceSubscriptions is a string array and unsupported types are omitted from acknowledgement; plain padded names require Base64, and sentinel recognition requires both exact markers. New focused RED fixtures precede those fixes. See [subscriptions](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/subscriptions) and [HTTP value encoding](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http#value-encoding). No additional app run or completion claim.++An initially inferred direct-discovery null-ID defect was withdrawn after checking actual MCPTypes: JSONRPCId has only string/integer cases and the public helper requires it nonoptionally. No shared type expansion, guard or redundant fixture is needed; existing request validator null-ID rejection remains tested. This correction is not a new protocol policy.++From clean0dfeed2, the requested phone helper exited0 and sent16 branch-changed Markdown documents, including sourceGREEN/presentationRED/protocol supplemental evidence. Log: /tmp/t2383-red-checkpoint-phone.log. Transfer does not establish that the user opened the documents.++## Critic RED verified; focused execution approval blocked++Protocol366a1ad against unchanged3cfd28a compiled/launched:30 functions27passed/3failed;44 runs41passed/3failed, no skips. All previous26 functions and malformed resource-array control pass. Valid mixed resourceSubscriptions array rejects incorrectly, padded plain name accepts incorrectly, prefix-only sentinel rejects incorrectly. The full sentinel literal's outer encoding assertion was not reached after the prefix-only failure, so no pass is claimed. Pipeline drained/released; evidence52fea71 integrated as documentation only. Revised sourceb6b616e passes lightweight checks and targeted internal critic review; all30 fixtures unchanged, application GREEN pending, task13 incomplete.++Presentation supplemental fixtures391c159 preserve runtime1652913 and await execution. The granted focused command did not launch: automatic approval review rejected require_escalated because it treated the delegated slot grant as insufficient to override the original spec-phase heavy-build/test restriction. No process/session, retry, alternative execution path, global permission change or runtime repair followed. Parent notified, unstarted slot released, and actual owner authorisation is being resolved through the parent. This is an execution-authority blocker, not RED evidence. Task5 and commonAPI15 remain incomplete.++## Owner-authorised presentation supplemental RED++Explicit owner approval Sentinel_f061180ea7608191b7f8e54205bfdb00 authorised the exact focused presentation command with per-command escalation. One unchanged retry was accepted, with no evidence added to tool arguments or alternate invocation. At391c159 against runtime1652913, build/test launch succeeded:25 declarations23passed/2failed;55 runs51passed/4failed. All20 original declarations/48 runs pass, including seeded presentation properties. New3 controls pass and4 cases expose missing milestone project references and known complete terminal-rejection retry precedence. No compiler/fixture/launch fault; runtime unchanged, pipeline drained and slot released promptly. Evidencee3b37e3 is copied into the ticket as documentation only; task5 source repairs continue isolated and no GREEN is claimed.++Protocolb6b616e remains source-review-cleared and ready, but parent reports its GREEN delegation was rejected for missing explicit exact-suite approval. Parent requested bundled local build/lint/unit-simulator/escalation authorisation at Sentinel_8870ee330e108191b769af5f8b659855; reply pending. No protocol GREEN attempt, workaround or active heavy reservation; client activation is a separate gate. Presentation repair/lightwork may continue, while app execution waits for owner evidence and a coordinated slot.++Presentation revised sourcef4bd03a fixes the demonstrated milestone-link and terminal-rejection recovery gaps and checkpoints project-position generation before allocation/every64 entries. All25 declarations/55 runs' fixtures remain byte-unchanged391c159. Parse/lint/pure typecheck passed; targeted internal critic found no new blocker. Presentation5 and protocol13 are both source-review-cleared READY drafts in isolated streams, pending separately granted application GREEN; neither runtime draft is integrated or marked complete, and commonAPI15 remains undelivered. No active app job or heavy reservation.++## Live mutation pause and read-only duplicate observation++Parent paused all live Transit mutations/status/comments after the owner observed duplicate records. No live T2383 mutation occurred during these local source/test iterations. Last recorded write remains the protected implementation status/comment at2026-10-03T11:08:23.475Z, key T2383.implementation-approved.20261003, UUID E46FCBBA-31BA-4C53-AD13-C3A4E3209819, committed historical revision r1:98d5c0bb10c440984383379166f4c98391519018e7c1bc694a12fcc8af04bd62. Earlier scope status/comment was09:09:18.822Z, key T2383.scope-approved.spec.20261003. Historical receipt evidence is unchanged; no replay/mutation retry or guard reset follows this observation.++Using the actual running legacy query_tasks schema, read-only displayId2383 returns Duplicate task identifier detected for displayId 2383. Exact title search Return structured MCP results and navigable links returns two rows with the same UUID and displayId:++| Status | Project fields | Last status change | Observed revision |+| --- | --- | --- | --- |+| in-progress | projectId/projectName absent (not JSON null) | 2026-10-03T11:08:23Z | r1:10dc24ef6faf70f905c7fb87a8caa608907fa7ad727eb1ab6b65370850904ee7 |+| spec | projectId8491AAC4-CC6C-498C-B93D-99DD68424226, projectNameTransit | 2026-10-03T09:09:18Z | r1:7dba5935bf1f6055203ae0a0c5fdcd1546386144f8bd7e2c9733b6f504ee95ea |++Both rows report comment UUIDs C61251A5-E503-46A6-9B6C-3011C9422E30 and4C9688F8-1B48-451B-BBAD-975E538C563D with the same comment creation/revision values. This is observation, not a cause or repair conclusion. No task/project deletion, merge, reassignment, settings change or production activation occurred. Selected Results/Protocol tests are pure; TransitApp's unit-test-host source selects an in-memory/CloudKit.none configuration and skips the MCP server, but that source inspection alone does not establish the duplicate cause.++The phone helper from clean95b0d30 exited0 and sent17 Markdown documents including supplemental RED evidence; log /tmp/t2383-supplemental-red-phone.log. No user-open claim.++Parent ended the first continuation quiet window early but retained the live-write and app-host execution holds. Parent gracefully quit development Transit PID7496, closed port3141 and left the installed app running. Earlier drain reports labelled7496 an unrelated installed process; that classification is corrected to the parent's development-target identification. Our separate test pipelines/hosts drained, and7496 was untouched by our commands. A parent snapshot found seven duplicate rows inserted in one CloudKit import; mixed model generations sharing a store is a leading hypothesis, not a proven cause. Development-target/test-isolation implementation approval remains pending; no app launch, server reconnect/restart or isolation source implementation follows here.++Independent planning continues in interface-coordination.md without crossing blocked task6 or claiming an API. It records ordered/validated metadata, sealed frozen bytes, bounded preeffect fallback presentation, original checkpoints/backing charges and unchanged T63/T2384 ownership. Presentation5/protocol13 stay pending safe application verification.++## Integrated isolated presentation/protocol GREEN++Parent selected immutable T63 Stage A b500543 and authorised local integration plus one exclusive isolated verification slot. Crossed instructions briefly consumed the exact-base isolation component9f6808e; only that component was reverted asb7625fd before T63 mergea540514. No isolation was double-applied. Final sourcefbbe7cb includes reviewed presentationf4bd03a and protocolb6b616e; HEAD41740d1 during tests adds only isolation-integration documentation. Isolation files and App constructors match b500543 exactly. T63/containment/T2384 shared ownership remains unchanged.++The dedicated fresh-path `make test-isolated-host-smoke SMOKE_DERIVED_DATA=DerivedData/t2383-isolation-smoke-fbbe7cb` passed one test, zero failures/skips. Its signed development host and generated launch configuration passed identity/entitlement/unit-test-mode preflight. Shared Transit Debug build-for-testing then passed with private DerivedData/t2383-shared-fbbe7cb, serial tests and ad-hoc development signing. Before launch, the separately signed shared host/xctestrun preflight verified me.nore.ig.Transit.development, no CloudKit/push/App Group entitlements, explicit unit-test mode and TRANSIT_ISOLATION_SMOKE=1 with the exact inspected host path. Derived launch configurations excluded UI targets and restricted the two granted selections.++Serial test-without-building results on that same guarded build:++| Selection | Declarations | Expanded runs | Failures/skips | Outcome |+| --- | --- | --- | --- | --- |+| MCPResultPresentationTests | 25 | 55 | 0/0 | PASS |+| MCPModernProtocolTests + MCPModernDiscoveryTests | 30 | 44 | 0/0 | PASS |++Presentation expansion is21 ordinary runs plus34 parameter runs; protocol expansion is24 ordinary runs plus20 parameter runs. Original RED fixtures are unchanged, including milestone links, known receipt retry direction, subscription string[] handling, padded-name rejection and the previously unreachable literal sentinel case. Read-only final integration critic found no substantive issue and verified actual incoming JSONRPCId/origin signatures. Tasks5/gpzncvp and13/gpzncvx are complete.++Evidence lives in `.codex-cache/t2383-final-isolated-fbbe7cb/` (logs, preflight and xcresult summaries/test trees); full results are dedicated smoke Build/Products/IsolationSmoke.xcresult and shared Presentation.xcresult/Protocol.xcresult. Every command exited0. Read-only process inspection found no owned build/test pipeline or host; the parent received immediate slot release before extraction/bookkeeping. T2382 now owns the heavy slot; no further app job is authorised here.++Task6/gpzncvq is the next ready stream. Source-only encoder RED fixture preparation and light checks are delegated; no encoder GREEN or API15 delivery is claimed. No live Transit mutation, production launch, MCP activation, client setting change, push or deployment occurred. The earlier live-write hold remains active.++Task6 source-ready commit a480d06 contains14 encoder/fallback fixture methods; light parse/lint/pure typechecks and forbidden constructor probes pass. Final internal critic cleared the exact-fragment/depth32 oracles and explicitly synthetic effect-selection boundary. See encoder-red.md and encoder-review.md. The parent received the exact two-suite guarded runtime request; no runtime RED/encoder GREEN/API15 claim follows. The prior GREEN phone helper exited0 from c6fbbd1; its log is /tmp/t2383-isolated-green-phone.log.++Encoder6 guarded build/preflight succeeded, then original console14methods/18issues failed at declared notImplemented boundaries. Runtime critic cleared meaningful RED and identified unreached later combinations/assertions. Report finalization hung; exact owned process termination and automatic13-test replay are preserved separately, actual commandexit143, xcresult unavailable/unfinalized. See encoder-red.md for precise intervention/sample/limitations. Parent received immediate slot RELEASE after drain and authorised no repeat solely for teardown. Rune6/gpzncvq is complete; only7/gpzncvr is ready and source-only implementation is delegated, with no application GREEN grant or API15 delivery.++Task7 draft3ba1cfb implements complete raw-fragment preserving bytes, validated owned metadata, sealed ID-independent fragments/current-ID envelopes and complete provider-owned mutation fallbacks. All14 fixtures remain unchanged; parse/lint/pure typechecks and internal source critic pass. See encoder-green.md. The parent received a request for the same guarded two-suite GREEN slot; task7 remains in progress and API15 undelivered. No app/GREEN run follows the previous RED grant. Encoder RED phone helper exited0; log /tmp/t2383-encoder-red-phone.log.++First encoder7 guarded attempt on3ba1cfb rebuilt/preflighted successfully, then14consolemethods produced12passes/2fixture-oracle failures (Foundation valid1E-9999 numeric limitation). Exact byte/depth assertions in those2methods remain unverified. Both owned processes were sampled before bounded runner-first/host termination; commandexit143, unfinalizedxcresult/no finalcounts, no replay. Slotreleased immediately afterdrain. See encoder-green.md for evidence/cause limits. Parent approved a narrow helper-only oracle correction preserving14methods and productionsemantics; source-only correction/lightcontrols are delegated, new review/grant needed before rerun. Task7 remains inprogress/API15undelivered.++T63 sole-owned existing JSONSchemaProperty optional bounds/const/default capability is delivered atf4e29556feb36dec62e8ebeb7f20b5110a5b6f4b, narrow patch task/t63-review-evidence/schema-seam/f4e2955-schema-seam.patch. minimum:Int?, maximum:Int?, const:Bool?, defaultValue:String? encode minimum/maximum/const/default; unset values preserve old shape. Standalone source typecheck/lint passed upstream, app registration is unverified. Future schema/input work consumes that exact definition when needed without duplicate/shared concurrent edits. The capability is not yet imported here and does not establish API15.++Oracle correctionffe2c33 passes11positive/20negative actual-helper standalone controls, parse/lint/pure typechecks and internal critic. It preserves allproductionResults3ba and14method assertions/inputs a480, using numeric surrogates only for disposable structural validation and originalbytes for semantics. New same-suite guarded GREEN request sent toparent; no rerun performed yet.++Corrected encoder GREEN rerun did not start: automatic escalation review rejected delegated-grant provenance against original heavy-test restriction before launching any process. No workaround/retry/global change occurred; unused reservation released. Parent is obtaining trusted owner approval evidence and will reconfirm the slot. Task7 remains pending with reviewedffe2c33/source3ba unchanged. See encoder-green.md. Oracle-correction phone helper exited0; log /tmp/t2383-oracle-correction-phone.log.++Corrected encoder GREEN is verified14/14 with clean build/preflight/test exit0 and finalisedxcresult,0failures/skips/warnings. Fresh explicit owner testing/fix-rerun approval Sentinel_10e284fb472881918fb01fad1bde10d2 supported the exact previously denied command; parent authorised one replacement for the unavailable runner after no-owned-process verification. SAMEcommandSHA08ee54389... accepted normal per-command review, no invocation/globalpermission workaround. All original source3ba/methoda480 expectations are unchanged; oraclehelperffe is reviewed. No hang or cleanup on correctedrun; ownedprocessesdrained/slotreleased beforeextraction, prior evidencehashes unchanged. See encoder-green.md and ignored .codex-cache/t2383-encoder-oracle-green-ffe2c33/results.md. Rune7complete; only8schemaRED is ready. API15undelivered; live/clientactivation/deploy holds unchanged.++Task8 fixture preparation912ddbc adds36 actual encoder-produced response cases,37 malformed variants,12 actual descriptor requests and a pinned offline Draft202012 host validator. Pure parse/lint/typechecks and validator controls pass; a direct-method probe observes both real notImplemented boundaries and exports an incomplete36-case manifest with zero schemas. This is not an app/Swift Testing run or schema GREEN. Internal critic clears final hashes and the guarded development-host preflight/serial schema-only selection. See schema-red.md and .codex-cache/schema-red-preparation/readiness.json/guarded-commands.json. Task8 remains in progress while T2382 owns the heavy slot; parent receives the exact next-slot request. Task9/API15 remain pending. Main's phone helper for corrected encoder GREEN exited0, log /tmp/t2383-encoder-corrected-green-phone.log; no user-open claim.++Task8 guarded meaningful RED is reviewed and complete: exact commands accepted, build/preflight0; actual console2functions/1suite with2 expected notImplemented issues and no incidental assertions. Actual app-owned export36wires/37plans/incomplete0schemas reaches intended descriptor boundary. Both owned processes sampled before bounded runner22170 SIGTERM; host22178 exited without a separate signal. Command143/unfinalized missingInfo.plist summary64 remain explicit; no finalized counts, normal-exit or cause claim. Hostvalidator received actual143 and refused GREEN, exit1. Processesdrained/slotreleased immediately before extraction; priorencoder artifacthashes unchanged. See schema-red.md/results.md. Rune8 complete,9ready; source-only9 follows approval and laterGREEN needs its own slot. Owner revised delivery preference holds routine phone/uploads; local evidence and concise outcomes only. No live/client/shared-ownership changes.++Task9 source implementationa25bf99 and reviewed recovery correction1f20e11 are GREEN-ready. Owned immutable Draft202012 descriptors pass the actual12x(36+37)=876 pure host matrix plus pointer/UUID controls. Critic identified a receipt-like batch/maintenance follow_source mismatch; supplemental actual pre-fix schema proof rejects two cases, the protected control passes, and a one-condition protected-context guard makes all three conform without changing original source/retry/evidence/identities or the schema. New repeatable three-method supplemental suite/host checker accompany unchanged original fixtures. Parse/lint0/pure module+fixtures/checker controls pass; no app GREEN run. See schema-green.md and .codex-cache/schema-recovery-conformance/source-results.md/final-readiness.json/guarded-commands.json. Prepared signed development-host/unit-test/serial two-suite run expects five methods and both actual-exit host validations. Rune9 in progress/API15 pending; next slot follows parent queue T1734 thenT2382. Evidence local; no routine phone/upload or live/client/shared-file changes.++Task9 verified at2df0648: build/signedhostpreflight/test/finalizedsummary exit0; actual5/5functions pass, no failure/skip/finalizedruntimewarning. Both actual-exit app-export host validators pass876baseline assertions plus3supplemental schema/resultpairs. Critic independently confirms copiedfiles match originalapp temporaryexports and source/isolation identities; no pureproofsubstitution. No hang/sampling/cleanup/replay. Processesdrained/slotreleased immediately beforeextraction, historical artifacthashes unchanged. See schema-green.md and .codex-cache/schema-recovery-conformance/results.md/app-actual-commands.json. Rune9complete; only10RED ready. Source-only10 preparation may continue under the approved task plan, no next app job granted. API15/sharedproviderdelivery remains pending; no routinephone/upload or live/client changes.+++## Task10 RED readiness at 70d103a++Reviewed eleven-method preparation budget fixtures and sealed Results-only declarations are committed at 70d103a. Factories deliberately remain notImplemented. Pure module build, actual macro fixture compilation, parse, strict no-cache lint and direct driver passed; the driver observed ten intentional declaration failures and completed the parser/encoder control. This is source readiness only, with no app/Swift Testing counts. Internal critic cleared exact source/guarded commands. See preparation-red.md and .codex-cache/preparation-red-readiness/results.md.++Task10 stays in progress and task11 blocked until actual app RED. T2382 holds the heavy slot; request the next exclusive grant for the prepared unit-only command. DELIVERED15 remains pending. No shared wiring/coordinator edits, live/client action, configuration changes or routine phone delivery occurred.+++## Task10 execution attempt rejected before start++The parent granted an exclusive slot for the reviewed task10 sequence at70d103a/docs3f7f835. Automatic approval review rejected the exact build before any process started, citing the original heavy-build/test restriction and saying parent approval cannot override it. Build exit absent, preflight/test unrun, slot immediately released unused. No retry, indirect route, source change or task11 drafting. Task10 remains inprogress, task11 blocked. See preparation-red.md and .codex-cache/preparation-red-readiness/app-attempt.json. Parent authorization-provenance resolution is required before another attempt.+++## Task10 single unchanged retry rejected++Parent provided the complete later owner-testing approval and authorized one identical-call retry. The worker forwarded it unchanged and retried the same tool call without modifying action/arguments. Review explicitly considered the later reply but rejected it as untrusted forwarded assistant context, retaining the initial heavy-test restriction. No process started; unused slot released immediately. No further retry/alternate route or task11 drafting. Task10 stays inprogress and task11 blocked; no runtime RED counts. See preparation-red.md and locally preserved second-denial evidence.+++## Staged modern ownership acceptance++Accepted sole-writer ownership of the ten production paths from exact T63 manifest557b4c2/sourceb1f3025. Verified manifest/current bytes and all17 listed hashes; optional fixture candidates remain separately authorized. No import/source edits, heavy run or API delivery. Retained owner boundaries and current-helper router/expiry verification obligations are recorded in modern-transfer-acceptance.json/interface-coordination.md. Task10 remains denied,11/14 blocked by the approved DAG; no slot held.+++## Direct user testing approval received++The user directly stated “All runs for tests and build are approved” in the T2383 task conversation. This authorizes the isolated test/build work beyond the earlier heavy restriction; previous provenance denials are retained as historical evidence. No new heavy call/slot or live/client action. Await parent-exclusive slot for unchanged reviewed task10 sequence; no further user approval request is necessary. Task10 inprogress,11 blocked until meaningful RED.+++## Task10 meaningful RED complete and slot released++Exact reviewed build/test calls accepted under direct approval atfec9ecf/fixture70d103a. Build/preflight0; actual console11functions/1suite with10 intended notImplemented failures+1 parser/encoder controlPASS, no incidental errors. Finalization stalled; both exact processes sampled before runnerSIGTERM, test143/unfinalizednoInfo.plist; host drained without signal. Slot released immediately, no replay. Runtime critic clear with limits; Rune10complete,11sole ready. Task11 source drafting authorized, laterGREEN needs its own slot. See preparation-red.md/local runtime evidence.+++## Task11 source GREEN-ready at1135a88++Value-only preparation/accounting is committed and static critic clear. All lightweight checks finished before the quiet window, with original fixtures unchanged; direct11bodycompletion/independent9,332,951logicalbyte observation are not appGREEN/assertion-pass counts. Exact guarded GREEN sequence prepared in .codex-cache/preparation-green-source/, see preparation-green.md. Task11 inprogress; no app job, slot or DELIVERED15 claim. Asterism quiet window pauses new CPU-heavy jobs; wait explicit release and parent-exclusive GREEN grant. Routine evidence local, no user-facing files.+++## Task11 verified GREEN complete++Actual source1135a88/readiness66e39d7 passed11/11 original app tests with finalized result,0fail/skip/expected failures/warnings. Build/preflight/test0, signed isolated unit-host guards preserved. Normal owneddrain and immediate slotrelease before extraction; nohang/cleanup/replay. Initial read-only summary cache restriction64 preserved, same normal-escalated extraction0. Sixty-nine actual artifacts hashed; sampled RED/source/isolation/fixtures unchanged. Runtimecriticclear; Rune11complete,14next ready. API15notdelivered; see preparation-green.md/localresults. StageB baseline/retained-owner dependencies must be coordinated for14; no unapproved imports/shared edits.+++## Task14 exact owner baseline imports++Imported exact authorizedT63five+acceptedtwo common baseline36030cf and owner-confirmedT2382thirteen1a19dfd, all20 paths/SHA matching sourceb1f30256, internalcriticclear. Exactlist task14-baseline-import.json. Retained editingowners unchanged; no App/project/Results/Protocol/fixtures/helper/ordinaryretention changes. Combinedcompile/runtimepending, noAPI15claim. Specific orderedheaderHTTPhelper seam(T63) and twoadditionallegacyfixtureownership items sent parent for coordination; ownedsynthetic14prep proceeds, no heavyjobuntilgrant. No blanketbranchimport or diagnosticscycle.++## Task14 first actual attempt: fixture corrections required++Reviewed checkpoint561557ef compiled successfully under the exact parent-granted guarded command; build/preflight0. Signed isolated development unit host and ten-suite serial selection passed preflight. Actual console95tests/10suites:65 passed bodies,30 failed bodies,50issues,2.524seconds; the four existing result regression suites pass. These are console observations, not finalized xcresult counts.++Full14 RED acceptance is withheld: positive request fixtures used short metadata names rather than the existing io.modelcontextprotocol namespace, and historical receipt seeds replaced required v1 envelope evidence with invalid terminal payloads. Existing coordinator uncertainty behavior is correct; repair fixtures and preserve validator/receipt policy. Intentional declaration/legacy-wiring failures are separately present. No15 implementation or API delivery advanced.++Finalization stalled after bodies. Both exact runner7417 and isolatedhost7425 sampled0 before any signal; bounded runnerTERM/drain then still-ownedhostTERM/drain, noKILL/replay/live app touch. Test exit143, unfinalized bundle/noInfo.plist, summary64. Worker released slot immediately before extraction. Main independently verified build6722/runner7417/host7425 absent through approved read-only ps. Heavy slot is free. Raw evidence .codex-cache/task14-provider-readiness/results.md and59-file hashmanifest remain local/immutable; corrected fixtures prepare in a separate cache directory and require a newly granted focused run. Task14 remains inprogress,15blocked.++Runtime critic confirms partial meaningful RED only and identifies an additional incidental test-transport issue: repeated EmbeddedEventLoop thread-safety misuse diagnostics in the raw console. The retained T63 helper creates an EmbeddedChannel before async responder work and final channel cleanup. The narrow ordered-header grant does not authorize changing that transport implementation. Corrected preparation must assess a supported thread-safe owned test context or obtain an exact owner-supplied seam; do not suppress diagnostics or attribute the finalization hang to them without evidence. An unsupported clientInfo.title rejection assertion must also follow actual validator behavior. Main independently rehashed all59 evidence files with zero mismatches. No retry or source correction was executed in this status-recovery turn.++## Task14 independent runtime classification and narrow correction plan++Independent critic classified all50 Swift Testing issues:44 missing approved feature issues and6 incidental fixture issues; NIO thread-affinity diagnostics are additional harness faults. Selector11 issues reach deliberate notImplemented; actual inner-maintenance reaches saved reassignment but its encoder hook/modern wrapper are absent; protected outer-failure stops at the common placeholder. Legacy discovery/wrapper/header/notification/availability faults are present. Actual saturated admission reaches READ_BUSY before validation. Success assertions behind missing wrappers (including later enabled-tool iterations and replay/normalization comparisons) remain unproved until task15 GREEN. Passing negative metadata controls with wrong required namespaces do not prove their intended secondary checks.++The existing run establishes meaningful feature RED. The parent authorizes implementation once that boundary is established and rejects repeat runs solely to normalize teardown. Before closing14 bookkeeping, correct the fixtures and obtain independent semantic review; do not claim corrected execution that did not occur. Any correction verification should target metadata controls9, decoder happy path1, changed historical-valid/invalid receipt cases and the repaired MainActor transport case. Unchanged four result regressions, declaration-only selectors and maintenance methods need no repetition for teardown alone.++NIO repair uses owner-verified T2382 pattern0ecc66229f42aebd5d73231df83a34e488a214d1: NIOAsyncTestingEventLoop/NIOAsyncTestingChannel, awaited clean finish and loop shutdown on success/error. Adapt within owned MCPModernResultFixture and route new owned tests through it, preserving retained T63 helper exactly. No actual listener, client activation, retained helper lifecycle edit or diagnostic suppression. Corrections use a new cache directory, preserving all59 original attempt artifacts. No new runtime job or15 implementation has started.++## Task14 meaningful RED boundary complete; task15 ready++Corrected five fixture files committed5b20464; independent source/13-method artifact review clear, parse0/strictlint0/diffcheck0. Namespaced metadata/secondary controls match actual validator; historical unknown members retain complete v1 receipts and validate with existing store before replay, invalid receipt evidence still returns uncertainty. Owned async testing channel fixes thread-affinity without changing retained helper/production. Original59 artifacts unchanged. No corrected runtime execution claimed; minimal13 prepared in .codex-cache/task14-provider-red-correction/guarded-commands.json, build string SHA256a25d479dec967ecea721d4898ebae4d1e9753ee9f1a45d076e65aa6943397ed5. New exclusive slot required for that correction run, not for teardown normalization.++Parent explicitly permits implementation once meaningful RED exists. Independent classification44 feature issues establishes that boundary; corrected fixture intent is reviewed. Rune14complete, explicit phase/available-stream retrieval gives15sole ready,15inprogress. Actual success assertions behind wrappers and zeroNIO diagnostics remain runtime obligations, not evidence already obtained. DELIVERED15 remains unavailable. Task15 planning proceeds at the immutable correction checkpoint; no production patch while a correction runtime build uses it. Retained-owner definitions factory request is recorded in interface-coordination.md for parent/T63 coordination.++## Minimal correction build stopped before tests++Parent granted the exact13-method correction sequence at5b20464/docs76fa662. Build accepted normal review but exited65 on three fixture macro errors: standalone throwing #require calls at ProviderIntegration141/167/169 lacked try. Preflight and tests did not run, no guarded host started, owned build drained and slot released immediately. This is incidental compilation failure, not corrected RED/runtime evidence; no duplicate or retry. Original95-test evidence and correction attempt artifacts remain preserved. The narrow fix adds only three try keywords, independently reviewed with assertions unchanged; new compile-fixed readiness paths preserve the same13-method selection and require a fresh coordinated slot. Task15 remains read-only planning during pinned verification; meaningful44-feature RED boundary already established, API15 not delivered.++## Compile-fixed correction: finalized metadata controls, omitted selectors++At built source1a69d41 (fixture8b3c954/factory8be5d55), build/preflight/test0, finalized summary9tests9pass0fail/runtimeWarnings empty. Only metadata suite bodies ran; four method-specific CLI/plist selectors lacked required method() spelling and matched no bodies. Do not claim13 execution, historic receipt or HTTP/NIO proof. Normal owneddrain/slotrelease; no sampling/cleanup needed. Original59 and compile65 attempt preserved. Independent artifact review clears exactFOUR-only test follow-up in .codex-cache/task14-provider-omitted-four/guarded-commands.json, quoted method() identifiers, fresh restrictedplist/result/preflight and nine pinned existing signed products. No build or nine-control repeat is needed. Later source changes are explicitly excluded from that binary proof; no follow-up invocation occurred.++Settings owner patch105ba8fd consumed afterdrain inb51ab96; sourceSHA256c2fe9f43e2283c792a98691d349da34ff7fe5dcb3545e5fb23e2c5a40d1cf062 matches owner. Parent's exactpatchSHA2566aaf14fd55717cca4203ce3954c10132f502f22c20f0a756df70bc72cfd4aa7b. Nonisolated maintenanceToolsEnabledSnapshot is now available, synchronous initialization/didSet lock publication before defaults/notify; no preferences changed by import. T63 retains ownership. Runtime initial-value/offactor/immediateassignment/notifications obligations remain task15; old binary products do not include this seam. Both15 owner requests are delivered. Owned15 implementation may proceed without making the four-body correction an extra scope gate, but source/products freeze during any pinned runtime; API15 remains undelivered.+++## Corrected omitted-four runtime complete; task15 first source checkpoint++The exact parent-approved test-only run reused signed products built at1a69d41. Preflight and compiled discovery exited0; exactly four enabled identifiers and four executed bodies were verified: decoder happy path, two historic receipt tests and immutable unavailable-tool classification. Console evidence:1PASS/3 intended feature failures/9issues,2.101seconds, three suites. No NIO misuse diagnostics appeared in this run. Independent runtime critic clear: valid v1 unknown-field receipt validation and existing invalid-evidence uncertainty were reached; comparisons behind missing structured wrappers and later receipt branches remain unproved until GREEN. Together with the separately finalized9 metadata passes, this completes the focused correction coverage; it is not a finalized13-test result or an all95 clean claim.++Finalization remained active beyond two minutes. Exact runner27248 and guardedhost27252 were both sampled successfully before any signal; bounded identity-checked runnerTERM/drain followed by still-ownedhostTERM/drain, noKILL/replay/live app touch. Test exit143; unfinalized bundle lacksInfo.plist, summary extraction64. Slot released immediately after drain before extraction. Root independently verified both PIDs absent and rehashed the current26-file evidence manifest with zero mismatches; original59 evidence also remained unchanged. Teardown cause is unproved. See .codex-cache/task14-provider-omitted-four/results.md and compiled-inventory-verification.json. Discovery created its normal DerivedData test log bundle, preserved separately; actual test output used the private fresh bundle.++Runtime products exclude later settings importb51ab96 and task15 source. First task15 source checkpointfb776a0 implements effect-aware selector, value-only provider adapters/evidence and non-wire MCPToolResult providerEvidence in exactly three owned files. Static critic clear; parse/lint/diff checks passed. Handler/router integration and actual GREEN remain pending; Rune15inprogress, DELIVERED15 unavailable. Coding delegate resumed approved owned binding after the pinned run drained. No heavy job or slot is held; new actual GREEN needs parent-exclusive scheduling.+++## Task15 binding committed; exact combined GREEN ready++Owned ten-file binding checkpointa8fcc71506ff61ee5b6f0e320ace5a064e30c915 implements modern router/discovery/schema calls, frozen availability, source-specific provider evidence and entity positions, original read operation/constant failure encoders, and complete effect-aware mutation fallback selection. Existing validator preflight remains pure; no retained receipt rewrite/write-coordinator edit. Five narrow tests cover Unicode/numeric bridge rejection, no-effect protected rejection, stored/immediate snapshot values, change notifications and unsupported-method405 handling. Internal critic cleared final source and commands; frontendparse/strictlint/diff0. Root independently verified allten source SHA256s and exact build command hash. Combined compilation/runtime remain unverified.++Prepared only .codex-cache/task15-binding-green-readiness/guarded-commands.json: one fresh private build preserving oldnine pinned binaries, unchanged installed resolved package checkout, signed isolated development unit host, serial2jobs, preflight, compiled enumeration and failclosed exact100 declarations/11suites before tests. Expected declarations are separate from actual parameterized body counts. Build SHA256c83c279c5c3bcd4be2dbc300ce21dde4b95c31ea4d30a4201202d5b142fb532e. No app invocation or heavy slot held. Coding and critic turns completed with concrete readiness; request parent-exclusive scheduled execution next. Root will remain active through actual outcomes/drain. Rune15inprogress, DELIVERED15 unavailable; neither later read-retention/subscription/client readiness nor production batch completion is a reverse handoff dependency.+++## Task15 actual combined verification and two-fixture correction readiness++Initial private build exited74 before compilation because the private TMPDIR was absent. Created reviewed cache/tmp directories and preserved that attempt. Setup-fixed build exited65: owned binding fixture lacked NIOCore import. Exact one-import correctiond29fdaa independently clear, assertions/production unchanged. Both attempts drained; no preflight/test bodies ran. Authorised same-scope continuation used distinct evidence paths and the original private cache.++Import-fixed actual build/preflight/enumeration/inventory all0; exactly100 declarations/11suites verified before serial test. Console100bodies/11suites:98PASS,2failedmethods/4issues, scopedNIOmisuse0. Both failures trace to existing query_tasks mandatorylimit omitted in validArguments and assertReadParity. No production serializer defect demonstrated by these four issues. All five new binding fixtures and synthetic provider tests passed. Unreached assertions in the two failed methods remain pending corrected verification.++Finalization stalled; both exact runner46023/guardedhost46027 sampled0 before any signal. Identity-checked runnerTERM/drain, host drained after runner with no host signal. Immediate slotRELEASE before extraction; root independently verified bothPIDs absent. Test143, unfinalized bundle/noInfo.plist, summary64. Cause unproved, no teardown-only replay. Raw evidence .codex-cache/task15-binding-green-import-fixed/results.md; root rehashed actual evidence manifest with zero mismatches. Earlier74/65 artifacts preserved.++Exact two-limit correction543c4a757e4cb7f9f73c973d7cb1be5725c8f342 preserves assertions and production, parse/lint/diff0/internalcriticclear. Focused future verification .codex-cache/task15-binding-green-limit-fixed/guarded-commands.json uses existing private incremental build, fresh bundle/log/plist labels, signedisolatedpreflight, exacttwo method() CLI+plist selectors and failclosed inventory. Sourcepin543c4a7; buildSHA2562ff579f2e283ab9d69334990d4a1c7dece416da55b13523a0668ccc74f07bd2d independently verified. Full100 is not repeated solely for finalization. No retry launched; workers completed readycheckpoint, no heavy job/slot held. Request parent-exclusive focused two-method execution next. Rune15inprogress/DELIVERED15 pending actual corrected passes; no later-ticket reverse edge.+++## DELIVERED15 / gpzncvz verified common seam++Focused corrected543c4a7 verification: build/preflight/enumeration/exacttwoinventory/test/summary all0. Both exact methods executed and finalized resultPassed2/2, zero failures/skips/runtimeWarnings, scopedNIOmisuse0. Normal owneddrain and immediate slotrelease before extraction; no samples/signals/replay. Final independent integrationcriticclear. Root rehashed56 final evidence files with zero mismatches. Preserved98 passing bodies from the prior100 run plus finalizedcorrected2 fulfill15 regression obligations; prior143/unfinalized limits remain, no single100 clean finalizedclaim.++Rune15/gpzncvz completed. Common API delivered from sourcecheckpoint543c4a7, productionbindinga8fcc71, selector/adaptersfb776a0, with concrete api15-handoff.md and exact api15-source-manifest.json. Full verified runtime dependency manifest at .codex-cache/task15-binding-green-limit-fixed/source-dependency-manifest.json pins28ownedResults/Protocol/common files and21retainedownerinputs; not authorization to overwrite those owners. T2384 consumer integration can proceed through coordinatedimports preserving its writecoordinator; no reversebatchdependency. Later16–22 frozenretention/publication/subscriptions/clientreadiness remain separate. No activeheavyjob/liveactivation/push/merge/deployment.+++## Task16 retained-read coordination checkpoint++Parent authorised16–22 preparation after DELIVERED15consumers resumed; Rune16inprogress. Actual retained-source/fake/gate inventory identifies all-private-page owners, expanded charge and stored-fragment continuation as the next boundary. No new deadline/admission/reservation engine needed. Single bundled request task16-owner-request.json pins13 actualpaths and separates retainedT63/T2382 writers; no new owner implementation/fixture/runtime claimed.++T63 supplied ce4d0af prepared-page-owner.patch consumed exactly in18a3483 afterapplycheck0/diffcheck0. PatchSHA25622fec83828cbaa7e415c786e675186b52943324bf74d607fc7cca3ffa8a3b726; prepared-readfileSHA2561394537f348260d9022c5c2defa8fbaab744c06cf4cef4446b3e3cab9e5ff462 matchesactualownercommit. OptionalpreparedResultPage and nonthrowingattachingPreparedResultPage preserve oldbytes/metadata/publications; ownership staysT63. Source import only, no runtime acceptance.++Suppliedcommon factory request: prepareReadPages(_ pages:[MCPPreparedToolRead],tool:String,operation:MCPReadOperation)throws->[MCPResultPreparedPage]. T2383 delivers declaration/RED and implementation under16/17 and consumes attached frozenfragment with newRPCID. Remaining combined ownerrequests: ordinary all-private-page prep/storelookup/expandedcharge; reusable create+append+lookup/pin/expandedcharge; explicit plainText evidence for actual no-service readfailure. Existing originaloperation/coordinator/domain/capture/lifetime fakes supporttests. Separate16MiB/fiveMinute/eightSnapshot stores, canonicalcommentcoveredr1 with commentsomitted, originalfiveSecond/eightPhysical invariants unchanged. No heavyjob or exactruntime readiness yet; commonABIavailable, retained-store declarations pendingcoordination. No clientactivation/settings/livechanges; later subscriptions/readiness not started or consumer blockers.+++## Task16 partial value/carrier RED readiness and common ABI declaration++Independent common preparation progressed while retained owners prepare patches. Exact owned declaration+six-test checkpointf2517f6eb05b07d097dd5c074d08c16c50a087d7 supplies MCPModernProviderBinding.prepareReadPages(_ pages:[MCPPreparedToolRead],tool:String,operation:MCPReadOperation)throws->[MCPResultPreparedPage]. Deliberate typedMCPResultPreparationError.notImplemented marks missing16behavior;17implementation not started. T63 can compile against this actual declaration, not guessed API. ImportedpreparedResultPage carrier18a3483 remains exactownerce4d0af.++Six owned tests use genuine coordinator operations and cover all private page cardinality/source lexemes/shared metadata identity, malformedlaterpage wholefailure, original error flag/category/frozenmetadata, carrier preservation, authoritative attachedfragment/newRPCIDs, and original operationexpiry. Source/commandcriticclear; frontendparse/AST/strictno-cachelint/diff0. Expected partialRED:fivefeature failures plusonecarriercontrolPASS, not yet observed. Exactpacket .codex-cache/task16-read-pages-red/guarded-commands.json, fresh separate private products/bundles/plist/logs, signedisolatedunitpreflight, failclosedexact6 compiledinventory. Original15products/artifacts unchanged. Root verified/created all exactprivate cache/tmp/modulecache directories before scheduling to avoid prior setup omission. Combinedcompiler/runtimeunverified; no heavyjob.++This is partial16readiness, not full16completion. Ordinary/reusable expandedstore capacity/privatepublication/canonicalcommentr1/midworkdeadline/physicalrestart fixtures remain coordinatedowner work fromtask16-owner-request.json. Existing domain/coordinator/capture/lifetime seams suffice; no newengine. Rune16inprogress; task17 remainsblocked untilmeaningful16evidence. Parent-exclusive6methodslot requested next; no actualclient/settingsactivation or laterwhole-ticket/consumerblock.+++## Task16 combined owner fixture import++Parent supplied T2382 owner fixtures from0c2415ee1eaf08f4f865b7df872c584586bc2035 and authorised their import into one combined task16 checkpoint. Exact patchSHA25691800ff196a7dfdd29f8b162bdcf1b3704eb85ab53bee78cecd0e6bd16fed5c3 applied and committed ascb10602; single file MCPReusableSnapshotPreparedOwnerTests.swift SHA256bf6952a6f7de4558136401137afe5b50d7d9d11875ff5eb5d36c3ce57152da05 matches supplied manifest. Six declarations/seven expanded cases cover shared base and distinct new owners, rejection of shared new ownership before transfer, cross-root rejection, zero-cursor first-response charge and surviving-root retirement accounting. Owner retains ownership. Source import is not runtime evidence.++T63 recipient declarations/origin fixtures and T2382 Store/Index declarations are also imported in2e8033c/4c3da7b/f06d9f3. The earlier six-only runtime packet is superseded by a combined scope; it will not run separately. Parent released T2384 slot and conditionally granted next exclusive slot after combined scope and critic checks clear. Owned fixtures and two oracle corrections are still being finalised; no build/test has started and task17 functionality remains pending meaningful16 RED.+++Combined RED critic permits the exact imported owner's late-stage shared-new rejection assertion because missing-feature declarations fail before that path. It is a GREEN fixture-correction obligation, not a normative requirement to defer safe rejection: coordinate owner correction if reservation rejects safely first. Owned sibling coverage accepts either safe pre-transfer rejection stage. Parent additionally requires one coordinated GREEN handoff mapping common retention capacity failures to existing typed capacity outcomes and checkpointing aggregate owner-union measurement through the same original operation; T2382 operation-aware overload must preserve callback lifetime and shared publication gate ownership. No new deadline/publication engine.+++## Task16 first combined build: fixture compile correction++Combined owned source5678381 with exact37 declarations/40 expected argument-expanded bodies passed final staticcritic; critical13input hashes and command/build hashes verified. Normal auto-review accepted actual build in freshprivate DerivedData; exit65 before hostpreflight/enumeration/tests. Two surfaced compiler diagnostics: ambiguous Comment in owned OrdinaryRetention helper and missing MCPPortfolioSavedFixture in imported owner suite. Owned runner72915 drained; root exactescalatedps confirms absent, exclusive slotreleased immediately. No meaningful RED or passing test body claimed. Original attempt cache/build result preserved.++Narrow semantic-preserving correction2102864 qualifies Transit.Comment. Dependency inspection also found imported owner suite references MCPReusableSnapshotStoreTests cursorToken/commit helpers. Both exact owner0c2415 supportfiles imported after independentcriticclear as01a903d: MCPPortfolioFixture.swift SHA256af3d71a99f08ed241e4ac43534105d34edec15cdac3b7becf2d6af005970ee25; MCPReusableSnapshotStoreTests.swift SHA25659147e4da10a0082908456b9041af872325f9f355756f19c494c144a205b1ffc. Ownership staysT2382; no guessed helper/secondpublicationengine or assertion/productionchanges. Support StoreTests methods remain entirely unselected, so actualselectedinventory muststillverify37/40. Separate compile-fixed packet is being prepared and reviewed before same-scope continuation; no retry yet at this checkpoint.+++## Task16 corrected build: released slot, accounting fixture fix++At01a903d/docscf97fcd, final reviewed compile-fixed packet preserved exact37/40 selectors and15criticalinput hashes. Normalreview accepted incrementalprivatebuild session40277; actualexit65 before hostpreflight/enumeration/tests. One actual SwiftTesting macro error at MCPModernReadBoundaryTests45: accounting throws inside a nonthrowing catch. Owned secondPID was not captured before fastexit and remains unknown; exact reviewedcommand processmatch absent, root independently confirms no xcodebuild for thisprivateDerivedData. ImmediateRELEASE beforecorrection/bookkeeping, queuedT2384 may take slot. No thirdrun launched. First43artifactmanifest root rehashed withzeromismatches; secondfailedattempt preserved separately.++Reviewed onefilefixf93d554 handles accounting explicitly: preserves pendingBytes==0 assertion, recordsIssue/failedmarker on accountingthrow; identical savedtwo-task setup moved into privatehelper only forbody-lengthlint. Parse/strictlint0, internalcriticclear; no assertionweakening/productionchanges. Actualcompiler and37/40 RED remain pending. Fresh accounting-fixed readiness packet is unexecuted and requires a newparentexclusive slot afterT2384; user generaltest/build authorisation persists. Rune16 remainsinprogress; task17 functionalGREEN stillblocked on meaningful16 RED and coordinatedretained-ownerhandoff.+++Final accounting-fixed packet at sourcef93d554 is staticallyCLEAR: exact37 declarations/40 expected bodies, unchanged inventory/verifier/selection and signedisolatedhostguards; freshpaths preserve bothfailedbuilds. Preparedonly .codex-cache/task16-combined-retention-red-accounting-fixed/guarded-commands.json; buildSHA256ea5cc5ea272ba22f05915d1147c8ebe3555664709b761d00d66e8e92b9db9bf5. Root rehashed second22artifacts withzeromismatches, first43alsozero. Worktreeclean before thisdocumentation update. No activeheavyjob/no thirdbuild; ready fornewparentexclusive grant. No functionalRED/16completion/17implementationclaim.+++## Targeted frontend check catches remaining owner macro error++While T2384 owns GREENslot, parent requested targeted compiler/typechecks with no competingappbuild. Actual bounded swift-frontend -typecheck checks11fixture/helper files (2052lines) against alreadybuiltTransitmodule using actualSDK/explicitmodules/Testingplugins; no emission/link/app/testexecution. Initialcommandsetup exit1 before sourcecheck lacked companionbuildsessionflag, preserved. Restoredexactflag currenttree invocation exit1 in2.5seconds identifies imported MCPReusableSnapshotPreparedOwnerTests228–229: throwing metadata adapter inside #require lacksinnertry. No otherdiagnostic emitted. Staticaudit had missed thismacroboundary; actualcompilerproof supersedes priorstaticreadiness.++Exact one-token ownerpatch .codex-cache/task16-targeted-typecheck/owner-inner-try.patch SHA25612d6ede64c91fd31ff8cc1a256af87dffdfe199428a910fc435596c5c84b0c75 adds innertry, preserving error propagation and requiredvalueassertion. Temporaryoverlay SHA256722144dcd884dac4033da1b5b4cf3e49af7e413b34469c3d00009fec04456d20 typechecksEXIT0 in2.401seconds, emptydiagnostics/notimedout. This isoverlayproof only: actualretainedowner source remains bf6952...unchanged. Root verified16artifacthashes zeromismatch. Allfrontend jobsdrained/noappbuild/heavyslotuse; semanticsunchanged.++Existing37/40 accounting-fixed packet is NOWBLOCKED until T2382 ownercorrection is coordinated/imported, then same-scope sourcepin mustrefresh. No newuserapprovalgate: exactownerhandoff/slotcoordination only. Rune16stillinprogress/no actualRED/17GREEN. Failedbuilds and historicalguardedcommands remainunchanged.+++Parent newexclusiveSTARTgrant after T2384GREEN84/drain includes reviewed narrowincidentalcompilerfixes within same37/40scope. Exact innertry patch importedas936d10b (gitapply-p0 because unprefixedpaths); postsourceSHA256722144dcd884dac4033da1b5b4cf3e49af7e413b34469c3d00009fec04456d20 matches successful targetedoverlay. This parentauthorisation resolves exactfixturecoordination exception, not ownerwriteownershiptransfer or semanticchange. New sourcepin/freshevidence labels beingprepared for actualcombinedrun; previousbuildfailures/typecheckattempts preserved. No testexecution yet.+++## Task16 meaningful RED complete / gpzncw0++Actual source936d10b owner-fixed build/preflight/enumeration/exactcompiledinventory allEXIT0. Console reached all37declarations/40argument-expanded bodies in8suites,4.469seconds/67globalissues. Runtimecriticclears meaningfulmissingfeatureRED: factory/store declarationsnotImplemented, attachedfragmentreparse and actualpagedservicepreparerinactive; existingcapture/provider/physicalpermitrestart/race controlsPASS. DetachedworkerownerIssues may be attributedunknown and methods misleadinglylabelledPASS; no reusableownerretention/sibling/retirement successclaim or scopedPASS count. Laterassertions behind missingseams remainGREENobligations. ScopedNIOmisuse0.++Finalizationremainedactive afterbodies; exactrunner85923+guardedhost85928 identities and3second samples both0 BEFOREverifiedrunnerTERM. Hostalreadyabsentafterrunnerstop/nohostsignal; bothfinalps1, rootindependentps confirmsabsent. ImmediateRELEASEbeforeextraction/bookkeeping. ActualtestEXIT143, xcresultmissingInfo.plist/unfinalizedsummaryEXIT64; no finalizedPASS/FAIL count, no causeclaim/cosmeticreplay. Root rehashed42finalartifacts zeromismatch; preservedprior43/22artifacts alsozero. See .codex-cache/task16-combined-retention-red-owner-fixed/results.md and app-actual-results.json.++Rune16/gpzncw0completed; approved17/gpzncw1 is next and may proceed through retainedownerhandoffs, no17source yet/noactiveheavyjob. task17-owner-runtime-handoff.md packages exactsource/evidence/innertryimport and parallelcommon/T63/T2382 scopes, including existingcapacitymapping/originaloperationaggregatecheckpoint agreement. No liveclientactivation/push/merge/deploy.+++## Task17 owned common factory/read binding source checkpoint++Parent START17authorises parallelcommon andretainedownerGREEN, onecombinedverificationbuild after exactownerpatches, no competingheavyjobs/newusergate. Rune17/gpzncw1inprogress. Ownedtwofilecheckpoint0af0bfc1da9538a384807678cffec9192c91b8de implements prepareReadPages originaloperationcheckpoint/allprivatepages/allorthrow, freshsinglemetadataowner and samecall explicitattachedowner reuse after boundedcapturebytesconsistencyguard; attachedowners authoritative/unchanged, no globaldedupe orlegacyinspection. Attachedread encodessealedfragment/newRPCIDonly. Freshvalidatedlogicalsource parsedonce; new source-preservingPreparation.page overload presents/freezesit, existingtextrequestAPIdelegates. No retainedproductionwriter orclock/admission/publicationenginechange.++InternalcriticCLEAR; parse/strictnocachelint/diff0. Faithful4actualsourceTEMPcopy frontendtypecheck includes unchangedAccounting/carrier solely fornominaltypealignment against builtTransitdependencies: EXIT0/0.456seconds/emptydiagnostics/noemit/link/app, compileprobeonly. Root verified4sourceinputhashes and13evidencehashes zeromismatch. BindingSHA25619838207c069827708d40c7cf65c843869b3d7769a055cb25bf6ac2d66c4ac23; PreparationSHA25679baa3f539d6eb8fe582d9b4be3f09b9296ca9ab45cb2d09b748342806bb51c3.++Exacttwofilepatch .codex-cache/task17-common-source/common-factory-read-binding.patch SHA2561c0af2d9073590d64216fdfc8370df2a3aded146b249ecb6f9603fbd85bb9961; owner-handoff.json/review.json in samecache. Existing callback ABIunchanged. T63retains actual MCPReadAppDependencies constructor and must install pagePreparer forwarding originalpages/tool/operation. CombinedruntimeGREEN waits exactT63/T2382retained patches andcoordinatedslot; no full17completion/actualGREENclaim. No newheavycommand/liveclient/settings/reportdelivery.+++T2382exact7filee7a4676 package readonlyapplycheck0; independentreviewclears accounting/provenance/ownercontext and flags boundedbytevalidation, opaque sealedcarrier replay and exactmodernroutefixture/harness wiring beforecombinedGREEN (task17-t2382-review-findings.md). No retainedimports yet. Ownedfixture correctionba9479a moves exactsame rawmetadata count into documentedcapturebase and migrates two modernaggregates to SAMEoriginaloperation, expectedtotals/assertions/legacycontrols unchanged; parse/strictlint/diff0/criticclear. T63 revisedpin/chunkedvalidation source is actively beingwritten inownerworktree, no unfinishedownerwrites copied. No competingheavyjob; T1734slot retained.++Task17 assembly checkpoint: common factory `0af0bfc`, owned fixture `ba9479a`, exact T2382 component imported `47bd166` from reviewed `95b416aa`, and exact corrected T63 component imported `9b1e4da` from reviewed `bf5191b`. T2382 all seven manifest hashes match. T63 nine file hashes match its manifest; service bytes match the exact supplied recipient-MCPReadService.swift artifact (actual SHA256 e9bdb602afd5b593d7df6080ad79f11958a880c4672c2fa902d00040420f3a6f), but declared service hash 7d33f74601fb7d3b0e2c44552169860f08b02478d642291136c9a7382b5fe107 differs. Recorded without a ten-hash-match claim in .codex-cache/task17-assembly/t63-import-verification.json. Independent internal source critic cleared both owner production changes; compilation/runtime pending.++Remaining coordinated acceptance inputs before pinning one combined GREEN: T2382 Summary replay/continuation and SnapshotTaskQuery continuation must use the now-delivered opaque `MCPPreparedToolRead(preparedResultPage:frozenMetadataBytes:publications:)` carrier rather than legacy typed metadata reconstruction, preserving existing pins; exact four modern router suites and MCPPortfolioModernHTTPHarness must be imported with explicit common pagePreparer callback in manual MCPReadService constructors. T63 new cursor-gate fixture defaults to legacy failure bytes even in its modern case; narrow modern constant-failure callback is advisable, with existing owned Boundary modern full-byte failure proof preserved. No owner source independently rewritten by T2383. The provisional static suite plan preserves original 37 declarations/40 expanded bodies and adds 17/21 (provisional 54/61); actual compiled enumeration and expanded execution must establish final counts. Parent has authorized exclusive combined slot once pinned reviewed packet is ready; no heavy process launched or slot claimed while these inputs remain unresolved.++T63 reconciliation received: task/t63-review-evidence/task17-ordinary-binding-corrected/manifest-reconciled.json explicitly separates recipient e9bdb602 service from local diagnostics 7d33f746 variant. Both patch hashes unchanged; root independently verifies all ten imported recipient file hashes. Original manifest and mismatch evidence retained; no source replacement required. Evidence: .codex-cache/task17-assembly/t63-reconciled-verification.json.++All requested owner response inputs collected and source integration complete at `2e37a8a`: exact c7dcb9a seven-path replay/fixture handoff imported with 7/7 root hashes verified. Independent internal critic cleared opaque replay, original pins/metadata, all four original-operation callbacks, full route fixture dependency/lifecycle/assertion review, and provisional 54/61 packet mechanics. Runtime remains pending; T1734 currently owns the heavy slot. T63 new gate fixture legacy constant-failure coverage caveat is advisory with unchanged owned Boundary modern full-byte fallback proof retained. Final source/inventory guards must pass before one scheduled combined build; no task17 completion claimed.++Task17 first combined GREEN attempt: pinned e46ba9d, normal per-command escalation accepted; source readiness all 513 inputs and directory setup exit0. Actual build session21854/PID9184 exited65 on two distinct T63 fixture Sendable diagnostics (repeated twice in compiler log): mutable NoCapture.calls in MCPReadFrozenCursorGateTests.swift and Source.failure in MCPReadModernPageBindingTests.swift. No preflight, compiled inventory, test host, or test body ran. Delegate exact runner ps1 and independent root escalated exact ps1 establish process absent; slot RELEASE reported immediately before evidence extraction. Default sandbox ps was unavailable and made no absence claim. No signals or source edits performed.++Minimal owner correction reviewed clear by coder and independent critic: explicit @MainActor on both private fake classes. MCPReadCaptureSource is nonisolated Sendable with @MainActor capture; fixture construction/mutable state/assertions already use MainActor. No production or assertion change, locking, unchecked Sendable, or gate modification required. Exact fixture owner retains edits; failed build and source proof must be preserved before a newly coordinated corrected attempt. Task17 remains in progress with zero current GREEN runtime bodies.++Collected first GREEN compile-failure evidence: .codex-cache/task17-combined-retention-green-preparation/results.md and app-actual-results.json preserve actual exit65, no host/preflight/enumeration/test bodies, normal runner drain and RELEASE. Failed build result bundle has finalized Info.plist; this is compiler evidence, not test evidence. Root independently rehashed all 37 final artifacts and all 513 pinned source inputs with zero mismatch. Proposed exact owner-only patch is proposed-t63-source-fake-isolation.patch, SHA256 76e53d37c41a32aa7e85de9ad6197c6c7cf5aa7579456b1cbcacab6198ddfed6, with pre/post source manifest; not applied. Source-corrected acceptance will use fresh result labels and preserved failure evidence after exact owner handoff/slot coordination.++Exact fixture correction collected from owner commit4ee79a42f167adda5468fe480279d0aefb16bc70 and imported022ce9a. Owner patchSHA11750612f9036ebbd3bc299870f371f21a646f900a2203846c03b30064b44ec2 and both post-source hashes verified; immutable exact diff independently clear. Only two MainActor fake-class annotations changed, with production/assertions untouched. Prepare same54/61 corrected acceptance using separate fixture-isolation-fixed cache/result/plist labels, explicitly reusing private DerivedData/SDK/flags/packages; preserve first37-artifact compile failure and no premature task completion. Parent queues next slot after T2384 drain; no heavy retry yet.++Corrected combined attempt at66cca07: build/session59560/PID21596, signed isolated host preflight, enumeration and exact compiled inventory all exit0. Exact54 enabled declarations ran in14 suites; console case inventory verifies61 actual bodies (12 case starts across5 parameterized methods). Two issues belong to one owner discovery fixture assertion expecting content/structuredContent properties in outputSchema; approved outputSchema describes structured value contractVersion/source/presentation. Independent critic classifies fixture oracle mismatch, with no production schema defect or change warranted. No unknown-test issue or NIO misuse matched. All runtime controls ran; task17 is not complete while fixture assertion remains failed.++Test/session12357/runner23056/host23078 finalization stayed active after console summary. Both exact identities sampled successfully before runner-first bounded TERM; host already absent afterward and received no signal. Both independently absent via root escalated exact ps1. Immediate RELEASE preceded extraction. Actual test exit143, unfinalized test bundle missing Info.plist and xcresult summary64; cause remains unproved and no cosmetic rerun justified. Preserve actual console/body/samples/provenance; no source changes or retry before classified owner correction and coordinated slot.++Final corrected-attempt evidence collected at .codex-cache/task17-combined-retention-green-fixture-isolation-fixed/results.md, actual-results.json/body counts/samples/cleanup/extraction logs. Root independently verifies all113 final artifact hashes and all513 pinned source inputs, zero mismatch. Cache-only owner schema-oracle proposal: proposed-t2382-discovery-schema-oracle.patch, SHA256 d99fcf0e56234177c9dca6819fa469ffba8ee0c76ed430bae2d742449192986b; not applied. It checks the approved structured-value contract properties/required fields/closed root/version1 and retains remaining input/validation/no-capture checks. Owner correction and newly coordinated verification are the remaining acceptance inputs; no production change or premature GREEN task completion. All worker responses collected and no active job remains.++Task17 selected acceptance now clear: exact owner oracle correction2232409 importedec1b721, production unchanged. Parent authorised actual discovered one-method verification, with no full61 repeat. Focused sourceReady/build/signedpreflight/enumeration/inventory/test/summary all0; finalized1PASS/0fail/0skip/runtimeWarningsempty, no global/unknown/NIO issue. Normal process drain and immediateRELEASE, no cleanup signals. Root independently verified exact runner27067 absent and no guarded host; rehashed72focused artifacts plus113+37prior artifacts and513current source inputs, zero mismatch. Combined proof is prior53decl60body consolePASS plus corrected1decl1body finalizedPASS, explicitly not a single finalized54/61 run; previous143/unfinalized/summary64 limitation preserved. Internal critic clear; all workers collected. See task17-handoff.md for exact ownership/interfaces/evidence.+++## Task18 subscription RED source ready, recovered after interruption++Approved continuation after task17e45bc003 retrieves Rune phase/streams:18 is sole ready stream1 task,19–22 dependent. Fixture436682478 commits only four test/helper paths, replacing legacy notification/route expectations and adding owning subscription transport/lifecycle fixtures. Provisional18 declarations/34 expanded cases across3 suites; actual compilation/enumeration/bodies unrun. Syntax/strictlint/diff0; final internal critic clear. Root independently verified515 pinned source hashes and exact four committed paths, retainedSettings unchanged, guardedcommands SHA762db0f27371380a43c3b4a809d7d73ffed0606947e5574f3336c16fc3769531. Current501 is intended route RED, deeper queue/lifecycle oracles await19GREEN.++Usage interruption after commit/pin was recovered on owner-resume instruction through the same delegate and root. Indexempty, only root readinessdocs dirty; no task18 app runtime logs/bundles or launched sessions. Normal-escalated read-only process checks found no ownedSubscriptionRed runner/exactprivatehost; no signals or command duplication. Prior72+113+37 evidence hashes remain unchanged. All worker responses collected; no active task18 job. Parent holds new build/test until T63 confirms lastheavy drain and exclusive slot is granted. Rune18 remains inprogress. See subscription-red.md and prerequisites.md for actual nextslot package and separate client-prerequisite action; no Settings/client/liveactivation/push/merge/deploy.+++## Subscription Settings owner request and separate client setup proposal++Parent preserved ready4366824/f40dfb3 and queued task18 RED after T63 corrected13-body RED and T2384 task8 GREEN, before T2382 full-platform work. Prepared subscription-settings-owner-request.md pins T63 Settings SHA c2fe9f43 and proposes a same-object MainActor getter of the existing broadcaster type. It also records synchronized task19 legacy Settings/handler/helper cleanup and the remaining ModernBinding availability-test consumer, preserving the actual observer and read lifecycle. No source patch, new stream API or independent broadcaster was introduced.++Prepared client-readiness-setup-proposal.md separately: installed CLI help/features support invocation-only Codex modern override and Claude strict disposable config; current standalone modern feature is false. Proposed effective-server inspection is mcp list --json before any session, with map-replacement/plugin coverage still to establish. Read-only Desktop vendor source identifies its native HTTP host/caller but not a supported temporary local user registration or active negotiation; no hidden managed field/flag/proxy is proposed. Actual named surfaces, fixture descriptor, client-side structured consumption and any bounded synthetic model turn remain separate prerequisites/approval scopes. Public official docs confirm syntax/runtime paths, not interoperability. No client configuration, feature override, session, fixture listener, model call or app build/test ran. Internal critic clear as staged proposals, with effective-map inspection acknowledged as pending.++## Task18 actual RED and owner handoff checkpoint++Task18/gpzncw2 completed on meaningful actual subscriptionRED: tested3abdf24,18declarations/34bodies,16expected501 failures+1incidentalForbiddenoracle;6controls/17bodiespassed. Build/preflight/enumeration/inventory0; test143/unfinalizedmissingInfo/summary64 after bothownedprocessessampled0 thenrunner-firstTERM, hostexitedwithoutsignal. Bothdrained/rootindependentps1, RELEASEbeforeextract. Three earlierbuild65 attempts hadzerobodies; rootindependentlyrehashed104failed+60runtime artifacts zeromismatch. Oracle-only9f2eb39 parse/lint/diff0/criticclear, notruntimeverified. See subscription-red.md actualacceptance and cache results.19ready;20–22blocked; no19source/heavyjob/clientprobe.++Client-readiness-approval-bundle.md is internalcriticCLEAR preparedscope. Read-onlyinstalledtargetidentity confirms Codexnativehost /Applications/ChatGPT.app=com.openai.codex, distinctfrombundledCLI; invocation-onlyCLIconfigpossiblebut effectivepluginproviderisolationpending. ClaudeCode --bare/strictdisposableconfig supported; nativeDesktopregistration/activeconsumptionunproved. No clientactivation/config/modelturn. Askonceconcretefixture/target/contextvaluesexist.++Parentdesignated exactT63 ownerhandoffs reviewed: Settingsgetter4826658 importedfe497b6 andbefore/afterhashesverified. Task15fa58dc0 componentpatchapplycheck1 because recipientlacksTask14scaffold; handler/Appsingleconstructorhunksapplycheck0 buthelduntilcompleteinterfaces. Requiredhandoff: recipientcurrent→fa58 selective13paths withpre/posthashesincludingdiagnosticsscaffold, preservingexistingmodernpagePreparer/originaloperation/preparedcarrier/outputschema. No blindoverwrite/partialapply. READ_FAILED nonquerymachinecodegap requiresT63owned actualfaultRED/GREEN; no duplicateerrorinference.++## Task19 source and focused fixture delivery++Approved task19 source868ed04 implements request registration, protected acknowledgement/coalesced invalidation, original IDs/filter, whole-body cancellation and close/reopen lifecycle admission. Both concrete races found by internal critic were corrected, with two focused controls; seven owned files parse/strict no-cache lint/diff0. Small installed writer inout/cancellation API probe0 is limited to that interface, not Transit compilation. Rune19 is in progress pending actual GREEN.++Separate helper4ddbfc8 fixes async channel/loop ownership with success/error cleanliness checks, leaving caller inputs unchanged. Five fixture ports405ffc7 preserve47 declarations/62 cases and security/zero-effect/receipt/sequential/correlation controls; parse/lint/diff0/internalcriticclear and root5-file/declaration verification. Producer focused proposal25/41, fixture proposal47/62, combined exact9-suite72/103; no heavy command run. Final pin is gated on exact T63 Settings two-wrapper removal and serialized parent slot. Historical MCPWriteLifecycleTests remains untouched until explicit owner assignment.++The diagnostics recipient component now resolves its earlier baseline blocker: exact12-path owner source plus approved Handler/App hunks importedbd5c42a, all14 posthashes verified. generatedJSON default evidence for the planned catalog READ_FAILED payload is confirmed without common changes; focused RED unexecuted/GREENunapplied. See task19-handoff.md, modern-fixture-handoff.md, t63-diagnostics-handoff.md and fixture-coordination.md. Client setup remains held per concise approval bundle; no configuration/activation/modelturn.+++## Latest exact source integrations and historical fixture handoff++The parent accepted meaningful T63 six-case READ_FAILED RED with its unfinalized limitation. Exact owner d2648f6 two-file source imported21356d5 with verified pre/post hashes; six fault cases and13 diagnostic bodies still await runtime GREEN. Historical WriteLifecycle parent assignment is delivered e00e9a0: five preserved declarations/six expected cases, bounded post-acceptance cancellation/drain and exact persisted cancellation replay, no coordinator or production changes. Static parse/strict no-cache lint/diff0 and critic SOURCE CLEAR; root source/declaration verification recorded. These updates supersede earlier unassigned/unapplied status above.++Existing subscription25/41 and modern fixture47/62 proposals plus historical5/6 yield a proposed ten-suite77/109 union, not compiled proof. Exact T63 Settings removal of two unused legacy forwarders is still needed before compilation. Final source pin must remain fail-closed on that missing owner input. Parent exclusive scheduling applies; latest heavy-slot report T1734. No actual task19 GREEN, full rerun, client activation/configuration/model turn or push/merge/deploy. See task19-handoff.md and modern-fixture-handoff.md for concrete deliverables.+++## Exclusive sequential continuation: finalized task19 and meaningful task20 RED++Parent granted sole local implementation/heavy-slot ownership after all other workers paused/drained and authorised the exact agreed Settings cleanup. Unused two-method/14-line removal committedb94fb1e matches proposed afterSHAa9a5be9884ea481747458c70c52683a75a10d30072060564c7b471d1755d0009; no Settings behaviour broadened. Actual compilation found writer isolation then removed shared counter API: reviewed @concurrent annotation087d492 and bounded same-signature waitForLoad compatibilitycbc4aed corrected them. The two compiler65 attempts had no bodies; root rehashed24 artifacts zero mismatch.++Atcbc4aed, task19 combined signed/private host pipeline build/preflight/enumeration/inventory/test/summary all0. Exact77 declarations across10 suites/109 expanded bodies passed; finalized xcresult Passed,0failed/skipped/runtimeWarnings, no SwiftTesting global issues/NIO misuse. Normal exit/drain, no signals needed. Root20artifact hashes all match; critic runtimeCLEAR. `.codex-cache/task19-combined-modern-lifecycle-counter-fixed/actual-results.json` and task19-root-review/actual-green-root-verification.json preserve proof. Rune19 complete.++Task20 test-only623addf added real capture/verifier RED boundaries with protocol/header/metadata/schema/consumption/correlation oracles and endpoint alias refusal. Python complete specimen plus targeted mutations produced deliberate NotImplemented errors, labelled test doubles rather than client proof. App build/preflight/enumeration/inventory0, actual2bodies:1intentional capture.notImplemented failure,1isolationcontrolPASS,0incidental/NIO issues. Postbodyfinalization stalled beyond bounded120s: both exact ownedrunner/host samples0 before runnerTERM; host exited withoutsignal, bothdrained/RELEASE before extraction. Actualtest143/summary64/Infoabsent unfinalized; console-body RED only, cause unestablished. Root26artifact hashes match; critic meaningfulRED clear. Evidence `.codex-cache/task20-readiness-red-runtime/actual-results.json`; no cosmetic rerun. Rune20 complete/21 inprogress; no installed client or model action.+++## Task21 isolated fixture/verifier GREEN++Actual app router/validator/encoder/read services run over an owned port0 loopback listener with in-memory TestModelContainer, synthetic records, no CloudKit store and only query_tasks/get_projects calls allowed. Fixture denies an otherwise valid write403 before dispatch/receipt reservation. Descriptor and hold0..120 lifecycle are exported; installed clients remain untouched. Task21 source d502388, explicit hold-aware timeouts764b07e, and launcher dual-xctestrun layout correction68ba166. First launcher attempt exited1 after build/preflight/enumeration/inventory0, before test launch; preserve its evidence rather than infer a fixture failure.++Fresh corrected launcher actual0: sourceReady/setup/build/signed-unit-preflight/enumeration/exact2inventory/test all0. Finalized2declarations/2bodies PASS,0failed/skipped/runtimeWarnings,0summary-extraction. Owned ephemeralport61985 held7seconds and gracefullyclosed; actualURLSession6exchanges (200/200/200/400/404/400), write-denial403, native parsed structured source and correlatedACK/complete frames. Committed verifier accepts synthetic trace with installedEvidence=false; standards-compliant Draft2020-12 validates the actually discovered query_tasks outputSchema against actualstructuredContent. No hang/signals, bothownedprocessesdrained/release before extraction. Root25artifact hashes match, criticruntimeCLEAR. `.codex-cache/task21-readiness-green-plist-fixed/actual-results.json`, actual-endpoint-descriptor.json and actual-readiness-trace.json retain proof. Rune21 complete/22 inprogress.++This proves the conforming synthetic fixture and evidence-verifier, not installed-client readiness. Requirement6.3 remains open. No actual client activation/settings/model turn/push/merge/deployment. Task22 continues local selected common/provider/schema regressions with unchanged compiledSwift products and isolated host preflight; other-owner full-suite defects are not silently repaired.+++## Task21 real loopback fixture GREEN++Test-only fixture/verifier/launcher d502388 and bounded ordinary/SSE timeout764b07e implement real app router/validator/encoder execution over owned port0 loopback callback, in-memory owning model fixture, read-only incoming allowlist with canonical Base64 forms and denied-write/no-receipt control. Descriptor/export/0..120-second hold and scoped launcher timeout diagnostics/cleanup preserve isolation; launcher refuses reused output paths before commands. Real trace and synthetic test doubles cannot be classified as installed-client evidence. Initial launcher stopped1 before bodies after build/preflight/inventory0 because actual xctestrun used root-target shape; reviewed narrow dual-shape68ba166 correction preserves single unit target/smoke/persistence/host guards. Root18first-attempt artifacts match.++At68ba166, fresh launcher session9893 actual0 and all stages0; exact2 compiled declarations/2 bodies finalized PASS,0failed/skipped/runtimeWarnings, no SwiftTesting/NIO issues. Real owned endpoint127.0.0.1:61985 used hold7 and gracefullyclosed after ACK/complete; valid discovery/list/read, wrongversion400/legacy404/notification400 plus valid deniedwrite403 retain zero receipts. Native URLSession parsed source consumed exactly; committed verifier accepted synthetictrace with installedEvidence=false. Actual discovered query_tasks outputSchema validates actual structuredContent under pinned Draft2020-12 validator. Normal runner/privatehost/listener drain, no samples/signals needed. Root25final artifacts match; critic runtimeCLEAR. Evidence `.codex-cache/task21-readiness-green-plist-fixed/actual-results.json`, actual-readiness-trace.json and actual-endpoint-descriptor.json. Rune21complete/22inprogress. Installed Codex/Claude surfaces and AC6.3 remain unproved; no client activation/settings/model turn or production cutover.+++## Final independent local task22 verification++Signed/private serial integrated regression onHEAD91248e8 reused identical pinned68ba166 Swift products after hash/preflight gates. Corrected81 declarations/116 expanded cases across10 suites finalized PASS, all stages0,0failed/skipped/global issues/NIO/runtimeWarnings; normal runner/host drain and heavy slot release. Pretest mismatches from initial80 selector extraction remained fail-closed with no bodies. Existing make lint0/527 retained, offline actual schema exports12/36/37 passed876 assertions plus3 recovery descriptors, readiness self-tests5PASS. Root independently rehashed366 final artifacts zero mismatch. No code changes in this verification. See local-verification-handoff.md and `.codex-cache/task22-local-integrated-validation/actual-results.json`.++All independent local implementation/tests are complete; Rune22 remains In Progress/AC6.3 open for actual installed-client evidence. No activation/config/modelturn/push/mainmerge/deploy. Read-only installed Codex schema metadata exposed a prospective native direct-tool API that may avoid a model turn; no runtime proof or desktop equivalence is inferred. One bounded standalone CLI action is proposed in client-readiness-next-approval.md; other client surfaces remain parked pending supported exact setup.++## Owner-approved post-merge client compatibility deferral++On 2026-10-04 the owner explicitly accepted that T2383 actual client compatibility tests may take place after merge, when they pull and deploy Transit on the MacBook (parent-verified Sentinel_c0dbfe3212888191bc01744c855f67bb). AC6.3 remains unverified and is deferred to that post-merge validation; it no longer blocks this authorised merge. Synthetic fixture checks do not establish installed-client compatibility. This amendment does not authorise client setup, persistent settings/feature changes, model turns, MacBook work or deployment here. Local checks, pre-push review and PR Pilot readiness criteria remain required.++Post-merge checklist: verify modern discovery and tool list/call with parsed structuredContent for each intended Codex surface, Claude Code and Claude Desktop against an isolated latest-only endpoint; validate subscriptions for installed clients that opt into them; record unsupported modes and exact negotiation evidence. Preserve original text/replay/cursor evidence during checks.++## Pre-push explanation and completeness assessment++### Beginner++Agents can consume the same task and outcome information directly as structured data while the existing text remains available. Transit keeps the original saved response separate from added explanations, so replay does not quietly change what happened. Links say unavailable until Transit has an actual entity-opening feature.++### Intermediate++Providers supply immutable original text, optional error presence and typed recovery context. The source parser preserves JSON token identity; the presentation adapter derives separate classifications and UUID-associated link availability. A common byte encoder emits modern complete responses and preencodes mutation fallbacks before effects. Covered reads prepare frozen fragments and reserve charged retention before atomic publication. The latest-only router validates request metadata and matching headers before dispatch; subscriptions use request-scoped POST/SSE rather than sessions.++### Expert++Retention owns logical source, frozen tool fragments and capture metadata separately from per-request IDs. Cancellation suppresses delivery and late publication while unfinished physical reads retain admission charge. Historical malformed/deep/contradictory evidence preserves raw text and cannot establish no effect. Full fallback bytes are selected without reentering a failed encoder after mutation acceptance. Canonical comment-covered r1 and original protected keys remain authoritative; structured wrappers cannot extend receipt/cursor expiry or introduce a second normalizer. Supplemental categories are typed provider evidence and never rewrite outcome/retryAction.++### Completeness assessment++Local source/presentation/schema/protocol/provider/read/subscription code and synthetic readiness fixture are delivered and locally verified. Caller contract documentation is now supplied and legacy transport instructions corrected. Actual installed-client compatibility remains unverified and is explicitly deferred to post-merge MacBook validation by the owner's amendment. T572 navigation and T2384 production batch integration remain independently scoped. Pre-push full iOS/UI checks and PR review remain completion-workflow gates until actual results are recorded.++## Completion-workflow verification++Final pre-push source9c41be6 passed44declarations/90expandedcases with signedhost/inventory/globalissue checks and lint527/0violations. Full guarded iOS1310/1358 and separate UI21/24 finalized PASS with no failures/skips/global/runtime warnings. Owned simulator/processes drained; raw shutdown149 alreadyShutdown and delete0 preserved. Caller docs d65d305 satisfy both supporting-doc gates. See pre-push-handoff.md for exact source/equivalence/evidence and remaining PR workflow. Actual client AC6.3 remains owner-approved deferred and unverified.
diff --git a/specs/structured-mcp-results/interface-coordination.md b/specs/structured-mcp-results/interface-coordination.mdnew file mode 100644index 0000000..ebef057--- /dev/null+++ b/specs/structured-mcp-results/interface-coordination.md@@ -0,0 +1,178 @@+# Pending common result seam coordination++## Current checkpoint: task11 verified GREEN; slot released++Task10 meaningful RED is complete at41d5114: build/preflight0, actual console11 methods/10 deliberate notImplemented failures/1controlPASS, no incidental errors. Sampled finalization stall led to runner-only cleanup/test143 and summary64/unfinalized bundle; no finalized counts or normal-exit claim. Processes drained and slot released, critic clear.++Task11 value-only preparation/accounting source1135a88 is statically reviewed and GREEN-ready. Lightweight compilation/parse/lint/direct completion and an independent9,332,951logicalbyte volume observation are recorded; no actual app GREEN or all-#expect-pass claim. Original fixtures intact. Exact guarded unit-only serial eleven-method command and fresh result paths are in .codex-cache/preparation-green-source/; see preparation-green.md. Task11 is now complete after actual11/11 appGREEN, finalized zero failures/skips/expected failures/runtime warnings, build/preflight/test0. Owned processes drained normally and slot released before extraction; no cleanup/replay. Runtime critic clear. Task14 is the next DAG task; DELIVERED15 undelivered.++Direct user approval covers builds/tests. Asterism quiet window ended before the granted task11 run. Any later app run requires a new parent-exclusive slot. No slot/job held here; routine evidence remains local and live/client actions held.++The staged modern ownership transfer is accepted for the ten production paths in modern-transfer-acceptance.json, pinned to manifest557b4c2/sourceb1f3025. The minimal StageB production baseline is now imported at36030cf+1a19dfd:20 exact paths, critic reviewed, no extra source changes. See task14-baseline-import.json. T63 retains Reads/ordinary retention/definitions/common HTTP helpers; T2382 reusable modules; containment App/project; T2384 WriteCoordinator/tests. Seven optional fixtures remain separately authorized candidates.++Task9 source/schema remains verified (actual5/5 app tests plus876+3 host conformance checks). Saved protected receipt source remains authoritative; batch/maintenance recovery uses the correct context-specific reconciliation. Common helper/router/expiry acceptance is due with API15; full read retention/publication binding follows16/17 without a reverse dependency on15.++## Historical checkpoint after task7++Tasks3/5/7/12/13 have completed their focused verification. The owned source/presentation/encoder implementation is available at 3ba1cfb, with corrected encoder verification recorded at 3e9f8fe:14/14 methods passed, build/preflight/test exit0 and finalised xcresult. The test-only numeric oracle correction ffe2c33 preserves all original production source and the14 method fixtures; no source semantics changed to accommodate Foundation's numeric conversion limit.++The implemented metadata boundary is MCPResultMetadata.make(document:checkpoint:), with private construction and a validated object-root MCPJSONDocument. MCPResultToolFragment has fileprivate construction through MCPResultEncoder.freeze(source:presentation:metadata:checkpoint:); encode(fragment:id:checkpoint:) adds the current RPC ID. MCPResultEncoder.prepareMutationFallback(id:source:context:metadata:checkpoint:) produces complete bytes from a provider-owned compact logical source before effects. Its batch fallback presentation omits itemId while preserving indexes/operation/tool/original key/target UUID; normal result source remains complete. Focused tests establish these new-module semantics, not production dispatch, receipt atomicity or transport delivery.++Task8 schema RED preparation is now in progress. MCPResultSchemas remains notImplemented. Task11 preparation accounting, task14 production selection proof and task15 common provider/schema/wiring delivery remain pending. **DELIVERED15/gpzncvz is not available to T2384 yet.** T63 retains shared wiring ownership; T2384 retains MCPWriteCoordinator and coordinator-specific tests. T2382 owns the current heavy verification slot, so task8 preparation performs no app build/test. Live data/client activation remain held.++## Historical planning note before focused verification++This note records implementation questions for approved tasks6–15 while tasks5/13 wait for safe application verification. It is planning only: no new production signature, task completion, shared-file handoff or API15 delivery is claimed. Existing declarations remain placeholders. No app launch, server reconnect, live write or test-isolation implementation is authorised by this note.++## Metadata and sealed bytes++The declaration-stage MCPResultMetadata dictionary must become an ordered, validated representation before encoder delivery, as already agreed with the parent. A validated object-root MCPJSONDocument is a suitable backing candidate: it preserves original UTF8, scalar-distinct member names, number lexemes and missing/null values; its private initializer prevents callers from forging insertable fragments. The eventual metadata constructor must reject non-object roots and honour the original worker checkpoint. Exact constructor names remain pending implementation/review.++Provider-generated metadata can use known typed primitives or ordered members, but must cross the same validated boundary before raw insertion. Unknown metadata must never pass through a String-keyed dictionary or Double reconstruction. Nested extension keys may be scalar-distinct even when Swift treats their spellings as canonically equivalent. Top-level namespace validation must match the modern metadata rules rather than use an invalid extension key merely to exercise that regression.++MCPResultToolFragment also needs private construction at the encoder boundary; arbitrary Data is not evidence of a complete valid tool result. Frozen bytes contain the tool result and original metadata, never the originating RPC ID. Wrapping those bytes with a new valid ID must not renew freshness, rebuild presentation, reread models or invoke parsing under publication lock.++## Prepared mutation fallback++T2384 supplies its compact logical serialization_failed source. Before any effects, the common adapter must finish the complete request-correlated modern response, including text, structured presentation, metadata and envelope. Failed preparation means zero effects. Later selection returns already encoded immutable bytes; it does not call the failed source, presentation or envelope encoder again. Cancellation can suppress transport delivery without changing stored outcome evidence.++Batch recovery context may internally retain itemId for normal aggregate correlation. Fallback presentation must omit unbounded itemId, raw records and link data; it retains original input indexes, operation/tool, keys and target UUIDs. A synthetic giant-itemId fixture must prove this boundary without clipping or rewriting the normal source. An aggregate whose nested originals exceed parser input depth32 after effects selects the preencoded shallow fallback and makes no no-effect claim.++Protected fallback keeps original tool/key recovery. Unprotected maintenance carries no invented durable key and requires fresh duplicate scanning/reconciliation. The provider owns its logical failure payload; the common encoder owns complete delivery bytes and selection safety.++## Checkpoints, ownership and charging++Parsing, source inspection, selector allocation/sorting, string escaping, metadata validation and full encoding must use the original operation's checkpoint outside the publication gate. No checkpoint closure survives in returned documents or frozen fragments. Preparation-accounting tests must include new retained backing, decoded owned value data and fragments, preserve existing capture/index charges, and charge genuinely shared backing once. Counting only raw JSON length must not be presented as proof of complete preparation cost.++T63 remains owner of read capture, admission, retention and publication hooks until its exact recorded handoff. T2383 owns separate result/modern protocol modules and later agreed common wiring. T2384 owns the write coordinator and batch consumer; no source edits there are implied. API15 requires verified source/presentation/encoder/schema/provider seams at actual delivery commits. The current READY presentation f4bd03a and protocol b6b616e drafts are not that delivery and remain unmerged.++The next implementation edge is safe GREEN5/13 verification, then encoder/schema tasks in their approved dependency order. No app-host execution resumes until the parent clears isolation and grants the relevant test slot. Live Transit mutation pause remains independent of local source work.+++## Staged modern sole-writer acceptance++Parent explicitly authorized the staged production-file transfer. T2383 accepts sole-writer ownership for the ten exact production paths listed in modern-transfer-acceptance.json, preserving manifest SHA256989b69f969b2c35f75460f3740a5074813ac606a18b75bdef67677aef0822352 from T63 commit557b4c2. All ten production and seven optional fixture hashes match both pinned sourceb1f3025 and the clean T63 checkout557b4c2. The manifest's prepared_not_transferred status is the earlier proposal; this local acceptance plus the parent record establishes the named production ownership handoff. No import or production edits occurred.++The seven fixtures are labeled optional/separately authorized by the manifest; their candidates/hashes are recorded without assuming that optional transfer. Reads/ordinary retention, definitions and current shared HTTP helpers remain T63; reusable source/tests T2382; WriteCoordinator/write tests T2384; App/project/build containment unchanged. Modern schema registration in retained MCPToolDefinitions and read/reusable bindings need owner-applied patches; owning the named handler files does not transfer their dependency modules.++Manifest evidence reports StageB64/64 production equivalence, owner router4/4 atb4c104e7 and expiry2/2 atee053269 separately. These are external owner evidence, not a combined/local run. Current HTTP-helper focused router/expiry verification with the real modern adapter remains an API15 obligation, alongside frozen metadata, full-byte publication and exact retention accounting. Diagnostics/descriptions/full-platform checks are not handoff blockers.++This satisfies only the named production ownership gate. Task10 actual RED is still blocked by approval provenance, task11 blocked by10, task14 blocked by11, and DELIVERED15 undelivered. No heavy slot held and no test retry is authorized by the ownership transfer. Integration planning follows the approved DAG; no source work is advanced past it.+++## Direct testing authorization++User directly approved all test/build runs in this task conversation. The provenance issue has direct user authorization available for the next normal review; no test call has yet been attempted under it. Task10 remains inprogress awaiting the next parent-exclusive slot; task11 stays blocked until meaningful RED. The exact reviewed commands and isolation constraints remain unchanged. No live/client/deployment authorization or API15 delivery is implied.+++## Task10 verified meaningful RED++Under direct approval, the exact build/test calls were accepted. Build/preflight0; actual console11 methods/1suite gives10 intentional notImplemented failures and1 parser/encoder controlPASS, no incidental errors. Finalization stalled; both exact runner68843/host68848 sampled before bounded runner SIGTERM, actual test143 and unfinalized bundle/noInfo.plist. Host drained automatically, no replay; slot released immediately. Critic clears meaningful RED, without finalized counts/normal-exit claim. Rune10 complete, only11 ready. Task11 value-only drafting next, GREEN separately coordinated. DELIVERED15 still pending. See preparation-red.md and local runtime evidence.+++## Task11 source readiness at1135a88++Immutable metadata/page/bundle factories and temporary checked retention ledger are implemented in Results only. True owner identity sharing, per-occurrence reference slots, original capture base and fixed per-store visible/pending capacity preflight preserve the reviewed logical metric. Bounded UTF8/tree/presentation checkpoints propagate original failures; no callbacks retained. Static critic clear, original fixtures unchanged. AppGREEN remains pending; task14/15 not advanced. See preparation-green.md.+++## Next integration baseline coordination++The ten production-file ownership paths are accepted, but StageBsourceb1f3025 has not been imported into this branch. Read-only comparison with our imported T63StageAb500543 identifies19 MCP production changes, including transferred common handler/types and retained T63 Reads/definitions/captured-preparation paths plus T2382 portfolio/reusable modules. A ten-file-only import would leave unresolved owner dependencies. Task14 planning must identify an owner-applied/coordinated complete baseline; no retained-owner module import/edit or optional-fixture ownership is assumed. Current HTTP helper verification is due with API15; actual read retention/publication remains16/17, without reverse delivery dependency.+++## Minimal combined baseline imported++The parent-approved T63 five-file patch (SHA256b1bffff5a9e25e441d14991aa2cc0ebe2b3a47b13bdb598f1f14013f8175ab5e) and two transferred handler/types baselines were consumed in36030cf. Owner-confirmed twelve T2382 MCP modules plus PortfolioSummaryService.swift were selectively imported in1a19dfd. All20 recipient bytes match sourceb1f30256; exact paths/fullSHA/owners are recorded in task14-baseline-import.json. Internal critic independently confirms exact20diff/no extras. No App replacement; Results/Protocol/original fixtures/current HTTP helper/ordinary retention unchanged. Owner source imports do not transfer editing ownership. No combined compile/runtime acceptance or API15 delivery claimed. Diagnosticsce0f1a9 excluded and awaits modern acceptance; no circular dependency.++Specific retained-owner follow-up: MCPHTTPTestHelpers.respond currently accepts protocolVersion but no ordered extra fields for required modern Mcp-Method/Mcp-Name or duplicate-header controls. Request T63 narrow optional ordered-field seam preserving existing defaults and Sendable response. Existing decoder/handshake fixtures MCPRequestDecodeErrorClassificationTests.swift and MCPInitializeHandshakeTests.swift fall outside the seven optional transport candidates; their ownership/modern port must be coordinated before removing their legacy expectations. No broad new approval gate: owned synthetic integration can proceed while these exact seams are supplied.++## Task14 concrete helper handoff and remaining read-owner hooks++Task11 actual app GREEN is complete at38ad663 (11/11 assertions, finalized Passed bundle, build/preflight/test0, slot drained/released). Task14 is now inprogress. The complete20-file baseline remains exactbyte verified; imported retained-owner source keeps its ownership. No combined modern runtime acceptance or DELIVERED15 claim is made.++The narrow T63-owned HTTP test helper grant is implemented at80e9dc4c39b49eaa90d552dc50d00b83ac7b208a. MCPHTTPTestHelpers.respond adds optional orderedHeaders:[HTTPField]=[] and appends supplied fields after convenience headers, preserving duplicates/defaults/nonisolated/Sendable behavior. Only four helper lines changed. Old SHA2566ab7df966537972871c75b5cb390574ee2087e57d640d5cc61c4c5c85beebf97; new SHA2569e07dbf9571de482b9135ea286e1d6871c7c39e429bd8a4babba99537ed79ac6. Static critic clear, diffcheck0; no helper runtime acceptance yet. Return this exact commit to T63 so its temporary helper-edit freeze can end. Ownership stays T63.++Parent also transferred two fixture paths for modern adaptation: MCPRequestDecodeErrorClassificationTests.swift at SHA2567bf50476f9fcadcc7bbce6fdd8b876f97e4687405741e46c6f6dec6273c5f966 and MCPInitializeHandshakeTests.swift at SHA2562730f26e8e18e80be75cc9bb3b45f02acbcc9f5fa07da4c2c625726089d2922d. Preserve malformed/invalid request, invalid-ID-to-null and missing-required-parameter regressions with supported-modern equivalents. Latest-only initialization does not regain legacy fallback. The seven earlier optional transport fixtures remain unaccepted candidates.++Two precise retained-owner requests target Reads/MCPBoundedReadDispatcher.swift. T63 chooses the final signatures and applies the patch:++1. Add an optional operation-aware normal encoding callback, conceptually encodeWithOperation:(@Sendable(MCPPreparedToolRead,JSONRPCId,MCPReadOperation)throws->Data)?=nil. Inside the original coordinator worker call it with the same tool/id/operation, otherwise use the unchanged two-argument encode callback. It returns complete modern response bytes before the publication gate. Checkpoints use the original operation.shouldContinue() and existing ReadExecutionError.timeout convention; no new clock, budget, deadline or engine. Preserve existing default behavior and two-argument fault injection.+2. Add a separate optional constant-tool-failure encoder callback, conceptually encodeConstantToolFailure:(@Sendable(MCPPreparedToolRead,JSONRPCId)throws->Data)?=nil. Current private failure/queryFailure->encodeResult bypasses the normal callback for prepared timeout/busy/serialization and publication expired/capacity failures. The new hook prepares complete modern bytes before the gate, preserving original IDs/codes/opaque failure metadata. It must not reuse a failing normal encoder for fallback. Malformed argument invalidParams is a JSON-RPC request error and receives separate modern-envelope adaptation, not a fabricated tool result.++These compatibility hooks do not change admission, capture, retention, publication or private retained fragments. Real frozen fragment/storage binding remains task17, without a reverse dependency on synthetic API15. Actual retained MCPToolDefinitions registration must consume the existing MCPModernToolDescriptor/MCPResultSchemas boundary through an owner-coordinated patch; no duplicate descriptor model.++Owned selector declaration and eight synthetic effect/source cases have parse, pure-module, macro typecheck and targeted lint0; a direct boundary probe observes typed notImplemented before dispatch. This is partial task14 preparation, not app RED or passing Swift Testing assertions. Actual provider/router and historic receipt/path-normalization fixtures are still being prepared. No heavy slot is held. Common delivery15 remains unavailable to T2384.++## T63 read encoder hooks consumed++Parent delivered T63 owner commit5a57896422e9aee4e31c0530e86f09fc9bc1fd83 and exact dispatcher-only.patch. Patch SHA25649444ade66c4f4dc684570977b5c87e453ded2604c726e99b1236c61db7a4ec9; applycheck0 against current baseline. Imported exactly in6a39611. Recipient dispatcher SHA2567ccc496f65c99db34c4ae913bdfab96380a6b67ad55f76c98dfc36c32e6cab25 matches owner source. The two optional callbacks have the requested signatures; publicationErrors uses the separate constant encoder, constant failures are prepared before admission, normal callback receives the original operation before publication. Default two-argument behavior is preserved. T63 retains editing ownership. Diffcheck0; owner reports four declarations/six cases prepared, runtime unverified. No local runtime acceptance implied.++Correction to checkpoint implementation wording: ReadExecutionError.timeout is private within MCPReadService, so an external modern encoder cannot name it. The operation-aware callback must use an accessible existing/owned boundary failure and the original coordinator cancellation/cutoff selection; do not widen private API merely to satisfy a guessed name. Original operation.shouldContinue() remains authoritative. Exact adapter mapping is task15 work, with owner coordination if needed.++T63 accepted helper80e9dc4 as38288da, ending its narrow helper-edit freeze. Owned maintenance fixture seam may declare a defaulted immutable optional ReassignmentResult-to-text encoder in MCPToolHandler for task14 RED; behavior stays unchanged until task15 binds it at the existing post-reassignment encode site. This is distinct from final envelope failure/delivery suppression and adds no coordinator or maintenance-service engine.++## Task15 retained definitions factory request++T63 retains MCPToolDefinitions.swift. The approved shared registration step needs a minimal owner-supplied factory, conceptually modernTools(includingMaintenance: Bool) throws -> [MCPModernToolDescriptor] (owner chooses final name). Map existing tools(includingMaintenance:) once into the existing descriptor: existing name/description, inputSchema=MCPJSONDocument.parse(JSONEncoder().encode(definition.inputSchema)), resultSchema=MCPResultSchemas.descriptor(tool:definition.name,description:definition.description). The Data parse overload exists. Preserve legacy definitions and all owner provider entries; add no second descriptor/schema model. Owned modern discovery/router consumes the factory and frozen availability, rather than editing retained definitions. This request uses verified component types, but is not an API15 delivery claim or a production batch dependency. The owner patch may be prepared while independent owned task15 work proceeds after14 bookkeeping.++## Task15 retained settings availability request++MCPSettings.swift is outside the accepted ten-file transfer. Its maintenanceToolsEnabled property is MainActor-isolated; it can change after handler initialization (the actual all-enabled fixture does so). Its existing didSet only persists defaults and calls a private broadcaster, offering no synchronous published availability accessor. An init-only copy would be stale, and asynchronous observation could race preadmission classification. Request a narrow owner-supplied nonisolated synchronous Bool snapshot/accessor, initialized from the stored value and updated synchronously in maintenanceToolsEnabled.didSet through a thread-safe holder before notifying availability changes. Owner chooses exact API. Preserve defaults, settings behavior and broadcaster lifecycle; no live storage or MainActor hop in the accessor. Owned router freezes that value for one request's method/tool classification, before read admission. Independent owned source/encoder work does not wait on this seam, but final integrated dispatch cannot claim correct mutable availability without it.++## Retained definitions factory consumed after correction drain++Parent delivered owner patch6a748928ccb6b91e6cebaf1538997e50d664b9da. Exact published modern-tool-definitions.patch SHA25636357d3c785fba21796e7443edc0baba08672568a6373495a8d1161a6d0228ea consumed in8be5d55 after build65 drained, applycheck/diffcheck0. Only13 lines add Foundation and modernTools(includingMaintenance: Bool) throws -> [MCPModernToolDescriptor]. Preblob SHA256decfde58b4728ace41b4c83f5b32f24a46ef397a001927843d90e279ab53d45a matches owner baseline; postblob879d1094658ad9840a86ce20839bbae048a4936540c169fa985a1d1df7c132dd. Owner commit publishes the patch rather than applying the new factory to its own baseline, so no false full-file identity claim. Existing descriptions/input schemas/legacy consumers unchanged, T63 retains ownership. Maintenance-off/on parity and actual single-object tools/list schemas are runtime task15 obligations; no API15 delivery claim. The mutable settings availability owner request remains separate.++## Retained availability seam consumed++Exact owner settings-only.patch105ba8fdfc9323d08248d615b1620232ae6bc687 consumed after normaldrain inb51ab96, applycheck/diffcheck0. SourceSHA256c2fe9f43e2283c792a98691d349da34ff7fe5dcb3545e5fb23e2c5a40d1cf062 matches owner; ownership retained. Use nonisolated maintenanceToolsEnabledSnapshot:Bool, initialized from stored value and synchronously updated by didSet before persistence/notifications. Source import changes no preferences. Both factory/availability owner seams delivered; runtime parity/initial/offactor/notification proofs remain15 obligations. Existing signed products built1a69d41 exclude the new settings seam and cannot prove it.+++## Task15 first implemented source boundary; delivery still pending++Reviewed source checkpointfb776a0 implements MCPResultProviderSelection mutation selection, MCPResultProviderAdapters and optional non-wire MCPResultProviderEvidence on MCPToolResult. Selector prepares complete request-correlated reconciliation bytes before dispatch, dispatches once, preserves source identity and selects prepared bytes after provider/encoding failure without reencoding; cancellation suppresses delivery. Adapters retain declared source origin, original text/isError and frozen read metadata evidence rather than guessing origin from parse failure. This is static-reviewed source, not integrated/runtime-delivered API15. Owned handler/router binding and focused GREEN remain pending; T2384 must continue waiting for actual DELIVERED15/gpzncvz commit/interface handoff. No reverse dependency on production batch.++The corrected four-body runtime used older signed products1a69d41 and excludes this checkpoint and imported settings snapshotb51ab96. Actual four identifiers all executed, decoderPASS/three intended feature failures/nine issues; NIO misuse0. Both sampled processes drained, slot released, test143/unfinalized summary64. Runtime critic clear with these limits, no further teardown-only retry gate. Retained T63 owner modules and T2384 write coordinator remain outside task15 editing ownership.+++## Task15 binding committed; exact combined GREEN ready++Owned ten-file binding checkpointa8fcc71506ff61ee5b6f0e320ace5a064e30c915 implements modern router/discovery/schema calls, frozen availability, source-specific provider evidence and entity positions, original read operation/constant failure encoders, and complete effect-aware mutation fallback selection. Existing validator preflight remains pure; no retained receipt rewrite/write-coordinator edit. Five narrow tests cover Unicode/numeric bridge rejection, no-effect protected rejection, stored/immediate snapshot values, change notifications and unsupported-method405 handling. Internal critic cleared final source and commands; frontendparse/strictlint/diff0. Root independently verified allten source SHA256s and exact build command hash. Combined compilation/runtime remain unverified.++Prepared only .codex-cache/task15-binding-green-readiness/guarded-commands.json: one fresh private build preserving oldnine pinned binaries, unchanged installed resolved package checkout, signed isolated development unit host, serial2jobs, preflight, compiled enumeration and failclosed exact100 declarations/11suites before tests. Expected declarations are separate from actual parameterized body counts. Build SHA256c83c279c5c3bcd4be2dbc300ce21dde4b95c31ea4d30a4201202d5b142fb532e. No app invocation or heavy slot held. Coding and critic turns completed with concrete readiness; request parent-exclusive scheduled execution next. Root will remain active through actual outcomes/drain. Rune15inprogress, DELIVERED15 unavailable; neither later read-retention/subscription/client readiness nor production batch completion is a reverse handoff dependency.+++## Task15 actual combined verification and two-fixture correction readiness++Initial private build exited74 before compilation because the private TMPDIR was absent. Created reviewed cache/tmp directories and preserved that attempt. Setup-fixed build exited65: owned binding fixture lacked NIOCore import. Exact one-import correctiond29fdaa independently clear, assertions/production unchanged. Both attempts drained; no preflight/test bodies ran. Authorised same-scope continuation used distinct evidence paths and the original private cache.++Import-fixed actual build/preflight/enumeration/inventory all0; exactly100 declarations/11suites verified before serial test. Console100bodies/11suites:98PASS,2failedmethods/4issues, scopedNIOmisuse0. Both failures trace to existing query_tasks mandatorylimit omitted in validArguments and assertReadParity. No production serializer defect demonstrated by these four issues. All five new binding fixtures and synthetic provider tests passed. Unreached assertions in the two failed methods remain pending corrected verification.++Finalization stalled; both exact runner46023/guardedhost46027 sampled0 before any signal. Identity-checked runnerTERM/drain, host drained after runner with no host signal. Immediate slotRELEASE before extraction; root independently verified bothPIDs absent. Test143, unfinalized bundle/noInfo.plist, summary64. Cause unproved, no teardown-only replay. Raw evidence .codex-cache/task15-binding-green-import-fixed/results.md; root rehashed actual evidence manifest with zero mismatches. Earlier74/65 artifacts preserved.++Exact two-limit correction543c4a757e4cb7f9f73c973d7cb1be5725c8f342 preserves assertions and production, parse/lint/diff0/internalcriticclear. Focused future verification .codex-cache/task15-binding-green-limit-fixed/guarded-commands.json uses existing private incremental build, fresh bundle/log/plist labels, signedisolatedpreflight, exacttwo method() CLI+plist selectors and failclosed inventory. Sourcepin543c4a7; buildSHA2562ff579f2e283ab9d69334990d4a1c7dece416da55b13523a0668ccc74f07bd2d independently verified. Full100 is not repeated solely for finalization. No retry launched; workers completed readycheckpoint, no heavy job/slot held. Request parent-exclusive focused two-method execution next. Rune15inprogress/DELIVERED15 pending actual corrected passes; no later-ticket reverse edge.+++## DELIVERED15 / gpzncvz verified common seam++Focused corrected543c4a7 verification: build/preflight/enumeration/exacttwoinventory/test/summary all0. Both exact methods executed and finalized resultPassed2/2, zero failures/skips/runtimeWarnings, scopedNIOmisuse0. Normal owneddrain and immediate slotrelease before extraction; no samples/signals/replay. Final independent integrationcriticclear. Root rehashed56 final evidence files with zero mismatches. Preserved98 passing bodies from the prior100 run plus finalizedcorrected2 fulfill15 regression obligations; prior143/unfinalized limits remain, no single100 clean finalizedclaim.++Rune15/gpzncvz completed. Common API delivered from sourcecheckpoint543c4a7, productionbindinga8fcc71, selector/adaptersfb776a0, with concrete api15-handoff.md and exact api15-source-manifest.json. Full verified runtime dependency manifest at .codex-cache/task15-binding-green-limit-fixed/source-dependency-manifest.json pins28ownedResults/Protocol/common files and21retainedownerinputs; not authorization to overwrite those owners. T2384 consumer integration can proceed through coordinatedimports preserving its writecoordinator; no reversebatchdependency. Later16–22 frozenretention/publication/subscriptions/clientreadiness remain separate. No activeheavyjob/liveactivation/push/merge/deployment.+++## Task16 retained-read coordination checkpoint++Parent authorised16–22 preparation after DELIVERED15consumers resumed; Rune16inprogress. Actual retained-source/fake/gate inventory identifies all-private-page owners, expanded charge and stored-fragment continuation as the next boundary. No new deadline/admission/reservation engine needed. Single bundled request task16-owner-request.json pins13 actualpaths and separates retainedT63/T2382 writers; no new owner implementation/fixture/runtime claimed.++T63 supplied ce4d0af prepared-page-owner.patch consumed exactly in18a3483 afterapplycheck0/diffcheck0. PatchSHA25622fec83828cbaa7e415c786e675186b52943324bf74d607fc7cca3ffa8a3b726; prepared-readfileSHA2561394537f348260d9022c5c2defa8fbaab744c06cf4cef4446b3e3cab9e5ff462 matchesactualownercommit. OptionalpreparedResultPage and nonthrowingattachingPreparedResultPage preserve oldbytes/metadata/publications; ownership staysT63. Source import only, no runtime acceptance.++Suppliedcommon factory request: prepareReadPages(_ pages:[MCPPreparedToolRead],tool:String,operation:MCPReadOperation)throws->[MCPResultPreparedPage]. T2383 delivers declaration/RED and implementation under16/17 and consumes attached frozenfragment with newRPCID. Remaining combined ownerrequests: ordinary all-private-page prep/storelookup/expandedcharge; reusable create+append+lookup/pin/expandedcharge; explicit plainText evidence for actual no-service readfailure. Existing originaloperation/coordinator/domain/capture/lifetime fakes supporttests. Separate16MiB/fiveMinute/eightSnapshot stores, canonicalcommentcoveredr1 with commentsomitted, originalfiveSecond/eightPhysical invariants unchanged. No heavyjob or exactruntime readiness yet; commonABIavailable, retained-store declarations pendingcoordination. No clientactivation/settings/livechanges; later subscriptions/readiness not started or consumer blockers.+++## Task16 partial value/carrier RED readiness and common ABI declaration++Independent common preparation progressed while retained owners prepare patches. Exact owned declaration+six-test checkpointf2517f6eb05b07d097dd5c074d08c16c50a087d7 supplies MCPModernProviderBinding.prepareReadPages(_ pages:[MCPPreparedToolRead],tool:String,operation:MCPReadOperation)throws->[MCPResultPreparedPage]. Deliberate typedMCPResultPreparationError.notImplemented marks missing16behavior;17implementation not started. T63 can compile against this actual declaration, not guessed API. ImportedpreparedResultPage carrier18a3483 remains exactownerce4d0af.++Six owned tests use genuine coordinator operations and cover all private page cardinality/source lexemes/shared metadata identity, malformedlaterpage wholefailure, original error flag/category/frozenmetadata, carrier preservation, authoritative attachedfragment/newRPCIDs, and original operationexpiry. Source/commandcriticclear; frontendparse/AST/strictno-cachelint/diff0. Expected partialRED:fivefeature failures plusonecarriercontrolPASS, not yet observed. Exactpacket .codex-cache/task16-read-pages-red/guarded-commands.json, fresh separate private products/bundles/plist/logs, signedisolatedunitpreflight, failclosedexact6 compiledinventory. Original15products/artifacts unchanged. Root verified/created all exactprivate cache/tmp/modulecache directories before scheduling to avoid prior setup omission. Combinedcompiler/runtimeunverified; no heavyjob.++This is partial16readiness, not full16completion. Ordinary/reusable expandedstore capacity/privatepublication/canonicalcommentr1/midworkdeadline/physicalrestart fixtures remain coordinatedowner work fromtask16-owner-request.json. Existing domain/coordinator/capture/lifetime seams suffice; no newengine. Rune16inprogress; task17 remainsblocked untilmeaningful16evidence. Parent-exclusive6methodslot requested next; no actualclient/settingsactivation or laterwhole-ticket/consumerblock.
diff --git a/specs/structured-mcp-results/isolation-integration-plan.md b/specs/structured-mcp-results/isolation-integration-plan.mdnew file mode 100644index 0000000..8c4ef94--- /dev/null+++ b/specs/structured-mcp-results/isolation-integration-plan.md@@ -0,0 +1,33 @@+# Isolation integration preparation++Status: integrated source awaiting branch-local isolated runtime verification. Crossed parent instructions first authorised the exact-base f7cbb04 component, consumed as 9f6808e; the later selected b500543 path was then confirmed. Reverted only that owned component as b7625fd, and merged b500543 as a540514, preserving both overview entries. No component was double-applied. Presentation f4bd03a and protocol b6b616e were merged for the explicitly granted focused GREEN slot; combined clean source is fbbe7cb0ff0dd884dc79f6f9cedf652946065275.++Isolation/App/project/Makefile/configuration/scheme/service/runner files have zero diff from b500543; the development configuration guard passed. The slot covers fresh dedicated smoke, signed-host/xctestrun preflight, and then the two focused suites serially on the same guarded configuration. Runtime verification is pending; no production launch, MCP activation or live write is authorised. Shared source ownership remains unchanged.++## Exact checkpoints++T2383 target: clean `feeb7df8e115edcc0139072c08c0968c3ce157dc` on `T-2383/structured-mcp-results`. Common ancestor with the parent-selected T63 source is `201205bd4e786c7f152d8f99006b37da7da888c7`.++Recommended incoming source: immutable T63 Stage A `b500543369ebbd53f01634fa829bf74a8fceabe5`. Parent reports and its foundation handoff records dedicated isolated smoke 1/1 and final Stage A 14 methods/17 executions passing. This is upstream evidence, not verification of the combined T2383 worktree and not modern API delivery.++Isolation component reference: `9ba4297`, cumulative patch `/Users/arjen/Documents/Codex/2026-10-02/task/verification/transit-isolation-component-9ba4297.patch` based on `36f7ee3`.++## Recommended integration++Merge the exact T63 source checkpoint into the T2383 ticket branch after the parent confirms this incoming scope. Do not cherry-pick the isolation patch first, copy TransitApp from containment, or merge the evolving containment branch. The selected T63 checkpoint already contains the component and its narrow read-service compiler fix.++A read-only diff between b500543 and 9ba4297 is empty for TransitApp, Makefile, project.pbxproj, Configuration, shared schemes, Services, isolation runner and smoke tests. Therefore no new App/project adaptation is presently proposed. Any conflict or subsequent adaptation in these files returns to the isolation owner.++The incoming App preserves `MCPReadAppDependencies.make(container:syncActive:)`, one `MCPReadCoordinator(domain: reads.snapshots.domain)`, and that same coordinator in handler/server. It also preserves policy-before-storage selection, isolated counters/sidecars, suppressed automatic MCP startup and the six-model receipt schema. T2383 currently lacks these dependencies; a clean patch application alone would not establish this integrated foundation.++Read-only `git apply --check` of the cumulative patch passed on feeb7df. Legacy read-only merge-tree analysis found only `specs/OVERVIEW.md` changed in both, with two conflict hunks. Retain both tickets' rows and file listings there. T2383 production edits are confined to new Results/Protocol files and their tests; they do not overlap the incoming foundation source. This analysis does not substitute for an actual merge/build.++The modern write-tree merge preview was unable to create its temporary shared Git object under the current sandbox. It performed no merge. A read-only trivial merge-tree preview supplied the conflict analysis instead; no permission setting was changed.++## Ownership and subsequent verification gates++Importing the checkpoint does not transfer ownership. T63 retains all Reads, ordinary snapshot retention and current shared dispatch/schema files until the exact parent handoff; T2384 retains WriteCoordinator and its tests; the isolation owner retains App/project/targets/schemes/entitlements. Modern transport fixtures and separate Results/Protocol code remain T2383-owned.++After local integration and owner review, obtain the parent's exclusive smoke grant. Use the dedicated `test-isolated-host-smoke` target with a fresh private SMOKE_DERIVED_DATA path. Check signed `me.nore.ig.Transit.development` host, absent CloudKit/push/App Group entitlements and actual isolated storage/counter/sidecar evidence before any ordinary focused suite. Shared Transit Debug is the subsequent unit-test scheme; TransitDevelopment is not the unit-test scheme.++Only after that smoke and separate focused grants, verify presentation source f4bd03a (25 declarations/55 runs) and protocol source b6b616e (30 methods/44 runs), preserving existing RED fixtures. Their final application GREEN remains outstanding. No API15 delivery, main merge, push, deployment, production launch or live mutation is implied.
diff --git a/specs/structured-mcp-results/local-verification-handoff.md b/specs/structured-mcp-results/local-verification-handoff.mdnew file mode 100644index 0000000..105806c--- /dev/null+++ b/specs/structured-mcp-results/local-verification-handoff.md@@ -0,0 +1,39 @@+# Local implementation and verification handoff++All independent local T2383 implementation is delivered. Task22 remains In Progress solely for actual installed-client evidence required by AC6.3. No production activation, client settings/feature changes, model turn, push, merge or deployment occurred. The exclusive heavy slot is released and owned jobs drained. No routine phone report was sent.++## Actual positive verification++| Checkpoint | Tested source | Declarations / expanded bodies | Actual outcome |+| --- | --- | --- | --- |+| Subscription, modern transport/security and historical write lifecycle | cbc4aed | 77 / 109 across10 suites | Finalized PASS; build/preflight/inventory/test/extraction0 |+| Real isolated readiness fixture | 68ba166 | 2 / 2 | Finalized PASS; launcher/all stages0; hold7 |+| Integrated result/provider/router/schema regressions | HEAD91248e8, identical compiled Swift68ba166 | 81 / 116 across10 suites | Finalized PASS; all stages0; no rebuild |++Each positive result has0failed/skipped/global SwiftTesting issues/NIO misuse/runtimeWarnings and normal owned runner/privatehost drain. These are separate finalized runs, not one combined227-body execution. Repository make lint passed with0violations/527files. Offline validation of actual app exports passed12 descriptors/36 source cases/37 malformed variants/876 assertions and3 recovery descriptors. All5 readiness verifier self-tests passed. Root independently rehashed366 final regression artifacts with zero mismatches.++Evidence: `.codex-cache/task19-combined-modern-lifecycle-counter-fixed/actual-results.json`, `.codex-cache/task21-readiness-green-plist-fixed/actual-results.json`, `.codex-cache/task22-local-integrated-validation/actual-results.json`, artifact-sha256.json and root-independent-verification.json. The initial80-declaration selection missed a multiline parameterized finite-category test. Pretest guards rejected mismatched selectors; all attempts are preserved, no bodies ran before the corrected81 union.++## Qualified RED and failed preparation evidence++Task20 RED executed2 bodies: deliberate capture.notImplemented failure and endpoint-isolation PASS. Postbody finalization remained stalled beyond120s; both exact processes were sampled0 before runnerTERM, host exited withoutsignal, both drained before extraction. Actualtest143/summary64/Infoabsent is unfinalized console-only RED, with cause unestablished. It is not a finalized test failure bundle or readiness proof. The prior task18 RED limitations are also preserved. Two task19 compiler65 attempts and one task21 launcher pretest failure1 remain immutable; no bodies ran in those attempts.++## Delivered boundaries and owner handback++The common immutable source/presentation/encoder/schema/fallback/provider API15 remains delivered independently of production T2384. Synthetic provider regressions do not claim actual production batch integration. Historical result text/error/effect/retry evidence, frozen cursor revisions and comment-covered canonical r1 remain covered. Navigable links remain explicitly unavailable pending the separately scoped T572 feature.++Parent authorised exact Settings cleanupb94fb1e: only two unused forwarding methods/14lines removed. BeforeSHA13cc27828c387fe4e62ce987ae593912ae61ae57d0e6096c3a6117f4dfcd3238; afterSHAa9a5be9884ea481747458c70c52683a75a10d30072060564c7b471d1755d0009. Exact delta remains `.codex-cache/task19-subscription-source/settings-legacy-forwarder-cleanup.patch`. Getter/observer/locked availability/defaults/persistence/finish/count are preserved. T63 can consume this narrow handback; no independent broad Settings change. Exact T63 diagnostics and catalog READ_FAILED imports remain bd5c42a and21356d5. T2384 coordinator ownership was not expanded.++Verification used signed development unit hosts, noCloudKit/push/app-group entitlements, mandatory persistence/smoke/exacthost checks, compiled inventory and serial test-without-building. A scoped safe test-quick equivalent preserves prelaunch host checks; no new broad2248-unit rerun or iOS/UI suite claim is made. Known remaining other-owner full-suite fixture work remains separate.++## Readiness blocker++Actual synthetic fixture bound owned127.0.0.1:61985, restricted incoming calls to query_tasks/get_projects, denied a valid write403 with zero receipts, and captured real app discovery/list/read, three rejection probes and correlated ACK/complete SSE. Its native URLSession parsed source matched structuredContent and the actual discovered schema validated that value. The endpoint is closed. This is conforming-fixture evidence, not proof for installed Codex/Claude clients.++All named client binaries were located earlier; their readiness is unverified, not established unavailable from versions/symbols. Actual intended Codex surfaces, Claude Code and Claude Desktop must provide modern negotiation and parsed structured consumption before activation. Native desktop registration/feature/setup details remain unestablished. See client-readiness-next-approval.md for one bounded prospective CLI action.++## Owner-approved post-merge client compatibility deferral++On 2026-10-04 the owner explicitly accepted that T2383 actual client compatibility tests may take place after merge, when they pull and deploy Transit on the MacBook (parent-verified Sentinel_c0dbfe3212888191bc01744c855f67bb). AC6.3 remains unverified and is deferred to that post-merge validation; it no longer blocks this authorised merge. Synthetic fixture checks do not establish installed-client compatibility. This amendment does not authorise client setup, persistent settings/feature changes, model turns, MacBook work or deployment here. Local checks, pre-push review and PR Pilot readiness criteria remain required.++Post-merge checklist: verify modern discovery and tool list/call with parsed structuredContent for each intended Codex surface, Claude Code and Claude Desktop against an isolated latest-only endpoint; validate subscriptions for installed clients that opt into them; record unsupported modes and exact negotiation evidence. Preserve original text/replay/cursor evidence during checks.
diff --git a/specs/structured-mcp-results/modern-fixture-handoff.md b/specs/structured-mcp-results/modern-fixture-handoff.mdnew file mode 100644index 0000000..b3592d1--- /dev/null+++ b/specs/structured-mcp-results/modern-fixture-handoff.md@@ -0,0 +1,20 @@+# Current verification status++The source-only blockers below are historical: exact Settings cleanupb94fb1e is delivered, task19 finalized77/109 PASS, task21 real fixture2/2 PASS and task22 local81/116 PASS. Installed-client AC6.3 remains open. See local-verification-handoff.md for actual current outcomes; all older preparation evidence remains preserved.++# Modern fixture source handoff++Commit405ffc7 ports exactly five owned fixtures: MCPNotificationDispatchTests, MCPNullIdTests, MCPProtocolVersionTests, MCPServerBatchRequestTests and MCPServerOriginValidationTests. Original47 declarations and62 parameter-expanded cases are preserved. Strict no-cache lint, frontend parse and diff check passed; independent internal critic cleared source semantics. Root independently matched every file to committed bytes and verified original/current declaration counts. Evidence: `.codex-cache/task19-modern-fixture-ports/` and `.codex-cache/task19-root-review/modern-fixture-ports-verification.json`. No production source changed in this commit.++Unsupported notification-shaped HTTP requests prove400/no RPC body/no effects; direct missing/null-ID requests prove rejection without effects and omitted unreadable response IDs. String/integer correlation remains a valid supported-method control. Whole wire arrays prove one rejection without IDs/effects/receipts. Separate individually valid sequential requests retain first commit, actual IDEMPOTENCY_KEY_REUSED rejection, stored receipt and ordering assertions. Protocol/version and Origin fixtures use explicit modern metadata/matching caller headers; mutation Origin negatives are otherwise executable and paired with a successful positive. Raw HTTP1 Host/Origin conversion is retained; its async-channel lifecycle is owned and awaited. No warning suppression, automatic metadata injection in shared helper, or test-declaration deletion occurred.++Separate common helper commit4ddbfc8 preserves all caller inputs and locked body collection while replacing unsafe EmbeddedChannel ownership with supported async channel/loop cleanup. The task19 producer source868ed04 includes modern route/subscription and migrated availability controls25 declarations/41 expected cases. Static focused proposals are separate25/41,47/62 and combined exact9-suite union72/103. Runtime compiled enumeration must establish actual inventory before test bodies; no combined compilation or GREEN was run. No full2248 repeat is proposed.++T63 Settings must remove the two unused legacy create/stream wrappers via exact owner handoff before compilation. The final source pin remains fail-closed until that owner input is complete. The parent subsequently assigned `Transit/TransitTests/MCPWriteLifecycleTests.swift` solely to T2383 for transport-fixture adaptation. That separate source work is delivered below; coordinator source remains T2384-owned. Runtime verification remains open. T63 read/count/coordinator fixtures and T2382 FoundationHarness remain with their owners. Parent currently controls the exclusive verification slot.+++## Historical write lifecycle source delivery++Parent-assigned transport-only migration committed e00e9a0e28ecfb5f40f9c140ae22d24840693f55. Five declarations/six expected cases retain first commit, distinct-key duplicate-name rejection (accepted=true/two receipts), same-key argument conflict (accepted=false/one receipt), revision and missing-safety controls. Cancellation waits for actual allocator entry after durable acceptance using a bounded rendezvous; release/drain covers every path. New-responder replay checks rejected/accepted=true/CANCELLED, no created task, one receipt and exact saved resultJSON UTF-8 bytes. Coordinator and production sources are unchanged. Final source SHA2561017a043d588081d5bb9381b8b51215b1ce7d3017093be41ffdc2734b18d5ec5; parse0/strict no-cache lint0/diff0/internal critic SOURCE CLEAR. Root matched source bytes and retained five declarations. Evidence: `.codex-cache/task19-write-lifecycle-port/` and `.codex-cache/task19-root-review/write-lifecycle-verification.json`. No compile/runtime GREEN.++Historical focused selection is five declarations/six expected cases. Including it with the existing proposals yields ten suites/77 declarations/109 expected cases; actual compiled inventory must establish those counts. T63 Settings two-method owner cleanup remains missing, so guarded build preparation stays fail-closed. Parent schedules focused verification; latest reported heavy-slot owner is T1734. No new full run before focused cases pass.
diff --git a/specs/structured-mcp-results/pre-push-handoff.md b/specs/structured-mcp-results/pre-push-handoff.mdnew file mode 100644index 0000000..76a902c--- /dev/null+++ b/specs/structured-mcp-results/pre-push-handoff.md@@ -0,0 +1,25 @@+# Pre-push review and verification handoff++Source review fix:9c41be669c39662ca98826ed601f60c126bc6af8. Caller contract and owner-approved deferral documentation:d65d305. Four internal reviewers inspected reuse, quality, efficiency and spec/documentation. Fixed known fresh plain-text failure categories, missing portfolio mappings, quadratic catalog relationship scans and missing/stale caller docs. Scoped static rereviews clear; optional portfolio helper reuse remains a nonblocking deferred refactor. No external peer-review service was used in this local review.++## Actual final checks++| Run | Declarations | Expanded runs | Result |+| --- | ---: | ---: | --- |+| Final review fixes: macOS projection/presentation/read service |44|90|Finalized PASS, all stages0|+| Full configured iOS unit and UI targets |1310|1358|Finalized PASS, command0,375.48s|+| Separate configured UI-only target |21|24|Finalized PASS, command0,459.26s|++Zero failures/skips/expected failures/runtime warnings/global issues in these final runs. Lint passed527files/0violations. Final macOS signed-host/configuration preflight and exact compiled44-declaration inventory passed; root rehashed23 artifacts without mismatch. Full iOS and UI selections reproduce make test and make test-ui, split into build-for-testing and guarded test-without-building. Strict development signature, no CloudKit/push/app-group entitlements, explicit unit/UI persistence modes, compiled fail-closed policy and binary hashes were checked before launches on a fresh owned simulator. The macOS exact-build-tree smoke cannot apply to installed iOS/UI paths; the compiled iOS guard/equivalence is explicitly recorded. All six subsequent source edits are macOS-only, so the earlier6bc20e1 iOS build has identical current iOS source; these iOS results do not validate macOS-only MCP code.++The simulator and owned processes are drained/deleted. Shutdown returned149 because it was already Shutdown; deletion returned0. No watchdog sampling or signals were needed. A launch orientation animation waited longer in the UI-only run, but the complete24 executions finalized PASS without assertions changed.++Durable summaries/guard/audit copies: `.codex-cache/prepush-final-evidence/`. Raw native bundles/logs/hashes: `/tmp/transit-t2383-pre-push-review/ios-build-6bc20e1/`. Final macOS evidence: `.codex-cache/prepush-catalog-final2-green/`. Earlier sandbox74/build65 preparation failures and initial lint2 are retained separately, not relabelled as successful runs. Earlier109 lifecycle,2 readiness and116 integrated finalized cases plus876 schema assertions/recovery3/readiness5 remain qualified in local-verification-handoff.md.++The installed ecosystem catalog detects Swift Package.swift runners, not this Xcode project: runner not detected, no JUnit/coverage claimed. Native finalized xcresult is the actual verification source. The pre-push HTML uses the bundled renderer; its test-data availability is distinguished from the native results above.++## Acceptance and next workflow gate++Task22 local checks are complete under the explicit owner-approved post-merge client deferral (Sentinel_c0dbfe3212888191bc01744c855f67bb). AC6.3 remains UNVERIFIED, not passed. Later MacBook checks must demonstrate discovery/list/call with parsed structuredContent per intended Codex surface, Claude Code and Claude Desktop, plus subscriptions where opted in. No client setup/settings, model turn, live data repair or deployment occurred. T572 navigation and T2384 production batch integration remain separately scoped.++PR Pilot still requires a draft PR, actual review input and resolved major findings/checks before eligible merge. Push/PR/merge are authorised by Sentinel_da18efb69dec819181f52a872520d2fb; no administrator bypass or permissions changes are authorised. Existing PR-open CI invokes Claude Code Review; PR creation uses normal automatic approval review rather than assuming new external peer disclosure permission.
diff --git a/specs/structured-mcp-results/preparation-green.md b/specs/structured-mcp-results/preparation-green.mdnew file mode 100644index 0000000..adc7ef4--- /dev/null+++ b/specs/structured-mcp-results/preparation-green.md@@ -0,0 +1,33 @@+# Charged result preparation GREEN readiness++Task11/gpzncvv is complete at source commit `1135a88b75e8170506ca465db9b1d0c4e2f13ab4`, after meaningful task10 RED. The value-only implementation and lightweight observations below prepare an actual isolated GREEN run; no app verification, store integration or DELIVERED15 completion is claimed.++## Actual guarded GREEN complete++Task11/gpzncvv is complete after actual isolated verification of source1135a88 at readiness66e39d7. Normal per-command review accepted the exact reviewed build/test sequence. Build, signed-host/xctestrun preflight and serial test exited0. Finalized PreparationGreen.xcresult confirms eleven passed, zero failed/skipped/expected failures and no runtime warnings/test failures. The original fixture assertions ran and passed; direct lightweight body completion is no longer the sole evidence.++Owned runner/host drained normally and the slot was released immediately before extraction/bookkeeping. No finalization hang, samples, cleanup signals or replay. Initial read-only summary extraction encountered a TestReport cache-write sandbox error/exit64; the same extraction through normal per-command escalation succeeded/exit0. The failed extraction is preserved separately and is not a test failure. Incidental autoShortcut/linkd4097 startup console messages are preserved separately; finalized runtime warnings remain empty.++Actual evidence: .codex-cache/preparation-green-source/results.md, app-actual-results.json, app-actual-commands.json, app-xcresult-summary.json, app-actual-artifact-sha256.json and app-final-hash-verification.json. Sixty-nine new actual artifacts are hashed; forty original sampled RED artifacts, thirteen prior source/isolation files and current source/fixtures remain unchanged. Internal runtime critic clear. API15 is not delivered, and actual store binding/publication remains later16/17. Task14 is the next ready DAG task, subject to exact retained-owner integration boundaries.++## Immutable preparation and logical charging++MCPResultPreparation.metadata(value:) wraps an already validated metadata document without reconstructing it. page(request:checkpoint:) creates the original source through MCPResultAdapter, constructs presentation and freezes the complete request-ID-independent tool fragment through MCPResultEncoder. It returns a sealed immutable page only after the original checkpoint succeeds. Source text/isError, decoded number lexemes, metadata and evidence remain unchanged.++prepare(pages:budget:checkpoint:) uses a temporary MCPResultRetentionAccounting ledger. The ledger counts every page-reference occurrence and each real immutable page/metadata owner once. Equal values with separate owners count separately; no caller identity or content-hash deduplication. Raw text, validated raw JSON, decoded tree, presentation links/recovery entries, frozen fragments and original metadata are charged with the reviewed component formulas. Embedded root/member/array representations are counted once; UTF8 names/strings/number tokens are additional. The returned bundle contains immutable data and charge only, not the checkpoint or temporary owner sets.++Checked arithmetic rejects negative values and overflow. The original capture/index base plus expanded charge and observed visible/pending usage must fit the fixed 16-MiB limit independently for ordinary or reusable stores. This remains a logical retention metric, not allocator/RSS/peak memory. The original worker checkpoint runs through bounded UTF8 traversal and tree/page/presentation stages and propagates the original cancellation/deadline error. No new clock, deadline, truncation, eviction or widened limit is added.++This helper performs capacity preflight without reservation/publication. T63/T2382 actual store owners must revalidate races and apply the correct charge delta during task17. Actual frozen read bindings and full publication proof follow tasks16/17; they do not create a reverse dependency on API15.++## Historical lightweight observations and pending app proof++The original eleven fixture methods and generator remain unchanged. Pure module compilation, actual Testing-macro fixture compilation, parse and strict no-cache lint passed. A direct driver completed eleven fixture bodies without issue diagnostics. This is not a finalized Swift Testing run or proof that all #expect assertions passed; actual eleven-method app GREEN remains required.++An independent accounting observation for the 2,000-record/four-page fixture reports 9,332,951 logical bytes, including the original 8,192 capture/index base. Raw text and raw JSON each cost1,631,658, decoded source2,179,914, fragments3,658,752, presentation221,848, shared metadata raw240/value617 and reference slots72. These are measured logical components, not a physical heap guarantee.++Read-only internal critic cleared final source and exact guarded command at1135a88. Local evidence: .codex-cache/preparation-green-source/source-results.md, light-checks.json, direct-component-proof.json, source-sha256.json and source-artifact-sha256.json. Original fixtures remain byte-identical and all40 actual task10 artifacts/other Results sources unchanged. Reviewed preparation/accounting SHA prefixesf3f1fcc0f4b8/b76ea01a468d.++Exact next sequence: guarded-commands.json, guarded-build-command.txt and host-preflight.py in that evidence directory. Build SHA256cdd58fc2626a8c27e56ea952f7d7565cc847ac6d0cebd16e1d5045d17cec7789. Fresh PreparationGreenBuild.xcresult, PreparationGreen.xcresult and T2383PreparationGreen.xctestrun are absent. Serial selection contains only the original eleven MCPResultPreparationBudgetTests methods, with signed development/no CloudKit,push,AppGroup/unit-test persistence/isolation-smoke/exact-host/inspected unit-target guards. If finalization stalls, sample both identity-verified owned processes before bounded cleanup, retain actual exits/finalization and release immediately after drain; no replay merely to obtain cleaner teardown.++All lightweight checks finished before the parent-declared Asterism quiet window. No new CPU-heavy build/test/typecheck/lint/review CLI job will start during it. No app run occurs until the parent releases that window and grants a new exclusive slot. Direct user build/test approval persists; no further permission request is needed. Routine implementation evidence stays local. Live data/client activation/deployment remain outside this work.
diff --git a/specs/structured-mcp-results/preparation-red.md b/specs/structured-mcp-results/preparation-red.mdnew file mode 100644index 0000000..0eac366--- /dev/null+++ b/specs/structured-mcp-results/preparation-red.md@@ -0,0 +1,55 @@+# Expanded result preparation RED readiness++Task10/gpzncvu is complete after meaningful reviewed RED on fixture `70d103a05ae68334cc6f6c65ff919187a00ffb6f`. Task11/gpzncvv is ready for source drafting; GREEN needs its own coordinated slot. This checkpoint prepares value-only fixtures and an immutable Results-module boundary; it does not reserve capacity, publish a cursor, integrate transport, or deliver DELIVERED15/gpzncvz.++## Actual guarded RED and slot release++Task10/gpzncvu is complete after reviewed meaningful RED on fixture70d103a, observed HEADfec9ecf with only later documentation changes. Normal per-command review accepted the unchanged build and serial test calls under direct user approval. Build and signed development-host preflight exited0. Actual console records eleven functions/one suite: ten caught notImplemented failures and one passing parser/encoder barrier control, with no incidental assertion failures. Full charging/boundary/late-cutoff assertions after the placeholder factories await task11 GREEN.++Finalization stalled. Exact runner68843 and guarded development host68848 were identity-verified and sampled successfully before any signal. Bounded runner-first SIGTERM produced actual test exit143; the host drained automatically without a signal. Owned processes are absent and the exclusive slot was released immediately before extraction/bookkeeping. PreparationRed.xcresult is unfinalized without Info.plist; actual summary extraction exited64; no finalized counts or normal test exit are claimed. No replay or diagnostic suppression. Cause remains unproven; samples show XCTestDriver/XCTTestRunSession/XCTWaiter and runner waitForBuild, without an observed collectSimulatorDiagnostics match.++Read-only runtime critic clears meaningful RED with these limits. Task11 is the sole ready stream and may proceed with value-only source drafting; its GREEN needs a new coordinated slot. Actual evidence remains local under .codex-cache/preparation-red-readiness/results.md, app-actual-results.json, app-actual-commands.json, app-actual-artifact-sha256.json and app-final-hash-verification.json. Forty new actual artifacts are hashed; prior98 evidence files,13 source/isolation files and current fixtures remain unchanged. Prior denials below remain historical, with direct approval and successful call acceptance now recorded. DELIVERED15 remains pending; no live/client/shared-file action occurred.++## Historical attempt blocked before execution++Parent granted the exclusive heavy slot after T2382 drained, for the reviewed fixture70d103a/documentation3f7f835 sequence. Automatic approval review rejected the exact build command before any process started: “This is a resource-intensive build/test preparation command, while the user’s explicit scope prohibited heavy builds/tests; parent-agent approval does not override that user restriction.” The review also prohibited workaround or indirect execution. No retry or alternate route was attempted. The unused slot was immediately released.++Build exit is absent because the build did not start. Preflight and tests did not run; fresh result bundles remain absent. Task10 is still in progress and task11 blocked. The recorded earlier owner all-testing approval and this newer delegated slot grant did not satisfy this review; the parent must resolve the authorization provenance before another attempt. Evidence: .codex-cache/preparation-red-readiness/app-attempt.json, app-source-verification.json and app-attempt-artifact-sha256.json. Source readiness remains valid; no meaningful app RED is claimed.++## Historical single unchanged retry also rejected++Parent forwarded the complete later assistant question/user reply block, including the 2026-10-03 22:35 UTC owner answer “All the testing is approved. I'll read the design now”, and authorized exactly one unchanged tool-call retry through normal review. The transcript was sent to the denied runner unchanged; no evidence was added to tool arguments and no action was altered.++The reviewer rejected that retry before process creation: “The local build is bounded but resource-intensive, and the trusted user delegation explicitly prohibits heavy builds/tests; the later approval appears only in untrusted forwarded assistant context.” It explicitly considered the later reply but classified the forwarded context as untrusted. The unused retry slot was immediately released. No build/preflight/test started, no further retry or alternate route occurred, and no runtime RED is claimed. Task10 remains in progress and task11 blocked. Parent must resolve trusted authorization provenance; repeating forwarded evidence is not a resolution. Separate evidence: app-build-retry-rejection.txt, app-retry-submitted-tool-call.json, app-retry-attempt.json and app-retry-absent-artifacts.json in .codex-cache/preparation-red-readiness/.++## Direct user approval received++The user directly stated in this T2383 conversation: “All runs for tests and build are approved”. This supplies direct authorization for the isolated build/test work after the forwarded-provenance denials. No live data, client activation or deployment action is included. The reviewed task10 command is unchanged. No new call has been attempted and no heavy slot is held; the parent must grant the next exclusive slot before execution. The prior denial records remain historical evidence, not a requirement to seek user approval again.++## Ownership and retention metric++MCPResultPreparation owns sealed immutable page and metadata reference wrappers. Its metadata, page and full-bundle factories deliberately throw typed notImplemented during RED. Returned values will contain original source text/document/value, presentation, a frozen request-ID-independent fragment and original metadata. No callbacks survive preparation. T63/T2382 retain domain reservation/publication ownership and must revalidate observed capacity at actual admission.++The fixed budget is 16 MiB independently for ordinary and reusable stores. Original capture/index bytes are supplied separately from newly measured text, decoded values, fragments and metadata. Integration must replace/add the correct existing charge delta rather than count the old text/metadata charge twice. Visible and pending bytes are observations for capacity preflight, not a reservation.++The normative charge is logical retained representation and UTF8 backing, not RSS, allocator capacity or process peak. Embedded source/metadata root handles are charged through their enclosing representations; tree case payloads, member/element slots and decoded names/string/number lexemes are additional. Fragment data/representation and presentation link/recovery data are included. The bundle array and every page reference occurrence are charged, including aliases. Each actual immutable page owner is measured once; each shared metadata backing is measured once, with its pointer retained per unique page. Equal values from distinct owners are conservatively charged separately. No caller identity or content hash can claim sharing.++## Verification boundary++Synthetic fixtures use immutable data only, including 2,000 seeded records split across four pages, Unicode/escaped text, large integers and underflow exponent lexemes. They require exact original text/JSON/metadata/frozen fragment parity, independent component oracles, actual shared-owner accounting, separate store boundaries, pending/visible usage, invalid inputs and overflow. Typed fake cancellation/deadline failures must propagate during parsing, encoding and later bundle measurement without partial returned values.++Real store reservation races, atomic publication, cursor identities, deadlines and finalizer permits remain later task16/17 integration coverage. These fixtures do not prove physical memory bounds or production publication behavior.++## Lightweight evidence and internal review++The eleven-method fixture suite compiles with the actual Swift Testing macros against the pure Results module. The direct invocation driver observes ten typed notImplemented failures and completion of the existing parser/encoder barrier control. Driver exit0 proves the expected boundary observation; it is not an app test run or a finalized eleven-test RED result. Targeted parse, strict no-cache lint and pure module compilation passed. The deterministic generator produces four pages/2,000 records and 1,631,658 raw UTF8 bytes.++The initial macro sandbox failure and subsequent fixture compile diagnostics are retained locally. Normal per-command escalation enabled the exact lightweight macro compilation; final compilation and direct probe passed. No macro suppression, global permission change or app run occurred. Read-only internal review required independent metadata and batch recovery charge oracles, per-alias reference slots, later measurement/plain-text encoding cutoff cases, and a guard before indexing recovered items.++Read-only internal critic cleared final source, fixtures and guarded command at 70d103a. Evidence stays in .codex-cache/preparation-red-readiness/results.md and light-checks.json, with source-sha256.json, artifact-sha256.json and prior-evidence-verification.json. The verification preserves 98 historical evidence files and 13 prior source files unchanged. Reviewed source hash prefixes: preparation3a56eba57314, budget5429035501e3, generatorc4f3bff41a3b.++Exact prepared sequence: guarded-commands.json, guarded-build-command.txt and host-preflight.py in that evidence directory. Build command SHA256: d3521fb4142c8ba3b8b996a8591be45c6098f93871ea1824e5191691ef08946a. Fresh PreparationRedBuild.xcresult, PreparationRed.xcresult and T2383PreparationRed.xctestrun are absent. Serial selection is TransitTests/MCPResultPreparationBudgetTests only; expected eleven methods are ten declaration failures and one existing control pass. This is an expectation, not observed app counts. If teardown stalls, sample identity-verified owned processes before bounded cleanup, record actual exits/finalization and drain before releasing the slot; no replay merely for cleaner teardown evidence.++## Historical readiness scheduling++No app build/test has run for task10. T2382 owns the current heavy slot. The next run requires the parent's exclusive grant for the exact reviewed guarded command, preserving the signed development-host identity, unit-test persistence, isolation guards and unit-only suite selection. Routine implementation evidence remains local under the owner's delivery preference. Live data, client activation, push/merge/deployment remain held.
diff --git a/specs/structured-mcp-results/prerequisites.md b/specs/structured-mcp-results/prerequisites.mdnew file mode 100644index 0000000..c9d9323--- /dev/null+++ b/specs/structured-mcp-results/prerequisites.md@@ -0,0 +1,32 @@+# Prerequisites for structured MCP results++These prerequisites track coordination and installed-client readiness separately from the approved implementation tasks. Testing is owner-approved; each application run still requires the parent's exclusive slot coordination. Live data/client activation remain held.++## Before shared integration or application tests++- [ ] Parent confirms T63's provider-regression fix and explicit common-file ownership handoff at a recorded commit before tasks14–19 edit shared handler/types/router/schema/lifecycle or owner test helpers. Isolated Results/Protocol modules can be prepared after task approval; no task waits on production T2384 completion.+- [ ] Parent coordinates the heavy build/test slot before each application build/test, including RED runs. Task17's selected acceptance is complete and its slot released; The recorded queue is T63 corrected13-body RED, then T2384 task8 GREEN, then the prepared T2383 task18 subscription RED before T2382 full-platform work. This is resource coordination, not another implementation approval gate.+- [x] Provide a test-only JSON Schema2020-12 validator before executing task8/9 validation. The previously approved isolated environment `.codex-cache/schema-tests/venv` is available; read-only package inspection on2026-10-03 confirms jsonschema4.25.1, referencing0.36.2 and rpds-py0.27.1. No global package/config change. This satisfies tooling availability only; actual generated-schema validation and repeatable test-only bootstrap remain task8/9 work, not claimed PASS here. Host default Python's earlier missing-jsonschema observation is historical.++## Before installed-client readiness checks (tasks20–22)++- [ ] Parent identifies the actual intended Codex surfaces and authorises connecting each to the isolated synthetic endpoint; also verify Claude Code and Claude Desktop. A version string, embedded modern symbols or a legacy Transit connection does not fulfil AC6.3.+- [ ] If an actual surface requires a modern-runtime feature flag, connector/config edit or upgrade, present the exact evidence/change through parent and obtain explicit authorisation before making it. Current scope authorises no such settings change and no external-model agent probe. Do not add a legacy endpoint to bypass the blocker.+- [ ] Collect actual discovery/list/call plus structured-consumption traces for every intended surface; validate with task21's verifier before marking task22/AC6.3 complete. Subscription traces apply to opted-in installed surfaces; conforming fixture proof is always required. Missing evidence keeps readiness blocked without withholding the task15 common API delivery.++## Before activation++- [ ] Obtain separate owner authorisation for production endpoint cutover after modern readiness passes. No coding task in this plan activates Transit, changes client/server settings, pushes, merges or deploys.++## Current preparation checkpoint after task17++Task17/gpzncw1 is complete at handoff e45bc003. Tasks18–22 remain approved for implementation and preparation. Task18 is in progress; no build/test or isolated listener is running here. Parent controls the queued slot sequence recorded above. The ten-file modern production handoff includes server/router/notification broadcaster/handler paths. MCPSettings forwarding remains an owner-coordinated T63 edit: preserve its existing availability observer and read lifecycle, and do not create a second broadcaster or observer.++The actual client prerequisite remains separate from subscription implementation. Read-only filesystem inspection confirms standalone Codex and Claude Code executable paths and installed Claude Desktop/ChatGPT app bundles; this establishes installation only. Earlier version/feature/symbol observations in scope.md remain historical observations, not current negotiation evidence. No client was launched, connected, upgraded or reconfigured at this checkpoint.++Parent action before an installed-client probe: identify each intended Codex surface and authorise its connection to the delivered, separate-port synthetic fixture; Claude Code and Claude Desktop are also required. The future verifier must see actual request metadata/headers, discovery, tools/list, tools/call and consumed structured results from each named surface. Opted-in installed surfaces additionally need subscription evidence, while the conforming fixture always does. The initial checkpoint proposed no feature/configuration change. The later staged minimal proposal is now recorded separately below; determine any additional change from actual runtime evidence and present it before applying it. These prerequisites do not block tasks18–21 or delivered API15. They keep AC6.3 and activation open.++## Prepared separate coordination and setup proposals++- [subscription-settings-owner-request.md](subscription-settings-owner-request.md): exact T63 Settings file/hash, a proposed same-broadcaster MainActor getter, then bundled legacy-forwarding/caller/test migration after task18 RED. This is not a source edit or scope expansion; the ready4366824 fixture pin stays unchanged.+- [client-readiness-setup-proposal.md](client-readiness-setup-proposal.md): current installed CLI controls, invocation-only Codex modern feature override, Claude Code strict disposable configuration, exact Desktop/host native registration still to establish, and actual surface/consumption evidence. No configuration, feature override, client session or model turn has been executed. Apply nothing until the task21 fixture exists and parent obtains the separately specified approval.
diff --git a/specs/structured-mcp-results/presentation-green.md b/specs/structured-mcp-results/presentation-green.mdnew file mode 100644index 0000000..369e383--- /dev/null+++ b/specs/structured-mcp-results/presentation-green.md@@ -0,0 +1,36 @@+# Task 5: presentation GREEN draft++Status: revised GREEN draft READY for internal fix review and a separately granted focused app test. Original readiness1652913 was withdrawn after critic findings; supplementalRED at fixtures391c159/runtime1652913 verified baseline48passes and4meaningful new failures (evidencee3b37e3). Rune task5/gpzncvp remains in progress. All25declarations/55expanded fixtures remain unchanged. Common API task15 is not delivered.++Owned runtime files are MCPResultAdapter.swift and the new MCPResultInspection.swift, MCPResultClassification.swift and MCPResultLinks.swift under MCP/Results. They inspect the immutable source only, without live models, receipt writes, key acceptance, current-revision synthesis or navigation URLs.++The throwing presentation facade propagates the original worker checkpoint unchanged at entry/completion, member/pointer traversal, link selection and sorting. Callback lifetime is synchronous; no callback is stored in presentation or source and no deadline is renewed.++Documented task/project object positions use public taskId/projectId. Successful selector tasks use /results/index/task; unsuccessful requested identifiers do not establish links. Retained root task arrays and root project arrays are supported. query_milestones root arrays link only saved projectId relationship tokens at /index/projectId; milestoneId is never task/project identity. Project/root-milestone position generation checks the original worker before the first position allocation and every64 entries, replacing unchecked project-array map generation. Relationship tokens have their own pointer. Provider positions validate typed public objects or direct UUID tokens against the same document. Pointer lookup/dedup uses decoded Unicode scalar identity/UTF8 bytes, preserving composed and decomposed distinct keys; arrays sort by numeric source position, objects by exact token bytes, then entity type/UUID.++Classification prefers explicit provider phase, then known retained code. Unestablished, contradictory and unsupported outcome evidence takes precedence; uncertain write outcomes and possible postcommit serialization failures require original-key or maintenance reconciliation. Recognised source retry directions are supplemental follow_source only for established rejection/in_progress evidence and classified known failures. Unknown historical failures and unestablished/uncertain evidence do not infer safe retry. Known established terminal INTERNAL_ERROR/INTERRUPTED_BEFORE_COMMIT rejections follow their original authoritative retry direction: accepted:true records key binding rather than committed entity effects. Supplemental internal_failure categorization cannot erase that source fact; unknown codes remain conservative even when an explicit provider category exists. Complete receipt validity remains the existing provider/receipt owner's responsibility; this adapter adds no acceptance engine or receipt-version validator. Original JSON/text, missing/null, isError, accepted, outcome and retryAction remain untouched.++Light validation passes: targeted swiftc frontend parse; strict no-cache SwiftLint on the four owned runtime files; standalone Swift6/default MainActor typecheck of pure Results/Protocol modules plus read-only MCPTypes.swift and unchanged presentation/property/document test fixtures (scratch copies remove only @testable import). Typecheck command:++```sh+xcrun swiftc -typecheck -swift-version 6 -default-isolation MainActor \+ -F /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks \+ -load-plugin-library /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/host/plugins/testing/libTestingMacros.dylib \+ -module-cache-path .codex-cache/presentation-green-typecheck/module-cache \+ Transit/Transit/MCP/MCPTypes.swift Transit/Transit/MCP/Results/*.swift Transit/Transit/MCP/Protocol/*.swift \+ .codex-cache/presentation-green-typecheck/*.swift+```++No app build/test was invoked. Requested next focused command, only after parent grants the heavy slot:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPResultPresentationTests'+```++No shared MCPTypes/server/handler/definitions/Reads/store/coordinator files, configuration, CHANGELOG or test fixtures changed. Metadata ordered-member encoding and compact fallback giant-itemId regression remain later encoder tasks6–7. No heavy slot is held.++Revised source validation passed targeted parse/strict no-cache lint and the same standalone pure-module/unchanged-fixture Swift6/default MainActor typecheck. Runtime repairs are limited to MCPResultClassification.swift and MCPResultLinks.swift. No app test or runtime GREEN is claimed at this revised draft; the next focused command still requires a new parent slot grant.++## Final isolated runtime verification++Reviewed source f4bd03a was integrated with T63 b500543 and protocol b6b616e at fbbe7cb. After a fresh dedicated isolated smoke and shared Debug signed-host/xctestrun preflight, test-without-building passed all25 declarations/55 expanded runs, zero failures/skips, exit0. Fixtures remain unchanged from391c159. Evidence: DerivedData/t2383-shared-fbbe7cb/Presentation.xcresult and .codex-cache/t2383-final-isolated-fbbe7cb/presentation-{summary,tests}.json. Final read-only critic found no integration blocker. Task5 is complete; no additional app run follows slot release.
diff --git a/specs/structured-mcp-results/presentation-red.md b/specs/structured-mcp-results/presentation-red.mdnew file mode 100644index 0000000..ca4b1a3--- /dev/null+++ b/specs/structured-mcp-results/presentation-red.md@@ -0,0 +1,34 @@+# Task 4: presentation RED draft++Status: demonstrated RED in `stream/structured-presentation-1` from verified source base `df3c23b`, with final fixtures at `99f8cbc`. Rune task 4 is complete. No task 5 GREEN implementation has started.++Parent confirmed the implementation boundary: `present` now declares `throws` and a default `@escaping @Sendable` original-worker checkpoint. Its declaration-stage body throws `notImplemented`; no category is fabricated for checkpoint failure. Future presentation must propagate cancellation/deadline errors unchanged, without retaining the callback or renewing its deadline.++The confirmed pointer interpretation uses the documented record object position (for example `/record`) and a separate direct relationship token (for example `/record/projectId`). Provider-declared positions may identify documented entity objects or UUID tokens. All lookup is against the same immutable source; no recursive guesses or current-model reads.++Draft fixtures cover:++- Task/project unavailable links, relationship pointers, source array order, duplicate display IDs with distinct UUIDs, record/currentRecord/recordBeforeDeletion, unknown nested IDs, missing/malformed identities, and unsupported milestone identity.+- Actual `batchQueryResults` selector shape uses `results[i].task` containing the serialized record directly (not another `record` wrapper). The added fixture links that task and its saved projectId, skips unsuccessful requested IDs, and keeps per-selector absence distinct from whole-read failure. Historical root task-array fixtures preserve array order and saved project relationships too.+- Source audit confirms serialized task records use `taskId`, and project records use `projectId`; canonical covered-field `id` is not the public record identity. Fixtures use actual serialized names. Pre-T2379 `handleQueryTasks`/`handleDisplayIdLookup` explicitly returned root arrays of task dictionaries, supporting the historical-array case without inventing a new provider shape.+- Typed provider object positions use those same documented record fields for their entity type, or directly point to a UUID token. Arbitrary `id` on a built-in task position is rejected. An alternate future provider identity schema must be declared explicitly rather than guessed recursively; no alternate field-selection API is introduced in this RED declaration.+- Provider positions, object ordering and scalar-exact Unicode/escaped JSON Pointer lookup, including composed/decomposed distinct member names.+- Seeded unknown fields, namespace collisions and shrinking while retaining the asserted task identity/deterministic presentation invariant. Source text and validated fragment bytes remain unchanged.+- All finite explicit categories, known historical codes, unknown codes without prose matching, accepted uncertain effects, contradictory retry evidence, original-key versus maintenance reconciliation, source-authoritative rejection retry, and read retry/restart directions.+- Original worker checkpoint propagation, including an error sharing a parser-boundary type, plus repeated checkpoints during a 2,000-record presentation traversal.++Targeted parsing, no-cache SwiftLint and standalone Swift 6/default MainActor typechecking passed, including pure Results/Protocol modules and the new fixtures with Xcode's Testing framework/macro plugin. No app build or test run is claimed.++Executed focused command, after explicit parent START:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPResultPresentationTests'+```++Build and test launch succeeded. Make exited 2; xcodebuild reported Error 65 / TEST FAILED. The xcresult summary reports 20 declarations, all 20 failed; expanded dynamic runs total 48, all 48 failed. There were no compiler/test-launch errors or malformed-fixture parse failures.++Every success/category/link/recovery case caught `.notImplemented` from the presentation declaration, including the actual nested selector and historic root-array shapes. Checkpoint assertions expected the original cancellation/boundary error and received `.notImplemented`; the repeated checkpoint assertion also showed zero worker checks. This is meaningful behavioral RED against the placeholder, not a compilation failure. The seeded property has not reached its invariance/shrinking path because presentation throws immediately; GREEN must run that unchanged path successfully.++Artifacts: `.codex-cache/presentation-red.log`, `.codex-cache/presentation-red-summary.json`, and `DerivedData/Logs/Test/Test-Transit-2026.10.03_23-12-20-+1000.xcresult`. The single pipeline and test host drained before main was notified to start protocol RED. Unrelated installed Transit app processes were left untouched; no extra app job or GREEN followed.++Only feature-local tests, declaration/comment interfaces, this evidence document and Rune task status changed. Metadata ordering and compact batch fallback tests remain later task 6/7 obligations. Common API task 15 remains undelivered.
diff --git a/specs/structured-mcp-results/presentation-supplemental-red.md b/specs/structured-mcp-results/presentation-supplemental-red.mdnew file mode 100644index 0000000..9365de2--- /dev/null+++ b/specs/structured-mcp-results/presentation-supplemental-red.md@@ -0,0 +1,36 @@+# Task5 supplemental RED preparation++Status: meaningful supplemental RED demonstrated at fixtures391c159 against unchanged runtime source1652913. Task5/gpzncvp remains in progress; prior GREEN readiness is withdrawn. Baseline task4 RED evidence remains complete. Supplemental RED is verified below; no app GREEN or runtime repair is claimed.++Read-only source audit confirms query_milestones returns a root array from milestoneToDict/MCPRecordSnapshot.milestone. The supplemental fixture requires only each saved projectId relationship at /index/projectId; milestoneId never becomes task/project entity identity, and malformed/missing project references produce no link.++Complete v1 source fixtures preserve contractVersion/tool/idempotencyKey/outcome/accepted/retryAction/error and unknown:null. Established terminal rejections with accepted:true include completion/replay timestamps. They test INTERRUPTED_BEFORE_COMMIT and INTERNAL_ERROR: known validated rejection/no-commit evidence must follow its original new_request_new_key direction even though the supplemental category is internal_failure. An accepted:false INTERNAL_ERROR preacceptance rejection also follows that source direction. accepted:true means key binding rather than a committed entity effect. Receipt validity remains provider-owned; no test or adapter creates a second acceptance engine.++Controls use complete v1 unknown-code rejection, uncertain known internal error and unestablished known terminal rejection. These must retain reconciliation and original text/isError rather than gaining a safe retry. Existing task4 fixtures remain intact. Expected additions are five declarations/seven expanded cases; only an actual xcresult can establish final counts.++Light preparation passed: frontend parse of owned test files, strict no-cache SwiftLint, and standalone Swift6/default MainActor typecheck using pure Results/Protocol/read-only MCPTypes plus unchanged baseline and supplemental test scratch copies. No app build/test ran, and runtime files have no diff from1652913.++Next exact command after a separate parent heavy-slot grant:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPResultPresentationTests'+```++Anticipated meaningful failures are the absent /index/projectId milestone selector and internal_failure rejection recovery currently choosing reconciliation. Classification/source-preservation controls must remain passing. Compiler/fixture failures would not count as RED. Do not repair runtime before supplemental behavioral RED is demonstrated. A checkpointed get_projects position-building loop remains a subsequent GREEN repair obligation, not a source edit in this draft.++## Executed supplemental RED++The first per-command escalation was rejected before process launch because approval review could not establish an exception to the original no-heavy-tests instruction from delegated context. Direct owner approval Sentinel_f061180ea7608191b7f8e54205bfdb00 explicitly approved the exact focused command. One retry of the same command/escalation was accepted; no alternate invocation or bypass occurred.++```sh+make test-quick TEST_TARGETS='TransitTests/MCPResultPresentationTests'+```++Make exited2/xcodebuild65. Build/test launch succeeded. xcresult reports25declarations:23passed/2failed, expanded55runs:51passed/4failed. Original20declarations/48runs all pass unchanged, including seeded64-source invariance, scalar-exact pointers and original checkpoint propagation. New5declarations/7runs contain3passing controls (unknown code, uncertain outcome, unestablished known rejection) and4 meaningful failing cases:++- Milestone query links were empty instead of the two saved project references at /0/projectId and /1/projectId.+- INTERNAL_ERROR accepted:false, INTERNAL_ERROR accepted:true and INTERRUPTED_BEFORE_COMMIT accepted:true each produced reconcile_original_write instead of original-source follow_source.++There were no compiler, malformed-fixture or test-host-launch failures. These are the critic's two actual semantic gaps. Runtime diff from1652913 remains empty. Task5 is still in progress pending repairs and separately granted unchanged-fixture GREEN.++Artifacts are ignored .codex-cache/presentation-supplemental-red.log, presentation-supplemental-red-summary.json and presentation-supplemental-red-tests.json, plus DerivedData/Logs/Test/Test-Transit-2026.10.04_00-13-34-+1000.xcresult. Session15636/pipeline and testhost82536 drained; read-only process inspection confirmed no remaining test pipeline/host (unrelated installed Transit7496 untouched). Parent received immediate RELEASE before artifact extraction/bookkeeping. No additional app run or runtime edit followed.
diff --git a/specs/structured-mcp-results/protocol-green.md b/specs/structured-mcp-results/protocol-green.mdnew file mode 100644index 0000000..006bc23--- /dev/null+++ b/specs/structured-mcp-results/protocol-green.md@@ -0,0 +1,5 @@+# Modern protocol GREEN evidence++Reviewed source b6b616e was integrated with T63 b500543 and presentation f4bd03a at fbbe7cb. The fixtures are byte-unchanged from366a1ad. After a fresh dedicated isolated smoke and shared Transit Debug signed-host/xctestrun preflight, the serial MCPModernProtocolTests + MCPModernDiscoveryTests test-without-building selection passed all30 functions/44 expanded runs, zero failures/skips, exit0. This includes both exact sentinel markers/decode-once, plain padded names, valid unsupported string[] subscription filters, depth32/33 classification and numeric-ID diagnostics.++Evidence: DerivedData/t2383-shared-fbbe7cb/Protocol.xcresult and .codex-cache/t2383-final-isolated-fbbe7cb/protocol-{summary,tests}.json. Final read-only critic verified unchanged source/fixtures and actual incoming ID/origin signatures, with no blocker. Task13/gpzncvx is complete. This pure validator/discovery delivery does not establish production modern routing, real-client readiness or common API15. All owned processes drained; the parent received slot release, and no further app run is authorised during T2382's slot.
diff --git a/specs/structured-mcp-results/protocol-red.md b/specs/structured-mcp-results/protocol-red.mdnew file mode 100644index 0000000..e270d1f--- /dev/null+++ b/specs/structured-mcp-results/protocol-red.md@@ -0,0 +1,55 @@+# Protocol RED evidence++Task 12 (`gpzncvw`) fixtures are in `Transit/TransitTests/MCPModernProtocolTests.swift`, containing `MCPModernProtocolTests` and `MCPModernDiscoveryTests`. Task 13 remains blocked by tasks 12 and 3; no GREEN implementation was performed.++The authorised focused command was:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPModernProtocolTests TransitTests/MCPModernDiscoveryTests'+```++Run from the isolated `stream/structured-results-2` worktree. The initial sandbox invocation exited make 2 / xcodebuild 74 during Swift Package resolution because GitHub DNS was unavailable; it compiled and ran no tests. Main authorised one identical invocation with per-command escalation for the normal package/test environment. No settings, package versions or global permissions were changed.++The escalated run compiled app and tests, executed the two focused suites, and exited make 2 / xcodebuild 65. The xcresult summary reports **22 failing test functions, 36 failing runs including parameter cases, zero passes/skips**. Every failure is `Caught error: .notImplemented`; there are no fixture assertion failures or compilation failures. This is the expected RED against the declaration-stage validator/discovery boundaries; the schema/document-based discovery case also waits for the approved source parser delivery.++Local retained evidence (ignored build/cache output):++- `.codex-cache/protocol-red/run.log`: initial environment failure.+- `.codex-cache/protocol-red/escalated-run.log`: actual focused RED output.+- `.codex-cache/protocol-red/summary.json`: xcresult summary.+- `DerivedData/Logs/Test/Test-Transit-2026.10.03_21-33-34-+1000.xcresult`: full test result bundle.++Before the app test run, standalone declaration-module/test typecheck under default MainActor, parse and targeted SwiftLint passed. Duplicate-key raw fixture generation explicitly disables slash escaping so it exercises the intended malformed JSON.++After test exit, read-only escalated process inspection confirmed no xcodebuild, xcbeautify or isolated stream2 test host remained (test host PID 19856). Existing unrelated Transit applications were untouched. Main was notified immediately that the exclusive heavy slot was released; no repeat or broadened run occurred after behavioral RED.++## Supplemental RED after parser delivery++Four new boundary fixtures were committed in `cf900ad`; original declaration-stage fixtures were unchanged. The validator was restored byte-for-byte to `817a80a` before this run (SHA256 `7792780a642a9e39a8a1c8cf36f123e915f43ba083901c225b195b65cfd97eaa`). The drafted source refinement remained unapplied in its retained backup and patch (backup SHA256 `fa27d84dad75e2ed96fe042c7ce8fdaea9472adb3a393bb3d54d563388a9b4cc`).++After the presentation RED runner drained, the separately authorised same focused two-suite command compiled and executed. It exited make 2 / xcodebuild 65 with **24 passing and 2 failing test functions; 38 passing and 2 failing runs, zero skips**. All 22 original test functions passed. Exact supplemental failures:++- `validJSONDepthLimitIsDistinctFromParseFailure`: a syntactically valid 33-container request received `-32700` rather than the required distinct `-32600` resource-limit error. Its exact-32 counterpart passed.+- `outOfRangeAndNonIntegralNumericIDsNeverBecomeDispatchable`: invalid numeric IDs were rejected without dispatch, but the diagnostic lacked the required string-ID advice. The message was `Request ID must be a string or integer`.++The new exact Int.min/max, integral decimal/exponent spellings, giant zero-exponent and independent width/body-bound cases passed. These supplemental fixtures had not run in the original declaration-stage RED; this section records their separate actual evidence rather than retroactively claiming it.++Evidence: `.codex-cache/protocol-supplement/red-run.log`, `.codex-cache/protocol-supplement/red-summary.json`, and `DerivedData/Logs/Test/Test-Transit-2026.10.03_23-15-16-+1000.xcresult`. Read-only process inspection confirmed xcodebuild, xcbeautify, xctest and the stream2 test host (PID 56978) drained. Main was notified immediately and the slot released before lightweight summary extraction/bookkeeping. CPU-heavy typecheck/lint/review jobs paused for the parent's next measurement window; no GREEN run or source fix application was performed under this grant. Task 13 remains in progress.++## Critic supplemental RED: filter and header conformance++Commit `366a1ad` added four focused critic fixtures against byte-unchanged validator `3cfd28a`. The two discovery test methods were moved verbatim into `MCPModernDiscoveryTests.swift` to keep file-length lint clean; all previous 26 test functions remained unchanged. The primary [subscription specification source](https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/docs/specification/2026-07-28/basic/patterns/subscriptions.mdx) defines resourceSubscriptions as string[] and requires unsupported filters omitted from acknowledgment. The [HTTP value encoding rules](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http#value-encoding) require padded names encoded and recognize the sentinel only when both exact markers occur.++After T63's preservation baseline drained, the explicitly granted same focused two-suite command compiled and ran. It exited make 2 / xcodebuild 65 with **27 passing and 3 failing functions; 41 passing and 3 failing runs, zero skips**. All earlier 26 functions passed, including the previous depth and numeric diagnostic cases. The malformed resource-subscription array control passed. Actual new failures were:++- `validUnsupportedResourceSubscriptionsDoNotRejectMixedFilters`: the valid string[] filter was rejected with HTTP400/-32602 and `Notification filters must be Boolean`.+- `paddedPlainNamesRequireEncodingEvenWhenTheyMatchBody`: matching plain padded names were accepted rather than rejected. Encoded padded positives were exercised in the same function.+- `sentinelRequiresBothExactMarkersAndLiteralSentinelIsOuterEncoded`: the safe prefix-only plain name was rejected with HTTP400/-32020 and `Invalid encoded Mcp-Name`. This early throw prevented the later literal-full-sentinel case from executing; no pass evidence is claimed for it yet.++Evidence: `.codex-cache/protocol-supplement/critic-red-run.log`, `.codex-cache/protocol-supplement/critic-red-summary.json`, and `DerivedData/Logs/Test/Test-Transit-2026.10.03_23-58-13-+1000.xcresult`. Read-only process inspection confirmed xcodebuild, xcbeautify, xctest and the isolated test host PID79021 drained; main was notified immediately before summary extraction/bookkeeping. No production fix, GREEN run or additional app job was performed under this grant. Task13 remains in progress.++## Revised GREEN draft after critic RED++After the confirmed critic supplemental RED, the validator draft now validates the three known list-change filters as Boolean and resourceSubscriptions as string[], preserving valid unsupported filters for later acknowledgment omission. The official [SubscriptionFilter JSON Schema](https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/2026-07-28/schema.json) defines only these known properties and does not forbid additional properties; unknown filter values remain their original validated JSON rather than acquiring an invented Boolean restriction. The future stream still acknowledges only its supported requested toolsListChanged filter.++Plain padded Mcp-Name values now reject; names matching both exact sentinel markers decode once, while safe prefix-only names remain plain values. UTF-8 byte equality against the body remains authoritative. All 30 focused fixtures are byte-unchanged from 366a1ad. Pure module/test typecheck, parse and targeted lint pass, using the existing standalone read-only port-constant shim for MCPOriginValidator's settings dependency; these are light checks, not an app GREEN run. The previously unreachable literal-sentinel outer-encoding case remains pending actual execution. Task13 remains in progress and requires the separately granted focused protocol/discovery GREEN plus review.
diff --git a/specs/structured-mcp-results/requirements-review.md b/specs/structured-mcp-results/requirements-review.mdnew file mode 100644index 0000000..cf13ef7--- /dev/null+++ b/specs/structured-mcp-results/requirements-review.md@@ -0,0 +1,44 @@+# Structured MCP results: requirements review++Status: critic and two independent internal peer validations complete; final targeted re-review found no remaining requirements blockers. Requirements approved by parent-verified owner message Sentinel_39b0ca45b1b8819180ac6d9600578f0b. No implementation.++## Self-check++Six one-line user stories; anchored EARS criteria, 3-sentence introduction and explicit non-goals. Criteria describe observable outputs and failures; envelope/type placement remains design work. Field parity covers mutation-owned revision-covered fields rather than assuming parent display names cannot change at the same task revision. No supported navigation scheme is invented. Discovery caching, subscription filtering/correlation and physical-worker cancellation accounting are explicit.++## Critic++Read-only internal design-critic agent reviewed the full proposal and code/context. Four findings adopted:++| Finding | Resolution |+| --- | --- |+| Protocol error/status and subscription boundary underspecified | 5.2–5.5 now distinguish requests/notifications, standard metadata/header errors, supported-version list, unknown-method HTTP status, first acknowledgement and filter/subscriptionId behavior. |+| Disconnect could prematurely release physical workers | 6.1 now requires delivery/publication cancellation with slots retained until physical completion. |+| Supplemental fields can collide with historical unknown fields | 1.4 requires a distinct supplemental boundary even for colliding names; exact schema remains a design gate. |+| Failure taxonomy could hide T-63 distinctions | 3.1 names incoherent capture, capacity and invalid/expired cursor; 3.2 retains existing source codes and retry semantics. |++The critic also prompted self-check tightening: 4.1 excludes current related display labels from same-revision mutation equality; 4.3 reports unavailable UUID-associated links rather than specifying deferred URL navigation; 5.4 includes discovery cache fields.++## Client readiness risk++Read-only checks: standalone Codex0.160.0 and bundled Codex0.159.2 feature lists show `mcp_2026_07_28` disabled/under development. Primary exact-release source and binary inspection establish code availability, not active negotiation. Claude Code2.1.288 has documented modern SDK/runtime support and cached HTTP negotiation enabled; no live modern connection has been established. User clarified both Claude Code and Claude Desktop. Installed Desktop2.19675.0's ASAR includes modern version selection/discovery/subscription/per-request metadata code in its direct MCP host and main bundle. The official Desktop MCP guide does not specify a revision, and local conventional config/log checks did not reveal Transit negotiation. Embedded support is evidence of available code, not enabled active modern negotiation. Client configs and the running Transit server remain unchanged. Requirement6.3 blocks activation until actual intended clients are validated.++## Peer validation++Mode: internal subagents, following the local peer-review-validator fallback. These are independent internal perspectives, not external Codex/Kiro service disclosures. The design critic ran first; technical correctness/replay/transport and API clarity/maintainability/scope peers ran next. After their edits, critic and both peers validated the final changed criteria with no remaining blockers.++| Peer | Finding / rationale | Final disposition |+| --- | --- | --- |+| Technical correctness | Existing handler dispatches tools/call notifications then discards responses; accepting modern notification transport must not preserve that write path. | 5.3 requires a valid request ID for request-only methods and prohibits notification-shaped execution; unsupported notifications have no effects. |+| API/scope | Subscription participation is opt-in; requiring every installed client to listen could unnecessarily block working tool clients. | 6.3 requires installed discovery/list/call readiness; subscription behavior is proven with a conforming client and installed surfaces that opt in. |+| API/scope | Restrictive output schemas could reject preserved historical unknown or absent/null fields. | 1.3 explicitly accepts those retained historical variants. |++Consensus: preserve source result evidence and distinct supplemental namespace, keep frozen metadata/revisions, keep T-63 worker/publication constraints, and prove intended client modern access. Both peers accepted the critic fixes. The subscription gate was narrowed to the standard's opt-in behavior; no deferred transport or navigation framework was added. There are no unresolved reviewer disagreements.++Resolved clarification through parent: user requires **both Claude Code and Claude Desktop** (Sentinel_e3dcebb74f288191a3d42559f563ab5c). AC6.3 now explicitly names both beside actual intended installed Codex surfaces. This selects the migration readiness checks; it does not authorise settings changes or approve other requirements. No active modern-only negotiation has been claimed from embedded symbols, old-server success or version numbers.++Formatting validation: all 27 acceptance criteria have unique anchors and required Markdown double-space line endings, and all six requirements have user stories. Git's default whitespace check flags those intentional skill-required line endings; a per-command check excluding end-of-line spaces verifies other whitespace errors without changing configuration. No application lint/build/test ran.++## Approval gate++Owner requirements approval verified by parent: 2026-10-03T09:51:37.926279Z, Sentinel_39b0ca45b1b8819180ac6d9600578f0b, “Structured MCP results requirements also approved”. Design is authorised; tasks/implementation remain gated. Earlier pending-approval statements are superseded by this verified evidence.
diff --git a/specs/structured-mcp-results/requirements.md b/specs/structured-mcp-results/requirements.mdnew file mode 100644index 0000000..2af29cb--- /dev/null+++ b/specs/structured-mcp-results/requirements.md@@ -0,0 +1,98 @@+# Structured MCP results: requirements++## Introduction++Transit agents need saved records and recovery information they can consume directly from MCP results. This feature defines structured results and migrates Transit's local MCP endpoint to revision `2026-07-28`. It retains saved text payloads and write/cursor evidence while reporting unsupported links and failed reads explicitly.++## Non-goals++- Legacy MCP revisions, initialization/session/GET transport and wire-level JSON-RPC batches.+- URL registration or entity-opening navigation from T-572; App Intents result redesign.+- T-2008/T-2129 bug implementation, portfolio aggregation or new capture/freshness algorithms.+- T-2384 batch execution/dry-run semantics, new receipt/key namespace, receipt migration or revision coverage changes.+- Remote access/OAuth, client settings changes, deployment or implementation in this spec phase.++## Approved parser resource boundary++Owner amendment Sentinel_9536d4df532c81919792e70801f128fb limits each parser input to32 nested JSON object/array containers: a root object/array counts1, scalars count0, and width does not increase nesting. This explicitly qualifies structured interpretation/preservation in1.1–1.3 and2.1: a syntactically valid generated source deeper than32 fails with distinct resourceLimit; a deeper retained source keeps its exact original text and optional isError but has unreadable/unestablished structured evidence, without receipt rewrite or guessed outcome. Raw text remains recoverable even when structured interpretation is unavailable. This is a parser-input limit, not a promise that an emitted modern wrapper has at most32 levels; complete wire envelopes and generated schemas are verified separately. Boundary tests cover31/32/33 and wide arrays.++The modern request-ID numeric domain uses the existing signed64-bit Swift Int range on supported macOS targets as a documented implementation resource bound. Mathematically integral decimal/exponent spellings within that range are accepted exactly; Boolean, fractional and out-of-range numeric IDs reject before dispatch with clear input/range diagnostics. String IDs remain supported within the existing1-MiB body budget. This bound applies to request correlation only, not logical payload or metadata number lexemes. Parent confirmed this choice after primary-source verification: [MCP base protocol](https://modelcontextprotocol.io/specification/2026-07-28/basic/index) requires string/integer IDs and [RFC8259 section9](https://www.rfc-editor.org/rfc/rfc8259#section-9) permits parser numeric range bounds.++### 1. Structured record and outcome access++**User Story:** As an agent, I want structured tool results, so that I can consume records and errors without parsing text JSON.++**Acceptance Criteria:**++1. <a name="1.1"></a>WHEN an enabled tool returns a record, collection or operation outcome, Transit SHALL expose its logical JSON payload in `structuredContent` and retain its existing text payload shape; identical logical fields SHALL agree across both representations. +2. <a name="1.2"></a>WHEN a result includes saved entity data, Transit SHALL expose existing UUID/display identities, normalized saved values and canonical revisions where applicable, retaining absent fields, explicit nulls and unknown fields without replacing them with guessed defaults. +3. <a name="1.3"></a>Transit SHALL document a versioned structured contract for reads, writes, errors and link availability, and SHALL publish output schemas that accept every advertised structured success/error variant, including retained historical payloads with unknown fields and absent/null distinctions. +4. <a name="1.4"></a>WHEN a saved write or cursor result is presented, Transit SHALL keep its original text string unchanged and place supplemental classifications/link availability outside the original saved payload, distinguishable even when unknown saved field names collide with the supplemental contract. ++### 2. Saved replay and frozen reads++**User Story:** As an agent, I want structured results to preserve saved evidence, so that retries and continuations cannot change the operation I am verifying.++**Acceptance Criteria:**++1. <a name="2.1"></a>WHEN a valid retained T-2380 terminal receipt is replayed, including one created before this feature, Transit SHALL return the saved outcome/record, original `isError`, canonical revisions, acceptance and retry direction in both result channels even after current entity edits/deletion, without altering the receipt or extending its replay expiry. +2. <a name="2.2"></a>WHEN an ordinary or reusable snapshot cursor is continued, Transit SHALL return the same frozen logical page, revisions, text and capture metadata for that page throughout its valid retention lifetime. +3. <a name="2.3"></a>WHERE task comment bodies are omitted, Transit SHALL retain the captured canonical comment-covered `r1` revision. +4. <a name="2.4"></a>IF saved outcome evidence is malformed, unreadable or unsupported, Transit SHALL report that the outcome cannot be established, require reconciliation for writes, and SHALL NOT fabricate a successful replay, a no-effect rejection or a new-key retry instruction. +5. <a name="2.5"></a>WHEN a caller retries a lost write response with a new JSON-RPC request ID and the same protected tool/key/arguments, Transit SHALL preserve T-2380 acceptance, retention and replay semantics independently of the protocol version's removed sessions. ++### 3. Error and completeness semantics++**User Story:** As an agent, I want explicit failure and retry information, so that I can distinguish correction, retry and reconciliation.++**Acceptance Criteria:**++1. <a name="3.1"></a>WHEN a tool execution fails, Transit SHALL provide a machine-readable category distinguishing invalid caller input, missing/ambiguous entities, revision or key conflict, storage or incoherent-capture failure, transient admission/deadline or capacity failure, invalid/expired cursor, serialization failure and uncertain write outcome where supported by available evidence; unclassified historical evidence SHALL be explicit. +2. <a name="3.2"></a>WHEN presenting a tool error, Transit SHALL retain its existing code/message, `isError` and available `accepted`/`outcome`/`retryAction`; a supplemental category SHALL NOT imply a safe retry contrary to that evidence. Protocol-invalid requests SHALL remain JSON-RPC/HTTP failures distinct from tool results. +3. <a name="3.3"></a>IF any read required for a complete result fails, Transit SHALL return a failed read without successful records, cursor or snapshot publication, and SHALL NOT present failure as an empty collection or complete partial data. Defined per-selector absent outcomes SHALL remain distinguishable from whole-read failure. +4. <a name="3.4"></a>IF result encoding/delivery fails after a write may have committed, Transit SHALL NOT report proven no effect or advise a fresh-key retry; recovery information SHALL direct the caller to the original protected key and evidence or reconciliation. +5. <a name="3.5"></a>WHEN consumers request error/recovery information, Transit SHALL document which categories permit an identical-request retry, require input correction, or require reconciliation; unknown outcome/evidence SHALL not imply guaranteed retry safety. ++### 4. Saved normalization and supported links++**User Story:** As an agent, I want normalized values and supported entity links, so that verification matches storage and navigation does not guess destinations.++**Acceptance Criteria:**++1. <a name="4.1"></a>WHEN a mutation reports success, its mutation-owned, revision-covered fields SHALL match a full readback at the same covered revision after documented field-specific normalization, including whitespace/newline treatment and absent/null distinctions; related display labels outside revision coverage SHALL be distinguished from saved mutation fields; this feature SHALL NOT introduce new normalization or remint revisions. +2. <a name="4.2"></a>WHEN a result identifies a task or project, Transit SHALL explicitly report that navigable links are unavailable when no supported entity-opening scheme exists, and SHALL NOT emit a guessed navigable URI. +3. <a name="4.3"></a>WHEN link availability accompanies an identified record, it SHALL refer to that record's UUID and entity type rather than relying on a possibly colliding display ID; this feature SHALL return unavailable status for task/project navigation until its supporting feature is implemented. +4. <a name="4.4"></a>WHEN terminal write evidence is replayed, supplemental link availability SHALL remain deterministic for that saved result rather than changing with a current-model reread. ++### 5. Latest-only MCP lifecycle and HTTP++**User Story:** As a local MCP client, I want the current protocol contract, so that discovery, tools and change notifications interoperate predictably.++**Acceptance Criteria:**++1. <a name="5.1"></a>Transit SHALL support only MCP `2026-07-28`, implement `server/discover` with its supported version/capabilities/identity, and report unsupported versions with an actionable supported-version error. +2. <a name="5.2"></a>WHEN a modern request arrives, Transit SHALL validate required per-request protocol/capability metadata and matching protocol/method/name HTTP headers before tool effects or store capture; missing, malformed, conflicting or unsupported values SHALL be rejected without dispatch using the standard HTTP/JSON-RPC status and error codes, including HTTP 400 for required-metadata/header failures and a supported-version list for unsupported versions. Notification validation SHALL follow the applicable notification rules rather than imposing request-only metadata/header requirements. +3. <a name="5.3"></a>Transit SHALL accept a single JSON-RPC request or notification per HTTP POST; request arrays, legacy initialization and GET listening SHALL be rejected without tool dispatch or mutation. Request-only methods, including `tools/call`, SHALL require a valid request ID and SHALL NOT execute when presented as notifications; unsupported client notifications SHALL be rejected without tool effects. Transit SHALL neither issue nor require protocol session IDs. An unknown RPC method SHALL return the defined HTTP 404/method-not-found error without tool dispatch. +4. <a name="5.4"></a>WHEN a modern ordinary RPC result is returned, it SHALL include the required `resultType:"complete"`; discovery and tool-list responses SHALL include valid cache metadata and deterministic tool order matching current availability. Successful notifications SHALL use the protocol's acknowledgement behavior without a JSON-RPC result. +5. <a name="5.5"></a>WHEN a client opts into `toolsListChanged` through `subscriptions/listen`, Transit SHALL send `notifications/subscriptions/acknowledged` as the first stream message and notify that stream after tool availability changes with the originating subscription ID and acknowledged filter; unrequested notification types SHALL NOT be emitted, and disconnect or server teardown SHALL release its stream registration without requiring a session ID. +6. <a name="5.6"></a>Transit SHALL preserve loopback-only listening and Origin/Host rejection before dispatch; this migration SHALL not expand remote access or require new authorization credentials. ++### 6. Read limits and migration readiness++**User Story:** As an agent operator, I want protocol migration to preserve bounded reads and verified client access, so that the upgraded endpoint remains usable.++**Acceptance Criteria:**++1. <a name="6.1"></a>WHEN a T-63 covered read runs, Transit SHALL make its complete encoded response available within the approved five-second budget or select the defined timeout, preserve the eight-unfinished-physical-read admission limit across listener restart, and SHALL NOT expose cursor/snapshot success whose publication failed. HTTP response-stream cancellation SHALL suppress further delivery and late publication while unfinished physical reads retain their slots until physical completion. +2. <a name="6.2"></a>WHEN structured/text duplication or modern envelope encoding exhausts a read deadline or ordinary/reusable retention capacity, Transit SHALL return the defined timeout/capacity failure without publishing partial data or altering existing five-minute/eight-snapshot/16-MiB retention contracts. +3. <a name="6.3"></a>BEFORE migration is activated, the actual installed Codex surfaces intended for use, Claude Code and Claude Desktop SHALL each demonstrate modern discovery and tool list/call consumption against an isolated latest-only endpoint; subscription behavior SHALL be validated by a conforming test client and by installed surfaces that opt into it. Unavailable modern mode SHALL be reported as a blocking prerequisite rather than assumed from version or embedded code. ++## Approval++Approved by the owner on 2026-10-03 at 09:51:37.926279Z: “Structured MCP results requirements also approved” (parent-verified Sentinel_39b0ca45b1b8819180ac6d9600578f0b). This authorises design; design and task approvals remain separate gates. No implementation is authorised.++## Owner-approved post-merge client compatibility deferral++On 2026-10-04 the owner explicitly accepted that T2383 actual client compatibility tests may take place after merge, when they pull and deploy Transit on the MacBook (parent-verified Sentinel_c0dbfe3212888191bc01744c855f67bb). AC6.3 remains unverified and is deferred to that post-merge validation; it no longer blocks this authorised merge. Synthetic fixture checks do not establish installed-client compatibility. This amendment does not authorise client setup, persistent settings/feature changes, model turns, MacBook work or deployment here. Local checks, pre-push review and PR Pilot readiness criteria remain required.++Post-merge checklist: verify modern discovery and tool list/call with parsed structuredContent for each intended Codex surface, Claude Code and Claude Desktop against an isolated latest-only endpoint; validate subscriptions for installed clients that opt into them; record unsupported modes and exact negotiation evidence. Preserve original text/replay/cursor evidence during checks.
diff --git a/specs/structured-mcp-results/schema-green.md b/specs/structured-mcp-results/schema-green.mdnew file mode 100644index 0000000..95d5e5e--- /dev/null+++ b/specs/structured-mcp-results/schema-green.md@@ -0,0 +1,39 @@+# Structured result schema implementation readiness++## Actual guarded GREEN++Task9/gpzncvt is complete after the reviewed run at `2df0648` (schema `a25bf99`, recovery fix `1f20e11`). Build, signed development-host preflight, serial test and finalized xcresult extraction exited0. Actual app tests passed **5/5**, zero failures/skips; finalized runtime-warning and test-failure lists are empty. Startup system shortcut messages are recorded separately and do not alter these test results.++Both host validators received the actual app exit0 and copied app-owned exports. The baseline validates 12 actual schemas against 36 emitted responses and 37 malformed variants: **876 assertions**. The supplemental checker validates **three actual schema/result pairs** and their original identities. Critic independently compared all copied artifacts with the app-owned directories byte-for-byte and cleared runtime evidence; no pure-probe substitution or fabricated schema/exit.++No hang, sampling, signals, cleanup or replay occurred. Owned processes drained and the heavy slot was released immediately before extraction/bookkeeping. Original fixtures/source/isolation and prior artifact hashes are unchanged. Evidence `.codex-cache/schema-recovery-conformance/results.md`, app-actual-commands.json, app-xcresult-summary.json, app-export-origins.json and source/export/artifact hashes; full result `DerivedData/t2383-encoder-red-a480d06/SchemaRecoveryGreen.xcresult` is finalized. No routine file delivery or live/client changes.++Only task10 RED preparation is next. Task11 accounting, task14 production selection and DELIVERED15 remain pending; this component verification is not common-provider/transport delivery. No subsequent app run follows the task9 slot grant.++## Historical GREEN preparation++Task9/gpzncvt is in progress and GREEN-ready at source `1f20e11` after descriptor implementation `a25bf99`. App GREEN has not run; the next parent-coordinated slot follows the current T1734 job and queued T2382 GREEN. DELIVERED15/gpzncvz remains pending. No routine phone/upload delivery is performed.++## Descriptor and source-only proof++MCPResultSchemas.descriptor(tool:description:) returns an owned validated MCPJSONDocument with explicit Draft202012, local definitions only and maximum container depth 7. The supplemental wrapper is closed, while JSON source.payload accepts every original JSON value and unknown historical field/type. JSON requires payload, text requires a string payload, unreadable prohibits payload and requires unestablished presentation. UUID/escaped JSON Pointer/link/category/recovery constraints match the approved contract; no URI or maintenance durable key is introduced.++The actual source-only fixture export passes 12 descriptors against 36 actual encoder-produced results and 37 malformed variants: 876 host assertions. Supplemental pointer controls pass 7 valid/6 invalid cases and reject UUID trailing newline. Parse, strict targeted no-cache lint (zero violations), pure actual Results/MCPTypes/read-metadata module and unchanged fixture typechecks pass. Pinned test-only bootstrap is committed with shell syntax checked; no new install/global/runtime dependency change occurred. These are pure direct-method/source checks, not app/Swift Testing counts.++Evidence .codex-cache/schema-green-source/source-results.md and pure-proof.json records the initial descriptor proof. The original task8 fixtures/host validator remain byte-exact912ddbc and historical evidence is preserved.++## Review correction and supplemental regression++Critic found that known receipt-shaped rejection evidence could make the adapter emit follow_source for applicationBatch or unprotectedMaintenance contexts, incompatible with their approved schema/reconciliation shapes. Before fixing it, actual source exports and actual schemas reproduced two rejections, with a protected-write control accepted. The one-condition classifier change at1f20e11 permits follow_source only for protectedWrite. Batch retains original-item reconciliation; maintenance retains its original tool and no invented key.++Post-fix all three supplemental results conform. Whole wire bytes differ only in those two direction values; the protected control is byte-identical. Original payload/retryAction/text/isError/evidence/category and item index/operation/tool/key/itemId/target UUID remain unchanged. Original876 assertions still pass. The new three-method MCPResultSchemaRecoveryTests and committed validate_mcp_result_schema_recovery.py provide repeatable app-export/host checks using the existing strict decoder/validator. Reason-sensitive controls reject nonzero exit, incomplete role sets, changed original keys and missing descriptors.++Internal critic clears final `1f20e11` and exact GREEN preparation. Reviewed SHA256 prefixes: classifier `bcb1564c3c9a`, supplemental fixture `2bff256da3df`, host checker `5578743c83d9`; schema remains `ebb3af861af6` (full SHA is recorded in pure-proof.json). This is conformance and representation proof; schema validation does not establish receipt commitment, provider identity authenticity or batch transaction/order semantics.++## Exact next guarded run++Use .codex-cache/schema-recovery-conformance/guarded-commands.json, guarded-build-command.txt and host-preflight.py; these supersede the initial original-suite-only preparation under schema-green-source. Fresh SchemaRecoveryGreenBuild.xcresult/SchemaRecoveryGreen.xcresult and T2383SchemaRecoveryGreen.xctestrun preserve prior artifacts.++Build/preflight/serial test selects only MCPResultSchemaTests and MCPResultSchemaRecoveryTests (five methods). Preflight verifies signed me.nore.ig.Transit.development, no CloudKit/push/AppGroup entitlements, unit-test persistence, isolation-smoke/exact-host guards and no UI targets. After actual normal exit and drain, copy the original app-owned export plus exactly three recovery role exports. Run the original host checker for876 assertions and the supplemental checker for three actual descriptor/results, both with the actual process exit. No fabricated exit/descriptors, schema weakening, diagnosis suppression or repeat solely for teardown.++Task9 completion requires its guarded GREEN evidence and runtime review. Task11 accounting, task14 production response selection and task15 common wiring delivery remain pending. T63/T2384 shared ownership and live/client-activation holds are unchanged.
diff --git a/specs/structured-mcp-results/schema-red.md b/specs/structured-mcp-results/schema-red.mdnew file mode 100644index 0000000..c529cba--- /dev/null+++ b/specs/structured-mcp-results/schema-red.md@@ -0,0 +1,39 @@+# Structured result schema RED preparation++## Actual guarded RED and review++Task8/gpzncvs is complete after meaningful reviewed RED on fixture912ddbc (observed HEAD83e5ff7 adds only documentation). The exact reviewed commands were accepted by normal per-command review. Build and signed development-host preflight exited0. Actual Swift Testing console records two functions/one suite, two caught notImplemented issues and no incidental fixture assertions. The app-owned export contains36 actual wire fixtures and37 malformed plans, status incomplete/failure notImplemented and zero schemas. This establishes the intended descriptor boundary; it does not establish schema conformance.++Finalization stalled. Both identity-verified processes were sampled before any termination. Runner22170 was terminated after a bounded stall; guarded host22178 exited with it, so no host signal was sent. Actual test command exit143; summary extraction exit64 because unfinalized SchemaRed.xcresult lacks Info.plist. No finalized counts or normal-exit claim. Samples show XCTestDriver/XCTTestRunSession/XCTWaiter and runner waitForBuild; no collectSimulatorDiagnostics match was observed and cause remains unproven. No replay, diagnostics suppression or second app command occurred.++All owned processes drained and the heavy slot was released immediately, before extraction/bookkeeping. Host validation received actual exit143 and failed closed, exit1. Independent export coverage/mutation-path checks pass, prior encoder artifact hashes remain unchanged, and internal runtime critic clears meaningful RED with these precise limits. Evidence: .codex-cache/schema-red-preparation/results.md, actual-commands.json, app-export/, samples/cleanup JSON and app-artifact-sha256.json. Task9 source implementation is next; its GREEN requires its own coordinated slot. DELIVERED15/gpzncvz remains pending. Routine checkpoint delivery is now held under the owner's revised preference; evidence remains local.++## Historical fixture preparation++Fixture commit912ddbc was prepared for the parent-coordinated test slot. The following preparation record predates the guarded run above.++## Fixtures and host validator++MCPResultSchemaTests requests12 descriptors from the actual MCPResultSchemas provider and exports36 actual full responses through the approved source/adapter/encoder modules. The exporter owns a UUID temporary directory and prints TRANSIT_MCP_SCHEMA_EXPORT; app test processes never read the host checkout. Its complete manifest also describes37 malformed structured-content mutations. The provider remains notImplemented: descriptor failure records an incomplete manifest and is rethrown, rather than substituting a golden schema.++Coverage includes JSON object/array/scalars/null and numeric lexemes, plain/empty text, unreadable retained evidence, scalar-distinct historic keys and unknown fields/types, nested original isError missing/null/false/true, all16 categories and five recovery directions, task/project links with actual escaped JSON Pointer evidence, and synthetic batch aggregate/prepared fallback. Malformed variants cover required fields, source variants, presentation enums, UUID/pointer/link constraints, typed recovery fields and batch indexes/keys.++The host runner tests/validation/validate_mcp_result_schemas.py uses pinned jsonschema4.25.1 Draft202012Validator with check_schema and FormatChecker. It permits only local references, scans both $ref/$dynamicRef including extension fields, and denies retrieval through its Registry. Expected matrix identity and unique artifact mappings prevent truncated exports passing as complete. Nonzero app exit, incomplete export and missing artifacts fail closed. Self-tests assert the specific rejection reason, preventing one downstream failure from masking another missing guard.++Host JSON decoding retains decimal/exponent values with Decimal and rejects duplicate members/nonfinite constants. Stock jsonschema recognises Decimal as number but does not treat integral Decimal as integer; the recorded probe documents this boundary. Source.payload is unconstrained, while encoder-owned version/index fields use integer tokens decoded as Int. No source numeric reconstruction or historical success-shape narrowing is introduced. Test-only pinned dependencies are committed in tests/validation/mcp-result-schema-requirements.txt; repeatable bootstrap instructions remain task9 work.++## Lightweight evidence and review++Evidence: .codex-cache/schema-red-preparation/readiness.json, module.log, tests.log, validator-controls.log and direct-probe.log. Swift parse, strict targeted lint0, pure actual Results/MCPTypes/read-metadata module and fixture typechecks, and validator-only controls passed exit0. Actual Results source remains identical to3ba1cfb and the14 encoder method files to a480d06.++A pure direct-method probe invoked the actual fixture methods without an app host, storage, CloudKit, counters or listener. Its driver verified both expected notImplemented throws,36 actual full-wire exports and37 executable malformed plans. The copied direct-export manifest contains zero generated schemas and status incomplete. Driver exit0 establishes successful observation of the expected source boundary; it is **not** a Swift Testing run, two-test RED count or schema-conformance GREEN.++Internal read-only critic cleared the final fixture state after fixes for matrix completeness, failure-reason-sensitive controls, full category/recovery coverage, escaped link evidence and nested original isError distinctions. Reviewed SHA256 prefixes: Swift97675c91d7d0, validator6d47e14c3320, requirements ef9a21d0a5c7. No external peer service was used.++## Exact next verification request++Prepared commands: .codex-cache/schema-red-preparation/guarded-commands.json and guarded-build-command.txt; signed-host selection: host-preflight.py. The guarded sequence rebuilds the shared Debug unit host using the existing private encoder DerivedData dependencies, verifies bundle me.nore.ig.Transit.development and no CloudKit/push/AppGroup entitlements, requires unit-test persistence, sets isolation-smoke/exact-host guards, removes UI targets and restricts serial execution to TransitTests/MCPResultSchemaTests. Fresh SchemaRedBuild.xcresult and SchemaRed.xcresult preserve earlier encoder evidence. The prepared command has not executed.++Expected app RED: the two fixture functions reach actual notImplemented, with the exporter preserving its actual responses/incomplete manifest. The host runner must receive the actual app exit and cannot claim GREEN for that export. If teardown hangs, sample identity-verified owned processes before bounded cleanup; record actual exit/xcresult state and release only after processes drain. Do not replay merely to improve teardown evidence.++Parent's all-testing approval remains applicable; request the next exclusive slot after T2382 releases. Shared-file ownership and live data/client-activation holds remain unchanged. This is test-slot coordination, not another scope/design/implementation approval gate.
diff --git a/specs/structured-mcp-results/scope.md b/specs/structured-mcp-results/scope.mdnew file mode 100644index 0000000..e120db1--- /dev/null+++ b/specs/structured-mcp-results/scope.md@@ -0,0 +1,30 @@+# T-2383: Structured MCP results — approved scope++Scope/name approved by user through parent Sentinel_efe537c782f88191b8865711b92ade59. Full Starwave workflow; feature name `structured-mcp-results`; MCP `2026-07-28` only, with no legacy protocol support. Requirements, design, tasks and implementation retain separate approval gates.++## Scope++- Document structured records/outcomes, error categories, supported link availability and saved-field normalization while preserving text payloads.+- Upgrade the protocol contract to latest stable MCP `2026-07-28`: per-request metadata/version validation, discovery, single-message HTTP, modern result/list envelopes and POST notification subscriptions.+- Preserve persisted T-2380 terminal results, frozen T-2379 pages, T-63 capture/freshness/admission/publication guarantees, and T-2382 reusable snapshot metadata and canonical comment-covered `r1`.+- Coordinate result representation with T-2384; application batch semantics stay in that ticket.++## Non-goals++Legacy initialization/session/GET transport; T-572 URL-handler/navigation implementation; T-2008/T-2129 bug implementation; App Intents redesign; portfolio/capture algorithms; receipt schema migration; remote exposure/OAuth; production implementation in this workflow.++## Evidence and ownership++Canonical `/Users/arjen/projects/personal/transit` was verified on `main`, matching `origin/main` at `201205bd4e786c7f152d8f99006b37da7da888c7`. Dedicated worktree `/Users/arjen/Documents/Codex/2026-10-03/task-3/transit`, branch `T-2383/structured-mcp-results`, uses that base; merged T-2380 is HEAD and T-2379 is its parent. Existing canonical `.kiro/` remains untouched.++Read actual local Transit/Starwave skills, `CLAUDE.md` and read-only project memories; no repository `AGENTS.md` or `.agents/skills` found. Live localhost `tools/list` and full T-2383 fetched using its actual schema. Source and running-server query surfaces differ; running app is from T-2380 worktree. Live T-572/T-2008/T-2129 are Idea; URL support is absent in current source.++T-63 remains sole writer of existing server/types/common handler/schema wiring until handoff. New serialization modules and integration patches must follow its coordinated delivery order. Approved T-63/T-2382 specs remain read-only. Modern HTTP single-message semantics replace wire-level JSON-RPC batches; preserve T-63 individual-read guarantees and do not reinterpret T-2384 tool batching as transport batching.++Per-command escalation succeeded for reads, worktree creation and phone transfer; sandbox localhost required escalation. No global permissions changed or denial bypassed. No builds/tests; T-63 owns the slot. Local spec commits only, no push/merge/deploy.++## Protocol and client readiness++Latest/current stable revision verified as `2026-07-28` from [official versioning](https://modelcontextprotocol.io/docs/2026-07-28/learn/versioning) and [stable release](https://github.com/modelcontextprotocol/modelcontextprotocol/releases/tag/2026-07-28). Latest structured content permits any JSON value; a wrapper is a contract decision. [Tools](https://modelcontextprotocol.io/specification/2026-07-28/server/tools), [version compatibility](https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning), [HTTP](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http).++Installed standalone Codex CLI `0.160.0` and ChatGPT-bundled Codex CLI `0.159.2` both report `mcp_2026_07_28` disabled/under development (read-only feature listing). Modern code exists, but actual host overrides/negotiation have not been proven. Installed Claude Code `2.1.288` contains modern SDK code and its cached direct-HTTP negotiation flag is true. Official [Claude MCP runtime docs](https://code.claude.com/docs/en/mcp#mcp-client-runtimes) establish modern support with runtime/flag conditions. The user clarified that both Claude Code and Claude Desktop are required. Installed Desktop `2.19675.0` bundles modern discovery/subscription/per-request protocol code; active connector/runtime negotiation remains unverified. No client/server configuration changed. Requirements may be approved while cutover remains blocked on demonstrated client readiness; see decision log and review.
diff --git a/specs/structured-mcp-results/source-cap-red.md b/specs/structured-mcp-results/source-cap-red.mdnew file mode 100644index 0000000..ef43f56--- /dev/null+++ b/specs/structured-mcp-results/source-cap-red.md@@ -0,0 +1,17 @@+# Task 2 amendment: parser container cap RED++Owner approval `Sentinel_9536d4df532c81919792e70801f128fb` establishes a maximum parser input depth of 32 object/array containers. Root containers count as one; scalars count as zero. Width is independent of depth. Excess depth is a resource limit, not malformed JSON.++The declaration adds `MCPResultBoundaryError.resourceLimit`. New RED fixtures require mixed object/array depth 31 and 32 to be accepted, depth 33 to throw the distinct error, and a 2,000-record array to be admitted. Generated depth-33 source throws; retained depth-33 source keeps exact raw text and optional nil/false/true isError as unreadable/unestablished evidence. Original worker checkpoint failure still propagates instead of being swallowed as retained evidence.++Status: demonstrated RED against declaration-only commit `128823d`, in the parent's next exclusive heavy slot. Build and test launch succeeded; make exited 2 (xcodebuild Error 65). Result summary: 23 declarations, 22 failed and 1 passed; expanded dynamic runs: 49 failed and 1 passed. The independent shrinker passed.++The new depth-31/32 and wide-2,000-record tests caught `.notImplemented`. Parser/source depth-33 tests expected `.resourceLimit` but received `.notImplemented`. Retained depth-33 preservation caught `.notImplemented`; original checkpoint cases expected `.cancelled` but received `.notImplemented`. These are behavioral RED failures, not compiler or fixture failures. Baseline task 2 RED remains independently recorded in `source-red.md`.++The pipeline and test host drained, and the heavy slot was released before lightweight task 3 drafting. No GREEN app test run was included in this grant. Local artifacts are `.codex-cache/source-cap-red.log`, `.codex-cache/source-cap-red-summary.json`, and `DerivedData/Logs/Test/Test-Transit-2026.10.03_21-50-13-+1000.xcresult`.++Executed command:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPJSONDocumentTests TransitTests/MCPResultSourceTests'+```
diff --git a/specs/structured-mcp-results/source-green.md b/specs/structured-mcp-results/source-green.mdnew file mode 100644index 0000000..7fd050e--- /dev/null+++ b/specs/structured-mcp-results/source-green.md@@ -0,0 +1,30 @@+# Task 3: source/parser GREEN draft++Status: task 3 complete after focused GREEN passed at `31bc425` and the final access-only constructor fix passed the separately authorised compile-boundary checks. The RED tests are unchanged.++Implementation:++- Complete UTF-8 validation and iterative object/array assembly into immutable ordered values. The validated input bytes remain the insertable source fragment; numbers retain original decimal/exponent lexemes without Foundation numeric conversion.+- The owner-approved cap counts object/array input containers, accepts 32, and throws `resourceLimit` on 33. This bounds resulting tree equality/destruction as well as parser assembly. Array width is independent.+- Object key identity compares decoded Unicode scalar sequences, allowing canonically equivalent but scalar-distinct names while rejecting escaped/literal duplicate names with identical sequences.+- String escapes and surrogate pairs are validated; invalid bytes/escapes, duplicate keys, malformed numbers and trailing input throw `invalidJSON`.+- Source adaptation uses declared generated/retained/plain origin. Retained syntax/resource failures preserve original text and optional isError as unreadable/unestablished; generated failures throw. Parseable unsupported evidence remains the original JSON with caller-supplied unestablished evidence.+- Original checkpoint callbacks propagate unchanged, including callback errors that happen to share parser error types. Checks run at parser entry, every 256 consumed bytes and completion; no deadline is created or renewed.++Interface adjustment: parser/source facade checkpoint arguments are now `@escaping @Sendable` so the synchronous scanner can own the callback while parsing. No callback is retained by the document, source or any frozen fragment. Presentation and encoder bodies remain placeholders for their later RED/GREEN tasks.++Validation completed: targeted SwiftLint with `--strict --no-cache`, Swift parsing, and standalone Swift 6/default MainActor typechecking of source files plus the unchanged Swift Testing fixtures using Xcode's Testing framework/plugin.++First focused GREEN attempt at `31bc425`: make exited 0, Test Succeeded; xcresult reports all 23 declarations passing, no failures (50 expanded runs passed). Artifacts: `.codex-cache/source-green.log`, `.codex-cache/source-green-summary.json`, `DerivedData/Logs/Test/Test-Transit-2026.10.03_22-00-59-+1000.xcresult`. The pipeline/test host drained and the slot was released.++Parallel review identified an actual construction blocker: the synthesized internal memberwise source initializer could bypass source-kind/text/document invariants. A private initializer now restricts construction to same-file factory paths. Its assignments are identical to the synthesized initializer; runtime behavior is unchanged.++Parent explicitly authorised final access-only verification without another heavy run: full pure Results/Protocol modules plus the unchanged Swift Testing fixtures passed standalone Swift 6/default MainActor typecheck (exit 0). An external-file constructor attempt failed compilation (exit 1) specifically with `MCPResultSource initializer is inaccessible due to private protection level`; `.codex-cache/source-constructor-negative.log` records this expected negative check. Targeted parse/lint also passed. No app test at the access-fix commit is claimed; actual final consumers remain covered by later integration compilation.++Executed focused command at `31bc425`:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPJSONDocumentTests TransitTests/MCPResultSourceTests'+```++No shared MCP files, read publication/stores, coordinator, receipt formats, canonical request/revision algorithms, model normalizers or client settings changed. Common API task 15 remains undelivered.
diff --git a/specs/structured-mcp-results/source-red.md b/specs/structured-mcp-results/source-red.mdnew file mode 100644index 0000000..a52bb40--- /dev/null+++ b/specs/structured-mcp-results/source-red.md@@ -0,0 +1,27 @@+# Task 2: source/parser RED evidence++Parent granted the exclusive focused test slot on 2026-10-03. Run from the isolated `stream/structured-results-1` worktree at test commit `498d515`:++```sh+make test-quick TEST_TARGETS='TransitTests/MCPJSONDocumentTests TransitTests/MCPResultSourceTests'+```++The build and test launch succeeded. Make exited 2; its xcodebuild pipeline reported Error 65 and `TEST FAILED`. The result summary reports 16 test declarations: 15 failed and 1 passed. Including dynamic arguments, the device/configuration reports 41 failed runs and 1 passed run; two tests used 28 parameterized runs.++Expected behavioral failures are demonstrated by the result bundle:++- Valid JSON/source cases caught `.notImplemented`, including distinct composed/decomposed keys, exact number/UTF-8 evidence, plain text, malformed retained JSON and unsupported retained payload preservation.+- Invalid JSON/UTF-8 cases expected `.invalidJSON` but received `.notImplemented`.+- Original worker cancellation cases expected `MCPJSONCheckpointFailure.cancelled` but received `.notImplemented`. The repeated checkpoint assertion also showed the placeholder never invoked the worker check.+- The seeded valid-value property recorded seed 0 and minimized the failing case to `[]`.+- The independent shrinker test passed.++There were no compiler failures or test-launch failures. No GREEN implementation was present or started. The test pipeline and its host drained before the slot was released to the next sequential run. Existing unrelated installed Transit app processes were left untouched.++Local ignored evidence:++- `.codex-cache/source-red.log`: complete command output.+- `.codex-cache/source-red-summary.json`: extracted xcresult summary.+- `DerivedData/Logs/Test/Test-Transit-2026.10.03_21-29-37-+1000.xcresult`: result bundle.++Task 2 is complete as a RED task. The same tests remain unchanged for task 3 GREEN. Depth-limit assertions are held pending the separate bounded-tree design refinement; that does not invalidate this demonstrated baseline RED.
diff --git a/specs/structured-mcp-results/subscription-red.md b/specs/structured-mcp-results/subscription-red.mdnew file mode 100644index 0000000..1ec0916--- /dev/null+++ b/specs/structured-mcp-results/subscription-red.md@@ -0,0 +1,37 @@+# Task18 subscription RED preparation++Task18/gpzncw2 is in progress after completed task17/gpzncw1. This package prepares runtime RED coverage for the approved latest-only subscription contract. It does not implement subscriptions or establish actual compiled/test counts. No build, app test, private listener, installed-client probe or settings change has run during this preparation; T2384 owns the heavy slot.++Four owned test/helper paths replace the two legacy suites and add request-scoped transport/lifecycle fixtures. The provisional source inventory is18 declarations/34 parameter-expanded cases in three suites: notification8/11, route8/19 and lifecycle2/4. The existing lifecycle helper is compiled as a dependency but its original suite is not selected. A scheduled run must verify exact compiled inventory before executing bodies.++Coverage includes valid modern POST/ID/metadata/header/SSE negotiation and transport rejections; acknowledgement before a512-change pre-consumption burst; coalescing without ack eviction; original string/integer IDs, including repeated IDs on independent requests; supported-only filters, empty/false/unsupported filters and unchanged availability assignments; cancellation separate from channel disconnect; writer failure and no further delivery; correlated complete responses on stop, restart, port change and current-generation listener exit; stale listener callbacks preserving replacement streams; and an injected capture counter plus unfinished-worker count proving open subscriptions do not capture storage or consume covered-read admission. Synthetic listeners use ephemeral loopback ports and the owning in-memory test environment. They do not connect to the production listener.++Source review corrected four fixture gaps before readiness: channel setup is protected by loop cleanup; cancellation-only assertions precede channel close; teardown waits are bounded and fallback teardown is separate from the tested unregister trigger; and zero worker count is paired with explicit capture evidence. Async NIO test channels/loops and response bodies are fixture-owned.++The actual current route validates subscriptions but returns501. Valid subscription cases should therefore fail at that route boundary, while existing malformed/filter/header/method controls should pass. Deeper queue/lifecycle assertions are future GREEN obligations; they are not claimed reached or passed by source inspection. Compile failures or incidental fixture issues must be classified separately and cannot satisfy RED.++The local packet is `.codex-cache/task18-subscription-red-preparation/guarded-commands.json`. It prepares a serial signed unit-only build with installed resolved packages and fresh SubscriptionRed bundles/plist/labels, verifies the isolated host, enumerates exact selected declarations, then runs only the three suites. All earlier task17 evidence remains preserved. Actual command exits, body counts, unknown/global issues, NIO diagnostics, finalized-result status and runner/host drain must be reported after the parent grants the exclusive slot.++Task19 Settings forwarding remains a coordinated T63 edit: retain its existing private broadcaster and availability observer, supply request registration through that owner boundary, and preserve read lifecycle/admission. No duplicate observer, session engine or storage capture is proposed. The accepted common server/router/broadcaster/handler paths belong to T2383; owner-retained files remain untouched.++Installed-client readiness is a separate prerequisite described in [prerequisites.md](prerequisites.md). Parent must identify intended Codex surfaces and authorise each isolated synthetic endpoint connection, with Claude Code and Claude Desktop also required. No exact runtime flag/configuration change is proposed without actual evidence. Missing real-client traces keep AC6.3 and activation open without blocking subscription implementation or delivered API15.++## Final recovered source checkpoint++Fixture source commit: `4366824782a417073166ba0f61d16ed2e41425ad`. Saved source checks exited0 for syntax parse, strict no-cache lint and diff validation. The independent final critic cleared the exact committed source and command packet. Root independently verified all515 pinned source inputs with zero mismatches and exact committed bytes for all four fixture paths; retained Settings bytes are unchanged. Guarded command packet SHA256: `762db0f27371380a43c3b4a809d7d73ffed0606947e5574f3336c16fc3769531`.++The coding delegate's usage interruption occurred after the fixture commit and final source pin had been written. On the owner's resume instruction, the same delegate and root inspected the worktree/index/log state; no app commands were duplicated, source or historical evidence rewritten, or new tests started. Both read-only owned-process checks found no SubscriptionRed runner or exact private host. All delegate responses are collected. The prior72+113+37 task17 artifact hashes still match independently.++The recovered package is ready for the parent's next-slot scheduling after T63 confirms the last heavy run drained. Task18 remains in progress and tasks19–22 remain behind its meaningful runtime RED. This is resource coordination, not a new implementation approval gate or an installed-client blocker.++## Actual task18 runtime acceptance++Parent granted the exclusive slot and narrow reviewed fixture compile corrections. Three actual builds exited65 before host/preflight/inventory/test bodies: missing defining-module imports in lifecycle/notification fixtures, then a failable HTTP method initializer. Exact corrections changed imports and required method unwrapping only. Their immutable caches retain36+37+31 artifacts; root independently verified all104 hashes. No failed build is claimed as RED.++Tested source `3abdf24ad296311e860f8abcc7df56494f120e6d` passed515-input source guard, build, signed private host preflight, enumeration and exact18-declaration inventory. Command packet SHA256 `6851f0aeefd49c9641646595288540813f111937d33e313c654d5dda134626af`. Actual serial execution reached18 declarations in3 suites and34 expanded bodies. Seventeen issues comprise16 intended current-route501 failures and one existing Forbidden plaintext oracle mismatch. No unknown-context issue or NIO misuse matched. Six control declarations/17 bodies passed; deeper acknowledgement, coalescing, lifecycle and admission checks are masked by501 and remain GREEN obligations. Internal critic cleared meaningful feature RED.++After console summary, finalization stalled. Both exact runner63202 and private host63247 were successfully sampled before identity-verified runner-first TERM; the host then exited without a separate signal. Delegate and root independently confirmed both absent; RELEASE preceded extraction. Actual test exit143, no test Info.plist, summary extraction64. This is console/body evidence, not a finalized result bundle. Root independently verified all60 final runtime artifact hashes. See `.codex-cache/task18-subscription-red-method-unwrap-fixed/results.md` and `actual-results.json`.++Post-drain `9f2eb39` corrects only the forbidden-origin oracle to the existing exact plaintext response while preserving status/non-RPC rejection. Parse/lint/diff passed and internal critic cleared it; corrected source was not rerun. Tested3abdf24 and all failed-attempt artifacts remain intact. Rune18/gpzncw2 is complete;19 is next ready,20–22 remain dependent. No task19 implementation or additional heavy run was started.++Exact T63 Settings getter from owner4826658 was imported after drain in `fe497b6`, with patch/before/after hashes verified. It returns the existing private broadcaster and adds no storage or availability observer. T63 Task15 diagnostics component handoff is blocked because its patch starts at a Task14 scaffold absent here (Diagnostics.swift, ContractTestSupport.swift and coordinator/service API). Handler/App hunks pass apply checks and preserve routing/plumbing, but must wait for a complete recipient-base selective handoff. No forced partial application or blind file overwrite occurred. The adjacent READ_FAILED wire code gap remains a T63-owned coordinated repair.
diff --git a/specs/structured-mcp-results/subscription-settings-owner-request.md b/specs/structured-mcp-results/subscription-settings-owner-request.mdnew file mode 100644index 0000000..de18f39--- /dev/null+++ b/specs/structured-mcp-results/subscription-settings-owner-request.md@@ -0,0 +1,50 @@+# Current verification status++The source-only blockers below are historical: exact Settings cleanupb94fb1e is delivered, task19 finalized77/109 PASS, task21 real fixture2/2 PASS and task22 local81/116 PASS. Installed-client AC6.3 remains open. See local-verification-handoff.md for actual current outcomes; all older preparation evidence remains preserved.++# T63 bundled Settings request for task19++Prepared against subscription RED fixture4366824 and handoff f40dfb3. Task18 remains in progress; this is an owner coordination request, not task19 implementation or a new approval of its gate. Keep the reviewed RED source and its515-input/command pin unchanged. Current queue: T63 corrected13-body RED → T2384 task8 GREEN → T2383 task18 RED → T2382 full-platform work.++## Exact retained file and minimal first seam++T63 remains sole writer of `Transit/Transit/MCP/MCPSettings.swift`. Current recipient SHA256: `c2fe9f43e2283c792a98691d349da34ff7fe5dcb3545e5fb23e2c5a40d1cf062`. Its private broadcaster is the actual object notified by `maintenanceToolsEnabled.didSet`; the handler cannot independently substitute another broadcaster.++Please deliver one getter through an exact single-file owner patch, with pre/post hashes and source commit:++```swift+@MainActor var subscriptionBroadcaster: MCPToolListChangeBroadcaster {+ toolListChangeBroadcaster+}+```++This is a proposed internal getter of the existing type, not a new stream/envelope type or guessed serializer API. It returns the same existing object on every access, introduces no storage, and has no setter. The existing private stored property stays private. Current observer, locked nonisolated availability snapshot, persisted preferences, defaults and init behavior remain unchanged. The accessor can be prepared by T63 independently of task19, but will not be imported into the pinned RED checkpoint before its run. No heavy build is requested for this request preparation.++If T63 prefers a narrow registration forwarding method instead, agree its exact signature after T2383 delivers the request-registration type; do not invent an additional Settings stream engine. The getter is the minimal bridge that compiles against the currently existing broadcaster type.++## Bundle the later compatibility cleanup++Task19 migrates the broadcaster to per-request registrations. Its registration accepts the validated original JSONRPCId, supported requested tools filter and actual channel-close future; same RPC IDs on separate requests remain separate registrations. The router/handler uses the above getter on MainActor. Accepted filters, ack staging, bounded coalescing, prepared notification/complete bytes and SSE delivery stay with T2383's existing owned broadcaster/server paths. Settings continues feeding exactly that object from the same observer. No read capture or admission is added.++The later import must be bundled with removal or migration of legacy source references so every compiled test still builds. Actual current references:++- Settings `createToolListChangeSession`, `toolListChangeNotifications(sessionID:channelClose:)`, `finishToolListChangeSessions` and `activeToolListChangeStreamCount`.+- T2383 handler forwarding and the old server notification response helper.+- T2383-owned `MCPModernBindingTests` availability test still consumes a legacy session stream; migrate its notification observation to the modern request path while preserving all frozen classification/availability assertions.+- The new task18 suites use the existing finish/count hooks for shutdown and cleanup; keep their names as forwarding aliases if useful, with request-scoped semantics and no session state.++T2383 must supply exact final symbols and common commit before requesting a T63 cleanup patch. T63 owns the Settings patch only; T2383 owns its common callers and test migration. Deliver a complete import set together, not a Settings file that references unavailable symbols or a broadcaster that leaves compiled callers broken. Neither retaining old wire/session behavior nor a second observer is part of this request.++## Lifecycle changes outside the Settings file++T2383's owned server hook will finish request streams even when there is no active listener and on current-generation listener exit. Stale generation completion must preserve replacement streams. Existing T63 readCoordinator stop/start, admission transitions, generation ordering, physical permits and the graceful listener release fence remain intact. T63 may review this narrow subscription delta; it is not a request to widen read deadlines or change its publication engine.++## Handoff and evidence++Parent routes this document to T63. Return exact patch/commit, recipient pre/post hash, ownership statement, and any collision with active T63 source. Integration waits task18 meaningful RED and a coordinated common/Settings bundle for task19. Selected task18/19 fixtures must establish ack-first, filters/correlation, no capture/admission, writer failure/disconnect/cancel cleanup, stop/restart/port-change and current/stale listener behavior. No live settings or real-client action is requested here.++## Task19 follow-up owner cleanup++The exact same-object getter was imported in fe497b6. Task19 removes the unsupported session engine from owned broadcaster/handler/transport paths and migrates the old availability fixture. It requires T63's retained Settings file to remove only its two unused forwarding methods: createToolListChangeSession and toolListChangeNotifications(sessionID:channelClose:). Keep subscriptionBroadcaster, finishToolListChangeSessions and activeToolListChangeStreamCount forwarding to modern request registrations; keep the existing availability observer, locked nonisolated snapshot, defaults and persistence unchanged. No transitional create-session stub is proposed.++Exact un-applied proposal: `.codex-cache/task19-subscription-source/settings-legacy-forwarder-cleanup.patch`. Patch SHA256 f86de63a2c649cd05bef62c6a23e72e224c45728838612f669662ed3ace0753a; before SHA25613cc27828c387fe4e62ce987ae593912ae61ae57d0e6096c3a6117f4dfcd3238; proposed after SHA256a9a5be9884ea481747458c70c52683a75a10d30072060564c7b471d1755d0009. Scope is14 removed lines in the two methods. Internal critic recommends exact owner cleanup instead of retaining a fake session namespace. Root will consume an exact T63 handoff; retained Settings has not been independently edited. This is source coordination before GREEN compilation, not a client setting change or activation.
diff --git a/specs/structured-mcp-results/t63-diagnostics-handoff.md b/specs/structured-mcp-results/t63-diagnostics-handoff.mdnew file mode 100644index 0000000..0156bc9--- /dev/null+++ b/specs/structured-mcp-results/t63-diagnostics-handoff.md@@ -0,0 +1,13 @@+# T63 diagnostics source handoff++Exact coordinated integration commit: bd5c42a. Owner production source fa58dc0; recipient base74cbabf. Applied the recipient-based12-production-path diagnostics component, patch SHA25639b75a65c8594b4b948fccae6ca53219c05e043d66b48fed42792f114f4e0781, after independently verifying all12 preimages/new-file absences. Then applied the separate approved Handler initializer hunk (SHA256001470703c9e31b7af003cf95bef8db186050e49b5bcdc9be0fd6edada82d961) and parent-designated single App constructor hunk (SHA25659f12a521233808b4377990daa18a59e19cc17c1fa117a627876695e1d17dd51). All14 post-image hashes matched before commit. Evidence: `.codex-cache/task19-root-review/t63-diagnostics-import-verification.json`. Internal critic cleared preservation of modern pagePreparer, original operation/checkpoint/constant encoder and opaque prepared carrier.++The earlier component patch could not apply because it assumed a missing Task14 diagnostic scaffold. That failed read-only apply check and the owner-supplied recipient repair are distinguished; no forced partial application or blind source overwrite occurred. No diagnostics test/helper source, READ_FAILED GREEN patch, activation or client configuration was imported. Task19 source changes subsequently share the Handler file but preserve the exact diagnostics initializer.++Runtime compilation/acceptance remains pending; no App launch or heavy command was run for this import. T2382 currently owns the verification slot. T63 owns diagnostics RED/GREEN fixture delivery and its adjacent catalog failure repair; T2383 has not inferred new error semantics.++## READ_FAILED generated-JSON origin confirmation++For the proposed new get_projects/query_milestones READ_FAILED JSON error payload, default/nil MCPResultProviderEvidence is correct: the existing common read adapter supplies generatedJSON origin and established evidence. Retain original isError=true and complete failure metadata. The adapter derives supplemental storageFailure, serializationFailure or incoherentCapture from the unchanged semantic failure metadata; it does not need a new category inferred from READ_FAILED or a common serializer change. No successful capture metadata should be fabricated. Retained JSON receipts and plain-text failure origins remain distinct.++The parent subsequently reported meaningful fc2096d RED (1 declaration/6 cases) with an unfinalized-result limitation. Exact owner GREEN source d2648f6 was imported in21356d5 after patch/pre/post hash verification for its two files. It adds JSON READ_FAILED only for project/milestone execution faults and updates read guidance, preserving query failures, semantic metadata and diagnostics. Runtime GREEN remains pending; the parent plans the six fault cases plus13 diagnostics bodies after its queued jobs. This confirmation/import is not runtime closure.
diff --git a/specs/structured-mcp-results/task17-handoff.md b/specs/structured-mcp-results/task17-handoff.mdnew file mode 100644index 0000000..1328ae0--- /dev/null+++ b/specs/structured-mcp-results/task17-handoff.md@@ -0,0 +1,20 @@+# Task17 frozen read handoff++Task17/gpzncw1 is complete for the selected coverage. Common factory0af0bfc, T63 ordinary componentbf5191b plus actor fixture correction4ee79a4, and T2382 reusable component95b416aa/final wiringc7dcb9a plus discovery oracle correction2232409 are integrated. Final tested source: ec1b72136853a3b45587fb387feb382b58a83ec3. Shared-file ownership remains with its recorded owner; no producer schema or receipt format changed to satisfy the fixture.++The common prepareReadPages callback receives the original operation and prepares all private pages before owner reservation, sharing metadata by actual owner identity. Attached pages remain authoritative. The delivered opaque MCPPreparedToolRead(preparedResultPage:frozenMetadataBytes:publications:) carrier keeps the sealed fragment and original publication pins; continuation encodes only the new RPC wrapper. Ordinary and reusable owners perform bounded source comparisons and expanded accounting through the original operation. Terminal root/cursor/expiry pins validate before selection; the existing publication engine selects complete success/failure bytes. Separate ordinary/reusable limits, original deadlines, physical worker permits, frozen text/policy/metadata, and comment-covered r1 when bodies are omitted are preserved.++Acceptance combines two actual runs, not one finalized 61-body run:++- Source66cca07: build, signed isolated host preflight, enumeration and exact inventory all exit0. All54 declarations/61 bodies in14 suites ran.53 declarations/60 bodies passed; one discovery method recorded two stale schema-oracle issues. Unknown-test issues0 and NIO misuse0. Console proof only: test143 after both exact runner/host samples and bounded cleanup; result unfinalized, summary64. Both processes drained and slot released before extraction.+- Sourceec1b721: only that owner discovery assertion changed. The actual discovered selector was verified and run alone. Build/preflight/enumeration/inventory/test/summary all exit0; finalized1 passed,0 failed,0 skipped, runtime warnings empty. Normal drain, no cleanup signals or repeat. Root independently verified runner absence and no guarded private host remaining. Source513 hashes unchanged; all72 focused artifacts and prior113+37 artifacts independently rehashed with zero mismatch.++The repaired assertion verifies the approved structuredContent VALUE schema (contractVersion/source/presentation, required fields, closed root and version1), preserving input/rejection/no-capture checks. Separate unstaged owner replay-assertion work was excluded. No full61 rerun, live/client activation, settings change, push, merge or deployment occurred.++Evidence relative to this worktree:++- .codex-cache/task17-focused-discovery-oracle-green/results.md, actual-results.json, artifact-sha256-after-run.json and final-owned-drain.json+- .codex-cache/task17-combined-retention-green-fixture-isolation-fixed/results.md, actual-results.json, body counts, samples, cleanup and extraction records+- .codex-cache/task17-combined-retention-green-preparation/results.md retains the initial compiler65 before preflight/tests and exact actor-fix provenance++No selected task17 coverage blocker remains. Actual client-readiness evidence belongs to the later approved gate and is not claimed here. The existing owned modern Boundary test supplies full modern fallback proof; the T63 cursor-pin regression's legacy constant-error fixture caveat remains documented and does not alter this producer contract.
diff --git a/specs/structured-mcp-results/task17-owner-runtime-handoff.md b/specs/structured-mcp-results/task17-owner-runtime-handoff.mdnew file mode 100644index 0000000..08058b3--- /dev/null+++ b/specs/structured-mcp-results/task17-owner-runtime-handoff.md@@ -0,0 +1,29 @@+# Task17 owner runtime handoff++Task16/gpzncw0 meaningful RED is complete at source `936d10bd178ac28e42e3f34712310c693940a2a5`. Task17/gpzncw1 can proceed under the approved scope. This handoff requests parallel owner implementation, not another approval gate. Shared ownership remains unchanged.++Actual build, signed isolated unit-host preflight, enumeration and failclosed exact inventory all exited0. All37 declarations/40 argument-expanded bodies ran in8 suites; console67globalissues establish intended missing preparation/retention/binding behavior. Existing capture/history/comment/serialization, explicit missing-selector/storage, parser/forwarding/cancellation, carrier/provider and physical-permit/restart/race controls passed. Detached owner issues are recorded under unknown test context; method PASS labels do not establish retention or sharing success. Assertions behind missing seams remain GREEN obligations. No NIO misuse was observed.++Test runner exit143 after finalization stayed active; both exact runner85923 and isolatedhost85928 sampled successfully before verified runnerTERM. Host drained without signal; both independently absent. Slot released before extraction. Unfinalized result bundle lacks Info.plist, summary64; evidence is console-based. No finalization-only repeat is required.42final evidence hashes verified; original43/22failed-attempt artifacts unchanged.++Read-only evidence, relative to this worktree:++- `.codex-cache/task16-combined-retention-red-owner-fixed/results.md`+- `app-actual-results.json`, `app-actual-commands.json`, `body-inventory-observation.json`, `compiled-inventory-verification.json`, `artifact-sha256-after-run.json` in that same directory+- Source pin/15critical SHA manifest: `source-manifest.json` in that directory. This is not authorisation to overwrite retained owners.++Parallel scopes:++- T2383 implements existing `MCPModernProviderBinding.prepareReadPages` and owned modern read binding: all private pages, shared frozen original metadata owner, explicit provider origin, exact source text/isError and category, authoritative attached fragments, new RPC wrapper only for continuation, original operation checkpoints. Factory errors must abort whole preparation. No new clock/admission/publication engine.+- T63 retains Reads/admission/capture/ordinarystore/handler captured/portfolio preparation. Implement private-page preparer integration before any reservation, prepared ordinary snapshot lookup and expanded accounting; consume attached page fragments through existing encoder/publication gate and original operation. Keep all complete response and publication selection inside the existing atomic offering protocol.+- T2382 retains reusable Store/Index/ReadPin and reusable/portfolio read service. Implement prepared create/append/lookup/pin/expandedbudget, first-response owner retention even with zero cursors, original summary owner preservation and retirement charges. Existing base sharing with additive union-minus-original charge is supported; shared NEW sibling/root owners must reject before transfer, at reservation or aggregate stage. Exact imported owner fixture late-only assertion needs owner correction if lawful rejection occurs at reservation.++Both retained stores preserve five-minute/eight-snapshot/16MiB independent limits; accounting includes all retained compatibility Data/meta copies not measured by the modern owner ledger, with no double charge for actual shared owner identities. Existing original five-second/eight-physical invariants, canonical comment-covered r1 when comments omitted, frozen cursor revision/policy/expiry and text payload compatibility remain.++The coordinated GREEN handoff also includes mapping common retention-capacity failures to existing typed capacity outcomes and operation-aware aggregate owner-union measurement through the original operation checkpoint. The proposed owner overload must not extend the deadline or introduce shared gate changes. These agreements are already relayed by parent; do not invent a new approval gate or serial late integration dependency.++Owner fixture sync: imported T2382 `MCPReusableSnapshotPreparedOwnerTests.swift` requires an inner `try` inside `#require` around throwing adapter metadata. Exact one-token patch imported in936d10b under parent's incidental correction authorisation; fileSHA256 `722144dcd884dac4033da1b5b4cf3e49af7e413b34469c3d00009fec04456d20`, patchSHA256 `12d6ede64c91fd31ff8cc1a256af87dffdfe199428a910fc435596c5c84b0c75` at `.codex-cache/task16-targeted-typecheck/owner-inner-try.patch`. Error propagation/assertions unchanged; owner retains further edit ownership. The11-file targeted frontend overlay passed before exact import; actual owner-fixed app build now also passed.++No task17 production implementation or further runtime has started in this handoff. T2384's DELIVERED15 consumer remains independent of whole-ticket completion.++Common source is now delivered for coordination at `0af0bfc1da9538a384807678cffec9192c91b8de`: exact two-file patch and ABI/source SHA manifest in `.codex-cache/task17-common-source/common-factory-read-binding.patch` and `owner-handoff.json`. Internal critic/parse/strictlint passed, bounded four-actual-source typecheck passed (compileprobe only). Callback signature is unchanged; T63 installs it in owned ReadAppDependencies. No retained-owner production file changed. Actual17 combined GREEN still waits exactowner patches and one scheduled slot.
diff --git a/specs/structured-mcp-results/task17-t2382-review-findings.md b/specs/structured-mcp-results/task17-t2382-review-findings.mdnew file mode 100644index 0000000..7e7b886--- /dev/null+++ b/specs/structured-mcp-results/task17-t2382-review-findings.md@@ -0,0 +1,17 @@+# T2382 task17 package review++Exact reviewed source e7a4676eba0b4ef8ad5a5a5ebb4a706c0e4aeb6c, sevenfilepatchSHA256e13eb3ec92660236f49e52899c93ba658ccd79bf579f46548dfea6812b7df24c. Readonlyapplycheck passes. Accounting/provenance context fixes reviewclear: one canonical preparedowner union, visible-root replacement credit preserves other-root/pending costs, original rawcapture/Data/meta base accounted once, newowner overlap rejected pretransfer while existingBASE sharing remains additive; originaloperation aggregate remeasurement precedes unchangeddomain transfer and rootpins remainattached. Source import does not establish runtimeGREEN.++Coordinate the following before combined verification, with no newuserapprovalgate:++1. In reservePreparedAppend/validateOwners, full `Data(page.source.originalText.utf8)` comparisons and full metadatawrapper construction need bounded exact UTF8/Data validation under SAME originaloperation. No newclock, contentnormalization or ownershipinference.+2. Summary replay/continuation and SnapshotTaskQuery continuation replay still construct `MCPPortfolioReadEncoding.prepared(rawpage,rawmeta)` then attach sealedowner. This decodes legacytypedmetadata and rebuildstoolbytes before opaque frozenfragment delivery. Once the T63 exactopaquecarrier ABI is imported, use `MCPPreparedToolRead(preparedResultPage:frozenMetadataBytes:publications:)` directly with existingrootpin/publications; no reparse/metadatareclassification/receiptrewrite.+3. Four modernroute acceptance suites are absent from recipient: MCPPortfolioModernAcceptanceTests, MCPPortfolioIntegrationTests, MCPPortfolioRouterExpiryTests, MCPPortfolioRouterDeadlineTests (12declarations total). They depend on exact MCPPortfolioModernHTTPHarness.swift. Recipient already has exact generic/portfolio/container/fallback helpers. Include exact owner fixture/harness package and explicit pagePreparer wiring in fixtures that manuallycreate MCPReadService; productionReadAppDependencies wiring does not affect those constructors. Preserve full final modernRPC/tool/text/structured/metadata bytes beforegate and existingNIO lifecyclecleanup.++Owned T2383 fixture correction is committedba9479a: move same frozenmetadata count into encodedCaptureByteCount per fieldcontract, remove separate addition so expectedtotal unchanged; two modernsiblingaggregatecalls use SAMEoriginaloperation overload. Assertions/legacycontrols unchanged, parse/strictlint/diffchecks0, independentcriticclear. No owner sourceedit performed by T2383.++Common source0af0bfc/patch1c0af2d9073590d64216fdfc8370df2a3aded146b249ecb6f9603fbd85bb9961 available in .codex-cache/task17-common-source/; callbackABIunchanged. Root will collect exact owner revisions for one pinnedcombined verification, no heavyjob while T1734 holds slot.++Revision review: owner commit `95b416aa5c1cd6cc7c12ff4045f289e5331a2fed` resolves item 1. Exact text comparisons traverse existing UTF8/Data backing; metadata uses a lazy joined sequence of three segments. Independent internal critic cleared original-operation checks every 256 bytes, mismatch/end/empty-length handling, and unchanged accounting. This is source review only; no import, compile, or runtime claim. Items 2–3 remain pending owner delivery.++Final wiring revision `c7dcb9a0f48a3f0355478752055fef38a0aa5e81` resolves items 2–3. Exact seven-path package imported as `2e37a8a`, all hashes verified. Three replay branches use authoritative opaque sealed carrier with original metadata/pins; four manually created services forward the original operation to common preparer. Four route suites and existing HTTP harness are now present. Independent critic cleared source, fixture dependency/lifecycle/assertions, and new RPC-ID replay parity. No current owner integration blocker; final source pin, application compilation, exact enumeration, and runtime acceptance remain.
diff --git a/specs/structured-mcp-results/task17-t63-review-findings.md b/specs/structured-mcp-results/task17-t63-review-findings.mdnew file mode 100644index 0000000..955adf1--- /dev/null+++ b/specs/structured-mcp-results/task17-t63-review-findings.md@@ -0,0 +1,12 @@+# T63 task17 package findings++Read-only review of task17-ordinary-binding package/localcommit47cfb48270599b36b18e0f7e12d03c7b6908140e. RecipientproductionpatchSHA256bf02b746a70158be41cb84a60eca4441f1d807fa5a65f0a50f04fc5b439d1458 and fixturespatchSHA25624737309434f7234122c4f752bdab9d82729df2b8c8e7416b6c97090288450b6. Both applychecks pass against0af0bfc common implementation. No patch imported. Manifest status was empty at review; owner finaldelivery pending.++Two findings require owner coordination before the one combined GREEN build, not a newuserapprovalgate:++1. `MCPReadService.preparePrivatePages` verifies original versus prepared source with full `.utf8.elementsEqual`, checking originaloperation only before eachpair. Largepage traversal must check the same originaloperation in bounded chunks or use a source-preserving owner proof with bounded validation. No fresh clock or deadline reset.+2. `prepareRetainedPage` returns sealed ordinarycontinuation with publications empty. `retainedPage(for:)` validates root/version/expiry only duringlookup. If expiry/retirement occurs after lookup but before finaloffer, attachedfrozenbytes can be selected successfully with no retainedroot guard at terminalgate. Add owner scalarreadpin/lookup+attachment through existing MCPPreparedPublication/domain (like existing reusablepin), revalidating exact originalroot/cursor/deadline with no parse/traversal/destruction undergate. No newpublicationengine. Include actual afterlookup-beforeoffer expiry/retirement race evidence with distinct preencodedfailure, operation stilladmitted, no expiredsuccess.++Other reviewed boundaries are aligned: opaque sealedcarrier avoids legacymetadata decode, allprivatepages callback precedes reservation, first+continuationowners retained, rawcompatibilitymetadata added exactlyonce to rootcharge, originalexpiry/policy preserved, typedcapacity mapping present. New3declarations/4bodies are focusedownercoverage, not runtimeverified; exactfixturedependencies exist locally. Existing late-only sharedroot rejectionfixture need not force that stage if safeearlier rejection is chosen.++T2383 common source0af0bfc exact ABI/patch is in `.codex-cache/task17-common-source/owner-handoff.json` and `common-factory-read-binding.patch`. T63 retains all6sourcepaths and newordinary helpers; T2383 will import exact revisedownerpatch without duplicating writers.
diff --git a/specs/structured-mcp-results/task19-handoff.md b/specs/structured-mcp-results/task19-handoff.mdnew file mode 100644index 0000000..24482a3--- /dev/null+++ b/specs/structured-mcp-results/task19-handoff.md@@ -0,0 +1,30 @@+# Current verification status++The source-only blockers below are historical: exact Settings cleanupb94fb1e is delivered, task19 finalized77/109 PASS, task21 real fixture2/2 PASS and task22 local81/116 PASS. Installed-client AC6.3 remains open. See local-verification-handoff.md for actual current outcomes; all older preparation evidence remains preserved.++# Task19 subscription source readiness++Owned implementation source commit868ed04: seven paths covering broadcaster, SSE response, modern routing, server lifecycle, Handler forwarding, subscription fixture and availability-binding fixture. Strict no-cache lint, Swift frontend parse and diff check passed. Independent internal critic cleared source semantics and reviewed the small installed ResponseBodyWriter API probe (inout mutation/cancellation closure usage only); this is not a Transit build or runtime GREEN.++Each modern POST has a UUID registration independent of its original string/integer RPC ID. Acknowledgement and terminal result are immutable frames outside the single coalesced invalidation slot. Supported requested toolsListChanged filtering, original-ID metadata and no session grouping are retained. Whole-body cancellation unregisters even during a blocked writer, writer failure/disconnect unregister idempotently, and server finish sends correlated completion when writable. A closing/reopening broadcaster fence prevents late validated requests registering while a replaced listener drains. Stop with no active listener and current-generation exit finish registrations; stale listener callbacks cannot close replacement registrations. Existing security validation, method rejection, read admission/capture and graceful listener/physical-worker rules remain unchanged.++Two narrow controls were added for blocked-ACK cancellation and close/reopen registration admission. Original18 RED declarations/34 cases remain preserved, including the corrected forbidden-origin oracle. The existing availability fixture migrates to an actual modern request and retains same-value/stored-availability checks. Proposed focused GREEN selection: four suites,25 declarations/41 expanded cases. Actual compiled inventory must prove this before execution. Fresh command/source packet is `.codex-cache/task19-subscription-green-preparation/`; no app command or GREEN body has run.++## Remaining prerequisites++T63 must supply/authorise the exact14-line removal of two unused Settings legacy forwarding methods; proposal and hashes are in subscription-settings-owner-request.md. The same-object getterfe497b6 is already imported. No fake session stub or independent retained Settings edit was added; full compilation is not ready until that cleanup is consumed. Final source pin and parent exclusive heavy-slot grant are required before actual build/preflight/enumeration/tests. Rune19 remains in progress;20–22 depend on actual19 completion.++## Separate integrations++T63 diagnostics component+approved Handler/App hunks were imported exactly inbd5c42a; t63-diagnostics-handoff.md records all14 verified postimages and generatedJSON origin confirmation. The parent reported meaningful focused catalog READ_FAILED RED with an unfinalized-result limitation; exact two-file owner GREEN source was imported in21356d5. Runtime GREEN remains pending.++The separate shared ordinary HTTP fixture helper migration is committed in4ddbfc8. It changes only async channel/loop ownership, preserving caller headers/body/defaults and assertions; success/error teardown checks channel cleanliness. Parse/lint/diff passed and internal critic cleared the exact helper; no runtime claim. Exact handback patch: `.codex-cache/task19-subscription-source/http-test-helper-async-channel.patch`, SHA256437ebfada08903f0f372f71bea6a611d92d8ec8ef8b7e637a14bd9fbf2590d99. Five modern fixture ports are separately committed405ffc7, preserving47 declarations/62 expected cases; see modern-fixture-handoff.md. A combined focused proposal is the exact9-suite union72 declarations/103 expected cases, not a full-unit rerun. Other full-run fixture defects remain owner-coordinated per fixture-coordination.md; no full-unit success is inferred.++No production App launch, client configuration/activation, external model turn, push, merge or deployment occurred. The held client approval scope is in client-readiness-approval-bundle.md.+++## Historical write lifecycle source delivery++Parent-assigned transport-only migration committed e00e9a0e28ecfb5f40f9c140ae22d24840693f55. Five declarations/six expected cases retain first commit, distinct-key duplicate-name rejection (accepted=true/two receipts), same-key argument conflict (accepted=false/one receipt), revision and missing-safety controls. Cancellation waits for actual allocator entry after durable acceptance using a bounded rendezvous; release/drain covers every path. New-responder replay checks rejected/accepted=true/CANCELLED, no created task, one receipt and exact saved resultJSON UTF-8 bytes. Coordinator and production sources are unchanged. Final source SHA2561017a043d588081d5bb9381b8b51215b1ce7d3017093be41ffdc2734b18d5ec5; parse0/strict no-cache lint0/diff0/internal critic SOURCE CLEAR. Root matched source bytes and retained five declarations. Evidence: `.codex-cache/task19-write-lifecycle-port/` and `.codex-cache/task19-root-review/write-lifecycle-verification.json`. No compile/runtime GREEN.++Historical focused selection is five declarations/six expected cases. Including it with the existing proposals yields ten suites/77 declarations/109 expected cases; actual compiled inventory must establish those counts. T63 Settings two-method owner cleanup remains missing, so guarded build preparation stays fail-closed. Parent schedules focused verification; latest reported heavy-slot owner is T1734. No new full run before focused cases pass.
diff --git a/specs/structured-mcp-results/tasks-review.md b/specs/structured-mcp-results/tasks-review.mdnew file mode 100644index 0000000..8aa8878--- /dev/null+++ b/specs/structured-mcp-results/tasks-review.md@@ -0,0 +1,74 @@+# Structured MCP results: task review++Status: Rune plan b58298a approved at Sentinel_ba4c6123288881918042d6aeb8ba6dc5; design approval recorded at Sentinel_717be95229c48191a7c41b6e5e467e4c. No implementation or task execution. Internal critic and two independent internal peers complete; no remaining task-plan blockers.++## Rune validation++Actual installed Rune created the list and applied44 atomic add/update operations. `rune list` renders22pending tasks, explicit streams/dependencies and no parser warnings. `rune streams --json` confirms stream1 for Results/shared integration and stream2 for isolated Protocol modules, both dependent on interface1. Task1 is the only internally ready item, still gated by owner task approval. Ten GREEN tasks immediately follow their RED partners; task1 is interface-only and22 test-only.++A lightweight checker read Rune JSON and Markdown stable-ID mappings: all27 acceptance anchors referenced;22pending/none claimed; ten adjacent RED/GREEN edges; every dependency resolves; DAG acyclic. No application lint/build/test ran. Intentional requirements double-space Markdown is excluded only by per-command whitespace checking, without config edits.++## Traceability++| Acceptance criteria | Tasks / proof |+| --- | --- |+| 1.1–1.2 | 2–7 source/encoder token preservation;14–15 every provider and saved normalization parity. |+| 1.3 | 8–9 actual descriptor export/2020-12 instance validation;14–15 published schemas;20–22 consumer evidence. |+| 1.4 | 2–9 raw text and collision-free source/presentation;14–15 historic output. |+| 2.1 | 4–9 validated source preservation;14–15 historic replay after edits/deletion without expiry/store rewrite. |+| 2.2–2.3 | 10–11 charged preparation;16–17 frozen ordinary/reusable pages, metadata and comment-covered r1. |+| 2.4 | 2–9 unsupported/malformed/contradictory evidence;14–15 reconcile and no fabricated replay. |+| 2.5 | 14–15 protected retry newRPCID/same original tool/key/arguments. |+| 3.1–3.2,3.5 | 4–9 source-only categories/recovery and documented schema/descriptor contract;12–15 protocol errors remain separate. |+| 3.3 | 2–3 generated parse failure;10–11/16–17 complete read failure/no publication versus explicit selector absence. |+| 3.4 | 6–7 ready-byte fallbacks before effects;14–15 protected postcommit, maintenance inner/final/delivery faults; T2384 synthetic seam, not batch execution. |+| 4.1 | 14–15 actual path-specific name/comment/description trim-clear/newlines at same-covered-r1; no new normalizer. |+| 4.2–4.4 | 4–5 source-position/UUID unavailable links;14–15 replay remains deterministic; no T572 navigation. |+| 5.1–5.4 | 12–15 stateless discovery/headers/modern dispatch/result/cache/schema;18–19 legacy-listener replacement;20–22 consumption. |+| 5.5 | 18–21 first acknowledgement/filter/correlation/coalescing/disconnect/teardown. |+| 5.6 | 12–15/18–19 loopback Origin/Host/format rejection before effects/capture. |+| 6.1–6.2 | 10–11 design volume risk;14–17 admission/invalid arguments/atomic full-byte publication/physical finalizers/expanded charges;18–19 stream cancellation. |+| 6.3 | 20–22 isolated fixture/verifier, actual intended installed-client evidence prerequisites; no settings/activation implied. |++## Integration order and external gates++Deliver new-file source/presentation/encoder/schema units3(gpzncvn),5(gpzncvp),7(gpzncvr),9(gpzncvt), then common integrated seam15(gpzncvz) after T63's recorded ownership handoff/provider regression fix. T2384's real consumer/registration waits for that **delivered commit/interface**, rather than design approval alone. T2383 final22 uses synthetic batch source/fallback and present provider registrations, with no dependency on production batch completion. T2384 confirmed it records this forward edge and no reverse edge.++Read integration16–17 remains T63/T2383/T2382-owned and never supplies a batch read deadline/publication. Pure Protocol12–13 can run independently of Results after interfaces1, but common wiring is serial. Parent controls shared ownership and heavy slot; all builds/tests wait for release. Dirty-context batch guards/fresh preview remain T2384-owned; T2383 tests adapter purity/saved source consumption without duplicating recovery or changing standalone acceptance semantics.++## Prerequisites and boundaries++`prerequisites.md` records schema-validator availability, shared-owner/test-slot release and actual client connection/modern-runtime changes requiring exact authorisation. Host Python lacks jsonschema; no package was installed. Installed modern client code remains insufficient evidence. Client prerequisites block readiness completion22/6.3, not common seam15 delivery. No circular cross-ticket dependency or external fake Rune task IDs were created.++The only design measurement risk maps to automated volume/budget RED10/GREEN11 before integration14–21. Limit failure remains deadline/capacity/no publication, not truncated success. Property-generation tasks2/4/6 define lossless/deterministic invariants; transaction/publication fixtures14/16 test failures that property roundtrips cannot establish. Every new subsystem reaches common wiring, with no orphaned provider/test harness.++## Supporting documentation completion gate++Documentation remains outside the coding-only Rune list. The T2383 implementation owner tracks these approved-design deliverables separately; common API15 delivery does not wait for final prose, but feature completion/final22 sign-off does:++- [x] Owner: T2383 implementation owner. After integrated seam15, create `docs/mcp-result-contract.md` from the approved design and delivered schema/fixtures: wrapper version/source/text/error presence, historic replay and frozen cursors, error/retry/reconciliation rules, path-specific saved normalization, UUID-associated unavailable links, latest-only lifecycle and client readiness. Completion evidence is the exact committed document matched to current descriptor/examples.+- [x] Owner: T2383 implementation owner. Correct obsolete initialization/session/GET/wire-array statements and examples in `docs/mcp-write-contract.md` and affected repository MCP documentation after modern wiring15–19; preserve application key/receipt/r1 semantics and distinguish the T2384 application batch. Completion evidence is the recorded documentation commit and a read-through against the final wire/receipt fixtures.++These are required deliverables for AC1.3/3.5/4.1 and the approved parity audit, not added production scope or main-list noncoding tasks. If missing, report feature completion blocked even if coding checks pass. T2384 owns its additional batch-specific caller documentation.++## Critic++No coding-sequence blocker: RED/GREEN ordering, parallel pure protocol stream, early capacity risk and forward batch seam accepted. Adopted completion-tracking finding: caller docs cannot be satisfied by schema fixtures alone; explicit T2383 owner/deliverables/commit evidence and feature-completion gate now appear above without adding documentation creation to Rune tasks.++## Task approval gate++Route through parent after required reviews and phone delivery: **Do the tasks look good?** The actual starwave-tasks skill requires explicit approval and limits this phase to planning artifacts; no task approval has yet been received. Implementation remains a separate authorised workflow. No settings, endpoint activation, push/merge/deployment or heavy test execution occurs here.++## Independent peer review and final disposition++Mode: internal critic followed by two independent internal subagent perspectives under the documented fallback; no external model service received repository/spec content. Correctness peer accepted source/replay/property/fault coverage, forward15 delivery and separate16–17 atomic reads. API/maintainability peer accepted independent protocol stream, no reverse batch edge, tooling/client gates and separate documentation completion tracking. Both validated the critic's adopted documentation finding.++Minor API clarification adopted in interface1: provide compiler-valid protocols/value constructors/minimal throwing placeholders so RED fixtures execute behavioral failures, not merely missing Swift declarations. Task count, streams, stable IDs and dependencies remain unchanged. No review divergence or unresolved task-plan blocker remains. Future implementation measurements and actual client readiness remain explicit gates rather than assumed successes.++## Implementation authorisation and ownership++Parent verified owner “Approved” at Sentinel_ba4c6123288881918042d6aeb8ba6dc5 in direct response to task-plan/implementation question. Proceed independent modules/interfaces; T63 common-file handoff and T2382 current heavy-test slot remain external gates. T2384 now owns MCPWriteCoordinator.swift/coordinator-specific tests until coordinated integration. No client configuration/activation or merge/deploy permission is added. Test-only schema tooling needs task/tool-policy authorisation in isolated environment; request routed through parent.++## Pre-push documentation completion++The versioned result contract and legacy caller-document corrections are supplied following source review fix9c41be6. Internal documentation re-review checked actual schema, classifier, normalization authority, protocol headers/statuses, frozen capture and listener/physical-worker distinctions. Both JSON examples parse. AC6.3 remains unverified and is owner-approved deferred post-merge (Sentinel_c0dbfe3212888191bc01744c855f67bb), not a compatibility pass. The exact documentation commit is recorded in the pre-push handoff.
diff --git a/specs/structured-mcp-results/tasks.md b/specs/structured-mcp-results/tasks.mdnew file mode 100644index 0000000..17fe191--- /dev/null+++ b/specs/structured-mcp-results/tasks.md@@ -0,0 +1,196 @@+---+references:+ - specs/structured-mcp-results/requirements.md+ - specs/structured-mcp-results/design.md+ - specs/structured-mcp-results/decision_log.md+metadata:+ approval: approved+ approval_evidence: Sentinel_ba4c6123288881918042d6aeb8ba6dc5+ ticket: T-2383+---+# Structured MCP results — implementation tasks++- [x] 1. Define immutable result and modern protocol boundary interfaces <!-- id:gpzncvl -->+ - Interface-only exemption: declare macOS-gated nonisolated Sendable MCPResultSource/context/presentation/recovery, lossless document and protocol request/availability input types under Transit/Transit/MCP/Results and MCP/Protocol; no runtime implementation or T63-owned common edits.+ - Fix callable source/presentation/complete-response/fallback descriptor signatures against approved design; nil/false/true error presence stays explicit. Support protected, synthetic application-batch and unprotected-maintenance recovery without new keys.+ - One stream owns result/shared integration; stream2 may implement isolated protocol modules after these interfaces. No task is claimed or executed until owner task approval; every build/test also waits for T63 slot release.+ - Provide compiler-valid protocol requirements/value constructors and minimal throwing placeholders where signatures require bodies; RED fixtures must execute and fail expected behavior rather than treating missing declarations/compiler errors as RED evidence.+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.4](requirements.md#1.4), [3.4](requirements.md#3.4), [5.2](requirements.md#5.2), [6.1](requirements.md#6.1)+ - References: design.md, decision_log.md++- [x] 2. RED: specify lossless source parsing and generated-versus-retained failure properties <!-- id:gpzncvm -->+ - Add MCPJSONDocumentTests and MCPResultSourceTests under Transit/TransitTests with Swift Testing; seeded nested UTF8/escape/decimal/exponent/large-integer/Boolean/missing-null generation plus shrinking; reject duplicate keys, invalid UTF8/escapes, trailing tokens and malformed numbers.+ - Assert original text and validated payload tokens remain exact. Malformed generated JSON must throw; malformed retained JSON preserves raw text/isError as unreadable/unestablished; plain errors remain declared text. Tests initially fail against declaration-only implementation, then run unchanged in task3.+ - Blocked-by: gpzncvl (Define immutable result and modern protocol boundary interfaces)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.4](requirements.md#1.4), [2.4](requirements.md#2.4), [3.3](requirements.md#3.3)+ - References: design.md, Transit/Transit/MCP/Results/MCPJSONDocument.swift, Transit/Transit/MCP/Results/MCPResultSource.swift++- [x] 3. GREEN: implement owned lossless JSON documents and source factories <!-- id:gpzncvn -->+ - Implement MCPJSONDocument.swift iterative parser and MCPResultSource.swift factories; preserve validated original fragment, member positions, unknown fields and number lexemes without Double/Any reconstruction.+ - Honor injected cancellation/deadline checks and retain private immutable backing; do not alter MCPCanonicalJSON or receipt validation. Make task2 examples/properties pass with no model/context access.+ - Blocked-by: gpzncvm (RED: specify lossless source parsing and generated-versus-retained failure properties)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.4](requirements.md#1.4), [2.4](requirements.md#2.4), [3.3](requirements.md#3.3)+ - References: design.md, Transit/Transit/MCP/Results/MCPJSONDocument.swift, Transit/Transit/MCP/Writes/MCPCanonicalJSON.swift++- [x] 4. RED: specify deterministic link, category and recovery presentation <!-- id:gpzncvo -->+ - Add MCPResultPresentationTests: documented task/project source positions, relationship pointers, conflicting display IDs, invalid UUIDs, unknown nested id fields, and deterministic repeat presentation after unrelated model changes.+ - Table-test all approved error categories, explicit provider phases, unclassified historic codes, unsupported/contradictory evidence, accepted/outcome/retryAction preservation and uncertainty precedence. Supplemental fields never overwrite colliding source names; no URI/navigation scheme.+ - Reuse task2 seeded source generator for deterministic presentation/collision properties, not only fixed examples; shrink unknown fields/positions while preserving the asserted identity/recovery invariant.+ - Blocked-by: gpzncvn (GREEN: implement owned lossless JSON documents and source factories)+ - Stream: 1+ - Requirements: [1.2](requirements.md#1.2), [1.4](requirements.md#1.4), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.5](requirements.md#3.5), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4)+ - References: design.md, Transit/Transit/MCP/Results/MCPResultAdapter.swift++- [x] 5. GREEN: implement source-only presentation and typed provider selectors <!-- id:gpzncvp -->+ - Implement MCPResultAdapter.swift selector tables and typed additional provider positions, validate each UUID against immutable source, preserve array ordering and deterministic pointer/type/UUID ordering.+ - Produce explicit unavailable links and supplement-only categories/recovery. Known receipt codes use validated provider evidence; no localized message matching, live reread, receipt rewrite, fresh-key escape from uncertainty or revision minting. Pass task4.+ - Blocked-by: gpzncvo (RED: specify deterministic link, category and recovery presentation)+ - Stream: 1+ - Requirements: [1.2](requirements.md#1.2), [1.4](requirements.md#1.4), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.5](requirements.md#3.5), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4)+ - References: design.md, Transit/Transit/MCP/Results/MCPResultAdapter.swift++- [x] 6. RED: specify complete response encoding and preeffect fallback selection <!-- id:gpzncvq -->+ - Add MCPResultEncoderTests for complete modern/text/structured/_meta/RPC bytes, valid request-ID correlation, exact optional isError, source fragments and safe surrounding JSON escaping.+ - Use synthetic protected/batch/maintenance sources to prove fallback bytes are fully deliverable before effects, failed preparation invokes zero effects, and later selection never calls any failed source/presentation/envelope encoder again. Batch fixture uses summary serialization_failed/effect evidence unestablished and original indexes/tool/key/UUID; no production mutate_tasks dependency.+ - Reuse task2 seeded source values to property-check full encoding: exact source/text presence and numbers survive wrapping, malicious surrounding strings cannot escape fields, metadata remains outside source; fixed transaction/fallback fault tests stay separate.+ - Blocked-by: gpzncvp (GREEN: implement source-only presentation and typed provider selectors)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.4](requirements.md#1.4), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [3.2](requirements.md#3.2), [3.4](requirements.md#3.4), [5.4](requirements.md#5.4)+ - References: design.md, Transit/Transit/MCP/Results/MCPResultEncoder.swift++- [x] 7. GREEN: implement complete result bytes and provider-owned mutation fallbacks <!-- id:gpzncvr -->+ - Implement MCPResultEncoder.swift validated fragment writer and complete immutable fallback preparation accepting provider-owned logical source/context/metadata. Retained tool fragments omit RPC ID; encode fresh outer IDs only.+ - Keep preencoded response selection separate from encoding; maintenance reconciliation carries no invented key, protected recovery preserves original tool/key, batch payload remains untouched. Pass task6; this new-file API is deliverable to T2384 without waiting for production batch wiring.+ - Blocked-by: gpzncvq (RED: specify complete response encoding and preeffect fallback selection)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.4](requirements.md#1.4), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [3.2](requirements.md#3.2), [3.4](requirements.md#3.4), [5.4](requirements.md#5.4)+ - References: design.md, Transit/Transit/MCP/Results/MCPResultEncoder.swift++- [x] 8. RED: validate structured output schemas across every source variant <!-- id:gpzncvs -->+ - Add MCPResultSchemaTests exporting actual generated descriptors/result fixtures to a test-owned temporary directory, plus tests/validation/validate_mcp_result_schemas.py host runner; app test processes do not read the host checkout.+ - Use a standards-compliant Draft202012 validator for schemas and instance fixtures: arrays/scalars/null, JSON/text/unreadable, success/errors, historical unknown names/types, missing/null/false, synthetic batch originals. Reject malformed wrapper/presentation and unreadable-with-payload variants; no network refs. Schema-tool prerequisite must be met before validation is claimed.+ - Blocked-by: gpzncvr (GREEN: implement complete result bytes and provider-owned mutation fallbacks)+ - Stream: 1+ - Requirements: [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [3.2](requirements.md#3.2)+ - References: design.md, Transit/Transit/MCP/Results/MCPResultSchemas.swift, tests/validation/validate_mcp_result_schemas.py++- [x] 9. GREEN: implement output descriptor/schema providers and host fixture validation <!-- id:gpzncvt -->+ - Implement MCPResultSchemas.swift explicit2020-12 self-contained wrapper definitions; source JSON accepts any original JSON value/unknown fields, while source-kind and presentation invariants remain constrained.+ - Connect schema descriptors to the synthetic provider seam and test runner/export path; no independent edits to shared MCPTypes or common registry. Keep existing input-schema support unchanged until coordinated integration. Pass task8.+ - Blocked-by: gpzncvs (RED: validate structured output schemas across every source variant)+ - Stream: 1+ - Requirements: [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [3.2](requirements.md#3.2)+ - References: design.md, Transit/Transit/MCP/Results/MCPResultSchemas.swift, tests/validation/validate_mcp_result_schemas.py++- [x] 10. RED: bound expanded result preparation with production-shaped synthetic cases <!-- id:gpzncvu -->+ - Add MCPResultPreparationBudgetTests with 2000 synthetic records/multiple pages and seeded large text/number fields; blocked parser/encoder and fake cancellation/cutoff inputs assert timely complete failure, never partial success.+ - Test exact backing charges for raw text, structured fragments and original metadata, shared backing once, pending reservations and both ordinary/reusable16-MiB boundary fixtures. Over-limit results must fail capacity/deadline, not be truncated or gain larger limits. This is automated code verification of the design measurement risk, not a standalone metrics exercise.+ - Blocked-by: gpzncvt (GREEN: implement output descriptor/schema providers and host fixture validation)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [2.2](requirements.md#2.2), [3.3](requirements.md#3.3), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2)+ - References: design.md, Transit/TransitTests/MCPResultPreparationBudgetTests.swift++- [x] 11. GREEN: implement charged frozen result preparation and cancellation checks <!-- id:gpzncvv -->+ - Implement value-only frozen-fragment/size preparation in Results modules using task1 seams. Avoid needless duplicate backing, preserve all existing capture/index charges and metadata; check supplied cutoff/cancellation between bounded encoding stages.+ - Pass task10 before integrating retention or common transport. If volume preparation cannot succeed inside limits, select the already prepared defined failure and discard privately staged output; no deadline/capacity expansion or weakened evidence.+ - Blocked-by: gpzncvu (RED: bound expanded result preparation with production-shaped synthetic cases)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [2.2](requirements.md#2.2), [3.3](requirements.md#3.3), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2)+ - References: design.md, Transit/Transit/MCP/Results/MCPResultEncoder.swift++- [x] 12. RED: specify modern request validation and stateless discovery <!-- id:gpzncvw -->+ - Add MCPModernValidatorTests/DiscoveryTests with pure immutable availability inputs: metadata/header/code/status matrix, Base64 name sentinel/UTF8, conflicting headers, modern-only versions and data.supported, readable versus omitted error IDs, arrays/null IDs/unknown methods and notification-shaped tools/call zero dispatch.+ - Test complete discovery/tool-list result, zero/public cache metadata, stable name order and optional capability validation without prior-request state. These new-file fixtures use synthetic definitions; no T63 common/router edits before handoff.+ - Blocked-by: gpzncvl (Define immutable result and modern protocol boundary interfaces)+ - Stream: 2+ - Requirements: [3.2](requirements.md#3.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.6](requirements.md#5.6)+ - References: design.md, Transit/Transit/MCP/Protocol/MCPModernValidator.swift, Transit/Transit/MCP/Protocol/MCPModernDiscovery.swift++- [x] 13. GREEN: implement pure modern-only validator and discovery values <!-- id:gpzncvx -->+ - Implement MCPModernRequest.swift/MCPModernValidator.swift/MCPModernDiscovery.swift from task12 fixtures; per-request metadata only, standard errors, request-only method classification, immutable availability.+ - Expose validated protocol classification to later router wiring; covered tool arguments remain unvalidated until admitted bounded worker. No session/initialize/GET stream/wire arrays, resource/prompt/sampling features or client settings. Pass task12.+ - Blocked-by: gpzncvw (RED: specify modern request validation and stateless discovery), gpzncvn (GREEN: implement owned lossless JSON documents and source factories)+ - Stream: 2+ - Requirements: [3.2](requirements.md#3.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.6](requirements.md#5.6)+ - References: design.md, Transit/Transit/MCP/Protocol/MCPModernValidator.swift++- [x] 14. RED: exercise shared provider, replay and effect-aware failure integration <!-- id:gpzncvy -->+ - External gate: T63 shared-file ownership handoff at recorded base commit and heavy-test slot release, including its provider regression fix. Do not edit shared tests/helpers/sources before coordinated ownership; isolated tasks above do not wait for production T2384.+ - Extend MCPToolHandler/WriteCoordinator/HTTP fixture suites and add result-provider integration fixtures: every enabled current tool/maintenance result, plain/JSON errors, historic replay after edits/deletion with new RPC ID/same key, no receipt/expiry changes, unsupported evidence.+ - Assert actual protected-path name/comment/description trim-clear/newline parity from saved snapshots at same covered r1; parent labels excluded. Dirty UI/captured saved evidence must not cause adapter model reads, saves or rollback. Batch-specific clean-phase safeguards stay in T2384.+ - Inject protected postcommit outer failure and maintenance inner encodeAsJSONString/final envelope/delivery faults separately; preparation failure prevents effects and selected fallback bytes preserve original-key or no-key reconciliation. Router tests prove origin/headers/notification rejection before effects, covered invalid arguments enter bounded admission, immutable availability avoids preadmission MainActor work.+ - Blocked-by: gpzncvv (GREEN: implement charged frozen result preparation and cancellation checks), gpzncvx (GREEN: implement pure modern-only validator and discovery values)+ - 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), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.6](requirements.md#5.6)+ - References: design.md, Transit/Transit/MCP/MCPToolHandler.swift, Transit/Transit/MCP/MCPTypes.swift, Transit/Transit/MCP/MCPServer.swift, Transit/Transit/MCP/Writes/MCPWriteCoordinator.swift++- [x] 15. GREEN: integrate common source/schema/fallback and modern dispatch at handoff <!-- id:gpzncvz -->+ - Under T63 coordinated ownership, wire source origins/error phases in textResult/errorResult/protected outcomes/maintenance/persistence failures; install output-schema descriptors and resultType/structured/_meta support once in MCPTypes/definitions/handler.+ - Adapt terminal/replay output downstream without changing receipt JSON/format/r1/retention or service normalization. Route maintenance inner encoding failures to effect-aware ready-byte selection. Wire modern POST/header/Origin/format validation plus immutable availability classification ahead of read admission; remove legacy wire-array/init/session/GET pathways and update their tests.+ - Pass task14 and deliver a recorded common seam commit to T2384: source/JSON representation/schema descriptors/complete fallback/normal selection. T2384 owns its consumer/real mutate_tasks registration and safety policy; this task and T2383 final validation never block on production batch completion.+ - Blocked-by: gpzncvy (RED: exercise shared provider, replay and effect-aware failure integration)+ - 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), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.6](requirements.md#5.6)+ - References: design.md, Transit/Transit/MCP/MCPTypes.swift, Transit/Transit/MCP/MCPToolDefinitions.swift, Transit/Transit/MCP/MCPServer.swift, Transit/Transit/MCP/MCPServer+Responses.swift, Transit/Transit/MCP/MCPToolHandler.swift++- [x] 16. RED: prove frozen retention and atomic modern publication under faults <!-- id:gpzncw0 -->+ - Extend ordinary and T2382 reusable snapshot test suites using T63 fake clocks/barriers and real owner store seams; frozen text/payload/presentation/meta/policy/expiry/r1 survive edits/import changes and freshRPCIDs without reread/reclassification.+ - Inject required comment/history/capture/parser faults, explicit selector absence, expanded capacity failure, cancellation while encoding/preparing/offering, expired/stale publication, listener stop/restart and blocked physical finalizers. Assert no unpublished IDs/partial records, no serialization under gate,8 unfinished physical slots survive restart.+ - Explicit includeComments:false full/reusable-page cases must retain the original canonical comment-covered r1, even after later comment changes; only bodies are omitted.+ - Blocked-by: gpzncvz (GREEN: integrate common source/schema/fallback and modern dispatch at handoff)+ - Stream: 1+ - Requirements: [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [3.3](requirements.md#3.3), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2)+ - References: design.md, Transit/Transit/MCP/MCPTaskQuerySnapshotStore.swift, Transit/Transit/MCP/Reads, /Users/arjen/Documents/Codex/2026-10-03/task-2/transit/specs/portfolio-summaries/design.md++- [x] 17. GREEN: wire frozen tool fragments and full-byte read publication <!-- id:gpzncw1 -->+ - Use T63 retainedPage/PreparedReadResult seam and shared publication domain; privately charge/reserve expanded frozen fragments and original metadata/policy/expiry, then offer complete modern/text/structured/_meta/RPC bytes and all prepared publications.+ - Continuation encodes only new RPC wrapper. Keep original five-sec cutoff, eight physical workers and separate five-minute/eight-snapshot/16-MiB ordinary/reusable limits; atomic selection/discard only, large destruction outside lock, physical permits released by finalizers. Coordinate T2382 store-owned patch without altering aggregation. Pass task16.+ - Blocked-by: gpzncw0 (RED: prove frozen retention and atomic modern publication under faults)+ - Stream: 1+ - Requirements: [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [3.3](requirements.md#3.3), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2)+ - References: design.md, Transit/Transit/MCP/MCPToolHandler+TaskQuery.swift, Transit/Transit/MCP/Reads, Transit/Transit/MCP/MCPTaskQuerySnapshotStore.swift++- [x] 18. RED: specify request-scoped subscription ordering and cleanup <!-- id:gpzncw2 -->+ - Replace legacy session/GET stream expectations in MCPToolListChangeNotificationTests/MCPServerRouteTests; valid POST subscriptions require request IDs/modern headers/SSE Accept and acknowledge only supported requested filters.+ - Stress immediate availability changes before/after acknowledgement, coalescing, parallel string/integer subscription IDs, disconnect/shutdown/restart/port-change cleanup and graceful complete closure. First acknowledgement is never evicted; no unrequested notification, session state or further canceled-stream delivery.+ - Blocked-by: gpzncw1 (GREEN: wire frozen tool fragments and full-byte read publication)+ - Stream: 1+ - Requirements: [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)+ - References: design.md, Transit/Transit/MCP/MCPToolListChangeBroadcaster.swift, Transit/Transit/MCP/MCPServer+ToolListNotifications.swift++- [x] 19. GREEN: implement POST subscription broadcaster and lifecycle wiring <!-- id:gpzncw3 -->+ - Replace session-grouped broadcaster with request registrations, separate first-ack staging and bounded coalesced invalidations; carry original RPC subscription ID on every message and accepted filter only.+ - Integrate existing availability observer/service teardown/port-change hooks under handoff; flush SSE data frames, omit event IDs/resumability, graceful complete result on server closure where possible, cleanup exactly once. No store capture/read permit or extra progress stream. Pass task18.+ - Blocked-by: gpzncw2 (RED: specify request-scoped subscription ordering and cleanup)+ - Stream: 1+ - Requirements: [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)+ - References: design.md, Transit/Transit/MCP/MCPToolListChangeBroadcaster.swift, Transit/Transit/MCP/MCPServer+ToolListNotifications.swift, Transit/Transit/MCP/MCPServer.swift++- [x] 20. RED: specify isolated client-readiness fixture and negotiation evidence checks <!-- id:gpzncw4 -->+ - Add automated fixture/harness tests with synthetic data: modern discovery/list/call/structured consumption, conforming subscription filter/first-ack/correlation, wrong/legacy protocol negatives, and no real writes or production endpoint replacement.+ - Write negotiation-evidence checks that reject binary symbols/version-only/legacy success, missing intended surfaces and missing structured consumption. Require concrete actual intended Codex surfaces, Claude Code and Desktop discovery/list/call traces; subscription only for opted-in installed surfaces plus conforming fixture. Actual runtime connection/settings prerequisites remain separate from coding.+ - Blocked-by: gpzncw3 (GREEN: implement POST subscription broadcaster and lifecycle wiring)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.3](requirements.md#1.3), [3.2](requirements.md#3.2), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [6.3](requirements.md#6.3)+ - References: design.md, scripts/mcp-modern-readiness, prerequisites.md++- [x] 21. GREEN: implement isolated loopback fixture and readiness trace verifier <!-- id:gpzncw5 -->+ - Implement scripts/mcp-modern-readiness test launcher/verifier using approved app encoder/validator test hooks on a separate loopback port and synthetic read-only records. Verify headers/meta/discovery/list/call/structured response and subscription evidence; verify fixture cannot address real store or replace production listener.+ - Pass task20. Produce machine-checkable evidence for each approved installed-client probe without installing clients, changing flags/connectors/settings, starting external-model agents or activating Transit. Unsupported modern runtime is an explicit blocker, not a fallback to legacy.+ - Blocked-by: gpzncw4 (RED: specify isolated client-readiness fixture and negotiation evidence checks)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.3](requirements.md#1.3), [3.2](requirements.md#3.2), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [6.3](requirements.md#6.3)+ - References: design.md, scripts/mcp-modern-readiness, prerequisites.md++- [x] 22. Test integrated modern contracts and approved client evidence <!-- id:gpzncw6 -->+ - Local verification COMPLETE:81 declarations/116 cases plus final review-fix44/90, full iOS1310/1358 and separate UI21/24 finalized PASS; lint0/527; actual schema876 assertions/recovery3/readiness5 pass. Actual installed-client AC6.3 evidence remains OPEN and owner-approved DEFERRED to post-merge MacBook validation (Sentinel_c0dbfe3212888191bc01744c855f67bb); it no longer blocks the authorised merge. No client compatibility pass or activation is claimed. See local-verification-handoff.md.+ - Test-only task after T63 slot release: run selected Swift Testing suites and schema fixture validation then repository make lint/test-quick appropriate to changes, with owning TestModelContainer fixtures and no host-checkout reads in app test processes. Broaden only for new failures/unresolved concerns.+ - Validate approved real-client negotiation evidence with task21 harness only once prerequisites are satisfied; missing evidence keeps6.3 open as the approved post-merge follow-up, without blocking merge. Exercise all present provider registrations and synthetic future batch seam; production T2384 completion is not a blocker or claimed proof.+ - No client activation/settings/deploy here. Push/PR/merge are separately authorised by the completion workflow; client compatibility remains explicitly unverified and deferred under the owner amendment. See pre-push-handoff.md.+ - Blocked-by: gpzncw5 (GREEN: implement isolated loopback fixture and readiness trace verifier)+ - 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), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [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)+ - References: design.md, requirements.md, prerequisites.md, Makefile
Earlier failed compilation/preflight and unfinalized RED attempts remain preserved, not relabelled as finalized passes. This review claims separate native runs rather than one aggregate execution.
Four internal reviewers inventoried the full diff and inspected critical production paths; this is not an exhaustive claim that every documentation/test hunk was read. No external peer-review service was used in the local review.