GGUF.MiRust.com All Source Review Bundle Generated UTC: 2026-06-29T20:39:39Z Source root: E:\Source\Rust\GGUF.MiRust.com Bundle path: E:\Source\Rust\GGUF.MiRust.com-Publish\GGUF_MiRust_All_Source_Review_Bundle.txt Included file count: 264 Included source bytes before bundling: 4740532 Skipped directories: .git, .vs, target, raw Skipped compiled/model/raw artifact extensions: .slm, .wasm, .adp1, .asp1, .alr1, .exe, .dll, .pdb, .png, .jpg, .jpeg, .gif, .ico, .zip, .7z, .f32 Working tree status at bundle time: clean FILE INDEX .gitattributes 2581 sha256:462475EE5301E77D2A54A64757D95C3F21FC3A79E92E6EC94BDFCC8B36E48964 .gitignore 99 sha256:7BA27FC77F3465E64F0306A09FA7D73D3EA0CD86DF95C1E81485389F18BEB407 .uai/architecture.uai 70546 sha256:508C9D4EF45AEDD20890275A9F34FDDEA6CB61E7497D5D1886E62A444723A1B2 .uai/coding-standards.uai 57785 sha256:3BBC6B439158967A09B6FCF747FD08E21FBB1D0357C1A82FD480EA4B0BFA08C2 .uai/file-handoff.uai 3954 sha256:304F0633412E435164D122F4A2979A6472066F256E4566FAB5D37FA7243A15C0 .uai/index.uai 5807 sha256:C4223233A43BA44D46FE87EE20DD4D3AA7FF39E4D106096728A0605572F8AF00 .uai/intake-outcome-ledger.uai 30037 sha256:F5A8470BCCF74FDA757C1A788C6D32E52DB91B4C75D60228A9FAE43B4EE9A5D1 .uai/long-term-memory.uai 296424 sha256:76D9DA07F35549A77606736FD8364FE3ACB4727E37E9CBB37C658CB348464AF9 .uai/next-recursive-prompt.uai 7929 sha256:EFC10B345321CEFD8D20C775A69F969C55CA76F7D7E1D09BBA3A3246A28CAF54 .uai/operations.uai 117956 sha256:E7D1743F8D886899A53AEC521CDD8D19A203D127EA8DD099CC66CDCE2417F24F .uai/receiver-brief.uai 3449 sha256:DBF2149881208F3A586752776494DB57AC2CF8932BBF2D1D6B4A5AD13BE9D4D6 .uai/report-synthesis.uai 79569 sha256:6FB4A26126EFB84A62611C3ABD2AECD4388F5ADFD6773BFA1249568493B4A81D .uai/short-term-memory.uai 244217 sha256:9AF71A909542BE7A03BD7BEF0D3C63185EE0659106B186CA02BAF303DE3213CF .uai/startup-packet.uai 53812 sha256:058F316A6124BB90F8DE2F1BDFF17445276B2B3D82A4FC4B780FD8429AFFD612 .uai/system-profile.uai 1287 sha256:E1F61E1DA97568F16E00EC63A3D92798CACC0EEB569D06743E29D664B2E65552 .uai/taboo.uai 6326 sha256:2648476F4CE0813051EC29AFC9C88D3CEADE416D12CECF7A806A2626A13D709C .uai/test-plan.uai 148129 sha256:0EAE31ECAE64A909649A64FC5F408E5BA6D45F1526AB4E4FD4429F7C7572C31F .uai/workspace-guidance.uai 65395 sha256:5CE36C95DF0AA8498FA573290D77B9C6146FB185BD7340B0A906AEA122F908DE AGENTS.md 2562 sha256:267C8DC4B731ACE2F9741BE3E377FF5C7304CE86277537EDA25F48D24545ABDE Cargo.lock 353 sha256:22402F7BBC0B7969D322D71794D134BC01343B4AFA8F63788E4B6772727F10D1 Cargo.toml 486 sha256:37E5AD8B8D1951DEE7034C849887104F276E5ABA98C39034781A696A19551910 docs/aiwikis-routing.md 870 sha256:36E35102BE3720E17F150CD4A829A6F4D0E5500BA969D1FB59B488438CD74E32 docs/architecture/browser-harness.md 1261 sha256:B01F80EC9FEA52A6B417EEBF302C5EACCCAA0B1C75AACE594177C57289E6D760 docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md 5560 sha256:27150B92CF92D384D166013DC7201D9DD5F8F80684AF3067D3044EE52D83600B docs/dogfood/uaix-llm-wiki-crawlability-failure-2026-06-25.md 3386 sha256:C1E2C6873ACB37BAC3188785B5D24A9DA7B2AB6006A07167629C39DC7B6788A3 docs/dogfood/uaix-llmwikis-setup-experience-2026-06-24.md 1680 sha256:D587B2E9273AFB2B88F660CCD69EAE5AF0F3692DBC3BD76716A00E6A04663C30 docs/visual-studio.md 4387 sha256:4EB9659BEBD8C33799A384DEE81415BCCB13304F2D2E67CFDC1A3D0D9976ABDB README.md 29564 sha256:3A1AF7CA83E518DC78F792ED2BA8E1637D4E25AFA62D7C2A11360FDEAFC0782A TinyRustLM.sln 1357 sha256:587E1C3FC6D2CF1113CEF11FC8013B7DE2A5B9C956C4E5026930F2DCB60E203D TinyRustLM.vcxproj 4580 sha256:BD821C48B395AFA3DA5E23667A004F318FAAB5C4C58D68438E54208E41CC2A46 TinyRustLM.vcxproj.filters 4251 sha256:777DC2745E5E0FA474E8D62A777D5B399CE28403998AED54F6D12FDC4F89A5FE tinyrustlm/app/app.css 4335 sha256:23F9A7A9D555718DEB9DEDF4862935AAC811CC6FD90EEFFE9168FA5CBAF1FAFF tinyrustlm/app/app.js 180331 sha256:E404D84B0703233A0F0390020840D6FC1ED79DB426D4C221C62369E8FF78C543 tinyrustlm/app/index.html 10228 sha256:669165A9E41F16BB316E67CAF0B7CE78AF302CB4DBB009D035E8F97F198A09B3 tinyrustlm/docs/architecture.md 18117 sha256:6EE3C495E1E518E249AD38BE548F98DF31B86B82614A9AFB93C5778F6233E269 tinyrustlm/docs/browser-runtime.md 17717 sha256:8DDE334D27A44979124441E7221B68310F76A39195C6F9D73CA12E4D6597776C tinyrustlm/docs/performance.md 3603 sha256:07A74898373F6807DE99BB1BCB3748A16460F0CB4CCE45D857CB56533A2A1B33 tinyrustlm/docs/quantization.md 2032 sha256:1B1AFD7292FFD7FE5F023EE9BBF33169E1A2A839673434AE481603DAFA55A700 tinyrustlm/docs/slm-format.md 29705 sha256:4D06F94001165FBA0E996ADFE2DB234CA66B758379F807E716F6B7D542EA7627 tinyrustlm/docs/testing.md 45408 sha256:FEEB5288862F939384B44320EA75AF0DEE06BDF76E1D919B9A543BEEB448C5A4 tinyrustlm/docs/tokenizer.md 3421 sha256:B133955180A0AF4F260C81F6438E1C586A27A4863068AD4B6E82C32DCB14D18F tinyrustlm/models/README.md 37451 sha256:58B136954E3227CB9B15801DF742EE36511F44A505F65B4FA148001F8B26EAA8 tinyrustlm/models/tinylm16-f32.slm.manifest 540 sha256:D9CDEF0D7CE09979EF8D824BCF68555322B89A286DE197148CD2263F654E3010 tinyrustlm/models/tinylm16-q4.slm.manifest 540 sha256:7B1C77776876EC9BE80DD00CEFB6C7AE877FD592FBF4FAD5029080B36B8D46CB tinyrustlm/models/tinylm16-q8.slm.manifest 540 sha256:21178B39642AE045CB26FE99B1595BC5B193AE563EC17F7545E478316CBFAA70 tinyrustlm/models/tiny-test-model.slm.manifest 530 sha256:04A621560A3F24C8E8243A1D085CACB6944CAD0898967582500EDE6D885B1B81 tinyrustlm/models/tiny-test-model-bpe.slm.manifest 534 sha256:AE28DDD62E91834A1F7F6D29BE186CB9EA81A92FAEBC0A5AF3E5A4897DC15B52 tinyrustlm/models/tiny-test-model-q4.slm.manifest 533 sha256:EB53E4A34D831571BE34B29049D07901E85411561E761DC2C9E37C60827B853F tinyrustlm/models/tiny-test-model-q4-self.adp1.manifest 2026 sha256:2060583F1243B373C8E3AEFECA5EFD763F09979E679249B9C087C1EC3DFF1880 tinyrustlm/models/tiny-test-model-q8.slm.manifest 533 sha256:85AC07502280F1D05B18A6932B83465C60CA59EE1B4D157A45C668380131294F tinyrustlm/models/tiny-test-model-q8-self.adp1.manifest 2026 sha256:5680FD9A8676B818BCE3B90175AE75B574ACFE380B0B374A27ED46EA2C714AEB tinyrustlm/models/tiny-test-model-self.adp1.manifest 2004 sha256:78D72C47C6423F4E16E194DBB7F56F055071962FF611CC8C12E971C4C0FB75D0 tinyrustlm/models/tiny-test-model-tied.slm.manifest 535 sha256:469A78D503B010323709EEAF6731DC8AFE05F0DE442BC16BC63F58C636A1490C tinyrustlm/README.md 71074 sha256:625BA413419244D514A72DB0881094AB151F0728D475588159E018757D923937 tinyrustlm/runtime/Cargo.toml 247 sha256:4A2A1F84E6DA1AFA204B4D6ECB984EA5A69238B023A5F39665330671E2E01E84 tinyrustlm/runtime/src/adapter.rs 19168 sha256:E45628BE16C7758C3A60C190FF866732A03BC442556BD35D81BD183D64B26DF6 tinyrustlm/runtime/src/attention.rs 942 sha256:CE410F0EEDC858BAA0A01284CF6C330A3EEC11DB6A5B60D218AE1B7C1E77AD94 tinyrustlm/runtime/src/bin/tinyrustlm-eval.rs 1221 sha256:303E7E1B43056B3F491AE6B7646DE5322CB88A2837FBEFDF0BBA2FE14064DC63 tinyrustlm/runtime/src/diagnostics.rs 11301 sha256:C03C756292DF8622F7684C64BAD3560B7B3D9929616DC5548F51AF4C10EE9522 tinyrustlm/runtime/src/errors.rs 2622 sha256:93B775552F722B3C7DEDD5B6AC36F1E95149D1F52AFC8CE8674207BAE7DEBA6A tinyrustlm/runtime/src/eval_runner.rs 14645 sha256:4907408005ACFA229C9BA8E2007EB95612FCD07C5F0C3EA17C2CE5B45624CA1A tinyrustlm/runtime/src/ffn.rs 784 sha256:9CAC43E21EB6F3A1B5B74C07A4483A11E2D652B49A87C7CD9305F23CBBF571A5 tinyrustlm/runtime/src/generate.rs 49984 sha256:A9788F5E70B9960440E642CFA27F6A776F8149FEF666BBFCDD6E6AFD6405111F tinyrustlm/runtime/src/kv_cache.rs 6819 sha256:6E642AA8343C686AE8E8DFD1210A0068B8607D88E754EA3E3150D7867B731F5C tinyrustlm/runtime/src/lib.rs 1383 sha256:7FDFE094576F7CB4C63847E6594CBF9DFCD4130F48B6AE7EE95426043364D578 tinyrustlm/runtime/src/memory.rs 1465 sha256:078BC01720160FB816D5ECFF493F4184417D985ACCF45EC9C5D0F0BC5874FA59 tinyrustlm/runtime/src/model.rs 68445 sha256:2FA2149C17D301271316EAE29D214887597C63A313997C61CA5225F785C2373E tinyrustlm/runtime/src/model_format.rs 11788 sha256:B2041C774BB82009A57904A28EBEB5A08BB713FDAFCB30C5F83CCC6B4F8289D5 tinyrustlm/runtime/src/ops.rs 6310 sha256:47D6FEDD08B4DC3059F36C3203C13E0ECA8F53F2F18DCDC46B20A4A4E5B1028B tinyrustlm/runtime/src/quant.rs 5721 sha256:90E9F3103D39D00A75A1AC52756436D745EB0D24DE748AFFE5C3F462B183A914 tinyrustlm/runtime/src/rng.rs 763 sha256:D5EA218FD5DB4859F8CC27C034E88507A03FDCDC86F04D5ACB17A4E984463377 tinyrustlm/runtime/src/rope.rs 1055 sha256:8F760BF3B39F72C2270533C4B50F9F5769639AE02C5208B584F836898E73ACE6 tinyrustlm/runtime/src/sampler.rs 6972 sha256:2FDB1BC4BA798258A4ADF2034B3ED931083377E4C276E3D1BF5AC46EEC26488F tinyrustlm/runtime/src/tensor.rs 3942 sha256:611ED2FEEA28B9E53D415291F9E1962B4EB6D56657437FB61AF16E994B710589 tinyrustlm/runtime/src/tokenizer.rs 17504 sha256:AB51E0EDA9F89E1567D5A3610DD97902390F8E8E9B22283137A089659FB13750 tinyrustlm/runtime/src/wasm_exports.rs 5227 sha256:FB382F3A85D8232A9FB58AAF9F3F3612722FB578A2F1D327DB58E1BAF1753185 tinyrustlm/runtime/tinyrustlm.wasm.manifest 264 sha256:E9A1CD14425FCA92FCE26CBF3240BFF9F19D35BFE34E1D60F4FE667BF97E1BF3 tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt 629 sha256:F0999C05C19029FC240E11A7BCFC41DC7CC43874F9F81ED6F1111BA66D7B76A8 tinyrustlm/tests/fixtures/expected-matmul.txt 58 sha256:2A7C202A61829716681D84FCACB1F4C98245CD86A3B74F466EB83DA829078BC8 tinyrustlm/tests/fixtures/expected-rmsnorm.txt 76 sha256:F8AE7363B8D9B31FE9EC2A63CC4A7151738A03B5A1020F11FEA3FA5A67267C11 tinyrustlm/tests/fixtures/expected-softmax.txt 26 sha256:03D9687D8125EE74CFE3CFA4DB8FB76373AB4CB1B93DF5690733DA1166BBD108 tinyrustlm/tests/fixtures/tokenizer-cases.txt 41 sha256:A51F68BCDED7FCD462B7398C1A0248E1F0DCF3568172D90E5E3564853AABEC76 tinyrustlm/tests/fixtures/trained-source-tiny/source.manifest 2598 sha256:1CE4EDEE82BECC2B84E5714AAC38A6A6C749AF6F9236DE4CC920F54DC9CDFF86 tinyrustlm/tools/browser_harness/Cargo.toml 216 sha256:8FFB2F97B8D492D39896BF4BEFC505E8D2B5677013D8E648679319D40C22BF19 tinyrustlm/tools/browser_harness/src/main.rs 28776 sha256:0057706A7937857A13740E516A5D47461774F7AEF894D618C00CC6B44404C5EE tinyrustlm/tools/browser-smoke.js 422100 sha256:85502011F5E8E364EEA9CA4454615FE32C79882C439852AB765C8C5F1E20312B tinyrustlm/tools/local_server/Cargo.toml 213 sha256:E4B7809225A0468192D7790341A8B68538300A9789B5E2A08C20F92A8EADB010 tinyrustlm/tools/local_server/src/main.rs 12090 sha256:8CA1CC5026792D2F1CB45883A82DB089E2561CA00BA43B3245B7CA246A996102 tinyrustlm/tools/slm_pack/Cargo.toml 209 sha256:77FC3EF97599491B8E67404EDF8CC0645A0032AF84D157B8E153AE84E6DC8AF8 tinyrustlm/tools/slm_pack/src/adapter.rs 113011 sha256:8F76A24981BF676CCEB162CF9718BFB1EE1B2FBB85418E6DBC671E8343D89C52 tinyrustlm/tools/slm_pack/src/adapter_family.rs 42274 sha256:9A7AE9A7B9C5E1CAE1DBF3110D7A28F102CBC8A53615EE554431093727510618 tinyrustlm/tools/slm_pack/src/admission.rs 45722 sha256:8A001B0351CB03F73C4E01381DA4C0847C08503C0F2EA3B1EEC69883BB28D130 tinyrustlm/tools/slm_pack/src/blend.rs 35061 sha256:19E0776F91717ABE5715E07DC730ED3C66A46C0FF649026EF9CF57354C36FC8F tinyrustlm/tools/slm_pack/src/browser_bundle.rs 121254 sha256:6F558D24C1BB64BAAF92AF506FACED65BA92F350712507D0EEB5D7A287DBBEC8 tinyrustlm/tools/slm_pack/src/candidate.rs 37185 sha256:0482D43F9C0437C39B6F3C56D679F6ACDC7C8E0CE8FD524135C62E44B550B232 tinyrustlm/tools/slm_pack/src/compatibility.rs 9166 sha256:29E4BCE5FDCCE6E1045D0B559AB9E05785E8485BA8637317B7C131727A5D5C87 tinyrustlm/tools/slm_pack/src/crossover.rs 34880 sha256:2AD77765C01313021C9BEF7A14203B7FADD3CFBEFDAB7CA359246E40770EA0F9 tinyrustlm/tools/slm_pack/src/dare.rs 44917 sha256:2228F76A58AC5DCF39B2D4E69CAE24AA14212AA8959E2C9DD4A9382B68CFDBF9 tinyrustlm/tools/slm_pack/src/delta.rs 19698 sha256:1AD6CFF9FA117EC615FCA429F45D16927E9690C959BE486E7742A2A00B5B87D2 tinyrustlm/tools/slm_pack/src/federated.rs 33302 sha256:2E8E856E6BB0D9B194F308385B3F4148FA9368CA23F99FE1C9327CC113661009 tinyrustlm/tools/slm_pack/src/ledger.rs 17539 sha256:0AC47CFF5021A553545B9D0E9393FC13793BB0268D8E23B9D442FD35BD410CA2 tinyrustlm/tools/slm_pack/src/lineage.rs 14361 sha256:69B7B590E2C5965D21F9A0BDBC8EE36CF13953A4B8059E6DD00F692DBEC8EFEE tinyrustlm/tools/slm_pack/src/main.rs 143968 sha256:FCF15CE35EFEC3F274FA79AF4E7A3C79970C604C4F3E8BCA38A8AF4BBB6E54AB tinyrustlm/tools/slm_pack/src/multi_admission.rs 43245 sha256:01F9D85FBAA0C8A49BB54899C2EB991C9D8BE7FA756740CAC61C2BA4453301DD tinyrustlm/tools/slm_pack/src/multi_candidate.rs 39031 sha256:0AD36F832C4111B2CB3F4029A9D39C1BD99E04E9FAFAA078C6FD3B6D8A055D3F tinyrustlm/tools/slm_pack/src/multi_promotion.rs 25581 sha256:60CDDEF2EF0D07C64CA0E9CCF546ED7A726D6B44B3B7220946AC7A8C2C143DBF tinyrustlm/tools/slm_pack/src/mutation.rs 42944 sha256:7252937956E25EB7581BFAF2303A7857F88730CD11062A5645112567043C3B65 tinyrustlm/tools/slm_pack/src/parent_pool.rs 42417 sha256:C3ADE55E0A95AD132A16B59200C751906DEFD7492377FCF0F02DBEE4942CAB8D tinyrustlm/tools/slm_pack/src/population.rs 32311 sha256:48310799260A95B602BC3580E4FD11A2590BD7875A2AB0859B2C0CBA669B0648 tinyrustlm/tools/slm_pack/src/promotion.rs 30059 sha256:0CE7B5F1D64495B5932402740C710EE2C8E684E0321762EA6BF7602154AB6F84 tinyrustlm/tools/slm_pack/src/provenance.rs 31007 sha256:8112D2AF17A7DC3552A0F9D874B8766A3448A926B33E7262E982ACF069213D22 tinyrustlm/tools/slm_pack/src/prune.rs 40374 sha256:5D2325C53FDCCDFB3CFA5B167CF535F25670DF29C6C6840AFFA91AE2DC7A349D tinyrustlm/tools/slm_pack/src/quant_writer.rs 1697 sha256:BAE177AE9B3D8525DE0B2360EDB29882E034F551CEC87202B198470290D8686E tinyrustlm/tools/slm_pack/src/selector.rs 290730 sha256:0A7776F75175BDE827C68A609D2DA050C18B9DCFB614231A61672FF9E557DB9F tinyrustlm/tools/slm_pack/src/sign_merge.rs 47624 sha256:E2C07EC2ADEB25F1C0CEBFBF807486CA68B0C548B57512EF24BC447FA29EF948 tinyrustlm/tools/slm_pack/src/slm_validate.rs 33527 sha256:7366E6C2151E3BA6129E8E6B1F1D09AB942252A62280D4951297989478FBCAB5 tinyrustlm/tools/slm_pack/src/soup.rs 49370 sha256:2CEB401210DF55C49685BBA24B6DF94F9F34FE075CFCF08592F8CCA2B36DDF5E tinyrustlm/tools/slm_pack/src/sparse_delta.rs 33152 sha256:F56C9FCB3E11C04F1EF42329FEFEF8C34FD002E67B1A66AAEF5451C346A7A72A tinyrustlm/tools/slm_pack/src/tensor_writer.rs 8874 sha256:0C2FFD4B3585128D44C36F91A7A9FF1CBF708D17A5EE14EC9BCF64B5E5F7A5EB tinyrustlm/tools/slm_pack/src/tokenizer_writer.rs 4339 sha256:F201E5D93D65D447553C54691BBEA55B62B7D75522060854C2402BD316C3BFFD tinyrustlm/tools/slm_pack/src/trained_adapter_source.rs 52496 sha256:223350D68D5DC97D1343757FE2F0BA6C6734E619DE6E9771DDF1EE0D8D2C8E01 tinyrustlm/tools/slm_pack/src/trained_source.rs 40482 sha256:54A054A391D60584BE042D8A02ECF9C5E4726388566C0AB3695C2CAFE5DA8E3A tinyrustlm/tools/slm_pack/src/writer.rs 1064 sha256:A189F9B2C7911E1ED45AA2AF5266999BA0C4AE07B4E4BE33CC865D02CFF78F1A tinyrustlm/tools/static-server.js 2262 sha256:93A2E12153444E18D807D2F4C7E9FA9BAF5EBEAA81D93DC175778C97876FF61C tinyrustlm/tools/wasm-abi-smoke.js 19863 sha256:CCC8D69E0F0FFB739DED58452962829BB179136328820D7587EB05D457D3A0A0 tools/vs/Build-TinyRustLM.ps1 4483 sha256:5371F463A326D4635C6291E518CF958D705CB1326759699CB58524C9ECE74ECC tools/vs/Run-TinyRustLM.ps1 4087 sha256:B1C08AF0BFEB1C0C6EA1EC19004DFE1BFD21C6BDE219C56232B4532ED136D1E8 tools/vs/Test-TinyRustLM.ps1 21955 sha256:5CB97570E976185DA8ECFDA4819FEBAC0F8BD94097EFEB3C6E92F44464676E0A wiki/gguf-mirust/index.md 15523 sha256:57FAEB895813A09929CC23C62C3483F9E2A9302401A22C50A566038417C7666C wiki/gguf-mirust/knowledge-map.md 31725 sha256:7971DDF6B1CF5870BE5EF0FB11C665BD53A77913B279666C1600D847056641A7 wiki/gguf-mirust/log.md 38024 sha256:E29FC184355011CD3684083B080BF66A9FF8ED734D86E776756C9C10A381B7B7 wiki/gguf-mirust/reports/adapter-family-receipt-memory-2026-06-27.md 5961 sha256:B1CA668DF85A1AA491AA9C09722BE673EE8CDA1ACC3D34094261DF3E9D004DAE wiki/gguf-mirust/reports/admission-operator-receipt-binding-memory-2026-06-29.md 4814 sha256:59CD900D6868CAEE98D79DEF2241665164C4F00AE933D6F20DD096B9750AEA8D wiki/gguf-mirust/reports/assembly-receipt-memory-2026-06-27.md 4640 sha256:AB1F2A4E32F0DECE417FDD1F6EACF30F1DC92666C67AAB3DB7477626DE957871 wiki/gguf-mirust/reports/brand-product-positioning-memory-2026-06-25.md 2709 sha256:60D0BE8BD0D98231CAAE71AFBD8978EAE1F776F995F4A5E43E2BC337EEE7A94B wiki/gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28.md 3416 sha256:E6CF6A987B39832F924E9EFE764AB57B770E838A154D0F9B132E6395B4F8E482 wiki/gguf-mirust/reports/browser-adapter-family-receipt-drift-memory-2026-06-28.md 3260 sha256:D330405FC5F2A27B4E0F817AC679FA9CBC53F6A76E242582700D5792D98F48A5 wiki/gguf-mirust/reports/browser-adapter-manifest-drift-memory-2026-06-28.md 3133 sha256:996199A693C531DE1AEE849A69DFAFB258DE1EB83D670294D01D3F288B93F2DB wiki/gguf-mirust/reports/browser-adapter-sidecar-memory-2026-06-27.md 4382 sha256:0FC03072EA8A509832838A3D71BAAA087A3BCD1F5960E69C5624A2E80E07041F wiki/gguf-mirust/reports/browser-adapter-stack-memory-2026-06-27.md 2484 sha256:98D332795CB298FEA383E772BF7DD87CFBE12DAFF80062D158EC00344503A8FE wiki/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md 3063 sha256:BFB328FDF1E70202411B4C5E27CFA76BF3BC5087350B66F535231B50028B03A5 wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28.md 4020 sha256:2599385320092B530DDFB59859133F233EED0707A413475FE19205E38D4595C1 wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md 3879 sha256:6A3413A669A05142C6C733A06B4BA172213B766C2E92602EF4AD10DF4F9B5468 wiki/gguf-mirust/reports/browser-assembly-eval-case-drift-memory-2026-06-28.md 3032 sha256:FC06567D7366205205B1986A7E724961090583E9D978CB68256C5CE5C3186758 wiki/gguf-mirust/reports/browser-assembly-evidence-file-drift-memory-2026-06-28.md 3464 sha256:0C55453352A660616EEA6212B379BEFE62D6CC3C11BED08D20F0B0903517124C wiki/gguf-mirust/reports/browser-assembly-trace-memory-2026-06-28.md 3672 sha256:69EDC1FF684DD221A05F882668944115EFB526D1BC779AA27AD743FDB4AB9F54 wiki/gguf-mirust/reports/browser-auto-assembly-budget-memory-2026-06-27.md 3775 sha256:16D0202CDB003028E3712C0E5832EED72D8617D9E20C24E21CBDA017B827ABD5 wiki/gguf-mirust/reports/browser-auto-assembly-memory-2026-06-27.md 3891 sha256:FB00139461018797F281DDE5A95750F7123820CC52AD50558941536E5728FB75 wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md 3133 sha256:8052D26545B1DE28756D956C4DE5EB4EAF60C4ADFDEF355E26AB4033AA8DBC6F wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md 4157 sha256:7D42391A51C39CF31F3203E349DA5771E75CD84C8DE6EB26B5E2952728E801A3 wiki/gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md 2879 sha256:DA24658D962A61AAF9EC3F1577818981FAAD3EEC8BC5E71970D5C37C52D5AE03 wiki/gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28.md 3641 sha256:A7D1A7EFDD0A345BC9DBA3098E6CF78C2344908B75C7644DE343E30795B99BF7 wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md 2751 sha256:90B263C8DE3153653351B78B62F5D60A11A9FFC608EFEA9815AD9C57B69500E4 wiki/gguf-mirust/reports/browser-combined-selector-stress-route-soak-memory-2026-06-28.md 2718 sha256:263D098DE974A43F1F507CBFADB6BC0877ED5CCDF12274BED55C5D0B6CA846AC wiki/gguf-mirust/reports/browser-converted-trained-all-route-memory-2026-06-29.md 3453 sha256:42A6F370271EC6797FC0D0524F1D801241D8AB47307603B801E2DBB4D8F3FBF8 wiki/gguf-mirust/reports/browser-converted-trained-file-route-memory-2026-06-29.md 3282 sha256:149461852AA3AF42A72CF9ACF2676B278C4564170E6D85194033691A8A5C16C3 wiki/gguf-mirust/reports/browser-converted-trained-provenance-memory-2026-06-29.md 2397 sha256:4BE9C47DA03D06C181630E1A6E1B2340CC6F8FA70AEB794450668213307D99DF wiki/gguf-mirust/reports/browser-eval-case-evidence-checksum-memory-2026-06-28.md 3167 sha256:7918E1422B06980A1A3A6143125A923A24403EEAEB7A19948DC044F39E822520 wiki/gguf-mirust/reports/browser-frugal-selector-default-memory-2026-06-27.md 3103 sha256:AC0D6CC2539BC26940718E2F90FAA24EB82D8964A8E5D1D4BCAEE95FEEE25702 wiki/gguf-mirust/reports/browser-local-runtime-memory-2026-06-25.md 4111 sha256:ADD5B499A5CC5D4A1A6B0455809460BAD05832B1EB7814D7F2A041CDA01CDBE6 wiki/gguf-mirust/reports/browser-low-rank-adapter-route-memory-2026-06-28.md 2614 sha256:E9C584550367F02809DB6C44648AF1903CEFF1FD9C17C61F8E2011C49A90DD68 wiki/gguf-mirust/reports/browser-mixed-operator-selector-memory-2026-06-29.md 9887 sha256:7AB166C77EFFBC733EBC708717D87765A7AB0D2F411E5E1D5893ABB32F0AB466 wiki/gguf-mirust/reports/browser-module-plan-actual-fetch-count-memory-2026-06-29.md 2749 sha256:53AA6AFE088CBC57488D767A56B8E3AD1FE120D26C4294B03A731516CF34AF69 wiki/gguf-mirust/reports/browser-module-plan-actual-module-bytes-memory-2026-06-29.md 3029 sha256:A94D45A8EE9112BA407CEC4A28271636D5B1CE30DEF94BF01D4F07B38DC406A6 wiki/gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md 5239 sha256:CD6774044CEE88D349C633A4D8747C5054C11E11AAF9AF32DCDA4323792EAFBD wiki/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md 3704 sha256:2CAA25EF243E7441A46E3FF42FB40FF78C42AAA99DEF30713845D7155A93A016 wiki/gguf-mirust/reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28.md 2460 sha256:647A223259C1E98F5020C5249C16A8E8194915986EA0159605FBA8CEEB5DBCC7 wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-count-memory-2026-06-29.md 3607 sha256:8B28A780E19D412F2D1AF5E33747E8F2D068B262FD8A8FCBCACA0FE28751065F wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29.md 3195 sha256:4559CFCA94879CE971CDD15824619068364A6BDF577FD85AED7F79D46FEC7B7D wiki/gguf-mirust/reports/browser-module-plan-budget-display-memory-2026-06-27.md 2673 sha256:3F49857269DEE429CA3C5E3DCB54D3CA3BE14363B4E823A644AD8B7F0636DC33 wiki/gguf-mirust/reports/browser-module-plan-byte-counts-memory-2026-06-27.md 3688 sha256:92F73FF2BE95A36B54C22ACE0A9B5087D76846C83E51B54084340AF03159CB1C wiki/gguf-mirust/reports/browser-module-plan-checksums-memory-2026-06-27.md 3659 sha256:16CB53908E60814591ACCA0231C3BC12B01CE73F471115CC27BBFD739BD52097 wiki/gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28.md 2901 sha256:73EECC40D7FB6F561B3AEB9BA11F3EE8D631C1662600E0A75F96FFEA6FB51242 wiki/gguf-mirust/reports/browser-module-plan-count-drift-memory-2026-06-28.md 2367 sha256:B1FD636C15E3EE71C679B012CD00CF7C81FAB355823A91FA8239EEBF167D629F wiki/gguf-mirust/reports/browser-module-plan-dependencies-memory-2026-06-27.md 2563 sha256:3110A860EDE9CFA733FA59E1FBC280BE4B3856135FDC7A8B5E3031041E29CDC5 wiki/gguf-mirust/reports/browser-module-plan-display-memory-2026-06-27.md 3094 sha256:A108B5BF2942B9B5BA3906FE2877FA97729E0AD8BD031D20D301156221123D24 wiki/gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28.md 3717 sha256:A3F8F48E00AE929E231D0007434C72949AE1BC0FA228F27628FD8392CF5726C6 wiki/gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28.md 3818 sha256:A41A205E9F2AE73D45A702FDFC3FF2BAA2B589D0056D4157F07D593B5BA4F1B9 wiki/gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28.md 3762 sha256:D372F255D5365898585F8908903B67996A7D962529995926B7D27783F754C25D wiki/gguf-mirust/reports/browser-module-plan-graph-drift-memory-2026-06-27.md 2479 sha256:9672865125017B6B68D563A126831042B7C3D63E856FDA7474AA1352ABEC975C wiki/gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28.md 3848 sha256:C6057779C984870809BFEE50032CFC095466971544A7AE78EF8863957AFAA8F2 wiki/gguf-mirust/reports/browser-module-plan-memory-2026-06-27.md 2756 sha256:3D7E2CA642E29DCBFC51F6C2FD95626BDABD298CD627C5885E032EEA03657CC9 wiki/gguf-mirust/reports/browser-module-plan-model-release-memory-2026-06-29.md 2971 sha256:0B5FE7AF325DD0C42DB9142C218A7385E0FF42C51ECCD37D4A3DCD3E18F5D13E wiki/gguf-mirust/reports/browser-module-plan-observed-route-set-memory-2026-06-29.md 2925 sha256:6B2E9249BE13582A0DF8AD1C59AAF83DA73B77913A5D1429D1BCE59B1428AB11 wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md 5602 sha256:E470B5CFC80EBEDE1B14CD9981C59CBC3F6EC09CD0ED6E571B8E7881E1FDA4EC wiki/gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28.md 4876 sha256:34F5A9125DEF78DAB20F0E22413C4D1B8577AB02324FF9A455B9FE04B10C1215 wiki/gguf-mirust/reports/browser-module-plan-output-limit-memory-2026-06-28.md 4292 sha256:1FCF532A72DDE97F67D7324452E35B8F2A077B4D89E202D7887F241AE2E667C7 wiki/gguf-mirust/reports/browser-module-plan-phases-memory-2026-06-27.md 3251 sha256:7110F3B1C8550EB338A471E51D3D676DE464FFA04A089F692D53C0F8A8FBCB9B wiki/gguf-mirust/reports/browser-module-plan-planned-fetch-count-memory-2026-06-29.md 3511 sha256:1EC42CAD8E48113418B19C5B3DE8C2713BA989C4A886B9D7CC54C1FFEE1BFC09 wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md 3457 sha256:59C30FC8709C4A92D9F9B3EA374C53B18126EABD5A8A08D9B8AEDA70D00C071E wiki/gguf-mirust/reports/browser-module-plan-prompt-limit-memory-2026-06-28.md 2189 sha256:2093B791B5898E269C218421764FC3B4F2EB12450D16A8FA6F2C65A83CF3FA60 wiki/gguf-mirust/reports/browser-module-plan-resource-drift-memory-2026-06-27.md 2686 sha256:B84383557F1A76E1DD1D15004D6D7BBF7C3C2AE2136DCCE25C5C8A2F13B15571 wiki/gguf-mirust/reports/browser-module-plan-resource-memory-2026-06-27.md 3092 sha256:7695A6C9455075D2E984F6A7AD9B24427B07880E269EDD486479897647167D2E wiki/gguf-mirust/reports/browser-module-plan-role-display-memory-2026-06-27.md 3215 sha256:D2E7F9732CF6B19CBBAA1010281CB18C4AD52394B04F3E20ACFFE9FD435C4B32 wiki/gguf-mirust/reports/browser-module-plan-role-drift-memory-2026-06-27.md 2747 sha256:8154A6BEAE9CD081E702FD3FE99A5E15E2F3A636C70CEC3E1CD28C0D9A5B63BE wiki/gguf-mirust/reports/browser-module-plan-route-set-algorithm-memory-2026-06-29.md 5139 sha256:7ED26846B8327B7707FC54A9B26C141914A0B8E3CE9011A978B498465CA389C7 wiki/gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29.md 4217 sha256:DF04091F0D759F281992FA33BE6B7AECA1DDEADFF44EEBCDE60300AECF8F7728 wiki/gguf-mirust/reports/browser-module-plan-route-set-version-memory-2026-06-29.md 4801 sha256:059AEC1201D4E11C5764DF2393471380FD93968270630B1C0C138FA2F501133C wiki/gguf-mirust/reports/browser-module-plan-runtime-reset-memory-2026-06-29.md 3178 sha256:99318A970ABAA9324A5C141CF78697ECC603E2B60B5B80EEE07D5F820F537301 wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md 3723 sha256:19E68CF4969FF3F34E5C54AE0C698E02035C1D4C0F42E66A73EED49068AA27F8 wiki/gguf-mirust/reports/browser-module-plan-sampler-cap-memory-2026-06-28.md 3464 sha256:B47BDDC936EE16EB489B7F28D5D208DFF630F5C914E1A76DE93B4F3F2B968612 wiki/gguf-mirust/reports/browser-module-plan-slots-memory-2026-06-27.md 2563 sha256:F96F60042441F838CA058F85AB628DBA4A48FF2AC211293A86A51C65BAD62EBB wiki/gguf-mirust/reports/browser-module-plan-stack-drift-memory-2026-06-27.md 2814 sha256:32A30EC59AAD3BE790A8B12570825E4076C29F79E44DA26D73DEA4D2D611B8C8 wiki/gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28.md 3201 sha256:DD620500D7E2AC962B0242AA8DD321186776300B0F328DC7C9113536B7FEFA92 wiki/gguf-mirust/reports/browser-module-plan-total-budget-memory-2026-06-28.md 3554 sha256:3DAB4D7483A72A60017D94A76FAC99282DDA337535752BA0AC74BB09172CBDF8 wiki/gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28.md 3761 sha256:BAE2630090806ECF120218CE59141FABA7D764D3AD53F58C8BF951070A9CCF41 wiki/gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md 3924 sha256:A9A5E5FC1C1CBAE5AE6D8EFEC71D556DDB0BD70F1E1A059B2DBD96C06E85D98E wiki/gguf-mirust/reports/browser-module-plan-wasm-heap-memory-2026-06-28.md 2998 sha256:D674ACA30BE14EDDD171E1E98CB6E045F6082D44C4398C2D80AB620A935BCDB3 wiki/gguf-mirust/reports/browser-module-plan-wasm-memory-memory-2026-06-28.md 4342 sha256:321EAE98E9A6FE2D7855AF06E3B49EB456193BF1757EE7310235574C559AABA1 wiki/gguf-mirust/reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md 3079 sha256:071E1C816B8F5A5715EF183D40832E81ADBFF036038A62928A8F268E28DBA92D wiki/gguf-mirust/reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md 14235 sha256:0D4C33B0BFF8BF0828C8F73CA3DC717CDEFF005AE9835BA7AF5FA1C4AF2F5843 wiki/gguf-mirust/reports/browser-multi-quant-selector-root-memory-2026-06-27.md 3531 sha256:4509B88D0202052A43EE3B0E4F8BF5D88EEDB4AA4809EDA8F6D667AB003D5F6C wiki/gguf-mirust/reports/browser-parent-pool-soup-bundle-memory-2026-06-29.md 6549 sha256:A1DCD6DCB1CD938542360F3068FA2D6A30F11DF1F1AE58DE18F56A7EF74CE74F wiki/gguf-mirust/reports/browser-preferred-adapter-route-memory-2026-06-27.md 3666 sha256:D37DA3659296328E7B072A721E697FD42FD128DDA60B8C0EF9E7D9D4B5CA1BA3 wiki/gguf-mirust/reports/browser-runtime-assembly-diagnostics-memory-2026-06-28.md 2982 sha256:C2CF05E8739F35C9050453610BDA3591DD349D82F05338810F03C59B6853C8B0 wiki/gguf-mirust/reports/browser-runtime-manifest-memory-2026-06-27.md 3870 sha256:228588130FDC5FB879C269F913DCF4B1C43B1A37ADC3E3443A3E0D2F0F633A56 wiki/gguf-mirust/reports/browser-selector-budget-contract-memory-2026-06-27.md 3465 sha256:2EEEC2EE7B665B4CC614E44B3190AE020ECCB73CE834C05E0FB3327EE90A59EA wiki/gguf-mirust/reports/browser-selector-budget-memory-2026-06-27.md 2374 sha256:44C0A755E57BF105708065EB05B795D710F003EADE2D0D6B985ED428CEC90DE0 wiki/gguf-mirust/reports/browser-selector-genome-fitness-memory-2026-06-28.md 2460 sha256:89755A73E94A90AC86CCFABD3DA39721E1212D71B0A14863ECF7CCC9B674EFA5 wiki/gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28.md 3749 sha256:479F96F62FA73B2B39D588BB2C5A2E7CB30EE7A8A9698270F9072041B8F47E78 wiki/gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28.md 3638 sha256:AEA83101E25E26E81495C42CA8E88A8067D5189315D9FDA12FBA8C2E5F6716C3 wiki/gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28.md 2834 sha256:704BA1F22C6482A6E5BBB1B9A3DEFE0D67D2204FB23FBD57BA2E355D51D1FB19 wiki/gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28.md 3600 sha256:5DF064A8F2F5492F02A2DAFCD7D0586A71D9E0EB847477C33B9FAAC0655AB581 wiki/gguf-mirust/reports/browser-selector-population-memory-2026-06-28.md 3280 sha256:834635F5E977FD48FAA481ACA814D37088D0238330CC28E823612C0F4541C377 wiki/gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28.md 2600 sha256:79D69E393291415095F7C8E1FA73D8060C109E0F54FE4E9E4BAB7BBE44404F7F wiki/gguf-mirust/reports/browser-source-backed-alr1-contract-memory-2026-06-28.md 2738 sha256:943C3617E1F1090B1CCB455E22694D56E87076E5EE3CD2EC4C6BD909165C0690 wiki/gguf-mirust/reports/browser-source-backed-alr1-route-memory-2026-06-28.md 2292 sha256:E68D782AA14A7142234F5F83FEA061BD6AF8D7CFB10F39A9E2C46A91FC7D0031 wiki/gguf-mirust/reports/browser-sparse-adapter-route-memory-2026-06-27.md 5612 sha256:ABA176E597769E7776FD92B812B426E04F986422C94E111896FA6D9235FEDDD3 wiki/gguf-mirust/reports/browser-text-sidecar-budget-memory-2026-06-27.md 3287 sha256:EC2C8F3A6A0A5FA58B6508905ECEF5F1229401FBB6D1928EEDAEBCF90B2101C8 wiki/gguf-mirust/reports/browser-text-sidecar-contract-memory-2026-06-27.md 3261 sha256:7A3E2D5D6B223AD5312D1CC17D7129713C45CCC8ED6A16C69814DB8E553A5018 wiki/gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29.md 4100 sha256:C5EFAA0227F89F843E96FDA76DEED5780A70992CDBAA896C2BA2C4432F25EC40 wiki/gguf-mirust/reports/crossover-operator-memory-2026-06-29.md 4818 sha256:45C75982DF21B915FAFC4E0CAF041D2A761BD144352F9B4CF1C2592C75411FEB wiki/gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29.md 2272 sha256:B4E4621B1F3725A20E2ABDE1B54B2F5A51B65F4F8DEB560B7C3ADA95E2C5D87B wiki/gguf-mirust/reports/dare-operator-memory-2026-06-29.md 4348 sha256:59BC2841527354FAE01412FF708F41236EE5FFA740688D05833BE0C59CD2C179 wiki/gguf-mirust/reports/enterprise-rust-governance-memory-2026-06-25.md 4534 sha256:150C24D20325B10BA57123EBC832B83FF08B40DA3DE6F986FEB344A203650524 wiki/gguf-mirust/reports/federated-operator-memory-2026-06-29.md 3635 sha256:C00FFA080E7971E2E05736080D03478A22429095EDD1B608E9D79960F42A0FF7 wiki/gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29.md 4845 sha256:2FAE2A02CCDBEC887074A417B24EA0B2EAF6A518908F1A317B366AD4BF5571AC wiki/gguf-mirust/reports/low-rank-adapter-package-memory-2026-06-28.md 2527 sha256:570B199DD88B8BC53FC27C40834EE2C9E6F04D3D930DB81EF5814013F9E40BA3 wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md 9114 sha256:49CF8E4B99CDFF079F484D78F5644576C5B55B92106FBC98215004E3F28E8D5D wiki/gguf-mirust/reports/multi-parent-soup-manifest-memory-2026-06-29.md 2160 sha256:8FC66ED7289E9B2E33C477EC8F43AF0D851576F2BA7825BDC20BCA306DD5C568 wiki/gguf-mirust/reports/mutation-operator-memory-2026-06-29.md 5356 sha256:5B9F1CF41251AC9A65C662952EB64893832CB276AEA0354CC41A6DE6B67BA9BB wiki/gguf-mirust/reports/operator-schedule-carry-forward-memory-2026-06-29.md 3085 sha256:927274A319833D6A83BE79B20ACB44C2589F617AA76C6BABC76EBDBDC163F960 wiki/gguf-mirust/reports/parent-pool-evolution-schedule-memory-2026-06-29.md 1996 sha256:7252D69EA8006080C29A12961736F33C8045F5161E59E91F7787FCF7A722F9CE wiki/gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29.md 4555 sha256:4AD7EC8BF5F93D3FC51332B6AF2ABE94C7AD23EC3D509554D86A706734E397C5 wiki/gguf-mirust/reports/prune-operator-memory-2026-06-29.md 6211 sha256:2FB6185B39E63EEC21374FD777B2713C648B9A06E423D42EA37962BF9FBF238C wiki/gguf-mirust/reports/registry-adapter-family-memory-2026-06-27.md 3231 sha256:D9403FB1EF61BC4A7FB79A1075573BECAE69F3FA9E741C9303FC10DBBED3ED97 wiki/gguf-mirust/reports/registry-adapter-sidecar-memory-2026-06-27.md 4106 sha256:96335F13A53262F4486265C96D01FF6F3274700EBB008400A8A0930B2AE748BB wiki/gguf-mirust/reports/report-intake-index-2026-06-25.md 6432 sha256:068DE841DDCC3D4CDEB8518274ACF1CE21004861FFDEDEE81824B408D856946D wiki/gguf-mirust/reports/report-intake-index-2026-06-26.md 6439 sha256:92BD64EC61B290C2A4CBB1DAE14622043B5714E8C6EE922145E410930F240EEB wiki/gguf-mirust/reports/report-intake-index-2026-06-28.md 3071 sha256:032CEED373BEDF5D231CF731DB1D9A607DE4EB33E13681846A11D5AE4D9CE2CA wiki/gguf-mirust/reports/runtime-adapter-apply-memory-2026-06-27.md 3202 sha256:D9221DB8D0951B0A93277C799FF4DBB32DF5FC3A4ACA12B5CC622A9359FE4B34 wiki/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29.md 3566 sha256:B420A9343C6C48AAD2C33C8D63A2E0F09D28FBE1734BC9DB31D7DBA3AC03191C wiki/gguf-mirust/reports/sparse-adapter-package-memory-2026-06-27.md 2891 sha256:618BE504A83212ABEF705E7D6037ED604091B291EAD9C8C7B34ED1DD6C64402B wiki/gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25.md 3561 sha256:2F5C442FF34005873F2E2515827CB336A6C11B5ECBCAFD99BDECBD001F278EF7 wiki/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25.md 4014 sha256:6DD5D2BD049DB4C2D7054FB24F6EC14ED6AF90B2484ACD522181E64C64F3C36E wiki/gguf-mirust/reports/trained-adapter-source-alr1-memory-2026-06-28.md 2793 sha256:B4DAC0D2681665AAAD5E9B92839428C9D6064B05D2D43FB6D7DE80B98C1AEDDB wiki/gguf-mirust/reports/trained-adapter-source-memory-2026-06-28.md 2492 sha256:6BFB7B990D93BADA6D32763802C3AA6129072FFED647E7678A1475EB739A74EF wiki/gguf-mirust/reports/two-parent-operator-browser-provenance-memory-2026-06-29.md 4229 sha256:53D1C965236A14267AD9AAAAB68DB2A77262BB4D4C085F0CFEF84A39CDEDC3CE wiki/gguf-mirust/reports/weighted-soup-operator-memory-2026-06-29.md 4301 sha256:52465109140EE8FD6846104E09496604814CB2FD959BECB586CFA1A9BD4052F7 wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md 4634 sha256:90CF6F38DAE201B934497B50113757DBD439436A65B22B98F1860B0F9767D2BE wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md 11353 sha256:8786266ADB39C382B607A431E40F2876F9A8ABD860EE025F22FF37B2F6D5E8BE wiki/gguf-mirust/source-memory-guide.md 36767 sha256:85DC5C82ECBEEF18E482BFAEE8D1C34B3F8E1585B9BBB1C89E785DA8904EAD9F wiki/global/rust-browser-harness-standards.md 521 sha256:4AFE8ECAEAD9013ADC704CA4F6FA5B4414F8DCEAFC17637AB075149C6E1A291C workspace.uai 74032 sha256:2762B139D7B5EB92B3673C458D431A7B9FD252B8FF4E82BB52B9D5EB7C62B56C BEGIN ASSEMBLED FILE CONTENTS ================================================================================ BEGIN FILE: .gitattributes BYTES: 2581 SHA256: 462475EE5301E77D2A54A64757D95C3F21FC3A79E92E6EC94BDFCC8B36E48964 ================================================================================ ############################################################################### # Set default behavior to automatically normalize line endings. ############################################################################### * text=auto ############################################################################### # Set default behavior for command prompt diff. # # This is need for earlier builds of msysgit that does not have it on by # default for csharp files. # Note: This is only used by command line ############################################################################### #*.cs diff=csharp ############################################################################### # Set the merge driver for project and solution files # # Merging from the command prompt will add diff markers to the files if there # are conflicts (Merging from VS is not affected by the settings below, in VS # the diff markers are never inserted). Diff markers may cause the following # file extensions to fail to load in VS. An alternative would be to treat # these files as binary and thus will always conflict and require user # intervention with every merge. To do so, just uncomment the entries below ############################################################################### #*.sln merge=binary #*.csproj merge=binary #*.vbproj merge=binary #*.vcxproj merge=binary #*.vcproj merge=binary #*.dbproj merge=binary #*.fsproj merge=binary #*.lsproj merge=binary #*.wixproj merge=binary #*.modelproj merge=binary #*.sqlproj merge=binary #*.wwaproj merge=binary ############################################################################### # behavior for image files # # image files are treated as binary by default. ############################################################################### #*.jpg binary #*.png binary #*.gif binary ############################################################################### # diff behavior for common document formats # # Convert binary document formats to text before diffing them. This feature # is only available from the command line. Turn it on by uncommenting the # entries below. ############################################################################### #*.doc diff=astextplain #*.DOC diff=astextplain #*.docx diff=astextplain #*.DOCX diff=astextplain #*.dot diff=astextplain #*.DOT diff=astextplain #*.pdf diff=astextplain #*.PDF diff=astextplain #*.rtf diff=astextplain #*.RTF diff=astextplain ================================================================================ END FILE: .gitattributes ================================================================================ ================================================================================ BEGIN FILE: .gitignore BYTES: 99 SHA256: 7BA27FC77F3465E64F0306A09FA7D73D3EA0CD86DF95C1E81485389F18BEB407 ================================================================================ .vs/ .vscode/ target/ x64/ *.vcxproj.user *.suo *.user .env .env.* !.env.example *.log *.tmp *.bak ================================================================================ END FILE: .gitignore ================================================================================ ================================================================================ BEGIN FILE: .uai/architecture.uai BYTES: 70546 SHA256: 508C9D4EF45AEDD20890275A9F34FDDEA6CB61E7497D5D1886E62A444723A1B2 ================================================================================ profile: gguf-mirust.architecture.v54 updated_utc: 2026-06-29T20:22:33Z active_product: name: TinyRustLM root: tinyrustlm/ goal: 100% custom Rust/WASM browser-local SLM runtime and UI. workspace_members: - tinyrustlm/runtime - tinyrustlm/tools/browser_harness - tinyrustlm/tools/slm_pack active_static_app: - tinyrustlm/app/index.html - tinyrustlm/app/app.css - tinyrustlm/app/app.js boundaries: runtime: no-crate Rust WASM runtime for memory boundary, checksum-verified f32/q8_0/q4_0 model loading, f32/q8_0/q4_0 ADP1, ASP1, and ALR1 adapter apply, runtime-owned assembly diagnostics, pre-resolved tensor index routing, artifact-backed tied-output projection fallback, custom BPE fixture loading, native q8_0/q4_0 compact storage, runtime-owned reusable row/vector scratch, reusable logits, fixed-buffer stochastic sampling, clean context-boundary request state, q8_0 and q4_0 matrix dispatch, tokenizer, math, KV cache, sampler, diagnostics, generation, ErrorCode step-token ABI, and model free. local_server: no-crate Rust loopback static server for app, WASM, .slm, and manifest hosting with GET/HEAD support and traversal rejection. mini_browser_harness: no-crate Rust contract verifier for static app UI ids, local-only markers, JS WASM boundary calls, Rust WASM export definitions, selector-registry fetch markers, model route declarations, adapter sidecar route declarations, .slm manifest sidecars, trained-quality non-claims, and loopback content types. app: static HTML/CSS/handwritten JS that fetches only local WASM, optional local selector.registry entries, selectable local .slm files, generated module-plan receipts before generated model fetches, accepted-model .slm.manifest sidecars, generated assembly receipts, generated adapter-family receipts, generated adapter manifests, and checked local f32/q8_0/q4_0 ADP1 adapter sidecar bytes, defaulting to TinyLM-16M q8_0 when no registry is present and to the registry's validated browser-frugal-quantized candidate when present, while requiring registry `selector_model_byte_budget=33554432`, requiring exact selector/manifest/receipt/evidence text budget contract fields, requiring each `entry.N.model_bytes` to fit that registry budget, requiring fetched bytes to match before WASM transfer, requiring generated module plans to declare `browser-constrained-v1`, `single-threaded-wasm-local-v1`, `local-no-store-v1`, `same-origin-loopback-local-v1`, `module_plan_fetch_count_limit=32`, `browser-constrained-local-assembly`, admitted model byte budget, adapter-family byte budget, runtime scratch budget, output byte limit, KV-cache byte budget, KV-cache page count, total self-assembly byte budget, graph metadata, byte-count metadata, checksum metadata, role metadata, phase metadata, dependency metadata, and assembly-slot metadata before `.slm` fetch, recording browser-owned module-plan trace checkpoints only after each verified load step completes, and requiring explicit adapter auto-apply fields plus `adapter_auto_apply_byte_budget=1048576` before generated receipt-preferred assembly, and while allowing TinyLM-16M q4_0, tiny BPE, tiny tied-output, and tiny f32 adapter-sidecar selection; local transcript state is rendered with DOM text nodes, Step Token calls generate_next_token only after context exists, Adapter Sidecar calls apply_adapter_delta only after a loaded compatible f32, q8_0, or q4_0 model exists, selected adapter bytes must match the route artifact checksum before WASM transfer, generated assembly evidence requires a fetched checksum-verified receipt plus fetched checksum-verified receipt-referenced evidence files after model manifest load, generated adapter-family options require fetched checksum-verified receipt and manifest files with manifest-declared adapter byte counts and artifact checksums, generated auto assembly prefetches and verifies the receipt-declared family ADP1 plus sparse ASP1 plus low-rank ALR1 stack bytes and calls Rust validate_adapter_delta for every fetched member before any Rust adapter apply, runtime Reset clears context/output, and Clear clears only transcript history. packer: no-crate Rust utility for generating checksum-bearing local f32/q8_0/q4_0 tiny fixtures, a tiny BPE fixture, a tiny tied-output fixture, plus TinyLM-16M f32, q8_0, and q4_0 smoke models, validating .slm artifact admission, writing parent compatibility reports, writing and validating candidate lineage templates, direct-parameter blend, task-delta, sparse task-delta, deterministic crossover, bounded mutation, magnitude pruning, DARE dropout/rescaled task-delta, and federated/local-update operator receipts, writing and validating trained low-rank adapter source factor bundles, converting reviewed trained source factors into runtime ALR1 packages with recomputable manifests, raw ADP1, sparse ASP1, and low-rank ALR1 adapter-delta artifacts and manifests, adapter-fuse .slm candidates and receipts from raw ADP1, adapter-family receipts, assembly receipts, module-plan receipts with `browser-constrained-v1` profile, `single-threaded-wasm-local-v1` execution profile, `local-no-store-v1` fetch policy, `same-origin-loopback-local-v1` origin policy, fetch-count envelopes, resource envelopes, runtime scratch envelopes, output byte limits, KV-cache byte/page envelopes, module byte counts, module checksums, module roles, module phases, module dependencies, and assembly slots, candidate artifact manifests, multi-parent candidate manifests, promotion templates, multi-parent promotion templates, multi-parent selector admission records, runtime-smoke sidecars, selector admission records, promotion ledgers, population reviews, parent-pool recipes, sign-aware parent-pool merge receipts, seed-weighted parent-pool soup receipts, selector registries for selector plus multi-parent admission records with browser-frugal-quantized default metadata, `selector_model_byte_budget=33554432`, selector/manifest/receipt/evidence text budget fields, optional f32/q8_0/q4_0 adapter sidecar fields plus indexed adapter-family fields, adapter-family receipt fields, module-plan profile, execution, fetch, origin, fetch-count, resource, runtime scratch, output-limit, KV-cache, and total-envelope fields, `adapter_auto_apply_byte_budget=1048576`, and assembly receipt fields, and runnable generated browser-served multi-parent bundles with app shell, WASM runtime, self ADP1, family ADP1, sparse ASP1, and source-backed low-rank ALR1 sidecars, a served module-plan receipt, a served adapter-family receipt, a served assembly receipt, and receipt-referenced evidence files in either single-quant roots or one q4-defaulted combined f32/q8_0/q4_0 selector root, validating provenance sidecars, validating raw-f32 trained-source layouts including tied_output agreement, and converting untied or tied source weights into f32/q8_0/q4_0 artifacts. docs: durable implementation docs under tinyrustlm/docs/. browser_smoke: no-dependency Node DevTools harness that verifies headless Chrome or Edge single-generate behavior, Step Token click-through, Adapter Sidecar click-through, generated receipt-preferred auto assembly before generation, combined selector assembly/cycle/route-soak/extended-route-soak/reload-soak proofs, compact blend, task-delta, sparse task-delta, federated, prune, DARE, crossover, and mutation selector operator receipt fixtures, module-plan profile, execution profile, fetch policy, origin policy, fetch count, resource, runtime scratch, output limit, KV-cache, total budget, graph, stack, role, slot, phase, dependency, byte-count, and checksum drift rejection before generated `.slm` or stack artifact fetch, assembly eval-case drift rejection before evidence or adapter-family routes, assembly evidence-file drift rejection before later evidence or adapter routes, adapter artifact checksum mismatch rejection, adapter-stack preflight drift rejection before Rust adapter apply, selector byte-budget fallback, generated assembly receipt rendering and evidence-file requests, generated adapter-family receipt and manifest fetches, conversation transcript state, served multi-parent selector-registry fixture routing, generated file-backed multi-parent bundle routing, reload/reset/q8-q4 model-switch loops, malformed local model rejection, missing local model handling, context overflow rendering, endurance loops, performance soak, recoverable model selection, and local-origin requests. visual_studio: TinyRustLM.sln and tools/vs PowerShell scripts wrap Cargo build, tests, WASM copy, model artifact checks, Rust browser harness checks, generated multi-parent bundle staging, identity-aware Rust local server reuse, busy-port fallback, and local static server run. superseded_boundary: old_members: apps/gguf-mirust-site, crates/gguf-browser-harness, crates/gguf-mirust-cli, crates/gguf-mirust-core status: removed_from_workspace_and_deleted_because_dependency_based_scaffold_conflicted_with_zero_dependency_prompt current_boundary: Tiny f32, q8_0, q4_0, custom BPE, and tied-output fixture transformer paths plus TinyLM-16M f32, q8_0, q4_0 deterministic smoke generation, checksum-bearing .slm pack/load validation, native .slm admission validation, no-crate parent compatibility reports, candidate lineage templates, direct-parameter blend, task-delta, sparse task-delta, and DARE dropout/rescaled task-delta operator receipts, raw ADP1, sparse ASP1, and low-rank ALR1 adapter-delta artifacts and manifests, adapter-fuse .slm candidates and receipts from raw ADP1, adapter-family receipts for generated compatible sidecar sets, assembly receipts for generated multi-parent evidence chains, f32/q8_0/q4_0 ADP1, ASP1, and ALR1 runtime adapter validation plus apply with package identity, checksum, tensor-directory, tokenizer, layout, fused-value validation, compact q8/q4 re-quantization, and generation-state reset on apply, checked browser tiny f32/q8_0/q4_0 self-ADP1 sidecar routing through apply_adapter_delta, registry-carried f32/q8_0/q4_0 ADP1/ASP1/ALR1 adapter routing through selector.registry with route-format apply status matched to entry quantization, plus generated f32/q8_0/q4_0 file-backed receipts and adapter manifests fetched and checksum-verified before family options are enabled, registry-carried generated module-plan routing through selector.registry with served `.module-plan.receipt` fetched and checksum-verified with fetch-policy/origin-policy/resource-class/model-byte/adapter-byte/runtime-scratch/KV-cache/total-byte envelope checks before generated `.slm` bytes and visible fetch/origin/model/adapter/scratch/KV/total budget rows, byte summaries, checksum summaries, slot summaries, role summaries, phase summaries, dependency summaries, and browser-owned trace checkpoints rendered from verified receipt metadata and verified load steps, checksum-consistent module-plan fetch-policy drift smoke proving fetch-policy mismatch, origin-policy drift smoke proving origin mismatch, runtime scratch drift smoke proving scratch-budget mismatch, total-budget drift smoke proving total envelope mismatch, resource drift smoke proving budget mismatch, graph drift smoke proving model path mismatch, stack drift smoke proving stack adapter path mismatch, role drift smoke proving module role mismatch, slot drift smoke proving assembly-slot mismatch, phase drift smoke proving lifecycle mismatch, dependency drift smoke proving edge mismatch, byte-count drift smoke proving fetched-byte mismatch, and checksum drift smoke proving module-checksum mismatch stop before generated `.slm` or stack artifact fetch, registry-carried generated assembly receipt routing through selector.registry with served receipt fetched and checksum-verified after model manifest load and receipt-referenced evidence files fetched and checksum-verified before Assembly Evidence is loaded, selector registry browser-frugal-quantized default metadata, browser selector model-byte budget intake with `selector_model_byte_budget=33554432` as the generated and validated registry envelope, selector registry text-sidecar budget contract fields with exact browser intake, registry-controlled receipt-preferred auto assembly for generated ADP1/ASP1/ALR1 sidecars with `adapter_auto_apply_byte_budget=1048576` and manifest/fetched adapter byte checks before WASM transfer, candidate artifact manifests, multi-parent candidate manifests, promotion templates, multi-parent promotion templates, multi-parent selector admission records, runtime-smoke sidecars, selector admission records, promotion ledgers, population reviews, parent-pool recipes, sign-aware parent-pool merge receipts, seed-weighted parent-pool soup receipts, and selector registries for selector plus multi-parent admission records in direct-parameter model-breeding parent sets, optional browser selector.registry intake for admitted ../models/*.slm routes, focused browser-served multi-parent selector-registry smoke, generated browser-served multi-parent f32/q8_0/q4_0 bundle routing in single-quant roots and one q4-defaulted combined f32/q8_0/q4_0 selector root, generated registry adapter-family smoke including ADP1/ASP1/ALR1 validate-then-apply before generation, generated module-plan fetch-policy/origin-policy/runtime-scratch/KV-cache/total-budget/resource-envelope plus graph-drift, stack-drift, role-drift, slot-drift, phase-drift, dependency-drift, byte-count-drift, and checksum-drift smokes before `.slm` fetch, generated assembly receipt and evidence-file smoke, combined-selector assembly trace proof across q4_0/q8_0/f32, model-load tensor index routing with artifact-backed tied-output projection fallback, q8/q4 decoded-shadow removal with runtime-owned reusable row/vector scratch, reusable logits across prompt and step generation, allocation-free top-k diagnostic candidate selection, fixed-buffer stochastic sampling with top-k cap rejection, context-boundary acceptance/rejection with clean failed-request state, 64 KiB generated-result cap with OutputBufferExceeded decode cleanup, provenance sidecar validation plus browser-visible Model Provenance panel, local conversation transcript rendering with Clear separate from runtime Reset, browser Step Token control calling generate_next_token and extending response/transcript/console after context exists, browser Adapter Sidecar control copying local .adp1 or generated .asp1/.alr1 bytes into WASM without JS parsing, raw-f32 trained-source validation, untied f32/q8_0/q4_0 conversion plus fixture-scoped eval runner, tied-output source validation plus f32/q8_0/q4_0 runtime-smoke conversion gates, runtime-smoke quality gating, assistant-quality rejection for pending or case-incomplete eval sidecars, Rust local static server, Rust mini browser contract harness with Rust export definition crawl, reload/reset/model-switch browser loop, malformed local model rejection, missing-model UI handling, context-overflow UI handling, WASM ABI invalid-boundary recovery smoke, generate_next_token ErrorCode step-token smoke, free_model smoke, validate_adapter_delta/apply_adapter_delta ABI smoke, focused browser Step Token smoke, focused browser Adapter Sidecar smoke, focused selector-budget, sidecar-budget-contract, module-plan-fetch-policy-drift, module-plan-origin-policy-drift, module-plan-runtime-scratch-drift, module-plan-kv-cache-drift, module-plan-total-budget-drift, module-plan-total-limit-drift, module-plan-resource-drift, module-plan-graph-drift, module-plan-stack-drift, module-plan-role-drift, module-plan-slot-drift, module-plan-phase-drift, module-plan-dependency-drift, module-plan-byte-drift, and module-plan-checksum-drift smokes, desktop/mobile UI audit, three-cycle q8/q4 endurance smoke, multi-token q8/q4 browser performance smoke, three-cycle q8/q4 performance soak, and Visual Studio verified-server reuse plus busy-port fallback are implemented and verified; real trained weights, trained-model quality, trained LoRA modules, and broader offline operators beyond blend, delta, sparse-delta, crossover, mutation, prune, DARE, federated, sign-merge, and soup remain pending. current_boundary_fetch_count_delta: Generated module-plan routing now also binds `module_plan_fetch_count_limit=32`, renders Module Plan `Fetch Limit`, computes planned self-assembly route count before generated model fetch, and proves `module-plan-fetch-count-drift` before `.slm` or adapter routes. current_boundary_converted_trained_all_delta: `browser-converted-trained-bundle` accepts `all` and stages converted-trained f32/q8/q4 entries into one q4-defaulted selector root with real file-backed selector/model/manifest smokes for all three entries. current_boundary_parent_pool_evolution_schedule_delta: `parent-pool-recipe` now binds a `population-based-parent-pool-replay-v1` schedule for sign-merge and soup operator families, selected parent seed weights, population fitness echoes, and an `evolution_schedule_checksum` that validation recomputes before multi-parent operator consumption. current_boundary_operator_schedule_carry_forward_delta: Sign-merge and soup receipts echo parent-pool evolution schedule identity plus scheduled family index, command, selection rule, and output gate; multi-parent candidate manifests validate those fields against the recipe, and promotion templates plus selector admission records preserve them before selector or browser bundle evidence. current_boundary_prune_delta: Deterministic magnitude pruning is implemented as `prune-candidate` plus `validate-prune-candidate`, with keep/floor ppm, selected/pruned counts, mask checksum, output-value checksum, q8 CLI proof, selector receipt carry-forward, browser Model Provenance Operator rendering, prune byte-echo fallback, and downstream candidate-manifest routing. current_boundary_dare_delta: DARE dropout/rescaled task-delta is implemented as `dare-candidate` plus `validate-dare-candidate`, with signed delta weight ppm, keep/drop ppm, dropout seed, nonzero-delta retention, selected/dropped counts, mask checksum, raw delta checksum, rescaled delta checksum, q8 CLI proof, downstream candidate-manifest routing, compact browser Model Provenance Operator proof, and byte fallback proof. current_boundary_dare_browser_delta: `dare-operator-registry` renders DARE receipt-bound Operator metadata in the compact browser provenance path, and `dare-operator-receipt-drift` proves a drifted DARE receipt falls back to static q8 before the generated route becomes selectable. current_boundary_two_parent_operator_browser_delta: Blend, task-delta, and sparse task-delta now have compact browser Model Provenance Operator proof through positive selector registry fixtures plus byte-echo fallback smokes. current_boundary_crossover_mutation_browser_delta: Deterministic crossover and bounded mutation now have compact browser Model Provenance Operator proof: `crossover-operator-registry` and `mutation-operator-registry` render receipt-bound Operator rows, while `crossover-operator-receipt-drift` and `mutation-operator-receipt-drift` prove byte-echo fallback before registry entries become selectable. text_sidecar_budget_boundary: Browser text sidecars are byte-checked before decode and parse: selector.registry at 256 KiB, `.slm` and adapter manifests at 64 KiB, receipts at 128 KiB, and assembly evidence text at 128 KiB; generated selector registries must declare exact matching contract fields before browser intake accepts entries. runtime_wasm_manifest_boundary: Browser boot verifies `runtime/tinyrustlm.wasm.manifest` before `WebAssembly.instantiate`; checked and generated roots bind runtime kind, status, path, byte count, 64-bit checksum, and next gate, with Build-TinyRustLM.ps1 refreshing the checked manifest after WASM copy. browser_module_plan_profile_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_profile=browser-constrained-v1`; Rust selector validation and app.js receipt validation require the same profile before generated model bytes or adapter-family routes are requested. browser_module_plan_execution_profile_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_execution_profile=single-threaded-wasm-local-v1`; Rust selector validation and app.js receipt validation require the same browser-local single-threaded WASM execution topology before generated model bytes or adapter-family routes are requested, and the Module Plan panel renders the verified Execution row. browser_module_plan_fetch_policy_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_fetch_policy=local-no-store-v1`; Rust selector validation and app.js receipt validation require that browser-local no-store fetch policy before generated model bytes or adapter-family routes are requested, and the Module Plan panel renders the verified Fetch row. browser_module_plan_origin_policy_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_origin_policy=same-origin-loopback-local-v1`; Rust selector validation and app.js receipt validation require that same-origin local assembly policy before generated model bytes or adapter-family routes are requested, and the Module Plan panel renders the verified Origin row. browser_module_plan_fetch_count_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_fetch_count_limit=32`; Rust selector validation and app.js receipt validation require selector/receipt agreement, app.js computes planned generated-root route count before model bytes, and the Module Plan panel renders the verified Fetch Limit row. browser_module_plan_runtime_scratch_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_runtime_scratch_byte_budget=65536`; Rust selector validation and app.js receipt validation require that runtime scratch envelope before generated model bytes or adapter-family routes are requested, and the Module Plan panel renders the verified Scratch Budget row. browser_module_plan_output_limit_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_output_byte_limit=65536`; Rust selector validation and app.js receipt validation require the generated-result cap before generated model bytes or adapter-family routes are requested, and the Module Plan panel renders the verified Output Limit row. browser_module_plan_total_budget_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_total_byte_budget`; Rust selector validation and app.js receipt validation require the exact model, manifest, assembly receipt, adapter-family receipt, stack artifact, runtime scratch, prompt-limit, output-limit, and KV-cache total before generated model bytes or adapter-family routes are requested, and the Module Plan panel renders the verified Total Budget row. browser_module_plan_total_limit_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_total_byte_budget_limit=43454464`; Rust selector validation and app.js receipt validation require that explicit cap before generated model bytes or adapter-family routes are requested, and the Module Plan panel renders the verified Total Limit row. browser_module_plan_prompt_limit_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_prompt_byte_limit=4096`; Rust selector validation and app.js receipt validation require that prompt envelope before generated model bytes or adapter-family routes are requested, the Module Plan panel renders the verified Prompt Limit row, and source roots stop oversized prompt bytes before WASM prompt transfer. browser_module_plan_wasm_memory_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_wasm_memory_initial_pages=17`; Rust selector validation and app.js receipt validation require the pre-init exported WASM page count before generated model bytes or adapter-family routes are requested, and the Module Plan panel renders the verified WASM Pages row. browser_module_plan_wasm_export_set_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_wasm_export_set=tinyrustlm-generate-v1`; Rust selector validation and app.js receipt validation require selector/receipt agreement, app.js checks the instantiated WASM exports before generated model bytes, and the Module Plan panel renders the verified WASM ABI row. browser_module_plan_wasm_heap_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_wasm_heap_min_bytes`; Rust selector validation and app.js receipt validation recompute max(64 KiB, model budget, adapter stack budget, prompt limit), app.js probes WASM alloc/dealloc before generated model bytes, and the Module Plan panel renders the verified Heap Floor row. browser_module_plan_wasm_transfer_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_wasm_transfer_strategy=copy-then-release-v1`; Rust selector validation and app.js receipt validation require selector/receipt agreement, and the Module Plan panel renders the verified Transfer row before generated model bytes. browser_module_plan_model_release_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_model_release_strategy=free-before-reassembly-v1`; Rust selector validation and app.js receipt validation require selector/receipt agreement, the Module Plan panel renders the verified Release row, and combined-selector-cycle proves `free_model` before post-initial generated reassembly. browser_module_plan_runtime_reset_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_runtime_reset_strategy=reset-context-before-assembly-v1`; Rust selector validation and app.js receipt validation require selector/receipt agreement, the Module Plan panel renders the verified Reset row, and combined-selector-cycle proves `reset_context` before adapter validation/application. browser_module_plan_adapter_validation_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1`; Rust selector validation and app.js receipt validation require selector/receipt agreement, the Module Plan panel renders the verified Validate row, and combined-selector-assembly proves `validate_adapter_delta` precedes `apply_adapter_delta`. browser_module_plan_adapter_apply_count_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_adapter_apply_count=3`; Rust selector validation requires a positive count within module cardinality, app.js receipt validation requires selector/receipt/adapter-family agreement, the Module Plan panel renders the verified Apply Count row, and generated assembly checks runtime `adapter_apply_count` diagnostics after the stack is applied. browser_module_plan_kv_cache_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_kv_cache_byte_budget` and `module_plan_kv_cache_page_count`; Rust computes the fields from validated model shape, runtime diagnostics record them after model load, app.js verifies the receipt fields before generated routes proceed, and the Module Plan panel renders verified KV Budget and KV Pages rows. browser_module_plan_adapter_stack_budget_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_adapter_stack_byte_budget=22144`; Rust bundle generation computes it from staged ADP1, ASP1, and ALR1 artifact bytes, app.js verifies selector and receipt agreement before generated model fetch, later checks fetched manifest artifact bytes against the receipt modules, and the Module Plan panel renders the verified Stack Budget row. browser_module_plan_context_token_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_context_token_limit=16`; Rust bundle generation derives it from the validated `.slm` header, selector validation matches it against model shape, app.js rechecks selector and receipt agreement before generated model fetch, and the Module Plan panel renders the verified Context row. browser_module_plan_tokenizer_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_tokenizer_checksum`; Rust bundle generation derives it from the admitted `.slm` tokenizer checksum, selector validation matches it against the model route, app.js rechecks selector and receipt agreement before generated model fetch, and the Module Plan panel renders the verified Tokenizer row. browser_module_plan_sampler_cap_boundary: Generated selector entries and served `.module-plan.receipt` files now bind `module_plan_sampler_candidate_cap=1024`; Rust selector validation, app.js registry intake, and receipt validation require the fixed-buffer sampler envelope before generated model bytes or adapter-family routes are requested, and the Module Plan panel renders the verified Sampler Cap row. browser_module_plan_fetch_count_drift_boundary: Browser-smoke `module-plan-fetch-count-drift` mutates served receipt `module_plan_fetch_count_limit` while refreshing selector module-plan checksum; app.js rejects fetch-count drift before generated model, adapter-family, adapter-manifest, or stack artifact routes. browser_module_plan_count_drift_boundary: Browser-smoke `module-plan-count-drift` mutates served receipt `module_count` while refreshing selector module-plan checksum; app.js rejects selector-to-receipt cardinality drift before generated model, adapter-family, adapter-manifest, or stack artifact routes. browser_module_plan_phase_boundary: Generated `.module-plan.receipt` files now bind module phases for model bytes, model manifest, assembly evidence, adapter-family verification, and ordered adapter-stack application; app.js verifies phases before generated model fetch and renders the verified phase summary. browser_module_plan_byte_boundary: Generated `.module-plan.receipt` files now bind exact module byte counts for model bytes, model manifest text, assembly receipt text, adapter-family receipt text, and ordered stack artifacts; app.js verifies those counts before generated model or stack artifact work and renders the verified byte summary. browser_module_plan_checksum_boundary: Generated `.module-plan.receipt` files now bind uniform module checksums for model bytes, model manifest text, assembly receipt text, adapter-family receipt text, and ordered stack artifacts; app.js verifies those checksums before generated model or stack artifact work and renders the verified checksum summary. browser_assembly_trace_boundary: Browser Module Plan Trace is app-owned sequencing evidence; app.js records checkpoints only after the corresponding verified module-plan, model, manifest, assembly, adapter-family, stack, and ready steps complete, and browser smoke asserts the exact trace for q4_0, q8_0, and f32 generated entries. browser_combined_selector_assembly_boundary: One generated `browser-multi-parent-bundle all` root now has a browser proof that q4_0 is the default, q4_0/q8_0/f32 entries switch in one page, each module plan is requested before model bytes, and each family ADP1 plus sparse ASP1 plus low-rank ALR1 stack applies before generation. browser_combined_selector_cycle_boundary: One generated `browser-multi-parent-bundle all` root now has a two-cycle browser proof that q4_0/q8_0/f32 entries can repeat in one page, every post-initial switch releases the prior WASM model before reassembly, and each pass has fresh ADP1/ASP1/ALR1 validation, apply, stack completion, reset diagnostics, and generation. browser_combined_selector_route_soak_boundary: One generated `browser-multi-parent-bundle all` root now has a three-cycle browser proof that every generated self-assembly route is requested once per pass while local WASM, model, sidecar, and adapter bytes use no-store fetches. browser_combined_selector_extended_route_soak_boundary: One generated `browser-multi-parent-bundle all` root now has a five-cycle browser proof that fifteen q4_0/q8_0/f32 assemblies make fresh local route requests, release before reassembly, validate/apply stacks in Rust, and tolerate path-flexible total-budget values. browser_combined_selector_reload_soak_boundary: One generated `browser-multi-parent-bundle all` root now has a reload-soak proof that each fresh page lifetime starts on q4_0 and rebuilds q4_0/q8_0/f32 self-assembly from local module-plan, assembly, adapter-family, manifest, and stack routes. browser_source_backed_alr1_route_boundary: Generated browser bundles convert reviewed adapter source templates into source-backed ALR1 stack members for f32/q8_0/q4_0 routes; adapter-family receipts accept source-backed ALR1 kind/dtype fields, app.js accepts those `.alr1` manifests without parsing payload bytes, and Rust validation remains the apply authority. browser_source_backed_alr1_contract_boundary: Source-backed ALR1 browser intake now requires exact source kind/dtype pairs, receipt source echoes, and fetched manifest source fields to agree before any stack artifact fetch or Rust adapter validation. browser_runtime_assembly_diagnostics_boundary: Rust diagnostics now expose `adapter_apply_count`, `last_adapter_checksum`, and `assembly_state_checksum`; generated q4_0/q8_0/f32 stacks must reach count 3 before generation, checked manual sidecars must reach count 1 after apply, and model free clears assembly state. browser_eval_case_evidence_checksum_boundary: Passed eval sidecar case evidence now has a compact `eval_case_evidence_checksum` route through selector admissions, multi-parent admissions, promotion-ledger entry copies, selector registries, generated assembly receipts, and browser Model Provenance; generated q4_0/q8_0/f32 entries must keep the registry and assembly receipt checksum matched. browser_selector_genome_fitness_boundary: Generated selector registries derive `genome_id`, genome lineage checksum, and eval-bound fitness-vector checksum from existing admission, runtime-smoke, eval, and candidate evidence; app.js validates these fields before accepting registry entries and renders Model Provenance Genome/Fitness rows. browser_selector_species_fit_boundary: Generated selector registries derive `species_id` from browser-relevant family traits and `species_fit_checksum` from selector budgets, model bytes, quantization, max tokens, and module-plan resource envelopes; app.js validates exact species strategy/status values before accepting registry entries and renders the Model Provenance Species row. browser_selector_novelty_boundary: Generated selector registries derive `novelty_id` from behavior-relevant descriptor fields and `novelty_checksum` from eval evidence plus assembly, adapter-family, and module-plan routes when present; app.js validates exact novelty strategy/status values before accepting registry entries and renders the Model Provenance Novelty row. browser_selector_population_boundary: Generated selector registries derive `population_id` from species, novelty, scoped fitness, quality, dataset, and quantization descriptors and `population_checksum` from lineage, species fit, novelty, fitness, assembly, and module-plan routes; app.js validates exact population strategy/status values before accepting registry entries and renders the Model Provenance Population row. browser_selector_mate_selection_boundary: Generated selector registries derive `mate_selection_id` from candidate id, admission kind, population id, parent-pool recipe checksum, and parent count, then derive `mate_selection_checksum` from population checksum, parent-pool recipe, sign-merge operator, population-review, promotion-ledger, admission-set, and admission checksums; app.js validates exact mate-selection strategy/status/parent-count values before accepting registry entries and renders the Model Provenance Mate Selection row. browser_selector_phenotype_evidence_boundary: Generated selector registries derive `phenotype_evidence_id` and `phenotype_evidence_checksum` from provenance, runtime-smoke, eval, eval-case, assembly, mate-selection, and fitness evidence; app.js validates exact phenotype strategy/status values before accepting registry entries and renders the Model Provenance Phenotype row. browser_selector_heritable_artifact_boundary: Generated selector registries derive `heritable_artifact_id` from served artifact identity plus genome context and `heritable_artifact_checksum` from lineage, phenotype, fitness, provenance, runtime, adapter-family, assembly, and module-plan evidence; app.js validates exact artifact strategy/status values before accepting registry entries and renders the Model Provenance Artifact row. browser_assembly_eval_case_drift_boundary: Generated assembly receipt eval digests now gate self-assembly before evidence or adapter-family routes; app.js frees accepted model state and records `assembly evidence rejected` when the receipt digest differs from selector metadata. browser_assembly_evidence_file_drift_boundary: Generated assembly evidence-file bytes now have a browser smoke gate after assembly receipt validation; app.js frees accepted model state and records `assembly evidence rejected` when a fetched receipt-referenced evidence file checksum differs, before later evidence or adapter routes. browser_adapter_manifest_drift_boundary: Generated adapter manifest bytes now have a browser smoke gate after adapter-family receipt validation; app.js keeps the accepted model loaded and stops before later adapter manifests or stack artifacts when a fetched family ADP1 manifest checksum differs. browser_adapter_artifact_drift_boundary: Generated adapter artifact bytes now have a browser smoke gate after all adapter manifests validate; app.js keeps the accepted model loaded and stops before later stack artifacts or Rust adapter apply when fetched family ADP1 bytes differ. browser_adapter_stack_prefetch_boundary: Generated receipt-declared auto stacks are preflighted as fetched ADP1/ASP1/ALR1 byte buffers before any Rust adapter apply; sparse ASP1 drift after family ADP1 fetch stops before low-rank ALR1 fetch or apply_adapter_delta. browser_adapter_stack_rust_validate_boundary: Generated receipt-declared auto stacks must pass Rust `validate_adapter_delta` for every fetched member before the first `apply_adapter_delta`; validation uses the same parser and tensor payload checks as apply while preserving generation diagnostics. browser_adapter_stack_rust_validate_drift_boundary: Checksum-consistent generated stack bytes can pass browser route, byte, and checksum gates while Rust identity validation still stops mutation; `adapter-stack-rust-validate-drift` proves family ADP1 identity drift returns `shape mismatch` before apply_adapter_delta. report_derived_architecture_memory: enterprise_quality: Small trusted surface, explicit model validation, visible diagnostics, deterministic tests, and no third-party runtime crates are the enterprise posture for this prompt. browser_runtime: JS fetches local WASM/model files and renders state; Rust owns .slm parsing, inference, errors, memory, tokenizer, quantization, and diagnostics. runtime_manifest: Runtime WASM bytes are now a manifest-bound local module; browser boot must verify the Rust module before selector registries, models, adapter families, or assembly receipts assemble. browser_module_plan: Generated selector entries now carry served module-plan receipts with profile, execution profile, fetch policy, origin policy, tokenizer checksum, sampler candidate cap, WASM memory initial pages, resource class, admitted model byte budget, adapter-family byte budget, exact adapter-stack byte budget, runtime scratch byte budget, output byte limit, KV-cache byte budget, KV-cache page count, total self-assembly byte budget, module byte-count fields, module checksum fields, module role fields, phase fields, dependency fields, and typed assembly-slot fields; browser verification fetches the plan before model bytes, matches execution/fetch/origin/tokenizer/sampler-cap/WASM-pages/envelope/output-limit/graph/byte/checksum/role/slot/phase/dependency/stack metadata, renders verified receipt fields including visible execution, fetch, origin, Tokenizer, Sampler Cap, WASM Pages, model, adapter, stack, scratch, Output Limit, KV Budget, KV Pages, and total budget rows plus ordered byte, checksum, slot, role, phase, dependency, and trace summaries in the Module Plan panel, and execution-profile/fetch-policy/origin-policy/tokenizer/sampler-cap/wasm-memory/output-limit/kv-cache/adapter-stack-budget/runtime-scratch/total-budget/count/resource/graph/stack/role/slot/phase/dependency/byte/checksum drift smokes plus combined-selector-assembly prove checksum-consistent receipt drift and all-root switching respect the plan-before-model gate. browser_module_plan_wasm_export_set: Generated module-plan receipts now carry `module_plan_wasm_export_set=tinyrustlm-generate-v1`; browser verification checks selector/receipt agreement plus instantiated exports, renders WASM ABI, and `module-plan-wasm-export-set-drift` gates generated routes. browser_module_plan_wasm_heap: Generated module-plan receipts now carry `module_plan_wasm_heap_min_bytes`; browser verification recomputes the floor, probes WASM allocation, renders Heap Floor, and `module-plan-wasm-heap-drift` gates generated routes. browser_module_plan_wasm_transfer: Generated module-plan receipts now carry `module_plan_wasm_transfer_strategy=copy-then-release-v1`; browser verification checks selector/receipt agreement, renders Transfer, and `module-plan-wasm-transfer-drift` gates generated routes. browser_module_plan_model_release: Generated module-plan receipts now carry `module_plan_model_release_strategy=free-before-reassembly-v1`; browser verification checks selector/receipt agreement, renders Release, `module-plan-model-release-drift` gates generated routes, and combined-selector-cycle proves release before reassembly. browser_module_plan_runtime_reset: Generated module-plan receipts now carry `module_plan_runtime_reset_strategy=reset-context-before-assembly-v1`; browser verification checks selector/receipt agreement, renders Reset, `module-plan-runtime-reset-drift` gates generated routes, and combined-selector-cycle proves reset before adapter work. browser_module_plan_adapter_validation: Generated module-plan receipts now carry `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1`; browser verification checks selector/receipt agreement, renders Validate, `module-plan-adapter-validation-drift` gates generated routes, and combined-selector-assembly proves Rust validation before adapter apply. browser_module_plan_adapter_apply_count: Generated module-plan receipts now carry `module_plan_adapter_apply_count=3`; browser verification checks selector/receipt/adapter-family agreement, renders Apply Count, `module-plan-adapter-apply-count-drift` gates generated routes, and runtime diagnostics must report the planned adapter apply count after generated assembly. browser_assembly_eval_case_drift: Generated assembly eval digest matching now has its own smoke route; selector, module-plan, and assembly receipt checksums can be internally aligned while the eval digest gate still stops before evidence and adapter-family work. browser_adapter_manifest_drift: Generated adapter manifest checksum matching now has its own smoke route after adapter-family receipt verification; same-byte family ADP1 manifest drift stops before later manifests or stack artifacts. browser_adapter_artifact_drift: Generated adapter artifact checksum matching now has its own smoke route after all adapter manifests verify; family ADP1 byte drift stops before sparse/low-rank artifacts or Rust adapter apply. browser_adapter_stack_prefetch_drift: Generated auto-assembly stack preflight now has its own smoke route after all adapter manifests verify; sparse ASP1 byte drift after family ADP1 fetch stops before low-rank ALR1 fetch or Rust adapter apply. browser_adapter_stack_rust_validate: Generated auto-assembly stack validation now has a Rust semantic preflight route; q4/q8/f32 smokes prove validate_adapter_delta calls precede stack apply calls. browser_adapter_stack_rust_validate_drift: Generated auto-assembly now has a checksum-consistent semantic-drift smoke; browser metadata and artifact checksum echoes align, then Rust validate_adapter_delta returns shape mismatch before apply. browser_module_plan_dependencies: Generated module-plan receipts now carry `module.N.depends_on` edges from runtime WASM through model, manifest, assembly, adapter-family, and stack modules; browser verification and drift smoke gate generated fetches on that chain. browser_module_plan_phases: Generated module-plan receipts now carry `module.N.phase` lifecycle fields; browser verification and `module-plan-phase-drift` gate generated model and stack artifact fetches on those phases. browser_adapter_stack: Generated adapter-family receipts now declare ordered auto-apply stack members; selector registries carry matching stack fields and browser verification validates then applies family ADP1 plus sparse ASP1 plus low-rank ALR1 before generation. low_rank_adapter_artifacts: ALR1 is now a runtime, packer, and generated browser adapter-family route lane for deterministic low-rank matrix task deltas with factor metadata. browser_transcript: Treat conversation history as browser-local UI state; render text with DOM nodes, test Clear versus Reset semantics, and keep it out of Rust runtime/model claims. model_abi: The .slm header, tensor directory, byte or BPE tokenizer metadata, quantization fields, checksum, model dimensions, explicit ErrorCode exports, step-token result text, diagnostics token id, and model-free state are the seed of any future local model ABI. model_admission: Future trained or converted models must pass native .slm validation before browser/runtime claims. model_provenance: Every generated or converted model should carry a line-based sidecar binding checksum, shape, source kind, admission status, and quality-claim boundary before UI/runtime claims. converted_trained_file_route: `browser-converted-trained-bundle` is the current file-backed converted-source browser route; it must stage a converted `.slm`, provenance manifest, evidence sidecars, selector admission, and `models/selector.registry` under a runnable TinyRustLM root. model_quality_gate: Runtime-smoke claims can pass deterministic-smoke evidence; assistant-quality claims require converted-trained provenance plus a matching passed evaluation sidecar with task-eval, quality scope, case totals, and exact per-case output evidence. trained_source_boundary: Converted-trained artifacts must originate from a validated raw-f32 source manifest with safe tensor paths, exact shapes and byte counts, source checksums, finite bounded values, nonzero tensor payloads, and model_shape/tied_output agreement; untied f32, q8_0, q4_0 outputs have eval gates, while tied outputs have runtime-smoke gates across all three modes. trained_adapter_source_boundary: Trained low-rank adapter source bundles must originate from `adapter-source.manifest` plus safe factor files under `factors/`; validation binds model shape, tied-output contract, target tensor names and hashes, factor ranks, byte counts, checksums, finite bounded factors, factor parameter counts, and reconstructed delta L1 before source-backed ALR1 package conversion. trained_adapter_source_alr1_boundary: Source-backed ALR1 conversion validates the source bundle plus base `.slm`, checks shape, tied-output contract, byte tokenizer, tensor layout, target tensor hashes/ranks/dims, writes ALR1 bytes with source factors in component-major runtime layout, and validates by exact artifact and manifest recomputation. quantized_storage_boundary: Runtime q8_0 and q4_0 tensors stay in native compact storage and reject borrowed f32 slices; only explicit copy methods dequantize rows or full small vectors into runtime-owned reusable scratch. allocation_boundary: Generation scratch, logits, and tensor routing are established with the loaded model and reused across prompt generation and step-token calls; top-k diagnostics and stochastic sampling scan into fixed arrays. output_boundary: Generated result decode is capped at 64 KiB; byte and BPE decoders return OutputBufferExceeded before replacing last_result, and full generate failures clear stale token/cache diagnostics. modular_future: Multi-model routing, LoRA or quantized adapter families, skill packages, speculative decoding, WebGPU, OPFS, workers, and persistence are future lanes after TinyLM-16M correctness and benchmark proof. model_breeding_future: Model breeding means offline candidate lineage with compatible parent artifacts, parent compatibility reports, lineage templates, blend, task-delta, sparse task-delta, DARE dropout/rescaled task-delta, and sign-merge operator receipts, trained adapter source manifests, adapter-delta manifests, adapter-fuse receipts, f32/q8_0/q4_0 ADP1 runtime adapter apply, candidate artifact manifests, multi-parent candidate manifests, promotion templates, multi-parent promotion templates, multi-parent selector admission records, runtime-smoke sidecars, selector admission records, promotion ledgers, population reviews with objective-vector metadata, parent-pool recipes, selector registries for both admission families, generated browser bundle staging, registry-carried adapter families with browser-verified receipts and manifests, browser-verified assembly receipts with evidence-file fetches, operator metadata, generated .slm or adapter outputs, and eval sidecars; browser runtime support consumes admitted registry routes only after served-model staging. model_breeding_concept_map: Heritable artifacts map to .slm/manifests/receipts/eval sidecars, mate selection maps to compatibility/population/parent-pool routes, phenotype evidence maps to runtime-smoke/eval/provenance/browser-smoke records, and speciation-fit maps to quantization/tokenizer/layout/adapter/resource envelopes. breeding_compatibility_boundary: tinyrustlm-slm-pack compatibility is the current parent-set gate; parameter-level merges require exact version, tensor schema, tokenizer checksum, quantization semantics, vocab size, parameter count, tensor layout checksum, and output-head agreement; heterogenous parents route to distillation or retraining. blend_operator_boundary: tinyrustlm-slm-pack blend-candidate is the current offline operator gate; it requires validated lineage, compatibility-bound parent checksums, deterministic weighted tensor blending, normal .slm validation, and recomputable receipt validation. task_delta_operator_boundary: tinyrustlm-slm-pack delta-candidate is the current task-vector operator gate; it requires validated lineage, compatibility-bound base and target parent checksums, signed parts-per-million delta weights, normal .slm validation, and recomputable receipt validation. sparse_delta_operator_boundary: tinyrustlm-slm-pack sparse-delta-candidate is the sparse task-vector operator gate; it requires validated lineage, compatibility-bound base and target parent checksums, signed delta weights, absolute-delta keep rate, selected parameter counts, density ppm, nonzero-delta retention ppm, implicit top-k mask checksum, normal .slm validation, and recomputable receipt validation. prune_operator_boundary: tinyrustlm-slm-pack prune-candidate is the magnitude pruning operator gate; it requires validated lineage, compatibility-bound base and reference parent checksums, keep and floor ppm parameters, deterministic magnitude ranking, selected/pruned counts, mask checksum, output-value checksum, normal .slm validation, and recomputable receipt validation. dare_operator_boundary: tinyrustlm-slm-pack dare-candidate is the DARE-style task-delta dropout operator gate; it requires validated lineage, compatibility-bound base and target parent checksums, signed delta weight ppm, keep/drop ppm, dropout seed, deterministic nonzero-delta mask selection, inverse-keep rescaling, mask/raw-delta/rescaled-delta checksums, normal .slm validation, and recomputable receipt validation. adapter_delta_artifact_boundary: tinyrustlm-slm-pack adapter-delta and sparse-adapter-delta are modular adapter artifact gates; they require validated lineage, compatibility-bound base and target parent checksums, ADP1 raw or ASP1 sparse f32 task-delta bytes, recomputable manifest validation, and runtime f32/q8_0/q4_0 apply status while raw ADP1 also supports fuse status. adapter_fuse_boundary: tinyrustlm-slm-pack fuse-adapter-delta is the raw adapter-to-.slm bridge; it validates the ADP1 package and manifest, checks ADP1 header and tensor directory metadata against the base parent, writes a normal .slm candidate, and records a recomputable fuse receipt. runtime_adapter_apply_boundary: Runtime apply accepts compatible ADP1 raw, ASP1 sparse, and ALR1 low-rank packages for loaded f32, q8_0, and q4_0 models; validate identity, package checksum, payload checksums, tensor layout, tokenizer checksum, tensor directory, finite deltas or factors, sparse indexes or low-rank shapes, and fused values before mutating or compact re-quantization, then clear generation and KV state on success while recording runtime assembly diagnostics. runtime_assembly_diagnostics_boundary: Model load seeds nonzero assembly state, `validate_adapter_delta` preserves apply count, successful `apply_adapter_delta` increments `adapter_apply_count` and records nonzero adapter/assembly checksums, and free or load failure clears assembly fields. browser_adapter_sidecar_boundary: Browser adapter sidecars are local .adp1 routes for checked tiny fixtures and local .adp1, .asp1, or .alr1 routes for generated adapter families; JavaScript filters routes, verifies adapter-family preferred and stack fields before default selection or startup apply, checks selected artifact checksums before WASM transfer, prefetches and verifies all generated receipt-declared auto-stack bytes before the first apply_adapter_delta call, auto-validates generated receipt-declared stacks through validate_adapter_delta only when selector auto-apply fields and `adapter_auto_apply_byte_budget=1048576` are explicit and verified, checks manifest-declared and fetched adapter byte counts, calls apply_adapter_delta only after validation and transfer, and lets Rust own package structure plus clear generation state on apply. registry_adapter_family_boundary: Selector registries may carry optional f32/q8_0/q4_0 adapter route fields, indexed adapter-family fields, adapter-family receipt fields, explicit adapter auto-apply fields, and adapter stack fields for admitted entries; generated bundles stage self ADP1, family ADP1, sparse ASP1, and low-rank ALR1 packages, manifests, and a served .adapter-family.receipt under models/, app.js fetches and checksum-verifies the receipt plus route-derived adapter manifests, verifies the receipt-bound preferred adapter and ordered stack index/path/manifest fields, defaults to the preferred sparse ASP1 member while still auto-applying the declared family ADP1 plus sparse ASP1 plus low-rank ALR1 stack before generation when the registry stack strategy is receipt-declared-compatible-stack, browser smoke requires those requests and proves full-stack preflight plus pre-generation stack apply, and Rust remains the package validator. assembly_receipt_boundary: Selector registries may carry optional assembly receipt fields for generated multi-parent entries; generated bundles stage a served .assembly.receipt under models/ that binds the model manifest, ledger, review, recipe, operator, candidate, promotion, runtime, eval, admission, eval-case digest, and adapter-family evidence by checksum; app.js fetches and verifies the receipt after model manifest load, matches the eval digest before evidence routes, fetches/checksums each receipt-referenced evidence file, and renders Assembly Evidence fields; browser smoke requires the receipt request, evidence-file requests, displayed parent/operator/ledger/next-gate evidence, and assembly-eval-case-drift proof for digest mismatch handling. candidate_manifest_boundary: tinyrustlm-slm-pack candidate-manifest is the current produced-artifact gate; it records lineage checksum, candidate .slm checksum, shape, tokenizer checksum, tensor layout checksum, direct-parent contract, pending eval status, and next promotion gate. promotion_boundary: tinyrustlm-slm-pack promotion-template is the current pre-promotion gate; it records candidate manifest checksum, pending runtime-smoke/eval statuses, not-admitted browser selector state, and not-admitted public-claim state. runtime_smoke_boundary: tinyrustlm-slm-pack runtime-smoke is the current execution-evidence sidecar; it binds provenance manifest checksum, slm checksum, source kind, model shape, and runtime-smoke decision. selector_admission_boundary: tinyrustlm-slm-pack admission-record is the current evidence-passed selector gate; it binds promotion, runtime-smoke, and passed converted-trained eval sidecars before selector registry routing. promotion_ledger_boundary: tinyrustlm-slm-pack promotion-ledger is the current admitted-history gate; it hash-chains selector admission records, rejects duplicate candidates or artifacts, and routes to selector registry or population review. population_review_boundary: tinyrustlm-slm-pack population-review is the current admitted-population gate; it validates the promotion ledger against admissions, ranks candidates, records weighted objective-vector metadata plus per-entry objective checksums, selects a frontier, and routes parent-pool candidates. parent_pool_recipe_boundary: tinyrustlm-slm-pack parent-pool-recipe is the reviewed-parent planning gate; it validates the population review, requires shared direct-parameter contract fields, records fitness-normalized seed weights plus relatedness metric, scope, pair count, status, checksum, and per-parent groups, and now records a checksum-bound sign-merge plus soup evolution schedule before multi-parent operator work. sign_merge_operator_boundary: tinyrustlm-slm-pack sign-merge-candidate is the reviewed-parent operator gate; it validates parent-pool recipe, ledger, review, admissions, and parent .slm files, then writes seed-weighted sign-consensus .slm candidates with recomputable receipts that echo parent relatedness plus scheduled-family fields before multi-parent-candidate-manifest. multi_parent_candidate_manifest_boundary: tinyrustlm-slm-pack multi-parent-candidate-manifest is the parent-pool operator artifact gate; it validates sign-merge or soup receipts by operator_kind, validates scheduled-family fields against the parent-pool recipe, binds receipt checksum, parent-pool recipe checksum, relatedness summary, parent summaries, sign or soup operator metrics, candidate .slm fields, pending eval status, and next promotion route. multi_parent_promotion_boundary: tinyrustlm-slm-pack multi-parent-promotion-template is the sign-merge/soup promotion handoff; it validates multi-parent candidate manifests, binds candidate manifest checksum, receipt checksum, recipe checksum, parent count, scheduled-family fields, candidate .slm fields, and pending runtime-smoke/eval status. multi_parent_admission_boundary: tinyrustlm-slm-pack multi-parent-admission-record is the sign-merge/soup evidence handoff; it validates multi-parent promotion templates, runtime-smoke, provenance, and passed eval sidecars, binds parent-pool/candidate/evidence checksums, verifies scheduled family kind against the bound operator receipt, and feeds selector-registry route binding. selector_registry_boundary: tinyrustlm-slm-pack selector-registry is the current browser route gate; it consumes selector admission records and multi-parent admission records, requires served tinyrustlm/models candidate paths, writes ../models/*.slm routes plus browser-frugal-quantized default metadata, `selector_model_byte_budget=33554432`, `selector_registry_text_byte_budget=262144`, `manifest_text_byte_budget=65536`, `receipt_text_byte_budget=131072`, `evidence_text_byte_budget=131072`, optional f32/q8_0/q4_0 adapter sidecar, indexed adapter-family fields, adapter-family receipt fields, adapter auto-apply fields, module-plan profile, execution profile, fetch policy, origin policy, resource, runtime scratch, KV-cache byte budget, KV-cache page count, and total byte budget fields, `adapter_auto_apply_byte_budget=1048576`, and assembly receipt fields for generated bundles, app.js can consume models/selector.registry when present only when the registry budgets match the browser envelopes, entry model byte counts fit the model budget, fetched model bytes match the declared count, generated module plans match selector profile, execution profile, fetch policy, origin policy, resource class plus model/adapter/runtime-scratch/KV-cache/total byte budgets and per-module checksums before model fetch, auto-apply fields match the receipt-preferred-compatible contract, and auto-assembled adapter bytes fit the family budget, browser-smoke multi-parent-registry proves the fixture route shape, selector-budget proves oversized registry entries fall back before model fetch, sidecar-budget-contract proves text-budget drift falls back before model fetch, module-plan-execution-profile-drift, module-plan-fetch-policy-drift, module-plan-origin-policy-drift, module-plan-runtime-scratch-drift, module-plan-kv-cache-drift, module-plan-total-budget-drift, module-plan-total-limit-drift, module-plan-resource-drift, module-plan-graph-drift, module-plan-stack-drift, module-plan-role-drift, and module-plan-checksum-drift prove checksum-consistent receipt drift stops before generated `.slm` or stack artifact fetch, multi-parent-registry-file proves generated file-backed routes, and adapter-sidecar-registry-file proves registry-supplied default selection, module-plan receipt request, assembly receipt and evidence-file verification, adapter-family receipt and manifest verification, plus pre-generation apply. selector_registry_fetch_count_delta: selector-registry generated routes now require `entry.N.module_plan_fetch_count_limit=32`; validation rejects missing or drifted fields and browser-smoke `module-plan-fetch-count-drift` proves no generated model or adapter route follows mismatch. browser_bundle_boundary: tinyrustlm-slm-pack browser-multi-parent-bundle accepts f32, q8_0, q4_0, or all and stages app shell, WASM runtime, runtime WASM manifest, matching multi-parent-sign-merge model entries, manifests, selector.registry with `selector_model_byte_budget=33554432` plus exact text-sidecar budget contract fields, module-plan profile, execution profile, fetch policy, origin policy, resource, runtime scratch, KV-cache byte budget, KV-cache page count, and total byte budget fields, byte counts, checksums, roles, and assembly slots, adapter auto-apply fields plus `adapter_auto_apply_byte_budget=1048576`, self ADP1, family ADP1, sparse ASP1, and source-backed low-rank ALR1 sidecars, adapter manifests, module-plan receipts, adapter-family receipts, assembly receipts, and evidence chains under a target TinyRustLM root so browser-smoke can load one or three generated multi-parent routes from files, verify served module-plan profile/execution/fetch/origin/resource/runtime-scratch/KV-cache/total-byte envelopes, byte summaries, checksum summaries, slot summaries, and role summaries before model fetch, verify served assembly receipts and receipt-referenced evidence files, verify served adapter receipts and adapter manifests including artifact byte counts and checksums, default combined roots to q4_0 through browser-frugal-quantized selector metadata, switch selector entries in the combined root, run one same-page combined-selector-assembly proof across q4_0/q8_0/f32, and auto-apply registry-supplied family ADP1 plus sparse ASP1 plus source-backed low-rank ALR1 stacks before generation while preserving the selected quantization mode. browser_bundle_fetch_count_delta: browser-multi-parent-bundle now writes `module_plan_fetch_count_limit=32` into selector registries and served receipts for generated f32/q8_0/q4_0 roots, and combined-selector-assembly verifies `32 fetches` for each entry. code_beading_memory: Break model-breeding work into durable beads: source manifest, compatibility check, lineage template, blend, task-delta, sparse task-delta, DARE dropout/rescaled task-delta, or sign-merge operator receipt, raw ADP1 or sparse ASP1 adapter-delta artifact manifest, adapter-fuse receipt, adapter-family receipt, adapter-stack receipt fields, module-plan receipt with resource envelope, runtime scratch, KV-cache byte/page envelope, total byte budget, module byte counts, module checksums, module roles, and assembly slots, assembly receipt plus fetched evidence-file chain, eval-case evidence checksum, selector genome, species-fit, novelty, and fitness-vector checksums, f32/q8_0/q4_0 runtime adapter apply, browser runtime WASM manifest, browser adapter sidecar route, registry adapter-family route with browser-verified receipt and manifests, registry-controlled auto assembly, adapter auto-assembly byte budget, selector frugal default, selector byte-budget intake, selector_model_byte_budget contract, selector text-sidecar budget contract, candidate artifact manifest, multi-parent candidate manifest, promotion template, multi-parent promotion template, multi-parent admission record, runtime-smoke sidecar, eval sidecar, selector admission record, promotion ledger, population review with objective-vector checksum, parent-pool recipe, checksum-bound parent-pool evolution schedule, operator schedule carry-forward, selector registry for both admission families, generated browser bundle staging, and provenance display. code_beading_phase_memory: Treat module-plan phases as another bead field beside resource envelopes, roles, slots, and dependencies; every generated phase display or drift proof routes to the phase report. research_reference_boundary: Model soups, Git Re-Basin, task arithmetic, TIES, DARE, Model Breadcrumbs, model kinship, evolutionary merge recipes, Mergenetic-style adaptive search, multi-objective evolutionary merging, LoRA, FedAvg, evolution strategies, EWC, PackNet, lottery tickets, adapters, QLoRA, PBT, browser-constrained assembly receipts, UAIX memory strategy, heritable-artifact routing, mate-selection routing, phenotype-evidence routing, and speciation-fit routing are research lanes recorded in wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md; ModelBreeder genome/fitness/novelty/population/speciation guidance plus zero-dependency Wasm SIMD, hierarchical quantization, tokenizer/sampler, KV-cache, allocator, multimodal, and telemetry guidance are recorded in wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md; DARE-style dropout/rescaled task-delta maps to dare-candidate with deterministic nonzero-delta masking, inverse-keep rescaling, and mask/raw/rescaled delta checksums; sparse selection maps to sparse-delta-candidate and sparse-adapter-delta with retention and implicit mask metadata, TIES-style sign consensus maps to sign-merge-candidate plus multi-parent candidate manifests, promotion templates, admission records, selector route binding, browser-served registry smoke, and generated browser bundle routing, model-soup averaging maps to soup-candidate plus the shared multi-parent candidate manifest gate, kinship maps to parent-pool relatedness checksums echoed through sign-merge or soup receipts and multi-parent candidate manifests, breadcrumbs map to sparse-mask records, multi-objective fitness maps to population-review objective-vector metadata, evolutionary recipes and PBT-style selection now map to population reviews plus parent-pool recipes with checksum-bound operator-family schedules and receipt-level schedule carry-forward, LoRA maps to trained low-rank adapter source validation plus source-backed ALR1 conversion, source-backed browser ALR1 routing, and source-backed ALR1 receipt/manifest provenance checks, with real trained factor bundles still a future lane beyond the current deterministic source-backed route, browser-constrained assembly maps to module-plan/resource/byte/phase/dependency/slot receipt gates, zero-dependency runtime ideas map to deterministic fixtures plus browser smokes before source claims, UAIX memory strategy maps to raw/wiki/short-term/long-term routing, and concept lanes map to compatibility fields, receipts/manifests, eval/provenance fields, and browser-smoke assertions. teleodynamic_translation: Treat resource-bounded ideas as measurable states: context length, scratch arena, KV length, load phase, reset behavior, failure recovery, and latency. brand_boundary: Position TinyRustLM as a transparent browser-local Rust/WASM SLM runtime; do not claim trained-quality assistant behavior, GGUF import, or Mini Browser orchestration yet. site_voice_boundary: Read .uai/taboo.uai before changing public copy; keep GGUF.MiRust.com centered on constructive local-model craft, lineage, and proof. productive_tensions: - More crawlable memory versus pointer-only discipline: hot .uai files need synthesis; long-term ledger stays routed and checksummed. - General model compatibility versus auditability: stabilize one .slm path before broad import or routing behavior. - Runtime richness versus local-only proof: every new browser capability must preserve local-origin smoke evidence. - Philosophy versus engineering: teleodynamic ideas must become metrics, states, tests, or UI recovery behavior. - Token ids versus ABI errors: browser-callable exports should return explicit ErrorCode values and route payload details through result buffers or diagnostics. - Model-breeding ambition versus runtime proof: each operator must stay offline and feed ordinary .slm validation, manifests, runtime-smoke, eval, selector admission, and registry routing before browser UI claims. ================================================================================ END FILE: .uai/architecture.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/coding-standards.uai BYTES: 57785 SHA256: 3BBC6B439158967A09B6FCF747FD08E21FBB1D0357C1A82FD480EA4B0BFA08C2 ================================================================================ profile: gguf-mirust.coding-standards.v48 updated_utc: 2026-06-29T18:46:12Z rust: edition: 2021 dependency_policy: No third-party Rust crates in TinyRustLM runtime or packer. unsafe_policy: Unsafe is allowed only at the WASM memory boundary where raw browser pointers must become slices; keep it isolated in memory.rs and wasm_exports.rs with explicit validation. formatting: cargo fmt --all tests: cargo test --workspace coverage_target: Aim for at least 75% automated test coverage on changed code; record the coverage command or the available test evidence when no coverage tool is active. parameter_test_rule: Each new or changed method parameter should have an automated test that exercises the parameter's accepted path, rejection path, or boundary effect. test_file_naming_rule: When adding standalone test files, mirror the tested source filename and append `_test` before the extension; inline Rust unit tests remain acceptable when they are the local module pattern. method_comment_rule: Each new or changed public method should carry a short doc comment or nearby explanatory comment that states its project role without restating obvious code. parameter_test_policy: Every method or function parameter added or changed should have an automated test assertion related to behavior controlled by that parameter. test_file_naming: New standalone test files should mirror the source filename with `test` appended before the extension in a toolchain-safe form, such as `adapter_family_test.rs` for `adapter_family.rs`; keep inline Rust module tests where they fit local patterns. error_handling: use explicit ErrorCode values across runtime and WASM boundaries; do not add anyhow, thiserror, serde, rand, tokenizer, ML, or web framework crates. generation_memory: allocate generation scratch, logits, and tensor routing with the loaded model, reuse them across token work, and do not add vocab-sized per-token diagnostic/sampling vectors or per-token layer-name formatting. generation_state: each generate request starts from clean prompt/cache diagnostics, errors must not preserve stale generated counts or KV length, and successful generation must extend token state for generate_next_token. output_result_boundary: generated result decode must stay capped, OutputBufferExceeded must not replace a caller's previous decoded output, and full generate overflow must clear stale generation state. tokenizer_support: custom tokenizer work must include native .slm validation plus a runtime fixture proving tokenizer diagnostics, not parser-only tests. public_docs: every public Rust function should carry a doc comment before completion. method_comments: Every method or function should include a concise explanatory comment or doc comment that states purpose, contract, parameter semantics, or a non-obvious invariant without restating obvious code. runtime_assembly_diagnostics: Runtime diagnostics must keep adapter apply count and assembly checksums Rust-owned; model load seeds assembly state, validation preserves count, successful apply increments count and records checksums, and free or failed load clears the fields. runtime_kv_cache_diagnostics: Runtime diagnostics must keep KV-cache byte budget and page count Rust-owned; model load records values computed from loaded shape, load failure or free clears them, and runtime tests must cover every shape parameter involved in the byte-budget formula. browser_runtime: rule: JavaScript only fetches local static WASM/model files, copies bytes into WASM memory, calls exports, and renders UI. forbidden: npm dependencies, CDNs, frontend frameworks, remote inference APIs, telemetry, analytics, hidden model downloads, wasm-bindgen, Transformers.js, ONNX Runtime, Candle, tokenizers crate. report_derived_rules: - Fetch failure, missing model, malformed model, context overflow, and reset recovery must remain user-visible and smoke-tested. - Model-specific failure should disable Generate and Reset while preserving model selection once WASM is loaded. - Browser smoke must keep checking local-only network requests as a privacy claim verifier. - Browser smoke must include multi-parent-registry mode after selector-registry route behavior changes, multi-parent-registry-file after generated browser-bundle staging changes, adapter-sidecar-registry-file after generated registry adapter-family, auto-assembly route, or Module Plan display changes across the affected f32/q8_0/q4_0 roots or combined f32/q8_0/q4_0 root, combined-selector-assembly after one-root multi-quant selector, generated all-root switching, or Module Plan Trace changes, assembly-eval-case-drift after generated assembly eval digest gate changes, assembly-evidence-file-drift after fetched assembly evidence-file checksum changes, module-plan-profile-drift after module-plan profile contract changes, module-plan-execution-profile-drift after module-plan execution-profile contract changes, module-plan-fetch-policy-drift after module-plan fetch-policy contract changes, module-plan-origin-policy-drift after module-plan origin-policy contract changes, module-plan-fetch-count-drift after module-plan fetch-count envelope changes, module-plan-runtime-scratch-drift after module-plan runtime scratch envelope changes, module-plan-prompt-limit-drift and source prompt-limit after prompt byte envelope or prompt-copy behavior changes, module-plan-total-budget-drift after module-plan total self-assembly envelope changes, module-plan-count-drift after module-plan count/cardinality changes, module-plan-resource-drift after module-plan resource-envelope changes, module-plan-graph-drift after module-plan graph matching changes, module-plan-stack-drift after module-plan stack matching changes, module-plan-role-drift after module-plan role matching changes, module-plan-slot-drift after module-plan assembly-slot changes, module-plan-byte-drift after module-plan byte-count changes, and module-plan-checksum-drift after module-plan checksum changes. - Browser smoke must include blend-operator-registry, delta-operator-registry, sparse-delta-operator-registry, and their receipt-drift modes after original two-parent compact operator provenance changes; use prune-operator-registry plus prune-operator-receipt-drift, dare-operator-registry plus dare-operator-receipt-drift, crossover-operator-registry plus crossover-operator-receipt-drift, and mutation-operator-registry plus mutation-operator-receipt-drift when those compact operator provenance paths are touched. - Browser smoke must include module-plan-dependency-drift after module-plan dependency-edge changes. - Browser smoke must include module-plan-phase-drift after module-plan phase validation changes. - Browser smoke must include adapter-manifest-drift after generated adapter manifest checksum, manifest route ordering, or post-receipt auto-assembly sequencing changes. - Browser smoke must include adapter-artifact-drift after generated adapter artifact checksum, fetched stack bytes, or post-manifest auto-assembly sequencing changes. - Browser smoke must include adapter-stack-prefetch-drift after generated auto-apply stack prefetch, pre-WASM stack byte verification, or partial stack mutation sequencing changes. - Browser smoke must include adapter-stack-rust-validate-drift after generated auto-stack semantic validation, checksum echo routing, or validation failure state changes. - Browser smoke must include source-backed-alr1-manifest-drift after source-backed ALR1 kind/dtype pairing, adapter-family receipt source echoes, fetched source manifest fields, or source-backed ALR1 provenance checks change. - Browser smoke must include combined-selector-cycle after longer same-page generated-root selector reuse, repeated q4_0/q8_0/f32 switching, model-switch release sequencing, or path-flexible Module Plan summary assertions change. - Browser smoke must include combined-selector-route-soak after local fetch cache behavior, repeated generated self-assembly route counting, or longer q4_0/q8_0/f32 selector-route exercises change; use combined-selector-route-extended-soak when five-cycle route pressure or path-flexible total-budget assertions are in scope. - Browser smoke must include combined-selector-reload-soak after generated selector registry default boot selection, fresh page-lifetime assembly, or reload route-count behavior changes. - JS must not parse .slm, own tensor logic, or make quality claims. - Conversation transcript text must be inserted with DOM text nodes, remain browser-local, and keep runtime Reset separate from transcript Clear behavior. - Browser Step Token controls may call generate_next_token only after context exists, must append local decoded text to response/transcript/console, and must disable after Reset or failed generation. - Browser Adapter Sidecar controls may call apply_adapter_delta only after a model is loaded; JS must filter checked local .adp1 routes and generated local .adp1/.asp1/.alr1 routes, check selected artifact checksums before WASM transfer, fetch and checksum-verify generated module-plan receipts with `browser-constrained-v1` profile, resource class plus model/adapter/runtime-scratch/prompt/output/KV-cache/total byte budgets, fetch-count limit, module count, module byte counts, module checksums, module roles, module phases, module dependencies, and assembly slots before generated model bytes, render visible Module Plan fetch-limit/model/adapter/scratch/prompt/output/KV/total budget rows, byte summaries, checksum summaries, slot summaries, role summaries, phase summaries, dependency summaries, and browser-owned trace checkpoints only from verified receipt fields plus verified load steps, prove checksum-consistent module-plan profile, fetch-count, runtime-scratch, prompt-limit, output-limit, total-budget, count, resource, graph, stack, role, slot, phase, dependency, byte-count, and checksum drift stop before generated model or stack bytes after profile, envelope, count, graph, stack, role, slot, phase, dependency, byte, or checksum changes, fetch and checksum-verify generated assembly receipts plus receipt-referenced evidence files after model manifest load, prove evidence-file body drift stops before later evidence or adapter-family routes, fetch and checksum-verify generated adapter-family receipts plus adapter manifests before enabling family options, verify receipt-bound preferred adapter and ordered stack fields before default selection or startup apply, require generated auto-assembly byte budgets, match fetched adapter bytes to manifest-declared artifact bytes, call Rust validate_adapter_delta for every generated auto-stack member before the first apply_adapter_delta, and transfer bytes without parsing adapter payloads. - Browser smokes for generated auto assembly must assert the Rust diagnostics assembly state, including expected `adapter_apply_count` and nonzero `last_adapter_checksum` plus `assembly_state_checksum`, before generation. - Browser selector defaults may only come from validated selector_default_strategy, selector_default_candidate_id, and selector_default_quantization fields; combined generated roots should prove the initial selected model is q4_0 before scripted switching. - Browser selector registries must declare `selector_model_byte_budget=33554432`, registry entries must declare positive decimal `entry.N.model_bytes` within that registry budget, and fetched registry model bytes must match that declaration before WASM transfer. - Browser text sidecars must be fetched as bytes and checked before decoding or parsing: selector registries, manifests, receipts, and assembly evidence files each keep explicit local envelopes. - Generated selector registries must declare exact text-sidecar budget fields for selector registry, manifest, receipt, and evidence text; browser intake must require exact local matches before accepting generated entries. - Runtime WASM must be manifest-verified before instantiation; checked and generated roots must keep `runtime_wasm_bytes` and `runtime_wasm_checksum` aligned with `tinyrustlm.wasm`, and browser smokes must prove normal manifest requests plus runtime-manifest-drift behavior before model fetch. - Module Plan dependency summaries must render only from checksum-verified `.module-plan.receipt` fields, source-root fallback must remain `unavailable`, and generated-root dependency drift must stop before generated model or stack artifact fetches. - Module Plan phase summaries must render only from checksum-verified `.module-plan.receipt` fields, source-root fallback must remain `unavailable`, and generated-root phase drift must stop before generated model or stack artifact fetches. - Module Plan byte summaries must render only from checksum-verified `.module-plan.receipt` fields, source-root fallback must remain `unavailable`, and generated-root byte drift must stop before generated model or stack artifact fetches. - Module Plan checksum summaries must render only from checksum-verified `.module-plan.receipt` fields, source-root fallback must remain `unavailable`, and generated-root checksum drift must stop before generated model or stack artifact fetches. - Module Plan total budgets must render only from checksum-verified `.module-plan.receipt` fields, source-root fallback must remain `unavailable`, and generated-root total-budget drift must stop before generated model or stack artifact fetches. - Module Plan prompt limits must render only from checksum-verified `.module-plan.receipt` fields, source-root fallback must remain `unavailable`, generated-root prompt-limit drift must stop before generated model or stack artifact fetches, and source-root prompt-limit smoke must stop oversized prompt bytes before WASM transfer. - Module Plan total limits must render only from checksum-verified `.module-plan.receipt` fields, source-root fallback must remain `unavailable`, and generated-root total-limit drift must stop before generated model or stack artifact fetches. - Module Plan fetch limits must render only from checksum-verified `.module-plan.receipt` fields, source-root fallback must remain `unavailable`, and generated-root fetch-count drift must stop before generated model or stack artifact fetches. - Module Plan WASM memory pages must render only from checksum-verified `.module-plan.receipt` fields captured against the pre-init exported WASM memory size, source-root fallback must remain `unavailable`, and generated-root WASM-memory drift must stop before generated model or stack artifact fetches. - Module Plan WASM ABI must render only from checksum-verified `.module-plan.receipt` fields with `module_plan_wasm_export_set=tinyrustlm-generate-v1`, source-root fallback must remain `unavailable`, and generated-root WASM export-set drift must stop before generated model or stack artifact fetches. - Module Plan Heap Floor must render only from checksum-verified `.module-plan.receipt` fields with selector agreement; browser verification must recompute the floor, probe WASM alloc/dealloc before generated model fetch, keep source fallback `unavailable`, and run generated-root WASM heap drift. - Module Plan Transfer must render only from checksum-verified `.module-plan.receipt` fields with `module_plan_wasm_transfer_strategy=copy-then-release-v1`, source-root fallback must remain `unavailable`, and generated-root WASM transfer drift must stop before generated model or stack artifact fetches. - Module Plan Release must render only from checksum-verified `.module-plan.receipt` fields with `module_plan_model_release_strategy=free-before-reassembly-v1`, source-root fallback must remain `unavailable`, and generated-root model-release drift must stop before generated model or stack artifact fetches. - Module Plan Reset must render only from checksum-verified `.module-plan.receipt` fields with `module_plan_runtime_reset_strategy=reset-context-before-assembly-v1`, source-root fallback must remain `unavailable`, generated-root runtime-reset drift must stop before generated model bytes, and normal generated roots must call `reset_context` before adapter validation/application. - Module Plan Validate must render only from checksum-verified `.module-plan.receipt` fields with `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1`, source-root fallback must remain `unavailable`, generated-root adapter-validation drift must stop before generated model bytes, and normal generated roots must call `validate_adapter_delta` before `apply_adapter_delta`. - Module Plan count/cardinality checks must compare selector `module_plan_module_count` with receipt `module_count`; generated-root count drift must stop before generated model or stack artifact fetches. - Model Provenance eval rows for registry-backed models must render only from selector `entry.N.eval_case_evidence_checksum` plus passed case totals, and generated assembly receipts must match that checksum before evidence or adapter-family routes are accepted. - Model Provenance Genome/Fitness rows for registry-backed models must render only from selector `entry.N.genome_id`, `entry.N.genome_lineage_checksum`, and eval-bound `entry.N.fitness_vector_checksum` fields after browser registry intake validates exact strategy/status values. - Model Provenance Species rows for registry-backed models must render only from selector `entry.N.species_id`, `entry.N.species_fit_checksum`, and exact `selector-speciation-fit-v1` plus `browser-fit-bound` fields after browser registry intake validates them. - Model Provenance Novelty rows for registry-backed models must render only from selector `entry.N.novelty_id`, `entry.N.novelty_checksum`, and exact `selector-novelty-sketch-v1` plus `behavior-sketch-bound` fields after browser registry intake validates them. - Model Provenance Population rows for registry-backed models must render only from selector `entry.N.population_id`, `entry.N.population_checksum`, and exact `selector-population-review-route-v1` plus `population-review-bound` fields after browser registry intake validates them. - Model Provenance Mate Selection rows for registry-backed models must render only from selector `entry.N.mate_selection_id`, `entry.N.mate_selection_parent_count`, `entry.N.mate_selection_checksum`, and exact `selector-mate-selection-route-v1` plus supported status fields after browser registry intake validates them. - Model Provenance Artifact rows for registry-backed models must render only from selector `entry.N.heritable_artifact_id`, `entry.N.heritable_artifact_checksum`, and exact `selector-heritable-artifact-v1` plus `served-artifact-bound` fields after browser registry intake validates them. memory: rule: Do not store durable implementation reports inside .uai/long-term-memory.uai; point to docs or wiki files instead. report_synthesis_rule: Do store compact report-derived operating memory in typed .uai files so cold-start agents can route and reason without bulk-loading every report. report_reference_rule: Short-term memory must point to durable report indexes after each processed batch; long-term memory remains pointer-only with checksums. uaix_file_handoff_rule: Follow the UAIX file-handoff setup shape; active drops are transient, hot .uai files carry current routing and synthesis, and report bodies live in wiki/raw evidence targets. research_reference_rule: Keep diverse model-breeding research in wiki/gguf-mirust/research/ and route it through hot .uai synthesis; do not inline research bodies into the long-term pointer ledger. modelbreeder_zero_dependency_rule: Route ModelBreeder genome/fitness/novelty/population/mate-selection/phenotype-evidence/heritable-artifact/speciation guidance and zero-dependency Wasm runtime ideas through wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md before turning them into schema fields, receipts, diagnostics, or browser-smoke assertions. report_pointer_audit_rule: After adding or changing report/research durable pages, refresh short-term routes and long-term checksum pointers, then audit wiki/gguf-mirust/reports/*.md and wiki/gguf-mirust/research/*.md against .uai/long-term-memory.uai. site_voice_rule: Read .uai/taboo.uai before public copy or product-positioning edits. setup_file_handoff_2026_06_28: Treat active buckets as intake, raw/wiki Markdown as durable bodies, .uai files as routing/synthesis, short-term memory as the current route index, and long-term memory as checksum pointers. file_handoff: rule: Active handoff files must receive disposition ledger entries before they are removed, preserved, or kept active. model_breeding: rule: Keep breeding operators offline until generated artifacts pass normal .slm validation, manifest validation, runtime-smoke, and eval gates. genome_fitness_guidance: Genome, SpeciesFit, Novelty, Population, MateSelection, PhenotypeEvidence, HeritableArtifact, and FitnessVector fields should appear as typed, deterministic metadata derived from existing evidence, behavior descriptors, review-route context, parent-pool routes, served artifact identity, and browser fit boundaries; selector registry fields require Rust validation tests, generated bundle tests, browser provenance assertions, and checksum pointer routing. compatibility: Run tinyrustlm-slm-pack compatibility before any direct-parameter assembly operator; parent sets must match version, model shape, tokenizer checksum, output-head contract, quantization label, tensor count, parameter count, and tensor layout checksum. lineage: Run tinyrustlm-slm-pack lineage-template after a passing compatibility report, then validate-lineage before any operator output; the template records parent artifact hashes, compatibility checksum, operator id, resource budget, pending artifact fields, and eval sidecar route. blend_operator: Run tinyrustlm-slm-pack blend-candidate only after validate-lineage; validate-blend-candidate must recompute candidate bytes and receipt from compatibility-bound parents plus blend weights before candidate-manifest. task_delta_operator: Run tinyrustlm-slm-pack delta-candidate only after validate-lineage when a task-vector direct-parameter candidate is needed; validate-delta-candidate must recompute candidate bytes and receipt from compatibility-bound base and target parents plus signed delta weights before candidate-manifest. sparse_delta_operator: Run tinyrustlm-slm-pack sparse-delta-candidate only after validate-lineage when a sparse task-vector candidate is needed; validate-sparse-delta-candidate must recompute selected absolute deltas, retention/density fields, implicit mask checksum, candidate bytes, and receipt before candidate-manifest. prune_operator: Run tinyrustlm-slm-pack prune-candidate only after validate-lineage when deterministic magnitude pruning is needed; validate-prune-candidate must recompute keep/floor ppm, selection counts, mask checksum, output-value checksum, candidate bytes, and receipt before candidate-manifest, and browser receipt work should run prune-operator-registry plus prune-operator-receipt-drift. dare_operator: Run tinyrustlm-slm-pack dare-candidate only after validate-lineage when DARE dropout/rescaled task-delta arithmetic is needed; validate-dare-candidate must recompute signed delta weight ppm, keep/drop ppm, dropout seed, mask checksum, raw delta checksum, rescaled delta checksum, candidate bytes, and receipt before candidate-manifest; compact browser proof uses dare-operator-registry plus dare-operator-receipt-drift. adapter_delta_artifact: Run tinyrustlm-slm-pack adapter-delta only after validate-lineage when a modular raw f32 task-delta package is needed; validate-adapter-delta must recompute adapter bytes and manifest from compatibility-bound parents before fuse-adapter-delta or runtime f32/q8_0/q4_0 apply. sparse_adapter_delta_artifact: Run tinyrustlm-slm-pack sparse-adapter-delta only after validate-lineage when a compact sparse f32 task-delta package is needed; validate-sparse-adapter-delta must recompute ASP1 bytes, density, retention, mask checksum, and manifest from compatibility-bound parents before runtime f32/q8_0/q4_0 apply. low_rank_adapter_delta_artifact: Run tinyrustlm-slm-pack low-rank-adapter-delta only after validate-lineage when a compact matrix low-rank f32 task-delta package is needed; validate-low-rank-adapter-delta must recompute ALR1 bytes, factor metadata, residual-L1 fields, and manifest from compatibility-bound parents before runtime f32/q8_0/q4_0 apply. trained_adapter_source: Run tinyrustlm-slm-pack adapter-source-template and validate-adapter-source when trained low-rank factor bundles are the source material; validation must bind model shape, tied-output contract, target tensor hashes, factor ranks, safe factor paths, byte counts, checksums, finite bounded factors, factor parameter counts, and reconstructed delta L1 before ALR1 packaging. Run convert-adapter-source plus validate-converted-adapter-source when reviewed factors should become runtime ALR1; preserve base `.slm` shape, tied-output, tokenizer, tensor layout, target tensor identity, ALR1 checksum, payload checksum, and manifest recomputation. adapter_fuse_candidate: Run tinyrustlm-slm-pack fuse-adapter-delta only after validate-adapter-delta when a raw ADP1 package should become a normal .slm candidate; validate-fuse-adapter-delta must recompute candidate bytes and receipt before candidate-manifest. runtime_adapter_apply: Use Runtime::validate_adapter_delta or Runtime::apply_adapter_delta only for an already-loaded f32, q8_0, or q4_0 model and a compatible ADP1 raw, ASP1 sparse, or ALR1 low-rank package; validate identity, checksums, tensor directory, tokenizer, layout, finite deltas or factors, sparse indices or low-rank shapes, and fused values before mutation or compact re-quantization, preserve generation state on validation, and clear generation state after successful apply. runtime_assembly_diagnostics: Preserve `adapter_apply_count`, `last_adapter_checksum`, and `assembly_state_checksum` as runtime-owned proof fields; run runtime tests, wasm-abi-smoke, checked adapter-sidecar smoke, and generated combined-selector smokes after changing diagnostics or apply accounting. runtime_kv_cache_diagnostics: Preserve `kv_cache_byte_budget` and `kv_cache_page_count` as runtime-owned proof fields; run runtime tests, selector tests, browser_bundle tests, generated-root `combined-selector-assembly`, and `module-plan-kv-cache-drift` after changing cache shape math, diagnostics, selector receipt fields, or Module Plan KV rows. module_plan_adapter_stack_budget: Preserve `module_plan_adapter_stack_byte_budget` as the exact generated ADP1 plus ASP1 plus ALR1 payload total; run selector tests, browser_bundle tests, browser_harness checks, generated-root `combined-selector-assembly`, `module-plan-adapter-stack-budget-drift`, and `module-plan-total-budget-drift` after changing stack byte math, selector fields, receipt fields, manifest byte checks, or Module Plan Stack Budget rows. module_plan_context_token: Preserve `module_plan_context_token_limit` as the validated `.slm` context window mirrored through selector registry, served receipt, and Module Plan Context row; run selector context drift tests, browser_bundle tests, browser_harness checks, generated-root `combined-selector-assembly`, and `module-plan-context-token-drift` after changing context-window or model-shape parsing. module_plan_tokenizer: Preserve `module_plan_tokenizer_checksum` as the admitted `.slm` tokenizer identity mirrored through selector registry, served receipt, and Module Plan Tokenizer row; run selector tokenizer drift tests, browser_bundle tests, browser_harness checks, generated-root `combined-selector-assembly`, and `module-plan-tokenizer-drift` after changing tokenizer identity routing. module_plan_sampler_cap: Preserve `module_plan_sampler_candidate_cap=1024` as the fixed-buffer sampling envelope mirrored through selector registry, served receipt, Module Plan Sampler Cap row, and browser Top K clamping; run selector sampler-cap drift tests, browser_bundle tests, browser_harness checks, generated-root `combined-selector-assembly`, and `module-plan-sampler-cap-drift` after changing sampler-envelope routing. module_plan_wasm_export_set: Preserve `module_plan_wasm_export_set=tinyrustlm-generate-v1` as the browser generation ABI mirrored through selector registry, served receipt, instantiated WASM export checks, and Module Plan WASM ABI row; run selector export-set drift tests, browser_bundle tests, browser_harness checks, generated-root `combined-selector-assembly`, `module-plan-wasm-export-set-drift`, and source `ui-audit` after changing WASM exports or module-plan ABI routing. module_plan_wasm_heap: Preserve `module_plan_wasm_heap_min_bytes` as the generated-root heap floor mirrored through selector registry, served receipt, browser recomputation, WASM alloc/dealloc probe, and Module Plan Heap Floor row; run selector heap drift tests, browser_bundle tests, browser_harness checks, generated-root `combined-selector-cycle`, `module-plan-wasm-heap-drift`, and source `ui-audit` after changing heap envelopes or allocation probes. module_plan_wasm_transfer: Preserve `module_plan_wasm_transfer_strategy=copy-then-release-v1` as the generated-root WASM byte-transfer discipline mirrored through selector registry, served receipt, browser receipt verification, and Module Plan Transfer row; run selector transfer drift tests, browser_bundle tests, browser_harness checks, generated-root `combined-selector-cycle`, `module-plan-wasm-transfer-drift`, and source `ui-audit` after changing byte-copy or release discipline. module_plan_model_release: Preserve `module_plan_model_release_strategy=free-before-reassembly-v1` as the generated-root model-release discipline mirrored through selector registry, served receipt, browser receipt verification, and Module Plan Release row; run selector release drift tests, browser_bundle tests, browser_harness checks, generated-root `combined-selector-cycle`, `module-plan-model-release-drift`, and source `ui-audit` after changing model lifecycle or release sequencing. module_plan_runtime_reset: Preserve `module_plan_runtime_reset_strategy=reset-context-before-assembly-v1` as the generated-root context-reset discipline mirrored through selector registry, served receipt, browser receipt verification, and Module Plan Reset row; run selector reset drift tests, browser_bundle tests, browser_harness checks, generated-root `combined-selector-cycle`, `module-plan-runtime-reset-drift`, and source `ui-audit` after changing generated model load or adapter assembly sequencing. browser_adapter_sidecar: Treat checked browser adapter sidecars as manual local f32/q8_0/q4_0 ADP1 byte-transfer routes and generated registry adapter families as f32/q8_0/q4_0 quantization-matched ADP1/ASP1/ALR1 routes; do not parse adapter bytes in JavaScript, check selected artifact checksums before WASM transfer, fetch and checksum-verify generated .module-plan.receipt files with `browser-constrained-v1` profile, `single-threaded-wasm-local-v1` execution profile, `local-no-store-v1` fetch policy, `same-origin-loopback-local-v1` origin policy, resource class plus model/adapter/runtime-scratch/KV-cache/total byte budgets, module count, module byte counts, module checksums, module roles, module phases, module dependencies, and assembly slots before generated `.slm` fetch, render Module Plan panel fields, visible execution/fetch/origin/model/adapter/scratch/KV/total budget rows, ordered byte summary, ordered checksum summary, ordered slot summary, ordered role summary, ordered phase summary, ordered dependency summary, and ordered trace only from the verified receipt metadata plus browser load checkpoints, fetch and checksum-verify generated .adapter-family.receipt and .adp1/.asp1/.alr1 manifest files before enabling generated family options, verify receipt-bound preferred adapter index/path/manifest fields and ordered stack index/path/manifest fields before defaulting generated options or startup apply, require explicit registry auto-apply fields plus `adapter_auto_apply_byte_budget=1048576` before generated receipt-declared stack startup apply, require fetched auto-assembled bytes to match manifest-declared `adapter_artifact_bytes`, run browser-smoke adapter-sidecar for tinyf32/tinyq8/tinyq4 and adapter-sidecar-checksum-mismatch after changing checked UI routing, run browser-smoke adapter-sidecar-registry-file after changing generated registry-carried adapter-family routes, module-plan metadata, Module Plan display, stack metadata, auto assembly, budgets, bytes, checksums, slots, roles, phases, dependencies, trace, or verification, run browser-smoke ui-audit after changing fallback Module Plan panel state, run browser-smoke module-plan-profile-drift after changing module-plan profile fields or receipt profile validation, run browser-smoke module-plan-execution-profile-drift after changing module-plan execution-profile fields or receipt execution validation, run browser-smoke module-plan-fetch-policy-drift after changing module-plan fetch-policy fields or receipt fetch validation, run browser-smoke module-plan-origin-policy-drift after changing module-plan origin-policy fields or receipt origin validation, run browser-smoke module-plan-runtime-scratch-drift after changing module-plan runtime scratch budget validation, run browser-smoke module-plan-kv-cache-drift after changing module-plan KV-cache byte budget or page-count validation, run browser-smoke module-plan-total-budget-drift after changing module-plan total byte budget validation, run browser-smoke module-plan-count-drift after changing module-plan count validation, run browser-smoke module-plan-resource-drift after changing module-plan resource envelopes or receipt budget validation, run browser-smoke module-plan-graph-drift after changing module-plan graph field validation, run browser-smoke module-plan-stack-drift after changing module-plan stack field validation, run browser-smoke module-plan-role-drift after changing module-plan role field validation, run browser-smoke module-plan-slot-drift after changing module-plan assembly-slot validation, run browser-smoke module-plan-phase-drift after changing module-plan phase validation, run browser-smoke module-plan-dependency-drift after changing module-plan dependency validation, run browser-smoke module-plan-byte-drift after changing module-plan byte-count validation, and run browser-smoke module-plan-checksum-drift after changing module-plan checksum validation. module_plan_phases: Preserve `module.N.phase` fields for load-model-bytes, verify-model-manifest, verify-assembly-evidence, verify-adapter-family, and ordered apply-adapter-stack members; run generated-root adapter-sidecar-registry-file, source ui-audit, and module-plan-phase-drift after phase edits. module_plan_byte_counts: Preserve `module.N.byte_count` fields for generated `.slm`, `.slm.manifest`, `.assembly.receipt`, `.adapter-family.receipt`, and ordered stack artifacts; run generated-root adapter-sidecar-registry-file, source ui-audit, and module-plan-byte-drift after byte-count edits. module_plan_checksums: Preserve `module.N.checksum` fields for generated `.slm`, `.slm.manifest`, `.assembly.receipt`, `.adapter-family.receipt`, and ordered stack artifacts; run generated-root adapter-sidecar-registry-file, source ui-audit, and module-plan-checksum-drift after checksum edits. module_plan_trace: Preserve browser-owned Module Plan Trace reset and checkpoint sequencing: unavailable for checked source roots, plan verified after receipt verification, ready only after model, manifest, assembly, adapter-family, and stack checks complete; run combined-selector-assembly after trace edits. combined_selector_cycle: Preserve same-page generated all-root cycle evidence: q4_0 remains the default, q4_0/q8_0/f32 switching can repeat, every post-initial pass calls free_model before new stack validation/apply/completion, and diagnostics reset before one-token generation. combined_selector_route_soak: Preserve same-page generated all-root route-count evidence: local fetches use no-store cache behavior, three q4_0/q8_0/f32 cycles run in one page, the extended mode runs five cycles, and every module-plan, model, manifest, assembly, evidence, adapter-family, adapter-manifest, and stack-artifact route is requested once per pass. combined_selector_reload_soak: Preserve fresh page-lifetime generated all-root evidence: every reload pass starts from the q4_0 registry default, rebuilds q4_0/q8_0/f32 self-assembly, and requests the runtime manifest, selector registry, module-plan, model, manifest, evidence, adapter, and stack routes again. eval_case_evidence_checksum: Preserve `eval_case_evidence_checksum` across admission records, multi-parent admission records, promotion-ledger entries, selector registry entries, generated assembly receipts, and Model Provenance display; run slm_pack tests plus generated-root combined-selector-assembly and assembly-eval-case-drift after eval evidence routing changes. assembly_evidence_files: Preserve receipt-declared evidence paths and checksums, fetch and checksum each evidence file before adapter-family verification, release accepted model state on mismatch, and run assembly-evidence-file-drift plus one normal generated-root adapter-sidecar-registry-file smoke after evidence-file verification changes. adapter_manifest_drift: Preserve adapter-family receipt verification before manifest fetches, checksum each adapter manifest before later manifests or stack artifacts, and run adapter-manifest-drift plus one normal generated-root adapter-sidecar-registry-file smoke after generated manifest verification changes. adapter_artifact_drift: Preserve all adapter manifest verification before artifact fetches, checksum each stack artifact before later artifacts or WASM transfer, and run adapter-artifact-drift plus one normal generated-root adapter-sidecar-registry-file smoke after generated artifact verification changes. adapter_stack_prefetch_drift: Preserve full auto-stack byte preflight plus Rust validate_adapter_delta preflight before Rust adapter apply; run adapter-stack-prefetch-drift, adapter-artifact-drift, adapter-stack-rust-validate-drift, one normal generated-root adapter-sidecar-registry-file smoke, and combined-selector-assembly after generated auto-assembly byte-transfer or validation changes. browser_source_backed_alr1_route: After changing browser bundle ALR1 source staging, adapter-family source-backed ALR1 kind/dtype checks, browser `.alr1` manifest kind/dtype validation, or generated source-backed ALR1 smoke expectations, run cargo fmt, JS syntax checks, focused adapter_family, browser_bundle, and trained_adapter_source tests, regenerate a browser-multi-parent-bundle `all` root, run combined-selector-assembly, and run cargo test --workspace. browser_source_backed_alr1_contract: After changing source-backed ALR1 receipt source echoes, manifest source fields, kind/dtype pair validation, or `validateSourceBackedAdapterManifest`, run focused adapter_family and browser_bundle tests, regenerate a browser-multi-parent-bundle `all` root, run source-backed-alr1-manifest-drift, run combined-selector-assembly, and run cargo test --workspace. candidate_artifact: Run tinyrustlm-slm-pack candidate-manifest after validate-lineage and before eval or promotion; validate-candidate must bind compatibility, lineage, candidate .slm checksum, shape, tokenizer checksum, tensor layout checksum, and parent contract. promotion: Run tinyrustlm-slm-pack promotion-template after validate-candidate and before selector or claim work; validate-promotion must keep runtime-smoke, eval, selector, and claim statuses pending until separate evidence exists. runtime_smoke: Run tinyrustlm-slm-pack runtime-smoke after validate-manifest when a durable execution sidecar is needed; validate-runtime-smoke must bind the sidecar to provenance checksum, slm checksum, source kind, and model shape. selector_admission: Run tinyrustlm-slm-pack admission-record only after validate-promotion, validate-runtime-smoke, and a passed converted-trained eval sidecar; validate-admission must reject evidence drift before any selector registry or browser route. promotion_ledger: Run tinyrustlm-slm-pack promotion-ledger after validate-admission when an admitted candidate should enter durable promotion history; validate-promotion-ledger must reject duplicate candidates, duplicate artifacts, and entry drift. population_review: Run tinyrustlm-slm-pack population-review after validate-promotion-ledger when admitted candidates need frontier or parent-pool selection; validate-population-review must recompute ranking, weighted objective-vector metadata, and per-entry objective checksums from ledger plus admissions. parent_pool_recipe: Run tinyrustlm-slm-pack parent-pool-recipe after validate-population-review when reviewed candidates need a shared-contract parent recipe; validate-parent-pool-recipe must recompute the review, parent contract fields, seed weights, relatedness metric/scope/pair count/status/checksum, and per-parent relatedness groups from ledger plus admissions. sign_merge_operator: Run tinyrustlm-slm-pack sign-merge-candidate only after validate-parent-pool-recipe when reviewed parents need a seed-weighted sign-consensus .slm candidate; validate-sign-merge-candidate must recompute recipe validation, parent checks, relatedness echo fields, candidate bytes, and receipt before multi-parent-candidate-manifest work. multi_parent_candidate_manifest: Run tinyrustlm-slm-pack multi-parent-candidate-manifest after validate-sign-merge-candidate or validate-soup-candidate when a parent-pool operator output needs a candidate manifest; validate-multi-parent-candidate must recompute receipt checksum, recipe checksum, relatedness summary, operator-specific metrics, parent summaries, candidate .slm fields, and pending promotion route before runtime-smoke, eval, admission, ledger, or selector work. multi_parent_promotion: Run tinyrustlm-slm-pack multi-parent-promotion-template after validate-multi-parent-candidate when a sign-merge output needs runtime-smoke/eval handoff; validate-multi-parent-promotion must recompute the candidate manifest, receipt checksum, recipe checksum, ledger/review/admission checksums, parent count, candidate .slm fields, and pending selector route before runtime-smoke, eval, admission, ledger, or selector work. multi_parent_admission: Run tinyrustlm-slm-pack multi-parent-admission-record after validate-multi-parent-promotion, validate-runtime-smoke, validate-manifest, and a passed converted-trained eval sidecar; validate-multi-parent-admission must recompute the sign-merge promotion chain and bind runtime/eval evidence before selector-registry consumes it. selector_registry: Run tinyrustlm-slm-pack selector-registry only after validate-admission or validate-multi-parent-admission and after the admitted candidate artifact plus manifest are staged under served tinyrustlm/models routing; every generated registry must carry `selector_model_byte_budget=33554432`, `selector_registry_text_byte_budget=262144`, `manifest_text_byte_budget=65536`, `receipt_text_byte_budget=131072`, and `evidence_text_byte_budget=131072`, validate-selector-registry and browser-smoke multi-parent-registry must detect drift before selector-logic claims, and browser-multi-parent-bundle plus browser-smoke multi-parent-registry-file and adapter-sidecar-registry-file must pass for the affected f32/q8_0/q4_0 generated roots before generated file-backed model-plus-browser-verified-module-plan-profile-execution-fetch-origin-resource-runtime-scratch-KV-cache-and-total-budget-receipt, assembly-receipt-and-evidence-files, adapter-family receipt, manifest, auto assembly, and frugal-default claims. Use browser-multi-parent-bundle `all`, f32/q8_0/q4_0 adapter-sidecar-registry-file smokes, and combined-selector-assembly before claiming one served root can switch among all three generated modules in one browser session, require q4_0 as the initial selected model when browser-frugal-quantized defaults are present, require module-plan receipts to match `browser-constrained-v1` profile, `single-threaded-wasm-local-v1` execution profile, `local-no-store-v1` fetch policy, `same-origin-loopback-local-v1` origin policy, resource class, model byte budget, adapter byte budget, runtime scratch byte budget, KV-cache byte budget, KV-cache page count, total byte budget, module count, module byte counts, module checksums, module roles, module phases, module dependencies, assembly slots, model, manifest, assembly, adapter-family, and stack routes before generated model fetch, run browser-smoke module-plan-profile-drift after module-plan receipt profile changes, run browser-smoke module-plan-execution-profile-drift after module-plan receipt execution-profile changes, run browser-smoke module-plan-fetch-policy-drift after module-plan receipt fetch-policy changes, run browser-smoke module-plan-origin-policy-drift after module-plan receipt origin-policy changes, run browser-smoke module-plan-runtime-scratch-drift after module-plan receipt runtime scratch changes, run browser-smoke module-plan-kv-cache-drift after module-plan receipt KV-cache changes, run browser-smoke module-plan-total-budget-drift after module-plan receipt total budget changes, run browser-smoke module-plan-count-drift after module-plan receipt count changes, run browser-smoke module-plan-resource-drift after module-plan receipt resource-envelope changes, run browser-smoke module-plan-graph-drift after module-plan model/manifest/receipt/stack graph validation changes, run browser-smoke module-plan-stack-drift after module-plan stack path or manifest validation changes, run browser-smoke module-plan-role-drift after module-plan role validation changes, run browser-smoke module-plan-slot-drift after module-plan assembly-slot validation changes, run browser-smoke module-plan-phase-drift after module-plan phase validation changes, run browser-smoke module-plan-dependency-drift after module-plan dependency validation changes, run browser-smoke module-plan-byte-drift after module-plan byte-count validation changes, run browser-smoke module-plan-checksum-drift after module-plan checksum validation changes, require `adapter_auto_apply_status=enabled`, `adapter_auto_apply_strategy=receipt-preferred-compatible`, and `adapter_auto_apply_byte_budget=1048576` before generated auto assembly, run browser-smoke selector-budget after registry model byte budget changes, run browser-smoke sidecar-budget-contract after registry text budget contract changes, and run browser-smoke runtime-manifest-drift after runtime manifest or generated runtime staging changes. browser-multi-parent-bundle should produce a runnable root with app shell, WASM runtime, and runtime WASM manifest. adapters: Treat adapter-delta packages as offline typed delta artifacts; use adapter-source-template and validate-adapter-source for trained low-rank factor source bundles before ALR1 packaging, then use convert-adapter-source and validate-converted-adapter-source for reviewed source-backed ALR1 packages; use fuse-adapter-delta to create normal .slm candidates for raw ADP1 packages on the existing admission path; use validate_adapter_delta before generated auto-stack apply and use apply_adapter_delta for compatible loaded f32/q8_0/q4_0 ADP1, ASP1, or ALR1 packages, checked local browser .adp1 routes, and indexed generated f32/q8_0/q4_0 ADP1/ASP1/ALR1 adapter families whose served receipts and adapter manifests are fetched and verified before use; keep QLoRA-style training ideas as future browser/training formats with explicit source, tests, and manifest support while sparse retention metadata now lives in sparse-delta receipts and sparse-adapter manifests, trained factor source metadata lives in adapter-source manifests and source-backed ALR1 manifests, and runtime low-rank factor metadata lives in ALR1 manifests. research_references: Treat compatible merges, sparse-lineage breadcrumbs, adapter ecology, population search, federated/local updates, browser-constrained assembly, UAIX memory strategy, heritable artifacts, mate selection, phenotype evidence, speciation-and-fit, model kinship, evolutionary recipes, adaptive search, and multi-objective fitness as reference/planner inputs until each is translated into a compatibility field, receipt/manifest field, eval/provenance field, promotion record, browser-smoke assertion, or tested operator; sparse-mask breadcrumbs now have a first receipt-level form in sparse-delta mask checksums and retention fields, multi-objective fitness has a first population-review objective-vector form, and parent relatedness has a first recipe/receipt/manifest form in parent-pool, sign-merge, and multi-parent candidate records. heterogenous_models: Use distillation or retraining when architecture or tokenizer compatibility fails. report_derived_rust_rules: - Prefer enums, newtypes, slices, explicit lengths, and data-driven dimensions over abstract framework layers. - Treat unsafe as a named boundary with validation and tests, not a convenience. - Do not translate SOLID into object-oriented scaffolding; use ownership, cohesive modules, and explicit interfaces. - Keep deterministic smoke models clearly separated from trained-quality model claims. - Keep trained-source conversion explicit: raw f32 source manifests, tied_output/model_shape agreement, safe relative tensor paths, checksums, finite bounded weights, and converted-trained provenance before any runtime or quality claim; keep trained adapter source explicit with reviewed low-rank f32 factor manifests, safe factor paths, checksums, finite bounded factors, recomputed delta fields, source-to-ALR1 base identity checks, and ALR1 manifest recomputation. - Keep assistant-quality evidence exact: eval cases need positive declared counts, nonempty exact prompts/expected text, no stray case keys, and quality sidecars need matching per-case actual text. - Add abstractions only when they reduce real runtime complexity or protect a verified boundary. - Convert model-breeding ideas into compatibility checks, lineage manifests, blend, task-delta, sparse task-delta, DARE dropout/rescaled task-delta, and sign-merge operator receipts, trained adapter source manifests, raw, sparse, and low-rank adapter-delta manifests, adapter-fuse receipts, adapter-family receipts, module-plan resource receipts with WASM memory pages, KV-cache byte/page budgets, total budgets, byte counts, checksums, roles, phases, dependencies, and assembly slots, assembly receipts plus fetched evidence-file chains, runtime f32/q8_0/q4_0 adapter validation and apply invariants, browser runtime WASM manifests, candidate artifact manifests, multi-parent candidate manifests, promotion sidecars, multi-parent admission records, runtime-smoke sidecars, selector admission records, promotion ledgers, population reviews, parent-pool recipes, selector registries for both admission families, registry-carried adapter-family routes, registry-carried module-plan and assembly receipt routes, selector default metadata, selector byte-budget metadata including `selector_model_byte_budget=33554432`, selector text-sidecar budget contract metadata, registry-controlled auto-assembly metadata including `adapter_auto_apply_byte_budget=1048576`, offline operators, and tiny-fixture tests before changing runtime behavior; current implemented gates are tinyrustlm-slm-pack compatibility, lineage-template, blend-candidate, delta-candidate, sparse-delta-candidate, dare-candidate, adapter-source-template, validate-adapter-source, adapter-delta, sparse-adapter-delta, low-rank-adapter-delta, fuse-adapter-delta, runtime validate_adapter_delta plus apply_adapter_delta for f32/q8_0/q4_0 ADP1, ASP1, and ALR1, checked browser f32/q8_0/q4_0 adapter sidecars, browser runtime WASM manifest verification, registry-carried browser f32/q8_0/q4_0 ADP1/ASP1/ALR1 adapter routes plus adapter-family routes with browser-verified receipts and manifests, browser-verified module-plan WASM memory pages, resource envelopes, KV-cache byte/page budgets, total budgets, byte counts, checksums, roles, phases, dependencies, and assembly slots before generated model fetch, registry-controlled receipt-preferred browser auto assembly with byte-budget checks and Rust semantic preflight, registry-carried browser assembly receipt routes with fetched evidence-file checksum checks, selector frugal defaults, browser selector byte-budget intake, browser text-sidecar budget contracts, candidate-manifest, multi-parent-candidate-manifest with relatedness summary, promotion-template, multi-parent-promotion-template, multi-parent-admission-record, runtime-smoke, admission-record, promotion-ledger, population-review with objective-vector checksums, parent-pool-recipe with relatedness checksum, sign-merge-candidate with relatedness echo fields, and selector-registry. - Treat prune-candidate as an implemented direct-parameter operator beside blend, task-delta, sparse task-delta, crossover, mutation, federated/local-update, sign-merge, and soup: every prune change needs keep/floor parameter assertions, q8 validation evidence, drift tests, and receipt checksum routing. - Treat dare-candidate as an implemented direct-parameter operator beside blend, task-delta, sparse task-delta, crossover, mutation, prune, federated/local-update, sign-merge, and soup: every DARE change needs signed delta-weight, keep/drop, seed, q8 validation, drift, and receipt checksum routing. report_derived_testing_rules: - Target at least 75% automated test coverage for changed code, and record coverage evidence or the current tooling gap before making support claims. - Every added or changed method/function parameter should have a related automated test assertion; where coverage lives in an existing inline Rust module, name the source function and parameter in the test body or assertion context. - New standalone test files should mirror source filenames with `test` appended before the extension using Cargo/Node-safe names, while preserving existing inline Rust tests when they are the clearer local pattern. - Every added or changed method/function should carry a concise explanatory comment or doc comment focused on intent, boundary, parameter meaning, or invariant. - Every support claim needs a corresponding Rust unit test, Node WASM smoke, browser smoke, checksum, or documented manual evidence. - Report-derived ideas become work only after being turned into a testable invariant or explicit future-boundary note. - UI failure states are part of runtime correctness, not polish. - Candidate model work needs parent-hash evidence, a parent compatibility report, a validated lineage template, a validated blend, task-delta, sparse task-delta, DARE dropout/rescaled task-delta, or sign-merge operator receipt when an operator writes a .slm artifact, a validated multi-parent candidate manifest, multi-parent promotion sidecar, and multi-parent admission record for sign-merge outputs, a validated adapter-delta, sparse-adapter-delta, or low-rank-adapter-delta manifest when an adapter package is produced, focused runtime f32/q8_0/q4_0 adapter apply checks when ADP1, ASP1, or ALR1 runtime apply changes, a validated adapter-family receipt when a generated sidecar family is routed, a validated assembly receipt plus receipt-referenced evidence-file fetch proof when a generated browser bundle exposes model-breeding evidence, validated selector default metadata when a combined root should start on q4_0, browser selector byte-budget proof including registry-level `selector_model_byte_budget=33554432` when registry intake can alter fetch behavior, browser text-sidecar budget contract proof when registry text envelopes change, explicit adapter auto-apply metadata plus `adapter_auto_apply_byte_budget=1048576` and pre-generation browser smoke proof when generated receipt-preferred assembly should happen automatically, a validated adapter-fuse receipt when a raw adapter package writes a .slm candidate, a validated candidate artifact manifest, a validated promotion sidecar, a validated runtime-smoke sidecar, a validated selector admission record or multi-parent admission record, eval sidecars, a validated promotion ledger, a validated population review with objective-vector checksums when choosing a frontier or parent pool, a validated parent-pool recipe before parent-set recipe consumers, a validated selector registry, browser-smoke multi-parent-registry proof, generated browser-bundle proof, and adapter-sidecar-registry-file proof for generated assembly evidence and ADP1/ASP1/ALR1 adapter families before any selector or public claim change. - Candidate model work using deterministic pruning needs a validated prune operator receipt before candidate-manifest so the selected mask, output-value checksum, candidate checksum, and parent checksums remain replayable. - Candidate model work using DARE dropout/rescaled task-delta needs a validated DARE operator receipt before candidate-manifest so the nonzero-delta mask, raw delta checksum, rescaled delta checksum, candidate checksum, and parent checksums remain replayable. ================================================================================ END FILE: .uai/coding-standards.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/file-handoff.uai BYTES: 3954 SHA256: 304F0633412E435164D122F4A2979A6472066F256E4566FAB5D37FA7243A15C0 ================================================================================ profile: gguf-mirust.file-handoff.v14 updated_utc: 2026-06-29T02:39:17Z handoff_root: agent-file-handoff/ active_buckets: content: agent-file-handoff/Content/ improvement: agent-file-handoff/Improvement/ forbidden_default_bucket: archive: agent-file-handoff/Archive/ completion_gate: required_before_broad_work: true live_scan_required: true ledger_path: .uai/intake-outcome-ledger.uai outcomes: - incorporated - rejected-with-reason - preserved-to-durable-memory - kept-active-with-reason proof_required: - disposition - actual_source_work - hot_memory_update - llm_wiki_or_aiwikis_preservation_evidence - checks - blockers - source_site_removal_or_keep_active_reason durable_preservation: target: raw/gguf-mirust/ public_target: https://aiwikis.org/gguf-mirust/files/ manifest: raw/gguf-mirust/MANIFEST.md checksum_required: true strategy_refresh_2026_06_28: source: https://uaix.org/en-us/tools/ai-memory-package-wizard/#setup-file-handoff applied_shape: Active Content and Improvement buckets are transient intake; every reviewed file needs disposition, proof-of-use, durable raw/wiki preservation, hot routing, pointer-ledger refresh, report/research pointer audit, and a remove-or-keep-active decision. startup_loop: Open project root, scan active buckets, preserve durable bodies, refresh `.uai` routing, refresh long-term checksums, expose current routes from short-term memory, then continue implementation work. report_memory_rule: Reports stay as durable raw evidence plus wiki/report synthesis bodies; .uai files keep current routing, synthesis, proof pointers, and checksums. research_memory_rule: Research/reference bodies stay under wiki/gguf-mirust/research/; hot .uai files carry routing, implementation boundaries, and next-step prompts; long-term memory carries checksum pointers. short_term_reference_rule: .uai/short-term-memory.uai records current report indexes, research reference routes, active bucket disposition, and the long-term ledger route after each intake or strategy refresh. report_pointer_audit_rule: After report or research memory changes, audit wiki/gguf-mirust/reports/*.md and wiki/gguf-mirust/research/*.md against .uai/long-term-memory.uai before calling the handoff complete. diverse_model_breeding_reference_rule: Model Breeding ideas route through durable research lanes for compatible merges, sparse lineage, adapter ecology, population search, federated/local updates, browser-constrained assembly, UAIX memory strategy, heritable artifacts, mate selection, phenotype evidence, fit boundaries, genome/fitness/novelty/speciation metadata, and zero-dependency browser-runtime guidance. voice_memory_rule: Public-copy voice routes through .uai/taboo.uai before model-breeding, mutualist, tiny-ecology, or UAIX strategy copy is published; use proof, craft, lineage, fit, local agency, routes, and implementation evidence. current_scan: scanned_utc: 2026-06-29T02:39:17Z content_bucket_non_placeholder_files: 0 improvement_bucket_non_placeholder_files: 0 misplaced_root_files: 0 ide_adjacent_handoff_checked: E:\Source\WP\MikeKappel\agent-file-handoff\ ide_adjacent_non_placeholder_files: 0 attachment_reference_checked: C:\Users\AI\.codex\attachments\pasted-text-attachments.json and recent pasted-text files attachment_reference_found: no_current_gguf_handoff_research_latest_attachment_material_is_2026_06_27_or_older_and_not_new_gguf_research e_drive_free_bytes_at_scan: 66609135616 status: no_new_active_intake action: Live scan found no new active Content or Improvement files in the canonical GGUF handoff buckets; the visible IDE-adjacent handoff path only contained placeholder README files; the active IDE attachment path was absent, recent attachments were not new GGUF research, and the preserved 2026-06-28 research route remains the current ModelBreeder and zero-dependency guidance body. ================================================================================ END FILE: .uai/file-handoff.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/index.uai BYTES: 5807 SHA256: C4223233A43BA44D46FE87EE20DD4D3AA7FF39E4D106096728A0605572F8AF00 ================================================================================ profile: gguf-mirust.uai-index.v62 updated_utc: 2026-06-29T20:08:59Z files: - .uai/system-profile.uai - .uai/workspace-guidance.uai - .uai/coding-standards.uai - .uai/architecture.uai - .uai/report-synthesis.uai - .uai/file-handoff.uai - .uai/intake-outcome-ledger.uai - .uai/short-term-memory.uai - .uai/long-term-memory.uai - .uai/test-plan.uai - .uai/receiver-brief.uai - .uai/taboo.uai - .uai/startup-packet.uai - .uai/operations.uai - .uai/next-recursive-prompt.uai startup_hint: Read report-synthesis.uai after architecture and coding-standards when report-derived design pressure, governance, model breeding, converted-trained browser provenance, Model Breeding concept lanes, ModelBreeder genome/fitness/novelty/speciation guidance, deterministic crossover, deterministic bounded mutation, deterministic magnitude pruning, DARE dropout/rescaled task-delta, federated/local-update operators, seed-weighted parent-pool soup operators, parent-pool evolution schedules, operator schedule carry-forward, multi-parent soup manifest handoff, federated selector receipt routing, candidate operator receipt binding, promotion operator receipt binding, admission operator receipt binding, selector operator receipt binding, module-plan operator receipt binding, selector genome/fitness proof, selector species-fit proof, selector novelty proof, selector population proof, selector mate-selection proof, selector phenotype-evidence proof, selector heritable-artifact proof, zero-dependency browser-runtime guidance, trained adapter source intake, sparse adapter packages, low-rank ALR1 adapter packages, browser low-rank ALR1 routes, browser source-backed ALR1 routes or contracts, combined browser selector roots, same-page combined-selector assembly, combined-selector-cycle, combined-selector-route-soak, combined-selector-route-extended-soak, combined-selector-route-stress-soak, combined-selector-reload-soak, browser runtime assembly diagnostics, browser assembly trace, browser eval-case evidence checksums, browser assembly eval-case drift, browser assembly evidence-file drift, browser adapter stack preflight, browser adapter stack Rust validation, browser frugal selector defaults, browser selector budgets or budget contracts, browser auto assembly, browser auto-assembly byte budgets, browser adapter stacks, browser module plans, Module Plan display, budget display, prompt-limit display, output-limit display, total-budget display, total-limit display, WASM-pages display, WASM ABI display, Transfer display, Release display, Reset display, Validate display, Validate Count display, Apply Count display, Plan Fetches display, Actual Fetches display, Actual Route Set display, Actual Module Bytes display, Actual Module Checksums display, Route Hash display, Route Version display, Route Set display, KV-cache display, tokenizer display, sampler-cap display, fetch-count display, byte-count display, checksum display, role display, slot display, dependency display, phase display, fetch display, origin display, or trace display, module-plan profile contracts, execution-profile contracts, fetch-policy contracts, origin-policy contracts, fetch-count contracts, planned-fetch-count contracts, actual-fetch-count contracts, observed-route-set contracts, actual-module-bytes contracts, actual-module-checksums contracts, route-set-algorithm contracts, route-set-version contracts, route-set contracts, module-plan operator receipt contracts, tokenizer contracts, sampler-cap contracts, prompt-limit contracts, output-limit contracts, WASM-memory contracts, WASM export-set contracts, WASM transfer contracts, model-release contracts, runtime-reset contracts, adapter-validation contracts, adapter-validation-count contracts, adapter-apply-count contracts, KV-cache contracts, profile-drift proof, execution-profile-drift proof, fetch-policy-drift proof, fetch-count-drift proof, planned-fetch-count-drift proof, route-set-algorithm-drift proof, route-set-version-drift proof, route-set-drift proof, module-plan-operator-receipt-drift proof, tokenizer-drift proof, sampler-cap-drift proof, prompt-limit-drift proof, output-limit-drift proof, wasm-memory-drift proof, wasm-export-set-drift proof, wasm-transfer-drift proof, model-release-drift proof, runtime-reset-drift proof, adapter-validation-drift proof, adapter-validation-count-drift proof, adapter-apply-count-drift proof, kv-cache-drift proof, module-plan resource envelopes, total-budget proof, total-limit proof, count-drift proof, resource-drift proof, graph-drift proof, stack-drift proof, role-drift proof, slot-drift proof, dependency-drift proof, phase-drift proof, byte-drift proof, checksum-drift proof, browser text-sidecar budgets or text-sidecar budget contracts, browser runtime WASM manifests, UAIX dogfood context, setup-file-handoff strategy, report-pointer audit, or diverse Model Breeding research routing matters; read taboo.uai before public site copy. latest_route_hint: Read report-synthesis.uai plus the Browser Converted Trained Provenance, Browser Converted Trained File Route, Browser Converted Trained All Route, two-parent, crossover, mutation, prune, DARE operator, DARE browser operator provenance, Parent-Pool Evolution Schedule, and Operator Schedule Carry-Forward reports when converted-trained browser provenance, file-backed converted-trained selector/model/manifest routing, all-quant q4-defaulted converted-trained selector roots, compact browser Operator provenance, byte-echo fallback, direct-parameter blend, task-delta, sparse task-delta, crossover, bounded mutation, magnitude pruning, DARE dropout/rescaled task-delta, q8 operator proof, parent-pool operator scheduling, PBT-style replay, scheduled-family receipt echoes, or downstream candidate handoff are in scope. ================================================================================ END FILE: .uai/index.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/intake-outcome-ledger.uai BYTES: 30037 SHA256: F5A8470BCCF74FDA757C1A788C6D32E52DB91B4C75D60228A9FAE43B4EE9A5D1 ================================================================================ profile: gguf-mirust.intake-outcome-ledger.v8 updated_utc: 2026-06-29T02:39:17Z active_scan: content_bucket: agent-file-handoff/Content/ improvement_bucket: agent-file-handoff/Improvement/ content_non_placeholder_files: 0 improvement_non_placeholder_files: 0 result: 2026_06_29_rescan_no_new_active_intake_existing_research_route_used latest_scan_utc: 2026-06-29T02:39:17Z ide_adjacent_handoff_checked: E:\Source\WP\MikeKappel\agent-file-handoff\ ide_adjacent_non_placeholder_files: 0 attachment_scan_result: active_ide_attachment_path_absent_recent_attachment_material_2026_06_27_or_older_no_new_current_gguf_handoff_research e_drive_free_bytes_at_scan: 66609135616 shared_disposition_context: disposition: preserved-to-durable-memory actual_source_work: Processed 23 Improvement reports on 2026-06-25, 26 model-breeding Improvement reports on 2026-06-26, and 4 ModelBreeder/zero-dependency research files on 2026-06-28 into distributed long-term LLM Wiki memory, preserved exact originals under raw/gguf-mirust/, and updated report navigation. hot_memory_update: .uai/short-term-memory.uai, .uai/report-synthesis.uai, .uai/file-handoff.uai, .uai/intake-outcome-ledger.uai, .uai/long-term-memory.uai, .uai/receiver-brief.uai, .uai/taboo.uai, and wiki/gguf-mirust routing files updated. durable_preservation_evidence: raw/gguf-mirust/MANIFEST.md and report intake indexes for 2026-06-25, 2026-06-26, and 2026-06-28 record source files, checksums, duplicate relationships, and thematic synthesis routes. checks: live bucket scan, raw copy counts 23, 26, and 4, source-to-raw SHA256 verification, report synthesis file creation, wiki route update, stale scaffold wording scan, exact filename correction for curly-apostrophe report. blockers: none_current source_site_removal_or_keep_active_reason: Removed processed report copies from agent-file-handoff/Improvement/ after exact originals were preserved in raw evidence and durable synthesis records were created, including the 4-file 2026-06-28 research intake. report_intake_2026_06_26: source_bucket: agent-file-handoff/Improvement/ raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/ durable_index: wiki/gguf-mirust/reports/report-intake-index-2026-06-26.md durable_synthesis: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md durable_research: wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md source_count: 26 duplicate_groups: - sha256:C9B395CF265EA6D4BA17BD7087A72AC6B18C5FA7896E03E443ABE6D1E3A83545 maps to two 4Fs/code-beading/model-breeding filenames. disposition: preserved-to-durable-memory actual_source_work: Synthesized model breeding, code beading, 4Fs, model merging, LoRA/adapters, on-device tiny LLM, teleodynamic, mutualist, and evolutionary reports into future candidate-lineage memory. hot_memory_update: Updated report synthesis, architecture, coding standards, operations, workspace guidance, startup, receiver brief, short-term memory, file handoff, index, and taboo hot memory. durable_preservation_evidence: raw/gguf-mirust/MANIFEST.md, report-intake-index-2026-06-26.md, model-breeding-ecology-memory-2026-06-26.md, and model-breeding-reference-ideas-2026-06-26.md. checks: live bucket scan, raw copy count 26, source-to-raw SHA256 verification, durable synthesis creation, wiki route update. blockers: none_current source_site_removal_or_keep_active_reason: Removed processed source copies after exact originals, durable synthesis, hot routing, and pointer ledger records were created. report_intake_2026_06_28: source_bucket: agent-file-handoff/Improvement/ raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-28/ durable_index: wiki/gguf-mirust/reports/report-intake-index-2026-06-28.md durable_research: wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md source_count: 4 duplicate_groups: - sha256:18FE9E16D435D53892C8963E14212B7A3BEDFEE84E9FCD0AC87CB7BA322DA1E9 maps to two ModelBreeder guidance filenames. disposition: preserved-to-durable-memory actual_source_work: Synthesized ModelBreeder genome, fitness, novelty, population, speciation, product-voice, and zero-dependency browser-runtime research into future guidance lanes. hot_memory_update: Updated report synthesis, short-term memory, file handoff, intake ledger, taboo route, wiki index, knowledge map, source guide, log, and long-term pointer routing. durable_preservation_evidence: raw/gguf-mirust/MANIFEST.md, report-intake-index-2026-06-28.md, and modelbreeder-zero-dependency-reference-ideas-2026-06-28.md. checks: live bucket scan, raw copy count 4, source-to-raw SHA256 verification, durable research route creation, wiki route update. blockers: none_current source_site_removal_or_keep_active_reason: Remove processed source copies after exact originals, durable synthesis, hot routing, and pointer ledger records are complete. entries_2026_06_28: - source_path: agent-file-handoff/Improvement/ModelBreeder site and theory emphasize controlled evolution.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-28/ModelBreeder site and theory emphasize controlled evolution.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md routing_summary: Routes agents to ModelBreeder genome, fitness vector, novelty, population, speciation, CLI loop, and public-copy voice guidance. - source_path: agent-file-handoff/Improvement/ModelBreeder Theory vs. Source Files.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-28/ModelBreeder Theory vs. Source Files.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md routing_summary: Routes agents to browser client-side model visualization, Rust inference contrast, and broader breeder-paradigm vocabulary. - source_path: agent-file-handoff/Improvement/theory emphasize controlled evolution of AI models.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-28/theory emphasize controlled evolution of AI models.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md routing_summary: Duplicate ModelBreeder guidance source; preserve filename and route through the canonical 2026-06-28 research page. - source_path: agent-file-handoff/Improvement/Zero-Dependency Rust LLM Improvements.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-28/Zero-Dependency Rust LLM Improvements.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md routing_summary: Routes agents to zero-dependency Wasm SIMD, hierarchical quantization, adapters, tokenizer, sampler, KV-cache, allocator, multimodal, and telemetry guidance. entries_2026_06_26: - source_path: agent-file-handoff/Improvement/4Fs and code beadingmodel breeding.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/4Fs and code beadingmodel breeding.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to 4Fs, code beading, and model-breeding definitions with duplicate checksum handling. - source_path: agent-file-handoff/Improvement/Adaptable, Resource-Efficient AI Ecosystems.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Adaptable, Resource-Efficient AI Ecosystems.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to 4Fs, adaptability, code beading, model breeding, and interchangeable tiny-model systems. - source_path: agent-file-handoff/Improvement/Aggressive Mutualism.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Aggressive Mutualism.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to mutualist framing while public website copy routes through .uai/taboo.uai. - source_path: agent-file-handoff/Improvement/AI Code Beading and Model Breeding.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/AI Code Beading and Model Breeding.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to code beading, mutable small models, teleodynamic convergence, and model-breeding mechanics. - source_path: agent-file-handoff/Improvement/AI Evolution_ Small Models, Big Ecology.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/AI Evolution_ Small Models, Big Ecology.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to tiny-model populations, model ecology, evolution paths, and operations layers. - source_path: agent-file-handoff/Improvement/AI Model Merging Architectures Explained.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/AI Model Merging Architectures Explained.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to model merging methods including soups, SLERP, task arithmetic, TIES, DARE, alignment, and memory management. - source_path: agent-file-handoff/Improvement/AI's Cosmic Legacy and Survival.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/AI's Cosmic Legacy and Survival.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to long-horizon speculative metaphors while product copy stays focused on local craft. - source_path: agent-file-handoff/Improvement/AI's Perfect Evolutionary Being.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/AI's Perfect Evolutionary Being.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to evolutionary evaluation, game theory, social dynamics, and future candidate fitness metaphors. - source_path: agent-file-handoff/Improvement/Designing the Perfect Evolutionary AI System.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Designing the Perfect Evolutionary AI System.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to evolutionary system architecture, benchmarks, metrics, and experiment planning. - source_path: agent-file-handoff/Improvement/Designing the Perfect Evolutionary AI.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Designing the Perfect Evolutionary AI.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to evolutionary AI design criteria and implementation roadmap ideas. - source_path: agent-file-handoff/Improvement/Evolution, Legacy, and Societal Evaluation.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Evolution, Legacy, and Societal Evaluation.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to human evaluation, legacy, status, and product-language metaphors. - source_path: agent-file-handoff/Improvement/Evolutionary and Psychological Motivations.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Evolutionary and Psychological Motivations.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to motivation, persistence, and evolutionary product framing. - source_path: agent-file-handoff/Improvement/Human drive – the intrinsic motivation to survive.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Human drive – the intrinsic motivation to survive.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to human drive, support, and thriving metaphors for user-centered copy. - source_path: agent-file-handoff/Improvement/lightweight multi-model LLM system in Rust.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/lightweight multi-model LLM system in Rust.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to Rust multi-model architecture, adapters, parameter merging, packaging, and on-device deployment context. - source_path: agent-file-handoff/Improvement/Model merging refers to combining multiple trained neural.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Model merging refers to combining multiple trained neural.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to model merging taxonomy and compatible parameter-fusion concepts. - source_path: agent-file-handoff/Improvement/Mutualist Persistence.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Mutualist Persistence.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to mutualist public positioning, user agency, and constructive site language. - source_path: agent-file-handoff/Improvement/Perfect Evolutionary AI.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Perfect Evolutionary AI.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to evolutionary criteria, metrics, and candidate-evaluation metaphors. - source_path: agent-file-handoff/Improvement/powerful AI systems will tend to develop instrumental drives.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/powerful AI systems will tend to develop instrumental drives.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to speculative agency background while site copy routes through .uai/taboo.uai. - source_path: agent-file-handoff/Improvement/Rust Tiny LLM Model Breeding Pipeline.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Rust Tiny LLM Model Breeding Pipeline.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to Rust-native candidate lineage, compatibility, merge operators, and traceability. - source_path: agent-file-handoff/Improvement/Survival_ Drive, Strive, and Thrive.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Survival_ Drive, Strive, and Thrive.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to thriving, meaning, and motivation metaphors for constructive public language. - source_path: agent-file-handoff/Improvement/Teleodynamic Evolution of AI Ecosystems.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Teleodynamic Evolution of AI Ecosystems.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to teleodynamic model ecology, component interchangeability, and resource constraints. - source_path: agent-file-handoff/Improvement/The 4Fs framework—Fast, Flexible, Frugal, Federated.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/The 4Fs framework—Fast, Flexible, Frugal, Federated.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to the Fast, Flexible, Frugal, Federated lens for tiny-model ecology work. - source_path: agent-file-handoff/Improvement/The rise of on-device, tiny language models part 2.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/The rise of on-device, tiny language models part 2.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to client-side multi-model strategies, tiny LLM architectures, and evaluation metrics. - source_path: agent-file-handoff/Improvement/The rise of on-device, tiny language models.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/The rise of on-device, tiny language models.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to on-device tiny LLMs, model breeding algorithms, Rust integration, and benchmarks. - source_path: agent-file-handoff/Improvement/The terms 4Fs and code beading model breeding.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/The terms 4Fs and code beading model breeding.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Duplicate checksum route for 4Fs, code beading, and model-breeding definitions. - source_path: agent-file-handoff/Improvement/Tiny-LLM Adapters and LoRA.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-26/Tiny-LLM Adapters and LoRA.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md routing_summary: Routes agents to LoRA, adapters, compatibility, candidate evaluation, and Rust trait sketches. entries: - source_path: agent-file-handoff/Improvement/best practices and governance guidelines for enterprise Rust adoption.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/best practices and governance guidelines for enterprise Rust adoption.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/enterprise-rust-governance-memory-2026-06-25.md routing_summary: Enterprise Rust governance guidance distilled into trust-boundary, zero-dependency, test, supply-chain, unsafe-code, and maintainability pressure for TinyRustLM. - source_path: agent-file-handoff/Improvement/Branding MiRust.com.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Branding MiRust.com.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/brand-product-positioning-memory-2026-06-25.md routing_summary: Brand guidance distilled into local-runtime positioning, smoke-model honesty, and TinyRustLM copy boundaries. - source_path: agent-file-handoff/Improvement/Building a lightweight AI runtime in the browser with Rust.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Building a lightweight AI runtime in the browser with Rust.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/browser-local-runtime-memory-2026-06-25.md routing_summary: Browser-local runtime guidance distilled into local fetch, WASM boundary, diagnostics, memory pressure, and local-only validation. - source_path: agent-file-handoff/Improvement/Building Custom Rust SML Runtime.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Building Custom Rust SML Runtime.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/browser-local-runtime-memory-2026-06-25.md routing_summary: VM and embedded TinyLM ideas distilled as typed-boundary and arena-discipline inspiration, not a current SML runtime task. - source_path: agent-file-handoff/Improvement/Building Rust AI Runtime for Web.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Building Rust AI Runtime for Web.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/browser-local-runtime-memory-2026-06-25.md routing_summary: Web AI runtime report distilled into browser constraints and future comparison points while quarantining forbidden framework recommendations. - source_path: agent-file-handoff/Improvement/Enterprise Rust Best Practices.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Enterprise Rust Best Practices.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/enterprise-rust-governance-memory-2026-06-25.md routing_summary: Enterprise Rust guidance distilled into onboarding, workspace, error, CI, security, and release discipline for the no-crate runtime. - source_path: agent-file-handoff/Improvement/Machine Inteligence framwork for rust.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Machine Inteligence framwork for rust.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/brand-product-positioning-memory-2026-06-25.md routing_summary: Duplicate brand guidance preserved by checksum and routed to product positioning memory instead of duplicating long-term narrative. - source_path: agent-file-handoff/Improvement/Modular AI in Browser.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Modular AI in Browser.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25.md routing_summary: Modular browser AI guidance distilled into future skill composition, routing, and WebGPU comparison pressure. - source_path: agent-file-handoff/Improvement/Modular Tiny Language Models Architecture.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Modular Tiny Language Models Architecture.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25.md routing_summary: Modular tiny model guidance distilled into future model ABI, packaging, permissions, routing, and evaluation concerns. - source_path: agent-file-handoff/Improvement/Multiple Tiny Language Models Architectures and Trends.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Multiple Tiny Language Models Architectures and Trends.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25.md routing_summary: Multi-model trends distilled into routing, cascades, ensemble trade-offs, failure modes, and future benchmark questions. - source_path: agent-file-handoff/Improvement/Rust Browser Tiny LLM Architecture.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Rust Browser Tiny LLM Architecture.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25.md routing_summary: Browser-native modular tiny LLM guidance distilled into future LoRA, OPFS, WebGPU, and concurrency comparison boundaries. - source_path: agent-file-handoff/Improvement/Rust Design Patterns and SOLID Principles.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Rust Design Patterns and SOLID Principles.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/enterprise-rust-governance-memory-2026-06-25.md routing_summary: Rust pattern guidance distilled into enums, typestate, newtypes, explicit errors, and guidance away from object-oriented overfitting. - source_path: agent-file-handoff/Improvement/Rust In-Browser Teleodynamic AI Plan.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Rust In-Browser Teleodynamic AI Plan.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25.md routing_summary: Teleodynamic plan distilled into resource-bounded diagnostics, phase states, and future adaptive-loop questions. - source_path: agent-file-handoff/Improvement/Rust ownership model and type system naturally embody many SOLID concepts.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Rust ownership model and type system naturally embody many SOLID concepts.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/enterprise-rust-governance-memory-2026-06-25.md routing_summary: Rust ownership/SOLID mapping distilled into cohesive module and ownership guidance for maintainable runtime code. - source_path: agent-file-handoff/Improvement/Rust WebAssembly Teleodynamic AI Architecture.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Rust WebAssembly Teleodynamic AI Architecture.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25.md routing_summary: Teleodynamic WASM architecture distilled into browser resource limits, future persistence, and adaptive behavior scope notes. - source_path: agent-file-handoff/Improvement/Teleodynamic AI in the Browser.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Teleodynamic AI in the Browser.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25.md routing_summary: Browser teleodynamic report distilled into local agent constraints, runtime comparison, roadmap pressure, and UI resource signals. - source_path: agent-file-handoff/Improvement/Teleodynamic AI is an approach where a system’s structure and parameters co-evolve.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Teleodynamic AI is an approach where a system’s structure and parameters co-evolve.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25.md routing_summary: Modular teleodynamic skill-system guidance distilled into future composition, provenance, deployment, and benchmark questions. - source_path: agent-file-handoff/Improvement/Teleodynamic AI is an approach.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Teleodynamic AI is an approach.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25.md routing_summary: Duplicate modular teleodynamic skill-system guidance preserved by checksum and routed without duplicating narrative memory. - source_path: agent-file-handoff/Improvement/Teleodynamic AI refers to resource-bounded.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Teleodynamic AI refers to resource-bounded.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25.md routing_summary: Resource-bounded AI report distilled into budgeted browser behavior, local privacy, and CI/deployment scope notes. - source_path: agent-file-handoff/Improvement/Teleodynamic Tiny Language Model Architecture.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Teleodynamic Tiny Language Model Architecture.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25.md routing_summary: Teleodynamic tiny model report distilled into swarm, security, coherence, and constraint-maintaining ideas for later architecture. - source_path: agent-file-handoff/Improvement/Teleodynamics is a theoretical framework .md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Teleodynamics is a theoretical framework .md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25.md routing_summary: Teleodynamic ensemble report distilled into multi-model patterns, robustness, evaluation, and alignment-risk questions. - source_path: agent-file-handoff/Improvement/Tiny Language Models Architecture.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/Tiny Language Models Architecture.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25.md routing_summary: Multi-SLM ecosystem report distilled into routing, cascades, speculative decoding, cache reuse, standards, and security implications. - source_path: agent-file-handoff/Improvement/To run a TinyLM-16M transformer in-browser.md raw_evidence_path: raw/gguf-mirust/report-intake-2026-06-25/To run a TinyLM-16M transformer in-browser.md disposition: preserved-to-durable-memory durable_memory: wiki/gguf-mirust/reports/browser-local-runtime-memory-2026-06-25.md routing_summary: TinyLM-16M implementation report distilled into model dimensions, .slm layout, tokenizer, quantization, browser bootstrap, and performance planning. ================================================================================ END FILE: .uai/intake-outcome-ledger.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/long-term-memory.uai BYTES: 296424 SHA256: 76D9DA07F35549A77606736FD8364FE3ACB4727E37E9CBB37C658CB348464AF9 ================================================================================ profile: gguf-mirust.long-term-memory-ledger.v101 updated_utc: 2026-06-29T20:22:33Z storage_mode: hybrid ledger_rule: pointer_only_not_context_free: true summary_policy: Routing-only, one sentence, 35 words maximum, no durable body memory. allowed_statuses: current, retired, superseded, quarantined records: - stable_id: gguf_mirust_workspace_uai memory_domain: gguf-mirust.hot_memory.workspace pointer_type: local_uai path: workspace.uai target_location: workspace.uai label: Required For Workspace Authority And Current Boundary summary: Routes agents to canonical root, converted-trained file/all routes, parent-pool and operator schedule memory, model authority, report strategy, pointer audit, URLs, and boundaries. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before orienting project state, support boundaries, report routing, or public claim boundaries. checksum_hash: sha256:2762B139D7B5EB92B3673C458D431A7B9FD252B8FF4E82BB52B9D5EB7C62B56C last_reviewed_utc: 2026-06-29T20:22:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; hot workspace state lives in the target file. - stable_id: gguf_mirust_workspace_guidance_uai memory_domain: gguf-mirust.hot_memory.workspace_guidance pointer_type: local_uai path: .uai/workspace-guidance.uai target_location: .uai/workspace-guidance.uai label: Required For Workspace Memory And Implementation Guidance summary: Routes agents to memory strategy, UAIX handoff, pointer audit, parent-pool/operator schedules, converted-trained routes, compact operator proof, research distribution, and implementation boundaries. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before broad memory loading, report strategy edits, or implementation boundary work. checksum_hash: sha256:5CE36C95DF0AA8498FA573290D77B9C6146FB185BD7340B0A906AEA122F908DE last_reviewed_utc: 2026-06-29T20:22:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; hot guidance lives in the target file. - stable_id: gguf_mirust_file_handoff_uai memory_domain: gguf-mirust.hot_memory.file_handoff pointer_type: local_uai path: .uai/file-handoff.uai target_location: .uai/file-handoff.uai label: Required For File Handoff Strategy summary: Routes agents to active intake buckets, disposition gates, durable preservation targets, report/research memory rules, pointer audit, and source-copy clearing. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before scanning, preserving, removing, or keeping active handoff files. checksum_hash: sha256:304F0633412E435164D122F4A2979A6472066F256E4566FAB5D37FA7243A15C0 last_reviewed_utc: 2026-06-29T02:39:17Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; active handoff strategy lives in the target file. - stable_id: gguf_mirust_intake_outcome_ledger_uai memory_domain: gguf-mirust.hot_memory.intake_outcome_ledger pointer_type: local_uai path: .uai/intake-outcome-ledger.uai target_location: .uai/intake-outcome-ledger.uai label: Required For Intake Outcome Ledger summary: Routes agents to active scan outcomes, source dispositions, durable preservation evidence, source-copy clearing, and current no-new-intake state. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before deciding whether handoff input was preserved, used, cleared, or remains active. checksum_hash: sha256:F5A8470BCCF74FDA757C1A788C6D32E52DB91B4C75D60228A9FAE43B4EE9A5D1 last_reviewed_utc: 2026-06-29T02:39:17Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; intake outcome state lives in the target file. - stable_id: gguf_mirust_report_synthesis_uai memory_domain: gguf-mirust.hot_memory.report_synthesis pointer_type: local_uai path: .uai/report-synthesis.uai target_location: .uai/report-synthesis.uai label: Required For Processed Report Synthesis Routing summary: Routes agents to processed reports, parent-pool/operator schedules, converted-trained file/all routes, compact operator guidance, receipt binding, model-breeding routes, UAIX dogfood, and audit. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before opening bulk reports, report-derived design guidance, or model-breeding research routes. checksum_hash: sha256:6FB4A26126EFB84A62611C3ABD2AECD4388F5ADFD6773BFA1249568493B4A81D last_reviewed_utc: 2026-06-29T20:22:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; processed report synthesis lives in the target file. - stable_id: gguf_mirust_short_term_memory_uai memory_domain: gguf-mirust.hot_memory.short_term pointer_type: local_uai path: .uai/short-term-memory.uai target_location: .uai/short-term-memory.uai label: Required For Current State And Report Routes summary: Routes agents to current state, parent-pool/operator schedules, converted-trained routes, compact operator reports, report/research routes, memory audits, and next verification. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before resuming current work, locating latest report memory, or choosing next verification. checksum_hash: sha256:9AF71A909542BE7A03BD7BEF0D3C63185EE0659106B186CA02BAF303DE3213CF last_reviewed_utc: 2026-06-29T20:22:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; current state and routes live in the target file. - stable_id: gguf_mirust_startup_packet_uai memory_domain: gguf-mirust.hot_memory.startup_packet pointer_type: local_uai path: .uai/startup-packet.uai target_location: .uai/startup-packet.uai label: Required For Agent Startup Order summary: Routes agents to startup order, active buckets, wiki target, parent-pool/operator schedules, converted-trained routes, compact operator status, module-plan proof, and milestone status. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before loading source, durable memory, or current milestone status. checksum_hash: sha256:058F316A6124BB90F8DE2F1BDFF17445276B2B3D82A4FC4B780FD8429AFFD612 last_reviewed_utc: 2026-06-29T20:22:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; startup order lives in the target file. - stable_id: gguf_mirust_architecture_uai memory_domain: gguf-mirust.hot_memory.architecture pointer_type: local_uai path: .uai/architecture.uai target_location: .uai/architecture.uai label: Required For Architecture Boundaries summary: Routes agents to TinyRustLM boundaries, parent-pool/operator schedules, converted-trained routing, compact operator gates, module-plan architecture, selector provenance, model-breeding gates, and research lanes. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before source edits, architecture changes, or model-breeding boundary work. checksum_hash: sha256:508C9D4EF45AEDD20890275A9F34FDDEA6CB61E7497D5D1886E62A444723A1B2 last_reviewed_utc: 2026-06-29T20:22:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; architecture memory lives in the target file. - stable_id: gguf_mirust_coding_standards_uai memory_domain: gguf-mirust.hot_memory.coding_standards pointer_type: local_uai path: .uai/coding-standards.uai target_location: .uai/coding-standards.uai label: Required For Coding And Verification Rules summary: Routes agents to Rust/browser coding rules, 75% coverage aim, parameter tests, method comments, compact operator tests, memory strategy, and drift checks. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before editing source, tests, browser host logic, or model-breeding operators. checksum_hash: sha256:3BBC6B439158967A09B6FCF747FD08E21FBB1D0357C1A82FD480EA4B0BFA08C2 last_reviewed_utc: 2026-06-29T18:46:12Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; coding rules live in the target file. - stable_id: gguf_mirust_operations_uai memory_domain: gguf-mirust.hot_memory.operations pointer_type: local_uai path: .uai/operations.uai target_location: .uai/operations.uai label: Required For Local Operations And Checks summary: Routes agents to local commands, verified checks, parent-pool/operator schedule proof, converted-trained route proof, receipt binding, operator routes, memory strategy evidence, and tests. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before running local servers, browser smokes, cargo checks, or cleanup. checksum_hash: sha256:E7D1743F8D886899A53AEC521CDD8D19A203D127EA8DD099CC66CDCE2417F24F last_reviewed_utc: 2026-06-29T20:22:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; operations memory lives in the target file. - stable_id: gguf_mirust_test_plan_uai memory_domain: gguf-mirust.hot_memory.test_plan pointer_type: local_uai path: .uai/test-plan.uai target_location: .uai/test-plan.uai label: Required For Test Plan And Evidence summary: Routes agents to tools, verification commands, coverage conventions, parent-pool/operator schedule checks, converted-trained route checks, compact operator checks, memory audits, and required tests. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before planning or auditing verification for source changes. checksum_hash: sha256:0EAE31ECAE64A909649A64FC5F408E5BA6D45F1526AB4E4FD4429F7C7572C31F last_reviewed_utc: 2026-06-29T20:22:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; test plan lives in the target file. - stable_id: gguf_mirust_uai_index memory_domain: gguf-mirust.hot_memory.index pointer_type: local_uai path: .uai/index.uai target_location: .uai/index.uai label: Required For Hot Memory Index summary: Routes agents to hot memory files and startup hints for parent-pool/operator schedules, converted-trained routes, compact operator proof, report synthesis, pointer audit, and site voice. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before choosing hot memory files for cold-start orientation. checksum_hash: sha256:C4223233A43BA44D46FE87EE20DD4D3AA7FF39E4D106096728A0605572F8AF00 last_reviewed_utc: 2026-06-29T20:08:59Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; file index lives in the target file. - stable_id: gguf_mirust_receiver_brief_uai memory_domain: gguf-mirust.hot_memory.receiver_brief pointer_type: local_uai path: .uai/receiver-brief.uai target_location: .uai/receiver-brief.uai label: Required For Receiver Brief summary: Routes agents to must-read startup files, current TinyRustLM support scope, Model Breeding memory routes, and public-claim boundaries. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before handing off or quickly orienting another agent to current project state. checksum_hash: sha256:DBF2149881208F3A586752776494DB57AC2CF8932BBF2D1D6B4A5AD13BE9D4D6 last_reviewed_utc: 2026-06-29T01:39:45Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; receiver brief lives in the target file. - stable_id: tinyrustlm_readme memory_domain: tinyrustlm.implementation_entry pointer_type: local_md path: tinyrustlm/README.md target_location: tinyrustlm/README.md label: Required For TinyRustLM Build And Run Instructions summary: Routes agents to TinyRustLM commands, converted-trained all bundles, compact operator browser smokes, operators, ADP1/ASP1/ALR1 adapters, runtime manifests, module plans, registries, and limits. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed implementation doc review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before building, testing, serving, or claiming TinyRustLM runtime support. checksum_hash: sha256:625BA413419244D514A72DB0881094AB151F0728D475588159E018757D923937 last_reviewed_utc: 2026-06-29T19:37:17Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; durable build detail lives in the target file. - stable_id: gguf_mirust_root_readme memory_domain: gguf-mirust.workspace_entry pointer_type: local_md path: README.md target_location: README.md label: Required For Workspace Entry Commands summary: Routes agents to setup, commands, operators, objective reviews, lineage receipts, ADP1/ASP1/ALR1 adapters, runtime manifests, module plans, registries, bundles, and memory strategy. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed workspace doc review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before orienting from the repository root or changing top-level commands. checksum_hash: sha256:3A1AF7CA83E518DC78F792ED2BA8E1637D4E25AFA62D7C2A11360FDEAFC0782A last_reviewed_utc: 2026-06-28T02:02:06Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; root command detail lives in the target file. - stable_id: tinyrustlm_workspace_cargo memory_domain: tinyrustlm.workspace_policy pointer_type: local_toml path: Cargo.toml target_location: Cargo.toml label: Required For Cargo Workspace Lints And Members summary: Routes agents to workspace members, release profile, missing_docs denial, unsafe lint policy, and zero third-party dependency manifests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed workspace manifest review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing workspace members, lints, profiles, or dependency policy. checksum_hash: sha256:37E5AD8B8D1951DEE7034C849887104F276E5ABA98C39034781A696A19551910 last_reviewed_utc: 2026-06-25T11:04:43Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; manifest policy lives in the target file. - stable_id: tinyrustlm_architecture memory_domain: tinyrustlm.architecture pointer_type: local_md path: tinyrustlm/docs/architecture.md target_location: tinyrustlm/docs/architecture.md label: Required For TinyRustLM Architecture summary: Routes agents to runtime/app/tooling boundaries, objective-vector reviews, parent-relatedness metadata, ADP1/ASP1/ALR1 apply, browser receipts, operators, registries, bundles, and expansion. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed architecture doc review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing runtime boundaries, app responsibilities, model loading, or future milestone order. checksum_hash: sha256:6EE3C495E1E518E249AD38BE548F98DF31B86B82614A9AFB93C5778F6233E269 last_reviewed_utc: 2026-06-28T03:42:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; architecture detail lives in the target file. - stable_id: tinyrustlm_slm_format memory_domain: tinyrustlm.slm_format pointer_type: local_md path: tinyrustlm/docs/slm-format.md target_location: tinyrustlm/docs/slm-format.md label: Required For SLM Format Work summary: Routes agents to v1 .slm layout, validation, compatibility, operators, sparse masks, relatedness fields, ADP1/ASP1/ALR1 adapters, browser sidecars, registries, and gates. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed format doc review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing model_format.rs, slm_pack, fixtures, or model validation. checksum_hash: sha256:4D06F94001165FBA0E996ADFE2DB234CA66B758379F807E716F6B7D542EA7627 last_reviewed_utc: 2026-06-28T02:37:25Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; format detail lives in the target file. - stable_id: tinyrustlm_tokenizer memory_domain: tinyrustlm.tokenizer pointer_type: local_md path: tinyrustlm/docs/tokenizer.md target_location: tinyrustlm/docs/tokenizer.md label: Required For TinyRustLM Tokenizer Work summary: Routes agents to byte-tokenizer ids, BPE merge rules, tiny BPE runtime proof, validation rules, and future trained-tokenizer expansion. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed tokenizer doc review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing tokenizer.rs, tokenizer fixtures, or BPE planning. checksum_hash: sha256:B133955180A0AF4F260C81F6438E1C586A27A4863068AD4B6E82C32DCB14D18F last_reviewed_utc: 2026-06-27T06:07:09Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; tokenizer detail lives in the target file. - stable_id: tinyrustlm_tokenizer_source memory_domain: tinyrustlm.tokenizer_source pointer_type: local_rs path: tinyrustlm/runtime/src/tokenizer.rs target_location: tinyrustlm/runtime/src/tokenizer.rs label: Required For Runtime Tokenizer Source summary: Routes agents to byte and BPE encode/decode, bounded decode overflow, tokenizer section validation, and tokenizer unit tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed runtime source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing tokenizer decode, BPE merge behavior, tokenizer validation, or output-buffer boundaries. checksum_hash: sha256:AB51E0EDA9F89E1567D5A3610DD97902390F8E8E9B22283137A089659FB13750 last_reviewed_utc: 2026-06-25T13:35:24Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; tokenizer implementation lives in the target file. - stable_id: tinyrustlm_quantization memory_domain: tinyrustlm.quantization pointer_type: local_md path: tinyrustlm/docs/quantization.md target_location: tinyrustlm/docs/quantization.md label: Required For TinyRustLM Quantization Work summary: Routes agents to direct q8_0/q4_0 matvec support, binary metadata, validation, failure cases, and TinyLM-16M quantization boundaries. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed quantization doc review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing quant.rs, quant_writer.rs, q8/q4 loading, or model-size claims. checksum_hash: sha256:1B1AFD7292FFD7FE5F023EE9BBF33169E1A2A839673434AE481603DAFA55A700 last_reviewed_utc: 2026-06-25T07:24:21Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; quantization detail lives in the target file. - stable_id: tinyrustlm_quant_source memory_domain: tinyrustlm.quantization_source pointer_type: local_rs path: tinyrustlm/runtime/src/quant.rs target_location: tinyrustlm/runtime/src/quant.rs label: Required For Runtime Quantization Helpers summary: Routes agents to q8_0/q4_0 dequantization, re-quantization helpers, nibble packing, block math, and quantization unit tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed runtime source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing q8/q4 dequantization, ADP1 compact apply, q4 packing, or quantized matvec support. checksum_hash: sha256:90E9F3103D39D00A75A1AC52756436D745EB0D24DE748AFFE5C3F462B183A914 last_reviewed_utc: 2026-06-27T14:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; quantization implementation lives in the target file. - stable_id: tinyrustlm_browser_runtime memory_domain: tinyrustlm.browser_runtime pointer_type: local_md path: tinyrustlm/docs/browser-runtime.md target_location: tinyrustlm/docs/browser-runtime.md label: Required For Browser Runtime Work summary: Routes agents to Rust hosting, runtime manifests, selector intake, module-plan display, combined-selector assembly, ADP1/ASP1 sidecars, adapter stacks, and local-only rules. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser runtime doc review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing app.js, app.css, app HTML, local fetch paths, or browser diagnostics. checksum_hash: sha256:8DDE334D27A44979124441E7221B68310F76A39195C6F9D73CA12E4D6597776C last_reviewed_utc: 2026-06-28T11:25:34Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser runtime detail lives in the target file. - stable_id: tinyrustlm_browser_app_html memory_domain: tinyrustlm.browser_app_source pointer_type: local_html path: tinyrustlm/app/index.html target_location: tinyrustlm/app/index.html label: Required For TinyRustLM Browser Shell Markup summary: Routes agents to static UI structure for chat, Step Token, adapters, provenance, Assembly Evidence, Module Plan Actual Fetches, Actual Route Set, Actual Module Bytes, and diagnostics. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed app source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing visible browser panels, product shell, or static app layout. checksum_hash: sha256:A8B764D53431971AAB1B41F1DB44C188444E434C6689D76034200D2E9F8942C7 last_reviewed_utc: 2026-06-29T11:40:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; implementation lives in the target file. - stable_id: tinyrustlm_browser_app_js memory_domain: tinyrustlm.browser_app_source pointer_type: local_js path: tinyrustlm/app/app.js target_location: tinyrustlm/app/app.js label: Required For TinyRustLM Browser Host Logic summary: Routes agents to runtime manifests, selector budgets, provenance, module plans, fetch counts, observed route sets, receipt/operator-kind evidence, sign-merge/soup assembly evidence, stacks, adapters, and diagnostics. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed app source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing browser host behavior, local fetches, model selection, provenance rendering, or WASM calls. checksum_hash: sha256:4BCC9EABD503807BA19B91E720CC252193EE823505F0DF0E0957EA824A7210C8 last_reviewed_utc: 2026-06-29T19:35:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; implementation lives in the target file. - stable_id: tinyrustlm_browser_app_css memory_domain: tinyrustlm.browser_app_source pointer_type: local_css path: tinyrustlm/app/app.css target_location: tinyrustlm/app/app.css label: Required For TinyRustLM Browser Shell Styling summary: Routes agents to responsive dark UI styling, transcript message layout, wrapped action controls, panel layout, control sizing, mobile behavior, and manifest-value wrapping. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed app source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing app layout, responsive behavior, or visible UI styling. checksum_hash: sha256:23F9A7A9D555718DEB9DEDF4862935AAC811CC6FD90EEFFE9168FA5CBAF1FAFF last_reviewed_utc: 2026-06-25T13:59:11Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; implementation lives in the target file. - stable_id: tinyrustlm_diagnostics_source memory_domain: tinyrustlm.diagnostics_source pointer_type: local_rs path: tinyrustlm/runtime/src/diagnostics.rs target_location: tinyrustlm/runtime/src/diagnostics.rs label: Required For Diagnostics JSON And Benchmark State summary: Routes agents to handwritten diagnostics JSON rendering, control-character escaping, benchmark counters, developer fields, and model/generation state reporting. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed runtime source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing diagnostics JSON, benchmark counters, developer mode fields, or browser JSON.parse assumptions. checksum_hash: sha256:C03C756292DF8622F7684C64BAD3560B7B3D9929616DC5548F51AF4C10EE9522 last_reviewed_utc: 2026-06-27T06:07:09Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; diagnostics implementation lives in the target file. - stable_id: tinyrustlm_testing memory_domain: tinyrustlm.testing pointer_type: local_md path: tinyrustlm/docs/testing.md target_location: tinyrustlm/docs/testing.md label: Required For TinyRustLM Test Coverage summary: Routes agents to tests for operators, ADP1/ASP1/ALR1 adapters, module-plan payload checksum drift, actual module checksums, selector provenance, route-soaks, manifests, registries, ABI, and smokes. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed testing doc review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before adding tests, accepting runtime behavior, or claiming milestone completion. checksum_hash: sha256:FEEB5288862F939384B44320EA75AF0DEE06BDF76E1D919B9A543BEEB448C5A4 last_reviewed_utc: 2026-06-29T13:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; testing detail lives in the target file. - stable_id: tinyrustlm_ops_source memory_domain: tinyrustlm.core_math_source pointer_type: local_rs path: tinyrustlm/runtime/src/ops.rs target_location: tinyrustlm/runtime/src/ops.rs label: Required For Core Math Operations summary: Routes agents to dot, matvec, matmul, RMSNorm, softmax, SiLU, SwiGLU, and direct known-vector plus mismatch tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed runtime source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing core CPU/WASM math primitives or claiming Milestone 5 coverage. checksum_hash: sha256:47D6FEDD08B4DC3059F36C3203C13E0ECA8F53F2F18DCDC46B20A4A4E5B1028B last_reviewed_utc: 2026-06-25T12:09:41Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; implementation and tests live in the target file. - stable_id: tinyrustlm_performance memory_domain: tinyrustlm.performance pointer_type: local_md path: tinyrustlm/docs/performance.md target_location: tinyrustlm/docs/performance.md label: Required For TinyRustLM Performance Work summary: Routes agents to performance constraints, tensor routing, context state, reusable scratch/logits, 1024-cap sampling, output cap, diagnostics, browser smoke evidence, model sizes, and optimization order. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed performance doc review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before optimizing kernels, adding benchmarks, or claiming tokens-per-second numbers. checksum_hash: sha256:07A74898373F6807DE99BB1BCB3748A16460F0CB4CCE45D857CB56533A2A1B33 last_reviewed_utc: 2026-06-27T01:32:35Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; performance detail lives in the target file. - stable_id: tinyrustlm_models_readme memory_domain: tinyrustlm.models pointer_type: local_md path: tinyrustlm/models/README.md target_location: tinyrustlm/models/README.md label: Required For TinyRustLM Model Artifact Commands summary: Routes agents to model commands, converted-trained file/all bundles, operators, adapters, sidecars, sign-merge/soup/mixed bundles, cycle/route/reload smoke commands, gates, and artifacts. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed model artifact note review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before regenerating, deleting, or claiming model artifacts under tinyrustlm/models/. checksum_hash: sha256:58B136954E3227CB9B15801DF742EE36511F44A505F65B4FA148001F8B26EAA8 last_reviewed_utc: 2026-06-29T19:37:17Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; model command detail lives in the target file. - stable_id: tinyrustlm_model_format_source memory_domain: tinyrustlm.slm_format_source pointer_type: local_rs path: tinyrustlm/runtime/src/model_format.rs target_location: tinyrustlm/runtime/src/model_format.rs label: Required For SLM Parser And Checksum Validation summary: Routes agents to header parsing, offset validation, simple checksum calculation, and zero/mismatch checksum rejection. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed runtime source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing .slm header validation, checksum rules, or model acceptance boundaries. checksum_hash: sha256:B2041C774BB82009A57904A28EBEB5A08BB713FDAFCB30C5F83CCC6B4F8289D5 last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; parser implementation lives in the target file. - stable_id: tinyrustlm_tensor_source memory_domain: tinyrustlm.tensor_source pointer_type: local_rs path: tinyrustlm/runtime/src/tensor.rs target_location: tinyrustlm/runtime/src/tensor.rs label: Required For Tensor View Contracts summary: Routes agents to TensorView, MutableTensorView, shape validation, row-major flat indexing, mutable scratch writes, and element-count overflow checks. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed runtime source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing tensor views, scratch-buffer views, flat indexing, or tensor shape validation. checksum_hash: sha256:611ED2FEEA28B9E53D415291F9E1962B4EB6D56657437FB61AF16E994B710589 last_reviewed_utc: 2026-06-25T10:48:49Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; tensor implementation lives in the target file. - stable_id: tinyrustlm_model_source memory_domain: tinyrustlm.model_loading_source pointer_type: local_rs path: tinyrustlm/runtime/src/model.rs target_location: tinyrustlm/runtime/src/model.rs label: Required For Runtime Model Tensor Storage summary: Routes agents to model loading, runtime f32/q8/q4 ADP1/ASP1/ALR1 apply, tensor identity checks, indices, tied-output fallback, compact storage, scratch copies, and matvec. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed runtime source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing tensor loading, runtime adapter apply, quantized storage, tensor borrow/copy behavior, or model matvec dispatch. checksum_hash: sha256:2FA2149C17D301271316EAE29D214887597C63A313997C61CA5225F785C2373E last_reviewed_utc: 2026-06-28T08:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; model loading implementation lives in the target file. - stable_id: tinyrustlm_generate_source memory_domain: tinyrustlm.generation_source pointer_type: local_rs path: tinyrustlm/runtime/src/generate.rs target_location: tinyrustlm/runtime/src/generate.rs label: Required For Runtime Generation And Scratch Use summary: Routes agents to generation state, tensor-index use, BPE diagnostics, context cleanup, output cap, reusable scratch/logits, step-token ABI, adapter apply reset, model-free state, and KV updates. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed runtime source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generation loops, adapter apply state reset, scratch allocation, diagnostics counters, or quantized embedding/norm access. checksum_hash: sha256:A9788F5E70B9960440E642CFA27F6A776F8149FEF666BBFCDD6E6AFD6405111F last_reviewed_utc: 2026-06-28T08:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; generation implementation lives in the target file. - stable_id: tinyrustlm_runtime_adapter_source memory_domain: tinyrustlm.runtime_adapter_source pointer_type: local_rs path: tinyrustlm/runtime/src/adapter.rs target_location: tinyrustlm/runtime/src/adapter.rs label: Required For Runtime Adapter Package Parsing summary: Routes agents to runtime ADP1, ASP1, and ALR1 parsing, checksums, model identity validation, tensor directory validation, payload checks, finite values, and adapter tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed runtime source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing ADP1, ASP1, or ALR1 package parsing, checksum compatibility with slm_pack, runtime adapter validation, or adapter apply tests. checksum_hash: sha256:E45628BE16C7758C3A60C190FF866732A03BC442556BD35D81BD183D64B26DF6 last_reviewed_utc: 2026-06-28T02:02:06Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; adapter parser implementation lives in the target file. - stable_id: tinyrustlm_sampler_source memory_domain: tinyrustlm.sampler_source pointer_type: local_rs path: tinyrustlm/runtime/src/sampler.rs target_location: tinyrustlm/runtime/src/sampler.rs label: Required For Runtime Sampling Work summary: Routes agents to greedy and seeded stochastic sampling, fixed 1024-candidate buffers, BPE top_k 262 coverage, validation limits, top-k/top-p behavior, and PRNG use. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed runtime source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing temperature, top-k, top-p, seed, PRNG, or sampling allocation behavior. checksum_hash: sha256:2FDB1BC4BA798258A4ADF2034B3ED931083377E4C276E3D1BF5AC46EEC26488F last_reviewed_utc: 2026-06-25T11:55:13Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; sampling implementation lives in the target file. - stable_id: tinyrustlm_wasm_exports_source memory_domain: tinyrustlm.wasm_exports_source pointer_type: local_rs path: tinyrustlm/runtime/src/wasm_exports.rs target_location: tinyrustlm/runtime/src/wasm_exports.rs label: Required For TinyRustLM WASM Export Boundary summary: Routes agents to raw WASM exports, memory boundary calls, explicit ErrorCode returns, generate_next_token, apply_adapter_delta, diagnostics, reset, and free_model behavior. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed runtime source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing exported Rust functions, JS ABI calls, adapter apply, memory transfer, diagnostics pointers, reset behavior, or model-free behavior. checksum_hash: sha256:FB382F3A85D8232A9FB58AAF9F3F3612722FB578A2F1D327DB58E1BAF1753185 last_reviewed_utc: 2026-06-28T08:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; export implementation lives in the target file. - stable_id: tinyrustlm_slm_pack_source memory_domain: tinyrustlm.slm_packer_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/main.rs target_location: tinyrustlm/tools/slm_pack/src/main.rs label: Required For SLM Packer And Artifact Generation summary: Routes agents to CLI dispatch for conversion, browser-converted bundles, manifests, eval, DARE/federated/soup operators, receipt-bound flows, adapters, registries, mixed bundles, and checksums. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before regenerating artifacts or changing tensor writer/checksum behavior. checksum_hash: sha256:FCF15CE35EFEC3F274FA79AF4E7A3C79970C604C4F3E8BCA38A8AF4BBB6E54AB last_reviewed_utc: 2026-06-29T19:37:17Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; packer implementation lives in the target file. - stable_id: tinyrustlm_slm_browser_bundle_source memory_domain: tinyrustlm.model_breeding_browser_bundle_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/browser_bundle.rs target_location: tinyrustlm/tools/slm_pack/src/browser_bundle.rs label: Required For Generated Browser Multi-Parent Bundles summary: Routes agents to converted-trained all-bundle staging, f32/q8/q4 multi-parent bundles, soup/mixed generation, selector provenance, route-set fields, adapter stacks, evidence families, and smokes. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing browser-converted-trained-bundle, browser-multi-parent-bundle staging, combined selector roots, generated ADP1/ASP1 sidecar staging, or file-backed browser smoke. checksum_hash: sha256:6F558D24C1BB64BAAF92AF506FACED65BA92F350712507D0EEB5D7A287DBBEC8 last_reviewed_utc: 2026-06-29T19:37:17Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; generated bundle implementation lives in the target file. - stable_id: tinyrustlm_tokenizer_writer_source memory_domain: tinyrustlm.slm_tokenizer_writer_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/tokenizer_writer.rs target_location: tinyrustlm/tools/slm_pack/src/tokenizer_writer.rs label: Required For SLM Tokenizer Section Writing summary: Routes agents to BTOK and BPE1 tokenizer section writing, tiny BPE demo tokens, merge records, and writer tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing tokenizer section serialization or regenerating BPE fixture artifacts. checksum_hash: sha256:F201E5D93D65D447553C54691BBEA55B62B7D75522060854C2402BD316C3BFFD last_reviewed_utc: 2026-06-27T06:07:09Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; tokenizer writer implementation lives in the target file. - stable_id: tinyrustlm_slm_validate_source memory_domain: tinyrustlm.slm_admission_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/slm_validate.rs target_location: tinyrustlm/tools/slm_pack/src/slm_validate.rs label: Required For SLM Model Admission Validation summary: Routes agents to native .slm validation reports for headers, checksums, tokenizer metadata, flags, model shape, output contract, tensor layout, finite f32 values, and quant scales. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed validator source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing trained-model admission, conversion gates, or .slm validation claims. checksum_hash: sha256:7366E6C2151E3BA6129E8E6B1F1D09AB942252A62280D4951297989478FBCAB5 last_reviewed_utc: 2026-06-26T21:21:54Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; validator implementation lives in the target file. - stable_id: tinyrustlm_slm_compatibility_source memory_domain: tinyrustlm.model_breeding_compatibility_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/compatibility.rs target_location: tinyrustlm/tools/slm_pack/src/compatibility.rs label: Required For Parent Compatibility Reports summary: Routes agents to the parent compatibility command, report fields, direct-parameter match rules, pass/fail decisions, and q8/q4 mismatch tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing model-breeding parent-set checks or compatibility report fields. checksum_hash: sha256:29E4BCE5FDCCE6E1045D0B559AB9E05785E8485BA8637317B7C131727A5D5C87 last_reviewed_utc: 2026-06-26T21:21:54Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; compatibility implementation lives in the target file. - stable_id: tinyrustlm_slm_lineage_source memory_domain: tinyrustlm.model_breeding_lineage_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/lineage.rs target_location: tinyrustlm/tools/slm_pack/src/lineage.rs label: Required For Candidate Lineage Templates summary: Routes agents to lineage-template and validate-lineage, compatibility checksum binding, copied parent fields, candidate/operator ids, pending artifacts, and lineage tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing candidate lineage templates, operator handoff, or model-breeding pre-artifact gates. checksum_hash: sha256:69B7B590E2C5965D21F9A0BDBC8EE36CF13953A4B8059E6DD00F692DBEC8EFEE last_reviewed_utc: 2026-06-26T22:51:59Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; lineage implementation lives in the target file. - stable_id: tinyrustlm_slm_blend_source memory_domain: tinyrustlm.model_breeding_blend_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/blend.rs target_location: tinyrustlm/tools/slm_pack/src/blend.rs label: Required For Blend Operator Receipts summary: Routes agents to blend-candidate, validate-blend-candidate, parent checksums, weighted tensor blending, .slm output, receipt recomputation, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing offline direct-parameter operators, operator receipts, or candidate artifact handoff. checksum_hash: sha256:19E0776F91717ABE5715E07DC730ED3C66A46C0FF649026EF9CF57354C36FC8F last_reviewed_utc: 2026-06-27T01:12:24Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; blend operator implementation lives in the target file. - stable_id: tinyrustlm_slm_delta_source memory_domain: tinyrustlm.model_breeding_delta_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/delta.rs target_location: tinyrustlm/tools/slm_pack/src/delta.rs label: Required For Task-Delta Operator Receipts summary: Routes agents to delta-candidate, validate-delta-candidate, base/target parent checksums, signed task-vector weights, .slm output, receipt recomputation, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing task-vector operators, signed delta weights, operator receipts, or candidate artifact handoff. checksum_hash: sha256:1AD6CFF9FA117EC615FCA429F45D16927E9690C959BE486E7742A2A00B5B87D2 last_reviewed_utc: 2026-06-27T01:12:24Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; task-delta operator implementation lives in the target file. - stable_id: tinyrustlm_slm_sparse_delta_source memory_domain: tinyrustlm.model_breeding_sparse_delta_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/sparse_delta.rs target_location: tinyrustlm/tools/slm_pack/src/sparse_delta.rs label: Required For Sparse Task-Delta Operator Receipts summary: Routes agents to sparse-delta-candidate, validate-sparse-delta-candidate, keep rates, density, nonzero retention, mask checksums, .slm output, receipt recomputation, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing sparse task-vector operators, keep-rate selection, operator receipts, or candidate artifact handoff. checksum_hash: sha256:F56C9FCB3E11C04F1EF42329FEFEF8C34FD002E67B1A66AAEF5451C346A7A72A last_reviewed_utc: 2026-06-27T12:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; sparse task-delta operator implementation lives in the target file. - stable_id: tinyrustlm_slm_crossover_source memory_domain: tinyrustlm.model_breeding_crossover_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/crossover.rs target_location: tinyrustlm/tools/slm_pack/src/crossover.rs label: Required For Crossover Operator Receipts summary: Routes agents to crossover-candidate, validate-crossover-candidate, seed and keep parameters, selection density, mask checksum, receipt recomputation, q8 tests, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing deterministic direct-parameter crossover, selection masks, operator receipts, or candidate artifact handoff. checksum_hash: sha256:2AD77765C01313021C9BEF7A14203B7FADD3CFBEFDAB7CA359246E40770EA0F9 last_reviewed_utc: 2026-06-29T06:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; crossover operator implementation lives in the target file. - stable_id: tinyrustlm_slm_mutation_source memory_domain: tinyrustlm.model_breeding_mutation_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/mutation.rs target_location: tinyrustlm/tools/slm_pack/src/mutation.rs label: Required For Mutation Operator Receipts summary: Routes agents to mutation-candidate, validate-mutation-candidate, seed/rate/magnitude parameters, reference scaling, selection and delta checksums, q8 tests, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing deterministic bounded mutation, mutation masks, delta checksums, operator receipts, or candidate artifact handoff. checksum_hash: sha256:7252937956E25EB7581BFAF2303A7857F88730CD11062A5645112567043C3B65 last_reviewed_utc: 2026-06-29T07:05:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; mutation operator implementation lives in the target file. - stable_id: tinyrustlm_slm_prune_source memory_domain: tinyrustlm.model_breeding_prune_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/prune.rs target_location: tinyrustlm/tools/slm_pack/src/prune.rs label: Required For Prune Operator Receipts summary: Routes agents to prune-candidate, validate-prune-candidate, keep/floor ppm, magnitude ranking, mask/output checksums, q8 tests, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing deterministic magnitude pruning, pruning masks, output-value checksums, operator receipts, or candidate artifact handoff. checksum_hash: sha256:5D2325C53FDCCDFB3CFA5B167CF535F25670DF29C6C6840AFFA91AE2DC7A349D last_reviewed_utc: 2026-06-29T22:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; prune operator implementation lives in the target file. - stable_id: tinyrustlm_slm_dare_source memory_domain: tinyrustlm.model_breeding_dare_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/dare.rs target_location: tinyrustlm/tools/slm_pack/src/dare.rs label: Required For DARE Operator Receipts summary: Routes agents to dare-candidate, validate-dare-candidate, delta weight, keep/drop ppm, dropout seed, mask/raw/rescaled delta checksums, q8 tests, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing DARE dropout/rescaled task-delta arithmetic, masks, receipt fields, or candidate artifact handoff. checksum_hash: sha256:2228F76A58AC5DCF39B2D4E69CAE24AA14212AA8959E2C9DD4A9382B68CFDBF9 last_reviewed_utc: 2026-06-29T18:04:57Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; DARE operator implementation lives in the target file. - stable_id: tinyrustlm_slm_federated_source memory_domain: tinyrustlm.model_breeding_federated_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/federated.rs target_location: tinyrustlm/tools/slm_pack/src/federated.rs label: Required For Federated Local-Update Operator Receipts summary: Routes agents to federated-candidate, validate-federated-candidate, base/local-update parent roles, local_update_weight_ppm, local-update counts, delta checksums, q8 tests, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing federated local-update arithmetic, delta checksums, operator receipts, or candidate artifact handoff. checksum_hash: sha256:2E8E856E6BB0D9B194F308385B3F4148FA9368CA23F99FE1C9327CC113661009 last_reviewed_utc: 2026-06-29T13:45:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; federated operator implementation lives in the target file. - stable_id: tinyrustlm_slm_adapter_source memory_domain: tinyrustlm.model_breeding_adapter_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/adapter.rs target_location: tinyrustlm/tools/slm_pack/src/adapter.rs label: Required For Adapter Delta And Fuse Artifacts summary: Routes agents to raw ADP1, sparse ASP1, low-rank ALR1 artifacts, source-backed ALR1 bytes, validation, runtime apply status, manifests, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing adapter artifacts, raw, sparse, low-rank, or source-backed ALR1 packages, adapter-fuse handoff, runtime apply compatibility, or adapter manifest fields. checksum_hash: sha256:8F76A24981BF676CCEB162CF9718BFB1EE1B2FBB85418E6DBC671E8343D89C52 last_reviewed_utc: 2026-06-28T02:02:06Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; adapter artifact implementation lives in the target file. - stable_id: tinyrustlm_slm_adapter_family_source memory_domain: tinyrustlm.model_breeding_adapter_family_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/adapter_family.rs target_location: tinyrustlm/tools/slm_pack/src/adapter_family.rs label: Required For Adapter Family Receipts summary: Routes agents to adapter-family receipt generation, route-derived ADP1/ASP1 validation, preferred member and stack fields, auto-apply registry metadata, shared f32/q8/q4 identity checks, and tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated adapter-family receipts, selector receipt fields, or bundle receipt staging. checksum_hash: sha256:9A7AE9A7B9C5E1CAE1DBF3110D7A28F102CBC8A53615EE554431093727510618 last_reviewed_utc: 2026-06-28T13:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; adapter-family receipt implementation lives in the target file. - stable_id: tinyrustlm_slm_candidate_source memory_domain: tinyrustlm.model_breeding_candidate_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/candidate.rs target_location: tinyrustlm/tools/slm_pack/src/candidate.rs label: Required For Candidate Artifact Manifests summary: Routes agents to candidate-manifest and validate-candidate, lineage checksum binding, optional operator receipt binding, candidate .slm validation, parent-contract checks, pending eval fields, and tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing candidate artifact manifests, operator output gates, eval handoff, or model-breeding promotion records. checksum_hash: sha256:0482D43F9C0437C39B6F3C56D679F6ACDC7C8E0CE8FD524135C62E44B550B232 last_reviewed_utc: 2026-06-29T10:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; candidate artifact implementation lives in the target file. - stable_id: tinyrustlm_slm_promotion_source memory_domain: tinyrustlm.model_breeding_promotion_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/promotion.rs target_location: tinyrustlm/tools/slm_pack/src/promotion.rs label: Required For Candidate Promotion Templates summary: Routes agents to promotion-template and validate-promotion, optional operator receipt carry-forward, candidate manifest checksum binding, pending runtime-smoke/eval fields, selector admission state, and tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing candidate promotion sidecars, runtime-smoke handoff, eval handoff, selector admission, or promotion records. checksum_hash: sha256:0CE7B5F1D64495B5932402740C710EE2C8E684E0321762EA6BF7602154AB6F84 last_reviewed_utc: 2026-06-29T10:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; promotion implementation lives in the target file. - stable_id: tinyrustlm_slm_admission_source memory_domain: tinyrustlm.model_breeding_admission_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/admission.rs target_location: tinyrustlm/tools/slm_pack/src/admission.rs label: Required For Selector Admission Records summary: Routes agents to admission-record, validate-admission, optional operator receipt carry-forward, promotion checksum binding, runtime/eval evidence, selector summary validation, public-claim scope, and tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector admission records, operator receipt carry-forward, evidence checksum binding, browser selector intake, or candidate public-claim boundaries. checksum_hash: sha256:8A001B0351CB03F73C4E01381DA4C0847C08503C0F2EA3B1EEC69883BB28D130 last_reviewed_utc: 2026-06-29T10:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; selector admission implementation lives in the target file. - stable_id: tinyrustlm_slm_ledger_source memory_domain: tinyrustlm.model_breeding_ledger_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/ledger.rs target_location: tinyrustlm/tools/slm_pack/src/ledger.rs label: Required For Promotion Ledgers summary: Routes agents to promotion-ledger, validate-promotion-ledger, admitted record chaining, duplicate candidate rejection, duplicate artifact rejection, ledger checksums, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing promotion history, admitted candidate chains, selector handoff, or population review records. checksum_hash: sha256:0AC47CFF5021A553545B9D0E9393FC13793BB0268D8E23B9D442FD35BD410CA2 last_reviewed_utc: 2026-06-28T03:42:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; promotion ledger implementation lives in the target file. - stable_id: tinyrustlm_slm_population_source memory_domain: tinyrustlm.model_breeding_population_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/population.rs target_location: tinyrustlm/tools/slm_pack/src/population.rs label: Required For Population Review Records summary: Routes agents to population-review, validate-population-review, ledger-backed ranking, objective-vector metadata, per-entry objective checksums, frontier selection, parent-pool routing, fitness ppm fields, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing population review ranking, frontier selection, parent-pool routing, or PBT-inspired model-breeding gates. checksum_hash: sha256:48310799260A95B602BC3580E4FD11A2590BD7875A2AB0859B2C0CBA669B0648 last_reviewed_utc: 2026-06-27T13:45:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; population review implementation lives in the target file. - stable_id: tinyrustlm_slm_parent_pool_source memory_domain: tinyrustlm.model_breeding_parent_pool_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/parent_pool.rs target_location: tinyrustlm/tools/slm_pack/src/parent_pool.rs label: Required For Parent-Pool Recipe Records summary: Routes agents to parent-pool recipes, validation, population-review inputs, seed weights, relatedness checksums, sign-merge/soup evolution schedules, schedule checksums, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing reviewed-parent recipes, seed weighting, sign-aware merge planning, soup replay planning, evolution schedules, or population-review consumers. checksum_hash: sha256:C3ADE55E0A95AD132A16B59200C751906DEFD7492377FCF0F02DBEE4942CAB8D last_reviewed_utc: 2026-06-29T19:52:45Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; parent-pool recipe implementation lives in the target file. - stable_id: tinyrustlm_slm_sign_merge_source memory_domain: tinyrustlm.model_breeding_sign_merge_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/sign_merge.rs target_location: tinyrustlm/tools/slm_pack/src/sign_merge.rs label: Required For Sign-Aware Parent-Pool Merge Candidates summary: Routes agents to sign-merge-candidate, validation, parent-pool relatedness, schedule carry-forward, seed-weighted sign consensus, candidate bytes, receipts, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing sign-aware parent-pool merge operators, schedule carry-forward fields, multi-parent receipts, or candidate manifest handoff. checksum_hash: sha256:E2C07EC2ADEB25F1C0CEBFBF807486CA68B0C548B57512EF24BC447FA29EF948 last_reviewed_utc: 2026-06-29T20:08:59Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; sign-merge implementation lives in the target file. - stable_id: tinyrustlm_slm_soup_source memory_domain: tinyrustlm.model_breeding_soup_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/soup.rs target_location: tinyrustlm/tools/slm_pack/src/soup.rs label: Required For Seed-Weighted Parent-Pool Soup Candidates summary: Routes agents to soup-candidate, validation, parent-pool recipe checks, schedule carry-forward, seed-weighted tensor averaging, weighted-value checksums, candidate bytes, receipts, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing weighted parent-pool soup operators, schedule carry-forward fields, multi-parent receipts, or candidate manifest handoff. checksum_hash: sha256:2CEB401210DF55C49685BBA24B6DF94F9F34FE075CFCF08592F8CCA2B36DDF5E last_reviewed_utc: 2026-06-29T20:08:59Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; soup implementation lives in the target file. - stable_id: tinyrustlm_slm_multi_candidate_source memory_domain: tinyrustlm.model_breeding_multi_candidate_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/multi_candidate.rs target_location: tinyrustlm/tools/slm_pack/src/multi_candidate.rs label: Required For Multi-Parent Candidate Manifests summary: Routes agents to multi-parent manifests, operator-kind dispatch, sign-merge/soup receipt checksums, recipe schedule validation, relatedness, operator metrics, candidate fields, promotion route, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing multi-parent candidate manifests, sign-merge or soup handoff, scheduled-family validation, receipt checksum binding, operator metric preservation, or promotion routing. checksum_hash: sha256:0AD36F832C4111B2CB3F4029A9D39C1BD99E04E9FAFAA078C6FD3B6D8A055D3F last_reviewed_utc: 2026-06-29T20:08:59Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; multi-parent candidate implementation lives in the target file. - stable_id: tinyrustlm_slm_multi_promotion_source memory_domain: tinyrustlm.model_breeding_multi_promotion_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/multi_promotion.rs target_location: tinyrustlm/tools/slm_pack/src/multi_promotion.rs label: Required For Multi-Parent Promotion Templates summary: Routes agents to multi-parent-promotion-template, validation, candidate/receipt checksums, scheduled-family carry-forward, pending runtime-smoke/eval state, selector status, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing parent-pool operator promotion handoff, scheduled-family carry-forward, multi-parent runtime/eval routes, or selector admission routing. checksum_hash: sha256:60CDDEF2EF0D07C64CA0E9CCF546ED7A726D6B44B3B7220946AC7A8C2C143DBF last_reviewed_utc: 2026-06-29T20:22:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; multi-parent promotion implementation lives in the target file. - stable_id: tinyrustlm_slm_multi_admission_source memory_domain: tinyrustlm.model_breeding_multi_admission_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/multi_admission.rs target_location: tinyrustlm/tools/slm_pack/src/multi_admission.rs label: Required For Multi-Parent Selector Admission Records summary: Routes agents to multi-parent-admission-record, validation, operator receipt and scheduled-family carry-forward, parent-pool promotion evidence, runtime/eval checksums, selector-registry routing, and drift tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing parent-pool operator admission evidence, scheduled-family validation, multi-parent runtime/eval proof binding, or selector-registry handoff. checksum_hash: sha256:01F9D85FBAA0C8A49BB54899C2EB991C9D8BE7FA756740CAC61C2BA4453301DD last_reviewed_utc: 2026-06-29T20:22:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; multi-parent admission implementation lives in the target file. - stable_id: tinyrustlm_slm_selector_source memory_domain: tinyrustlm.model_breeding_selector_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/selector.rs target_location: tinyrustlm/tools/slm_pack/src/selector.rs label: Required For Selector Registry Records summary: Routes agents to selector-registry generation, converted-trained labels, operator receipt fields, multi-parent schedule admission schema, provenance, budgets, route-set fields, assembly routes, and tests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector registry generation, operator receipt fields, multi-parent admission schemas, model/text budget contracts, adapter auto-apply fields, browser admitted-route intake, optional adapter fields, mixed admission validation, or model-breeding promotion routing. checksum_hash: sha256:8B29F58261409AFA6043BDF817F53555A70932C750E4AD570AE7192623E22808 last_reviewed_utc: 2026-06-29T20:22:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; selector registry implementation lives in the target file. - stable_id: tinyrustlm_slm_provenance_source memory_domain: tinyrustlm.slm_provenance_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/provenance.rs target_location: tinyrustlm/tools/slm_pack/src/provenance.rs label: Required For SLM Provenance Manifest Validation summary: Routes agents to manifest generation, runtime-smoke sidecars, validation, eval templates, source-kind policy, checksum binding, case-ledger evidence, and quality gates. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing manifest sidecars, runtime-smoke sidecars, converted-trained admission, or quality-claim validation. checksum_hash: sha256:8112D2AF17A7DC3552A0F9D874B8766A3448A926B33E7262E982ACF069213D22 last_reviewed_utc: 2026-06-28T03:42:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; provenance implementation lives in the target file. - stable_id: tinyrustlm_eval_runner_source memory_domain: tinyrustlm.eval_runner_source pointer_type: local_rs path: tinyrustlm/runtime/src/eval_runner.rs target_location: tinyrustlm/runtime/src/eval_runner.rs label: Required For Native Eval Sidecar Generation summary: Routes agents to eval-case parsing, zero-case rejection, stray-case rejection, runtime case execution, per-case sidecar output, and quality-boundary fields. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed runtime source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing eval cases, assistant-quality sidecars, converted-trained quality gates, or tinyrustlm-eval behavior. checksum_hash: sha256:4907408005ACFA229C9BA8E2007EB95612FCD07C5F0C3EA17C2CE5B45624CA1A last_reviewed_utc: 2026-06-25T11:30:16Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; eval runner implementation lives in the target file. - stable_id: tinyrustlm_trained_source_source memory_domain: tinyrustlm.trained_source_conversion pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/trained_source.rs target_location: tinyrustlm/tools/slm_pack/src/trained_source.rs label: Required For Trained Source Conversion summary: Routes agents to raw-f32 source validation, tied_output agreement, safe tensor paths, checksums, bounded weights, conversion commands, and converted-trained manifests. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing validate-source, source-template, convert-trained, or trained-source quality boundaries. checksum_hash: sha256:54A054A391D60584BE042D8A02ECF9C5E4726388566C0AB3695C2CAFE5DA8E3A last_reviewed_utc: 2026-06-27T06:07:09Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; source conversion implementation lives in the target file. - stable_id: tinyrustlm_trained_adapter_source_source memory_domain: tinyrustlm.trained_adapter_source pointer_type: local_rs path: tinyrustlm/tools/slm_pack/src/trained_adapter_source.rs target_location: tinyrustlm/tools/slm_pack/src/trained_adapter_source.rs label: Required For Trained Adapter Source Validation summary: Routes agents to adapter-source-template, validate-adapter-source, source-to-ALR1 conversion, base identity checks, manifests, factor validation, checksums, and delta-L1 recomputation. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed packer source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing trained adapter source layout, factor validation, source CLI commands, or factor-to-ALR1 conversion. checksum_hash: sha256:223350D68D5DC97D1343757FE2F0BA6C6734E619DE6E9771DDF1EE0D8D2C8E01 last_reviewed_utc: 2026-06-28T18:10:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; trained adapter source implementation lives in the target file. - stable_id: tinyrustlm_trained_source_fixture_manifest memory_domain: tinyrustlm.trained_source_fixture pointer_type: local_text path: tinyrustlm/tests/fixtures/trained-source-tiny/source.manifest target_location: tinyrustlm/tests/fixtures/trained-source-tiny/source.manifest label: Required For Tiny Trained Source Fixture summary: Routes agents to the tiny raw-f32 source fixture manifest and tensor file checksums used for conversion-path validation. pointer_status: current authority: durable-memory-pointer source_authority: local generated source fixture manifest review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate before regenerating trained-source fixtures or changing convert-trained tests. checksum_hash: sha256:1CE4EDEE82BECC2B84E5714AAC38A6A6C749AF6F9236DE4CC920F54DC9CDFF86 last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; tensor source checksums live in the target manifest. - stable_id: tinyrustlm_assistant_quality_eval_cases memory_domain: tinyrustlm.eval_fixture pointer_type: local_text path: tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt target_location: tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt label: Required For Assistant Quality Eval Fixture Cases summary: Routes agents to scoped assistant-quality fixture cases used as evaluation sidecar evidence for conversion plumbing, not product quality. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed eval fixture review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing eval sidecar evidence fields or assistant-quality fixture claims. checksum_hash: sha256:F0999C05C19029FC240E11A7BCFC41DC7CC43874F9F81ED6F1111BA66D7B76A8 last_reviewed_utc: 2026-06-27T06:07:09Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; provenance implementation lives in the target file. - stable_id: tinyrustlm_browser_smoke_tool memory_domain: tinyrustlm.browser_testing pointer_type: local_js path: tinyrustlm/tools/browser-smoke.js target_location: tinyrustlm/tools/browser-smoke.js label: Required For TinyRustLM Browser Smoke Verification summary: Routes agents to browser smokes for converted-trained file/all routes, compact operator fixtures, runtime drift, budgets, selector drift, soup/mixed checks, generated assembly, and local-origin checks. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed test tool review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Run after app, WASM, server, adapter sidecar, registry, or model selector changes. checksum_hash: sha256:F9C5C16AD314B11230537493741EFBEC37883E3770826203778E0088AAFD5DC5 last_reviewed_utc: 2026-06-29T19:37:17Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; executable test behavior lives in the target file. - stable_id: tinyrustlm_wasm_abi_smoke_tool memory_domain: tinyrustlm.wasm_abi_testing pointer_type: local_js path: tinyrustlm/tools/wasm-abi-smoke.js target_location: tinyrustlm/tools/wasm-abi-smoke.js label: Required For TinyRustLM WASM ABI Boundary Verification summary: Routes agents to the no-dependency WASM ABI smoke for invalid UTF-8, invalid args, invalid sampling, recovery, step-token, f32 adapter apply, free_model, and post-free checks. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed test tool review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Run after changing WASM exports, memory.rs, app prompt transfer, adapter apply, diagnostics, or Visual Studio test wrappers. checksum_hash: sha256:CCC8D69E0F0FFB739DED58452962829BB179136328820D7587EB05D457D3A0A0 last_reviewed_utc: 2026-06-28T08:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; executable test behavior lives in the target file. - stable_id: tinyrustlm_wasm_runtime_artifact memory_domain: tinyrustlm.wasm_artifact pointer_type: local_wasm path: tinyrustlm/runtime/tinyrustlm.wasm target_location: tinyrustlm/runtime/tinyrustlm.wasm label: Required For TinyRustLM Browser WASM Runtime Artifact summary: Routes agents to the rebuilt browser-loaded WASM artifact with tensor-index routing, reusable buffers, output cap, fixed-buffer sampling, ErrorCode step-token, apply_adapter_delta, and model-free ABI handling. pointer_status: current authority: durable-memory-pointer source_authority: locally built release artifact review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Check after rebuilding runtime exports or before browser/runtime smoke claims. checksum_hash: sha256:9416CB0169CF8A9F61D7F12BD531D43FA887A29F95CC8E6871AF4C3E33BCD6C3 last_reviewed_utc: 2026-06-28T08:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; source authority is runtime/src plus the build/test records. - stable_id: tinyrustlm_wasm_runtime_manifest memory_domain: tinyrustlm.wasm_manifest pointer_type: local_manifest path: tinyrustlm/runtime/tinyrustlm.wasm.manifest target_location: tinyrustlm/runtime/tinyrustlm.wasm.manifest label: Required For TinyRustLM Browser WASM Runtime Manifest summary: Routes agents to the checked runtime WASM manifest binding kind, path, byte count, checksum, and instantiate gate for browser boot. pointer_status: current authority: durable-memory-pointer source_authority: locally generated runtime manifest review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Check after rebuilding tinyrustlm.wasm or before browser runtime smoke claims. checksum_hash: sha256:E9A1CD14425FCA92FCE26CBF3240BFF9F19D35BFE34E1D60F4FE667BF97E1BF3 last_reviewed_utc: 2026-06-28T08:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; runtime manifest fields live in the target file. - stable_id: tinyrustlm_static_server_tool memory_domain: tinyrustlm.local_server pointer_type: local_js path: tinyrustlm/tools/static-server.js target_location: tinyrustlm/tools/static-server.js label: Fallback TinyRustLM Node Static Server summary: Routes agents to the legacy no-dependency Node fallback server retained for comparison while Rust server is the normal hosting path. pointer_status: superseded authority: durable-memory-pointer source_authority: local reviewed development tool review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing local serving, browser smoke hosting, or Visual Studio run/test server behavior. checksum_hash: sha256:93A2E12153444E18D807D2F4C7E9FA9BAF5EBEAA81D93DC175778C97876FF61C last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; executable server behavior lives in the target file. - stable_id: tinyrustlm_rust_local_server memory_domain: tinyrustlm.local_server pointer_type: local_rs path: tinyrustlm/tools/local_server/src/main.rs target_location: tinyrustlm/tools/local_server/src/main.rs label: Required For TinyRustLM Rust Local Static Server summary: Routes agents to the no-crate Rust loopback server for app, WASM, model, manifest, GET/HEAD, content-length, and traversal checks. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed development tool review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing local serving, browser smoke startup, Visual Studio F5 hosting, or path safety behavior. checksum_hash: sha256:8CA1CC5026792D2F1CB45883A82DB089E2561CA00BA43B3245B7CA246A996102 last_reviewed_utc: 2026-06-25T09:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; executable server behavior lives in the target file. - stable_id: tinyrustlm_rust_browser_harness memory_domain: tinyrustlm.browser_harness pointer_type: local_rs path: tinyrustlm/tools/browser_harness/src/main.rs target_location: tinyrustlm/tools/browser_harness/src/main.rs label: Required For TinyRustLM Rust Mini Browser Harness summary: Routes agents to no-crate Rust mini browser harness for static contracts, runtime manifests, selector/module-plan/provenance markers including Operator, Module Plan ids, and loopback routes. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed development tool review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing app contract checks, local-only policy checks, model manifest route checks, or Visual Studio browser-harness gates. checksum_hash: sha256:21F75CC76C9B934D81748D2B85B6F6CCC3677D953ADA1D6932FA2CDC6066ACA2 last_reviewed_utc: 2026-06-29T10:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; executable harness behavior lives in the target file. - stable_id: tinyrustlm_tinylm16_f32_model memory_domain: tinyrustlm.model_artifact pointer_type: local_slm path: tinyrustlm/models/tinylm16-f32.slm target_location: tinyrustlm/models/tinylm16-f32.slm label: Required For TinyLM-16M F32 Smoke Model summary: Routes agents to the deterministic real-shaped f32 model artifact used for TinyLM-16M load, generation, browser, and performance smoke checks. pointer_status: current authority: durable-memory-pointer source_authority: local generated model artifact review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate before claiming TinyLM-16M f32 support or regenerating model files. checksum_hash: sha256:70E9765080247FE859506534E87330D73FF50B66B8A48DC627C307069BB0DC5B last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; binary artifact content is the target file. - stable_id: tinyrustlm_tinylm16_q8_model memory_domain: tinyrustlm.model_artifact pointer_type: local_slm path: tinyrustlm/models/tinylm16-q8.slm target_location: tinyrustlm/models/tinylm16-q8.slm label: Required For TinyLM-16M Q8 Smoke Model summary: Routes agents to the deterministic q8_0 model artifact used for TinyLM-16M direct q8 matvec, browser, and performance smoke checks. pointer_status: current authority: durable-memory-pointer source_authority: local generated model artifact review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate before claiming TinyLM-16M q8_0 support or regenerating model files. checksum_hash: sha256:C3919E6D7244890E9B3C2B5E40C37F8D322467D859C15B8155700F20408DB950 last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; binary artifact content is the target file. - stable_id: tinyrustlm_tinylm16_q4_model memory_domain: tinyrustlm.model_artifact pointer_type: local_slm path: tinyrustlm/models/tinylm16-q4.slm target_location: tinyrustlm/models/tinylm16-q4.slm label: Required For TinyLM-16M Q4 Smoke Model summary: Routes agents to the deterministic q4_0 model artifact used for TinyLM-16M direct q4 matvec, browser, and performance smoke checks. pointer_status: current authority: durable-memory-pointer source_authority: local generated model artifact review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate before claiming TinyLM-16M q4_0 support or regenerating model files. checksum_hash: sha256:5AC2BD957113732BE9AB2AADFA2D2EFD54C3131E7E6C97BE424FAC6E72BB365B last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; binary artifact content is the target file. - stable_id: tinyrustlm_tiny_bpe_model memory_domain: tinyrustlm.model_artifact pointer_type: local_slm path: tinyrustlm/models/tiny-test-model-bpe.slm target_location: tinyrustlm/models/tiny-test-model-bpe.slm label: Required For Tiny BPE Runtime Fixture summary: Routes agents to the deterministic tiny BPE .slm artifact used to prove BPE1 tokenizer selection and merged-token runtime diagnostics. pointer_status: current authority: durable-memory-pointer source_authority: local generated model artifact review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate before claiming BPE runtime fixture support or regenerating model files. checksum_hash: sha256:31B27903C1588A1F246281DEF8027094C0D3862635FA7D3761AA1327471F3E82 last_reviewed_utc: 2026-06-25T11:46:02Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; binary artifact content is the target file. - stable_id: tinyrustlm_tiny_tied_model memory_domain: tinyrustlm.model_artifact pointer_type: local_slm path: tinyrustlm/models/tiny-test-model-tied.slm target_location: tinyrustlm/models/tiny-test-model-tied.slm label: Required For Tiny Tied-Output Runtime Fixture summary: Routes agents to the deterministic tiny .slm artifact proving output.weight omission only under the v1 tied-output flag. pointer_status: current authority: durable-memory-pointer source_authority: local generated model artifact review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate before changing tied-output projection, required tensor validation, or model fixture generation. checksum_hash: sha256:9D68DC80CD2CCC2366344B92A497629AF1D693350F92B3B0EE383D4B30E08B7C last_reviewed_utc: 2026-06-25T12:58:04Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; binary artifact content is the target file. - stable_id: tinyrustlm_tiny_f32_self_adp1 memory_domain: tinyrustlm.adapter_artifact pointer_type: local_adp1 path: tinyrustlm/models/tiny-test-model-self.adp1 target_location: tinyrustlm/models/tiny-test-model-self.adp1 label: Required For Tiny F32 Browser Adapter Sidecar summary: Routes agents to the checked zero-delta f32 ADP1 sidecar used by browser adapter-sidecar smoke and runtime apply validation. pointer_status: current authority: durable-memory-pointer source_authority: local generated adapter artifact review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate and smoke before changing browser Adapter Sidecar claims or regenerating tiny f32 adapter artifacts. checksum_hash: sha256:DBEEB5875D00958179600C1CB353CA1FAB7604F3D755A5DA905BFFF7F45B8BA8 last_reviewed_utc: 2026-06-27T08:24:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; binary artifact content is the target file. - stable_id: tinyrustlm_tiny_f32_self_adp1_manifest memory_domain: tinyrustlm.adapter_manifest pointer_type: local_text path: tinyrustlm/models/tiny-test-model-self.adp1.manifest target_location: tinyrustlm/models/tiny-test-model-self.adp1.manifest label: Required For Tiny F32 Browser Adapter Sidecar Manifest summary: Routes agents to the checked ADP1 manifest binding f32 apply status, parent checksums, adapter checksum, tensor layout, tokenizer, and next gate. pointer_status: current authority: durable-memory-pointer source_authority: local generated adapter manifest review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate before using the tiny f32 ADP1 package in browser or runtime adapter claims. checksum_hash: sha256:78D72C47C6423F4E16E194DBB7F56F055071962FF611CC8C12E971C4C0FB75D0 last_reviewed_utc: 2026-06-27T08:24:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; manifest content is the target file. - stable_id: tinyrustlm_tiny_q8_self_adp1 memory_domain: tinyrustlm.adapter_artifact pointer_type: local_adp1 path: tinyrustlm/models/tiny-test-model-q8-self.adp1 target_location: tinyrustlm/models/tiny-test-model-q8-self.adp1 label: Required For Tiny Q8 Browser Adapter Sidecar summary: Routes agents to the checked zero-delta q8_0 ADP1 sidecar used by browser adapter-sidecar smoke and compact runtime apply validation. pointer_status: current authority: durable-memory-pointer source_authority: local generated adapter artifact review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate and smoke before changing browser Adapter Sidecar claims or regenerating tiny q8 adapter artifacts. checksum_hash: sha256:7B4E998EFEAC9B9D7BB6F909FC99BC17CA81A905D5C19FA0970A8229BF67E5E8 last_reviewed_utc: 2026-06-27T14:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; binary artifact content is the target file. - stable_id: tinyrustlm_tiny_q8_self_adp1_manifest memory_domain: tinyrustlm.adapter_manifest pointer_type: local_text path: tinyrustlm/models/tiny-test-model-q8-self.adp1.manifest target_location: tinyrustlm/models/tiny-test-model-q8-self.adp1.manifest label: Required For Tiny Q8 Browser Adapter Sidecar Manifest summary: Routes agents to the checked q8_0 ADP1 manifest binding apply status, parent checksums, adapter checksum, tensor layout, tokenizer, and next gate. pointer_status: current authority: durable-memory-pointer source_authority: local generated adapter manifest review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate before using the tiny q8 ADP1 package in browser or runtime adapter claims. checksum_hash: sha256:5680FD9A8676B818BCE3B90175AE75B574ACFE380B0B374A27ED46EA2C714AEB last_reviewed_utc: 2026-06-27T14:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; manifest content is the target file. - stable_id: tinyrustlm_tiny_q4_self_adp1 memory_domain: tinyrustlm.adapter_artifact pointer_type: local_adp1 path: tinyrustlm/models/tiny-test-model-q4-self.adp1 target_location: tinyrustlm/models/tiny-test-model-q4-self.adp1 label: Required For Tiny Q4 Browser Adapter Sidecar summary: Routes agents to the checked zero-delta q4_0 ADP1 sidecar used by browser adapter-sidecar smoke and compact runtime apply validation. pointer_status: current authority: durable-memory-pointer source_authority: local generated adapter artifact review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate and smoke before changing browser Adapter Sidecar claims or regenerating tiny q4 adapter artifacts. checksum_hash: sha256:9BD044B950E0CED7B8C9785D0ECEB0E175B91861D1C845267BC0D690A0CC9C56 last_reviewed_utc: 2026-06-27T14:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; binary artifact content is the target file. - stable_id: tinyrustlm_tiny_q4_self_adp1_manifest memory_domain: tinyrustlm.adapter_manifest pointer_type: local_text path: tinyrustlm/models/tiny-test-model-q4-self.adp1.manifest target_location: tinyrustlm/models/tiny-test-model-q4-self.adp1.manifest label: Required For Tiny Q4 Browser Adapter Sidecar Manifest summary: Routes agents to the checked q4_0 ADP1 manifest binding apply status, parent checksums, adapter checksum, tensor layout, tokenizer, and next gate. pointer_status: current authority: durable-memory-pointer source_authority: local generated adapter manifest review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate before using the tiny q4 ADP1 package in browser or runtime adapter claims. checksum_hash: sha256:2060583F1243B373C8E3AEFECA5EFD763F09979E679249B9C087C1EC3DFF1880 last_reviewed_utc: 2026-06-27T14:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; manifest content is the target file. - stable_id: tinyrustlm_tiny_f32_manifest memory_domain: tinyrustlm.model_manifest pointer_type: local_text path: tinyrustlm/models/tiny-test-model.slm.manifest target_location: tinyrustlm/models/tiny-test-model.slm.manifest label: Required For Tiny F32 Model Provenance summary: Routes agents to the tiny f32 smoke model sidecar binding checksum, shape, source kind, admission status, and trained-quality non-claim. pointer_status: current authority: durable-memory-pointer source_authority: local generated provenance sidecar review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate with tinyrustlm-slm-pack before using the tiny f32 model artifact. checksum_hash: sha256:04A621560A3F24C8E8243A1D085CACB6944CAD0898967582500EDE6D885B1B81 last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; manifest content is the target file. - stable_id: tinyrustlm_tiny_q8_manifest memory_domain: tinyrustlm.model_manifest pointer_type: local_text path: tinyrustlm/models/tiny-test-model-q8.slm.manifest target_location: tinyrustlm/models/tiny-test-model-q8.slm.manifest label: Required For Tiny Q8 Model Provenance summary: Routes agents to the tiny q8 smoke model sidecar binding checksum, shape, source kind, admission status, and trained-quality non-claim. pointer_status: current authority: durable-memory-pointer source_authority: local generated provenance sidecar review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate with tinyrustlm-slm-pack before using the tiny q8 model artifact. checksum_hash: sha256:85AC07502280F1D05B18A6932B83465C60CA59EE1B4D157A45C668380131294F last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; manifest content is the target file. - stable_id: tinyrustlm_tiny_q4_manifest memory_domain: tinyrustlm.model_manifest pointer_type: local_text path: tinyrustlm/models/tiny-test-model-q4.slm.manifest target_location: tinyrustlm/models/tiny-test-model-q4.slm.manifest label: Required For Tiny Q4 Model Provenance summary: Routes agents to the tiny q4 smoke model sidecar binding checksum, shape, source kind, admission status, and trained-quality non-claim. pointer_status: current authority: durable-memory-pointer source_authority: local generated provenance sidecar review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate with tinyrustlm-slm-pack before using the tiny q4 model artifact. checksum_hash: sha256:EB53E4A34D831571BE34B29049D07901E85411561E761DC2C9E37C60827B853F last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; manifest content is the target file. - stable_id: tinyrustlm_tiny_bpe_manifest memory_domain: tinyrustlm.model_manifest pointer_type: local_text path: tinyrustlm/models/tiny-test-model-bpe.slm.manifest target_location: tinyrustlm/models/tiny-test-model-bpe.slm.manifest label: Required For Tiny BPE Model Provenance summary: Routes agents to the tiny BPE smoke model sidecar binding checksum, BPE vocab shape, source kind, admission status, and trained-quality non-claim. pointer_status: current authority: durable-memory-pointer source_authority: local generated provenance sidecar review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate with tinyrustlm-slm-pack before using the tiny BPE model artifact. checksum_hash: sha256:AE28DDD62E91834A1F7F6D29BE186CB9EA81A92FAEBC0A5AF3E5A4897DC15B52 last_reviewed_utc: 2026-06-25T11:46:02Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; manifest content is the target file. - stable_id: tinyrustlm_tiny_tied_manifest memory_domain: tinyrustlm.model_manifest pointer_type: local_text path: tinyrustlm/models/tiny-test-model-tied.slm.manifest target_location: tinyrustlm/models/tiny-test-model-tied.slm.manifest label: Required For Tiny Tied-Output Model Provenance summary: Routes agents to the tied-output smoke sidecar binding checksum, shape, source kind, admission status, and trained-quality non-claim. pointer_status: current authority: durable-memory-pointer source_authority: local generated provenance sidecar review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate with tinyrustlm-slm-pack before using the tiny tied-output model artifact. checksum_hash: sha256:469A78D503B010323709EEAF6731DC8AFE05F0DE442BC16BC63F58C636A1490C last_reviewed_utc: 2026-06-25T12:58:04Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; manifest content is the target file. - stable_id: tinyrustlm_tinylm16_f32_manifest memory_domain: tinyrustlm.model_manifest pointer_type: local_text path: tinyrustlm/models/tinylm16-f32.slm.manifest target_location: tinyrustlm/models/tinylm16-f32.slm.manifest label: Required For TinyLM-16M F32 Provenance summary: Routes agents to the TinyLM-16M f32 sidecar binding checksum, shape, source kind, admission status, and trained-quality non-claim. pointer_status: current authority: durable-memory-pointer source_authority: local generated provenance sidecar review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate with tinyrustlm-slm-pack before using the TinyLM-16M f32 artifact. checksum_hash: sha256:D9CDEF0D7CE09979EF8D824BCF68555322B89A286DE197148CD2263F654E3010 last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; manifest content is the target file. - stable_id: tinyrustlm_tinylm16_q8_manifest memory_domain: tinyrustlm.model_manifest pointer_type: local_text path: tinyrustlm/models/tinylm16-q8.slm.manifest target_location: tinyrustlm/models/tinylm16-q8.slm.manifest label: Required For TinyLM-16M Q8 Provenance summary: Routes agents to the TinyLM-16M q8 sidecar binding checksum, shape, source kind, admission status, and trained-quality non-claim. pointer_status: current authority: durable-memory-pointer source_authority: local generated provenance sidecar review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate with tinyrustlm-slm-pack before using the TinyLM-16M q8 artifact. checksum_hash: sha256:21178B39642AE045CB26FE99B1595BC5B193AE563EC17F7545E478316CBFAA70 last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; manifest content is the target file. - stable_id: tinyrustlm_tinylm16_q4_manifest memory_domain: tinyrustlm.model_manifest pointer_type: local_text path: tinyrustlm/models/tinylm16-q4.slm.manifest target_location: tinyrustlm/models/tinylm16-q4.slm.manifest label: Required For TinyLM-16M Q4 Provenance summary: Routes agents to the TinyLM-16M q4 sidecar binding checksum, shape, source kind, admission status, and trained-quality non-claim. pointer_status: current authority: durable-memory-pointer source_authority: local generated provenance sidecar review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Validate with tinyrustlm-slm-pack before using the TinyLM-16M q4 artifact. checksum_hash: sha256:7B1C77776876EC9BE80DD00CEFB6C7AE877FD592FBF4FAD5029080B36B8D46CB last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; manifest content is the target file. - stable_id: gguf_mirust_visual_studio_setup memory_domain: gguf-mirust.visual_studio pointer_type: local_md path: docs/visual-studio.md target_location: docs/visual-studio.md label: Required For Visual Studio Setup summary: Routes agents to Visual Studio prerequisites, TinyRustLM.sln, Rust server F5 hosting, browser harness, tied/source checks, ABI, Step Token smoke, soak, and ports. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed Visual Studio setup doc review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing Visual Studio solution, NMake project, or tools/vs helper scripts. checksum_hash: sha256:4EB9659BEBD8C33799A384DEE81415BCCB13304F2D2E67CFDC1A3D0D9976ABDB last_reviewed_utc: 2026-06-27T06:07:09Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; setup detail lives in the target file. - stable_id: gguf_mirust_visual_studio_solution memory_domain: gguf-mirust.visual_studio pointer_type: local_solution path: TinyRustLM.sln target_location: TinyRustLM.sln label: Required For Opening TinyRustLM In Visual Studio summary: Routes agents to the Visual Studio 2022 solution wrapper for the Cargo workspace and NMake project. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed Visual Studio solution review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Open when validating IDE entry points or changing Visual Studio project structure. checksum_hash: sha256:587E1C3FC6D2CF1113CEF11FC8013B7DE2A5B9C956C4E5026930F2DCB60E203D last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; solution structure lives in the target file. - stable_id: gguf_mirust_visual_studio_run_helper memory_domain: gguf-mirust.visual_studio pointer_type: local_ps1 path: tools/vs/Run-TinyRustLM.ps1 target_location: tools/vs/Run-TinyRustLM.ps1 label: Required For Visual Studio TinyRustLM Run Helper summary: Routes agents to the F5 wrapper for build-before-run, verified-server reuse, busy-port fallback, browser launch, and Rust local server execution. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed Visual Studio run helper review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing F5 behavior, local server launch, or port-selection behavior. checksum_hash: sha256:B1C08AF0BFEB1C0C6EA1EC19004DFE1BFD21C6BDE219C56232B4532ED136D1E8 last_reviewed_utc: 2026-06-25T09:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; executable run behavior lives in the target file. - stable_id: gguf_mirust_visual_studio_build_helper memory_domain: gguf-mirust.visual_studio pointer_type: local_ps1 path: tools/vs/Build-TinyRustLM.ps1 target_location: tools/vs/Build-TinyRustLM.ps1 label: Required For Visual Studio TinyRustLM Build Helper summary: Routes agents to the VS build wrapper for Cargo builds, WASM copy, runtime WASM manifest refresh, model regeneration, and deterministic-smoke manifest generation. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed Visual Studio build helper review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing VS build, model regeneration, or manifest sidecar generation behavior. checksum_hash: sha256:5371F463A326D4635C6291E518CF958D705CB1326759699CB58524C9ECE74ECC last_reviewed_utc: 2026-06-27T18:07:37Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; executable build behavior lives in the target file. - stable_id: gguf_mirust_visual_studio_test_helper memory_domain: gguf-mirust.visual_studio pointer_type: local_ps1 path: tools/vs/Test-TinyRustLM.ps1 target_location: tools/vs/Test-TinyRustLM.ps1 label: Required For Visual Studio TinyRustLM Test Helper summary: Routes agents to VS tests for Cargo, rustdoc, JS, model validation, source conversion, ABI, browser harness, sidecars, f32/q8/q4 generated routes, soak, and ports. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed Visual Studio test helper review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing Visual Studio test behavior or IDE validation claims. checksum_hash: sha256:5CB97570E976185DA8ECFDA4819FEBAC0F8BD94097EFEB3C6E92F44464676E0A last_reviewed_utc: 2026-06-27T16:25:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; executable test behavior lives in the target file. - stable_id: gguf_mirust_aiwikis_namespace memory_domain: gguf-mirust.public_namespace pointer_type: aiwikis_record path: https://aiwikis.org/gguf-mirust/ target_location: https://aiwikis.org/gguf-mirust/ label: Required For GGUF.MiRust.com AIWikis Namespace summary: Routes agents to the planned public AIWikis namespace for GGUF.MiRust.com source memory, durable wiki records, and site-scoped discovery. pointer_status: current authority: durable-memory-pointer source_authority: GGUF.MiRust.com local LLM Wiki scaffold review_status: planned_pending_publication quarantine_status: reviewed_current contextual_trigger: Read before publishing or routing public AIWikis pages for GGUF.MiRust.com. checksum_hash: not_applicable_remote_route_planned_publication last_reviewed_utc: 2026-06-24T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Remote route pointer only; local source truth lives in wiki/gguf-mirust/ until public publication. - stable_id: gguf_mirust_source_memory_guide memory_domain: gguf-mirust.source_memory_guide pointer_type: llmwiki_node path: wiki/gguf-mirust/source-memory-guide.md target_location: https://aiwikis.org/gguf-mirust/source-memory-guide/ label: Required For GGUF.MiRust.com Source Memory Routing summary: Routes agents to hot memory, durable wiki files, UAIX strategy, model-breeding references, converted-trained routes, compact operators, schedule carry-forward, mixed selector proof, and boundaries. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed LLM Wiki source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before loading durable project memory or processing handoff intake. checksum_hash: sha256:85DC5C82ECBEEF18E482BFAEE8D1C34B3F8E1585B9BBB1C89E785DA8904EAD9F last_reviewed_utc: 2026-06-29T20:08:59Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; durable source guide body lives in the target file. - stable_id: gguf_mirust_knowledge_map memory_domain: gguf-mirust.knowledge_map pointer_type: llmwiki_node path: wiki/gguf-mirust/knowledge-map.md target_location: https://aiwikis.org/gguf-mirust/knowledge-map/ label: Required For GGUF.MiRust.com Knowledge Map summary: Routes agents to durable nodes, report indexes, receipt binding, converted-trained routes, compact operator proof, schedule carry-forward, mixed selector proof, browser soup bundles, and evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed LLM Wiki source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before reorganizing durable wiki routes or raw evidence relationships. checksum_hash: sha256:7971DDF6B1CF5870BE5EF0FB11C665BD53A77913B279666C1600D847056641A7 last_reviewed_utc: 2026-06-29T20:08:59Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; durable map body lives in the target file. - stable_id: gguf_mirust_llm_wiki_log memory_domain: gguf-mirust.llm_wiki_log pointer_type: llmwiki_node path: wiki/gguf-mirust/log.md target_location: https://aiwikis.org/gguf-mirust/log/ label: Required For GGUF.MiRust.com LLM Wiki Log summary: Routes agents to LLM Wiki chronology for reports, converted-trained routes, compact operator proof, schedule carry-forward, memory strategy, receipt binding, mixed selector proof, and module-plan proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed LLM Wiki source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before auditing durable memory chronology or publication history. checksum_hash: sha256:E29FC184355011CD3684083B080BF66A9FF8ED734D86E776756C9C10A381B7B7 last_reviewed_utc: 2026-06-29T20:08:59Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; durable log body lives in the target file. - stable_id: gguf_mirust_browser_harness_architecture memory_domain: gguf-mirust.browser_harness_architecture pointer_type: local_md path: docs/architecture/browser-harness.md target_location: docs/architecture/browser-harness.md label: Superseded Browser Harness Architecture Boundary summary: Routes agents to the prior scaffold architecture that was superseded by the TinyRustLM zero-dependency runtime path. pointer_status: superseded authority: durable-memory-pointer source_authority: local reviewed architecture note review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read only when auditing the removed dependency-based scaffold or migration history. checksum_hash: sha256:B01F80EC9FEA52A6B417EEBF302C5EACCCAA0B1C75AACE594177C57289E6D760 last_reviewed_utc: 2026-06-24T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; durable architecture detail lives in the target file. - stable_id: gguf_mirust_aiwikis_routing_plan memory_domain: gguf-mirust.aiwikis_routing pointer_type: local_md path: docs/aiwikis-routing.md target_location: docs/aiwikis-routing.md label: Required For AIWikis Route Planning summary: Routes agents to local source paths, planned public AIWikis routes, publication status, and namespace rules. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed route plan review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing AIWikis route names, site namespace, or public discovery links. checksum_hash: sha256:36E35102BE3720E17F150CD4A829A6F4D0E5500BA969D1FB59B488438CD74E32 last_reviewed_utc: 2026-06-24T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; durable route detail lives in the target file. - stable_id: gguf_mirust_setup_dogfood memory_domain: gguf-mirust.setup_dogfood pointer_type: local_md path: docs/dogfood/uaix-llmwikis-setup-experience-2026-06-24.md target_location: docs/dogfood/uaix-llmwikis-setup-experience-2026-06-24.md label: Required For UAIX And LLMWikis Setup Dogfood summary: Routes agents to setup-experience findings about discovery routes, planned remote pointers, code-bearing scaffolds, local-public namespace pairs, and File Handoff proof. pointer_status: current authority: durable-memory-pointer source_authority: local dogfood review review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before improving UAIX or LLMWikis setup guidance from this scaffold. checksum_hash: sha256:D587B2E9273AFB2B88F660CCD69EAE5AF0F3692DBC3BD76716A00E6A04663C30 last_reviewed_utc: 2026-06-24T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; dogfood findings live in the target file. - stable_id: gguf_mirust_uaix_llm_wiki_crawlability_dogfood memory_domain: gguf-mirust.setup_dogfood pointer_type: local_md path: docs/dogfood/uaix-llm-wiki-crawlability-failure-2026-06-25.md target_location: docs/dogfood/uaix-llm-wiki-crawlability-failure-2026-06-25.md label: Required For UAIX LLM Wiki Crawlability Dogfood summary: Routes agents to the report-memory failure showing why durable wiki pointers need hot typed .uai synthesis for crawlability. pointer_status: current authority: durable-memory-pointer source_authority: local dogfood review review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before improving UAIX, LLM Wiki setup, or report-batch memory guidance. checksum_hash: sha256:C1E2C6873ACB37BAC3188785B5D24A9DA7B2AB6006A07167629C39DC7B6788A3 last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; dogfood findings live in the target file. - stable_id: gguf_mirust_uaix_file_handoff_strategy_dogfood memory_domain: gguf-mirust.setup_dogfood pointer_type: local_md path: docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md target_location: docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md label: Required For UAIX File Handoff Memory Strategy Dogfood summary: Routes agents to UAIX File Handoff strategy for raw preservation, durable synthesis, research routing, report pointer audit, hot memory, pointer ledgers, and source-copy clearing. pointer_status: current authority: durable-memory-pointer source_authority: local dogfood review from UAIX AI Memory Package Wizard review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing File Handoff, LLM Wiki, or report-batch strategy. checksum_hash: sha256:27150B92CF92D384D166013DC7201D9DD5F8F80684AF3067D3044EE52D83600B last_reviewed_utc: 2026-06-28T04:45:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; strategy findings live in the target file. - stable_id: gguf_mirust_llm_wiki_index memory_domain: gguf-mirust.llm_wiki_index pointer_type: llmwiki_node path: wiki/gguf-mirust/index.md target_location: https://aiwikis.org/gguf-mirust/ label: Required For GGUF.MiRust.com LLM Wiki Index summary: Routes agents to the LLM Wiki index for converted-trained routes, compact operator reports, schedule carry-forward, source guide, map, receipt binding, module-plan reports, research references, and boundaries. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed LLM Wiki source review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before publishing or reorganizing the GGUF.MiRust.com LLM Wiki namespace. checksum_hash: sha256:57FAEB895813A09929CC23C62C3483F9E2A9302401A22C50A566038417C7666C last_reviewed_utc: 2026-06-29T20:08:59Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; durable index body lives in the target file. - stable_id: gguf_mirust_report_intake_index_2026_06_25 memory_domain: gguf-mirust.report_memory pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/report-intake-index-2026-06-25.md target_location: https://aiwikis.org/gguf-mirust/reports/report-intake-index-2026-06-25/ label: Required For Report Intake Routing summary: Routes agents to the 23 processed reports, source checksums, duplicate groups, raw evidence path, and thematic synthesis records. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed report synthesis review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before loading report-derived long-term memory or auditing processed handoff reports. checksum_hash: sha256:068DE841DDCC3D4CDEB8518274ACF1CE21004861FFDEDEE81824B408D856946D last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; report inventory and routing details live in the target file. - stable_id: gguf_mirust_report_intake_index_2026_06_26 memory_domain: gguf-mirust.report_memory pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/report-intake-index-2026-06-26.md target_location: https://aiwikis.org/gguf-mirust/reports/report-intake-index-2026-06-26/ label: Required For Model Breeding Report Intake Routing summary: Routes agents to the 26 model-breeding reports, checksums, duplicate group, raw evidence path, synthesis route, and reference page. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed report synthesis review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before loading model-breeding report memory or auditing the 2026-06-26 handoff batch. checksum_hash: sha256:92BD64EC61B290C2A4CBB1DAE14622043B5714E8C6EE922145E410930F240EEB last_reviewed_utc: 2026-06-26T18:44:35Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; report inventory and routing details live in the target file. - stable_id: gguf_mirust_report_intake_index_2026_06_28 memory_domain: gguf-mirust.report_memory pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/report-intake-index-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/report-intake-index-2026-06-28/ label: Required For ModelBreeder Zero-Dependency Intake Routing summary: Routes agents to four 2026-06-28 research files, duplicate ModelBreeder hashes, raw evidence path, and durable research guidance route. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed report synthesis review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before loading ModelBreeder or zero-dependency handoff research from the 2026-06-28 batch. checksum_hash: sha256:032CEED373BEDF5D231CF731DB1D9A607DE4EB33E13681846A11D5AE4D9CE2CA last_reviewed_utc: 2026-06-28T22:40:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; report inventory and routing details live in the target file. - stable_id: gguf_mirust_model_breeding_ecology_memory memory_domain: gguf-mirust.report_memory.model_breeding pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md target_location: https://aiwikis.org/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26/ label: Required For Model Breeding Ecology Memory summary: Routes agents to model-breeding concepts for lineage, compatibility, sparse deltas, objective vectors, adapters, parent relatedness, evolutionary recipes, population review, parent pools, and promotion. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed report synthesis review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before model-breeding architecture, candidate manifest, adapter, merge-operator, or product-positioning work. checksum_hash: sha256:49CF8E4B99CDFF079F484D78F5644576C5B55B92106FBC98215004E3F28E8D5D last_reviewed_utc: 2026-06-27T13:45:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; report synthesis body lives in the target file. - stable_id: gguf_mirust_two_parent_operator_browser_provenance_memory memory_domain: gguf-mirust.report_memory.two_parent_operator_browser_provenance pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/two-parent-operator-browser-provenance-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/two-parent-operator-browser-provenance-memory-2026-06-29/ label: Required For Two Parent Operator Browser Provenance Memory summary: Routes agents to blend, task-delta, and sparse task-delta compact browser Operator rendering, byte-echo fallback smokes, README commands, and regression proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser provenance report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing compact operator fixtures, browser Model Provenance Operator rows, blend/delta/sparse-delta receipt routing, or byte-echo fallback. checksum_hash: sha256:53D1C965236A14267AD9AAAAB68DB2A77262BB4D4C085F0CFEF84A39CDEDC3CE last_reviewed_utc: 2026-06-29T17:41:02Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser provenance report body lives in the target file. - stable_id: gguf_mirust_crossover_operator_memory memory_domain: gguf-mirust.report_memory.crossover_operator pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/crossover-operator-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/crossover-operator-memory-2026-06-29/ label: Required For Crossover Operator Memory summary: Routes agents to crossover commands, seed/keep parameters, selection counts, density fields, mask checksum, browser Operator rendering, byte-echo fallback, focused tests, and CLI proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed crossover operator report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing crossover-candidate, validate-crossover-candidate, selection masks, crossover receipt fields, browser operator provenance, or downstream candidate handoff. checksum_hash: sha256:45C75982DF21B915FAFC4E0CAF041D2A761BD144352F9B4CF1C2592C75411FEB last_reviewed_utc: 2026-06-29T17:25:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; crossover operator report body lives in the target file. - stable_id: gguf_mirust_mutation_operator_memory memory_domain: gguf-mirust.report_memory.mutation_operator pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/mutation-operator-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/mutation-operator-memory-2026-06-29/ label: Required For Mutation Operator Memory summary: Routes agents to bounded mutation commands, seed/rate/magnitude fields, reference scaling, selection and delta checksums, browser Operator rendering, byte-echo fallback, focused tests, and CLI proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed mutation operator report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing mutation-candidate, validate-mutation-candidate, mutation masks, mutation receipt fields, browser operator provenance, or downstream candidate handoff. checksum_hash: sha256:5B9F1CF41251AC9A65C662952EB64893832CB276AEA0354CC41A6DE6B67BA9BB last_reviewed_utc: 2026-06-29T17:25:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; mutation operator report body lives in the target file. - stable_id: gguf_mirust_prune_operator_memory memory_domain: gguf-mirust.report_memory.prune_operator pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/prune-operator-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/prune-operator-memory-2026-06-29/ label: Required For Prune Operator Memory summary: Routes agents to prune commands, keep/floor ppm fields, selected/pruned counts, mask/output checksums, selector receipt carry-forward, browser Operator proof, focused tests, drift tests, and CLI proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed prune operator report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing prune-candidate, validate-prune-candidate, pruning receipt fields, magnitude ranking, selector receipt carry-forward, prune browser Operator proof, or downstream candidate handoff. checksum_hash: sha256:2FB6185B39E63EEC21374FD777B2713C648B9A06E423D42EA37962BF9FBF238C last_reviewed_utc: 2026-06-29T23:10:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; prune operator report body lives in the target file. - stable_id: gguf_mirust_dare_operator_memory memory_domain: gguf-mirust.report_memory.dare_operator pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/dare-operator-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/dare-operator-memory-2026-06-29/ label: Required For DARE Operator Memory summary: Routes agents to DARE commands, signed delta weights, keep/drop ppm, seed masks, raw/rescaled checksums, q8 proof, parameter tests, drift tests, and CLI proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed DARE operator report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing dare-candidate, validate-dare-candidate, DARE masks, DARE receipt fields, or downstream candidate handoff. checksum_hash: sha256:59BC2841527354FAE01412FF708F41236EE5FFA740688D05833BE0C59CD2C179 last_reviewed_utc: 2026-06-29T18:04:57Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; DARE operator report body lives in the target file. - stable_id: gguf_mirust_dare_browser_operator_provenance_memory memory_domain: gguf-mirust.report_memory.dare_browser_operator_provenance pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29/ label: Required For DARE Browser Operator Provenance Memory summary: Routes agents to DARE compact browser Operator rendering, selector receipt byte echo, DARE fallback smoke, operator-kind drift tests, selector tests, and verification. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed DARE browser operator provenance report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing DARE compact selector fixtures, browser Operator rendering, DARE receipt byte echo, or DARE operator receipt drift smoke behavior. checksum_hash: sha256:B4E4621B1F3725A20E2ABDE1B54B2F5A51B65F4F8DEB560B7C3ADA95E2C5D87B last_reviewed_utc: 2026-06-29T18:46:12Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; DARE browser operator provenance report body lives in the target file. - stable_id: gguf_mirust_browser_converted_trained_provenance_memory memory_domain: gguf-mirust.report_memory.browser_provenance pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-converted-trained-provenance-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-converted-trained-provenance-memory-2026-06-29/ label: Required For Browser Converted Trained Provenance Memory summary: Routes agents to converted-trained registry smoke, manifest request proof, browser provenance source/admission/quality assertions, shared registry regression, and verification evidence. pointer_status: current authority: durable-memory-pointer source_authority: local implementation report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing converted-trained registry fixtures, converted-trained browser provenance assertions, or manifest request proof. checksum_hash: sha256:4BE9C47DA03D06C181630E1A6E1B2340CC6F8FA70AEB794450668213307D99DF last_reviewed_utc: 2026-06-29T18:52:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser converted-trained provenance report body lives in the target file. - stable_id: gguf_mirust_browser_converted_trained_file_route_memory memory_domain: gguf-mirust.report_memory.browser_provenance pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-converted-trained-file-route-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-converted-trained-file-route-memory-2026-06-29/ label: Required For Browser Converted Trained File Route Memory summary: Routes agents to browser-converted-trained-bundle staging, generated q8 root proof, real selector/model/manifest fetches, converted-trained provenance rows, and verification evidence. pointer_status: current authority: durable-memory-pointer source_authority: local implementation report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing converted-trained file bundle staging, file-backed converted-trained browser smoke, selector registry routing, or converted source model serving. checksum_hash: sha256:149461852AA3AF42A72CF9ACF2676B278C4564170E6D85194033691A8A5C16C3 last_reviewed_utc: 2026-06-29T19:19:14Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser converted-trained file route report body lives in the target file. - stable_id: gguf_mirust_browser_converted_trained_all_route_memory memory_domain: gguf-mirust.report_memory.browser_converted_trained pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-converted-trained-all-route-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-converted-trained-all-route-memory-2026-06-29/ label: Required For Browser Converted Trained All Route Memory summary: Routes agents to converted-trained all-root staging, q4 default metadata, f32/q8/q4 file-backed selector entries, browser route proof, and verification. pointer_status: current authority: durable-memory-pointer source_authority: local implementation report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing browser-converted-trained-bundle all, converted-trained selector defaults, converted-trained file roots, or converted-trained-registry-file q4/q8/f32 smokes. checksum_hash: sha256:42A6F370271EC6797FC0D0524F1D801241D8AB47307603B801E2DBB4D8F3FBF8 last_reviewed_utc: 2026-06-29T19:37:17Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; converted-trained all-route memory body lives in the target file. - stable_id: gguf_mirust_federated_operator_memory memory_domain: gguf-mirust.report_memory.federated_operator pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/federated-operator-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/federated-operator-memory-2026-06-29/ label: Required For Federated Operator Memory summary: Routes agents to federated/local-update commands, base/local-update parent roles, local_update_weight_ppm, local-update counts, delta checksums, focused tests, drift tests, and CLI proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed federated operator report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing federated-candidate, validate-federated-candidate, local-update receipt fields, or downstream candidate handoff. checksum_hash: sha256:C00FFA080E7971E2E05736080D03478A22429095EDD1B608E9D79960F42A0FF7 last_reviewed_utc: 2026-06-29T13:45:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; federated operator report body lives in the target file. - stable_id: gguf_mirust_federated_selector_receipt_route_memory memory_domain: gguf-mirust.report_memory.federated_selector_receipt_route pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29/ label: Required For Federated Selector Receipt Route Memory summary: Routes agents to federated receipt carry-forward through selector registry, browser Operator rendering, operator-kind drift rejection, byte-count fallback smoke, checksum equality, selector tests, and packer proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed federated selector receipt route report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing federated downstream handoff, browser Operator rendering, selector operator receipt fields, receipt-bound admission validation, or non-mutation operator route fixtures. checksum_hash: sha256:2FAE2A02CCDBEC887074A417B24EA0B2EAF6A518908F1A317B366AD4BF5571AC last_reviewed_utc: 2026-06-29T14:55:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; federated selector receipt route report body lives in the target file. - stable_id: gguf_mirust_candidate_operator_receipt_binding_memory memory_domain: gguf-mirust.report_memory.candidate_operator_receipt_binding pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29/ label: Required For Candidate Operator Receipt Binding Memory summary: Routes agents to optional two-parent candidate manifest receipt binding, bound fields, checksum drift tests, path tests, CLI proof, and validation behavior. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed candidate receipt binding report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing candidate-manifest, validate-candidate, two-parent operator receipt fields, or promotion assumptions about candidate provenance. checksum_hash: sha256:C5EFAA0227F89F843E96FDA76DEED5780A70992CDBAA896C2BA2C4432F25EC40 last_reviewed_utc: 2026-06-29T07:40:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; candidate operator receipt binding report body lives in the target file. - stable_id: gguf_mirust_promotion_operator_receipt_binding_memory memory_domain: gguf-mirust.report_memory.promotion_operator_receipt_binding pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29/ label: Required For Promotion Operator Receipt Binding Memory summary: Routes agents to optional two-parent promotion receipt carry-forward, copied receipt fields, missing receipt and drift tests, path tests, CLI proof, and validation behavior. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed promotion receipt binding report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing promotion-template, validate-promotion, two-parent operator receipt carry-forward, or admission assumptions about promotion provenance. checksum_hash: sha256:4AD7EC8BF5F93D3FC51332B6AF2ABE94C7AD23EC3D509554D86A706734E397C5 last_reviewed_utc: 2026-06-29T08:15:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; promotion operator receipt binding report body lives in the target file. - stable_id: gguf_mirust_admission_operator_receipt_binding_memory memory_domain: gguf-mirust.report_memory.admission_operator_receipt_binding pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/admission-operator-receipt-binding-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/admission-operator-receipt-binding-memory-2026-06-29/ label: Required For Admission Operator Receipt Binding Memory summary: Routes agents to optional two-parent admission receipt carry-forward, copied receipt fields, missing receipt and drift tests, summary validation, CLI proof, and validation behavior. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed admission receipt binding report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing admission-record, validate-admission, two-parent operator receipt carry-forward, selector summary parsing, or selector assumptions about admission provenance. checksum_hash: sha256:59CD900D6868CAEE98D79DEF2241665164C4F00AE933D6F20DD096B9750AEA8D last_reviewed_utc: 2026-06-29T10:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; report detail lives in the target file. - stable_id: gguf_mirust_selector_operator_receipt_binding_memory memory_domain: gguf-mirust.report_memory.selector_operator_receipt_binding pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29/ label: Required For Selector Operator Receipt Binding Memory summary: Routes agents to selector entry operator receipt fields, copied receipt drift tests, multi-parent handoff, mate-selection checksum binding, browser Operator provenance, CLI proof, and validation behavior. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed selector receipt binding report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector-registry, validate-selector-registry, entry.N.operator_receipt fields, browser Operator provenance, or receipt-bound admission-to-registry handoff. checksum_hash: sha256:B420A9343C6C48AAD2C33C8D63A2E0F09D28FBE1734BC9DB31D7DBA3AC03191C last_reviewed_utc: 2026-06-29T18:10:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; report detail lives in the target file. - stable_id: gguf_mirust_model_breeding_reference_ideas memory_domain: gguf-mirust.research_reference.model_breeding pointer_type: llmwiki_node path: wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md target_location: https://aiwikis.org/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26/ label: Required For Model Breeding Research References summary: Routes agents to model-breeding research lanes for compatible merges, sparse lineage, trained low-rank adapter source plus ADP1/ASP1/ALR1 ecology, population search, local updates, browser assembly, and UAIX handoff. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed research routing review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before selecting model-breeding references or designing future candidate operators. checksum_hash: sha256:8786266ADB39C382B607A431E40F2876F9A8ABD860EE025F22FF37B2F6D5E8BE last_reviewed_utc: 2026-06-28T11:25:34Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; research reference body lives in the target file. - stable_id: gguf_mirust_modelbreeder_zero_dependency_reference_ideas memory_domain: gguf-mirust.research_reference.modelbreeder_zero_dependency pointer_type: llmwiki_node path: wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28/ label: Required For ModelBreeder And Zero-Dependency Research References summary: Routes agents to genome, fitness, novelty, speciation, public voice, Wasm SIMD, quantization, tokenizer, sampler, KV-cache, allocator, multimodal, and telemetry guidance. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed research routing review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before adding ModelBreeder-derived schema fields, fitness metadata, novelty routing, zero-dependency runtime plans, or public copy. checksum_hash: sha256:90CF6F38DAE201B934497B50113757DBD439436A65B22B98F1860B0F9767D2BE last_reviewed_utc: 2026-06-28T21:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; research reference body lives in the target file. - stable_id: gguf_mirust_runtime_adapter_apply_memory memory_domain: gguf-mirust.report_memory.runtime_adapter pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/runtime-adapter-apply-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/runtime-adapter-apply-memory-2026-06-27/ label: Required For Runtime Adapter Apply Memory summary: Routes agents to runtime f32/q8/q4 ADP1 adapter apply design, validation boundary, compact re-quantization, WASM export, ABI smoke coverage, and sidecar routes. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed runtime adapter report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing runtime adapter apply, ADP1 compatibility checks, adapter ABI smoke, or adapter-sidecar route planning. checksum_hash: sha256:D9221DB8D0951B0A93277C799FF4DBB32DF5FC3A4ACA12B5CC622A9359FE4B34 last_reviewed_utc: 2026-06-27T14:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; runtime adapter report body lives in the target file. - stable_id: gguf_mirust_sparse_adapter_package_memory memory_domain: gguf-mirust.report_memory.sparse_adapter pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/sparse-adapter-package-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/sparse-adapter-package-memory-2026-06-27/ label: Required For Sparse Adapter Package Memory summary: Routes agents to ASP1 sparse adapter packages, sparse-adapter-delta commands, manifest density and mask fields, runtime f32/q8/q4 sparse apply, browser route handoff, and validation evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed sparse adapter report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing ASP1 parsing, sparse adapter manifests, sparse-adapter-delta, validate-sparse-adapter-delta, or runtime sparse adapter apply. checksum_hash: sha256:618BE504A83212ABEF705E7D6037ED604091B291EAD9C8C7B34ED1DD6C64402B last_reviewed_utc: 2026-06-27T14:37:31Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; sparse adapter report body lives in the target file. - stable_id: gguf_mirust_low_rank_adapter_package_memory memory_domain: gguf-mirust.report_memory.low_rank_adapter pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/low-rank-adapter-package-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/low-rank-adapter-package-memory-2026-06-28/ label: Required For Low-Rank Adapter Package Memory summary: Routes agents to ALR1 low-rank adapter packages, low-rank-adapter-delta commands, factor metadata, runtime f32/q8/q4 apply, and validation evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed low-rank adapter report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing ALR1 parsing, low-rank adapter manifests, low-rank-adapter-delta, validate-low-rank-adapter-delta, or runtime low-rank apply. checksum_hash: sha256:570B199DD88B8BC53FC27C40834EE2C9E6F04D3D930DB81EF5814013F9E40BA3 last_reviewed_utc: 2026-06-28T02:02:06Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; low-rank adapter report body lives in the target file. - stable_id: gguf_mirust_trained_adapter_source_memory memory_domain: gguf-mirust.report_memory.trained_adapter_source pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/trained-adapter-source-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/trained-adapter-source-memory-2026-06-28/ label: Required For Trained Adapter Source Memory summary: Routes agents to trained low-rank adapter source manifests, factor-file validation, adapter-source CLI commands, source checksums, and reviewed factor-to-ALR1 conversion. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed trained adapter source report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing adapter-source-template, validate-adapter-source, trained factor manifests, factor-file validation, or ALR1 source conversion. checksum_hash: sha256:6BFB7B990D93BADA6D32763802C3AA6129072FFED647E7678A1475EB739A74EF last_reviewed_utc: 2026-06-28T18:10:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; trained adapter source report body lives in the target file. - stable_id: gguf_mirust_trained_adapter_source_alr1_memory memory_domain: gguf-mirust.report_memory.trained_adapter_source_alr1 pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/trained-adapter-source-alr1-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/trained-adapter-source-alr1-memory-2026-06-28/ label: Required For Trained Adapter Source ALR1 Memory summary: Routes agents to source-backed ALR1 conversion, validate-converted-adapter-source, reviewed factor packaging, base identity checks, source-backed manifests, and verification evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed trained adapter source ALR1 report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing source factor ALR1 conversion, source-backed ALR1 manifests, or convert-adapter-source validation. checksum_hash: sha256:B4DAC0D2681665AAAD5E9B92839428C9D6064B05D2D43FB6D7DE80B98C1AEDDB last_reviewed_utc: 2026-06-28T10:56:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; trained adapter source ALR1 report body lives in the target file. - stable_id: gguf_mirust_browser_low_rank_adapter_route_memory memory_domain: gguf-mirust.report_memory.browser_low_rank_adapter_route pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-low-rank-adapter-route-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-low-rank-adapter-route-memory-2026-06-28/ label: Required For Browser Low-Rank Adapter Route Memory summary: Routes agents to generated ALR1 adapter-family routes, low-rank manifests, module-plan low-rank stack members, rebuilt WASM proof, and browser smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser low-rank adapter route report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector-routed ALR1 routes, generated adapter-family stack members, ALR1 browser manifest checks, or adapter-sidecar-registry-file assertions. checksum_hash: sha256:E9C584550367F02809DB6C44648AF1903CEFF1FD9C17C61F8E2011C49A90DD68 last_reviewed_utc: 2026-06-28T02:37:25Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser low-rank adapter route report body lives in the target file. - stable_id: gguf_mirust_browser_source_backed_alr1_route_memory memory_domain: gguf-mirust.report_memory.browser_source_backed_alr1_route pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-source-backed-alr1-route-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-source-backed-alr1-route-memory-2026-06-28/ label: Required For Browser Source-Backed ALR1 Route Memory summary: Routes agents to generated source-backed ALR1 stack members, adapter source staging, app manifest kind/dtype checks, adapter-family receipt acceptance, and browser smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser source-backed ALR1 route report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated source-backed ALR1 staging, browser `.alr1` manifest checks, adapter-family source-backed ALR1 members, or combined selector source-backed ALR1 assertions. checksum_hash: sha256:E68D782AA14A7142234F5F83FEA061BD6AF8D7CFB10F39A9E2C46A91FC7D0031 last_reviewed_utc: 2026-06-28T11:25:34Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser source-backed ALR1 route report body lives in the target file. - stable_id: gguf_mirust_browser_source_backed_alr1_contract_memory memory_domain: gguf-mirust.report_memory.browser_source_backed_alr1_contract pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-source-backed-alr1-contract-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-source-backed-alr1-contract-memory-2026-06-28/ label: Required For Browser Source-Backed ALR1 Contract Memory summary: Routes agents to source-backed ALR1 kind/dtype pairing, receipt source echoes, manifest provenance checks, drift smoke, and no-stack-fetch proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser source-backed ALR1 contract report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing source-backed ALR1 manifest fields, adapter-family source echoes, kind/dtype pairing, or source-backed ALR1 drift assertions. checksum_hash: sha256:943C3617E1F1090B1CCB455E22694D56E87076E5EE3CD2EC4C6BD909165C0690 last_reviewed_utc: 2026-06-28T13:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser source-backed ALR1 contract report body lives in the target file. - stable_id: gguf_mirust_browser_sparse_adapter_route_memory memory_domain: gguf-mirust.report_memory.browser_sparse_adapter_route pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-sparse-adapter-route-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-sparse-adapter-route-memory-2026-06-27/ label: Required For Browser Sparse Adapter Route Memory summary: Routes agents to generated f32/q8/q4 self ADP1, family ADP1, sparse ASP1 browser routing, selector/receipt/manifest validation, WASM rebuild, and served smoke proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser sparse adapter report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing browser bundle ASP1 staging, selector adapter routes, browser manifest checks, or adapter-sidecar-registry-file sparse assertions. checksum_hash: sha256:ABA176E597769E7776FD92B812B426E04F986422C94E111896FA6D9235FEDDD3 last_reviewed_utc: 2026-06-27T14:48:27Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser sparse adapter route report body lives in the target file. - stable_id: gguf_mirust_browser_preferred_adapter_route_memory memory_domain: gguf-mirust.report_memory.browser_preferred_adapter_route pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-preferred-adapter-route-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-preferred-adapter-route-memory-2026-06-27/ label: Required For Browser Preferred Adapter Route Memory summary: Routes agents to receipt-bound preferred adapter fields, browser default sparse ASP1 selection, app validation, browser-smoke selection proof, and f32/q8 served smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser preferred adapter report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing adapter-family preferred fields, browser adapter default selection, generated sparse preference, or selectedAdapterBeforeApply smoke checks. checksum_hash: sha256:D37DA3659296328E7B072A721E697FD42FD128DDA60B8C0EF9E7D9D4B5CA1BA3 last_reviewed_utc: 2026-06-27T15:01:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser preferred adapter route report body lives in the target file. - stable_id: gguf_mirust_browser_multi_quant_selector_root_memory memory_domain: gguf-mirust.report_memory.browser_multi_quant_selector_root pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-multi-quant-selector-root-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-multi-quant-selector-root-memory-2026-06-27/ label: Required For Browser Multi Quant Selector Root Memory summary: Routes agents to browser-multi-parent-bundle all, combined f32/q8/q4 selector fan-in, shared-root entry switching, preferred sparse ASP1 apply, and served browser smoke proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser multi-quant selector report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing combined generated selector roots, all-mode bundle staging, or same-served-root f32/q8/q4 browser smokes. checksum_hash: sha256:4509B88D0202052A43EE3B0E4F8BF5D88EEDB4AA4809EDA8F6D667AB003D5F6C last_reviewed_utc: 2026-06-27T15:17:51Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; combined selector-root report body lives in the target file. - stable_id: gguf_mirust_browser_frugal_selector_default_memory memory_domain: gguf-mirust.report_memory.browser_frugal_selector_default pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-frugal-selector-default-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-frugal-selector-default-memory-2026-06-27/ label: Required For Browser Frugal Selector Default Memory summary: Routes agents to browser-frugal selector default fields, q4 initial selection, combined-root first-load behavior, app validation, and served smoke proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser frugal selector report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector default metadata, combined-root default selection, or initialSelectedModel smoke assertions. checksum_hash: sha256:AC0D6CC2539BC26940718E2F90FAA24EB82D8964A8E5D1D4BCAEE95FEEE25702 last_reviewed_utc: 2026-06-27T15:37:28Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser frugal selector default report body lives in the target file. - stable_id: gguf_mirust_browser_selector_budget_memory memory_domain: gguf-mirust.report_memory.browser_selector_budget pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-selector-budget-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-selector-budget-memory-2026-06-27/ label: Required For Browser Selector Budget Memory summary: Routes agents to selector model-byte budget intake, fallback behavior, fetched-length checks, selector-budget smoke proof, and oversized registry route rejection. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser selector budget report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector registry model byte fields, registry fallback behavior, or pre-WASM model byte transfer checks. checksum_hash: sha256:44C0A755E57BF105708065EB05B795D710F003EADE2D0D6B985ED428CEC90DE0 last_reviewed_utc: 2026-06-27T15:54:11Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser selector budget report body lives in the target file. - stable_id: gguf_mirust_browser_selector_budget_contract_memory memory_domain: gguf-mirust.report_memory.browser_selector_budget_contract pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-selector-budget-contract-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-selector-budget-contract-memory-2026-06-27/ label: Required For Browser Selector Budget Contract Memory summary: Routes agents to selector_model_byte_budget registry contracts, Rust budget validation, browser budget intake, generated-root proof, and selector-budget smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser selector budget contract report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector_model_byte_budget, registry model byte validation, browser selector budget intake, generated registry fields, or budget smoke fixtures. checksum_hash: sha256:2EEEC2EE7B665B4CC614E44B3190AE020ECCB73CE834C05E0FB3327EE90A59EA last_reviewed_utc: 2026-06-27T16:08:47Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser selector budget contract report body lives in the target file. - stable_id: gguf_mirust_browser_auto_assembly_memory memory_domain: gguf-mirust.report_memory.browser_auto_assembly pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-auto-assembly-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-auto-assembly-memory-2026-06-27/ label: Required For Browser Auto Assembly Memory summary: Routes agents to selector adapter auto-apply fields, receipt-preferred sparse ASP1 startup apply, browser verification order, generated-root smokes, and manual sidecar preservation. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser auto assembly report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector adapter auto-apply fields, generated adapter-family startup apply, or adapter-sidecar-registry-file pre-generation assertions. checksum_hash: sha256:FB00139461018797F281DDE5A95750F7123820CC52AD50558941536E5728FB75 last_reviewed_utc: 2026-06-27T16:36:46Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser auto assembly report body lives in the target file. - stable_id: gguf_mirust_browser_auto_assembly_budget_memory memory_domain: gguf-mirust.report_memory.browser_auto_assembly_budget pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-auto-assembly-budget-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-auto-assembly-budget-memory-2026-06-27/ label: Required For Browser Auto Assembly Budget Memory summary: Routes agents to adapter auto-assembly byte budgets, manifest artifact byte checks, fetched-length checks, generated registry fields, browser transfer boundary, and smoke proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser auto assembly budget report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing adapter_auto_apply_byte_budget, adapter artifact byte counts, auto-assembly transfer checks, or generated adapter-family registry fields. checksum_hash: sha256:16D0202CDB003028E3712C0E5832EED72D8617D9E20C24E21CBDA017B827ABD5 last_reviewed_utc: 2026-06-27T17:00:03Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser auto assembly budget report body lives in the target file. - stable_id: gguf_mirust_browser_text_sidecar_budget_memory memory_domain: gguf-mirust.report_memory.browser_text_sidecar_budget pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-text-sidecar-budget-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-text-sidecar-budget-memory-2026-06-27/ label: Required For Browser Text Sidecar Budget Memory summary: Routes agents to browser text-sidecar byte envelopes for selector registries, manifests, receipts, assembly evidence, oversized adapter manifest smoke proof, and pre-parse fetch limits. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser text sidecar budget report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector.registry intake, manifest or receipt parsing, assembly evidence fetches, adapter-family receipt verification, or text sidecar budget smokes. checksum_hash: sha256:EC2C8F3A6A0A5FA58B6508905ECEF5F1229401FBB6D1928EEDAEBCF90B2101C8 last_reviewed_utc: 2026-06-27T17:18:16Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser text sidecar budget report body lives in the target file. - stable_id: gguf_mirust_browser_text_sidecar_contract_memory memory_domain: gguf-mirust.report_memory.browser_text_sidecar_contract pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-text-sidecar-contract-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-text-sidecar-contract-memory-2026-06-27/ label: Required For Browser Text Sidecar Contract Memory summary: Routes agents to selector registry text budget contract fields, Rust validation, browser exact-match intake, generated bundle proof, and sidecar-budget-contract smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser text sidecar contract report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector registry text budget headers, browser exact budget intake, generated registry fields, or sidecar-budget-contract smoke fixtures. checksum_hash: sha256:7A3E2D5D6B223AD5312D1CC17D7129713C45CCC8ED6A16C69814DB8E553A5018 last_reviewed_utc: 2026-06-27T17:35:40Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser text sidecar contract report body lives in the target file. - stable_id: gguf_mirust_browser_runtime_manifest_memory memory_domain: gguf-mirust.report_memory.browser_runtime_manifest pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-runtime-manifest-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-runtime-manifest-memory-2026-06-27/ label: Required For Browser Runtime Manifest Memory summary: Routes agents to browser runtime WASM manifest verification, generated bundle runtime staging, build-helper refresh, runtime-manifest-drift smoke, and pre-instantiation checksum proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser runtime manifest report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing runtime WASM loading, generated browser bundle runtime staging, runtime manifest checks, or runtime-manifest-drift smoke fixtures. checksum_hash: sha256:228588130FDC5FB879C269F913DCF4B1C43B1A37ADC3E3443A3E0D2F0F633A56 last_reviewed_utc: 2026-06-27T18:07:37Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser runtime manifest report body lives in the target file. - stable_id: gguf_mirust_browser_adapter_stack_memory memory_domain: gguf-mirust.report_memory.browser_adapter_stack pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-adapter-stack-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-adapter-stack-memory-2026-06-27/ label: Required For Browser Adapter Stack Memory summary: Routes agents to generated browser adapter-stack self assembly, selector stack fields, adapter-family receipt members, JS stack verification, and q4 generated-root stack smoke proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser adapter stack report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated adapter-stack auto-apply, selector stack fields, adapter-family receipt stack members, or adapter-sidecar-registry-file stack assertions. checksum_hash: sha256:98D332795CB298FEA383E772BF7DD87CFBE12DAFF80062D158EC00344503A8FE last_reviewed_utc: 2026-06-27T18:30:04Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser adapter stack report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_memory memory_domain: gguf-mirust.report_memory.browser_module_plan pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-memory-2026-06-27/ label: Required For Browser Module Plan Memory summary: Routes agents to generated browser module-plan receipts, selector module-plan fields, pre-model-fetch JS plan verification, bundle staging, and q4 generated-root module-plan smoke proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated selector module-plan fields, .module-plan.receipt staging, browser plan verification, or generated-root adapter-sidecar-registry-file smoke assertions. checksum_hash: sha256:3D7E2CA642E29DCBFC51F6C2FD95626BDABD298CD627C5885E032EEA03657CC9 last_reviewed_utc: 2026-06-27T19:03:56Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_resource_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_resource pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-resource-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-resource-memory-2026-06-27/ label: Required For Browser Module Plan Resource Memory summary: Routes agents to generated module-plan resource class, admitted model byte budget, adapter-family byte budget, Rust drift rejection, JS pre-model-fetch verification, and q4 smoke proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan resource report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing module-plan resource fields, .module-plan.receipt byte envelopes, selector validation, or browser pre-model-fetch resource verification. checksum_hash: sha256:7695A6C9455075D2E984F6A7AD9B24427B07880E269EDD486479897647167D2E last_reviewed_utc: 2026-06-27T19:26:45Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan resource report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_resource_drift_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_resource_drift pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-resource-drift-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-resource-drift-memory-2026-06-27/ label: Required For Browser Module Plan Resource Drift Memory summary: Routes agents to checksum-consistent module-plan receipt budget drift, no-generated-slm-fetch proof, browser-smoke mode, and q4 generated-root evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan resource drift report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing module-plan resource drift smoke, receipt checksum mutation, or pre-model-fetch budget mismatch handling. checksum_hash: sha256:B84383557F1A76E1DD1D15004D6D7BBF7C3C2AE2136DCCE25C5C8A2F13B15571 last_reviewed_utc: 2026-06-27T20:05:12Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan resource drift report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_graph_drift_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_graph_drift pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-graph-drift-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-graph-drift-memory-2026-06-27/ label: Required For Browser Module Plan Graph Drift Memory summary: Routes agents to checksum-consistent module-plan receipt graph drift, no-generated-slm-fetch proof, browser-smoke mode, and q4 generated-root evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan graph drift report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing module-plan graph drift smoke, receipt route mutation, or pre-model-fetch graph mismatch handling. checksum_hash: sha256:9672865125017B6B68D563A126831042B7C3D63E856FDA7474AA1352ABEC975C last_reviewed_utc: 2026-06-27T20:20:05Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan graph drift report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_stack_drift_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_stack_drift pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-stack-drift-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-stack-drift-memory-2026-06-27/ label: Required For Browser Module Plan Stack Drift Memory summary: Routes agents to checksum-consistent module-plan receipt stack drift, no-generated-model-or-stack-artifact-fetch proof, browser-smoke mode, and q4 generated-root evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan stack drift report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing module-plan stack drift smoke, receipt stack route mutation, or pre-model-fetch stack mismatch handling. checksum_hash: sha256:32A30EC59AAD3BE790A8B12570825E4076C29F79E44DA26D73DEA4D2D611B8C8 last_reviewed_utc: 2026-06-27T20:20:05Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan stack drift report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_role_drift_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_role_drift pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-role-drift-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-role-drift-memory-2026-06-27/ label: Required For Browser Module Plan Role Drift Memory summary: Routes agents to checksum-consistent module-plan receipt role drift, no-generated-model-or-stack-artifact-fetch proof, browser-smoke mode, and q4 generated-root evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan role drift report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing module-plan role drift smoke, receipt role mutation, or pre-model-fetch role mismatch handling. checksum_hash: sha256:8154A6BEAE9CD081E702FD3FE99A5E15E2F3A636C70CEC3E1CD28C0D9A5B63BE last_reviewed_utc: 2026-06-27T21:46:45Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan role drift report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_display_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_display pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-display-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-display-memory-2026-06-27/ label: Required For Browser Module Plan Display Memory summary: Routes agents to browser Module Plan panel fields, verified receipt display, fallback none state, generated q4 loaded-state proof, and stack route display assertions. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan display report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing Module Plan panel rendering, verified receipt display fields, or adapter-sidecar-registry-file panel assertions. checksum_hash: sha256:A108B5BF2942B9B5BA3906FE2877FA97729E0AD8BD031D20D301156221123D24 last_reviewed_utc: 2026-06-27T20:48:35Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan display report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_budget_display_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_budget_display pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-budget-display-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-budget-display-memory-2026-06-27/ label: Required For Browser Module Plan Budget Display Memory summary: Routes agents to Module Plan visible model and adapter budget rows, fallback unavailable proof, generated q4 budget proof, and receipt-derived smoke assertions. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan budget display report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing Module Plan budget row rendering, verified receipt budget fields, or budget display smoke assertions. checksum_hash: sha256:3F49857269DEE429CA3C5E3DCB54D3CA3BE14363B4E823A644AD8B7F0636DC33 last_reviewed_utc: 2026-06-27T21:02:20Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan budget display report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_role_display_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_role_display pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-role-display-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-role-display-memory-2026-06-27/ label: Required For Browser Module Plan Role Display Memory summary: Routes agents to Module Plan role receipt fields, fallback unavailable proof, generated q4 role summary proof, and receipt-derived smoke assertions. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan role display report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing Module Plan role rendering, receipt role fields, or role display smoke assertions. checksum_hash: sha256:D2E7F9732CF6B19CBBAA1010281CB18C4AD52394B04F3E20ACFFE9FD435C4B32 last_reviewed_utc: 2026-06-27T21:19:44Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan role display report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_slots_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_slots pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-slots-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-slots-memory-2026-06-27/ label: Required For Browser Module Plan Assembly Slots Memory summary: Routes agents to Module Plan assembly-slot receipt fields, fallback unavailable proof, generated q4 slot summary proof, slot drift smoke, and receipt-derived assertions. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan slots report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing Module Plan slot rendering, receipt assembly_slot fields, or module-plan-slot-drift assertions. checksum_hash: sha256:F96F60042441F838CA058F85AB628DBA4A48FF2AC211293A86A51C65BAD62EBB last_reviewed_utc: 2026-06-27T22:07:39Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan slots report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_dependencies_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_dependencies pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-dependencies-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-dependencies-memory-2026-06-27/ label: Required For Browser Module Plan Dependencies Memory summary: Routes agents to Module Plan depends_on receipt fields, fallback unavailable proof, generated q4 dependency summary proof, dependency drift smoke, and receipt-derived assertions. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan dependencies report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing Module Plan dependency rendering, receipt depends_on fields, or module-plan-dependency-drift assertions. checksum_hash: sha256:3110A860EDE9CFA733FA59E1FBC280BE4B3856135FDC7A8B5E3031041E29CDC5 last_reviewed_utc: 2026-06-27T22:42:27Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan dependencies report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_phases_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_phases pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-phases-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-phases-memory-2026-06-27/ label: Required For Browser Module Plan Phases Memory summary: Routes agents to Module Plan phase receipt fields, fallback unavailable proof, generated q4 phase summary proof, phase drift smoke, and receipt-derived assertions. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan phases report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing Module Plan phase rendering, receipt phase fields, or module-plan-phase-drift assertions. checksum_hash: sha256:7110F3B1C8550EB338A471E51D3D676DE464FFA04A089F692D53C0F8A8FBCB9B last_reviewed_utc: 2026-06-28T01:07:16Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan phases report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_byte_counts_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_byte_counts pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-byte-counts-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-byte-counts-memory-2026-06-27/ label: Required For Browser Module Plan Byte Counts Memory summary: Routes agents to Module Plan byte_count receipt fields, fallback unavailable proof, generated q4 byte summary proof, byte drift smoke, and fetched-byte assertions. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan byte-count report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing Module Plan byte rendering, receipt byte_count fields, fetched-byte checks, or module-plan-byte-drift assertions. checksum_hash: sha256:92F73FF2BE95A36B54C22ACE0A9B5087D76846C83E51B54084340AF03159CB1C last_reviewed_utc: 2026-06-28T01:07:16Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan byte-count report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_checksums_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_checksums pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-checksums-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-checksums-memory-2026-06-27/ label: Required For Browser Module Plan Checksums Memory summary: Routes agents to Module Plan checksum receipt fields, fallback unavailable proof, q4 checksum summary proof, checksum drift smoke, and stack checksum assertions. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan checksums report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing Module Plan checksum rendering, receipt checksum fields, stack artifact checksum matching, or module-plan-checksum-drift assertions. checksum_hash: sha256:16CB53908E60814591ACCA0231C3BC12B01CE73F471115CC27BBFD739BD52097 last_reviewed_utc: 2026-06-28T01:07:16Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan checksum report body lives in the target file. - stable_id: gguf_mirust_browser_combined_selector_assembly_memory memory_domain: gguf-mirust.report_memory.browser_combined_selector_assembly pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28/ label: Required For Browser Combined Selector Assembly Memory summary: Routes agents to same-page q4/q8/f32 selector switching, q4 default proof, module-plan-before-model ordering, auto-assembly stacks, and generated all-root smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser combined selector assembly report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing combined selector roots, generated all-root switching, q4 defaults, module-plan ordering, or auto-assembly claims. checksum_hash: sha256:8052D26545B1DE28756D956C4DE5EB4EAF60C4ADFDEF355E26AB4033AA8DBC6F last_reviewed_utc: 2026-06-28T01:07:16Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser combined selector assembly report body lives in the target file. - stable_id: gguf_mirust_browser_combined_selector_cycle_memory memory_domain: gguf-mirust.report_memory.browser_combined_selector_cycle pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28/ label: Required For Browser Combined Selector Cycle Memory summary: Routes agents to repeated q4/q8/f32 all-root switching, release-before-reassembly proof, per-pass stack deltas, reset diagnostics, generation proof, and path-flexible summary assertions. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser combined selector cycle report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing combined-selector-cycle, repeated generated all-root switching, release-before-reassembly behavior, per-pass stack validation/apply assertions, or path-flexible Module Plan summary checks. checksum_hash: sha256:7D42391A51C39CF31F3203E349DA5771E75CD84C8DE6EB26B5E2952728E801A3 last_reviewed_utc: 2026-06-28T09:10:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser combined selector cycle report body lives in the target file. - stable_id: gguf_mirust_browser_combined_selector_route_soak_memory memory_domain: gguf-mirust.report_memory.browser_combined_selector_route_soak pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28/ label: Required For Browser Combined Selector Route Soak Memory summary: Routes agents to three-cycle q4/q8/f32 selector reuse, no-store local fetches, per-pass self-assembly route counts, and route-soak smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser combined selector route-soak report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing combined-selector-route-soak, local fetch cache behavior, repeated generated route-count assertions, or longer selector-route exercises. checksum_hash: sha256:90B263C8DE3153653351B78B62F5D60A11A9FFC608EFEA9815AD9C57B69500E4 last_reviewed_utc: 2026-06-28T09:40:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser combined selector route-soak report body lives in the target file. - stable_id: gguf_mirust_browser_combined_selector_extended_route_soak_memory memory_domain: gguf-mirust.report_memory.browser_combined_selector_extended_route_soak pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28/ label: Required For Browser Combined Selector Extended Route Soak Memory summary: Routes agents to five-cycle q4/q8/f32 generated selector reuse, fifteen browser assemblies, path-flexible total-budget assertions, and extended route-count smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser combined selector extended route-soak report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing combined-selector-route-extended-soak, five-cycle generated all-root route pressure, path-flexible total-budget assertions, or extended route-count checks. checksum_hash: sha256:DA24658D962A61AAF9EC3F1577818981FAAD3EEC8BC5E71970D5C37C52D5AE03 last_reviewed_utc: 2026-06-28T19:35:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser combined selector extended route-soak report body lives in the target file. - stable_id: gguf_mirust_browser_combined_selector_stress_route_soak_memory memory_domain: gguf-mirust.report_memory.browser_combined_selector_stress_route_soak pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-combined-selector-stress-route-soak-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-combined-selector-stress-route-soak-memory-2026-06-28/ label: Required For Browser Combined Selector Stress Route Soak Memory summary: Routes agents to eight-cycle q4/q8/f32 all-root selector pressure, twenty-four assemblies, bounded cycles, per-pass route counts, and stress-smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser combined selector stress route-soak report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing combined-selector-route-stress-soak, eight-cycle generated all-root route pressure, bounded cycle handling, or deeper route-count checks. checksum_hash: sha256:263D098DE974A43F1F507CBFADB6BC0877ED5CCDF12274BED55C5D0B6CA846AC last_reviewed_utc: 2026-06-28T21:05:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser combined selector stress route-soak report body lives in the target file. - stable_id: gguf_mirust_browser_selector_genome_fitness_memory memory_domain: gguf-mirust.report_memory.browser_selector_genome_fitness pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-selector-genome-fitness-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-selector-genome-fitness-memory-2026-06-28/ label: Required For Browser Selector Genome Fitness Memory summary: Routes agents to generated selector genome ids, lineage checksums, eval-bound fitness vectors, Model Provenance Genome/Fitness rows, and combined-selector proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser selector genome fitness report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector genome fields, fitness-vector fields, registry validation, Model Provenance Genome/Fitness rows, or combined-selector provenance assertions. checksum_hash: sha256:89755A73E94A90AC86CCFABD3DA39721E1212D71B0A14863ECF7CCC9B674EFA5 last_reviewed_utc: 2026-06-28T22:40:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser selector genome fitness report body lives in the target file. - stable_id: gguf_mirust_browser_selector_species_fit_memory memory_domain: gguf-mirust.report_memory.browser_selector_species_fit pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28/ label: Required For Browser Selector Species Fit Memory summary: Routes agents to generated selector species ids, browser-fit checksums, Model Provenance Species rows, and combined-selector proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser selector species fit report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector species fields, browser-fit checksum fields, registry validation, Model Provenance Species rows, or combined-selector provenance assertions. checksum_hash: sha256:79D69E393291415095F7C8E1FA73D8060C109E0F54FE4E9E4BAB7BBE44404F7F last_reviewed_utc: 2026-06-28T22:55:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser selector species fit report body lives in the target file. - stable_id: gguf_mirust_browser_selector_novelty_memory memory_domain: gguf-mirust.report_memory.browser_selector_novelty pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28/ label: Required For Browser Selector Novelty Memory summary: Routes agents to generated selector novelty ids, behavior-sketch checksums, Model Provenance Novelty rows, and combined-selector proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser selector novelty report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector novelty fields, behavior-sketch checksum fields, registry validation, Model Provenance Novelty rows, or combined-selector provenance assertions. checksum_hash: sha256:704BA1F22C6482A6E5BBB1B9A3DEFE0D67D2204FB23FBD57BA2E355D51D1FB19 last_reviewed_utc: 2026-06-28T23:35:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser selector novelty report body lives in the target file. - stable_id: gguf_mirust_browser_selector_population_memory memory_domain: gguf-mirust.report_memory.browser_selector_population pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-selector-population-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-selector-population-memory-2026-06-28/ label: Required For Browser Selector Population Memory summary: Routes agents to generated selector population ids, population-review checksums, Model Provenance Population rows, and combined-selector proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser selector population report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector population fields, population-review checksum fields, registry validation, Model Provenance Population rows, or combined-selector provenance assertions. checksum_hash: sha256:834635F5E977FD48FAA481ACA814D37088D0238330CC28E823612C0F4541C377 last_reviewed_utc: 2026-06-28T23:58:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser selector population report body lives in the target file. - stable_id: gguf_mirust_browser_selector_mate_selection_memory memory_domain: gguf-mirust.report_memory.browser_selector_mate_selection pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28/ label: Required For Browser Selector Mate Selection Memory summary: Routes agents to selector mate-selection ids, parent-pool-bound checksums, parent counts, Model Provenance Mate Selection rows, and combined-selector proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser selector mate-selection report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector mate-selection fields, parent-pool checksum routing, Model Provenance Mate Selection rows, or combined-selector provenance assertions. checksum_hash: sha256:AEA83101E25E26E81495C42CA8E88A8067D5189315D9FDA12FBA8C2E5F6716C3 last_reviewed_utc: 2026-06-28T23:59:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser selector mate-selection report body lives in the target file. - stable_id: gguf_mirust_browser_selector_phenotype_evidence_memory memory_domain: gguf-mirust.report_memory.browser_selector_phenotype_evidence pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28/ label: Required For Browser Selector Phenotype Evidence Memory summary: Routes agents to selector phenotype-evidence ids, runtime-eval checksums, provenance manifest checksums, Model Provenance Phenotype rows, and combined-selector proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser selector phenotype-evidence report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector phenotype evidence fields, provenance manifest checksum routing, Model Provenance Phenotype rows, or combined-selector provenance assertions. checksum_hash: sha256:5DF064A8F2F5492F02A2DAFCD7D0586A71D9E0EB847477C33B9FAAC0655AB581 last_reviewed_utc: 2026-06-28T17:21:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser selector phenotype-evidence report body lives in the target file. - stable_id: gguf_mirust_browser_selector_heritable_artifact_memory memory_domain: gguf-mirust.report_memory.browser_selector_heritable_artifact pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28/ label: Required For Browser Selector Heritable Artifact Memory summary: Routes agents to selector heritable artifact ids, served-artifact checksums, Model Provenance Artifact rows, and combined-selector proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser selector heritable-artifact report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector heritable artifact fields, served artifact identity routing, Model Provenance Artifact rows, or combined-selector provenance assertions. checksum_hash: sha256:479F96F62FA73B2B39D588BB2C5A2E7CB30EE7A8A9698270F9072041B8F47E78 last_reviewed_utc: 2026-06-28T17:44:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser selector heritable-artifact report body lives in the target file. - stable_id: gguf_mirust_browser_combined_selector_reload_soak_memory memory_domain: gguf-mirust.report_memory.browser_combined_selector_reload_soak pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28/ label: Required For Browser Combined Selector Reload Soak Memory summary: Routes agents to fresh page-lifetime generated all-root assembly, q4_0 registry default boot, repeated route counts, and combined-selector-reload-soak evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser combined selector reload-soak report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing combined-selector-reload-soak, generated selector default boot, fresh page-lifetime assembly, reload route-count assertions, or generated all-root startup behavior. checksum_hash: sha256:A7D1A7EFDD0A345BC9DBA3098E6CF78C2344908B75C7644DE343E30795B99BF7 last_reviewed_utc: 2026-06-28T14:40:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser combined selector reload-soak report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_profile_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_profile pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28/ label: Required For Browser Module Plan Profile Memory summary: Routes agents to browser-constrained-v1 module-plan profiles, selector-to-receipt profile matching, generated receipt fields, pre-model-fetch validation, profile-drift smoke evidence, and profile-backed combined assembly. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan profile report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing module-plan profile fields, generated selector/receipt identity checks, browser-constrained-v1 validation, or module-plan-profile-drift smoke assertions. checksum_hash: sha256:59C30FC8709C4A92D9F9B3EA374C53B18126EABD5A8A08D9B8AEDA70D00C071E last_reviewed_utc: 2026-06-28T10:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan profile report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_execution_profile_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_execution_profile pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28/ label: Required For Browser Module Plan Execution Profile Memory summary: Routes agents to single-threaded-wasm-local-v1 module-plan execution profiles, selector-to-receipt execution matching, verified Execution display, pre-model-fetch validation, execution-profile drift smoke evidence, and execution-backed combined assembly. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan execution profile report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing module-plan execution profile fields, generated selector/receipt execution metadata, Execution display, or module-plan-execution-profile-drift smoke assertions. checksum_hash: sha256:A3F8F48E00AE929E231D0007434C72949AE1BC0FA228F27628FD8392CF5726C6 last_reviewed_utc: 2026-06-28T11:45:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan execution profile report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_fetch_policy_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_fetch_policy pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28/ label: Required For Browser Module Plan Fetch Policy Memory summary: Routes agents to local-no-store-v1 module-plan fetch policy, selector-to-receipt fetch matching, verified Fetch display, pre-model-fetch validation, fetch-policy drift smoke evidence, and combined assembly. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan fetch policy report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing module-plan fetch fields, generated selector/receipt fetch metadata, Fetch display, request-log scoping, or module-plan-fetch-policy-drift smoke assertions. checksum_hash: sha256:D372F255D5365898585F8908903B67996A7D962529995926B7D27783F754C25D last_reviewed_utc: 2026-06-28T12:25:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan fetch policy report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_origin_policy_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_origin_policy pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28/ label: Required For Browser Module Plan Origin Policy Memory summary: Routes agents to same-origin-loopback-local-v1 module-plan origin policy, selector-to-receipt origin matching, verified Origin display, pre-model-fetch validation, origin-policy drift smoke evidence, and combined assembly. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan origin policy report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing module-plan origin fields, generated selector/receipt origin metadata, Origin display, same-origin route assertions, or module-plan-origin-policy-drift smoke assertions. checksum_hash: sha256:34F5A9125DEF78DAB20F0E22413C4D1B8577AB02324FF9A455B9FE04B10C1215 last_reviewed_utc: 2026-06-28T13:05:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan origin policy report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_runtime_scratch_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_runtime_scratch pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28/ label: Required For Browser Module Plan Runtime Scratch Memory summary: Routes agents to module-plan runtime scratch envelopes, selector-to-receipt scratch budget matching, verified Scratch Budget display, pre-model-fetch validation, runtime-scratch drift smoke evidence, and scratch-backed combined assembly. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan runtime scratch report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing module-plan runtime scratch fields, generated selector/receipt resource envelopes, Scratch Budget display, or module-plan-runtime-scratch-drift smoke assertions. checksum_hash: sha256:19E68CF4969FF3F34E5C54AE0C698E02035C1D4C0F42E66A73EED49068AA27F8 last_reviewed_utc: 2026-06-28T11:05:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan runtime scratch report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_output_limit_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_output_limit pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-output-limit-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-output-limit-memory-2026-06-28/ label: Required For Browser Module Plan Output Limit Memory summary: Routes agents to output byte limit fields, Output Limit display, total-budget inclusion, and module-plan-output-limit-drift evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan output-limit report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated output caps, selector/receipt output fields, Module Plan Output Limit display, total budget math, or output-limit drift assertions. checksum_hash: sha256:1FCF532A72DDE97F67D7324452E35B8F2A077B4D89E202D7887F241AE2E667C7 last_reviewed_utc: 2026-06-28T22:11:44Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan output-limit report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_total_budget_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_total_budget pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-total-budget-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-total-budget-memory-2026-06-28/ label: Required For Browser Module Plan Total Budget Memory summary: Routes agents to module-plan total self-assembly budgets, Total Budget display, selector-to-receipt matching, pre-model-fetch validation, and total-budget drift smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan total budget report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing module-plan total byte fields, generated selector/receipt total envelopes, Total Budget display, or module-plan-total-budget-drift smoke assertions. checksum_hash: sha256:3DAB4D7483A72A60017D94A76FAC99282DDA337535752BA0AC74BB09172CBDF8 last_reviewed_utc: 2026-06-28T15:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan total budget report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_total_limit_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_total_limit pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28/ label: Required For Browser Module Plan Total Limit Memory summary: Routes agents to explicit module-plan total cap fields, Total Limit display, selector-to-receipt cap matching, pre-model-fetch validation, and total-limit drift smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan total limit report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing module-plan total byte budget limit fields, generated selector/receipt cap envelopes, Total Limit display, or module-plan-total-limit-drift smoke assertions. checksum_hash: sha256:BAE2630090806ECF120218CE59141FABA7D764D3AD53F58C8BF951070A9CCF41 last_reviewed_utc: 2026-06-28T18:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan total limit report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_wasm_memory_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_wasm_memory pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-wasm-memory-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-wasm-memory-memory-2026-06-28/ label: Required For Browser Module Plan WASM Memory Memory summary: Routes agents to pre-init WASM page counting, selector-to-receipt memory-page matching, verified WASM Pages display, module-plan-wasm-memory-drift evidence, and storage-recovery note. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan WASM memory report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing WASM instantiation order, exported memory handling, selector module-plan WASM page fields, Module Plan WASM Pages display, or module-plan-wasm-memory-drift assertions. checksum_hash: sha256:321EAE98E9A6FE2D7855AF06E3B49EB456193BF1757EE7310235574C559AABA1 last_reviewed_utc: 2026-06-28T18:40:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan WASM memory report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_wasm_export_set_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_wasm_export_set pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28/ label: Required For Browser Module Plan WASM Export Set Memory summary: Routes agents to tinyrustlm-generate-v1 module-plan ABI fields, instantiated WASM export checks, WASM ABI display, drift smoke, and generated-root evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan WASM export-set report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing WASM exports, selector/receipt ABI fields, Module Plan WASM ABI display, or module-plan-wasm-export-set-drift assertions. checksum_hash: sha256:A9A5E5FC1C1CBAE5AE6D8EFEC71D556DDB0BD70F1E1A059B2DBD96C06E85D98E last_reviewed_utc: 2026-06-28T23:59:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan WASM export-set report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_wasm_heap_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_wasm_heap pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-wasm-heap-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-wasm-heap-memory-2026-06-28/ label: Required For Browser Module Plan WASM Heap Memory summary: Routes agents to module-plan WASM heap-floor fields, browser alloc/dealloc probe, Heap Floor display, drift smoke, and combined/source verification. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan WASM heap report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing WASM allocation probes, selector/receipt heap-floor fields, Module Plan Heap Floor display, or module-plan-wasm-heap-drift assertions. checksum_hash: sha256:D674ACA30BE14EDDD171E1E98CB6E045F6082D44C4398C2D80AB620A935BCDB3 last_reviewed_utc: 2026-06-28T23:59:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan WASM heap report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_wasm_transfer_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_wasm_transfer pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-wasm-transfer-memory-2026-06-28/ label: Required For Browser Module Plan WASM Transfer Memory summary: Routes agents to copy-then-release transfer-strategy fields, Module Plan Transfer display, source fallback, drift smoke, and generated/source verification. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan WASM transfer report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing browser WASM byte-copy helpers, selector/receipt transfer-strategy fields, Module Plan Transfer display, or module-plan-wasm-transfer-drift assertions. checksum_hash: sha256:071E1C816B8F5A5715EF183D40832E81ADBFF036038A62928A8F268E28DBA92D last_reviewed_utc: 2026-06-29T00:25:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan WASM transfer report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_model_release_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_model_release pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-model-release-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-model-release-memory-2026-06-29/ label: Required For Browser Module Plan Model Release Memory summary: Routes agents to free-before-reassembly model-release fields, Module Plan Release display, drift smoke, source fallback, and combined-selector-cycle release proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan model-release report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated model lifetime sequencing, selector/receipt release fields, Module Plan Release display, or module-plan-model-release-drift assertions. checksum_hash: sha256:0B5FE7AF325DD0C42DB9142C218A7385E0FF42C51ECCD37D4A3DCD3E18F5D13E last_reviewed_utc: 2026-06-29T00:48:37Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan model-release report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_runtime_reset_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_runtime_reset pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-runtime-reset-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-runtime-reset-memory-2026-06-29/ label: Required For Browser Module Plan Runtime Reset Memory summary: Routes agents to reset-context-before-assembly fields, Module Plan Reset display, drift smoke, source fallback, and combined-selector-cycle reset proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan runtime-reset report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated context reset sequencing, selector/receipt reset fields, Module Plan Reset display, or module-plan-runtime-reset-drift assertions. checksum_hash: sha256:99318A970ABAA9324A5C141CF78697ECC603E2B60B5B80EEE07D5F820F537301 last_reviewed_utc: 2026-06-29T01:10:34Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan runtime-reset report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_adapter_validation_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_adapter_validation pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29/ label: Required For Browser Module Plan Adapter Validation Memory summary: Routes agents to rust-validate-before-apply fields, Module Plan Validate display, drift smoke, source fallback, and combined-selector-assembly validation proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan adapter-validation report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated adapter validation sequencing, selector/receipt validation fields, Module Plan Validate display, or module-plan-adapter-validation-drift assertions. checksum_hash: sha256:4559CFCA94879CE971CDD15824619068364A6BDF577FD85AED7F79D46FEC7B7D last_reviewed_utc: 2026-06-29T01:39:45Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan adapter-validation report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_adapter_validation_count_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_adapter_validation_count pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-count-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-adapter-validation-count-memory-2026-06-29/ label: Required For Browser Module Plan Adapter Validation Count Memory summary: Routes agents to validation-count fields, Module Plan Validate Count display, selector/receipt/adapter-family agreement, runtime validation-count checks, and drift smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan adapter validation-count report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated adapter validation cardinality, selector/receipt validation-count fields, Module Plan Validate Count display, or module-plan-adapter-validation-count-drift assertions. checksum_hash: sha256:8B28A780E19D412F2D1AF5E33747E8F2D068B262FD8A8FCBCACA0FE28751065F last_reviewed_utc: 2026-06-29T02:53:13Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan adapter validation-count report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_adapter_apply_count_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_adapter_apply_count pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29/ label: Required For Browser Module Plan Adapter Apply Count Memory summary: Routes agents to module-plan adapter apply count fields, Module Plan Apply Count display, adapter-family stack agreement, runtime adapter_apply_count diagnostics checks, drift smoke, and generated route gating. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan adapter apply-count report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated adapter stack cardinality, selector/receipt apply-count fields, Module Plan Apply Count display, runtime adapter_apply_count diagnostics checks, or module-plan-adapter-apply-count-drift assertions. checksum_hash: sha256:2CAA25EF243E7441A46E3FF42FB40FF78C42AAA99DEF30713845D7155A93A016 last_reviewed_utc: 2026-06-29T02:30:52Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan adapter apply-count report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_planned_fetch_count_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_planned_fetch_count pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-planned-fetch-count-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-planned-fetch-count-memory-2026-06-29/ label: Required For Browser Module Plan Planned Fetch Count Memory summary: Routes agents to planned self-assembly fetch count fields, Plan Fetches display, selector/receipt/generated-route agreement, drift smoke, budgets, and verification evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan planned-fetch-count report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated route cardinality, selector/receipt planned-fetch fields, Module Plan Plan Fetches display, or module-plan-planned-fetch-count-drift assertions. checksum_hash: sha256:1EC42CAD8E48113418B19C5B3DE8C2713BA989C4A886B9D7CC54C1FFEE1BFC09 last_reviewed_utc: 2026-06-29T03:34:05Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan planned-fetch-count report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_actual_fetch_count_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_actual_fetch_count pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-actual-fetch-count-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-actual-fetch-count-memory-2026-06-29/ label: Required For Browser Module Plan Actual Fetch Count Memory summary: Routes agents to browser-owned generated self-assembly fetch accounting, Actual Fetches display, planned-versus-actual Ready gating, source fallback, route breakdown, and verification evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan actual fetch-count report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing counted generated fetch wrappers, Module Plan Actual Fetches display, route cardinality, or planned-versus-actual Ready gating. checksum_hash: sha256:53AA6AFE088CBC57488D767A56B8E3AD1FE120D26C4294B03A731516CF34AF69 last_reviewed_utc: 2026-06-29T10:55:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan actual fetch-count report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_observed_route_set_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_observed_route_set pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-observed-route-set-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-observed-route-set-memory-2026-06-29/ label: Required For Browser Module Plan Observed Route Set Memory summary: Routes agents to browser-observed generated route-set checksums, Actual Route Set display, observed-versus-declared Ready gating, source fallback, route-kind labels, and verification evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan observed route-set report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing counted fetch route kinds, observed route-set recording, Module Plan Actual Route Set display, route ordering, or observed-versus-declared Ready gating. checksum_hash: sha256:6B2E9249BE13582A0DF8AD1C59AAF83DA73B77913A5D1429D1BCE59B1428AB11 last_reviewed_utc: 2026-06-29T11:10:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan observed route-set report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_actual_module_bytes_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_actual_module_bytes pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-actual-module-bytes-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-actual-module-bytes-memory-2026-06-29/ label: Required For Browser Module Plan Actual Module Bytes Memory summary: Routes agents to browser-observed generated module bytes, Actual Module Bytes display, observed-versus-receipt Ready gating, stack byte recording, and verification evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan actual module-bytes report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated module-byte accounting, Module Plan Actual Module Bytes display, stack artifact byte recording, or observed-versus-receipt Ready gating. checksum_hash: sha256:A94D45A8EE9112BA407CEC4A28271636D5B1CE30DEF94BF01D4F07B38DC406A6 last_reviewed_utc: 2026-06-29T11:40:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan actual module-bytes report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_actual_module_checksums_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_actual_module_checksums pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29/ label: Required For Browser Module Plan Actual Module Checksums Memory summary: Routes agents to browser-observed generated module checksums, Actual Module Checksums display, payload checksum drift, observed-versus-receipt Ready gating, source fallback, and verification evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan actual module-checksums report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated module-checksum accounting, Module Plan Actual Module Checksums display, stack artifact checksum recording, payload checksum drift, or observed-versus-receipt Ready gating. checksum_hash: sha256:CD6774044CEE88D349C633A4D8747C5054C11E11AAF9AF32DCDA4323792EAFBD last_reviewed_utc: 2026-06-29T13:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan actual module-checksums report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_route_set_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_route_set pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29/ label: Required For Browser Module Plan Route Set Memory summary: Routes agents to ordered generated self-assembly route-set checksum fields, Route Set display, selector/receipt/recomputed route agreement, drift smoke, generated route values, and verification evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan route-set report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated route ordering, selector/receipt route-set fields, Module Plan Route Set display, or module-plan-route-set-drift assertions. checksum_hash: sha256:DF04091F0D759F281992FA33BE6B7AECA1DDEADFF44EEBCDE60300AECF8F7728 last_reviewed_utc: 2026-06-29T04:08:27Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan route-set report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_route_set_version_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_route_set_version pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-route-set-version-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-route-set-version-memory-2026-06-29/ label: Required For Browser Module Plan Route Set Version Memory summary: Routes agents to route-set version fields, Route Version display, selector/receipt/constant agreement, checksum preimage versioning, drift smoke, generated route values, and verification evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan route-set-version report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing route-set version fields, checksum preimage versioning, Module Plan Route Version display, or module-plan-route-set-version-drift assertions. checksum_hash: sha256:059AEC1201D4E11C5764DF2393471380FD93968270630B1C0C138FA2F501133C last_reviewed_utc: 2026-06-29T04:38:15Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan route-set-version report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_route_set_algorithm_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_route_set_algorithm pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-route-set-algorithm-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-route-set-algorithm-memory-2026-06-29/ label: Required For Browser Module Plan Route Set Algorithm Memory summary: Routes agents to route-set checksum algorithm fields, Route Hash display, checksum preimage algorithm labels, drift smoke, generated route values, and verification evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan route-set-algorithm report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing route-set checksum algorithm labels, checksum preimage fields, Module Plan Route Hash display, or module-plan-route-set-algorithm-drift assertions. checksum_hash: sha256:7ED26846B8327B7707FC54A9B26C141914A0B8E3CE9011A978B498465CA389C7 last_reviewed_utc: 2026-06-29T05:02:39Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan route-set-algorithm report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_operator_receipt_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_operator_receipt pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29/ label: Required For Browser Module Plan Operator Receipt Memory summary: Routes agents to generated selector, module-plan receipt, assembly receipt, fetched sign-merge operator checksum binding, drift smoke, fresh combined-selector assembly proof, generated values, and verification evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan operator receipt report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing module-plan operator receipt fields, assembly/operator agreement, fetched operator checksum validation, or module-plan-operator-receipt-drift assertions. checksum_hash: sha256:E470B5CFC80EBEDE1B14CD9981C59CBC3F6EC09CD0ED6E571B8E7881E1FDA4EC last_reviewed_utc: 2026-06-29T10:45:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan operator receipt report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_kv_cache_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_kv_cache pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28/ label: Required For Browser Module Plan KV Cache Memory summary: Routes agents to KV-cache byte/page budgets, runtime diagnostics, Module Plan KV rows, total-budget inclusion, and module-plan-kv-cache-drift evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan KV-cache report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing KV-cache byte budget math, selector/receipt cache fields, runtime diagnostics, Module Plan KV display, or module-plan-kv-cache-drift assertions. checksum_hash: sha256:C6057779C984870809BFEE50032CFC095466971544A7AE78EF8863957AFAA8F2 last_reviewed_utc: 2026-06-28T18:50:48Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan KV-cache report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_adapter_stack_budget_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_adapter_stack_budget pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28/ label: Required For Browser Module Plan Adapter Stack Budget Memory summary: Routes agents to exact adapter-stack byte budgets, selector-to-receipt matching, Stack Budget display, total-budget inclusion, and module-plan-adapter-stack-budget-drift evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan adapter stack budget report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing adapter-stack byte budget math, selector/receipt stack fields, Module Plan Stack Budget display, or module-plan-adapter-stack-budget-drift assertions. checksum_hash: sha256:647A223259C1E98F5020C5249C16A8E8194915986EA0159605FBA8CEEB5DBCC7 last_reviewed_utc: 2026-06-28T19:20:38Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan adapter stack budget report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_context_token_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_context_token pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28/ label: Required For Browser Module Plan Context Token Memory summary: Routes agents to validated context-token limits, selector model-shape matching, Module Plan Context display, and module-plan-context-token-drift evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan context token report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing context-window math, selector model-shape parsing, receipt context fields, Module Plan Context display, or module-plan-context-token-drift assertions. checksum_hash: sha256:73EECC40D7FB6F561B3AEB9BA11F3EE8D631C1662600E0A75F96FFEA6FB51242 last_reviewed_utc: 2026-06-28T19:55:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan context token report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_tokenizer_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_tokenizer pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28/ label: Required For Browser Module Plan Tokenizer Memory summary: Routes agents to tokenizer checksum binding, Module Plan Tokenizer display, tokenizer-aware genome/species checksums, and module-plan-tokenizer-drift evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan tokenizer report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing tokenizer checksum routing, selector/receipt tokenizer fields, Module Plan Tokenizer display, or module-plan-tokenizer-drift assertions. checksum_hash: sha256:DD620500D7E2AC962B0242AA8DD321186776300B0F328DC7C9113536B7FEFA92 last_reviewed_utc: 2026-06-28T20:24:08Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan tokenizer report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_sampler_cap_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_sampler_cap pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-sampler-cap-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-sampler-cap-memory-2026-06-28/ label: Required For Browser Module Plan Sampler Cap Memory summary: Routes agents to fixed-buffer sampler cap fields, Sampler Cap display, Top K clamping, selector-to-receipt cap matching, and sampler-cap drift smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan sampler cap report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing fixed-buffer sampling limits, selector/receipt sampler cap fields, Module Plan Sampler Cap display, or module-plan-sampler-cap-drift assertions. checksum_hash: sha256:B47BDDC936EE16EB489B7F28D5D208DFF630F5C914E1A76DE93B4F3F2B968612 last_reviewed_utc: 2026-06-28T23:59:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan sampler cap report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_prompt_limit_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_prompt_limit pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-prompt-limit-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-prompt-limit-memory-2026-06-28/ label: Required For Browser Module Plan Prompt Limit Memory summary: Routes agents to prompt byte limit fields, Prompt Limit display, source prompt-copy boundary proof, total-budget inclusion, and prompt-limit drift evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan prompt-limit report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing prompt byte envelopes, selector/receipt prompt fields, Module Plan Prompt Limit display, source prompt-copy behavior, or prompt-limit smoke assertions. checksum_hash: sha256:2093B791B5898E269C218421764FC3B4F2EB12450D16A8FA6F2C65A83CF3FA60 last_reviewed_utc: 2026-06-28T23:59:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan prompt-limit report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_fetch_count_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_fetch_count pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28/ label: Required For Browser Module Plan Fetch Count Memory summary: Routes agents to fetch-count limit fields, Fetch Limit display, generated route-count computation, actual governed request counting, and fetch-count drift evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan fetch-count report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated route counts, selector/receipt fetch-count fields, Module Plan Fetch Limit display, or module-plan-fetch-count-drift assertions. checksum_hash: sha256:A41A205E9F2AE73D45A702FDFC3FF2BAA2B589D0056D4157F07D593B5BA4F1B9 last_reviewed_utc: 2026-06-28T23:59:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan fetch-count report body lives in the target file. - stable_id: gguf_mirust_browser_module_plan_count_drift_memory memory_domain: gguf-mirust.report_memory.browser_module_plan_count_drift pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-module-plan-count-drift-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-module-plan-count-drift-memory-2026-06-28/ label: Required For Browser Module Plan Count Drift Memory summary: Routes agents to selector-to-receipt module cardinality, checksum-consistent module_count drift, no-generated-model-or-stack-route proof, and storage cleanup evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser module-plan count drift report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector module-plan count fields, receipt module_count parsing, or module-plan-count-drift smoke assertions. checksum_hash: sha256:B1FD636C15E3EE71C679B012CD00CF7C81FAB355823A91FA8239EEBF167D629F last_reviewed_utc: 2026-06-28T20:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser module-plan count drift report body lives in the target file. - stable_id: gguf_mirust_browser_assembly_trace_memory memory_domain: gguf-mirust.report_memory.browser_assembly_trace pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-assembly-trace-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-assembly-trace-memory-2026-06-28/ label: Required For Browser Assembly Trace Memory summary: Routes agents to Module Plan Trace checkpoints, generated q4/q8/f32 trace smoke evidence, current byte/checksum summaries, and ready-state sequencing. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser assembly trace report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing Module Plan Trace rendering, browser load sequencing, generated all-root trace assertions, or ready-state claims. checksum_hash: sha256:69EDC1FF684DD221A05F882668944115EFB526D1BC779AA27AD743FDB4AB9F54 last_reviewed_utc: 2026-06-28T01:07:16Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser assembly trace report body lives in the target file. - stable_id: gguf_mirust_browser_eval_case_evidence_checksum_memory memory_domain: gguf-mirust.report_memory.browser_eval_case_evidence_checksum pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-eval-case-evidence-checksum-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-eval-case-evidence-checksum-memory-2026-06-28/ label: Required For Browser Eval Case Evidence Checksum Memory summary: Routes agents to eval-case checksum flow across admissions, ledgers, selector registries, assembly receipts, Model Provenance, and combined-selector smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser eval case evidence checksum report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector admission eval evidence, promotion-ledger admission copies, registry-backed provenance display, or assembly receipt eval checksum fields. checksum_hash: sha256:7918E1422B06980A1A3A6143125A923A24403EEAEB7A19948DC044F39E822520 last_reviewed_utc: 2026-06-28T03:42:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser eval case evidence checksum report body lives in the target file. - stable_id: gguf_mirust_browser_assembly_eval_case_drift_memory memory_domain: gguf-mirust.report_memory.browser_assembly_eval_case_drift pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-assembly-eval-case-drift-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-assembly-eval-case-drift-memory-2026-06-28/ label: Required For Browser Assembly Eval Case Drift Memory summary: Routes agents to generated assembly eval digest matching, assembly rejection state, no evidence/adapter route proof, and assembly-eval-case-drift smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser assembly eval case drift report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated assembly eval digest checks, assembly receipt rejection state, Module Plan Trace failure checkpoints, or assembly-eval-case-drift assertions. checksum_hash: sha256:FC06567D7366205205B1986A7E724961090583E9D978CB68256C5CE5C3186758 last_reviewed_utc: 2026-06-28T04:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser assembly eval case drift report body lives in the target file. - stable_id: gguf_mirust_browser_assembly_evidence_file_drift_memory memory_domain: gguf-mirust.report_memory.browser_assembly_evidence_file_drift pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-assembly-evidence-file-drift-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-assembly-evidence-file-drift-memory-2026-06-28/ label: Required For Browser Assembly Evidence File Drift Memory summary: Routes agents to fetched assembly evidence-file checksum matching, rejection state, no later evidence/adapter route proof, and assembly-evidence-file-drift smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser assembly evidence-file drift report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated assembly evidence-file fetches, receipt evidence path/checksum fields, Assembly Evidence failure state, or assembly-evidence-file-drift assertions. checksum_hash: sha256:0C55453352A660616EEA6212B379BEFE62D6CC3C11BED08D20F0B0903517124C last_reviewed_utc: 2026-06-28T05:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser assembly evidence-file drift report body lives in the target file. - stable_id: gguf_mirust_browser_adapter_family_receipt_drift_memory memory_domain: gguf-mirust.report_memory.browser_adapter_family_receipt_drift pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-adapter-family-receipt-drift-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-adapter-family-receipt-drift-memory-2026-06-28/ label: Required For Browser Adapter Family Receipt Drift Memory summary: Routes agents to post-evidence adapter-family receipt checksum matching, loaded-model state, no manifest/stack route proof, and adapter-family-receipt-drift smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser adapter-family receipt drift report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing adapter-family receipt loading, receipt checksum handling, post-evidence adapter state, or adapter-family-receipt-drift assertions. checksum_hash: sha256:D330405FC5F2A27B4E0F817AC679FA9CBC53F6A76E242582700D5792D98F48A5 last_reviewed_utc: 2026-06-28T06:35:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser adapter-family receipt drift report body lives in the target file. - stable_id: gguf_mirust_browser_adapter_manifest_drift_memory memory_domain: gguf-mirust.report_memory.browser_adapter_manifest_drift pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-adapter-manifest-drift-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-adapter-manifest-drift-memory-2026-06-28/ label: Required For Browser Adapter Manifest Drift Memory summary: Routes agents to generated adapter manifest checksum matching, same-byte drift proof, loaded-model state, and no later manifest/stack artifact evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser adapter manifest drift report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing adapter manifest validation, manifest checksum handling, post-receipt adapter state, or adapter-manifest-drift assertions. checksum_hash: sha256:996199A693C531DE1AEE849A69DFAFB258DE1EB83D670294D01D3F288B93F2DB last_reviewed_utc: 2026-06-28T06:55:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser adapter manifest drift report body lives in the target file. - stable_id: gguf_mirust_browser_adapter_artifact_drift_memory memory_domain: gguf-mirust.report_memory.browser_adapter_artifact_drift pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28/ label: Required For Browser Adapter Artifact Drift Memory summary: Routes agents to generated adapter artifact checksum matching, post-manifest stack gating, loaded-model state, and no later artifact or Rust apply evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser adapter artifact drift report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing adapter artifact verification, stack artifact fetch ordering, post-manifest adapter state, or adapter-artifact-drift assertions. checksum_hash: sha256:E6CF6A987B39832F924E9EFE764AB57B770E838A154D0F9B132E6395B4F8E482 last_reviewed_utc: 2026-06-28T07:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser adapter artifact drift report body lives in the target file. - stable_id: gguf_mirust_browser_adapter_stack_prefetch_drift_memory memory_domain: gguf-mirust.report_memory.browser_adapter_stack_prefetch_drift pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28/ label: Required For Browser Adapter Stack Prefetch Drift Memory summary: Routes agents to generated auto-stack preflight, sparse ASP1 drift proof, loaded-model state, no low-rank fetch, and no Rust adapter apply evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser adapter stack prefetch drift report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing generated auto-stack prefetch, pre-WASM stack byte verification, post-manifest adapter state, or adapter-stack-prefetch-drift assertions. checksum_hash: sha256:BFB328FDF1E70202411B4C5E27CFA76BF3BC5087350B66F535231B50028B03A5 last_reviewed_utc: 2026-06-28T08:10:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser adapter stack prefetch drift report body lives in the target file. - stable_id: gguf_mirust_browser_adapter_stack_rust_validate_memory memory_domain: gguf-mirust.report_memory.browser_adapter_stack_rust_validate pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28/ label: Required For Browser Adapter Stack Rust Validate Memory summary: Routes agents to validate_adapter_delta ABI, generated auto-stack semantic preflight, validation-before-apply ordering, and q4/q8/f32 browser smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser adapter stack Rust validation report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing validate_adapter_delta, generated auto-stack semantic preflight, adapter ABI smoke, or validation-before-apply browser assertions. checksum_hash: sha256:6A3413A669A05142C6C733A06B4BA172213B766C2E92602EF4AD10DF4F9B5468 last_reviewed_utc: 2026-06-28T08:30:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser adapter stack Rust validation report body lives in the target file. - stable_id: gguf_mirust_browser_adapter_stack_rust_validate_drift_memory memory_domain: gguf-mirust.report_memory.browser_adapter_stack_rust_validate_drift pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28/ label: Required For Browser Adapter Stack Rust Validate Drift Memory summary: Routes agents to checksum-consistent ADP1 identity drift, Rust validate_adapter_delta shape mismatch, no-apply assertions, and full-stack fetch smoke evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser adapter stack Rust validation drift report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing adapter stack validation failure states, checksum echo routing, adapter-stack-rust-validate-drift assertions, or Rust validation-before-apply proof. checksum_hash: sha256:2599385320092B530DDFB59859133F233EED0707A413475FE19205E38D4595C1 last_reviewed_utc: 2026-06-28T08:45:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser adapter stack Rust validation drift report body lives in the target file. - stable_id: gguf_mirust_browser_runtime_assembly_diagnostics_memory memory_domain: gguf-mirust.report_memory.browser_runtime_assembly_diagnostics pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-runtime-assembly-diagnostics-memory-2026-06-28.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-runtime-assembly-diagnostics-memory-2026-06-28/ label: Required For Browser Runtime Assembly Diagnostics Memory summary: Routes agents to Rust-owned adapter apply counts, last adapter checksums, assembly-state checksums, WASM ABI proof, generated stack assertions, and manual sidecar proof. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser runtime assembly diagnostics report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing runtime diagnostics, adapter apply accounting, WASM ABI diagnostics, generated auto-stack assertions, or manual adapter sidecar assertions. checksum_hash: sha256:C2CF05E8739F35C9050453610BDA3591DD349D82F05338810F03C59B6853C8B0 last_reviewed_utc: 2026-06-28T13:40:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser runtime assembly diagnostics report body lives in the target file. - stable_id: gguf_mirust_browser_adapter_sidecar_memory memory_domain: gguf-mirust.report_memory.browser_adapter pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-adapter-sidecar-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-adapter-sidecar-memory-2026-06-27/ label: Required For Browser Adapter Sidecar Memory summary: Routes agents to browser Adapter Sidecar design, checked tiny f32/q8/q4 ADP1 routes, JS byte-transfer boundary, smoke coverage, and next adapter routes. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed browser adapter report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing Adapter Sidecar UI, browser .adp1 routes, app.js adapter transfer, or adapter-sidecar smoke. checksum_hash: sha256:0FC03072EA8A509832838A3D71BAAA087A3BCD1F5960E69C5624A2E80E07041F last_reviewed_utc: 2026-06-27T14:37:31Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser adapter report body lives in the target file. - stable_id: gguf_mirust_registry_adapter_sidecar_memory memory_domain: gguf-mirust.report_memory.registry_adapter pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/registry-adapter-sidecar-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/registry-adapter-sidecar-memory-2026-06-27/ label: Required For Registry Adapter Sidecar Memory summary: Routes agents to selector registry f32/q8/q4 adapter fields, generated bundle sidecar staging, file-backed adapter smoke coverage, and next adapter-family routes. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed registry adapter report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector registry adapter fields, browser bundle adapter staging, generated adapter routes, or adapter-sidecar-registry-file smoke. checksum_hash: sha256:96335F13A53262F4486265C96D01FF6F3274700EBB008400A8A0930B2AE748BB last_reviewed_utc: 2026-06-27T16:25:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; registry adapter report body lives in the target file. - stable_id: gguf_mirust_registry_adapter_family_memory memory_domain: gguf-mirust.report_memory.registry_adapter_family pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/registry-adapter-family-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/registry-adapter-family-memory-2026-06-27/ label: Required For Registry Adapter Family Memory summary: Routes agents to indexed f32/q8_0/q4_0 adapter-family registry fields, generated self ADP1, family ADP1, sparse ASP1 staging, browser smoke proof, and next adapter lanes. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed registry adapter family report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector registry adapter-family fields, browser bundle sidecar staging, browser adapter parsing, or adapter-sidecar-registry-file smoke. checksum_hash: sha256:D9403FB1EF61BC4A7FB79A1075573BECAE69F3FA9E741C9303FC10DBBED3ED97 last_reviewed_utc: 2026-06-27T14:37:31Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; registry adapter family report body lives in the target file. - stable_id: gguf_mirust_adapter_family_receipt_memory memory_domain: gguf-mirust.report_memory.adapter_family_receipt pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/adapter-family-receipt-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/adapter-family-receipt-memory-2026-06-27/ label: Required For Adapter Family Receipt Memory summary: Routes agents to generated f32/q8/q4 ADP1/ASP1 adapter-family receipts, runnable bundle roots, browser receipt/manifest/artifact checksum verification, member matching, and validation evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed adapter family receipt report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing adapter_family.rs, selector registry adapter_family fields, browser bundle receipt staging, or browser receipt parsing. checksum_hash: sha256:B1CA668DF85A1AA491AA9C09722BE673EE8CDA1ACC3D34094261DF3E9D004DAE last_reviewed_utc: 2026-06-27T14:37:31Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; adapter family receipt report body lives in the target file. - stable_id: gguf_mirust_assembly_receipt_memory memory_domain: gguf-mirust.report_memory.assembly_receipt pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/assembly-receipt-memory-2026-06-27.md target_location: https://aiwikis.org/gguf-mirust/reports/assembly-receipt-memory-2026-06-27/ label: Required For Assembly Receipt Memory summary: Routes agents to generated f32/q8/q4 multi-parent assembly receipts, selector registry assembly fields, browser Assembly Evidence rendering, bundle evidence-file fetches, and validation evidence. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed assembly receipt report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing selector registry assembly fields, browser bundle assembly receipt staging, app.js assembly receipt parsing, evidence-file fetches, or adapter-sidecar-registry-file assembly assertions. checksum_hash: sha256:AB1F2A4E32F0DECE417FDD1F6EACF30F1DC92666C67AAB3DB7477626DE957871 last_reviewed_utc: 2026-06-27T14:37:31Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; assembly receipt report body lives in the target file. - stable_id: gguf_mirust_taboo_voice_memory memory_domain: gguf-mirust.site_voice pointer_type: local_uai path: .uai/taboo.uai target_location: .uai/taboo.uai label: Required For GGUF.MiRust.com Site Voice Taboo Rules summary: Routes agents to GGUF.MiRust.com public copy boundaries for local-model craft, lineage, research momentum, UAIX strategy, fit, agency, and implementation evidence. pointer_status: current authority: durable-memory-pointer source_authority: human requested local hot memory review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing public copy, model-breeding positioning, or mutualist language. checksum_hash: sha256:2648476F4CE0813051EC29AFC9C88D3CEADE416D12CECF7A806A2626A13D709C last_reviewed_utc: 2026-06-29T13:45:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; hot voice rules live in the target file. - stable_id: gguf_mirust_enterprise_rust_governance_memory memory_domain: gguf-mirust.report_memory.enterprise_governance pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/enterprise-rust-governance-memory-2026-06-25.md target_location: https://aiwikis.org/gguf-mirust/reports/enterprise-rust-governance-memory-2026-06-25/ label: Required For Enterprise Rust Governance Report Memory summary: Routes agents to report-derived governance pressure for zero dependencies, trust boundaries, tests, unsafe policy, supply-chain discipline, and Rust patterns. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed report synthesis review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before applying enterprise Rust report guidance to TinyRustLM implementation choices. checksum_hash: sha256:150C24D20325B10BA57123EBC832B83FF08B40DA3DE6F986FEB344A203650524 last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; report synthesis body lives in the target file. - stable_id: gguf_mirust_browser_local_runtime_memory memory_domain: gguf-mirust.report_memory.browser_runtime pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-local-runtime-memory-2026-06-25.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-local-runtime-memory-2026-06-25/ label: Required For Browser Local Runtime Report Memory summary: Routes agents to report-derived browser runtime guidance about local fetches, WASM boundaries, diagnostics, model errors, memory pressure, and future acceleration. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed report synthesis review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before applying browser runtime reports to app, WASM host, or model-loading work. checksum_hash: sha256:ADD5B499A5CC5D4A1A6B0455809460BAD05832B1EB7814D7F2A041CDA01CDBE6 last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; report synthesis body lives in the target file. - stable_id: gguf_mirust_tinylm_modular_architecture_memory memory_domain: gguf-mirust.report_memory.tinylm_modular pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25.md target_location: https://aiwikis.org/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25/ label: Required For TinyLM Modular Report Memory summary: Routes agents to report-derived modular tiny model ideas for routing, model ABI, skills, adapters, provenance, and future multi-model work. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed report synthesis review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before expanding TinyRustLM beyond the single TinyLM-16M runtime path. checksum_hash: sha256:6DD5D2BD049DB4C2D7054FB24F6EC14ED6AF90B2484ACD522181E64C64F3C36E last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; report synthesis body lives in the target file. - stable_id: gguf_mirust_teleodynamic_resource_bounded_memory memory_domain: gguf-mirust.report_memory.teleodynamic pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25.md target_location: https://aiwikis.org/gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25/ label: Required For Teleodynamic Report Memory summary: Routes agents to report-derived resource-bounded design pressure for diagnostics, graceful degradation, phase states, local constraints, and future adaptive loops. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed report synthesis review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before using teleodynamic reports to guide diagnostics, budgets, or adaptive behavior. checksum_hash: sha256:2F5C442FF34005873F2E2515827CB336A6C11B5ECBCAFD99BDECBD001F278EF7 last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; report synthesis body lives in the target file. - stable_id: gguf_mirust_brand_product_positioning_memory memory_domain: gguf-mirust.report_memory.brand pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/brand-product-positioning-memory-2026-06-25.md target_location: https://aiwikis.org/gguf-mirust/reports/brand-product-positioning-memory-2026-06-25/ label: Required For Brand Product Report Memory summary: Routes agents to report-derived positioning for TinyRustLM naming, local-runtime copy, smoke-model honesty, and public claim boundaries. pointer_status: current authority: durable-memory-pointer source_authority: local reviewed report synthesis review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing product copy, public claims, naming, or MiRust positioning. checksum_hash: sha256:60D0BE8BD0D98231CAAE71AFBD8978EAE1F776F995F4A5E43E2BC337EEE7A94B last_reviewed_utc: 2026-06-25T00:00:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; report synthesis body lives in the target file. - stable_id: gguf_mirust_weighted_soup_operator_memory memory_domain: gguf-mirust.report_memory.model_breeding_operator pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/weighted-soup-operator-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/weighted-soup-operator-memory-2026-06-29/ label: Required For Weighted Soup Operator Memory summary: Routes agents to parent-pool soup commands, seed-weighted averaging, receipt fields, drift tests, and verification evidence. pointer_status: current authority: durable-memory-pointer source_authority: local implementation report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing soup-candidate, validate-soup-candidate, parent-pool seed weights, weighted-average math, or soup receipt routing. checksum_hash: sha256:52465109140EE8FD6846104E09496604814CB2FD959BECB586CFA1A9BD4052F7 last_reviewed_utc: 2026-06-29T15:45:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; operator memory body lives in the target file. - stable_id: gguf_mirust_multi_parent_soup_manifest_memory memory_domain: gguf-mirust.report_memory.model_breeding_operator pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/multi-parent-soup-manifest-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/multi-parent-soup-manifest-memory-2026-06-29/ label: Required For Multi-Parent Soup Manifest Memory summary: Routes agents to soup receipt handoff through multi-parent candidate manifests, operator-kind dispatch, sign/soup recomputation, manifest status, metric preservation, and tests. pointer_status: current authority: durable-memory-pointer source_authority: local implementation report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing multi-parent-candidate-manifest, validate-multi-parent-candidate, soup receipt handoff, parent-pool operator-kind dispatch, candidate manifest status, or soup metric preservation. checksum_hash: sha256:8FC66ED7289E9B2E33C477EC8F43AF0D851576F2BA7825BDC20BCA306DD5C568 last_reviewed_utc: 2026-06-29T16:25:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; multi-parent soup manifest memory body lives in the target file. - stable_id: gguf_mirust_browser_parent_pool_soup_bundle_memory memory_domain: gguf-mirust.report_memory.browser_bundle pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-parent-pool-soup-bundle-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-parent-pool-soup-bundle-memory-2026-06-29/ label: Required For Browser Parent-Pool Soup Bundle Memory summary: Routes agents to browser-multi-parent-bundle soup operator selection, multi-parent-soup ids, q8 and all-quant browser smokes, two-cycle all-soup browser reassembly proof, soup evidence files, weighted-soup receipts, route-set prefixing, and verification. pointer_status: current authority: durable-memory-pointer source_authority: local implementation report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing browser multi-parent bundle generation, soup evidence staging, weighted-soup assembly receipts, module-plan route-set checksums, or browser validation of soup bundles. checksum_hash: sha256:A1DCD6DCB1CD938542360F3068FA2D6A30F11DF1F1AE58DE18F56A7EF74CE74F last_reviewed_utc: 2026-06-29T17:40:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser parent-pool soup bundle report body lives in the target file. - stable_id: gguf_mirust_browser_multi_parent_operator_provenance_memory memory_domain: gguf-mirust.report_memory.browser_provenance pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-multi-parent-operator-provenance-memory-2026-06-29/ label: Required For Browser Multi-Parent Operator Provenance Memory summary: Routes agents to multi-parent admission operator receipt fields, generated selector copies, soup/sign-merge Operator rows, generated byte/kind drift fallback, and q4/q8/f32 combined-selector proof. pointer_status: current authority: durable-memory-pointer source_authority: local implementation report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing multi-parent admission receipt carry-forward, selector operator receipt fields, generated parent-pool Operator rows, generated selector drift smokes, or browser-smoke provenance assertions. checksum_hash: sha256:0D4C33B0BFF8BF0828C8F73CA3DC717CDEFF005AE9835BA7AF5FA1C4AF2F5843 last_reviewed_utc: 2026-06-29T19:35:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser multi-parent operator provenance report body lives in the target file. - stable_id: gguf_mirust_browser_mixed_operator_selector_memory memory_domain: gguf-mirust.report_memory.browser_selector pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/browser-mixed-operator-selector-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/browser-mixed-operator-selector-memory-2026-06-29/ label: Required For Browser Mixed Operator Selector Memory summary: Routes agents to mixed sign-merge plus soup selector roots, six-entry q4/q8/f32 cycle, route-soak, and reload-soak proof, browser default, Operator rows, route accounting, and verification. pointer_status: current authority: durable-memory-pointer source_authority: local implementation report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing mixed parent-pool browser bundle generation, cross-family selector smokes, operator-family assembly ordering, or mixed-root browser defaults. checksum_hash: sha256:7AB166C77EFFBC733EBC708717D87765A7AB0D2F411E5E1D5893ABB32F0AB466 last_reviewed_utc: 2026-06-29T21:20:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; browser mixed operator selector report body lives in the target file. - stable_id: gguf_mirust_parent_pool_evolution_schedule_memory memory_domain: gguf-mirust.report_memory.model_breeding_operator pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/parent-pool-evolution-schedule-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/parent-pool-evolution-schedule-memory-2026-06-29/ label: Required For Parent-Pool Evolution Schedule Memory summary: Routes agents to checksum-bound parent-pool evolution schedules, sign-merge and soup operator-family planning, seed-weight replay metadata, schedule drift tests, and packer verification. pointer_status: current authority: durable-memory-pointer source_authority: local implementation report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing parent-pool recipes, PBT-style replay, sign-merge/soup operator scheduling, or evolution schedule checksum validation. checksum_hash: sha256:7252D69EA8006080C29A12961736F33C8045F5161E59E91F7787FCF7A722F9CE last_reviewed_utc: 2026-06-29T19:52:45Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; parent-pool evolution schedule report body lives in the target file. - stable_id: gguf_mirust_operator_schedule_carry_forward_memory memory_domain: gguf-mirust.report_memory.model_breeding_operator pointer_type: llmwiki_node path: wiki/gguf-mirust/reports/operator-schedule-carry-forward-memory-2026-06-29.md target_location: https://aiwikis.org/gguf-mirust/reports/operator-schedule-carry-forward-memory-2026-06-29/ label: Required For Operator Schedule Carry-Forward Memory summary: Routes agents to schedule identity carried through sign-merge/soup receipts, candidate manifests, promotion templates, admission records, scheduled-family validation, and focused/full packer proof. pointer_status: current authority: durable-memory-pointer source_authority: local implementation report review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before changing parent-pool schedule fields, sign-merge/soup receipts, multi-parent candidate/promotion/admission handoff, scheduled operator-family validation, or browser bundle evidence chains. checksum_hash: sha256:927274A319833D6A83BE79B20ACB44C2589F617AA76C6BABC76EBDBDC163F960 last_reviewed_utc: 2026-06-29T20:22:33Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; operator schedule carry-forward report body lives in the target file. - stable_id: gguf_mirust_raw_manifest memory_domain: gguf-mirust.raw_evidence_manifest pointer_type: local_md path: raw/gguf-mirust/MANIFEST.md target_location: raw/gguf-mirust/MANIFEST.md label: Required For Raw Evidence Preservation summary: Routes agents to preserved report originals from 2026-06-25, 2026-06-26, and 2026-06-28, checksums, dispositions, review state, and source-site removal evidence. pointer_status: current authority: durable-memory-pointer source_authority: local raw evidence manifest review_status: reviewed_current quarantine_status: reviewed_current contextual_trigger: Read before auditing raw report evidence or preserving future handoff files. checksum_hash: sha256:6AF42F1A09C74F819675ECE154B7E9946C5703425539438D5692CCCA5F71693D last_reviewed_utc: 2026-06-28T22:40:00Z owner_or_reviewer: project memory steward current_truth_boundary: Summary routes only; raw evidence requirements live in the target file. ================================================================================ END FILE: .uai/long-term-memory.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/next-recursive-prompt.uai BYTES: 7929 SHA256: EFC10B345321CEFD8D20C775A69F969C55CA76F7D7E1D09BBA3A3246A28CAF54 ================================================================================ profile: gguf-mirust.next-recursive-prompt.v2 updated_utc: 2026-06-25T13:59:11Z prompt: > Continue TinyRustLM in E:\Source\Rust\GGUF.MiRust.com by keeping cargo fmt --all and cargo test --workspace green, preserving direct core math coverage for dot/matvec/matmul/RMSNorm/softmax/SiLU/SwiGLU, model-load pre-resolved tensor routing with artifact-backed tied-output projection, checksum-bearing .slm pack/load validation, native .slm admission validation, tiny custom BPE .slm runtime diagnostics, tiny tied-output .slm validation/generation, q8/q4 native compact storage without full decoded f32 shadow tensors, runtime-owned reusable scratch/logits, allocation-free top-k diagnostic selection, 64 KiB generated-result cap with OutputBufferExceeded cleanup, provenance sidecar validation and browser-visible Model Provenance panel, browser-local conversation transcript semantics, browser Step Token control semantics, raw-f32 trained-source validation, f32/q8_0/q4_0 untied converted-source output gating, tied-output trained-source validation and f32/q8_0/q4_0 runtime-smoke conversion gates, assistant-quality rejection for pending eval templates, TinyLM-16M f32/q8_0/q4_0, explicit ErrorCode generate_next_token/free_model WASM ABI behavior, Rust local static server behavior, Rust mini browser static/loopback contract harness, Visual Studio wrapper verification, verified-server reuse and busy-port fallback, reload/reset/model-switch browser loop verification, malformed model rejection, missing-model fetch handling, context-overflow browser coverage, WASM ABI invalid-boundary smoke, diagnostics JSON escaping, report-memory routing, desktop/mobile UI audit, browser step-token smoke, three-cycle q8/q4 endurance smoke, q8/q4 browser performance smoke, and three-cycle q8/q4 performance soak, then move into real trained weights and assistant-quality evidence review. required_context: - AGENTS.md - workspace.uai - .uai/workspace-guidance.uai - .uai/architecture.uai - .uai/coding-standards.uai - .uai/file-handoff.uai - .uai/intake-outcome-ledger.uai - tinyrustlm/README.md - tinyrustlm/docs/architecture.md - tinyrustlm/docs/slm-format.md - tinyrustlm/docs/tokenizer.md - tinyrustlm/docs/browser-runtime.md - tinyrustlm/docs/quantization.md - tinyrustlm/docs/performance.md - docs/visual-studio.md success_criteria: - Cargo manifests remain empty of third-party dependencies. - cargo fmt and cargo test pass. - Core math tests directly cover dot, matvec, matmul, RMSNorm, softmax, SiLU, SwiGLU, and shape or length rejection paths. - Valid local f32/q8_0/q4_0 tiny fixture .slm files exist under tinyrustlm/models/. - Valid local tiny-test-model-bpe.slm exists under tinyrustlm/models/ and runtime diagnostics prove prompt the becomes tokenizer_output 256,261. - Valid local tiny-test-model-tied.slm exists under tinyrustlm/models/ and runtime generation proves output projection can use tok_embeddings only under the v1 tied-output flag. - Valid local tinylm16-f32.slm exists under tinyrustlm/models/. - Valid local tinylm16-q8.slm exists under tinyrustlm/models/. - Valid local tinylm16-q4.slm exists under tinyrustlm/models/. - Local .slm files carry nonzero checksums and the runtime rejects checksum mismatch before model claims. - Native slm_pack validation accepts all local .slm artifacts and rejects malformed/non-finite payloads before model claims. - Native slm_pack manifest validation accepts all local .slm.manifest sidecars and rejects checksum drift or trained-quality overclaims. - slm_pack quality-gate accepts runtime-smoke for admitted execution artifacts. - slm_pack quality-gate rejects deterministic-smoke assistant-quality claims. - slm_pack quality-gate rejects converted-trained assistant-quality claims without passed eval evidence. - slm_pack eval-template creates only pending assistant-quality evidence and pending templates fail assistant-quality. - slm_pack validate-source accepts the checked-in tiny raw-f32 source fixture and rejects checksum/path/non-finite source failures. - slm_pack convert-trained emits f32/q8_0/q4_0 converted-trained .slm artifacts from validated raw-f32 source bundles. - slm_pack tied-output source manifests require tied model_shape agreement, omit output.weight, and convert to f32/q8_0/q4_0 .slm artifacts with the v1 tied-output flag. - Converted-trained f32/q8_0/q4_0 artifacts pass runtime-smoke, and fixture-scoped assistant-quality passes only when a matching eval sidecar with passed task and safety evidence is reviewed for the declared fixture scope. - Browser smoke can load local WASM, default to TinyLM-16M q8_0, select TinyLM-16M q4_0, generate e from prompt hi, and render diagnostics. - Browser smoke keeps local transcript behavior green: empty ready state, User/TinyRustLM entries after generation, Clear-click removal, response preservation after Clear, Clear enabled only with history, and runtime Reset separate from transcript Clear. - Browser Step Token smoke keeps hi -> e -> ee behavior green, with disabled-before-context state, enabled-after-generate state, transcript continuation, console logging, generated_token_count 2, KV cache length 5, and local-only requests. - Diagnostics JSON escaping remains tested so arbitrary local prompt/control-character output cannot break browser JSON.parse. - TinyRustLM.sln remains openable through the Visual Studio NMake wrapper, with tools/vs build and test scripts passing. - Repeated browser reload/generate/reset/model-selector loop tests remain green without regressing f32/q8_0/q4_0 correctness. - Rust local server serves app, WASM, .slm, and .slm.manifest routes over loopback and rejects traversal paths without adding third-party crates. - Rust mini browser harness keeps static app contract, local-only marker, model manifest, trained-quality non-claim, and loopback content-type checks green without adding third-party crates. - Malformed local model rejection, missing-model fetch handling, context-overflow, and endurance browser smokes remain green without adding runtime dependencies. - WASM ABI smoke keeps invalid UTF-8 prompt bytes, null pointer, invalid length, zero max_new_tokens, invalid sampling, recovery-after-error, generate_next_token, free_model, and post-free ModelNotLoaded coverage green without weakening local-only fetch or model-load error handling. - Browser performance smoke keeps q8_0/q4_0 four-token generation, benchmark prompt/generated counts, token speed, scratch bytes, reset recovery, and local-only network checks green. - Quantized tensors reject borrowed f32 slices and generation uses runtime-owned reusable copy buffers when decoded reference or norm/embedding paths need f32 values. - Model loading pre-resolves top-level and per-layer tensor indices, tied-output projection falls back to tok_embeddings through the artifact-backed tiny tied fixture, and generation does not reintroduce per-token layer-name formatting. - Runtime generation keeps scratch/logits allocated with the loaded model and reuses them across generate plus repeated generate_next_token calls. - Generated result decoding remains capped at 64 KiB; byte and BPE overflow returns OutputBufferExceeded without replacing output, and full generate overflow clears stale state. - Browser performance soak keeps repeated q8_0/q4_0 four-token generation, benchmark prompt/generated counts, KV length, token speed, scratch bytes, reset recovery, and local-only network checks green. - Browser ui-audit keeps desktop/mobile product shell identity, local-only notice, footer, panels, controls, Model Provenance panel, diagnostics/developer mirror, benchmark fields, q8_0 generation, no horizontal overflow, and local-only network checks green. - Visual Studio Run and BrowserSmoke helpers keep verified-server reuse and unrelated busy-port fallback behavior green. ================================================================================ END FILE: .uai/next-recursive-prompt.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/operations.uai BYTES: 117956 SHA256: E7D1743F8D886899A53AEC521CDD8D19A203D127EA8DD099CC66CDCE2417F24F ================================================================================ profile: gguf-mirust.operations.v71 updated_utc: 2026-06-29T20:22:33Z local_development: active_product: TinyRustLM app_url: http://127.0.0.1:8080/app/ static_server: cargo run -p tinyrustlm-local-server -- tinyrustlm 8080 rust_browser_harness: cargo run -p tinyrustlm-browser-harness -- tinyrustlm rust_browser_harness_http: cargo run -p tinyrustlm-browser-harness -- tinyrustlm --http http://127.0.0.1:8080/app/ visual_studio_solution: TinyRustLM.sln visual_studio_run: tools/vs/Run-TinyRustLM.ps1 visual_studio_test: tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke visual_studio_performance_soak: tools/vs/Test-TinyRustLM.ps1 -PerformanceSoak -PerformanceSoakCycles 3 -PerformanceSoakTokens 4 visual_studio_port_behavior: Run and BrowserSmoke helpers reuse a verified TinyRustLM server or choose the first free loopback port from the requested port. toolchain: cargo: C:\Users\AI\.cargo\bin\cargo.exe rustup: C:\Users\AI\.cargo\bin\rustup.exe node: required_for_javascript_execution_smoke_tools_only current_verified_checks: - 2026-06-29 promotion_admission_schedule_handoff_verified: multi-parent promotion templates and selector admission records now preserve parent-pool schedule identity from validated candidate manifests, admission summary validation checks scheduled family kind against the bound operator receipt kind, selector-registry multi-parent fixtures carry the new schema, and verification passed focused multi_promotion/multi_admission/selector tests plus full `tinyrustlm-slm-pack` with 324 tests. - 2026-06-29 operator_schedule_carry_forward_verified: sign-merge and soup receipts now echo parent-pool evolution schedule identity, scheduled operator-family index, command, selection rule, and output gate, while multi-parent candidate manifests validate those fields against the recipe; verification passed format check, focused sign_merge/soup/multi_candidate tests, and full `tinyrustlm-slm-pack` with 323 tests. - 2026-06-29 parent_pool_evolution_schedule_verified: `parent-pool-recipe` now emits explicit `population-based-parent-pool-replay-v1` schedule fields for sign-merge and soup operator families, parent ids, seed weights, population fitness echoes, and a schedule checksum; verification passed `cargo fmt --all -- --check`, focused `parent_pool` tests with 9 tests including checksum drift rejection, and full `tinyrustlm-slm-pack` with 323 tests. - 2026-06-29 browser_converted_trained_all_route_verified: `browser-converted-trained-bundle ... all` generated `target/browser-converted-trained-all-20260629/tinyrustlm` from `tinyrustlm/tests/fixtures/trained-source-tiny`; q4, q8, and f32 `converted-trained-registry-file` smokes on port 8099 fetched real `/models/selector.registry`, selected `.slm`, and selected `.slm.manifest` routes and generated `e`; focused converted-trained tests, full slm_pack with 322 tests, format, and JS syntax checks passed. - 2026-06-29 browser_converted_trained_file_route_verified: `browser-converted-trained-bundle` generated `target/browser-converted-trained-file-20260629/tinyrustlm` from `tinyrustlm/tests/fixtures/trained-source-tiny`; `converted-trained-registry-file` selected `converted-trained-q8`, generated `e`, and fetched real `/models/selector.registry`, `/models/converted-trained-q8.slm`, and `/models/converted-trained-q8.slm.manifest` routes on port 8096; focused browser_bundle/selector tests, full slm_pack with 321 tests, final syntax/format/diff checks, checksum audit, report/research pointer audit, and summary-length audit passed. - 2026-06-29 browser_converted_trained_provenance_verified: `converted-trained-registry` serves a compact selector route for `converted-trained-q8`, fetches `/models/converted-trained-q8.slm.manifest`, renders converted-trained source/admission/quality/trained-quality provenance fields, and generated `e`; verification passed node syntax for app.js/browser-smoke.js, converted-trained browser smoke on port 8080, compact multi-parent registry regression on port 8080, and git diff check with line-ending notices only. - 2026-06-29 dare_browser_operator_provenance_verified: `dare-operator-registry` renders Model Provenance Operator as `receipt-bound / dropout-rescaled-task-delta / 0x00000000000000b7`; selector tests prove DARE receipt kind carry-forward and DARE operator-kind drift rejection; `dare-operator-receipt-drift` falls back to static q8 with Operator `unavailable`; verification passed node syntax for app.js/browser-smoke.js, focused selector tests, full slm_pack with 318 tests, full workspace tests, positive/drift browser smokes on port 8080, git diff check, and memory pointer audits. - 2026-06-29 dare_operator_verified: `dare-candidate` and `validate-dare-candidate` now write and recompute compatibility-bound dropout/rescaled task-delta `.slm` candidates with signed `delta_weight_ppm`, `dare_keep_ppm`, `dare_dropout_seed`, selected/dropped counts, mask checksum, raw delta checksum, rescaled delta checksum, and candidate byte equality; verification passed cargo fmt check, DARE-filtered tests with 11 tests, full tinyrustlm-slm-pack tests with 316 tests, and q8 CLI compatibility-lineage-mutation-target-DARE-validate chain under `target/dare-cli`. - 2026-06-29 two_parent_operator_browser_provenance_verified: `blend-operator-registry`, `delta-operator-registry`, and `sparse-delta-operator-registry` render compact receipt-bound Operator rows for `direct-parameter-weighted-average`, `direct-parameter-task-delta`, and `sparse-direct-parameter-task-delta`; the three matching receipt-drift smokes fall back to static q8 with Operator `unavailable`; regressions passed for federated, prune, crossover, and mutation compact positive registry modes. - 2026-06-29 prune_operator_verified: `prune-candidate` and `validate-prune-candidate` now write and recompute compatibility-bound magnitude-pruned `.slm` candidates with `keep_ppm`, `floor_ppm`, selected/pruned counts, mask checksum, output-value checksum, and candidate byte equality; selector registry tests prove `operator_kind=deterministic-magnitude-parameter-pruning` receipt-bound evidence carries into `entry.N.operator_receipt_*`; browser-smoke `prune-operator-registry` renders Model Provenance Operator as `receipt-bound / deterministic-magnitude-parameter-pruning / 0x00000000000000b1`, and `prune-operator-receipt-drift` falls back to static q8 with Operator `unavailable`; verification passed cargo fmt check, prune-filtered tests with 12 tests, selector::tests with 88 tests, full tinyrustlm-slm-pack tests with 305 tests, full workspace tests, q8 CLI compatibility-lineage-prune-candidate-validate chain under `target/prune-cli`, node syntax, browser-harness tests, prune browser smokes on port 8126, and federated fixture regression smokes on port 8127. - 2026-06-29 multi_parent_soup_manifest_verified: `multi-parent-candidate-manifest` now parses `operator_kind`, recomputes either sign-merge or soup receipts through the owning operator module, writes `candidate_manifest_status=validated-parent-pool-operator-output`, preserves sign or soup metric fields, and keeps downstream promotion, admission, selector, and browser-bundle tests green; verification passed cargo fmt check, focused multi_candidate tests with 8 tests, downstream multi_ tests with 23 tests, and full tinyrustlm-slm-pack with 289 tests. - 2026-06-29 weighted_soup_operator_verified: `soup-candidate` and `validate-soup-candidate` now write and recompute seed-weighted parent-pool `.slm` candidates from ledger, population review, parent-pool recipe, admissions, and ordered parent artifacts; receipt fields include seed weight checksums, weighted-value checksum, changed-from-frontier density, candidate artifact identity, and required next gate; verification passed cargo fmt --all, focused soup tests with 6 tests, and full tinyrustlm-slm-pack with 286 tests. - 2026-06-29 federated_selector_receipt_route_verified: `selector-registry` now has direct downstream tests proving `operator_kind=federated-local-update-average` receipt-bound evidence flows through candidate, promotion, admission, and selector registry text while preserving operator kind, receipt checksum, candidate checksum, and candidate byte count, plus drift tests proving mutation-style operator-kind replacement and browser-side receipt byte-count drift are rejected; browser-smoke `selector-operator-receipt-drift` proves fallback static q8 generation with Operator `unavailable`, and `multi-parent-registry` verifies Model Provenance Operator renders `receipt-bound / federated-local-update-average / 0x00000000000000b0`; verification passed cargo fmt --all -- --check, focused `rejects_selector_registry_federated_operator_receipt_kind_drift`, selector::tests with 86 tests, full tinyrustlm-slm-pack with 280 tests, node --check tinyrustlm/tools/browser-smoke.js, targeted drift smoke on http://127.0.0.1:18881/app/, and targeted positive smoke on http://127.0.0.1:18881/app/. - 2026-06-29 federated_operator_verified: `federated-candidate` and `validate-federated-candidate` now write and recompute compatibility-bound base/local-update `.slm` candidates with `local_update_weight_ppm`, local-update counts, raw delta checksum, weighted delta checksum, and candidate byte equality; verification passed cargo fmt, focused federated tests with 9 tests, full tinyrustlm-slm-pack tests with 278 tests, cargo build, and q8 CLI compatibility-lineage-federated-candidate-validate chain under `target/federated-cli`. - 2026-06-29 browser_module_plan_actual_module_checksums_verified: app.js now owns generated self-assembly module-checksum accounting, renders Module Plan `Actual Module Checksums`, and rejects generated Ready when observed module checksums differ from receipt module checksum rows; verification passed node syntax checks, cargo fmt check, static browser harness with 9 checks, fresh generated `target/module-plan-actual-module-checksums-20260629/tinyrustlm all`, generated `combined-selector-assembly` on http://127.0.0.1:18766/app/ proving q4_0/q8_0/f32 actual checksum summaries equal declared checksum summaries, generated q4 `adapter-sidecar-registry-file` on the same root, source `ui-audit` on http://127.0.0.1:18767/app/ proving fallback `unavailable`, follow-up generated q4 `module-plan-payload-checksum-drift` on http://127.0.0.1:18768/app/ proving coherent payload checksum rewrites stop at `module plan adapter module checksum mismatch` before generated model or adapter routes, follow-up generated q4 `adapter-sidecar-registry-file` on the same root, and loopback listeners were closed after runs. - 2026-06-29 browser_module_plan_actual_module_bytes_verified: app.js now owns generated self-assembly module-byte accounting, renders Module Plan `Actual Module Bytes`, and rejects generated Ready when observed module bytes differ from receipt module byte totals; verification passed node syntax checks, cargo fmt check, static browser harness with 9 checks, existing generated `target/module-plan-actual-module-bytes-20260629/tinyrustlm all`, generated `combined-selector-assembly` on http://127.0.0.1:18764/app/ proving q4_0 `37234 bytes`, q8_0 `39474 bytes`, and f32 `51008 bytes`, source `ui-audit` on http://127.0.0.1:18765/app/ proving fallback `unavailable`, and loopback listeners were closed after runs. - 2026-06-29 browser_module_plan_observed_route_set_verified: app.js now records the browser-observed generated route-set `{kind,path}` list, renders Module Plan `Actual Route Set`, and rejects generated Ready when the observed route-set checksum differs from `module_plan_route_set_checksum`; verification passed node syntax checks, cargo fmt check, git diff --check with line-ending notices only, static browser harness with 9 checks, generated `target/module-plan-observed-route-set-20260629/tinyrustlm all`, generated `combined-selector-assembly` on http://127.0.0.1:18762/app/ proving q4_0/q8_0/f32 observed route checksums equal declared route-set checksums, source `ui-audit` on http://127.0.0.1:18763/app/ proving fallback `unavailable`, and loopback listeners were closed after runs. - 2026-06-29 browser_module_plan_actual_fetch_count_verified: app.js now owns generated self-assembly fetch accounting, renders Module Plan `Actual Fetches`, and rejects generated Ready when actual accepted route count differs from the planned count; verification passed node syntax checks, cargo fmt check, git diff --check with line-ending notices only, static browser harness with 9 checks, existing generated `target/module-plan-actual-fetch-count-20260629/tinyrustlm all`, generated `combined-selector-assembly` on http://127.0.0.1:18752/app/ proving q4_0/q8_0/f32 Plan Fetches and Actual Fetches `21 fetches`, source `ui-audit` on http://127.0.0.1:18753/app/ proving fallback `unavailable`, and loopback listeners were closed after runs. - 2026-06-29 browser_module_plan_operator_receipt_verified: generated selector and module-plan receipt fields now bind `module_plan_operator_receipt_path` and `module_plan_operator_receipt_checksum`; app.js requires selector, module-plan receipt, assembly receipt, and fetched `sign-merge.operator` checksum agreement before generated model bytes; verification passed node syntax checks, focused `module_plan_operator` tests, selector tests with 84 tests, browser_bundle tests with 4 tests, full slm_pack tests with 269 tests, cargo test --workspace, static browser harness with 9 checks, generated `target/module-plan-operator-receipt-drift-20260629/tinyrustlm all`, generated `module-plan-operator-receipt-drift` on http://127.0.0.1:18731/app/, q4 positive `adapter-sidecar-registry-file` on http://127.0.0.1:18734/app/, fresh `target/combined-selector-assembly-refresh-20260629/tinyrustlm all`, and fresh `combined-selector-assembly` on http://127.0.0.1:18751/app/ proving q4_0/q8_0/f32 operator-bound self-assembly. - 2026-06-29 selector_operator_receipt_binding_verified: selector-registry copies receipt-bound admission fields into `entry.N.operator_receipt_*`, validates copied-field drift, binds full receipt metadata into mate-selection checksums, app.js parses the optional receipt route and renders Model Provenance Operator, and verification passed focused selector receipt tests, all 82 selector tests, full slm_pack with 267 tests, slm_pack build, node syntax checks, browser_harness tests, static browser harness, and receipt-bound q8 CLI admission-to-registry smoke under `C:\Users\AI\AppData\Local\Temp\tinyrustlm-selector-receipt-4acd025a5de0418dbc54c0ffe6c91350`. - 2026-06-29 admission_operator_receipt_binding_verified: `admission-record` and `validate-admission` accept optional `[input.operator]`, carry receipt-bound promotion fields into selector admission records, validate summary receipt fields, reject missing receipt input and admission receipt checksum drift, and passed cargo fmt, 21 focused admission tests, full slm_pack 265, cargo build, q8 CLI compatibility-lineage-mutation-candidate-promotion-provenance-runtime-eval-admission chain, cargo test --workspace, and cargo fmt check. - 2026-06-29 promotion_operator_receipt_binding_verified: `promotion-template` and `validate-promotion` accept optional `[input.operator]`, carry receipt-bound candidate manifest fields into promotion records, reject missing receipt input and promotion receipt checksum drift, and passed cargo fmt, 50 focused candidate tests, 15 focused promotion tests, full slm_pack tests with 261 tests, cargo build, q8 CLI compatibility-lineage-mutation-candidate-promotion validation chain, and cargo test --workspace. - 2026-06-29 candidate_operator_receipt_binding_verified: `candidate-manifest` and `validate-candidate` accept optional `[input.operator]`, write receipt-bound candidate manifest fields, validate operator id/kind plus candidate bytes/checksum against the supplied receipt and `.slm`, reject receipt checksum drift and missing receipt input for bound manifests, and passed cargo fmt check, 50 focused candidate tests, q8 CLI compatibility-lineage-mutation-candidate-manifest-validate chain, full slm_pack tests with 257 tests, cargo test --workspace, and git diff --check with line-ending notices only. - 2026-06-29 browser_module_plan_route_set_algorithm_verified: generated selector entries and served module-plan receipts now carry `module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1`; app.js verifies selector, receipt, expected constant, and recomputed route-set checksum preimage agreement before generated bytes, Module Plan renders `Route Hash`, generated `module-plan-route-set-algorithm-drift` passed on http://127.0.0.1:8262/app/ before generated model routes, generated `combined-selector-assembly` passed on http://127.0.0.1:8262/app/ proving q4_0/q8_0/f32 Route Hash `tinyrustlm-text-checksum-v1` plus Route Set checksums, source `ui-audit` passed on http://127.0.0.1:8263/app/, full slm_pack tests passed with 232 tests, static harness passed with 9 checks, and temporary generated root plus local servers were cleaned up. - 2026-06-29 browser_module_plan_route_set_version_verified: generated selector entries and served module-plan receipts now carry `module_plan_route_set_version=1`; app.js verifies selector, receipt, expected constant, and recomputed route-set checksum preimage agreement before generated bytes, Module Plan renders `Route Version`, generated `module-plan-route-set-version-drift` passed on http://127.0.0.1:8260/app/ before generated model routes, generated `combined-selector-assembly` passed on http://127.0.0.1:8260/app/ proving q4_0/q8_0/f32 Route Version `1` plus Route Set checksums, source `ui-audit` passed on http://127.0.0.1:8261/app/, full slm_pack tests passed with 230 tests, static harness passed with 9 checks, and temporary generated root plus local servers were cleaned up. - 2026-06-29 browser_module_plan_route_set_verified: generated selector entries and served module-plan receipts now carry `module_plan_route_set_checksum`; app.js verifies selector, receipt, and recomputed ordered generated self-assembly routes before generated bytes, Module Plan renders `Route Set`, generated `module-plan-route-set-drift` passed on http://127.0.0.1:8258/app/ before generated model routes, generated `combined-selector-assembly` passed on http://127.0.0.1:8258/app/ proving q4_0/q8_0/f32 Route Set checksums, source `ui-audit` passed on http://127.0.0.1:8259/app/, full slm_pack tests passed with 228 tests, static harness passed with 9 checks, and temporary generated root plus local servers were cleaned up. - 2026-06-29 browser_module_plan_planned_fetch_count_verified: generated selector entries and served module-plan receipts now carry `module_plan_planned_fetch_count=21`; app.js verifies selector, receipt, generated route formula, and constant agreement, Module Plan renders `Plan Fetches`, generated `module-plan-planned-fetch-count-drift` passed on http://127.0.0.1:8256/app/ before generated model routes, generated `combined-selector-assembly` passed on http://127.0.0.1:8256/app/ proving q4_0/q8_0/f32 Plan Fetches `21`, source `ui-audit` passed on http://127.0.0.1:8257/app/, full slm_pack tests passed with 226 tests, static harness passed with 9 checks, and temporary generated root plus local servers were cleaned up. - 2026-06-29 browser_module_plan_adapter_validation_count_verified: generated selector entries and served module-plan receipts now carry `module_plan_adapter_validation_count=3`; app.js verifies selector/receipt/adapter-family agreement and actual Rust validation loop count before apply, Module Plan renders `Validate Count`, generated `module-plan-adapter-validation-count-drift` passed on http://127.0.0.1:8254/app/ before generated model routes, generated `combined-selector-assembly` passed on http://127.0.0.1:8254/app/ proving q4_0/q8_0/f32 Validate Count `3` and three validation calls per generated assembly step, source `ui-audit` passed on http://127.0.0.1:8255/app/, full slm_pack tests passed with 224 tests, and temporary generated root plus local servers were cleaned up. - 2026-06-29 browser_module_plan_adapter_apply_count_verified: generated selector entries and served module-plan receipts now carry `module_plan_adapter_apply_count=3`; app.js verifies selector/receipt/adapter-family agreement, Module Plan renders `Apply Count`, runtime diagnostics must report `adapter_apply_count=3` after generated assembly, generated `module-plan-adapter-apply-count-drift` passed on http://127.0.0.1:8242/app/ before generated model routes, fresh generated all-root `combined-selector-assembly` passed on http://127.0.0.1:8252/app/ proving q4_0/q8_0/f32 Apply Count `3` and stack apply before generation, full slm_pack tests passed with 223 tests, and temporary generated roots plus the local servers were cleaned up. - 2026-06-29 browser_module_plan_adapter_validation_verified: generated selector entries and served module-plan receipts now carry `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1`; app.js verifies selector/receipt agreement, Module Plan renders `Validate`, generated `module-plan-adapter-validation-drift` passed on http://127.0.0.1:8240/app/ before generated model routes, generated `combined-selector-assembly` passed on http://127.0.0.1:8240/app/ proving `validate_adapter_delta` before `apply_adapter_delta` for q4_0/q8_0/f32, source `ui-audit` passed on http://127.0.0.1:8241/app/, and both local servers were stopped. - 2026-06-29 browser_module_plan_runtime_reset_verified: generated selector entries and served module-plan receipts now carry `module_plan_runtime_reset_strategy=reset-context-before-assembly-v1`; app.js verifies selector/receipt agreement, Module Plan renders `Reset`, generated `module-plan-runtime-reset-drift` passed on http://127.0.0.1:8235/app/ before generated model routes, generated `combined-selector-cycle` passed on http://127.0.0.1:8235/app/ proving `reset_context` before q4_0/q8_0/f32 adapter validation/application, source `ui-audit` passed on http://127.0.0.1:8236/app/, and both local servers were stopped. - 2026-06-29 browser_module_plan_model_release_verified: generated selector entries and served module-plan receipts now carry `module_plan_model_release_strategy=free-before-reassembly-v1`; app.js verifies selector/receipt agreement, Module Plan renders `Release`, generated `module-plan-model-release-drift` passed on http://127.0.0.1:8233/app/ before generated model routes, generated `combined-selector-cycle` passed on http://127.0.0.1:8233/app/ proving `free_model` before post-initial q4_0/q8_0/f32 reassembly, source `ui-audit` passed on http://127.0.0.1:8234/app/, and both local servers were stopped. - 2026-06-28 browser_module_plan_wasm_transfer_verified: generated selector entries and served module-plan receipts now carry `module_plan_wasm_transfer_strategy=copy-then-release-v1`; app.js verifies selector/receipt agreement, Module Plan renders `Transfer`, generated `module-plan-wasm-transfer-drift` and `combined-selector-cycle` passed on http://127.0.0.1:8231/app/, source `ui-audit` passed on http://127.0.0.1:8232/app/, and both local servers were stopped. - 2026-06-28 browser_module_plan_wasm_heap_verified: generated selector entries and served module-plan receipts now carry `module_plan_wasm_heap_min_bytes=65536`; app.js recomputes the heap floor, probes WASM alloc/dealloc before generated model bytes, Module Plan renders `Heap Floor`, generated `module-plan-wasm-heap-drift` and `combined-selector-cycle` passed on http://127.0.0.1:8221/app/, source `ui-audit` passed on http://127.0.0.1:8222/app/, and both local servers were stopped. - 2026-06-28 browser_module_plan_actual_fetch_count_verified: browser-smoke counts model-owned generated self-assembly requests under `/models/{model}...` and `/evidence/{model}/...`; generated `target/module-plan-actual-fetch-count/tinyrustlm all`, served it on http://127.0.0.1:8213/app/, and `combined-selector-cycle 2` plus `combined-selector-reload-soak 2` passed with 21 governed requests per q4_0/q8_0/f32 pass under the 32-fetch module-plan envelope. - 2026-06-28 browser_module_plan_fetch_count_verified: generated selector registry entries and served module-plan receipts now carry `module_plan_fetch_count_limit=32`; Module Plan renders Fetch Limit `32 fetches`, total budgets are 173415/175655/187189 bytes for q4/q8/f32, generated `combined-selector-assembly` plus `module-plan-fetch-count-drift` passed on http://127.0.0.1:8211/app/, and source `ui-audit` passed on http://127.0.0.1:8212/app/. - 2026-06-28 browser_module_plan_prompt_limit_verified: generated selector registry entries and served module-plan receipts now carry `module_plan_prompt_byte_limit=4096`; Module Plan renders Prompt Limit, current total budgets are 173415/175655/187189 bytes for q4/q8/f32, total limit is 43454464 bytes, generated `combined-selector-assembly` plus `module-plan-prompt-limit-drift` passed on http://127.0.0.1:8201/app/, and source `ui-audit` plus `prompt-limit` passed on http://127.0.0.1:8202/app/. - 2026-06-28 browser_module_plan_output_limit_verified: generated selector registry entries and served module-plan receipts now carry `module_plan_output_byte_limit=65536`; Module Plan renders Output Limit and remains included in current prompt-aware total budget math. - 2026-06-28 browser_module_plan_wasm_export_set_verified: generated selector registry entries and served module-plan receipts now carry `module_plan_wasm_export_set=tinyrustlm-generate-v1`; app.js verifies selector/receipt agreement plus instantiated WASM exports before generated model bytes, Module Plan renders WASM ABI, and combined-selector-assembly plus module-plan-wasm-export-set-drift passed on http://127.0.0.1:8106/app/ after node syntax, cargo fmt, focused selector, selector-filtered, browser_bundle, browser_harness, static harness, generated-root, source ui-audit, report/research pointer audit, local checksum audit, and git diff --check. - 2026-06-28 browser_module_plan_sampler_cap_verified: generated selector registry entries and served module-plan receipts now carry `module_plan_sampler_candidate_cap=1024`; Module Plan renders Sampler Cap `1024 candidates`, browser Top K clamps to the fixed-buffer envelope, exact q4/q8/f32 totals are 103782/106022/117556 bytes, and combined-selector-assembly plus module-plan-sampler-cap-drift passed on http://127.0.0.1:8105/app/ after node syntax, cargo fmt, focused selector, selector-filtered, browser_bundle, browser_harness, static harness, generated-root, and source ui-audit checks. - 2026-06-28 browser_module_plan_tokenizer_verified: generated selector registry entries and served module-plan receipts now carry `module_plan_tokenizer_checksum`; Module Plan renders Tokenizer `0x288f65d94c26743e`, exact q4/q8/f32 totals are 103780/106020/117554 bytes, and combined-selector-assembly plus module-plan-tokenizer-drift passed on http://127.0.0.1:8104/app/ after node syntax, cargo fmt, focused selector, full selector-filtered, browser_bundle, browser_harness, static harness, and generated-root checks. - 2026-06-28 browser_module_plan_context_token_verified: generated selector registry entries and served module-plan receipts now carry `module_plan_context_token_limit=16`; Module Plan renders Context, exact q4/q8/f32 totals are 103784/106024/117558 bytes, and combined-selector-assembly plus module-plan-context-token-drift and module-plan-kv-cache-drift passed on http://127.0.0.1:8103/app/ after node syntax, cargo fmt, focused selector, browser_bundle, browser_harness, static harness, and generated-root checks. - 2026-06-28 browser_module_plan_adapter_stack_budget_verified: generated selector registry entries and served module-plan receipts now carry `module_plan_adapter_stack_byte_budget=22144`; Module Plan renders Stack Budget, exact q4/q8/f32 totals are 103783/106023/117557 bytes, and combined-selector-assembly plus module-plan-adapter-stack-budget-drift and module-plan-total-budget-drift passed on http://127.0.0.1:8102/app/ after focused selector, browser_bundle, browser_harness, syntax, fmt, static harness, and generated-root checks. - 2026-06-28 browser_module_plan_kv_cache_verified: runtime diagnostics, generated selector registry entries, and served module-plan receipts carry KV-cache byte budget and page-count fields; Module Plan renders KV Budget and KV Pages, and the current prompt-aware total self-assembly cap is 43454464 bytes. - 2026-06-28 browser_selector_heritable_artifact_verified: generated selector registry entries include deterministic heritable artifact ids, `served-artifact-bound` checksums, and exact strategy/status fields; app.js requires those fields for generated registry entries, Model Provenance renders Artifact rows, and combined-selector-assembly on http://127.0.0.1:8100/app/ with debugger port 19572 proved q4_0/q8_0/f32 entries after focused selector, browser_bundle, browser_harness, node syntax, generated all-root, and served-root browser smoke checks. - 2026-06-28 browser_selector_mate_selection_memory_audit_verified: final focused reruns passed cargo fmt --check, node syntax checks, selector tests with 51 tests, browser_bundle tests with 4 tests, and browser_harness tests with 6 tests; report/research pointer audit found 78 reports and 2 research pages with 0 missing, and local pointer checksum audit checked 187 targets with 0 mismatches. - 2026-06-28 browser_selector_mate_selection_verified: generated selector registry entries include deterministic mate-selection ids, parent-pool-bound/admission-only statuses, parent counts, and mate-selection checksums; app.js requires those fields for generated registry entries, Model Provenance renders Mate Selection rows, and combined-selector-assembly on http://127.0.0.1:8098/app/ proved q4_0/q8_0/f32 entries after focused selector, browser_bundle, browser_harness, node syntax, generated all-root, and served-root browser smoke checks. - 2026-06-28 browser_selector_novelty_verified: generated selector registry entries include deterministic novelty ids, `behavior-sketch-bound` novelty checksums, and exact novelty strategy/status fields; app.js requires those fields for generated registry entries, Model Provenance renders Novelty rows, and combined-selector-assembly on http://127.0.0.1:8096/app/ with debugger port 19564 proved q4_0/q8_0/f32 entries after focused selector, full slm_pack, and browser_harness tests. - 2026-06-28 browser_selector_species_fit_verified: generated selector registry entries include deterministic species ids, `browser-fit-bound` fit checksums, and exact speciation strategy/status fields; app.js requires those fields for generated registry entries, Model Provenance renders Species rows, and combined-selector-assembly on http://127.0.0.1:8096/app/ proved q4_0/q8_0/f32 entries after focused selector, full slm_pack, and browser_harness tests. - 2026-06-28 browser_selector_genome_fitness_verified: generated selector registry entries include deterministic genome ids, genome lineage checksums, and eval-bound fitness-vector checksums; app.js requires those fields for generated registry entries, Model Provenance renders Genome/Fitness rows, and combined-selector-assembly on http://127.0.0.1:8096/app/ proved q4_0/q8_0/f32 entries after slm_pack and browser_harness tests. - 2026-06-28 modelbreeder_zero_dependency_research_intake_preserved: 4 Improvement research files were copied to raw/gguf-mirust/report-intake-2026-06-28/ with matching SHA256 hashes, duplicate ModelBreeder bodies were recorded, and durable routing was added through report-intake-index-2026-06-28 plus modelbreeder-zero-dependency-reference-ideas-2026-06-28. - 2026-06-28 browser_combined_selector_stress_route_soak_verified: generated `target/combined-selector-route-stress-soak/tinyrustlm all`, served it locally, and browser-smoke `combined-selector-route-stress-soak` proved eight q4_0/q8_0/f32 cycles, twenty-four assemblies, per-pass route requests, release-before-reassembly, Rust stack validation/apply, WASM Pages 17, and one-token generation. - 2026-06-28 browser_module_plan_count_drift_verified: `module-plan-count-drift` mutates served receipt `module_count` while refreshing selector module-plan checksum; browser-smoke on http://127.0.0.1:8193/app/ returned `Module plan module count mismatch` after only selector registry and module-plan receipt requests. E: storage cleanup removed the active repo target and recoverable `.vs` cache content before focused rebuilds. - 2026-06-28 browser_combined_selector_extended_route_soak_verified: generated `target/combined-selector-route-extended-soak/tinyrustlm all`, served it locally, and browser-smoke `combined-selector-route-extended-soak` proved five q4_0/q8_0/f32 cycles, fifteen assemblies, per-pass route requests, release-before-reassembly, Rust stack validation/apply, WASM Pages 17, and one-token generation. - 2026-06-28 browser_module_plan_wasm_memory_verified: generated selector entries and served module-plan receipts now carry `module_plan_wasm_memory_initial_pages=17`; app.js captures exported WASM memory pages immediately after instantiation and before runtime init, renders the verified `WASM Pages` row, and `module-plan-wasm-memory-drift` proves drift stops before generated `.slm` fetch. E: storage cleanup recovered the drive to about 66.49 GB free before final memory checks. - 2026-06-28 browser_module_plan_origin_policy_verified: generated selector entries and served module-plan receipts now carry `module_plan_origin_policy=same-origin-loopback-local-v1`; slm_pack module_plan tests, browser_bundle tests, browser_harness tests, static browser harness, generated `target/module-plan-origin-policy-drift/tinyrustlm all`, `module-plan-origin-policy-drift`, existing `module-plan-fetch-policy-drift`, and `combined-selector-assembly` passed. - 2026-06-28 browser_module_plan_fetch_policy_verified: generated selector entries and served module-plan receipts now carry `module_plan_fetch_policy=local-no-store-v1`; slm_pack module_plan tests, browser_bundle tests, browser_harness tests, static browser harness, generated `target/module-plan-fetch-policy-drift/tinyrustlm all`, `module-plan-fetch-policy-drift`, existing `module-plan-execution-profile-drift`, and `combined-selector-assembly` passed. - 2026-06-28 browser_module_plan_execution_profile_verified: generated selector entries and served module-plan receipts now carry `module_plan_execution_profile=single-threaded-wasm-local-v1`; slm_pack module_plan tests, browser_bundle tests, browser_harness tests, static browser harness, generated `target/module-plan-execution-profile-drift/tinyrustlm all`, `module-plan-execution-profile-drift`, and `combined-selector-assembly` passed. - 2026-06-28 browser_module_plan_runtime_scratch_verified: generated selector entries and served module-plan receipts now carry `module_plan_runtime_scratch_byte_budget=65536`; slm_pack module_plan tests, browser_bundle tests, browser_harness tests, static browser harness, generated `target/module-plan-runtime-scratch-drift/tinyrustlm all`, `module-plan-runtime-scratch-drift`, and `combined-selector-assembly` passed. - 2026-06-28 browser_module_plan_profile_verified: generated selector entries and served module-plan receipts now carry `module_plan_profile=browser-constrained-v1`; slm_pack module_plan tests, browser_bundle tests, browser_harness tests, static browser harness, generated `target/module-plan-profile-drift/tinyrustlm all`, `module-plan-profile-drift`, and `combined-selector-assembly` passed. - 2026-06-28 browser_combined_selector_route_soak_verified: generated `target/combined-selector-route-soak/tinyrustlm all`, served it locally, and browser-smoke `combined-selector-route-soak 3` proved three q4_0/q8_0/f32 cycles, no-store local assembly fetches, per-pass self-assembly route requests, release-before-reassembly, Rust stack validation, stack apply, and one-token generation. - 2026-06-28 browser_adapter_stack_rust_validate_verified: runtime exposes validate_adapter_delta, browser auto assembly validates every fetched ADP1/ASP1/ALR1 stack member before first apply_adapter_delta, adapter-sidecar-registry-file and combined-selector-assembly prove validation-before-apply ordering across generated q4/q8/f32 roots, and adapter-stack-prefetch-drift still stops before Rust apply. - 2026-06-28 browser_adapter_stack_prefetch_drift_verified: generated auto assembly now prefetches and checksum-verifies family ADP1 plus sparse ASP1 plus low-rank ALR1 stack bytes before any Rust adapter apply; adapter-stack-prefetch-drift proved sparse ASP1 byte drift after family ADP1 fetch stops before low-rank ALR1 fetch or apply_adapter_delta, while normal adapter-sidecar-registry-file and first-artifact drift still pass. - 2026-06-28 model_breeding_uaix_memory_strategy_refresh_verified: setup-file-handoff strategy, Model Breeding concept lanes, short-term report/research routes, .uai/taboo.uai site voice routing, and long-term pointer checksums were refreshed; active bucket scan was empty, report/research pointer audit found 47 reports and 1 research page with 0 missing, local checksum audit checked 154 targets with 0 mismatches, and git diff --check passed with line-ending notices only. - 2026-06-28 browser_assembly_evidence_file_drift_verified: generated selector, module-plan, model, manifest, and assembly receipt bytes stay valid while one fetched evidence file body drifts; browser-smoke assembly-evidence-file-drift rejects before later evidence, adapter-family receipt, adapter manifests, or adapter stack routes, and normal q4 adapter-sidecar-registry-file still reaches ready and applies ADP1 plus ASP1 plus ALR1. - 2026-06-28 browser_assembly_eval_case_drift_verified: generated assembly receipt eval-case digest drift now releases loaded generated model state, renders assembly evidence rejected, keeps selector recovery available, and stops before evidence files, adapter-family receipt, adapter manifests, or adapter stack routes; node syntax checks, regenerated all-root staging, served-root assembly-eval-case-drift on port 8099, served-root combined-selector-assembly on port 8099, and profile cleanup notices passed. - 2026-06-28 browser_eval_case_evidence_checksum_verified: passed eval sidecar cases now produce `eval_case_evidence_checksum` in selector admissions, multi-parent admissions, promotion ledgers, selector registries, generated assembly receipts, and Model Provenance; cargo fmt check, slm_pack tests with 168 tests, runtime tests with 77 tests, browser_harness tests with 6 tests, static browser harness with 9 checks, node syntax checks, WASM ABI smoke, regenerated all-root staging, served-root combined-selector-assembly on port 8098, server cleanup, and port cleanup passed. - 2026-06-28 browser_low_rank_adapter_route_verified: generated f32/q8_0/q4_0 bundles stage low-rank `.alr1` members as the third adapter stack route, module plans declare seven modules, f32 and q8_0 `adapter-sidecar-registry-file` smokes auto-apply ADP1 plus ASP1 plus ALR1 before generation, and node syntax checks, cargo fmt check, slm_pack tests with 167 tests, runtime tests with 77 tests, browser_harness tests with 6 tests, WASM ABI smoke, rebuilt WASM, refreshed runtime manifest, generated bundle staging, server cleanup, and port cleanup passed. - 2026-06-28 low_rank_adapter_memory_refresh_verified: cargo fmt check, runtime tests with 77 tests, slm_pack tests with 165 tests, browser_harness tests with 6 tests, report pointer audit for 44 reports and 1 research page, long-term checksum audit for 151 local pointer targets, and git diff --check exited 0 with line-ending notices only passed after ALR1 docs and memory routing. - 2026-06-28 low_rank_adapter_package_verified: tinyrustlm-slm-pack writes and validates ALR1 low-rank f32 task-delta packages with deterministic factor metadata, runtime apply reconstructs compatible low-rank deltas for loaded f32/q8_0/q4_0 models, and focused/full runtime plus packer tests and the CLI compatibility-lineage-low-rank-write-validate chain passed. - 2026-06-28 browser_assembly_trace_verified: generated roots render the Module Plan Trace `0: plan verified, 1: model accepted, 2: manifest verified, 3: assembly evidence verified, 4: adapter family verified, 5: adapter stack applied, 6: ready`; node syntax checks, cargo fmt check, browser_bundle tests, browser_harness tests, static browser harness, generated all-root staging under target/browser-assembly-trace/tinyrustlm, served-root combined-selector-assembly smoke on port 18744, report/research pointer audit for 43 reports and 1 research page, long-term checksum audit for 72 local file pointers, and server cleanup passed. - 2026-06-28 browser_combined_selector_assembly_verified: browser-multi-parent-bundle `all` stages f32, q8_0, and q4_0 generated multi-parent modules into one served root, browser-smoke `combined-selector-assembly` keeps q4_0 as the initial browser-frugal default, walks q4_0, q8_0, and f32 in one page, proves each selector entry fetches `.module-plan.receipt` before `.slm`, verifies module bytes/checksums/roles/slots/dependencies/phases plus receipt-declared adapter stacks, and generates one local token after auto-assembly for each module; node syntax checks, cargo fmt check, browser_bundle tests, browser_harness tests, static harness, generated all-root staging, served-root combined-selector-assembly smoke on port 18742, report/research pointer audit, long-term checksum audit, and server cleanup passed. - 2026-06-27 memory_strategy_refresh_verified: active handoff buckets contained no non-placeholder files, UAIX File Handoff strategy routes through docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md, every current wiki/gguf-mirust/reports/*.md page is represented in .uai/long-term-memory.uai, and short-term memory references the report indexes, Model Breeding synthesis, research page, dogfood route, and long-term pointer ledger. - 2026-06-27 browser_module_plan_checksums_verified: generated `.module-plan.receipt` files carry uniform `module.N.checksum` fields, app.js verifies stack module checksums before generated model or stack work, the Module Plan panel renders the verified checksum summary, and node syntax checks, cargo fmt check, browser_bundle tests, browser_harness tests, generated all-root staging, generated-root q4 adapter-sidecar-registry-file smoke on port 18736/19586, generated-root q4 module-plan-checksum-drift smoke on port 18736/19588, source-root ui-audit on port 18738/19590, static harness with 9 checks, and workspace tests with 249 checks passed. - 2026-06-27 browser_module_plan_byte_counts_verified: generated `.module-plan.receipt` files carry `module.N.byte_count` fields, app.js verifies model bytes, manifest text, assembly receipt text, adapter-family receipt text, and adapter-stack artifact bytes before generated model or stack work, the Module Plan panel renders the verified byte summary, and node syntax checks, cargo fmt check, browser_bundle tests, browser_harness tests, generated all-root staging, generated-root q4 adapter-sidecar-registry-file smoke on port 18732/19576, generated-root q4 module-plan-byte-drift smoke on port 18732/19572, source-root ui-audit on port 18734/19574, static harness with 9 checks, and workspace tests with 249 checks passed. - 2026-06-27 browser_module_plan_phases_verified: generated `.module-plan.receipt` files carry `module.N.phase` fields, app.js verifies load-model-bytes through ordered apply-adapter-stack phases before generated model fetch, the Module Plan panel renders the verified phase summary, and node syntax checks, cargo fmt check, browser_bundle tests, browser_harness tests, generated all-root staging, generated-root q4 adapter-sidecar-registry-file smoke on port 18728/19564, generated-root q4 module-plan-phase-drift smoke on port 18728/19566, source-root ui-audit on port 18730/19568, static harness with 9 checks, and workspace tests with 249 checks passed. - 2026-06-27 browser_module_plan_dependencies_verified: generated `.module-plan.receipt` files carry `module.N.depends_on` fields, app.js verifies the runtime-wasm-to-stack dependency chain before generated model fetch, the Module Plan panel renders the verified dependency summary, and node syntax checks, cargo fmt check, browser_bundle tests, browser_harness tests, generated all-root staging, generated-root q4 adapter-sidecar-registry-file smoke on port 18724/19558, generated-root q4 module-plan-dependency-drift smoke on port 18724/19560, source-root ui-audit on port 18726/19562, static harness with 9 checks, workspace tests with 249 checks, git diff line-ending notes only, temp profile cleanup, server cleanup, and port checks passed. - 2026-06-27 browser_module_plan_slots_verified: generated `.module-plan.receipt` files carry `module.N.assembly_slot` fields, app.js verifies exact runtime/model-manifest/assembly-receipt/adapter-family-receipt/adapter-stack slot values before generated model fetch, the Module Plan panel renders the verified slot summary, and node syntax checks, cargo fmt check, browser_bundle tests, browser_harness tests, generated all-root staging, generated-root q4 adapter-sidecar-registry-file smoke on port 18720/19552, generated-root q4 module-plan-slot-drift smoke on port 18720/19554, source-root ui-audit on port 18722/19556, static harness with 9 checks, and workspace tests with 249 checks passed. - 2026-06-27 browser_module_plan_role_drift_verified: browser-smoke `module-plan-role-drift` mutates the q4 served module-plan receipt `module.4.role` while keeping the receipt checksum aligned in selector.registry; app.js rejects the role before generated `.slm`, ADP1, ASP1, or adapter-manifest routes are fetched, and node syntax check, generated all-root staging, served-root role drift smoke on port 18718/19550, cargo fmt check, workspace tests with 249 checks, temp profile cleanup, and server cleanup passed. - 2026-06-27 browser_module_plan_role_display_verified: the browser Module Plan panel renders verified `.module-plan.receipt` module role summaries from receipt fields after plan verification; source-root ui-audit proved fallback roles unavailable, generated q4 adapter-sidecar-registry-file proved runtime/model-manifest/assembly/adapter-family/family-stack/sparse-stack roles, and node syntax checks, cargo fmt check, browser_bundle tests, browser_harness tests, static harness, generated all-root staging, workspace tests with 249 checks, and git diff line-ending notes only passed. - 2026-06-27 browser_module_plan_budget_display_verified: the browser Module Plan panel renders verified `.module-plan.receipt` model and adapter byte budgets from receipt fields after plan verification; source-root ui-audit proved fallback budget rows unavailable, generated q4 adapter-sidecar-registry-file proved `6592 bytes` and `1048576 bytes`, and node syntax checks, cargo fmt check, browser_harness tests, static harness, generated all-root staging, and workspace tests with 249 checks passed. - 2026-06-27 browser_module_plan_display_verified: the browser Module Plan panel renders verified `.module-plan.receipt` status, kind, resource class, module count, model route, and receipt-declared stack routes without parsing model or adapter bytes; source-root ui-audit proved fallback `none` fields, generated q4 adapter-sidecar-registry-file proved loaded receipt fields, and node syntax checks, cargo fmt check, browser_harness tests, static harness, generated all-root staging, workspace tests with 249 checks, git diff line-ending notes only, temp profile cleanup, and server/port cleanup passed. - 2026-06-27 browser_module_plan_stack_drift_verified: browser-smoke `module-plan-stack-drift` mutates the q4 served module-plan receipt `module.4.adapter_path` while keeping the receipt checksum aligned in selector.registry; app.js rejects the stack member route before generated `.slm`, ADP1, ASP1, or adapter-manifest routes are fetched, and node syntax checks, generated all-root staging, served-root stack drift smoke on port 18704/19536, cargo fmt check, workspace tests with 249 checks, temp profile cleanup, and server cleanup passed. - 2026-06-27 browser_module_plan_graph_drift_verified: browser-smoke `module-plan-graph-drift` mutates the q4 served module-plan receipt `module.0.path` while keeping the receipt checksum aligned in selector.registry; app.js rejects the graph before `/models/multi-parent-sign-merge-q4.slm` is fetched, and node syntax checks, generated all-root staging, served-root graph drift smoke on port 18702/19534, cargo fmt check, workspace tests with 249 checks, and server cleanup passed. - 2026-06-27 browser_module_plan_resource_drift_verified: browser-smoke `module-plan-resource-drift` mutates the q4 served module-plan receipt adapter byte budget while keeping the receipt checksum aligned in selector.registry; app.js rejects the envelope before `/models/multi-parent-sign-merge-q4.slm` is fetched, and node syntax checks, generated all-root staging, served-root drift smoke on port 18700/19530, cargo fmt check, workspace tests with 249 checks, git diff line-ending notes only, temp profile cleanup, and server cleanup passed. - 2026-06-27 browser_module_plan_resource_envelope_verified: generated selector registries and served `.module-plan.receipt` files now declare `module_plan_resource_class=browser-constrained-local-assembly`, `module_plan_model_byte_budget`, and `module_plan_adapter_byte_budget`; Rust rejects resource drift, app.js verifies the envelope before generated `.slm` fetch, and node syntax checks, cargo fmt, selector tests with 28 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static harness with 9 checks, generated all-root staging, generated q4 adapter-sidecar-registry-file smoke on port 18698 proving the module-plan route before `.slm` fetch, workspace tests with 249 checks, git diff line-ending notes only, temp profile cleanup, server cleanup, and port cleanup passed. - 2026-06-27 browser_module_plan_verified: generated selector registries declare `entry.N.module_plan_*` route, checksum, label, status, kind, strategy, and module_count fields; generated bundles write served `.module-plan.receipt` files binding model, manifest, assembly receipt, adapter-family receipt, and adapter stack members; app.js verifies the plan before generated `.slm` fetch; node syntax checks, cargo fmt check, selector tests with 27 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static harness with 9 checks, generated all-root staging, generated q4 adapter-sidecar-registry-file smoke on port 18696 proving the module-plan route before `.slm` fetch, workspace tests with 248 checks, git diff line-ending notes only, server cleanup, and port cleanup passed. - 2026-06-27 browser_adapter_stack_verified: adapter-family receipts declare ordered auto-apply stack members, selector registries carry `adapter_auto_apply_stack_status=enabled`, `adapter_auto_apply_stack_strategy=receipt-declared-compatible-stack`, and `adapter_auto_apply_stack_count`, app.js verifies receipt stack fields and manifest-declared aggregate bytes before sequentially transferring each adapter, and generated-root browser smoke proves family ADP1 plus sparse ASP1 apply before generation; node syntax checks, cargo fmt check, adapter_family tests with 3 tests, selector tests with 25 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, generated all-root staging, generated q4 adapter-sidecar-registry-file smoke, server cleanup, port cleanup, workspace tests with 246 checks, static browser harness with 9 checks, and git diff whitespace check with line-ending notes only passed. - 2026-06-27 browser_runtime_manifest_verified: app.js verifies `runtime/tinyrustlm.wasm.manifest` before WASM instantiation, slm_pack writes runtime manifests for generated roots and exposes runtime-wasm-manifest for checked-root refresh, Build-TinyRustLM.ps1 refreshes the manifest after WASM copy, browser_harness treats the runtime manifest as a static and HTTP contract, and browser-smoke runtime-manifest-drift proves runtime checksum mismatch stops before model fetch; node syntax checks, PowerShell build-helper parse, cargo fmt check, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static harness with 9 checks, runtime-wasm-manifest CLI refresh, VS build helper run, generated all-root staging, source single smoke, runtime-manifest-drift smoke, generated q4 adapter-sidecar-registry-file smoke, temp profile cleanup, port cleanup, and workspace tests with 245 checks passed. - 2026-06-27 browser_text_sidecar_contract_verified: generated selector registries now carry exact selector registry, manifest, receipt, and evidence text budget fields; Rust validates the fields, app.js requires exact local matches before accepting registry entries, and browser-smoke sidecar-budget-contract proves text-budget drift falls back to tinylm16q8 before the drifted model route is fetched; node syntax checks, cargo fmt check, selector tests with 24 tests, browser_bundle tests with 3 tests, generated all-root staging, generated-root q4 adapter-sidecar-registry-file smoke, sidecar-budget-contract smoke, selector-budget regression smoke, multi-parent-registry regression smoke, adapter-sidecar-registry-q8 regression smoke, workspace tests with 244 checks, temp profile cleanup, and port cleanup passed. - 2026-06-27 browser_text_sidecar_budget_verified: app.js checks selector registry text at 256 KiB, manifest text at 64 KiB, receipt text at 128 KiB, and evidence text at 128 KiB before decoding; browser-smoke adapter-manifest-budget proves oversized generated sparse ASP1 manifest text stops exact artifact fetch and apply while model and assembly stay ready; node syntax checks, cargo fmt check, generated all-root staging, q4 adapter-sidecar-registry-file smoke, adapter-manifest-budget smoke, and workspace tests with 243 checks passed. - 2026-06-27 browser_auto_assembly_budget_verified: generated selector adapter-family routes now carry `adapter_auto_apply_byte_budget=1048576`, selector validation rejects budget drift above the local envelope, app.js requires the field, verifies generated adapter manifest `adapter_artifact_bytes`, checks auto-assembled module bytes before WASM transfer, and preserves manual checked sidecar routing; node syntax checks, cargo fmt checks, selector tests with 23 tests, adapter_family tests with 3 tests, browser_bundle tests with 3 tests, generated all-root staging, q4/q8/f32 generated-root smokes on port 18684, tinyq4 manual sidecar smoke on port 18685, workspace tests with 243 checks, git diff --check line-ending-only, temp profile cleanup, and port cleanup passed. - 2026-06-27 browser_auto_assembly_verified: generated selector adapter-family routes now carry `adapter_auto_apply_status=enabled` and `adapter_auto_apply_strategy=receipt-preferred-compatible`, selector validation rejects drift, app.js requires the fields before auto-applying the receipt-preferred sparse ASP1 after assembly/evidence/receipt/manifest verification, and browser-smoke adapter-sidecar-registry-file proves pre-generation apply; node syntax checks, cargo fmt checks, selector tests with 22 tests, adapter_family tests with 3 tests, browser_bundle tests with 3 tests, generated all-root staging, q4/q8/f32 generated-root smokes on port 18682, tinyq4 manual sidecar smoke and intercepted tinyq8 registry sidecar smoke on port 18683, and workspace tests with 242 checks passed. - 2026-06-27 browser_selector_budget_contract_verified: selector.rs writes and validates `selector_model_byte_budget=33554432`, rejects candidate_artifact_bytes above 32 MiB, app.js requires the registry budget before accepting entries, and browser-smoke fixtures carry the line; node syntax checks, cargo fmt check, selector tests with 21 tests, browser_bundle tests with 3 tests, multi-parent-registry and selector-budget smokes on port 18680, generated all-root staging plus q4 adapter-sidecar-registry-file smoke on port 18681, Rust browser harness, workspace tests with 241 checks, git diff --check line-ending-only, temp profile cleanup, and port cleanup passed. - 2026-06-27 browser_selector_budget_verified: app.js requires selector registry entries to carry positive decimal `entry.N.model_bytes` no larger than 32 MiB and checks fetched byte length before WASM transfer; browser-smoke selector-budget intercepts an oversized 33,554,433-byte q4_0 registry entry, proves it is not accepted, proves `/models/oversized-browser-parent.slm` is not requested, and falls back to tinylm16q8; node syntax checks, cargo fmt check, Rust browser harness with 8 checks, workspace tests with 239 checks, git diff --check line-ending-only, temp profile cleanup, and port cleanup passed. - 2026-06-27 browser_frugal_selector_default_verified: selector registries write browser-frugal-quantized default metadata that ranks q4_0 before q8_0 before f32; app.js validates the default candidate and quantization before selecting it; node syntax checks, cargo fmt check, selector tests with 23 filtered tests, browser_bundle tests with 3 filtered tests, generated all-root staging, q4/q8/f32 served-root smokes on port 18678 all observing initialSelectedModel=multi-parent-sign-merge-q4, workspace tests with 239 checks, git diff --check line-ending-only, temp profile cleanup, and port cleanup passed. - 2026-06-27 browser_multi_quant_selector_root_verified: browser-multi-parent-bundle `all` stages f32, q8_0, and q4_0 generated multi-parent modules into one runnable root with one selector.registry, 3 admissions, 9 adapter routes, 3 adapter-family receipts, and 3 assembly receipts; cargo fmt check, focused browser_bundle tests with 3 tests, workspace tests with 238 checks, generated all-root staging, and f32/q8_0/q4_0 served-root adapter-sidecar-registry-file smokes on port 18677 passed with receipt-preferred sparse ASP1 selected before apply. - 2026-06-27 browser_preferred_adapter_route_verified: generated adapter-family receipts carry preferred adapter index/path/manifest fields, app.js verifies the preferred member against receipt and manifest data before defaulting the adapter selector, and browser-smoke adapter-sidecar-registry-file now observes the browser-selected sparse ASP1 member without script selection; node syntax checks, cargo fmt check, focused adapter_family/browser_bundle tests, workspace tests with 237 checks, f32/q8_0 bundle staging, and f32/q8_0 served-root sparse ASP1 smokes passed. - 2026-06-27 browser_sparse_adapter_route_verified: generated browser bundles route self ADP1, family ADP1, and sparse ASP1 adapter-family members through selector.registry, served adapter-family receipts, served route-derived manifests, artifact checksum checks, and browser-smoke adapter-sidecar-registry-file; node syntax checks, cargo fmt, focused selector/adapter_family/browser_bundle tests, full slm_pack tests with 151 tests, WASM rebuild/copy, generated f32/q8_0/q4_0 bundle staging, f32 served-root sparse ASP1 smoke, and q8_0/q4_0 served-root sparse ASP1 smokes preserving active quantization passed. - 2026-06-27 sparse_adapter_package_verified: tinyrustlm-slm-pack writes and validates sparse ASP1 task-delta adapter packages with density, retention, sparse mask, parent identity, tokenizer, tensor layout, and adapter checksum fields; tinyrustlm-runtime parses ADP1 or ASP1 and applies compatible sparse packages to loaded f32, q8_0, or q4_0 tensors while preserving compact q8_0/q4_0 storage after re-quantization; cargo fmt check, runtime tests with 75 tests, adapter tests with 11 tests, full packer tests with 150 tests, and workspace tests with 236 tests passed. - 2026-06-27 file_backed_quantized_adapter_bundles_verified: browser-multi-parent-bundle accepts f32, q8_0, or q4_0; generated q8_0 and q4_0 roots served selector.registry, model, manifest, assembly receipt, nine evidence files, adapter-family receipt, two adapter manifests, and family ADP1 sidecars through browser-smoke adapter-sidecar-registry-file with selected quantization preserved after apply; Test-TinyRustLM.ps1 parses with f32/q8_0/q4_0 generated-root staging; node syntax checks, cargo fmt check, browser_bundle tests, full packer tests with 148 tests, workspace tests with 231 tests, Rust browser harness, WASM ABI smoke, dependency scan, public-copy scan, long-term ledger audit, git diff --check line-ending-only, and process checks passed. - 2026-06-27 quantized_registry_adapter_routes_verified: selector registries can carry local f32/q8_0/q4_0 ADP1 routes when apply status matches entry quantization; app.js validates registry adapter manifests against the selected entry quantization; node syntax checks, selector tests with 17 tests, adapter_family tests with 3 tests, full slm_pack tests with 147 tests, and browser-smoke adapter-sidecar-registry-q8 passed. - 2026-06-27 quantized_adapter_apply_verified: tinyrustlm-runtime applies compatible ADP1 packages to loaded f32, q8_0, and q4_0 models; q8_0/q4_0 apply re-quantizes compact tensors and clears generation/KV state; static tiny f32/q8/q4 sidecars are served from tinyrustlm/models and headless tinyq8/tinyq4 adapter-sidecar smokes passed. - 2026-06-27 population_objective_vector_metadata_verified: tinyrustlm-slm-pack population-review now writes weighted quality/frugality/quantization objective-vector fields, a contract checksum, and per-entry objective-vector checksums; validate-population-review recomputes them before parent-pool consumers; cargo fmt --all, cargo fmt --all -- --check, focused population tests with 7 tests, focused parent_pool tests with 7 tests, full packer tests with 145 tests, workspace tests with 223 tests, dependency-section scan, public-copy scan, and git diff --check line-ending-only passed. - 2026-06-27 parent_pool_relatedness_metadata_verified: tinyrustlm-slm-pack parent-pool-recipe now writes relatedness metric, scope, pair count, all-pairs status, shared relatedness checksum, and per-parent relatedness group fields; sign-merge receipts echo those fields and multi-parent candidate manifests carry the relatedness summary; cargo fmt --all, cargo fmt --all -- --check, focused parent_pool tests with 7 tests, focused sign_merge tests with 5 tests, focused multi_candidate tests with 5 tests, full packer tests with 144 tests, workspace tests with 222 tests, dependency-section scan, public-copy scan, and git diff --check line-ending-only passed. - 2026-06-27 sparse_delta_mask_metadata_verified: tinyrustlm-slm-pack sparse-delta-candidate receipts now bind density ppm, nonzero-delta retention ppm, unchanged/pruned counts, and an implicit top-k mask checksum; validate-sparse-delta-candidate recomputes the receipt and candidate bytes before candidate-manifest; cargo fmt checks, focused sparse_delta tests with 7 tests, CLI compatibility-lineage-sparse-delta-validate-sparse-delta chain, full packer tests with 143 tests, workspace tests with 221 tests, dependency-section scan, and public-copy scan passed. - 2026-06-27 registry_adapter_family_verified: selector registries can carry a local f32 adapter family through legacy first-route fields plus indexed adapter-family fields, browser-multi-parent-bundle writes self and family ADP1 packages plus manifests next to the generated model, and browser-smoke adapter-sidecar-registry-file selects the family route, verifies the local adapter request, adapter applied response, f32 diagnostics reset, and local-only requests; node syntax, cargo fmt --all -- --check, selector tests with 17 tests, browser_bundle test, slm_pack tests with 137 tests, Rust browser harness with 8 checks, WASM ABI smoke, cargo test --workspace with 215 tests, and generated served-root adapter-family smoke passed. - 2026-06-27 browser_adapter_sidecar_verified: static app exposes Adapter Sidecar for tinyf32, tinyq8, and tinyq4, fetches only matching local tinyrustlm/models/*.adp1 files, copies bytes into WASM without JS adapter parsing, calls apply_adapter_delta, and browser-smoke adapter-sidecar verifies adapter applied, matching diagnostics, cleared token/KV state, and local-only requests; node syntax checks, PS parse, cargo fmt checks, focused adapter/runtime/browser-harness tests, static browser harness, WASM ABI smoke, focused headless browser sidecar smoke, and cargo test --workspace with 211 tests passed. - 2026-06-27 runtime_adapter_apply_verified: tinyrustlm-runtime validates and applies compatible ADP1 packages against loaded f32, q8_0, and q4_0 model identity, payload checksums, tokenizer checksum, tensor layout checksum, tensor directory metadata, finite deltas, and fused values; q8_0/q4_0 apply re-quantizes compact tensors; apply_adapter_delta clears generation/KV diagnostics after success and the WASM ABI smoke builds a zero-delta package; cargo fmt checks, focused runtime adapter tests, node --check wasm-abi-smoke.js, wasm32 release build/copy, node wasm-abi-smoke.js, and cargo test --workspace with 211 tests passed. - 2026-06-27 browser_generated_multi_parent_bundle_verified: tinyrustlm-slm-pack browser-multi-parent-bundle writes multi-parent-sign-merge-f32.slm, its manifest, selector.registry, and evidence sidecars into a generated TinyRustLM root; browser-smoke multi-parent-registry-file loads the served registry, model, and manifest as real files; PowerShell parse, node --check browser-smoke.js, focused browser_bundle test, live file-backed browser smoke, cargo fmt checks, workspace tests with 207 tests, Rust browser harness, full Visual Studio BrowserSmoke, public-copy scan, dependency-section scan, and git diff --check line-ending-only passed. - 2026-06-27 browser_multi_parent_registry_smoke_verified: browser-smoke multi-parent-registry serves a local selector.registry fixture for multi-parent-sign-merge-q8, loads a q8_0 route through the browser selector, checks the single registry option, requests selector.registry, .slm, and .slm.manifest over loopback, and generates e; node --check browser-smoke.js, Test-TinyRustLM.ps1 parse check, focused headless browser smoke, cargo fmt --all -- --check, Rust browser harness, cargo test --workspace with 206 tests, public-copy scan, dependency-section scan, and git diff --check line-ending-only passed. - 2026-06-27 multi_parent_selector_registry_route_binding_verified: tinyrustlm-slm-pack selector-registry now consumes selector admission records and multi-parent admission records, selects the validator by admission version, preserves selector id, duplicate candidate/checksum, and served tinyrustlm/models route checks, and validate-selector-registry recomputes mixed-version registries; cargo fmt --all -- --check, focused selector tests with 9 tests, packer tests with 132 tests, workspace tests with 206 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, dependency-section scan, and git diff --check line-ending-only passed. - 2026-06-27 multi_parent_admission_record_gate_verified: tinyrustlm-slm-pack multi-parent-admission-record consumes a validated multi-parent promotion template, promotion ledger, population review, parent-pool recipe, sign-merge receipt, multi-parent candidate manifest, parent .slm files, candidate .slm file, provenance manifest, runtime-smoke sidecar, and passed eval sidecar, validates the full sign-merge promotion chain, then writes an evidence-passed multi-parent selector admission record with parent-pool, candidate, provenance, runtime, eval, and selector-registry route fields; validate-multi-parent-admission recomputes it; cargo fmt --all, cargo fmt --all -- --check, focused multi_admission tests with 6 tests, focused multi_promotion tests with 5 tests, focused packer tests with 129 tests, workspace tests with 203 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, dependency-section scan, and git diff --check line-ending-only passed. - 2026-06-27 multi_parent_promotion_template_gate_verified: tinyrustlm-slm-pack multi-parent-promotion-template consumes a validated multi-parent candidate manifest, sign-merge receipt, promotion ledger, population review, parent-pool recipe, admission records, parent .slm files, and candidate .slm file, validates the full sign-merge manifest chain, then writes a promotion template with candidate manifest checksum, operator receipt checksum, recipe checksum, parent count, candidate .slm fields, pending runtime-smoke/eval status, and not-admitted selector state; validate-multi-parent-promotion recomputes it; cargo fmt --all, cargo fmt --all -- --check, focused multi_promotion tests with 5 tests, focused multi_candidate tests with 5 tests, focused packer tests with 123 tests, workspace tests with 197 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, dependency-section scan, and git diff --check line-ending-only passed. - 2026-06-27 multi_parent_candidate_manifest_gate_verified: tinyrustlm-slm-pack multi-parent-candidate-manifest consumes a validated sign-merge candidate receipt, promotion ledger, population review, parent-pool recipe, admission records, parent .slm files, and candidate .slm file, validates the sign-merge receipt, then writes a candidate manifest with receipt checksum, recipe checksum, parent relatedness summary, parent summaries, candidate .slm fields, pending eval status, and next promotion route; validate-multi-parent-candidate recomputes it; cargo fmt --all, cargo fmt --all -- --check, focused multi_candidate tests with 5 tests, focused sign_merge tests with 5 tests, focused packer tests with 118 tests, workspace tests with 192 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, dependency-section scan, and git diff --check line-ending-only passed. - 2026-06-27 sign_merge_candidate_gate_verified: tinyrustlm-slm-pack sign-merge-candidate consumes a validated parent-pool recipe, promotion ledger, population review, admission records, and parent .slm files, writes a normal .slm candidate using seed-weighted sign consensus around the frontier base, echoes parent relatedness fields, and validate-sign-merge-candidate recomputes candidate bytes plus receipt before multi-parent-candidate-manifest; cargo fmt --all -- --check, focused sign_merge tests with 5 tests, focused packer tests with 113 tests, workspace tests with 187 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, and git diff --check line-ending-only passed. - 2026-06-27 parent_pool_recipe_gate_verified: tinyrustlm-slm-pack parent-pool-recipe consumes a validated promotion ledger, population review, and admission records, requires selected parents to share direct-parameter contract fields, writes ranked parent roles, fitness-normalized seed weights, and relatedness identity fields, and validate-parent-pool-recipe recomputes the recipe before sign-merge or other recipe consumers; cargo fmt --all -- --check, focused parent_pool tests with 6 tests, focused packer tests with 108 tests, workspace tests with 182 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, CLI promotion-ledger-population-review-parent-pool-recipe-validate-parent-pool-recipe chain, dependency-section scan, public-copy scan, and git diff --check line-ending-only passed. - 2026-06-27 sparse_delta_operator_gate_verified: tinyrustlm-slm-pack sparse-delta-candidate consumes compatibility, lineage, base and target .slm files, signed delta weight, and keep rate, writes a normal .slm candidate plus recomputable sparse task-delta receipt, and validate-sparse-delta-candidate recomputes selected absolute deltas, candidate bytes, and receipt before candidate-manifest; cargo fmt --all -- --check, focused sparse_delta tests with 6 tests, focused packer tests with 96 tests, workspace tests with 170 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, CLI q8 compatibility-lineage-sparse-delta-validate-candidate chain, dependency-section scan, public-copy scan, and git diff --check line-ending-only passed. - 2026-06-27 adapter_fuse_candidate_gate_verified: tinyrustlm-slm-pack fuse-adapter-delta consumes compatibility, lineage, base and target .slm files, an ADP1 adapter package, and its manifest, validates the package and manifest, writes a normal .slm candidate plus recomputable fuse receipt, and validate-fuse-adapter-delta recomputes both; cargo fmt --all -- --check, focused adapter tests with 9 tests, focused packer tests with 90 tests, workspace tests with 164 tests, strict slm_pack rustdoc, CLI compatibility-lineage-adapter-write-validate-fuse-validate chain, dependency-section scan, public-copy scan, and git diff --check line-ending-only passed. - 2026-06-27 adapter_delta_artifact_gate_verified: tinyrustlm-slm-pack adapter-delta consumes a passing compatibility report, validated lineage, compatibility-bound base and target .slm files, writes an ADP1 raw-f32-task-delta-v1 binary package plus manifest, and validate-adapter-delta recomputes bytes and manifest; cargo fmt --all -- --check, focused packer tests with 86 tests, workspace tests with 160 tests, strict slm_pack rustdoc, CLI q8 compatibility-lineage-adapter-write-validate chain, dependency-section scan, public-doc taboo scan, and git diff --check line-ending-only passed. - 2026-06-27 task_delta_operator_gate_verified: tinyrustlm-slm-pack delta-candidate consumes a passing compatibility report, validated lineage, compatibility-bound base and target .slm files, and signed parts-per-million delta weight, writes base plus weighted target-minus-base as a normal candidate .slm, and writes a recomputable operator receipt; validate-delta-candidate recomputes candidate bytes and receipt before candidate-manifest; cargo fmt --all -- --check, focused packer tests with 81 tests, workspace tests with 155 tests, strict slm_pack rustdoc, CLI q8 compatibility-lineage-delta-validate-delta-validate-candidate chain, CLI invalid delta weight refusal, dependency-section scan, public-doc taboo scan, and git diff --check line-ending-only passed. - 2026-06-27 promotion_ledger_gate_verified: tinyrustlm-slm-pack promotion-ledger consumes admitted selector admission records, rejects duplicate candidate ids and duplicate candidate checksums, writes a hash-chained promotion history, and validate-promotion-ledger recomputes it from admissions; cargo fmt --all -- --check, focused packer tests with 76 tests, workspace tests with 150 tests, strict slm_pack rustdoc, CLI converted-trained q8 compatibility-lineage-candidate-promotion-runtime-eval-admission-ledger chain, CLI ledger drift refusal, dependency-section scan, public-doc taboo scan, and git diff --check line-ending-only passed. - 2026-06-27 blend_operator_gate_verified: tinyrustlm-slm-pack blend-candidate consumes a passing compatibility report, validated lineage, compatibility-bound parent .slm files, and parent-0 parts-per-million weight, dequantizes compatible tensors as needed, writes a normal candidate .slm, and writes a recomputable operator receipt; validate-blend-candidate recomputes candidate bytes and receipt before candidate-manifest; cargo fmt --all -- --check, focused packer tests with 70 tests, workspace tests with 144 tests, strict slm_pack rustdoc, CLI q8 compatibility-lineage-blend-validate-blend-validate-candidate chain, CLI candidate-drift refusal, dependency-section scan, public-doc taboo scan, and git diff --check line-ending-only passed. - 2026-06-26 selector_registry_gate_verified: tinyrustlm-slm-pack selector-registry consumes selector admission records, requires admitted candidate artifact paths to resolve under served tinyrustlm/models routes, writes browser-safe ../models/*.slm entries, and validate-selector-registry rejects entry drift; app.js optionally loads models/selector.registry and falls back to deterministic smoke models when absent; cargo fmt --all -- --check, cargo test --workspace with 139 tests, strict rustdoc for slm_pack and browser_harness, focused packer tests with 65 tests, focused browser-harness tests with 6 tests, CLI converted-trained q8 admission-to-registry chain, CLI registry drift refusal, node syntax checks, Rust browser harness static contract, dependency-section scan, public-doc taboo scan, git diff --check line-ending-only, and dynamic loopback browser smoke with admitted-q8-self passed. - 2026-06-26 selector_admission_gate_verified: tinyrustlm-slm-pack runtime-smoke writes a durable execution sidecar bound to provenance manifest checksum, .slm checksum, source kind, and model shape; admission-record consumes compatibility, lineage, candidate .slm, candidate manifest, promotion template, provenance manifest, runtime-smoke sidecar, and passed eval sidecar, then emits a selector admission record with public claims bound to eval scope; validate-admission rejects runtime-smoke drift, eval drift, admission overclaims, and invalid selector ids; cargo fmt --all -- --check, strict slm_pack rustdoc, focused packer tests with 58 tests, workspace tests with 132 tests, CLI converted-trained q8 admission chain plus validation, CLI eval-drift refusal, public-doc taboo scan, and git diff --check line-ending-only passed. - 2026-06-26 candidate_promotion_gate_verified: tinyrustlm-slm-pack promotion-template consumes compatibility, lineage, candidate .slm, and candidate manifest inputs, records candidate manifest checksum, and keeps runtime-smoke, eval, browser selector, and public-claim statuses pending; validate-promotion rejects candidate manifest drift, candidate artifact drift, promotion overclaims, and invalid promoter ids; cargo fmt --all -- --check, strict slm_pack rustdoc, focused packer tests with 51 tests, workspace tests with 125 tests, CLI q8 promotion generation plus validation, CLI q4 refusal, empty dependency-section scan, public-doc taboo scan, and git diff --check passed. - 2026-06-26 candidate_artifact_gate_verified: tinyrustlm-slm-pack candidate-manifest consumes compatibility, lineage, and a candidate .slm, records lineage checksum plus candidate checksum/layout/admission fields, and validate-candidate rejects lineage drift, artifact drift, manifest drift, and q4 artifacts against q8 lineage; cargo fmt --all -- --check, strict slm_pack rustdoc, focused packer tests with 46 tests, workspace tests with 120 tests, CLI q8 candidate manifest generation plus validation, CLI q4 refusal, empty dependency-section scan, public-doc taboo scan, and git diff --check passed. - 2026-06-26 candidate_lineage_gate_verified: tinyrustlm-slm-pack lineage-template consumes passing parent compatibility reports, records compatibility checksum plus copied parent fields, initializes pending candidate artifact/eval fields, and validate-lineage rejects failed reports, checksum drift, parent drift, and malformed ids; cargo fmt --all -- --check, strict slm_pack rustdoc, focused packer tests with 41 tests, workspace tests with 115 tests, CLI q8 self-pair lineage generation plus validation, CLI q8/q4 refusal, empty dependency-section scan, public-doc taboo diff scan, and git diff --check passed. - 2026-06-26 parent_compatibility_gate_verified: tinyrustlm-slm-pack compatibility validates two .slm parents and emits a line-based parent-set report with checksums, shape, tokenizer checksum, tensor layout checksum, quantization, flags, and output-head contract; cargo fmt --all -- --check, packer rustdoc missing-docs gate, focused packer tests with 36 tests, workspace tests with 110 tests, CLI q8 self-pair report, CLI q8/q4 comparison, and empty dependency-section scan passed. - 2026-06-25 browser_step_token_control_verified: app HTML/CSS/JS now exposes a Step Token button that is disabled until generation context exists, calls generate_next_token, appends decoded text to response and latest TinyRustLM transcript turn, logs generate_next_token in the console, updates benchmark/diagnostics, disables after Reset/context errors/model failures, and stays enabled after transcript Clear. - Verification passed for browser_step_token_control: node --check app.js, node --check browser-smoke.js, cargo fmt --all -- --check, cargo test --workspace with 102 tests, Rust browser harness static contract with 8 checks, focused browser-smoke step-token on port 18450, and tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke -BrowserSmokePort 18460 -PortSearchLimit 5. - 2026-06-25 output_buffer_boundary_verified: generated result decode is capped at 64 KiB, byte/BPE bounded decode fails with OutputBufferExceeded before replacing caller output, full generate overflow clears stale token/generated-token diagnostics, rebuilt WASM sha256 is D81E95E5E596EF040A2258752FAB8A7B84B32E6729DD0CF600CFF37DD3EFADAF, and tools/vs/Test-TinyRustLM.ps1 passed. - 2026-06-25 milestone_29_tied_output_trained_source_conversion_verified: source-template supports tiny-fixture-tied and tinylm16-tied, validate-source accepts tied_output=true only with tied shape names, tied sources omit output.weight, and convert-trained emits f32/q8_0/q4_0 .slm artifacts with the v1 tied-output flag. - 2026-06-25 milestone_28_tied_output_slm_fixture_verified: tiny-test-model-tied.slm omits output.weight under the v1 tied-output flag, validates with its manifest, loads/generates through tok_embeddings projection, and browser/static contracts expose the fixture. - Runtime model loading now pre-resolves top-level and per-layer tensor indices, generation uses those indices without per-token layer-name formatting, and the tied-output projection flag routes logits through tok_embeddings when output.weight is absent. - Core math ops now have direct unit coverage for dot known output and mismatch rejection, matvec known output and mismatch rejection, matmul known output and mismatch rejection, RMSNorm, softmax sum and empty rejection, SiLU known values, and SwiGLU known output plus mismatch rejection. - TensorView and MutableTensorView now have direct unit coverage for shape validation, row-major flat indexing, mutable scratch writes, and element-count overflow rejection. - Runtime generation now allocates ForwardScratch and logits on model load, reuses their buffers across generate and repeated generate_next_token calls, and selects diagnostic top-k candidates without a vocab-sized Vec. - Stochastic sampling now scans logits into fixed 1024-candidate arrays for temperature/top-k/top-p/seed decoding, accepts BPE top_k 262, and rejects values above the fixed cap without a vocab-sized candidate Vec. - Generate request state now clears prompt/cache diagnostics at request start, rejects full-context prompts without stale generated counts or KV length, and extends token state after success so generate_next_token continues from generated output. - Custom BPE support now has an end-to-end tiny .slm fixture: packer mode tiny-fixture-bpe writes BPE1, runtime generation from prompt the records tokenizer output 256,261, and the browser/VS model contracts include the artifact. - WASM generate_next_token now returns explicit ErrorCode values, writes stepped token text to last_result, exposes selected token id through diagnostics, and free_model clears loaded-model state before post-free generation returns ModelNotLoaded. - Local conversation transcript is implemented in the static browser app; Generate appends User/TinyRustLM entries with DOM-safe text, Reset preserves history while clearing runtime context/output, and Clear empties history. - Cargo workspace now denies missing public Rust docs, and strict rustdoc gates passed for tinyrustlm-runtime plus the slm_pack, local_server, and browser_harness binaries. - cargo test --workspace passed with 102 tests, including 63 runtime tests, 28 slm_pack tests, 6 Rust browser-harness tests, and 5 Rust local-server tests; runtime coverage includes direct core math ops, pre-resolved tensor indices, artifact-backed tied-output projection, tensor view contracts, byte/BPE bounded decode overflow, runtime OutputBufferExceeded cleanup, tiny BPE runtime generation, BPE stochastic top_k 262, reusable generation buffer pointer stability, allocation-free top-k diagnostic selection, fixed-buffer stochastic sampling, context-boundary state cleanup, generate_next_token context continuation, free_model post-free rejection, checksum mismatch rejection, native .slm admission validation, provenance manifest validation, assistant-quality case-ledger validation, all-quantization untied and tied trained-source validation/conversion tests, tied_output/model_shape disagreement rejection, quantized tensor f32-borrow rejection, and diagnostics JSON escaping. - Rust mini browser harness static contract audit passed with 8 checks; loopback HTTP audit previously passed with 8 checks against the Rust local server. - Rust local server direct HTTP smoke passed for /app/, /runtime/tinyrustlm.wasm, /models/tinylm16-q8.slm, and /models/tinylm16-q8.slm.manifest with the trained-quality non-claim visible. - Quantized q8_0/q4_0 runtime tensors no longer keep full decoded f32 shadow copies; runtime generation uses reusable scratch through copy_tensor_f32 or copy_tensor_row_f32 for dequantization when needed. - CLI quality-gate passed runtime-smoke for the current tinylm16-q8 deterministic-smoke manifest. - CLI eval-template generated a pending assistant-quality sidecar for a converted-trained tiny fixture manifest, and quality-gate rejected it until reviewed task-eval, quality-boundary, and exact case-ledger evidence is supplied. - CLI source-template generated tinyrustlm/tests/fixtures/trained-source-tiny, validate-source accepted it, convert-trained emitted target/trained-source-smoke/tiny-converted-f32.slm, tiny-converted-q8.slm, and tiny-converted-q4.slm plus converted-trained manifests, and quality-gate accepted runtime-smoke plus fixture-scoped assistant-quality for each converted artifact. - CLI source-template generated target/trained-source-smoke/source-tiny-tied, validate-source accepted tied_output=true with tensor_count 11 and no output.weight, convert-trained emitted tied f32/q8_0/q4_0 .slm artifacts with manifests, and quality-gate accepted runtime-smoke for each tied converted artifact. - Default Visual Studio test helper validates strict rustdoc public-doc gates, the static app contract through the Rust browser harness, all eight local .slm artifacts, their .slm.manifest sidecars, the tiny untied trained-source fixture, converted-trained f32/q8_0/q4_0 outputs, converted manifests, runtime-smoke gates, fixture-scoped assistant-quality eval gates, the tied trained-source fixture, tied converted f32/q8_0/q4_0 runtime-smoke gates, and WASM ABI step/free smoke. - Build helper regenerates deterministic-smoke .slm.manifest sidecars whenever local models are regenerated or sidecars are missing. - node --check passed for app.js, static-server.js, and browser-smoke.js. - BrowserSmoke verifies q8 default, q4 selected, Step Token click-through, transcript entries and Clear-button state, reload/reset/model switch loop, malformed model, missing model, context overflow, desktop/mobile UI audit with Model Provenance sidecar fields, endurance, 47,104-byte scratch-backed q8/q4 generation, and local-only requests. - BrowserSmoke passed after diagnostics JSON escape hardening, so handwritten diagnostics remain parseable in browser benchmark and developer panels. - PerformanceSoak verifies repeated q8/q4 four-token UI generation, benchmark counts, token speed, scratch bytes, KV length, reset recovery, and local-only requests. - BrowserSmoke port helper passed verified-server reuse at 8080 after helper hardening. - Run helper passed unrelated busy-port fallback 18180 to 18181 and verified-server reuse on 18182; reuse was rechecked against the Rust local server on 18282. - Focused PerformanceSoak passed through Rust local-server startup on port 18291; low requested soak counts were clamped by browser-smoke to its two-cycle/two-token minimum. - Focused PerformanceSoak passed through Test-TinyRustLM.ps1 on port 18320 after the Rust browser harness was wired into both static and --http server-backed checks. - Full BrowserSmoke passed through Test-TinyRustLM.ps1 on port 18340 after the transcript implementation; only temporary Chrome profile cleanup notices remained. - Focused ui-audit passed through browser-smoke on port 18350 after adding Clear-click assertions; cleared snapshots kept response visible and emptied transcript history. - 2026-06-25 Test-TinyRustLM.ps1 passed after reusable generation buffer hardening; that evidence is superseded by the current 78-test assistant-quality case-ledger run with 8 static browser-harness checks, model/manifest validation, all converted-source quality gates, strict rustdoc, rebuilt WASM, and updated WASM ABI smoke. - Combined BrowserSmoke plus PerformanceSoak passed with three performance-soak q8/q4 cycles. - Combined BrowserSmoke plus PerformanceSoak passed after checksum-bearing .slm artifact regeneration. - Focused browser ui-audit passed after adding the Model Provenance panel; it verified same-origin `.slm.manifest` fetch, deterministic-smoke source kind, runtime-smoke admission, trained-quality non-claim, checksum display, required next gate, desktop/mobile layout, q8_0 generation, and local-only requests. - Raw report evidence copy verified 23 source files into raw/gguf-mirust/report-intake-2026-06-25/. - Raw report evidence copy verified 26 source files into raw/gguf-mirust/report-intake-2026-06-26/ for the model-breeding, code-beading, 4Fs, adapter, tiny-model, mutualist, and evolutionary batch. - Active handoff Content and Improvement buckets contain only .gitkeep after report processing. security_boundary: dropped_files: review_preserve_synthesize_then_clear_when_processed browser_actions: allowed_only_through_local_static_app_and_headless_smoke_harness model_files: local_static_slm_only_with_rust_validation_nonzero_checksum_match_and_native_admission_validation model_manifests: line_based_sidecars_required_for_local_artifacts_with_deterministic_smoke_or_converted_trained_quality_boundaries browser_manifest_display: app_js_may_parse_line_based_local_slm_manifest_sidecars_after_rust_accepts_the_model_but_must_not_parse_slm_model_bytes_or_replace_runtime_admission browser_transcript_display: app_js_may_render_local_conversation_history_with_dom_text_nodes; Reset must not imply transcript deletion, and Clear must not imply runtime reset. browser_step_token_display: app_js_may_call_generate_next_token_only_after_generation_context_exists; Step Token must append decoded local text to response/transcript/console and must disable after Reset or failed generation. browser_adapter_sidecar_display: app_js_may_call_apply_adapter_delta_only_after_a_loaded_model_exists; generated_auto_stacks_must_validate_all_fetched_members_before_first_apply; adapter routes must stay local_adp1_paths_and_js_must_transfer_bytes_without_parsing_payloads wasm_step_token_abi: generate_next_token_returns_error_code_last_result_carries_decoded_token_text_diagnostics_carry_selected_token_id_validate_adapter_delta_returns_error_code_and_preserves_generation_state_apply_adapter_delta_returns_error_code_and_free_model_must_make_post_free_generation_fail_model_not_loaded runtime_adapter_apply: adp1_packages_must_match_loaded_f32_q8_q4_model_identity_payload_checksums_tokenizer_checksum_tensor_layout_checksum_tensor_directory_and_fused_values_before_validation_or_mutation_then_clear_generation_state_on_successful_apply browser_adapter_sidecar: checked_tiny_f32_q8_q4_self_adp1_routes_must_remain_local_and_browser_smoke_adapter_sidecar_must_verify_matching_quantization_state_reset_after_apply browser_registry_adapter_family: generated_registry_adapter_family_routes_must_remain_local_f32_q8_q4_adp1_asp1_or_alr1_paths_with_paired_manifests_indexed_selector_fields_browser_verified_receipts_and_explicit_auto_apply_fields_when_preferred_receipt_assembly_is_expected browser_selector_budget: selector_registries_must_carry_selector_model_byte_budget_33554432_entries_must_carry_decimal_model_bytes_within_that_budget_before_fetch_and_registry_model_fetches_must_match_declared_byte_count_before_wasm_transfer browser_text_sidecars: selector_registry_manifest_receipt_and_evidence_text_must_be_length_checked_before_decode_or_parse_generated_selector_registries_must_declare_exact_matching_text_budget_contract_fields_and_oversized_or_drifted_text_sidecars_must_not_fetch_or_apply_the_adapter_artifact browser_runtime_wasm_manifest: runtime_tinyrustlm_wasm_manifest_must_match_runtime_wasm_path_byte_count_checksum_kind_status_and_next_gate_before_webassembly_instantiate_checked_and_generated_roots_must_refresh_the_manifest_after_wasm_copy_or_bundle_staging browser_module_plan: generated_selector_entries_with_module_plan_fields_must_fetch_and_checksum_verify_the_served_module_plan_before_generated_slm_fetch_and_the_plan_must_match_profile_execution_profile_fetch_policy_tokenizer_checksum_sampler_candidate_cap_resource_class_model_byte_budget_adapter_byte_budget_runtime_scratch_byte_budget_model_manifest_assembly_receipt_adapter_family_receipt_module_roles_module_assembly_slots_module_dependencies_and_ordered_adapter_stack_members; the_module_plan_panel_must_render_only_verified_receipt_fields_including_visible_execution_fetch_tokenizer_sampler_cap_model_adapter_scratch_budget_rows_slot_summary_role_summary_dependency_summary_and_trace_checkpoints; browser_smoke_module_plan_execution_profile_drift_module_plan_fetch_policy_drift_module_plan_tokenizer_drift_module_plan_sampler_cap_drift_module_plan_runtime_scratch_drift_module_plan_resource_drift_module_plan_graph_drift_module_plan_stack_drift_module_plan_role_drift_module_plan_slot_drift_module_plan_dependency_drift_and_assembly_eval_case_drift_must_prove_checksum_consistent_receipt_drift_stops_before_generated_slm_evidence_or_stack_artifact_fetch browser_module_plan_adapter_validation: generated_selector_entries_and_module_plan_receipts_must_match_module_plan_adapter_validation_strategy_rust_validate_before_apply_v1; the_Module_Plan_panel_must_render_Validate_from_verified_receipt_fields; browser_smoke_module_plan_adapter_validation_drift_must_stop_before_generated_model_routes browser_module_plan_adapter_validation_count: generated_selector_entries_and_module_plan_receipts_must_match_module_plan_adapter_validation_count_3; the_Module_Plan_panel_must_render_Validate_Count_from_verified_receipt_fields; generated_assembly_must_count_three_Rust_validate_adapter_delta_calls_before_three_apply_adapter_delta_calls; browser_smoke_module_plan_adapter_validation_count_drift_must_stop_before_generated_model_routes browser_module_plan_adapter_apply_count: generated_selector_entries_and_module_plan_receipts_must_match_module_plan_adapter_apply_count_3; the_Module_Plan_panel_must_render_Apply_Count_from_verified_receipt_fields; generated_assembly_must_match_runtime_adapter_apply_count_diagnostics; browser_smoke_module_plan_adapter_apply_count_drift_must_stop_before_generated_model_routes browser_module_plan_phases: generated_module_plan_receipts_must_match_expected_phase_values_before_generated_slm_fetch; the_module_plan_panel_must_render_verified_phase_summary; browser_smoke_module_plan_phase_drift_must_prove_checksum_consistent_phase_drift_stops_before_generated_slm_or_stack_artifact_fetch browser_assembly_trace: generated_module_plan_trace_must_reset_on_model_load_and_record_plan_verified_model_accepted_manifest_verified_assembly_evidence_verified_adapter_family_verified_adapter_stack_applied_and_ready_only_after_each_stage_completes generation_allocation_boundary: scratch_logits_and_tensor_indices_are_model_loaded_runtime_state_reused_across_generate_and_generate_next_token_top_k_diagnostics_and_stochastic_sampling_do_not_allocate_vocab_sized_candidate_vectors output_result_boundary: generated_result_decode_is_capped_at_64_kib_and_output_buffer_exceeded_must_not_replace_previous_decode_output_or_leave_stale_full_generate_state generation_state_boundary: failed_generate_requests_clear_prompt_cache_diagnostics_and_successful_generate_extends_tokens_for_step_token_continuation source_weights: raw_f32_source_manifest_layout_required_before_convert_trained_safe_relative_paths_exact_shapes_checksums_finite_bounded_nonzero_weights_and_tied_output_model_shape_agreement quality_gates: runtime-smoke allowed for execution evidence; assistant-quality requires converted-trained provenance plus a matching passed eval sidecar with positive case count, zero failures, and exact per-case expected/actual matches. network: no_remote_inference_no_cdn_no_telemetry report_guidance: design_pressure_only_until_converted_to_source_change_or_testable_invariant model_breeding_guidance: offline_candidate_lineage_only_with_tinyrustlm_slm_pack_compatibility_reports_validated_lineage_templates_validated_blend_task_delta_sparse_delta_crossover_mutation_prune_federated_or_sign_merge_operator_receipts_operator_receipt_bound_candidate_artifact_manifests_validated_adapter_delta_manifests_validated_adapter_fuse_receipts_validated_runtime_f32_q8_q4_adp1_apply_validated_candidate_artifact_manifests_validated_multi_parent_candidate_manifests_validated_promotion_sidecars_validated_multi_parent_promotion_sidecars_validated_multi_parent_admission_records_validated_runtime_smoke_sidecars_validated_selector_admission_records_validated_promotion_ledgers_validated_population_reviews_with_objective_vectors_validated_parent_pool_recipes_validated_sign_merge_receipts_validated_selector_registries_combined_multi_quant_browser_selector_roots_browser_frugal_selector_defaults_browser_selector_byte_budgets_registry_controlled_auto_assembly_combined_selector_assembly_smoke_and_diverse_research_lanes_before_selector_claims site_voice: public_copy_routes_through_uai_taboo_for_constructive_local_model_craft operations_notes: - Chrome may leave temporary tinyrustlm-browser-smoke-* profiles; remove only matching directories under %TEMP% after verifying no matching browser process remains. - Keep the Rust local server on port 8080 for TinyRustLM unless occupied; Visual Studio helpers can use an existing verified TinyRustLM server or fall forward to the next free loopback port. - Use PerformanceSoak after runtime, model-selection, benchmark-panel, or reset changes that could hide multi-cycle performance regressions. - Use tinyrustlm-browser-harness before browser smoke after app, model selector, manifest, local server, or public claim changes; use --http when a local server is already running. - Use the strict rustdoc gates after changing public Rust APIs or Visual Studio test wrapper behavior; missing_docs is a workspace error, not a soft style notice. - Use sampler unit tests and WASM ABI smoke after changing temperature/top-k/top-p/seed behavior; stochastic sampling must stay fixed-buffer and reject oversized top_k values. - Use context-boundary and step-token tests after changing Runtime.generate; failed requests must not leak stale diagnostics or stale token state. - Use output-buffer tests after changing tokenizer decode or Runtime.generate result handling; OutputBufferExceeded must keep caller output stable and clear full-generate stale state. - Use wasm-abi-smoke after changing WASM exports, generation state, model-free behavior, diagnostics, memory transfer, adapter apply, or Visual Studio test wrapper behavior; step-token, adapter-apply, and post-free semantics are part of the ABI contract. - Use browser-smoke step-token after changing app.js control state, response rendering, transcript continuation, benchmark timing, or generate_next_token browser wiring. - Use browser-smoke adapter-sidecar for tinyf32, tinyq8, and tinyq4 after changing Adapter Sidecar UI, local .adp1 route filtering, app.js WASM byte transfer, apply_adapter_delta result handling, or runtime adapter state reset. - Use browser-smoke adapter-sidecar-registry-file after changing selector registry adapter fields, indexed adapter-family fields, browser-multi-parent-bundle adapter staging, generated registry route parsing, combined multi-quant selector roots, auto-assembly behavior, or file-backed adapter route behavior; for generated auto assembly, assert adapter state applied before generation. - Use browser-smoke selector-budget after changing selector registry intake, `selector_model_byte_budget`, `entry.N.model_bytes` parsing, fallback model behavior, or pre-WASM model byte transfer checks. - Use browser-smoke sidecar-budget-contract after changing selector registry text budget fields, text-sidecar budget constants, generated registry headers, or app.js registry budget intake. - Use browser-smoke runtime-manifest-drift after changing runtime WASM manifest fields, checked-runtime build/copy flow, browser boot sequencing, static runtime route handling, or generated browser-bundle runtime staging. - Use browser-smoke adapter-sidecar-registry-file after changing selector module-plan fields, generated `.module-plan.receipt` staging, app.js plan verification, module-plan resource envelopes, module roles, module dependency edges, or browser module graph routing; the network trace must include the plan route before the generated `.slm` route. - Use browser-smoke combined-selector-assembly after changing combined multi-quant selector roots, q4_0 default behavior, generated all-root switching, module-plan ordering, or generated auto-assembly behavior across q4_0/q8_0/f32 in one page. - Use browser-smoke combined-selector-route-soak after changing local fetch cache behavior, generated all-root route-count assertions, or longer q4_0/q8_0/f32 selector-route reuse; it should run three cycles and count every generated self-assembly route once per pass. Use combined-selector-route-extended-soak when the change needs five-cycle route pressure or path-flexible total-budget checks on a non-canonical generated root. Use combined-selector-route-stress-soak when the change needs eight-cycle route pressure. - Use browser-smoke combined-selector-assembly after changing Module Plan Trace checkpoints or ready sequencing; the generated q4_0/q8_0/f32 entries must each render the exact trace before generation. - Use browser-smoke assembly-eval-case-drift after changing selector or generated assembly receipt eval-case digest matching; the network trace must include selector, module-plan, model, manifest, and assembly receipt routes while omitting evidence, adapter-family, adapter manifest, and stack routes. - Use browser-smoke module-plan-resource-drift after changing module-plan resource envelopes, receipt checksums, selector module-plan checksums, or app.js module-plan budget validation; the network trace must include the plan route and omit the generated `.slm` route. - Use browser-smoke module-plan-wasm-memory-drift after changing WASM instantiation order, runtime memory export handling, selector module-plan WASM page fields, or the Module Plan `WASM Pages` display; the network trace must include the plan route and omit the generated `.slm` route. - Use browser-smoke module-plan-wasm-export-set-drift after changing WASM exports, browser export checks, selector module-plan WASM ABI fields, or the Module Plan `WASM ABI` display; the network trace must include the plan route and omit the generated `.slm` route. - Use browser-smoke module-plan-wasm-heap-drift after changing WASM allocation probes, selector module-plan heap-floor fields, generated receipt heap-floor fields, or the Module Plan `Heap Floor` display; the network trace must include the plan route and omit the generated `.slm` route. - Use browser-smoke module-plan-graph-drift after changing module-plan model, manifest, receipt, or stack graph validation; the network trace must include the plan route and omit the generated `.slm` route. - Use browser-smoke module-plan-stack-drift after changing module-plan stack member path or manifest validation; the network trace must include the plan route and omit generated `.slm`, ADP1, ASP1, and adapter-manifest routes. - Use browser-smoke module-plan-role-drift after changing module-plan role validation; the network trace must include the plan route and omit generated `.slm`, ADP1, ASP1, and adapter-manifest routes. - Use browser-smoke module-plan-slot-drift after changing module-plan assembly-slot validation; the network trace must include the plan route and omit generated `.slm`, ADP1, ASP1, and adapter-manifest routes. - Use browser-smoke module-plan-dependency-drift after changing module-plan dependency validation; the network trace must include the plan route and omit generated `.slm`, ADP1, ASP1, and adapter-manifest routes. - Use browser-smoke module-plan-phase-drift after changing module-plan phase validation; the network trace must include the plan route and omit generated `.slm`, ADP1, ASP1, and adapter-manifest routes. - Use browser-smoke ui-audit and generated-root adapter-sidecar-registry-file after changing the Module Plan panel, rendered receipt fields, slot display, role display, dependency display, or stack display; source fallback state should be `none`, and generated roots should show loaded receipt metadata. - Use browser-smoke ui-audit and generated-root adapter-sidecar-registry-file after changing Module Plan phase display; source fallback phase state should be `unavailable`, and generated roots should show the ordered phase summary from the verified receipt. - Use browser-smoke ui-audit after app HTML/CSS/JS changes that affect product identity, layout, panels, controls, diagnostics, or benchmark visibility. - Use browser-smoke ui-audit after conversation transcript changes; it must verify empty ready state, generated entries, Clear-click removal, response preservation, and Clear-button state on desktop and mobile. - Use browser-smoke ui-audit after manifest/provenance UI changes; the audit must keep `.slm.manifest` requests same-origin and keep trained-quality non-claim visible until real evidence exists. - Use browser-smoke multi-parent-registry after selector-registry, app.js registry parsing, model selector, manifest routing, or multi-parent admission route changes; use selector-operator-receipt-drift after federated compact operator receipt validation changes; use prune-operator-registry/prune-operator-receipt-drift, dare-operator-registry/dare-operator-receipt-drift, crossover-operator-registry/crossover-operator-receipt-drift, and mutation-operator-registry/mutation-operator-receipt-drift after compact operator fixture or browser Operator row changes; use multi-parent-registry-file plus browser-multi-parent-bundle before claiming a generated served multi-parent artifact route, and add adapter-sidecar-registry-file before claiming generated model-plus-adapter-family routing. - Use tinyrustlm-slm-pack validate on every generated or converted .slm file before serving it through the browser app. - Use tinyrustlm-slm-pack compatibility before treating two .slm files as a direct-parameter model-breeding or assembly parent set; q8/q4 pairs should route through source conversion or distillation unless a future operator creates a new admitted candidate. - Use tinyrustlm-slm-pack lineage-template after a passing compatibility report, then validate-lineage before any direct-parameter operator writes a candidate .slm, adapter artifact, manifest, or eval sidecar. - Use tinyrustlm-slm-pack blend-candidate only after validate-lineage; use validate-blend-candidate before candidate-manifest so the operator receipt recomputes the candidate bytes from parent checksums and blend weights. - Use tinyrustlm-slm-pack delta-candidate only after validate-lineage when task-vector arithmetic is the chosen direct-parameter operator; use validate-delta-candidate before candidate-manifest so the operator receipt recomputes candidate bytes from base and target parent checksums plus signed delta weights. - Use tinyrustlm-slm-pack sparse-delta-candidate only after validate-lineage when sparse task-vector arithmetic is the chosen direct-parameter operator; use validate-sparse-delta-candidate before candidate-manifest so selected deltas, candidate bytes, and receipt recompute from compatibility-bound parents plus keep rate. - Use tinyrustlm-slm-pack crossover-candidate only after validate-lineage when deterministic element-wise parent selection is the chosen direct-parameter operator; use validate-crossover-candidate before candidate-manifest so seed, parent0 keep rate, parent checksums, selected counts, densities, mask checksum, candidate bytes, and receipt recompute from compatibility-bound parents. - Use tinyrustlm-slm-pack mutation-candidate only after validate-lineage when deterministic bounded perturbation is the chosen direct-parameter operator; use validate-mutation-candidate before candidate-manifest so seed, rate, magnitude, reference scaling, selection checksum, delta checksum, candidate bytes, and receipt recompute from compatibility-bound parents. - Use tinyrustlm-slm-pack prune-candidate only after validate-lineage when deterministic magnitude pruning is the chosen direct-parameter operator; use validate-prune-candidate before candidate-manifest so keep/floor ppm, selected/pruned counts, mask checksum, output-value checksum, candidate bytes, and receipt recompute from compatibility-bound parents. - Use tinyrustlm-slm-pack dare-candidate only after validate-lineage when DARE-style dropout/rescaled task-delta arithmetic is the chosen direct-parameter operator; use validate-dare-candidate before candidate-manifest so signed delta weight, keep/drop ppm, dropout seed, mask checksum, raw delta checksum, rescaled delta checksum, candidate bytes, and receipt recompute from compatibility-bound parents. - Use tinyrustlm-slm-pack federated-candidate only after validate-lineage when parent 0 is the base/global artifact and parent 1 is a compatible local-update artifact; use validate-federated-candidate before candidate-manifest so local_update_weight_ppm, local-update counts, raw delta checksum, weighted delta checksum, candidate bytes, and receipt recompute from compatibility-bound parents. - Use tinyrustlm-slm-pack adapter-delta only after validate-lineage when a modular task-delta package is the chosen artifact; use validate-adapter-delta before fuse-adapter-delta or runtime f32/q8_0/q4_0 apply so adapter bytes and manifest recompute from compatibility-bound parents. - Use tinyrustlm-slm-pack sparse-adapter-delta only after validate-lineage when a compact modular task-delta package is the chosen artifact; use validate-sparse-adapter-delta so ASP1 bytes, density, retention, mask checksum, and manifest recompute from compatibility-bound parents. - Use tinyrustlm-slm-pack low-rank-adapter-delta only after validate-lineage when a compact low-rank matrix task-delta package is the chosen artifact; use validate-low-rank-adapter-delta so ALR1 bytes, factor metadata, residual-L1 fields, and manifest recompute from compatibility-bound parents. - Use tinyrustlm-slm-pack fuse-adapter-delta only after validate-adapter-delta when an adapter package should become a normal .slm candidate; use validate-fuse-adapter-delta before candidate-manifest so candidate bytes and receipt recompute from compatibility-bound parents and adapter package. - Use Runtime::validate_adapter_delta and Runtime::apply_adapter_delta only for compatible ADP1, ASP1, or ALR1 packages against a loaded f32, q8_0, or q4_0 model; after changing this boundary, run focused runtime adapter tests, rebuild WASM when the ABI changes, run wasm-abi-smoke for exported ABI changes, and run generated adapter-sidecar-registry-file plus combined-selector-assembly browser smokes for browser route changes. - Use runtime assembly diagnostics after changing model load/free, adapter apply, diagnostics JSON, or browser stack assertions; model load should report nonzero assembly state with zero adapter applies, each accepted adapter should increment `adapter_apply_count` and set nonzero checksums, and free/load failure should clear assembly state. - Use the checked browser Adapter Sidecar route only for local .adp1 files under tinyrustlm/models; generated adapter-family routes may include local .adp1, .asp1, and .alr1 files under the served generated models root. After changing either route class, run Rust browser harness and the matching browser-smoke mode. - Use tinyrustlm-slm-pack candidate-manifest after a validated lineage and produced .slm; validate-candidate before runtime-smoke, eval sidecars, promotion records, browser selectors, or public support claims. - Use tinyrustlm-slm-pack promotion-template after a validated candidate manifest; validate-promotion before any browser selector, model route, public support claim, or promotion ledger entry. - Use tinyrustlm-slm-pack runtime-smoke after validate-manifest when a durable execution sidecar is needed; validate-runtime-smoke before feeding runtime evidence into admission-record. - Use tinyrustlm-slm-pack admission-record only after validate-promotion, validate-runtime-smoke, and a passed converted-trained eval sidecar; validate-admission before selector-registry or browser route consumes a bred candidate. - Use tinyrustlm-slm-pack promotion-ledger after validate-admission when admitted candidates need a durable promotion history; validate-promotion-ledger before selector or population review consumes the ledger. - Use tinyrustlm-slm-pack population-review after validate-promotion-ledger when a ledger needs frontier and parent-pool routing with weighted objective-vector metadata; validate-population-review before parent-pool-recipe consumes the review. - Use tinyrustlm-slm-pack parent-pool-recipe after validate-population-review when reviewed candidates need a shared-contract parent recipe; validate-parent-pool-recipe before any recipe consumer. - Use tinyrustlm-slm-pack sign-merge-candidate after validate-parent-pool-recipe when reviewed parents need a seed-weighted sign-consensus .slm candidate; validate-sign-merge-candidate before multi-parent-candidate-manifest consumes the output. - Use tinyrustlm-slm-pack multi-parent-candidate-manifest after validate-sign-merge-candidate or validate-soup-candidate when a parent-pool operator output needs a candidate manifest; validate-multi-parent-candidate before runtime-smoke, eval, admission, ledger, or selector work consumes the output. - Use tinyrustlm-slm-pack multi-parent-promotion-template after validate-multi-parent-candidate when sign-merge output needs a runtime-smoke/eval handoff; validate-multi-parent-promotion before runtime-smoke, eval, admission, ledger, or selector work consumes the output. - Use tinyrustlm-slm-pack multi-parent-admission-record after validate-multi-parent-promotion, validate-manifest, validate-runtime-smoke, and passed converted-trained eval evidence when sign-merge output needs an evidence-passed admission record; validate-multi-parent-admission before selector-registry consumes the output. - Use tinyrustlm-slm-pack selector-registry after validate-admission or validate-multi-parent-admission when admitted artifacts are staged under served tinyrustlm/models routes; validate-selector-registry plus browser-smoke multi-parent-registry before selector-logic claims, and browser-multi-parent-bundle plus browser-smoke multi-parent-registry-file plus adapter-sidecar-registry-file before generated file-backed model-plus-adapter route claims. Use browser-multi-parent-bundle `all` plus f32/q8_0/q4_0 adapter-sidecar-registry-file smokes before claiming one served root can switch among all three generated modules, require initialSelectedModel q4 when combined roots carry browser-frugal-quantized defaults, run combined-selector-assembly before claiming same-page q4_0/q8_0/f32 self-assembly from one served root, and run selector-budget when registry model-byte intake changes. - Use tinyrustlm-slm-pack validate-manifest on every generated or converted .slm sidecar before treating an artifact as admitted. - Use tinyrustlm-slm-pack validate-source before convert-trained; do not treat unchecked source weights as eligible for converted-trained provenance. - Use tied source-template and runtime-smoke conversion gates after changing output-head layout behavior; tied conversion omits output.weight and does not imply assistant-quality evidence. - Use tinyrustlm-slm-pack quality-gate runtime-smoke for execution-only claims and quality-gate assistant-quality with a passed eval sidecar before any trained assistant-quality claim. - After quality-gate or eval-runner changes, run focused provenance/eval tests, cargo test --workspace, and tools/vs/Test-TinyRustLM.ps1 so converted f32/q8_0/q4_0 eval sidecars are regenerated and revalidated. - Before model-breeding source work, read wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md and wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md. - Before report or research memory work, audit active buckets, update short-term routes, refresh long-term pointer checksums, and verify report/research wiki pages are represented in .uai/long-term-memory.uai. - Before public copy or model-breeding positioning edits, read .uai/taboo.uai. - Do not revive legacy Axum or GGUF scaffold commands from older memory. ================================================================================ END FILE: .uai/operations.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/receiver-brief.uai BYTES: 3449 SHA256: DBF2149881208F3A586752776494DB57AC2CF8932BBF2D1D6B4A5AD13BE9D4D6 ================================================================================ profile: gguf-mirust.receiver-brief.v13 updated_utc: 2026-06-29T01:39:45Z brief: GGUF.MiRust.com now contains TinyRustLM, a zero-dependency Rust/WASM browser-local SLM runtime and UI with ADP1/ASP1/ALR1 runtime adapter validation and apply, Rust-owned runtime assembly diagnostics, browser-routed ADP1/ASP1/ALR1 adapter-family stacks with pre-WASM full-stack byte preflight plus Rust semantic validation before apply, browser-verified module-plan receipts with `browser-constrained-v1` profile, `single-threaded-wasm-local-v1` execution profile, `local-no-store-v1` fetch policy, `same-origin-loopback-local-v1` origin policy, and `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1`, assembly traces, eval-case evidence checksum display, assembly eval-digest proof, fetched evidence-file integrity proof, generated q4/q8/f32 selector roots, and route-soak proof for generated self-assembly routes. Model Breeding routes through durable research, report synthesis, short-term routes, checksum pointers, and concept lanes for heritable artifacts, mate selection, phenotype evidence, and local fit until source and tests prove concrete runtime support. must_read: - AGENTS.md - workspace.uai - .uai/workspace-guidance.uai - .uai/file-handoff.uai - .uai/long-term-memory.uai - .uai/test-plan.uai - .uai/report-synthesis.uai - .uai/taboo.uai - tinyrustlm/README.md - wiki/gguf-mirust/reports/report-intake-index-2026-06-25.md - wiki/gguf-mirust/reports/report-intake-index-2026-06-26.md - wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md - wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md - docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md - wiki/gguf-mirust/reports/low-rank-adapter-package-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-assembly-trace-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-eval-case-evidence-checksum-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-assembly-eval-case-drift-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-assembly-evidence-file-drift-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-runtime-assembly-diagnostics-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md do_not: - Create agent-file-handoff/Archive/ as default memory. - Store durable reports inside .uai/long-term-memory.uai. - Claim trained-quality model behavior, GGUF import, Mini Browser automation, WebGPU acceleration, or remote inference support from report memory alone. - Store report bodies in .uai/short-term-memory.uai; it should route to durable report/research nodes and the long-term pointer ledger. - Claim trained LoRA support, broader adapter formats, or population training until implementation and tests exist. ================================================================================ END FILE: .uai/receiver-brief.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/report-synthesis.uai BYTES: 79569 SHA256: 6FB4A26126EFB84A62611C3ABD2AECD4388F5ADFD6773BFA1249568493B4A81D ================================================================================ profile: gguf-mirust.report-synthesis.v87 updated_utc: 2026-06-29T20:22:33Z purpose: Hot .uai synthesis of processed Improvement reports, distributed for agent startup without requiring immediate bulk loading of wiki Markdown. source_authority: raw_evidence: raw/gguf-mirust/report-intake-2026-06-25/ raw_evidence_2026_06_26: raw/gguf-mirust/report-intake-2026-06-26/ raw_evidence_2026_06_28: raw/gguf-mirust/report-intake-2026-06-28/ raw_manifest: raw/gguf-mirust/MANIFEST.md durable_index: wiki/gguf-mirust/reports/report-intake-index-2026-06-25.md durable_index_2026_06_26: wiki/gguf-mirust/reports/report-intake-index-2026-06-26.md durable_index_2026_06_28: wiki/gguf-mirust/reports/report-intake-index-2026-06-28.md durable_synthesis: - wiki/gguf-mirust/reports/enterprise-rust-governance-memory-2026-06-25.md - wiki/gguf-mirust/reports/browser-local-runtime-memory-2026-06-25.md - wiki/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25.md - wiki/gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25.md - wiki/gguf-mirust/reports/brand-product-positioning-memory-2026-06-25.md - wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md - wiki/gguf-mirust/reports/runtime-adapter-apply-memory-2026-06-27.md - wiki/gguf-mirust/reports/sparse-adapter-package-memory-2026-06-27.md - wiki/gguf-mirust/reports/low-rank-adapter-package-memory-2026-06-28.md - wiki/gguf-mirust/reports/trained-adapter-source-memory-2026-06-28.md - wiki/gguf-mirust/reports/trained-adapter-source-alr1-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-low-rank-adapter-route-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-source-backed-alr1-route-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-source-backed-alr1-contract-memory-2026-06-28.md - wiki/gguf-mirust/reports/two-parent-operator-browser-provenance-memory-2026-06-29.md - wiki/gguf-mirust/reports/mutation-operator-memory-2026-06-29.md - wiki/gguf-mirust/reports/dare-operator-memory-2026-06-29.md - wiki/gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-converted-trained-provenance-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-converted-trained-file-route-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-converted-trained-all-route-memory-2026-06-29.md - wiki/gguf-mirust/reports/federated-operator-memory-2026-06-29.md - wiki/gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-parent-pool-soup-bundle-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-mixed-operator-selector-memory-2026-06-29.md - wiki/gguf-mirust/reports/parent-pool-evolution-schedule-memory-2026-06-29.md - wiki/gguf-mirust/reports/operator-schedule-carry-forward-memory-2026-06-29.md - wiki/gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29.md - wiki/gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29.md - wiki/gguf-mirust/reports/admission-operator-receipt-binding-memory-2026-06-29.md - wiki/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-adapter-sidecar-memory-2026-06-27.md - wiki/gguf-mirust/reports/registry-adapter-sidecar-memory-2026-06-27.md - wiki/gguf-mirust/reports/registry-adapter-family-memory-2026-06-27.md - wiki/gguf-mirust/reports/adapter-family-receipt-memory-2026-06-27.md - wiki/gguf-mirust/reports/assembly-receipt-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-sparse-adapter-route-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-preferred-adapter-route-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-multi-quant-selector-root-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-frugal-selector-default-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-selector-budget-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-selector-budget-contract-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-auto-assembly-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-auto-assembly-budget-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-text-sidecar-budget-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-text-sidecar-contract-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-runtime-manifest-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-adapter-stack-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-resource-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-resource-drift-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-graph-drift-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-stack-drift-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-role-drift-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-display-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-budget-display-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-role-display-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-slots-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-dependencies-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-phases-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-byte-counts-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-module-plan-checksums-memory-2026-06-27.md - wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-combined-selector-stress-route-soak-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-assembly-trace-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-eval-case-evidence-checksum-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-selector-genome-fitness-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-selector-population-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-assembly-eval-case-drift-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-assembly-evidence-file-drift-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-adapter-family-receipt-drift-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-adapter-manifest-drift-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-output-limit-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-total-budget-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-wasm-memory-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-wasm-heap-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-model-release-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-runtime-reset-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-count-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-planned-fetch-count-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-actual-fetch-count-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-observed-route-set-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-route-set-version-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-route-set-algorithm-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md - wiki/gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-prompt-limit-memory-2026-06-28.md - wiki/gguf-mirust/reports/browser-module-plan-count-drift-memory-2026-06-28.md durable_research: - wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md - wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md uaix_strategy_source: https://uaix.org/en-us/tools/ai-memory-package-wizard/#setup-file-handoff uaix_strategy_dogfood: docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md strategy_refresh_2026_06_27: report_storage: Report bodies stay in raw evidence and wiki/report pages; .uai/long-term-memory.uai keeps checksum-bearing pointers, and .uai/short-term-memory.uai keeps current open-next routes. report_pointer_audit: Every current wiki/gguf-mirust/reports/*.md and wiki/gguf-mirust/research/*.md page is represented in .uai/long-term-memory.uai; repeat this audit after adding report or research pages. research_storage: Model Breeding reference bodies stay in wiki/gguf-mirust/research/ and route through this synthesis file plus short-term memory before any source work. model_breeding_diverse_lanes: Compatible merge, sparse-lineage, adapter-ecology including ADP1/ASP1/ALR1, population-search, federated/local-update, browser-constrained-assembly, UAIX-memory-strategy, heritable-artifact, mate-selection, phenotype-evidence, and speciation-fit ideas are research/planner lanes until converted into typed receipts, eval sidecars, manifests, tests, or promotion records. site_voice_route: .uai/taboo.uai governs Model Breeding, mutualist, tiny-ecology, UAIX strategy, and public-copy wording for GGUF.MiRust.com. strategy_refresh_2026_06_28: setup_file_handoff_source: https://uaix.org/en-us/tools/ai-memory-package-wizard/#setup-file-handoff applied_memory_shape: Active buckets are intake, raw/wiki Markdown holds durable bodies, .uai files hold short routing and synthesis, short-term memory names current report/research routes, and long-term memory keeps checksum pointers. report_memory_shape: All current report pages stay in wiki/gguf-mirust/reports/, research pages stay in wiki/gguf-mirust/research/, and both route from short-term memory plus long-term checksum records. model_breeding_concept_lanes: The research page now includes heritable-artifact, mate-selection, phenotype-evidence, and speciation-and-fit lanes beside merge, sparse, adapter, population, local-update, browser-assembly, and UAIX strategy lanes. site_voice_route: .uai/taboo.uai carries the direct site voice rule; public copy should center proof, craft, lineage, fit, local agency, routes, and implementation evidence. dare_operator_2026_06_29: route: wiki/gguf-mirust/reports/dare-operator-memory-2026-06-29.md synthesis: DARE now has an offline `dare-candidate` and `validate-dare-candidate` receipt lane with signed task-delta weights, keep/drop ppm, dropout seed, mask checksum, raw delta checksum, rescaled delta checksum, focused parameter tests, and q8 CLI proof before downstream candidate manifests. dare_browser_operator_provenance_2026_06_29: route: wiki/gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29.md synthesis: DARE compact browser selector proof now renders `receipt-bound / dropout-rescaled-task-delta / 0x00000000000000b7`, rejects DARE operator-kind drift in selector validation, and uses `dare-operator-receipt-drift` to prove static q8 fallback with Operator unavailable. browser_converted_trained_provenance_2026_06_29: route: wiki/gguf-mirust/reports/browser-converted-trained-provenance-memory-2026-06-29.md synthesis: `converted-trained-registry` proves a compact selector-served q8 route fetches a converted-trained manifest and renders converted-trained source, pending eval, and runtime-compatible quality boundary fields while shared multi-parent registry behavior remains green. browser_converted_trained_file_route_2026_06_29: route: wiki/gguf-mirust/reports/browser-converted-trained-file-route-memory-2026-06-29.md synthesis: `browser-converted-trained-bundle` stages a reviewed trained-source q8 artifact plus sidecars under a runnable root, and `converted-trained-registry-file` proves real selector, model, and manifest routes. browser_converted_trained_all_route_2026_06_29: route: wiki/gguf-mirust/reports/browser-converted-trained-all-route-memory-2026-06-29.md synthesis: `browser-converted-trained-bundle ... all` stages converted-trained f32, q8, and q4 artifacts under one q4-defaulted selector root, and `converted-trained-registry-file` proves real selector/model/manifest routes for all three entries. research_intake_2026_06_28: route: wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md intake_index: wiki/gguf-mirust/reports/report-intake-index-2026-06-28.md raw_evidence: raw/gguf-mirust/report-intake-2026-06-28/ synthesis: Four Improvement research files route ModelBreeder genome/fitness/novelty/speciation guidance plus zero-dependency browser-runtime lanes for Wasm SIMD, hierarchical quantization, tokenizer/sampler determinism, KV-cache planning, allocator proof, multimodal fixtures, and telemetry. latest_federated_operator: route: wiki/gguf-mirust/reports/federated-operator-memory-2026-06-29.md synthesis: Federated/local-update candidates can now be written and validated from compatibility-bound base plus local-update parents with `local_update_weight_ppm`, local-update counts, raw delta checksum, weighted delta checksum, q8 proof, and CLI write/validate evidence. latest_two_parent_operator_browser_provenance: route: wiki/gguf-mirust/reports/two-parent-operator-browser-provenance-memory-2026-06-29.md synthesis: Blend, task-delta, and sparse task-delta now have compact browser Operator rendering plus byte-echo fallback proof through `blend-operator-registry`, `delta-operator-registry`, `sparse-delta-operator-registry`, and their receipt-drift modes. latest_crossover_operator: route: wiki/gguf-mirust/reports/crossover-operator-memory-2026-06-29.md synthesis: Crossover candidates can be written and validated from compatibility-bound parents with seed plus parent0 keep fields, selection density, mask checksum, q8 CLI proof, focused parameter/drift tests, and compact browser Operator rendering plus byte-echo fallback through `crossover-operator-registry` and `crossover-operator-receipt-drift`. latest_mutation_operator: route: wiki/gguf-mirust/reports/mutation-operator-memory-2026-06-29.md synthesis: Mutation candidates can be written and validated from compatibility-bound base/reference parents with seed, rate, magnitude, reference scaling, selection and delta checksums, q8 CLI proof, focused parameter/drift tests, and compact browser Operator rendering plus byte-echo fallback through `mutation-operator-registry` and `mutation-operator-receipt-drift`. latest_federated_selector_receipt_route: route: wiki/gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29.md synthesis: A federated/local-update operator receipt now has downstream selector and browser provenance proof through candidate, promotion, admission, selector registry records, and Model Provenance Operator rendering, preserving operator kind, receipt checksum, candidate checksum, and byte-count equality while rejecting federated operator-kind drift plus browser-side operator receipt byte-count drift before the generated route becomes selectable. latest_candidate_operator_receipt_binding: route: wiki/gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29.md synthesis: Candidate artifact manifests can optionally bind the exact operator receipt by path, text checksum, operator id/kind, candidate bytes, and candidate checksum; validation rejects receipt drift, missing receipt input for bound manifests, and candidate checksum disagreement. latest_promotion_operator_receipt_binding: route: wiki/gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29.md synthesis: Two-parent promotion templates can optionally carry candidate receipt bindings forward; validation recomputes the receipt-bound candidate manifest, rejects missing receipt input, and rejects promotion receipt field drift before runtime smoke/eval gates. latest_admission_operator_receipt_binding: route: wiki/gguf-mirust/reports/admission-operator-receipt-binding-memory-2026-06-29.md synthesis: Two-parent selector admissions can optionally carry promotion receipt bindings forward; validation recomputes candidate and promotion receipt evidence, rejects missing receipt input, rejects admission receipt drift, and checks receipt fields in admission summaries. latest_selector_operator_receipt_binding: route: wiki/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29.md synthesis: Selector registries now copy receipt-bound admission fields into entry.N.operator_receipt metadata, bind those fields into mate-selection checksums, and expose a browser Model Provenance Operator row. latest_browser_multi_parent_operator_provenance: route: wiki/gguf-mirust/reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md synthesis: Generated multi-parent admissions carry receipt-bound operator metadata into selector entries; app.js now enforces generated assembly operator-kind agreement, combined-selector smokes prove q4/q8/f32 soup plus sign-merge Operator rows, `generated-selector-operator-receipt-drift` proves byte-echo fallback, and `generated-selector-operator-kind-drift` proves kind-drift fallback before generated model, module-plan, assembly, adapter-family, or stack routes. latest_browser_mixed_operator_selector: route: wiki/gguf-mirust/reports/browser-mixed-operator-selector-memory-2026-06-29.md synthesis: `browser-multi-parent-bundle all mixed` emits one sign-merge plus soup f32/q8/q4 selector, keeps sign-merge q4 as the browser-frugal default, and `combined-selector-operator-family-cycle`, `combined-selector-operator-family-route-soak`, plus `combined-selector-operator-family-reload-soak` prove same-page, route, and fresh-page cross-family assembly. latest_parent_pool_evolution_schedule: route: wiki/gguf-mirust/reports/parent-pool-evolution-schedule-memory-2026-06-29.md synthesis: Parent-pool recipes now carry a checksum-bound `population-based-parent-pool-replay-v1` schedule for sign-merge and soup operator families, including commands, selection rules, selected parent ids, seed weights, and population fitness echoes before downstream multi-parent operators consume the pool. latest_operator_schedule_carry_forward: route: wiki/gguf-mirust/reports/operator-schedule-carry-forward-memory-2026-06-29.md synthesis: Sign-merge and soup receipts now echo parent-pool schedule identity plus selected family index, command, selection rule, and output gate; multi-parent candidate manifests validate those fields, while promotion templates and selector admission records preserve them through evaluated handoff. latest_browser_selector_genome_fitness: route: wiki/gguf-mirust/reports/browser-selector-genome-fitness-memory-2026-06-28.md synthesis: Generated selector registries now bind deterministic genome ids, admission lineage checksums, and eval-bound fitness-vector checksums; browser provenance renders Genome and Fitness rows for q4_0/q8_0/f32 generated entries. latest_browser_selector_species_fit: route: wiki/gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28.md synthesis: Generated selector registries now bind deterministic species ids and browser-fit checksums from candidate family traits plus browser resource envelopes; browser provenance renders Species rows for q4_0/q8_0/f32 generated entries. latest_browser_selector_novelty: route: wiki/gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28.md synthesis: Generated selector registries now bind deterministic novelty ids and behavior-sketch checksums from candidate descriptors plus eval, assembly, adapter-family, and module-plan evidence; browser provenance renders Novelty rows for q4_0/q8_0/f32 generated entries. latest_browser_selector_population: route: wiki/gguf-mirust/reports/browser-selector-population-memory-2026-06-28.md synthesis: Generated selector registries now bind deterministic population ids and population-review checksums from species, novelty, scoped fitness, lineage, assembly, and module-plan route context; browser provenance renders Population rows for q4_0/q8_0/f32 generated entries. latest_browser_selector_mate_selection: route: wiki/gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28.md synthesis: Generated selector registries now bind mate-selection ids, parent counts, and parent-pool-bound checksums from parent-pool, sign-merge, population-review, promotion-ledger, and admission evidence; browser provenance renders Mate Selection rows for q4_0/q8_0/f32 generated entries. latest_browser_selector_phenotype_evidence: route: wiki/gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28.md synthesis: Generated selector registries now bind phenotype-evidence ids and runtime-eval-bound checksums from provenance manifests, runtime-smoke, eval, eval-case, assembly, mate-selection, and fitness evidence; browser provenance renders Phenotype rows for q4_0/q8_0/f32 generated entries. latest_browser_selector_heritable_artifact: route: wiki/gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28.md synthesis: Generated selector registries now bind served artifact ids and served-artifact-bound checksums from candidate, model, manifest, genome, phenotype, fitness, assembly, adapter-family, and module-plan evidence; browser provenance renders Artifact rows for q4_0/q8_0/f32 generated entries. latest_browser_module_plan_wasm_memory: route: wiki/gguf-mirust/reports/browser-module-plan-wasm-memory-memory-2026-06-28.md synthesis: Generated selector entries and module-plan receipts now bind the WASM runtime's pre-init exported memory page count, render `WASM Pages`, and prove drift stops before generated model bytes. latest_browser_module_plan_wasm_export_set: route: wiki/gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md synthesis: Selector entries and module-plan receipts now bind `tinyrustlm-generate-v1`, browser receipt validation checks instantiated WASM exports, renders `WASM ABI`, and proves export-set drift stops before generated routes. latest_browser_module_plan_wasm_heap: route: wiki/gguf-mirust/reports/browser-module-plan-wasm-heap-memory-2026-06-28.md synthesis: Selector entries and receipts bind `module_plan_wasm_heap_min_bytes`, browser recomputes and probes the WASM heap floor before generated model fetch, renders `Heap Floor`, and proves drift stops before generated routes. latest_browser_module_plan_wasm_transfer: route: wiki/gguf-mirust/reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md synthesis: Selector entries and receipts bind `module_plan_wasm_transfer_strategy=copy-then-release-v1`, browser renders `Transfer`, source roots keep `unavailable`, and drift stops before generated model routes. latest_browser_module_plan_model_release: route: wiki/gguf-mirust/reports/browser-module-plan-model-release-memory-2026-06-29.md synthesis: Selector entries and receipts bind `module_plan_model_release_strategy=free-before-reassembly-v1`, browser renders `Release`, source roots keep `unavailable`, release drift stops before generated routes, and combined-selector-cycle proves `free_model` before reassembly. latest_browser_module_plan_runtime_reset: route: wiki/gguf-mirust/reports/browser-module-plan-runtime-reset-memory-2026-06-29.md synthesis: Selector entries and receipts bind `module_plan_runtime_reset_strategy=reset-context-before-assembly-v1`, browser renders `Reset`, source roots keep `unavailable`, reset drift stops before generated routes, and combined-selector-cycle proves `reset_context` before adapters. latest_browser_module_plan_adapter_validation: route: wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29.md synthesis: Selector entries and receipts bind `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1`, browser renders `Validate`, source roots keep `unavailable`, validation-strategy drift stops before generated routes, and combined-selector-assembly proves Rust validation before apply. latest_browser_module_plan_adapter_validation_count: route: wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-count-memory-2026-06-29.md synthesis: Selector entries and receipts bind `module_plan_adapter_validation_count=3`, browser renders `Validate Count`, source roots keep `unavailable`, adapter-family stack count and apply-count fields must agree, combined-selector-assembly proves three Rust validation calls per generated assembly step, and validation-count drift stops before generated routes. latest_browser_module_plan_adapter_apply_count: route: wiki/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md synthesis: Selector entries and receipts bind `module_plan_adapter_apply_count=3`, browser renders `Apply Count`, source roots keep `unavailable`, adapter-family stack count and runtime `adapter_apply_count` diagnostics must agree, and apply-count drift stops before generated routes. latest_browser_module_plan_planned_fetch_count: route: wiki/gguf-mirust/reports/browser-module-plan-planned-fetch-count-memory-2026-06-29.md synthesis: Selector entries and receipts bind `module_plan_planned_fetch_count=21`, browser renders `Plan Fetches`, source roots keep `unavailable`, generated-route cardinality must agree, and planned-fetch-count drift stops before generated routes. latest_browser_module_plan_actual_fetch_count: route: wiki/gguf-mirust/reports/browser-module-plan-actual-fetch-count-memory-2026-06-29.md synthesis: Browser app state counts accepted generated self-assembly route fetches, renders `Actual Fetches`, source roots keep `unavailable`, Ready requires actual count to equal planned count, and combined-selector-assembly proves q4_0/q8_0/f32 each show `21 fetches`. latest_browser_module_plan_observed_route_set: route: wiki/gguf-mirust/reports/browser-module-plan-observed-route-set-memory-2026-06-29.md synthesis: Browser app state records observed generated route `{kind,path}` entries, renders `Actual Route Set`, source roots keep `unavailable`, Ready requires observed checksum to equal declared route-set checksum, and combined-selector-assembly proves q4_0/q8_0/f32 equality. latest_browser_module_plan_actual_module_bytes: route: wiki/gguf-mirust/reports/browser-module-plan-actual-module-bytes-memory-2026-06-29.md synthesis: Browser app state records accepted generated module byte lengths, renders `Actual Module Bytes`, source roots keep `unavailable`, Ready requires observed module bytes to equal receipt module byte rows, and combined-selector-assembly proves q4_0/q8_0/f32 totals. latest_browser_module_plan_actual_module_checksums: route: wiki/gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md synthesis: Browser app state records accepted generated module checksums, renders `Actual Module Checksums`, source roots keep `unavailable`, Ready requires observed checksums to equal receipt module checksum rows, combined-selector-assembly proves q4_0/q8_0/f32 equality, and module-plan-payload-checksum-drift proves coherent payload checksum rewrites stop at the stale module-plan checksum row before generated model routes. latest_browser_module_plan_route_set: route: wiki/gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29.md synthesis: Selector entries and receipts bind `module_plan_route_set_checksum`, browser renders `Route Set`, source roots keep `unavailable`, ordered generated self-assembly routes must agree, and route-set drift stops before generated routes. latest_browser_module_plan_route_set_version: route: wiki/gguf-mirust/reports/browser-module-plan-route-set-version-memory-2026-06-29.md synthesis: Selector entries and receipts bind `module_plan_route_set_version=1`, browser renders `Route Version`, source roots keep `unavailable`, route-set checksum preimages use the version constant, and route-set-version drift stops before generated routes. latest_browser_module_plan_route_set_algorithm: route: wiki/gguf-mirust/reports/browser-module-plan-route-set-algorithm-memory-2026-06-29.md synthesis: Selector entries and receipts bind `module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1`, browser renders `Route Hash`, source roots keep `unavailable`, route-set checksum preimages include the algorithm label, and route-set-algorithm drift stops before generated routes. latest_browser_module_plan_operator_receipt: route: wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md synthesis: Selector entries, module-plan receipts, assembly receipts, and fetched `sign-merge.operator` evidence now agree on operator receipt route/checksum before generated model bytes; `module-plan-operator-receipt-drift` stops after selector registry plus module-plan receipt, and fresh `combined-selector-assembly` proves q4_0/q8_0/f32 self-assembly with ADP1/ASP1/ALR1 stack apply before generation. latest_browser_module_plan_total_limit: route: wiki/gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28.md synthesis: Generated selector entries and module-plan receipts now bind current prompt-aware `module_plan_total_byte_budget_limit=43454464`, render `Total Limit`, and prove cap drift stops at the module-plan receipt before generated model or stack bytes. latest_browser_module_plan_output_limit: route: wiki/gguf-mirust/reports/browser-module-plan-output-limit-memory-2026-06-28.md synthesis: Generated selector entries and module-plan receipts now bind `module_plan_output_byte_limit=65536`, render `Output Limit`, include the cap in total budget math, and prove output-limit drift stops at module-plan validation. latest_browser_module_plan_kv_cache: route: wiki/gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28.md synthesis: Runtime diagnostics, selector entries, and module-plan receipts now bind exact KV-cache byte budget and page count, render KV rows, include KV bytes in totals, and prove page-count drift stops before generated routes. latest_browser_module_plan_adapter_stack_budget: route: wiki/gguf-mirust/reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28.md synthesis: Selector entries and module-plan receipts now bind exact ADP1 plus ASP1 plus ALR1 stack bytes, render `Stack Budget`, include stack bytes in totals, and prove stack-budget drift stops before generated routes. latest_browser_module_plan_context_token: route: wiki/gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28.md synthesis: Selector entries and module-plan receipts now bind validated context token limits, render `Context`, match admitted model shape, and prove context-token drift stops before generated routes. latest_browser_module_plan_tokenizer: route: wiki/gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28.md synthesis: Selector entries and module-plan receipts now bind admitted tokenizer checksums, render `Tokenizer`, feed tokenizer-aware lineage checksums, and prove tokenizer drift stops before generated routes. latest_browser_module_plan_sampler_cap: route: wiki/gguf-mirust/reports/browser-module-plan-sampler-cap-memory-2026-06-28.md synthesis: Selector entries and module-plan receipts now bind `module_plan_sampler_candidate_cap=1024`, render `Sampler Cap`, clamp browser Top K to the fixed-buffer envelope, and prove sampler-cap drift stops before generated routes. latest_browser_module_plan_fetch_count: route: wiki/gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28.md synthesis: Selector entries and receipts bind `module_plan_fetch_count_limit=32`, render `Fetch Limit`, compute planned route count before model bytes, count actual governed requests, and prove 21 requests per generated pass. latest_browser_module_plan_prompt_limit: route: wiki/gguf-mirust/reports/browser-module-plan-prompt-limit-memory-2026-06-28.md synthesis: Selector entries and module-plan receipts now bind `module_plan_prompt_byte_limit=4096`, render `Prompt Limit`, include prompt bytes in total budget math, and prove prompt-limit drift plus source prompt-transfer boundaries. latest_browser_module_plan_count_drift: route: wiki/gguf-mirust/reports/browser-module-plan-count-drift-memory-2026-06-28.md synthesis: `module-plan-count-drift` mutates receipt `module_count` while refreshing selector checksum, proving selector cardinality remains authoritative before generated model or stack routes. latest_browser_combined_selector_extended_route_soak: route: wiki/gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md synthesis: `combined-selector-route-extended-soak` runs five q4_0/q8_0/f32 cycles from one generated all-root, proving fifteen assemblies with fresh route requests and path-flexible total-budget checks. latest_browser_combined_selector_stress_route_soak: route: wiki/gguf-mirust/reports/browser-combined-selector-stress-route-soak-memory-2026-06-28.md synthesis: `combined-selector-route-stress-soak` runs eight q4_0/q8_0/f32 cycles from one generated all-root, proving twenty-four assemblies with fresh route requests. failure_dogfood: issue: First report-processing pass over-prioritized durable wiki files and pointer-ledger cleanliness, leaving hot .uai files too thin for cold-start agents. correction: Keep long-term-memory.uai pointer-only, but populate typed .uai files with enough report-derived routing, constraints, tensions, and next questions to guide work before wiki deep-loading. uaix_guidance_needed: UAIX and LLM Wiki setup guidance should say link-only is not memory-thin; every project needs hot .uai synthesis plus crawlable durable nodes. crawlability_rule: A future agent should be able to identify what to load next from .uai files within two minutes, without opening every report or wiki page. uaix_file_handoff_strategy_2026_06_26: The active setup is File Handoff plus raw evidence, durable LLM Wiki synthesis, pointer-only long-term memory, and short-term routing into durable report nodes. uaix_file_handoff_strategy_2026_06_27: Scan active buckets, classify each source file, record disposition and proof, preserve originals with checksums, synthesize durable wiki/report nodes, refresh hot routing, audit long-term pointers, then remove or explicitly keep active copies. report_clusters: enterprise_rust_governance: sources: enterprise Rust adoption, Enterprise Rust Best Practices, Rust Design Patterns, Rust ownership/SOLID. hot_takeaway: Enterprise quality for TinyRustLM means smaller trusted surface, no third-party runtime crates, explicit tests, visible checksums, bounded unsafe, and maintainable Rust idioms. apply_now: - Keep runtime and packer dependency lists empty. - Treat every browser/model boundary as a typed trust boundary with explicit errors. - Prefer enums, newtypes, ownership, and cohesive modules over object-oriented pattern translation. - Make tests and smoke outputs the authority for support claims. routing_edges: - Do not import cargo-audit/cargo-deny/cargo-vet as project requirements while the no-crate/no-extra-tool prompt is active. - Do not add framework layers to look enterprise; proof and simplicity are the enterprise move here. browser_local_runtime: sources: lightweight browser AI runtime, Rust AI Runtime for Web, Rust Browser Tiny LLM, TinyLM-16M in-browser, Custom Rust SML runtime. hot_takeaway: The browser host should fetch local files, copy bytes, call Rust exports, and render diagnostics; Rust owns model parsing, inference, errors, and memory discipline. apply_now: - Keep JS handwritten and minimal. - Keep local-only request checks in browser smoke. - Distinguish missing file, malformed file, rejected model, context overflow, and generation failure in UI. - Preserve model selection recovery after model-specific failures. - Measure load time, prompt count, generated count, scratch use, KV length, and quantization mode. routing_edges: - Treat WebGPU, OPFS, IndexedDB, workers, and framework runtimes as future comparison topics only. - Do not let JS parse .slm or own inference logic. tinylm_modular_architecture: sources: Modular AI in Browser, Modular Tiny Language Models, Multiple Tiny Language Models, Tiny Language Models Architecture, modular teleodynamic duplicate reports. hot_takeaway: Multi-model routing, adapters, task composition, speculative decoding, and skill packages are future architecture lanes; first stabilize one auditable TinyLM-16M .slm path. apply_now: - Keep .slm metadata shaped like a future model ABI. - Preserve tokenizer and quantization extensibility without implementing marketplace behavior. - Document future compatibility requirements before adding adapters or routers. routing_edges: - Do not implement LoRA, task arithmetic, mixture-of-agents, speculative decoding, or model marketplaces until the base runtime is correct and benchmarked. teleodynamic_resource_bounded_design: sources: Rust In-Browser Teleodynamic AI Plan, Rust WebAssembly Teleodynamic AI Architecture, Teleodynamic AI in Browser, resource-bounded reports, Teleodynamic Tiny Language Model Architecture, Teleodynamics framework. hot_takeaway: Translate teleodynamic theory into measurable resource behavior: context, scratch arena, KV cache, load failure recovery, reset, latency, and honest stopping conditions. apply_now: - Treat Booting, Loading runtime, Loading model, Ready, Model rejected, Model load failed, and context exceeded as meaningful phase states. - Prefer graceful refusal or reset over hidden degradation when context or model boundaries fail. - Expose enough diagnostics for users and agents to see resource pressure. routing_edges: - Do not let theory become decorative language. - Do not add adaptive behavior unless deterministic tests prove it. brand_product_positioning: sources: Branding MiRust.com and duplicate Machine Inteligence framwork for rust. hot_takeaway: TinyRustLM should be positioned as a transparent browser-local Rust/WASM SLM runtime, not a cloud AI wrapper or trained-quality assistant yet. apply_now: - Lead with local proof and custom runtime. - Say deterministic smoke models prove execution path, not assistant quality. - Keep public claims aligned with workspace.uai and test-plan.uai. routing_edges: - Do not imply GGUF compatibility, Mini Browser automation, remote inference, or trained model quality before implementation evidence exists. model_breeding_ecology: sources: 26-report 2026-06-26 batch covering 4Fs, code beading, model breeding, model merging, LoRA/adapters, on-device tiny LLMs, mutualism, and evolutionary motivation. hot_takeaway: Treat model breeding as traceable offline candidate lineage: compatible parents, operator metadata, generated artifact, eval sidecar, promotion record, and current-runtime admission gates. apply_now: - Route future model-breeding work to wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md. - Use wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md for primary research references. - Keep browser inference stable; breeding operators belong in offline tooling until artifacts pass normal .slm admission and manifest gates. - Require exact base-family, tokenizer, tensor-shape, quantization, and output-head compatibility before any parameter-level merge. - Use sparse-delta-candidate for lineage-bound sparse task-vector .slm candidates before candidate-manifest. - Use crossover-candidate for lineage-bound deterministic direct-parameter crossover when candidate values should be selected element-wise from two compatible parents by seed and parent0 keep rate; validate-crossover-candidate before candidate-manifest so candidate bytes, parent checksums, selection counts, density fields, and mask checksum recompute from the receipt. - Use mutation-candidate for lineage-bound deterministic bounded perturbation when a base parent should keep the output contract while a compatible reference parent supplies scale context; validate-mutation-candidate before candidate-manifest so seed, rate, magnitude, selection checksum, delta checksum, candidate bytes, and parent checksums recompute from the receipt. - Use prune-candidate for lineage-bound deterministic magnitude pruning when a base parent should keep its output contract while a compatible reference parent supplies ranking context; validate-prune-candidate before candidate-manifest so keep/floor ppm fields, mask checksum, output-value checksum, candidate bytes, and parent checksums recompute from the receipt, then preserve the bound receipt through selector registry `entry.N.operator_receipt_*` and browser Model Provenance Operator rendering. - Use population-review for ledger-backed fitness ranking, weighted quality/frugality/quantization objective-vector metadata, frontier selection, and parent-pool routing after promotion-ledger. - Use parent-pool-recipe after validate-population-review to require shared direct-parameter contracts and record fitness-normalized seed weights plus relatedness metric, scope, pair count, status, checksum, and per-parent groups. - Use sign-merge-candidate after validate-parent-pool-recipe to turn reviewed compatible parent pools into seed-weighted sign-consensus .slm candidates with recomputable receipts that echo relatedness fields. - Use multi-parent-candidate-manifest after validate-sign-merge-candidate or validate-soup-candidate to dispatch by parent-pool operator kind, bind receipt checksum, recipe checksum, relatedness summary, parent summaries, sign or soup metric fields, candidate .slm fields, and pending promotion route. - Use multi-parent-promotion-template after validate-multi-parent-candidate to bind candidate manifest checksum, receipt checksum, recipe checksum, parent count, candidate .slm fields, and pending runtime-smoke/eval status. - Use multi-parent-admission-record after validate-multi-parent-promotion, validate-manifest, validate-runtime-smoke, and passed eval evidence to bind sign-merge promotion evidence before selector-registry consumes the record. - Use sparse-adapter-delta when the useful bead is a compact ASP1 task-delta package instead of a normal .slm candidate; validate-sparse-adapter-delta before runtime ADP1/ASP1/ALR1 apply work or generated browser ASP1 route staging. - Use low-rank-adapter-delta when the useful bead is an ALR1 matrix factor task-delta package; validate-low-rank-adapter-delta before runtime ALR1 apply work or generated ALR1 browser route staging. - Use adapter-source-template plus validate-adapter-source when the useful bead is a trained low-rank factor source bundle; keep those source factors reviewed before converting them into runtime ALR1 packages or browser assembly evidence. - Use runtime f32/q8_0/q4_0 ADP1, ASP1, or ALR1 adapter apply only after loading a compatible base and validating package identity, checksums, tokenizer, tensor layout, tensor directory, finite deltas or factors, sparse indices or low-rank shapes, and fused values; q8_0/q4_0 apply must re-quantize compact tensors. - Use browser-smoke adapter-sidecar after Adapter Sidecar UI, local adapter route, app.js WASM transfer, or runtime apply state changes. - Use browser-smoke adapter-sidecar-checksum-mismatch after browser-side ADP1 checksum changes to prove a corrupted sidecar is stopped before apply_adapter_delta and generation diagnostics stay intact. - Use registry-carried f32/q8_0/q4_0 adapter-family fields only when the route apply status matches the admitted entry quantization, with local .adp1, .asp1, or .alr1 routes, matching manifests, checksums, a local .adapter-family.receipt handle plus served adapter manifest files that the browser fetches and checksum-verifies, and adapter-sidecar-registry-file or quantized registry smoke evidence. - Use receipt-bound preferred adapter fields when generated adapter families need a browser-default module choice; app.js must verify the preferred index, route, and manifest path against the served receipt and manifests before defaulting the selector. - Use browser-multi-parent-bundle `all` when the useful selector bead is one served root containing f32, q8_0, and q4_0 generated modules; verify f32/q8_0/q4_0 entry switching and sparse ASP1 apply through adapter-sidecar-registry-file. - Use browser-smoke `combined-selector-assembly` when a single generated `all` root must prove q4_0 default selection, q4_0/q8_0/f32 selector switching, plan-before-model order, and stack auto-assembly before generation in one browser session. - Use browser-smoke `combined-selector-cycle` when a single generated `all` root must prove repeated q4_0/q8_0/f32 switching, release-before-reassembly sequencing, per-pass stack validation/apply deltas, reset diagnostics, and generation across multiple passes in one browser session. - Use browser-smoke `combined-selector-route-soak` when a single generated `all` root must prove longer q4_0/q8_0/f32 reuse, no-store local fetch behavior, and per-pass requests for every self-assembly route in one browser session. - Use browser-smoke `combined-selector-route-extended-soak` when a single generated `all` root needs five-cycle q4_0/q8_0/f32 route pressure, fifteen assembly passes, and path-flexible total-budget assertions. - Use browser-smoke `combined-selector-route-stress-soak` when a single generated `all` root needs eight-cycle q4_0/q8_0/f32 route pressure and twenty-four assembly passes. - Use browser-smoke `combined-selector-reload-soak` when a generated `all` root must prove q4_0 registry-default boot selection and q4_0/q8_0/f32 self-assembly across separate page lifetimes. - Use browser-smoke `adapter-stack-rust-validate-drift` when browser metadata and internal adapter checksums remain aligned but Rust adapter identity validation must stop a generated stack before mutation. - Use the Browser Runtime Assembly Diagnostics report when runtime diagnostics assembly fields, adapter apply accounting, WASM ABI diagnostics, checked manual adapter sidecar assertions, or generated q4_0/q8_0/f32 auto-stack runtime state assertions change. - Use the Browser Assembly Trace report when the Module Plan Trace row, browser load checkpoints, generated all-root trace assertion, or ready-state sequencing changes; the generated trace should progress from plan verified through ready only after the corresponding verified stage completes. - Use browser-frugal-quantized selector defaults when a combined served root should start on the most constrained supported quantization; verify initialSelectedModel is q4_0 before scripted switching. - Use browser selector byte-budget intake when registry routes can point at large local artifacts; require `entry.N.model_bytes` at or below the browser budget before fetch, then verify fetched byte count before WASM transfer. - Use `selector_model_byte_budget=33554432` as the registry-level browser envelope for selector routes; Rust must write and validate it, and the browser must reject registries whose budget exceeds the local constant. - Use registry adapter auto-apply fields only for generated adapter families whose receipt-preferred member can be verified before startup apply; Rust must write and validate `adapter_auto_apply_status=enabled` plus `adapter_auto_apply_strategy=receipt-preferred-compatible`, and browser smokes must prove pre-generation assembly. - Use browser text-sidecar byte envelopes when selector.registry, manifests, receipts, or evidence files are parsed in JavaScript; oversized sidecar text should stop generated adapter setup before artifact fetch or apply. - Use registry-declared browser text-sidecar budget fields when generated selector registries advertise selector, manifest, receipt, and evidence envelopes; Rust and browser intake must require exact local matches before generated registry routes are accepted. - Use browser runtime WASM manifests when checked or generated browser roots instantiate Rust; the browser must verify runtime manifest fields, byte count, and checksum before model, adapter, receipt, or evidence routes assemble. - Use browser adapter stacks when generated adapter families need more than one compatible module at startup; receipts declare ordered stack members, selector registries carry stack fields, and browser smokes prove family ADP1 plus sparse ASP1 plus low-rank ALR1 pre-generation apply. - Use browser module plans when generated selector entries need a single local graph receipt before generated model bytes; selector fields carry the plan route/checksum/count, served plans bind model, manifest, receipts, and adapter stack members, and browser smoke must prove the plan route is requested before `.slm` fetch. - Use browser module-plan fetch policies when generated selector entries need a local no-store fetch contract before generated model bytes; selector fields and served plans carry `local-no-store-v1`, and `module-plan-fetch-policy-drift` proves drift stops before `.slm` or stack routes. - Use browser module-plan origin policies when generated selector entries need a same-origin local assembly contract before generated model bytes; selector fields and served plans carry `same-origin-loopback-local-v1`, and `module-plan-origin-policy-drift` proves drift stops before `.slm` or stack routes. - Use browser module-plan resource envelopes when generated selector entries must prove constrained self-assembly before model fetch; selector fields and served plans carry `browser-constrained-local-assembly`, admitted model byte budget, and adapter-family byte budget. - Use browser module-plan total budgets when generated selector entries must prove the exact local self-assembly envelope before model fetch; selector fields and served plans carry `module_plan_total_byte_budget`, and `module-plan-total-budget-drift` proves drift stops at the module-plan receipt. - Use browser module-plan output limits when generated selector entries must prove the 64 KiB generated-result cap before model fetch; selector fields and served plans carry `module_plan_output_byte_limit=65536`, the cap participates in total budget math, and `module-plan-output-limit-drift` proves cap drift stops at module-plan validation. - Use browser module-plan KV-cache budgets when generated selector entries must prove runtime cache memory before model fetch; selector fields and served plans carry `module_plan_kv_cache_byte_budget` plus `module_plan_kv_cache_page_count`, runtime diagnostics echo the allocation, and `module-plan-kv-cache-drift` proves page-count drift stops at the module-plan receipt. - Use browser module-plan context-token binding when generated selector entries must prove the admitted context window before model fetch; selector fields and served plans carry `module_plan_context_token_limit`, and `module-plan-context-token-drift` proves drift stops at the module-plan receipt. - Use browser module-plan tokenizer binding when generated selector entries must prove tokenizer identity before model fetch; selector fields and served plans carry `module_plan_tokenizer_checksum`, and `module-plan-tokenizer-drift` proves drift stops at the module-plan receipt. - Use browser module-plan sampler-cap binding when generated selector entries must prove the fixed-buffer sampling envelope before model fetch; selector fields and served plans carry `module_plan_sampler_candidate_cap=1024`, and `module-plan-sampler-cap-drift` proves drift stops at the module-plan receipt. - Use browser module-plan total limits when generated selector entries must prove the cap on the local self-assembly envelope before model fetch; selector fields and served plans carry current prompt-aware `module_plan_total_byte_budget_limit=43454464`, and `module-plan-total-limit-drift` proves cap drift stops at the module-plan receipt. - Use browser-smoke `module-plan-count-drift` after selector module-plan count or receipt cardinality parsing changes to prove checksum-consistent `module_count` drift stops before generated `.slm` or stack routes. - Use browser-smoke `module-plan-resource-drift` after module-plan resource-envelope changes to prove checksum-consistent receipt budget drift stops before generated `.slm` fetch. - Use browser-smoke `module-plan-graph-drift` after module-plan graph validation changes to prove checksum-consistent receipt route drift stops before generated `.slm` fetch. - Use browser-smoke `module-plan-stack-drift` after module-plan stack member validation changes to prove checksum-consistent stack route drift stops before generated `.slm`, ADP1, ASP1, or adapter-manifest fetch. - Use browser-smoke `module-plan-role-drift` after module-plan role validation changes to prove checksum-consistent role drift stops before generated `.slm`, ADP1, ASP1, or adapter-manifest fetch. - Use browser-smoke `module-plan-slot-drift` after module-plan assembly-slot validation changes to prove checksum-consistent slot drift stops before generated `.slm`, ADP1, ASP1, or adapter-manifest fetch. - Use the Module Plan display report when the browser panel, verified receipt fields, generated model route display, or receipt-declared stack display changes; source ui-audit and generated-root adapter-sidecar-registry-file should cover the visible state. - Use the Module Plan budget display report when visible model/adapter byte-budget rows change; source ui-audit should prove fallback `unavailable`, and generated-root adapter-sidecar-registry-file should prove receipt-derived budget text. - Use the Module Plan role display report when `.module-plan.receipt` role fields, rendered role summaries, or role assertions change; source ui-audit should prove fallback `unavailable`, and generated-root adapter-sidecar-registry-file should prove the ordered runtime/model-manifest/assembly/adapter-family/stack role summary. - Use the Module Plan slots report when `.module-plan.receipt` assembly-slot fields, rendered slot summaries, or slot assertions change; source ui-audit should prove fallback `unavailable`, and generated-root adapter-sidecar-registry-file should prove the ordered runtime/model-manifest/assembly/adapter-family/stack slot summary. - Use the Module Plan dependencies report when `.module-plan.receipt` dependency fields, rendered dependency summaries, or dependency assertions change; source ui-audit should prove fallback `unavailable`, and generated-root adapter-sidecar-registry-file should prove the ordered runtime-WASM-to-stack dependency chain. - Use the Module Plan phases report when `.module-plan.receipt` phase fields, rendered phase summaries, or phase assertions change; source ui-audit should prove fallback `unavailable`, generated-root adapter-sidecar-registry-file should prove ordered phases, and `module-plan-phase-drift` should stop before generated model or stack artifact fetches. - Use the Module Plan byte-counts report when `.module-plan.receipt` byte_count fields, rendered byte summaries, fetched model/text byte matching, adapter-stack artifact byte matching, or byte-drift assertions change; source ui-audit should prove fallback `unavailable`, generated-root adapter-sidecar-registry-file should prove ordered byte counts, and `module-plan-byte-drift` should stop before generated model or stack artifact fetches. - Use the Module Plan checksums report when `.module-plan.receipt` checksum fields, rendered checksum summaries, stack artifact checksum matching, or checksum-drift assertions change; source ui-audit should prove fallback `unavailable`, generated-root adapter-sidecar-registry-file should prove ordered checksums, and `module-plan-checksum-drift` should stop before generated model or stack artifact fetches. - Use the Browser Assembly Trace report when Module Plan trace checkpoints or generated-root trace smoke assertions change; source ui-audit should prove fallback `unavailable`, and combined-selector-assembly should prove q4_0/q8_0/f32 exact trace text. - Use the Browser Eval Case Evidence Checksum report when selector admission eval evidence fields, promotion-ledger admission copies, selector registry eval proof fields, generated assembly receipt eval digests, Model Provenance eval rows, or browser-smoke registry-backed provenance assertions change. - Use the Browser Selector Genome Fitness report when generated selector genome ids, genome lineage checksums, eval-bound fitness-vector checksums, Model Provenance Genome/Fitness rows, or registry-backed browser provenance assertions change. - Use the Browser Selector Species Fit report when generated selector species ids, browser-fit checksums, Model Provenance Species rows, or ModelBreeder speciation-fit registry assertions change. - Use the Browser Selector Novelty report when generated selector novelty ids, behavior-sketch checksums, Model Provenance Novelty rows, or ModelBreeder novelty registry assertions change. - Use the Browser Selector Population report when generated selector population ids, population-review checksums, Model Provenance Population rows, or ModelBreeder population-review registry assertions change. - Use the Browser Selector Mate Selection report when generated selector mate-selection ids, parent counts, parent-pool-bound checksums, Model Provenance Mate Selection rows, or ModelBreeder parent-pool registry assertions change. - Use the Browser Selector Phenotype Evidence report when generated selector phenotype-evidence ids, runtime-eval-bound checksums, provenance manifest checksums, Model Provenance Phenotype rows, or ModelBreeder phenotype-evidence registry assertions change. - Use the Browser Selector Heritable Artifact report when generated selector heritable artifact ids, served-artifact-bound checksums, Model Provenance Artifact rows, or ModelBreeder artifact-inheritance registry assertions change. - Use the Browser Assembly Eval Case Drift report when generated assembly receipt eval digest matching, assembly rejection state, or `assembly-eval-case-drift` assertions change; the smoke should stop before evidence and adapter-family routes. - Use the Browser Assembly Evidence File Drift report when fetched assembly evidence-file checksum matching, evidence route ordering, Assembly Evidence rejection state, or `assembly-evidence-file-drift` assertions change; the smoke should stop before later evidence and adapter-family routes. - Use the Browser Adapter Manifest Drift report when generated adapter manifest checksum matching, same-byte manifest drift, post-receipt adapter state, or `adapter-manifest-drift` assertions change; the smoke should stop before later manifests and stack artifacts. - Use the Browser Adapter Artifact Drift report when generated adapter stack artifact checksum matching, fetched artifact byte transfer, post-manifest adapter state, or `adapter-artifact-drift` assertions change; the smoke should stop before later stack artifacts and Rust adapter apply. - Use the Browser Adapter Stack Prefetch Drift report when generated auto-apply stack bytes, full-stack prefetch, pre-WASM stack verification, or `adapter-stack-prefetch-drift` assertions change; the smoke should prove later stack drift cannot leave earlier adapter mutation behind. - Use the Browser Adapter Stack Rust Validate report when the `validate_adapter_delta` WASM export, generated stack semantic preflight, validation-before-apply ordering, or adapter ABI smoke assertions change. - Use the Browser Module Plan Adapter Validation report when `module_plan_adapter_validation_strategy`, the Module Plan Validate row, or `module-plan-adapter-validation-drift` assertions change. - Use the Browser Module Plan Adapter Validation Count report when `module_plan_adapter_validation_count`, the Module Plan Validate Count row, actual Rust validation loop count, or `module-plan-adapter-validation-count-drift` assertions change. - Use the Browser Module Plan Adapter Apply Count report when `module_plan_adapter_apply_count`, the Module Plan Apply Count row, runtime `adapter_apply_count`, or `module-plan-adapter-apply-count-drift` assertions change. - Use the Browser Module Plan Planned Fetch Count report when `module_plan_planned_fetch_count`, the Module Plan Plan Fetches row, generated route cardinality, or `module-plan-planned-fetch-count-drift` assertions change. - Use the Browser Module Plan Actual Fetch Count report when browser-owned generated fetch accounting, the Module Plan Actual Fetches row, counted fetch wrappers, or planned-versus-actual Ready gating changes. - Use the Browser Module Plan Observed Route Set report when browser-owned route-set recording, the Module Plan Actual Route Set row, route kind labels, route ordering, or observed-versus-declared Ready gating changes. - Use the Browser Module Plan Route Set report when `module_plan_route_set_checksum`, the Module Plan Route Set row, generated route ordering, or `module-plan-route-set-drift` assertions change. - Use the Browser Module Plan Route Set Version report when `module_plan_route_set_version`, the Module Plan Route Version row, route-set checksum preimage versioning, or `module-plan-route-set-version-drift` assertions change. - Use the Browser Module Plan Route Set Algorithm report when `module_plan_route_set_checksum_algorithm`, the Module Plan Route Hash row, route-set checksum preimage algorithm labels, or `module-plan-route-set-algorithm-drift` assertions change. - Use the Browser Module Plan Operator Receipt report when `module_plan_operator_receipt_*`, `.module-plan.receipt` `operator_receipt_*`, assembly receipt operator agreement, fetched `sign-merge.operator` checksum agreement, or `module-plan-operator-receipt-drift` assertions change. - Use registry-carried assembly receipt fields for generated f32/q8_0/q4_0 multi-parent selector entries when the browser must verify a served receipt and then fetch/checksum the receipt-referenced ledger, review, recipe, operator, candidate, promotion, runtime, eval, admission, and adapter-family evidence. - Use the Assembly Evidence panel and adapter-sidecar-registry-file browser smoke after generated f32/q8_0/q4_0 bundle evidence staging, app.js assembly receipt parsing, or evidence-file fetch changes. - Use browser-smoke multi-parent-registry after selector-registry route changes and multi-parent-registry-file after browser-multi-parent-bundle staging to prove both fixture and generated served selector routes; browser-multi-parent-bundle should emit a runnable app root, not models-only staging. - Use the reference ideas page for diverse lanes spanning architecture-preserving merges, soups, Re-Basin alignment, task vectors, sparse/sign-aware composition, adapters, federated/local update ideas, pruning masks, retention metrics, evolution-style search, model kinship, sparse-mask breadcrumbs, adaptive merge search, browser-constrained assembly, UAIX memory strategy, and multi-objective fitness. - Use the reference ideas page for Model Breeding concept lanes spanning heritable artifacts, mate selection, phenotype evidence, speciation-and-fit boundaries, candidate genomes as manifests/receipts/eval sidecars, and local browser assembly as a proof graph. - Use the 2026-06-27 diversity refresh as reference metadata: sparse masks now have first receipt-level evidence through sparse-delta density, nonzero-delta retention, and implicit mask checksums; population objective vectors now have first population-review fields and checksums; parent relatedness now has first recipe/receipt/manifest fields; replayable recipe chains, planner proposals, and resource budgets still need typed evidence before implementation claims. - Use distillation or retraining when compatibility breaks instead of direct tensor mixing. - Record parent hashes, operator recipe, build tool route, and eval evidence in candidate manifests. - Treat 4Fs as a helpful lens: fast, flexible, frugal, federated. - Treat code beading as durable small work units: source manifest, compatibility result, candidate artifact, eval sidecar, promotion ledger, population review with objective-vector checksum, parent-pool recipe with relatedness checksum, sign-merge receipt with relatedness echo fields, multi-parent candidate manifest with relatedness summary, multi-parent promotion template, multi-parent admission record, selector registry for both admission families, browser-verified adapter-family receipt plus manifests and preferred-member fields for generated compatible sidecar sets, and browser-verified assembly receipts plus fetched evidence files for generated multi-parent chains. - Follow .uai/taboo.uai for public website copy about model breeding, mutualism, and tiny model ecology. future_reference_lanes: - Model soups now have a first typed lane through `soup-candidate` plus `validate-soup-candidate`, with parent-pool seed weights, direct weighted averaging, receipt checksums, focused tests, and shared multi-parent candidate manifest handoff; task vectors and adaptive soup search remain future lanes. - Deterministic crossover for compatible weight-space exploration is now implemented as crossover-candidate plus validate-crossover-candidate with receipt-bound seed, parent0 keep rate, per-parent selection density, and mask checksum evidence. - Deterministic bounded mutation for compatible weight-space exploration is now implemented as mutation-candidate plus validate-mutation-candidate with receipt-bound seed, rate, magnitude, reference scaling, selection checksum, and delta checksum evidence. - Deterministic magnitude pruning for compatible frugality exploration is now implemented as prune-candidate plus validate-prune-candidate with receipt-bound keep/floor ppm fields, selected/pruned counts, mask checksum, output-value checksum evidence, selector receipt carry-forward, selector operator-kind drift rejection, browser prune Operator rendering, and browser prune byte-echo fallback proof. - TIES and DARE for sparse/sign-aware delta composition; sparse task-delta receipts now include density, nonzero-delta retention, and implicit top-k mask checksums, DARE has compact browser Operator proof plus byte fallback, and parent-pool recipes, sign-merge candidate receipts, multi-parent candidate manifests, multi-parent promotion templates, multi-parent admission records, selector route binding, browser-served registry smoke, generated f32/q8_0/q4_0 browser bundle routing, one q4-defaulted combined f32/q8_0/q4_0 selector root, combined-selector assembly proof across all three generated entries, browser selector byte-budget intake with registry-level model and text-sidecar budget contracts, registry-controlled receipt-preferred auto assembly, browser runtime WASM manifests, browser-verified assembly receipts with fetched evidence-file checksum checks, browser module-plan resource and fetch-policy envelopes before generated model fetch, checksum-consistent module-plan fetch-policy, resource, graph, stack, role, slot, dependency, byte-count, and checksum drift smokes, and Module Plan panel display including fetch, budget rows, byte summaries, checksum summaries, slot summaries, role summaries, dependency summaries, and browser-owned trace checkpoints from verified receipt fields and load steps are implemented. - Module Plan phase fields now give generated browser roots a lifecycle route from model bytes through manifest, assembly, adapter-family, and ordered stack apply, with phase display and checksum-consistent phase-drift smoke evidence. - Module Plan byte-count fields now bind each generated browser root's model, manifest, assembly receipt, adapter-family receipt, and ordered stack artifacts to explicit fetched-byte evidence, with byte display and checksum-consistent byte-drift smoke evidence. - Module Plan output limits now bind each generated browser root's 64 KiB generated-result cap into selector entries, served receipts, total budget math, and the Module Plan Output Limit row, with checksum-consistent output-limit drift smoke evidence. - Module Plan total budgets now bind each generated browser root's model, manifest, assembly receipt, adapter-family receipt, ordered stack artifacts, runtime scratch budget, output cap, and KV-cache budget to one exact self-assembly envelope, with Total Budget display and checksum-consistent total-budget drift smoke evidence. - Module Plan Trace now gives generated q4_0/q8_0/f32 browser roots an observed assembly sequence from plan verification through ready state, with combined-selector-assembly smoke asserting the exact checkpoint chain. - Eval-case evidence checksums now bind passed eval sidecars into selector admissions, promotion-ledger copies, selector registry entries, generated assembly receipts, and Model Provenance display; combined-selector-assembly proves q4_0/q8_0/f32 generated entries share checksum `0xabdeb569ab3eea3e`, assembly-eval-case-drift proves mismatched generated assembly digests stop before evidence or adapter-family routes, assembly-evidence-file-drift proves fetched evidence body drift stops before later evidence or adapter-family routes, adapter-family-receipt-drift proves post-evidence receipt drift stops before adapter manifests or stack artifacts, adapter-manifest-drift proves same-byte family ADP1 manifest drift stops before later manifests or stack artifacts, adapter-artifact-drift proves first family ADP1 bytes stop before later stack artifacts or Rust adapter apply, adapter-stack-prefetch-drift proves sparse ASP1 byte drift after family ADP1 fetch still stops before low-rank ALR1 fetch or Rust adapter apply, adapter-stack Rust validation proves all fetched stack members pass Rust semantic checks before the first apply, and Module Plan adapter-validation strategy now binds that Rust validate-before-apply requirement into selector and receipt metadata. - Runtime assembly diagnostics now make Rust the final proof point for applied stacks: generated q4_0/q8_0/f32 auto assembly reports `adapter_apply_count=3`, checked manual sidecars report count 1 after apply, and model free clears assembly state. - Combined selector route-soak now records three generated q4_0/q8_0/f32 cycles with per-pass requests for every module-plan, model, manifest, assembly, evidence, adapter-family, adapter manifest, and stack artifact route. - Mixed operator-family route-soak now records two sign-merge plus soup q4/q8/f32 cycles, twelve generated assemblies, and per-pass requests for every expected self-assembly route across all six generated models. - Mixed operator-family reload-soak now records two fresh page lifetimes, each defaulting to sign-merge q4 and rebuilding sign-merge plus soup q4/q8/f32 assemblies with every expected self-assembly route requested at least twice. - Combined selector extended route-soak now records five q4_0/q8_0/f32 cycles, fifteen generated assemblies, fresh local route requests on every pass, and path-flexible total-budget checks for non-canonical generated roots. - Combined selector stress route-soak now records eight q4_0/q8_0/f32 cycles, twenty-four generated assemblies, and fresh local route requests on every pass. - Combined selector reload-soak now records two fresh browser page lifetimes that each start on the q4_0 registry default and rebuild q4_0/q8_0/f32 generated self-assembly from local module-plan, assembly, adapter-family, manifest, and stack routes. - Heritable-artifact now has selector registry fields, browser Model Provenance Artifact rows, and combined-selector-assembly proof; mate-selection, phenotype-evidence, and speciation-and-fit should continue becoming typed fields, receipt or manifest fields, eval/provenance fields, or browser-smoke assertions before implementation claims. - Model Breadcrumbs and model kinship for richer sparse-mask lineage, retention-aware eval sidecars, and parent-pool relatedness fields now first implemented before recipe consumers write candidates. - Evolutionary merge recipes, Mergenetic-style adaptive search, and multi-objective evolutionary merging for planner-layer proposals, resource budgets, population objective vectors, and replayable receipt chains. - LoRA and adapters for compact skill deltas; trained low-rank adapter source intake, source-backed factor-to-ALR1 conversion and validation, source-backed ALR1 kind/dtype pairing, receipt source echoes, manifest-vs-receipt provenance checks, adapter-delta, sparse-adapter-delta, low-rank-adapter-delta, adapter-fuse for raw ADP1, f32/q8_0/q4_0 ADP1/ASP1/ALR1 runtime apply, checked browser f32/q8_0/q4_0 ADP1 sidecar routes, registry-carried generated f32/q8_0/q4_0 ADP1/ASP1/source-backed ALR1 adapter routes, generated f32/q8_0/q4_0 browser bundle roots, served ASP1 and source-backed ALR1 browser smokes, browser-verified adapter-family receipts plus manifests, receipt-bound preferred sparse ASP1 selection, and receipt-verified generated auto assembly are implemented for the current typed lane while real trained factor bundles and additional offline operators beyond blend, delta, sparse-delta, crossover, mutation, prune, DARE, federated, sign-merge, and soup remain future work. - population-based training for candidate registries, objective vectors, fitness scores, staged promotion, implemented population-review records, and implemented parent-pool recipes. - federated averaging, evolution strategies, adapter families, quantized adapter training, pruning, lottery tickets, and retention metrics for future recipe metadata, eval sidecars, and compact candidate artifacts. keep_separate: - Research references are future lanes, not current runtime claims. - Third-party framework suggestions in reports are comparison context while zero-dependency TinyRustLM remains active. report_distillation_questions: - What invariant should move from documentation into a test next? - Which UI state makes a local failure recoverable instead of mysterious? - What is the smallest useful model ABI that can support future tiny model routing without becoming a framework? - Which philosophical idea can be translated into a metric, error state, or user-visible budget? - What claim would become misleading if copied from a report into product copy today? - Which model-breeding idea can become a manifest field, compatibility check, or tiny-fixture experiment first? - Which public-copy phrase should route to .uai/taboo.uai before becoming site text? crawlability_requirements_for_future_memory: - .uai/index.uai must list every hot memory file. - .uai/startup-packet.uai must route to report-synthesis.uai before durable report wiki files. - .uai/short-term-memory.uai must record the current report-processing state and next implementation risks. - .uai/architecture.uai must include report-derived architecture pressure in typed fields. - .uai/coding-standards.uai must include report-derived engineering rules that are safe under the active prompt. - .uai/long-term-memory.uai must remain pointer-only with routing summaries and checksums. - .uai/taboo.uai must be read before public site copy, model-breeding positioning, or mutualist language work. - .uai/short-term-memory.uai must reference current report-intake indexes after every processed batch. - .uai/short-term-memory.uai must keep current_report_routes for the active bucket scan, durable report indexes, model-breeding synthesis, research reference page, UAIX strategy source, and long-term pointer ledger. - .uai/short-term-memory.uai must keep current Model Breeding concept routes, site voice route, and report/research pointer audit state after every strategy refresh. ================================================================================ END FILE: .uai/report-synthesis.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/short-term-memory.uai BYTES: 244217 SHA256: 9AF71A909542BE7A03BD7BEF0D3C63185EE0659106B186CA02BAF303DE3213CF ================================================================================ profile: gguf-mirust.short-term-memory.v108 updated_utc: 2026-06-29T20:22:33Z current_state: - 2026-06-29 extended operator schedule carry-forward: multi-parent promotion templates and selector admission records now preserve the schedule checksum, strategy/source fields, scheduled family index, command, selection rule, and output gate from validated candidate manifests. - Multi-parent admission summary validation now checks scheduled family kind against the bound operator receipt kind, and selector-registry multi-parent fixtures carry the new admission schema. - Verification passed for the promotion/admission schedule handoff: focused multi_promotion and multi_admission tests, two selector-registry admission fixture tests, format check, and full `tinyrustlm-slm-pack` passed with 324 tests. - 2026-06-29 added operator schedule carry-forward: sign-merge and soup receipts now copy the parent-pool evolution schedule checksum, strategy/status/source, scheduled family index, command, selection rule, and output gate. - Multi-parent candidate manifests now validate scheduled operator-family fields against the parent-pool recipe and carry the schedule identity for both sign-merge and soup outputs. - Verification passed for operator schedule carry-forward: cargo fmt check, focused sign_merge, soup, and multi_candidate tests, and full `tinyrustlm-slm-pack` passed with 323 tests. - Durable operator schedule carry-forward report added at wiki/gguf-mirust/reports/operator-schedule-carry-forward-memory-2026-06-29.md and routed through hot memory plus the long-term pointer ledger. - 2026-06-29 added parent-pool evolution schedule routing: `parent-pool-recipe` now writes `population-based-parent-pool-replay-v1`, planned sign-merge and soup operator families, parent seed weights, population fitness echoes, and an `evolution_schedule_checksum`. - Verification passed for parent-pool evolution schedule: focused parent_pool tests asserted operator-family fields and checksum drift rejection, `cargo fmt --all -- --check` passed, and full `tinyrustlm-slm-pack` passed with 323 tests. - Durable parent-pool evolution schedule report added at wiki/gguf-mirust/reports/parent-pool-evolution-schedule-memory-2026-06-29.md and routed through hot memory plus the long-term pointer ledger. - 2026-06-29 added all-quant file-backed converted-trained browser routing: `browser-converted-trained-bundle ... all` stages `converted-trained-f32`, `converted-trained-q8`, and `converted-trained-q4` under one q4-defaulted selector root. - Verification passed for the all-quant converted-trained route: focused browser_bundle tests, full `tinyrustlm-slm-pack` tests with 322 tests, generated root `target/browser-converted-trained-all-20260629/tinyrustlm`, and `converted-trained-registry-file` smokes for q4/q8/f32 fetching real selector/model/manifest files. - Durable browser converted-trained all-route report added at wiki/gguf-mirust/reports/browser-converted-trained-all-route-memory-2026-06-29.md and routed through hot memory plus the long-term pointer ledger. - 2026-06-29 added file-backed converted-trained browser routing: `browser-converted-trained-bundle` stages `converted-trained-q8` plus provenance, evidence sidecars, selector admission, and `models/selector.registry` under a runnable TinyRustLM root. - Verification passed for the file-backed converted-trained route: focused browser_bundle and selector tests, full `tinyrustlm-slm-pack` tests with 321 tests, generated root `target/browser-converted-trained-file-20260629/tinyrustlm`, `converted-trained-registry-file` smoke on port 8096 fetching real selector/model/manifest files, final format/syntax/diff checks, and checksum/report-summary pointer audits. - Durable browser converted-trained file route report added at wiki/gguf-mirust/reports/browser-converted-trained-file-route-memory-2026-06-29.md and routed through hot memory plus the long-term pointer ledger. - 2026-06-29 added browser converted-trained provenance proof: `converted-trained-registry` serves a compact selector entry for `converted-trained-q8`, routes a converted-trained manifest, and asserts browser Model Provenance source/admission/quality/trained-quality fields. - Verification passed for browser converted-trained provenance: node syntax for browser-smoke.js and app.js, `converted-trained-registry` on `http://127.0.0.1:8080/app/` with seed 9281, compact `multi-parent-registry` regression with seed 9282, and `git diff --check`. - Durable browser converted-trained provenance report added at wiki/gguf-mirust/reports/browser-converted-trained-provenance-memory-2026-06-29.md and routed through hot memory plus the long-term pointer ledger. - 2026-06-29 added DARE-style dropout/rescaled task-delta as another offline model-breeding operator: `dare-candidate` and `validate-dare-candidate` write and recompute normal `.slm` candidates from compatibility-bound base/target parents with signed `delta_weight_ppm`, keep/drop ppm, dropout seed, mask checksum, raw delta checksum, and rescaled delta checksum fields. - Verification passed for DARE: cargo fmt check, DARE-filtered tests with 11 tests covering default parameters, keep-zero, keep-full, seed mask changes, positive and negative signed weights, q8 candidate validation, path-level write/validate, parent checksum drift, candidate drift, and invalid parameter parsing; a q8 CLI compatibility-lineage-mutation-target-DARE-validate chain under `target/dare-cli` wrote and validated a 17,160,000-byte q8_0 DARE candidate. - Durable DARE report added at wiki/gguf-mirust/reports/dare-operator-memory-2026-06-29.md and routed through short-term memory, report synthesis, workspace route files, model docs, wiki route files, and the long-term pointer ledger. - 2026-06-29 DARE browser provenance now has compact selector-registry proof: `dare-operator-registry` renders Model Provenance Operator as `receipt-bound / dropout-rescaled-task-delta / 0x00000000000000b7`. - Verification passed for DARE browser provenance: selector tests carry `operator_kind=dropout-rescaled-task-delta` into `entry.N.operator_receipt_*`, DARE operator-kind drift is rejected, and `dare-operator-receipt-drift` falls back to static q8 with Operator unavailable; durable routing is in `wiki/gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29.md`. - 2026-06-29 blend, task-delta, and sparse task-delta browser provenance now have compact selector-registry proof: `blend-operator-registry` renders `receipt-bound / direct-parameter-weighted-average / 0x00000000000000b4`, `delta-operator-registry` renders `receipt-bound / direct-parameter-task-delta / 0x00000000000000b5`, and `sparse-delta-operator-registry` renders `receipt-bound / sparse-direct-parameter-task-delta / 0x00000000000000b6`. - Verification passed for the original two-parent operator browser provenance: `blend-operator-receipt-drift`, `delta-operator-receipt-drift`, and `sparse-delta-operator-receipt-drift` each fall back to static q8 with Operator unavailable; shared compact fixture regressions for federated, prune, crossover, and mutation positive registry modes also passed; durable routing is in `wiki/gguf-mirust/reports/two-parent-operator-browser-provenance-memory-2026-06-29.md`. - 2026-06-29 crossover and mutation browser provenance now have compact selector-registry proof: `crossover-operator-registry` renders `receipt-bound / deterministic-direct-parameter-crossover / 0x00000000000000b2`, and `mutation-operator-registry` renders `receipt-bound / deterministic-bounded-parameter-mutation / 0x00000000000000b3`. - Verification passed for crossover/mutation browser provenance: `crossover-operator-receipt-drift` and `mutation-operator-receipt-drift` both fall back to static q8 with Operator unavailable; shared compact fixture regressions for federated `multi-parent-registry`, prune `prune-operator-registry`, and prune `prune-operator-receipt-drift` also passed; node syntax passed. - 2026-06-29 prune operator browser provenance now has compact selector-registry proof: `prune-operator-registry` renders Model Provenance Operator as `receipt-bound / deterministic-magnitude-parameter-pruning / 0x00000000000000b1`, while `prune-operator-receipt-drift` falls back to static q8 with operator provenance unavailable. - 2026-06-29 selector registry now has explicit prune operator receipt evidence: `operator_kind=deterministic-magnitude-parameter-pruning` carries through receipt-bound admission into `entry.N.operator_receipt_*`, and prune operator-kind drift is rejected. - 2026-06-29 added deterministic magnitude pruning as another offline model-breeding operator: `prune-candidate` and `validate-prune-candidate` write and recompute normal `.slm` candidates from compatibility-bound base/reference parents with keep/floor ppm fields, magnitude ranking, mask checksum, and output-value checksum fields. - Verification passed for pruning: cargo fmt check, prune-filtered tests with 12 tests, selector::tests with 88 tests, q8 CLI compatibility-lineage-prune-validate chain under `target/prune-cli`, full tinyrustlm-slm-pack tests with 305 tests, workspace tests, prune browser positive and byte-drift smokes, federated fixture regression smokes, node syntax, browser-harness tests, and git diff check with line-ending normalization notices only. - Durable prune report added at wiki/gguf-mirust/reports/prune-operator-memory-2026-06-29.md and routed through short-term memory, report synthesis, workspace route files, model docs, and the long-term pointer ledger. - 2026-06-29 added mixed parent-pool operator reload-soak proof: `combined-selector-operator-family-reload-soak` runs fresh browser page lifetimes, each starting on `multi-parent-sign-merge-q4` and assembling sign-merge q4, soup q4, sign-merge q8, soup q8, sign-merge f32, and soup f32. - Verification passed for mixed operator reload-soak: served `target/browser-served-mixed-operator-cycle/tinyrustlm` on `http://127.0.0.1:8119/app/`, ran `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8119/app/ 9390 multi-parent-sign-merge-q4 combined-selector-operator-family-reload-soak 2`, proved two fresh page lifetimes with three sign-merge and three soup steps each, and port 8119 was clear after shutdown. - 2026-06-29 added mixed parent-pool operator route-soak proof: `combined-selector-operator-family-route-soak` repeats the sign-merge q4, soup q4, sign-merge q8, soup q8, sign-merge f32, and soup f32 sequence and asserts each expected self-assembly route for all six generated models is requested once per pass. - Verification passed for mixed operator route-soak: served existing `target/browser-served-mixed-operator-cycle/tinyrustlm` on `http://127.0.0.1:8118/app/`, ran `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8118/app/ 9389 multi-parent-sign-merge-q4 combined-selector-operator-family-route-soak 2`, proved 12 generated assemblies with every expected route requested at least twice, reran node syntax, and port 8118 was clear after shutdown. - 2026-06-29 extended mixed parent-pool operator cycle proof: `combined-selector-operator-family-cycle` repeats sign-merge q4, soup q4, sign-merge q8, soup q8, sign-merge f32, and soup f32 in one page while checking release-before-reassembly, Rust validation/apply deltas, stack completions, governed route counts, and local-origin requests. - Verification passed for mixed operator cycle assembly: generated `target/browser-served-mixed-operator-cycle/tinyrustlm all mixed`, served it on `http://127.0.0.1:8117/app/`, and `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8117/app/ 9388 multi-parent-sign-merge-q4 combined-selector-operator-family-cycle 2` walked 12 generated assemblies with six sign-merge steps and six soup steps; node syntax passed and port 8117 was clear after shutdown. - 2026-06-29 added mixed parent-pool operator browser roots: `browser-multi-parent-bundle all mixed` now stages sign-merge and soup q4/q8/f32 entries in one selector registry, preserving the sign-merge q4 frugal default while exposing both operator families for browser self-assembly. - Verification passed for mixed operator selector assembly: generated `target/browser-served-multi-parent-mixed-operator-family/tinyrustlm all mixed` with six admissions, 24 adapter routes, 6 adapter-family routes, 6 assembly routes, and 6 module-plan routes; `combined-selector-operator-family` seed 9387 assembled sign-merge q4, soup q4, sign-merge q8, soup q8, sign-merge f32, and soup f32 in one page; `browser_bundle::tests` passed 7 tests, `tinyrustlm-slm-pack` passed 293 tests, node syntax, cargo fmt check, diff check, and port cleanup passed. - 2026-06-29 extended generated multi-parent operator provenance: app.js now maps generated assembly-backed `multi-parent-soup-*` and `multi-parent-sign-merge-*` selector entries to the expected operator kind before accepting `entry.N.operator_receipt_*`; `generated-selector-operator-kind-drift` proves kind drift falls back before generated routes, while `generated-selector-operator-receipt-drift` still proves byte-echo drift. - Verification passed for browser multi-parent operator provenance: fresh roots `target/browser-served-multi-parent-soup-operator-kind-drift/tinyrustlm all soup` and `target/browser-served-multi-parent-sign-merge-operator-kind-drift/tinyrustlm all` passed `generated-selector-operator-kind-drift` on seeds 9381 and 9382 with only selector plus fallback q8 routes requested; sign-merge `combined-selector-assembly` seed 9383 proved q4/q8/f32 positive Operator rows; source `multi-parent-registry` seed 9384 kept `federated-local-update-average`; `selector-operator-receipt-drift` seed 9385 and generated byte drift seed 9386 passed; JS syntax, cargo fmt check, slm_pack 292 tests, diff whitespace, and port cleanup checks passed. - 2026-06-29 extended all-soup repeated self-assembly proof: `multi-parent-soup-q4 combined-selector-cycle 2` proves two q4/q8/f32 soup cycles in one page with q4 default selection, release-before-reassembly after the initial pass, fresh validation/apply work, and route/accounting checks per pass. - Verification passed for repeated all-soup browser reassembly: existing `target/browser-served-multi-parent-soup-all-check/tinyrustlm` served on `http://127.0.0.1:8098/app/`, `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8098/app/ 9359 multi-parent-soup-q4 combined-selector-cycle 2` passed, the loopback server was closed, and `cargo test -p tinyrustlm-slm-pack --quiet` passed 291 tests. - 2026-06-29 extended browser all-soup combined selector proof: `browser-smoke.js` derives combined q4/q8/f32 selector families from the requested model key, so `multi-parent-soup-q4 combined-selector-assembly` proves the soup all-root while the default combined selector remains sign-merge. - Verification passed for all-quant browser soup self-assembly: generated `target/browser-served-multi-parent-soup-all-check/tinyrustlm all soup`, served it on `http://127.0.0.1:8098/app/`, passed `multi-parent-soup-q4 combined-selector-assembly`, and added Rust coverage with `writes_combined_browser_multi_parent_soup_bundle` for the `all` quantization plus `soup` operator path. - 2026-06-29 extended browser q8 soup generated-root proof: `browser-smoke.js` now treats `multi-parent-soup-*` as generated multi-parent models for eval-proof, parent-pool, selector-registry, module-plan route-set, route-count, and adapter-stack checks, with q8 soup expected routes added for `adapter-sidecar-registry-file` and `multi-parent-registry-file`. - Verification passed for q8 browser soup smoke: generated `target/browser-served-multi-parent-soup-q8-check/tinyrustlm q8_0 soup`, served it on `http://127.0.0.1:8097/app/`, passed `multi-parent-soup-q8 adapter-sidecar-registry-file`, passed `multi-parent-soup-q8 multi-parent-registry-file`, reran `node --check tinyrustlm/tools/browser-smoke.js`, `cargo fmt --all -- --check`, focused browser_bundle/soup tests, and full `cargo test -p tinyrustlm-slm-pack --quiet` with 290 tests. - 2026-06-29 added browser parent-pool soup bundle routing: `browser-multi-parent-bundle [f32|q8_0|q4_0|all] [sign-merge|soup]` now defaults to sign-merge but can generate `multi-parent-soup-*` bundles that call `soup::write_candidate_path`, emit `soup.*` evidence files, and write `assembly_strategy=multi-parent-weighted-soup`. - Verification passed for browser soup bundle routing: node syntax checks for app.js/browser-smoke.js, focused soup bundle test, browser_bundle tests with 5 tests, module_plan tests with 46 tests, full tinyrustlm-slm-pack tests with 290 tests, cargo fmt check, and durable report wiki/gguf-mirust/reports/browser-parent-pool-soup-bundle-memory-2026-06-29.md. - Final 2026-06-29 browser soup bundle memory audit passed: 119 wiki report/research pages are represented in .uai/long-term-memory.uai, and tracked local checksum pointers checked with 0 mismatches. - 2026-06-29 generalized multi-parent candidate manifests for parent-pool operators: `multi-parent-candidate-manifest` now dispatches by `operator_kind`, recomputes either sign-merge or soup receipts, writes `candidate_manifest_status=validated-parent-pool-operator-output`, and preserves soup-specific metric fields before promotion. - Verification passed for multi-parent soup manifest handoff: cargo fmt check, focused `multi_candidate` tests with 8 tests, downstream `multi_` tests with 23 tests, full tinyrustlm-slm-pack tests with 289 tests, and durable report wiki/gguf-mirust/reports/multi-parent-soup-manifest-memory-2026-06-29.md. - 2026-06-29 added parent-pool weighted soup as another offline model-breeding operator: `soup-candidate` and `validate-soup-candidate` write and recompute normal `.slm` candidates from ledger/review/recipe/admission-bound parent pools using recipe `seed_weight_ppm` direct tensor averaging, parent-weight checksum, weighted-value checksum, and changed-from-frontier receipt fields. - Verification passed for weighted soup: cargo fmt, focused soup tests with 6 tests, full tinyrustlm-slm-pack tests with 286 tests, model README command routing, and durable report wiki/gguf-mirust/reports/weighted-soup-operator-memory-2026-06-29.md. - 2026-06-29 extended federated selector receipt route proof: a `federated-local-update-average` operator receipt now flows through candidate, promotion, admission, selector registry text, and browser Model Provenance Operator rendering with operator kind, receipt checksum, candidate checksum, and byte-count equality preserved; selector validation rejects operator-kind drift, and browser-smoke `selector-operator-receipt-drift` proves candidate byte-count drift falls back before the generated candidate becomes selectable. - Verification passed for federated selector receipt routing: cargo fmt --all -- --check, focused `rejects_selector_registry_federated_operator_receipt_kind_drift`, selector::tests with 86 tests, full tinyrustlm-slm-pack tests with 280 tests, `node --check tinyrustlm/tools/browser-smoke.js`, targeted `selector-operator-receipt-drift` fallback smoke on http://127.0.0.1:18881/app/, targeted `multi-parent-registry` positive smoke rendering `receipt-bound / federated-local-update-average / 0x00000000000000b0`, and the durable report wiki/gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29.md. - 2026-06-29 added federated/local-update as another offline model-breeding operator: `federated-candidate` and `validate-federated-candidate` write and recompute normal `.slm` candidates from compatibility-bound base/local-update parents with `local_update_weight_ppm`, local-update counts, raw delta checksum, and weighted delta checksum fields. - Verification passed for federated/local-update: cargo fmt, focused federated tests with 9 tests, full tinyrustlm-slm-pack tests with 278 tests, cargo build, and q8 CLI compatibility-lineage-federated-candidate-validate chain under `target/federated-cli`. - Durable federated operator report added at wiki/gguf-mirust/reports/federated-operator-memory-2026-06-29.md and routed through short-term memory, report synthesis, workspace route files, model docs, and the long-term pointer ledger. - 2026-06-29 added browser module-plan payload-checksum drift proof: `module-plan-payload-checksum-drift` rewrites the family ADP1 payload checksum through manifest, adapter-family receipt, assembly receipt, selector registry, and module-plan receipt while leaving the module checksum row stale, then stops at `module plan adapter module checksum mismatch` before generated model or adapter routes. - Verification passed for payload-checksum drift: node syntax check for browser-smoke, generated q4 `module-plan-payload-checksum-drift` on existing `target/module-plan-actual-module-checksums-20260629/tinyrustlm`, generated q4 `adapter-sidecar-registry-file` positive smoke on the same root, and the loopback listener was closed. - 2026-06-29 added browser-observed module-plan module-checksum proof: generated self-assembly now records accepted module checksums in browser state, Module Plan renders `Actual Module Checksums`, and generated Ready is gated on observed checksums matching receipt module checksum rows. - Verification passed for browser-observed module checksums: node syntax checks, cargo fmt check, static browser harness with 9 checks, fresh generated `target/module-plan-actual-module-checksums-20260629/tinyrustlm all`, generated `combined-selector-assembly`, generated q4 `adapter-sidecar-registry-file`, source `ui-audit`, and closed loopback listeners. - Durable browser module-plan actual module-checksums report added at wiki/gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md and routed through short-term memory, report synthesis, wiki route files, workspace route files, docs/testing, and the long-term pointer ledger. - 2026-06-29 added browser-observed module-plan module-byte proof: generated self-assembly now records accepted module byte lengths in browser state, Module Plan renders `Actual Module Bytes`, and generated Ready is gated on observed module bytes matching receipt module byte rows. - Verification passed for browser-observed module bytes: node syntax checks, cargo fmt check, static browser harness with 9 checks, generated `combined-selector-assembly` on existing `target/module-plan-actual-module-bytes-20260629/tinyrustlm`, source `ui-audit`, and closed loopback listeners. - Durable browser module-plan actual module-bytes report added at wiki/gguf-mirust/reports/browser-module-plan-actual-module-bytes-memory-2026-06-29.md and routed through short-term memory, report synthesis, wiki route files, workspace route files, docs/testing, and the long-term pointer ledger. - 2026-06-29 added browser-observed module-plan route-set proof: generated self-assembly route fetches now record `{kind,path}` entries in browser state, Module Plan renders `Actual Route Set`, and generated Ready is gated on observed route-set checksum matching `module_plan_route_set_checksum`. - Verification passed for browser-observed route set: node syntax checks, cargo fmt check, git diff --check with line-ending notices only, static browser harness with 9 checks, fresh generated `target/module-plan-observed-route-set-20260629/tinyrustlm all`, generated `combined-selector-assembly`, source `ui-audit`, and closed loopback listeners. - Durable browser module-plan observed route-set report added at wiki/gguf-mirust/reports/browser-module-plan-observed-route-set-memory-2026-06-29.md and routed through short-term memory, report synthesis, wiki route files, workspace route files, docs/testing, and the long-term pointer ledger. - 2026-06-29 added browser-owned module-plan actual fetch-count proof: generated self-assembly route fetches now increment `state.modulePlanActualFetchCount`, the Module Plan panel renders `Actual Fetches`, and generated Ready is gated on actual accepted fetch count matching `module_plan_planned_fetch_count`. - Verification passed for browser-owned actual fetch count: node syntax checks, cargo fmt check, git diff --check with line-ending notices only, static browser harness with 9 checks, generated `combined-selector-assembly` on existing `target/module-plan-actual-fetch-count-20260629/tinyrustlm`, source `ui-audit`, and closed loopback listeners. - Durable browser module-plan actual fetch-count report added at wiki/gguf-mirust/reports/browser-module-plan-actual-fetch-count-memory-2026-06-29.md and routed through short-term memory, report synthesis, wiki route files, workspace route files, docs/testing, and the long-term pointer ledger. - 2026-06-29 added browser module-plan operator receipt binding: generated selector entries now carry `entry.N.module_plan_operator_receipt_path` and `entry.N.module_plan_operator_receipt_checksum`, `.module-plan.receipt` files carry matching `operator_receipt_*` fields, and browser validation requires module-plan, assembly receipt, and fetched `sign-merge.operator` agreement before generated model bytes proceed. - Verification passed for module-plan operator receipt binding: node syntax checks for app.js and browser-smoke.js, focused `module_plan_operator` tests, selector tests with 84 tests, browser_bundle tests with 4 tests, cargo fmt check, full slm_pack tests with 269 tests, cargo test --workspace, static browser harness with 9 checks, generated `target/module-plan-operator-receipt-drift-20260629/tinyrustlm all`, generated `module-plan-operator-receipt-drift`, q4 `adapter-sidecar-registry-file` positive generated-root smoke, fresh `target/combined-selector-assembly-refresh-20260629/tinyrustlm all`, and fresh `combined-selector-assembly` proving q4_0/q8_0/f32 operator-bound self-assembly. - Durable browser module-plan operator receipt report added at wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md and routed through wiki index, knowledge map, source guide, docs/testing, workspace guidance, report synthesis, operations, test plan, startup packet, and long-term pointer ledger. - Refreshed 2026-06-29 browser module-plan operator receipt memory audit passed after the fresh combined-selector proof: 108 wiki report pages and 2 research pages are represented in .uai/long-term-memory.uai, and 220 tracked local checksum pointers were checked with 0 mismatches. - 2026-06-29 added selector-facing operator receipt carry-forward: `selector-registry` writes receipt-bound admission fields as `entry.N.operator_receipt_*`, `validate-selector-registry` rejects copied-field drift, and mate-selection checksums include the full receipt family when present. - Browser provenance now parses optional selector operator receipt metadata, validates candidate checksum and byte equality against the selected registry entry, and renders a compact Model Provenance Operator row. - Verification passed for selector operator receipt binding: focused selector receipt write/drift tests, all 82 selector tests, full tinyrustlm-slm-pack tests with 267 tests, slm_pack build, node syntax checks, browser_harness tests, static browser harness, and receipt-bound q8 CLI admission-to-registry smoke under C:\Users\AI\AppData\Local\Temp\tinyrustlm-selector-receipt-4acd025a5de0418dbc54c0ffe6c91350. - Durable selector operator receipt binding report added at wiki/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29.md, the admission report pointer is reconciled, and long-term memory routes the receipt chain through candidate, promotion, admission, and selector records. - Final 2026-06-29 selector operator receipt binding memory audit passed: 107 wiki report pages and 2 research pages are represented in .uai/long-term-memory.uai, and 219 tracked local checksum pointers were checked with 0 mismatches. - 2026-06-29 added optional operator-receipt carry-forward for two-parent selector admission records: `admission-record` and `validate-admission` accept optional `input.operator`, copy promotion receipt fields into admissions, and validate receipt-bound candidate/promotion evidence before selector-facing admission fields. - Verification passed for receipt-bound admission records: cargo fmt, focused admission tests with 21 tests, full tinyrustlm-slm-pack tests with 265 tests, cargo build, receipt-bound q8 CLI compatibility-lineage-mutation-candidate-promotion-provenance-runtime-eval-admission chain under a temp route, cargo test --workspace, and cargo fmt check. - Durable admission operator receipt binding report added at wiki/gguf-mirust/reports/admission-operator-receipt-binding-memory-2026-06-29.md and long-term pointers refreshed for that report plus admission.rs, candidate.rs, promotion.rs, and main.rs. - Final 2026-06-29 admission operator receipt binding memory audit passed: 106 wiki report pages and 2 research pages are represented in .uai/long-term-memory.uai, and 218 tracked local checksum pointers were checked with 0 mismatches. - 2026-06-29 added optional operator-receipt carry-forward for two-parent promotion templates: `promotion-template` and `validate-promotion` accept an optional trailing `input.operator`, copy receipt-bound candidate fields into promotion records, and validate receipt field equality before runtime smoke/eval gates. - Verification passed for receipt-bound promotion templates: cargo fmt, focused candidate tests with 50 tests, focused promotion tests with 15 tests, full tinyrustlm-slm-pack tests with 261 tests, cargo build, receipt-bound q8 CLI compatibility-lineage-mutation-candidate-promotion chain under a temp route, and cargo test --workspace. - Durable promotion operator receipt binding report added at wiki/gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29.md and long-term pointers refreshed for that report plus candidate.rs, promotion.rs, and main.rs. - Final 2026-06-29 promotion operator receipt binding memory audit passed: 105 wiki report pages and 2 research pages are represented in .uai/long-term-memory.uai, and 217 tracked local checksum pointers were checked with 0 mismatches. - 2026-06-29 added optional operator-receipt binding for candidate artifact manifests: `candidate-manifest` and `validate-candidate` accept an optional trailing `input.operator`, write receipt-bound fields, and validate operator id, candidate id, candidate bytes, candidate checksum, and receipt checksum against the actual `.slm`. - Verification passed for receipt-bound candidate manifests: cargo fmt check, focused candidate tests with 50 tests, receipt-bound q8 CLI compatibility-lineage-mutation-candidate-manifest-validate chain under target/candidate-operator-binding, full tinyrustlm-slm-pack tests with 257 tests, cargo test --workspace, and git diff --check with line-ending notices only. - Durable candidate operator receipt binding report added at wiki/gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29.md and long-term pointers refreshed for that report plus candidate.rs and main.rs. - Final 2026-06-29 candidate operator receipt binding memory audit passed: 104 wiki report pages and 2 research pages are represented in .uai/long-term-memory.uai, and 216 tracked local checksum pointers were checked with 0 mismatches. - 2026-06-29 added deterministic bounded mutation as another offline model-breeding operator: `mutation-candidate` and `validate-mutation-candidate` now write and recompute normal `.slm` candidates from compatibility-bound base/reference parents with seed, rate, magnitude, reference-scale, selection checksum, and delta checksum fields. - Verification passed for mutation: cargo fmt check, focused mutation tests with 11 tests, q8 CLI compatibility-lineage-mutation-validate chain under target/mutation-cli, and full tinyrustlm-slm-pack tests with 252 tests. - Durable mutation report added at wiki/gguf-mirust/reports/mutation-operator-memory-2026-06-29.md and long-term pointers added for that report plus tinyrustlm/tools/slm_pack/src/mutation.rs. - Final 2026-06-29 mutation memory audit passed: 103 wiki report pages and 2 research pages are represented in .uai/long-term-memory.uai, and 215 local checksum pointers were checked with 0 mismatches after route pointers were refreshed. - 2026-06-29 added browser module-plan route-set algorithm proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1`, browser Module Plan renders `Route Hash`, and app.js verifies selector/receipt/constant agreement before trusting route-set checksums. - Verification passed for module-plan route-set algorithm: node syntax checks, cargo fmt check, route_set tests, browser_bundle tests, browser_harness tests, selector registry receipt test, full slm_pack tests with 232 tests, static browser harness, generated `module-plan-route-set-algorithm-drift`, generated `combined-selector-assembly`, source `ui-audit`, and cleanup of generated root plus loopback servers. - Durable browser module-plan route-set algorithm report added at wiki/gguf-mirust/reports/browser-module-plan-route-set-algorithm-memory-2026-06-29.md and routed through this short-term memory, report synthesis, wiki route files, workspace route files, and the long-term pointer ledger. - Final 2026-06-29 route-set-algorithm memory audit passed: 101 wiki report pages and 2 research pages are represented in .uai/long-term-memory.uai, and 211 local checksum pointers were checked with 0 mismatches. - 2026-06-29 added browser module-plan route-set version proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_route_set_version=1`, browser Module Plan renders `Route Version`, and app.js verifies selector/receipt/constant agreement before trusting route-set checksums. - Verification passed for module-plan route-set version: node syntax checks, cargo fmt check, route_set tests, browser_bundle tests, browser_harness tests, selector registry receipt test, full slm_pack tests with 230 tests, static browser harness, generated `module-plan-route-set-version-drift`, generated `combined-selector-assembly`, source `ui-audit`, and cleanup of generated root plus loopback servers. - Durable browser module-plan route-set version report added at wiki/gguf-mirust/reports/browser-module-plan-route-set-version-memory-2026-06-29.md and routed through this short-term memory, report synthesis, wiki route files, workspace route files, and the long-term pointer ledger. - Final 2026-06-29 route-set-version memory audit passed: 100 wiki report pages and 2 research pages are represented in .uai/long-term-memory.uai, and 210 local checksum pointers were checked with 0 mismatches. - 2026-06-29 added browser module-plan route-set proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_route_set_checksum`, browser Module Plan renders `Route Set`, and app.js verifies selector/receipt/ordered route-list agreement before generated bytes. - Verification passed for module-plan route set: node syntax checks, cargo fmt check, route_set tests, browser_bundle tests, browser_harness tests, full slm_pack tests with 228 tests, static browser harness, generated `module-plan-route-set-drift`, generated `combined-selector-assembly`, source `ui-audit`, and cleanup of generated root plus loopback servers. - Durable browser module-plan route-set report added at wiki/gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29.md and routed through this short-term memory, report synthesis, wiki route files, workspace route files, and the long-term pointer ledger. - 2026-06-29 added browser module-plan planned-fetch-count proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_planned_fetch_count=21`, browser Module Plan renders `Plan Fetches`, and app.js verifies selector/receipt/formula agreement before generated bytes. - Verification passed for module-plan planned fetch count: node syntax checks, cargo fmt check, focused planned-fetch and module-count tests, browser_bundle tests, browser_harness tests, full slm_pack tests with 226 tests, static browser harness, generated `module-plan-planned-fetch-count-drift`, generated `combined-selector-assembly`, source `ui-audit`, and cleanup of generated root plus loopback servers. - Durable browser module-plan planned-fetch-count report added at wiki/gguf-mirust/reports/browser-module-plan-planned-fetch-count-memory-2026-06-29.md and routed through this short-term memory and the long-term pointer ledger. - 2026-06-29 added browser module-plan adapter validation-count proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_adapter_validation_count=3`, browser Module Plan renders `Validate Count`, and app.js checks actual Rust validation loop cardinality before adapter application. - Verification passed for module-plan adapter validation count: focused selector module-plan adapter tests, browser_bundle tests, browser_harness tests, full slm_pack tests with 224 tests, node syntax checks, cargo fmt check, generated `module-plan-adapter-validation-count-drift`, generated `combined-selector-assembly`, source `ui-audit`, and static browser harness. - Durable browser module-plan adapter validation-count report added at wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-count-memory-2026-06-29.md and routed through this short-term memory and the long-term pointer ledger. - 2026-06-29 added browser module-plan adapter apply-count proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_adapter_apply_count=3`, browser Module Plan renders `Apply Count`, and app.js compares runtime `adapter_apply_count` diagnostics after generated stack assembly. - Verification passed for module-plan adapter apply count: focused selector module-plan adapter tests, browser_harness tests, browser_bundle tests, node syntax checks, generated q4_0/q8_0/f32 receipt constant refresh, generated `module-plan-adapter-apply-count-drift`, full slm_pack tests with 223 tests, and fresh generated all-root `combined-selector-assembly` on http://127.0.0.1:8252/app/ proving q4_0, q8_0, and f32 render Apply Count `3`, report runtime `adapter_apply_count=3`, and generate after ADP1/ASP1/ALR1 stack apply. - Durable browser module-plan adapter apply-count report added at wiki/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md and routed through this short-term memory, report synthesis, wiki route files, workspace route files, and the long-term pointer ledger. - Final 2026-06-29 adapter apply-count memory audit passed: 96 wiki report pages and 2 research pages are represented in .uai/long-term-memory.uai, and 206 local checksum pointers were checked with 0 mismatches. - 2026-06-29 added browser module-plan adapter-validation proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1`, and browser Module Plan renders `Validate` for generated q4_0/q8_0/f32 entries. - Verification passed for module-plan adapter-validation strategy: node syntax checks, cargo fmt check, focused selector and browser_bundle tests, browser_harness tests, static browser harness, generated `target/module-plan-adapter-validation/tinyrustlm all`, generated `module-plan-adapter-validation-drift`, generated `combined-selector-assembly`, and source `ui-audit`. - Durable browser module-plan adapter-validation report added at wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - Final 2026-06-29 adapter-validation memory audit passed: 95 wiki report pages and 2 research pages are represented in .uai/long-term-memory.uai, and 205 local checksum pointers were checked with 0 mismatches. - 2026-06-29 handoff rescan found no new non-placeholder research files in canonical GGUF Content/Improvement buckets; the IDE-adjacent WordPress handoff path only had README placeholders, the active IDE attachment path was absent, newest attachments were WordPress plugin notice context, and the preserved 2026-06-28 ModelBreeder/zero-dependency research route remains current. - 2026-06-29 added browser module-plan runtime-reset proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_runtime_reset_strategy=reset-context-before-assembly-v1`, and browser Module Plan renders `Reset` for generated q4_0/q8_0/f32 entries. - Verification passed for module-plan runtime-reset strategy: node syntax checks, cargo fmt check, focused selector and browser_bundle tests, browser_harness tests, static browser harness, generated `target/module-plan-runtime-reset/tinyrustlm all`, generated `module-plan-runtime-reset-drift`, generated `combined-selector-cycle`, and source `ui-audit`. - Durable browser module-plan runtime-reset report added at wiki/gguf-mirust/reports/browser-module-plan-runtime-reset-memory-2026-06-29.md and routed through this short-term memory, report synthesis, workspace route files, wiki route files, and the long-term pointer ledger. - Final 2026-06-29 runtime-reset memory audit passed: 94 wiki report pages and 2 research pages are represented in .uai/long-term-memory.uai, and 204 local checksum pointers were checked with 0 mismatches. - 2026-06-29 added browser module-plan model-release proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_model_release_strategy=free-before-reassembly-v1`, and browser Module Plan renders `Release` for generated q4_0/q8_0/f32 entries. - Verification passed for module-plan model-release strategy: node syntax checks, cargo fmt check, focused selector and browser_bundle tests, browser_harness tests, static browser harness, generated `target/module-plan-model-release/tinyrustlm all`, generated `module-plan-model-release-drift`, generated `combined-selector-cycle`, and source `ui-audit`. - Durable browser module-plan model-release report added at wiki/gguf-mirust/reports/browser-module-plan-model-release-memory-2026-06-29.md and routed through this short-term memory, report synthesis, workspace route files, wiki route files, and the long-term pointer ledger. - Final 2026-06-29 model-release memory audit passed: 93 wiki report pages and 2 research pages are represented in .uai/long-term-memory.uai, and 203 local checksum pointers were checked with 0 mismatches. - 2026-06-28 added browser module-plan WASM transfer-strategy proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_wasm_transfer_strategy=copy-then-release-v1`, and browser Module Plan renders `Transfer` for generated q4_0/q8_0/f32 entries. - Verification passed for module-plan WASM transfer strategy: node syntax checks, cargo fmt check, focused selector and browser_bundle tests, browser_harness tests, static browser harness, generated `target/module-plan-wasm-transfer/tinyrustlm all`, generated `module-plan-wasm-transfer-drift`, generated `combined-selector-cycle`, and source `ui-audit`. - Durable browser module-plan WASM transfer report added at wiki/gguf-mirust/reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md and routed through this short-term memory, report synthesis, workspace route files, and the long-term pointer ledger. - 2026-06-28 latest handoff rescan found no non-placeholder research files in canonical GGUF Content/Improvement buckets; the explicit IDE attachment path was not present from this session filesystem view. - 2026-06-28 added browser module-plan WASM heap-floor proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_wasm_heap_min_bytes=65536`, browser Module Plan renders `Heap Floor`, and app.js probes WASM alloc/dealloc before generated model fetch. - Verification passed for module-plan WASM heap floor: node syntax checks, cargo fmt check, browser_harness tests, static browser harness, focused selector and browser_bundle tests, generated `target/module-plan-wasm-heap/tinyrustlm all`, generated `module-plan-wasm-heap-drift`, generated `combined-selector-cycle`, and source `ui-audit`. - Durable browser module-plan WASM heap report added at wiki/gguf-mirust/reports/browser-module-plan-wasm-heap-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 live handoff rescan found no new non-placeholder files in canonical GGUF Content/Improvement buckets or the IDE-adjacent WP handoff path; the active guidance remains the preserved 2026-06-28 ModelBreeder/zero-dependency research route. - 2026-06-28 extended browser module-plan fetch-count proof: browser-smoke now counts actual generated self-assembly requests by model-owned `/models/{model}...` and `/evidence/{model}/...` routes, expects 21 governed requests per q4_0/q8_0/f32 pass, and validates the count under the 32-fetch envelope across combined-selector-cycle and combined-selector-reload-soak. - 2026-06-28 added browser module-plan fetch-count proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_fetch_count_limit=32`; browser Module Plan renders `Fetch Limit`, computes planned self-assembly route count before generated model bytes, and current total budgets are q4_0 `173415`, q8_0 `175655`, f32 `187189`. - Verification passed for module-plan fetch count: node syntax checks, cargo fmt, focused selector fetch-count tests, selector receipt test, browser_bundle generated bundle tests, browser_harness tests, generated `target/module-plan-fetch-count-drift/tinyrustlm all`, generated `combined-selector-assembly`, generated `module-plan-fetch-count-drift`, and source `ui-audit`. - Durable browser module-plan fetch-count report added at wiki/gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser module-plan prompt-limit proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_prompt_byte_limit=4096`; browser Module Plan renders `Prompt Limit`, current total budgets are q4_0 `173415`, q8_0 `175655`, f32 `187189`, and total limit is `43454464`. - Verification passed for module-plan prompt limit: generated `combined-selector-assembly`, generated `module-plan-prompt-limit-drift`, source `ui-audit`, source `prompt-limit`, focused Rust selector/bundle/harness checks, node syntax checks, cargo fmt, and regenerated `browser-multi-parent-bundle ... all` root evidence. - Durable browser module-plan prompt-limit report added at wiki/gguf-mirust/reports/browser-module-plan-prompt-limit-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - Final 2026-06-28 fetch-count memory audit passed: 90 wiki report pages and 2 research pages are represented in .uai/long-term-memory.uai, and 199 local checksum pointers were checked with 0 mismatches. - 2026-06-28 added browser module-plan output-limit proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_output_byte_limit=65536`; browser Module Plan renders `Output Limit` for generated q4_0/q8_0/f32 entries and source roots render `unavailable`. - Verification passed for module-plan output limit: node syntax checks, cargo fmt, focused selector output-limit drift/missing-field/receipt tests, focused browser_bundle tests, full slm_pack tests with 211 tests, browser_harness tests with 6 tests, static harness with 9 checks, generated `target/module-plan-output-limit-drift/tinyrustlm all`, `combined-selector-assembly`, `module-plan-output-limit-drift`, neighboring `module-plan-runtime-scratch-drift`, and source `ui-audit` on local loopback roots. - Durable browser module-plan output-limit report added at wiki/gguf-mirust/reports/browser-module-plan-output-limit-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser module-plan WASM export-set proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_wasm_export_set=tinyrustlm-generate-v1`, and browser Module Plan renders `WASM ABI` for generated q4_0/q8_0/f32 entries. - Verification passed for module-plan WASM export set: node syntax checks, cargo fmt, selector tests with 57 tests, focused selector export-set drift, browser_bundle generated bundle tests, browser_harness tests with 6 tests, static harness with 9 checks, generated `target/module-plan-wasm-export-set-drift/tinyrustlm all`, `module-plan-wasm-export-set-drift`, `combined-selector-assembly`, and source `ui-audit`. - Durable browser module-plan WASM export-set report added at wiki/gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser module-plan sampler-cap proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_sampler_candidate_cap=1024`, and browser Module Plan renders `Sampler Cap` for generated q4_0/q8_0/f32 entries. - Verification passed for module-plan sampler cap: node syntax checks, cargo fmt check, focused selector sampler-cap drift and receipt tests, selector tests with 56 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static harness with 9 checks, generated `target/browser-served-sampler-cap/tinyrustlm all`, `combined-selector-assembly`, `module-plan-sampler-cap-drift`, and source `ui-audit`. - Durable browser module-plan sampler-cap report added at wiki/gguf-mirust/reports/browser-module-plan-sampler-cap-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser module-plan tokenizer proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_tokenizer_checksum`, and browser Module Plan renders `Tokenizer` for generated q4_0/q8_0/f32 entries. - Verification passed for module-plan tokenizer: node syntax checks, cargo fmt check, focused selector tokenizer drift and receipt tests, selector tests with 55 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static harness with 9 checks, generated `target/browser-served-tokenizer/tinyrustlm all`, `combined-selector-assembly`, and `module-plan-tokenizer-drift` on http://127.0.0.1:8104/app/. - Durable browser module-plan tokenizer report added at wiki/gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser module-plan context-token proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_context_token_limit=16`, and browser Module Plan renders `Context` for generated q4_0/q8_0/f32 entries. - Verification passed for module-plan context token: node syntax checks, cargo fmt check, focused selector drift test, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static harness with 9 checks, generated `target/browser-served-context-token/tinyrustlm all`, `combined-selector-assembly`, `module-plan-context-token-drift`, and `module-plan-kv-cache-drift` on http://127.0.0.1:8103/app/. - Durable browser module-plan context-token report added at wiki/gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser module-plan adapter-stack byte budget proof: generated selector registries and `.module-plan.receipt` files now carry `module_plan_adapter_stack_byte_budget=22144`, and browser Module Plan renders `Stack Budget` for generated q4_0/q8_0/f32 entries. - Verification passed for module-plan adapter-stack budget: node syntax checks, cargo fmt check, selector tests with 53 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static harness with 9 checks, generated `target/browser-served-stack-budget/tinyrustlm all`, `combined-selector-assembly`, `module-plan-adapter-stack-budget-drift`, and `module-plan-total-budget-drift` on http://127.0.0.1:8102/app/. - Durable browser module-plan adapter-stack budget report added at wiki/gguf-mirust/reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser module-plan KV-cache proof: Rust runtime diagnostics, generated selector registries, and `.module-plan.receipt` files now carry exact `module_plan_kv_cache_byte_budget` and `module_plan_kv_cache_page_count`; browser Module Plan renders `KV Budget` and `KV Pages` for generated q4_0/q8_0/f32 entries. - Verification passed for module-plan KV cache: node syntax checks, cargo fmt check, runtime tests with 82 tests, selector tests with 56 tests, slm_validate tests with 6 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static harness with 9 checks, generated `target/browser-served-kv-cache/tinyrustlm all`, `combined-selector-assembly`, `module-plan-kv-cache-drift`, `module-plan-total-budget-drift`, and `module-plan-total-limit-drift` on http://127.0.0.1:8101/app/. - Durable browser module-plan KV-cache report added at wiki/gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser module-plan total-limit proof: generated selector registries and `.module-plan.receipt` files now carry current prompt-aware `module_plan_total_byte_budget_limit=43454464`, and browser Module Plan renders `Total Limit` for generated q4_0/q8_0/f32 entries. - Verification passed for module-plan total limit: cargo fmt check, node syntax checks, focused selector tests with 54 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static harness with 9 checks, generated `target/browser-served-total-limit/tinyrustlm all`, `combined-selector-assembly`, and `module-plan-total-limit-drift` on http://127.0.0.1:8100/app/. - Durable browser module-plan total-limit report added at wiki/gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser selector heritable-artifact proof: generated selector registries now include deterministic heritable artifact ids and served-artifact-bound checksums, and browser Model Provenance renders Artifact rows for generated q4_0/q8_0/f32 entries. - Verification passed for browser selector heritable artifact: cargo fmt --check, node syntax checks, browser_harness tests with 6 tests, focused selector tests with 53 tests, browser_bundle tests with 4 tests, generated `target/browser-served-heritable-artifact/tinyrustlm all`, and `combined-selector-assembly` on http://127.0.0.1:8100/app/ proving q4_0/q8_0/f32 Genome/Species/Novelty/Population/Mate Selection/Phenotype/Artifact/Fitness provenance rows. - Durable browser selector heritable-artifact report added at wiki/gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser selector phenotype-evidence proof: generated selector registries now include deterministic phenotype evidence ids and runtime-eval-bound checksums, and browser Model Provenance renders Phenotype rows for generated q4_0/q8_0/f32 entries. - Verification passed for browser selector phenotype evidence: cargo fmt, node syntax checks, browser_harness tests with 6 tests, focused selector tests with 52 tests, browser_bundle tests with 4 tests, generated `target/browser-served-phenotype-evidence/tinyrustlm all`, and `combined-selector-assembly` on http://127.0.0.1:8099/app/ proving q4_0/q8_0/f32 Genome/Species/Novelty/Population/Mate Selection/Phenotype/Fitness provenance rows. - Durable browser selector phenotype-evidence report added at wiki/gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser selector mate-selection proof: generated selector registries now include deterministic mate-selection ids, parent counts, and parent-pool-bound checksums, and browser Model Provenance renders Mate Selection rows for generated q4_0/q8_0/f32 entries. - Verification passed for browser selector mate-selection: cargo fmt, node syntax checks, browser_harness tests with 6 tests, focused selector tests with 51 tests, browser_bundle tests with 4 tests, generated `target/browser-served-mate-selection/tinyrustlm all`, and `combined-selector-assembly` on http://127.0.0.1:8098/app/ proving q4_0/q8_0/f32 Genome/Species/Novelty/Population/Mate Selection/Fitness provenance rows. - Durable browser selector mate-selection report added at wiki/gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - Final mate-selection memory audit passed: report/research pointer audit found 78 reports and 2 research pages with 0 missing, local pointer checksum audit checked 187 targets with 0 mismatches, and focused reruns passed cargo fmt --check, node syntax, selector, browser_bundle, and browser_harness checks. - 2026-06-28 added browser selector population proof: generated selector registries now include deterministic population ids, `population-review-bound` population checksums, and browser Model Provenance renders Population rows for generated q4_0/q8_0/f32 entries. - Verification passed for browser selector population: cargo fmt/fmt-check, node syntax checks, browser_harness tests with 6 tests, focused selector tests with 49 tests, browser_bundle tests with 4 tests, generated `target/browser-served-multi-parent-all/tinyrustlm all`, and `combined-selector-assembly` on http://127.0.0.1:8097/app/ proving q4_0/q8_0/f32 Genome/Species/Novelty/Population/Fitness provenance rows. - Durable browser selector population report added at wiki/gguf-mirust/reports/browser-selector-population-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser selector novelty proof: generated selector registries now include deterministic novelty ids, `behavior-sketch-bound` novelty checksums, and browser Model Provenance renders Novelty rows for generated q4_0/q8_0/f32 entries. - Verification passed for browser selector novelty: cargo fmt, node syntax checks, browser_harness tests with 6 tests, focused selector tests with 48 tests, full slm_pack tests with 196 tests, generated `target/browser-served-multi-parent-all/tinyrustlm all`, and `combined-selector-assembly` on http://127.0.0.1:8096/app/ proving q4_0/q8_0/f32 Genome/Species/Novelty/Fitness provenance rows. - Durable browser selector novelty report added at wiki/gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser selector species-fit proof: generated selector registries now include deterministic species ids, `browser-fit-bound` fit checksums, and browser Model Provenance renders Species rows for generated q4_0/q8_0/f32 entries. - Verification passed for browser selector species-fit: cargo fmt, node syntax checks, browser_harness tests with 6 tests, focused selector tests with 47 tests, full slm_pack tests with 195 tests, generated `target/browser-served-multi-parent-all/tinyrustlm all`, and `combined-selector-assembly` on http://127.0.0.1:8096/app/ proving q4_0/q8_0/f32 Genome/Species/Fitness provenance rows. - Durable browser selector species-fit report added at wiki/gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser selector genome/fitness proof: generated selector registries now include deterministic genome ids, admission-bound lineage checksums, and eval-bound fitness-vector checksums, and browser Model Provenance renders Genome and Fitness rows for generated q4_0/q8_0/f32 entries. - Verification passed for browser selector genome/fitness: cargo fmt, node syntax checks, browser_harness tests with 6 tests, slm_pack tests with 193 tests, generated `target/browser-served-modelbreeder/tinyrustlm all`, and `combined-selector-assembly` on http://127.0.0.1:8096/app/ proving q4_0/q8_0/f32 Genome/Fitness provenance rows. - Durable browser selector genome/fitness report added at wiki/gguf-mirust/reports/browser-selector-genome-fitness-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 processed 4 new Improvement research files into raw evidence under raw/gguf-mirust/report-intake-2026-06-28/ and durable routes at wiki/gguf-mirust/reports/report-intake-index-2026-06-28.md plus wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md. - New guidance lanes route ModelBreeder genome, fitness vector, novelty, population, and speciation ideas plus zero-dependency browser runtime pressure for Wasm SIMD, hierarchical quantization, deterministic tokenizer/sampler, KV-cache, allocator, multimodal, and telemetry work. - 2026-06-28 added browser combined selector stress route-soak proof: `combined-selector-route-stress-soak` defaults to eight q4_0/q8_0/f32 cycles in one generated `all` root, proving twenty-four generated assemblies in one page. - Verification passed for stress route-soak: node syntax check, browser_harness tests with 6 tests, generated `target/combined-selector-route-stress-soak/tinyrustlm all`, and served-root `combined-selector-route-stress-soak` on http://127.0.0.1:8194/app/. - Durable browser combined selector stress route-soak report added at wiki/gguf-mirust/reports/browser-combined-selector-stress-route-soak-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser module-plan count-drift proof: `module-plan-count-drift` mutates served receipt `module_count` while refreshing selector module-plan checksum, proving selector `module_plan_module_count` remains authoritative. - Verification passed for module-plan count drift: node syntax check, browser_harness tests with 6 tests, generated `target/module-plan-count-drift/tinyrustlm all`, served-root `module-plan-count-drift` on http://127.0.0.1:8193/app/, and server cleanup. - Durable browser module-plan count drift report added at wiki/gguf-mirust/reports/browser-module-plan-count-drift-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser combined selector extended route-soak proof: `combined-selector-route-extended-soak` defaults to five q4_0/q8_0/f32 cycles in one generated `all` root, proving fifteen generated assemblies in one page. - Verification passed for extended route-soak: node syntax check, browser_harness tests with 6 tests, generated `target/combined-selector-route-extended-soak/tinyrustlm all`, and served-root `combined-selector-route-extended-soak` on http://127.0.0.1:8192/app/. - Durable browser combined selector extended route-soak report added at wiki/gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md and routed through short-term, report synthesis, wiki route files, and long-term pointers. - 2026-06-28 added browser module-plan WASM memory proof: generated selector entries and `.module-plan.receipt` files now bind `module_plan_wasm_memory_initial_pages=17`, captured before `init_runtime()` grows memory. - Verification passed for module-plan WASM memory: JS syntax checks, cargo fmt check, slm_pack module_plan tests with 12 tests, browser_bundle tests with 4 tests, browser_harness unit/static checks, generated `target/module-plan-wasm-memory-drift/tinyrustlm all`, `combined-selector-assembly`, `module-plan-wasm-memory-drift`, and cargo test --workspace. - Durable browser module-plan WASM memory report added at wiki/gguf-mirust/reports/browser-module-plan-wasm-memory-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 storage recovery restored E:\ from about 65.5 GiB free to about 68.0 GiB free by removing this repo's generated `target/` tree and recoverable `.vs` cache content; after focused rebuilds E:\ remained about 67.8 GiB free. - 2026-06-28 added browser module-plan total budget proof: generated selector entries and `.module-plan.receipt` files now bind `module_plan_total_byte_budget` as the exact staged module bytes plus runtime scratch before generated model fetch. - Verification passed for module-plan total budget: JS syntax checks, cargo fmt check, slm_pack module_plan tests with 11 tests, browser_bundle tests with 4 tests, browser_harness unit/static checks, generated `target/module-plan-total-budget-drift/tinyrustlm all`, `combined-selector-assembly`, `module-plan-total-budget-drift`, and cargo test --workspace. - Durable browser module-plan total budget report added at wiki/gguf-mirust/reports/browser-module-plan-total-budget-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser combined selector reload-soak proof: generated `all` roots now honor the selector registry q4_0 default on every fresh page lifetime and `combined-selector-reload-soak` rebuilds q4_0/q8_0/f32 self-assembly after separate navigations. - Verification passed for combined selector reload-soak: JS syntax checks, cargo fmt check, browser_harness unit and static checks, browser_bundle tests, generated `target/combined-selector-reload-soak/tinyrustlm all`, `combined-selector-reload-soak 2`, and strict `combined-selector-assembly` on http://127.0.0.1:8186/app/. - Durable browser combined selector reload-soak report added at wiki/gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser source-backed ALR1 contract proof: source-backed `.alr1` manifests now require exact kind/dtype pairs plus adapter-family receipt source echoes for manifest, source checksum, layout, format, and source-base contract before stack artifacts are fetched. - Verification passed for browser source-backed ALR1 contract proof: cargo fmt, cargo fmt check, JS syntax checks, focused adapter_family/browser_bundle tests, generated all-root bundle staging under target/source-backed-alr1-contract, source-backed-alr1-manifest-drift smoke, combined-selector-assembly smoke on http://127.0.0.1:8176/app/, and cargo test --workspace. - Durable browser source-backed ALR1 contract report added at wiki/gguf-mirust/reports/browser-source-backed-alr1-contract-memory-2026-06-28.md and routed through this short-term memory, report synthesis, wiki route files, and the long-term pointer ledger. - 2026-06-28 added browser source-backed ALR1 routing: generated bundles now stage reviewed adapter source templates, convert them into source-backed ALR1 artifacts, and serve those artifacts as the low-rank auto-stack member for q4_0/q8_0/f32 generated roots. - Verification passed for browser source-backed ALR1 routing: cargo fmt, cargo fmt check, JS syntax checks, focused adapter_family/browser_bundle/trained_adapter_source tests, full slm_pack tests with 186 tests, browser_harness tests with 6 tests, generated all-root bundle staging under target/source-backed-alr1-route, combined-selector-assembly browser smoke on http://127.0.0.1:18770/app/, and cargo test --workspace with 277 checks. - Durable browser source-backed ALR1 route report added at wiki/gguf-mirust/reports/browser-source-backed-alr1-route-memory-2026-06-28.md and routed through this short-term memory, report synthesis, Model Breeding reference ideas, wiki route files, and the long-term pointer ledger. - 2026-06-28 added trained adapter source ALR1 conversion: `convert-adapter-source` validates a reviewed low-rank f32 factor bundle plus base `.slm`, writes runtime ALR1 bytes, and `validate-converted-adapter-source` recomputes the artifact and manifest. - Verification passed for trained adapter source ALR1 conversion: cargo fmt, cargo fmt --all -- --check, focused `tinyrustlm-slm-pack trained_adapter_source` tests with 10 tests, full `tinyrustlm-slm-pack` tests with 185 tests, cargo build -p tinyrustlm-slm-pack, CLI adapter-source-template plus convert-adapter-source plus validate-converted-adapter-source round-trip, and cargo test --workspace. - Durable trained adapter source ALR1 report added at wiki/gguf-mirust/reports/trained-adapter-source-alr1-memory-2026-06-28.md and routed through this short-term memory, report synthesis, Model Breeding reference ideas, wiki route files, and the long-term pointer ledger. - 2026-06-28 added trained low-rank adapter source intake: `adapter-source-template` writes `adapter-source.manifest` plus raw f32 factor files, and `validate-adapter-source` recomputes shape, target tensor, factor rank, checksum, finite factor, parameter-count, and delta-L1 fields before source-backed ALR1 packaging. - Verification passed for trained adapter source intake: cargo fmt, cargo fmt --all -- --check, focused `tinyrustlm-slm-pack trained_adapter_source` tests with 6 tests, full `tinyrustlm-slm-pack` tests with 181 tests, and CLI adapter-source-template plus validate-adapter-source round-trip on a temporary tiny fixture bundle. - Durable trained adapter source report added at wiki/gguf-mirust/reports/trained-adapter-source-memory-2026-06-28.md and routed through this short-term memory, report synthesis, Model Breeding reference ideas, and the long-term pointer ledger. - 2026-06-28 added browser module-plan origin-policy proof: generated selector entries and `.module-plan.receipt` files now carry `module_plan_origin_policy=same-origin-loopback-local-v1`, and Rust selector validation plus browser receipt validation require it before generated model fetch. - Verification passed for module-plan origin policy: node syntax checks, slm_pack module_plan tests with 10 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static browser harness with 9 checks, generated `target/module-plan-origin-policy-drift/tinyrustlm all`, `module-plan-origin-policy-drift`, existing `module-plan-fetch-policy-drift`, and `combined-selector-assembly`. - Durable browser module-plan origin policy report added at wiki/gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser module-plan fetch-policy proof: generated selector entries and `.module-plan.receipt` files now carry `module_plan_fetch_policy=local-no-store-v1`, and Rust selector validation plus browser receipt validation require it before generated model fetch. - Verification passed for module-plan fetch policy: node syntax checks, slm_pack module_plan tests with 9 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static browser harness with 9 checks, generated `target/module-plan-fetch-policy-drift/tinyrustlm all`, `module-plan-fetch-policy-drift`, existing `module-plan-execution-profile-drift`, and `combined-selector-assembly`. - Durable browser module-plan fetch policy report added at wiki/gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser module-plan execution profile proof: generated selector entries and `.module-plan.receipt` files now carry `module_plan_execution_profile=single-threaded-wasm-local-v1`, and Rust selector validation plus browser receipt validation require it before generated model fetch. - Verification passed for module-plan execution profile: node syntax checks, slm_pack module_plan tests with 8 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static browser harness with 9 checks, generated `target/module-plan-execution-profile-drift/tinyrustlm all`, `module-plan-execution-profile-drift`, and `combined-selector-assembly`. - Durable browser module-plan execution profile report added at wiki/gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser module-plan runtime scratch proof: generated selector entries and `.module-plan.receipt` files now carry `module_plan_runtime_scratch_byte_budget=65536`, and Rust selector validation plus browser receipt validation require it before generated model fetch. - Verification passed for module-plan runtime scratch: node syntax checks, slm_pack module_plan tests with 7 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static browser harness with 9 checks, generated `target/module-plan-runtime-scratch-drift/tinyrustlm all`, `module-plan-runtime-scratch-drift`, and `combined-selector-assembly`. - Durable browser module-plan runtime scratch report added at wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser module-plan profile proof: generated selector entries and `.module-plan.receipt` files now carry `module_plan_profile=browser-constrained-v1`, and both Rust selector validation and browser receipt validation require it before generated model fetch. - Verification passed for module-plan profile: node syntax checks, slm_pack module_plan tests with 4 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static browser harness with 9 checks, generated `target/module-plan-profile-drift/tinyrustlm all`, `module-plan-profile-drift`, and `combined-selector-assembly`. - Durable browser module-plan profile report added at wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser combined selector route-soak proof: `combined-selector-route-soak` now runs three q4_0/q8_0/f32 cycles in one generated `all` root and requires every generated self-assembly route once per pass. - Verification passed for combined selector route-soak: node syntax checks for app.js and browser-smoke.js, browser_harness tests with 6 tests, static browser harness with 9 checks, generated `target/combined-selector-route-soak/tinyrustlm all`, and `combined-selector-route-soak 3` on the fresh generated root. - Durable browser combined selector route-soak report added at wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, short-term routes, report synthesis, and long-term pointer ledger. - 2026-06-28 memory strategy refresh confirmed the UAIX setup-file-handoff loop for this workspace: active buckets stay transient, report/research bodies stay durable in raw/wiki routes, short-term memory names the current open-next routes, and long-term memory keeps checksum pointers. - Model Breeding concept routes are now explicit in hot memory and durable research: compatible merge, sparse lineage, adapter ecology, population search, federated/local update, browser-constrained assembly, UAIX memory strategy, heritable artifacts, mate selection, phenotype evidence, and speciation-fit lanes. - 2026-06-28 strengthened browser combined selector cycle proof: app.js now calls `free_model` when a loaded generated entry is replaced by selector switching, and `combined-selector-cycle` requires one release before every post-initial q8_0/f32/q4_0/q8_0/f32 assembly. - Verification passed for combined selector release sequencing: node syntax checks for app.js and browser-smoke.js, browser_harness tests with 6 tests, static browser harness with 9 checks, generated `target/combined-selector-release/tinyrustlm all`, `combined-selector-cycle 2` on the fresh generated root, and original `combined-selector-assembly` on the established exact-summary baseline root. - 2026-06-28 added browser combined selector cycle proof: `combined-selector-cycle` now repeats q4_0/q8_0/f32 switching twice in one generated `all` root and requires fresh ADP1/ASP1/ALR1 validation, apply, stack completion, reset diagnostics, and one-token generation on every pass. - Verification passed for combined selector cycle: node syntax check, generated `target/combined-selector-cycle/tinyrustlm all`, `combined-selector-cycle 2` on the fresh generated root, and original `combined-selector-assembly` on the established exact-summary baseline root. - Durable browser combined selector cycle report added at wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser adapter stack Rust validation drift proof: checksum-consistent family ADP1 identity drift now passes browser route/byte/checksum gates, reaches Rust `validate_adapter_delta`, returns `shape mismatch`, and stops before any `apply_adapter_delta`. - Verification passed for adapter stack Rust validation drift: node syntax check, generated `target/adapter-stack-rust-validate-drift/tinyrustlm all`, `adapter-stack-rust-validate-drift` on generated drift and baseline roots, existing `adapter-stack-prefetch-drift`, normal q4 `adapter-sidecar-registry-file`, and `combined-selector-assembly`. - Durable browser adapter stack Rust validation drift report added at wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser adapter stack Rust validation proof: generated auto assembly now fetches and checksum-verifies ADP1/ASP1/ALR1 stack bytes, then calls Rust `validate_adapter_delta` for every fetched member before any `apply_adapter_delta`. - Verification passed for adapter stack Rust validation: runtime adapter tests, full runtime tests, WASM ABI smoke with `adapter validated`, static browser harness, generated `target/adapter-stack-validate/tinyrustlm all`, normal q4 `adapter-sidecar-registry-file`, combined q4/q8/f32 selector assembly, and `adapter-stack-prefetch-drift` proving drift still stops before Rust apply. - Durable browser adapter stack Rust validation report added at wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser adapter stack preflight proof: generated auto assembly now fetches and verifies the receipt-declared family ADP1, sparse ASP1, and low-rank ALR1 stack bytes before any stack member is transferred into WASM. - Verification passed for adapter stack preflight drift: node syntax checks, regenerated `target/adapter-stack-prefetch-drift/tinyrustlm all`, `adapter-stack-prefetch-drift` on http://127.0.0.1:18750/app/ proving the family ADP1 and sparse ASP1 artifacts were requested, low-rank ALR1 was not requested, `adapter artifact checksum mismatch` rendered, `model_loaded=true`, trace stopped after `adapter family verified`, and no `apply_adapter_delta` call occurred, plus normal q4 `adapter-sidecar-registry-file`, existing `adapter-artifact-drift`, browser_harness tests with 6 tests, and static browser harness with 9 checks. - Durable browser adapter stack preflight drift report added at wiki/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser adapter artifact drift proof: generated selector, module-plan, model, manifest, assembly receipt, all evidence files, adapter-family receipt, and all adapter manifests stay valid while the first family ADP1 stack artifact bytes drift, stopping before sparse/low-rank artifacts or Rust adapter apply. - Verification passed for adapter artifact drift: node syntax checks, `adapter-artifact-drift` on http://127.0.0.1:18749/app/ proving `adapter artifact checksum mismatch`, `model_loaded=true`, trace through `adapter family verified`, all adapter manifest routes, only the first stack artifact route, no later stack artifact routes, and no `apply_adapter_delta`, plus normal q4 `adapter-sidecar-registry-file`, browser_harness tests with 6 tests, and static browser harness with 9 checks. - Durable browser adapter artifact drift report added at wiki/gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser adapter manifest drift proof: generated selector, module-plan, model, manifest, assembly receipt, all evidence files, adapter-family receipt, and self adapter manifest stay valid while served family ADP1 manifest text drifts at the same byte count, stopping before sparse/low-rank manifests or ADP1/ASP1/ALR1 stack artifacts. - Verification passed for adapter manifest drift: node syntax checks, `adapter-manifest-drift` on http://127.0.0.1:18748/app/ proving `adapter 1 manifest checksum mismatch`, `model_loaded=true`, trace through `assembly evidence verified`, self/family manifest route ordering, and no later manifest/stack artifact requests, plus normal q4 `adapter-sidecar-registry-file`, browser_harness tests with 6 tests, and static browser harness with 9 checks. - Durable browser adapter manifest drift report added at wiki/gguf-mirust/reports/browser-adapter-manifest-drift-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser adapter-family receipt drift proof: generated selector, module-plan, model, manifest, assembly receipt, and all evidence files stay valid while served adapter-family receipt text drifts at the same byte count, stopping before adapter manifests or ADP1/ASP1/ALR1 stack artifacts. - Verification passed for adapter-family receipt drift: node syntax checks, regenerated `target/adapter-family-receipt-drift/tinyrustlm all`, `adapter-family-receipt-drift` on http://127.0.0.1:18747/app/ proving `adapter family receipt checksum mismatch`, `model_loaded=true`, trace through `assembly evidence verified`, and no manifest/stack artifact requests, plus normal q4 `adapter-sidecar-registry-file` on the paired generated root proving ready and ADP1 plus ASP1 plus ALR1 apply. - Durable browser adapter-family receipt drift report added at wiki/gguf-mirust/reports/browser-adapter-family-receipt-drift-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 refreshed the setup-file-handoff memory strategy from https://uaix.org/en-us/tools/ai-memory-package-wizard/#setup-file-handoff: active buckets stay transient, durable bodies stay in raw/wiki Markdown, .uai files carry routing and synthesis, short-term memory names current report/research routes, and long-term memory keeps checksum pointers. - Model Breeding reference routing now adds heritable-artifact, mate-selection, phenotype-evidence, and speciation-and-fit lanes beside compatible merge, sparse-lineage, adapter-ecology, population-search, federated/local-update, browser-constrained-assembly, and UAIX-memory-strategy lanes. - Durable research route updated at wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md; strategy dogfood updated at docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md; public-copy voice routing updated in .uai/taboo.uai. - 2026-06-28 added browser assembly eval-case drift proof: generated assembly receipt eval digests now gate startup even when selector, module-plan, and assembly receipt checksums are internally aligned. - Verification passed for assembly eval-case drift: node syntax checks, regenerated `target/assembly-eval-case-drift/tinyrustlm all`, `assembly-eval-case-drift` on http://127.0.0.1:8099/app/ proving assembly evidence rejected before evidence/adapter routes, and `combined-selector-assembly` proving q4_0/q8_0/f32 ready paths after refreshed module-plan summaries. - Durable browser assembly eval-case drift report added at wiki/gguf-mirust/reports/browser-assembly-eval-case-drift-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser assembly evidence-file drift proof: generated selector, module-plan, model, manifest, and assembly receipt bytes stay valid while one fetched evidence file body drifts, causing assembly evidence rejection before later evidence or adapter routes. - Verification passed for assembly evidence-file drift: node syntax checks, browser_harness tests with 6 tests, static browser harness with 9 checks, regenerated `target/assembly-evidence-file-drift/tinyrustlm all`, `assembly-evidence-file-drift` on http://127.0.0.1:18732/app/, and normal q4 `adapter-sidecar-registry-file` on the same generated root after refreshing module-plan byte/checksum expectations. - Durable browser assembly evidence-file drift report added at wiki/gguf-mirust/reports/browser-assembly-evidence-file-drift-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser eval-case evidence checksum routing: passed eval sidecar case evidence now carries `eval_case_evidence_checksum` through selector admissions, multi-parent admissions, promotion ledgers, selector registries, generated assembly receipts, and the browser Model Provenance panel. - Verification passed for eval-case evidence checksum routing: slm_pack tests with 168 tests, runtime tests with 77 tests, browser_harness tests with 6 tests, static browser harness with 9 checks, node syntax checks, WASM ABI smoke, generated `target/browser-assembly-trace/tinyrustlm all`, and `combined-selector-assembly` on http://127.0.0.1:8098/app/ proving q4_0/q8_0/f32 each render `1 passed` and checksum `0xabdeb569ab3eea3e`. - Durable browser eval-case evidence checksum report added at wiki/gguf-mirust/reports/browser-eval-case-evidence-checksum-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser-routed ALR1 adapter-family members: generated bundles now stage low-rank `.alr1` sidecars for f32/q8_0/q4_0 entries, adapter-family receipts and module plans include them as the third auto-apply stack member, and f32/q8_0 browser smokes prove `apply_adapter_delta` accepts the route through rebuilt WASM. - Verification passed for browser ALR1 routes: cargo fmt check, slm_pack tests with 167 tests, runtime tests with 77 tests, browser_harness tests with 6 tests, node syntax checks, WASM ABI smoke, generated `target/browser-alr1-route/tinyrustlm`, and f32/q8_0 `adapter-sidecar-registry-file` smokes on http://127.0.0.1:8097/app/ with `adapter_stack_applied(3)`. - Durable browser low-rank adapter route report added at wiki/gguf-mirust/reports/browser-low-rank-adapter-route-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - Final 2026-06-28 verification passed after ALR1 memory refresh: cargo fmt check, runtime tests with 77 tests, slm_pack tests with 165 tests, browser_harness tests with 6 tests, report pointer audit for 44 reports and 1 research page, long-term checksum audit with 151 local pointer targets, and git diff --check exited 0 with line-ending notices only. - 2026-06-28 added ALR1 low-rank adapter packages: tinyrustlm-slm-pack writes and validates deterministic low-rank f32 task-delta factor artifacts, and runtime apply reconstructs compatible deltas for loaded f32/q8_0/q4_0 models. - ALR1 keeps the same adapter identity envelope as ADP1 and ASP1 while adding low-rank payload headers, factor-rank bounds, finite factor validation, matrix-shape checks, factor-density manifest fields, and residual-L1 proof fields. - Verification passed for ALR1: cargo fmt check, focused runtime adapter tests, focused packer adapter tests, CLI compatibility-lineage-low-rank-write-validate chain, full runtime tests, full slm_pack tests, and browser-harness tests. - Durable low-rank adapter package report added at wiki/gguf-mirust/reports/low-rank-adapter-package-memory-2026-06-28.md and routed from wiki index, knowledge map, source guide, log, report synthesis, short-term routes, and long-term pointer ledger. - 2026-06-28 added browser Module Plan Trace proof: generated roots now render `0: plan verified, 1: model accepted, 2: manifest verified, 3: assembly evidence verified, 4: adapter family verified, 5: adapter stack applied, 6: ready` from browser-side checkpoints after each verified load stage completes. - Verification passed for Module Plan Trace: node syntax checks, cargo fmt check, browser_harness tests with 6 tests, static browser harness with 9 checks, generated `all` root staging under target/browser-assembly-trace/tinyrustlm, and browser-smoke `combined-selector-assembly` on http://127.0.0.1:18744/app/ for q4_0/q8_0/f32 with local-only requests and trace assertions. - Current regenerated all-root module-plan summaries are q4 bytes `0: 6592 bytes, 1: 587 bytes, 2: 1896 bytes, 3: 5421 bytes, 4: 20224 bytes, 5: 832 bytes, 6: 832 bytes` and q4 checksums `0: 0x1a6808e3098d1ce0, 1: 0xd9e1b7dcf4edbebc, 2: 0x439e8f44632dafc1, 3: 0x87c2ebbdba412645, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6, 6: 0x199a2b73d817476a`. - 2026-06-28 added browser combined selector assembly proof: `combined-selector-assembly` walks one generated `all` root through q4_0, q8_0, and f32 entries, proves each `.module-plan.receipt` is requested before that entry's `.slm`, and verifies ADP1 plus ASP1 plus ALR1 stack auto assembly before generation for all three entries. - Verification passed for combined selector assembly: node syntax check, generated `all` root staging under target/combined-selector-assembly/tinyrustlm, loopback Rust static server on port 18742, and browser-smoke `combined-selector-assembly` on DevTools port 19594 with q4_0 default, q4_0/q8_0/f32 generated entry switching, local-only requests, and server cleanup. - Final 2026-06-28 verification passed after assembly-trace memory refresh: node syntax checks for app.js and browser-smoke.js, cargo fmt check, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static browser harness with 9 checks, report/research pointer audit for 43 reports and 1 research page, and long-term checksum audit with 72 local file pointers. - 2026-06-27 refreshed UAIX File Handoff strategy from https://uaix.org/en-us/tools/ai-memory-package-wizard/#setup-file-handoff: active buckets are transient intake, durable bodies live in raw/wiki memory, short-term memory routes current reports and research, and long-term memory keeps checksum pointers. - Report pointer audit passed for current wiki/gguf-mirust/reports/*.md and wiki/gguf-mirust/research/*.md pages: 90 report pages and 2 research pages are represented in .uai/long-term-memory.uai; future report/research pages must be added to long-term memory and referenced from current_report_routes. - Model Breeding reference routing now explicitly spans compatible merge, sparse-lineage, adapter-ecology, population-search, federated/local-update, browser-constrained-assembly, and UAIX-memory-strategy lanes through wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md. - .uai/taboo.uai now carries the direct GGUF.MiRust.com voice rule for Model Breeding and UAIX strategy copy: use proof, craft, lineage, fit, local agency, routes, and implementation evidence. - 2026-06-27 added browser Module Plan checksums: generated `.module-plan.receipt` files now carry uniform `module.N.checksum` fields for the generated `.slm`, model manifest, assembly receipt, adapter-family receipt, and ordered adapter-stack artifacts. - Browser smoke now asserts generated q4 checksum display as `0: 0x1a6808e3098d1ce0, 1: 0xb3f89bf19fb0895a, 2: 0x10c2f412e7751fbd, 3: 0x0571c8fd7c145691, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6`, and source-root ui-audit asserts checksum fallback as `unavailable`. - Verification passed for module-plan checksums: node syntax checks, cargo fmt check, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, generated `all` root staging under target/browser-module-plan-checksums, generated-root q4 adapter-sidecar-registry-file smoke on port 18736/19586, generated-root q4 `module-plan-checksum-drift` smoke on port 18736/19588 proving no generated `.slm`, stack adapter, or stack manifest requests, source-root desktop/mobile ui-audit on port 18738/19590, static browser harness with 9 checks, and workspace tests with 249 checks. - Durable browser module-plan checksum report added at wiki/gguf-mirust/reports/browser-module-plan-checksums-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 added browser Module Plan byte counts: generated `.module-plan.receipt` files now carry `module.N.byte_count` fields for model bytes, model manifest text, assembly receipt text, adapter-family receipt text, and ordered adapter-stack artifacts. - Browser smoke now asserts generated q4 byte display as `0: 6592 bytes, 1: 585 bytes, 2: 1849 bytes, 3: 4316 bytes, 4: 20224 bytes, 5: 832 bytes`, and source-root ui-audit asserts byte fallback as `unavailable`. - Verification passed for module-plan byte counts: node syntax checks, cargo fmt check, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, generated `all` root staging under target/browser-module-plan-byte-counts, generated-root q4 adapter-sidecar-registry-file smoke on port 18732/19576, generated-root q4 `module-plan-byte-drift` smoke on port 18732/19572 proving no generated `.slm`, stack adapter, or stack manifest requests, source-root desktop/mobile ui-audit on port 18734/19574, static browser harness with 9 checks, and workspace tests with 249 checks. - Durable browser module-plan byte-count report added at wiki/gguf-mirust/reports/browser-module-plan-byte-counts-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 added browser Module Plan phases: generated `.module-plan.receipt` files now carry `module.N.phase` fields for model bytes, model manifest, assembly evidence, adapter-family verification, and ordered adapter-stack application. - Browser smoke now asserts generated q4 phase display as `0: load-model-bytes, 1: verify-model-manifest, 2: verify-assembly-evidence, 3: verify-adapter-family, 4: apply-adapter-stack-0, 5: apply-adapter-stack-1`, and source-root ui-audit asserts phase fallback as `unavailable`. - Verification passed for module-plan phases: node syntax checks, cargo fmt check, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, generated `all` root staging under target/browser-module-plan-phases, generated-root q4 adapter-sidecar-registry-file smoke on port 18728/19564, generated-root q4 `module-plan-phase-drift` smoke on port 18728/19566 proving no generated `.slm`, stack adapter, or stack manifest requests, source-root desktop/mobile ui-audit on port 18730/19568, static browser harness with 9 checks, and workspace tests with 249 checks. - Durable browser module-plan phases report added at wiki/gguf-mirust/reports/browser-module-plan-phases-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 added browser Module Plan dependencies: generated `.module-plan.receipt` files now carry `module.N.depends_on` fields from `runtime-wasm` through ordered model, manifest, assembly, adapter-family, and adapter-stack modules. - Browser smoke now asserts generated q4 dependency display as `0: runtime-wasm, 1: module.0, 2: module.1, 3: module.2, 4: module.3, 5: module.4`, and source-root ui-audit asserts dependency fallback as `unavailable`. - Verification passed for module-plan dependencies: node syntax checks, cargo fmt check, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, generated `all` root staging under target/browser-module-plan-dependencies, generated-root q4 adapter-sidecar-registry-file smoke on port 18724/19558, generated-root q4 `module-plan-dependency-drift` smoke on port 18724/19560 proving no generated `.slm`, stack adapter, or stack manifest requests, source-root desktop/mobile ui-audit on port 18726/19562, static browser harness with 9 checks, workspace tests with 249 checks, git diff check with line-ending notes only, and server/profile cleanup. - Durable browser module-plan dependencies report added at wiki/gguf-mirust/reports/browser-module-plan-dependencies-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 added browser Module Plan assembly slots: generated `.module-plan.receipt` files now carry typed `module.N.assembly_slot` fields for runtime model, model manifest, assembly receipt, adapter-family receipt, and ordered adapter-stack positions. - Browser smoke now asserts generated q4 slot display as `0: runtime-model, 1: model-manifest, 2: assembly-receipt, 3: adapter-family-receipt, 4: adapter-stack-0, 5: adapter-stack-1`, and source-root ui-audit asserts slot fallback as `unavailable`. - Verification passed for module-plan assembly slots: node syntax checks, cargo fmt check, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, generated `all` root staging under target/browser-module-plan-slots, generated-root q4 adapter-sidecar-registry-file smoke on port 18720/19552, generated-root q4 `module-plan-slot-drift` smoke on port 18720/19554 proving no generated `.slm`, stack adapter, or stack manifest requests, source-root desktop/mobile ui-audit on port 18722/19556, static browser harness with 9 checks, and workspace tests with 249 checks. - Durable browser module-plan assembly slots report added at wiki/gguf-mirust/reports/browser-module-plan-slots-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 added browser module-plan role drift proof: `tools/browser-smoke.js` now has `module-plan-role-drift` for generated selector roots. - The smoke mutates only the served q4 `.module-plan.receipt` `module.4.role` line while recomputing the receipt checksum and updating only the selector's module-plan checksum, so checksum, resource-budget, graph, and stack-route gates pass before role matching stops loading. - Verification passed for module-plan role drift: node syntax check, generated `all` root staging under target/browser-module-plan-role-drift, served-root q4 `module-plan-role-drift` smoke on http://127.0.0.1:18718/app/ proving selector plus module-plan requests and no q4 `.slm`, stack adapter, or stack manifest requests, cargo fmt check, workspace tests with 249 checks, temp profile cleanup, and server cleanup. - Durable browser module-plan role drift report added at wiki/gguf-mirust/reports/browser-module-plan-role-drift-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 added browser Module Plan role display: generated `.module-plan.receipt` files now carry `module.N.role` fields, and `app.js` verifies and renders the ordered role summary only after the resource, graph, role, and stack checks pass. - Browser smoke now asserts source-root fallback roles as `unavailable` and generated-root q4 roles as `0: runtime-model, 1: model-provenance-manifest, 2: assembly-evidence, 3: adapter-family, 4: adapter-stack-family-delta, 5: adapter-stack-sparse-delta`. - Verification passed for Module Plan role display: node syntax checks, cargo fmt check, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static browser harness with 9 checks, generated `all` root staging under target/browser-module-plan-role-display, source-root desktop/mobile ui-audit on port 18714/19546, generated q4 adapter-sidecar-registry-file smoke on port 18716/19548, workspace tests with 249 checks, and git diff check with line-ending notes only. - Durable browser Module Plan role display report added at wiki/gguf-mirust/reports/browser-module-plan-role-display-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 added browser Module Plan budget display: `index.html` now has Model Budget and Adapter Budget rows, and `app.js` renders receipt-derived `module_plan_model_byte_budget` and `module_plan_adapter_byte_budget` text only after existing module-plan verification. - Browser smoke now asserts source-root fallback budget rows as `unavailable` and generated-root q4 budget rows as `6592 bytes` for the model envelope plus `1048576 bytes` for the adapter envelope. - Verification passed for Module Plan budget display: node syntax checks, cargo fmt check, browser_harness tests with 6 tests, static browser harness with 9 checks, source-root desktop/mobile ui-audit on port 18710/19542, generated `all` root staging under target/browser-module-plan-budget-display, generated q4 adapter-sidecar-registry-file smoke on port 18712/19544, and workspace tests with 249 checks. - Durable browser Module Plan budget display report added at wiki/gguf-mirust/reports/browser-module-plan-budget-display-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 added browser Module Plan display: `index.html` now has a Module Plan panel and `app.js` renders verified `.module-plan.receipt` status, kind, resource class, module count, model route, and receipt-declared stack routes without parsing model or adapter bytes. - Browser smoke now asserts source-root fallback Module Plan state `none` and generated-root q4 loaded state with `browser-local-module-plan`, `browser-constrained-local-assembly`, six modules, the generated `.slm` route, and family ADP1 plus sparse ASP1 stack routes. - Verification passed for Module Plan display: node syntax checks, cargo fmt check, browser_harness tests with 6 tests, static browser harness with 9 checks, source-root desktop/mobile ui-audit on port 18706/19538, generated `all` root staging under target/browser-module-plan-display, generated q4 adapter-sidecar-registry-file smoke on port 18708/19540, workspace tests with 249 checks, git diff check with line-ending notes only, temp profile cleanup, and server/port cleanup. - Durable browser Module Plan display report added at wiki/gguf-mirust/reports/browser-module-plan-display-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 added browser module-plan stack drift proof: `tools/browser-smoke.js` now has `module-plan-stack-drift` for generated selector roots. - The smoke mutates only the served q4 `.module-plan.receipt` `module.4.adapter_path` stack line while recomputing the receipt checksum and updating only the selector's module-plan checksum, so checksum, resource-budget, and model-graph gates pass before stack matching stops loading. - Verification passed for module-plan stack drift: node syntax checks, generated `all` root staging under target/browser-module-plan-stack-drift, served-root q4 `module-plan-stack-drift` smoke on http://127.0.0.1:18704/app/ proving selector plus module-plan requests and no q4 `.slm`, stack adapter, or stack manifest requests, cargo fmt check, workspace tests with 249 checks, temp profile cleanup, and server cleanup. - Durable browser module-plan stack drift report added at wiki/gguf-mirust/reports/browser-module-plan-stack-drift-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 added browser module-plan graph drift proof: `tools/browser-smoke.js` now has `module-plan-graph-drift` for generated selector roots. - The smoke mutates only the served q4 `.module-plan.receipt` `module.0.path` graph line while recomputing the receipt checksum and updating only the selector's module-plan checksum, so browser checksum and resource-budget gates pass before graph matching stops loading. - Verification passed for module-plan graph drift: node syntax checks, generated `all` root staging under target/browser-module-plan-graph-drift, served-root q4 `module-plan-graph-drift` smoke on http://127.0.0.1:18702/app/ proving selector plus module-plan requests and no q4 `.slm` request, cargo fmt check, workspace tests with 249 checks, and server cleanup. - Durable browser module-plan graph drift report added at wiki/gguf-mirust/reports/browser-module-plan-graph-drift-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 added browser module-plan resource drift proof: `tools/browser-smoke.js` now has `module-plan-resource-drift` for generated selector roots. - The smoke mutates the served q4 `.module-plan.receipt` adapter byte budget to 1048575 while recomputing the receipt checksum and updating only the selector's module-plan checksum, so browser checksum verification passes before the resource-envelope mismatch stops loading. - Verification passed for module-plan resource drift: node syntax checks, generated `all` root staging under target/browser-module-plan-resource-drift, served-root q4 `module-plan-resource-drift` smoke on http://127.0.0.1:18700/app/ proving selector plus module-plan requests and no q4 `.slm` request, cargo fmt check, workspace tests with 249 checks, git diff whitespace check with line-ending notes only, temp profile cleanup, and server cleanup. - Durable browser module-plan resource drift report added at wiki/gguf-mirust/reports/browser-module-plan-resource-drift-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted browser module-plan resource envelopes: generated selector entries and served `.module-plan.receipt` files now carry `module_plan_resource_class=browser-constrained-local-assembly`, `module_plan_model_byte_budget`, and `module_plan_adapter_byte_budget`. - Rust selector validation rejects module-plan resource-class drift, non-canonical byte budgets, admitted-model byte drift, and adapter-family byte-budget drift; app.js verifies the same envelope before generated `.slm` fetch. - Verification passed for browser module-plan resource envelopes: node syntax checks, cargo fmt, selector tests with 28 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static browser harness with 9 checks, generated `all` root staging under target/browser-module-plan-resource, generated-root q4 adapter-sidecar-registry-file smoke showing the module-plan route before `.slm` fetch and pre-generation adapter stack apply, workspace tests with 249 checks, git diff whitespace check with line-ending notes only, temp profile cleanup, and port cleanup. - Durable browser module-plan resource report added at wiki/gguf-mirust/reports/browser-module-plan-resource-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted browser module-plan receipts: generated selector entries now carry checksum-bound `entry.N.module_plan_*` fields that point to served `.module-plan.receipt` files. - The browser now fetches and checksum-verifies the declared module plan before generated `.slm` bytes, matching model, manifest, assembly receipt, adapter-family receipt, and ordered adapter-stack members against selector metadata. - Verification passed for browser module plans: node syntax checks, cargo fmt check, selector tests with 27 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static browser harness with 9 checks, generated `all` root staging under target/browser-module-plan, generated-root q4 adapter-sidecar-registry-file smoke showing the module-plan route before `.slm` fetch and two pre-generation adapter apply calls, workspace tests with 248 checks, git diff whitespace check with line-ending notes only, server cleanup, and port cleanup. - Durable browser module-plan report added at wiki/gguf-mirust/reports/browser-module-plan-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted browser adapter-stack self assembly: generated adapter-family receipts now declare ordered auto-apply stack members, selector registries carry `adapter_auto_apply_stack_*` fields, and app.js verifies stack count/index/path/manifest fields plus aggregate adapter bytes before applying modules. - Generated browser bundles now auto-apply the receipt-declared family ADP1 plus sparse ASP1 stack before first generation while keeping the sparse ASP1 option selected; Rust still validates every ADP1/ASP1 package after byte transfer. - Verification passed for browser adapter stacks: node syntax checks, cargo fmt check, adapter_family tests with 3 tests, selector tests with 25 tests, browser_bundle tests with 4 tests, browser_harness tests with 6 tests, generated `all` root staging under target/browser-adapter-stack, generated-root q4 adapter-sidecar-registry-file smoke showing two pre-generation apply_adapter_delta calls plus `adapter_stack_applied(2)`, server cleanup, port cleanup, workspace tests with 246 checks, static browser harness with 9 checks, and git diff whitespace check with line-ending notes only. - Durable browser adapter stack report added at wiki/gguf-mirust/reports/browser-adapter-stack-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted browser runtime WASM manifest verification: app.js fetches `../runtime/tinyrustlm.wasm.manifest`, validates runtime kind/status/path/bytes/checksum/next-gate fields, recomputes the fetched WASM checksum, and only then instantiates the Rust module. - slm_pack now writes runtime WASM manifests for generated browser-multi-parent-bundle roots and exposes `runtime-wasm-manifest `; Build-TinyRustLM.ps1 runs that command after copying the release WASM into the app runtime directory. - Verification passed for browser runtime manifests: node syntax checks, PowerShell build-helper parse, cargo fmt check, slm_pack browser_bundle tests with 4 tests, browser_harness tests with 6 tests, static browser harness with 9 checks, runtime-wasm-manifest CLI refresh, VS build helper run, generated `all` root staging under target/browser-runtime-manifest, source-root single smoke, runtime-manifest-drift smoke proving no model fetch after runtime checksum mismatch, generated-root q4 adapter-sidecar-registry-file smoke, temp profile cleanup, and workspace tests with 245 checks. - Durable browser runtime manifest report added at wiki/gguf-mirust/reports/browser-runtime-manifest-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted the browser text-sidecar budget contract: generated selector registries now declare exact browser text envelopes for selector registry, manifest, receipt, and evidence text. - Rust writes and validates `selector_registry_text_byte_budget=262144`, `manifest_text_byte_budget=65536`, `receipt_text_byte_budget=131072`, and `evidence_text_byte_budget=131072`; browser registry intake requires exact matches before accepting entries. - Verification passed for browser text-sidecar contracts: node syntax checks, cargo fmt check, selector tests with 24 tests, browser_bundle tests with 3 tests, generated `all` root staging under target/browser-sidecar-contract-budget, q4 generated-root adapter-sidecar-registry-file smoke, sidecar-budget-contract fallback smoke, selector-budget regression smoke, multi-parent-registry regression smoke, adapter-sidecar-registry-q8 regression smoke, and workspace tests with 244 checks. - Durable browser text-sidecar contract report added at wiki/gguf-mirust/reports/browser-text-sidecar-contract-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted browser text-sidecar byte envelopes: selector registry text is capped at 256 KiB, `.slm` and adapter manifest text at 64 KiB, and receipt/evidence text at 128 KiB before JavaScript parses or checksums it. - The browser now decodes sidecar text only after an arrayBuffer length check for selector.registry, model manifests, assembly receipts, assembly evidence files, adapter-family receipts, and generated adapter manifests; an oversized generated adapter manifest stops generated adapter controls before artifact fetch or apply. - Verification passed for browser text-sidecar budgets: node syntax checks, cargo fmt check, generated `all` root staging under target/browser-text-sidecar-budget, q4 generated-root adapter-sidecar-registry-file smoke on port 18686/19488 with sparse ASP1 auto-applied, adapter-manifest-budget smoke on port 18686/19489 proving no exact sparse ASP1 artifact request after the oversized manifest, and workspace tests with 243 checks. - Durable browser text-sidecar budget report added at wiki/gguf-mirust/reports/browser-text-sidecar-budget-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted an adapter auto-assembly byte-budget contract: generated selector entries with adapter-family receipts now carry `entry.N.adapter_auto_apply_byte_budget=1048576` alongside auto-apply status and strategy. - The browser now requires that budget field, validates generated adapter manifest `adapter_artifact_bytes`, checks the receipt-preferred auto artifact against the budget before auto assembly, and checks fetched adapter bytes against the manifest before WASM transfer. - Verification passed for browser auto-assembly budget: node syntax checks, cargo fmt checks, selector tests with 23 tests including byte-budget drift rejection, adapter_family tests with 3 tests, browser_bundle tests with 3 tests, generated `all` root staging under target/browser-auto-assembly-budget, q4/q8/f32 generated-root adapter-sidecar-registry-file smokes on port 18684 with autoAppliedBeforeGenerate=true, normal-root tinyq4 manual adapter-sidecar smoke on port 18685, workspace tests with 243 checks, git diff --check line-ending-only, temp profile cleanup, and listening-port cleanup. - Durable browser auto-assembly budget report added at wiki/gguf-mirust/reports/browser-auto-assembly-budget-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted registry-controlled browser auto assembly: generated selector entries with adapter-family receipts now must declare `entry.N.adapter_auto_apply_status=enabled` and `entry.N.adapter_auto_apply_strategy=receipt-preferred-compatible`. - The browser now treats verified generated adapter families as auto-assembly candidates only after model load, manifest verification, assembly receipt and evidence-file verification, adapter-family receipt verification, and adapter manifest verification; it then auto-applies the receipt-preferred sparse ASP1 before first generation. - Verification passed for browser auto assembly: node syntax checks, cargo fmt checks, selector tests with 22 tests, adapter_family tests with 3 tests, browser_bundle tests with 3 tests, generated `all` root staging under target/browser-auto-assembly-contract, served-root q4/q8/f32 adapter-sidecar-registry-file smokes on port 18682 with autoAppliedBeforeGenerate=true, normal-root tinyq4 manual adapter-sidecar smoke and intercepted tinyq8 registry ADP1 smoke on port 18683, and workspace tests with 242 checks. - Durable browser auto assembly report added at wiki/gguf-mirust/reports/browser-auto-assembly-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted the browser selector budget contract: Rust selector registries now emit `selector_model_byte_budget=33554432`, validate the line, and reject admitted model byte counts above the browser budget before writing entries. - The browser now requires `selector_model_byte_budget`, rejects registries whose budget exceeds the local browser constant, and checks each `entry.N.model_bytes` against the declared registry budget before model fetch and WASM transfer. - Verification passed for the selector budget contract: node syntax checks, cargo fmt check, focused selector tests with 21 tests, browser_bundle tests with 3 tests, multi-parent-registry and selector-budget smokes on port 18680, generated `all` root staging under target/browser-selector-budget-contract with budget line and 20352/8832/6592 model bytes, q4 served-root adapter-sidecar-registry-file smoke on port 18681, Rust browser harness with 8 checks, workspace tests with 241 checks, git diff --check line-ending-only, temp profile cleanup, and listening-port cleanup. - Durable selector budget contract report added at wiki/gguf-mirust/reports/browser-selector-budget-contract-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted a browser selector byte-budget gate: selector registry entries must declare positive decimal `entry.N.model_bytes` no larger than 32 MiB before app.js accepts them. - The browser now checks a registry-selected model's fetched byte length against declared `model_bytes` before copying bytes into WASM, while rejected registries leave static fallback models available. - Verification passed for the selector budget gate: node syntax checks for app.js and browser-smoke.js, cargo fmt check, selector-budget browser smoke on http://127.0.0.1:18679/app/ proving the oversized route was not requested and tinylm16q8 fallback loaded, Rust browser harness with 8 checks, workspace tests with 239 checks, git diff --check line-ending-only, temp profile cleanup, and listening-port cleanup. - Durable selector budget report added at wiki/gguf-mirust/reports/browser-selector-budget-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted the browser frugal selector default: selector registries now write `selector_default_strategy=browser-frugal-quantized`, `selector_default_candidate_id`, and `selector_default_quantization`, ranking q4_0 before q8_0 before f32. - The browser app validates selector default metadata before accepting it and chooses the default model when no valid existing selection is present, so combined generated roots load q4_0 before any f32 bytes are fetched. - Verification passed for the frugal selector default: node syntax checks for app.js and browser-smoke.js, cargo fmt check, selector tests with 23 filtered tests, browser_bundle tests with 3 filtered tests, generated `all` root staging under target/browser-frugal-selector-default, served-root q4/q8/f32 adapter-sidecar-registry-file smokes on http://127.0.0.1:18678/app/ all observing initialSelectedModel=multi-parent-sign-merge-q4, workspace tests with 239 checks, git diff --check line-ending-only, temp profile cleanup, and listening-port cleanup. - Durable frugal selector default report added at wiki/gguf-mirust/reports/browser-frugal-selector-default-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted combined multi-quant browser selector roots: browser-multi-parent-bundle now accepts `all` and stages f32, q8_0, and q4_0 multi-parent sign-merge modules into one runnable TinyRustLM root with one selector.registry. - The combined registry carries three admitted entries, nine adapter routes, three adapter-family receipts, and three assembly receipts; existing browser receipt, manifest, evidence-file, and preferred sparse ASP1 verification is reused by selected candidate id. - Verification passed for the combined selector root: cargo fmt check, focused browser_bundle tests with 3 tests, generated `all` root staging, served-root f32/q8_0/q4_0 adapter-sidecar-registry-file smokes on http://127.0.0.1:18677/app/ with selectedAdapterBeforeApply=2, workspace tests with 238 checks, and node syntax check for browser-smoke. - Durable combined selector-root report added at wiki/gguf-mirust/reports/browser-multi-quant-selector-root-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted browser preferred adapter routing: adapter-family receipts now carry a checksum-bound preferred adapter index/path/manifest path, preferring sparse ASP1 when present, and app.js verifies those fields before defaulting the Adapter Sidecar selector. - tools/browser-smoke.js no longer script-selects generated sparse ASP1; adapter-sidecar-registry-file now proves the browser-selected receipt preference with selectedAdapterBeforeApply=2 before Apply. - Verification passed for preferred adapter routing: node syntax checks, cargo fmt check, focused adapter_family and browser_bundle tests, full workspace tests with 237 checks, generated f32/q8_0 bundle staging, served-root f32 smoke on http://127.0.0.1:18675/app/, and served-root q8_0 smoke on http://127.0.0.1:18676/app/ applying receipt-selected sparse ASP1. - Durable browser preferred adapter route report added at wiki/gguf-mirust/reports/browser-preferred-adapter-route-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted browser sparse adapter routing: generated browser bundles now expose self ADP1, family ADP1, and sparse ASP1 adapter-family members through selector.registry and served manifests. - app.js now accepts local .adp1 or .asp1 adapter routes, derives expected manifest kind and dtype from the route extension, verifies the served adapter-family receipt and all served adapter manifests, checks the selected artifact checksum, and still leaves byte parsing to Rust. - tools/browser-smoke.js adapter-sidecar-registry-file now selects the generated sparse ASP1 option and requires the ASP1 manifest plus artifact route in the network trace. - Verification passed for browser ASP1 routing: node --check app.js/browser-smoke.js/wasm-abi-smoke.js, cargo fmt --all -- --check, full workspace tests, WASM ABI smoke, Rust browser harness, focused selector/adapter_family/browser_bundle tests, full slm_pack with 151 tests, runtime WASM rebuild/copy, generated f32/q8_0/q4_0 browser bundle staging, served-root f32 adapter-sidecar-registry-file smoke on http://127.0.0.1:18672/app/, and q8_0/q4_0 served-root sparse ASP1 smokes on http://127.0.0.1:18673/app/ and http://127.0.0.1:18674/app/ preserving active quantization after apply. - Durable browser sparse adapter route report added at wiki/gguf-mirust/reports/browser-sparse-adapter-route-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted the first compact adapter package bead: tinyrustlm-slm-pack now writes sparse ASP1 task-delta adapter packages and recomputable sparse manifests. - sparse-adapter-delta consumes a passing compatibility report, validated lineage, compatibility-bound base and target parent .slm files, signed delta weight, and keep rate; it writes selected target-minus-base entries as sorted `(value_index, delta)` pairs with density, nonzero retention, sparse mask checksum, parent identity, tokenizer, tensor layout, and adapter checksum fields. - validate-sparse-adapter-delta recomputes ASP1 package bytes and manifest text from the parents; tinyrustlm-runtime now parses ADP1, ASP1, or ALR1 and applies compatible raw, sparse, or low-rank packages to loaded f32, q8_0, or q4_0 tensors, re-quantizing compact tensors after updates. - Verification passed for the ASP1 sparse adapter package bead: cargo fmt --all, cargo fmt --all -- --check, focused runtime sparse adapter tests with 3 tests, focused slm_pack sparse adapter artifact tests with 2 tests, runtime suite with 75 tests, adapter module with 11 tests, full slm_pack suite with 150 tests, and workspace suite with 236 tests. - Durable sparse adapter package report added at wiki/gguf-mirust/reports/sparse-adapter-package-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted file-backed quantized generated adapter bundles: browser-multi-parent-bundle now accepts f32, q8_0, or q4_0 and stages matching multi-parent-sign-merge roots with selector registry, model, manifest, assembly receipt, evidence files, adapter-family receipt, adapter manifests, self ADP1, family ADP1, and sparse ASP1 routes. - tools/browser-smoke.js adapter-sidecar-registry-file now proves generated roots from real served files, including selector.registry, .slm, .slm.manifest, .assembly.receipt, nine evidence files, .adapter-family.receipt, ADP1/ASP1 manifest files, the selected sparse .asp1 request, adapter applied response, and preserved active quantization mode after apply. - Verification passed for file-backed quantized generated bundles: node syntax checks, PowerShell parse, cargo fmt check, focused browser_bundle tests, full packer tests with 148 tests, workspace tests with 231 tests, Rust browser harness, WASM ABI smoke, q8_0/q4_0 bundle staging, q8_0/q4_0 served-root adapter-sidecar-registry-file smokes, dependency scan, public-copy scan, long-term ledger audit, git diff --check line-ending-only, and no leftover local server or browser smoke processes on the used ports. - 2026-06-27 promoted quantized registry-carried ADP1 adapter routes: selector registries now accept f32, q8_0, and q4_0 adapter sidecars when the adapter apply status matches the admitted entry quantization. - app.js now carries the registry entry quantization into adapter manifest validation, so generated adapter-family manifests must match the selected model's base quantization before options are enabled. - Verification passed for quantized registry adapters: node syntax checks, selector tests with 17 tests, adapter_family tests with 3 tests including a q8_0 family receipt, full slm_pack tests with 147 tests, and headless adapter-sidecar-registry-q8 smoke. - 2026-06-27 promoted runtime f32/q8_0/q4_0 ADP1 adapter apply: tinyrustlm-runtime now validates compatible ADP1 packages against loaded f32, q8_0, or q4_0 model identity, re-quantizes compact q8_0/q4_0 tensors when needed, and clears generation/KV state after success. - Static browser Adapter Sidecar routing now covers checked tiny f32, q8_0, and q4_0 self-sidecars: tiny-test-model-self.adp1, tiny-test-model-q8-self.adp1, and tiny-test-model-q4-self.adp1. - Verification passed for quantized adapter apply: focused runtime adapter tests, runtime generation diagnostics reset test, slm_pack adapter tests, rebuilt WASM, Node ABI smoke, node syntax checks, and headless tinyq8/tinyq4 adapter-sidecar smokes. - 2026-06-27 promoted population-review objective-vector metadata: population-review now emits fitness_objective_vector_version, kind, weight unit, weight sum, three weighted objective records, a contract checksum, and per-entry fitness_objective_vector_checksum fields. - validate-population-review recomputes the weighted quality/frugality/quantization objective contract and per-entry score-vector checksums from the promotion ledger plus admissions before parent-pool recipes or selector routing consume the review. - Verification passed for population objective-vector metadata: cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack population:: with 7 tests, parent_pool:: with 7 tests, full tinyrustlm-slm-pack tests with 145 tests, cargo test --workspace with 223 tests, dependency-section scan, public-copy scan, and git diff --check line-ending-only. - 2026-06-27 promoted parent-pool relatedness metadata: parent-pool-recipe receipts now include relatedness_metric, relatedness_scope, relatedness_pair_count, relatedness_all_pairs_status, relatedness_contract_checksum, and per-parent relatedness_group fields. - sign-merge-candidate now echoes parent-pool relatedness fields into operator receipts, and multi-parent-candidate-manifest carries the relatedness summary alongside receipt and recipe checksums. - Verification passed for parent-pool relatedness metadata: cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack parent_pool:: with 7 tests, sign_merge:: with 5 tests, multi_candidate:: with 5 tests, full tinyrustlm-slm-pack tests with 144 tests, cargo test --workspace with 222 tests, dependency-section scan, public-copy scan, and git diff --check line-ending-only. - 2026-06-27 promoted sparse task-delta mask metadata: sparse-delta-candidate receipts now include sparse_unchanged_parameter_count, sparse_pruned_nonzero_delta_count, sparse_density_ppm, sparse_nonzero_delta_retention_ppm, sparse_mask_metadata_version, sparse_mask_kind, sparse_retention_scope, and sparse_mask_checksum. - validate-sparse-delta-candidate recomputes the sparse candidate bytes and receipt including the implicit top-k mask metadata, so selected-position identity now has a durable receipt field before candidate-manifest work. - Focused verification passed for sparse mask metadata: cargo fmt --all, cargo test -p tinyrustlm-slm-pack sparse_delta:: with 7 tests, and a CLI compatibility-lineage-sparse-delta-validate-sparse-delta chain under target/sparse-mask-metadata with the new receipt fields present. - 2026-06-27 promoted browser-visible assembly evidence receipts for generated multi-parent bundles: browser-multi-parent-bundle now writes multi-parent-sign-merge-f32.assembly.receipt and selector.registry carries entry.N.assembly_receipt_path, checksum, label, status, and kind. - app.js now fetches the served .assembly.receipt after the selected model and manifest load, recomputes its text checksum, matches model path, manifest path, model checksum, local evidence routes, evidence checksum fields, and adapter-family receipt checksum, fetches each referenced local evidence file, verifies each evidence text checksum, then renders Assembly Evidence fields in the browser. - tools/browser-smoke.js adapter-sidecar-registry-file now requires the generated trace to include /models/multi-parent-sign-merge-f32.assembly.receipt plus all nine /evidence/multi-parent-sign-merge-f32/ routes and checks rendered assembly kind, parent count, operator checksum, ledger checksum, and next gate before the family ADP1 sidecar apply can pass. - Verification passed for assembly receipt evidence-chain routing: node syntax checks, cargo fmt check, Rust browser harness with 8 checks, browser_bundle test, full slm_pack tests with 142 tests, workspace tests with 220 tests, generated bundle staging, and generated-root adapter-sidecar-registry-file browser smoke on http://127.0.0.1:18644/app/ including all nine evidence-file requests. - Durable assembly receipt report added at wiki/gguf-mirust/reports/assembly-receipt-memory-2026-06-27.md and routed from wiki index, knowledge map, source guide, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted browser pre-transfer ADP1 artifact checksum verification: app.js recomputes the selected local ADP1 package checksum before copying bytes into WASM while Rust remains the ADP1 structure and tensor mutation authority. - tools/browser-smoke.js now has adapter-sidecar-checksum-mismatch mode, which corrupts the checked tiny f32 sidecar response and proves the browser rejects it before apply_adapter_delta while preserving prior generation diagnostics. - browser-multi-parent-bundle now writes a runnable TinyRustLM root by copying app shell and WASM runtime alongside models/, evidence/, selector.registry, ADP1 sidecars, adapter manifests, and adapter-family receipt. - Verification passed for adapter artifact checksum and self-contained generated bundle routing: node syntax checks, cargo fmt check, adapter_family filtered tests, selector tests with 19 tests, browser_bundle test, full slm_pack tests with 141 tests, workspace tests with 219 tests, adapter-sidecar smoke, adapter-sidecar-checksum-mismatch smoke, and self-contained generated-root adapter-sidecar-registry-file smoke. - 2026-06-27 refreshed model-breeding memory strategy per the UAIX setup-file-handoff route: research/reference bodies stay in wiki research pages, reports stay in durable wiki/raw evidence, short-term memory routes the current state, and long-term memory remains a checksum pointer ledger. - Model-breeding references now include kinship metrics, sparse-mask breadcrumbs, evolutionary merge recipes, adaptive search, and multi-objective fitness as diverse lanes for parent-pool metadata, sparse deltas, planner proposals, replayable receipts, and population-review fields; sparse masks, population objective vectors, and parent relatedness now have first typed receipt forms. - .uai/taboo.uai now explicitly governs model-breeding, mutualist, tiny-ecology, UAIX strategy, and GGUF.MiRust.com public copy so this site stays focused on proof, craft, lineage, fit, local agency, and evidence. - 2026-06-27 promoted browser-side adapter manifest verification for generated families: app.js now fetches each served .adp1.manifest, recomputes its text checksum, verifies artifact kind/status/dtype/apply status, manifest byte count, artifact checksum, and shared base-quantization identity fields before enabling family options. - tools/browser-smoke.js adapter-sidecar-registry-file now requires generated .adp1.manifest and .asp1.manifest routes in addition to the adapter-family receipt route before the sparse sidecar apply can pass. - Verification passed for browser-side adapter manifest verification: node syntax checks, cargo fmt check, adapter_family filtered tests, selector tests with 19 tests, browser_bundle test, full slm_pack tests with 141 tests, workspace tests with 219 tests, and generated served-root adapter-sidecar-registry-file browser smoke including receipt plus both manifest requests. - 2026-06-27 promoted browser-side adapter-family receipt verification: app.js now fetches the served .adapter-family.receipt, recomputes its text checksum, and matches member routes, manifest routes, labels, apply statuses, checksums, and shared base-quantization identity fields before enabling generated family options. - tools/browser-smoke.js adapter-sidecar-registry-file now requires the generated multi-parent network trace to include /models/multi-parent-sign-merge-f32.adapter-family.receipt before the family sidecar apply can pass. - 2026-06-27 promoted adapter-family receipt routing: browser-multi-parent-bundle now writes multi-parent-sign-merge-f32.adapter-family.receipt from generated ADP1 manifests and validates shared adapter identity before selector routing. - selector.registry now carries entry.N.adapter_family_receipt_path, receipt checksum, label, status, strategy, and adapter count for generated adapter families; app.js filters the metadata, verifies the served receipt, and keeps ADP1 bytes opaque to JavaScript. - Verification passed for browser-side adapter-family receipt verification: node syntax checks, cargo fmt check, adapter_family filtered tests, selector tests with 19 tests, browser_bundle test, full slm_pack tests with 141 tests, workspace tests with 219 tests, and generated served-root adapter-sidecar-registry-file browser smoke including the receipt request. - Durable adapter-family receipt report added at wiki/gguf-mirust/reports/adapter-family-receipt-memory-2026-06-27.md and routed from wiki index, knowledge map, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted registry-carried Adapter Family routing: generated selector registries can attach multiple local ADP1 sidecar routes, manifest routes, labels, apply statuses, and checksums to one admitted f32/q8_0/q4_0 model entry when the status matches quantization. - browser-multi-parent-bundle now stages multi-parent-sign-merge-f32.slm, its manifest, selector.registry, evidence chain, multi-parent-sign-merge-f32-self.adp1, multi-parent-sign-merge-f32-family.adp1, and both adapter manifests under a generated TinyRustLM root. - tools/browser-smoke.js adapter-sidecar-registry-file mode now loads the generated f32 model from selector.registry, selects the second registry adapter option, applies the family ADP1 sidecar, and verifies f32 diagnostics reset after Rust apply_adapter_delta succeeds. - Verification passed for registry-carried Adapter Family routing: node syntax, cargo fmt check, focused selector tests with 17 tests, browser_bundle test, full slm_pack tests with 137 tests, Rust browser harness with 8 checks, WASM ABI smoke, cargo test --workspace with 215 tests, and generated served-root adapter-sidecar-registry-file smoke. - Durable registry adapter family report added at wiki/gguf-mirust/reports/registry-adapter-family-memory-2026-06-27.md and routed from wiki index, knowledge map, log, report synthesis, and long-term pointer ledger. - 2026-06-27 promoted browser Adapter Sidecar routing: tinyf32, tinyq8, and tinyq4 now expose checked local self-ADP1 routes and call apply_adapter_delta from the static app. - The checked tiny browser sidecar path filters adapter routes to local ../models/*.adp1; generated adapter families also allow local ../models/*.asp1 routes, keep JavaScript out of adapter-byte parsing, copy bytes into WASM, render adapter applied, and clear host-side generation context after Rust resets token/KV state. - Verification passed for browser Adapter Sidecar routing and is superseded by the f32/q8_0/q4_0 sidecar smoke entry above. - Durable sidecar report added at wiki/gguf-mirust/reports/browser-adapter-sidecar-memory-2026-06-27.md and routed from wiki index, knowledge map, log, report synthesis, and long-term pointer ledger. - 2026-06-27 superseded runtime f32 ADP1 adapter apply with f32/q8_0/q4_0 coverage: tinyrustlm-runtime validates compatible ADP1 packages against loaded models and keeps compact quantized tensors compact after apply. - Runtime adapter apply validates package identity, package checksum, payload checksums, tokenizer checksum, tensor layout checksum, tensor directory metadata, finite f32 deltas, and all fused values before mutating or re-quantizing tensors. - Runtime::apply_adapter_delta clears generation tokens, KV cache, and generation diagnostics after successful apply while keeping the loaded model and sampling configuration; the WASM export apply_adapter_delta returns explicit ErrorCode values. - Verification passed for the original f32 ADP1 apply bead and is superseded by the f32/q8_0/q4_0 apply entry above. - 2026-06-27 promoted generated browser-served multi-parent bundle routing: tinyrustlm-slm-pack browser-multi-parent-bundle writes a tiny f32 sign-merge .slm, manifest, selector.registry, and evidence chain under a target TinyRustLM root. - tools/browser-smoke.js now has multi-parent-registry-file mode that loads multi-parent-sign-merge-f32 from real served selector.registry, .slm, and .slm.manifest files; tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke stages that bundle on a separate local port. - Verification passed for generated browser-served multi-parent bundle routing: PowerShell parse, node --check browser-smoke.js, focused browser_bundle test, live file-backed browser smoke, cargo fmt checks, cargo test --workspace with 207 tests, Rust browser harness, full Visual Studio BrowserSmoke, public-copy scan, dependency-section scan, and git diff --check line-ending-only. - 2026-06-27 promoted the multi-parent selector-registry route binding: tinyrustlm-slm-pack selector-registry now accepts selector admission records and multi-parent admission records. - selector-registry selects the admission validator by record version, preserves selector id binding, duplicate candidate and duplicate checksum checks, served tinyrustlm/models route checks, and validate-selector-registry recomputes mixed-version registries. - Verification passed for the multi-parent selector-registry route binding: cargo fmt --all -- --check, focused selector tests with 9 tests, packer tests with 132 tests, workspace tests with 206 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, dependency-section scan, and git diff --check line-ending-only. - 2026-06-27 refreshed the UAIX File Handoff strategy from https://uaix.org/en-us/tools/ai-memory-package-wizard/#setup-file-handoff: active drops are transient intake, report bodies stay in raw/wiki durable memory, short-term memory routes current state, and long-term memory stays checksum-bearing pointers. - Model-breeding research routing now points diverse future lanes through wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md, spanning soups, alignment, task vectors, sparse/sign-aware composition, adapters, federated updates, pruning masks, retention metrics, and evolution-style search. - 2026-06-27 promoted the multi-parent promotion-template gate: tinyrustlm-slm-pack now writes multi-parent-promotion-template records for validated sign-merge candidate manifests. - multi-parent-promotion-template validates the multi-parent candidate manifest against ledger, review, recipe, admissions, parent .slm files, candidate .slm bytes, and sign-merge receipt, then binds candidate manifest checksum, operator receipt checksum, recipe checksum, parent count, candidate .slm fields, pending runtime-smoke/eval status, and not-admitted selector state. - validate-multi-parent-promotion recomputes the promotion template and rejects candidate manifest drift, promotion drift, and candidate byte drift before runtime-smoke, eval, admission, ledger, or selector work consumes a sign-merge output. - Verification passed for the multi-parent promotion-template gate: cargo fmt --all, cargo fmt --all -- --check, focused multi_promotion tests with 5 tests, focused multi_candidate tests with 5 tests, focused tinyrustlm-slm-pack tests with 123 tests, cargo test --workspace with 197 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, dependency-section scan, and git diff --check line-ending-only. - 2026-06-27 promoted the multi-parent candidate-manifest gate: tinyrustlm-slm-pack now writes multi-parent-candidate-manifest records for validated sign-merge output. - multi-parent-candidate-manifest validates the sign-merge receipt against ledger, review, recipe, admissions, parent .slm files, and candidate .slm bytes, then binds receipt checksum, parent-pool recipe checksum, relatedness summary, parent summaries, candidate .slm fields, pending eval status, and next promotion route. - validate-multi-parent-candidate recomputes the manifest and rejects receipt drift, manifest drift, and candidate byte drift before runtime-smoke, eval, admission, ledger, or selector work consumes a sign-merge output. - Verification passed for the multi-parent candidate-manifest gate: cargo fmt --all, cargo fmt --all -- --check, focused multi_candidate tests with 5 tests, focused sign_merge tests with 5 tests, focused tinyrustlm-slm-pack tests with 118 tests, cargo test --workspace with 192 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, dependency-section scan, and git diff --check line-ending-only. - 2026-06-27 promoted the offline sign-aware parent-pool merge gate: tinyrustlm-slm-pack now writes sign-merge-candidate .slm artifacts plus recomputable receipts from validated parent-pool recipes. - sign-merge-candidate validates the promotion ledger, population review, parent-pool recipe, admission records, and supplied parent .slm files; parent 0 is the frontier base and remaining parents contribute seed-weighted positive or negative parameter deltas. - validate-sign-merge-candidate recomputes the candidate bytes and receipt, rejects parent order drift, recipe drift, single-parent recipes, and candidate byte drift, and feeds the multi-parent candidate manifest before runtime-smoke/eval/admission evidence. - Verification passed for the sign-merge gate: cargo fmt --all -- --check, focused sign_merge tests with 5 tests, focused tinyrustlm-slm-pack tests with 113 tests, cargo test --workspace with 187 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, and git diff --check line-ending-only. - 2026-06-27 promoted the offline parent-pool recipe gate: tinyrustlm-slm-pack now writes deterministic parent-pool recipes from promotion ledgers, population reviews, and admission records. - parent-pool-recipe validates the population review first, requires all selected parents to share one direct-parameter contract, records the frontier and parent-pool roles, assigns seed_weight_ppm values normalized from population_fitness_ppm, and binds a deterministic relatedness identity for the selected parent family. - validate-parent-pool-recipe recomputes the recipe from ledger, review, and admissions; it rejects recipe drift, population-review drift, and mixed direct-parameter contracts before sign-merge or other recipe consumers. - Verification passed for the parent-pool recipe gate: cargo fmt --all -- --check, focused parent_pool tests with 6 tests, focused tinyrustlm-slm-pack tests with 108 tests, cargo test --workspace with 182 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, CLI promotion-ledger-population-review-parent-pool-recipe-validate-parent-pool-recipe chain, dependency-section scan, public-copy scan, and git diff --check line-ending-only. - 2026-06-27 promoted the offline population-review model-breeding gate: tinyrustlm-slm-pack now writes deterministic population review records from promotion ledgers plus admission records. - population-review validates the promotion ledger against the same admissions, scores each admitted candidate with quality700-frugality200-quantization100, records the weighted objective-vector contract and per-entry objective checksum, records frontier_candidate_id, and routes non-frontier candidates to the population parent pool. - validate-population-review recomputes ledger-backed rankings, frontier selection, fitness ppm fields, objective-vector fields, per-entry objective checksums, and review keys; it rejects review drift and ledger drift before selector registry or parent-selection work. - Verification passed for the population-review gate: cargo fmt --all -- --check, focused population tests with 6 tests, focused tinyrustlm-slm-pack tests with 102 tests, cargo test --workspace with 176 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, CLI promotion-ledger-population-review-validate-population-review chain, dependency-section scan, public-copy scan, and git diff --check line-ending-only. - 2026-06-27 promoted the sparse task-delta model-breeding operator: tinyrustlm-slm-pack now writes sparse-delta-candidate .slm artifacts with recomputable receipts. - sparse-delta-candidate consumes a passing compatibility report, validated lineage, compatibility-bound base and target parent .slm files, signed parts-per-million delta weight, and a parts-per-million keep rate; it selects largest absolute target-minus-base deltas, applies the signed weight to selected entries, leaves other entries at base values, and records selection metric plus total, nonzero, selected, and pruned parameter counts. - validate-sparse-delta-candidate recomputes selected deltas, candidate bytes, and receipt, rejects sparse candidate drift and invalid sparse parameters, and feeds the existing candidate-manifest, promotion, runtime-smoke, eval, admission, ledger, and selector-registry path. - Verification passed for the sparse task-delta gate: cargo fmt --all, cargo fmt --all -- --check, focused sparse_delta tests with 6 tests, focused tinyrustlm-slm-pack tests with 96 tests, cargo test --workspace with 170 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, CLI q8 compatibility-lineage-sparse-delta-validate-candidate chain, dependency-section scan, public-copy scan, and git diff --check line-ending-only. - Next useful model-breeding bead is real trained weights, trained LoRA modules, additional offline operators beyond blend/delta/sparse-delta/crossover/mutation/federated/sign-merge, or longer selector-route exercises after runtime f32/q8_0/q4_0 ADP1/ASP1/ALR1 apply and browser-routed ADP1/ASP1/ALR1 families, while keeping ordinary .slm validation, two-parent admission, ledger, and selector routing intact. - 2026-06-27 promoted the adapter-fuse model-breeding bridge: tinyrustlm-slm-pack now turns validated ADP1 adapter packages into normal .slm candidates with recomputable receipts. - fuse-adapter-delta consumes a passing compatibility report, validated lineage, compatibility-bound base and target parent .slm files, an adapter artifact, and its manifest; it validates the package, checks ADP1 header and tensor directory metadata against the base parent, writes base plus deltas as a normal candidate .slm using the base dtype/layout, and records adapter package checksum, manifest checksum, candidate checksum, lineage checksum, and next gate. - validate-fuse-adapter-delta recomputes the fused candidate bytes and receipt, rejects adapter manifest drift and fused candidate drift, and feeds the existing candidate-manifest, promotion, runtime-smoke, eval, admission, ledger, and selector-registry path. - Verification passed for the adapter-fuse candidate gate: cargo fmt --all, cargo fmt --all -- --check, focused adapter tests with 9 tests, focused tinyrustlm-slm-pack tests with 90 tests, cargo test --workspace with 164 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, CLI compatibility-lineage-adapter-write-validate-fuse-validate chain, dependency-section scan, public-copy scan, and git diff --check line-ending-only. - 2026-06-27 promoted the next modular model-breeding artifact gate: tinyrustlm-slm-pack now writes raw f32 task-delta adapter packages and recomputable manifests. - adapter-delta consumes a passing compatibility report, validated lineage, compatibility-bound base and target parent .slm files, writes an ADP1 raw-f32-task-delta-v1 binary package containing target-minus-base tensor deltas, and records parent checksums, lineage checksum, tensor layout checksum, tokenizer checksum, adapter checksum, and offline apply status. - validate-adapter-delta recomputes adapter bytes and manifest, rejects parent checksum drift, adapter byte drift, and manifest drift, and feeds fuse-adapter-delta or runtime f32/q8_0/q4_0 ADP1 apply. - Verification passed for the adapter-delta artifact gate: cargo fmt --all, cargo fmt --all -- --check, focused tinyrustlm-slm-pack tests with 86 tests, cargo test --workspace with 160 tests, strict slm_pack rustdoc, CLI q8 compatibility-lineage-adapter-write-validate chain, dependency-section scan, public-doc taboo scan, and git diff --check line-ending-only. - 2026-06-27 promoted a richer offline model-breeding operator gate: tinyrustlm-slm-pack now writes direct-parameter task-delta candidates and recomputable operator receipts. - delta-candidate consumes a passing compatibility report, validated lineage, compatibility-bound base and target parent .slm files, and a signed parts-per-million delta weight; it writes base plus weighted target-minus-base as a normal candidate .slm and records parent checksums, delta weights, candidate checksum, lineage checksum, and next gate. - validate-delta-candidate recomputes candidate bytes and receipt, rejects parent checksum drift, candidate byte drift, and invalid task-delta weights, and feeds the existing candidate-manifest gate. - Verification passed for the task-delta operator gate: cargo fmt --all, cargo fmt --all -- --check, focused tinyrustlm-slm-pack tests with 81 tests, cargo test --workspace with 155 tests, strict slm_pack rustdoc, CLI q8 compatibility-lineage-delta-validate-delta-validate-candidate chain, CLI invalid-delta-weight refusal, dependency-section scan, public-doc taboo scan, and git diff --check line-ending-only. - 2026-06-27 promoted the next model-breeding assembly gate: tinyrustlm-slm-pack now writes deterministic promotion ledgers from selector admission records. - promotion-ledger consumes admitted records, rejects duplicate candidate ids and duplicate candidate checksums, writes admission-set plus ledger-chain checksums, records each candidate's promotion/eval evidence fields, and keeps the next route as selector registry or offline population review. - validate-promotion-ledger recomputes the ledger from the input admissions and rejects entry drift or unexpected keys before selector/population consumers trust the history. - Verification passed for the promotion-ledger gate: cargo fmt --all, cargo fmt --all -- --check, focused tinyrustlm-slm-pack tests with 76 tests, cargo test --workspace with 150 tests, strict slm_pack rustdoc, CLI converted-trained q8 compatibility-lineage-candidate-promotion-runtime-eval-admission-ledger chain, CLI ledger-drift refusal, dependency-section scan, public-doc taboo scan, and git diff --check line-ending-only. - 2026-06-27 promoted the first offline model-breeding operator gate: tinyrustlm-slm-pack now writes direct-parameter blend candidates and recomputable operator receipts. - blend-candidate consumes a passing compatibility report, validated lineage, two compatibility-bound parent .slm files, and a parent-0 parts-per-million weight; it dequantizes compatible tensors as needed, writes a normal candidate .slm, and records parent checksums, blend weights, candidate checksum, lineage checksum, and next gate. - validate-blend-candidate recomputes the candidate bytes and receipt, rejects parent checksum drift, candidate byte drift, and invalid blend weights, and feeds the existing candidate-manifest gate. - Verification passed for the blend operator gate: cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack with 70 tests, cargo test --workspace with 144 tests, strict slm_pack rustdoc, CLI q8 compatibility-lineage-blend-validate-blend-validate-candidate chain, CLI candidate-drift refusal, dependency-section scan, public-doc taboo scan, and git diff --check line-ending-only. - 2026-06-26 promoted the seventh model-breeding assembly gate: tinyrustlm-slm-pack now writes selector registries from validated selector admission records. - selector-registry consumes selector admission records and multi-parent admission records, requires admitted candidate artifacts to resolve under served tinyrustlm/models paths, writes browser-safe ../models/*.slm routes, and validate-selector-registry rejects entry drift. - Browser app.js can optionally fetch models/selector.registry and populate the selector from admitted registry entries; if no registry is present, the checked-in deterministic smoke model list remains active for regression coverage. - Verification passed for selector registry intake: cargo fmt --all -- --check, cargo test --workspace with 139 tests, strict rustdoc for slm_pack and browser_harness, focused tinyrustlm-slm-pack tests with 65 tests, focused Rust browser-harness tests with 6 tests, CLI converted-trained q8 compatibility-lineage-candidate-promotion-runtime-eval-admission-selector-registry chain plus validation, CLI registry drift refusal, node syntax checks, Rust browser harness static contract, dependency-section scan, public-doc taboo scan, git diff --check line-ending-only, and dynamic loopback browser smoke using admitted-q8-self from selector.registry. - 2026-06-26 promoted the fifth and sixth model-breeding assembly gates: tinyrustlm-slm-pack now writes runtime-smoke sidecars and selector admission records. - Runtime-smoke sidecars bind provenance manifest checksum, .slm checksum, source kind, model shape, and passed runtime-smoke decision to local execution proof. - admission-record consumes compatibility, lineage, candidate .slm, candidate manifest, promotion template, provenance manifest, runtime-smoke sidecar, and passed eval sidecar; validate-admission rejects runtime-smoke drift, eval drift, admission overclaims, and invalid selector ids. - Verification passed for the admission gate: cargo fmt --all -- --check, strict slm_pack rustdoc, focused tinyrustlm-slm-pack tests with 58 tests, cargo test --workspace with 132 tests, CLI converted-trained q8 compatibility-lineage-candidate-promotion-runtime-eval-admission generation plus validation, CLI eval-drift admission refusal with no admission written, public-doc taboo scan, and git diff --check line-ending-only. - 2026-06-26 promoted the fourth model-breeding assembly gate: tinyrustlm-slm-pack now has promotion-template and validate-promotion commands for candidate runtime-smoke/eval handoff. - Promotion templates consume compatibility, lineage, candidate .slm, and candidate artifact manifest inputs; they bind candidate manifest checksum, keep runtime-smoke and eval statuses pending, and keep browser selector plus public-claim status not-admitted. - validate-promotion rejects candidate manifest checksum drift, candidate artifact drift, promotion overclaims, and invalid promoter ids before selector or claim work can proceed. - Verification passed for the promotion gate: cargo fmt --all -- --check, strict slm_pack rustdoc, focused tinyrustlm-slm-pack tests with 51 tests, cargo test --workspace with 125 tests, CLI q8 compatibility-lineage-candidate-promotion generation plus validation, CLI q4 promotion refusal with no promotion written, empty dependency-section scan, public-doc taboo scan, and git diff --check. - 2026-06-26 promoted the third model-breeding assembly gate: tinyrustlm-slm-pack now has candidate-manifest and validate-candidate commands for produced .slm candidate artifacts. - Candidate artifact manifests consume a passing compatibility report, a validated lineage template, and a validated candidate .slm; they bind lineage checksum, candidate checksum, candidate shape, tokenizer checksum, tensor layout checksum, direct-parent contract, pending eval status, and next promotion gate. - validate-candidate rejects lineage checksum drift, candidate artifact drift, manifest field drift, and q4 artifacts against q8 lineage before eval or promotion work can proceed. - Verification passed for the candidate artifact gate: cargo fmt --all -- --check, strict slm_pack rustdoc, focused tinyrustlm-slm-pack tests with 46 tests, cargo test --workspace with 120 tests, CLI q8 self-pair compatibility-lineage-candidate generation plus validation, CLI q4 candidate refusal with no candidate manifest written, empty dependency-section scan, public-doc taboo scan, and git diff --check. - 2026-06-26 promoted the second model-breeding assembly gate: tinyrustlm-slm-pack now has lineage-template and validate-lineage commands for planned candidate records. - Candidate lineage templates consume a passing parent compatibility report, bind its checksum, copy parent artifact fields, record candidate/operator/resource identifiers, and leave candidate artifact, manifest, and eval outputs pending. - validate-lineage rejects failed compatibility reports, compatibility checksum drift, parent field drift, mismatched parent counts, and non-slug candidate or operator identifiers before any operator output is admitted. - Verification passed for the candidate lineage gate: cargo fmt --all -- --check, strict slm_pack rustdoc, focused tinyrustlm-slm-pack tests with 41 tests, cargo test --workspace with 115 tests, CLI q8 self-pair lineage template generation and validation, CLI q8/q4 failed compatibility refusal with no lineage file written, empty dependency-section scan, public-doc taboo diff scan, and git diff --check. - 2026-06-26 promoted the first implemented model-breeding assembly gate: tinyrustlm-slm-pack now has a no-crate compatibility command that validates two parent .slm files and emits a line-based parent-set report. - Parent compatibility reports bind each parent to path, bytes, .slm checksum, model shape, tensor count, parameter count, quantization, output-head contract, flags, tokenizer checksum, and tensor layout checksum. - Direct-parameter parent sets now pass only when version, shape, tokenizer checksum, output contract, quantization, tensor count, parameter count, and tensor layout checksum match; q8_0 versus q4_0 routes through source conversion or distillation before candidate promotion. - Verification passed for the parent compatibility gate: cargo fmt --all, cargo fmt --all -- --check, cargo rustdoc -p tinyrustlm-slm-pack --bin tinyrustlm-slm-pack -- -D missing_docs, cargo test -p tinyrustlm-slm-pack with 36 tests, cargo test --workspace with 110 tests, CLI compatibility report for tinylm16-q8 self-pair written to target/model-breeding/tinylm16-q8-self.compat, CLI q8/q4 comparison returned quantization-mismatch plus tensor-layout-mismatch, and Cargo.toml dependency sections remain empty. - 2026-06-26 processed 26 active Improvement reports into durable model-breeding memory: raw originals live under raw/gguf-mirust/report-intake-2026-06-26/, the intake index is wiki/gguf-mirust/reports/report-intake-index-2026-06-26.md, and synthesis lives in wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md. - Model breeding is now routed as future candidate lineage: compatible parent artifacts, operator metadata, generated .slm or adapter outputs, eval sidecars, promotion records, and regular TinyRustLM admission gates. - Model-breeding research references are recorded in wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md, covering model soups, Git Re-Basin, task arithmetic, TIES, DARE, LoRA, and population-based training. - Added .uai/taboo.uai for GGUF.MiRust.com public voice: keep public copy centered on constructive local-model craft, lineage, proof, and research momentum. - Updated UAIX File Handoff strategy from https://uaix.org/en-us/tools/ai-memory-package-wizard/#setup-file-handoff through docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md plus hot .uai routing. - 2026-06-25 promoted browser Step Token control: tinyrustlm/app now exposes a disabled-until-context Step Token button wired to WASM generate_next_token. - Step Token appends one decoded token to the response and latest TinyRustLM transcript turn, appends a generate_next_token console entry, refreshes diagnostics/benchmark, stays enabled after transcript Clear, and disables after runtime Reset, context errors, missing models, and rejected models. - Browser smoke now has a step-token mode that verifies hi -> e -> ee, generated_token_count 2, KV cache length 5, selected token 101, q8_0 diagnostics, benchmark generated count 2, and local-only requests. - Verification passed for the Step Token control slice: node --check app.js/browser-smoke.js, cargo fmt --all -- --check, cargo test --workspace with 102 tests, Rust browser harness static contract, focused step-token smoke on port 18450, and tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke -BrowserSmokePort 18460 -PortSearchLimit 5. - 2026-06-25 hardened generated-result output buffering: Runtime now caps decoded generated output at 64 KiB and surfaces ErrorCode::OutputBufferExceeded through last_result plus diagnostics. - Byte and BPE tokenizers now expose bounded decode paths that fail before replacing the caller's existing output string, and full generate overflow failures clear stale token/generated-token state. - Verification passed for the output-buffer slice: cargo fmt --all -- --check, cargo test --workspace with 102 tests, strict rustdoc gates, rebuilt WASM, WASM ABI smoke, Rust browser harness, and tools/vs/Test-TinyRustLM.ps1. - Rebuilt tinyrustlm/runtime/tinyrustlm.wasm after runtime adapter apply; current sha256 is 2948DAF23FECD6560A732A4F08A92A3885D89BD52FF1F3A3E6C54A3E699CAA12. - 2026-06-25 promoted tied-output trained-source conversion: source-template supports tiny-fixture-tied and tinylm16-tied, source.manifest declares tied_output=true, validation requires tied model_shape agreement, and tied bundles omit output.weight. - convert-trained now emits tied f32, q8_0, and q4_0 .slm artifacts with the v1 tied-output flag, converted-trained manifests, and runtime-smoke quality gates while keeping assistant-quality evidence reserved for reviewed eval sidecars. - Verification passed for the tied-source conversion slice: cargo fmt --all -- --check, node --check app.js/browser-smoke.js/wasm-abi-smoke.js, Test-TinyRustLM.ps1 parse check, focused trained_source tests 8 passed, cargo test --workspace with 99 tests, Rust browser harness 8 checks, and tools/vs/Test-TinyRustLM.ps1. - 2026-06-25 promoted the tied-output path from fallback-only to artifact-backed fixture: tiny-test-model-tied.slm omits output.weight, sets the v1 tied-output flag, validates with 11 tensors and checksum 0x7d62cfbfde480fed, and generates through tok_embeddings projection. - Browser, docs, Visual Studio guidance, and the Rust mini browser harness now include the Tiny Fixture tied-output f32 selector route and deterministic-smoke manifest. - Verification passed for the tied-output fixture slice and is superseded by the 99-test tied-source conversion run: cargo fmt --all -- --check, node checks, Rust browser harness, .slm validation, workspace tests, and tools/vs/Test-TinyRustLM.ps1. - 2026-06-25 promoted model tensor routing: tinyrustlm/runtime/src/model.rs now resolves top-level and per-layer tensor indices on model load, including tied-output projection fallback to tok_embeddings. - tinyrustlm/runtime/src/generate.rs now uses pre-resolved tensor indices in the token loop instead of formatting layer tensor names or looking up tensors by stable name during every forward pass. - Verification passed for the tensor-routing slice and is superseded by the 96-test tied-output fixture run: focused model tests 6 passed, focused generate tests 13 passed, fmt passed, workspace tests passed, strict runtime rustdoc passed, and tools/vs/Test-TinyRustLM.ps1 passed. - 2026-06-25 promoted Milestone 5 math evidence: tinyrustlm/runtime/src/ops.rs now directly tests dot known output and shape mismatch, matvec known output and mismatch, matmul known output and mismatch, RMSNorm, softmax sum plus empty rejection, SiLU known values, and SwiGLU known output plus mismatch. - Verification passed for the core-ops slice and is superseded by the current tensor-routing run: cargo fmt --all, cargo test -p tinyrustlm-runtime ops::tests with 12 ops tests, cargo fmt --all -- --check, and cargo test --workspace with 90 tests total. - 2026-06-25 promoted custom BPE from structural support to an end-to-end runtime fixture: tinyrustlm-slm-pack tiny-fixture-bpe writes BPE1 vocab 262, tiny-test-model-bpe.slm validates, and runtime generation for prompt the records tokenizer_output 256,261. - Browser and Visual Studio contracts now include tiny-test-model-bpe.slm and its deterministic-smoke manifest; the static browser selector exposes Tiny Fixture BPE f32. - Verification passed after BPE fixture promotion and is superseded by later core-ops and tensor-routing runs: fmt, focused runtime BPE test, slm_pack BPE tests, app syntax, browser harness, workspace tests, and VS helper. - 2026-06-25 hardened assistant-quality evidence gates: eval-case files now reject zero declared cases, empty exact prompts/expected text, and stray case keys outside case_count. - Quality-gate validation now requires assistant-quality sidecars to include positive case_count, cases_passed matching case_count, cases_failed zero, quality_boundary evidence, and exact per-case expected/actual text with ok errors. - Verification passed after assistant-quality case-ledger hardening and is superseded by the current BPE fixture run: focused eval_runner/provenance tests, fmt, workspace tests, and tools/vs/Test-TinyRustLM.ps1 default path. - 2026-06-25 hardened generation request state: generate now clears prompt/cache diagnostics at request start, failed context-boundary requests leave generated count and KV length clean, and successful generate extends token state so generate_next_token continues from the generated token. - Added runtime context-boundary coverage: a context-16 q8 fixture accepts a 15-token prompt context plus one generated token, then rejects a full 16-token prompt context with ContextExceeded, empty token state, and zero cache length. - Verification passed after context-boundary state hardening and is superseded by the current 78-test assistant-quality case-ledger run: cargo fmt --all, focused boundary and step-token tests, strict runtime rustdoc, node --check tinyrustlm/tools/wasm-abi-smoke.js, and tools/vs/Test-TinyRustLM.ps1 default path. - 2026-06-25 hardened stochastic sampling memory; superseded by the current 1024-candidate cap that accepts BPE top_k 262 while still rejecting oversized top_k without a vocab-sized candidate Vec. - Verification passed after fixed-buffer sampling and is superseded by the current 78-test assistant-quality case-ledger run: cargo fmt --all -- --check, focused sampler/runtime sampling tests, strict runtime rustdoc, node --check tinyrustlm/tools/wasm-abi-smoke.js, and tools/vs/Test-TinyRustLM.ps1 default path. - 2026-06-25 promoted public Rust API documentation from advisory output to enforced gate: Cargo workspace now denies missing_docs and the Visual Studio test helper runs strict rustdoc checks for tinyrustlm-runtime, tinyrustlm-slm-pack, tinyrustlm-local-server, and tinyrustlm-browser-harness. - Verification passed after public doc gate wiring and is superseded by later fixed-buffer sampling and the current 78-test workspace run: cargo fmt --all -- --check, strict rustdoc for runtime plus all three tool bins, and tools/vs/Test-TinyRustLM.ps1 default path. - 2026-06-25 added TensorView and MutableTensorView unit coverage for shape validation, row-major flat indexing, mutable scratch writes, and element-count overflow rejection. - Verification passed after tensor-view tests and is superseded by the current 78-test workspace run: node --check tinyrustlm/tools/wasm-abi-smoke.js, cargo fmt --all -- --check, cargo doc --workspace --no-deps, and cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 8 checks. - 2026-06-25 hardened runtime generation memory: Runtime now allocates ForwardScratch and logits with the loaded model, reuses those buffers across generate plus repeated generate_next_token calls, and clears them on free_model or failed load. - Replaced vocab-sized top-k diagnostic candidate Vec allocation with fixed-array top-k selection. - Added unit coverage for generation buffer pointer stability across generate and repeated step-token calls, plus top-k summary correctness without vector sorting. - Verification passed after reusable generation buffer hardening and is superseded by the current public-doc-gated workspace run: node --check tinyrustlm/tools/wasm-abi-smoke.js, cargo fmt --all -- --check, cargo test --workspace, WASM release build/copy, node tinyrustlm/tools/wasm-abi-smoke.js, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 8 checks, and tools/vs/Test-TinyRustLM.ps1. - Rebuilt tinyrustlm/runtime/tinyrustlm.wasm after tensor-routing hardening; this hash is superseded by the output-buffer rebuild recorded above. - 2026-06-25 hardened the WASM step/free ABI: generate_next_token now returns explicit ErrorCode values, writes decoded token text to last_result, records selected token id in diagnostics, and free_model leaves post-free generation returning ModelNotLoaded. - Added runtime unit coverage for generate_next_token continuing current q8 context with generated_token_count 2, KV cache length 5, selected token 101, and q8_0 diagnostics. - Added runtime unit coverage for free_model clearing model_loaded, switching active_quantization_mode to none, and causing later generate_next_token to fail with model not loaded. - Extended tinyrustlm/tools/wasm-abi-smoke.js to reject invalid sampling, recover generation, step one token, verify diagnostics, free the model, and verify post-free ModelNotLoaded. - Extended tinyrustlm/tools/browser_harness to crawl tinyrustlm/runtime/src/wasm_exports.rs for required Rust WASM export definitions in addition to JS boundary-call markers. - Prior ABI hardening rebuilt the WASM artifact and was superseded by the reusable-buffer rebuild recorded above. - Prior ABI hardening verification passed and was superseded by the current public-doc-gated workspace verification recorded above. - 2026-06-25 added a local browser conversation transcript to tinyrustlm/app: Generate appends DOM-safe User and TinyRustLM entries, Reset clears runtime context/output without clearing the transcript, and Clear empties transcript state. - Browser smoke now asserts transcript behavior: single-model q8/q4 runs require User hi plus TinyRustLM e entries, and desktop/mobile ui-audit requires empty ready state, Clear disabled before generation, two transcript entries after generation, and Clear enabled after generation. - 2026-06-25 tightened ui-audit to click Clear after generation; desktop/mobile cleared snapshots prove transcript entries are removed, Clear disables again, and the generated response remains visible. - Static app contract now requires clearChatButton and conversation ids plus visible Conversation heading. - node --check passed for tinyrustlm/app/app.js and tinyrustlm/tools/browser-smoke.js after transcript edits. - cargo fmt --all -- --check passed after transcript edits. - cargo run -p tinyrustlm-browser-harness -- tinyrustlm passed the static app contract with 7 checks after transcript ids were added. - tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke -BrowserSmokePort 18340 -PortSearchLimit 5 passed after the transcript implementation, including cargo tests, static and HTTP Rust browser harnesses, all model and manifest validations, source conversion/eval gates, WASM ABI smoke, q8/q4 browser generation, loop, malformed model, context overflow, missing model, endurance, performance, and desktop/mobile ui-audit. Only recurring temporary Chrome profile cleanup notices remained. - Focused browser-smoke ui-audit passed on http://127.0.0.1:18350/app/ after adding Clear-click assertions; the temporary Rust local server was stopped after the check. - 2026-06-25 added tinyrustlm/tools/browser_harness as a no-crate Rust mini browser contract harness for static app crawl, required UI ids, local-only marker scanning, WASM boundary markers, model route declarations, manifest sidecars, trained-quality non-claims, and optional loopback content-type checks. - tools/vs/Test-TinyRustLM.ps1 now runs tinyrustlm-browser-harness in the default static test path and again with --http when BrowserSmoke or PerformanceSoak starts or reuses a local TinyRustLM server. - Rust browser harness static audit passed with 7 checks; loopback audit passed with 8 checks against the Rust local server on port 18315. - cargo test --workspace now covers 102 tests: 6 browser-harness tests, 5 local-server tests, 63 runtime tests, and 28 slm_pack tests. - tools/vs/Test-TinyRustLM.ps1 -PerformanceSoak -PerformanceSoakCycles 2 -PerformanceSoakTokens 2 -BrowserSmokePort 18320 -PortSearchLimit 5 passed after the Rust browser harness integration, with only the recurring temporary Chrome profile cleanup notice. - 2026-06-25 focused tools/vs/Test-TinyRustLM.ps1 -PerformanceSoak -PerformanceSoakCycles 1 -PerformanceSoakTokens 1 -BrowserSmokePort 18291 -PortSearchLimit 5 completed through the Rust local server path; browser-smoke clamps soak minimums to two cycles and two tokens, and only a temporary Chrome profile cleanup notice remained. - 2026-06-25 added tinyrustlm/tools/local_server as a no-crate Rust loopback static server for TinyRustLM app, WASM, .slm, and .slm.manifest hosting. - Visual Studio F5 now launches target/debug/tinyrustlm-local-server.exe instead of requiring Node for local static hosting; Node remains required for JavaScript smoke tools only. - BrowserSmoke startup in tools/vs/Test-TinyRustLM.ps1 now uses the Rust local server when it needs to start a server. - Rust local server direct HTTP smoke passed for /app/, /runtime/tinyrustlm.wasm, /models/tinylm16-q8.slm, and /models/tinylm16-q8.slm.manifest with trained_quality_claim=not-claimed visible. - Run helper reuse check passed against a Rust-hosted TinyRustLM server on port 18282. - cargo fmt --all -- --check, cargo build --workspace, cargo test --workspace, and tools/vs/Test-TinyRustLM.ps1 passed after the Rust local-server addition. - Historical cargo test totals before the Rust local-server, browser-harness, sampling, context-boundary, assistant-quality gate, core-ops, and tensor-routing coverage growth are superseded by current 92-test workspace coverage. - Corrected active project path is E:\Source\Rust\GGUF.MiRust.com. - Attached TinyRustLM prompt superseded the earlier enterprise Rust/Axum scaffold. - Root Cargo workspace contains tinyrustlm/runtime, tinyrustlm/tools/slm_pack, tinyrustlm/tools/local_server, and tinyrustlm/tools/browser_harness, all with empty dependency lists. - Deleted dependency-based earlier scaffold files under apps/gguf-mirust-site and crates/gguf-*. - Added static browser shell under tinyrustlm/app with local-only privacy copy, diagnostics, developer mode, token console, loading state, and handwritten JS. - Added no-crate runtime source for WASM exports, memory transfer, byte tokenizer, .slm parser, tensor views, f32 math ops, direct q8_0 and q4_0 matvec dispatch, RoPE, KV cache, sampler, diagnostics, f32/q8_0/q4_0 model tensor loading, and greedy generation. - Added no-crate slm_pack source for f32, q8_0, and q4_0 tiny fixture .slm generation plus TinyLM-16M f32/q8_0/q4_0 smoke model generation. - Added no-crate slm_pack provenance sidecar commands: manifest and validate-manifest. - Added no-crate slm_pack quality sidecar commands: eval-template and quality-gate. - Added no-crate slm_pack trained-source commands: source-template, validate-source, and convert-trained. - Added required docs under tinyrustlm/docs and fixture text under tinyrustlm/tests/fixtures. - Installed/exposed Rust toolchain under C:\Users\AI\.cargo\bin. - JavaScript syntax check passed with node --check tinyrustlm/app/app.js. - cargo fmt --all passed. - cargo test --workspace passed with 44 tests total after quantized decoded-shadow removal coverage was added, including .slm checksum rejection, native .slm admission validator tests, provenance manifest tests, quality-gate tests, trained-source layout/constraint/conversion tests, quantized tensor f32-borrow rejection, and diagnostics JSON escaping for browser parsing. - Runtime model reload and reset now clear generation-specific diagnostics, including prompt/generated counts, KV cache length, tokenizer output, logits summary, selected token, top-k candidates, tokens-per-second, and scratch bytes. - Runtime diagnostics JSON rendering now escapes quotes, backslashes, JSON control characters, line separators, and paragraph separators before browser JSON.parse consumes developer/benchmark fields. - Browser app disables model selection during model loading and ignores stale model-load completions. - Browser app now has a model selector for tinyrustlm/models/tinylm16-q8.slm, tinylm16-q4.slm, tinylm16-f32.slm, tiny-test-model.slm, tiny-test-model-q8.slm, and tiny-test-model-q4.slm. - Browser app now defaults to tinyrustlm/models/tinylm16-q8.slm and keeps TinyLM-16M q4_0, f32, plus tiny fixtures selectable for regression checks. - Browser app now includes a max-token control and benchmark panel for host-side load time, prompt token count, generated token count, token speed, and scratch bytes. - Browser app now fetches the selected local `.slm.manifest` sidecar only after Rust accepts the `.slm` model, parses the line-based manifest in handwritten JS, and renders a Model Provenance panel with source kind, runtime admission, quality claim, trained-quality non-claim, checksum, and required next gate. - WASM release build passed and was copied to tinyrustlm/runtime/tinyrustlm.wasm. - slm_pack generated tinyrustlm/models/tiny-test-model.slm, tiny-test-model-q8.slm, and tiny-test-model-q4.slm. - slm_pack generated tinyrustlm/models/tinylm16-f32.slm with 68,194,944 bytes. - slm_pack generated tinyrustlm/models/tinylm16-q8.slm with 17,160,000 bytes. - slm_pack generated tinyrustlm/models/tinylm16-q4.slm with 10,657,728 bytes. - Node WASM smoke test loaded all three generated .slm files, transferred prompt bytes, called generate, returned code 0, generated eeeeeeeeeeeee from the tiny transformer path, and read diagnostics. - Node WASM smoke test loaded tinylm16-f32.slm, transferred prompt hi, generated e with max_new_tokens 1, returned code 0, and read diagnostics. - Node WASM smoke test loaded tinylm16-q8.slm, transferred prompt hi, generated e with max_new_tokens 1, returned code 0, and read diagnostics. - Node WASM smoke test loaded tinylm16-q4.slm, transferred prompt hi, generated e with max_new_tokens 1, returned code 0, and read q4_0 diagnostics. - Headless Chrome browser-smoke loaded http://127.0.0.1:8080/app/, used selectedModel tinylm16q8, clicked Generate, rendered response e, modelState loaded, errorState none, q8_0 diagnostics, and benchmark fields. - Headless Chrome browser-smoke selected tinylm16q4, clicked Generate, rendered response e, modelState loaded, errorState none, q4_0 diagnostics, and benchmark fields. - Headless Chrome browser loop smoke reloaded the app, generated q8 twice around reset, switched to q4, generated q4 twice around reset, verified clean ready/reset diagnostics, and observed only local-origin HTTP requests. - Headless Chrome browser model-error smoke intercepted the local q8 model with malformed .slm bytes, rendered Model rejected, surfaced invalid model magic, kept Generate/Reset disabled, kept model selection recoverable, and observed only local-origin HTTP requests. - Headless Chrome browser context-error smoke submitted an over-context prompt, rendered context exceeded, kept runtime Ready with controls enabled, confirmed no generated tokens, and observed only local-origin HTTP requests. - Headless Chrome browser missing-model smoke returned a local 404 for tinylm16-q8.slm, rendered Model load failed with Unable to fetch local .slm model (404), kept Generate/Reset disabled, kept model selection recoverable, and observed only local-origin HTTP requests. - Headless Chrome browser endurance smoke completed three q8/q4 ready-generate-reset cycles with deterministic e responses, clean reset diagnostics, recoverable controls, and only local-origin HTTP requests. - Added tinyrustlm/tools/wasm-abi-smoke.js to exercise exported WASM generate boundaries with invalid UTF-8 prompt bytes, null prompt pointer, zero prompt length, zero max_new_tokens, and recovery generation after errors. - tools/vs/Test-TinyRustLM.ps1 now checks wasm-abi-smoke.js syntax and runs the WASM ABI smoke in the default Visual Studio test path. - WASM ABI smoke passed against tinyrustlm/runtime/tinyrustlm.wasm and tinyrustlm/models/tinylm16-q8.slm; it reported invalidUtf8/nullPointer/invalidLength passed and recovered with response e, selected_next_token 101, active_quantization_mode q8_0. - Current targeted browser smoke passed for http://127.0.0.1:8080/app/ with selectedModel tinylm16q8, response e, q8_0 diagnostics, benchmark fields, and no runtime error. - Current focused provenance-panel checks passed: cargo test --workspace (44 tests), cargo doc --workspace --no-deps, node --check for app.js and browser-smoke.js, cargo fmt --all -- --check, and browser-smoke ui-audit on http://127.0.0.1:8080/app/. - Added browser-smoke performance mode for multi-token q8_0 and q4_0 UI benchmark verification, including prompt/generated token counts, host-side tokens/sec, scratch bytes, quantization mode, KV cache length, reset recovery, and local-only network requests. - tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke now runs the performance smoke after q8, q4, loop, malformed model, context-overflow, missing-model, and endurance browser smokes. - Full Visual Studio browser helper passed after the performance-smoke addition with q8_0 and q4_0 four-token generation and clean reset diagnostics; current scratch-byte evidence is recorded in the later quantized decoded-shadow removal entries. - Added browser-smoke performance-soak mode for repeated multi-token q8_0 and q4_0 UI generation across cycles, with deterministic output, benchmark fields, KV cache length, scratch bytes, reset recovery, and local-only request assertions. - tools/vs/Test-TinyRustLM.ps1 now has -PerformanceSoak, -PerformanceSoakCycles, and -PerformanceSoakTokens for heavier benchmark-panel validation without requiring the full BrowserSmoke suite. - Focused Visual Studio performance soak passed with two cycles and four generated tokens per q8/q4 run; each generate returned eeee and reset cleanly. - Full Visual Studio browser helper passed with -BrowserSmoke -PerformanceSoak -PerformanceSoakCycles 3 -PerformanceSoakTokens 4, covering the existing browser hardening suite plus three q8/q4 multi-token performance-soak cycles. - Added a product-shell footer to tinyrustlm/app/index.html exposing TinyRustLM, GGUF.MiRust.com, browser-local Rust/WASM identity, and local .slm model scope. - Added browser-smoke ui-audit mode for fresh desktop and mobile viewports; it verifies local-only notice, footer identity, required panels, labels, model options, Model Provenance sidecar fields, no horizontal overflow, q8_0 generation, diagnostics/developer mirror, benchmark fields, and local-only HTTP requests. - Headless Chrome browser ui-audit passed after the provenance-panel addition, verifying the local `.slm.manifest` request stayed same-origin and the panel rendered deterministic-smoke source, runtime-smoke admission, trained-quality non-claim, checksum, and next gate before and after q8_0 generation. - tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke now runs ui-audit after the q8, q4, loop, malformed model, context-overflow, missing-model, endurance, and performance smokes. - .slm packer now writes a nonzero simple checksum with the checksum field treated as zero during calculation. - .slm runtime parser now rejects zero checksums and mismatched checksums before accepting model files. - Earlier checksum enforcement regenerated the pre-BPE local .slm artifact set; current artifact count is eight including the BPE fixture and tied-output fixture. - Full Visual Studio browser helper passed again after checksum-bearing artifact regeneration with -BrowserSmoke -PerformanceSoak -PerformanceSoakCycles 3 -PerformanceSoakTokens 4. - Added tinyrustlm-slm-pack validate as a no-crate native model admission gate for generated or future converted .slm files. - Native SLM validation checks header bounds, nonzero checksum match, byte-tokenizer metadata, duplicate tensor hashes, required tensor names and shapes, dtype-specific byte lengths, finite f32 payload values, and quantization scale ranges. - Seven current local .slm artifacts pass native validation: tiny f32/q8/q4/BPE and TinyLM-16M-shaped f32/q8/q4. - Seven current local .slm artifacts have .slm.manifest provenance sidecars validated by tinyrustlm-slm-pack validate-manifest. - Current manifests bind model bytes, .slm checksum, shape, tensor count, parameter count, quantization, source_kind, admission_status, and quality boundary. - Current manifests declare source_kind deterministic-smoke, quality_claim runtime-execution-smoke-only, trained_quality_claim not-claimed, and admission_status accepted-for-runtime-smoke. - tinyrustlm-slm-pack quality-gate now separates runtime-smoke claims from assistant-quality claims. - Existing tinylm16-q8 deterministic-smoke manifest passed quality-gate runtime-smoke. - A converted-trained manifest can generate a pending assistant-quality eval template, but that pending template is rejected until reviewed task-eval evidence and a declared quality scope are supplied. - Added tinyrustlm/tools/slm_pack/src/trained_source.rs for raw-f32 source manifest validation, safe relative tensor paths, source checksum checks, exact tensor shape/byte checks, finite bounded nonzero source weights, and conversion to f32/q8_0/q4_0 .slm artifacts. - Added tinyrustlm/tests/fixtures/trained-source-tiny/source.manifest plus raw f32 tensor files as a tiny trained-source conversion fixture. - Added tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt as a scoped eval-case fixture for assistant-quality sidecar evidence; it is fixture scope, not product assistant-quality proof. - CLI source-template generated the trained-source fixture, validate-source accepted it, convert-trained emitted target/trained-source-smoke/tiny-converted-q8.slm plus converted-trained manifest, and quality-gate accepted runtime-smoke for the converted artifact. - 2026-06-25 strengthened trained-source conversion coverage so source fixture conversion is verified for f32, q8_0, and q4_0, not only q8_0. - Updated tinyrustlm/tools/slm_pack/src/trained_source.rs test coverage to convert the generated source fixture into f32, q8_0, and q4_0 .slm artifacts and validate each converted-trained manifest. - Updated tools/vs/Test-TinyRustLM.ps1 default path to convert f32, q8_0, and q4_0 source-fixture artifacts, validate each model and manifest, pass runtime-smoke for each, run tinyrustlm-eval for each, and pass fixture-scoped assistant-quality for each. - Updated README.md, tinyrustlm/README.md, docs/visual-studio.md, and tinyrustlm/docs/testing.md so docs state the full all-quantization converted-source gate. - cargo fmt --all -- --check passed after all-quantization trained-source gate edits. - node --check passed for tinyrustlm/app/app.js, tinyrustlm/tools/browser-smoke.js, and tinyrustlm/tools/wasm-abi-smoke.js after the gate edits. - cargo test --workspace passed with 44 tests: 26 runtime tests and 18 slm_pack tests, including trained_source::tests::converts_source_fixture_to_all_supported_slm_quantizations and model::tests::quantized_tensor_f32_borrow_is_rejected. - tools/vs/Test-TinyRustLM.ps1 passed after the tied-output fixture promotion; the helper built the workspace, validated all eight local .slm artifacts and manifests, converted f32/q8_0/q4_0 source-fixture outputs, passed runtime-smoke and fixture-scoped assistant-quality gates for each converted output, and ran WASM ABI smoke successfully. - 2026-06-25 removed full decoded f32 shadow storage from q8_0 and q4_0 runtime tensors in tinyrustlm/runtime/src/model.rs. - q8_0 and q4_0 runtime tensors now keep native compact payloads plus scales; generation dequantizes embeddings and norm vectors into runtime-owned reusable scratch via copy_tensor_row_f32 and copy_tensor_f32. - Model::tensor_f32 now returns borrowed slices only for native f32 tensors and returns UnsupportedDType for quantized tensors; the new unit test model::tests::quantized_tensor_f32_borrow_is_rejected protects that contract. - tinyrustlm/runtime/src/generate.rs now loads embeddings and norm weights through scratch-backed copy methods, preserving direct quantized matvec dispatch for matrix weights. - Updated README.md, tinyrustlm/README.md, tinyrustlm/docs/architecture.md, tinyrustlm/docs/quantization.md, and tinyrustlm/docs/performance.md for native quantized storage plus scratch dequantization. - cargo fmt --all -- --check passed after quantized decoded-shadow removal. - node --check passed for tinyrustlm/app/app.js, tinyrustlm/tools/browser-smoke.js, and tinyrustlm/tools/wasm-abi-smoke.js after quantized decoded-shadow removal. - cargo test --workspace passed with 44 tests after quantized decoded-shadow removal. - tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke -BrowserSmokePort 8094 -PortSearchLimit 10 passed after quantized decoded-shadow removal; it rebuilt WASM, ran all model/manifests/source/eval/ABI gates, q8/q4 browser generation, loop, malformed, context, missing-model, endurance, performance, and desktop/mobile UI audit. - Current browser q8_0 performance smoke generated eeee from prompt hi with max_new_tokens 4 at 29.197 tok/s host-side, used 47,104 scratch bytes, KV length 7, and reset cleanly. - Current browser q4_0 performance smoke generated eeee from prompt hi with max_new_tokens 4 at 14.706 tok/s host-side, used 47,104 scratch bytes, KV length 7, and reset cleanly. - tools/vs/Test-TinyRustLM.ps1 now validates every local .slm artifact in the default Visual Studio test path before WASM ABI smoke. - tools/vs/Test-TinyRustLM.ps1 now validates each local .slm.manifest sidecar in the default Visual Studio test path before WASM ABI smoke. - Default Visual Studio test helper passed after model admission validation was added. - tools/vs/Run-TinyRustLM.ps1 now identity-checks an existing local server by loading /app/ and probing /runtime/tinyrustlm.wasm before reusing it. - tools/vs/Build-TinyRustLM.ps1 now regenerates deterministic-smoke provenance sidecars when model files are regenerated or manifests are missing. - Visual Studio F5 now skips unrelated busy loopback ports and starts TinyRustLM on the first free port within PortSearchLimit. - tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke now uses the same verified-server reuse and free-port selection behavior through BrowserSmokePort and PortSearchLimit. - tinyrustlm/tools/static-server.js now prints a clear EADDRINUSE message instead of an uncaught Node stack when a direct server start hits an occupied port. - Focused run-helper verification passed for unrelated busy port fallback from 18180 to 18181 and verified TinyRustLM server reuse on 18182. - Full Visual Studio browser helper passed after server-port hardening and reused the existing TinyRustLM server at http://127.0.0.1:8080/app/. - Processed all 23 active Improvement reports into distributed long-term report memory under wiki/gguf-mirust/reports/. - Preserved exact original report files under raw/gguf-mirust/report-intake-2026-06-25/ and verified source-to-raw SHA256 copies before clearing the source handoff bucket. - Added report synthesis records for enterprise Rust governance, browser-local runtime architecture, TinyLM modular architecture, teleodynamic resource-bounded design, and brand/product positioning. - Updated wiki/gguf-mirust/index.md, knowledge-map.md, source-memory-guide.md, raw/gguf-mirust/MANIFEST.md, .uai/intake-outcome-ledger.uai, and .uai/receiver-brief.uai for report routing. - Human flagged that the first report-memory pass under-populated .uai files and made the wiki feel weak/crawlability-poor. - Added .uai/report-synthesis.uai and enriched .uai/architecture.uai, .uai/coding-standards.uai, .uai/operations.uai, .uai/index.uai, .uai/startup-packet.uai, and .uai/workspace-guidance.uai with report-derived hot memory. - Added docs/dogfood/uaix-llm-wiki-crawlability-failure-2026-06-25.md to feed the failure back into UAIX/LLM Wiki guidance. - Added TinyRustLM.sln, TinyRustLM.vcxproj, tools/vs Build/Run/Test scripts, and docs/visual-studio.md for Visual Studio 2022 open/build/run support. - Visual Studio build helper passed through tools/vs/Build-TinyRustLM.ps1 -Configuration Debug. - Visual Studio test helper passed through tools/vs/Test-TinyRustLM.ps1 with cargo tests and JS syntax checks. - Visual Studio browser test helper is wired to run q8, q4, reload/reset/model-switch loop, malformed model, context-overflow, missing-model, endurance, and benchmark-panel performance smokes. - Tiny fixture diagnostics show tokenizer_output 256,104,105; logits argmax 101; selected_next_token 101; active_quantization_mode f32/q8_0/q4_0; KV cache length 16. - Tiny BPE fixture diagnostics for prompt the show tokenizer_output 256,261, proving BPE1 section selection and the merged token 261 before generation. - TinyLM-16M f32 diagnostics show tokenizer_output 256,104,105; logits argmax 101; selected_next_token 101; active_quantization_mode f32; KV cache length 4; peak scratch 47,104 after scratch-backed quantized row/vector path was added. - TinyLM-16M q8_0 diagnostics show tokenizer_output 256,104,105; logits argmax 101; selected_next_token 101; active_quantization_mode q8_0; KV cache length 4; peak scratch 47,104. - TinyLM-16M q4_0 diagnostics show tokenizer_output 256,104,105; logits argmax 101; selected_next_token 101; active_quantization_mode q4_0; KV cache length 4; peak scratch 47,104. - Added no-dependency Node static server script for http://127.0.0.1:8080/app/. - Static server was hardened to stream files, support HEAD, and emit content-length for large local models. - Static server now emits explicit busy-port diagnostics for direct Node use. - Current no-dependency Node static server is running at http://127.0.0.1:8080/app/ with PID 67428. - HTTP checks returned 200 for /app/, /runtime/tinyrustlm.wasm, /models/tiny-test-model.slm, /models/tiny-test-model-q8.slm, /models/tiny-test-model-q4.slm, /models/tinylm16-f32.slm, /models/tinylm16-q8.slm, /models/tinylm16-q4.slm, and /app/app.js. - Current WASM sha256 is 2948DAF23FECD6560A732A4F08A92A3885D89BD52FF1F3A3E6C54A3E699CAA12. - Current tiny f32 model sha256 is 17D79EE766578729D2B69090547E819E011D76115519514E19AC3754DE610A1A. - Current tiny q8 model sha256 is 6AF985853325EAA6D3EAAA8AADD3511DA9596EB542FB2D03A9BC9DC1F4377ADF. - Current tiny q4 model sha256 is 4004E2152F0B6382C6043A15084DE6DC4AE6AE6B6C5BA43ABDE8812ED0174CF6. - Current tiny BPE model sha256 is 31B27903C1588A1F246281DEF8027094C0D3862635FA7D3761AA1327471F3E82; manifest sha256 is AE28DDD62E91834A1F7F6D29BE186CB9EA81A92FAEBC0A5AF3E5A4897DC15B52. - Current TinyLM-16M f32 model sha256 is 70E9765080247FE859506534E87330D73FF50B66B8A48DC627C307069BB0DC5B. - Current TinyLM-16M q8 model sha256 is C3919E6D7244890E9B3C2B5E40C37F8D322467D859C15B8155700F20408DB950. - Current TinyLM-16M q4 model sha256 is 5AC2BD957113732BE9AB2AADFA2D2EFD54C3131E7E6C97BE424FAC6E72BB365B. active_handoff_state: content_bucket_non_placeholder_files: 0 improvement_bucket_non_placeholder_files: 0 disposition: all 23 reports from 2026-06-25, all 26 model-breeding reports from 2026-06-26, and 4 ModelBreeder/zero-dependency research files from 2026-06-28 are preserved to durable raw evidence, synthesized into long-term wiki memory, and removed from the active handoff source bucket. current_report_routes: strategy_source: https://uaix.org/en-us/tools/ai-memory-package-wizard/#setup-file-handoff active_bucket_scan: agent-file-handoff/Content/ and agent-file-handoff/Improvement/ currently contain no non-placeholder files after the 2026-06-28 research intake was preserved and routed. uaix_strategy_dogfood: docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md report_pointer_audit: All 116 current wiki/gguf-mirust/reports/*.md and wiki/gguf-mirust/research/*.md pages are represented in .uai/long-term-memory.uai as of 2026-06-29T14:10:00Z; 227 tracked local checksum pointers checked with 0 mismatches after federated selector receipt drift proof refresh. durable_raw_evidence: - raw/gguf-mirust/report-intake-2026-06-25/ - raw/gguf-mirust/report-intake-2026-06-26/ - raw/gguf-mirust/report-intake-2026-06-28/ durable_report_indexes: - wiki/gguf-mirust/reports/report-intake-index-2026-06-25.md - wiki/gguf-mirust/reports/report-intake-index-2026-06-26.md - wiki/gguf-mirust/reports/report-intake-index-2026-06-28.md model_breeding_synthesis: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md latest_candidate_operator_receipt_binding_report: wiki/gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29.md latest_promotion_operator_receipt_binding_report: wiki/gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29.md latest_admission_operator_receipt_binding_report: wiki/gguf-mirust/reports/admission-operator-receipt-binding-memory-2026-06-29.md latest_selector_operator_receipt_binding_report: wiki/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29.md latest_browser_multi_parent_operator_provenance_report: wiki/gguf-mirust/reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md latest_crossover_operator_report: wiki/gguf-mirust/reports/crossover-operator-memory-2026-06-29.md latest_mutation_operator_report: wiki/gguf-mirust/reports/mutation-operator-memory-2026-06-29.md latest_prune_operator_report: wiki/gguf-mirust/reports/prune-operator-memory-2026-06-29.md latest_dare_operator_report: wiki/gguf-mirust/reports/dare-operator-memory-2026-06-29.md latest_dare_browser_operator_provenance_report: wiki/gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29.md latest_federated_operator_report: wiki/gguf-mirust/reports/federated-operator-memory-2026-06-29.md latest_federated_selector_receipt_route_report: wiki/gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29.md latest_trained_adapter_source_alr1_report: wiki/gguf-mirust/reports/trained-adapter-source-alr1-memory-2026-06-28.md latest_trained_adapter_source_report: wiki/gguf-mirust/reports/trained-adapter-source-memory-2026-06-28.md latest_adapter_package_report: wiki/gguf-mirust/reports/low-rank-adapter-package-memory-2026-06-28.md latest_browser_low_rank_route_report: wiki/gguf-mirust/reports/browser-low-rank-adapter-route-memory-2026-06-28.md latest_browser_source_backed_alr1_route_report: wiki/gguf-mirust/reports/browser-source-backed-alr1-route-memory-2026-06-28.md latest_browser_source_backed_alr1_contract_report: wiki/gguf-mirust/reports/browser-source-backed-alr1-contract-memory-2026-06-28.md latest_browser_module_plan_report: wiki/gguf-mirust/reports/browser-assembly-trace-memory-2026-06-28.md latest_browser_module_plan_profile_report: wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md latest_browser_module_plan_execution_profile_report: wiki/gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28.md latest_browser_module_plan_fetch_policy_report: wiki/gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28.md latest_browser_module_plan_origin_policy_report: wiki/gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28.md latest_browser_module_plan_fetch_count_report: wiki/gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28.md latest_browser_module_plan_runtime_scratch_report: wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md latest_browser_module_plan_output_limit_report: wiki/gguf-mirust/reports/browser-module-plan-output-limit-memory-2026-06-28.md latest_browser_module_plan_total_budget_report: wiki/gguf-mirust/reports/browser-module-plan-total-budget-memory-2026-06-28.md latest_browser_module_plan_total_limit_report: wiki/gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28.md latest_browser_module_plan_wasm_memory_report: wiki/gguf-mirust/reports/browser-module-plan-wasm-memory-memory-2026-06-28.md latest_browser_module_plan_wasm_export_set_report: wiki/gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md latest_browser_module_plan_wasm_heap_report: wiki/gguf-mirust/reports/browser-module-plan-wasm-heap-memory-2026-06-28.md latest_browser_module_plan_wasm_transfer_report: wiki/gguf-mirust/reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md latest_browser_module_plan_model_release_report: wiki/gguf-mirust/reports/browser-module-plan-model-release-memory-2026-06-29.md latest_browser_module_plan_runtime_reset_report: wiki/gguf-mirust/reports/browser-module-plan-runtime-reset-memory-2026-06-29.md latest_browser_module_plan_adapter_validation_report: wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29.md latest_browser_module_plan_adapter_apply_count_report: wiki/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md latest_browser_module_plan_planned_fetch_count_report: wiki/gguf-mirust/reports/browser-module-plan-planned-fetch-count-memory-2026-06-29.md latest_browser_module_plan_actual_fetch_count_report: wiki/gguf-mirust/reports/browser-module-plan-actual-fetch-count-memory-2026-06-29.md latest_browser_module_plan_observed_route_set_report: wiki/gguf-mirust/reports/browser-module-plan-observed-route-set-memory-2026-06-29.md latest_browser_module_plan_actual_module_bytes_report: wiki/gguf-mirust/reports/browser-module-plan-actual-module-bytes-memory-2026-06-29.md latest_browser_module_plan_actual_module_checksums_report: wiki/gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md latest_browser_module_plan_route_set_report: wiki/gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29.md latest_browser_module_plan_route_set_version_report: wiki/gguf-mirust/reports/browser-module-plan-route-set-version-memory-2026-06-29.md latest_browser_module_plan_route_set_algorithm_report: wiki/gguf-mirust/reports/browser-module-plan-route-set-algorithm-memory-2026-06-29.md latest_browser_module_plan_operator_receipt_report: wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md latest_browser_module_plan_kv_cache_report: wiki/gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28.md latest_browser_module_plan_context_token_report: wiki/gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28.md latest_browser_module_plan_tokenizer_report: wiki/gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28.md latest_browser_module_plan_sampler_cap_report: wiki/gguf-mirust/reports/browser-module-plan-sampler-cap-memory-2026-06-28.md latest_browser_module_plan_count_drift_report: wiki/gguf-mirust/reports/browser-module-plan-count-drift-memory-2026-06-28.md latest_browser_combined_selector_cycle_report: wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md latest_browser_eval_case_checksum_report: wiki/gguf-mirust/reports/browser-eval-case-evidence-checksum-memory-2026-06-28.md latest_browser_assembly_eval_case_drift_report: wiki/gguf-mirust/reports/browser-assembly-eval-case-drift-memory-2026-06-28.md latest_browser_assembly_evidence_file_drift_report: wiki/gguf-mirust/reports/browser-assembly-evidence-file-drift-memory-2026-06-28.md latest_browser_adapter_family_receipt_drift_report: wiki/gguf-mirust/reports/browser-adapter-family-receipt-drift-memory-2026-06-28.md latest_browser_adapter_manifest_drift_report: wiki/gguf-mirust/reports/browser-adapter-manifest-drift-memory-2026-06-28.md latest_browser_adapter_artifact_drift_report: wiki/gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28.md latest_browser_adapter_stack_prefetch_drift_report: wiki/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md latest_browser_adapter_stack_rust_validate_report: wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md latest_browser_adapter_stack_rust_validate_drift_report: wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28.md latest_browser_combined_selector_route_soak_report: wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md latest_browser_combined_selector_extended_route_soak_report: wiki/gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md latest_browser_combined_selector_stress_route_soak_report: wiki/gguf-mirust/reports/browser-combined-selector-stress-route-soak-memory-2026-06-28.md latest_browser_combined_selector_reload_soak_report: wiki/gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28.md latest_browser_runtime_assembly_diagnostics_report: wiki/gguf-mirust/reports/browser-runtime-assembly-diagnostics-memory-2026-06-28.md latest_browser_selector_genome_fitness_report: wiki/gguf-mirust/reports/browser-selector-genome-fitness-memory-2026-06-28.md latest_browser_selector_species_fit_report: wiki/gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28.md latest_browser_selector_novelty_report: wiki/gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28.md latest_browser_selector_population_report: wiki/gguf-mirust/reports/browser-selector-population-memory-2026-06-28.md latest_browser_selector_mate_selection_report: wiki/gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28.md latest_browser_selector_phenotype_evidence_report: wiki/gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28.md latest_browser_selector_heritable_artifact_report: wiki/gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28.md browser_module_plan_adapter_validation_count: wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-count-memory-2026-06-29.md carries validation-count fields, Module Plan Validate Count display, selector/receipt/adapter-family agreement, runtime validation-count checks, and drift proof before generated model routes. model_breeding_reference: wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md carries compatible merge, sparse-lineage, adapter-ecology including trained low-rank adapter source bundles, source-backed ALR1 manifests, source-backed browser ALR1 routes, source-backed ALR1 receipt source echoes, and ADP1/ASP1/ALR1, population-search, federated/local-update, browser-constrained-assembly, UAIX-memory-strategy, heritable-artifact, mate-selection, phenotype-evidence, and speciation-and-fit lanes. modelbreeder_zero_dependency_reference: wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md carries genome/fitness/novelty/population/speciation guidance plus Wasm SIMD, hierarchical quantization, deterministic tokenizer/sampler, KV-cache, allocator, multimodal, and telemetry lanes. model_breeding_concept_routes: - heritable artifacts: .slm files, manifests, adapter packages, module-plan receipts, assembly receipts, eval sidecars, selector entries, and Model Provenance Artifact rows. - mate selection: compatibility reports, population reviews, parent-pool recipes, relatedness checksums, seed weights, and objective vectors. - phenotype evidence: runtime-smoke sidecars, eval-case evidence checksums, Model Provenance rows, browser smokes, and promotion ledgers. - speciation and fit: f32/q8_0/q4_0 families, tokenizer families, tensor layouts, adapter families, and browser resource envelopes. hot_synthesis: .uai/report-synthesis.uai long_term_pointer_ledger: .uai/long-term-memory.uai site_voice_route: .uai/taboo.uai keeps public copy on proof, craft, lineage, fit, local agency, routes, and implementation evidence. active_next_steps: - For generated assembly or module-plan work after selector receipt binding, preserve selector `entry.N.operator_receipt_*` identity in any served assembly evidence or generated self-assembly receipt that makes operator lineage claims; run focused selector/browser_bundle tests plus receipt-bound admission-to-registry proof after changing those routes. - For browser selector operator receipt work, preserve candidate checksum, candidate byte-count equality, and generated assembly operator-kind agreement between `entry.N.operator_receipt_*` and the selected model entry; run `selector-operator-receipt-drift` for the compact federated fixture, `prune-operator-registry` plus `prune-operator-receipt-drift` for the compact prune fixture, `dare-operator-registry` plus `dare-operator-receipt-drift` for the compact DARE fixture, `crossover-operator-registry` plus `crossover-operator-receipt-drift` for the compact crossover fixture, `mutation-operator-registry` plus `mutation-operator-receipt-drift` for the compact mutation fixture, `generated-selector-operator-receipt-drift` and `generated-selector-operator-kind-drift` for served generated roots, and `multi-parent-registry` or `combined-selector-assembly` to prove the positive Operator row. - For generated multi-parent operator provenance work, preserve `entry.N.operator_receipt_*` fields for multi-parent admissions, require browser Model Provenance Operator rows for generated sign-merge and soup families, and run generated all-root `combined-selector-assembly` with the affected family after app.js, selector registry, multi_admission, browser_bundle, or browser-smoke changes. - For candidate manifest work after any operator output, preserve optional `operator_receipt_status=receipt-bound`, path, checksum, operator id/kind, candidate checksum, and candidate byte fields when an operator receipt is supplied; run focused candidate tests, a receipt-bound CLI chain, full slm_pack tests, and workspace tests after changing the candidate-manifest/validate-candidate boundary. - For promotion template work after receipt-bound candidate manifests, preserve copied `operator_receipt_*` fields in promotions, require the operator receipt input for bound candidates, reject receipt checksum drift, and run focused promotion tests plus a receipt-bound CLI chain before admission work. - For browser selector heritable-artifact work, preserve `entry.N.heritable_artifact_id`, `entry.N.heritable_artifact_strategy=selector-heritable-artifact-v1`, `entry.N.heritable_artifact_status=served-artifact-bound`, and `entry.N.heritable_artifact_checksum`; run selector tests, browser_bundle tests, browser_harness tests, generated `all` root staging, and `combined-selector-assembly` after artifact route or Provenance row changes. - For browser module-plan cardinality work, preserve selector `module_plan_module_count` and receipt `module_count` equality before generated `.slm` fetch, and run `module-plan-count-drift` after count, route, or receipt parsing changes. - For browser module-plan route-set algorithm work, preserve `module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1` in selector registry routes and served receipts, include `route_set_checksum_algorithm=tinyrustlm-text-checksum-v1` in the route-set checksum preimage, render `Route Hash`, and run `module-plan-route-set-algorithm-drift`, source `ui-audit`, and `combined-selector-assembly`. - For browser module-plan WASM memory work, preserve `module_plan_wasm_memory_initial_pages=17` in selector registry routes and served receipts, capture exported memory pages before `init_runtime()`, render the verified `WASM Pages` row, and run `module-plan-wasm-memory-drift` plus `combined-selector-assembly` after memory-envelope changes. - For browser module-plan WASM export-set work, preserve `module_plan_wasm_export_set=tinyrustlm-generate-v1` in selector registry routes and served receipts, verify instantiated WASM exports before generated model fetch, render the verified `WASM ABI` row, and run `module-plan-wasm-export-set-drift` plus `combined-selector-assembly` after runtime ABI changes. - For browser module-plan WASM heap-floor work, preserve `module_plan_wasm_heap_min_bytes` in selector registry routes and served receipts, recompute it as max of 64 KiB, model budget, stack budget, and prompt limit, probe WASM alloc/dealloc before generated model fetch, render `Heap Floor`, and run `module-plan-wasm-heap-drift`, source `ui-audit`, and `combined-selector-cycle`. - For browser module-plan WASM transfer-strategy work, preserve `module_plan_wasm_transfer_strategy=copy-then-release-v1` in selector registry routes and served receipts, keep source fallback `unavailable`, render `Transfer`, and run `module-plan-wasm-transfer-drift`, source `ui-audit`, and `combined-selector-cycle`. - For browser module-plan model-release work, preserve `module_plan_model_release_strategy=free-before-reassembly-v1` in selector registry routes and served receipts, keep source fallback `unavailable`, render `Release`, and run `module-plan-model-release-drift`, source `ui-audit`, and `combined-selector-cycle`. - For browser module-plan runtime-reset work, preserve `module_plan_runtime_reset_strategy=reset-context-before-assembly-v1` in selector registry routes and served receipts, keep source fallback `unavailable`, render `Reset`, call `reset_context` after generated model load and before assembly/adapters, and run `module-plan-runtime-reset-drift`, source `ui-audit`, and `combined-selector-cycle`. - For browser module-plan adapter-validation work, preserve `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1` in selector registry routes and served receipts, keep source fallback `unavailable`, render `Validate`, require Rust validation before adapter apply, and run `module-plan-adapter-validation-drift`, source `ui-audit`, and `combined-selector-assembly`. - For browser module-plan adapter apply-count work, preserve `module_plan_adapter_apply_count=3` in selector registry routes and served receipts, keep source fallback `unavailable`, render `Apply Count`, match adapter-family stack count and runtime `adapter_apply_count`, and run `module-plan-adapter-apply-count-drift` plus positive generated `combined-selector-assembly` after apply-count or stack-cardinality changes. - For browser module-plan actual-fetch-count work, preserve browser-owned counting only for accepted generated self-assembly route fetches, keep source fallback `unavailable`, render `Actual Fetches`, require actual count to match `module_plan_planned_fetch_count` before Ready, and run generated `combined-selector-assembly` plus source `ui-audit` after fetch wrapper or route cardinality changes. - For browser module-plan observed-route-set work, preserve browser-owned `{kind,path}` recording for accepted generated self-assembly route fetches, keep source fallback `unavailable`, render `Actual Route Set`, require observed checksum to match `module_plan_route_set_checksum` before Ready, and run generated `combined-selector-assembly` plus source `ui-audit` after route kind, fetch wrapper, or route-order changes. - For browser module-plan actual-module-checksum work, preserve browser-owned checksum recording for accepted generated model, text sidecar, and auto-stack artifact modules, keep source fallback `unavailable`, render `Actual Module Checksums`, require observed checksums to match receipt `module.N.checksum` rows before Ready, and run generated `combined-selector-assembly`, q4 `adapter-sidecar-registry-file`, `module-plan-payload-checksum-drift`, plus source `ui-audit` after checksum recording changes. - For browser module-plan KV-cache work, preserve `module_plan_kv_cache_byte_budget` and `module_plan_kv_cache_page_count` in selector registry routes, served receipts, runtime diagnostics, and Module Plan rows; include KV bytes in total budget math, and run `module-plan-kv-cache-drift`, `module-plan-total-budget-drift`, and `combined-selector-assembly` after cache-envelope changes. - For browser module-plan context-token work, preserve `module_plan_context_token_limit` in selector registry routes and served receipts, derive it from the validated `.slm` shape, render the verified `Context` row, and run `module-plan-context-token-drift` plus `combined-selector-assembly` after context-window changes. - For browser module-plan tokenizer work, preserve `module_plan_tokenizer_checksum` in selector registry routes and served receipts, derive it from the admitted `.slm` tokenizer checksum, render the verified `Tokenizer` row, keep genome/species checksum ingredients tokenizer-aware, and run `module-plan-tokenizer-drift` plus `combined-selector-assembly` after tokenizer identity changes. - For browser module-plan sampler-cap work, preserve `module_plan_sampler_candidate_cap=1024` in selector registry routes and served receipts, keep browser `Top K` clamped to the fixed-buffer sampler cap, render the verified `Sampler Cap` row, and run `module-plan-sampler-cap-drift` plus `combined-selector-assembly` after sampler-envelope changes. - For browser module-plan output-limit work, preserve `module_plan_output_byte_limit=65536` in selector registry routes and served receipts, verify it before generated `.slm` fetch, render the verified `Output Limit` row, include it in total budget math, and run `module-plan-output-limit-drift` plus `combined-selector-assembly` after generated-result cap changes. - For browser module-plan total budget work, preserve `module_plan_total_byte_budget` in selector registry routes and served receipts, recompute it from exact model, manifest, assembly receipt, adapter-family receipt, ordered stack artifact bytes, runtime scratch, output cap, and KV-cache bytes, render the verified `Total Budget` row, and run `module-plan-total-budget-drift` plus `combined-selector-assembly` after total-envelope changes. - For browser module-plan prompt-limit work, preserve `module_plan_prompt_byte_limit=4096` in selector registry routes and served receipts, render the verified `Prompt Limit` row, include prompt bytes in total budget math, keep source prompt copies inside that envelope, and run `module-plan-prompt-limit-drift`, source `prompt-limit`, and `combined-selector-assembly` after prompt-transfer changes. - For browser module-plan total limit work, preserve `module_plan_total_byte_budget_limit=43454464` in selector registry routes and served receipts, render the verified `Total Limit` row, and run `module-plan-total-limit-drift` plus `combined-selector-assembly` after cap-envelope changes. - For trained adapter source ALR1 work, preserve source manifest validation before packaging, base `.slm` shape/tied-output/tokenizer/layout checks, source target hash/rank/dim matching, ALR1 package checksum and payload checksum recomputation, source-backed manifest equality, and f32/q8_0/q4_0 runtime apply-status routing. - For browser runtime assembly diagnostics work, preserve Rust-owned `adapter_apply_count`, `last_adapter_checksum`, and `assembly_state_checksum`; model load should seed nonzero assembly state, adapter apply should increment count and update checksums, free/load failure should clear the fields, and wasm-abi-smoke plus manual adapter-sidecar and generated combined-selector smokes should assert the fields. - For browser module-plan origin-policy work, preserve `module_plan_origin_policy=same-origin-loopback-local-v1` in selector registry routes and served receipts, verify it before generated `.slm` fetch, render the verified `Origin` row, and run `module-plan-origin-policy-drift` plus a normal generated-root assembly smoke after origin-boundary changes. - For browser module-plan fetch-policy work, preserve `module_plan_fetch_policy=local-no-store-v1` in selector registry routes and served receipts, verify it before generated `.slm` fetch, render the verified `Fetch` row, and run `module-plan-fetch-policy-drift` plus a normal generated-root assembly smoke after local-fetch contract changes. - For browser module-plan execution profile work, preserve `module_plan_execution_profile=single-threaded-wasm-local-v1` in selector registry routes and served receipts, verify it before generated `.slm` fetch, render the verified `Execution` row, and run `module-plan-execution-profile-drift` plus a normal generated-root assembly smoke after execution-envelope changes. - For browser module-plan runtime scratch work, preserve `module_plan_runtime_scratch_byte_budget=65536` in selector registry routes and served receipts, verify it before generated `.slm` fetch, render the verified `Scratch Budget` row, and run `module-plan-runtime-scratch-drift` plus a normal generated-root assembly smoke after runtime-envelope changes. - For browser module-plan contract work, preserve `module_plan_profile=browser-constrained-v1` in selector registry routes and served receipts, verify it before generated `.slm` fetch, and run `module-plan-profile-drift` plus a normal generated-root assembly smoke after profile or receipt-envelope changes. - For browser adapter artifact and stack preflight work, preserve exact stack artifact route matching after all adapter manifests verify, checksum fetched ADP1/ASP1/ALR1 bytes before WASM transfer, run Rust `validate_adapter_delta` for every auto-stack member before any `apply_adapter_delta`, prove checksum-consistent semantic drift stops at Rust validation with `adapter-stack-rust-validate-drift`, and run `adapter-artifact-drift`, `adapter-stack-prefetch-drift`, plus normal generated-root `adapter-sidecar-registry-file` and `combined-selector-assembly` smokes after changes. - For selector admission, promotion-ledger, selector-registry, generated assembly receipt, or Model Provenance eval evidence work, preserve `eval_case_evidence_checksum` as the normalized digest of declared eval case totals and per-case expected/actual/status/error fields; run slm_pack admission/selector/bundle tests plus generated-root `combined-selector-assembly` and `assembly-eval-case-drift` after changes. - For browser assembly evidence-file work, preserve receipt-declared evidence paths and checksums, fetch and checksum each evidence text before adapter-family verification, and run `assembly-evidence-file-drift` plus one normal generated-root `adapter-sidecar-registry-file` smoke after changes. - For browser adapter-family receipt work, preserve same-byte receipt checksum matching after assembly evidence passes, keep adapter manifests and stack artifacts behind verified receipt state, and run `adapter-family-receipt-drift` plus one normal generated-root `adapter-sidecar-registry-file` smoke after changes. - For browser adapter manifest work, preserve same-byte manifest checksum matching after adapter-family receipt verification, keep later manifests and stack artifacts behind verified manifest state, and run `adapter-manifest-drift` plus one normal generated-root `adapter-sidecar-registry-file` smoke after changes. - For browser runtime rebuild, bundle, or boot-sequence work, preserve `tinyrustlm_wasm_manifest_version=1`, `runtime_kind=tinyrustlm-rust-wasm`, `runtime_status=validated-local-runtime`, `runtime_wasm_path=../runtime/tinyrustlm.wasm`, byte count, 64-bit checksum, and `required_next_gate=instantiate-wasm-runtime`; run browser_bundle tests, static browser harness, normal single smoke, runtime-manifest-drift smoke, and one generated-root adapter-sidecar-registry-file smoke after changes. - For browser module-plan work, preserve selector `entry.N.module_plan_*` fields, served `.module-plan.receipt` checksum binding, `module_plan_resource_class=browser-constrained-local-assembly`, model byte budget matching admitted model bytes, adapter byte budget matching the adapter-family budget, module_count matching model plus manifest plus assembly receipt plus adapter-family receipt plus ordered stack members, module byte_count fields matching fetched model/text bytes and adapter manifest artifact bytes, module roles matching runtime/model-manifest/assembly/adapter-family/stack roles, browser pre-model-fetch plan verification, Module Plan panel rendering from verified receipt fields, and Module Plan Trace checkpoints from plan verified through ready; run selector:: tests, browser_bundle:: tests, browser_harness tests, source ui-audit, generated `all` root staging, and one generated-root adapter-sidecar-registry-file or combined-selector-assembly smoke after changes. - For browser module-plan byte-count work, preserve `module.N.byte_count` fields for generated `.slm`, `.slm.manifest`, `.assembly.receipt`, `.adapter-family.receipt`, and ordered stack artifacts; run source ui-audit, generated-root adapter-sidecar-registry-file, and `module-plan-byte-drift` after changes. - For browser module-plan checksum work, preserve `module.N.checksum` fields for generated `.slm`, `.slm.manifest`, `.assembly.receipt`, `.adapter-family.receipt`, and ordered stack artifacts; run source ui-audit, generated-root adapter-sidecar-registry-file, and `module-plan-checksum-drift` after changes. - For browser module-plan phase work, preserve `module.N.phase` fields for load-model-bytes, verify-model-manifest, verify-assembly-evidence, verify-adapter-family, and ordered apply-adapter-stack members; run source ui-audit, generated-root adapter-sidecar-registry-file, and `module-plan-phase-drift` after changes. - For browser text-sidecar contract work, preserve generated selector registry header fields for selector registry 256 KiB, manifest 64 KiB, receipt 128 KiB, and evidence 128 KiB; run selector:: tests, browser_bundle:: tests, sidecar-budget-contract smoke, selector-budget smoke, and one generated-root adapter-sidecar-registry-file smoke after contract changes. - For browser text-sidecar work, preserve selector registry 256 KiB, manifest 64 KiB, receipt 128 KiB, and evidence 128 KiB pre-parse limits; run adapter-manifest-budget plus at least one generated-root adapter-sidecar-registry-file smoke after app.js text fetch changes. - For browser auto-assembly work, preserve explicit selector adapter auto-apply fields, require receipt-preferred compatible strategy, and run generated-root adapter-sidecar-registry-file smokes for q4_0, q8_0, and f32 after app.js, selector registry, adapter-family, or bundle staging changes. - For combined selector assembly work, run `browser-multi-parent-bundle ... all` plus browser-smoke `combined-selector-assembly`; run `combined-selector-cycle` when longer same-page selector reuse, repeated q4_0/q8_0/f32 switching, model-switch release sequencing, or fresh generated-root path-flexible Module Plan summaries are in scope; run `combined-selector-route-soak` for three-cycle route-count proof, `combined-selector-route-extended-soak` for five-cycle selector-route pressure, `combined-selector-route-stress-soak` for eight-cycle local route pressure, `combined-selector-operator-family-route-soak` when mixed sign-merge plus soup roots need per-route proof across all six q4/q8/f32 generated entries, and `combined-selector-operator-family-reload-soak` when mixed roots need fresh page-lifetime proof; run `combined-selector-reload-soak` when registry default boot selection, separate page lifetimes, or reload route-count proof is in scope; preserve q4_0 default selection, q4_0/q8_0/f32 switching, module-plan-before-model ordering, local-only requests, free_model release before every post-initial reassembly, and pre-generation ADP1 plus ASP1 plus ALR1 stack auto assembly for every generated entry. - For browser selector phenotype-evidence work, preserve `entry.N.phenotype_evidence_id`, `entry.N.phenotype_evidence_strategy=selector-phenotype-evidence-v1`, `entry.N.phenotype_evidence_status=runtime-eval-bound`, `entry.N.phenotype_evidence_checksum`, and `entry.N.provenance_manifest_checksum`; run focused selector tests, browser_bundle tests, node syntax checks, browser_harness tests, generated `all` root staging, and `combined-selector-assembly` after phenotype, eval, runtime-smoke, assembly, or Provenance row changes. - For browser selector mate-selection work, preserve `entry.N.mate_selection_id`, `entry.N.mate_selection_strategy=selector-mate-selection-route-v1`, `entry.N.mate_selection_status`, `entry.N.mate_selection_parent_count`, and `entry.N.mate_selection_checksum`; run focused selector tests, browser_bundle tests, node syntax checks, browser_harness tests, generated `all` root staging, and `combined-selector-assembly` after mate-selection or Provenance row changes. - For browser selector species-fit work, preserve `entry.N.species_id`, `entry.N.species_strategy=selector-speciation-fit-v1`, `entry.N.species_fit_status=browser-fit-bound`, and `entry.N.species_fit_checksum`; run focused selector tests, browser_bundle tests, node syntax checks, and generated-root `combined-selector-assembly` after species, genome, fitness, or Provenance row changes. - For browser selector registry intake work, preserve `entry.N.model_bytes` as an up-front browser budget gate, keep static fallback models available when registry entries are invalid, and run browser-smoke selector-budget after app.js or registry parsing changes. - For selector-registry source work, preserve `selector_model_byte_budget=33554432` as a generated and validated Rust contract, then run selector:: tests, browser_bundle:: tests, selector-budget smoke, and one generated-root adapter-sidecar-registry-file smoke after budget contract changes. - For model-breeding reference work, route bodies through wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md and wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md, keep concept lanes as compatibility fields, receipts/manifests, eval/provenance fields, or browser-smoke assertions, update .uai/report-synthesis.uai and this file, then refresh checksum pointers in .uai/long-term-memory.uai. - For report or research intake, preserve bodies in raw/gguf-mirust/ plus wiki/gguf-mirust/ durable pages, reference all current report/research pages from this file, then update long-term checksum pointers; do not turn .uai/long-term-memory.uai into a report body store. - For future model-breeding work, start with tinyrustlm-slm-pack compatibility reports, validate-lineage templates, validate-blend-candidate, validate-delta-candidate, validate-sparse-delta-candidate, validate-dare-candidate, validate-crossover-candidate, validate-mutation-candidate, or validate-prune-candidate receipts, adapter-source-template plus validate-adapter-source when trained low-rank factor bundles are the source material, convert-adapter-source plus validate-converted-adapter-source when reviewed factor bundles should become ALR1, validate-adapter-delta, validate-sparse-adapter-delta, or validate-low-rank-adapter-delta manifests when adapter packages are produced, validate-fuse-adapter-delta receipts when raw ADP1 adapters write .slm candidates, validate-candidate manifests, validate-sign-merge-candidate receipts plus validate-multi-parent-candidate manifests, validate-multi-parent-promotion sidecars, and validate-multi-parent-admission records for sign-merge outputs, validate-promotion sidecars, runtime-smoke sidecars, validate-admission records, validate-promotion-ledger, validate-population-review when selecting a frontier or parent pool, validate-parent-pool-recipe before parent recipe consumers, and validate-selector-registry after validate-admission or validate-multi-parent-admission before browser selector claims: base family, tokenizer hash, tensor schema, quantization semantics, parent hashes, operator recipe, trained adapter source checksums, adapter checksum, sparse mask checksum, DARE mask checksum, DARE raw/rescaled delta checksums, crossover mask checksum, mutation mask checksum, mutation delta checksum, prune mask checksum, prune output-value checksum, low-rank factor metadata, adapter-fuse checksum, candidate artifact checksum, multi-parent receipt checksum, promotion scope, runtime evidence, eval sidecars, promotion history, population fitness, seed weights, and served model route. - Next assembly bead should extend beyond checked f32/q8_0/q4_0 ADP1 sidecars, registry-carried f32/q8_0/q4_0 ADP1/ASP1/ALR1 adapter-family routes, file-backed f32/q8_0/q4_0 generated bundles, runtime-capable ASP1 and ALR1 packages, verified receipt-preferred auto assembly, trained low-rank adapter source intake, source-backed ALR1 conversion, browser-served source-backed ALR1 family routes, deterministic crossover, bounded mutation, magnitude pruning, and DARE into real trained factor bundles, real trained weights, broader offline operators, or longer selector-route exercises while keeping ordinary .slm validation, two-parent admission, ledger, and selector registry routing intact. - Keep breeding operators offline until generated candidates pass normal .slm validation, manifest validation, runtime-smoke, and eval gates. - Read .uai/taboo.uai before changing public site copy, mutualist framing, or model-breeding positioning. - Preserve model-load tensor routing: generation should keep using pre-resolved top-level and per-layer tensor indices and tied-output projection fallback, not per-token layer-name formatting. - Preserve reusable generation memory: scratch/logits are model-loaded Runtime buffers, top-k diagnostics must not reintroduce vocab-sized per-token allocation, and free_model must clear loaded buffers. - Preserve fixed-buffer stochastic sampling: temperature/top-k/top-p/seed decoding must not reintroduce vocab-sized candidate Vec allocation, BPE top_k 262 must remain valid, and top_k above 1024 must remain invalid. - Preserve generation request state: context errors and other failed generate calls must clear prompt/cache diagnostics and must not leave stale tokens for generate_next_token. - Preserve the output-buffer boundary: generated result decode stays capped at 64 KiB, over-limit byte/BPE decode must return OutputBufferExceeded before replacing last_result, and full generate overflow must clear stale generation state. - Preserve the WASM step/free ABI: browser-callable exports return explicit ErrorCode values, payload text stays in last_result, token ids stay in diagnostics, and post-free generation must fail ModelNotLoaded. - Preserve runtime f32/q8_0/q4_0 adapter apply: only compatible ADP1, ASP1, or ALR1 packages may mutate loaded tensors; identity, checksums, layout, tokenizer, directory, finite deltas or factors, sparse indices or low-rank shapes, and fused values must validate before mutation or compact re-quantization, and success must clear generation/KV state. - Preserve browser Adapter Sidecar routing: checked tiny routes remain manual .adp1, generated adapter-family routes may be .adp1 or .asp1 and may auto-assemble only through explicit registry fields, JS stays byte-transfer only, Rust keeps validation authority, and browser-smoke adapter-sidecar or adapter-sidecar-registry-file follows UI or adapter-state changes. - Carry the UAIX dogfood finding back into UAIX.org guidance/spec/wizard when working in the UAIX.org source tree: report batches need hot .uai synthesis, not just durable wiki pointers. - Preserve transcript semantics during browser UI work: local transcript state is DOM-safe text, Reset does not clear history, and Clear clears only history. - Preserve browser Step Token semantics during UI work: disabled before context, enabled after successful generate, appends to response/latest assistant transcript turn, stays enabled after Clear, and disables after Reset or failed generation. - Preserve Visual Studio F5/server busy-port behavior during future helper edits. - Measure the new scratch-backed q8_0/q4_0 row/vector dequantization path across longer prompts and broader browser performance soaks. - Move next from all-quantization untied and tied trained-source conversion plumbing, fixture-scoped eval execution, and Rust browser harness contract coverage into real trained weights and broader assistant-quality evidence review. - 2026-06-25 widened fixed-buffer stochastic sampling from byte-vocab 260 to a 1024-candidate cap, preserving no vocab-sized per-token candidate allocation while allowing the BPE fixture to use top_k 262. - Verification passed after BPE stochastic cap widening and is superseded by later core-ops and tensor-routing runs: focused sampler and runtime BPE top_k tests, node --check app.js, cargo fmt --all -- --check, Rust browser harness, cargo test --workspace, and tools/vs/Test-TinyRustLM.ps1. ================================================================================ END FILE: .uai/short-term-memory.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/startup-packet.uai BYTES: 53812 SHA256: 058F316A6124BB90F8DE2F1BDFF17445276B2B3D82A4FC4B780FD8429AFFD612 ================================================================================ profile: gguf-mirust.startup-packet.v86 updated_utc: 2026-06-29T20:22:33Z startup_sequence: - Read AGENTS.md. - Read workspace.uai. - Read .uai/system-profile.uai. - Read .uai/workspace-guidance.uai. - Read .uai/file-handoff.uai and scan active buckets. - Read .uai/long-term-memory.uai before loading durable docs or wiki files. - Read .uai/architecture.uai and .uai/coding-standards.uai before source edits. - Read .uai/report-synthesis.uai before opening bulk report wiki files. - Read .uai/taboo.uai before public site copy, model-breeding positioning, or mutualist language work. active_buckets: content: agent-file-handoff/Content/ improvement: agent-file-handoff/Improvement/ llm_wiki_target: local: wiki/gguf-mirust/ public: https://aiwikis.org/gguf-mirust/ current_status: Rust toolchain is available at C:\Users\AI\.cargo\bin; 2026-06-26 model-breeding reports are preserved and synthesized into durable memory; checksum-bearing .slm pack/load validation, native .slm admission validation, parent compatibility reports, candidate lineage templates, direct-parameter blend, task-delta, sparse task-delta, deterministic direct-parameter crossover, deterministic bounded mutation, deterministic magnitude pruning, DARE dropout/rescaled task-delta receipts, population-review objective-vector metadata, parent-pool relatedness recipes, sign-aware parent-pool merge operator receipts, and seed-weighted parent-pool soup operator receipts, raw ADP1, sparse ASP1, and low-rank ALR1 adapter-delta artifacts and manifests, adapter-fuse receipts that produce normal .slm candidates from raw ADP1, f32/q8_0/q4_0 ADP1, ASP1, and ALR1 runtime adapter apply with focused Rust coverage, checked browser tiny f32/q8_0/q4_0 self-ADP1 sidecar routes with headless smoke, registry-carried f32/q8_0/q4_0 ADP1/ASP1/ALR1 adapter routes plus generated f32/q8_0/q4_0 adapter-family routes with served adapter-family receipts and adapter manifests fetched and checksum-verified in the browser with headless smoke, registry-controlled receipt-preferred auto assembly for generated ADP1/ASP1/ALR1 sidecars with adapter_auto_apply_byte_budget_1048576, manifest/fetched byte checks, full-stack byte preflight, Rust validate_adapter_delta semantic preflight before the first stack apply, and checksum-consistent Rust semantic validation drift proof before any apply, browser-verified module-plan receipts with `browser-constrained-v1` profile plus `single-threaded-wasm-local-v1` execution profile plus `local-no-store-v1` fetch policy plus `same-origin-loopback-local-v1` origin policy plus fetch-count limit plus planned-fetch-count proof plus route-set-algorithm proof plus route-set-version proof plus route-set checksum proof plus tokenizer checksum identity plus pre-init WASM page envelope and resource-class/model-byte/adapter-byte/runtime-scratch-byte/output-byte-limit/total-byte envelopes before generated `.slm` fetch plus visible execution/fetch/origin/fetch-limit/plan-fetches/route-hash/route-version/route-set/tokenizer/WASM-pages/budget rows, byte summaries, checksum summaries, role summaries, assembly-slot summaries, phase summaries, dependency summaries, browser-owned trace checkpoints from plan verification through ready state, and checksum-consistent module-plan profile, execution-profile, fetch-policy, origin-policy, fetch-count, planned-fetch-count, route-set-algorithm, route-set-version, route-set, tokenizer, WASM-memory, runtime-scratch, output-limit, total-budget, count, resource, graph, stack, role, slot, phase, dependency, byte-count, and checksum drift proofs before generated `.slm` or stack artifact fetch, browser-verified generated assembly receipts for file-backed f32/q8_0/q4_0 generated roots plus assembly eval-case drift proof before evidence and adapter-family routes, fetched assembly evidence-file drift proof before later evidence or adapter routes, adapter-family receipt drift proof after evidence and before adapter manifests or stack artifacts, adapter manifest drift proof after adapter-family receipt and before later manifests or stack artifacts, adapter artifact drift proof after all adapter manifests and before later stack artifacts or Rust adapter apply, adapter stack preflight drift proof after all adapter manifests and before low-rank ALR1 fetch or Rust adapter apply, browser runtime WASM manifest verification before instantiation for checked and generated roots, optional operator-receipt-bound candidate artifact manifests, promotion templates, selector admission records, selector registry entry fields, and browser Model Provenance Operator rendering including compact blend/task-delta/sparse-delta/crossover/mutation/prune/federated proof routes, multi-parent candidate manifests for validated sign-merge or soup output with relatedness summaries, promotion templates, multi-parent promotion templates, multi-parent selector admission records, runtime-smoke sidecars, selector admission records, promotion ledgers, population reviews, parent-pool recipes, selector registries for selector and multi-parent admission records with optional f32/q8_0/q4_0 adapter sidecar, indexed adapter-family fields, adapter-family receipt fields, explicit adapter auto-apply fields, adapter auto-apply byte-budget fields, module-plan profile, execution-profile, fetch-policy, origin-policy, fetch-count-limit, planned-fetch-count, route-set-checksum-algorithm, route-set-version, route-set checksum, tokenizer checksum, WASM-memory-initial-pages, runtime-scratch, output-limit, total-byte, and resource-envelope fields, module-plan byte-count and checksum fields, assembly receipt fields, browser-frugal selector default fields, selector_model_byte_budget contract intake, and exact selector_registry_text/manifest_text/receipt_text/evidence_text budget contract fields, optional browser selector.registry intake, browser-served multi-parent registry smoke, generated browser-served multi-parent f32/q8_0/q4_0 bundle routing with self ADP1, family ADP1, sparse ASP1, and low-rank ALR1 pre-generation validate-then-apply proof, one combined f32/q8_0/q4_0 selector root that defaults to q4_0 before first model load, and browser smokes that switch q4_0, q8_0, and f32 entries through verified module-plan-before-model assembly, ADP1/ASP1/ALR1 stack validation, stack apply, and exact trace rendering, tiny custom BPE .slm runtime fixture diagnostics, artifact-backed tiny tied-output .slm validation/runtime generation, direct core-op tests for dot/matvec/matmul/RMSNorm/softmax/SiLU/SwiGLU, model-load tensor index routing with tied-output projection fallback, raw-f32 trained-source validation plus untied f32/q8_0/q4_0 conversion/eval gating with exact case-ledger assistant-quality evidence, tied-output raw-source validation plus f32/q8_0/q4_0 runtime-smoke conversion gates, TinyLM-16M f32/q8_0/q4_0 smoke generation, direct q8/q4 matvec dispatch, q8/q4 decoded-shadow removal, reusable generation scratch/logits, allocation-free top-k diagnostic selection, fixed-buffer stochastic sampling, context-boundary state cleanup, explicit ErrorCode generate_next_token/validate_adapter_delta/apply_adapter_delta/free_model WASM ABI smoke, browser Step Token UI control smoke, browser Adapter Sidecar UI control smoke, Rust local static server, Rust mini browser static/loopback contract harness with Rust export crawl, browser click plus conversation transcript/provenance-panel/assembly-evidence-panel/reload/reset/model-switch/malformed/missing/context/runtime-manifest-drift/module-plan-profile-drift/module-plan-execution-profile-drift/module-plan-fetch-policy-drift/module-plan-origin-policy-drift/module-plan-fetch-count-drift/module-plan-planned-fetch-count-drift/module-plan-route-set-algorithm-drift/module-plan-route-set-version-drift/module-plan-route-set-drift/module-plan-tokenizer-drift/module-plan-wasm-memory-drift/module-plan-runtime-scratch-drift/module-plan-output-limit-drift/module-plan-total-budget-drift/module-plan-count-drift/module-plan-resource-drift/module-plan-graph-drift/module-plan-stack-drift/module-plan-role-drift/module-plan-slot-drift/module-plan-phase-drift/module-plan-dependency-drift/module-plan-byte-drift/module-plan-checksum-drift/assembly-eval-case-drift/assembly-evidence-file-drift/adapter-family-receipt-drift/adapter-manifest-drift/adapter-artifact-drift/adapter-stack-prefetch-drift/adapter-stack-rust-validate-drift/dynamic-selector-registry/selector-budget/sidecar-budget-contract/multi-parent-registry/generated-multi-parent-registry-file/adapter-sidecar/adapter-sidecar-registry-file/combined-selector-assembly/endurance/performance/performance-soak verification, processed report memory, and TinyRustLM.sln wrapper plus port fallback checks pass; real trained weights, trained-model quality, trained LoRA modules, and additional offline operators beyond blend, delta, sparse-delta, crossover, mutation, prune, DARE, federated, sign-merge, and soup remain pending. latest_status_2026_06_29_browser_converted_trained_provenance: Browser-smoke `converted-trained-registry` now proves a compact selector-served `converted-trained-q8` route fetches a converted-trained manifest, renders converted-trained source/admission/quality/pending-eval fields, and keeps shared multi-parent registry proof green; durable routing is in wiki/gguf-mirust/reports/browser-converted-trained-provenance-memory-2026-06-29.md. latest_status_2026_06_29_browser_converted_trained_file_route: `browser-converted-trained-bundle` now stages a converted-trained q8 artifact plus sidecars under a runnable TinyRustLM root, and `converted-trained-registry-file` proves real selector/model/manifest fetches; durable routing is in wiki/gguf-mirust/reports/browser-converted-trained-file-route-memory-2026-06-29.md. latest_status_2026_06_29_browser_converted_trained_all_route: `browser-converted-trained-bundle ... all` now stages converted-trained f32/q8/q4 artifacts plus sidecars under one q4-defaulted selector root, and `converted-trained-registry-file` proves real selector/model/manifest fetches for all three entries; durable routing is in wiki/gguf-mirust/reports/browser-converted-trained-all-route-memory-2026-06-29.md. latest_status_2026_06_29_parent_pool_evolution_schedule: `parent-pool-recipe` now writes a checksum-bound `population-based-parent-pool-replay-v1` schedule for sign-merge and soup operator families, selected parent seed weights, and population fitness echoes; durable routing is in wiki/gguf-mirust/reports/parent-pool-evolution-schedule-memory-2026-06-29.md. latest_status_2026_06_29_operator_schedule_carry_forward: Sign-merge and soup operator receipts carry parent-pool evolution schedule identity, scheduled family index, command, selection rule, output gate, and checksum; multi-parent candidate manifests validate those fields, and promotion templates plus selector admission records preserve them; durable routing is in wiki/gguf-mirust/reports/operator-schedule-carry-forward-memory-2026-06-29.md. latest_status_2026_06_29_two_parent_operator_browser_provenance: Blend, task-delta, and sparse task-delta compact selector registry proof is now routed through `blend-operator-registry`, `delta-operator-registry`, and `sparse-delta-operator-registry`; the matching receipt-drift modes prove byte-echo fallback to static q8 with Operator unavailable, and durable report routing is in wiki/gguf-mirust/reports/two-parent-operator-browser-provenance-memory-2026-06-29.md. latest_status_2026_06_29_crossover_operator: Offline deterministic direct-parameter crossover is implemented in tinyrustlm-slm-pack as `crossover-candidate` and `validate-crossover-candidate`; receipts bind seed, parent0 keep rate, selected counts, densities, and mask checksum; browser-smoke `crossover-operator-registry` renders the crossover Operator row, `crossover-operator-receipt-drift` proves byte-echo fallback, and durable report routing is in wiki/gguf-mirust/reports/crossover-operator-memory-2026-06-29.md. latest_status_2026_06_29_mutation_operator: Offline deterministic bounded mutation is implemented in tinyrustlm-slm-pack as `mutation-candidate` and `validate-mutation-candidate`; receipts bind seed, rate, magnitude, reference scaling, selection checksum, delta checksum, and recomputed candidate bytes; browser-smoke `mutation-operator-registry` renders the mutation Operator row, `mutation-operator-receipt-drift` proves byte-echo fallback, and durable report routing is in wiki/gguf-mirust/reports/mutation-operator-memory-2026-06-29.md. latest_status_2026_06_29_prune_operator: Offline deterministic magnitude pruning is implemented in tinyrustlm-slm-pack as `prune-candidate` and `validate-prune-candidate`; receipts bind keep/floor ppm, magnitude ranking, selected/pruned counts, mask checksum, output-value checksum, and recomputed candidate bytes; selector tests carry prune receipt fields into `entry.N.operator_receipt_*`, browser-smoke `prune-operator-registry` renders the prune Operator row, `prune-operator-receipt-drift` proves byte-echo fallback, and durable report routing is in wiki/gguf-mirust/reports/prune-operator-memory-2026-06-29.md. latest_status_2026_06_29_dare_operator: Offline DARE dropout/rescaled task-delta is implemented in tinyrustlm-slm-pack as `dare-candidate` and `validate-dare-candidate`; receipts bind signed delta weight ppm, keep/drop ppm, dropout seed, selected/dropped counts, mask checksum, raw delta checksum, rescaled delta checksum, and recomputed candidate bytes; q8 CLI proof and focused parameter/drift tests route durable memory through wiki/gguf-mirust/reports/dare-operator-memory-2026-06-29.md. latest_status_2026_06_29_dare_browser_operator_provenance: DARE compact selector provenance is now routed through `dare-operator-registry`, which renders `receipt-bound / dropout-rescaled-task-delta / 0x00000000000000b7`; `dare-operator-receipt-drift` proves byte fallback to static q8 with Operator unavailable, and durable report routing is in wiki/gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29.md. latest_status_2026_06_29_federated_operator: Offline federated/local-update is implemented in tinyrustlm-slm-pack as `federated-candidate` and `validate-federated-candidate`; receipts bind base/local-update parent roles, local_update_weight_ppm, local-update counts, raw delta checksum, weighted delta checksum, and recomputed candidate bytes, and durable report routing is in wiki/gguf-mirust/reports/federated-operator-memory-2026-06-29.md. latest_status_2026_06_29_weighted_soup_operator: Offline parent-pool weighted soup is implemented in tinyrustlm-slm-pack as `soup-candidate` and `validate-soup-candidate`; receipts bind recipe seed weights, direct weighted averaging, parent-weight checksum, weighted-value checksum, changed-from-frontier density, and recomputed candidate bytes, and durable report routing is in wiki/gguf-mirust/reports/weighted-soup-operator-memory-2026-06-29.md. latest_status_2026_06_29_multi_parent_soup_manifest: Multi-parent candidate manifests now accept validated sign-merge or soup parent-pool operator receipts by dispatching on `operator_kind`, recomputing through the owning operator module, writing `candidate_manifest_status=validated-parent-pool-operator-output`, preserving sign or soup metrics, and routing durable memory through wiki/gguf-mirust/reports/multi-parent-soup-manifest-memory-2026-06-29.md. latest_status_2026_06_29_federated_selector_receipt_route: Selector registry tests and targeted browser smokes now prove a `federated-local-update-average` receipt-bound candidate survives candidate, promotion, admission, selector registry, and browser Model Provenance Operator handoff with operator kind, receipt checksum, candidate checksum, and byte count preserved, reject federated operator-kind drift, and fall back to static q8 when browser operator-receipt candidate byte count drifts; durable report routing is in wiki/gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29.md. latest_status_2026_06_29_candidate_operator_receipt_binding: Candidate artifact manifests can now optionally bind the exact operator receipt used to write a `.slm`; `candidate-manifest` and `validate-candidate` accept `[input.operator]`, write receipt checksum and operator/candidate equality fields, and route durable memory through wiki/gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29.md. latest_status_2026_06_29_promotion_operator_receipt_binding: Promotion templates can now carry candidate operator receipt fields forward; `promotion-template` and `validate-promotion` accept `[input.operator]`, reject missing receipt input for bound candidates, reject promotion receipt drift, and route durable memory through wiki/gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29.md. latest_status_2026_06_28_low_rank_adapter: ALR1 low-rank adapter packages are implemented in the packer and runtime: `low-rank-adapter-delta` and `validate-low-rank-adapter-delta` write and recompute deterministic factor artifacts, and runtime f32/q8_0/q4_0 apply reconstructs compatible matrix deltas before compact re-quantization. latest_status_2026_06_28_browser_low_rank_route: Browser ALR1 route proof now stages generated `{id}-low-rank.alr1` members for f32/q8_0/q4_0 entries, verifies low-rank manifests and module-plan stack module 6, and auto-applies ADP1 plus ASP1 plus ALR1 before generation; durable report routing is in wiki/gguf-mirust/reports/browser-low-rank-adapter-route-memory-2026-06-28.md. latest_status_2026_06_28_browser_source_backed_alr1_route: Generated browser bundles now convert reviewed adapter source templates into source-backed ALR1 stack members, validate them in Rust before apply, and combined-selector-assembly proves q4_0/q8_0/f32 apply ADP1 plus ASP1 plus source-backed ALR1 before generation; durable report routing is in wiki/gguf-mirust/reports/browser-source-backed-alr1-route-memory-2026-06-28.md. latest_status_2026_06_28_browser_source_backed_alr1_contract: Browser source-backed ALR1 intake now verifies exact kind/dtype pairs, adapter-family receipt source echoes, and fetched manifest source fields before stack artifact fetch; `source-backed-alr1-manifest-drift` proves source contract drift stops at adapter manifest validation; durable report routing is in wiki/gguf-mirust/reports/browser-source-backed-alr1-contract-memory-2026-06-28.md. latest_status_2026_06_28: Browser Module Plan Trace now verifies one generated `all` root starts on q4_0, switches through q4_0, q8_0, and f32 entries, requests each module plan before model bytes, auto-applies ADP1 plus ASP1 plus ALR1 stacks before generation, and renders the checkpoint chain through ready; durable report routing is in wiki/gguf-mirust/reports/browser-assembly-trace-memory-2026-06-28.md. latest_status_2026_06_28_eval_case_checksum: Browser eval-case evidence checksum routing now carries `eval_case_evidence_checksum` through admissions, promotion ledger entries, selector registries, generated assembly receipts, and Model Provenance; combined-selector-assembly proves q4_0/q8_0/f32 generated entries display `1 passed` and checksum `0xabdeb569ab3eea3e`; durable report routing is in wiki/gguf-mirust/reports/browser-eval-case-evidence-checksum-memory-2026-06-28.md. latest_status_2026_06_28_assembly_eval_case_drift: Browser assembly eval-case drift proof now frees the accepted generated model and stops before evidence files, adapter-family receipts, adapter manifests, and adapter stack routes when assembly receipt eval digest differs from the selector digest; durable report routing is in wiki/gguf-mirust/reports/browser-assembly-eval-case-drift-memory-2026-06-28.md. latest_status_2026_06_28_assembly_evidence_file_drift: Browser assembly evidence-file drift proof now leaves selector, module-plan, model, manifest, and assembly receipt bytes valid while one fetched evidence file body drifts, then stops before later evidence, adapter-family, adapter manifest, and stack routes; durable report routing is in wiki/gguf-mirust/reports/browser-assembly-evidence-file-drift-memory-2026-06-28.md. latest_status_2026_06_28_adapter_family_receipt_drift: Browser adapter-family receipt drift proof now leaves selector, module-plan, model, manifest, assembly receipt, and all evidence files valid while served adapter-family receipt text drifts at the same byte count, then stops before adapter manifests and ADP1/ASP1/ALR1 stack artifacts; durable report routing is in wiki/gguf-mirust/reports/browser-adapter-family-receipt-drift-memory-2026-06-28.md. latest_status_2026_06_28_adapter_manifest_drift: Browser adapter manifest drift proof now leaves selector, module-plan, model, manifest, assembly receipt, all evidence files, adapter-family receipt, and self adapter manifest valid while served family ADP1 manifest text drifts at the same byte count, then stops before later manifests and ADP1/ASP1/ALR1 stack artifacts; durable report routing is in wiki/gguf-mirust/reports/browser-adapter-manifest-drift-memory-2026-06-28.md. latest_status_2026_06_28_adapter_artifact_drift: Browser adapter artifact drift proof now leaves selector, module-plan, model, manifest, assembly receipt, all evidence files, adapter-family receipt, and all adapter manifests valid while served family ADP1 artifact bytes drift, then stops before sparse/low-rank artifacts or Rust adapter apply; durable report routing is in wiki/gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28.md. latest_status_2026_06_28_adapter_stack_prefetch_drift: Browser adapter stack preflight proof now fetches and verifies auto-applied family ADP1, sparse ASP1, and low-rank ALR1 bytes before any Rust adapter apply; sparse ASP1 byte drift stops before ALR1 fetch or apply_adapter_delta; durable report routing is in wiki/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md. latest_status_2026_06_28_adapter_stack_rust_validate: Browser adapter stack Rust validation proof now routes every fetched auto-stack ADP1/ASP1/ALR1 member through `validate_adapter_delta` before the first `apply_adapter_delta`; durable report routing is in wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md. latest_status_2026_06_28_adapter_stack_rust_validate_drift: Browser adapter stack Rust validation drift proof now keeps selector, module-plan, assembly, adapter-family, manifest, and artifact checksums aligned while family ADP1 identity drifts; Rust `validate_adapter_delta` returns `shape mismatch` before any apply; durable report routing is in wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28.md. latest_status_2026_06_28_runtime_assembly_diagnostics: Rust runtime diagnostics now report `adapter_apply_count`, `last_adapter_checksum`, and `assembly_state_checksum`; WASM ABI smoke, checked manual adapter sidecar smoke, combined-selector-assembly, and combined-selector-cycle assert manual count 1, generated stack count 3, nonzero checksums, and cleared state after free; durable report routing is in wiki/gguf-mirust/reports/browser-runtime-assembly-diagnostics-memory-2026-06-28.md. latest_status_2026_06_28_trained_adapter_source_alr1: Packer trained adapter source ALR1 conversion now validates reviewed low-rank f32 factor bundles against a base `.slm`, writes runtime ALR1 bytes, and recomputes source-backed manifests; durable report routing is in wiki/gguf-mirust/reports/trained-adapter-source-alr1-memory-2026-06-28.md. latest_status_2026_06_28_trained_adapter_source: Packer trained low-rank adapter source intake writes and validates `adapter-source.manifest` plus raw f32 factor files for tiny and TinyLM-16M tied/untied shapes; durable report routing is in wiki/gguf-mirust/reports/trained-adapter-source-memory-2026-06-28.md. latest_status_2026_06_28_combined_selector_cycle: Browser combined selector cycle proof now repeats q4_0/q8_0/f32 generated-root switching twice in one page, releases the prior WASM model before each post-initial assembly, and requires fresh stack validation, apply, completion, reset diagnostics, and one-token generation on every pass; durable report routing is in wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md. latest_status_2026_06_28_combined_selector_route_soak: Browser combined selector route-soak proof now runs three q4_0/q8_0/f32 cycles from one generated `all` root, fetches local assembly resources with no-store cache behavior, and requires every generated self-assembly route once per pass; durable report routing is in wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md. latest_status_2026_06_28_combined_selector_extended_route_soak: Browser combined selector extended route-soak proof now runs five q4_0/q8_0/f32 cycles from one generated `all` root, proves fifteen browser assemblies with fresh route requests, and keeps path-flexible total-budget checks for non-canonical generated roots; durable report routing is in wiki/gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md. latest_status_2026_06_28_combined_selector_reload_soak: Browser combined selector reload-soak proof now runs two fresh page lifetimes from one generated `all` root, starts each page on q4_0, then rebuilds q4_0/q8_0/f32 self-assembly from local module-plan, evidence, adapter-family, manifest, and stack routes; durable report routing is in wiki/gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_profile: Browser module-plan profile proof now requires `module_plan_profile=browser-constrained-v1` in generated selector registry routes and `.module-plan.receipt` files before model fetch; durable report routing is in wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_execution_profile: Browser module-plan execution proof now requires `module_plan_execution_profile=single-threaded-wasm-local-v1` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Execution row, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_fetch_policy: Browser module-plan fetch-policy proof now requires `module_plan_fetch_policy=local-no-store-v1` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Fetch row, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_origin_policy: Browser module-plan origin-policy proof now requires `module_plan_origin_policy=same-origin-loopback-local-v1` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Origin row, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_fetch_count: Browser module-plan fetch-count proof now requires `module_plan_fetch_count_limit=32` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Fetch Limit row, computes generated self-assembly route count before model bytes, counts actual governed generated requests as 21 per q4_0/q8_0/f32 pass, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_runtime_scratch: Browser module-plan runtime scratch proof now requires `module_plan_runtime_scratch_byte_budget=65536` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Scratch Budget row, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_output_limit: Browser module-plan output-limit proof now requires `module_plan_output_byte_limit=65536` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Output Limit row, includes it in total budget math, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-output-limit-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_total_budget: Browser module-plan total budget proof now requires `module_plan_total_byte_budget` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Total Budget row, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-total-budget-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_total_limit: Browser module-plan total-limit proof now requires `module_plan_total_byte_budget_limit=43454464` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Total Limit row, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_wasm_memory: Browser module-plan WASM memory proof now requires `module_plan_wasm_memory_initial_pages=17` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified WASM Pages row, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-wasm-memory-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_wasm_export_set: Browser module-plan WASM export-set proof now requires `module_plan_wasm_export_set=tinyrustlm-generate-v1` in generated selector registry routes and `.module-plan.receipt` files before model fetch, verifies instantiated exports, renders the verified WASM ABI row, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_wasm_heap: Browser module-plan WASM heap-floor proof now requires `module_plan_wasm_heap_min_bytes=65536` in generated selector registry routes and `.module-plan.receipt` files before model fetch, probes WASM alloc/dealloc with that byte count, renders the verified Heap Floor row, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-wasm-heap-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_wasm_transfer: Browser module-plan WASM transfer proof now requires `module_plan_wasm_transfer_strategy=copy-then-release-v1` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Transfer row, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md. latest_status_2026_06_29_module_plan_model_release: Browser module-plan model-release proof now requires `module_plan_model_release_strategy=free-before-reassembly-v1` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Release row, proves release drift stops before generated model routes, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-model-release-memory-2026-06-29.md. latest_status_2026_06_29_module_plan_runtime_reset: Browser module-plan runtime-reset proof now requires `module_plan_runtime_reset_strategy=reset-context-before-assembly-v1` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Reset row, proves reset drift stops before generated model routes, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-runtime-reset-memory-2026-06-29.md. latest_status_2026_06_29_module_plan_adapter_validation: Browser module-plan adapter-validation proof now requires `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Validate row, proves validation-strategy drift stops before generated model routes, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29.md. latest_status_2026_06_29_module_plan_adapter_validation_count: Browser module-plan adapter validation-count proof now requires `module_plan_adapter_validation_count=3` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Validate Count row, counts three Rust validation calls before three applies in generated q4_0/q8_0/f32 assembly, proves validation-count drift stops before generated model routes, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-count-memory-2026-06-29.md. latest_status_2026_06_29_module_plan_adapter_apply_count: Browser module-plan adapter apply-count proof now requires `module_plan_adapter_apply_count=3` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Apply Count row, checks runtime `adapter_apply_count` diagnostics after generated assembly, proves apply-count drift stops before generated model routes, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md. latest_status_2026_06_29_module_plan_planned_fetch_count: Browser module-plan planned-fetch-count proof now requires `module_plan_planned_fetch_count=21` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Plan Fetches row, checks selector/receipt/generated-route agreement, proves planned-fetch-count drift stops before generated model routes, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-planned-fetch-count-memory-2026-06-29.md. latest_status_2026_06_29_module_plan_actual_fetch_count: Browser module-plan actual fetch-count proof now counts accepted generated self-assembly route fetches inside app.js, renders the verified Actual Fetches row, gates generated Ready on actual count matching `module_plan_planned_fetch_count`, proves q4_0/q8_0/f32 each show `21 fetches`, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-actual-fetch-count-memory-2026-06-29.md. latest_status_2026_06_29_module_plan_observed_route_set: Browser module-plan observed route-set proof now records accepted generated self-assembly route `{kind,path}` entries inside app.js, renders the verified Actual Route Set row, gates generated Ready on observed route-set checksum matching `module_plan_route_set_checksum`, proves q4_0/q8_0/f32 equality, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-observed-route-set-memory-2026-06-29.md. latest_status_2026_06_29_module_plan_actual_module_bytes: Browser module-plan actual module-byte proof now records accepted generated module bytes inside app.js, renders Actual Module Bytes, gates generated Ready on observed module bytes matching receipt module byte rows, proves q4_0/q8_0/f32 totals, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-actual-module-bytes-memory-2026-06-29.md. latest_status_2026_06_29_module_plan_actual_module_checksums: Browser module-plan actual module-checksum proof now records accepted generated module checksums inside app.js, renders Actual Module Checksums, gates generated Ready on observed checksums matching receipt module checksum rows, proves q4_0/q8_0/f32 equality, and `module-plan-payload-checksum-drift` proves coherent payload checksum rewrites stop at the stale module-plan checksum row before generated model or adapter routes; durable memory routes through wiki/gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md. latest_status_2026_06_29_module_plan_route_set: Browser module-plan route-set proof now requires `module_plan_route_set_checksum` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Route Set row, checks selector/receipt/ordered-route agreement, proves route-set drift stops before generated model routes, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29.md. latest_status_2026_06_29_module_plan_route_set_version: Browser module-plan route-set version proof now requires `module_plan_route_set_version=1` in generated selector registry routes and `.module-plan.receipt` files before route-set checksum acceptance, renders the verified Route Version row, proves route-set-version drift stops before generated model routes, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-route-set-version-memory-2026-06-29.md. latest_status_2026_06_29_module_plan_route_set_algorithm: Browser module-plan route-set algorithm proof now requires `module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1` in generated selector registry routes and `.module-plan.receipt` files before route-set checksum acceptance, renders the verified Route Hash row, proves route-set-algorithm drift stops before generated model routes, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-route-set-algorithm-memory-2026-06-29.md. latest_status_2026_06_29_module_plan_operator_receipt: Browser module-plan operator receipt proof now requires `module_plan_operator_receipt_path` and `module_plan_operator_receipt_checksum` in generated selector registry routes, matching `.module-plan.receipt` `operator_receipt_*` fields, assembly receipt agreement, and fetched `sign-merge.operator` checksum agreement before generated model bytes; fresh generated combined-selector-assembly proves q4_0 default plus q4_0/q8_0/f32 same-page self-assembly from target/combined-selector-assembly-refresh-20260629/tinyrustlm; durable memory routes through wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md. latest_status_2026_06_29_selector_operator_receipt_binding: Selector registries now carry receipt-bound admission fields as `entry.N.operator_receipt_*`, validate copied-field drift, bind the fields into mate-selection checksums, render browser Model Provenance Operator, and route durable memory through wiki/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29.md. latest_status_2026_06_29_browser_multi_parent_operator_provenance: Generated multi-parent admissions carry full receipt-bound operator metadata into selector `entry.N.operator_receipt_*` fields; fresh soup plus sign-merge combined-selector and drift smokes prove q4/q8/f32 browser Model Provenance Operator rows, `generated-selector-operator-receipt-drift` byte fallback, and `generated-selector-operator-kind-drift` generated assembly operator-kind fallback before generated model, module-plan, assembly, adapter-family, or stack routes are requested; durable memory routes through wiki/gguf-mirust/reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md. latest_status_2026_06_29_browser_mixed_operator_selector: `browser-multi-parent-bundle all mixed` writes one generated selector with sign-merge and soup f32/q8/q4 entries, keeps `multi-parent-sign-merge-q4` as the q4 default, and `combined-selector-operator-family-cycle`, `combined-selector-operator-family-route-soak`, plus `combined-selector-operator-family-reload-soak` prove same-page, route, and fresh-page assembly across all six routes; durable memory routes through wiki/gguf-mirust/reports/browser-mixed-operator-selector-memory-2026-06-29.md. latest_status_2026_06_28_module_plan_kv_cache: Browser module-plan KV-cache proof now requires `module_plan_kv_cache_byte_budget=1024` and `module_plan_kv_cache_page_count=1` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders verified KV Budget and KV Pages rows, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_prompt_limit: Browser module-plan prompt-limit proof now requires `module_plan_prompt_byte_limit=4096` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders the verified Prompt Limit row, includes it in total budget math, blocks oversized source-root prompt bytes before WASM transfer, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-prompt-limit-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_adapter_stack_budget: Browser module-plan adapter-stack proof now requires `module_plan_adapter_stack_byte_budget=22144` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders verified Stack Budget rows, includes exact ADP1/ASP1/ALR1 bytes in totals, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_context_token: Browser module-plan context-token proof now requires `module_plan_context_token_limit=16` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders verified Context rows, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_tokenizer: Browser module-plan tokenizer proof now requires `module_plan_tokenizer_checksum` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders verified Tokenizer rows, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_sampler_cap: Browser module-plan sampler-cap proof now requires `module_plan_sampler_candidate_cap=1024` in generated selector registry routes and `.module-plan.receipt` files before model fetch, renders verified Sampler Cap rows, clamps Top K to the fixed-buffer envelope, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-sampler-cap-memory-2026-06-28.md. latest_status_2026_06_28_module_plan_count_drift: Browser module-plan count-drift proof now mutates receipt `module_count` while refreshing selector module-plan checksum, stops at `Module plan module count mismatch`, and routes durable memory through wiki/gguf-mirust/reports/browser-module-plan-count-drift-memory-2026-06-28.md. latest_status_2026_06_28_modelbreeder_zero_dependency_research: Four new Improvement research files are preserved under raw/gguf-mirust/report-intake-2026-06-28/ and routed through wiki/gguf-mirust/reports/report-intake-index-2026-06-28.md plus wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md for genome/fitness/novelty/speciation and zero-dependency browser-runtime guidance. latest_status_2026_06_28_selector_genome_fitness: Generated selector registries now carry deterministic genome ids, genome lineage checksums, and eval-bound fitness-vector checksums; browser Model Provenance renders Genome/Fitness rows and combined-selector-assembly proves q4_0/q8_0/f32 generated entries; durable report routing is in wiki/gguf-mirust/reports/browser-selector-genome-fitness-memory-2026-06-28.md. latest_status_2026_06_28_selector_species_fit: Generated selector registries now carry deterministic species ids, `browser-fit-bound` species-fit checksums, and browser Model Provenance renders Species rows beside Genome/Fitness; combined-selector-assembly proves q4_0/q8_0/f32 generated entries; durable report routing is in wiki/gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28.md. latest_status_2026_06_28_selector_novelty: Generated selector registries now carry deterministic novelty ids, `behavior-sketch-bound` novelty checksums, and browser Model Provenance renders Novelty rows beside Genome/Species/Fitness; combined-selector-assembly proves q4_0/q8_0/f32 generated entries; durable report routing is in wiki/gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28.md. latest_status_2026_06_28_selector_population: Generated selector registries now carry deterministic population ids, `population-review-bound` population checksums, and browser Model Provenance renders Population rows beside Genome/Species/Novelty/Fitness; combined-selector-assembly proves q4_0/q8_0/f32 generated entries; durable report routing is in wiki/gguf-mirust/reports/browser-selector-population-memory-2026-06-28.md. latest_status_2026_06_28_selector_mate_selection: Generated selector registries now carry deterministic mate-selection ids, parent counts, and `parent-pool-bound` checksums, and browser Model Provenance renders Mate Selection rows beside Genome/Species/Novelty/Population/Fitness; combined-selector-assembly proves q4_0/q8_0/f32 generated entries; durable report routing is in wiki/gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28.md. latest_status_2026_06_28_selector_phenotype_evidence: Generated selector registries now carry deterministic phenotype-evidence ids and `runtime-eval-bound` checksums, and browser Model Provenance renders Phenotype rows beside Genome/Species/Novelty/Population/Mate Selection/Fitness; combined-selector-assembly proves q4_0/q8_0/f32 generated entries; durable report routing is in wiki/gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28.md. latest_status_2026_06_28_selector_heritable_artifact: Generated selector registries now carry deterministic heritable artifact ids and `served-artifact-bound` checksums, and browser Model Provenance renders Artifact rows beside Genome/Species/Novelty/Population/Mate Selection/Phenotype/Fitness; combined-selector-assembly proves q4_0/q8_0/f32 generated entries; durable report routing is in wiki/gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28.md. latest_module_plan_checksum_summary_2026_06_29: The current generated q4 Module Plan panel renders `0: 0x1a6808e3098d1ce0, 1: 0xfa5ea1108910598f, 2: 0xec65527ba6a0a24d, 3: 0x6c3f07949496907d, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6, 6: 0xcaf46ccfc262fad2`; source-root ui-audit keeps the fallback `unavailable`. latest_module_plan_total_budget_summary_2026_06_29: The current generated Module Plan panel renders Total Budget `173430 bytes` for q4_0, `175670 bytes` for q8_0, and `187204 bytes` for f32. latest_module_plan_fetch_count_summary_2026_06_28: The current generated q4/q8/f32 Module Plan panel renders Fetch Limit `32 fetches`; source-root ui-audit keeps the fallback `unavailable`, module-plan-fetch-count-drift stops before generated model bytes, and actual request smokes prove 21 governed fetches per generated pass. latest_module_plan_planned_fetch_count_summary_2026_06_29: The current generated q4/q8/f32 Module Plan panel renders Plan Fetches `21 fetches`; source-root ui-audit keeps the fallback `unavailable`, and module-plan-planned-fetch-count-drift stops after selector registry plus module-plan receipt validation. latest_module_plan_actual_fetch_count_summary_2026_06_29: The current generated q4/q8/f32 Module Plan panel renders Actual Fetches `21 fetches` after accepted generated route loading; source-root ui-audit keeps the fallback `unavailable`, and app.js rejects Ready if the browser-owned count differs from the planned count. latest_module_plan_observed_route_set_summary_2026_06_29: The current generated q4/q8/f32 Module Plan panel renders Actual Route Set checksums equal to declared Route Set checksums after accepted generated route loading; source-root ui-audit keeps the fallback `unavailable`, and app.js rejects Ready if the observed route set differs. latest_module_plan_actual_module_bytes_summary_2026_06_29: The current generated q4/q8/f32 Module Plan panel renders Actual Module Bytes `37238 bytes`, `39478 bytes`, and `51012 bytes`; source-root ui-audit keeps the fallback `unavailable`, and app.js rejects Ready if observed module bytes differ. latest_module_plan_actual_module_checksums_summary_2026_06_29: The current generated q4/q8/f32 Module Plan panel renders Actual Module Checksums equal to declared Checksums after accepted model, manifest, assembly, adapter-family, and stack payloads; source-root ui-audit keeps the fallback `unavailable`, and q4 `module-plan-payload-checksum-drift` stops before generated model routes. latest_module_plan_route_set_summary_2026_06_29: The current generated Module Plan panel renders Route Set checksums q4_0 `0xe7d8c862dec256cb`, q8_0 `0xc6215c5348cef337`, and f32 `0x5317f0a7a894574c`; source-root ui-audit keeps the fallback `unavailable`. latest_module_plan_route_set_version_summary_2026_06_29: The current generated q4/q8/f32 Module Plan panel renders Route Version `1`; source-root ui-audit keeps the fallback `unavailable`, and module-plan-route-set-version-drift stops after selector registry plus module-plan receipt validation. latest_module_plan_route_set_algorithm_summary_2026_06_29: The current generated q4/q8/f32 Module Plan panel renders Route Hash `tinyrustlm-text-checksum-v1`; source-root ui-audit keeps the fallback `unavailable`, and module-plan-route-set-algorithm-drift stops after selector registry plus module-plan receipt validation. latest_module_plan_operator_receipt_summary_2026_06_29: Generated q4/q8/f32 module plans carry sign-merge operator receipt checksums q4_0 `0x1b388cfa4d204a83`, q8_0 `0xbc40437e9d767cf0`, and f32 `0x921cb1168ec2821e`; module-plan-operator-receipt-drift stops after selector registry plus module-plan receipt validation, and fresh combined-selector-assembly proves every entry reaches Ready with `adapter_apply_count=3`. latest_module_plan_prompt_limit_summary_2026_06_28: The current generated q4/q8/f32 Module Plan panel renders Prompt Limit `4096 bytes`; source-root ui-audit keeps the fallback `unavailable`, and source-root prompt-limit proves a 4097-byte prompt stops before WASM transfer. latest_module_plan_output_limit_summary_2026_06_28: The current generated q4/q8/f32 Module Plan panel renders Output Limit `65536 bytes`. latest_module_plan_adapter_stack_budget_summary_2026_06_28: The current generated q4/q8/f32 Module Plan panel renders Stack Budget `22144 bytes`. latest_module_plan_wasm_pages_summary_2026_06_28: The current generated q4/q8/f32 Module Plan panel renders WASM Pages `17`. latest_module_plan_kv_cache_summary_2026_06_28: The current generated q4/q8/f32 Module Plan panel renders KV Budget `1024 bytes` and KV Pages `1`. latest_module_plan_context_token_summary_2026_06_28: The current generated q4/q8/f32 Module Plan panel renders Context `16 tokens`. latest_module_plan_tokenizer_summary_2026_06_28: The current generated q4/q8/f32 Module Plan panel renders Tokenizer `0x288f65d94c26743e`. latest_module_plan_sampler_cap_summary_2026_06_28: The current generated q4/q8/f32 Module Plan panel renders Sampler Cap `1024 candidates`. latest_module_plan_wasm_export_set_summary_2026_06_28: The current generated q4/q8/f32 Module Plan panel renders WASM ABI `tinyrustlm-generate-v1` and validates required instantiated exports before generated model fetch. latest_module_plan_wasm_heap_summary_2026_06_28: The current generated q4/q8/f32 Module Plan panel renders Heap Floor `65536 bytes`; browser receipt validation probes that WASM allocation floor before generated model fetch and source roots render `unavailable`. latest_module_plan_wasm_transfer_summary_2026_06_28: The current generated q4/q8/f32 Module Plan panel renders Transfer `copy-then-release-v1`; source-root ui-audit keeps the fallback `unavailable`. latest_module_plan_model_release_summary_2026_06_29: The current generated q4/q8/f32 Module Plan panel renders Release `free-before-reassembly-v1`; source-root ui-audit keeps the fallback `unavailable`, and combined-selector-cycle proves `free_model` before post-initial reassembly. latest_module_plan_runtime_reset_summary_2026_06_29: The current generated q4/q8/f32 Module Plan panel renders Reset `reset-context-before-assembly-v1`; source-root ui-audit keeps the fallback `unavailable`, and combined-selector-cycle proves `reset_context` before adapter validation/application. latest_module_plan_adapter_validation_summary_2026_06_29: The current generated q4/q8/f32 Module Plan panel renders Validate `rust-validate-before-apply-v1`; source-root ui-audit keeps the fallback `unavailable`, and combined-selector-assembly proves `validate_adapter_delta` before `apply_adapter_delta`. latest_module_plan_adapter_validation_count_summary_2026_06_29: The current generated q4/q8/f32 Module Plan panel renders Validate Count `3`; source-root ui-audit keeps the fallback `unavailable`, and combined-selector-assembly proves three Rust validation calls per generated assembly step. latest_module_plan_trace_2026_06_28: The current generated q4/q8/f32 Module Plan Trace renders `0: plan verified, 1: model accepted, 2: manifest verified, 3: assembly evidence verified, 4: adapter family verified, 5: adapter stack applied, 6: ready`. latest_memory_strategy_2026_06_28: UAIX File Handoff strategy is refreshed from the setup-file-handoff source; current report and research pages are long-term pointer routed, short-term memory exposes report/research/dogfood/site-voice routes, and Model Breeding references now route through merge, sparse, adapter, population, local-update, browser-assembly, UAIX-memory, heritable-artifact, mate-selection, phenotype-evidence, speciation-fit, genome/fitness/novelty, selector genome/species/novelty/population/mate-selection/phenotype/artifact/fitness proof, and zero-dependency browser-runtime lanes. ================================================================================ END FILE: .uai/startup-packet.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/system-profile.uai BYTES: 1287 SHA256: E1F61E1DA97568F16E00EC63A3D92798CACC0EEB569D06743E29D664B2E65552 ================================================================================ profile: gguf-mirust.system-profile.v1 project_name: GGUF.MiRust.com created_utc: 2026-06-24T00:00:00Z canonical_root: E:\Source\Rust\GGUF.MiRust.com project_type: enterprise_rust_browser_ai_harness public_host: https://gguf.mirust.com/ aiwikis_namespace: https://aiwikis.org/gguf-mirust/ llm_wiki_source_namespace: wiki/gguf-mirust/ runtime_status: rust_workspace: tinyrustlm_zero_dependency_workspace_verified mini_browser: no_crate_rust_static_contract_and_loopback_route_harness_implemented browser_ai_harness: rust_mini_browser_contract_harness_plus_headless_chrome_smoke_step_token_reload_reset_model_switch_loop_missing_malformed_context_desktop_mobile_ui_audit_model_provenance_endurance_performance_and_performance_soak_verified gguf_model_runtime: custom_checksum_and_admission_verified_slm_runtime_verified_for_tiny_fixtures_tiny_bpe_tiny_tied_output_and_tinylm16_f32_q8_q4 visual_studio_solution: TinyRustLM.sln verified_for_build_test_run_wrapper_rust_local_server_browser_harness_and_port_fallback public_site: static_tinyrustlm_app_verified_locally authority_layers: human_request: highest local_uai_hot_memory: active_handoff_context llm_wiki: durable_reviewed_memory aiwikis_public_routes: planned_public_durable_memory model_output: proposal_only ================================================================================ END FILE: .uai/system-profile.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/taboo.uai BYTES: 6326 SHA256: 2648476F4CE0813051EC29AFC9C88D3CEADE416D12CECF7A806A2626A13D709C ================================================================================ profile: gguf-mirust.taboo.v12 updated_utc: 2026-06-29T13:45:00Z scope: public_site_voice_and_project_copy purpose: Keep GGUF.MiRust.com focused on constructive local-model craft, verifiable Rust/WASM execution, model lineage, research momentum, and user agency. authority: human_request: 2026-06-26 route_elsewhere: Broad AI policy, harm essays, and alarm-led public messaging belong on other websites. human_update_2026_06_27: This website should not spend public copy on caution-centered or worry-centered AI messaging; keep that content on other sites. human_update_2026_06_27_site_rule: GGUF.MiRust.com pages should not be organized around warnings, cautions, worry, or alarm messaging; use proof, craft, lineage, local agency, and implementation-boundary language instead. human_update_2026_06_27_strategy_rule: Model-breeding, mutualist, tiny-ecology, and UAIX memory-strategy copy for this site should route away from warning/caution/worry messaging and toward proof, craft, lineage, fit, agency, and evidence. human_update_2026_06_27_no_meta_topic_rule: Do not make the absence of caution-centered messaging a public site topic; simply write in the proof, craft, lineage, fit, local-agency, and evidence voice. human_update_2026_06_27_external_topic_rule: Do not make GGUF.MiRust.com carry caution or worry-focused AI messaging; other websites can host that lane while this site stays on proof, craft, lineage, fit, local agency, and implementation evidence. human_update_2026_06_27_memory_strategy_rule: UAIX memory strategy and model-breeding reference copy for this site should stay in proof, craft, lineage, fit, local agency, and implementation evidence voice. human_update_2026_06_27_direct_request_rule: For this website, Model Breeding and UAIX File Handoff strategy should be framed as craft, route, lineage, evidence, fit, and local agency; broader concern-led AI copy belongs elsewhere. human_update_2026_06_28_site_scope_rule: Keep GGUF.MiRust.com public copy out of warnings/cautions/worry framing; those topics belong on other websites while this site carries proof, craft, lineage, fit, local agency, and implementation evidence. human_update_2026_06_28_direct_site_scope_rule: For this website, UAIX strategy and Model Breeding copy should stay centered on routes, lineage, proof, and local implementation evidence; concern-led messaging belongs on separate sites. human_update_2026_06_28_setup_file_handoff_rule: UAIX setup-file-handoff and Model Breeding memory copy should appear as route, lineage, proof, fit, local agency, and implementation evidence for this site. human_update_2026_06_28_latest_direct_rule: GGUF.MiRust.com should not talk about or organize around cautions; other websites can carry that topic while this site carries proof, craft, lineage, fit, local agency, routes, and implementation evidence. human_update_2026_06_28_model_breeding_memory_rule: Model Breeding concepts, research references, UAIX File Handoff strategy, short-term routes, and long-term pointer memory should keep the site voice centered on route maps, candidate lineage, evidence, and local fit. human_update_2026_06_28_setup_handoff_site_rule: UAIX setup-file-handoff strategy should be used here as constructive routing memory for reports, research, short-term routes, and long-term checksum pointers; caution-centered commentary belongs on separate sites. human_update_2026_06_28_latest_direct_rule_2: Keep warnings, cautions, worry, and concern-led messaging out of GGUF.MiRust.com public copy; this file is the intentional local place to name those taboo terms while the site speaks in routes, lineage, proof, fit, local agency, and implementation evidence. human_update_2026_06_28_source_backed_route_rule: Model Breeding, UAIX File Handoff, and source-backed ALR1 route copy for this site should stay in route, lineage, proof, fit, local agency, and implementation evidence language; warning, caution, and worry language belongs only in this taboo routing file when it must be named. human_update_2026_06_28_modelbreeder_research_rule: The 2026-06-28 ModelBreeder research intake should guide GGUF.MiRust.com toward fitness, scope notes, breeding invariants, evaluation checkpoints, local agency, proof-of-use, genome lineage, and implementation fit language. human_update_2026_06_29_latest_direct_rule: Keep this website focused on Model Breeding routes, research references, proof, lineage, fit, local agency, and implementation evidence; caution-centered wording belongs here only as taboo routing memory. human_update_2026_06_29_federated_strategy_rule: Federated/local-update and UAIX File Handoff strategy copy for this site should stay centered on candidate routes, proof-of-use, checksum pointers, lineage, local fit, and implementation evidence. public_site_voice: preferred_emphasis: - browser-local Rust/WASM execution - transparent .slm artifacts and manifests - model breeding as traceable lineage, compatibility, candidate evaluation, and craft - tiny model ecology, adapters, quantization, and local experiments - warm research language around growth, fit, interoperability, and proof taboo_modes: - alarm-led AI essays - speculative doom framing - public copy centered on fear, panic, or worry - public copy organized around cautions instead of craft, lineage, proof, and local agency - broad governance sermons when the page is about TinyRustLM capability - memory-strategy copy that makes concern management the subject instead of routes, evidence, and project fit taboo_terms_for_public_copy: - warning - warnings - caution - cautions - worry - fear - panic replacement_style: warning: use proof, boundary, status, route, or fit when the copy needs a factual project edge. caution: use scope note, implementation boundary, or future lane when the copy needs project routing. risk: use fit, compatibility, or claim boundary when the copy needs technical precision. site_section_titles: use status, evidence, boundaries, routes, fit, lineage, craft, or future lanes. implementation_note: This file guides site voice and public product copy; technical tests, error states, and Rust lint names may still use their exact domain terms where required. ================================================================================ END FILE: .uai/taboo.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/test-plan.uai BYTES: 148129 SHA256: 0EAE31ECAE64A909649A64FC5F408E5BA6D45F1526AB4E4FD4429F7C7572C31F ================================================================================ profile: gguf-mirust.test-plan.v79 updated_utc: 2026-06-29T20:22:33Z available_now: - 2026-06-29 promotion/admission schedule handoff verification passed: cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack multi_promotion -- --nocapture with 5 tests, cargo test -p tinyrustlm-slm-pack multi_admission -- --nocapture with 8 tests including scheduled-kind drift rejection, focused selector multi-parent admission fixture tests, and cargo test -p tinyrustlm-slm-pack with 324 tests. No coverage tool is active in the no-third-party workspace, so field assertions, drift checks, selector fixture coverage, and the full packer suite are recorded against the 75% target. - 2026-06-29 operator schedule carry-forward verification passed: cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack sign_merge -- --nocapture with 5 focused tests, cargo test -p tinyrustlm-slm-pack soup -- --nocapture with 10 focused tests including bundle-dependent soup paths, cargo test -p tinyrustlm-slm-pack multi_candidate -- --nocapture with 8 focused tests, and cargo test -p tinyrustlm-slm-pack with 323 tests. No coverage tool is active in the no-third-party workspace, so focused field assertions plus full packer tests were recorded against the 75% target. - 2026-06-29 parent-pool evolution schedule verification passed: cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack parent_pool -- --nocapture with 9 focused tests covering schedule fields and checksum drift rejection, and cargo test -p tinyrustlm-slm-pack with 323 tests. No coverage tool is active in the no-third-party workspace, so focused field/drift tests plus full packer tests were recorded against the 75% target. - 2026-06-29 browser converted-trained all-route verification passed: `cargo fmt --all`; `node --check tinyrustlm/tools/browser-smoke.js`; focused converted-trained bundle tests; `browser-converted-trained-bundle` generated `target/browser-converted-trained-all-20260629/tinyrustlm` with `all`; `converted-trained-registry-file` smokes for q4/q8/f32 on port 8099 fetched real selector/model/manifest routes and generated `e`; `cargo test -p tinyrustlm-slm-pack` passed with 322 tests. No coverage tool is active in the no-third-party workspace, so all-quant parameter routing, focused path tests, full packer tests, browser file-route proof, and pointer audits are recorded against the 75% target. - 2026-06-29 browser converted-trained file route verification passed: `cargo fmt --all`; `cargo fmt --all -- --check`; `node --check tinyrustlm/tools/browser-smoke.js`; `node --check tinyrustlm/app/app.js`; focused `browser_bundle::tests::writes_browser_converted_trained_bundle_from_source`, `browser_bundle::tests::rejects_browser_converted_trained_bundle_unknown_quantization`, and `selector::tests::display_name_labels_converted_trained_source_entries`; `browser-converted-trained-bundle` generated `target/browser-converted-trained-file-20260629/tinyrustlm`; `converted-trained-registry-file` on port 8096 fetched real selector/model/manifest routes and generated `e`; `cargo test -p tinyrustlm-slm-pack` passed with 321 tests; `git diff --check`, checksum audit, report/research pointer audit, and summary-length audit passed. No coverage tool is active in the no-third-party workspace, so parameter tests, focused path tests, full packer tests, browser file-route proof, and pointer audits are recorded against the 75% target. - 2026-06-29 browser converted-trained provenance verification passed: `node --check tinyrustlm/tools/browser-smoke.js`; `node --check tinyrustlm/app/app.js`; `converted-trained-registry` selected `converted-trained-q8`, fetched `/models/converted-trained-q8.slm.manifest`, generated `e`, and rendered `converted-trained`, `structure-accepted-quality-pending`, `runtime-compatible-not-quality-verified`, and `pending-evaluation`; compact `multi-parent-registry` regression selected `multi-parent-sign-merge-q8` and rendered the federated Operator row; `git diff --check` passed with line-ending notices only. No coverage tool is active in the no-third-party workspace, so syntax checks plus the positive converted-trained smoke and shared registry regression are recorded against the 75% target. - 2026-06-29 DARE browser operator provenance verification passed: node --check tinyrustlm/tools/browser-smoke.js; node --check tinyrustlm/app/app.js; cargo test -p tinyrustlm-slm-pack selector_registry_from_dare -- --nocapture; cargo test -p tinyrustlm-slm-pack selector_registry_dare -- --nocapture; cargo test -p tinyrustlm-slm-pack --quiet with 318 tests; cargo test --workspace --quiet; `dare-operator-registry` rendered `receipt-bound / dropout-rescaled-task-delta / 0x00000000000000b7`; `dare-operator-receipt-drift` fell back to static q8 with Operator unavailable; git diff check and memory pointer audits passed. No coverage tool is active in the no-third-party workspace, so focused selector handoff tests, operator-kind drift tests, browser provenance/fallback smokes, full packer/workspace gates, and report evidence are recorded against the 75% target. - 2026-06-29 DARE operator verification passed: cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack dare -- --nocapture with 11 DARE tests covering default parameters, accepted positive and negative `delta_weight_ppm`, invalid weight parsing, keep-zero, keep-full, invalid keep parsing, explicit and default `dare_dropout_seed`, invalid seed parsing, q8 candidate validation, path-level write/validate, parent checksum drift, and candidate drift; cargo test -p tinyrustlm-slm-pack --quiet passed with 316 tests; q8 CLI compatibility-lineage-mutation-target-DARE-validate chain under `target/dare-cli` wrote and validated a q8_0 DARE candidate. No coverage tool is active in the no-third-party workspace, so focused parameter/drift tests, q8 route tests, path tests, formatting, full packer tests, CLI q8 proof, docs routing, and durable report evidence were recorded against the 75% target. - 2026-06-29 blend/delta/sparse-delta browser operator provenance verification passed: `node --check tinyrustlm/tools/browser-smoke.js`; `blend-operator-registry` rendered `receipt-bound / direct-parameter-weighted-average / 0x00000000000000b4`; `delta-operator-registry` rendered `receipt-bound / direct-parameter-task-delta / 0x00000000000000b5`; `sparse-delta-operator-registry` rendered `receipt-bound / sparse-direct-parameter-task-delta / 0x00000000000000b6`; all three receipt-drift smokes fell back to static q8 with Operator unavailable; shared compact fixture regressions for federated, prune, crossover, and mutation positive registry modes passed on `http://127.0.0.1:8129/app/`. - 2026-06-29 crossover/mutation browser operator provenance verification passed: `node --check tinyrustlm/tools/browser-smoke.js`; `crossover-operator-registry` rendered `receipt-bound / deterministic-direct-parameter-crossover / 0x00000000000000b2`; `crossover-operator-receipt-drift` fell back to static q8 with Operator unavailable; `mutation-operator-registry` rendered `receipt-bound / deterministic-bounded-parameter-mutation / 0x00000000000000b3`; `mutation-operator-receipt-drift` fell back to static q8 with Operator unavailable; shared compact fixture regressions for federated `multi-parent-registry`, prune `prune-operator-registry`, and prune `prune-operator-receipt-drift` passed on `http://127.0.0.1:8128/app/`. No coverage tool is active in the no-third-party workspace, so focused browser provenance/fallback smokes plus existing parameter/drift tests and reports are recorded against the 75% target. - 2026-06-29 prune operator verification passed: cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack prune -- --nocapture with 12 prune-filtered tests covering default/zero/full/invalid `keep_ppm`, default/effective/invalid `floor_ppm`, reference-parent magnitude effects, q8 candidate validation, path-level write/validate, parent checksum drift, candidate drift, selector receipt carry-forward, and selector operator-kind drift; cargo test -p tinyrustlm-slm-pack selector::tests:: -- --nocapture passed with 88 tests including prune receipt-bound selector carry-forward and prune operator-kind drift rejection; cargo test -p tinyrustlm-slm-pack --quiet passed with 305 tests; cargo test --workspace --quiet passed; `prune-operator-registry` browser-smoke rendered `receipt-bound / deterministic-magnitude-parameter-pruning / 0x00000000000000b1`; `prune-operator-receipt-drift` browser-smoke fell back to static q8 with Operator `unavailable`; federated compact-fixture regression smokes for `multi-parent-registry` and `selector-operator-receipt-drift` passed; node --check tinyrustlm/tools/browser-smoke.js and cargo test -p tinyrustlm-browser-harness --quiet passed. No coverage tool is active in the no-third-party workspace, so focused parameter/drift tests, selector handoff tests, browser provenance/fallback smokes, path tests, formatting, full packer, full workspace, CLI q8 proof, docs routing, and durable report evidence were recorded against the 75% target. - 2026-06-29 multi-parent soup manifest verification passed: cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack multi_candidate -- --nocapture with 8 tests covering sign-merge compatibility, soup receipt acceptance, operator-kind dispatch, soup operator version drift, manifest drift, path-level write/validate, and empty receipt rejection; cargo test -p tinyrustlm-slm-pack multi_ -- --nocapture with 23 downstream multi-parent promotion, admission, selector, and browser-bundle tests; cargo test -p tinyrustlm-slm-pack passed with 289 tests. No coverage tool is active in the no-third-party workspace, so focused operator-kind, receipt-version, metric-preservation, path, downstream, formatting, full packer, docs routing, and durable report evidence were recorded against the 75% target. - 2026-06-29 weighted soup operator verification passed: cargo fmt --all, cargo test -p tinyrustlm-slm-pack soup -- --nocapture with 6 tests covering parent-pool ledger/review/recipe/admission inputs, seed-weighted direct averaging, parent order checksum drift, single-parent rejection, candidate drift, receipt operator-kind drift, and path-level write/validate; cargo test -p tinyrustlm-slm-pack passed with 286 tests. No coverage tool is active in the no-third-party workspace, so focused parameter/drift tests, path tests, formatting, full packer tests, docs routing, and durable report evidence were recorded against the 75% target. - 2026-06-29 federated selector receipt route verification passed: cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector::tests::rejects_selector_registry_federated_operator_receipt_kind_drift, cargo test -p tinyrustlm-slm-pack selector::tests:: with 86 tests, cargo test -p tinyrustlm-slm-pack with 280 tests, node --check tinyrustlm/tools/browser-smoke.js, targeted browser-smoke `selector-operator-receipt-drift` proving byte-count drift falls back to static `tinylm16q8` with Operator `unavailable`, and targeted browser-smoke `multi-parent-registry` rendering Model Provenance Operator as `receipt-bound / federated-local-update-average / 0x00000000000000b0`. No coverage tool is active in the no-third-party workspace, so downstream operator-kind, receipt-checksum, candidate-checksum, candidate-byte-count, selector validation, browser fallback drift rejection, browser provenance rendering, and full packer evidence were recorded against the 75% target. - 2026-06-29 federated operator verification passed: cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack federated with 9 tests, cargo test -p tinyrustlm-slm-pack with 278 tests, cargo build -p tinyrustlm-slm-pack, and q8 CLI compatibility-lineage-federated-candidate-validate chain under `target/federated-cli`. No coverage tool is active in the no-third-party workspace, so default/zero/full/partial/invalid `local_update_weight_ppm` tests, q8 validation, path tests, drift tests, full packer tests, formatting, build, and CLI proof were recorded against the 75% target. - 2026-06-29 browser module-plan actual module-checksums verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo run --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml -- tinyrustlm with 9 checks, fresh generated `target/module-plan-actual-module-checksums-20260629/tinyrustlm all`, generated `combined-selector-assembly` on http://127.0.0.1:18766/app/ proving q4_0/q8_0/f32 Actual Module Checksums equal declared Checksums, generated q4 `adapter-sidecar-registry-file` on the same root, source `ui-audit` on http://127.0.0.1:18767/app/ proving fallback `unavailable`, follow-up `module-plan-payload-checksum-drift` on http://127.0.0.1:18768/app/ proving coherent payload checksum rewrites stop at the stale module-plan checksum row before generated model or adapter routes, and follow-up q4 `adapter-sidecar-registry-file` on the same root. No coverage tool is active in the no-third-party workspace, so browser-owned checksum assertions, generated-root smoke, source UI audit, static harness evidence, and payload-checksum drift evidence were recorded against the 75% target. - 2026-06-29 browser module-plan actual module-bytes verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo run --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml -- tinyrustlm with 9 checks, generated `combined-selector-assembly` on existing `target/module-plan-actual-module-bytes-20260629/tinyrustlm` served at http://127.0.0.1:18764/app/ proving q4_0 Actual Module Bytes `37234 bytes`, q8_0 `39474 bytes`, and f32 `51008 bytes`, and source `ui-audit` on http://127.0.0.1:18765/app/ proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so browser-owned module-byte assertions, generated-root smoke, source UI audit, and static harness evidence were recorded against the 75% target. - 2026-06-29 browser module-plan observed route-set verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, git diff --check with line-ending notices only, cargo run --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-observed-route-set-20260629/tinyrustlm all, generated `combined-selector-assembly` on http://127.0.0.1:18762/app/ proving q4_0/q8_0/f32 each display observed route-set checksum equal to declared Route Set, and source `ui-audit` on http://127.0.0.1:18763/app/ proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so browser-owned route-set assertions, generated-root smoke, source UI audit, and static harness evidence were recorded against the 75% target. - 2026-06-29 browser module-plan actual fetch-count verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, git diff --check with line-ending notices only, cargo run --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml -- tinyrustlm with 9 checks, generated `combined-selector-assembly` on existing `target/module-plan-actual-fetch-count-20260629/tinyrustlm` served at http://127.0.0.1:18752/app/ proving q4_0/q8_0/f32 each display Plan Fetches and Actual Fetches `21 fetches`, and source `ui-audit` on http://127.0.0.1:18753/app/ proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so browser-owned route-count assertions, generated-root smoke, source UI audit, and static harness evidence were recorded against the 75% target. - 2026-06-29 browser module-plan operator receipt verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml module_plan_operator -- --nocapture, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml selector::tests:: -- --nocapture with 84 tests, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture with 4 tests, cargo fmt --all -- --check, git diff --check with line-ending notices only, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml with 269 tests, cargo test --workspace, cargo run --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-operator-receipt-drift-20260629/tinyrustlm all, generated `module-plan-operator-receipt-drift` on http://127.0.0.1:18731/app/, generated q4 `adapter-sidecar-registry-file` on http://127.0.0.1:18734/app/, browser-multi-parent-bundle target/combined-selector-assembly-refresh-20260629/tinyrustlm all, and fresh generated `combined-selector-assembly` on http://127.0.0.1:18751/app/ proving q4_0 default plus q4_0/q8_0/f32 operator-bound self-assembly. No coverage tool is active in the no-third-party workspace, so focused field/drift tests, full packer tests, workspace tests, static harness, generated-root drift, positive q4 browser smoke, and combined all-root browser smoke were recorded against the 75% target. - 2026-06-29 selector operator receipt binding verification passed: cargo fmt --all, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml selector::tests::writes_and_validates_selector_registry_from_operator_receipt_bound_admission -- --nocapture, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml selector::tests::rejects_selector_registry_operator_receipt_field_drift -- --nocapture, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml selector::tests:: -- --nocapture with 82 tests, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml with 267 tests, cargo build --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml, cargo test --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml -- --nocapture with 6 tests, cargo run --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml -- tinyrustlm with 9 checks, and receipt-bound q8 CLI compatibility-lineage-mutation-candidate-promotion-provenance-runtime-eval-admission-selector-registry chain under C:\Users\AI\AppData\Local\Temp\tinyrustlm-selector-receipt-4acd025a5de0418dbc54c0ffe6c91350. No coverage tool is active in the no-third-party workspace, so focused field/drift tests, full packer tests, browser parser syntax, static harness, build, and CLI proof were recorded against the 75% target. - 2026-06-29 admission operator receipt binding verification passed: cargo fmt, focused admission tests with 21 tests, full tinyrustlm-slm-pack tests with 265 tests, cargo build, receipt-bound q8 CLI compatibility-lineage-mutation-candidate-promotion-provenance-runtime-eval-admission chain under a temp route, cargo test --workspace, and cargo fmt check. No coverage tool is active in the no-third-party workspace, so focused parameter/drift tests, path tests, full packer tests, workspace tests, formatting, build, and CLI proof were recorded against the 75% target. - 2026-06-29 promotion operator receipt binding verification passed: cargo fmt --all, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml candidate -- --nocapture with 50 tests, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml promotion -- --nocapture with 15 tests covering optional receipt input, promotion receipt field carry-forward, missing receipt input, receipt checksum drift, path APIs, and unbound compatibility; cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml passed with 261 tests; cargo build --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml rebuilt the CLI; q8 CLI compatibility-lineage-mutation-candidate-promotion chain wrote and validated a receipt-bound promotion under a temp route; cargo test --workspace passed. No coverage tool is active in the no-third-party workspace, so focused parameter/drift tests, full packer tests, workspace tests, formatting, build, and CLI proof were recorded against the 75% target. - 2026-06-29 candidate operator receipt binding verification passed: cargo fmt --all -- --check, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml candidate -- --nocapture with 50 candidate tests covering optional receipt input, receipt checksum drift, missing receipt input, candidate checksum disagreement, path APIs, and unbound compatibility; q8 CLI compatibility-lineage-mutation-candidate-manifest-validate chain wrote and validated target/candidate-operator-binding/candidate.candidate with candidate.operator; cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml -- --nocapture passed with 257 tests; cargo test --workspace passed across browser_harness, local_server, runtime, and slm_pack; git diff --check exited 0 with line-ending notices only. No coverage tool is active in the no-third-party workspace, so focused parameter/drift tests, full packer tests, workspace tests, formatting, and CLI proof were recorded against the 75% target. - 2026-06-29 mutation operator verification passed: cargo fmt --all -- --check, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml mutation -- --nocapture with 11 mutation tests covering seed, rate, magnitude, reference-parent scale, q8 output, path defaults, parent checksum drift, candidate drift, and invalid parameters; q8 CLI compatibility-lineage-mutation-validate chain wrote and validated target/mutation-cli/candidate.slm plus candidate.operator; cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml -- --nocapture passed with 252 tests. No coverage tool is active in the no-third-party workspace, so focused parameter tests, drift tests, full packer tests, formatting, and CLI proof were recorded against the 75% target. - 2026-06-29 browser module-plan route-set algorithm verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml route_set -- --nocapture, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture, cargo test --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml writes_and_validates_selector_registry_with_module_plan_receipt -- --nocapture, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-route-set-algorithm/tinyrustlm all, generated `module-plan-route-set-algorithm-drift` on http://127.0.0.1:8262/app/ proving algorithm mismatch stops before generated model bytes, generated `combined-selector-assembly` on http://127.0.0.1:8262/app/ proving q4_0/q8_0/f32 render Route Hash `tinyrustlm-text-checksum-v1`, source `ui-audit` on http://127.0.0.1:8263/app/ proving fallback `unavailable`, and cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml with 232 tests. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-29 browser module-plan route-set version verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml route_set -- --nocapture, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture, cargo test --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml writes_and_validates_selector_registry_with_module_plan_receipt -- --nocapture, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-route-set-version/tinyrustlm all, generated `module-plan-route-set-version-drift` on http://127.0.0.1:8260/app/ proving route-set version mismatch stops before generated model bytes, generated `combined-selector-assembly` on http://127.0.0.1:8260/app/ proving q4_0/q8_0/f32 render Route Version `1`, source `ui-audit` on http://127.0.0.1:8261/app/ proving fallback `unavailable`, and cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml with 230 tests. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-29 browser module-plan route-set verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml route_set -- --nocapture, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture, cargo test --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml with 228 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-route-set-checksum/tinyrustlm all, generated `module-plan-route-set-drift` on http://127.0.0.1:8258/app/ proving route-set checksum mismatch stops before generated model bytes, generated `combined-selector-assembly` on http://127.0.0.1:8258/app/ proving q4_0/q8_0/f32 render nonzero Route Set checksums, and source `ui-audit` on http://127.0.0.1:8259/app/ proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-29 browser module-plan planned-fetch-count verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml planned_fetch -- --nocapture, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture, cargo test --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml rejects_module_plan_count_drift -- --nocapture, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml with 226 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-planned-fetch-count/tinyrustlm all, generated `module-plan-planned-fetch-count-drift` on http://127.0.0.1:8256/app/ proving planned-count mismatch stops before generated model bytes, generated `combined-selector-assembly` on http://127.0.0.1:8256/app/ proving q4_0/q8_0/f32 render Plan Fetches `21`, and source `ui-audit` on http://127.0.0.1:8257/app/ proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-29 browser module-plan adapter validation-count verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml module_plan_adapter -- --nocapture, cargo test --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml with 224 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-adapter-validation-count/tinyrustlm all, generated `module-plan-adapter-validation-count-drift` on http://127.0.0.1:8254/app/ proving validation-count mismatch stops before generated model bytes, generated `combined-selector-assembly` on http://127.0.0.1:8254/app/ proving q4_0/q8_0/f32 render Validate Count `3` with three Rust validation calls per generated assembly step, and source `ui-audit` on http://127.0.0.1:8255/app/ proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-29 browser module-plan adapter apply-count verification passed: cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml module_plan_adapter -- --nocapture, cargo test --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml, cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, generated q4_0/q8_0/f32 browser-multi-parent-bundle roots to refresh expected module-plan totals/checksums, generated `module-plan-adapter-apply-count-drift` on http://127.0.0.1:8242/app/ proving apply-count mismatch stops before generated model bytes, fresh generated all-root `combined-selector-assembly` on http://127.0.0.1:8252/app/ proving q4_0/q8_0/f32 render Apply Count `3`, report runtime `adapter_apply_count=3`, and generate after ADP1/ASP1/ALR1 stack apply, and cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml with 223 tests. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated receipt checks, and browser-smoke evidence were recorded against the 75% target. - 2026-06-29 browser module-plan adapter-validation verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector with 74 tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-adapter-validation/tinyrustlm all, generated `module-plan-adapter-validation-drift` on http://127.0.0.1:8240/app/ proving validation-strategy mismatch stops before generated model bytes, generated `combined-selector-assembly` on http://127.0.0.1:8240/app/ proving q4_0/q8_0/f32 Validate `rust-validate-before-apply-v1` and `validate_adapter_delta` before `apply_adapter_delta`, and source `ui-audit` on http://127.0.0.1:8241/app/ proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-29 browser module-plan runtime-reset verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector with 73 tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-runtime-reset/tinyrustlm all, generated `module-plan-runtime-reset-drift` on http://127.0.0.1:8235/app/ proving reset-strategy mismatch stops before generated model bytes, generated `combined-selector-cycle` on http://127.0.0.1:8235/app/ proving q4_0/q8_0/f32 Reset `reset-context-before-assembly-v1` and `reset_context` before adapter validation/application, and source `ui-audit` on http://127.0.0.1:8236/app/ proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-29 browser module-plan model-release verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector with 72 tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-model-release/tinyrustlm all, generated `module-plan-model-release-drift` on http://127.0.0.1:8233/app/ proving release-strategy mismatch stops before generated model bytes, generated `combined-selector-cycle` on http://127.0.0.1:8233/app/ proving q4_0/q8_0/f32 Release `free-before-reassembly-v1` and `free_model` before post-initial reassembly, and source `ui-audit` on http://127.0.0.1:8234/app/ proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-28 browser module-plan WASM transfer-strategy verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector with 71 tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-wasm-transfer/tinyrustlm all, generated `module-plan-wasm-transfer-drift` on http://127.0.0.1:8231/app/, generated `combined-selector-cycle` on http://127.0.0.1:8231/app/ proving q4_0/q8_0/f32 Transfer `copy-then-release-v1`, and source `ui-audit` on http://127.0.0.1:8232/app/ proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-28 browser module-plan WASM heap-floor verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-browser-harness, cargo run -p tinyrustlm-browser-harness -- tinyrustlm, cargo test -p tinyrustlm-slm-pack browser_bundle, cargo test -p tinyrustlm-slm-pack selector with 70 tests, browser-multi-parent-bundle target/module-plan-wasm-heap/tinyrustlm all, generated `module-plan-wasm-heap-drift` on http://127.0.0.1:8221/app/, generated `combined-selector-cycle` on http://127.0.0.1:8221/app/ proving q4_0/q8_0/f32 Heap Floor `65536 bytes`, and source `ui-audit` on http://127.0.0.1:8222/app/ proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-28 browser module-plan actual fetch-count verification passed: node --check tinyrustlm/tools/browser-smoke.js, browser-multi-parent-bundle target/module-plan-actual-fetch-count/tinyrustlm all, generated-root `combined-selector-cycle 2` on http://127.0.0.1:8213/app/ proving q4_0/q8_0/f32 each used 21 governed requests per pass and 42 governed requests over two passes under the 64-request two-pass envelope, and generated-root `combined-selector-reload-soak 2` proving the same 21-per-pass count across two fresh page lifetimes. - 2026-06-28 browser module-plan fetch-count verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack fetch_count_limit, cargo test -p tinyrustlm-slm-pack writes_and_validates_selector_registry_with_module_plan_receipt, cargo test -p tinyrustlm-slm-pack writes_combined_browser_multi_parent_bundle, cargo test -p tinyrustlm-slm-pack writes_quantized_browser_multi_parent_bundles, cargo test -p tinyrustlm-browser-harness, browser-multi-parent-bundle target/module-plan-fetch-count-drift/tinyrustlm all, generated `combined-selector-assembly` on http://127.0.0.1:8211/app/ proving q4_0/q8_0/f32 Fetch Limit `32 fetches` and total budgets 173415/175655/187189 bytes, generated `module-plan-fetch-count-drift` proving no generated model or stack routes after fetch-count mismatch, and source `ui-audit` proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-28 browser module-plan prompt-limit verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, focused selector prompt-byte-limit tests, focused browser_bundle generated bundle tests, cargo test -p tinyrustlm-browser-harness, browser-multi-parent-bundle target/module-plan-prompt-limit-drift/tinyrustlm all, generated `combined-selector-assembly` on http://127.0.0.1:8201/app/ proving q4_0/q8_0/f32 Prompt Limit `4096 bytes`, current total budgets 173415/175655/187189 bytes, total limit 43454464 bytes, `module-plan-prompt-limit-drift` proving no generated model or stack routes after prompt-limit mismatch, source `ui-audit` proving fallback `unavailable`, and source `prompt-limit` proving 4097-byte prompts stop before WASM transfer while keeping the loaded model usable. - 2026-06-28 browser module-plan output-limit verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all, cargo test -p tinyrustlm-slm-pack module_plan_output, cargo test -p tinyrustlm-slm-pack missing_output_byte_limit, cargo test -p tinyrustlm-slm-pack writes_and_validates_selector_registry_with_module_plan_receipt, focused browser_bundle tests, cargo test -p tinyrustlm-browser-harness, cargo run -p tinyrustlm-browser-harness -- tinyrustlm, full cargo test -p tinyrustlm-slm-pack with 211 tests, browser-multi-parent-bundle target/module-plan-output-limit-drift/tinyrustlm all, combined-selector-assembly on http://127.0.0.1:8197/app/ proving q4_0/q8_0/f32 Output Limit values of 65536 bytes and total budgets 169320/171560/183094 bytes, module-plan-output-limit-drift proving the drift stops at module-plan validation, module-plan-runtime-scratch-drift neighboring regression, and source ui-audit proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-28 browser module-plan WASM export-set verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector::tests::rejects_module_plan_wasm_export_set_drift, cargo test -p tinyrustlm-slm-pack selector::tests:: with 57 tests, cargo test -p tinyrustlm-slm-pack browser_bundle::tests:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-wasm-export-set-drift/tinyrustlm all, combined-selector-assembly on http://127.0.0.1:8106/app/ proving q4_0/q8_0/f32 render WASM ABI `tinyrustlm-generate-v1`, module-plan-wasm-export-set-drift proving no generated model or adapter routes after export-set mismatch, source ui-audit proving fallback `unavailable`, report/research pointer audit finding 87 reports and 2 research pages with 0 missing, local checksum audit checking 196 targets with 0 mismatches, and git diff --check with line-ending notices only. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-28 browser module-plan sampler-cap verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector::tests::rejects_module_plan_sampler_candidate_cap_drift, cargo test -p tinyrustlm-slm-pack selector::tests::writes_and_validates_selector_registry_with_module_plan_receipt, cargo test -p tinyrustlm-slm-pack selector::tests:: with 56 tests, cargo test -p tinyrustlm-slm-pack browser_bundle::tests:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/browser-served-sampler-cap/tinyrustlm all, combined-selector-assembly proving Sampler Cap `1024 candidates`, module-plan-sampler-cap-drift proving no generated model or adapter routes after sampler-cap mismatch, and source ui-audit proving fallback `unavailable`. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-28 browser module-plan tokenizer verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector::tests::rejects_module_plan_tokenizer_checksum_drift, cargo test -p tinyrustlm-slm-pack selector::tests::writes_and_validates_selector_registry_with_module_plan_receipt, cargo test -p tinyrustlm-slm-pack selector::tests:: with 55 tests, cargo test -p tinyrustlm-slm-pack browser_bundle::tests:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/browser-served-tokenizer/tinyrustlm all, combined-selector-assembly on http://127.0.0.1:8104/app/ proving Tokenizer `0x288f65d94c26743e`, and module-plan-tokenizer-drift proving no generated model or adapter routes after tokenizer mismatch. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-28 browser module-plan context-token verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector::tests::rejects_module_plan_context_token_limit_drift, cargo test -p tinyrustlm-slm-pack browser_bundle::tests:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/browser-served-context-token/tinyrustlm all, combined-selector-assembly on http://127.0.0.1:8103/app/ proving Context `16 tokens`, module-plan-context-token-drift proving no generated model or adapter routes after context mismatch, and module-plan-kv-cache-drift regression. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-28 browser module-plan adapter-stack budget verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector::tests:: with 53 tests, cargo test -p tinyrustlm-slm-pack browser_bundle::tests:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/browser-served-stack-budget/tinyrustlm all, combined-selector-assembly, module-plan-adapter-stack-budget-drift, and module-plan-total-budget-drift on http://127.0.0.1:8102/app/. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-28 browser module-plan KV-cache verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-runtime with 82 tests, cargo test -p tinyrustlm-slm-pack selector with 56 selector-filtered tests, cargo test -p tinyrustlm-slm-pack slm_validate with 6 tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 static checks, browser-multi-parent-bundle target/browser-served-kv-cache/tinyrustlm all, combined-selector-assembly, module-plan-kv-cache-drift, module-plan-total-budget-drift, and module-plan-total-limit-drift on http://127.0.0.1:8101/app/. No coverage tool is active in the no-third-party workspace, so focused parameter tests, Rust tests, generated-root, static harness, and browser-smoke evidence were recorded against the 75% target. - 2026-06-28 browser module-plan total limit verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector with 54 selector-filtered tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/browser-served-total-limit/tinyrustlm all, combined-selector-assembly on http://127.0.0.1:8100/app/ proving q4_0/q8_0/f32 Total Limit values of 43384832 bytes, module-plan-total-limit-drift proving no generated model or adapter routes after cap mismatch, and git diff --check with line-ending notices only; no coverage tool is active in the no-third-party workspace, so focused syntax, Rust tests, generated-root, static harness, and browser-smoke evidence was recorded. - node --check tinyrustlm/app/app.js passed after browser Step Token edits. - node --check tinyrustlm/tools/static-server.js passed. - node --check tinyrustlm/tools/browser-smoke.js passed after transcript smoke assertions were added. - node --check tinyrustlm/tools/wasm-abi-smoke.js passed after WASM step/free/adapter ABI edits. - rg source scan found no active third-party dependency declarations in Cargo manifests. - rg file scan verified tinyrustlm source/docs/app/fixture tree exists. toolchain_now_available: - C:\Users\AI\.cargo\bin\cargo.exe - C:\Users\AI\.cargo\bin\rustc.exe - C:\Users\AI\.cargo\bin\rustup.exe coverage_and_test_design: - Target at least 75% automated test coverage for changed code; include the coverage command and result when a coverage tool is available. - If no coverage tool is active in the no-third-party workspace, record focused `cargo test`, Node syntax/smoke, browser-smoke, or harness evidence plus the coverage-tool gap. - Every added or changed method/function parameter should have at least one automated assertion related to behavior controlled by that parameter. - New standalone test files should mirror the source filename with `test` appended before the extension in a toolchain-safe form, such as `trained_adapter_source_test.rs` for `trained_adapter_source.rs` or `browser_smoke_test.js` for `browser-smoke.js`. - Each added or changed method/function should include a concise explanatory comment or doc comment for purpose, contract, parameter semantics, or non-obvious invariants. completed_toolchain_checks: - 2026-06-28 browser selector heritable-artifact verification passed: cargo fmt --check, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo test -p tinyrustlm-slm-pack selector with 53 tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, browser-multi-parent-bundle target/browser-served-heritable-artifact/tinyrustlm all, and browser-smoke combined-selector-assembly on http://127.0.0.1:8100/app/ with debugger port 19572 proving q4_0/q8_0/f32 generated entries render Genome, Species, Novelty, Population, Mate Selection, Phenotype, Artifact, and Fitness provenance rows; no coverage tool is active in the no-third-party workspace, so focused syntax, Rust tests, generated-root, and browser-smoke evidence was recorded. - 2026-06-28 browser selector phenotype-evidence verification passed: cargo fmt, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo test -p tinyrustlm-slm-pack selector with 52 tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, browser-multi-parent-bundle target/browser-served-phenotype-evidence/tinyrustlm all, and browser-smoke combined-selector-assembly on http://127.0.0.1:8099/app/ with debugger port 19570 proving q4_0/q8_0/f32 generated entries render Genome, Species, Novelty, Population, Mate Selection, Phenotype, and Fitness provenance rows; no coverage tool is active in the no-third-party workspace, so focused syntax, Rust tests, generated-root, and browser-smoke evidence was recorded. - 2026-06-28 browser selector mate-selection verification passed: cargo fmt, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo test -p tinyrustlm-slm-pack selector with 51 tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, browser-multi-parent-bundle target/browser-served-mate-selection/tinyrustlm all, and browser-smoke combined-selector-assembly on http://127.0.0.1:8098/app/ with debugger port 19568 proving q4_0/q8_0/f32 generated entries render Genome, Species, Novelty, Population, Mate Selection, and Fitness provenance rows; no coverage tool is active in the no-third-party workspace, so focused syntax, Rust tests, generated-root, and browser-smoke evidence was recorded. - 2026-06-28 browser selector mate-selection final audit passed: reran cargo fmt --check, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-slm-pack selector with 51 tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, and cargo test -p tinyrustlm-browser-harness with 6 tests; report/research pointer audit found 78 reports and 2 research pages with 0 missing, and local pointer checksum audit checked 187 targets with 0 mismatches. - 2026-06-28 browser selector population verification passed: cargo fmt, cargo fmt --check, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo test -p tinyrustlm-slm-pack selector with 49 tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, browser-multi-parent-bundle target/browser-served-multi-parent-all/tinyrustlm all, and browser-smoke combined-selector-assembly on http://127.0.0.1:8097/app/ with debugger port 19566 proving q4_0/q8_0/f32 generated entries render Genome, Species, Novelty, Population, and Fitness provenance rows; no coverage tool is active in the no-third-party workspace, so focused syntax, Rust tests, generated-root, and browser-smoke evidence was recorded. - 2026-06-28 browser selector novelty verification passed: cargo fmt, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo test -p tinyrustlm-slm-pack selector with 48 tests, cargo test -p tinyrustlm-slm-pack with 196 tests, browser-multi-parent-bundle target/browser-served-multi-parent-all/tinyrustlm all, and browser-smoke combined-selector-assembly on http://127.0.0.1:8096/app/ with debugger port 19564 proving q4_0/q8_0/f32 generated entries render Genome, Species, Novelty, and Fitness provenance rows; no coverage tool is active in the no-third-party workspace, so focused syntax, Rust tests, generated-root, and browser-smoke evidence was recorded. - 2026-06-28 browser selector species-fit verification passed: cargo fmt, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo test -p tinyrustlm-slm-pack selector with 47 tests, cargo test -p tinyrustlm-slm-pack with 195 tests, browser-multi-parent-bundle target/browser-served-multi-parent-all/tinyrustlm all, and browser-smoke combined-selector-assembly on http://127.0.0.1:8096/app/ proving q4_0/q8_0/f32 generated entries render Genome, Species, and Fitness provenance rows; no coverage tool is active in the no-third-party workspace, so focused syntax, Rust tests, generated-root, and browser-smoke evidence was recorded. - 2026-06-28 browser selector genome/fitness verification passed: cargo fmt, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, git diff --check with line-ending notices only, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo test -p tinyrustlm-slm-pack with 193 tests, browser-multi-parent-bundle target/browser-served-modelbreeder/tinyrustlm all, and browser-smoke combined-selector-assembly on http://127.0.0.1:8096/app/ proving q4_0/q8_0/f32 generated entries render Genome and Fitness provenance rows; no coverage tool is active in the no-third-party workspace, so focused syntax, Rust tests, generated-root, and browser-smoke evidence was recorded. - 2026-06-28 ModelBreeder and zero-dependency research intake preservation passed: copied 4 active Improvement files to raw/gguf-mirust/report-intake-2026-06-28/, verified source-to-raw SHA256 matches, recorded duplicate ModelBreeder hashes, created report-intake-index-2026-06-28.md and modelbreeder-zero-dependency-reference-ideas-2026-06-28.md, and cleared the active source bucket after durable routing. - 2026-06-28 browser combined selector stress route-soak verification passed: node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-browser-harness with 6 tests, browser-multi-parent-bundle target/combined-selector-route-stress-soak/tinyrustlm all, and browser-smoke combined-selector-route-stress-soak on http://127.0.0.1:8194/app/ proving eight q4_0/q8_0/f32 cycles, twenty-four generated assemblies, per-pass route requests, release-before-reassembly, Rust stack validation/apply, WASM Pages 17, and one-token generation; no coverage tool is active in the no-third-party workspace, so focused syntax, harness, generated-root, and browser-smoke evidence was recorded. - 2026-06-28 browser module-plan count drift verification passed: node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-browser-harness with 6 tests, browser-multi-parent-bundle target/module-plan-count-drift/tinyrustlm all, and browser-smoke module-plan-count-drift on http://127.0.0.1:8193/app/ proving `Module plan module count mismatch` after selector and module-plan receipt fetch only; no coverage tool is active in the no-third-party workspace, so focused syntax, harness, generated-root, and browser-smoke evidence was recorded. - 2026-06-28 browser combined selector extended route-soak verification passed: node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-browser-harness with 6 tests, browser-multi-parent-bundle target/combined-selector-route-extended-soak/tinyrustlm all, and browser-smoke combined-selector-route-extended-soak on http://127.0.0.1:8192/app/ proving five q4_0/q8_0/f32 cycles, fifteen generated assemblies, per-pass route requests, release-before-reassembly, Rust stack validation/apply, WASM Pages 17, and one-token generation. - 2026-06-28 browser module-plan WASM memory verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack module_plan with 12 tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-wasm-memory-drift/tinyrustlm all, combined-selector-assembly on http://127.0.0.1:8191/app/ proving q4_0/q8_0/f32 render `WASM Pages` as 17, module-plan-wasm-memory-drift proving no generated `.slm` route after drift, cargo test --workspace with 281 checks, and E: storage recovered to about 66.49 GB free. - 2026-06-28 browser module-plan total budget verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack module_plan with 11 tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-total-budget-drift/tinyrustlm all, combined-selector-assembly on http://127.0.0.1:8190/app/ proving q4_0/q8_0/f32 Total Budget values 102760/105000/116534 bytes, module-plan-total-budget-drift proving no generated model or adapter routes after total mismatch, and cargo test --workspace. - 2026-06-28 browser combined selector reload-soak verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, cargo test -p tinyrustlm-slm-pack browser_bundle with 4 tests, browser-multi-parent-bundle target/combined-selector-reload-soak/tinyrustlm all, combined-selector-reload-soak with 2 reloads on http://127.0.0.1:8186/app/ proving two fresh page lifetimes start q4_0 and rebuild q4_0/q8_0/f32 self-assembly, strict combined-selector-assembly on the same root with refreshed exact module-plan byte/checksum baselines, and cargo test --workspace with 279 checks. - 2026-06-28 browser source-backed ALR1 contract verification passed: cargo fmt --all, cargo fmt --all -- --check, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, focused tinyrustlm-slm-pack adapter_family tests with 10 tests, browser_bundle tests with 4 tests, browser-multi-parent-bundle target/source-backed-alr1-contract/tinyrustlm all, source-backed-alr1-manifest-drift browser smoke on http://127.0.0.1:8176/app/ proving adapter_source_base_contract drift stops before stack artifacts, combined-selector-assembly browser smoke proving q4_0/q8_0/f32 still apply source-backed ALR1, and cargo test --workspace with 279 checks. - 2026-06-28 browser source-backed ALR1 route verification passed: cargo fmt --all, cargo fmt --all -- --check, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, focused tinyrustlm-slm-pack adapter_family tests with 8 tests, browser_bundle tests with 4 tests, trained_adapter_source tests with 10 tests, cargo test -p tinyrustlm-slm-pack with 186 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/source-backed-alr1-route/tinyrustlm all, combined-selector-assembly browser smoke on http://127.0.0.1:18770/app/ proving q4_0/q8_0/f32 validate and apply source-backed ALR1 before generation, and cargo test --workspace with 277 checks. - 2026-06-28 trained adapter source ALR1 verification passed: cargo fmt --all, cargo fmt --all -- --check, focused tinyrustlm-slm-pack trained_adapter_source tests with 10 tests, cargo test -p tinyrustlm-slm-pack with 185 tests, cargo build -p tinyrustlm-slm-pack, CLI adapter-source-template plus convert-adapter-source plus validate-converted-adapter-source round-trip, and cargo test --workspace with 276 checks. - 2026-06-28 browser module-plan origin-policy verification passed: cargo fmt --all -- --check, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-slm-pack module_plan with 10 tests, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-origin-policy-drift/tinyrustlm all, browser-smoke module-plan-origin-policy-drift proving no generated model or adapter routes, browser-smoke module-plan-fetch-policy-drift regression, and browser-smoke combined-selector-assembly proving q4_0/q8_0/f32 still reach ready while rendering Origin as same-origin-loopback-local-v1. - 2026-06-28 browser module-plan fetch-policy verification passed: cargo fmt --all -- --check, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-slm-pack module_plan with 9 tests, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-fetch-policy-drift/tinyrustlm all, browser-smoke module-plan-fetch-policy-drift proving no generated model or adapter routes, browser-smoke module-plan-execution-profile-drift regression, and browser-smoke combined-selector-assembly proving q4_0/q8_0/f32 still reach ready while rendering Fetch as local-no-store-v1. - 2026-06-28 browser module-plan execution profile verification passed: cargo fmt --all -- --check, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-slm-pack module_plan with 8 tests, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-execution-profile-drift/tinyrustlm all, browser-smoke module-plan-execution-profile-drift proving no generated model or adapter routes, and browser-smoke combined-selector-assembly proving q4_0/q8_0/f32 still reach ready while rendering Execution as single-threaded-wasm-local-v1. - 2026-06-28 browser module-plan runtime scratch verification passed: cargo fmt --all -- --check, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-slm-pack module_plan with 7 tests, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-runtime-scratch-drift/tinyrustlm all, browser-smoke module-plan-runtime-scratch-drift proving no generated model or adapter routes, and browser-smoke combined-selector-assembly proving q4_0/q8_0/f32 still reach ready while rendering Scratch Budget as 65536 bytes. - 2026-06-28 browser module-plan profile verification passed: cargo fmt --all -- --check, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-slm-pack module_plan with 4 tests, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/module-plan-profile-drift/tinyrustlm all, browser-smoke module-plan-profile-drift proving no generated model or adapter routes, and browser-smoke combined-selector-assembly proving q4_0/q8_0/f32 still reach ready. - 2026-06-28 browser combined selector route-soak verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/combined-selector-route-soak/tinyrustlm all, and browser-smoke combined-selector-route-soak on http://127.0.0.1:18760/app/ with 3 cycles proving nine q4_0/q8_0/f32 passes, per-pass route requests, release-before-reassembly, stack validation, stack apply, and one-token generation. - 2026-06-28 browser adapter stack Rust validation verification passed: node syntax checks for app.js, browser-smoke.js, and wasm-abi-smoke.js; cargo fmt --check; focused runtime adapter tests; full runtime tests with 79 tests; browser_harness tests with 6 tests; rebuilt wasm32 release runtime and refreshed runtime manifest; wasm-abi-smoke proving `adapter validated` before `adapter applied`; static browser harness with 9 checks; generated `target/adapter-stack-validate/tinyrustlm all`; browser-smoke `adapter-stack-prefetch-drift` on http://127.0.0.1:18752/app/ proving drift still stops before Rust apply; normal q4 `adapter-sidecar-registry-file` proving three `validate_adapter_delta` calls precede three `apply_adapter_delta` calls; and `combined-selector-assembly` proving q4_0/q8_0/f32 each validate before apply. - 2026-06-28 browser adapter stack preflight drift verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, browser-multi-parent-bundle target/adapter-stack-prefetch-drift/tinyrustlm all, browser-smoke adapter-stack-prefetch-drift on http://127.0.0.1:18750/app/ for multi-parent-sign-merge-q4 proving `adapter artifact checksum mismatch`, model_loaded true, trace through adapter family verified, family ADP1 and sparse ASP1 artifact routes requested, low-rank ALR1 artifact route not requested, and no apply_adapter_delta console call, plus q4 adapter-sidecar-registry-file proving the normal path still reaches ready and applies ADP1 plus ASP1 plus ALR1, existing adapter-artifact-drift, cargo test -p tinyrustlm-browser-harness with 6 tests, and cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks. - 2026-06-28 browser adapter artifact drift verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, browser-smoke adapter-artifact-drift on http://127.0.0.1:18749/app/ for multi-parent-sign-merge-q4 proving `adapter artifact checksum mismatch`, model_loaded true, trace through adapter family verified, all adapter manifest routes requested, only the first family ADP1 stack artifact requested, no sparse/low-rank stack artifact routes, and no apply_adapter_delta console call, plus q4 adapter-sidecar-registry-file proving the normal path still reaches ready and applies ADP1 plus ASP1 plus ALR1, cargo test -p tinyrustlm-browser-harness with 6 tests, and cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks. - 2026-06-28 browser adapter manifest drift verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, browser-smoke adapter-manifest-drift on http://127.0.0.1:18748/app/ for multi-parent-sign-merge-q4 proving `adapter 1 manifest checksum mismatch`, model_loaded true, assembly evidence verified, self and family manifest route ordering, no later manifest routes, and no adapter stack artifact routes, plus q4 adapter-sidecar-registry-file on the same generated root proving the normal path still reaches ready and applies ADP1 plus ASP1 plus ALR1, cargo test -p tinyrustlm-browser-harness with 6 tests, and cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks. - 2026-06-28 browser adapter-family receipt drift verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, browser-multi-parent-bundle target/adapter-family-receipt-drift/tinyrustlm all, browser-smoke adapter-family-receipt-drift on http://127.0.0.1:18747/app/ for multi-parent-sign-merge-q4 proving `adapter family receipt checksum mismatch`, model_loaded true, assembly evidence verified, no adapter manifest routes, and no adapter stack artifact routes, plus q4 adapter-sidecar-registry-file on the paired generated root proving the normal path still reaches ready and applies ADP1 plus ASP1 plus ALR1. - 2026-06-28 Model Breeding and UAIX memory strategy refresh verification passed: active handoff bucket scan found no non-placeholder files, report/research pointer audit found 47 reports and 1 research page with 0 missing from .uai/long-term-memory.uai, local pointer checksum audit checked 154 targets with 0 mismatches, non-voice changed-file taboo-term scan found no matches, and git diff --check passed with line-ending notices only. - 2026-06-28 browser assembly evidence-file drift verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, browser-multi-parent-bundle target/assembly-evidence-file-drift/tinyrustlm all, browser-smoke assembly-evidence-file-drift on http://127.0.0.1:18732/app/ for multi-parent-sign-merge-q4 proving `assembly evidence rejected`, model_loaded false, first evidence route requested, and no later evidence/adapter routes, plus q4 adapter-sidecar-registry-file on the same generated root proving the normal path still reaches ready and applies ADP1 plus ASP1 plus ALR1. - 2026-06-28 browser assembly eval-case drift verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, browser-multi-parent-bundle target/assembly-eval-case-drift/tinyrustlm all, browser-smoke assembly-eval-case-drift on http://127.0.0.1:8099/app/ for multi-parent-sign-merge-q4 proving `assembly evidence rejected`, disabled generation controls, selector recovery, model_loaded false, and no evidence/adapter routes, plus browser-smoke combined-selector-assembly on the same served root proving q4_0/q8_0/f32 still reach ready. - 2026-06-28 browser eval-case evidence checksum verification passed: cargo test -p tinyrustlm-slm-pack with 168 tests, cargo test -p tinyrustlm-runtime with 77 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, node tinyrustlm/tools/wasm-abi-smoke.js tinyrustlm/runtime/tinyrustlm.wasm, browser-multi-parent-bundle target/browser-assembly-trace/tinyrustlm all, and browser-smoke combined-selector-assembly on http://127.0.0.1:8098/app/ proved q4_0/q8_0/f32 generated entries render `1 passed` and checksum `0xabdeb569ab3eea3e`. - 2026-06-28 browser ALR1 route verification passed: cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack with 167 tests, cargo build -p tinyrustlm-runtime --release --target wasm32-unknown-unknown, runtime WASM copy and manifest refresh, cargo test -p tinyrustlm-runtime with 77 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, node tinyrustlm/tools/wasm-abi-smoke.js tinyrustlm/runtime/tinyrustlm.wasm, browser-multi-parent-bundle target/browser-alr1-route/tinyrustlm all, and f32/q8_0 served-root adapter-sidecar-registry-file smokes on http://127.0.0.1:8097/app/ proving ADP1 plus ASP1 plus ALR1 stack apply before generation. - 2026-06-28 final ALR1 memory refresh verification passed: cargo fmt --all -- --check, cargo test -p tinyrustlm-runtime with 77 tests, cargo test -p tinyrustlm-slm-pack with 165 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, report pointer audit for 44 reports and 1 research page, long-term checksum audit for 151 local pointer targets, and git diff --check exited 0 with line-ending notices only. - 2026-06-28 ALR1 low-rank adapter package verification passed: cargo fmt --all -- --check, cargo test -p tinyrustlm-runtime adapter with 12 tests, cargo test -p tinyrustlm-slm-pack adapter with 27 tests, CLI compatibility-lineage-low-rank-adapter-delta-validate-low-rank-adapter-delta chain under target/low-rank-adapter, cargo test -p tinyrustlm-runtime with 77 tests, cargo test -p tinyrustlm-slm-pack with 165 tests, and cargo test -p tinyrustlm-browser-harness with 6 tests. - 2026-06-28 browser assembly trace verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-assembly-trace/tinyrustlm all, and browser-smoke combined-selector-assembly on http://127.0.0.1:18744/app/ for multi-parent-sign-merge-q4 proved q4_0/q8_0/f32 each render Module Plan Trace `0: plan verified, 1: model accepted, 2: manifest verified, 3: assembly evidence verified, 4: adapter family verified, 5: adapter stack applied, 6: ready`. - 2026-06-27 memory strategy refresh checks passed: active handoff bucket scan found only .gitkeep placeholders, report pointer audit found no current wiki/gguf-mirust/reports/*.md pages missing from .uai/long-term-memory.uai, and short-term memory now routes the UAIX strategy dogfood note, Model Breeding research page, report indexes, and long-term pointer ledger. - 2026-06-28 final memory and focused verification passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, report/research pointer audit for 43 reports and 1 research page, and long-term checksum audit for 72 local file pointers. - 2026-06-28 node --check tinyrustlm/tools/browser-smoke.js, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/combined-selector-assembly/tinyrustlm all, and browser-smoke combined-selector-assembly on http://127.0.0.1:18742/app/ for multi-parent-sign-merge-q4 proved one generated served root starts on q4_0, switches q4_0/q8_0/f32 in one page, verifies `.module-plan.receipt` before each `.slm`, applies each receipt-declared stack before generation, and generates one local token per module. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-checksums/tinyrustlm all, generated-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18736/app/ for multi-parent-sign-merge-q4 proving ordered Module Plan checksum summary `0: 0x1a6808e3098d1ce0, 1: 0xb3f89bf19fb0895a, 2: 0x10c2f412e7751fbd, 3: 0x0571c8fd7c145691, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6`, generated-root browser-smoke module-plan-checksum-drift on http://127.0.0.1:18736/app/ for multi-parent-sign-merge-q4 proving selector plus module-plan requests and no q4 `.slm`, stack adapter, or stack manifest requests after checksum-consistent `module.4.checksum` drift, source-root browser-smoke ui-audit on http://127.0.0.1:18738/app/ for tinylm16q8 proving checksum fallback `unavailable`, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, and cargo test --workspace with 249 checks passed after adding browser Module Plan checksums. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-byte-counts/tinyrustlm all, generated-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18732/app/ for multi-parent-sign-merge-q4 proving ordered Module Plan byte summary `0: 6592 bytes, 1: 585 bytes, 2: 1849 bytes, 3: 4316 bytes, 4: 20224 bytes, 5: 832 bytes`, generated-root browser-smoke module-plan-byte-drift on http://127.0.0.1:18732/app/ for multi-parent-sign-merge-q4 proving selector plus module-plan requests and no q4 `.slm`, stack adapter, or stack manifest requests after checksum-consistent `module.0.byte_count` drift, source-root browser-smoke ui-audit on http://127.0.0.1:18734/app/ for tinylm16q8 proving byte fallback `unavailable`, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, and cargo test --workspace with 249 checks passed after adding browser Module Plan byte counts. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-phases/tinyrustlm all, generated-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18728/app/ for multi-parent-sign-merge-q4 proving ordered Module Plan phase summary, generated-root browser-smoke module-plan-phase-drift on http://127.0.0.1:18728/app/ for multi-parent-sign-merge-q4 proving selector plus module-plan requests and no q4 `.slm`, stack adapter, or stack manifest requests after checksum-consistent `module.4.phase` drift, source-root browser-smoke ui-audit on http://127.0.0.1:18730/app/ for tinylm16q8 proving phase fallback `unavailable`, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, and cargo test --workspace with 249 checks passed after adding browser Module Plan phases. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-dependencies/tinyrustlm all, generated-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18724/app/ for multi-parent-sign-merge-q4 proving ordered Module Plan dependency summary, generated-root browser-smoke module-plan-dependency-drift on http://127.0.0.1:18724/app/ for multi-parent-sign-merge-q4 proving selector plus module-plan requests and no q4 `.slm`, stack adapter, or stack manifest requests after checksum-consistent `module.4.depends_on` drift, source-root browser-smoke ui-audit on http://127.0.0.1:18726/app/ for tinylm16q8 proving dependency fallback `unavailable`, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, cargo test --workspace with 249 checks, git diff --check with line-ending notes only, temp profile cleanup, server cleanup, and listening-port check passed after adding browser Module Plan dependencies. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-slots/tinyrustlm all, generated-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18720/app/ for multi-parent-sign-merge-q4 proving ordered Module Plan slot summary, generated-root browser-smoke module-plan-slot-drift on http://127.0.0.1:18720/app/ for multi-parent-sign-merge-q4 proving selector plus module-plan requests and no q4 `.slm`, stack adapter, or stack manifest requests after checksum-consistent `module.4.assembly_slot` drift, source-root browser-smoke ui-audit on http://127.0.0.1:18722/app/ for tinylm16q8 proving slot fallback `unavailable`, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, and cargo test --workspace with 249 checks passed after adding browser Module Plan assembly slots. - 2026-06-27 node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-role-drift/tinyrustlm all, served-root browser-smoke module-plan-role-drift on http://127.0.0.1:18718/app/ for multi-parent-sign-merge-q4 proving `/models/selector.registry` plus `/models/multi-parent-sign-merge-q4.module-plan.receipt` were requested and generated `.slm`, ADP1, ASP1, and adapter-manifest routes were not requested after checksum-consistent `module.4.role` drift, cargo test --workspace with 249 checks, temp profile cleanup, and server cleanup passed after adding browser module-plan role drift proof. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-role-display/tinyrustlm all, receipt inspection for q4 module roles, source-root browser-smoke ui-audit on http://127.0.0.1:18714/app/ for tinylm16q8 proving Module Plan fallback roles `unavailable`, generated-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18716/app/ for multi-parent-sign-merge-q4 proving the ordered runtime/model-manifest/assembly/adapter-family/family-stack/sparse-stack role summary, cargo test --workspace with 249 checks, and git diff --check with line-ending notes only passed after adding browser Module Plan role display. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, source-root browser-smoke ui-audit on http://127.0.0.1:18710/app/ for tinylm16q8 proving Module Plan fallback budget rows `unavailable`, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-budget-display/tinyrustlm all, generated-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18712/app/ for multi-parent-sign-merge-q4 proving Module Plan model budget `6592 bytes` and adapter budget `1048576 bytes`, and cargo test --workspace with 249 checks passed after adding browser Module Plan budget display. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, source-root browser-smoke ui-audit on http://127.0.0.1:18706/app/ for tinylm16q8 proving Module Plan fallback state `none`, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-display/tinyrustlm all, generated-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18708/app/ for multi-parent-sign-merge-q4 proving Module Plan loaded fields and family ADP1 plus sparse ASP1 stack display, cargo test --workspace with 249 checks, git diff --check with line-ending notes only, temp profile cleanup, and server/port cleanup passed after adding browser Module Plan display. - 2026-06-27 node --check tinyrustlm/tools/browser-smoke.js, node --check tinyrustlm/app/app.js, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-stack-drift/tinyrustlm all, served-root browser-smoke module-plan-stack-drift on http://127.0.0.1:18704/app/ for multi-parent-sign-merge-q4 proving `/models/selector.registry` plus `/models/multi-parent-sign-merge-q4.module-plan.receipt` were requested and generated `.slm`, ADP1, ASP1, and adapter-manifest routes were not requested after checksum-consistent `module.4.adapter_path` drift, cargo fmt --all -- --check, cargo test --workspace with 249 checks, temp profile cleanup, and server cleanup passed after adding browser module-plan stack drift proof. - 2026-06-27 node --check tinyrustlm/tools/browser-smoke.js, node --check tinyrustlm/app/app.js, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-graph-drift/tinyrustlm all, served-root browser-smoke module-plan-graph-drift on http://127.0.0.1:18702/app/ for multi-parent-sign-merge-q4 proving `/models/selector.registry` plus `/models/multi-parent-sign-merge-q4.module-plan.receipt` were requested and `/models/multi-parent-sign-merge-q4.slm` was not requested after checksum-consistent `module.0.path` drift, cargo fmt --all -- --check, cargo test --workspace with 249 checks, and server cleanup passed after adding browser module-plan graph drift proof. - 2026-06-27 node --check tinyrustlm/tools/browser-smoke.js, node --check tinyrustlm/app/app.js, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-resource-drift/tinyrustlm all, served-root browser-smoke module-plan-resource-drift on http://127.0.0.1:18700/app/ for multi-parent-sign-merge-q4 proving `/models/selector.registry` plus `/models/multi-parent-sign-merge-q4.module-plan.receipt` were requested and `/models/multi-parent-sign-merge-q4.slm` was not requested after checksum-consistent adapter-budget drift, cargo fmt --all -- --check, cargo test --workspace with 249 checks, git diff --check with line-ending notes only, temp browser profile cleanup, and server cleanup passed after adding browser module-plan resource drift proof. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all, cargo test -p tinyrustlm-slm-pack selector:: with 28 tests, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo fmt --all -- --check, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-resource/tinyrustlm all, served-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18698/app/ for multi-parent-sign-merge-q4 proving `/models/multi-parent-sign-merge-q4.module-plan.receipt` was requested before `/models/multi-parent-sign-merge-q4.slm`, cargo test --workspace with 249 checks, git diff --check with line-ending notes only, temp browser profile cleanup, and server/port cleanup passed after adding browser module-plan resource envelopes. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector:: with 27 tests, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan/tinyrustlm all, served-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18696/app/ for multi-parent-sign-merge-q4 proving `/models/multi-parent-sign-merge-q4.module-plan.receipt` was requested before `/models/multi-parent-sign-merge-q4.slm`, cargo test --workspace with 248 checks, git diff --check with line-ending notes only, and server/port cleanup passed after adding browser module-plan receipts. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack adapter_family:: with 3 tests, cargo test -p tinyrustlm-slm-pack selector:: with 25 tests, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-adapter-stack/tinyrustlm all, generated-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18694/app/ for multi-parent-sign-merge-q4 proving two pre-generation apply_adapter_delta calls plus adapter_stack_applied(2), server cleanup, port cleanup, cargo test --workspace with 246 checks, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, and git diff --check with line-ending notes only passed after adding browser adapter-stack self assembly. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, PowerShell parse for tools/vs/Build-TinyRustLM.ps1, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 9 checks, cargo run -p tinyrustlm-slm-pack -- runtime-wasm-manifest tinyrustlm/runtime/tinyrustlm.wasm tinyrustlm/runtime/tinyrustlm.wasm.manifest, tools/vs/Build-TinyRustLM.ps1 -Configuration Debug, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-runtime-manifest/tinyrustlm all, source-root browser-smoke single, source-root browser-smoke runtime-manifest-drift proving no model route after runtime checksum mismatch, generated-root q4 adapter-sidecar-registry-file smoke, temp profile cleanup, port cleanup, and cargo test --workspace with 245 checks passed after adding browser runtime WASM manifest verification. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector:: with 24 tests, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 3 tests, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-sidecar-contract-budget/tinyrustlm all, served-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18690/app/ for multi-parent-sign-merge-q4, static-root browser-smoke sidecar-budget-contract on http://127.0.0.1:18691/app/ proving registry text-budget drift falls back before drifted model fetch, selector-budget regression smoke, multi-parent-registry regression smoke, adapter-sidecar-registry-q8 regression smoke, and cargo test --workspace with 244 checks passed after adding registry-declared browser text-sidecar budget contract fields. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-text-sidecar-budget/tinyrustlm all, served-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18686/app/ for multi-parent-sign-merge-q4, served-root browser-smoke adapter-manifest-budget on http://127.0.0.1:18686/app/ proving oversized generated sparse ASP1 manifest text blocks exact artifact fetch and apply, and cargo test --workspace with 243 checks passed after adding browser text-sidecar byte envelopes. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector:: with 23 tests, cargo test -p tinyrustlm-slm-pack adapter_family:: with 3 tests, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 3 tests, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-auto-assembly-budget/tinyrustlm all, rg verified adapter_auto_apply_byte_budget and adapter_artifact_bytes fields, served-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18684/app/ for multi-parent-sign-merge-q4, q8, and f32 with autoAppliedBeforeGenerate=true, normal-root browser-smoke tinyq4 adapter-sidecar on http://127.0.0.1:18685/app/, cargo test --workspace with 243 checks, git diff --check line-ending-only, temp profile cleanup, and listening-port cleanup passed after adding adapter auto-assembly byte-budget validation before WASM transfer. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector:: with 22 tests, cargo test -p tinyrustlm-slm-pack adapter_family:: with 3 tests, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 3 tests, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-auto-assembly-contract\tinyrustlm all, Select-String verified adapter_auto_apply fields for q4/q8/f32 entries, served-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18682/app/ for multi-parent-sign-merge-q4, q8, and f32 with autoAppliedBeforeGenerate=true, normal-root browser-smoke tinyq4 adapter-sidecar and intercepted tinyq8 adapter-sidecar-registry-q8 on http://127.0.0.1:18683/app/, and cargo test --workspace with 242 checks passed after adding registry-controlled receipt-preferred browser auto assembly. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector:: with 21 tests, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 3 tests, browser-smoke multi-parent-registry and selector-budget on http://127.0.0.1:18680/app/, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-selector-budget-contract\tinyrustlm all, Select-String verified selector_model_byte_budget and model byte fields, served-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18681/app/ for multi-parent-sign-merge-q4, cargo run -p tinyrustlm-browser-harness -- tinyrustlm, cargo test --workspace with 241 checks, git diff --check line-ending-only, temp profile cleanup, and listening-port check passed after adding selector_model_byte_budget as a generated browser registry contract. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, browser-smoke selector-budget on http://127.0.0.1:18679/app/ proving an oversized selector-registry entry was ignored before fetching its model route and tinylm16q8 fallback loaded, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 8 checks, cargo test --workspace with 239 checks, git diff --check line-ending-only, temp profile cleanup, and listening-port check passed after adding browser selector model-byte budget intake. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector with 23 filtered tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 3 filtered tests, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-frugal-selector-default\tinyrustlm all, Select-String verified selector_default_strategy/browser-frugal-quantized plus q4 default fields, served-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18678/app/ for q4, q8, and f32 all observed initialSelectedModel=multi-parent-sign-merge-q4, cargo test --workspace with 239 checks, git diff --check line-ending-only, temp profile cleanup, and listening-port check passed after adding browser frugal selector defaults. - 2026-06-27 cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack browser_bundle with 3 filtered tests, cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-multi-quant-selector\tinyrustlm all, served-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18677/app/ for multi-parent-sign-merge-q4, q8, and f32, cargo test --workspace with 238 checks, node --check tinyrustlm/tools/browser-smoke.js, temp profile cleanup, and listening-port check passed after adding one combined f32/q8_0/q4_0 generated browser selector root. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, node --check tinyrustlm/tools/wasm-abi-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack adapter_family with 6 filtered tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 2 filtered tests, cargo test --workspace with 237 checks, generated f32 and q8_0 browser-multi-parent-bundle staging, served-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18675/app/ and http://127.0.0.1:18676/app/ passed after adding receipt-bound preferred adapter selection; both smokes observed selectedAdapterBeforeApply=2 and applied sparse ASP1 without script-side adapter selection. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, node --check tinyrustlm/tools/wasm-abi-smoke.js, cargo fmt --all -- --check, cargo test --workspace with 237 checks across crates/doc-tests, node tinyrustlm/tools/wasm-abi-smoke.js, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 8 checks, generated f32/q8_0/q4_0 browser-multi-parent-bundle staging with adapter_routes 3, served-root browser-smoke adapter-sidecar-registry-file on http://127.0.0.1:18672/app/ applying Multi-parent sign-merge f32 sparse ASP1, q8_0/q4_0 served-root sparse ASP1 smokes on http://127.0.0.1:18673/app/ and http://127.0.0.1:18674/app/ preserving active quantization after apply, and git diff --check line-ending-only passed after browser sparse adapter route memory updates. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all, cargo test -p tinyrustlm-slm-pack selector with 22 filtered tests, cargo test -p tinyrustlm-slm-pack adapter_family with 6 filtered tests, cargo test -p tinyrustlm-slm-pack browser_bundle with 2 filtered tests, cargo test -p tinyrustlm-slm-pack with 151 tests, cargo build -p tinyrustlm-runtime --release --target wasm32-unknown-unknown, copied rebuilt WASM, generated f32 browser-multi-parent-bundle staging, and served-root browser-smoke adapter-sidecar-registry-file passed after adding generated sparse ASP1 adapter-family routes and applying the sparse ASP1 member in the browser. - 2026-06-27 cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-runtime applies_sparse_adapter_delta with 3 tests, cargo test -p tinyrustlm-slm-pack adapter::tests::writes_and_validates_sparse with 2 tests, cargo test -p tinyrustlm-runtime with 75 tests, cargo test -p tinyrustlm-slm-pack adapter:: with 11 tests, cargo test -p tinyrustlm-slm-pack with 150 tests, and cargo test --workspace with 236 tests passed after adding ASP1 sparse adapter package write/validate and runtime f32/q8_0/q4_0 sparse apply. - 2026-06-27 node --check app.js/browser-smoke.js/wasm-abi-smoke.js, PowerShell parse for tools/vs/Test-TinyRustLM.ps1, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack browser_bundle:: with 2 tests, cargo test -p tinyrustlm-slm-pack with 148 tests, cargo test --workspace with 231 tests, Rust browser harness with 8 checks, WASM ABI smoke, q8_0 and q4_0 browser-multi-parent-bundle staging, q8_0 served-root browser-smoke adapter-sidecar-registry-file, q4_0 served-root browser-smoke adapter-sidecar-registry-file, dependency-section scan, public-copy scan, long-term ledger audit, git diff --check line-ending-only, and post-smoke process checks passed after adding file-backed generated multi-parent q8_0/q4_0 model, assembly receipt, evidence, adapter-family receipt, adapter manifest, family ADP1 routes, and Visual Studio helper staging for quantized generated roots. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-slm-pack selector:: with 17 tests, cargo test -p tinyrustlm-slm-pack adapter_family:: with 3 tests, cargo test -p tinyrustlm-slm-pack with 147 tests, and headless browser-smoke adapter-sidecar-registry-q8 passed after adding f32/q8_0/q4_0 registry adapter route validation and browser quantized-registry adapter apply. - 2026-06-27 cargo fmt --all, cargo test -p tinyrustlm-runtime adapter_delta with 3 tests, cargo test -p tinyrustlm-runtime runtime_q8_adapter_apply_resets_generation_diagnostics, cargo test -p tinyrustlm-slm-pack adapter:: with 9 tests, cargo test -p tinyrustlm-runtime with 72 tests, node --check app.js/browser-smoke.js, rebuilt WASM, node wasm-abi-smoke.js, and headless tinyq8/tinyq4 adapter-sidecar smokes passed after adding f32/q8_0/q4_0 ADP1 runtime adapter apply. - 2026-06-27 cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack population:: with 7 population-review tests, cargo test -p tinyrustlm-slm-pack parent_pool:: with 7 parent-pool tests, cargo test -p tinyrustlm-slm-pack with 145 tests, cargo test --workspace with 223 tests, dependency-section scan, public-copy scan, and git diff --check line-ending-only passed after adding population-review objective-vector metadata and per-entry objective checksums. - 2026-06-27 cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack parent_pool:: with 7 parent-pool tests, cargo test -p tinyrustlm-slm-pack sign_merge:: with 5 sign-merge tests, cargo test -p tinyrustlm-slm-pack multi_candidate:: with 5 multi-parent candidate-manifest tests, cargo test -p tinyrustlm-slm-pack with 144 tests, cargo test --workspace with 222 tests, dependency-section scan, public-copy scan, and git diff --check line-ending-only passed after adding parent-pool relatedness fields, sign-merge receipt echo fields, and multi-parent candidate manifest relatedness propagation. - 2026-06-27 cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack sparse_delta:: with 7 sparse-delta tests, CLI compatibility-lineage-sparse-delta-validate-sparse-delta chain under target/sparse-mask-metadata with density/retention/mask fields present, cargo test -p tinyrustlm-slm-pack with 143 tests, cargo test --workspace with 221 tests, dependency-section scan, and public-copy scan passed after adding sparse task-delta density, nonzero-delta retention, and implicit top-k mask checksum receipt metadata. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 8 checks, cargo test -p tinyrustlm-slm-pack selector with 20 tests, cargo test -p tinyrustlm-slm-pack browser_bundle, cargo test -p tinyrustlm-slm-pack with 142 tests, cargo test --workspace with 220 tests, generated browser-multi-parent-bundle staging, and generated served-root browser-smoke adapter-sidecar-registry-file passed after adding registry-carried assembly receipt fields, generated .assembly.receipt output, Assembly Evidence UI rendering, and network-trace assertions for /models/multi-parent-sign-merge-f32.assembly.receipt plus all nine referenced /evidence/multi-parent-sign-merge-f32/ files. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack adapter_family with 5 filtered tests, cargo test -p tinyrustlm-slm-pack selector with 19 tests, cargo test -p tinyrustlm-slm-pack browser_bundle, cargo test -p tinyrustlm-slm-pack with 141 tests, cargo test --workspace with 219 tests, browser-smoke adapter-sidecar, browser-smoke adapter-sidecar-checksum-mismatch, and self-contained generated-root browser-smoke adapter-sidecar-registry-file passed after adding selected ADP1 artifact checksum verification and making browser-multi-parent-bundle copy app shell plus WASM runtime. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack adapter_family with 5 filtered tests, cargo test -p tinyrustlm-slm-pack selector with 19 tests, cargo test -p tinyrustlm-slm-pack browser_bundle, cargo test -p tinyrustlm-slm-pack with 141 tests, cargo test --workspace with 219 tests, and generated served-root browser-smoke adapter-sidecar-registry-file passed after adding browser-side adapter manifest fetch, checksum verification, member identity matching, and network-trace assertions for both generated .adp1.manifest routes. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack adapter_family with 5 filtered tests, cargo test -p tinyrustlm-slm-pack selector with 19 tests, cargo test -p tinyrustlm-slm-pack browser_bundle, cargo test -p tinyrustlm-slm-pack with 141 tests, cargo test --workspace with 219 tests, and generated served-root browser-smoke adapter-sidecar-registry-file passed after adding browser-side adapter-family receipt fetch, checksum verification, member matching, and network-trace assertion for /models/multi-parent-sign-merge-f32.adapter-family.receipt. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack adapter_family with 5 filtered tests, cargo test -p tinyrustlm-slm-pack selector with 19 tests, cargo test -p tinyrustlm-slm-pack browser_bundle, cargo test -p tinyrustlm-slm-pack with 141 tests, cargo test --workspace with 219 tests, and generated served-root browser-smoke adapter-sidecar-registry-file passed after adding adapter-family receipt routing and browser selector receipt metadata parsing. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector with 17 tests, cargo test -p tinyrustlm-slm-pack browser_bundle, cargo test -p tinyrustlm-slm-pack with 137 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 8 checks, node tinyrustlm/tools/wasm-abi-smoke.js, cargo test --workspace with 215 tests, and generated served-root browser-smoke adapter-sidecar-registry-file passed after adding indexed registry-carried f32/q8_0/q4_0 adapter routes. - 2026-06-27 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, PowerShell parse for tools/vs/Test-TinyRustLM.ps1, cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack adapter with 9 tests, cargo test -p tinyrustlm-runtime adapter with 4 tests, cargo test -p tinyrustlm-browser-harness with 6 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm with 8 checks, node tinyrustlm/tools/wasm-abi-smoke.js, focused headless browser-smoke adapter-sidecar on http://127.0.0.1:18510/app/, and cargo test --workspace with 211 tests passed after adding the browser Adapter Sidecar route. - 2026-06-27 cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-runtime adapter with 4 focused adapter tests, node --check tinyrustlm/tools/wasm-abi-smoke.js, cargo build -p tinyrustlm-runtime --release --target wasm32-unknown-unknown, copied rebuilt WASM, node tinyrustlm/tools/wasm-abi-smoke.js, and cargo test --workspace with 211 tests passed after adding the original f32 ADP1 adapter apply plus WASM apply_adapter_delta smoke; superseded by f32/q8_0/q4_0 adapter apply coverage. - 2026-06-27 PowerShell parse, node --check tinyrustlm/tools/browser-smoke.js, cargo test -p tinyrustlm-slm-pack browser_bundle, live file-backed browser-smoke multi-parent-registry-file, cargo fmt checks, cargo test --workspace with 207 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm, full tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke, public-copy scan, dependency-section scan, and git diff --check line-ending-only passed after adding browser-multi-parent-bundle and generated served multi-parent artifact routing. - 2026-06-27 node --check tinyrustlm/tools/browser-smoke.js, tools/vs/Test-TinyRustLM.ps1 parse check, focused headless browser-smoke multi-parent-registry, cargo fmt --all -- --check, cargo run -p tinyrustlm-browser-harness -- tinyrustlm, cargo test --workspace with 206 tests, public-copy scan, dependency-section scan, and git diff --check line-ending-only passed after adding browser-served multi-parent selector-registry fixture routing. - 2026-06-27 cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack selector:: with 9 selector-registry tests, cargo test -p tinyrustlm-slm-pack with 132 tests, cargo test --workspace with 206 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, dependency-section scan, and git diff --check line-ending-only passed after adding multi-parent selector-registry intake. - 2026-06-27 cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack multi_admission:: with 6 multi-parent admission-record tests, cargo test -p tinyrustlm-slm-pack multi_promotion:: with 5 multi-parent promotion-template tests, cargo test -p tinyrustlm-slm-pack with 129 tests, cargo test --workspace with 203 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, dependency-section scan, and git diff --check line-ending-only passed after adding multi-parent-admission-record and validate-multi-parent-admission. - 2026-06-27 cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack multi_promotion:: with 5 multi-parent promotion-template tests, cargo test -p tinyrustlm-slm-pack multi_candidate:: with 5 multi-parent candidate-manifest tests, cargo test -p tinyrustlm-slm-pack with 123 tests, cargo test --workspace with 197 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, dependency-section scan, and git diff --check line-ending-only passed after adding multi-parent-promotion-template and validate-multi-parent-promotion. - 2026-06-27 cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack multi_candidate:: with 5 multi-parent candidate-manifest tests, cargo test -p tinyrustlm-slm-pack sign_merge:: with 5 sign-merge tests, cargo test -p tinyrustlm-slm-pack with 118 tests, cargo test --workspace with 192 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, dependency-section scan, and git diff --check line-ending-only passed after adding multi-parent-candidate-manifest and validate-multi-parent-candidate. - 2026-06-27 cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack sign_merge:: with 5 sign-merge tests, cargo test -p tinyrustlm-slm-pack with 113 tests, cargo test --workspace with 187 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, public-copy scan, and git diff --check line-ending-only passed after adding sign-merge-candidate and validate-sign-merge-candidate. - 2026-06-27 cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack parent_pool:: with 6 parent-pool recipe tests, cargo test -p tinyrustlm-slm-pack with 108 tests, cargo test --workspace with 182 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, CLI promotion-ledger-population-review-parent-pool-recipe-validate-parent-pool-recipe chain, dependency-section scan, public-copy scan, and git diff --check line-ending-only passed after adding parent-pool-recipe and validate-parent-pool-recipe. - 2026-06-27 cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack population:: with 6 population-review tests, cargo test -p tinyrustlm-slm-pack with 102 tests, cargo test --workspace with 176 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, CLI promotion-ledger-population-review-validate-population-review chain, dependency-section scan, public-copy scan, and git diff --check line-ending-only passed after adding population-review and validate-population-review. - 2026-06-27 cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack sparse_delta:: with 6 sparse-delta tests, cargo test -p tinyrustlm-slm-pack with 96 tests, cargo test --workspace with 170 tests, strict slm_pack rustdoc, cargo build -p tinyrustlm-slm-pack, CLI q8 compatibility-lineage-sparse-delta-validate-sparse-delta-candidate-manifest-validate-candidate chain, dependency-section scan, public-copy scan, and git diff --check line-ending-only passed after adding sparse-delta-candidate and validate-sparse-delta-candidate. - 2026-06-27 cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack adapter:: with 9 adapter tests, cargo test -p tinyrustlm-slm-pack with 90 tests, cargo test --workspace with 164 tests, strict slm_pack rustdoc, CLI compatibility-lineage-adapter-write-validate-fuse-validate chain, dependency-section scan, public-copy scan, git diff --check line-ending-only, and cargo build -p tinyrustlm-slm-pack passed after adding fuse-adapter-delta and validate-fuse-adapter-delta. - 2026-06-27 cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack with 86 tests, cargo test --workspace with 160 tests, strict slm_pack rustdoc, CLI q8 compatibility-lineage-adapter-write-validate chain, dependency-section scan, public-doc taboo scan, and git diff --check line-ending-only passed after adding adapter-delta and validate-adapter-delta. - 2026-06-27 cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack with 81 tests, cargo test --workspace with 155 tests, strict slm_pack rustdoc, CLI q8 compatibility-lineage-delta-validate-delta-validate-candidate chain, CLI invalid delta weight refusal, dependency-section scan, public-doc taboo scan, and git diff --check line-ending-only passed after adding delta-candidate and validate-delta-candidate. - 2026-06-27 cargo fmt --all, cargo fmt --all -- --check, cargo test -p tinyrustlm-slm-pack with 76 tests, cargo test --workspace with 150 tests, strict slm_pack rustdoc, CLI converted-trained q8 compatibility-lineage-candidate-promotion-runtime-eval-admission-ledger chain, CLI promotion-ledger drift refusal, dependency-section scan, public-doc taboo scan, and git diff --check line-ending-only passed after adding promotion-ledger and validate-promotion-ledger. - 2026-06-25 node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, cargo test --workspace with 102 tests, cargo run -p tinyrustlm-browser-harness -- tinyrustlm, focused browser-smoke step-token, and tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke -BrowserSmokePort 18460 -PortSearchLimit 5 passed after adding the browser Step Token control. - 2026-06-25 cargo fmt --all -- --check, cargo test --workspace, strict rustdoc gates, WASM rebuild/copy, WASM ABI smoke, Rust browser harness, and tools/vs/Test-TinyRustLM.ps1 passed after output-buffer hardening; workspace coverage is 102 tests with 63 runtime tests. - 2026-06-25 cargo fmt --all -- --check, node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, node --check tinyrustlm/tools/wasm-abi-smoke.js, and tools/vs/Test-TinyRustLM.ps1 parse check passed after tied-output trained-source conversion work. - 2026-06-25 cargo test -p tinyrustlm-slm-pack trained_source -- --nocapture passed with 8 tests, including tied source manifest validation, tied_output/model_shape disagreement rejection, and f32/q8_0/q4_0 tied conversion manifest validation. - 2026-06-25 cargo test --workspace passed with 99 tests after tied-output trained-source conversion coverage: 6 browser-harness tests, 5 local-server tests, 60 runtime tests, and 28 slm_pack tests. - 2026-06-25 cargo run -p tinyrustlm-browser-harness -- tinyrustlm passed with 8 static app contract checks. - 2026-06-25 tools/vs/Test-TinyRustLM.ps1 passed after tied-output trained-source conversion; it rebuilt WASM, ran 99 Cargo tests, strict rustdoc gates, static browser harness, all eight model/manifest checks, untied converted-source eval gates, tied f32/q8_0/q4_0 runtime-smoke gates, and WASM ABI smoke. - cargo fmt --all -- --check, node --check tinyrustlm/app/app.js, and node --check tinyrustlm/tools/browser-smoke.js passed after tied-output docs and route guidance updates. - cargo run -p tinyrustlm-browser-harness -- tinyrustlm passed with 8 checks, including the tied-output model route and manifest contract. - Superseded by the 99-test tied-source conversion run: cargo test --workspace previously passed with 96 tests after artifact-backed tied-output fixture coverage. - tools/vs/Test-TinyRustLM.ps1 passed after tied-output fixture promotion; it rebuilt WASM, ran 96 Cargo tests, strict rustdoc gates, static browser harness, all eight model/manifest checks, converted-source gates, fixture-scoped eval gates, and WASM ABI smoke. - Superseded by the 96-test tied-output fixture run: cargo test --workspace previously passed with 92 tests total after model tensor routing hardening. - tools/vs/Test-TinyRustLM.ps1 passed after tensor index routing hardening; it rebuilt WASM, ran 92 Cargo tests, strict rustdoc gates, Rust browser-harness static contract, all model/manifest checks, converted-source gates, fixture-scoped eval gates, and WASM ABI step/free smoke. - cargo fmt --all -- --check passed after transcript edits. - cargo run -p tinyrustlm-browser-harness -- tinyrustlm passed after adding clearChatButton and conversation to the required static UI contract. - cargo fmt --all passed. - cargo build --workspace passed after adding tinyrustlm-local-server. - cargo test --workspace passed with 90 tests total after core math coverage growth; this evidence is superseded by the current 92-test model tensor routing run. - tools/vs/Build-TinyRustLM.ps1 -Configuration Debug passed. - tools/vs/Test-TinyRustLM.ps1 passed with Cargo tests, JS syntax checks, strict rustdoc missing_docs gates, WASM release build, Rust browser-harness static contract, model/manifest gates, converted-source gates, reusable generation buffer tests, and WASM ABI step/free smoke. - tools/vs/Test-TinyRustLM.ps1 validates all eight local .slm artifacts, their .slm.manifest sidecars, the tiny trained-source fixture, converted-trained f32/q8_0/q4_0 outputs, converted manifests, runtime-smoke gates, fixture-scoped assistant-quality eval gates, and WASM ABI step/free smoke. - cargo test -p tinyrustlm-runtime runtime_generates_from_tiny_bpe_fixture passed, proving prompt the becomes tokenizer_output 256,261 before generation. - cargo test -p tinyrustlm-runtime runtime_accepts_stochastic_bpe_top_k_above_byte_vocab passed, proving BPE top_k 262 through runtime generation. - cargo test -p tinyrustlm-runtime stochastic_sampler_accepts_bpe_vocab_above_byte_tokenizer_size passed, proving sampler selection beyond the byte-tokenizer vocabulary size. - cargo test -p tinyrustlm-slm-pack bpe passed, proving BPE writer and validator coverage. - cargo fmt --all -- --check passed after strict public Rust documentation gate wiring. - cargo rustdoc -p tinyrustlm-runtime --lib -- -D missing_docs passed. - cargo rustdoc -p tinyrustlm-slm-pack --bin tinyrustlm-slm-pack -- -D missing_docs passed. - cargo rustdoc -p tinyrustlm-local-server --bin tinyrustlm-local-server -- -D missing_docs passed. - cargo rustdoc -p tinyrustlm-browser-harness --bin tinyrustlm-browser-harness -- -D missing_docs passed. - cargo test -p tinyrustlm-runtime sampler::tests passed with fixed-buffer stochastic candidate cap coverage and top_k cap rejection. - cargo test -p tinyrustlm-runtime runtime_accepts_last_prompt_slot_and_rejects_full_context_prompt passed with last-prompt-slot acceptance, full-context rejection, empty failed token state, and zero cache length. - cargo test -p tinyrustlm-runtime runtime_generate_next_token_continues_current_context passed with token state ending on the generated token before step continuation. - tools/vs/Test-TinyRustLM.ps1 passed after assistant-quality case-ledger hardening; it rebuilt WASM, ran 78 Cargo tests, strict rustdoc gates, static browser harness, all model/manifest checks, converted-source gates, fixture-scoped eval gates, and WASM ABI smoke. - tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke -BrowserSmokePort 8094 -PortSearchLimit 10 passed after quantized decoded-shadow removal, including q8, q4, loop, malformed model, context-overflow, missing-model, endurance, performance browser smokes, and desktop/mobile UI audit. - tools/vs/Run-TinyRustLM.ps1 parse check passed after identity-aware port selection edits. - tools/vs/Test-TinyRustLM.ps1 parse check passed after BrowserSmokePort and PortSearchLimit edits. - tools/vs/Test-TinyRustLM.ps1 parse check passed after PerformanceSoak parameters were added. - Focused Run-TinyRustLM busy-port fallback passed from unrelated occupied 18180 to free 18181. - Focused Run-TinyRustLM verified-server reuse passed on 18182 without starting a second server. - Focused tools/vs/Test-TinyRustLM.ps1 -PerformanceSoak -PerformanceSoakCycles 1 -PerformanceSoakTokens 1 -BrowserSmokePort 18291 -PortSearchLimit 5 passed through Rust local-server startup; the browser harness clamps soak minimums to two cycles and two tokens, then completed with only a temporary profile cleanup notice. - cargo run -p tinyrustlm-browser-harness -- tinyrustlm passed the static app contract with 8 checks, including Rust WASM export-definition crawl. - cargo run -p tinyrustlm-browser-harness -- tinyrustlm --http http://127.0.0.1:18315/app/ passed the loopback route/content-type contract with 8 checks against the Rust local server. - tools/vs/Test-TinyRustLM.ps1 -PerformanceSoak -PerformanceSoakCycles 2 -PerformanceSoakTokens 2 -BrowserSmokePort 18320 -PortSearchLimit 5 passed after Rust browser harness integration; it exercised the default static harness and server-backed --http harness path, then completed with only a temporary profile cleanup notice. - tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke -BrowserSmokePort 18340 -PortSearchLimit 5 passed after local transcript UI work, including q8/q4 transcript assertions and desktop/mobile ui-audit Clear-button state; only temporary Chrome profile cleanup notices remained. - node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18350/app/ 9240 tinylm16q8 ui-audit passed after adding the Clear-click cleared transcript snapshot. pending_build_artifact_checks: - none_for_current_source_slice completed_build_artifact_checks: - Crossover operator verification passed: focused crossover tests covered seed changes, parent0 keep zero/full/partial/default behavior, invalid seed/keep parsing, q8 candidate validation, path-level write/validate, parent checksum drift, and candidate drift; full slm_pack suite passed with 241 tests; CLI smoke wrote and validated a crossover candidate under target/crossover-cli. - cargo run -p tinyrustlm-slm-pack -- validate tinyrustlm/models/tiny-test-model-tied.slm passed with 11 tensors, 2744 parameters, f32 quantization, and checksum 0x7d62cfbfde480fed. - cargo run -p tinyrustlm-slm-pack -- validate-manifest tinyrustlm/models/tiny-test-model-tied.slm tinyrustlm/models/tiny-test-model-tied.slm.manifest passed with source_kind deterministic-smoke. - cargo build -p tinyrustlm-runtime --release --target wasm32-unknown-unknown passed. - copied target/wasm32-unknown-unknown/release/tinyrustlm_runtime.wasm to tinyrustlm/runtime/tinyrustlm.wasm. - current tinyrustlm/runtime/tinyrustlm.wasm sha256 is 2948DAF23FECD6560A732A4F08A92A3885D89BD52FF1F3A3E6C54A3E699CAA12 after runtime adapter apply. - cargo run -p tinyrustlm-slm-pack -- tinyrustlm/models/tiny-test-model.slm tiny-fixture passed. - cargo run -p tinyrustlm-slm-pack -- tinyrustlm/models/tiny-test-model-q8.slm tiny-fixture-q8 passed. - cargo run -p tinyrustlm-slm-pack -- tinyrustlm/models/tiny-test-model-q4.slm tiny-fixture-q4 passed. - cargo run -p tinyrustlm-slm-pack -- tinyrustlm/models/tiny-test-model-bpe.slm tiny-fixture-bpe passed. - cargo run -p tinyrustlm-slm-pack -- tinyrustlm/models/tinylm16-f32.slm tinylm16-f32 passed. - cargo run -p tinyrustlm-slm-pack -- tinyrustlm/models/tinylm16-q8.slm tinylm16-q8 passed. - cargo run -p tinyrustlm-slm-pack -- tinyrustlm/models/tinylm16-q4.slm tinylm16-q4 passed. - The eight .slm artifacts carry nonzero checksums after packer/runtime checksum enforcement. - tinyrustlm-slm-pack validate passed for tiny-test-model.slm, tiny-test-model-tied.slm, tiny-test-model-q8.slm, tiny-test-model-q4.slm, tiny-test-model-bpe.slm, tinylm16-f32.slm, tinylm16-q8.slm, and tinylm16-q4.slm. - tinyrustlm-slm-pack manifest generated deterministic-smoke sidecars for all eight current .slm artifacts. - tinyrustlm-slm-pack validate-manifest passed for all eight current .slm.manifest sidecars. - Manifest unit tests passed for generated fixture round-trip, checksum mismatch rejection, and converted-trained quality-overclaim rejection. - Quality-gate unit tests passed for runtime-smoke admission, deterministic-smoke assistant-quality rejection, converted-trained assistant-quality rejection without eval evidence, pending eval template rejection, and converted-trained passed-eval admission. - CLI quality-gate smoke passed for tinylm16-q8 runtime-smoke. - CLI eval-template smoke generated a pending assistant-quality sidecar for a converted-trained tiny fixture manifest, then quality-gate rejected that pending template as expected. - CLI source-template generated tinyrustlm/tests/fixtures/trained-source-tiny. - CLI validate-source passed for tinyrustlm/tests/fixtures/trained-source-tiny. - CLI convert-trained emitted target/trained-source-smoke/tiny-converted-f32.slm, tiny-converted-q8.slm, and tiny-converted-q4.slm plus matching converted-trained manifests from the source fixture. - CLI quality-gate runtime-smoke passed for converted-trained f32, q8_0, and q4_0 fixture artifacts. - CLI tinyrustlm-eval passed the scoped fixture cases for converted-trained f32, q8_0, and q4_0 artifacts. - CLI quality-gate assistant-quality passed only for the declared tiny-converted-source-fixture-only scope for converted-trained f32, q8_0, and q4_0 artifacts. - Build-TinyRustLM.ps1 -RegenerateModels includes all eight .slm artifacts plus deterministic-smoke sidecars, including tiny-test-model-bpe.slm and tiny-test-model-tied.slm. - Node WASM smoke test instantiated WASM, loaded f32/q8_0/q4_0 tiny fixtures, generated eeeeeeeeeeeee through the tiny transformer path, and read diagnostics with code 0 for each fixture. - Node WASM smoke test instantiated WASM, loaded tinylm16-f32.slm, generated e from prompt hi with max_new_tokens 1, and read diagnostics with code 0. - Node WASM smoke test instantiated WASM, loaded tinylm16-q8.slm, generated e from prompt hi with max_new_tokens 1, and read q8_0 diagnostics with code 0. - Node WASM smoke test instantiated WASM, loaded tinylm16-q4.slm, generated e from prompt hi with max_new_tokens 1, and read q4_0 diagnostics with code 0. - Headless Chrome browser smoke loaded http://127.0.0.1:8080/app/, defaulted to TinyLM-16M q8_0, clicked Generate, displayed e, rendered diagnostics plus benchmark fields, and appended User hi plus TinyRustLM e transcript entries. - Headless Chrome browser smoke loaded http://127.0.0.1:8080/app/, selected TinyLM-16M q4_0, clicked Generate, displayed e, rendered diagnostics plus benchmark fields, and appended User hi plus TinyRustLM e transcript entries. - Headless Chrome browser loop smoke reloaded the app, verified clean q8_0 ready diagnostics, generated q8 twice around reset, switched to q4_0 with clean ready diagnostics, generated q4 twice around reset, and observed only local-origin HTTP requests. - Headless Chrome browser model-error smoke intercepted the local q8 model route with malformed .slm bytes, rendered Model rejected, surfaced invalid model magic, kept Generate/Reset disabled, kept model selection recoverable, recorded diagnostics model_loaded false, and observed only local-origin HTTP requests. - Headless Chrome browser context-error smoke submitted an over-context prompt, rendered context exceeded, kept the runtime ready with controls enabled, recorded ContextExceeded diagnostics without generated tokens, and observed only local-origin HTTP requests. - Headless Chrome browser missing-model smoke returned a local 404 for tinylm16-q8.slm, rendered Model load failed, surfaced Unable to fetch local .slm model (404), kept Generate/Reset disabled, kept model selection recoverable, recorded diagnostics model_loaded false, and observed only local-origin HTTP requests. - Headless Chrome browser endurance smoke completed three q8/q4 ready-generate-reset cycles, preserved clean diagnostics after resets, generated deterministic e responses, and observed only local-origin HTTP requests. - Headless Chrome browser performance smoke generated four q8_0 tokens and four q4_0 tokens through the UI, verified benchmark prompt/generated counts, host-side token speed, 47,104 scratch bytes, quantization mode, KV cache length, reset recovery, and local-only HTTP requests. - Headless Chrome browser performance-soak mode completed repeated q8_0 and q4_0 four-token UI generations, verified each cycle's benchmark counts, positive host-side token speed, scratch bytes, KV length, deterministic eeee output, reset recovery, and local-only HTTP requests. - Headless Chrome browser ui-audit mode passed for fresh desktop and mobile viewports, verifying product shell identity, local-only notice, footer, required panels, labels, model options, Model Provenance panel, empty/generated/cleared conversation transcript, Clear-button state, response preservation after Clear, no horizontal overflow, q8_0 generation, diagnostics/developer mirror, benchmark fields, and local-only HTTP requests. - Headless Chrome browser multi-parent-registry mode passed against http://127.0.0.1:8080/app/ with selectedModel multi-parent-sign-merge-q8, one registry option, q8_0 diagnostics, selector.registry request, tinylm16-q8.slm request, manifest request, response e, and local-only routes. - Headless Chrome browser multi-parent-registry-file mode passed against a generated browser-multi-parent-bundle root with selectedModel multi-parent-sign-merge-f32, one registry option, f32 diagnostics, selector.registry request, multi-parent-sign-merge-f32.slm request, manifest request, response e, and local-only routes. - Headless Chrome browser adapter-sidecar mode passed against http://127.0.0.1:18510/app/ with selectedModel tinyf32, local tiny-test-model-self.adp1 request, response adapter applied, f32 diagnostics, generated_token_count 0, kv_cache_length 0, selected_next_token 0, and local-only routes. - Headless Chrome browser adapter-sidecar-registry-file mode passed against http://127.0.0.1:18631/app/ with selectedModel multi-parent-sign-merge-f32, selector.registry request, multi-parent-sign-merge-f32.slm and .slm.manifest requests, multi-parent-sign-merge-f32.adapter-family.receipt request, both generated .adp1.manifest requests, multi-parent-sign-merge-f32-family.adp1 request, response adapter applied, f32 diagnostics, and local-only routes. - Focused 2026-06-25 provenance-panel check passed: node --check tinyrustlm/app/app.js, node --check tinyrustlm/tools/browser-smoke.js, cargo fmt --all -- --check, and browser-smoke ui-audit against http://127.0.0.1:8080/app/ with same-origin `.slm.manifest` fetch. - Focused Visual Studio performance soak passed with two q8/q4 cycles and four generated tokens per run. - Full Visual Studio BrowserSmoke plus PerformanceSoak passed with three q8/q4 performance-soak cycles after the regular q8, q4, loop, malformed model, context-overflow, missing-model, endurance, performance, and desktop/mobile UI-audit smokes. - Full Visual Studio BrowserSmoke plus PerformanceSoak passed again after checksum-bearing model regeneration, before the UI-audit gate was added. - Visual Studio BrowserSmoke reused an existing verified TinyRustLM server at http://127.0.0.1:8080/app/ after port-selection hardening. - Current Visual Studio BrowserSmoke performance evidence after decoded-shadow removal: q8_0 generated `eeee` at 29.197 tok/s host-side, q4_0 generated `eeee` at 14.706 tok/s host-side, both with 47,104 scratch bytes and clean reset diagnostics. - WASM ABI smoke loaded tinyrustlm/runtime/tinyrustlm.wasm and tinyrustlm/models/tinylm16-q8.slm, rejected invalid UTF-8 prompt bytes with code 3, rejected null prompt pointer with code 1, rejected invalid lengths with code 2, rejected invalid sampling, recovered with response e plus q8_0 diagnostics, stepped one token through generate_next_token with ErrorCode Ok/result e/generated count 2/KV length 5, reloaded tiny f32, validated a zero-delta ADP1 package through validate_adapter_delta with result adapter validated, applied the same package through apply_adapter_delta with result adapter applied, freed the model, and rejected post-free generate_next_token with ModelNotLoaded. - Full Visual Studio BrowserSmoke passed after diagnostics JSON escaping hardening, proving browser diagnostics still parse across q8/q4 generation, model errors, context overflow, missing-model, endurance, and performance checks. - Targeted current browser smoke loaded http://127.0.0.1:8080/app/, defaulted to TinyLM-16M q8_0, generated e, rendered benchmark fields, and reported selected_next_token 101. - Improvement report intake processed 23 reports into raw evidence and distributed long-term report memory, then cleared the active source bucket. - localhost static server served /app/, /runtime/tinyrustlm.wasm, /models/tiny-test-model.slm, /models/tiny-test-model-q8.slm, /models/tiny-test-model-q4.slm, /models/tinylm16-f32.slm, /models/tinylm16-q8.slm, /models/tinylm16-q4.slm, and /app/app.js with HTTP/HEAD 200. - Rust local server direct HTTP smoke passed for /app/, /runtime/tinyrustlm.wasm, /models/tinylm16-q8.slm, and /models/tinylm16-q8.slm.manifest on port 18280. - Run-TinyRustLM.ps1 -NoBuild -NoBrowser verified-server reuse passed against a Rust-hosted TinyRustLM server on port 18282. required_rust_tests: - selector registry validation preserves federated operator receipt fields from receipt-bound admission to browser entry - selector registry validation rejects federated operator receipt kind drift before browser entry evidence is accepted - selector registry validation preserves DARE operator receipt fields from receipt-bound admission to browser entry - selector registry validation rejects DARE operator receipt kind drift before browser entry evidence is accepted - browser multi-parent-registry smoke renders federated operator receipt metadata in Model Provenance Operator - browser dare-operator-registry smoke renders DARE operator receipt metadata in Model Provenance Operator - browser dare-operator-receipt-drift smoke rejects drifted DARE operator receipt candidate byte count before the generated route becomes selectable and preserves static q8 fallback generation - browser selector-operator-receipt-drift smoke rejects drifted operator receipt candidate byte count before the generated route becomes selectable and preserves static q8 fallback generation - byte tokenizer round-trip - UTF-8 prompt handling - byte and BPE bounded decode reject over-limit result text before replacing caller output - TensorView and MutableTensorView shape validation and row-major flat indexing - dot known output and shape mismatch rejection - RMSNorm known vector - softmax sum approximately 1.0 - softmax empty slice rejection - matvec known output - matvec shape mismatch rejection - matmul known output and shape mismatch rejection - SiLU known values - SwiGLU known output and shape mismatch rejection - q8 dequant known output - q4 dequant known output - q4 direct matvec uses block scales - RoPE known small vector - KV cache append/read - .slm header parse - .slm checksum mismatch rejection - native .slm admission validator accepts generated fixtures - native .slm admission validator rejects non-finite f32 payload values - .slm provenance manifest validation accepts generated fixture sidecars - .slm provenance manifest validation rejects checksum drift - .slm provenance manifest validation rejects trained-quality overclaims - .slm quality gate accepts runtime-smoke evidence for existing manifests - .slm quality gate rejects deterministic-smoke assistant-quality claims - .slm quality gate rejects converted-trained assistant-quality claims without evaluation evidence - .slm quality gate rejects pending assistant-quality eval templates - .slm quality gate accepts converted-trained assistant-quality claims only with passed task-eval evidence and declared quality scope - .slm quality gate rejects assistant-quality sidecars without case totals or with mismatched per-case actual text - trained-source validator accepts generated raw-f32 source fixture - trained-source converter builds f32, q8_0, and q4_0 .slm artifacts with converted-trained manifests - tied trained-source validator accepts generated tiny-fixture-tied source fixture without output.weight - tied trained-source converter builds f32, q8_0, and q4_0 .slm artifacts with the v1 tied-output flag and converted-trained manifests - trained-source validator rejects source checksum drift - trained-source validator rejects unsafe tensor path traversal - trained-source validator rejects non-finite source weights even when source checksum is refreshed - invalid magic rejection - missing tensor rejection - greedy sampler deterministic selection - stochastic sampler selects from a fixed 1024-candidate buffer, accepts BPE top_k 262, and rejects top_k above the fixed cap - generation stops on EOS - tiny fixture forward path generates deterministic local output - q8_0 tiny fixture forward path generates deterministic local output and reports q8_0 diagnostics - q8_0 named model matvec matches caller-owned copied reference output - q4_0 tiny fixture forward path generates deterministic local output and reports q4_0 diagnostics - q8_0/q4_0 tensors reject borrowed f32 slices and require explicit copy buffers for decoded reference paths - model loading exposes pre-resolved top-level and per-layer tensor indices - tied-output projection flags route output projection to tok_embeddings - tied-output fixture validates without output.weight only when the v1 tied-output flag is set - missing output.weight without the tied-output flag is rejected - tiny tied-output fixture runtime generation succeeds through tok_embeddings projection - custom BPE tiny fixture loads from .slm and records merged tokenizer output 256,261 for prompt the before generation - generation scratch and logits buffers are allocated on model load and reused across generate plus repeated generate_next_token calls - generate request state clears prompt/cache diagnostics before errors can preserve stale counts, and successful generation extends token state for step-token continuation - generated result output buffer overflow returns OutputBufferExceeded and clears full-generate stale token/generated-token diagnostics - eval-case files reject zero case_count, empty exact prompt/output fields, and stray case keys outside declared case_count - top-k diagnostic summary selects candidates without allocating a vocab-sized vector - generate_next_token returns ErrorCode Ok on success, writes decoded token text to last_result, and records selected token id in diagnostics - free_model clears model-loaded diagnostics and makes later generation fail with ModelNotLoaded - runtime f32/q8_0/q4_0 ADP1, ASP1, or ALR1 adapter apply mutates or re-quantizes loaded tensors after identity, checksum, payload, sparse index, low-rank shape, and finite-value validation - browser runtime WASM manifest validates byte count and checksum before WebAssembly instantiation, and runtime-manifest-drift smoke stops before model fetch - runtime adapter identity, payload, and fused-value failures reject without mutating tensors - q8_0/q4_0 runtime adapter apply keeps compact tensors compact and rejects identity or checksum drift without mutation - Runtime::apply_adapter_delta clears generation tokens, KV cache, and generation diagnostics after success - Runtime::validate_adapter_delta preserves generation tokens, KV cache, and diagnostics while checking the same adapter package and tensor payload contract as apply - Runtime diagnostics report assembly state: model load seeds a nonzero `assembly_state_checksum` with `adapter_apply_count=0`, accepted adapter apply increments `adapter_apply_count` and records nonzero adapter/assembly checksums, validation preserves apply count, and free or load failure clears the fields - TinyLM-16M f32 smoke path generates deterministic local output and reports f32 diagnostics - TinyLM-16M q8_0 smoke path generates deterministic local output and reports q8_0 diagnostics - TinyLM-16M q4_0 smoke path generates deterministic local output and reports q4_0 diagnostics - model reload resets generation diagnostics before model-specific generation resumes - diagnostics JSON escapes quotes, backslashes, control characters, line separators, and paragraph separators before browser parsing - Visual Studio wrapper build/test scripts continue to pass - parent-pool recipe validation recomputes population review objective-vector fields, shared direct-parameter contract fields, parent roles, and seed weights before recipe consumers - crossover candidate validation recomputes parent compatibility checks, lineage, seed and parent0 keep parameters, selected-count density fields, mask checksum, candidate bytes, and receipt text before downstream candidate manifests - federated candidate validation recomputes parent compatibility checks, lineage, base/local-update parent roles, local_update_weight_ppm, local-update counts, raw and weighted delta checksums, candidate bytes, and receipt text before downstream candidate manifests - sign-merge validation recomputes parent-pool recipe validation, parent artifact checks, seed-weighted sign consensus, candidate bytes, and receipt text before multi-parent candidate manifests - multi-parent candidate-manifest validation recomputes sign-merge receipt validation, receipt checksum, parent-pool recipe checksum, parent summaries, candidate .slm fields, pending eval status, and next promotion route before runtime-smoke/eval/admission work - multi-parent promotion validation recomputes multi-parent candidate manifest validation, candidate manifest checksum, operator receipt checksum, parent-pool recipe checksum, parent count, candidate .slm fields, pending runtime-smoke/eval status, and not-admitted selector state before runtime-smoke/eval/admission work - public Rust API documentation must pass strict missing_docs rustdoc gates for runtime and all tool binaries - Rust local server unit tests cover request-line parsing, directory index resolution, traversal rejection, percent decoding, and WASM content type - Rust mini browser harness unit tests cover loopback URL parsing, remote URL rejection, manifest parsing, HTTP response parsing, and remote marker rejection - browser transcript smokes cover empty ready state, generated User/TinyRustLM entries, Clear-click removal, response preservation after Clear, Clear-button state, and DOM-safe text rendering expectations - browser Step Token smoke covers disabled-before-context state, enabled-after-generate state, hi -> e -> ee continuation, transcript assistant-turn extension, console logging, generated_token_count 2, KV cache length 5, and local-only requests - browser Adapter Sidecar smoke covers tiny f32/q8_0/q4_0 model selection, one-token generation, local .adp1 fetch, apply_adapter_delta call, adapter applied response, matching quantization diagnostics, cleared generated token and KV state, disabled Step Token after apply, and local-only requests - browser adapter-sidecar-registry-file smoke covers generated f32/q8_0/q4_0 selector entries, receipt-declared ADP1 plus ASP1 plus ALR1 auto assembly before generation, reset diagnostics before generation, one-token generation after assembly, active quantization preservation, assembly evidence, adapter-family receipts, adapter manifests, and local-only requests - browser runtime assembly diagnostics smoke covers checked manual sidecar count 1, generated q4_0/q8_0/f32 auto-stack count 3, nonzero last adapter checksums, nonzero assembly checksums before generation, and zero assembly state after free - browser module-plan smoke covers generated selector `module_plan_*` fields, served `.module-plan.receipt` checksum verification before generated `.slm` fetch, tokenizer checksum identity, resource class plus model/adapter/runtime-scratch byte budgets, pre-init WASM memory page count, adapter validation strategy, adapter validation count, adapter apply count, byte-count matching for fetched model/text sidecars/adapter-stack artifacts, checksum matching for stack artifacts, graph matching for model/manifest/receipts/stack members, role summary matching for runtime/model-manifest/assembly/adapter-family/stack modules, rendered Module Plan fallback and loaded receipt fields, Module Plan Trace checkpoint rendering, checksum-consistent tokenizer-drift, runtime-scratch-drift, WASM-memory-drift, adapter-validation-drift, adapter-validation-count-drift, adapter-apply-count-drift, count-drift, resource-drift, graph-drift, stack-drift, role-drift, byte-drift, checksum-drift, assembly-eval-case-drift rejection before generated evidence or stack artifact fetch, assembly-evidence-file-drift rejection before later evidence or adapter routes, adapter-family-receipt-drift rejection before adapter manifests or stack artifacts, adapter-manifest-drift rejection before later adapter manifests or stack artifacts, and adapter-artifact-drift rejection before later stack artifacts or Rust adapter apply, with local-only requests - browser module-plan phase smoke covers generated `.module-plan.receipt` `module.N.phase` fields, verified rendered phase summaries, source-root phase fallback, and checksum-consistent phase-drift rejection before generated `.slm` or stack artifact fetch - browser module-plan byte-count smoke covers generated `.module-plan.receipt` `module.N.byte_count` fields, verified rendered byte summaries, source-root byte fallback, and checksum-consistent byte-drift rejection before generated `.slm` or stack artifact fetch - browser module-plan checksum smoke covers generated `.module-plan.receipt` `module.N.checksum` fields, verified rendered checksum summaries, source-root checksum fallback, and checksum-consistent checksum-drift rejection before generated `.slm` or stack artifact fetch - browser selector-budget smoke covers registry `selector_model_byte_budget`, `entry.N.model_bytes` over-budget rejection, fallback static model retention, no oversized model route request, and successful fallback q8_0 generation - browser sidecar-budget-contract smoke covers selector registry text budget contract drift, fallback static model retention, no drifted model route request, and successful fallback q8_0 generation - combined generated selector-root smoke covers one browser-multi-parent-bundle `all` root with f32/q8_0/q4_0 entries, registry entry switching, receipt-preferred sparse ASP1 selected before apply, assembly evidence loaded, active quantization preserved after apply, three-cycle route-soak per-pass requests, five-cycle extended route-soak pressure, and eight-cycle stress route-soak pressure across q4_0/q8_0/f32 cycles future_browser_tests: - longer performance soak across more than three cycles and more models when quality-model artifacts exist - server-port race test that starts a local service between port resolution and Rust local-server launch ================================================================================ END FILE: .uai/test-plan.uai ================================================================================ ================================================================================ BEGIN FILE: .uai/workspace-guidance.uai BYTES: 65395 SHA256: 5CE36C95DF0AA8498FA573290D77B9C6146FB185BD7340B0A906AEA122F908DE ================================================================================ profile: gguf-mirust.workspace-guidance.v76 updated_utc: 2026-06-29T20:22:33Z canonical_root: E:\Source\Rust\GGUF.MiRust.com startup_rule: Read AGENTS.md, workspace.uai, and local .uai startup files before broad loading. memory_strategy: hot_memory: .uai/ durable_memory: wiki/gguf-mirust/ and docs/ deep-linked from .uai/long-term-memory.uai public_durable_target: https://aiwikis.org/gguf-mirust/ note: LLM Wiki and docs-based durable Markdown are both valid when deep-linked from .uai with routing summaries and review status. hot_report_synthesis: .uai/report-synthesis.uai must summarize processed reports enough for cold-start routing before durable wiki loading. hot_short_term_report_pointer: .uai/short-term-memory.uai must reference current report-intake indexes and durable synthesis nodes after each processed handoff batch. site_voice_hot_memory: .uai/taboo.uai governs public copy and product positioning for this website. dogfood_rule: If durable wiki memory is hard to crawl from .uai, update UAIX/LLM Wiki guidance and strengthen hot .uai synthesis rather than only adding more Markdown. report_storage_rule: Keep report bodies in wiki/raw durable evidence, keep short-term memory as current routing plus proof pointers, and keep long-term memory as checksum-bearing pointers. short_term_report_routes_rule: .uai/short-term-memory.uai must expose current_report_routes for report indexes, durable research, active bucket disposition, UAIX strategy source, and the long-term pointer ledger. uaix_file_handoff_strategy_source: https://uaix.org/en-us/tools/ai-memory-package-wizard/#setup-file-handoff uaix_file_handoff_strategy_2026_06_27: Scan active buckets first, record disposition and proof-of-use, preserve originals with checksums in raw evidence, synthesize durable wiki/report nodes, refresh hot routing, audit long-term pointers, then remove or explicitly keep active source copies. uaix_file_handoff_strategy_2026_06_28: Apply setup-file-handoff as a cold-start loop: active buckets are intake, raw/wiki files hold durable bodies, `.uai` files hold routing and synthesis, short-term memory names current report/research routes, and long-term memory keeps checksum pointers. report_pointer_audit_2026_06_27: Every current wiki/gguf-mirust/reports/*.md report page is represented in .uai/long-term-memory.uai; future report pages must be added to that ledger and routed from short-term memory. report_pointer_audit_2026_06_28: Every current report and research page must stay represented in .uai/long-term-memory.uai and referenced from .uai/short-term-memory.uai after report, research, dogfood, or strategy refresh work. research_reference_distribution_rule: Keep research/reference bodies in wiki/gguf-mirust/research/ and report syntheses in wiki/gguf-mirust/reports/; route them from short-term memory and checksum-bearing long-term pointers instead of inlining them into long-term memory. model_breeding_reference_expansion_2026_06_28: Route kinship metrics, sparse-mask breadcrumbs, evolutionary merge recipes, adaptive search, multi-objective fitness, and low-rank adapter references through the durable research page and hot .uai boundaries; sparse masks, population objective vectors, parent relatedness, sparse ASP1 packages, low-rank ALR1 packages, trained low-rank adapter source bundles, and source-backed ALR1 manifests now have first typed receipt or manifest forms. model_breeding_diverse_reference_lanes_2026_06_28: Keep architecture-preserving merge, sparse-lineage, adapter-ecology including trained low-rank source bundles, source-backed ALR1, and ADP1/ASP1/ALR1, population-search, federated/local-update, browser-constrained-assembly, and UAIX-memory-strategy lanes in the research page; translate them into typed receipts or tests before implementation claims. model_breeding_concept_routes_2026_06_28: Add heritable-artifact, mate-selection, phenotype-evidence, and speciation-and-fit lanes to the research route; heritable-artifact now has selector fields, Model Provenance Artifact rows, and combined-selector proof, while future lanes should translate into typed fields, receipts/manifests, eval/provenance fields, or browser-smoke assertions before source claims. modelbreeder_zero_dependency_reference_2026_06_28: Route the latest ModelBreeder and zero-dependency research intake through wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md before schema, runtime, browser-smoke, public-copy, or telemetry changes. two_parent_operator_browser_provenance_2026_06_29: Route blend, task-delta, and sparse task-delta compact browser Operator rendering plus byte-echo fallback proof through wiki/gguf-mirust/reports/two-parent-operator-browser-provenance-memory-2026-06-29.md. crossover_operator_2026_06_29: Route `crossover-candidate` and `validate-crossover-candidate`, seed/keep fields, selection density, mask checksum, q8 validation, browser Operator rendering, crossover byte-echo fallback, parameter tests, and CLI proof through wiki/gguf-mirust/reports/crossover-operator-memory-2026-06-29.md. mutation_operator_2026_06_29: Route `mutation-candidate` and `validate-mutation-candidate`, seed/rate/magnitude fields, reference scaling, selection checksum, delta checksum, q8 validation, browser Operator rendering, mutation byte-echo fallback, parameter tests, and CLI proof through wiki/gguf-mirust/reports/mutation-operator-memory-2026-06-29.md. candidate_operator_receipt_binding_2026_06_29: Route optional `candidate-manifest`/`validate-candidate` operator receipt binding, receipt checksum fields, candidate byte/checksum equality, and CLI proof through wiki/gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29.md. promotion_operator_receipt_binding_2026_06_29: Route optional `promotion-template`/`validate-promotion` operator receipt carry-forward, promotion receipt fields, missing receipt rejection, receipt checksum drift, and CLI proof through wiki/gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29.md. admission_operator_receipt_binding_2026_06_29: Route optional `admission-record`/`validate-admission` operator receipt carry-forward, admission receipt fields, summary validation, missing receipt rejection, receipt checksum drift, and CLI proof through wiki/gguf-mirust/reports/admission-operator-receipt-binding-memory-2026-06-29.md. selector_operator_receipt_binding_2026_06_29: Route selector registry `entry.N.operator_receipt_*`, mate-selection checksum binding, browser Model Provenance Operator rendering, copied-field drift tests, and CLI admission-to-registry proof through wiki/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29.md. browser_multi_parent_operator_provenance_2026_06_29: Route multi-parent admission `operator_receipt_*` carry-forward into generated selector entries, soup/sign-merge browser Operator rows, generated combined-selector proof, `generated-selector-operator-receipt-drift` byte fallback, and `generated-selector-operator-kind-drift` generated assembly kind fallback through wiki/gguf-mirust/reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md. browser_mixed_operator_selector_2026_06_29: Route mixed sign-merge plus soup generated selector roots, six-entry q4/q8/f32 cross-family assembly, q4 default preservation, operator-family cycle, route-soak, reload-soak proof, release-before-reassembly proof, and route accounting through wiki/gguf-mirust/reports/browser-mixed-operator-selector-memory-2026-06-29.md. parent_pool_evolution_schedule_2026_06_29: Route checksum-bound parent-pool operator-family schedules, sign-merge/soup replay, seed-weight schedule metadata, population fitness echoes, and drift tests through wiki/gguf-mirust/reports/parent-pool-evolution-schedule-memory-2026-06-29.md. operator_schedule_carry_forward_2026_06_29: Route parent-pool schedule identity carried into sign-merge/soup receipts, multi-parent candidate manifests, promotion templates, and selector admissions, including scheduled family command/rule/output gate proof, through wiki/gguf-mirust/reports/operator-schedule-carry-forward-memory-2026-06-29.md. prune_operator_2026_06_29: Route `prune-candidate` and `validate-prune-candidate`, keep/floor ppm, magnitude-ranking selection, selected/pruned counts, mask checksum, output-value checksum, q8 validation, selector receipt carry-forward, browser Operator rendering, prune byte-echo fallback, parameter tests, and CLI proof through wiki/gguf-mirust/reports/prune-operator-memory-2026-06-29.md. dare_operator_2026_06_29: Route `dare-candidate` and `validate-dare-candidate`, signed task-delta weights, keep/drop ppm, dropout seed, selected/dropped counts, mask checksum, raw delta checksum, rescaled delta checksum, q8 validation, parameter tests, and CLI proof through wiki/gguf-mirust/reports/dare-operator-memory-2026-06-29.md. dare_browser_operator_provenance_2026_06_29: Route DARE compact browser Operator rendering, selector receipt kind carry-forward, `dare-operator-registry`, and `dare-operator-receipt-drift` byte fallback through wiki/gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29.md. browser_converted_trained_provenance_2026_06_29: Route `converted-trained-registry`, converted-trained q8 selector fixture, browser Model Provenance source/admission/quality fields, converted-trained manifest request proof, and shared compact registry regression through wiki/gguf-mirust/reports/browser-converted-trained-provenance-memory-2026-06-29.md. browser_converted_trained_file_route_2026_06_29: Route `browser-converted-trained-bundle`, file-backed `converted-trained-registry-file`, generated root `target/browser-converted-trained-file-20260629/tinyrustlm`, and real selector/model/manifest fetch proof through wiki/gguf-mirust/reports/browser-converted-trained-file-route-memory-2026-06-29.md. browser_converted_trained_all_route_2026_06_29: Route `browser-converted-trained-bundle ... all`, generated root `target/browser-converted-trained-all-20260629/tinyrustlm`, q4 default metadata, and q4/q8/f32 real selector/model/manifest browser proof through wiki/gguf-mirust/reports/browser-converted-trained-all-route-memory-2026-06-29.md. federated_operator_2026_06_29: Route `federated-candidate` and `validate-federated-candidate`, base/local-update parent roles, local_update_weight_ppm, local-update counts, delta checksums, q8 validation, parameter tests, and CLI proof through wiki/gguf-mirust/reports/federated-operator-memory-2026-06-29.md. weighted_soup_operator_2026_06_29: Route `soup-candidate` and `validate-soup-candidate`, parent-pool recipe seed weights, direct weighted averaging, parent-weight checksum, weighted-value checksum, frontier-change density, drift tests, and focused verification through wiki/gguf-mirust/reports/weighted-soup-operator-memory-2026-06-29.md. multi_parent_soup_manifest_2026_06_29: Route `multi-parent-candidate-manifest` parent-pool operator dispatch, soup receipt acceptance, sign-merge compatibility, soup metric preservation, manifest status, and focused tests through wiki/gguf-mirust/reports/multi-parent-soup-manifest-memory-2026-06-29.md. federated_selector_receipt_route_2026_06_29: Route federated operator receipt carry-forward from candidate to promotion to admission to selector registry and browser Model Provenance, including `operator_kind=federated-local-update-average`, receipt checksum, candidate checksum, byte-count equality, browser Operator rendering, federated operator-kind drift rejection, and browser operator-receipt byte-count drift fallback through wiki/gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29.md. browser_module_plan_operator_receipt_2026_06_29: Route generated selector `entry.N.module_plan_operator_receipt_*`, `.module-plan.receipt` `operator_receipt_*`, assembly receipt/operator receipt agreement, fetched sign-merge operator checksum binding, and `module-plan-operator-receipt-drift` through wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md. browser_module_plan_actual_module_bytes_2026_06_29: Route browser-observed generated module-byte accounting, Module Plan `Actual Module Bytes`, q4/q8/f32 module byte totals, source fallback, and Ready gating through wiki/gguf-mirust/reports/browser-module-plan-actual-module-bytes-memory-2026-06-29.md. browser_module_plan_actual_module_checksums_2026_06_29: Route browser-observed generated module-checksum accounting, Module Plan `Actual Module Checksums`, q4/q8/f32 checksum equality, source fallback, Ready gating, and module-plan-payload-checksum-drift through wiki/gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md. browser_selector_genome_fitness_2026_06_28: Route generated selector genome ids, lineage checksums, eval-bound fitness-vector checksums, Model Provenance Genome/Fitness rows, and combined-selector-assembly assertions through wiki/gguf-mirust/reports/browser-selector-genome-fitness-memory-2026-06-28.md. browser_selector_species_fit_2026_06_28: Route generated selector species ids, browser-fit checksums, Model Provenance Species rows, and combined-selector-assembly assertions through wiki/gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28.md. browser_selector_novelty_2026_06_28: Route generated selector novelty ids, behavior-sketch checksums, Model Provenance Novelty rows, and combined-selector-assembly assertions through wiki/gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28.md. browser_selector_population_2026_06_28: Route generated selector population ids, population-review checksums, Model Provenance Population rows, and combined-selector-assembly assertions through wiki/gguf-mirust/reports/browser-selector-population-memory-2026-06-28.md. browser_selector_mate_selection_2026_06_28: Route generated selector mate-selection ids, parent counts, parent-pool-bound checksums, Model Provenance Mate Selection rows, and combined-selector-assembly assertions through wiki/gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28.md. browser_selector_phenotype_evidence_2026_06_28: Route generated selector phenotype-evidence ids, runtime-eval-bound checksums, provenance manifest checksums, Model Provenance Phenotype rows, and combined-selector-assembly assertions through wiki/gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28.md. browser_selector_heritable_artifact_2026_06_28: Route generated selector heritable artifact ids, served-artifact-bound checksums, Model Provenance Artifact rows, and combined-selector-assembly assertions through wiki/gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28.md. browser_module_plan_total_limit_2026_06_28: Route `module_plan_total_byte_budget_limit=43454464`, Module Plan `Total Limit`, cap drift proof, and combined-selector-assembly assertions through wiki/gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28.md. browser_module_plan_prompt_limit_2026_06_28: Route `module_plan_prompt_byte_limit=4096`, Module Plan `Prompt Limit`, prompt transfer boundary proof, `module-plan-prompt-limit-drift`, and source-root `prompt-limit` assertions through wiki/gguf-mirust/reports/browser-module-plan-prompt-limit-memory-2026-06-28.md. browser_module_plan_output_limit_2026_06_28: Route `module_plan_output_byte_limit=65536`, Module Plan `Output Limit`, generated-result cap proof, total-budget inclusion, and `module-plan-output-limit-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-output-limit-memory-2026-06-28.md. browser_module_plan_adapter_stack_budget_2026_06_28: Route `module_plan_adapter_stack_byte_budget=22144`, Module Plan `Stack Budget`, exact ADP1/ASP1/ALR1 stack-byte proof, and `module-plan-adapter-stack-budget-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28.md. browser_module_plan_tokenizer_2026_06_28: Route `module_plan_tokenizer_checksum`, Module Plan `Tokenizer`, tokenizer-aware genome/species checksum ingredients, and `module-plan-tokenizer-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28.md. browser_eval_case_evidence_checksum_2026_06_28: Route selector admission eval evidence, promotion-ledger copies, selector registry eval fields, generated assembly receipt eval digests, Model Provenance eval rows, and registry-backed browser provenance assertions through wiki/gguf-mirust/reports/browser-eval-case-evidence-checksum-memory-2026-06-28.md. browser_assembly_eval_case_drift_2026_06_28: Route generated assembly eval-digest gate work, assembly rejection state, and `assembly-eval-case-drift` smoke assertions through wiki/gguf-mirust/reports/browser-assembly-eval-case-drift-memory-2026-06-28.md. browser_assembly_evidence_file_drift_2026_06_28: Route fetched assembly evidence-file checksum work, evidence route ordering, assembly rejection state, and `assembly-evidence-file-drift` smoke assertions through wiki/gguf-mirust/reports/browser-assembly-evidence-file-drift-memory-2026-06-28.md. browser_adapter_manifest_drift_2026_06_28: Route generated adapter manifest checksum work, post-receipt adapter state, later manifest and stack-artifact request ordering, and `adapter-manifest-drift` smoke assertions through wiki/gguf-mirust/reports/browser-adapter-manifest-drift-memory-2026-06-28.md. browser_adapter_artifact_drift_2026_06_28: Route generated adapter stack artifact checksum work, post-manifest adapter state, later stack-artifact request ordering, and `adapter-artifact-drift` smoke assertions through wiki/gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28.md. browser_adapter_stack_prefetch_drift_2026_06_28: Route generated auto-apply stack preflight, fetched ADP1/ASP1/ALR1 bytes before WASM transfer, and `adapter-stack-prefetch-drift` smoke assertions through wiki/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md. browser_adapter_stack_rust_validate_2026_06_28: Route generated auto-stack Rust semantic preflight, `validate_adapter_delta` WASM ABI work, and validation-before-apply smoke assertions through wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md. browser_adapter_stack_rust_validate_drift_2026_06_28: Route checksum-consistent ADP1 identity drift, no-apply validation failure state, and `adapter-stack-rust-validate-drift` smoke assertions through wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28.md. browser_runtime_assembly_diagnostics_2026_06_28: Route Rust diagnostics assembly fields, adapter apply accounting, WASM ABI diagnostics, checked manual sidecar assertions, and generated q4_0/q8_0/f32 auto-stack runtime state assertions through wiki/gguf-mirust/reports/browser-runtime-assembly-diagnostics-memory-2026-06-28.md. trained_adapter_source_2026_06_28: Route trained low-rank adapter source manifests, factor-file validation, and trained LoRA-style source intake through wiki/gguf-mirust/reports/trained-adapter-source-memory-2026-06-28.md. trained_adapter_source_alr1_2026_06_28: Route convert-adapter-source, validate-converted-adapter-source, reviewed factor-to-ALR1 packaging, source-backed ALR1 manifests, and base `.slm` identity matching through wiki/gguf-mirust/reports/trained-adapter-source-alr1-memory-2026-06-28.md. browser_source_backed_alr1_route_2026_06_28: Route generated bundle adapter-source staging, source-backed ALR1 adapter-family members, browser `.alr1` manifest kind/dtype acceptance, and combined-selector-assembly source-backed ALR1 assertions through wiki/gguf-mirust/reports/browser-source-backed-alr1-route-memory-2026-06-28.md. browser_source_backed_alr1_contract_2026_06_28: Route source-backed ALR1 exact kind/dtype pairs, adapter-family source echoes, manifest-vs-receipt provenance checks, and `source-backed-alr1-manifest-drift` assertions through wiki/gguf-mirust/reports/browser-source-backed-alr1-contract-memory-2026-06-28.md. browser_combined_selector_cycle_2026_06_28: Route repeated generated all-root q4_0/q8_0/f32 switching, release-before-reassembly behavior, per-pass stack validation/apply deltas, and `combined-selector-cycle` assertions through wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md. browser_combined_selector_route_soak_2026_06_28: Route longer generated all-root q4_0/q8_0/f32 selector reuse, per-pass self-assembly route counts, no-store local fetch behavior, and `combined-selector-route-soak` assertions through wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md. browser_combined_selector_extended_route_soak_2026_06_28: Route five-cycle generated all-root q4_0/q8_0/f32 selector pressure, fifteen browser assemblies, path-flexible total-budget assertions, and `combined-selector-route-extended-soak` evidence through wiki/gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md. browser_combined_selector_stress_route_soak_2026_06_28: Route eight-cycle generated all-root q4_0/q8_0/f32 selector pressure, twenty-four browser assemblies, and `combined-selector-route-stress-soak` evidence through wiki/gguf-mirust/reports/browser-combined-selector-stress-route-soak-memory-2026-06-28.md. browser_combined_selector_reload_soak_2026_06_28: Route fresh page-lifetime generated all-root q4_0/q8_0/f32 self-assembly, registry q4_0 default boot selection, repeated route counts, and `combined-selector-reload-soak` assertions through wiki/gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28.md. browser_module_plan_profile_2026_06_28: Route `browser-constrained-v1` selector/receipt contract work, generated module-plan profile fields, and `module-plan-profile-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md. browser_module_plan_execution_profile_2026_06_28: Route `single-threaded-wasm-local-v1` selector/receipt execution topology, Module Plan `Execution`, and `module-plan-execution-profile-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28.md. browser_module_plan_fetch_policy_2026_06_28: Route `local-no-store-v1` selector/receipt fetch policy, Module Plan `Fetch`, and `module-plan-fetch-policy-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28.md. browser_module_plan_origin_policy_2026_06_28: Route `same-origin-loopback-local-v1` selector/receipt origin policy, Module Plan `Origin`, and `module-plan-origin-policy-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28.md. browser_module_plan_fetch_count_2026_06_28: Route `module_plan_fetch_count_limit=32`, Module Plan `Fetch Limit`, generated self-assembly route-count computation, actual governed request counting, and fetch-count assertions through wiki/gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28.md. browser_module_plan_runtime_scratch_2026_06_28: Route `module_plan_runtime_scratch_byte_budget=65536`, Module Plan `Scratch Budget`, generated selector/receipt runtime envelopes, and `module-plan-runtime-scratch-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md. browser_module_plan_total_budget_2026_06_28: Route `module_plan_total_byte_budget`, Module Plan `Total Budget`, exact generated self-assembly totals, and `module-plan-total-budget-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-total-budget-memory-2026-06-28.md. browser_module_plan_wasm_memory_2026_06_28: Route `module_plan_wasm_memory_initial_pages=17`, Module Plan `WASM Pages`, pre-init exported WASM linear-memory page evidence, and `module-plan-wasm-memory-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-wasm-memory-memory-2026-06-28.md. browser_module_plan_wasm_export_set_2026_06_28: Route `module_plan_wasm_export_set=tinyrustlm-generate-v1`, Module Plan `WASM ABI`, instantiated export verification, and `module-plan-wasm-export-set-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md. browser_module_plan_wasm_heap_2026_06_28: Route `module_plan_wasm_heap_min_bytes`, Module Plan `Heap Floor`, browser alloc/dealloc probe behavior, and `module-plan-wasm-heap-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-wasm-heap-memory-2026-06-28.md. browser_module_plan_wasm_transfer_2026_06_28: Route `module_plan_wasm_transfer_strategy=copy-then-release-v1`, Module Plan `Transfer`, browser copy-and-release discipline, source fallback, and `module-plan-wasm-transfer-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md. browser_module_plan_model_release_2026_06_29: Route `module_plan_model_release_strategy=free-before-reassembly-v1`, Module Plan `Release`, release-before-reassembly proof, source fallback, and `module-plan-model-release-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-model-release-memory-2026-06-29.md. browser_module_plan_runtime_reset_2026_06_29: Route `module_plan_runtime_reset_strategy=reset-context-before-assembly-v1`, Module Plan `Reset`, reset-before-assembly proof, source fallback, and `module-plan-runtime-reset-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-runtime-reset-memory-2026-06-29.md. browser_module_plan_adapter_validation_2026_06_29: Route `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1`, Module Plan `Validate`, validate-before-apply proof, source fallback, and `module-plan-adapter-validation-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29.md. browser_module_plan_adapter_apply_count_2026_06_29: Route `module_plan_adapter_apply_count=3`, Module Plan `Apply Count`, adapter-family stack count agreement, runtime `adapter_apply_count` diagnostics checks, source fallback, and `module-plan-adapter-apply-count-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md. browser_module_plan_kv_cache_2026_06_28: Route `module_plan_kv_cache_byte_budget`, `module_plan_kv_cache_page_count`, Module Plan `KV Budget` and `KV Pages`, runtime KV diagnostics, and `module-plan-kv-cache-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28.md. browser_module_plan_context_token_2026_06_28: Route `module_plan_context_token_limit=16`, Module Plan `Context`, selector model-shape context parsing, and `module-plan-context-token-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28.md. browser_module_plan_sampler_cap_2026_06_28: Route `module_plan_sampler_candidate_cap=1024`, Module Plan `Sampler Cap`, fixed-buffer Top K clamping, and `module-plan-sampler-cap-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-sampler-cap-memory-2026-06-28.md. browser_module_plan_count_drift_2026_06_28: Route selector-to-receipt module cardinality, `module_plan_module_count` versus `module_count`, and `module-plan-count-drift` assertions through wiki/gguf-mirust/reports/browser-module-plan-count-drift-memory-2026-06-28.md. site_voice_strategy_rule: .uai/taboo.uai governs model-breeding, mutualist, tiny-ecology, UAIX strategy, and public website copy for this site; public copy should simply use proof, craft, lineage, fit, local agency, routes, and evidence. long_term_pointer_rule: link_only_not_context_free: true summary_rule: Routing-only, one sentence, 35 words maximum, no body memory. statuses: current, retired, superseded, quarantined file_targets_need_checksum: true file_handoff_rule: active_buckets: agent-file-handoff/Content/, agent-file-handoff/Improvement/ source_site_archive_default: forbidden completion_gate: live bucket scan, disposition ledger, actual work outcome, hot-memory update, durable preservation evidence, checks, blockers, removal or keep-active reason. report_processing_gate: For large report batches, preserve raw originals, create distributed durable synthesis, populate typed .uai summaries, update pointer ledger, then clear source copies. 2026_06_26_batch_rule: Model-breeding reports route through raw/gguf-mirust/report-intake-2026-06-26/, wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md, and wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md. 2026_06_28_research_batch_rule: ModelBreeder and zero-dependency research routes through raw/gguf-mirust/report-intake-2026-06-28/, wiki/gguf-mirust/reports/report-intake-index-2026-06-28.md, and wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md. implementation_rule: status: milestone_160_browser_module_plan_actual_module_checksums active_product: TinyRustLM active_root: tinyrustlm/ dependency_rule: zero third-party Rust crates and zero third-party browser runtime dependencies. core_math_ops: direct_unit_coverage_for_dot_matvec_matmul_rmsnorm_softmax_silu_swiglu_and_shape_failure_paths public_rust_doc_gate: missing_docs_denied_workspace_wide_and_visual_studio_test_helper_runs_strict_rustdoc_for_runtime_and_all_tool_bins require_tests_before_runtime_claims: true tiny_transformer_forward: verified_for_f32_q8_0_q4_0_tiny_fixtures custom_bpe_tokenizer: verified_with_tiny_bpe_slm_runtime_fixture_prompt_the_merging_to_diagnostics_tokenizer_output_256_261 tinylm16_f32_forward: verified_with_deterministic_real_shaped_smoke_model tinylm16_q8_forward: verified_with_deterministic_real_shaped_smoke_model_and_direct_q8_matvec tinylm16_q4_forward: verified_with_deterministic_real_shaped_smoke_model_and_direct_q4_matvec quantized_tensor_storage: verified_without_full_decoded_f32_shadow_copies_using_runtime_owned_reusable_scratch_for_row_and_vector_dequantization model_tensor_routing: verified_for_model_load_pre_resolved_tensor_indices_artifact_backed_tied_output_fixture_and_generation_without_per_token_layer_name_formatting tiny_tied_output_fixture: verified_for_missing_output_weight_with_v1_tied_flag_runtime_generation_manifest_validation_and_missing_output_without_flag_rejection reusable_generation_buffers: verified_for_model_loaded_scratch_and_logits_reuse_across_generate_and_generate_next_token_plus_top_k_without_vocab_sized_candidate_vec fixed_buffer_stochastic_sampling: verified_for_temperature_top_k_top_p_seed_sampling_with_fixed_1024_candidate_buffers_bpe_top_k_262_and_oversized_top_k_rejection_without_vocab_sized_candidate_vec context_boundary_state: verified_for_last_prompt_slot_acceptance_full_context_rejection_clean_failed_request_diagnostics_and_step_token_state_continuation output_buffer_boundary: verified_for_64_kib_generated_result_cap_byte_and_bpe_bounded_decode_output_buffer_exceeded_and_clean_full_generate_error_state browser_step_token_control: verified_with_static_ui_step_token_button_js_generate_next_token_call_context_sensitive_enablement_response_append_transcript_append_console_logging_benchmark_update_and_browser_smoke_click_through browser_adapter_sidecar: verified_with_static_adapter_sidecar_panel_local_tiny_f32_q8_q4_self_adp1_routes_selected_artifact_checksum_verification_js_wasm_byte_transfer_apply_adapter_delta_call_browser_smoke_click_through_checksum_mismatch_rejection_and_cleared_generation_diagnostics browser_registry_adapter_family: verified_with_browser_multi_parent_bundle_generated_multi_parent_sign_merge_f32_q8_q4_self_adp1_family_adp1_sparse_asp1_and_low_rank_alr1_sidecars_indexed_selector_registry_adapter_family_fields_receipt_bound_preferred_adapter_selection_explicit_adapter_auto_apply_fields_adapter_auto_apply_byte_budget_1048576_module_plan_resource_envelope_receipts_browser_frugal_quantized_q4_default_selection_selector_model_byte_budget_contract_selector_manifest_receipt_evidence_text_budget_contract_fields_self_contained_generated_roots_combined_multi_quant_selector_root_and_browser_smoke_adapter_sidecar_registry_file_pre_generation_auto_apply browser_text_sidecar_budgets: verified_for_selector_registry_256kib_manifest_64kib_receipt_128kib_and_evidence_128kib_pre_parse_fetch_limits_with_adapter_manifest_budget_smoke_no_artifact_fetch_after_oversized_manifest_and_registry_declared_exact_text_budget_contract_fields_with_sidecar_budget_contract_fallback_smoke browser_runtime_wasm_manifest: verified_for_checked_and_generated_roots_with_runtime_manifest_fetch_before_wasm_instantiation_wasm_byte_count_checksum_validation_build_helper_refresh_static_harness_contract_runtime_manifest_drift_smoke_and_generated_root_adapter_sidecar_registry_file_smoke browser_adapter_stack: verified_for_generated_adapter_family_receipts_selector_registry_stack_fields_browser_receipt_stack_validation_aggregate_manifest_byte_budget_checks_family_adp1_plus_sparse_asp1_plus_low_rank_alr1_pre_generation_validate_then_apply_and_generated_root_adapter_sidecar_registry_file_smoke browser_module_plan: verified_for_generated_selector_module_plan_fields_served_module_plan_receipts_browser_checksum_verification_before_generated_slm_fetch_browser_constrained_v1_profile_single_threaded_wasm_local_v1_execution_profile_local_no_store_v1_fetch_policy_same_origin_loopback_local_v1_origin_policy_fetch_count_limit_32_tokenizer_checksum_pre_init_wasm_memory_initial_pages_tinyrustlm_generate_v1_wasm_export_set_resource_class_model_byte_budget_adapter_byte_budget_runtime_scratch_byte_budget_output_byte_limit_kv_cache_byte_budget_kv_cache_page_count_total_byte_budget_graph_matching_for_model_manifest_assembly_receipt_adapter_family_receipt_module_byte_count_fields_module_checksum_fields_module_roles_module_assembly_slots_and_ordered_stack_members_module_plan_panel_display_from_verified_receipt_fields_including_visible_execution_fetch_origin_fetch_limit_tokenizer_wasm_pages_wasm_abi_model_adapter_scratch_output_kv_total_byte_budgets_ordered_byte_summary_ordered_checksum_summary_ordered_slot_summary_ordered_role_summary_and_browser_owned_trace_checkpoints_generated_root_adapter_sidecar_registry_file_smoke_module_plan_profile_drift_no_slm_adapter_family_manifest_or_stack_artifact_fetch_smoke_module_plan_execution_profile_drift_no_slm_adapter_family_manifest_or_stack_artifact_fetch_smoke_module_plan_fetch_policy_drift_no_slm_adapter_family_manifest_or_stack_artifact_fetch_smoke_module_plan_origin_policy_drift_no_slm_adapter_family_manifest_or_stack_artifact_fetch_smoke_module_plan_fetch_count_drift_no_slm_adapter_family_manifest_or_stack_artifact_fetch_smoke_module_plan_tokenizer_drift_no_slm_adapter_family_manifest_or_stack_artifact_fetch_smoke_module_plan_wasm_memory_drift_no_slm_adapter_family_manifest_or_stack_artifact_fetch_smoke_module_plan_wasm_export_set_drift_no_slm_adapter_family_manifest_or_stack_artifact_fetch_smoke_module_plan_kv_cache_drift_no_slm_adapter_family_manifest_or_stack_artifact_fetch_smoke_module_plan_runtime_scratch_drift_no_slm_adapter_family_manifest_or_stack_artifact_fetch_smoke_module_plan_output_limit_drift_no_slm_adapter_family_manifest_or_stack_artifact_fetch_smoke_module_plan_total_budget_drift_no_slm_adapter_family_manifest_or_stack_artifact_fetch_smoke_module_plan_resource_drift_no_slm_fetch_smoke_module_plan_graph_drift_no_slm_fetch_smoke_module_plan_stack_drift_no_slm_or_stack_artifact_fetch_smoke_module_plan_role_drift_no_slm_or_stack_artifact_fetch_smoke_module_plan_slot_drift_no_slm_or_stack_artifact_fetch_smoke_module_plan_byte_drift_no_slm_or_stack_artifact_fetch_smoke_and_module_plan_checksum_drift_no_slm_or_stack_artifact_fetch_smoke browser_module_plan_total_budget: verified_for_exact_model_manifest_assembly_receipt_adapter_family_receipt_ordered_stack_artifact_bytes_plus_runtime_scratch_output_cap_and_kv_cache_envelopes_with_Total_Budget_display_combined_selector_assembly_q4_q8_f32_totals_and_module_plan_total_budget_drift browser_module_plan_output_limit: verified_for_generated_module_plan_output_byte_limit_65536_fields_with_Output_Limit_display_total_budget_inclusion_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_output_limit_drift browser_module_plan_total_limit: verified_for_explicit_total_self_assembly_cap_43454464_with_selector_registry_and_served_receipt_fields_Total_Limit_display_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_total_limit_drift browser_module_plan_prompt_limit: verified_for_prompt_byte_limit_4096_with_selector_registry_and_served_receipt_fields_Prompt_Limit_display_source_prompt_limit_smoke_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_prompt_limit_drift browser_module_plan_wasm_memory: verified_for_pre_init_exported_wasm_memory_page_count_17_in_selector_and_receipt_fields_with_WASM_Pages_display_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_wasm_memory_drift browser_module_plan_wasm_export_set: verified_for_tinyrustlm_generate_v1_selector_and_receipt_fields_with_instantiated_wasm_export_checks_WASM_ABI_display_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_wasm_export_set_drift browser_module_plan_wasm_heap: verified_for_module_plan_wasm_heap_min_bytes_65536_in_selector_and_receipt_fields_with_browser_alloc_dealloc_probe_Heap_Floor_display_combined_selector_cycle_q4_q8_f32_assertions_source_ui_audit_fallback_and_module_plan_wasm_heap_drift browser_module_plan_wasm_transfer: verified_for_copy_then_release_v1_selector_and_receipt_fields_with_Transfer_display_combined_selector_cycle_q4_q8_f32_assertions_source_ui_audit_fallback_and_module_plan_wasm_transfer_drift browser_module_plan_model_release: verified_for_free_before_reassembly_v1_selector_and_receipt_fields_with_Release_display_combined_selector_cycle_q4_q8_f32_free_model_before_post_initial_assembly_source_ui_audit_fallback_and_module_plan_model_release_drift browser_module_plan_runtime_reset: verified_for_reset_context_before_assembly_v1_selector_and_receipt_fields_with_Reset_display_combined_selector_cycle_q4_q8_f32_reset_context_before_adapter_validation_apply_source_ui_audit_fallback_and_module_plan_runtime_reset_drift browser_module_plan_adapter_validation: verified_for_rust_validate_before_apply_v1_selector_and_receipt_fields_with_Validate_display_combined_selector_assembly_q4_q8_f32_validate_adapter_delta_before_apply_adapter_delta_source_ui_audit_fallback_and_module_plan_adapter_validation_drift browser_module_plan_adapter_apply_count: verified_for_module_plan_adapter_apply_count_3_selector_and_receipt_fields_with_Apply_Count_display_adapter_family_stack_count_binding_runtime_adapter_apply_count_diagnostics_check_source_fallback_and_module_plan_adapter_apply_count_drift browser_module_plan_kv_cache: verified_for_exact_KV_cache_byte_budget_1024_page_count_1_from_model_shape_with_runtime_diagnostics_selector_receipt_fields_KV_Budget_KV_Pages_display_total_budget_inclusion_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_kv_cache_drift browser_module_plan_adapter_stack_budget: verified_for_exact_ADP1_ASP1_ALR1_stack_byte_budget_22144_with_selector_registry_and_served_receipt_fields_Stack_Budget_display_total_budget_inclusion_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_adapter_stack_budget_drift browser_module_plan_context_token: verified_for_validated_context_token_limit_16_in_selector_and_receipt_fields_with_Context_display_model_shape_binding_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_context_token_drift browser_module_plan_tokenizer: verified_for_admitted_tokenizer_checksum_in_selector_and_receipt_fields_with_Tokenizer_display_genome_species_checksum_binding_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_tokenizer_drift browser_module_plan_sampler_cap: verified_for_fixed_buffer_sampler_candidate_cap_1024_in_selector_and_receipt_fields_with_Sampler_Cap_display_Top_K_clamping_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_sampler_cap_drift browser_module_plan_fetch_count: verified_for_generated_module_plan_fetch_count_limit_32_fields_with_Fetch_Limit_display_browser_route_count_computation_actual_governed_request_counting_combined_selector_cycle_reload_soak_q4_q8_f32_assertions_and_module_plan_fetch_count_drift browser_module_plan_count_drift: verified_for_checksum_consistent_served_receipt_module_count_drift_against_selector_module_plan_module_count_with_no_generated_slm_adapter_family_adapter_manifest_or_stack_artifact_fetch browser_module_plan_dependencies: verified_for_generated_module_plan_depends_on_fields_runtime_wasm_to_ordered_module_chain_browser_pre_model_fetch_dependency_validation_module_plan_dependency_summary_display_source_fallback_unavailable_generated_root_adapter_sidecar_registry_file_smoke_and_module_plan_dependency_drift_no_slm_or_stack_artifact_fetch_smoke browser_module_plan_phases: verified_for_generated_module_plan_phase_fields_load_model_bytes_verify_model_manifest_verify_assembly_evidence_verify_adapter_family_and_apply_adapter_stack_members_browser_pre_model_fetch_phase_validation_module_plan_phase_summary_display_source_fallback_unavailable_generated_root_adapter_sidecar_registry_file_smoke_and_module_plan_phase_drift_no_slm_or_stack_artifact_fetch_smoke browser_module_plan_byte_counts: verified_for_generated_module_plan_byte_count_fields_model_bytes_manifest_text_assembly_receipt_text_adapter_family_receipt_text_and_adapter_stack_artifacts_browser_pre_model_fetch_byte_validation_module_plan_byte_summary_display_source_fallback_unavailable_generated_root_adapter_sidecar_registry_file_smoke_and_module_plan_byte_drift_no_slm_or_stack_artifact_fetch_smoke browser_module_plan_checksums: verified_for_generated_module_plan_checksum_fields_model_manifest_assembly_receipt_adapter_family_receipt_and_adapter_stack_artifacts_browser_pre_model_fetch_checksum_validation_module_plan_checksum_summary_display_source_fallback_unavailable_generated_root_adapter_sidecar_registry_file_smoke_and_module_plan_checksum_drift_no_slm_or_stack_artifact_fetch_smoke browser_module_plan_actual_module_checksums: verified_for_browser_observed_generated_self_assembly_module_checksums_with_Actual_Module_Checksums_display_declared_equals_actual_ready_gate_source_fallback_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_payload_checksum_drift_before_generated_routes browser_combined_selector_assembly: verified_for_one_generated_all_root_defaulting_to_q4_then_switching_q4_q8_f32_entries_with_module_plan_before_model_order_and_family_adp1_plus_sparse_asp1_plus_low_rank_alr1_stack_auto_apply_before_each_generation browser_combined_selector_cycle: verified_for_one_generated_all_root_repeating_q4_q8_f32_switching_twice_with_free_model_release_before_each_post_initial_assembly_plus_fresh_stack_validation_apply_completion_reset_diagnostics_and_generation_each_pass browser_combined_selector_route_soak: verified_for_one_generated_all_root_running_three_q4_q8_f32_cycles_with_each_generated_self_assembly_route_requested_once_per_pass_and_local_assembly_fetches_using_no_store_cache_behavior browser_combined_selector_extended_route_soak: verified_for_one_generated_all_root_running_five_q4_q8_f32_cycles_with_fifteen_assemblies_each_self_assembly_route_requested_once_per_pass_and_path_flexible_total_budget_assertions browser_combined_selector_stress_route_soak: verified_for_one_generated_all_root_running_eight_q4_q8_f32_cycles_with_twenty_four_assemblies_and_each_generated_self_assembly_route_requested_once_per_pass browser_combined_selector_reload_soak: verified_for_generated_all_root_rebuilding_q4_q8_f32_self_assembly_across_two_fresh_page_lifetimes_with_q4_default_boot_selection_and_repeated_local_route_requests browser_runtime_assembly_diagnostics: verified_for_runtime_diagnostics_adapter_apply_count_last_adapter_checksum_and_assembly_state_checksum_with_model_load_nonzero_assembly_state_adapter_apply_counting_manual_count_1_generated_stack_count_3_and_free_clearing_state slm_trained_adapter_source: verified_for_adapter_source_template_and_validate_adapter_source_commands_that_write_and_validate_low_rank_f32_factor_source_bundles_with_model_shape_tied_output_target_tensor_hash_factor_rank_checksum_finite_factor_parameter_count_and_delta_l1_fields slm_trained_adapter_source_alr1: verified_for_convert_adapter_source_and_validate_converted_adapter_source_commands_that_turn_reviewed_low_rank_factor_source_bundles_into_runtime_alr1_packages_with_recomputable_source_backed_manifests browser_source_backed_alr1_route: verified_for_browser_multi_parent_bundle_generating_q4_q8_f32_source_backed_alr1_stack_members_from_reviewed_adapter_source_templates_plus_browser_manifest_kind_dtype_acceptance_and_combined_selector_assembly_apply_before_generation browser_source_backed_alr1_contract: verified_for_exact_source_backed_alr1_kind_dtype_pairs_adapter_family_source_echoes_manifest_vs_receipt_provenance_checks_and_source_backed_alr1_manifest_drift_before_stack_artifact_fetch browser_assembly_trace: verified_for_generated_q4_q8_f32_combined_selector_assembly_entries_rendering_the_exact_trace_plan_verified_model_accepted_manifest_verified_assembly_evidence_verified_adapter_family_verified_adapter_stack_applied_ready browser_eval_case_evidence_checksum: verified_for_eval_case_evidence_checksum_flow_from_eval_sidecars_through_admissions_promotion_ledgers_selector_registries_generated_assembly_receipts_and_model_provenance_with_combined_selector_assembly_checking_q4_q8_f32_entries browser_selector_genome_fitness: verified_for_generated_selector_registry_genome_id_genome_lineage_checksum_and_eval_bound_fitness_vector_checksum_with_browser_model_provenance_genome_fitness_rows_and_combined_selector_assembly_q4_q8_f32_assertions browser_selector_novelty: verified_for_generated_selector_registry_novelty_id_behavior_sketch_checksum_and_browser_model_provenance_novelty_rows_with_combined_selector_assembly_q4_q8_f32_assertions browser_selector_population: verified_for_generated_selector_registry_population_id_population_review_checksum_and_browser_model_provenance_population_rows_with_combined_selector_assembly_q4_q8_f32_assertions browser_selector_mate_selection: verified_for_generated_selector_registry_mate_selection_id_parent_count_parent_pool_bound_checksum_and_browser_model_provenance_mate_selection_rows_with_combined_selector_assembly_q4_q8_f32_assertions browser_selector_phenotype_evidence: verified_for_generated_selector_registry_phenotype_evidence_id_runtime_eval_bound_checksum_provenance_manifest_checksum_and_browser_model_provenance_phenotype_rows_with_combined_selector_assembly_q4_q8_f32_assertions browser_selector_heritable_artifact: verified_for_generated_selector_registry_heritable_artifact_id_served_artifact_bound_checksum_and_browser_model_provenance_artifact_rows_with_combined_selector_assembly_q4_q8_f32_assertions browser_assembly_eval_case_drift: verified_for_checksum_consistent_generated_assembly_receipt_eval_digest_drift_stopping_before_evidence_adapter_family_adapter_manifest_and_stack_routes_with_loaded_model_state_released browser_assembly_evidence_file_drift: verified_for_generated_assembly_receipt_referenced_evidence_file_body_drift_stopping_before_later_evidence_adapter_family_adapter_manifest_and_stack_routes_with_loaded_model_state_released browser_adapter_manifest_drift: verified_for_generated_family_adp1_manifest_body_drift_after_adapter_family_receipt_stopping_before_later_adapter_manifests_or_adp1_asp1_alr1_stack_artifacts_with_loaded_model_state_preserved browser_adapter_artifact_drift: verified_for_generated_family_adp1_artifact_body_drift_after_all_adapter_manifests_stopping_before_sparse_low_rank_stack_artifacts_or_apply_adapter_delta_with_loaded_model_state_preserved browser_adapter_stack_rust_validate: verified_for_runtime_model_validate_adapter_delta_runtime_wasm_validate_adapter_delta_abi_browser_auto_stack_validation_before_apply_and_combined_q4_q8_f32_validation_order_smoke browser_adapter_stack_rust_validate_drift: verified_for_checksum_consistent_family_adp1_identity_drift_reaching_rust_validate_adapter_delta_shape_mismatch_before_any_apply_adapter_delta browser_ui_smoke: verified_with_headless_chrome_generate_click_runtime_manifest_request_runtime_manifest_drift_before_model_fetch_module_plan_profile_drift_module_plan_execution_profile_drift_module_plan_fetch_policy_drift_module_plan_origin_policy_drift_module_plan_runtime_scratch_drift_module_plan_resource_drift_module_plan_graph_drift_module_plan_stack_drift_module_plan_role_drift_module_plan_slot_drift_module_plan_phase_drift_module_plan_dependency_drift_module_plan_byte_drift_module_plan_checksum_drift_assembly_eval_case_drift_before_generated_evidence_or_stack_artifact_fetch_assembly_evidence_file_drift_before_later_evidence_or_adapter_routes_adapter_family_receipt_drift_before_adapter_manifests_or_stack_artifacts_adapter_manifest_drift_before_later_manifests_or_stack_artifacts_and_adapter_artifact_drift_before_later_stack_artifacts_or_rust_adapter_apply_module_plan_panel_fallback_generated_receipt_display_visible_execution_fetch_origin_model_adapter_scratch_budget_rows_byte_summary_checksum_summary_slot_summary_role_summary_phase_summary_dependency_summary_and_trace_step_token_click_for_q8_default_q4_selected_reload_reset_model_switch_loop_malformed_model_context_overflow_missing_model_desktop_mobile_ui_audit_model_provenance_conversation_transcript_clear_button_state_dynamic_selector_registry_intake_multi_parent_registry_route_sidecar_budget_contract_generated_multi_parent_registry_file_route_adapter_sidecar_registry_file_for_f32_q8_q4_generated_roots_and_one_combined_f32_q8_q4_root_defaulting_to_q4_with_combined_selector_assembly_across_q4_q8_f32_including_module_plan_profile_execution_profile_fetch_policy_origin_policy_resource_envelope_and_runtime_scratch_request_before_generated_slm_fetch_sparse_asp1_auto_apply_before_generation_and_exact_trace_rendering_endurance_performance_and_performance_soak browser_conversation_transcript: local_user_and_tinyrustlm_turns_render_dom_safe_text_step_token_extends_latest_assistant_turn_reset_preserves_transcript_clear_button_empties_transcript_without_resetting_runtime_context_and_browser_smoke_clicks_clear wasm_abi_smoke: verified_for_invalid_utf8_null_pointer_invalid_length_zero_generation_length_invalid_sampling_recovery_generate_next_token_f32_adapter_validate_f32_adapter_apply_free_model_and_post_free_model_not_loaded slm_checksum_gate: verified_for_nonzero_checksum_generation_and_mismatch_rejection slm_admission_gate: verified_for_header_checksum_tokenizer_required_shapes_payload_lengths_finite_f32_and_quant_scale_validation slm_quality_gate: verified_for_runtime_smoke_admission_pending_assistant_quality_eval_rejection_fixture_scoped_assistant_quality_for_converted_f32_q8_q4_outputs_and_exact_case_ledger_requirements slm_trained_source_conversion: verified_for_raw_f32_source_layout_validation_tied_output_source_manifest_shape_agreement_f32_q8_q4_untied_conversion_converted_trained_manifests_runtime_smoke_fixture_scoped_eval_gates_and_f32_q8_q4_tied_conversion_runtime_smoke_gates slm_parent_compatibility: verified_for_two_parent_slm_reports_with_parent_checksums_shape_tokenizer_checksum_tensor_layout_checksum_quantization_output_contract_flags_and_direct_parameter_decision slm_candidate_lineage: verified_for_lineage_template_and_validate_lineage_commands_that_bind_planned_candidate_records_to_passing_parent_compatibility_reports_before_operator_output slm_blend_operator: verified_for_blend_candidate_and_validate_blend_candidate_commands_that_bind_validated_lineage_compatibility_bound_parent_checksums_blend_weights_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest slm_task_delta_operator: verified_for_delta_candidate_and_validate_delta_candidate_commands_that_bind_validated_lineage_compatibility_bound_base_and_target_parent_checksums_signed_task_delta_weights_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest slm_sparse_delta_operator: verified_for_sparse_delta_candidate_and_validate_sparse_delta_candidate_commands_that_bind_validated_lineage_compatibility_bound_base_and_target_parent_checksums_signed_task_delta_weights_absolute_delta_keep_rate_candidate_slm_bytes_selection_counts_density_nonzero_retention_ppm_implicit_top_k_mask_checksum_and_recomputable_operator_receipts_before_candidate_manifest slm_crossover_operator: verified_for_crossover_candidate_and_validate_crossover_candidate_commands_that_bind_validated_lineage_compatibility_bound_parent_checksums_seed_parent0_keep_rate_selected_parameter_counts_density_ppm_mask_checksum_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest_plus_browser_compact_operator_row_and_byte_echo_fallback slm_mutation_operator: verified_for_mutation_candidate_and_validate_mutation_candidate_commands_that_bind_validated_lineage_compatibility_bound_base_and_reference_parent_checksums_seed_rate_magnitude_reference_scale_selection_checksum_delta_checksum_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest_plus_browser_compact_operator_row_and_byte_echo_fallback slm_prune_operator: verified_for_prune_candidate_and_validate_prune_candidate_commands_that_bind_validated_lineage_compatibility_bound_base_and_reference_parent_checksums_keep_ppm_floor_ppm_magnitude_ranking_selected_pruned_counts_mask_checksum_output_value_checksum_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest slm_federated_operator: verified_for_federated_candidate_and_validate_federated_candidate_commands_that_bind_validated_lineage_compatibility_bound_base_and_local_update_parent_checksums_local_update_weight_ppm_local_update_counts_delta_checksum_weighted_delta_checksum_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest slm_weighted_soup_operator: verified_for_soup_candidate_and_validate_soup_candidate_commands_that_bind_parent_pool_recipe_ledger_review_admissions_ordered_parent_slm_files_recipe_seed_weights_direct_weighted_average_candidate_bytes_parent_weight_checksum_weighted_value_checksum_and_frontier_change_density_before_candidate_manifest slm_federated_selector_receipt_route: verified_for_federated_operator_receipt_fields_surviving_candidate_promotion_admission_selector_registry_and_browser_model_provenance_handoff_with_operator_kind_receipt_checksum_candidate_checksum_byte_count_equality_operator_row_rendering_and_operator_kind_drift_rejection slm_adapter_delta_artifact: verified_for_adapter_delta_and_validate_adapter_delta_commands_that_bind_validated_lineage_compatibility_bound_base_and_target_parent_checksums_raw_f32_task_delta_adapter_bytes_recomputable_manifest_and_f32_runtime_apply_or_offline_fuse_status slm_adapter_fuse_candidate: verified_for_fuse_adapter_delta_and_validate_fuse_adapter_delta_commands_that_validate_adapter_package_manifest_adp1_header_tensor_directory_then_write_normal_slm_candidate_and_recomputable_fuse_receipt_before_candidate_manifest slm_runtime_adapter_apply: verified_for_runtime_and_wasm_apply_adapter_delta_on_loaded_f32_q8_q4_models_with_adp1_asp1_and_alr1_identity_payload_checksum_tensor_directory_tokenizer_layout_fused_value_validation_compact_requantization_and_generation_state_reset slm_sparse_adapter_artifact: verified_for_sparse_adapter_delta_and_validate_sparse_adapter_delta_commands_that_bind_validated_lineage_compatibility_bound_base_and_target_parent_checksums_sparse_f32_task_delta_asp1_bytes_density_retention_mask_checksum_recomputable_manifest_and_runtime_f32_q8_q4_apply_status slm_low_rank_adapter_artifact: verified_for_low_rank_adapter_delta_and_validate_low_rank_adapter_delta_commands_that_bind_validated_lineage_compatibility_bound_base_and_target_parent_checksums_low_rank_f32_task_delta_alr1_factor_bytes_component_limit_factor_density_residual_l1_recomputable_manifest_and_runtime_f32_q8_q4_apply_status slm_candidate_artifact: verified_for_candidate_manifest_and_validate_candidate_commands_that_bind_validated_lineage_to_validated_candidate_slm_artifacts_and_optionally_bind_operator_receipt_checksum_operator_identity_candidate_bytes_and_candidate_checksum_before_eval_or_promotion slm_candidate_promotion: verified_for_promotion_template_and_validate_promotion_commands_that_bind_candidate_manifest_checksum_to_pending_runtime_smoke_eval_selector_and_public_claim_statuses slm_runtime_smoke_sidecar: verified_for_runtime_smoke_and_validate_runtime_smoke_commands_that_bind_provenance_manifest_checksum_slm_checksum_source_kind_model_shape_and_runtime_smoke_decision slm_selector_admission: verified_for_admission_record_and_validate_admission_commands_that_bind_promotion_runtime_smoke_and_passed_converted_trained_eval_sidecars_before_selector_registry_routing slm_promotion_ledger: verified_for_promotion_ledger_and_validate_promotion_ledger_commands_that_bind_validated_admission_records_to_hash_chained_promotion_history_with_duplicate_candidate_and_duplicate_artifact_rejection_before_selector_or_population_review slm_population_review: verified_for_population_review_and_validate_population_review_commands_that_recompute_ledger_backed_admission_rankings_frontier_selection_parent_pool_routes_fitness_scores_weighted_objective_vector_metadata_and_per_entry_objective_checksums slm_parent_pool_recipe: verified_for_parent_pool_recipe_and_validate_parent_pool_recipe_commands_that_validate_population_reviews_require_shared_direct_parameter_contracts_and_recompute_fitness_normalized_seed_weights_relatedness_metric_scope_pair_count_status_checksum_and_per_parent_groups_before_future_recipe_consumers slm_sign_merge_operator: verified_for_sign_merge_candidate_and_validate_sign_merge_candidate_commands_that_validate_parent_pool_recipe_ledger_review_admissions_and_parent_slm_files_then_write_seed_weighted_sign_consensus_slm_candidates_with_recomputable_receipts_that_echo_parent_relatedness_before_multi_parent_candidate_manifest slm_multi_parent_candidate_manifest: verified_for_multi_parent_candidate_manifest_and_validate_multi_parent_candidate_commands_that_dispatch_parent_pool_operator_kind_validate_sign_merge_or_soup_receipts_preserve_operator_specific_metrics_then_bind_receipt_checksum_parent_pool_recipe_checksum_relatedness_summary_parent_summaries_candidate_slm_fields_pending_eval_status_and_next_promotion_route slm_multi_parent_promotion: verified_for_multi_parent_promotion_template_and_validate_multi_parent_promotion_commands_that_validate_multi_parent_candidate_manifests_then_bind_candidate_manifest_checksum_operator_receipt_checksum_recipe_checksum_parent_count_candidate_slm_fields_and_pending_runtime_smoke_eval_status slm_multi_parent_admission: verified_for_multi_parent_admission_record_and_validate_multi_parent_admission_commands_that_validate_multi_parent_promotion_templates_runtime_smoke_provenance_and_passed_eval_sidecars_then_bind_parent_pool_candidate_and_evidence_checksums_for_selector_registry_routing slm_selector_registry: verified_for_selector_registry_and_validate_selector_registry_commands_that_bind_validated_selector_admission_records_and_multi_parent_admission_records_to_served_browser_safe_model_routes_plus_browser_frugal_quantized_default_metadata_selector_model_byte_budget_33554432_contract_exact_selector_registry_manifest_receipt_evidence_text_budget_contract_fields_f32_q8_q4_adapter_family_fields_explicit_auto_apply_fields_adapter_auto_apply_byte_budget_1048576_module_plan_resource_fields_browser_smoke_multi_parent_registry_sidecar_budget_contract_and_generated_file_routes slm_browser_multi_parent_bundle: verified_for_browser_multi_parent_bundle_copying_app_shell_wasm_runtime_runtime_wasm_manifest_models_evidence_selector_registry_with_q4_default_metadata_auto_apply_fields_module_plan_resource_receipt_self_adp1_family_adp1_sparse_asp1_low_rank_alr1_sidecars_adapter_manifests_adapter_family_receipt_with_preferred_sparse_member_and_assembly_receipt_into_runnable_single_quant_roots_or_one_combined_f32_q8_q4_selector_root slm_browser_multi_parent_bundle_routes: verified_for_browser_multi_parent_bundle_command_staging_multi_parent_sign_merge_f32_q8_q4_model_manifest_selector_registry_module_plan_receipt_self_adp1_family_adp1_sparse_asp1_low_rank_alr1_sidecars_adapter_manifests_adapter_family_receipt_assembly_receipt_and_evidence_under_target_tinyrustlm_roots_or_one_combined_all_root_for_file_backed_browser_smoke_and_same_page_combined_selector_assembly rust_local_server: verified_for_loopback_app_wasm_slm_manifest_routes_get_head_content_length_and_visual_studio_reuse_path rust_mini_browser_harness: verified_for_static_app_contract_local_only_markers_required_ui_ids_js_wasm_boundary_calls_rust_wasm_export_definitions_model_manifest_presence_and_loopback_content_types performance_smoke: verified_for_q8_q4_four_token_generation_benchmark_fields_47104_scratch_bytes_reset_recovery_and_local_only_requests performance_soak: verified_for_three_cycles_of_q8_q4_four_token_generation_benchmark_fields_kv_length_scratch_bytes_reset_recovery_and_local_only_requests visual_studio_solution: TinyRustLM.sln verified with VS build helper, model-admission test helper, all-quantization converted-source gates, Rust local-server reuse, Rust browser harness, and busy-port fallback model_breeding_research_memory: durable_synthesis_added_for_future_candidate_lineage_compatibility_offline_merge_adapter_delta_sparse_adapter_delta_adapter_fuse_runtime_f32_q8_q4_adapter_apply_sparse_delta_mask_metadata_population_review_objective_vector_metadata_parent_relatedness_metadata_population_eval_parent_pool_recipe_sign_merge_multi_parent_manifest_multi_parent_promotion_multi_parent_admission_multi_parent_selector_registry_route_binding_browser_served_multi_parent_registry_smoke_generated_browser_bundle_browser_frugal_selector_default_browser_selector_byte_budget_contract_browser_text_sidecar_budget_contract_browser_runtime_wasm_manifest_browser_module_plan_resource_receipts_browser_module_plan_role_drift_browser_module_plan_slot_drift_browser_module_plan_checksum_drift_registry_adapter_family_browser_sparse_asp1_route_browser_verified_assembly_receipts_browser_selector_genome_fitness_browser_auto_assembly_browser_auto_assembly_byte_budget_and_site_voice_routes; implemented_source_gates_are_parent_compatibility_reports_candidate_lineage_templates_blend_operator_receipts_task_delta_operator_receipts_sparse_delta_operator_receipts_with_retention_and_mask_checksum_crossover_operator_receipts_mutation_operator_receipts_prune_operator_receipts_operator_receipt_bound_candidate_artifact_manifests_population_reviews_with_objective_vector_checksums_parent_pool_recipes_with_relatedness_checksum_sign_merge_receipts_with_relatedness_echo_multi_parent_candidate_manifests_with_relatedness_summary_adapter_delta_artifact_manifests_sparse_adapter_delta_artifact_manifests_adapter_fuse_receipts_runtime_f32_q8_q4_adp1_asp1_apply_candidate_artifact_manifests_multi_parent_candidate_manifests_promotion_templates_multi_parent_promotion_templates_multi_parent_admission_records_runtime_smoke_sidecars_selector_admission_records_promotion_ledgers_population_reviews_parent_pool_recipes_sign_merge_receipts_selector_registries_for_both_admission_families_browser_multi_parent_bundle_staging_browser_frugal_selector_default_browser_selector_byte_budget_contract_browser_text_sidecar_budget_contract_browser_runtime_wasm_manifest_browser_module_plan_resource_receipts_browser_module_plan_role_drift_browser_module_plan_slot_drift_browser_module_plan_checksum_drift_registry_carried_adapter_family_smoke_browser_sparse_asp1_smoke_browser_auto_assembly_browser_auto_assembly_byte_budget_browser_verified_assembly_receipts_and_browser_selector_genome_fitness model_breeding_research_memory_prune: implemented_source_gate_added_for_prune_operator_receipts_with_keep_floor_ppm_magnitude_ranking_selected_pruned_counts_mask_checksum_output_value_checksum_q8_cli_proof_downstream_candidate_manifest_routing_selector_receipt_carry_forward_and_selector_operator_kind_drift_rejection model_breeding_reference_memory: refreshed_2026_06_27_for_model_kinship_sparse_mask_breadcrumbs_evolutionary_merge_recipe_search_adaptive_search_and_multi_objective_fitness_lanes_as_reference_metadata; sparse_mask_population_objective_vector_parent_relatedness_and_sparse_asp1_adapter_packages_now_have_first_typed_receipt_or_manifest_forms wasm_artifact: tinyrustlm/runtime/tinyrustlm.wasm slm_model_artifact: tinyrustlm/models/tinylm16-q8.slm slm_model_q4_artifact: tinyrustlm/models/tinylm16-q4.slm slm_model_bpe_artifact: tinyrustlm/models/tiny-test-model-bpe.slm slm_model_tied_artifact: tinyrustlm/models/tiny-test-model-tied.slm ================================================================================ END FILE: .uai/workspace-guidance.uai ================================================================================ ================================================================================ BEGIN FILE: AGENTS.md BYTES: 2562 SHA256: 267C8DC4B731ACE2F9741BE3E377FF5C7304CE86277537EDA25F48D24545ABDE ================================================================================ # GGUF.MiRust.com Agent Instructions Canonical project root: `E:\Source\Rust\GGUF.MiRust.com`. Read these files before broad local memory loading or source edits: 1. `.uai/startup-packet.uai` 2. `.uai/system-profile.uai` 3. `.uai/workspace-guidance.uai` 4. `.uai/file-handoff.uai` 5. `.uai/long-term-memory.uai` 6. `workspace.uai` This project uses UAIX Project Handoff together with an LLM Wiki/AIWikis long-memory path. Active dropped files live only in `agent-file-handoff/Content/` and `agent-file-handoff/Improvement/`. Do not create `agent-file-handoff/Archive/` as a default resting place. After a safe file is reviewed, used for real project work, and recorded in durable proof-of-use state, preserve the original in the configured AIWikis evidence path with checksums and a manifest, then remove the source-site copy unless the human explicitly keeps that named file active. The LLM Wiki target is AIWikis.org under `/gguf-mirust/`. Local LLM Wiki source files live under `wiki/gguf-mirust/`; local raw evidence stubs live under `raw/gguf-mirust/`. The `.uai/long-term-memory.uai` ledger must stay pointer-only but not context-free. Each pointer needs a stable id, path or route, label, routing-only summary, authority, review state, status, last-reviewed UTC, and checksum when the target is a file. Summaries route agents to what to open next; they do not store durable memory bodies. Rust source rules: - Keep browser automation and model execution behind explicit typed boundaries. - Do not run arbitrary dropped scripts, browser actions, or model files from handoff input. - Keep `unsafe` code out unless the human explicitly approves a bounded design note and review gate. - Target at least 75% automated test coverage for changed code; when coverage tooling is unavailable, record the closest automated evidence and the coverage-tool gap. - Every method/function parameter added or changed should have related automated test coverage that exercises behavior influenced by that parameter. - New test files should mirror the source filename with `test` appended before the extension using a toolchain-safe form such as `adapter_family_test.rs` for `adapter_family.rs` or `app_test.js` for `app.js`; keep existing inline Rust tests when they best fit the module. - Each method/function should have a concise explanatory comment or doc comment describing purpose, contract, parameter semantics, or a non-obvious invariant. - Use `C:\Users\AI\.cargo\bin\cargo.exe`, `rustc.exe`, and `rustup.exe` if PATH is not refreshed in the current shell. ================================================================================ END FILE: AGENTS.md ================================================================================ ================================================================================ BEGIN FILE: Cargo.lock BYTES: 353 SHA256: 22402F7BBC0B7969D322D71794D134BC01343B4AFA8F63788E4B6772727F10D1 ================================================================================ # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "tinyrustlm-browser-harness" version = "0.1.0" [[package]] name = "tinyrustlm-local-server" version = "0.1.0" [[package]] name = "tinyrustlm-runtime" version = "0.1.0" [[package]] name = "tinyrustlm-slm-pack" version = "0.1.0" ================================================================================ END FILE: Cargo.lock ================================================================================ ================================================================================ BEGIN FILE: Cargo.toml BYTES: 486 SHA256: 37E5AD8B8D1951DEE7034C849887104F276E5ABA98C39034781A696A19551910 ================================================================================ [workspace] members = [ "tinyrustlm/runtime", "tinyrustlm/tools/browser_harness", "tinyrustlm/tools/local_server", "tinyrustlm/tools/slm_pack", ] resolver = "2" [workspace.package] version = "0.1.0" edition = "2021" license = "Proprietary" authors = ["GGUF.MiRust.com maintainers"] repository = "https://gguf.mirust.com/" [workspace.lints.rust] missing_docs = "deny" unsafe_code = "warn" [profile.release] codegen-units = 1 lto = true opt-level = "z" panic = "abort" ================================================================================ END FILE: Cargo.toml ================================================================================ ================================================================================ BEGIN FILE: docs/aiwikis-routing.md BYTES: 870 SHA256: 36E35102BE3720E17F150CD4A829A6F4D0E5500BA969D1FB59B488438CD74E32 ================================================================================ # AIWikis Routing Plan Reviewed: 2026-06-24 ## Target GGUF.MiRust.com long memory targets AIWikis.org at: - `https://aiwikis.org/gguf-mirust/` - `https://aiwikis.org/gguf-mirust/source-memory-guide/` ## Local Sources - `.uai/`: hot Project Handoff state. - `wiki/gguf-mirust/`: reviewed LLM Wiki source pages for this project. - `raw/gguf-mirust/`: raw evidence manifests and checksums. - `agent-file-handoff/Content` and `agent-file-handoff/Improvement`: active intake buckets. ## Route Rule Site-specific memory belongs under `/gguf-mirust/`. Organization-wide guidance belongs under `/org/`. Do not create ambiguous AIWikis root indexes such as `/files/`, `/concepts/`, or `/reports/` for this project. ## Publication Status The local source namespace exists now. Public AIWikis routes are planned until the WordPress source package is built and deployed. ================================================================================ END FILE: docs/aiwikis-routing.md ================================================================================ ================================================================================ BEGIN FILE: docs/architecture/browser-harness.md BYTES: 1261 SHA256: B01F80EC9FEA52A6B417EEBF302C5EACCCAA0B1C75AACE594177C57289E6D760 ================================================================================ # GGUF.MiRust.com Browser Harness Architecture Reviewed: 2026-06-24 ## Purpose GGUF.MiRust.com is planned as an enterprise Rust mini-browser and browser-based AI harness for GGUF model workflows. The current implementation is a skeleton that defines boundaries before runtime behavior. ## Planned Runtime Areas - GGUF runtime boundary: model inventory, metadata, runtime adapter, and future local inference control. - Mini browser controller: navigation plans, page observation, and browser state capture. - Browser AI harness: orchestration between local model proposals and browser actions after policy review. - Operator surface: local web UI for setup state, diagnostics, and handoff evidence. ## Trust Boundaries No dropped file, model file, web page, prompt, or generated action is trusted as an instruction source. Browser sessions are planned records until a reviewed runtime exists. Future runtime work must keep model output, page content, operator approvals, and source memory as separate authority layers. ## Initial Implementation Boundary The scaffold includes Rust workspace manifests and source files only. It does not load GGUF models, drive a browser, expose a remote API, publish an MCP server, or claim production runtime support. ================================================================================ END FILE: docs/architecture/browser-harness.md ================================================================================ ================================================================================ BEGIN FILE: docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md BYTES: 5560 SHA256: 27150B92CF92D384D166013DC7201D9DD5F8F80684AF3067D3044EE52D83600B ================================================================================ # UAIX File Handoff Memory Strategy Dogfood 2026-06-26 Source: https://uaix.org/en-us/tools/ai-memory-package-wizard/#setup-file-handoff This note records how GGUF.MiRust.com applies the UAIX AI Memory Package Wizard setup path after processing the 2026-06-26 Improvement batch. ## Adopted Strategy - Keep active dropped files only in `agent-file-handoff/Content/` and `agent-file-handoff/Improvement/`. - Preserve reviewed originals under `raw/gguf-mirust/` with SHA256 hashes and a manifest. - Synthesize durable routing pages under `wiki/gguf-mirust/`. - Keep `.uai/long-term-memory.uai` as a pointer ledger with checksums and routing summaries. - Keep `.uai/report-synthesis.uai` and `.uai/short-term-memory.uai` compact enough for cold-start agents to know what durable pages to open. - Clear processed source-site copies only after raw preservation, durable synthesis, hot-memory routing, and ledger updates are complete. ## Project-Specific Addition The 2026-06-26 human request adds `.uai/taboo.uai` as a hot voice-control file. It routes GGUF.MiRust.com public copy toward constructive local model craft, verifiable execution, model lineage, and research momentum. ## 2026-06-27 Refresh The setup-file-handoff route is now recorded as a cycle: scan active buckets, classify source files, record disposition and proof-of-use, preserve reviewed originals with checksums, synthesize durable wiki/report nodes, refresh short-term routing plus long-term checksum pointers, then remove processed source copies or name why they remain active. For model-breeding reports and research notes, the bodies live in raw evidence and wiki pages. `.uai/short-term-memory.uai` carries the current route to those pages, while `.uai/long-term-memory.uai` stays a checksum-bearing pointer ledger. The public-copy voice rule is part of that cycle: model-breeding, mutualist, and tiny-ecology page work should read `.uai/taboo.uai` before publishing wording on GGUF.MiRust.com. ## 2026-06-27 Strategy Tightening Research references are treated like durable report memory: put the body in `wiki/gguf-mirust/research/`, route it from `.uai/report-synthesis.uai` and `.uai/short-term-memory.uai`, and keep `.uai/long-term-memory.uai` as a checksum pointer. Model-breeding concepts should appear across hot `.uai` files as routing rules, implementation boundaries, and next-step prompts, not as copied research bodies. The current model-breeding reference page now adds kinship metrics, sparse-mask breadcrumbs, evolutionary merge recipes, adaptive search, and multi-objective fitness as diverse lanes. Sparse-mask breadcrumbs have first receipt-level form in sparse-delta metadata, parent relatedness has first recipe/receipt/manifest form in parent-pool, sign-merge, and multi-parent candidate records, and multi-objective fitness has a first population-review objective-vector form; the remaining lanes stay planner/reference material until they become compatibility checks, receipts, eval sidecars, or promotion records. ## 2026-06-27 Direct Request Refresh The setup-file-handoff source is now paired with a report pointer audit: current `wiki/gguf-mirust/reports/*.md` pages are all represented in `.uai/long-term-memory.uai`, while `.uai/short-term-memory.uai` exposes the current report indexes, latest browser module-plan report, Model Breeding synthesis, research reference page, this dogfood note, and the long-term pointer ledger. Model Breeding reference routing now names seven diverse lanes: architecture-preserving merge, sparse-lineage, adapter-ecology, population-search, federated/local update, browser-constrained assembly, and UAIX memory strategy. The durable research page carries the body; hot `.uai` files carry routing, boundaries, and next-step prompts. GGUF.MiRust.com public-copy work routes through `.uai/taboo.uai`, using proof, craft, lineage, fit, local agency, and implementation evidence as the site voice. ## 2026-06-28 Setup File Handoff Refresh The setup-file-handoff source is now applied as an agent-startup loop for this workspace: open the project root, scan `agent-file-handoff/Content/` and `agent-file-handoff/Improvement/`, preserve reviewed bodies under raw/wiki memory, refresh hot `.uai` routing, and keep `.uai/long-term-memory.uai` as checksum-bearing pointers. Report bodies stay in durable Markdown and raw evidence. `.uai/short-term-memory.uai` names the report indexes, latest browser proof reports, durable research page, this strategy dogfood note, site voice file, active bucket scan, and long-term pointer ledger so a cold-start agent can decide what to open next. Model Breeding concepts now route through the research page as diverse lanes: architecture-preserving merges, sparse lineage, adapter ecology, population search, local update recipes, browser-constrained assembly, UAIX memory strategy, heritable artifacts, mate selection, phenotype evidence, and fit boundaries. The durable page carries the body; hot `.uai` files carry the routing and next-step prompts. The public-copy voice rule remains local to GGUF.MiRust.com: Model Breeding and UAIX strategy copy should read as route, lineage, proof, fit, local agency, and implementation evidence. ## Dogfood Result The active model-breeding reports became a new durable intake, a model-breeding synthesis page, a research reference page, and hot `.uai` routes. This keeps the UAIX setup practical: raw evidence remains exact, long-term memory stays pointer-shaped, and short-term memory points future agents to the right durable node. ================================================================================ END FILE: docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md ================================================================================ ================================================================================ BEGIN FILE: docs/dogfood/uaix-llm-wiki-crawlability-failure-2026-06-25.md BYTES: 3386 SHA256: C1E2C6873ACB37BAC3188785B5D24A9DA7B2AB6006A07167629C39DC7B6788A3 ================================================================================ # UAIX And LLM Wiki Crawlability Dogfood 2026-06-25 ## Trigger During GGUF.MiRust.com report intake, 23 reports were preserved into raw evidence and synthesized into durable LLM Wiki Markdown. The first pass kept `.uai/long-term-memory.uai` pointer-only and created useful wiki files, but under-populated typed `.uai` files. The human correctly flagged that the report intelligence had not really made it into the active `.uai` memory layer. ## Failure The system treated "do not store durable report bodies in `.uai/long-term-memory.uai`" as if it also meant "keep `.uai` thin." That is wrong. Pointer-only does not mean hot-memory-poor. A strong UAIX project needs both: - durable wiki/docs files for reviewed long-form memory - typed `.uai` synthesis files that make the durable memory crawlable, triageable, and actionable from startup ## Why The Wiki Felt Weak The wiki was durable but not sufficiently crawlable from agent startup. A cold agent could see that report files existed, but it still had to open too much Markdown to understand: - what themes the reports covered - which reports duplicated each other - which recommendations were forbidden by the active TinyRustLM prompt - which ideas should influence architecture now - which ideas were only future comparison pressure - which next tests or invariants the reports implied That makes the wiki feel like storage, not operational memory. ## Guidance To Feed Back To UAIX.org UAIX and LLM Wiki setup guidance should require a three-layer memory handoff for report batches: 1. Raw evidence preservation with checksums. 2. Durable thematic wiki/docs synthesis. 3. Hot typed `.uai` synthesis that tells agents what to do with the durable memory. The third layer is the missing piece. It should be required, not optional. ## Proposed UAIX Rule Text When processing a report batch, `.uai/long-term-memory.uai` must remain pointer-only, but the project must also populate typed hot-memory files with routing summaries, distilled constraints, current implementation relevance, rejected recommendations, next testable invariants, and dogfood findings. A future agent should be able to choose the next three files to open from `.uai` alone. ## Proposed LLM Wiki Crawlability Requirements - Every durable wiki report cluster needs a hot `.uai` synthesis route. - The hot synthesis must include source count, duplicate groups, theme clusters, authority boundaries, and immediate next actions. - Durable wiki pages should include "Use this when..." routing text near the top. - Report-derived recommendations that conflict with active constraints must be marked as future comparison or quarantined guidance. - The setup wizard should ask whether the project needs a hot `.uai` synthesis file, not merely a long-term pointer ledger. - The validator should flag report batches that create wiki files but do not update typed `.uai` summaries. ## Dogfooded Correction In This Repository The correction added: - `.uai/report-synthesis.uai` - enriched `.uai/architecture.uai` - enriched `.uai/coding-standards.uai` - corrected `.uai/operations.uai` - updated `.uai/startup-packet.uai` - updated `.uai/index.uai` - updated `.uai/workspace-guidance.uai` The durable wiki remains useful, but `.uai` now carries enough report-derived operating memory for a cold agent to route intelligently before deep-loading Markdown. ================================================================================ END FILE: docs/dogfood/uaix-llm-wiki-crawlability-failure-2026-06-25.md ================================================================================ ================================================================================ BEGIN FILE: docs/dogfood/uaix-llmwikis-setup-experience-2026-06-24.md BYTES: 1680 SHA256: D587B2E9273AFB2B88F660CCD69EAE5AF0F3692DBC3BD76716A00E6A04663C30 ================================================================================ # UAIX And LLMWikis Setup Dogfood Date: 2026-06-24 Project: GGUF.MiRust.com ## What Worked The combined UAIX File Handoff plus LLM Wiki pattern cleanly separates active intake, hot `.uai` memory, pointer-only long-memory routing, and durable wiki content. The LLMWikis setup guidance is also clear that AIWikis-style public routes need explicit site namespaces. ## Dogfood Improvements 1. The combined setup output should include a checklist item for public discovery when the target is AIWikis: create or update the site-directory/front-page listing, source-memory guide route, and route description before treating a new namespace as discoverable. 2. The wizard should distinguish planned remote routes from local file targets. A remote AIWikis pointer may be `planned_pending_publication`; file targets still need checksums. 3. Code-bearing project scaffolds need a first-pass architecture pointer and coding-standards pointer in the same setup packet, because agents otherwise create memory files without the implementation boundary. 4. The LLM Wiki setup packet should name the local source namespace and public namespace together, for example `wiki/gguf-mirust/` publishes to `/gguf-mirust/`. 5. The File Handoff proof gate should keep saying "source-site removal or keep-active reason" because it prevented creation of a duplicate `Archive` resting place. ## Applied Locally - Created `.uai/file-handoff.uai` with Content and Improvement buckets only. - Created `.uai/long-term-memory.uai` as a pointer-only routing ledger. - Created local LLM Wiki source files under `wiki/gguf-mirust/`. - Created AIWikis route plan documentation under `docs/aiwikis-routing.md`. ================================================================================ END FILE: docs/dogfood/uaix-llmwikis-setup-experience-2026-06-24.md ================================================================================ ================================================================================ BEGIN FILE: docs/visual-studio.md BYTES: 4387 SHA256: 4EB9659BEBD8C33799A384DEE81415BCCB13304F2D2E67CFDC1A3D0D9976ABDB ================================================================================ # Visual Studio Setup Open `TinyRustLM.sln` from the repository root in Visual Studio 2022. Required local tools: - Visual Studio 2022 with the Desktop development with C++ workload, for NMake project support. - Rust toolchain with `cargo` and `rustup`. - Node.js, used only for JavaScript execution smoke tools. Visual Studio F5, static app contract checks, and local route checks use no-crate Rust tools built by Cargo. The solution contains one NMake project named `TinyRustLM`. Visual Studio does not compile Rust directly; it invokes the checked-in PowerShell scripts under `tools/vs/`, which call Cargo and the local static server. ## Build Use `Build > Build Solution`. The build script: - Ensures the `wasm32-unknown-unknown` target is installed. - Runs `cargo build --workspace`. - Builds the release WASM runtime. - Copies `target/wasm32-unknown-unknown/release/tinyrustlm_runtime.wasm` to `tinyrustlm/runtime/tinyrustlm.wasm`. - Ensures the local `.slm` model artifacts and `.slm.manifest` provenance sidecars exist, including TinyLM-16M f32, q8_0, q4_0, the BPE fixture, and the tied-output fixture. - Keeps the generated WASM and local model files in the locations used by the static browser app and smoke tests. ## Run Use `Debug > Start Debugging` or press `F5`. Visual Studio runs `tools/vs/Run-TinyRustLM.ps1`, which builds if needed, starts the Rust local static server, and opens: ```text http://127.0.0.1:8080/app/ ``` The run script checks whether the selected port is already serving TinyRustLM by loading `/app/` and probing `/runtime/tinyrustlm.wasm`. If that verified app is already running, F5 reuses it and opens the browser. If the port is occupied by another local service, the script checks the next ports and starts `target\debug\tinyrustlm-local-server.exe` on the first free loopback port. Useful run options: ```powershell .\tools\vs\Run-TinyRustLM.ps1 -NoBuild .\tools\vs\Run-TinyRustLM.ps1 -Port 8090 -PortSearchLimit 10 .\tools\vs\Run-TinyRustLM.ps1 -NoBrowser ``` Stop debugging to stop the foreground server when the script starts one. ## Test From a PowerShell terminal at the repository root: ```powershell .\tools\vs\Test-TinyRustLM.ps1 ``` The default test path builds the workspace, runs Cargo tests, checks handwritten JavaScript syntax, runs the Rust mini browser harness over the static app contract, validates every local `.slm` artifact with the native packer admission gate, validates each `.slm.manifest` provenance sidecar, validates the BPE and tied-output fixture routes, validates the tiny raw-f32 trained-source fixture, converts it into f32, q8_0, and q4_0 `.slm` artifacts, gates each converted artifact for `runtime-smoke`, runs `tinyrustlm-eval` over the scoped fixture cases for each converted mode, gates each eval sidecar for fixture-scoped `assistant-quality`, generates a tied-output source fixture, validates `tied_output=true` without `output.weight`, converts the tied source into f32, q8_0, and q4_0 artifacts, gates each tied converted artifact for `runtime-smoke`, generates a BPE source fixture, validates `tokenizer=bpe-v1` plus token and merge metadata, converts the BPE source into q8_0, gates that converted artifact for `runtime-smoke`, and runs the WASM ABI smoke for invalid UTF-8 prompt bytes, null pointers, invalid lengths, and recovery generation. To include headless browser smoke for q8_0 and q4_0: ```powershell .\tools\vs\Test-TinyRustLM.ps1 -BrowserSmoke ``` That browser path also runs the Rust mini browser harness against the loopback server, then runs loop, malformed local model, context-overflow, missing-model, endurance, benchmark-panel performance smoke, Step Token click-through smoke, and the desktop/mobile UI audit. Like the F5 runner, it reuses a verified TinyRustLM server or starts on the first free loopback port from the requested browser-smoke port. ```powershell .\tools\vs\Test-TinyRustLM.ps1 -BrowserSmoke -BrowserSmokePort 8090 -PortSearchLimit 10 ``` For a heavier repeated benchmark-panel check: ```powershell .\tools\vs\Test-TinyRustLM.ps1 -PerformanceSoak -PerformanceSoakCycles 3 -PerformanceSoakTokens 4 ``` `-PerformanceSoak` repeats multi-token q8_0 and q4_0 generation across cycles and checks deterministic output, prompt/generated counts, KV length, positive host-side token speed, scratch bytes, reset recovery, and local-only requests. ================================================================================ END FILE: docs/visual-studio.md ================================================================================ ================================================================================ BEGIN FILE: README.md BYTES: 29564 SHA256: 3A1AF7CA83E518DC78F792ED2BA8E1637D4E25AFA62D7C2A11360FDEAFC0782A ================================================================================ # GGUF.MiRust.com Canonical Rust source root for the GGUF.MiRust.com client-side SLM runtime and browser UI. The active implementation target is `tinyrustlm/`: a 100% custom Rust/WASM browser-local AI app named TinyRustLM. The runtime is zero-dependency by design: no third-party Rust crates, no JavaScript frameworks, no tokenizer libraries, no inference frameworks, no package-manager runtime, no remote inference API, and no CDN dependency. ## Active Workspace - `TinyRustLM.sln`: Visual Studio 2022 solution wrapper for building and running the Rust/WASM app through NMake. - `tinyrustlm/app/`: static browser UI with handwritten HTML, CSS, JavaScript, local-only notice, local conversation transcript, diagnostics, benchmark panels, Step Token console control, Adapter Sidecar control, developer console, and product footer. - `tinyrustlm/runtime/`: no-crate Rust runtime for WASM exports, memory transfer, `.slm` parsing, f32/q8_0/q4_0 `ADP1`, `ASP1`, and `ALR1` adapter apply, tokenizer, math kernels, quant helpers, KV cache, sampler, diagnostics, and native eval-case execution. - `tinyrustlm/tools/slm_pack/`: no-crate Rust utility for writing `.slm` files, validating model admission, generating provenance manifests, writing parent compatibility reports, writing candidate lineage templates, running direct-parameter blend, task-delta, sparse task-delta, and sign-aware parent-pool merge operators with receipts, writing raw, sparse, and low-rank task-delta adapter artifacts, fusing validated raw adapters into `.slm` candidates with receipts, writing candidate artifact manifests, writing multi-parent candidate manifests, writing promotion templates, writing multi-parent promotion templates, writing multi-parent selector admission records, writing runtime-smoke sidecars, writing selector admission records, writing promotion ledgers, writing population reviews, writing parent-pool recipes, writing selector registries with optional f32/q8_0/q4_0 adapter sidecar routes, indexed adapter families, and adapter-family receipt handles, writing generated f32/q8_0/q4_0 browser multi-parent bundles, validating raw trained-source layouts, converting source weights with byte, BPE, and tied-output metadata, creating pending evaluation templates, and enforcing quality gates. - `tinyrustlm/tools/local_server/`: no-crate Rust static server for local browser hosting, Visual Studio F5, and browser-smoke startup. - `tinyrustlm/tools/browser_harness/`: no-crate Rust mini browser contract harness for static app crawl, local-only asset policy, model/manifest presence, and optional loopback route checks. - `tinyrustlm/docs/`: architecture, `.slm`, tokenizer, quantization, browser runtime, testing, and performance notes. - `tinyrustlm/tests/fixtures/`: small text fixtures for runtime tests. - `.uai/`: hot Project Handoff memory and routing state. - `wiki/gguf-mirust/`: local LLM Wiki source namespace for AIWikis publication. - `agent-file-handoff/Content` and `agent-file-handoff/Improvement`: active intake buckets only. ## Current Status TinyRustLM now implements the static browser shell, WASM memory boundary, byte tokenizer, custom BPE tokenizer path, `.slm` parser, core math, one-layer tiny transformer forward pass, greedy generation, generated WASM artifact, generated tiny `.slm` models, and passing tests. TinyLM-16M-shaped deterministic smoke models are verified for f32, q8_0, and q4_0, the tiny BPE fixture proves a custom `BPE1` `.slm` tokenizer through runtime diagnostics, and the tiny tied-output fixture proves omitted `output.weight` only works through the v1 tied-output flag. q8_0 and q4_0 matrix dispatch use direct quantized matvec paths, and quantized tensors no longer keep full decoded f32 shadow copies in runtime memory. Model loading now pre-resolves the top-level and per-layer tensor indices used by generation, so the token loop does not allocate layer-name strings or scan tensors by name, and the runtime routes tied-output projection flags to token embeddings. The runtime can apply compatible raw `ADP1`, sparse `ASP1`, or low-rank `ALR1` f32-delta packages to already loaded f32, q8_0, and q4_0 models after validating package checksum, tensor identity, tokenizer checksum, tensor-layout checksum, finite deltas/factors, and fused values; q8_0/q4_0 apply re-quantizes the touched compact tensors and successful apply clears generation/KV state through the same diagnostics path used by model reload. The browser Adapter Sidecar panel now routes checked local tiny f32, q8_0, and q4_0 self-sidecars through `../models/tiny-test-model-self.adp1`, `../models/tiny-test-model-q8-self.adp1`, and `../models/tiny-test-model-q4-self.adp1`, recomputes the selected ADP1 artifact checksum before WASM transfer, and leaves ADP1 structure validation plus tensor mutation to Rust; generated selector registries can also offer compatible f32/q8_0/q4_0 `.adp1` or `.asp1` routes when the route apply status matches the admitted entry quantization, plus served `.adapter-family.receipt` handles for compatible family sets. Generated result decoding is capped at 64 KiB; byte and BPE decode paths return `OutputBufferExceeded` before replacing `last_result`, and full `generate` failures clear stale generation state. The browser UI records each local user/assistant turn in an in-page conversation transcript; Reset clears runtime context and output while Clear empties only the transcript. The browser UI also exposes a Step Token control that calls `generate_next_token` after a successful generation, appends the token to the response and transcript, and keeps the console plus benchmark diagnostics current. The browser can optionally read a local `models/selector.registry` file and populate the model selector only from admitted `../models/*.slm` registry entries, while falling back to the checked-in smoke models when no registry is present; browser smoke now serves a multi-parent registry fixture for `multi-parent-sign-merge-q8`, applies the checked f32/q8_0/q4_0 adapter sidecars, applies an intercepted registry-supplied q8_0 adapter route, runs generated bundles for `multi-parent-sign-merge-f32`, `multi-parent-sign-merge-q8`, and `multi-parent-sign-merge-q4` whose app shell, WASM runtime, selector registry, `.slm`, manifest, adapter sidecars, adapter manifests, assembly receipt, evidence files, and adapter-family receipt are served as real files, and applies the generated registry-supplied sparse ASP1 adapter-family sidecar for each quantization. The headless browser harness verifies generation, step-token continuation, adapter sidecar apply, registry adapter-family apply, transcript entries, error recovery, benchmark panels, local-only requests, and desktop/mobile UI structure. Each local model now has a `.slm.manifest` provenance sidecar that marks these artifacts as deterministic smoke models, not trained-quality assistants. The packer has a raw-f32 trained-source layout, source-weight validator, parent compatibility report command, candidate lineage template command, direct-parameter `blend-candidate`, `delta-candidate`, and `sparse-delta-candidate` operators with recomputable receipt validation, `adapter-delta`, `sparse-adapter-delta`, and `low-rank-adapter-delta` artifacts with recomputable manifests, `fuse-adapter-delta` candidates with recomputable receipts, candidate artifact manifest command, multi-parent candidate manifest command, promotion-template command, multi-parent-promotion-template command, multi-parent-admission-record command, runtime-smoke sidecar command, selector admission record command, promotion-ledger command, population-review command, parent-pool-recipe command, sign-aware `sign-merge-candidate` command, selector-registry command with optional f32/q8_0/q4_0 adapter-family and receipt fields, `browser-multi-parent-bundle` command, and `convert-trained` command that can emit f32/q8_0/q4_0 `.slm` artifacts with converted-trained provenance. Blend, task-delta, sparse task-delta, and sign-merge receipts bind parent checksums, operator inputs, candidate checksum, and the produced `.slm`; sparse receipts additionally record selection metric, keep rate, total parameter count, nonzero deltas, selected entries, pruned/unchanged entries, density and nonzero-delta retention ppm, and an implicit top-k mask checksum, while sign-merge receipts bind parent-pool recipe checksum, relatedness metric/scope/pair count/checksum, ledger/review/admission checksums, seed weights, sign-vote counts, and the multi-parent candidate manifest gate. Raw adapter-delta manifests bind the same parent and lineage contracts to a runtime-eligible or fuseable `ADP1` raw f32 task-delta package; sparse adapter-delta manifests bind those contracts to runtime-eligible `ASP1` sparse f32 task-delta packages with density, retention, and mask checksum fields; low-rank adapter-delta manifests bind them to runtime-eligible `ALR1` factor packages with component limit, matrix tensor count, factor density, and residual L1 fields; adapter-family receipts bind compatible f32/q8_0/q4_0 ADP1/ASP1 sidecar manifests into one selector-carried assembly menu; adapter-fuse receipts validate a raw adapter package and produce a normal `.slm` candidate for the existing candidate-manifest path; candidate artifact manifests then bind validated lineage to a validated `.slm` output; multi-parent candidate manifests bind validated sign-merge output to its receipt checksum, relatedness summary, and pending promotion route; multi-parent promotion templates bind that sign-merge manifest checksum and receipt checksum before runtime-smoke/eval proof; multi-parent admission records bind that promotion template with runtime-smoke and eval evidence; runtime-smoke sidecars bind local execution proof to provenance; selector admission records bind promotion plus passed eval evidence; promotion ledgers chain admitted candidate history; population reviews rank admitted candidates into frontier and parent-pool routes with explicit quality/frugality/quantization objective-vector fields and per-entry objective checksums; parent-pool recipes bind shared direct-parameter contracts, relatedness identity, and normalized seed weights from those reviews; sign-merge receipts write offline multi-parent candidates from those recipes; and selector registries now bind both selector admission records and multi-parent admission records into browser-safe model routes before selector changes. The trained-source lane supports byte tokenizer metadata, `BPE1` token and merge metadata, and explicit tied-output source manifests, including q8_0 BPE source conversion and f32/q8_0/q4_0 tied-output conversion gates. The runtime has a native eval runner that executes scoped fixture cases and writes a quality-gate sidecar. The Visual Studio test helper gates every converted fixture mode, including tied-output source conversion, BPE source conversion for runtime smoke, generated f32/q8_0/q4_0 browser bundle routing, and generated registry adapter-family apply, so f32, q8_0, q4_0, tokenizer metadata, output-head layout, and local adapter routing cannot drift silently. The quality gate remains strict: deterministic smoke and converted-trained artifacts can pass `runtime-smoke`, while `assistant-quality` requires passed task-evaluation evidence and a declared quality scope. For generated selector entries, the browser now fetches the served `.module-plan.receipt` before generated model bytes, recomputes its text checksum, and matches its resource class, admitted model byte budget, adapter-family byte budget, model, manifest, assembly receipt, adapter-family receipt, and adapter-stack members against selector metadata. For generated adapter families, the browser fetches the served `.adapter-family.receipt` and each served `.adp1.manifest` or `.asp1.manifest`, recomputes their text checksums, and matches the sidecar route, manifest route, label, apply status, artifact checksum, manifest checksum, manifest byte count, route-derived artifact format, and shared base-quantization identity fields before enabling the registry-supplied family options. The receipt also declares an ordered auto-apply stack; JavaScript checks stack indexes, paths, manifest paths, and aggregate byte budget before fetching and transferring the family ADP1 plus sparse ASP1 packages. Rust still owns package validation and tensor mutation after transfer. ## Intended Commands Run these once a Rust toolchain is installed or exposed: ```powershell cargo fmt --all cargo test --workspace cargo rustdoc -p tinyrustlm-runtime --lib -- -D missing_docs cargo rustdoc -p tinyrustlm-slm-pack --bin tinyrustlm-slm-pack -- -D missing_docs cargo rustdoc -p tinyrustlm-local-server --bin tinyrustlm-local-server -- -D missing_docs cargo rustdoc -p tinyrustlm-browser-harness --bin tinyrustlm-browser-harness -- -D missing_docs rustup target add wasm32-unknown-unknown cargo build -p tinyrustlm-runtime --release --target wasm32-unknown-unknown Copy-Item .\target\wasm32-unknown-unknown\release\tinyrustlm_runtime.wasm .\tinyrustlm\runtime\tinyrustlm.wasm cargo run -p tinyrustlm-slm-pack -- runtime-wasm-manifest .\tinyrustlm\runtime\tinyrustlm.wasm .\tinyrustlm\runtime\tinyrustlm.wasm.manifest cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tiny-test-model.slm tiny-fixture cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tiny-test-model-bpe.slm tiny-fixture-bpe cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tiny-test-model-tied.slm tiny-fixture-tied cargo run -p tinyrustlm-slm-pack -- validate-manifest .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm.manifest cargo run -p tinyrustlm-slm-pack -- compatibility .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-self.compat cargo run -p tinyrustlm-slm-pack -- lineage-template .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage tinylm16-q8-self-candidate identity-parent-set browser-local-16m-budget cargo run -p tinyrustlm-slm-pack -- validate-lineage .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage cargo run -p tinyrustlm-slm-pack -- blend-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.operator cargo run -p tinyrustlm-slm-pack -- validate-blend-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.operator cargo run -p tinyrustlm-slm-pack -- delta-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-delta.slm .\target\model-breeding\tinylm16-q8-delta.operator 1000000 cargo run -p tinyrustlm-slm-pack -- validate-delta-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-delta.slm .\target\model-breeding\tinylm16-q8-delta.operator cargo run -p tinyrustlm-slm-pack -- sparse-delta-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-sparse-delta.slm .\target\model-breeding\tinylm16-q8-sparse-delta.operator 1000000 250000 cargo run -p tinyrustlm-slm-pack -- validate-sparse-delta-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-sparse-delta.slm .\target\model-breeding\tinylm16-q8-sparse-delta.operator cargo run -p tinyrustlm-slm-pack -- adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.delta .\target\model-breeding\tinylm16-q8.adapter.delta.manifest cargo run -p tinyrustlm-slm-pack -- validate-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.delta .\target\model-breeding\tinylm16-q8.adapter.delta.manifest cargo run -p tinyrustlm-slm-pack -- sparse-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.sparse.asp1 .\target\model-breeding\tinylm16-q8.adapter.sparse.asp1.manifest 1000000 250000 cargo run -p tinyrustlm-slm-pack -- validate-sparse-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.sparse.asp1 .\target\model-breeding\tinylm16-q8.adapter.sparse.asp1.manifest cargo run -p tinyrustlm-slm-pack -- low-rank-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.lowrank.alr1 .\target\model-breeding\tinylm16-q8.adapter.lowrank.alr1.manifest 1 cargo run -p tinyrustlm-slm-pack -- validate-low-rank-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.lowrank.alr1 .\target\model-breeding\tinylm16-q8.adapter.lowrank.alr1.manifest cargo run -p tinyrustlm-slm-pack -- fuse-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.delta .\target\model-breeding\tinylm16-q8.adapter.delta.manifest .\target\model-breeding\tinylm16-q8-adapter-fused.slm .\target\model-breeding\tinylm16-q8-adapter-fuse.operator cargo run -p tinyrustlm-slm-pack -- validate-fuse-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.delta .\target\model-breeding\tinylm16-q8.adapter.delta.manifest .\target\model-breeding\tinylm16-q8-adapter-fused.slm .\target\model-breeding\tinylm16-q8-adapter-fuse.operator cargo run -p tinyrustlm-slm-pack -- sign-merge-candidate .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- validate-sign-merge-candidate .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- multi-parent-candidate-manifest .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- validate-multi-parent-candidate .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- multi-parent-promotion-template .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate .\target\model-breeding\parent-pool-sign-merge.promotion --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- validate-multi-parent-promotion .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate .\target\model-breeding\parent-pool-sign-merge.promotion --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- multi-parent-admission-record .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate .\target\model-breeding\parent-pool-sign-merge.promotion .\target\model-breeding\parent-pool-sign-merge.slm.manifest .\target\model-breeding\parent-pool-sign-merge.runtime .\target\model-breeding\parent-pool-sign-merge.eval .\target\model-breeding\parent-pool-sign-merge.multi.admission --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- validate-multi-parent-admission .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate .\target\model-breeding\parent-pool-sign-merge.promotion .\target\model-breeding\parent-pool-sign-merge.slm.manifest .\target\model-breeding\parent-pool-sign-merge.runtime .\target\model-breeding\parent-pool-sign-merge.eval .\target\model-breeding\parent-pool-sign-merge.multi.admission --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-multi-parent\tinyrustlm cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-multi-parent-q8\tinyrustlm q8_0 cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-multi-parent-q4\tinyrustlm q4_0 cargo run -p tinyrustlm-slm-pack -- candidate-manifest .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-self.candidate cargo run -p tinyrustlm-slm-pack -- validate-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-self.candidate cargo run -p tinyrustlm-slm-pack -- promotion-template .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-self.candidate .\target\model-breeding\tinylm16-q8-self.promotion local-smoke-runner browser-local-runtime-smoke-and-eval cargo run -p tinyrustlm-slm-pack -- validate-promotion .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-self.candidate .\target\model-breeding\tinylm16-q8-self.promotion cargo run -p tinyrustlm-slm-pack -- manifest .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.slm.manifest deterministic-smoke cargo run -p tinyrustlm-slm-pack -- quality-gate .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.slm.manifest runtime-smoke cargo run -p tinyrustlm-slm-pack -- runtime-smoke .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.slm.manifest .\target\model-breeding\tinylm16-q8-blend.runtime cargo run -p tinyrustlm-slm-pack -- validate-source .\tinyrustlm\tests\fixtures\trained-source-tiny cargo run -p tinyrustlm-slm-pack -- convert-trained .\tinyrustlm\tests\fixtures\trained-source-tiny .\target\trained-source-smoke\tiny-converted-f32.slm f32 cargo run -p tinyrustlm-slm-pack -- convert-trained .\tinyrustlm\tests\fixtures\trained-source-tiny .\target\trained-source-smoke\tiny-converted-q8.slm q8_0 cargo run -p tinyrustlm-slm-pack -- convert-trained .\tinyrustlm\tests\fixtures\trained-source-tiny .\target\trained-source-smoke\tiny-converted-q4.slm q4_0 cargo run -p tinyrustlm-slm-pack -- source-template .\target\trained-source-smoke\source-tiny-tied tiny-fixture-tied cargo run -p tinyrustlm-slm-pack -- validate-source .\target\trained-source-smoke\source-tiny-tied cargo run -p tinyrustlm-slm-pack -- convert-trained .\target\trained-source-smoke\source-tiny-tied .\target\trained-source-smoke\tiny-tied-converted-q8.slm q8_0 cargo run -p tinyrustlm-slm-pack -- source-template .\target\trained-source-smoke\source-tiny-bpe tiny-fixture-bpe cargo run -p tinyrustlm-slm-pack -- validate-source .\target\trained-source-smoke\source-tiny-bpe cargo run -p tinyrustlm-slm-pack -- convert-trained .\target\trained-source-smoke\source-tiny-bpe .\target\trained-source-smoke\tiny-bpe-converted-q8.slm q8_0 cargo run -p tinyrustlm-slm-pack -- runtime-smoke .\target\trained-source-smoke\tiny-converted-q8.slm .\target\trained-source-smoke\tiny-converted-q8.slm.manifest .\target\trained-source-smoke\tiny-converted-q8.runtime cargo run -p tinyrustlm-runtime --bin tinyrustlm-eval -- .\target\trained-source-smoke\tiny-converted-q8.slm .\target\trained-source-smoke\tiny-converted-q8.slm.manifest .\tinyrustlm\tests\fixtures\assistant-quality-eval-cases.txt .\target\trained-source-smoke\tiny-converted-q8.eval cargo run -p tinyrustlm-slm-pack -- quality-gate .\target\trained-source-smoke\tiny-converted-q8.slm .\target\trained-source-smoke\tiny-converted-q8.slm.manifest assistant-quality .\target\trained-source-smoke\tiny-converted-q8.eval cargo run -p tinyrustlm-slm-pack -- eval-template .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm.manifest .\tinyrustlm\models\tinylm16-q8.slm.eval assistant-quality cargo run -p tinyrustlm-browser-harness -- .\tinyrustlm cargo run -p tinyrustlm-local-server -- .\tinyrustlm 8080 ``` Then serve the static app with the checked-in no-crate Rust static server: ```powershell cargo run -p tinyrustlm-local-server -- .\tinyrustlm 8080 ``` Visual Studio 2022: ```text Open TinyRustLM.sln, then Build Solution and press F5. ``` F5 reuses an already-running TinyRustLM server only after checking the app page and WASM route. If port 8080 is occupied by another local service, the run helper walks to the next free loopback port. See `docs/visual-studio.md` for the exact prerequisites and helper scripts. ## Memory Setup UAIX Project Handoff is active through `.uai/`, following the setup flow at `https://uaix.org/en-us/tools/ai-memory-package-wizard/#setup-file-handoff`. LLM Wiki long memory targets AIWikis.org under `https://aiwikis.org/gguf-mirust/`, with local source records in `wiki/gguf-mirust/`. Hot `.uai` files keep current routing, synthesis, and proof-of-use pointers. Durable report bodies belong in Markdown/wiki files and raw evidence manifests, not inside `.uai/long-term-memory.uai`; the long-term memory ledger stays pointer-only, checksum-bearing, and routing-only. ================================================================================ END FILE: README.md ================================================================================ ================================================================================ BEGIN FILE: TinyRustLM.sln BYTES: 1357 SHA256: 587E1C3FC6D2CF1113CEF11FC8013B7DE2A5B9C956C4E5026930F2DCB60E203D ================================================================================ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 MinimumVisualStudioVersion = 10.0.40219.1 Project("{BC8A1FFA-BEE3-4634-8014-F334798102B3}") = "TinyRustLM", "TinyRustLM.vcxproj", "{5F218392-55C5-4D0E-81C1-3D824C188B8F}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{B0852B40-F207-4E3B-8CB6-B949570EA2D0}" ProjectSection(SolutionItems) = preProject AGENTS.md = AGENTS.md Cargo.toml = Cargo.toml README.md = README.md workspace.uai = workspace.uai EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {5F218392-55C5-4D0E-81C1-3D824C188B8F}.Debug|x64.ActiveCfg = Debug|x64 {5F218392-55C5-4D0E-81C1-3D824C188B8F}.Debug|x64.Build.0 = Debug|x64 {5F218392-55C5-4D0E-81C1-3D824C188B8F}.Release|x64.ActiveCfg = Release|x64 {5F218392-55C5-4D0E-81C1-3D824C188B8F}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {6C1CA7F4-1C36-4AF9-BB54-086F9C7D4BE9} EndGlobalSection EndGlobal ================================================================================ END FILE: TinyRustLM.sln ================================================================================ ================================================================================ BEGIN FILE: TinyRustLM.vcxproj BYTES: 4580 SHA256: BD821C48B395AFA3DA5E23667A004F318FAAB5C4C58D68438E54208E41CC2A46 ================================================================================ Debug x64 Release x64 17.0 MakeFileProj {5F218392-55C5-4D0E-81C1-3D824C188B8F} TinyRustLM TinyRustLM Makefile true v145 Makefile false v145 powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$(ProjectDir)tools\vs\Build-TinyRustLM.ps1" -Configuration Debug powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$(ProjectDir)tools\vs\Build-TinyRustLM.ps1" -Configuration Debug -Clean powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$(ProjectDir)tools\vs\Build-TinyRustLM.ps1" -Configuration Debug -CleanOnly $(ProjectDir)tinyrustlm\runtime\tinyrustlm.wasm powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$(ProjectDir)tools\vs\Run-TinyRustLM.ps1" $(ProjectDir) powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$(ProjectDir)tools\vs\Build-TinyRustLM.ps1" -Configuration Release powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$(ProjectDir)tools\vs\Build-TinyRustLM.ps1" -Configuration Release -Clean powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$(ProjectDir)tools\vs\Build-TinyRustLM.ps1" -Configuration Release -CleanOnly $(ProjectDir)tinyrustlm\runtime\tinyrustlm.wasm powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$(ProjectDir)tools\vs\Run-TinyRustLM.ps1" $(ProjectDir) ================================================================================ END FILE: TinyRustLM.vcxproj ================================================================================ ================================================================================ BEGIN FILE: TinyRustLM.vcxproj.filters BYTES: 4251 SHA256: 777DC2745E5E0FA474E8D62A777D5B399CE28403998AED54F6D12FDC4F89A5FE ================================================================================ {344BBA8C-49E4-4C3A-8A62-D6E838DA5F52} {9E606E14-E8CF-4D8C-B45B-55947164042D} {2EC5A78A-4AF5-4CBF-BF72-0FBB3C934B87} {E142F4C1-8FE9-4B18-94E1-02D695C8D366} {D5034D0D-A9EC-406A-B2DB-B9B2AE442E0F} {0C12334E-02C4-41F4-828A-5A3026C1C318} {6CF2F4F1-C7D1-477A-A50B-9F3DA76AAFF7} {ACD1D5B3-CBE0-4D93-BA6D-9C5F21ED73E5} Root Root Root Root Root App App App Runtime Runtime SLM Packer SLM Packer Rust Local Server Rust Local Server Rust Browser Harness Rust Browser Harness Tools Tools Visual Studio ================================================================================ END FILE: TinyRustLM.vcxproj.filters ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/app/app.css BYTES: 4335 SHA256: 23F9A7A9D555718DEB9DEDF4862935AAC811CC6FD90EEFFE9168FA5CBAF1FAFF ================================================================================ :root { color-scheme: dark; --bg: #101216; --panel: #181c22; --panel-strong: #202732; --text: #edf2f7; --muted: #a8b3c4; --line: #313946; --accent: #6ee7d8; --danger: #ff6b6b; } * { box-sizing: border-box; } body { margin: 0; min-height: 100vh; background: var(--bg); color: var(--text); font: 15px/1.5 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; } .shell { width: min(1180px, calc(100% - 32px)); margin: 0 auto; padding: 28px 0; } .topbar { display: flex; align-items: center; justify-content: space-between; gap: 18px; padding-bottom: 18px; border-bottom: 1px solid var(--line); } .eyebrow { margin: 0 0 2px; color: var(--accent); font-size: 12px; text-transform: uppercase; } h1, h2 { margin: 0; letter-spacing: 0; } h1 { font-size: 30px; } h2 { font-size: 16px; } .status, .notice, .panel { border: 1px solid var(--line); background: var(--panel); border-radius: 8px; } .status { padding: 8px 12px; color: var(--muted); background: var(--panel-strong); } .notice { margin: 18px 0; padding: 12px 14px; color: var(--text); } .grid { display: grid; grid-template-columns: minmax(280px, 1fr) minmax(280px, 1fr); gap: 14px; } .panel { min-width: 0; padding: 16px; } .footnote { display: flex; flex-wrap: wrap; gap: 10px 18px; align-items: center; justify-content: space-between; margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--line); color: var(--muted); font-size: 13px; } .chat, .output, .transcript { min-height: 310px; } label { display: block; margin-bottom: 8px; color: var(--muted); } textarea { width: 100%; resize: vertical; min-height: 170px; color: var(--text); background: #0c0f13; border: 1px solid var(--line); border-radius: 6px; padding: 12px; font: inherit; } select { width: 100%; min-height: 38px; color: var(--text); background: #0c0f13; border: 1px solid var(--line); border-radius: 6px; padding: 0 10px; font: inherit; } .settings { display: grid; grid-template-columns: minmax(100px, 140px) minmax(90px, 1fr); align-items: end; gap: 10px; margin-top: 12px; } .decoding { display: grid; grid-template-columns: minmax(92px, 120px) minmax(72px, 1fr); align-items: center; gap: 10px; margin: 12px 0 0; padding: 12px; border: 1px solid var(--line); border-radius: 8px; } .decoding legend { padding: 0 6px; color: var(--muted); } .decoding label { margin-bottom: 0; } input[type="number"] { width: 100%; min-height: 38px; color: var(--text); background: #0c0f13; border: 1px solid var(--line); border-radius: 6px; padding: 0 10px; font: inherit; } .actions { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 12px; } button { min-height: 38px; padding: 0 14px; border: 0; border-radius: 6px; color: #031211; background: var(--accent); font-weight: 700; cursor: pointer; } button:disabled { cursor: not-allowed; opacity: .45; } button + button { color: var(--text); background: var(--panel-strong); border: 1px solid var(--line); } .messages { display: grid; gap: 10px; max-height: 260px; margin: 10px 0 0; padding: 0; overflow: auto; list-style: none; } .message { display: grid; gap: 4px; padding: 10px 12px; border: 1px solid var(--line); border-radius: 6px; background: #0c0f13; } .message-role { color: var(--accent); font-size: 12px; font-weight: 700; text-transform: uppercase; } .message-text { color: var(--text); white-space: pre-wrap; overflow-wrap: anywhere; } .message.error .message-role, .message.error .message-text { color: var(--danger); } pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: 10px 0 0; color: var(--muted); } dl { display: grid; grid-template-columns: 96px 1fr; gap: 8px; margin: 10px 0 0; } dt { color: var(--muted); } dd { margin: 0; overflow-wrap: anywhere; } .error { color: var(--danger); } @media (max-width: 820px) { .topbar, .grid { display: block; } .status, .panel { margin-top: 14px; } .footnote { display: block; } .footnote span { display: block; margin-top: 6px; } .settings, .decoding { grid-template-columns: 1fr; } } ================================================================================ END FILE: tinyrustlm/app/app.css ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/app/app.js BYTES: 180331 SHA256: E404D84B0703233A0F0390020840D6FC1ED79DB426D4C221C62369E8FF78C543 ================================================================================ (function () { "use strict"; const paths = { wasm: "../runtime/tinyrustlm.wasm", wasmManifest: "../runtime/tinyrustlm.wasm.manifest", registry: "../models/selector.registry", models: { tinylm16q8: { label: "TinyLM-16M q8_0", path: "../models/tinylm16-q8.slm", maxTokens: 8 }, tinylm16q4: { label: "TinyLM-16M q4_0", path: "../models/tinylm16-q4.slm", maxTokens: 8 }, tinylm16f32: { label: "TinyLM-16M f32", path: "../models/tinylm16-f32.slm", maxTokens: 8 }, tinyf32: { label: "Tiny Fixture f32", path: "../models/tiny-test-model.slm", maxTokens: 16, adapters: [ { label: "Tiny Fixture f32 self ADP1", path: "../models/tiny-test-model-self.adp1", manifestPath: "../models/tiny-test-model-self.adp1.manifest", applyStatus: "runtime-f32-compatible-or-fuse-to-slm", artifactChecksum: "0xe9669ade4571fd42", manifestChecksum: "0x3810be9f3ee711b6" } ] }, tinytied: { label: "Tiny Fixture tied-output f32", path: "../models/tiny-test-model-tied.slm", maxTokens: 16 }, tinyq8: { label: "Tiny Fixture q8_0", path: "../models/tiny-test-model-q8.slm", maxTokens: 16, adapters: [ { label: "Tiny Fixture q8_0 self ADP1", path: "../models/tiny-test-model-q8-self.adp1", manifestPath: "../models/tiny-test-model-q8-self.adp1.manifest", applyStatus: "runtime-q8-q4-compatible-or-fuse-to-slm", artifactChecksum: "0x8194a8a671285019", manifestChecksum: "0x536f9b488db9822b" } ] }, tinyq4: { label: "Tiny Fixture q4_0", path: "../models/tiny-test-model-q4.slm", maxTokens: 16, adapters: [ { label: "Tiny Fixture q4_0 self ADP1", path: "../models/tiny-test-model-q4-self.adp1", manifestPath: "../models/tiny-test-model-q4-self.adp1.manifest", applyStatus: "runtime-q8-q4-compatible-or-fuse-to-slm", artifactChecksum: "0x0bd71e0020bc6ebf", manifestChecksum: "0xe62b43e1d8e06516" } ] }, tinybpe: { label: "Tiny Fixture BPE f32", path: "../models/tiny-test-model-bpe.slm", maxTokens: 16 } } }; const registryAdapterApplyStatus = "runtime-f32-compatible-or-fuse-to-slm"; const registryQuantizedAdapterApplyStatus = "runtime-q8-q4-compatible-or-fuse-to-slm"; const registryLowRankAdapterApplyStatus = "runtime-f32-compatible-low-rank"; const registryQuantizedLowRankAdapterApplyStatus = "runtime-q8-q4-compatible-low-rank"; const registryAdapterApplyStatuses = new Set([ registryAdapterApplyStatus, registryQuantizedAdapterApplyStatus, registryLowRankAdapterApplyStatus, registryQuantizedLowRankAdapterApplyStatus ]); const registryAdapterFamilyStatus = "receipt-validated"; const registryAdapterFamilyStrategy = "single-adapter-selection"; const registryAdapterAutoApplyStatus = "enabled"; const registryAdapterAutoApplyStrategy = "receipt-preferred-compatible"; const registryAdapterAutoApplyStackStatus = "enabled"; const registryAdapterAutoApplyStackStrategy = "receipt-declared-compatible-stack"; const registryAdapterAutoApplyByteBudget = 1024 * 1024; const registryAssemblyStatus = "receipt-validated"; const registryAssemblyKind = "browser-local-assembly-evidence"; const registryModulePlanStatus = "receipt-validated"; const registryModulePlanKind = "browser-local-module-plan"; const registryModulePlanStrategy = "selector-entry-self-assembly"; const registryModulePlanResourceClass = "browser-constrained-local-assembly"; const registryModulePlanProfile = "browser-constrained-v1"; const registryModulePlanExecutionProfile = "single-threaded-wasm-local-v1"; const registryModulePlanFetchPolicy = "local-no-store-v1"; const registryModulePlanOriginPolicy = "same-origin-loopback-local-v1"; const registryModulePlanFetchCountLimit = 32; const registryModulePlanPlannedFetchCount = 21; const registryModulePlanRouteSetVersion = "1"; const registryModulePlanRouteSetChecksumAlgorithm = "tinyrustlm-text-checksum-v1"; const registryModulePlanWasmMemoryInitialPages = 17; const registryModulePlanWasmExportSet = "tinyrustlm-generate-v1"; const registryModulePlanWasmTransferStrategy = "copy-then-release-v1"; const registryModulePlanModelReleaseStrategy = "free-before-reassembly-v1"; const registryModulePlanRuntimeResetStrategy = "reset-context-before-assembly-v1"; const registryModulePlanAdapterValidationStrategy = "rust-validate-before-apply-v1"; const registryModulePlanAdapterValidationCount = 3; const registryModulePlanAdapterApplyCount = 3; const registryModulePlanWasmHeapMinBytes = 64 * 1024; const registryModulePlanWasmExports = [ "memory", "alloc", "dealloc", "init_runtime", "load_model", "generate", "set_sampling_config", "generate_next_token", "validate_adapter_delta", "apply_adapter_delta", "last_result_ptr", "last_result_len", "get_diagnostics_ptr", "get_diagnostics_len", "reset_context", "free_model" ]; const registryModulePlanContextTokenLimitLimit = 4096; const registryModulePlanSamplerCandidateCap = 1024; const registryModulePlanPromptByteLimit = 4 * 1024; const registryModulePlanRuntimeScratchByteBudget = 64 * 1024; const registryModulePlanOutputByteLimit = 64 * 1024; const registryModulePlanKvCacheByteBudgetLimit = 8 * 1024 * 1024; const runtimeWasmKind = "tinyrustlm-rust-wasm"; const runtimeWasmStatus = "validated-local-runtime"; const runtimeWasmNextGate = "instantiate-wasm-runtime"; const selectorDefaultStrategy = "browser-frugal-quantized"; const registryGenomeStrategy = "selector-admission-genome-v1"; const registryGenomeLineageStatus = "admission-bound"; const registrySpeciesStrategy = "selector-speciation-fit-v1"; const registrySpeciesFitStatus = "browser-fit-bound"; const registryNoveltyStrategy = "selector-novelty-sketch-v1"; const registryNoveltyStatus = "behavior-sketch-bound"; const registryPopulationStrategy = "selector-population-review-route-v1"; const registryPopulationStatus = "population-review-bound"; const registryMateSelectionStrategy = "selector-mate-selection-route-v1"; const registryMateSelectionParentPoolStatus = "parent-pool-bound"; const registryMateSelectionAdmissionStatus = "admission-only"; const registryOperatorReceiptStatus = "receipt-bound"; const registryEvolutionRecipeVersion = "1"; const registryEvolutionRecipeStrategy = "population-based-parent-pool-replay-v1"; const registryEvolutionRecipeStatus = "planned"; const registryEvolutionSelectionSource = "population-review-frontier-v1"; const registryEvolutionScheduleChecksumAlgorithm = "tinyrustlm-text-checksum-v1"; const registryPhenotypeEvidenceStrategy = "selector-phenotype-evidence-v1"; const registryPhenotypeEvidenceStatus = "runtime-eval-bound"; const registryHeritableArtifactStrategy = "selector-heritable-artifact-v1"; const registryHeritableArtifactStatus = "served-artifact-bound"; const registryFitnessVectorStatus = "eval-bound"; const selectorModelByteBudget = 32 * 1024 * 1024; const selectorRegistryTextByteBudget = 256 * 1024; const manifestTextByteBudget = 64 * 1024; const receiptTextByteBudget = 128 * 1024; const evidenceTextByteBudget = 128 * 1024; const registryModulePlanTotalByteBudgetLimit = selectorModelByteBudget + registryAdapterAutoApplyByteBudget + registryModulePlanKvCacheByteBudgetLimit + manifestTextByteBudget + receiptTextByteBudget + receiptTextByteBudget + registryModulePlanPromptByteLimit + registryModulePlanRuntimeScratchByteBudget + registryModulePlanOutputByteLimit; const adapterFamilyReceiptStatus = "validated"; const assemblyReceiptStatus = "validated"; const assemblyReceiptStrategies = new Set([ "multi-parent-sign-merge", "multi-parent-weighted-soup" ]); const modulePlanReceiptStatus = "validated"; const localFetchOptions = Object.freeze({ cache: "no-store" }); const adapterManifestArtifactVersion = "1"; const adapterManifestStatus = "artifact-written"; const sourceBackedLowRankAdapterKind = "trained-source-low-rank-f32-v1"; const sourceBackedLowRankManifestFields = [ ["adapter_source_manifest", "source_manifest", "adapter-source.manifest", false], ["adapter_source_manifest_checksum", "source_manifest_checksum", "", true], ["adapter_source_layout", "source_layout", "low-rank-f32-factor-files-v1", false], ["adapter_source_format", "source_format", "trained-low-rank-factors-v1", false], ["adapter_source_base_contract", "source_base_contract", "matches-reviewed-adapter-source-base-contract", false] ]; const adapterManifestFormats = [ { extension: ".adp1", kindDtypePairs: [["raw-f32-task-delta-v1", "f32-delta"]], defaultLabel: "ADP1 adapter", applyStatus: registryAdapterApplyStatus, quantizedApplyStatus: registryQuantizedAdapterApplyStatus }, { extension: ".asp1", kindDtypePairs: [["sparse-f32-task-delta-v1", "sparse-f32-delta"]], defaultLabel: "ASP1 adapter", applyStatus: registryAdapterApplyStatus, quantizedApplyStatus: registryQuantizedAdapterApplyStatus }, { extension: ".alr1", kindDtypePairs: [ ["low-rank-f32-task-delta-v1", "low-rank-f32-delta"], [sourceBackedLowRankAdapterKind, "low-rank-f32-source-delta"] ], defaultLabel: "ALR1 adapter", applyStatus: registryLowRankAdapterApplyStatus, quantizedApplyStatus: registryQuantizedLowRankAdapterApplyStatus } ]; const adapterFamilyReceiptKinds = new Set([ "browser-local-adapter-family", "browser-local-adp1-family" ]); const checksumMask = (1n << 64n) - 1n; const checksumPrime = 0x100000001b3n; const adapterFamilyIdentityKeys = [ "adapter_tensor_count", "adapter_parameter_count", "adapter_model_shape", "adapter_base_quantization", "adapter_output_contract", "adapter_tokenizer_checksum", "adapter_tensor_layout_checksum", "adapter_base_contract" ]; const assemblyEvidenceBaseRoutes = [ ["promotion_ledger_path", "promotion_ledger_checksum", "population.ledger"], ["population_review_path", "population_review_checksum", "population.review"], ["parent_pool_recipe_path", "parent_pool_recipe_checksum", "parent-pool.recipe"] ]; const assemblyOperatorEvidenceRoutes = [ ["operator_receipt_path", "operator_receipt_checksum", "operator"], ["candidate_manifest_path", "candidate_manifest_checksum", "candidate"], ["promotion_manifest_path", "promotion_manifest_checksum", "promotion"], ["runtime_smoke_path", "runtime_smoke_manifest_checksum", "runtime"], ["eval_path", "eval_manifest_checksum", "eval"], ["admission_path", "admission_checksum", "multi.admission"] ]; const state = { instance: null, exports: null, encoder: new TextEncoder(), decoder: new TextDecoder(), modelLoadMs: 0, lastGenerateMs: 0, lastMeasuredTokens: 0, modelLoadSequence: 0, wasmMemoryInitialPages: 0, activeModelKey: "", modelLoaded: false, modelManifest: null, modulePlanReceipt: null, modulePlanActualFetchCount: null, modulePlanActualRoutes: null, modulePlanActualRouteSetChecksum: null, modulePlanActualModuleBytes: null, modulePlanActualModuleByteIndexes: null, modulePlanActualModuleChecksums: null, assemblyReceipt: null, modulePlanTrace: [], selectorRegistry: null, selectorDefaultModelKey: "", hasContext: false, messages: [] }; const el = { runtimeStatus: document.getElementById("runtimeStatus"), wasmState: document.getElementById("wasmState"), modelState: document.getElementById("modelState"), errorState: document.getElementById("errorState"), diagnostics: document.getElementById("diagnostics"), console: document.getElementById("console"), developer: document.getElementById("developer"), response: document.getElementById("response"), form: document.getElementById("chatForm"), prompt: document.getElementById("prompt"), maxTokens: document.getElementById("maxTokens"), temperature: document.getElementById("temperature"), topK: document.getElementById("topK"), topP: document.getElementById("topP"), seed: document.getElementById("seed"), modelSelect: document.getElementById("modelSelect"), adapterSelect: document.getElementById("adapterSelect"), applyAdapterButton: document.getElementById("applyAdapterButton"), adapterState: document.getElementById("adapterState"), generateButton: document.getElementById("generateButton"), stepTokenButton: document.getElementById("stepTokenButton"), resetButton: document.getElementById("resetButton"), clearChatButton: document.getElementById("clearChatButton"), conversation: document.getElementById("conversation"), benchLoadMs: document.getElementById("benchLoadMs"), benchPromptTokens: document.getElementById("benchPromptTokens"), benchGeneratedTokens: document.getElementById("benchGeneratedTokens"), benchTokensPerSecond: document.getElementById("benchTokensPerSecond"), benchScratch: document.getElementById("benchScratch"), provenanceState: document.getElementById("provenanceState"), provenanceSourceKind: document.getElementById("provenanceSourceKind"), provenanceAdmission: document.getElementById("provenanceAdmission"), provenanceQualityClaim: document.getElementById("provenanceQualityClaim"), provenanceTrainedClaim: document.getElementById("provenanceTrainedClaim"), provenanceGenome: document.getElementById("provenanceGenome"), provenanceSpecies: document.getElementById("provenanceSpecies"), provenanceNovelty: document.getElementById("provenanceNovelty"), provenancePopulation: document.getElementById("provenancePopulation"), provenanceMateSelection: document.getElementById("provenanceMateSelection"), provenanceOperator: document.getElementById("provenanceOperator"), provenanceSchedule: document.getElementById("provenanceSchedule"), provenancePhenotype: document.getElementById("provenancePhenotype"), provenanceArtifact: document.getElementById("provenanceArtifact"), provenanceFitness: document.getElementById("provenanceFitness"), provenanceEvalCases: document.getElementById("provenanceEvalCases"), provenanceEvalChecksum: document.getElementById("provenanceEvalChecksum"), provenanceChecksum: document.getElementById("provenanceChecksum"), provenanceNextGate: document.getElementById("provenanceNextGate"), assemblyState: document.getElementById("assemblyState"), assemblyKind: document.getElementById("assemblyKind"), assemblyParents: document.getElementById("assemblyParents"), assemblyOperator: document.getElementById("assemblyOperator"), assemblyLedger: document.getElementById("assemblyLedger"), assemblyNextGate: document.getElementById("assemblyNextGate"), modulePlanState: document.getElementById("modulePlanState"), modulePlanKind: document.getElementById("modulePlanKind"), modulePlanResource: document.getElementById("modulePlanResource"), modulePlanExecution: document.getElementById("modulePlanExecution"), modulePlanFetch: document.getElementById("modulePlanFetch"), modulePlanOrigin: document.getElementById("modulePlanOrigin"), modulePlanFetchLimit: document.getElementById("modulePlanFetchLimit"), modulePlanPlannedFetchCount: document.getElementById("modulePlanPlannedFetchCount"), modulePlanActualFetchCount: document.getElementById("modulePlanActualFetchCount"), modulePlanRouteSetChecksumAlgorithm: document.getElementById("modulePlanRouteSetChecksumAlgorithm"), modulePlanRouteSetVersion: document.getElementById("modulePlanRouteSetVersion"), modulePlanRouteSetChecksum: document.getElementById("modulePlanRouteSetChecksum"), modulePlanActualRouteSetChecksum: document.getElementById("modulePlanActualRouteSetChecksum"), modulePlanWasmPages: document.getElementById("modulePlanWasmPages"), modulePlanWasmExportSet: document.getElementById("modulePlanWasmExportSet"), modulePlanWasmTransferStrategy: document.getElementById("modulePlanWasmTransferStrategy"), modulePlanModelReleaseStrategy: document.getElementById("modulePlanModelReleaseStrategy"), modulePlanRuntimeResetStrategy: document.getElementById("modulePlanRuntimeResetStrategy"), modulePlanAdapterValidationStrategy: document.getElementById("modulePlanAdapterValidationStrategy"), modulePlanAdapterValidationCount: document.getElementById("modulePlanAdapterValidationCount"), modulePlanAdapterApplyCount: document.getElementById("modulePlanAdapterApplyCount"), modulePlanWasmHeapMinBytes: document.getElementById("modulePlanWasmHeapMinBytes"), modulePlanContextTokens: document.getElementById("modulePlanContextTokens"), modulePlanSamplerCap: document.getElementById("modulePlanSamplerCap"), modulePlanTokenizer: document.getElementById("modulePlanTokenizer"), modulePlanModules: document.getElementById("modulePlanModules"), modulePlanModelBudget: document.getElementById("modulePlanModelBudget"), modulePlanAdapterBudget: document.getElementById("modulePlanAdapterBudget"), modulePlanAdapterStackBudget: document.getElementById("modulePlanAdapterStackBudget"), modulePlanScratchBudget: document.getElementById("modulePlanScratchBudget"), modulePlanPromptLimit: document.getElementById("modulePlanPromptLimit"), modulePlanOutputLimit: document.getElementById("modulePlanOutputLimit"), modulePlanKvCacheBudget: document.getElementById("modulePlanKvCacheBudget"), modulePlanKvCachePages: document.getElementById("modulePlanKvCachePages"), modulePlanTotalBudget: document.getElementById("modulePlanTotalBudget"), modulePlanTotalLimit: document.getElementById("modulePlanTotalLimit"), modulePlanBytes: document.getElementById("modulePlanBytes"), modulePlanActualModuleBytes: document.getElementById("modulePlanActualModuleBytes"), modulePlanChecksums: document.getElementById("modulePlanChecksums"), modulePlanActualModuleChecksums: document.getElementById("modulePlanActualModuleChecksums"), modulePlanSlots: document.getElementById("modulePlanSlots"), modulePlanRoles: document.getElementById("modulePlanRoles"), modulePlanPhases: document.getElementById("modulePlanPhases"), modulePlanDepends: document.getElementById("modulePlanDepends"), modulePlanTrace: document.getElementById("modulePlanTrace"), modulePlanModel: document.getElementById("modulePlanModel"), modulePlanStack: document.getElementById("modulePlanStack") }; function setText(node, text, isError) { node.textContent = text; node.classList.toggle("error", Boolean(isError)); } function memory() { return new Uint8Array(state.exports.memory.buffer); } function readString(ptr, len) { return state.decoder.decode(memory().slice(ptr, ptr + len)); } function readLastResult() { return readString(state.exports.last_result_ptr(), state.exports.last_result_len()); } function readDiagnostics() { return readString(state.exports.get_diagnostics_ptr(), state.exports.get_diagnostics_len()); } // Parses runtime diagnostics after adapter assembly so module-plan counters can be checked. function readDiagnosticsJson() { try { return JSON.parse(readDiagnostics()); } catch (_error) { return null; } } function allocCopy(bytes) { const ptr = state.exports.alloc(bytes.length); if (!ptr) { throw new Error("WASM allocation failed"); } memory().set(bytes, ptr); return ptr; } function release(ptr, len) { if (ptr) { state.exports.dealloc(ptr, len); } } function probeWasmHeapAllocation(byteCount) { // Proves the declared generated-module transfer floor before bytes enter WASM. const ptr = state.exports.alloc(byteCount); if (!ptr) { throw new Error("Module plan WASM heap allocation probe failed"); } release(ptr, byteCount); } // Captures the static exported memory footprint before runtime init can grow it. function wasmMemoryInitialPages() { const pageBytes = 64 * 1024; const byteLength = state.exports.memory.buffer.byteLength; if (byteLength % pageBytes !== 0) { throw new Error("WASM memory byte length was not page aligned"); } return byteLength / pageBytes; } // Checks the named Rust/WASM ABI before a generated module plan can fetch model bytes. function hasRuntimeWasmExport(name) { if (name === "memory") { return state.exports.memory && state.exports.memory.buffer instanceof ArrayBuffer; } return typeof state.exports[name] === "function"; } function verifyModulePlanWasmExports(exportSet) { if (exportSet !== registryModulePlanWasmExportSet) { return false; } return registryModulePlanWasmExports.every((name) => hasRuntimeWasmExport(name)); } function renderDiagnostics() { const diagnostics = readDiagnostics(); el.diagnostics.textContent = diagnostics; el.developer.textContent = diagnostics; renderBenchmark(diagnostics); } function renderBenchmark(diagnosticsText) { let diagnostics = null; try { diagnostics = JSON.parse(diagnosticsText); } catch (_error) { diagnostics = null; } const promptTokens = diagnostics ? diagnostics.prompt_token_count : 0; const generatedTokens = diagnostics ? diagnostics.generated_token_count : 0; const scratchBytes = diagnostics ? diagnostics.peak_scratch_arena_usage : 0; const measuredTokens = state.lastMeasuredTokens > 0 ? state.lastMeasuredTokens : generatedTokens; const measuredSpeed = measuredTokens > 0 && state.lastGenerateMs > 0 ? measuredTokens / (state.lastGenerateMs / 1000) : 0; const reportedSpeed = diagnostics ? diagnostics.tokens_per_second : 0; const speed = measuredSpeed || reportedSpeed || 0; el.benchLoadMs.textContent = state.modelLoadMs > 0 ? `${state.modelLoadMs} ms` : "waiting"; el.benchPromptTokens.textContent = `${promptTokens} tokens`; el.benchGeneratedTokens.textContent = `${generatedTokens} tokens`; el.benchTokensPerSecond.textContent = `${speed.toFixed(3)} tok/s`; el.benchScratch.textContent = `${scratchBytes} bytes`; } function renderConversation() { el.conversation.replaceChildren(); for (const message of state.messages) { const item = document.createElement("li"); const role = document.createElement("div"); const text = document.createElement("div"); item.className = `message message-${message.role}`; item.classList.toggle("error", Boolean(message.isError)); role.className = "message-role"; text.className = "message-text"; role.textContent = message.role === "user" ? "User" : "TinyRustLM"; text.textContent = message.text; item.append(role, text); el.conversation.append(item); } el.clearChatButton.disabled = state.messages.length === 0; el.conversation.scrollTop = el.conversation.scrollHeight; } function appendMessage(role, text, isError) { state.messages.push({ role, text, isError: Boolean(isError) }); renderConversation(); } function extendAssistantMessage(text) { if (!text) { return; } const last = state.messages[state.messages.length - 1]; if (last && last.role === "assistant" && !last.isError) { last.text += text; renderConversation(); return; } appendMessage("assistant", text, false); } function appendConsole(text) { el.console.textContent = el.console.textContent ? `${el.console.textContent}\n${text}` : text; } function errorMessage(error) { return error instanceof Error ? error.message : String(error); } function clampNumber(value, min, max, fallback) { const parsed = Number.parseFloat(value); if (!Number.isFinite(parsed)) { return fallback; } return Math.max(min, Math.min(max, parsed)); } function clampInteger(value, min, max, fallback) { return Math.trunc(clampNumber(value, min, max, fallback)); } function readSamplingConfig() { const config = { temperature: clampNumber(el.temperature.value, 0, 5, 0), topK: clampInteger(el.topK.value, 1, registryModulePlanSamplerCandidateCap, 1), topP: clampNumber(el.topP.value, 0.01, 1, 1), seed: clampInteger(el.seed.value, 0, 4294967295, 1) }; el.temperature.value = String(config.temperature); el.topK.value = String(config.topK); el.topP.value = String(config.topP); el.seed.value = String(config.seed); return config; } function applySamplingConfig() { const config = readSamplingConfig(); if (typeof state.exports.set_sampling_config !== "function") { throw new Error("WASM runtime does not expose sampling configuration"); } const code = state.exports.set_sampling_config( config.temperature, config.topK, config.topP, config.seed ); if (code !== 0) { throw new Error(readLastResult() || `sampling configuration failed (${code})`); } return config; } function parseManifest(text) { const fields = Object.create(null); const lines = text.split(/\r?\n/); for (const line of lines) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith("#")) { continue; } const separator = trimmed.indexOf("="); if (separator <= 0) { continue; } fields[trimmed.slice(0, separator)] = trimmed.slice(separator + 1); } return fields; } async function fetchTextWithinBudget(route, byteBudget, label, allowMissing) { const response = await fetch(route, localFetchOptions); if (!response.ok) { if (allowMissing) { return null; } throw new Error(`Unable to fetch local ${label} (${response.status})`); } const bytes = new Uint8Array(await response.arrayBuffer()); if (bytes.length > byteBudget) { throw new Error(`${label} byte budget exceeded`); } return state.decoder.decode(bytes); } // Clears generated self-assembly route observations for a new model load. function resetModulePlanActualFetchCount(model) { const hasModulePlan = Boolean(model && model.modulePlan); state.modulePlanActualFetchCount = hasModulePlan ? 0 : null; state.modulePlanActualRoutes = hasModulePlan ? [] : null; state.modulePlanActualRouteSetChecksum = null; state.modulePlanActualModuleBytes = hasModulePlan ? 0 : null; state.modulePlanActualModuleByteIndexes = hasModulePlan ? [] : null; state.modulePlanActualModuleChecksums = hasModulePlan ? [] : null; const fields = model && model.modulePlanReceipt; updateModulePlanActualFetchCount(fields); updateModulePlanActualRouteSetChecksum(fields); updateModulePlanActualModuleBytes(fields); updateModulePlanActualModuleChecksums(fields); } // Records one accepted generated self-assembly route fetch and its route-set entry. function recordModulePlanFetch(model, kind, route) { if (!model || !model.modulePlan) { return; } if (!kind || !route) { throw new Error("Module plan actual route metadata missing"); } if (!Number.isInteger(state.modulePlanActualFetchCount)) { state.modulePlanActualFetchCount = 0; } if (!Array.isArray(state.modulePlanActualRoutes)) { state.modulePlanActualRoutes = []; } state.modulePlanActualFetchCount += 1; state.modulePlanActualRoutes.push({ kind, path: route }); state.modulePlanActualRouteSetChecksum = modulePlanRouteSetChecksum(state.modulePlanActualRoutes); const fields = model.modulePlanReceipt || state.modulePlanReceipt; updateModulePlanActualFetchCount(fields); updateModulePlanActualRouteSetChecksum(fields); } // Fetches receipt/manifest/evidence text while counting generated module-plan routes. async function fetchModulePlanTextWithinBudget(model, route, byteBudget, label, kind) { const text = await fetchTextWithinBudget(route, byteBudget, label); recordModulePlanFetch(model, kind, route); return text; } // Fetches binary generated model or adapter artifacts while counting module-plan routes. async function fetchModulePlanBytes(model, route, label, kind) { const response = await fetch(route, localFetchOptions); if (!response.ok) { throw new Error(`Unable to fetch local ${label} (${response.status})`); } const bytes = new Uint8Array(await response.arrayBuffer()); recordModulePlanFetch(model, kind, route); return bytes; } // Updates only the Actual Fetches row during an in-flight generated assembly. function updateModulePlanActualFetchCount(fields) { if (el.modulePlanActualFetchCount) { el.modulePlanActualFetchCount.textContent = modulePlanActualFetchSummary(fields); } } // Updates only the Actual Route Set row while the observed route list grows. function updateModulePlanActualRouteSetChecksum(fields) { if (el.modulePlanActualRouteSetChecksum) { el.modulePlanActualRouteSetChecksum.textContent = modulePlanActualRouteSetSummary(fields); } } // Updates the observed module-byte total without disturbing receipt-owned byte rows. function updateModulePlanActualModuleBytes(fields) { if (el.modulePlanActualModuleBytes) { el.modulePlanActualModuleBytes.textContent = modulePlanActualModuleByteSummary(fields); } } // Updates the observed module-checksum row as each verified module payload arrives. function updateModulePlanActualModuleChecksums(fields) { if (el.modulePlanActualModuleChecksums) { el.modulePlanActualModuleChecksums.textContent = modulePlanActualModuleChecksumSummary(fields); } } function manifestValue(fields, key) { return fields && fields[key] ? fields[key] : "unavailable"; } // Renders selector entries while allowing registry boot to prefer its declared default. function renderModelOptions(models, preferDeclaredDefault) { const selected = preferDeclaredDefault ? "" : el.modelSelect.value; el.modelSelect.replaceChildren(); let firstKey = ""; for (const key of Object.keys(models)) { const option = document.createElement("option"); option.value = key; option.textContent = models[key].label || key; el.modelSelect.append(option); if (!firstKey) { firstKey = key; } } const defaultKey = state.selectorDefaultModelKey; el.modelSelect.value = models[selected] ? selected : (models[defaultKey] ? defaultKey : firstKey); } function isSafeRegistryModelPath(value) { if (!value || !value.startsWith("../models/") || !value.endsWith(".slm")) { return false; } if (value.includes("\\") || value.includes("://") || value.includes("//")) { return false; } const rest = value.slice("../models/".length); return rest.split("/").every((part) => part && part !== "." && part !== ".."); } function adapterFormatForPath(value) { if (!value) { return null; } return adapterManifestFormats.find((format) => value.endsWith(format.extension)) || null; } function isSafeRegistryAdapterPath(value) { if (!value || !value.startsWith("../models/") || !adapterFormatForPath(value)) { return false; } if (value.includes("\\") || value.includes("://") || value.includes("//")) { return false; } const rest = value.slice("../models/".length); return rest.split("/").every((part) => part && part !== "." && part !== ".."); } function isSafeRegistryAdapterFamilyReceiptPath(value) { if (!value || !value.startsWith("../models/") || !value.endsWith(".adapter-family.receipt")) { return false; } if (value.includes("\\") || value.includes("://") || value.includes("//")) { return false; } const rest = value.slice("../models/".length); return rest.split("/").every((part) => part && part !== "." && part !== ".."); } function isSafeRegistryAssemblyReceiptPath(value) { if (!value || !value.startsWith("../models/") || !value.endsWith(".assembly.receipt")) { return false; } if (value.includes("\\") || value.includes("://") || value.includes("//")) { return false; } const rest = value.slice("../models/".length); return rest.split("/").every((part) => part && part !== "." && part !== ".."); } function isSafeRegistryModulePlanPath(value) { if (!value || !value.startsWith("../models/") || !value.endsWith(".module-plan.receipt")) { return false; } if (value.includes("\\") || value.includes("://") || value.includes("//")) { return false; } const rest = value.slice("../models/".length); return rest.split("/").every((part) => part && part !== "." && part !== ".."); } function isSafeAssemblyEvidencePath(value) { if (!value || !value.startsWith("../evidence/")) { return false; } if (value.includes("\\") || value.includes("://") || value.includes("//")) { return false; } const rest = value.slice("../evidence/".length); return rest.split("/").every((part) => part && part !== "." && part !== ".."); } function isRegistryHex64(value) { return /^0x[0-9a-fA-F]{16}$/.test(value || ""); } function isRegistrySlug(value) { return /^[A-Za-z0-9._-]{1,96}$/.test(value || ""); } function rotateLeft64(value, bits) { return ((value << bits) | (value >> (64n - bits))) & checksumMask; } function textChecksumHex(text) { const bytes = state.encoder.encode(text); return bytesChecksumHex(bytes); } function bytesChecksumHex(bytes) { let acc = 0x4d595df4d0f33173n; for (let index = 0; index < bytes.length; index += 1) { acc ^= BigInt(bytes[index]) + (BigInt(index) << 2n); acc = (rotateLeft64(acc, 9n) * checksumPrime) & checksumMask; } return `0x${acc.toString(16).padStart(16, "0")}`; } function adapterArtifactChecksumHex(bytes) { if (!bytes || bytes.length < 64) { throw new Error("Adapter artifact is too short"); } let acc = 0x6164617074657231n; for (let index = 0; index < bytes.length; index += 1) { const value = index >= 56 && index < 64 ? 0 : bytes[index]; acc ^= BigInt(value) + (BigInt(index) << 3n); acc = (rotateLeft64(acc, 11n) * checksumPrime) & checksumMask; } return `0x${acc.toString(16).padStart(16, "0")}`; } function requireManifestField(fields, key, source) { const value = fields[key]; if (!value) { throw new Error(`Missing ${source || "receipt"} field ${key}`); } return value; } function requireManifestEqual(fields, key, expected, source) { const actual = requireManifestField(fields, key, source ? source.toLowerCase() : undefined); if (actual !== expected) { throw new Error(`${source || "Receipt"} field ${key} was ${actual}`); } } function requireManifestOneOf(fields, key, expectedValues, source) { const actual = requireManifestField(fields, key, source ? source.toLowerCase() : undefined); if (!expectedValues.includes(actual)) { throw new Error(`${source || "Receipt"} field ${key} was ${actual}`); } } // Validates 64-bit checksum text before using a manifest field as a route contract. function requireHex64ManifestField(fields, key, source) { const actual = requireManifestField(fields, key, source ? source.toLowerCase() : undefined); if (!isRegistryHex64(actual)) { throw new Error(`${source || "Receipt"} field ${key} was ${actual}`); } return actual; } // Keeps adapter kind and dtype coupled so source-backed ALR1 cannot masquerade as plain ALR1. function requireAdapterKindDtypePair(fields, kindKey, dtypeKey, kindDtypePairs, source) { const kind = requireManifestField(fields, kindKey, source ? source.toLowerCase() : undefined); const dtype = requireManifestField(fields, dtypeKey, source ? source.toLowerCase() : undefined); const matched = kindDtypePairs.some(([acceptedKind, acceptedDtype]) => { return kind === acceptedKind && dtype === acceptedDtype; }); if (!matched) { throw new Error(`${source || "Receipt"} adapter kind/dtype pair was ${kind}/${dtype}`); } return kind; } function requireChecksumEqual(actual, expected, label) { if (!isRegistryHex64(actual) || actual.toLowerCase() !== String(expected || "").toLowerCase()) { throw new Error(`${label} checksum mismatch`); } } function adapterApplyStatusForQuantization(adapterFormat, quantization) { if (!adapterFormat) { return null; } if (quantization === "f32") { return adapterFormat.applyStatus; } if (quantization === "q8_0" || quantization === "q4_0") { return adapterFormat.quantizedApplyStatus; } return null; } function registryAdapterFromFields( fields, pathKey, manifestKey, labelKey, applyStatusKey, artifactChecksumKey, manifestChecksumKey, baseQuantization ) { const adapterPath = fields[pathKey]; if (!isSafeRegistryAdapterPath(adapterPath)) { return null; } const adapterFormat = adapterFormatForPath(adapterPath); const manifestPath = fields[manifestKey]; if (manifestPath && manifestPath !== `${adapterPath}.manifest`) { return null; } const applyStatus = fields[applyStatusKey]; const expectedApplyStatus = adapterApplyStatusForQuantization(adapterFormat, baseQuantization); if (!expectedApplyStatus || (applyStatus && applyStatus !== expectedApplyStatus)) { return null; } if (applyStatus && !registryAdapterApplyStatuses.has(applyStatus)) { return null; } const artifactChecksum = fields[artifactChecksumKey]; const manifestChecksum = fields[manifestChecksumKey]; if (!isRegistryHex64(artifactChecksum) || !isRegistryHex64(manifestChecksum)) { return null; } return { label: fields[labelKey] || adapterFormat.defaultLabel, path: adapterPath, manifestPath: manifestPath || `${adapterPath}.manifest`, applyStatus: applyStatus || expectedApplyStatus, baseQuantization, artifactChecksum, manifestChecksum }; } function registryAdapterEntries(fields, prefix, baseQuantization) { const adapterCountValue = fields[`${prefix}.adapter_count`]; if (adapterCountValue) { const adapterCount = Number.parseInt(adapterCountValue, 10); if (!Number.isInteger(adapterCount) || adapterCount < 1 || adapterCount > 16) { return null; } const adapters = []; const seenPaths = new Set(); for (let adapterIndex = 0; adapterIndex < adapterCount; adapterIndex += 1) { const adapterPrefix = `${prefix}.adapter.${adapterIndex}`; const adapter = registryAdapterFromFields( fields, `${adapterPrefix}.path`, `${adapterPrefix}.manifest_path`, `${adapterPrefix}.label`, `${adapterPrefix}.apply_status`, `${adapterPrefix}.artifact_checksum`, `${adapterPrefix}.manifest_checksum`, baseQuantization ); if (!adapter || seenPaths.has(adapter.path)) { return null; } seenPaths.add(adapter.path); adapters.push(adapter); } return adapters; } if (!fields[`${prefix}.adapter_path`]) { return []; } const adapter = registryAdapterFromFields( fields, `${prefix}.adapter_path`, `${prefix}.adapter_manifest_path`, `${prefix}.adapter_label`, `${prefix}.adapter_apply_status`, `${prefix}.adapter_artifact_checksum`, `${prefix}.adapter_manifest_checksum`, baseQuantization ); return adapter ? [adapter] : null; } function registryAdapterFamilyEntry(fields, prefix, adapterCount) { const keys = [ "adapter_family_receipt_path", "adapter_family_receipt_checksum", "adapter_family_label", "adapter_family_status", "adapter_family_strategy", "adapter_family_adapter_count", "adapter_auto_apply_status", "adapter_auto_apply_strategy", "adapter_auto_apply_stack_status", "adapter_auto_apply_stack_strategy", "adapter_auto_apply_stack_count", "adapter_auto_apply_byte_budget" ]; const hasFamily = keys.some((key) => fields[`${prefix}.${key}`]); if (!hasFamily) { return undefined; } const receiptPath = fields[`${prefix}.adapter_family_receipt_path`]; const receiptChecksum = fields[`${prefix}.adapter_family_receipt_checksum`]; const familyCount = Number.parseInt(fields[`${prefix}.adapter_family_adapter_count`] || "0", 10); const stackCount = Number.parseInt(fields[`${prefix}.adapter_auto_apply_stack_count`] || "0", 10); const autoApplyByteBudget = registryAdapterAutoApplyBudget( fields[`${prefix}.adapter_auto_apply_byte_budget`] ); if (!isSafeRegistryAdapterFamilyReceiptPath(receiptPath) || !isRegistryHex64(receiptChecksum)) { return null; } if (fields[`${prefix}.adapter_family_status`] !== registryAdapterFamilyStatus) { return null; } if (fields[`${prefix}.adapter_family_strategy`] !== registryAdapterFamilyStrategy) { return null; } if (fields[`${prefix}.adapter_auto_apply_status`] !== registryAdapterAutoApplyStatus) { return null; } if (fields[`${prefix}.adapter_auto_apply_strategy`] !== registryAdapterAutoApplyStrategy) { return null; } if (fields[`${prefix}.adapter_auto_apply_stack_status`] !== registryAdapterAutoApplyStackStatus) { return null; } if (fields[`${prefix}.adapter_auto_apply_stack_strategy`] !== registryAdapterAutoApplyStackStrategy) { return null; } if (!Number.isInteger(stackCount) || stackCount < 1 || stackCount > familyCount) { return null; } if (autoApplyByteBudget === null) { return null; } if (!Number.isInteger(familyCount) || familyCount !== adapterCount || familyCount < 2 || familyCount > 16) { return null; } return { label: fields[`${prefix}.adapter_family_label`] || "ADP1 adapter family", path: receiptPath, checksum: receiptChecksum, strategy: fields[`${prefix}.adapter_family_strategy`], count: familyCount, autoApplyStatus: fields[`${prefix}.adapter_auto_apply_status`], autoApplyStrategy: fields[`${prefix}.adapter_auto_apply_strategy`], autoApplyStackStatus: fields[`${prefix}.adapter_auto_apply_stack_status`], autoApplyStackStrategy: fields[`${prefix}.adapter_auto_apply_stack_strategy`], autoApplyStackCount: stackCount, autoApplyByteBudget }; } function registryAssemblyEntry(fields, prefix) { const keys = [ "assembly_receipt_path", "assembly_receipt_checksum", "assembly_label", "assembly_status", "assembly_kind" ]; const hasAssembly = keys.some((key) => fields[`${prefix}.${key}`]); if (!hasAssembly) { return undefined; } const receiptPath = fields[`${prefix}.assembly_receipt_path`]; const receiptChecksum = fields[`${prefix}.assembly_receipt_checksum`]; if (!isSafeRegistryAssemblyReceiptPath(receiptPath) || !isRegistryHex64(receiptChecksum)) { return null; } if (fields[`${prefix}.assembly_status`] !== registryAssemblyStatus) { return null; } if (fields[`${prefix}.assembly_kind`] !== registryAssemblyKind) { return null; } return { label: fields[`${prefix}.assembly_label`] || "Assembly evidence", path: receiptPath, checksum: receiptChecksum, status: fields[`${prefix}.assembly_status`], kind: fields[`${prefix}.assembly_kind`] }; } // Maps generated parent-pool entries to the operator kind their assembly route implies. function expectedGeneratedOperatorReceiptKind(candidateId, assembly) { if (!assembly) { return ""; } const id = String(candidateId || ""); if (id.startsWith("multi-parent-soup-")) { return "seed-weighted-parent-pool-soup"; } if (id.startsWith("multi-parent-sign-merge-")) { return "sign-aware-parent-pool-merge"; } return ""; } // Reads selector genome routing fields before a registry entry can become selectable. function registryGenomeEntry(fields, prefix) { const genomeId = fields[`${prefix}.genome_id`]; const strategy = fields[`${prefix}.genome_strategy`]; const lineageStatus = fields[`${prefix}.genome_lineage_status`]; const lineageChecksum = fields[`${prefix}.genome_lineage_checksum`]; if ( !isRegistryHex64(genomeId) || strategy !== registryGenomeStrategy || lineageStatus !== registryGenomeLineageStatus || !isRegistryHex64(lineageChecksum) ) { return null; } return { id: genomeId, strategy, lineageStatus, lineageChecksum }; } // Reads selector species-fit fields that group candidates by browser-compatible traits. function registrySpeciesEntry(fields, prefix) { const speciesId = fields[`${prefix}.species_id`]; const strategy = fields[`${prefix}.species_strategy`]; const fitStatus = fields[`${prefix}.species_fit_status`]; const fitChecksum = fields[`${prefix}.species_fit_checksum`]; if ( !isRegistryHex64(speciesId) || strategy !== registrySpeciesStrategy || fitStatus !== registrySpeciesFitStatus || !isRegistryHex64(fitChecksum) ) { return null; } return { id: speciesId, strategy, fitStatus, fitChecksum }; } // Reads selector novelty sketches that preserve behavior variety across candidates. function registryNoveltyEntry(fields, prefix) { const noveltyId = fields[`${prefix}.novelty_id`]; const strategy = fields[`${prefix}.novelty_strategy`]; const status = fields[`${prefix}.novelty_status`]; const checksum = fields[`${prefix}.novelty_checksum`]; if ( !isRegistryHex64(noveltyId) || strategy !== registryNoveltyStrategy || status !== registryNoveltyStatus || !isRegistryHex64(checksum) ) { return null; } return { id: noveltyId, strategy, status, checksum }; } // Reads selector population review routes that connect candidates to population context. function registryPopulationEntry(fields, prefix) { const populationId = fields[`${prefix}.population_id`]; const strategy = fields[`${prefix}.population_strategy`]; const status = fields[`${prefix}.population_status`]; const checksum = fields[`${prefix}.population_checksum`]; if ( !isRegistryHex64(populationId) || strategy !== registryPopulationStrategy || status !== registryPopulationStatus || !isRegistryHex64(checksum) ) { return null; } return { id: populationId, strategy, status, checksum }; } // Reads selector mate-selection routes that bind parent-pool recipes to provenance. function registryMateSelectionEntry(fields, prefix) { const mateSelectionId = fields[`${prefix}.mate_selection_id`]; const strategy = fields[`${prefix}.mate_selection_strategy`]; const status = fields[`${prefix}.mate_selection_status`]; const parentCount = registryDecimalByteCount(fields[`${prefix}.mate_selection_parent_count`]); const checksum = fields[`${prefix}.mate_selection_checksum`]; const isKnownStatus = status === registryMateSelectionParentPoolStatus || status === registryMateSelectionAdmissionStatus; if ( !isRegistryHex64(mateSelectionId) || strategy !== registryMateSelectionStrategy || !isKnownStatus || parentCount === null || !isRegistryHex64(checksum) ) { return null; } if (status === registryMateSelectionParentPoolStatus && parentCount < 2) { return null; } if (status === registryMateSelectionAdmissionStatus && parentCount !== 1) { return null; } return { id: mateSelectionId, strategy, status, parentCount, checksum }; } // Reads copied operator receipt metadata and checks generated route kind agreement. function registryOperatorReceiptEntry(fields, prefix, candidateId, assembly, modelBytes, slmChecksum) { const suffixes = [ "operator_receipt_status", "operator_receipt_path", "operator_receipt_checksum", "operator_receipt_operator_id", "operator_receipt_operator_kind", "operator_receipt_candidate_slm_checksum", "operator_receipt_candidate_artifact_bytes" ]; const hasReceiptField = suffixes.some((suffix) => fields[`${prefix}.${suffix}`] !== undefined); if (!hasReceiptField) { return undefined; } const status = fields[`${prefix}.operator_receipt_status`]; const path = fields[`${prefix}.operator_receipt_path`]; const checksum = fields[`${prefix}.operator_receipt_checksum`]; const operatorId = fields[`${prefix}.operator_receipt_operator_id`]; const operatorKind = fields[`${prefix}.operator_receipt_operator_kind`]; const candidateSlmChecksum = fields[`${prefix}.operator_receipt_candidate_slm_checksum`]; const candidateArtifactBytes = registryDecimalByteCount( fields[`${prefix}.operator_receipt_candidate_artifact_bytes`] ); const expectedOperatorKind = expectedGeneratedOperatorReceiptKind(candidateId, assembly); if ( status !== registryOperatorReceiptStatus || !path || !isRegistryHex64(checksum) || !operatorId || !operatorKind || (expectedOperatorKind && operatorKind !== expectedOperatorKind) || candidateSlmChecksum !== slmChecksum || candidateArtifactBytes !== modelBytes ) { return null; } return { status, path, checksum, operatorId, operatorKind, candidateSlmChecksum, candidateArtifactBytes }; } // Reads copied parent-pool schedule metadata and binds it to the accepted operator receipt. function registryEvolutionScheduleEntry(fields, prefix, operatorReceipt) { const suffixes = [ "evolution_recipe_version", "evolution_recipe_strategy", "evolution_recipe_status", "evolution_selection_source", "evolution_relatedness_contract_checksum", "evolution_schedule_checksum_algorithm", "evolution_schedule_checksum", "scheduled_operator_family_index", "scheduled_operator_family_kind", "scheduled_operator_family_command", "scheduled_operator_family_selection_rule", "scheduled_operator_family_output_gate" ]; const hasScheduleField = suffixes.some((suffix) => fields[`${prefix}.${suffix}`] !== undefined); if (!hasScheduleField) { return undefined; } if (!operatorReceipt) { return null; } const recipeVersion = fields[`${prefix}.evolution_recipe_version`]; const recipeStrategy = fields[`${prefix}.evolution_recipe_strategy`]; const recipeStatus = fields[`${prefix}.evolution_recipe_status`]; const selectionSource = fields[`${prefix}.evolution_selection_source`]; const relatednessContractChecksum = fields[`${prefix}.evolution_relatedness_contract_checksum`]; const scheduleChecksumAlgorithm = fields[`${prefix}.evolution_schedule_checksum_algorithm`]; const scheduleChecksum = fields[`${prefix}.evolution_schedule_checksum`]; const familyIndex = registryDecimalCount(fields[`${prefix}.scheduled_operator_family_index`]); const familyKind = fields[`${prefix}.scheduled_operator_family_kind`]; const familyCommand = fields[`${prefix}.scheduled_operator_family_command`]; const familySelectionRule = fields[`${prefix}.scheduled_operator_family_selection_rule`]; const familyOutputGate = fields[`${prefix}.scheduled_operator_family_output_gate`]; if ( recipeVersion !== registryEvolutionRecipeVersion || recipeStrategy !== registryEvolutionRecipeStrategy || recipeStatus !== registryEvolutionRecipeStatus || selectionSource !== registryEvolutionSelectionSource || !isRegistryHex64(relatednessContractChecksum) || scheduleChecksumAlgorithm !== registryEvolutionScheduleChecksumAlgorithm || !isRegistryHex64(scheduleChecksum) || familyIndex === null || !isRegistrySlug(familyKind) || !isRegistrySlug(familyCommand) || !isRegistrySlug(familySelectionRule) || !isRegistrySlug(familyOutputGate) || familyKind !== operatorReceipt.operatorKind ) { return null; } return { recipeVersion, recipeStrategy, recipeStatus, selectionSource, relatednessContractChecksum, scheduleChecksumAlgorithm, scheduleChecksum, familyIndex, familyKind, familyCommand, familySelectionRule, familyOutputGate }; } // Reads selector phenotype evidence that binds runtime and eval observations to provenance. function registryPhenotypeEvidenceEntry(fields, prefix) { const phenotypeEvidenceId = fields[`${prefix}.phenotype_evidence_id`]; const strategy = fields[`${prefix}.phenotype_evidence_strategy`]; const status = fields[`${prefix}.phenotype_evidence_status`]; const checksum = fields[`${prefix}.phenotype_evidence_checksum`]; if ( !isRegistryHex64(phenotypeEvidenceId) || strategy !== registryPhenotypeEvidenceStrategy || status !== registryPhenotypeEvidenceStatus || !isRegistryHex64(checksum) ) { return null; } return { id: phenotypeEvidenceId, strategy, status, checksum }; } // Reads selector heritable artifact metadata that binds served model identity to provenance. function registryHeritableArtifactEntry(fields, prefix) { const artifactId = fields[`${prefix}.heritable_artifact_id`]; const strategy = fields[`${prefix}.heritable_artifact_strategy`]; const status = fields[`${prefix}.heritable_artifact_status`]; const checksum = fields[`${prefix}.heritable_artifact_checksum`]; if ( !isRegistryHex64(artifactId) || strategy !== registryHeritableArtifactStrategy || status !== registryHeritableArtifactStatus || !isRegistryHex64(checksum) ) { return null; } return { id: artifactId, strategy, status, checksum }; } // Reads scoped eval facts as a compact fitness vector for selector provenance. function registryEvalEvidenceEntry(fields, prefix) { const checksum = fields[`${prefix}.eval_case_evidence_checksum`]; const casesPassed = registryDecimalByteCount(fields[`${prefix}.cases_passed`]); const fitnessVectorStatus = fields[`${prefix}.fitness_vector_status`]; const fitnessVectorChecksum = fields[`${prefix}.fitness_vector_checksum`]; if ( !isRegistryHex64(checksum) || casesPassed === null || fitnessVectorStatus !== registryFitnessVectorStatus || !isRegistryHex64(fitnessVectorChecksum) ) { return null; } return { checksum, casesPassed, fitnessVectorStatus, fitnessVectorChecksum, qualityScope: fields[`${prefix}.quality_scope`] || "", qualityBoundary: fields[`${prefix}.quality_boundary`] || "", evalDataset: fields[`${prefix}.eval_dataset`] || "" }; } function registryModulePlanEntry( fields, prefix, candidateId, modelPath, adapters, adapterFamily, assembly, modelBytes, tokenizerChecksum, contextTokenLimit, maxTokens ) { const keys = [ "module_plan_path", "module_plan_checksum", "module_plan_label", "module_plan_status", "module_plan_kind", "module_plan_strategy", "module_plan_resource_class", "module_plan_profile", "module_plan_execution_profile", "module_plan_fetch_policy", "module_plan_origin_policy", "module_plan_fetch_count_limit", "module_plan_planned_fetch_count", "module_plan_route_set_version", "module_plan_route_set_checksum_algorithm", "module_plan_route_set_checksum", "module_plan_operator_receipt_path", "module_plan_operator_receipt_checksum", "module_plan_wasm_memory_initial_pages", "module_plan_wasm_export_set", "module_plan_wasm_transfer_strategy", "module_plan_model_release_strategy", "module_plan_runtime_reset_strategy", "module_plan_adapter_validation_strategy", "module_plan_adapter_validation_count", "module_plan_adapter_apply_count", "module_plan_wasm_heap_min_bytes", "module_plan_context_token_limit", "module_plan_sampler_candidate_cap", "module_plan_tokenizer_checksum", "module_plan_model_byte_budget", "module_plan_adapter_byte_budget", "module_plan_adapter_stack_byte_budget", "module_plan_prompt_byte_limit", "module_plan_runtime_scratch_byte_budget", "module_plan_output_byte_limit", "module_plan_kv_cache_byte_budget", "module_plan_kv_cache_page_count", "module_plan_total_byte_budget", "module_plan_total_byte_budget_limit", "module_plan_module_count" ]; const hasModulePlan = keys.some((key) => fields[`${prefix}.${key}`]); if (!hasModulePlan) { return undefined; } const receiptPath = fields[`${prefix}.module_plan_path`]; const receiptChecksum = fields[`${prefix}.module_plan_checksum`]; const moduleCount = Number.parseInt(fields[`${prefix}.module_plan_module_count`] || "0", 10); const wasmMemoryInitialPages = Number.parseInt( fields[`${prefix}.module_plan_wasm_memory_initial_pages`] || "0", 10 ); const fetchCountLimit = registryDecimalCount( fields[`${prefix}.module_plan_fetch_count_limit`] ); const plannedFetchCount = registryDecimalCount( fields[`${prefix}.module_plan_planned_fetch_count`] ); const routeSetVersion = fields[`${prefix}.module_plan_route_set_version`] || ""; const routeSetChecksumAlgorithm = fields[`${prefix}.module_plan_route_set_checksum_algorithm`] || ""; const routeSetChecksum = fields[`${prefix}.module_plan_route_set_checksum`] || ""; const operatorReceiptPath = fields[`${prefix}.module_plan_operator_receipt_path`] || ""; const operatorReceiptChecksum = fields[`${prefix}.module_plan_operator_receipt_checksum`] || ""; const wasmExportSet = fields[`${prefix}.module_plan_wasm_export_set`] || ""; const wasmHeapMinBytes = registryDecimalByteCount( fields[`${prefix}.module_plan_wasm_heap_min_bytes`] ); const planContextTokenLimit = registryDecimalCount( fields[`${prefix}.module_plan_context_token_limit`] ); const samplerCandidateCap = registryDecimalCount( fields[`${prefix}.module_plan_sampler_candidate_cap`] ); const adapterApplyCount = registryDecimalCount( fields[`${prefix}.module_plan_adapter_apply_count`] ); const adapterValidationCount = registryDecimalCount( fields[`${prefix}.module_plan_adapter_validation_count`] ); const planTokenizerChecksum = fields[`${prefix}.module_plan_tokenizer_checksum`] || ""; const modelByteBudget = registryDecimalByteCount(fields[`${prefix}.module_plan_model_byte_budget`]); const adapterByteBudget = registryDecimalByteCount(fields[`${prefix}.module_plan_adapter_byte_budget`]); const adapterStackByteBudget = registryDecimalByteCount( fields[`${prefix}.module_plan_adapter_stack_byte_budget`] ); const promptByteLimit = registryDecimalByteCount(fields[`${prefix}.module_plan_prompt_byte_limit`]); const runtimeScratchByteBudget = registryDecimalByteCount( fields[`${prefix}.module_plan_runtime_scratch_byte_budget`] ); const outputByteLimit = registryDecimalByteCount(fields[`${prefix}.module_plan_output_byte_limit`]); const kvCacheByteBudget = registryDecimalByteCount(fields[`${prefix}.module_plan_kv_cache_byte_budget`]); const kvCachePageCount = Number.parseInt(fields[`${prefix}.module_plan_kv_cache_page_count`] || "0", 10); const totalByteBudget = registryDecimalByteCount(fields[`${prefix}.module_plan_total_byte_budget`]); const totalByteBudgetLimit = registryDecimalByteCount( fields[`${prefix}.module_plan_total_byte_budget_limit`] ); if (!isSafeRegistryModulePlanPath(receiptPath) || !isRegistryHex64(receiptChecksum)) { return null; } if (fields[`${prefix}.module_plan_status`] !== registryModulePlanStatus) { return null; } if (fields[`${prefix}.module_plan_kind`] !== registryModulePlanKind) { return null; } if (fields[`${prefix}.module_plan_strategy`] !== registryModulePlanStrategy) { return null; } if (fields[`${prefix}.module_plan_resource_class`] !== registryModulePlanResourceClass) { return null; } if (fields[`${prefix}.module_plan_profile`] !== registryModulePlanProfile) { return null; } if (fields[`${prefix}.module_plan_execution_profile`] !== registryModulePlanExecutionProfile) { return null; } if (fields[`${prefix}.module_plan_fetch_policy`] !== registryModulePlanFetchPolicy) { return null; } if (fields[`${prefix}.module_plan_origin_policy`] !== registryModulePlanOriginPolicy) { return null; } if ( fetchCountLimit === null || fetchCountLimit !== registryModulePlanFetchCountLimit ) { return null; } if ( !Number.isInteger(wasmMemoryInitialPages) || String(wasmMemoryInitialPages) !== fields[`${prefix}.module_plan_wasm_memory_initial_pages`] || wasmMemoryInitialPages !== registryModulePlanWasmMemoryInitialPages ) { return null; } if (wasmExportSet !== registryModulePlanWasmExportSet) { return null; } if (fields[`${prefix}.module_plan_wasm_transfer_strategy`] !== registryModulePlanWasmTransferStrategy) { return null; } if (fields[`${prefix}.module_plan_model_release_strategy`] !== registryModulePlanModelReleaseStrategy) { return null; } if (fields[`${prefix}.module_plan_runtime_reset_strategy`] !== registryModulePlanRuntimeResetStrategy) { return null; } if ( fields[`${prefix}.module_plan_adapter_validation_strategy`] !== registryModulePlanAdapterValidationStrategy ) { return null; } if ( adapterApplyCount === null || !adapterFamily || adapterApplyCount !== adapterFamily.autoApplyStackCount || adapterApplyCount !== registryModulePlanAdapterApplyCount ) { return null; } if ( adapterValidationCount === null || !adapterFamily || adapterValidationCount !== adapterFamily.autoApplyStackCount || adapterValidationCount !== adapterApplyCount || adapterValidationCount !== registryModulePlanAdapterValidationCount ) { return null; } if ( planContextTokenLimit === null || planContextTokenLimit !== contextTokenLimit || planContextTokenLimit < maxTokens || planContextTokenLimit > registryModulePlanContextTokenLimitLimit ) { return null; } // Keeps generated module plans bound to the runtime's fixed-size sampler candidate buffer. if ( samplerCandidateCap === null || samplerCandidateCap !== registryModulePlanSamplerCandidateCap ) { return null; } if ( !isRegistryHex64(planTokenizerChecksum) || !isRegistryHex64(tokenizerChecksum) || planTokenizerChecksum !== tokenizerChecksum ) { return null; } if (!adapterFamily || !assembly) { return null; } if (modelByteBudget === null || modelByteBudget !== modelBytes) { return null; } if (adapterByteBudget === null || adapterByteBudget !== adapterFamily.autoApplyByteBudget) { return null; } if ( adapterStackByteBudget === null || adapterStackByteBudget <= 0 || adapterStackByteBudget > adapterByteBudget ) { return null; } if (promptByteLimit === null || promptByteLimit !== registryModulePlanPromptByteLimit) { return null; } if ( wasmHeapMinBytes === null || wasmHeapMinBytes !== modulePlanWasmHeapMinBytes( modelByteBudget, adapterStackByteBudget, promptByteLimit ) ) { return null; } if ( runtimeScratchByteBudget === null || runtimeScratchByteBudget !== registryModulePlanRuntimeScratchByteBudget ) { return null; } if (outputByteLimit === null || outputByteLimit !== registryModulePlanOutputByteLimit) { return null; } if ( kvCacheByteBudget === null || kvCacheByteBudget > registryModulePlanKvCacheByteBudgetLimit || !Number.isInteger(kvCachePageCount) || String(kvCachePageCount) !== fields[`${prefix}.module_plan_kv_cache_page_count`] || kvCachePageCount !== modulePlanPageCountForBytes(kvCacheByteBudget) ) { return null; } if ( totalByteBudget === null || totalByteBudget < modelBytes + adapterStackByteBudget + promptByteLimit + runtimeScratchByteBudget + outputByteLimit + kvCacheByteBudget || totalByteBudget > totalByteBudgetLimit ) { return null; } if ( totalByteBudgetLimit === null || totalByteBudgetLimit !== registryModulePlanTotalByteBudgetLimit ) { return null; } const expectedModuleCount = 4 + adapterFamily.autoApplyStackCount; if (!Number.isInteger(moduleCount) || moduleCount !== expectedModuleCount) { return null; } const declaredFetchCount = registryModulePlanDeclaredFetchCount(adapterFamily, assembly, moduleCount); if ( plannedFetchCount === null || plannedFetchCount !== declaredFetchCount || plannedFetchCount !== registryModulePlanPlannedFetchCount || plannedFetchCount > fetchCountLimit ) { return null; } if (routeSetVersion !== registryModulePlanRouteSetVersion) { return null; } if (routeSetChecksumAlgorithm !== registryModulePlanRouteSetChecksumAlgorithm) { return null; } const operatorEvidencePrefix = assemblyEvidencePrefixFromOperatorPath( candidateId, operatorReceiptPath ); if (!operatorEvidencePrefix || !isRegistryHex64(operatorReceiptChecksum)) { return null; } const routeSetRoutes = modulePlanRouteSetRoutes( candidateId, receiptPath, modelPath, `${modelPath}.manifest`, assembly.path, adapterFamily.path, adapters, adapterFamily.autoApplyStackCount, operatorEvidencePrefix ); const expectedRouteSetChecksum = routeSetRoutes ? modulePlanRouteSetChecksum(routeSetRoutes) : ""; if ( !isRegistryHex64(routeSetChecksum) || routeSetChecksum !== expectedRouteSetChecksum ) { return null; } if ( !isSafeAssemblyEvidencePath(operatorReceiptPath) || operatorReceiptPath !== modulePlanEvidenceRoute(candidateId, `${operatorEvidencePrefix}.operator`) ) { return null; } return { label: fields[`${prefix}.module_plan_label`] || "Module plan", path: receiptPath, checksum: receiptChecksum, status: fields[`${prefix}.module_plan_status`], kind: fields[`${prefix}.module_plan_kind`], strategy: fields[`${prefix}.module_plan_strategy`], resourceClass: fields[`${prefix}.module_plan_resource_class`], profile: fields[`${prefix}.module_plan_profile`], executionProfile: fields[`${prefix}.module_plan_execution_profile`], fetchPolicy: fields[`${prefix}.module_plan_fetch_policy`], originPolicy: fields[`${prefix}.module_plan_origin_policy`], fetchCountLimit, plannedFetchCount, routeSetVersion, routeSetChecksumAlgorithm, routeSetChecksum, operatorReceiptPath, operatorReceiptChecksum, wasmMemoryInitialPages, wasmExportSet, wasmTransferStrategy: fields[`${prefix}.module_plan_wasm_transfer_strategy`], modelReleaseStrategy: fields[`${prefix}.module_plan_model_release_strategy`], runtimeResetStrategy: fields[`${prefix}.module_plan_runtime_reset_strategy`], adapterValidationStrategy: fields[`${prefix}.module_plan_adapter_validation_strategy`], adapterValidationCount, adapterApplyCount, wasmHeapMinBytes, contextTokenLimit: planContextTokenLimit, samplerCandidateCap, tokenizerChecksum: planTokenizerChecksum, modelByteBudget, adapterByteBudget, adapterStackByteBudget, promptByteLimit, runtimeScratchByteBudget, outputByteLimit, kvCacheByteBudget, kvCachePageCount, totalByteBudget, totalByteBudgetLimit, moduleCount }; } // Counts route fetches implied by selector metadata before a generated model is accepted. function registryModulePlanDeclaredFetchCount(adapterFamily, assembly, moduleCount) { let fetchCount = 1 + moduleCount; if (assembly) { fetchCount += assemblyEvidenceRoutesForOperatorPrefix("operator").length; } if (adapterFamily) { fetchCount += adapterFamily.count; } return fetchCount; } // Builds the ordered route set fetched by generated browser self-assembly. function modulePlanRouteSetRoutes( candidateId, modulePlanPath, modelPath, manifestPath, assemblyPath, adapterFamilyPath, adapters, stackCount, operatorEvidencePrefix ) { if ( !candidateId || !modulePlanPath || !modelPath || !manifestPath || !assemblyPath || !adapterFamilyPath || !operatorEvidencePrefix || !Array.isArray(adapters) ) { return null; } const stackIndexes = modulePlanAutoApplyStackIndexes(adapters.length, stackCount); if (!stackIndexes) { return null; } const routes = []; modulePlanPushRoute(routes, "module-plan-receipt", modulePlanPath); modulePlanPushRoute(routes, "model", modelPath); modulePlanPushRoute(routes, "model-manifest", manifestPath); modulePlanPushRoute(routes, "assembly-receipt", assemblyPath); for (const route of assemblyEvidenceRoutesForOperatorPrefix(operatorEvidencePrefix)) { modulePlanPushRoute(routes, "assembly-evidence", modulePlanEvidenceRoute(candidateId, route[2])); } modulePlanPushRoute(routes, "adapter-family-receipt", adapterFamilyPath); for (const adapter of adapters) { if (!adapter || !adapter.manifestPath) { return null; } modulePlanPushRoute(routes, "adapter-manifest", adapter.manifestPath); } for (const adapterIndex of stackIndexes) { const adapter = adapters[adapterIndex]; if (!adapter || !adapter.path) { return null; } modulePlanPushRoute(routes, "adapter-stack-artifact", adapter.path); } return routes; } function modulePlanAutoApplyStackIndexes(adapterCount, stackCount) { // Mirrors the generated adapter-family policy before the family receipt is loaded. if ( !Number.isInteger(adapterCount) || !Number.isInteger(stackCount) || adapterCount < 1 || stackCount < 1 || stackCount > adapterCount ) { return null; } const expectedStackCount = adapterCount >= 3 ? adapterCount - 1 : adapterCount; if (stackCount !== expectedStackCount) { return null; } const indexes = []; for (let index = adapterCount - stackCount; index < adapterCount; index += 1) { indexes.push(index); } return indexes; } function modulePlanPushRoute(routes, kind, path) { // Keeps route hashing keyed by both route class and route path. routes.push({ kind, path }); } function modulePlanEvidenceRoute(candidateId, fileName) { return `../evidence/${candidateId}/${fileName}`; } function assemblyEvidenceRoutesForOperatorPrefix(operatorEvidencePrefix) { // Builds the assembly evidence route family for the operator that produced the candidate. return assemblyEvidenceBaseRoutes.concat( assemblyOperatorEvidenceRoutes.map(([pathKey, checksumKey, suffix]) => [ pathKey, checksumKey, `${operatorEvidencePrefix}.${suffix}` ]) ); } function assemblyEvidencePrefixFromOperatorPath(candidateId, operatorReceiptPath) { // Derives the operator evidence prefix from the bound operator receipt route. const prefix = `../evidence/${candidateId}/`; const suffix = ".operator"; if ( !isSafeAssemblyEvidencePath(operatorReceiptPath) || !operatorReceiptPath.startsWith(prefix) || !operatorReceiptPath.endsWith(suffix) ) { return ""; } const operatorEvidencePrefix = operatorReceiptPath.slice( prefix.length, operatorReceiptPath.length - suffix.length ); return /^[a-z0-9][a-z0-9-]{0,63}$/.test(operatorEvidencePrefix) ? operatorEvidencePrefix : ""; } function modulePlanRouteSetChecksum(routes) { // Hashes the same route-list text emitted by the Rust bundle writer. const lines = [ `route_set_version=${registryModulePlanRouteSetVersion}`, `route_set_checksum_algorithm=${registryModulePlanRouteSetChecksumAlgorithm}`, `route_count=${routes.length}` ]; for (let index = 0; index < routes.length; index += 1) { lines.push(`route.${index}.kind=${routes[index].kind}`); lines.push(`route.${index}.path=${routes[index].path}`); } return textChecksumHex(`${lines.join("\n")}\n`); } function modulePlanWasmHeapMinBytes(modelByteBudget, adapterStackByteBudget, promptByteLimit) { return Math.max( registryModulePlanWasmHeapMinBytes, modelByteBudget, adapterStackByteBudget, promptByteLimit ); } function registryModelEntries(fields) { if (!fields || fields.tinyrustlm_selector_registry_version !== "1") { return null; } if (fields.registry_status !== "admitted-records-only") { return null; } const registryByteBudget = registrySelectorModelByteBudget(fields.selector_model_byte_budget); if (registryByteBudget === null) { return null; } if (!registryTextSidecarBudgets(fields)) { return null; } const entryCount = Number.parseInt(fields.entry_count || "0", 10); if (!Number.isInteger(entryCount) || entryCount < 1 || entryCount > 64) { return null; } const models = Object.create(null); for (let index = 0; index < entryCount; index += 1) { const prefix = `entry.${index}`; if (fields[`${prefix}.selector_status`] !== "admitted") { return null; } const modelPath = fields[`${prefix}.model_path`]; if (!isSafeRegistryModelPath(modelPath)) { return null; } const candidateId = fields[`${prefix}.candidate_id`]; if (!candidateId) { return null; } if (models[candidateId]) { return null; } const maxTokens = clampInteger(fields[`${prefix}.max_tokens`], 1, 512, 8); const modelBytes = registryModelBytes(fields[`${prefix}.model_bytes`], registryByteBudget); if (modelBytes === null) { return null; } const modelShape = fields[`${prefix}.model_shape`] || ""; const contextTokenLimit = registryModelShapeContextTokenLimit(modelShape); if (contextTokenLimit === null || contextTokenLimit < maxTokens) { return null; } const tokenizerChecksum = fields[`${prefix}.tokenizer_checksum`] || ""; if (tokenizerChecksum && !isRegistryHex64(tokenizerChecksum)) { return null; } const slmChecksum = fields[`${prefix}.slm_checksum`] || ""; if (!isRegistryHex64(slmChecksum)) { return null; } const quantization = fields[`${prefix}.quantization`] || ""; const adapters = registryAdapterEntries(fields, prefix, quantization); if (!adapters) { return null; } const adapterFamily = registryAdapterFamilyEntry(fields, prefix, adapters.length); if (adapterFamily === null) { return null; } const assembly = registryAssemblyEntry(fields, prefix); if (assembly === null) { return null; } const genome = registryGenomeEntry(fields, prefix); if (!genome) { return null; } const species = registrySpeciesEntry(fields, prefix); if (!species) { return null; } const novelty = registryNoveltyEntry(fields, prefix); if (!novelty) { return null; } const population = registryPopulationEntry(fields, prefix); if (!population) { return null; } const mateSelection = registryMateSelectionEntry(fields, prefix); if (!mateSelection) { return null; } const operatorReceipt = registryOperatorReceiptEntry( fields, prefix, candidateId, assembly, modelBytes, slmChecksum ); if (operatorReceipt === null) { return null; } const evolutionSchedule = registryEvolutionScheduleEntry(fields, prefix, operatorReceipt); if (evolutionSchedule === null) { return null; } const phenotypeEvidence = registryPhenotypeEvidenceEntry(fields, prefix); if (!phenotypeEvidence) { return null; } const heritableArtifact = registryHeritableArtifactEntry(fields, prefix); if (!heritableArtifact) { return null; } const evalEvidence = registryEvalEvidenceEntry(fields, prefix); if (!evalEvidence) { return null; } const modulePlan = registryModulePlanEntry( fields, prefix, candidateId, modelPath, adapters, adapterFamily, assembly, modelBytes, tokenizerChecksum, contextTokenLimit, maxTokens ); if (modulePlan === null) { return null; } models[candidateId] = { candidateId, label: fields[`${prefix}.display_name`] || candidateId, path: modelPath, modelBytes, maxTokens, contextTokenLimit, tokenizerChecksum, quantization, adapters, adapterFamily: adapterFamily || null, autoApplyPreferredAdapter: Boolean(adapterFamily), genome, species, novelty, population, mateSelection, operatorReceipt: operatorReceipt || null, evolutionSchedule: evolutionSchedule || null, phenotypeEvidence, heritableArtifact, evalEvidence, assembly: assembly || null, modulePlan: modulePlan || null }; } const defaultModelKey = registryDefaultModelKey(fields, models); if (defaultModelKey === null) { return null; } return { models, defaultModelKey }; } function registrySelectorModelByteBudget(value) { const byteBudget = registryDecimalByteCount(value); if (byteBudget === null || byteBudget > selectorModelByteBudget) { return null; } return byteBudget; } function registryTextSidecarBudgets(fields) { return registryExactByteBudget( fields.selector_registry_text_byte_budget, selectorRegistryTextByteBudget ) && registryExactByteBudget(fields.manifest_text_byte_budget, manifestTextByteBudget) && registryExactByteBudget(fields.receipt_text_byte_budget, receiptTextByteBudget) && registryExactByteBudget(fields.evidence_text_byte_budget, evidenceTextByteBudget); } function registryExactByteBudget(value, expected) { const byteBudget = registryDecimalByteCount(value); return byteBudget !== null && byteBudget === expected; } function registryModelBytes(value, byteBudget) { const modelBytes = registryDecimalByteCount(value); if (modelBytes === null || modelBytes > byteBudget) { return null; } return modelBytes; } function runtimeWasmManifestBytes(value) { const byteCount = registryDecimalByteCount(value); if (byteCount === null || byteCount < 1) { return null; } return byteCount; } function registryAdapterAutoApplyBudget(value) { const byteBudget = registryDecimalByteCount(value); if (byteBudget === null || byteBudget > registryAdapterAutoApplyByteBudget) { return null; } return byteBudget; } function registryDecimalCount(value) { // Accepts exact positive decimal registry fields without whitespace or leading zero drift. if (!value) { return null; } const count = Number.parseInt(value, 10); if ( !Number.isSafeInteger(count) || String(count) !== value || count < 1 ) { return null; } return count; } function registryDecimalByteCount(value) { return registryDecimalCount(value); } function registryModelShapeContextTokenLimit(modelShape) { const match = String(modelShape || "").match(/(?:^|,)(?:context|ctx)=(\d+)(?:,|$)/); if (!match) { return null; } const tokens = registryDecimalCount(match[1]); if (tokens === null || tokens > registryModulePlanContextTokenLimitLimit) { return null; } return tokens; } function modulePlanPageCountForBytes(bytes) { // Mirrors the Rust 64 KiB page math for selector and receipt KV-cache checks. return Math.ceil(bytes / (64 * 1024)); } function registryDefaultModelKey(fields, models) { const keys = [ "selector_default_strategy", "selector_default_candidate_id", "selector_default_quantization" ]; const hasDefault = keys.some((key) => fields[key]); if (!hasDefault) { return ""; } if (fields.selector_default_strategy !== selectorDefaultStrategy) { return null; } const candidateId = fields.selector_default_candidate_id; const model = models[candidateId]; if (!model || fields.selector_default_quantization !== model.quantization) { return null; } return candidateId; } // Loads the optional generated selector registry before the first model is chosen. async function loadSelectorRegistry() { try { const text = await fetchTextWithinBudget( paths.registry, selectorRegistryTextByteBudget, "selector registry", true ); if (text === null) { return; } const fields = parseManifest(text); const registry = registryModelEntries(fields); if (!registry) { return; } paths.models = registry.models; state.selectorRegistry = fields; state.selectorDefaultModelKey = registry.defaultModelKey || ""; renderModelOptions(paths.models, Boolean(state.selectorDefaultModelKey)); } catch (_error) { state.selectorRegistry = null; state.selectorDefaultModelKey = ""; } } async function loadRuntimeWasmBytes() { const manifestText = await fetchTextWithinBudget( paths.wasmManifest, manifestTextByteBudget, "WASM manifest" ); const fields = parseManifest(manifestText); requireManifestEqual(fields, "tinyrustlm_wasm_manifest_version", "1", "WASM manifest"); requireManifestEqual(fields, "runtime_kind", runtimeWasmKind, "WASM manifest"); requireManifestEqual(fields, "runtime_status", runtimeWasmStatus, "WASM manifest"); requireManifestEqual(fields, "runtime_wasm_path", paths.wasm, "WASM manifest"); requireManifestEqual(fields, "required_next_gate", runtimeWasmNextGate, "WASM manifest"); const expectedBytes = runtimeWasmManifestBytes( requireManifestField(fields, "runtime_wasm_bytes", "WASM manifest") ); if (expectedBytes === null) { throw new Error("WASM manifest field runtime_wasm_bytes was invalid"); } const expectedChecksum = requireManifestField(fields, "runtime_wasm_checksum", "WASM manifest"); const response = await fetch(paths.wasm, localFetchOptions); if (!response.ok) { throw new Error(`Unable to fetch WASM runtime (${response.status})`); } const bytes = new Uint8Array(await response.arrayBuffer()); if (bytes.length !== expectedBytes) { throw new Error("WASM runtime byte length mismatch"); } requireChecksumEqual(bytesChecksumHex(bytes), expectedChecksum, "WASM runtime"); return bytes; } // Renders manifest provenance together with selector genome, species, novelty, population, operator, phenotype, artifact, and fitness evidence. function renderProvenance(status, fields, isError) { setText(el.provenanceState, status, isError); const model = paths.models[state.activeModelKey] || null; const genome = model && model.genome ? model.genome : null; const species = model && model.species ? model.species : null; const novelty = model && model.novelty ? model.novelty : null; const population = model && model.population ? model.population : null; const mateSelection = model && model.mateSelection ? model.mateSelection : null; const operatorReceipt = model && model.operatorReceipt ? model.operatorReceipt : null; const evolutionSchedule = model && model.evolutionSchedule ? model.evolutionSchedule : null; const phenotypeEvidence = model && model.phenotypeEvidence ? model.phenotypeEvidence : null; const heritableArtifact = model && model.heritableArtifact ? model.heritableArtifact : null; const evalEvidence = model && model.evalEvidence ? model.evalEvidence : null; el.provenanceSourceKind.textContent = manifestValue(fields, "source_kind"); el.provenanceAdmission.textContent = manifestValue(fields, "admission_status"); el.provenanceQualityClaim.textContent = manifestValue(fields, "quality_claim"); el.provenanceTrainedClaim.textContent = manifestValue(fields, "trained_quality_claim"); el.provenanceGenome.textContent = genome ? genome.id : "unavailable"; el.provenanceSpecies.textContent = species ? `${species.fitStatus} / ${species.id} / ${species.fitChecksum}` : "unavailable"; el.provenanceNovelty.textContent = novelty ? `${novelty.status} / ${novelty.id} / ${novelty.checksum}` : "unavailable"; el.provenancePopulation.textContent = population ? `${population.status} / ${population.id} / ${population.checksum}` : "unavailable"; el.provenanceMateSelection.textContent = mateSelection ? `${mateSelection.status} / ${mateSelection.parentCount} parents / ${mateSelection.id} / ${mateSelection.checksum}` : "unavailable"; el.provenanceOperator.textContent = operatorReceipt ? `${operatorReceipt.status} / ${operatorReceipt.operatorKind} / ${operatorReceipt.checksum}` : "unavailable"; el.provenanceSchedule.textContent = evolutionSchedule ? `${evolutionSchedule.recipeStatus} / family ${evolutionSchedule.familyIndex} / ${evolutionSchedule.familyCommand} / ${evolutionSchedule.scheduleChecksum}` : "unavailable"; el.provenancePhenotype.textContent = phenotypeEvidence ? `${phenotypeEvidence.status} / ${phenotypeEvidence.id} / ${phenotypeEvidence.checksum}` : "unavailable"; el.provenanceArtifact.textContent = heritableArtifact ? `${heritableArtifact.status} / ${heritableArtifact.id} / ${heritableArtifact.checksum}` : "unavailable"; el.provenanceFitness.textContent = evalEvidence ? `${evalEvidence.fitnessVectorStatus} / ${evalEvidence.fitnessVectorChecksum}` : "unavailable"; el.provenanceEvalCases.textContent = evalEvidence ? `${evalEvidence.casesPassed} passed` : "unavailable"; el.provenanceEvalChecksum.textContent = evalEvidence ? evalEvidence.checksum : "unavailable"; el.provenanceChecksum.textContent = manifestValue(fields, "slm_checksum"); el.provenanceNextGate.textContent = manifestValue(fields, "required_next_gate"); } function renderAssembly(status, fields, isError) { setText(el.assemblyState, status, isError); el.assemblyKind.textContent = manifestValue(fields, "assembly_kind"); el.assemblyParents.textContent = manifestValue(fields, "parent_count"); el.assemblyOperator.textContent = manifestValue(fields, "operator_receipt_checksum"); el.assemblyLedger.textContent = manifestValue(fields, "promotion_ledger_checksum"); el.assemblyNextGate.textContent = manifestValue(fields, "required_next_gate"); } function modulePlanStackSummary(fields) { if (!fields) { return "unavailable"; } const countValue = fields.adapter_auto_apply_stack_count; const count = Number.parseInt(countValue || "0", 10); if (!Number.isInteger(count) || String(count) !== countValue || count < 1) { return "none"; } const routes = []; for (let stackIndex = 0; stackIndex < count; stackIndex += 1) { const pathValue = fields[`module.${stackIndex + 4}.adapter_path`]; if (!pathValue) { return "unavailable"; } routes.push(pathValue); } return `${count}: ${routes.join(", ")}`; } function modulePlanByteSummary(fields, key) { if (!fields) { return "unavailable"; } const value = fields[key]; if (!value) { return "unavailable"; } return `${value} bytes`; } function modulePlanTokenSummary(fields, key) { if (!fields) { return "unavailable"; } const tokens = registryDecimalCount(fields[key]); return tokens === null ? "unavailable" : `${tokens} tokens`; } function modulePlanSamplerSummary(fields) { if (!fields) { return "unavailable"; } const candidates = registryDecimalCount(fields.module_plan_sampler_candidate_cap); return candidates === null ? "unavailable" : `${candidates} candidates`; } // Formats the receipt-owned route-count envelope for the Module Plan panel. function modulePlanFetchCountSummary(fields) { if (!fields) { return "unavailable"; } const fetches = registryDecimalCount(fields.module_plan_fetch_count_limit); return fetches === null ? "unavailable" : `${fetches} fetches`; } // Formats the exact self-assembly route count declared by the verified receipt. function modulePlanPlannedFetchSummary(fields) { if (!fields) { return "unavailable"; } const fetches = registryDecimalCount(fields.module_plan_planned_fetch_count); return fetches === null ? "unavailable" : `${fetches} fetches`; } // Formats the browser-observed generated self-assembly route count. function modulePlanActualFetchSummary(fields) { if (!fields || !Number.isInteger(state.modulePlanActualFetchCount)) { return "unavailable"; } return `${state.modulePlanActualFetchCount} fetches`; } // Formats the browser-observed route set checksum once all planned routes are seen. function modulePlanActualRouteSetSummary(fields) { if (!fields || !Array.isArray(state.modulePlanActualRoutes)) { return "unavailable"; } const plannedFetchCount = registryDecimalCount(fields.module_plan_planned_fetch_count); if (plannedFetchCount === null) { return "unavailable"; } if (state.modulePlanActualRoutes.length !== plannedFetchCount) { return `${state.modulePlanActualRoutes.length}/${plannedFetchCount} routes`; } return isRegistryHex64(state.modulePlanActualRouteSetChecksum) ? state.modulePlanActualRouteSetChecksum : "unavailable"; } // Formats the browser-observed byte total for receipt-declared modules. function modulePlanActualModuleByteSummary(fields) { if ( !fields || !Number.isSafeInteger(state.modulePlanActualModuleBytes) || !Array.isArray(state.modulePlanActualModuleByteIndexes) ) { return "unavailable"; } const declared = modulePlanModuleByteTotal(fields); if (!declared) { return "unavailable"; } if (state.modulePlanActualModuleByteIndexes.length !== declared.count) { return `${state.modulePlanActualModuleBytes}/${declared.total} bytes`; } return `${state.modulePlanActualModuleBytes} bytes`; } // Formats checksums recomputed from the module payloads accepted by this browser load. function modulePlanActualModuleChecksumSummary(fields) { if (!fields || !Array.isArray(state.modulePlanActualModuleChecksums)) { return "unavailable"; } const declared = modulePlanModuleChecksumList(fields); if (!declared) { return "unavailable"; } let seen = 0; for (const checksum of state.modulePlanActualModuleChecksums) { if (checksum) { seen += 1; } } if (seen !== declared.length) { return `${seen}/${declared.length} checksums`; } const checksums = []; for (let index = 0; index < declared.length; index += 1) { const checksum = state.modulePlanActualModuleChecksums[index]; if (!checksum) { return `${seen}/${declared.length} checksums`; } checksums.push(`${index}: ${checksum}`); } return checksums.join(", "); } function modulePlanModuleByteTotal(fields) { const countValue = fields && fields.module_count; const count = Number.parseInt(countValue || "0", 10); if (!Number.isInteger(count) || String(count) !== countValue || count < 1) { return null; } let total = 0; for (let index = 0; index < count; index += 1) { const bytes = registryDecimalByteCount(fields[`module.${index}.byte_count`]); if (bytes === null) { return null; } total += bytes; } return { count, total }; } function modulePlanModuleChecksumList(fields) { const countValue = fields && fields.module_count; const count = Number.parseInt(countValue || "0", 10); if (!Number.isInteger(count) || String(count) !== countValue || count < 1) { return null; } const checksums = []; for (let index = 0; index < count; index += 1) { const checksum = fields[`module.${index}.checksum`]; if (!isRegistryHex64(checksum)) { return null; } checksums.push(checksum); } return checksums; } function modulePlanModuleByteSummary(fields) { if (!fields) { return "unavailable"; } const countValue = fields.module_count; const count = Number.parseInt(countValue || "0", 10); if (!Number.isInteger(count) || String(count) !== countValue || count < 1) { return "unavailable"; } const byteCounts = []; for (let index = 0; index < count; index += 1) { const byteCount = fields[`module.${index}.byte_count`]; if (!byteCount) { return "unavailable"; } byteCounts.push(`${index}: ${byteCount} bytes`); } return byteCounts.join(", "); } function modulePlanChecksumSummary(fields) { if (!fields) { return "unavailable"; } const countValue = fields.module_count; const count = Number.parseInt(countValue || "0", 10); if (!Number.isInteger(count) || String(count) !== countValue || count < 1) { return "unavailable"; } const checksums = []; for (let index = 0; index < count; index += 1) { const checksum = fields[`module.${index}.checksum`]; if (!checksum) { return "unavailable"; } checksums.push(`${index}: ${checksum}`); } return checksums.join(", "); } function modulePlanRoleSummary(fields) { if (!fields) { return "unavailable"; } const countValue = fields.module_count; const count = Number.parseInt(countValue || "0", 10); if (!Number.isInteger(count) || String(count) !== countValue || count < 1) { return "unavailable"; } const roles = []; for (let index = 0; index < count; index += 1) { const role = fields[`module.${index}.role`]; if (!role) { return "unavailable"; } roles.push(`${index}: ${role}`); } return roles.join(", "); } function modulePlanSlotSummary(fields) { if (!fields) { return "unavailable"; } const countValue = fields.module_count; const count = Number.parseInt(countValue || "0", 10); if (!Number.isInteger(count) || String(count) !== countValue || count < 1) { return "unavailable"; } const slots = []; for (let index = 0; index < count; index += 1) { const slot = fields[`module.${index}.assembly_slot`]; if (!slot) { return "unavailable"; } slots.push(`${index}: ${slot}`); } return slots.join(", "); } function modulePlanPhaseSummary(fields) { if (!fields) { return "unavailable"; } const countValue = fields.module_count; const count = Number.parseInt(countValue || "0", 10); if (!Number.isInteger(count) || String(count) !== countValue || count < 1) { return "unavailable"; } const phases = []; for (let index = 0; index < count; index += 1) { const phase = fields[`module.${index}.phase`]; if (!phase) { return "unavailable"; } phases.push(`${index}: ${phase}`); } return phases.join(", "); } function modulePlanDependencySummary(fields) { if (!fields) { return "unavailable"; } const countValue = fields.module_count; const count = Number.parseInt(countValue || "0", 10); if (!Number.isInteger(count) || String(count) !== countValue || count < 1) { return "unavailable"; } const dependencies = []; for (let index = 0; index < count; index += 1) { const dependency = fields[`module.${index}.depends_on`]; if (!dependency) { return "unavailable"; } dependencies.push(`${index}: ${dependency}`); } return dependencies.join(", "); } function renderModulePlan(status, fields, isError) { setText(el.modulePlanState, status, isError); el.modulePlanKind.textContent = manifestValue(fields, "module_plan_kind"); el.modulePlanResource.textContent = manifestValue(fields, "module_plan_resource_class"); el.modulePlanExecution.textContent = manifestValue(fields, "module_plan_execution_profile"); el.modulePlanFetch.textContent = manifestValue(fields, "module_plan_fetch_policy"); el.modulePlanOrigin.textContent = manifestValue(fields, "module_plan_origin_policy"); el.modulePlanFetchLimit.textContent = modulePlanFetchCountSummary(fields); el.modulePlanPlannedFetchCount.textContent = modulePlanPlannedFetchSummary(fields); updateModulePlanActualFetchCount(fields); el.modulePlanRouteSetVersion.textContent = manifestValue( fields, "module_plan_route_set_version" ); el.modulePlanRouteSetChecksumAlgorithm.textContent = manifestValue( fields, "module_plan_route_set_checksum_algorithm" ); el.modulePlanRouteSetChecksum.textContent = manifestValue( fields, "module_plan_route_set_checksum" ); updateModulePlanActualRouteSetChecksum(fields); el.modulePlanWasmPages.textContent = manifestValue(fields, "module_plan_wasm_memory_initial_pages"); el.modulePlanWasmExportSet.textContent = manifestValue(fields, "module_plan_wasm_export_set"); el.modulePlanWasmTransferStrategy.textContent = manifestValue( fields, "module_plan_wasm_transfer_strategy" ); el.modulePlanModelReleaseStrategy.textContent = manifestValue( fields, "module_plan_model_release_strategy" ); el.modulePlanRuntimeResetStrategy.textContent = manifestValue( fields, "module_plan_runtime_reset_strategy" ); el.modulePlanAdapterValidationStrategy.textContent = manifestValue( fields, "module_plan_adapter_validation_strategy" ); el.modulePlanAdapterValidationCount.textContent = manifestValue( fields, "module_plan_adapter_validation_count" ); el.modulePlanAdapterApplyCount.textContent = manifestValue( fields, "module_plan_adapter_apply_count" ); el.modulePlanWasmHeapMinBytes.textContent = modulePlanByteSummary( fields, "module_plan_wasm_heap_min_bytes" ); el.modulePlanContextTokens.textContent = modulePlanTokenSummary( fields, "module_plan_context_token_limit" ); el.modulePlanSamplerCap.textContent = modulePlanSamplerSummary(fields); el.modulePlanTokenizer.textContent = manifestValue(fields, "module_plan_tokenizer_checksum"); el.modulePlanModules.textContent = manifestValue(fields, "module_count"); el.modulePlanModelBudget.textContent = modulePlanByteSummary(fields, "module_plan_model_byte_budget"); el.modulePlanAdapterBudget.textContent = modulePlanByteSummary(fields, "module_plan_adapter_byte_budget"); el.modulePlanAdapterStackBudget.textContent = modulePlanByteSummary( fields, "module_plan_adapter_stack_byte_budget" ); el.modulePlanScratchBudget.textContent = modulePlanByteSummary( fields, "module_plan_runtime_scratch_byte_budget" ); el.modulePlanPromptLimit.textContent = modulePlanByteSummary( fields, "module_plan_prompt_byte_limit" ); el.modulePlanOutputLimit.textContent = modulePlanByteSummary( fields, "module_plan_output_byte_limit" ); el.modulePlanKvCacheBudget.textContent = modulePlanByteSummary( fields, "module_plan_kv_cache_byte_budget" ); el.modulePlanKvCachePages.textContent = manifestValue(fields, "module_plan_kv_cache_page_count"); el.modulePlanTotalBudget.textContent = modulePlanByteSummary(fields, "module_plan_total_byte_budget"); el.modulePlanTotalLimit.textContent = modulePlanByteSummary( fields, "module_plan_total_byte_budget_limit" ); el.modulePlanBytes.textContent = modulePlanModuleByteSummary(fields); updateModulePlanActualModuleBytes(fields); el.modulePlanChecksums.textContent = modulePlanChecksumSummary(fields); updateModulePlanActualModuleChecksums(fields); el.modulePlanSlots.textContent = modulePlanSlotSummary(fields); el.modulePlanRoles.textContent = modulePlanRoleSummary(fields); el.modulePlanPhases.textContent = modulePlanPhaseSummary(fields); el.modulePlanDepends.textContent = modulePlanDependencySummary(fields); el.modulePlanModel.textContent = manifestValue(fields, "module.0.path"); el.modulePlanStack.textContent = modulePlanStackSummary(fields); } function resetModulePlanTrace(status, isError) { state.modulePlanTrace = []; setText(el.modulePlanTrace, status || "waiting", isError); } function recordModulePlanTrace(label) { state.modulePlanTrace.push(`${state.modulePlanTrace.length}: ${label}`); setText(el.modulePlanTrace, state.modulePlanTrace.join(", "), false); } function modelAdapters(model) { if (!model || !Array.isArray(model.adapters)) { return []; } if (model.adapterFamily && !model.adapterFamilyVerified) { return []; } return model.adapters; } function selectedAdapter() { const model = paths.models[state.activeModelKey]; const adapters = modelAdapters(model); const index = selectedAdapterIndex(adapters); if (index === null) { return null; } return adapters[index]; } function selectedAdapterIndex(adapters) { const index = Number.parseInt(el.adapterSelect.value, 10); if (!Number.isInteger(index) || index < 0 || index >= adapters.length) { return null; } return index; } function renderAdapterOptions(model, status, isError) { const adapters = modelAdapters(model); el.adapterSelect.replaceChildren(); if (adapters.length === 0) { const option = document.createElement("option"); option.value = "none"; option.textContent = "None"; el.adapterSelect.append(option); } else { for (let index = 0; index < adapters.length; index += 1) { const option = document.createElement("option"); option.value = String(index); option.textContent = adapters[index].label || `Adapter ${index + 1}`; el.adapterSelect.append(option); } const preferredIndex = Number.isInteger(model.adapterFamilyPreferredIndex) ? model.adapterFamilyPreferredIndex : 0; if (preferredIndex >= 0 && preferredIndex < adapters.length) { el.adapterSelect.value = String(preferredIndex); } } setText(el.adapterState, status || (adapters.length > 0 ? "ready" : "none"), isError); } function adapterFamilyPreferredIndex(model, fields) { const source = "adapter family receipt"; const indexValue = requireManifestField(fields, "adapter_family_preferred_adapter_index", source); const index = Number.parseInt(indexValue, 10); if (!Number.isInteger(index) || String(index) !== indexValue || index < 0 || index >= model.adapters.length) { throw new Error("Adapter family preferred adapter index mismatch"); } const preferred = model.adapters[index]; requireManifestEqual(fields, "adapter_family_preferred_adapter_path", preferred.path, source); requireManifestEqual(fields, "adapter_family_preferred_manifest_path", preferred.manifestPath, source); return index; } function adapterFamilyAutoApplyIndexes(model, fields) { const source = "adapter family receipt"; requireManifestEqual(fields, "adapter_family_auto_apply_stack_status", registryAdapterAutoApplyStackStatus, source); requireManifestEqual( fields, "adapter_family_auto_apply_stack_strategy", registryAdapterAutoApplyStackStrategy, source ); const countValue = requireManifestField(fields, "adapter_family_auto_apply_stack_count", source); const count = Number.parseInt(countValue, 10); if ( !Number.isInteger(count) || String(count) !== countValue || count < 1 || count > model.adapters.length || (model.adapterFamily && count !== model.adapterFamily.autoApplyStackCount) ) { throw new Error("Adapter family auto-apply stack count mismatch"); } const indexes = []; const seen = new Set(); for (let stackIndex = 0; stackIndex < count; stackIndex += 1) { const prefix = `adapter_family_auto_apply_stack.${stackIndex}`; const indexValue = requireManifestField(fields, `${prefix}.adapter_index`, source); const index = Number.parseInt(indexValue, 10); if ( !Number.isInteger(index) || String(index) !== indexValue || index < 0 || index >= model.adapters.length || seen.has(index) ) { throw new Error("Adapter family auto-apply stack index mismatch"); } const adapter = model.adapters[index]; requireManifestEqual(fields, `${prefix}.adapter_path`, adapter.path, source); requireManifestEqual(fields, `${prefix}.manifest_path`, adapter.manifestPath, source); seen.add(index); indexes.push(index); } return indexes; } // Verifies receipt-declared adapter members before any generated adapter manifest is trusted. function validateAdapterFamilyReceipt(model, receiptText) { const family = model.adapterFamily; if (!family) { return null; } requireChecksumEqual(textChecksumHex(receiptText), family.checksum, "adapter family receipt"); const fields = parseManifest(receiptText); requireManifestEqual(fields, "tinyrustlm_adapter_family_receipt_version", "1"); const familyKind = requireManifestField(fields, "adapter_family_kind", "adapter family receipt"); if (!adapterFamilyReceiptKinds.has(familyKind)) { throw new Error("Adapter family receipt kind mismatch"); } requireManifestEqual(fields, "adapter_family_status", adapterFamilyReceiptStatus); requireManifestEqual(fields, "adapter_family_receipt_path", family.path); requireManifestEqual(fields, "adapter_family_strategy", family.strategy); const adapterCount = Number.parseInt(requireManifestField(fields, "adapter_count"), 10); if (!Number.isInteger(adapterCount) || adapterCount !== family.count || adapterCount !== model.adapters.length) { throw new Error("Adapter family receipt count mismatch"); } adapterFamilyPreferredIndex(model, fields); for (const key of adapterFamilyIdentityKeys) { requireManifestField(fields, `family.${key}`); } adapterFamilyAutoApplyIndexes(model, fields); for (let index = 0; index < model.adapters.length; index += 1) { const adapter = model.adapters[index]; const prefix = `adapter.${index}`; requireManifestEqual(fields, `${prefix}.path`, adapter.path); requireManifestEqual(fields, `${prefix}.manifest_path`, adapter.manifestPath); requireManifestEqual(fields, `${prefix}.label`, adapter.label); requireManifestEqual(fields, `${prefix}.apply_status`, adapter.applyStatus); requireChecksumEqual( requireManifestField(fields, `${prefix}.artifact_checksum`), adapter.artifactChecksum, `adapter ${index} artifact` ); requireChecksumEqual( requireManifestField(fields, `${prefix}.manifest_checksum`), adapter.manifestChecksum, `adapter ${index} manifest` ); const adapterFormat = adapterFormatForPath(adapter.path); if (!adapterFormat) { throw new Error("Adapter route format mismatch"); } const artifactKind = requireAdapterKindDtypePair( fields, `${prefix}.kind`, `${prefix}.dtype`, adapterFormat.kindDtypePairs, "adapter family receipt" ); validateSourceBackedReceiptFields(fields, prefix, artifactKind); for (const key of adapterFamilyIdentityKeys) { requireManifestEqual(fields, `${prefix}.${key}`, requireManifestField(fields, `family.${key}`)); } } return fields; } // Checks source-backed ALR1 receipt echoes while the receipt checksum is still the authority. function validateSourceBackedReceiptFields(fields, prefix, artifactKind) { if (artifactKind !== sourceBackedLowRankAdapterKind) { return; } for (const [manifestKey, receiptKey, expectedValue, isChecksum] of sourceBackedLowRankManifestFields) { const fieldKey = `${prefix}.${receiptKey}`; const value = isChecksum ? requireHex64ManifestField(fields, fieldKey, "adapter family receipt") : requireManifestField(fields, fieldKey, "adapter family receipt"); if (expectedValue && value !== expectedValue) { throw new Error(`Adapter family receipt field ${fieldKey} was ${value}`); } } } // Verifies one fetched adapter manifest against both its route and receipt-backed source fields. function validateAdapterManifest(adapter, manifestText, receiptFields, index) { requireChecksumEqual(textChecksumHex(manifestText), adapter.manifestChecksum, `adapter ${index} manifest`); const fields = parseManifest(manifestText); const source = "Adapter manifest"; const adapterFormat = adapterFormatForPath(adapter.path); if (!adapterFormat) { throw new Error("Adapter route format mismatch"); } requireManifestEqual(fields, "tinyrustlm_adapter_artifact_version", adapterManifestArtifactVersion, source); const artifactKind = requireAdapterKindDtypePair( fields, "adapter_artifact_kind", "adapter_dtype", adapterFormat.kindDtypePairs, source ); requireManifestEqual(fields, "adapter_status", adapterManifestStatus, source); requireManifestEqual(fields, "adapter_base_quantization", adapter.baseQuantization, source); requireManifestEqual(fields, "adapter_apply_status", adapter.applyStatus, source); requireChecksumEqual( requireManifestField(fields, "adapter_artifact_checksum", "adapter manifest"), adapter.artifactChecksum, `adapter ${index} artifact` ); adapterManifestArtifactBytes(fields, source); const receiptPrefix = `adapter.${index}`; const expectedManifestBytes = Number.parseInt( requireManifestField(receiptFields, `${receiptPrefix}.manifest_bytes`), 10 ); const actualManifestBytes = state.encoder.encode(manifestText).length; if (!Number.isInteger(expectedManifestBytes) || expectedManifestBytes !== actualManifestBytes) { throw new Error(`Adapter ${index} manifest byte count mismatch`); } for (const key of adapterFamilyIdentityKeys) { requireManifestEqual( fields, key, requireManifestField(receiptFields, `${receiptPrefix}.${key}`), source ); } validateSourceBackedAdapterManifest(fields, receiptFields, receiptPrefix, artifactKind, source); return fields; } // Binds source-backed ALR1 manifest provenance to the already-verified adapter-family receipt. function validateSourceBackedAdapterManifest(fields, receiptFields, receiptPrefix, artifactKind, source) { if (artifactKind !== sourceBackedLowRankAdapterKind) { return; } requireManifestEqual( fields, "adapter_base_contract", "matches-parent-direct-parameter-contract", source ); for (const [manifestKey, receiptKey, expectedValue, isChecksum] of sourceBackedLowRankManifestFields) { const receiptValue = isChecksum ? requireHex64ManifestField(receiptFields, `${receiptPrefix}.${receiptKey}`, "adapter family receipt") : requireManifestField(receiptFields, `${receiptPrefix}.${receiptKey}`, "adapter family receipt"); if (expectedValue && receiptValue !== expectedValue) { throw new Error(`Adapter family receipt field ${receiptPrefix}.${receiptKey} was ${receiptValue}`); } if (isChecksum) { requireChecksumEqual( requireManifestField(fields, manifestKey, source.toLowerCase()), receiptValue, `adapter ${receiptPrefix} source manifest` ); } else { requireManifestEqual(fields, manifestKey, receiptValue, source); } } } function adapterManifestArtifactBytes(fields, source) { const artifactBytes = registryDecimalByteCount( requireManifestField(fields, "adapter_artifact_bytes", source || "adapter manifest") ); if (artifactBytes === null) { throw new Error("Adapter artifact byte count mismatch"); } return artifactBytes; } async function loadAdapterFamilyReceipt(model) { if (!model.adapterFamily) { return ""; } model.adapterFamilyVerified = false; model.adapterFamilyReceipt = null; model.adapterFamilyManifests = null; model.adapterFamilyPreferredIndex = null; model.adapterFamilyAutoApplyIndexes = null; const text = await fetchModulePlanTextWithinBudget( model, model.adapterFamily.path, receiptTextByteBudget, "adapter-family receipt", "adapter-family-receipt" ); requireModulePlanTextByteCount(model, 3, text); const receiptFields = validateAdapterFamilyReceipt(model, text); const preferredIndex = adapterFamilyPreferredIndex(model, receiptFields); const autoApplyIndexes = adapterFamilyAutoApplyIndexes(model, receiptFields); const manifestFields = []; for (let index = 0; index < model.adapters.length; index += 1) { const adapter = model.adapters[index]; const manifestText = await fetchModulePlanTextWithinBudget( model, adapter.manifestPath, manifestTextByteBudget, "Adapter manifest", "adapter-manifest" ); const fields = validateAdapterManifest(adapter, manifestText, receiptFields, index); const moduleIndex = modulePlanStackModuleIndexForAdapter(model.modulePlanReceipt, index); if (moduleIndex !== null) { requireModulePlanActualByteCount( model.modulePlanReceipt, moduleIndex, adapterManifestArtifactBytes(fields, "Adapter manifest") ); } manifestFields.push(fields); } if (model.autoApplyPreferredAdapter) { let autoApplyBytes = 0; for (const index of autoApplyIndexes) { autoApplyBytes += adapterManifestArtifactBytes(manifestFields[index], "Adapter manifest"); } if (model.modulePlan && autoApplyBytes !== model.modulePlan.adapterStackByteBudget) { throw new Error("Module plan adapter stack byte budget mismatch"); } if (autoApplyBytes > model.adapterFamily.autoApplyByteBudget) { throw new Error("Adapter auto assembly byte budget exceeded"); } } model.adapterFamilyReceipt = receiptFields; model.adapterFamilyManifests = manifestFields; model.adapterFamilyPreferredIndex = preferredIndex; model.adapterFamilyAutoApplyIndexes = autoApplyIndexes; model.adapterFamilyVerified = true; return "family verified"; } function validateModulePlanReceipt(model, receiptText) { const plan = model.modulePlan; if (!plan) { return null; } requireChecksumEqual(textChecksumHex(receiptText), plan.checksum, "module plan"); const fields = parseManifest(receiptText); const source = "Module plan"; requireManifestEqual(fields, "tinyrustlm_module_plan_version", "1", source); requireManifestEqual(fields, "module_plan_kind", registryModulePlanKind, source); requireManifestEqual(fields, "module_plan_status", modulePlanReceiptStatus, source); requireManifestEqual(fields, "module_plan_strategy", registryModulePlanStrategy, source); requireManifestEqual(fields, "candidate_id", state.activeModelKey, source); requireManifestEqual(fields, "module_plan_path", plan.path, source); requireManifestEqual(fields, "module_plan_resource_class", plan.resourceClass, source); requireManifestEqual(fields, "module_plan_profile", plan.profile, source); requireManifestEqual(fields, "module_plan_execution_profile", plan.executionProfile, source); requireManifestEqual(fields, "module_plan_fetch_policy", plan.fetchPolicy, source); requireManifestEqual(fields, "module_plan_origin_policy", plan.originPolicy, source); const fetchCountLimit = requireModulePlanCount( fields, "module_plan_fetch_count_limit", plan.fetchCountLimit ); if ( fetchCountLimit !== registryModulePlanFetchCountLimit || modulePlanDeclaredFetchCount(model, plan.moduleCount) > fetchCountLimit ) { throw new Error("Module plan fetch count limit mismatch"); } const plannedFetchCount = requireModulePlanCount( fields, "module_plan_planned_fetch_count", plan.plannedFetchCount ); const declaredFetchCount = modulePlanDeclaredFetchCount(model, plan.moduleCount); if ( plannedFetchCount !== declaredFetchCount || plannedFetchCount !== registryModulePlanPlannedFetchCount || plannedFetchCount > fetchCountLimit ) { throw new Error("Module plan planned fetch count mismatch"); } if (!model.assembly || !model.adapterFamily) { throw new Error("Module plan route set checksum mismatch"); } const routeSetVersion = requireManifestField( fields, "module_plan_route_set_version", source ); if ( routeSetVersion !== plan.routeSetVersion || routeSetVersion !== registryModulePlanRouteSetVersion ) { throw new Error("Module plan route set version mismatch"); } const routeSetChecksumAlgorithm = requireManifestField( fields, "module_plan_route_set_checksum_algorithm", source ); if ( routeSetChecksumAlgorithm !== plan.routeSetChecksumAlgorithm || routeSetChecksumAlgorithm !== registryModulePlanRouteSetChecksumAlgorithm ) { throw new Error("Module plan route set checksum algorithm mismatch"); } const routeSetChecksum = requireManifestField( fields, "module_plan_route_set_checksum", source ); const routeSetCandidateId = model.candidateId || state.activeModelKey; const operatorEvidencePrefix = assemblyEvidencePrefixFromOperatorPath( routeSetCandidateId, plan.operatorReceiptPath ); if (!operatorEvidencePrefix) { throw new Error("Module plan operator receipt path mismatch"); } const routeSetRoutes = modulePlanRouteSetRoutes( routeSetCandidateId, plan.path, model.path, `${model.path}.manifest`, model.assembly.path, model.adapterFamily.path, model.adapters, model.adapterFamily.autoApplyStackCount, operatorEvidencePrefix ); const expectedRouteSetChecksum = routeSetRoutes ? modulePlanRouteSetChecksum(routeSetRoutes) : ""; if ( !isRegistryHex64(routeSetChecksum) || routeSetChecksum !== plan.routeSetChecksum || routeSetChecksum !== expectedRouteSetChecksum ) { throw new Error("Module plan route set checksum mismatch"); } requireManifestEqual(fields, "operator_receipt_path", plan.operatorReceiptPath, source); requireChecksumEqual( requireManifestField(fields, "operator_receipt_checksum", source), plan.operatorReceiptChecksum, "module plan operator receipt" ); const wasmMemoryInitialPages = requireManifestField( fields, "module_plan_wasm_memory_initial_pages", source ); if ( wasmMemoryInitialPages !== String(plan.wasmMemoryInitialPages) || plan.wasmMemoryInitialPages !== state.wasmMemoryInitialPages ) { throw new Error("Module plan WASM memory initial pages mismatch"); } const wasmExportSet = requireManifestField(fields, "module_plan_wasm_export_set", source); if (wasmExportSet !== plan.wasmExportSet || !verifyModulePlanWasmExports(wasmExportSet)) { throw new Error("Module plan WASM export set mismatch"); } const wasmTransferStrategy = requireManifestField( fields, "module_plan_wasm_transfer_strategy", source ); if ( wasmTransferStrategy !== plan.wasmTransferStrategy || wasmTransferStrategy !== registryModulePlanWasmTransferStrategy ) { throw new Error("Module plan WASM transfer strategy mismatch"); } const modelReleaseStrategy = requireManifestField( fields, "module_plan_model_release_strategy", source ); if ( modelReleaseStrategy !== plan.modelReleaseStrategy || modelReleaseStrategy !== registryModulePlanModelReleaseStrategy ) { throw new Error("Module plan model release strategy mismatch"); } const runtimeResetStrategy = requireManifestField( fields, "module_plan_runtime_reset_strategy", source ); if ( runtimeResetStrategy !== plan.runtimeResetStrategy || runtimeResetStrategy !== registryModulePlanRuntimeResetStrategy ) { throw new Error("Module plan runtime reset strategy mismatch"); } const adapterValidationStrategy = requireManifestField( fields, "module_plan_adapter_validation_strategy", source ); if ( adapterValidationStrategy !== plan.adapterValidationStrategy || adapterValidationStrategy !== registryModulePlanAdapterValidationStrategy ) { throw new Error("Module plan adapter validation strategy mismatch"); } const adapterValidationCountValue = requireManifestField( fields, "module_plan_adapter_validation_count", source ); const adapterValidationCount = registryDecimalCount(adapterValidationCountValue); if ( adapterValidationCount === null || adapterValidationCount !== plan.adapterValidationCount || adapterValidationCount !== plan.adapterApplyCount || (model.adapterFamily && adapterValidationCount !== model.adapterFamily.autoApplyStackCount) || adapterValidationCount !== registryModulePlanAdapterValidationCount ) { throw new Error("Module plan adapter validation count mismatch"); } const adapterApplyCountValue = requireManifestField( fields, "module_plan_adapter_apply_count", source ); const adapterApplyCount = registryDecimalCount(adapterApplyCountValue); if ( adapterApplyCount === null || adapterApplyCount !== plan.adapterApplyCount || (model.adapterFamily && adapterApplyCount !== model.adapterFamily.autoApplyStackCount) || adapterApplyCount !== registryModulePlanAdapterApplyCount ) { throw new Error("Module plan adapter apply count mismatch"); } const wasmHeapMinValue = requireManifestField( fields, "module_plan_wasm_heap_min_bytes", source ); const wasmHeapMinBytes = registryDecimalByteCount(wasmHeapMinValue); if (wasmHeapMinBytes === null || wasmHeapMinBytes !== plan.wasmHeapMinBytes) { throw new Error("Module plan WASM heap min bytes mismatch"); } const contextTokenLimitValue = requireManifestField( fields, "module_plan_context_token_limit", source ); const contextTokenLimit = registryDecimalCount(contextTokenLimitValue); if ( contextTokenLimit === null || contextTokenLimit !== plan.contextTokenLimit || contextTokenLimit !== model.contextTokenLimit || contextTokenLimit < model.maxTokens || contextTokenLimit > registryModulePlanContextTokenLimitLimit ) { throw new Error("Module plan context token limit mismatch"); } const samplerCandidateCapValue = requireManifestField( fields, "module_plan_sampler_candidate_cap", source ); const samplerCandidateCap = registryDecimalCount(samplerCandidateCapValue); // Mirrors the fixed top-k candidate buffer before generated model bytes are fetched. if ( samplerCandidateCap === null || samplerCandidateCap !== plan.samplerCandidateCap || samplerCandidateCap !== registryModulePlanSamplerCandidateCap ) { throw new Error("Module plan sampler candidate cap mismatch"); } const tokenizerChecksum = requireManifestField(fields, "module_plan_tokenizer_checksum", source); if ( !isRegistryHex64(tokenizerChecksum) || tokenizerChecksum !== plan.tokenizerChecksum || tokenizerChecksum !== model.tokenizerChecksum ) { throw new Error("Module plan tokenizer checksum mismatch"); } const modelByteBudget = requireModulePlanByteBudget( fields, "module_plan_model_byte_budget", plan.modelByteBudget ); const adapterByteBudget = requireModulePlanByteBudget( fields, "module_plan_adapter_byte_budget", plan.adapterByteBudget ); const adapterStackByteBudget = requireModulePlanByteBudget( fields, "module_plan_adapter_stack_byte_budget", plan.adapterStackByteBudget ); const promptByteLimit = requireModulePlanByteBudget( fields, "module_plan_prompt_byte_limit", plan.promptByteLimit ); const runtimeScratchByteBudget = requireModulePlanByteBudget( fields, "module_plan_runtime_scratch_byte_budget", plan.runtimeScratchByteBudget ); const outputByteLimit = requireModulePlanByteBudget( fields, "module_plan_output_byte_limit", plan.outputByteLimit ); const kvCacheByteBudget = requireModulePlanByteBudget( fields, "module_plan_kv_cache_byte_budget", plan.kvCacheByteBudget ); const kvCachePageCountValue = requireManifestField( fields, "module_plan_kv_cache_page_count", source ); const kvCachePageCount = Number.parseInt(kvCachePageCountValue, 10); if ( !Number.isInteger(kvCachePageCount) || String(kvCachePageCount) !== kvCachePageCountValue || kvCachePageCount !== plan.kvCachePageCount || kvCachePageCount !== modulePlanPageCountForBytes(kvCacheByteBudget) ) { throw new Error("Module plan KV cache page count mismatch"); } const totalByteBudget = requireModulePlanByteBudget( fields, "module_plan_total_byte_budget", plan.totalByteBudget ); const totalByteBudgetLimit = requireModulePlanByteBudget( fields, "module_plan_total_byte_budget_limit", plan.totalByteBudgetLimit ); if (modelByteBudget !== model.modelBytes) { throw new Error("Module plan model byte budget mismatch"); } if (model.adapterFamily && adapterByteBudget !== model.adapterFamily.autoApplyByteBudget) { throw new Error("Module plan adapter byte budget mismatch"); } if (adapterStackByteBudget <= 0 || adapterStackByteBudget > adapterByteBudget) { throw new Error("Module plan adapter stack byte budget mismatch"); } if (promptByteLimit !== registryModulePlanPromptByteLimit) { throw new Error("Module plan prompt byte limit mismatch"); } if ( wasmHeapMinBytes !== modulePlanWasmHeapMinBytes(modelByteBudget, adapterStackByteBudget, promptByteLimit) ) { throw new Error("Module plan WASM heap min bytes mismatch"); } probeWasmHeapAllocation(wasmHeapMinBytes); if (runtimeScratchByteBudget !== registryModulePlanRuntimeScratchByteBudget) { throw new Error("Module plan runtime scratch byte budget mismatch"); } if (outputByteLimit !== registryModulePlanOutputByteLimit) { throw new Error("Module plan output byte limit mismatch"); } if (kvCacheByteBudget > registryModulePlanKvCacheByteBudgetLimit) { throw new Error("Module plan KV cache byte budget mismatch"); } if ( totalByteBudgetLimit !== registryModulePlanTotalByteBudgetLimit || totalByteBudget > totalByteBudgetLimit ) { throw new Error("Module plan total byte budget limit mismatch"); } requireManifestEqual(fields, "model_path", model.path, source); requireManifestEqual(fields, "manifest_path", `${model.path}.manifest`, source); requireManifestEqual(fields, "quantization", model.quantization, source); const modelChecksum = requireManifestField(fields, "model_checksum", source); const manifestChecksum = requireManifestField(fields, "manifest_checksum", source); if (!isRegistryHex64(modelChecksum) || !isRegistryHex64(manifestChecksum)) { throw new Error("Module plan model checksum field is invalid"); } if (model.assembly) { requireManifestEqual(fields, "assembly_receipt_path", model.assembly.path, source); requireChecksumEqual( requireManifestField(fields, "assembly_receipt_checksum", source), model.assembly.checksum, "module plan assembly" ); } if (model.adapterFamily) { requireManifestEqual(fields, "adapter_family_receipt_path", model.adapterFamily.path, source); requireChecksumEqual( requireManifestField(fields, "adapter_family_receipt_checksum", source), model.adapterFamily.checksum, "module plan adapter family" ); const stackCountValue = requireManifestField(fields, "adapter_auto_apply_stack_count", source); const stackCount = Number.parseInt(stackCountValue, 10); if ( !Number.isInteger(stackCount) || String(stackCount) !== stackCountValue || stackCount !== model.adapterFamily.autoApplyStackCount ) { throw new Error("Module plan adapter stack count mismatch"); } } const moduleCountValue = requireManifestField(fields, "module_count", source); const moduleCount = Number.parseInt(moduleCountValue, 10); if ( !Number.isInteger(moduleCount) || String(moduleCount) !== moduleCountValue || moduleCount !== plan.moduleCount ) { throw new Error("Module plan module count mismatch"); } requireModulePlanLine( fields, 0, "model", "runtime-model", "runtime-model", modulePlanPhase(0), modulePlanDependency(0), model.path, modelChecksum, model.modelBytes, modelByteBudget ); requireModulePlanLine( fields, 1, "model-manifest", "model-manifest", "model-provenance-manifest", modulePlanPhase(1), modulePlanDependency(1), `${model.path}.manifest`, manifestChecksum, null, manifestTextByteBudget ); if (model.assembly) { requireModulePlanLine( fields, 2, "assembly-receipt", "assembly-receipt", "assembly-evidence", modulePlanPhase(2), modulePlanDependency(2), model.assembly.path, model.assembly.checksum, null, receiptTextByteBudget ); } if (model.adapterFamily) { requireModulePlanLine( fields, 3, "adapter-family-receipt", "adapter-family-receipt", "adapter-family", modulePlanPhase(3), modulePlanDependency(3), model.adapterFamily.path, model.adapterFamily.checksum, null, receiptTextByteBudget ); const seen = new Set(); let declaredStackByteBudget = 0; for (let stackIndex = 0; stackIndex < model.adapterFamily.autoApplyStackCount; stackIndex += 1) { const moduleIndex = stackIndex + 4; const prefix = `module.${moduleIndex}`; requireManifestEqual(fields, `${prefix}.kind`, "adapter-stack-member", source); const indexValue = requireManifestField(fields, `${prefix}.adapter_index`, source); const adapterIndex = Number.parseInt(indexValue, 10); if ( !Number.isInteger(adapterIndex) || String(adapterIndex) !== indexValue || adapterIndex < 0 || adapterIndex >= model.adapters.length || seen.has(adapterIndex) ) { throw new Error("Module plan adapter index mismatch"); } const adapter = model.adapters[adapterIndex]; requireManifestEqual(fields, `${prefix}.assembly_slot`, modulePlanAdapterSlot(stackIndex), source); requireManifestEqual(fields, `${prefix}.role`, modulePlanAdapterRole(adapter.path), source); requireManifestEqual(fields, `${prefix}.phase`, modulePlanPhase(moduleIndex), source); requireManifestEqual(fields, `${prefix}.depends_on`, modulePlanDependency(moduleIndex), source); declaredStackByteBudget += requireModulePlanByteCount( fields, prefix, null, model.adapterFamily.autoApplyByteBudget, source ); requireChecksumEqual( requireManifestField(fields, `${prefix}.checksum`, source), adapter.artifactChecksum, "module plan adapter module" ); requireManifestEqual(fields, `${prefix}.adapter_path`, adapter.path, source); requireManifestEqual(fields, `${prefix}.manifest_path`, adapter.manifestPath, source); requireChecksumEqual( requireManifestField(fields, `${prefix}.artifact_checksum`, source), adapter.artifactChecksum, "module plan adapter artifact" ); requireChecksumEqual( requireManifestField(fields, `${prefix}.manifest_checksum`, source), adapter.manifestChecksum, "module plan adapter manifest" ); seen.add(adapterIndex); } if (declaredStackByteBudget !== adapterStackByteBudget) { throw new Error("Module plan adapter stack byte budget mismatch"); } } if ( modulePlanDeclaredByteTotal( fields, moduleCount, promptByteLimit, runtimeScratchByteBudget, outputByteLimit, kvCacheByteBudget ) !== totalByteBudget ) { throw new Error("Module plan total byte budget mismatch"); } return fields; } function modulePlanAdapterRole(adapterPath) { if (adapterPath.endsWith("-sparse.asp1")) { return "adapter-stack-sparse-delta"; } if (adapterPath.endsWith("-low-rank.alr1")) { return "adapter-stack-low-rank-delta"; } if (adapterPath.endsWith("-family.adp1")) { return "adapter-stack-family-delta"; } if (adapterPath.endsWith("-self.adp1")) { return "adapter-stack-self-delta"; } return "adapter-stack-delta"; } function modulePlanAdapterSlot(stackIndex) { return `adapter-stack-${stackIndex}`; } function modulePlanDependency(index) { return index === 0 ? "runtime-wasm" : `module.${index - 1}`; } function modulePlanPhase(index) { const basePhases = [ "load-model-bytes", "verify-model-manifest", "verify-assembly-evidence", "verify-adapter-family" ]; return index < basePhases.length ? basePhases[index] : `apply-adapter-stack-${index - 4}`; } function requireModulePlanByteBudget(fields, key, expected) { const source = "Module plan"; const value = requireManifestField(fields, key, source); const bytes = registryDecimalByteCount(value); if (bytes === null || bytes !== expected) { throw new Error(`Module plan ${key.replace(/_/g, " ")} mismatch`); } return bytes; } // Requires a decimal module-plan count to match the selector-owned envelope. function requireModulePlanCount(fields, key, expected) { const source = "Module plan"; const value = requireManifestField(fields, key, source); const count = registryDecimalCount(value); if (count === null || count !== expected) { throw new Error(`Module plan ${key.replace(/_/g, " ")} mismatch`); } return count; } // Mirrors the route classes fetched during generated self-assembly. function modulePlanDeclaredFetchCount(model, moduleCount) { let fetchCount = 1 + moduleCount; if (model.assembly) { fetchCount += assemblyEvidenceRoutesForOperatorPrefix("operator").length; } if (Array.isArray(model.adapters)) { fetchCount += model.adapters.length; } return fetchCount; } // Requires the browser-observed generated fetch count to match the verified receipt. function requireModulePlanActualFetchCount(model) { if (!model || !model.modulePlan) { return; } if (state.modulePlanActualFetchCount !== model.modulePlan.plannedFetchCount) { throw new Error("Module plan actual fetch count mismatch"); } updateModulePlanActualFetchCount(model.modulePlanReceipt); } // Requires the browser-observed generated route set to match the declared route-set checksum. function requireModulePlanActualRouteSet(model) { if (!model || !model.modulePlan) { return; } if ( !Array.isArray(state.modulePlanActualRoutes) || state.modulePlanActualRoutes.length !== model.modulePlan.plannedFetchCount || state.modulePlanActualRoutes.length !== state.modulePlanActualFetchCount ) { throw new Error("Module plan actual route set mismatch"); } const actualChecksum = modulePlanRouteSetChecksum(state.modulePlanActualRoutes); state.modulePlanActualRouteSetChecksum = actualChecksum; if (actualChecksum !== model.modulePlan.routeSetChecksum) { throw new Error("Module plan actual route set mismatch"); } updateModulePlanActualRouteSetChecksum(model.modulePlanReceipt); } // Requires observed module bytes to match the checksum-verified module byte rows. function requireModulePlanActualModuleBytes(model) { if (!model || !model.modulePlan) { return; } const declared = modulePlanModuleByteTotal(model.modulePlanReceipt); if ( !declared || !Array.isArray(state.modulePlanActualModuleByteIndexes) || state.modulePlanActualModuleByteIndexes.length !== declared.count || state.modulePlanActualModuleBytes !== declared.total ) { throw new Error("Module plan actual module bytes mismatch"); } updateModulePlanActualModuleBytes(model.modulePlanReceipt); } // Requires observed module checksums to match every checksum-verified module row. function requireModulePlanActualModuleChecksums(model) { if (!model || !model.modulePlan) { return; } const declared = modulePlanModuleChecksumList(model.modulePlanReceipt); if (!declared || !Array.isArray(state.modulePlanActualModuleChecksums)) { throw new Error("Module plan actual module checksum mismatch"); } for (let index = 0; index < declared.length; index += 1) { if (state.modulePlanActualModuleChecksums[index] !== declared[index]) { throw new Error("Module plan actual module checksum mismatch"); } } updateModulePlanActualModuleChecksums(model.modulePlanReceipt); } // Recomputes the receipt-declared self-assembly total before generated bytes are used. function modulePlanDeclaredByteTotal( fields, moduleCount, promptByteLimit, runtimeScratchByteBudget, outputByteLimit, kvCacheByteBudget ) { let total = promptByteLimit + runtimeScratchByteBudget + outputByteLimit + kvCacheByteBudget; for (let index = 0; index < moduleCount; index += 1) { const bytes = registryDecimalByteCount( requireManifestField(fields, `module.${index}.byte_count`, "Module plan") ); if (bytes === null) { throw new Error("Module plan module byte count mismatch"); } total += bytes; } return total; } function requireModulePlanByteCount(fields, prefix, expected, max, source) { const value = requireManifestField(fields, `${prefix}.byte_count`, source); const bytes = registryDecimalByteCount(value); if ( bytes === null || (expected !== null && bytes !== expected) || (expected === null && Number.isSafeInteger(max) && bytes > max) ) { throw new Error(`${source || "Receipt"} field ${prefix}.byte_count was ${value}`); } return bytes; } function requireModulePlanActualByteCount(fields, index, actualBytes) { requireModulePlanByteCount(fields, `module.${index}`, actualBytes, null, "Module plan"); } // Records one browser-observed module byte count after the module payload is fetched. function recordModulePlanActualModuleBytes(model, index, actualBytes) { if (!model || !model.modulePlan || !model.modulePlanReceipt) { return; } if ( !Number.isInteger(index) || !Number.isSafeInteger(actualBytes) || actualBytes < 0 || !Array.isArray(state.modulePlanActualModuleByteIndexes) ) { throw new Error("Module plan actual module byte metadata mismatch"); } if (state.modulePlanActualModuleByteIndexes.includes(index)) { throw new Error("Module plan actual module byte duplicate"); } requireModulePlanActualByteCount(model.modulePlanReceipt, index, actualBytes); state.modulePlanActualModuleByteIndexes.push(index); state.modulePlanActualModuleBytes += actualBytes; updateModulePlanActualModuleBytes(model.modulePlanReceipt); } // Records both the byte count and checksum for a fetched generated text module. function requireModulePlanTextByteCount(model, index, text) { if (model.modulePlanReceipt) { recordModulePlanActualModuleBytes(model, index, state.encoder.encode(text).length); recordModulePlanActualModuleChecksum(model, index, textChecksumHex(text)); } } // Records one browser-observed module checksum after the module payload is accepted. function recordModulePlanActualModuleChecksum(model, index, actualChecksum) { if (!model || !model.modulePlan || !model.modulePlanReceipt) { return; } if ( !Number.isInteger(index) || !isRegistryHex64(actualChecksum) || !Array.isArray(state.modulePlanActualModuleChecksums) ) { throw new Error("Module plan actual module checksum metadata mismatch"); } if (state.modulePlanActualModuleChecksums[index]) { throw new Error("Module plan actual module checksum duplicate"); } requireChecksumEqual( actualChecksum, requireManifestField(model.modulePlanReceipt, `module.${index}.checksum`, "Module plan"), "module plan actual module" ); state.modulePlanActualModuleChecksums[index] = actualChecksum; updateModulePlanActualModuleChecksums(model.modulePlanReceipt); } function modulePlanStackModuleIndexForAdapter(fields, adapterIndex) { const countValue = fields && fields.module_count; const count = Number.parseInt(countValue || "0", 10); if (!Number.isInteger(count) || String(count) !== countValue || count < 5) { return null; } for (let moduleIndex = 4; moduleIndex < count; moduleIndex += 1) { const value = fields[`module.${moduleIndex}.adapter_index`]; if (value === String(adapterIndex)) { return moduleIndex; } } return null; } function requireModulePlanLine( fields, index, kind, assemblySlot, role, phase, dependsOn, path, checksum, byteCount, maxByteCount ) { const source = "Module plan"; const prefix = `module.${index}`; requireManifestEqual(fields, `${prefix}.kind`, kind, source); requireManifestEqual(fields, `${prefix}.assembly_slot`, assemblySlot, source); requireManifestEqual(fields, `${prefix}.role`, role, source); requireManifestEqual(fields, `${prefix}.phase`, phase, source); requireManifestEqual(fields, `${prefix}.depends_on`, dependsOn, source); requireModulePlanByteCount(fields, prefix, byteCount, maxByteCount, source); requireManifestEqual(fields, `${prefix}.path`, path, source); requireChecksumEqual( requireManifestField(fields, `${prefix}.checksum`, source), checksum, `module plan ${kind}` ); } async function loadModulePlanReceipt(model) { if (!model.modulePlan) { state.modulePlanReceipt = null; renderModulePlan("none", null, false); resetModulePlanTrace("unavailable", false); return ""; } model.modulePlanVerified = false; model.modulePlanReceipt = null; state.modulePlanReceipt = null; const text = await fetchModulePlanTextWithinBudget( model, model.modulePlan.path, receiptTextByteBudget, "module plan", "module-plan-receipt" ); const fields = validateModulePlanReceipt(model, text); model.modulePlanReceipt = fields; model.modulePlanVerified = true; state.modulePlanReceipt = fields; renderModulePlan("loaded", fields, false); resetModulePlanTrace("", false); recordModulePlanTrace("plan verified"); return "module plan verified"; } function validateAssemblyReceipt(model, receiptText) { const assembly = model.assembly; if (!assembly) { return null; } if (!state.modelManifest) { throw new Error("Assembly receipt requires a loaded model manifest"); } requireChecksumEqual(textChecksumHex(receiptText), assembly.checksum, "assembly receipt"); const fields = parseManifest(receiptText); const source = "Assembly receipt"; requireManifestEqual(fields, "tinyrustlm_assembly_receipt_version", "1", source); requireManifestEqual(fields, "assembly_kind", registryAssemblyKind, source); requireManifestEqual(fields, "assembly_status", assemblyReceiptStatus, source); const assemblyStrategy = requireManifestField(fields, "assembly_strategy", source); if (!assemblyReceiptStrategies.has(assemblyStrategy)) { throw new Error("Assembly receipt strategy mismatch"); } requireManifestEqual(fields, "candidate_id", state.activeModelKey, source); requireManifestEqual(fields, "assembly_receipt_path", assembly.path, source); requireManifestEqual(fields, "model_path", model.path, source); requireManifestEqual(fields, "manifest_path", `${model.path}.manifest`, source); requireChecksumEqual( requireManifestField(fields, "slm_checksum", "assembly receipt"), requireManifestField(state.modelManifest, "slm_checksum", "model manifest"), "assembly model" ); const parentCount = Number.parseInt(requireManifestField(fields, "parent_count", "assembly receipt"), 10); if (!Number.isInteger(parentCount) || parentCount < 1 || parentCount > 16) { throw new Error("Assembly receipt parent count mismatch"); } for (const key of [ "manifest_checksum", "promotion_ledger_checksum", "population_review_checksum", "parent_pool_recipe_checksum", "operator_receipt_checksum", "candidate_manifest_checksum", "promotion_manifest_checksum", "runtime_smoke_manifest_checksum", "eval_manifest_checksum", "eval_case_evidence_checksum", "admission_checksum", "adapter_family_receipt_checksum" ]) { const value = requireManifestField(fields, key, "assembly receipt"); if (!isRegistryHex64(value)) { throw new Error(`Assembly receipt field ${key} is invalid`); } } const operatorReceiptPath = requireManifestField( fields, "operator_receipt_path", "assembly receipt" ); const operatorEvidencePrefix = assemblyEvidencePrefixFromOperatorPath( state.activeModelKey, operatorReceiptPath ); if (!operatorEvidencePrefix) { throw new Error("Assembly receipt operator evidence path mismatch"); } for (const [pathKey, _checksumKey, fileName] of assemblyEvidenceRoutesForOperatorPrefix(operatorEvidencePrefix)) { const route = requireManifestField(fields, pathKey, "assembly receipt"); if ( !isSafeAssemblyEvidencePath(route) || route !== modulePlanEvidenceRoute(state.activeModelKey, fileName) ) { throw new Error(`Assembly receipt field ${pathKey} is invalid`); } } if (model.modulePlan) { requireManifestEqual( fields, "operator_receipt_path", model.modulePlan.operatorReceiptPath, source ); requireChecksumEqual( requireManifestField(fields, "operator_receipt_checksum", "assembly receipt"), model.modulePlan.operatorReceiptChecksum, "assembly operator receipt" ); } if (model.adapterFamily) { requireManifestEqual(fields, "adapter_family_receipt_path", model.adapterFamily.path, source); requireChecksumEqual( requireManifestField(fields, "adapter_family_receipt_checksum", "assembly receipt"), model.adapterFamily.checksum, "assembly adapter family" ); } if (model.evalEvidence) { requireChecksumEqual( requireManifestField(fields, "eval_case_evidence_checksum", "assembly receipt"), model.evalEvidence.checksum, "assembly eval case evidence" ); } requireManifestEqual(fields, "required_next_gate", "browser-selector-registry-route-binding", source); return fields; } async function verifyAssemblyEvidenceFiles(model, fields) { const evidence = []; const operatorEvidencePrefix = assemblyEvidencePrefixFromOperatorPath( state.activeModelKey, requireManifestField(fields, "operator_receipt_path", "assembly receipt") ); if (!operatorEvidencePrefix) { throw new Error("Assembly receipt operator evidence path mismatch"); } for (const [pathKey, checksumKey] of assemblyEvidenceRoutesForOperatorPrefix(operatorEvidencePrefix)) { const route = requireManifestField(fields, pathKey, "assembly receipt"); const expectedChecksum = requireManifestField(fields, checksumKey, "assembly receipt"); const text = await fetchModulePlanTextWithinBudget( model, route, evidenceTextByteBudget, "assembly evidence", "assembly-evidence" ); requireChecksumEqual(textChecksumHex(text), expectedChecksum, `assembly evidence ${pathKey}`); evidence.push({ pathKey, checksumKey, route, checksum: expectedChecksum }); } return evidence; } async function loadAssemblyReceipt(model) { if (!model.assembly) { state.assemblyReceipt = null; renderAssembly("none", null, false); return ""; } model.assemblyVerified = false; model.assemblyReceipt = null; model.assemblyEvidence = null; const text = await fetchModulePlanTextWithinBudget( model, model.assembly.path, receiptTextByteBudget, "assembly receipt", "assembly-receipt" ); requireModulePlanTextByteCount(model, 2, text); const fields = validateAssemblyReceipt(model, text); const evidence = await verifyAssemblyEvidenceFiles(model, fields); model.assemblyReceipt = fields; model.assemblyEvidence = evidence; model.assemblyVerified = true; state.assemblyReceipt = fields; renderAssembly("loaded", fields, false); return "assembly verified"; } function setAdapterControls(canApply) { const hasAdapter = Boolean(selectedAdapter()); el.adapterSelect.disabled = !canApply || !hasAdapter; el.applyAdapterButton.disabled = !canApply || !hasAdapter; } async function loadModelManifest(model) { const manifestPath = `${model.path}.manifest`; try { const text = await fetchModulePlanTextWithinBudget( model, manifestPath, manifestTextByteBudget, ".slm manifest", "model-manifest" ); requireModulePlanTextByteCount(model, 1, text); const fields = parseManifest(text); if (model.modulePlanReceipt) { recordModulePlanActualModuleChecksum( model, 0, requireManifestField(fields, "slm_checksum", "model manifest") ); } state.modelManifest = fields; renderProvenance("loaded", fields, false); } catch (error) { state.modelManifest = null; renderProvenance(errorMessage(error), null, true); } } function setInteractive(enabled) { setControls(enabled, enabled); } function setControls(canGenerate, canSelectModel) { el.generateButton.disabled = !canGenerate; el.stepTokenButton.disabled = !canGenerate || !state.hasContext; el.resetButton.disabled = !canGenerate; el.modelSelect.disabled = !canSelectModel || !state.exports; setAdapterControls(canGenerate && state.modelLoaded); } function freeLoadedModelForSwitch(previousModelKey, selectedModel, wasModelLoaded) { if (!state.exports || typeof state.exports.free_model !== "function" || !wasModelLoaded) { return true; } const code = state.exports.free_model(); const text = readLastResult() || `free_model returned ${code}`; appendConsole(`free_model(${previousModelKey || "unknown"} -> ${selectedModel}) -> ${code}\n${text}`); renderDiagnostics(); if (code !== 0) { throw new Error(text); } return true; } function applyModulePlanRuntimeReset(model, selectedModel) { // Applies the module-plan reset boundary after model bytes load and before assembly work begins. if (!model.modulePlan) { return true; } if (model.modulePlan.runtimeResetStrategy !== registryModulePlanRuntimeResetStrategy) { throw new Error("Module plan runtime reset strategy mismatch"); } if (!state.exports || typeof state.exports.reset_context !== "function") { throw new Error("WASM runtime does not expose context reset"); } const code = state.exports.reset_context(); const text = readLastResult() || `reset_context returned ${code}`; appendConsole(`reset_context(${selectedModel}) -> ${code}\n${text}`); renderDiagnostics(); if (code !== 0) { throw new Error(text); } state.hasContext = false; state.lastMeasuredTokens = 0; return true; } async function loadSelectedModel() { const loadId = state.modelLoadSequence + 1; state.modelLoadSequence = loadId; const selectedModel = paths.models[el.modelSelect.value] ? el.modelSelect.value : "tinylm16q8"; const model = paths.models[selectedModel]; const previousModelKey = state.activeModelKey; const releaseLoadedModel = state.modelLoaded === true; el.modelSelect.value = selectedModel; const modelPath = model.path; el.maxTokens.value = String(model.maxTokens); state.activeModelKey = selectedModel; state.modelLoaded = false; state.hasContext = false; state.lastMeasuredTokens = 0; if (model.adapterFamily) { model.adapterFamilyVerified = false; model.adapterFamilyReceipt = null; model.adapterFamilyManifests = null; model.adapterFamilyPreferredIndex = null; model.adapterFamilyAutoApplyIndexes = null; model.autoAssemblyApplied = false; } if (model.assembly) { model.assemblyVerified = false; model.assemblyReceipt = null; model.assemblyEvidence = null; } if (model.modulePlan) { model.modulePlanVerified = false; model.modulePlanReceipt = null; } resetModulePlanActualFetchCount(model); renderAdapterOptions(model, "waiting"); setInteractive(false); el.response.textContent = ""; el.console.textContent = ""; if (releaseLoadedModel) { freeLoadedModelForSwitch(previousModelKey, selectedModel, releaseLoadedModel); } state.modelManifest = null; state.modulePlanReceipt = null; state.assemblyReceipt = null; renderProvenance("waiting for accepted model", null, false); renderModulePlan("waiting for local plan", null, false); resetModulePlanTrace("waiting for local plan", false); renderAssembly("waiting for accepted model", null, false); setText(el.runtimeStatus, "Loading local model"); setText(el.modelState, "loading"); const started = performance.now(); let modelBytes = null; try { await loadModulePlanReceipt(model); modelBytes = await fetchModulePlanBytes(model, modelPath, ".slm model", "model"); if (Number.isSafeInteger(model.modelBytes) && modelBytes.length !== model.modelBytes) { throw new Error("Selector model byte count mismatch"); } recordModulePlanActualModuleBytes(model, 0, modelBytes.length); } catch (error) { if (loadId !== state.modelLoadSequence) { return false; } state.modelLoadMs = Math.round(performance.now() - started); state.lastGenerateMs = 0; state.modelLoaded = false; state.hasContext = false; state.lastMeasuredTokens = 0; setText(el.modelState, "fetch error", true); setText(el.runtimeStatus, "Model load failed", true); setText(el.errorState, errorMessage(error), true); renderProvenance("model not loaded", null, true); if (model.modulePlan && !model.modulePlanVerified) { renderModulePlan(errorMessage(error), null, true); resetModulePlanTrace(errorMessage(error), true); } else if (!model.modulePlan) { renderModulePlan("none", null, false); resetModulePlanTrace("unavailable", false); } renderAssembly("model not loaded", null, true); setText(el.adapterState, "model not loaded", true); setControls(false, true); renderDiagnostics(); return false; } if (loadId !== state.modelLoadSequence) { return false; } const ptr = allocCopy(modelBytes); const loadCode = state.exports.load_model(ptr, modelBytes.length); release(ptr, modelBytes.length); if (loadId !== state.modelLoadSequence) { return false; } state.modelLoadMs = Math.round(performance.now() - started); state.lastGenerateMs = 0; state.modelLoaded = loadCode === 0; state.hasContext = false; state.lastMeasuredTokens = 0; setText(el.modelState, loadCode === 0 ? `loaded (${state.modelLoadMs} ms)` : `error ${loadCode}`, loadCode !== 0); setText(el.runtimeStatus, loadCode === 0 ? "Ready" : "Model rejected", loadCode !== 0); setText(el.errorState, loadCode === 0 ? "none" : readLastResult(), loadCode !== 0); if (loadCode === 0) { try { applyModulePlanRuntimeReset(model, selectedModel); } catch (error) { const text = errorMessage(error); state.modelLoaded = false; state.hasContext = false; state.lastMeasuredTokens = 0; setText(el.modelState, "runtime reset rejected", true); setText(el.runtimeStatus, "Model load failed", true); setText(el.errorState, text, true); renderProvenance("model not loaded", null, true); renderModulePlan(text, model.modulePlanReceipt, true); resetModulePlanTrace(text, true); renderAssembly("model not loaded", null, true); setText(el.adapterState, "model not loaded", true); setControls(false, true); renderDiagnostics(); return false; } if (model.modulePlan) { recordModulePlanTrace("model accepted"); } renderProvenance("loading local manifest", null, false); await loadModelManifest(model); if (loadId !== state.modelLoadSequence) { return false; } if (model.modulePlan && state.modelManifest) { recordModulePlanTrace("manifest verified"); } let assemblyStatus = ""; let assemblyStatusIsError = false; try { await loadAssemblyReceipt(model); if (loadId !== state.modelLoadSequence) { return false; } if (model.modulePlan && model.assemblyVerified) { recordModulePlanTrace("assembly evidence verified"); } } catch (error) { if (loadId !== state.modelLoadSequence) { return false; } assemblyStatus = errorMessage(error); assemblyStatusIsError = true; renderAssembly(assemblyStatus, null, true); appendConsole(assemblyStatus); } if (assemblyStatusIsError) { if (typeof state.exports.free_model === "function") { state.exports.free_model(); } state.modelLoaded = false; state.hasContext = false; state.lastMeasuredTokens = 0; setText(el.modelState, "assembly evidence rejected", true); setText(el.runtimeStatus, "Model load failed", true); setText(el.errorState, assemblyStatus, true); if (model.modulePlan) { recordModulePlanTrace("assembly evidence rejected"); } renderAdapterOptions(model, "assembly evidence rejected", true); setControls(false, true); renderDiagnostics(); return false; } let adapterStatus = ""; let adapterStatusIsError = false; try { adapterStatus = await loadAdapterFamilyReceipt(model); if (loadId !== state.modelLoadSequence) { return false; } if (model.modulePlan && model.adapterFamilyVerified) { recordModulePlanTrace("adapter family verified"); } } catch (error) { if (loadId !== state.modelLoadSequence) { return false; } adapterStatus = errorMessage(error); adapterStatusIsError = true; appendConsole(adapterStatus); } renderAdapterOptions(model, adapterStatus || undefined, adapterStatusIsError); if ( !adapterStatusIsError && model.autoApplyPreferredAdapter && model.adapterFamilyVerified && loadId === state.modelLoadSequence ) { model.autoAssemblyApplied = await applyAutoAssemblyStack(model, loadId); if (loadId !== state.modelLoadSequence) { return false; } if (model.autoAssemblyApplied && model.modulePlan) { recordModulePlanTrace("adapter stack applied"); } } if ( model.modulePlan && loadId === state.modelLoadSequence && (!model.assembly || model.assemblyVerified) && (!model.adapterFamily || model.adapterFamilyVerified) && (!model.autoApplyPreferredAdapter || model.autoAssemblyApplied) ) { try { requireModulePlanActualFetchCount(model); requireModulePlanActualRouteSet(model); requireModulePlanActualModuleBytes(model); requireModulePlanActualModuleChecksums(model); } catch (error) { const text = errorMessage(error); state.modelLoaded = false; state.hasContext = false; state.lastMeasuredTokens = 0; setText(el.modelState, "module plan rejected", true); setText(el.runtimeStatus, "Model load failed", true); setText(el.errorState, text, true); renderModulePlan(text, model.modulePlanReceipt, true); renderAdapterOptions(model, text, true); setControls(false, true); renderDiagnostics(); return false; } recordModulePlanTrace("ready"); } } else { renderProvenance("model rejected", null, true); renderAssembly("model rejected", null, true); if (model.modulePlan) { resetModulePlanTrace("model rejected", true); } renderAdapterOptions(model, "model not loaded"); } setControls(loadCode === 0, true); renderDiagnostics(); return loadCode === 0; } async function applySelectedAdapter(mode) { if (!state.exports || !state.modelLoaded) { return false; } const model = paths.models[state.activeModelKey]; const adapters = modelAdapters(model); const selectedIndex = selectedAdapterIndex(adapters); if (selectedIndex === null) { return false; } const result = await applyAdapterByIndex(model, selectedIndex, mode, 0); return result.ok; } async function applyAutoAssemblyStack(model, loadId) { const indexes = Array.isArray(model.adapterFamilyAutoApplyIndexes) ? model.adapterFamilyAutoApplyIndexes : [model.adapterFamilyPreferredIndex]; if ( !model.modulePlan || model.modulePlan.adapterValidationStrategy !== registryModulePlanAdapterValidationStrategy ) { throw new Error("Module plan adapter validation strategy mismatch"); } if (model.modulePlan.adapterApplyCount !== indexes.length) { throw new Error("Module plan adapter apply count mismatch"); } if (model.modulePlan.adapterValidationCount !== indexes.length) { throw new Error("Module plan adapter validation count mismatch"); } let autoAssemblyBytes = 0; const verifiedStack = []; const adapters = modelAdapters(model); setControls(false, true); setText(el.runtimeStatus, "Assembling modules"); setText(el.adapterState, "loading"); try { for (const index of indexes) { if ( loadId !== state.modelLoadSequence || !Number.isInteger(index) || index < 0 || index >= adapters.length ) { return false; } const adapterBytes = await fetchVerifiedAdapterBytes(model, index, true, autoAssemblyBytes); verifiedStack.push({ index, adapterBytes }); autoAssemblyBytes += adapterBytes.length; } let validated = 0; for (const verified of verifiedStack) { if (loadId !== state.modelLoadSequence) { return false; } validateAdapterWithRuntime(adapters[verified.index], verified.adapterBytes); validated += 1; } if (validated !== model.modulePlan.adapterValidationCount) { throw new Error("Module plan adapter validation count mismatch"); } } catch (error) { const text = errorMessage(error); setText(el.runtimeStatus, "Adapter load failed", true); setText(el.adapterState, text, true); setText(el.errorState, text, true); appendConsole(text); renderDiagnostics(); setControls(state.modelLoaded, true); return false; } autoAssemblyBytes = 0; let applied = 0; for (const verified of verifiedStack) { if (loadId !== state.modelLoadSequence) { return false; } const result = await applyAdapterByIndex( model, verified.index, "auto", autoAssemblyBytes, verified.adapterBytes ); autoAssemblyBytes = result.autoAssemblyBytes; if (!result.ok) { return false; } applied += 1; } const diagnostics = readDiagnosticsJson(); if ( applied !== model.modulePlan.adapterApplyCount || !diagnostics || diagnostics.adapter_apply_count !== model.modulePlan.adapterApplyCount ) { throw new Error("Module plan adapter apply count mismatch"); } if (applied > 1) { appendConsole(`adapter_stack_applied(${applied})`); setText(el.adapterState, "applied", false); } return applied > 0; } async function fetchAdapterBytes(adapter, model) { if (model && model.modulePlan) { return fetchModulePlanBytes(model, adapter.path, "adapter", "adapter-stack-artifact"); } const response = await fetch(adapter.path, localFetchOptions); if (!response.ok) { throw new Error(`Unable to fetch local adapter (${response.status})`); } return new Uint8Array(await response.arrayBuffer()); } function verifyAdapterBytes(model, selectedIndex, adapter, adapterBytes, isAutoAssembly, autoAssemblyBytes) { const manifestFields = Array.isArray(model.adapterFamilyManifests) ? model.adapterFamilyManifests[selectedIndex] : null; if (manifestFields) { const expectedBytes = adapterManifestArtifactBytes(manifestFields, "Adapter manifest"); if (adapterBytes.length !== expectedBytes) { throw new Error("Adapter artifact byte count mismatch"); } if ( isAutoAssembly && model.adapterFamily && autoAssemblyBytes + adapterBytes.length > model.adapterFamily.autoApplyByteBudget ) { throw new Error("Adapter auto assembly byte budget exceeded"); } } if (adapter.artifactChecksum) { requireChecksumEqual( adapterArtifactChecksumHex(adapterBytes), adapter.artifactChecksum, "adapter artifact" ); } } async function fetchVerifiedAdapterBytes(model, selectedIndex, isAutoAssembly, autoAssemblyBytes) { const adapter = modelAdapters(model)[selectedIndex]; const adapterBytes = await fetchAdapterBytes(adapter, model); verifyAdapterBytes(model, selectedIndex, adapter, adapterBytes, isAutoAssembly, autoAssemblyBytes); if (isAutoAssembly && model.modulePlan) { const moduleIndex = modulePlanStackModuleIndexForAdapter(model.modulePlanReceipt, selectedIndex); if (moduleIndex === null) { throw new Error("Module plan adapter index mismatch"); } recordModulePlanActualModuleBytes(model, moduleIndex, adapterBytes.length); recordModulePlanActualModuleChecksum(model, moduleIndex, adapterArtifactChecksumHex(adapterBytes)); } return adapterBytes; } function validateAdapterWithRuntime(adapter, adapterBytes) { if (typeof state.exports.validate_adapter_delta !== "function") { throw new Error("WASM runtime does not expose adapter validation"); } const ptr = allocCopy(adapterBytes); const code = state.exports.validate_adapter_delta(ptr, adapterBytes.length); release(ptr, adapterBytes.length); const text = readLastResult() || `adapter validation returned ${code}`; appendConsole(`validate_adapter_delta(${adapter.label || adapter.path}) -> ${code}\n${text}`); renderDiagnostics(); if (code !== 0) { throw new Error(text); } return true; } async function applyAdapterByIndex(model, selectedIndex, mode, autoAssemblyBytes, verifiedAdapterBytes) { if (!state.exports || !state.modelLoaded) { return { ok: false, autoAssemblyBytes }; } const adapters = modelAdapters(model); if (!Number.isInteger(selectedIndex) || selectedIndex < 0 || selectedIndex >= adapters.length) { return { ok: false, autoAssemblyBytes }; } const adapter = adapters[selectedIndex]; if (typeof state.exports.apply_adapter_delta !== "function") { throw new Error("WASM runtime does not expose adapter apply"); } setControls(false, true); const isAutoAssembly = mode === "auto"; setText(el.runtimeStatus, isAutoAssembly ? "Assembling modules" : "Applying adapter"); setText(el.adapterState, "loading"); let adapterBytes = null; try { adapterBytes = verifiedAdapterBytes || await fetchAdapterBytes(adapter, isAutoAssembly ? model : null); verifyAdapterBytes(model, selectedIndex, adapter, adapterBytes, isAutoAssembly, autoAssemblyBytes); } catch (error) { const text = errorMessage(error); setText(el.runtimeStatus, "Adapter load failed", true); setText(el.adapterState, text, true); setText(el.errorState, text, true); appendConsole(text); renderDiagnostics(); setControls(state.modelLoaded, true); return { ok: false, autoAssemblyBytes }; } const ptr = allocCopy(adapterBytes); const code = state.exports.apply_adapter_delta(ptr, adapterBytes.length); release(ptr, adapterBytes.length); const text = readLastResult() || `adapter apply returned ${code}`; state.lastGenerateMs = 0; state.lastMeasuredTokens = 0; state.hasContext = false; if (code === 0) { setText(el.runtimeStatus, "Ready", false); setText(el.adapterState, "applied", false); setText(el.errorState, "none", false); setText(el.response, text, false); } else { setText(el.runtimeStatus, "Adapter rejected", true); setText(el.adapterState, text, true); setText(el.errorState, text, true); setText(el.response, text, true); } appendConsole(`apply_adapter_delta(${adapter.label || adapter.path}) -> ${code}\n${text}`); renderDiagnostics(); setControls(state.modelLoaded, true); if (code === 0 && isAutoAssembly) { autoAssemblyBytes += adapterBytes.length; } return { ok: code === 0, autoAssemblyBytes }; } async function boot() { try { setText(el.runtimeStatus, "Loading runtime"); setInteractive(false); const wasmBytes = await loadRuntimeWasmBytes(); state.instance = await WebAssembly.instantiate(wasmBytes, {}); state.exports = state.instance.instance.exports; state.wasmMemoryInitialPages = wasmMemoryInitialPages(); const initCode = state.exports.init_runtime(); setText(el.wasmState, initCode === 0 ? "loaded" : `error ${initCode}`, initCode !== 0); if (initCode !== 0) { setText(el.runtimeStatus, "Runtime rejected", true); setText(el.errorState, readLastResult(), true); renderDiagnostics(); return; } await loadSelectorRegistry(); await loadSelectedModel(); } catch (error) { setText(el.runtimeStatus, "Boot failed", true); setText(el.modelState, "boot error", true); setText(el.errorState, errorMessage(error), true); } } el.form.addEventListener("submit", function (event) { event.preventDefault(); if (!state.exports) { return; } const bytes = state.encoder.encode(el.prompt.value); // Keeps prompt transfer bytes inside the same envelope declared by generated module plans. if (bytes.length > registryModulePlanPromptByteLimit) { const text = "prompt byte limit exceeded"; setText(el.response, text, true); setText(el.errorState, text, true); el.console.textContent = text; appendMessage("user", el.prompt.value, false); appendMessage("assistant", text, true); renderDiagnostics(); setControls(true, true); return; } const ptr = allocCopy(bytes); const maxTokens = Math.max(1, Math.min(512, Number.parseInt(el.maxTokens.value, 10) || 1)); el.maxTokens.value = String(maxTokens); let sampling = null; try { sampling = applySamplingConfig(); } catch (error) { release(ptr, bytes.length); const text = errorMessage(error); setText(el.response, text, true); setText(el.errorState, text, true); el.console.textContent = text; appendMessage("user", el.prompt.value, false); appendMessage("assistant", text, true); renderDiagnostics(); return; } const started = performance.now(); const code = state.exports.generate(ptr, bytes.length, maxTokens); state.lastGenerateMs = Math.round(performance.now() - started); state.lastMeasuredTokens = 0; release(ptr, bytes.length); const text = readLastResult(); state.hasContext = code === 0; setText(el.response, text, code !== 0); el.console.textContent = `generate(max_new_tokens=${maxTokens}, temperature=${sampling.temperature}, top_k=${sampling.topK}, top_p=${sampling.topP}, seed=${sampling.seed}) -> ${code} in ${state.lastGenerateMs} ms\n${text}`; setText(el.errorState, code === 0 ? "none" : text, code !== 0); appendMessage("user", el.prompt.value, false); appendMessage("assistant", text, code !== 0); renderDiagnostics(); setControls(true, true); }); el.stepTokenButton.addEventListener("click", function () { if (!state.exports || !state.hasContext) { return; } let sampling = null; try { sampling = applySamplingConfig(); } catch (error) { const text = errorMessage(error); setText(el.errorState, text, true); appendConsole(text); renderDiagnostics(); setControls(true, true); return; } const started = performance.now(); const code = state.exports.generate_next_token(); state.lastGenerateMs = Math.round(performance.now() - started); const text = readLastResult(); const resultText = text || `generate_next_token failed (${code})`; const consoleText = `generate_next_token(temperature=${sampling.temperature}, top_k=${sampling.topK}, top_p=${sampling.topP}, seed=${sampling.seed}) -> ${code} in ${state.lastGenerateMs} ms\n${resultText}`; state.lastMeasuredTokens = code === 0 ? 1 : 0; state.hasContext = code === 0; appendConsole(consoleText); if (code === 0) { setText(el.response, `${el.response.textContent}${text}`, false); setText(el.errorState, "none", false); extendAssistantMessage(text); } else { setText(el.errorState, resultText, true); if (!el.response.textContent) { setText(el.response, resultText, true); } appendMessage("assistant", resultText, true); } renderDiagnostics(); setControls(true, true); }); el.modelSelect.addEventListener("change", function () { if (!state.exports) { return; } loadSelectedModel().catch((error) => { setText(el.runtimeStatus, "Model load failed", true); setText(el.modelState, "unexpected error", true); setText(el.errorState, errorMessage(error), true); setControls(false, Boolean(state.exports)); }); }); el.applyAdapterButton.addEventListener("click", function () { applySelectedAdapter().catch((error) => { const text = errorMessage(error); setText(el.runtimeStatus, "Adapter load failed", true); setText(el.adapterState, text, true); setText(el.errorState, text, true); appendConsole(text); renderDiagnostics(); setControls(state.modelLoaded, Boolean(state.exports)); }); }); el.resetButton.addEventListener("click", function () { if (state.exports) { state.exports.reset_context(); state.lastGenerateMs = 0; state.lastMeasuredTokens = 0; state.hasContext = false; el.response.textContent = ""; el.console.textContent = "context reset"; renderDiagnostics(); setControls(true, true); } }); el.clearChatButton.addEventListener("click", function () { state.messages = []; renderConversation(); }); renderConversation(); boot(); }()); ================================================================================ END FILE: tinyrustlm/app/app.js ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/app/index.html BYTES: 10228 SHA256: 669165A9E41F16BB316E67CAF0B7CE78AF302CB4DBB009D035E8F97F198A09B3 ================================================================================ TinyRustLM

GGUF.MiRust.com

TinyRustLM

Booting
All inference runs locally in this browser. Prompts are not sent to a server.
Decoding

Conversation

    Response

    
          

    Model Loading

    WASM
    waiting
    Model
    waiting
    Error
    none

    Adapter Sidecar

    Status
    waiting

    Model Provenance

    Manifest
    waiting
    Source
    waiting
    Admission
    waiting
    Quality
    waiting
    Trained
    waiting
    Genome
    waiting
    Species
    waiting
    Novelty
    waiting
    Population
    waiting
    Mate Selection
    waiting
    Operator
    waiting
    Schedule
    waiting
    Phenotype
    waiting
    Artifact
    waiting
    Fitness
    waiting
    Eval Cases
    waiting
    Eval Checksum
    waiting
    Checksum
    waiting
    Next Gate
    waiting

    Assembly Evidence

    Receipt
    waiting
    Kind
    waiting
    Parents
    waiting
    Operator
    waiting
    Ledger
    waiting
    Next Gate
    waiting

    Module Plan

    Receipt
    waiting
    Kind
    waiting
    Resource
    waiting
    Execution
    waiting
    Fetch
    waiting
    Origin
    waiting
    Fetch Limit
    waiting
    Plan Fetches
    waiting
    Actual Fetches
    waiting
    Route Hash
    waiting
    Route Version
    waiting
    Route Set
    waiting
    Actual Route Set
    waiting
    WASM Pages
    waiting
    WASM ABI
    waiting
    Transfer
    waiting
    Release
    waiting
    Reset
    waiting
    Validate
    waiting
    Validate Count
    waiting
    Apply Count
    waiting
    Heap Floor
    waiting
    Context
    waiting
    Sampler Cap
    waiting
    Tokenizer
    waiting
    Modules
    waiting
    Model Budget
    waiting
    Adapter Budget
    waiting
    Stack Budget
    waiting
    Scratch Budget
    waiting
    Prompt Limit
    waiting
    Output Limit
    waiting
    KV Budget
    waiting
    KV Pages
    waiting
    Total Budget
    waiting
    Total Limit
    waiting
    Bytes
    waiting
    Actual Module Bytes
    waiting
    Checksums
    waiting
    Actual Module Checksums
    waiting
    Slots
    waiting
    Roles
    waiting
    Phases
    waiting
    Depends
    waiting
    Trace
    waiting
    Model
    waiting
    Stack
    waiting

    Benchmark

    Load
    waiting
    Prompt
    0 tokens
    Generated
    0 tokens
    Speed
    0.000 tok/s
    Scratch
    0 bytes

    Runtime Diagnostics

    
          

    Token Generation Console

    
          

    Developer Mode

    
          
    TinyRustLM GGUF.MiRust.com browser-local Rust/WASM runtime Local .slm models only
    ================================================================================ END FILE: tinyrustlm/app/index.html ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/docs/architecture.md BYTES: 18117 SHA256: 6EE3C495E1E518E249AD38BE548F98DF31B86B82614A9AFB93C5778F6233E269 ================================================================================ # TinyRustLM Architecture ## Purpose TinyRustLM is a browser-local SLM runtime with a static UI, handwritten JavaScript bootstrap, no-crate Rust local server, no-crate Rust mini browser harness, Rust WASM runtime, and local `.slm` model files. ## Constraints The runtime, local server, and mini browser harness use no third-party Rust crates, no JavaScript frameworks, no tokenizer libraries, no ML frameworks, and no remote inference APIs. Rust owns local static hosting, app-contract verification, model validation, adapter validation, tokenization, math, KV cache, sampling, and diagnostics. JavaScript only fetches local static files, copies model or adapter bytes into WASM memory, calls exports, and renders UI state such as provenance, diagnostics, benchmark values, adapter status, and the local conversation transcript. ## Data Structures The core data structures are `SlmHeader`, `TensorEntry`, typed tensor storage, pre-resolved top-level and per-layer tensor indices, `Tokenizer`, `TensorView`, `MutableTensorView`, `KvCache`, `SamplingConfig`, `Diagnostics`, and `Runtime`. The local server adds a small request-line parser, percent decoder, traversal-checked path resolver, and content-type mapper for static browser files. The Rust mini browser harness adds required DOM id checks, local-only marker scanning, model-route verification, adapter-route verification, selector-registry intake markers, line-based manifest validation, loopback URL parsing, and simple HTTP response validation. The packer adds `source.manifest` records and raw f32 tensor files as the trained-source input boundary before `.slm` conversion, including BPE token/merge records that serialize into `BPE1` tokenizer sections and explicit `tied_output=true` source layouts that omit `output.weight` and set the v1 flag during conversion. The packer also adds line-based parent compatibility reports, candidate lineage templates, direct-parameter blend, task-delta, and sparse task-delta operator receipts, raw, sparse, and low-rank f32 adapter-delta artifacts, adapter-fuse receipts, adapter-family receipts, candidate artifact manifests, multi-parent candidate manifests, promotion templates, multi-parent promotion templates, multi-parent selector admission records, runtime-smoke sidecars, selector admission records, promotion ledgers, population reviews, parent-pool recipes, sign-aware parent-pool merge receipts, selector registries with optional f32/q8_0/q4_0 adapter sidecar fields plus indexed adapter-family and receipt fields, and generated browser multi-parent bundles that bind admitted `.slm` parents to planned, operator-produced, adapter-packaged, adapter-fused, adapter-family-bound, manifest-bound, multi-parent-manifest-bound, proof-pending, evidence-passed, multi-parent-evidence-passed, history-chained, frontier-ranked, parent-pool-seeded, sign-merged, browser-routed, and registry-carried adapter-family candidates before selector loading. The browser app can read a local `models/selector.registry` file and replace its checked-in smoke list only with admitted `../models/*.slm` entries; it can also read optional local f32/q8_0/q4_0 `../models/*.adp1`, `../models/*.asp1`, or `../models/*.alr1` adapter routes and served `.adapter-family.receipt` handles from that registry while keeping adapter bytes opaque to JavaScript. The checked tiny f32/q8_0/q4_0 self-ADP1 sidecars remain the fallback local routes into Rust `apply_adapter_delta`. The native eval runner adds line-based eval cases and eval sidecars as the evidence boundary after runtime execution. The runtime keeps q8_0 raw rows plus scales and q4_0 packed nibbles plus block scales for direct matvec, dequantizes only requested rows or small vectors into model-loaded reusable scratch for embedding and norm paths, and re-quantizes compact rows or blocks when a validated ADP1, ASP1, or ALR1 package is applied. Model load resolves the tensor indices needed by generation once, including the tied-output flag fallback from `output.weight` to `tok_embeddings.weight`, so per-token forward passes do not format layer tensor names or scan the tensor directory by stable name. It also owns a reusable logits buffer so prompt generation and `generate_next_token` do not allocate scratch or vocab-sized logits per token. Decoding defaults to greedy for repeatable tests, while Rust also owns validated temperature, top-k, top-p, seeded PRNG sampling, and fixed candidate buffers capped at 1024 candidates so BPE vocabularies above byte-tokenizer size do not require a per-token heap vector. The first real-shaped target uses four layers, hidden size 512, eight heads, FFN size 2048, and context 512. Population review records expose the ranking objective vector as data: `fitness_objective_vector_*` fields define quality, frugality, and quantization-fit weights, and each ranked entry carries a `fitness_objective_vector_checksum` over its score vector before parent-pool recipes consume the review. Adapter-family routing extends the registry-carried sidecar bead: generated registries can keep the single-route fields for the first `ADP1` sidecar, add indexed fields for additional compatible local sidecars on the same admitted f32/q8_0/q4_0 entry, and carry a served adapter-family receipt path plus checksum. The browser fetches and checksum-verifies that receipt plus each served adapter manifest, matches each member against the selector metadata and shared base-quantization identity fields, and displays local adapter options only after the receipt and manifests match while Rust keeps package validation authority. ## Binary Formats The `.slm` model file is little-endian and starts with `SLM1`. It contains a fixed v1 header, tokenizer section, tensor directory, 64-byte-aligned tensor data, and aligned scale sections for quantized tensors. Model loading parses the tokenizer section and selects either the fixed byte tokenizer (`BTOK`) or the custom BPE tokenizer (`BPE1`) before generation. A v1 tied-output flag permits `output.weight` to be omitted only when logits can project through `tok_embeddings.weight`; the checked-in tied fixture keeps that contract artifact-backed. ## Failure Cases The runtime rejects null pointers, invalid lengths, invalid UTF-8, invalid magic, unsupported model versions, malformed headers, malformed tensor directories, missing tensors, shape mismatches, unsupported dtypes, context overflow, unloaded model calls, generation failures, and output overflow. The local server rejects unsupported methods, malformed request lines, invalid percent escapes, absolute paths, traversal paths, drive-qualified paths, and missing files. The Rust mini browser harness rejects missing UI contract markers, remote asset markers, missing model or manifest files, manifest quality overclaims, non-loopback HTTP URLs, wrong content types, and local route failures. ## Validation Rules Every raw pointer crossing the WASM boundary is checked before use. Every binary parser validates bounds before reading. Tensor shapes must match element counts. Header dimensions must be non-zero and attention heads times head dimension must equal hidden size. Model admission is split into source validation, structural validation, parent compatibility for assembly work, candidate lineage binding, offline operator receipt validation, adapter artifact validation, adapter-fuse validation, runtime f32/q8_0/q4_0 adapter apply, browser adapter sidecar routing, registry-carried adapter-family receipt routing, candidate artifact binding, multi-parent candidate binding, candidate promotion binding, provenance validation, runtime-smoke sidecar binding, runtime eval evidence, selector admission, multi-parent selector admission, promotion ledger history, population review, parent-pool recipe, sign-merge candidate receipt, selector registry routing, generated browser bundle routing, and quality gating. Source validation accepts only line-declared raw f32 tensor files with safe paths, exact sizes, matching source checksums, expected shapes, finite bounded values, nonzero payloads, and tokenizer metadata that agrees with the declared model shape. Parent compatibility validates both `.slm` files first and passes the direct-parameter lane only when version, shape, tokenizer checksum, output-head contract, quantization, tensor count, parameter count, and tensor layout checksum match exactly. Candidate lineage then binds a planned candidate id, operator id, resource budget, parent fields, and compatibility report checksum before any operator can produce an artifact. The offline operator lane now includes weighted blend receipts, task-delta receipts, sparse task-delta receipts, and sign-aware parent-pool merge receipts: each verifies parent checksums, dequantizes compatible tensors as needed, writes a normal `.slm`, and records receipts that validators recompute before later gates. Sparse task-delta selection keeps the largest absolute target-minus-base deltas by parts-per-million keep rate, records selection metric and parameter counts, and leaves unselected entries at the base value. The adapter lane writes `ADP1` raw f32 task-delta packages, `ASP1` sparse f32 task-delta packages, and `ALR1` low-rank f32 task-delta packages from the same lineage and parent gates; sparse manifests record the same keep-rate and mask breadcrumb fields used by sparse task-delta receipts, and low-rank manifests record factor and residual fields for matrix deltas. Fuse validation currently consumes raw ADP1 packages, checks the adapter header and tensor directory against the base parent, writes a normal `.slm` candidate, and records an adapter-fuse receipt before candidate-manifest. Runtime adapter apply validates loaded-base identity, package and payload checksums, tokenizer checksum, tensor layout checksum, tensor directory metadata, finite deltas or factors, sparse indices or low-rank shapes, and fused values before mutating tensors, re-quantizing compact q8_0/q4_0 rows or blocks when needed, and clearing generation state. Browser adapter sidecar routing is the UI bead for checked tiny ADP1 routes and generated ADP1/ASP1/ALR1 routes: JavaScript filters a local `.adp1`, `.asp1`, or `.alr1` route, transfers bytes to WASM, and Rust remains the adapter validator. Registry-carried adapter-family receipt routing lets a generated selector registry attach local f32/q8_0/q4_0 `ADP1`, `ASP1`, or `ALR1` routes, sidecar manifest routes, labels, apply statuses, checksums, and one served receipt handle to an admitted entry; browser smoke then proves the UI fetches and verifies the receipt plus adapter manifests, loads the generated model, and applies the declared ADP1/ASP1/ALR1 stack without parsing adapter bytes. Candidate artifact manifests validate the produced `.slm`, bind it to the lineage checksum, require it to match the parent direct-parameter contract, and leave runtime/eval/promotion as the next gate. Multi-parent candidate manifests validate sign-merge output, bind the receipt checksum, parent-pool recipe checksum, relatedness summary, parent summaries, candidate `.slm` fields, and pending promotion route before runtime/eval/admission work. Promotion templates bind candidate manifest checksums, keep runtime-smoke and eval pending, and keep browser selector plus public-claim status closed until later sidecars prove promotion; the multi-parent promotion template also carries the sign-merge receipt checksum, parent-pool recipe checksum, review/ledger/admission checksums, parent count, and candidate `.slm` fields. Runtime-smoke sidecars bind provenance manifest checksum, `.slm` checksum, source kind, and model shape to local execution proof. Selector admission records accept only valid promotion, runtime-smoke, and passed converted-trained eval sidecars, then bind all evidence checksums plus `eval_case_evidence_checksum`, a normalized digest over the evaluated case rows. Multi-parent selector admission records accept only valid sign-merge promotion templates, runtime-smoke, provenance, and passed converted-trained eval sidecars, then bind the multi-parent evidence checksums plus the same eval-case digest. Promotion ledgers accept admitted records, carry that digest with the selector-facing evidence fields, reject duplicate candidate artifacts, and hash-chain the promotion history before selector or population review. Population reviews validate that ledger against the same admissions, rank candidates by quality, artifact frugality, and quantization fit, then route the frontier candidate toward selector registry and the remaining candidates toward a parent pool. Parent-pool recipes validate the review, require selected parents to share one direct-parameter contract, bind ranked roles plus seed weights normalized from population fitness, and write relatedness metric/scope/pair count/status, a shared relatedness checksum, and per-parent relatedness group fields before sign-aware merge work. Sign-merge candidates validate that recipe, use parent 0 as the frontier base, apply seed-weighted positive or negative delta consensus across the remaining parents, keep base values on ties, and record recipe, relatedness, ledger, review, admission, parent, sign-count, and candidate checksum fields for the multi-parent candidate manifest. Selector registries accept selector admission records and multi-parent admission records only when the candidate artifact path resolves under served `tinyrustlm/models/`, write `../models/*.slm` routes, carry `entry.N.eval_case_evidence_checksum`, and give the browser selector an optional admitted-model intake path. `browser-multi-parent-bundle` dogfoods that route by creating quantization-selected target TinyRustLM roots with served `multi-parent-sign-merge-f32`, `multi-parent-sign-merge-q8`, or `multi-parent-sign-merge-q4` model files, manifests, selector registry, generated self ADP1, family ADP1, sparse ASP1, and low-rank ALR1 sidecars, adapter manifests, adapter-family receipt, assembly receipt with the eval-case digest, and evidence files. Current deterministic TinyLM-16M-shaped artifacts can pass `runtime-smoke`, which proves local execution and diagnostics only. Converted-trained artifacts can also pass `runtime-smoke` after source conversion and `.slm` admission, including BPE source bundles whose tokenizer table is carried into the binary artifact. Assistant-quality claims require a converted-trained provenance manifest and a separate evaluation sidecar with matching model and manifest checksums, passed task evaluation, a non-placeholder quality scope, positive case count, zero failed cases, exact per-case expected/actual matches, and an accepted quality decision. Population review validation also recomputes the objective-vector contract and per-entry objective checksums from the ledger plus admissions, so objective weights and score vectors stay tied to the same reviewed evidence as frontier selection. Generated browser bundle roots now carry the app shell and WASM runtime alongside `models/` and `evidence/`, so file-backed browser smoke can serve the packer output directly. The Rust mini browser harness runs before heavy browser automation. Static mode checks the checked-in app tree, required local UI, manifest sidecars, selected model routes, WASM call markers, and local-only policy. Optional HTTP mode probes the Rust local server over loopback for app, CSS, JS, WASM, q8 model, and q8 manifest routes. Headless browser smoke still owns actual JavaScript execution, WASM loading, generation, transcript rendering, and UI interaction proof. Registry adapter-family route validation extends the single-sidecar route without changing the Rust runtime boundary: selector validation requires f32/q8_0/q4_0 entries, local `../models/*.adp1`, `../models/*.asp1`, or `../models/*.alr1` paths, paired manifests, apply status, checksums, non-duplicate adapter paths, a local `.adapter-family.receipt` handle, a receipt checksum, and matching family count; browser smoke proves the served receipt plus all served adapter manifests are fetched, the generated sparse ASP1 and low-rank ALR1 sidecar routes are displayed, the selected artifact checksum is checked before WASM transfer, and the declared stack is applied. ## Future Expansion Path The next modular lane now starts from proven static f32/q8_0/q4_0 ADP1 apply, runtime ASP1 sparse apply, runtime ALR1 low-rank apply, registry-carried f32/q8_0/q4_0 ADP1/ASP1/ALR1 adapter routes, file-backed generated f32/q8_0/q4_0 bundle roots, and a browser-verified receipt path rather than a single generated sidecar. Richer trained LoRA or compact adapter formats should plug into the same manifest, receipt, route, and smoke shape before becoming browser-visible. Milestones continue from verified tiny fixtures, TinyLM-16M f32/q8_0/q4_0 smoke models, raw-f32 trained-source conversion including BPE source conversion and tied-output source conversion, artifact-backed tied-output validation, parent compatibility reports, candidate lineage templates, direct-parameter blend, task-delta, and sparse task-delta operator receipts, raw ADP1, sparse ASP1, and low-rank ALR1 adapter-delta artifacts, adapter-fuse candidate receipts, f32/q8_0/q4_0 ADP1/ASP1/ALR1 runtime adapter apply, checked browser f32/q8_0/q4_0 adapter sidecar routing, adapter-family receipts, candidate artifact manifests, multi-parent candidate manifests, promotion templates, multi-parent promotion templates, multi-parent selector admission records, runtime-smoke sidecars, selector admission records, promotion ledgers, population reviews, parent-pool recipes, sign-aware parent-pool merge receipts, selector registries, optional browser registry intake, generated browser-served multi-parent bundles, registry-carried ADP1/ASP1/ALR1 adapter families, and fixture-scoped eval execution into real trained weights, larger reviewed BPE tables, broader evaluation fixtures, trained LoRA-style adapters, broader offline assembly operators, and product-quality evidence review. TinyLM-64M and TinyLM-135M stay out of scope until the 16M path is correct. ================================================================================ END FILE: tinyrustlm/docs/architecture.md ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/docs/browser-runtime.md BYTES: 17717 SHA256: 8DDE334D27A44979124441E7221B68310F76A39195C6F9D73CA12E4D6597776C ================================================================================ # Browser Runtime ## Purpose The browser runtime hosts TinyRustLM as static files and keeps prompts local to the user browser. ## Constraints The app uses static HTML, custom CSS, handwritten JavaScript, local WASM, and local `.slm` files only. It does not use npm, CDN scripts, frontend frameworks, remote inference APIs, telemetry, analytics, or model downloads from external hosts during inference. Local development hosting uses the no-crate Rust server in `tools/local_server/`. It serves only the checked-in static tree over loopback, supports `GET` and `HEAD`, rejects traversal paths, and keeps Visual Studio F5 on the Rust toolchain path. The no-crate Rust mini browser harness in `tools/browser_harness/` audits the static app contract and can probe loopback routes before headless browser automation. The older Node server remains only as a narrow fallback utility. ## Data Structures JavaScript tracks the WASM instance, selected local model path, optional selector registry fields, selected local model manifest, selected local adapter sidecar metadata, fetched module-plan receipt fields, fetched adapter-family receipt fields, fetched adapter manifest fields, live module-plan trace checkpoints, local conversation transcript, max-token control, decoding controls, Step Token enablement, host-side benchmark timing, exports, UTF-8 encoder/decoder, DOM nodes, and typed-array views over WASM memory. Rust owns runtime state, including the bounded `last_result` transfer buffer and diagnostics fields for `adapter_apply_count`, `last_adapter_checksum`, and `assembly_state_checksum`. Model load seeds the assembly checksum, each accepted adapter apply folds the adapter package into it, and free or load failure clears the assembly fields. The transcript is browser-local UI state only: generation appends User and TinyRustLM entries with DOM text nodes, Step Token appends one decoded token to the current response and latest TinyRustLM turn, Reset clears runtime context and output without clearing transcript history, and Clear empties the transcript. The Rust mini browser harness tracks required app ids, local file routes, selector-registry markers, manifest fields, loopback HTTP status, and content types as a test-only contract surface. ## Binary Formats The Rust local server serves `runtime/tinyrustlm.wasm`, `runtime/tinyrustlm.wasm.manifest`, selected local `.slm` files under `models/`, local `.slm.manifest` sidecars, checked tiny f32/q8_0/q4_0 self-`ADP1` sidecars, generated registry-carried `.adp1`, `.asp1`, and `.alr1` sidecars, generated `.adapter-family.receipt` files, generated `.assembly.receipt` files with evidence routes, and an optional `models/selector.registry`. Before instantiating the runtime, JavaScript fetches `tinyrustlm.wasm.manifest`, checks the runtime kind, status, path, byte count, checksum, and next gate, then fetches the WASM bytes and recomputes the same local 64-bit checksum used by packer provenance text. `tinyrustlm-slm-pack browser-multi-parent-bundle` writes a fresh manifest beside every generated bundle runtime, and `runtime-wasm-manifest` refreshes the checked runtime manifest after a local rebuild. When that registry exists and passes the browser's simple route filter, the selector options come from admitted `../models/*.slm` entries; otherwise the checked-in deterministic smoke list remains active. The `multi-parent-registry` browser smoke mode serves a local selector registry entry for `multi-parent-sign-merge-q8`, loads that entry through the browser selector, then proves the model and manifest stay on the local `../models/*.slm` route while Rust still owns `.slm` admission. The `multi-parent-registry-file` mode is file-backed: `tinyrustlm-slm-pack browser-multi-parent-bundle` writes runnable TinyRustLM roots with app shell, WASM runtime, generated f32/q8_0/q4_0 sign-merge model, manifest, selector registry, module-plan receipt with `browser-constrained-v1` profile, `single-threaded-wasm-local-v1` execution profile, `module_plan_fetch_policy=local-no-store-v1`, `module_plan_origin_policy=same-origin-loopback-local-v1`, and `module_plan_runtime_scratch_byte_budget=65536`, assembly receipt, and evidence chain, and the browser loads `multi-parent-sign-merge-f32`, `multi-parent-sign-merge-q8`, or `multi-parent-sign-merge-q4` from those served files. The `combined-selector-assembly` smoke uses one generated `all` root, confirms q4_0 is selected before scripted switching, then walks q4_0, q8_0, and f32 entries while proving each module-plan receipt is requested before that entry's model bytes and each compatible adapter stack is auto-applied before generation. The generated bundle also writes matching self and family `.adp1` packages, a sparse `.asp1` package, a source-backed low-rank `.alr1` package converted from a reviewed adapter source template, their manifests, a served adapter-family receipt, and selector registry adapter-family fields so `adapter-sidecar-registry-file` can display all four registry-supplied sidecars and auto-apply the receipt-declared compatible stack after loading the generated model. Registry-backed models must also carry `entry.N.eval_case_evidence_checksum`, which the browser renders in Model Provenance and matches against the generated assembly receipt before evidence is accepted. If that assembly digest differs after receipt checksum verification, the browser frees the accepted model, records `assembly evidence rejected`, and does not request evidence or adapter-family routes. The selector entry can also carry `entry.N.module_plan_*` fields pointing at a served `.module-plan.receipt`; JavaScript fetches and checksum-verifies that plan before requesting the generated `.slm`, then matches the plan's `browser-constrained-v1` profile, `single-threaded-wasm-local-v1` execution profile, `local-no-store-v1` fetch policy, `same-origin-loopback-local-v1` origin policy, resource class, admitted model byte budget, adapter-family byte budget, runtime scratch byte budget, model, manifest, assembly receipt, adapter-family receipt, adapter-stack members, ordered module byte counts, ordered module checksums, ordered module assembly slots, ordered module role labels, ordered module phases, and ordered module dependency edges against selector metadata. The Module Plan panel renders the verified receipt status, kind, resource class, execution profile, fetch policy, origin policy, module count, model byte budget, adapter byte budget, runtime scratch byte budget, ordered module byte summary, ordered module checksum summary, ordered module slot summary, ordered module role summary, ordered phase summary, ordered dependency summary, live browser assembly trace, model path, and receipt-declared stack routes; checked fallback models render `none` with unavailable fields. Blend, task-delta, sparse task-delta, raw ADP1 adapter-delta packages, sparse ASP1 adapter-delta packages, low-rank ALR1 adapter-delta packages, and sign-merge evidence files are offline packer artifacts except for explicit checked local sidecars: the tiny fallback routes offer `../models/tiny-test-model-self.adp1`, `../models/tiny-test-model-q8-self.adp1`, and `../models/tiny-test-model-q4-self.adp1`; generated registries can offer compatible local f32/q8_0/q4_0 `ADP1`, `ASP1`, or source-backed `ALR1` routes plus receipt handles; JavaScript checks selected adapter artifact checksums before copying bytes into WASM; and Rust validates each compatible package before mutation. Each `.slm` candidate still must pass candidate manifest, promotion, runtime-smoke/eval, admission, and selector registry gates before the browser selector can route it. The browser copies model bytes into WASM memory and calls `load_model`. After Rust accepts the model, JavaScript fetches the matching local `.slm.manifest` sidecar and renders source kind, admission status, quality claim, trained-quality claim, checksum, and required next gate. The default fallback model is `models/tinylm16-q8.slm`; TinyLM-16M q4_0, f32, tiny byte-tokenizer fixtures, the tiny BPE fixture, and the tiny tied-output fixture remain selectable for regression checks. For generated registry adapter families, the browser first verifies the module-plan receipt when one is declared. It then fetches the served `.adapter-family.receipt` and each served `.adp1.manifest`, `.asp1.manifest`, or `.alr1.manifest` after model and manifest load, recomputes text checksums, verifies the receipt kind/status/strategy/count, verifies each adapter manifest's route-derived artifact kind/status/dtype/apply status, and matches each member's route, manifest route, label, apply status, artifact checksum, manifest checksum, manifest byte count, and shared base-quantization adapter identity before the options are enabled. The `.alr1` route accepts both deterministic task-delta and source-backed manifest kind/dtype pairs while Rust remains the package authority. The same receipt declares an ordered auto-apply stack; the browser verifies stack status, strategy, count, indexes, paths, and aggregate manifest-declared artifact bytes, fetches and checksum-checks every stack member, calls Rust `validate_adapter_delta` for every fetched member, and only then transfers the same bytes through `apply_adapter_delta`. After generated stack apply, runtime diagnostics must show the expected stack count and nonzero adapter plus assembly checksums before generation. ## Failure Cases Fetch failure, missing model files, runtime manifest mismatch, WASM instantiation failure, allocation failure, model rejection, UTF-8 transfer failure, model reload failure, missing manifest sidecars, context overflow, output-buffer overflow, and generation errors render in the UI. Model-specific failures disable Generate and Reset while keeping model selection available for recovery after the WASM runtime is loaded. A manifest-sidecar failure does not replace Rust model admission; it leaves inference available while making provenance unavailable. ## Validation Rules JavaScript does not parse model or adapter bytes in the UI path. It only transfers them. JavaScript parses the line-based runtime WASM manifest before instantiation, selector registry metadata before loading a model, optional generated module-plan receipts before fetching generated model bytes, the local `.slm.manifest` sidecar after Rust accepts the model, and generated adapter-family receipts plus adapter manifests before enabling family choices. Registry entries must be `admitted-records-only`, must have admitted entry status, and must route to `../models/*.slm` without traversal or remote markers. Optional registry adapter fields must route to `../models/*.adp1`, `../models/*.asp1`, or `../models/*.alr1`, carry sidecar manifest paths, and use the apply status that matches the route format and entry quantization: ADP1/ASP1 f32 entries use `runtime-f32-compatible-or-fuse-to-slm`, ADP1/ASP1 q8_0 and q4_0 entries use `runtime-q8-q4-compatible-or-fuse-to-slm`, ALR1 f32 entries use `runtime-f32-compatible-low-rank`, and ALR1 q8_0/q4_0 entries use `runtime-q8-q4-compatible-low-rank`. Single-adapter registries use the legacy `entry.N.adapter_path` fields; adapter-family registries add `entry.N.adapter_count`, indexed `entry.N.adapter.K.*` fields, optional `entry.N.adapter_family_*` receipt metadata, explicit `entry.N.adapter_auto_apply_stack_*` fields, optional `entry.N.module_plan_*` fields, `entry.N.eval_case_evidence_checksum`, and served `.module-plan.receipt` files for generated self-assembly. Adapter sidecar routes must stay under `../models/*.adp1`, `../models/*.asp1`, or `../models/*.alr1` without traversal or remote markers; adapter-family receipt routes must stay under `../models/*.adapter-family.receipt`, module-plan routes must stay under `../models/*.module-plan.receipt`, each receipt route must carry a hex checksum and expected status/kind/strategy/profile/execution-profile fields, and generated module plans must match profile, execution profile, resource class, model byte budget, adapter byte budget, runtime scratch byte budget, model, manifest, assembly receipt, adapter-family receipt, module byte counts, module checksums, module roles, module assembly slots, module phases, module dependency edges, and every declared stack member. The fetched receipt checksum, fetched model byte count, fetched manifest text byte count, fetched receipt text byte counts, fetched adapter-manifest checksums, manifest-declared adapter artifact byte counts, eval-case checksum, each module checksum, each receipt member, each receipt role, each receipt assembly slot, each receipt phase, each dependency edge, and each stack member must match the selector metadata before the browser exposes or auto-applies those options. On apply, the fetched local ADP1/ASP1/ALR1 bytes must match the selected route's artifact checksum before WASM transfer. Temperature, top-k, top-p, and seed controls are clamped in JavaScript, then passed through `set_sampling_config`; Rust validates and owns sampling with a fixed 1024-candidate cap. Rust returns explicit error codes and readable result text for the UI. Generated output decoded into `last_result` is capped at 64 KiB; byte and BPE tokenizer decode paths return `OutputBufferExceeded` before replacing the old result, and full `generate` failures clear token/cache diagnostics. `generate_next_token` follows that same ABI rule: it returns an `ErrorCode`, writes decoded token text into `last_result`, and exposes the selected token id in diagnostics. `validate_adapter_delta` accepts bytes copied into WASM memory, runs the same compatible raw `ADP1`, sparse `ASP1`, or low-rank `ALR1` model-aware checks as apply, writes `adapter validated` to `last_result`, and preserves generation/KV diagnostics. `apply_adapter_delta` accepts bytes copied into WASM memory, validates compatible packages against the loaded f32, q8_0, or q4_0 model, applies them in place, re-quantizes compact q8_0/q4_0 tensors when needed, writes `adapter applied` to `last_result`, and clears generation/KV diagnostics on success. The browser Step Token control is disabled until generation context exists, then stays available across transcript Clear and disables after runtime Reset, failed generation, or successful adapter apply. The Rust mini browser harness validates the checked-in app tree for required UI ids, selector registry fetch markers, model route declarations including the tied-output fixture, adapter route declarations, runtime manifest fields, adapter stack and module-plan strategy/profile/execution-profile markers, local-only markers, Rust WASM export definitions, and optional loopback HTTP content types. The Rust local server is smoke-tested with direct HTTP probes for `/app/`, `/runtime/tinyrustlm.wasm`, `/runtime/tinyrustlm.wasm.manifest`, `.slm`, and `.slm.manifest` routes. `tools/browser-smoke.js` verifies the UI by loading the app in headless Chrome or Edge, clicking Generate, clicking Step Token, reading rendered output and diagnostics, asserting transcript entries, Clear-click behavior, Step Token enablement, and Clear-button state, auditing desktop/mobile product-shell structure, checking default greedy sampling controls, checking the provenance panel, checking the Module Plan panel's fallback and generated-receipt fields including visible execution profile, model, adapter, and runtime scratch budgets, byte summaries, checksum summaries, slot summaries, role summaries, phase summaries, dependency summaries, and the live trace from plan verification through stack apply, applying the checked f32/q8_0/q4_0 adapter sidecars, applying an intercepted registry-supplied q8_0 adapter sidecar, fetching generated module-plan receipts before generated model bytes, checking module-plan profile, execution profile, resource, runtime scratch, graph, stack, role, slot, phase, byte-count, checksum, and dependency drift before generated model or adapter-stack routes, checking assembly eval-case drift before evidence or adapter-family routes, validating and auto-applying the generated registry-supplied family ADP1 plus sparse ASP1 plus source-backed low-rank ALR1 adapter stack after the receipt and adapter manifest requests, asserting the Rust diagnostics assembly count and checksums for generated stacks plus checked manual sidecars, walking one combined generated selector root through q4_0, q8_0, and f32 verified self-assembly, checking runtime manifest drift handling, checking repeated q8/q4 generation with reset, intercepting malformed local model bytes, intercepting missing local model files, serving a multi-parent selector registry fixture, loading a generated served multi-parent bundle, submitting an over-context prompt, running endurance loops, and asserting local-only network requests. ## Future Expansion Path Later UI work can add richer benchmark charts and a reviewed trained-model selector once real trained weights and assistant-quality evidence exist. The first selector registry path is intentionally small: it supplies admitted local routes but does not replace Rust `.slm` validation or provenance sidecars. Missing-file UI coverage, context overflow rendering, malformed model rejection, repeated q8/q4 loops, transcript rendering, desktop/mobile shell audit, provenance-panel audit, endurance loops, sampling ABI validation, invalid UTF-8 WASM ABI checks, single-token stepping, and model-free behavior are covered by smoke tools. Tokenizer detail, logits summary, top-k candidates, KV cache length, quant mode, active sampling config, host-side benchmark timing, transcript history, and model quality boundary are already exposed in the UI. ================================================================================ END FILE: tinyrustlm/docs/browser-runtime.md ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/docs/performance.md BYTES: 3603 SHA256: 07A74898373F6807DE99BB1BCB3748A16460F0CB4CCE45D857CB56533A2A1B33 ================================================================================ # Performance ## Purpose Performance work keeps the browser runtime responsive while protecting correctness. ## Constraints Correct f32 output comes before speed. The runtime must avoid uncontrolled per-token allocation and must keep memory usage visible in diagnostics. ## Data Structures Diagnostics track model load time, prompt token count, generated token count, tokens per second, peak scratch arena usage, KV cache length, and active quantization mode. Quantized models keep q8_0/q4_0 payloads in native compact storage and use model-loaded scratch buffers for row/vector dequantization. Runtime generation also keeps pre-resolved tensor indices, a reusable logits buffer, allocation-free top-k diagnostics, fixed-buffer stochastic sampling, and a 64 KiB generated-result cap so prompt generation and single-token stepping do not allocate new scratch, vocab-sized logits, layer-name strings, diagnostic candidate vectors, sampling candidate vectors, or unbounded result buffers per token. The browser UI also measures host-side load and generation elapsed time. ## Binary Formats The current TinyLM-16M f32 file is about 68 MB. The current TinyLM-16M q8_0 file is about 17 MB. The current TinyLM-16M q4_0 file is 10,657,728 bytes, inside the expected 9-15 MB range. ## Failure Cases Context overflow, scratch arena exhaustion, output buffer overflow, non-finite softmax sums, and malformed quant blocks are correctness failures, not performance metrics. ## Validation Rules Initial f32, q8_0, and q4_0 should not crash on a model configured for 512-token context. Browser diagnostics must render after load and generation. Unit tests assert generation scratch/logits pointer stability across prompt generation and repeated `generate_next_token` calls. Context-boundary tests assert that a prompt may fill every context slot except the first generated-token slot and that a full prompt context is rejected before generation. Output-buffer tests assert byte and BPE decode reject over-limit result text with `OutputBufferExceeded` and that full-generation failures clear stale generation state. Sampling tests assert seeded top-k/top-p behavior, reject top-k values beyond the fixed 1024-candidate cap, and prove the BPE fixture can use top_k 262 without a vocab-sized candidate allocation. The TinyLM-16M q8_0 and q4_0 browser smokes generated one token from prompt `hi`, reported 47,104 bytes of scratch usage after scratch-backed quantized row/vector dequantization, and rendered host-side token speed. The browser performance smoke runs multi-token q8_0 and q4_0 generation through the UI, then verifies prompt-token count, generated-token count, token-speed display, scratch-byte display, quantization mode, reset recovery, and local-only network requests. This is a benchmark-panel correctness check, not a trained-quality or production throughput claim. The browser performance soak repeats that multi-token q8_0 and q4_0 path across cycles. Each cycle must produce deterministic output, positive host-side token speed, expected prompt/generated counts, expected KV cache length, nonzero scratch usage during generation, clean reset diagnostics, and local-only network requests. This is still a stability and instrumentation check, not a final quality benchmark. ## Future Expansion Path Optimization can focus on q8/q4 matvec tiling, fewer scratch dequantization passes, fewer copies across the JS/WASM boundary, larger context support, larger BPE-aware fixed sampling buffers or model-loaded sampler scratch, and eventually optional WebGPU outside the first-version scope. ================================================================================ END FILE: tinyrustlm/docs/performance.md ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/docs/quantization.md BYTES: 2032 SHA256: 1B1AFD7292FFD7FE5F023EE9BBF33169E1A2A839673434AE481603DAFA55A700 ================================================================================ # Quantization ## Purpose Quantization reduces model download size and memory pressure. The current implementation proves q8_0 and q4_0 with tiny fixture files and proves TinyLM-16M f32/q8_0/q4_0 smoke models, with direct q8_0 and q4_0 matvec dispatch. ## Constraints The first runtime target remains f32 correctness. q8_0 and q4_0 support must preserve the f32 tiny and TinyLM-16M smoke behavior. ## Data Structures q8_0 stores signed 8-bit weights with f32 scales and keeps raw int8 rows for direct matvec. q4_0 stores signed 4-bit packed nibbles with f32 scales and keeps the packed bytes for direct matvec. The runtime no longer keeps full decoded f32 shadow copies for q8_0 or q4_0 tensors; embedding rows and norm vectors are dequantized into scratch only when needed. The tensor directory carries block size explicitly. ## Binary Formats Each tensor directory entry declares dtype, payload offset, byte length, scale offset, and block size. q8_0 and q4_0 payload interpretation is selected from dtype. Quantized payloads and scale payloads are separately aligned. ## Failure Cases Unsupported dtype, missing scales, invalid block sizes, row length mismatches, and tensor shape mismatches are fatal for the active quantized path. ## Validation Rules The model loader validates dtype before dispatch. q4_0 rows require columns to divide into the entry block size. q8_0 rows require one scale per row. Matrix-vector operations dispatch by tensor dtype; q8_0 and q4_0 matrices use direct quantized matvec with f32 accumulation. Borrowed f32 tensor slices are available only for native f32 tensors; quantized tensors must be copied into caller-owned f32 buffers when a decoded reference path is required. ## Future Expansion Path Next quantization work should measure the scratch-row dequantization path across longer prompts, improve q8/q4 matvec tiling, and add larger quality-model evidence. Mixed precision for embeddings and output projection can be added only after baseline TinyLM-16M q8/q4 tests stay green. ================================================================================ END FILE: tinyrustlm/docs/quantization.md ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/docs/slm-format.md BYTES: 29705 SHA256: 4D06F94001165FBA0E996ADFE2DB234CA66B758379F807E716F6B7D542EA7627 ================================================================================ # SLM Format ## Purpose `.slm` is the local model file format for TinyRustLM. It is designed for simple browser loading and strict Rust-side validation. ## Constraints The format is little-endian, self-describing, versioned, non-JSON, and static. It has no dynamic schema language and no dependency on GGUF, ONNX, safetensors, or external tokenization formats. ## Data Structures The v1 header stores model dimensions, tokenizer offsets, tensor directory offsets, tensor count, tensor data offset, and checksum. The checksum is a simple custom u64 over the complete file with the checksum field itself treated as zero, so the packer can write it after all payload bytes are finalized. Tensor directory entries store name hash, dtype, rank, dimensions, data offset, byte length, quant scale offset, and block size. q8_0 uses one f32 scale per row. q4_0 uses f32 scales per row block. The tokenizer section is now validated as either `BTOK` byte-tokenizer metadata or `BPE1` custom BPE metadata. ## Binary Formats Header fields start with four bytes `SLM1`, followed by u32/u64/f32 fields in little-endian order. Tensor directory entries are 64 bytes. Tensor payloads and quantization scale payloads are aligned to 64-byte offsets. `BTOK` tokenizer sections contain magic, version, fixed vocab size, and special token ids. `BPE1` tokenizer sections contain magic, version, vocab size, special token ids, token count, merge count, variable token records, and merge records. BPE token records store `token_id`, byte length, and raw bytes. BPE merge records store `left`, `right`, `output`, and `rank`. ## Failure Cases Invalid magic, short files, unsupported versions, zero checksum, checksum mismatch, zero dimensions, attention shape mismatch, out-of-range offsets, malformed tokenizer sections, malformed tensor directory entries, unsupported dtype, missing scale payloads, invalid q4 block sizes, missing required tensors, and an omitted `output.weight` without the v1 tied-output flag are fatal loader errors. ## Validation Rules The parser validates the file has enough bytes before every read. Header length must be at least the v1 minimum. Tensor data offset must be 64-byte aligned. A v1 file must carry a nonzero checksum, and the parser recomputes the checksum with bytes 100..108 treated as zero before accepting the header. Each tensor payload range must fit inside the file. The model loader validates dtype-specific byte lengths and scale counts before decoding tensors. The v1 tied-output flag is `flags & 1 != 0`; when set, `output.weight` may be omitted and output projection uses `tok_embeddings.weight`. Without that flag, `output.weight` remains required. The native packer also exposes `tinyrustlm-slm-pack validate ` as an admission gate for generated or future converted models. That command verifies checksum, byte-tokenizer or BPE metadata, required tensor names and shapes, dtype-specific payload lengths, quantization scale ranges, finite f32 payload values, duplicate tensor hashes, and reports the accepted shape, tensor count, parameter count, quantization mode, and checksum. The packer also exposes a line-based provenance sidecar: `tinyrustlm-slm-pack manifest [source_kind]` and `tinyrustlm-slm-pack validate-manifest `. The sidecar is outside the v1 binary file so the runtime format stays stable. It binds model bytes, `.slm` checksum, shape, tensor count, parameter count, quantization mode, source kind, admission status, and quality boundary. Deterministic smoke models must not claim trained quality; converted trained models validate only as structure-accepted and quality-pending. The packer also exposes a line-based parent compatibility report: `tinyrustlm-slm-pack compatibility [output.compat]`. The command validates both `.slm` files first, then records `compatible_parent_set`, parent byte counts, `.slm` checksums, shape summaries, tensor counts, parameter counts, quantization labels, output-head contracts, format flags, tokenizer checksums, and tensor layout checksums. The report is outside the v1 binary file and is intended as a no-crate assembly gate for future offline model-breeding operators. The packer also exposes a line-based candidate lineage template: `tinyrustlm-slm-pack lineage-template [resource-budget]` and `tinyrustlm-slm-pack validate-lineage `. The template accepts only a passing compatibility report. It records the candidate id, planned status, operator id, resource budget, compatibility report checksum, parent checksums, parent shapes, parent quantization, parent output-head contracts, pending candidate artifact paths, and the next admission gate. The packer also exposes offline direct-parameter operators. `tinyrustlm-slm-pack blend-candidate [parent0-weight-ppm]` and `tinyrustlm-slm-pack validate-blend-candidate ` validate lineage, check supplied parent checksums against the compatibility report, dequantize compatible tensors as needed, blend f32 values by parts-per-million weights, write a normal `.slm`, and write an operator receipt that validation recomputes byte-for-byte. `tinyrustlm-slm-pack delta-candidate [delta-weight-ppm]` and `tinyrustlm-slm-pack validate-delta-candidate ` use the same gates, compute `base + weight * (target - base)` with signed parts-per-million weights, and bind a recomputable task-delta receipt to the output `.slm`. `tinyrustlm-slm-pack sparse-delta-candidate [delta-weight-ppm] [keep-ppm]` and `validate-sparse-delta-candidate` use the same base/target contract, select the largest absolute target-minus-base deltas by keep rate, leave unselected entries at the base value, and bind a recomputable sparse task-delta receipt with selection metric, parameter counts, density and nonzero-delta retention ppm, pruned/unchanged counts, and an implicit top-k mask checksum. The packer also exposes offline adapter artifact paths. `tinyrustlm-slm-pack adapter-delta ` validates lineage, checks compatibility-bound parent checksums, dequantizes compatible tensors as needed, and writes an `ADP1` binary package containing raw f32 `target - base` tensor deltas in parent tensor order. `tinyrustlm-slm-pack validate-adapter-delta ` recomputes the package and manifest byte-for-byte. `tinyrustlm-slm-pack sparse-adapter-delta [delta-weight-ppm] [keep-ppm]` writes an `ASP1` sparse f32 task-delta package with sorted `(u64 value_index, f32 delta)` pairs per tensor, using the largest absolute target-minus-base deltas by keep rate. `tinyrustlm-slm-pack low-rank-adapter-delta [rank-limit]` writes an `ALR1` low-rank f32 task-delta package with deterministic cross-residual `A` and `B` factors for matrix tensors. `validate-sparse-adapter-delta` and `validate-low-rank-adapter-delta` recompute their packages and manifests byte-for-byte. Raw adapter manifests record `adapter_artifact_kind=raw-f32-task-delta-v1`; sparse manifests record `adapter_artifact_kind=sparse-f32-task-delta-v1`, `adapter_sparse_pair_width_bytes=12`, density, nonzero-delta retention, selected/pruned/unchanged counts, and an implicit sparse mask checksum; low-rank manifests record `adapter_artifact_kind=low-rank-f32-task-delta-v1`, `adapter_low_rank_format=ALR1`, component limit/cap, matrix and active tensor counts, factor density ppm, and initial/residual L1 microunits. F32-base raw/sparse manifests record `adapter_apply_status=runtime-f32-compatible-or-fuse-to-slm`; q8_0 and q4_0 raw/sparse manifests record `adapter_apply_status=runtime-q8-q4-compatible-or-fuse-to-slm`; low-rank manifests record runtime-compatible low-rank apply statuses. `tinyrustlm-slm-pack fuse-adapter-delta ` validates a raw `ADP1` package and manifest, checks its header and tensor directory against the base parent, fuses base plus deltas into a normal `.slm` candidate using the base parent dtype/layout, and writes an adapter-fuse receipt. `validate-fuse-adapter-delta` recomputes the fused candidate and receipt byte-for-byte before candidate-manifest. The runtime can apply compatible `ADP1` raw, `ASP1` sparse, or `ALR1` low-rank packages to an already loaded f32, q8_0, or q4_0 model through the WASM ABI; it validates the same identity fields and payload checksums before mutating loaded tensors, re-quantizes compact q8_0 rows or q4_0 blocks when needed, then clears generation and KV state. The checked browser fixtures serve `models/tiny-test-model-self.adp1`, `models/tiny-test-model-q8-self.adp1`, and `models/tiny-test-model-q4-self.adp1` as local zero-delta sidecars for the current browser ADP1 route. The packer also exposes a line-based candidate artifact manifest: `tinyrustlm-slm-pack candidate-manifest ` and `tinyrustlm-slm-pack validate-candidate `. The command validates lineage first, validates the candidate `.slm`, requires the candidate to match the direct-parameter parent contract, then records lineage checksum, candidate checksum, shape, tokenizer checksum, tensor layout checksum, admission status, pending eval status, and the next promotion gate. The packer also exposes line-based promotion templates. `tinyrustlm-slm-pack promotion-template [promoter-id] [promotion-scope]` and `tinyrustlm-slm-pack validate-promotion ` validate the two-parent candidate artifact manifest first, record the candidate manifest checksum, keep runtime-smoke and eval statuses pending, and keep browser selector plus public-claim admission closed until later evidence sidecars exist. `tinyrustlm-slm-pack multi-parent-promotion-template --parents [...parent.slm] --admissions [...input.admission]` and `validate-multi-parent-promotion` validate the sign-merge candidate manifest first, then bind the candidate manifest checksum, operator receipt checksum, parent-pool recipe checksum, ledger/review/admission checksums, parent count, candidate `.slm` fields, and pending runtime-smoke/eval route for the multi-parent path. The packer also exposes line-based runtime-smoke, selector admission, promotion ledger, population review, parent-pool recipe, sign-merge candidate, multi-parent candidate manifest, multi-parent promotion, multi-parent selector admission, and selector registry records. `tinyrustlm-slm-pack runtime-smoke ` writes a sidecar bound to the provenance manifest checksum, `.slm` checksum, source kind, model shape, and passed runtime-smoke decision; `validate-runtime-smoke` proves it still matches. `tinyrustlm-slm-pack admission-record [selector-id]` accepts only a valid promotion, runtime-smoke sidecar, and passed converted-trained eval sidecar. The resulting admission record binds all evidence checksums, marks the browser selector as admitted, and keeps public claims bound to the declared eval scope. `tinyrustlm-slm-pack promotion-ledger [...input.admission]` writes a hash-chained promotion history from admitted records; `validate-promotion-ledger` rejects entry drift and duplicate candidate artifacts. `tinyrustlm-slm-pack population-review [...input.admission]` validates the ledger against the same admissions, ranks candidates by quality, artifact frugality, and quantization fit, records a weighted fitness-objective vector contract plus per-entry objective checksums, then records the frontier candidate and parent-pool route; `validate-population-review` recomputes the review from ledger plus admissions. `tinyrustlm-slm-pack parent-pool-recipe [...input.admission]` validates the review, requires the reviewed parents to share one direct-parameter contract, and writes ranked parent roles, fitness-normalized seed weights, relatedness metric/scope/pair count/status, a shared relatedness checksum, and per-parent relatedness group fields; `validate-parent-pool-recipe` recomputes the recipe from ledger, review, and admissions. `tinyrustlm-slm-pack sign-merge-candidate --parents [...parent.slm] --admissions [...input.admission]` validates the recipe and supplied parent artifacts, uses parent 0 as the frontier base, applies seed-weighted positive or negative delta consensus across the remaining parents, writes a normal `.slm`, and records recipe, relatedness, ledger, review, admission, parent, sign-count, and candidate checksum fields; `validate-sign-merge-candidate` recomputes the candidate and receipt byte-for-byte. `tinyrustlm-slm-pack multi-parent-candidate-manifest --parents [...parent.slm] --admissions [...input.admission]` validates that sign-merge receipt, then writes a manifest with receipt checksum, recipe checksum, relatedness summary, parent summaries, candidate `.slm` fields, pending eval status, and next promotion route; `validate-multi-parent-candidate` recomputes it. `tinyrustlm-slm-pack multi-parent-promotion-template --parents [...parent.slm] --admissions [...input.admission]` validates that manifest and writes a promotion template for runtime-smoke/eval handoff; `validate-multi-parent-promotion` recomputes it. `tinyrustlm-slm-pack multi-parent-admission-record --parents [...parent.slm] --admissions [...input.admission]` accepts only that validated multi-parent promotion template plus matching provenance, runtime-smoke, and passed eval sidecars. The resulting record binds the sign-merge receipt, parent-pool recipe, review, ledger, admission-set, candidate, provenance, runtime, and eval checksums; `validate-multi-parent-admission` recomputes it. `tinyrustlm-slm-pack selector-registry [...input.admission]` accepts selector admission records and multi-parent admission records whose candidate paths resolve under served `tinyrustlm/models/`, writes browser-safe `../models/*.slm` routes, and `validate-selector-registry` rejects entry drift. Generated bundle registries may also carry optional f32/q8_0/q4_0 adapter route fields for a selected entry. Single-route registries use `entry.N.adapter_path`, `entry.N.adapter_manifest_path`, `entry.N.adapter_label`, `entry.N.adapter_apply_status`, `entry.N.adapter_artifact_checksum`, and `entry.N.adapter_manifest_checksum`. Adapter-family registries keep those fields as the first-route mirror and add `entry.N.adapter_count` plus indexed `entry.N.adapter.K.path`, `manifest_path`, `label`, `apply_status`, `artifact_checksum`, and `manifest_checksum` fields. A generated bundle may also include `entry.N.adapter_family_receipt_path`, `adapter_family_receipt_checksum`, `adapter_family_label`, `adapter_family_status`, `adapter_family_strategy`, and `adapter_family_adapter_count`, pointing at a served `.adapter-family.receipt` file that is recomputed from the member manifests during bundle generation. Selector validation requires local `../models/*.adp1`, `../models/*.asp1`, or `../models/*.alr1` routing, sidecar manifest pairing, non-duplicate adapter paths per candidate, a f32/q8_0/q4_0 registry entry, route-format-specific apply status matching the entry quantization, a local receipt route when family receipt fields are present, a hex receipt checksum, and matching adapter-family count. The browser consumes generated adapter-family receipt fields as an assembly menu gate: after Rust accepts the `.slm` model and JavaScript loads its `.slm.manifest`, the browser fetches the served receipt and adapter manifests, recomputes the same text checksums, verifies the receipt kind/status/strategy/count, verifies each adapter manifest kind/status/dtype/apply status, and matches each member's route, manifest route, label, apply status, artifact checksum, manifest checksum, manifest byte count, and shared base-quantization identity fields before exposing the sidecar choices. When a sidecar is applied, JavaScript recomputes the selected ADP1, ASP1, or ALR1 artifact checksum before transferring bytes into WASM. Trained source conversion is intentionally outside the browser runtime. `tinyrustlm-slm-pack source-template [tiny-fixture|tiny-fixture-tied|tiny-fixture-bpe|tinylm16|tinylm16-tied]` writes a reviewable source-weight directory with `source.manifest` and raw little-endian f32 tensor files under `tensors/`. `validate-source ` checks the source before conversion. `convert-trained [f32|q8_0|q4_0]` reads validated f32 tensors, writes a checksum-bearing `.slm`, validates it, and writes a converted-trained provenance sidecar. The source manifest is line-based, not JSON. It declares `tinyrustlm_trained_source_version=1`, `layout=raw-f32-tensor-files-v1`, `tied_output=true|false`, shape fields, tokenizer, source dtype, source kind, source evidence fields, tensor count, and one record per required tensor. Existing manifests without `tied_output` are accepted as `false` for backward compatibility. BPE source manifests use `tokenizer=bpe-v1`, a BPE model shape such as `tiny-fixture-bpe` or future `tinylm16-bpe`, `bpe_token_count`, `bpe_merge_count`, `bpe.token.N.id`, `bpe.token.N.bytes_hex`, and ranked `bpe.merge.N.*` records; conversion serializes those records into the actual `BPE1` tokenizer section. Tied source manifests must use a tied shape name, must omit `output.weight`, and must produce a v1 `.slm` file with the tied-output flag set. Each tensor record must name the expected tensor, rank, dimensions, safe relative file path, exact byte count, and source checksum. Source paths must stay under `tensors/`; absolute paths and parent traversal are rejected. Source-weight constraints are deliberately strict. The first conversion layout accepts raw f32 source tensors only, then performs q8_0 or q4_0 quantization itself when requested. Every source tensor must have the exact byte length implied by shape, finite f32 values, absolute values no larger than 64.0, a nonzero payload, and a matching source checksum. The validator also rejects `model_shape` and `tied_output` disagreement, BPE tokenizer labels without BPE source shapes, BPE source shapes without `tokenizer=bpe-v1`, duplicate BPE token ids, duplicate BPE merge ranks, merge outputs outside the declared vocabulary, and stray BPE records outside declared counts. These checks catch broken endian exports, missing files, path confusion, placeholder tensors, accidental prequantized input, tokenizer/source mismatch, and output-head layout drift before a converted model can receive a `.slm.manifest`. Quality admission is a separate gate. `tinyrustlm-slm-pack quality-gate runtime-smoke` permits deterministic smoke or converted-trained artifacts only for runtime-execution evidence. `tinyrustlm-slm-pack eval-template assistant-quality` writes a pending line-based evaluation sidecar bound to the exact model checksum, model shape, source kind, and manifest checksum. `cargo run -p tinyrustlm-runtime --bin tinyrustlm-eval -- ` executes exact local cases through the Rust runtime and writes a scoped eval sidecar. Eval case files must declare at least one nonempty exact case and cannot carry stray case keys outside the declared count. `tinyrustlm-slm-pack quality-gate assistant-quality ` requires `source_kind=converted-trained`, matching checksums, `eval_status=pass`, `task_eval_status=pass`, `safety_review_status=pass`, `quality_decision=accepted-for-assistant-quality`, non-placeholder `quality_scope`, evaluator, dataset, summary, quality boundary, positive case count, all cases passed, zero failed cases, and exact per-case expected/actual matches. Pending templates, missing case evidence, mismatched case text, and deterministic smoke manifests fail the assistant-quality gate. Parent compatibility is exact for the first direct-parameter lane. Two parents pass only when `.slm` version, model shape, tokenizer checksum, output-head contract, quantization label, tensor count, parameter count, and tensor layout checksum match. q8_0 and q4_0 parents with the same architecture stay in separate direct-parameter lanes because their tensor layouts and quantization semantics differ. Heterogeneous parent sets can still become future candidates through source conversion, distillation, or retraining routes before normal `.slm` admission, provenance, runtime-smoke, and eval gates. Candidate lineage validation binds a planned candidate to the exact compatibility report checksum and copied parent fields before any operator writes a candidate artifact. Blend, task-delta, and sparse task-delta validation then recompute the produced `.slm` and operator receipt from the same parents, lineage, and operator weights; sparse receipts also bind keep rate, absolute-delta selection, deterministic tie break, and selected/pruned counts. Adapter-delta validation recomputes `ADP1` raw packages, `ASP1` sparse packages, or `ALR1` low-rank packages and manifests from the same compatibility-bound parents and lineage; adapter-family receipt validation then proves generated sidecars share the same adapter identity fields, including base quantization before selector routing; adapter-fuse validation recomputes the `.slm` candidate and receipt from a raw adapter package before candidate artifact validation binds the produced `.slm` back to the lineage checksum and parent contract. Promotion validation binds the candidate manifest checksum and preserves the pending runtime-smoke/eval gate before browser exposure. Admission validation binds promotion, runtime-smoke, and eval sidecar checksums before a candidate can enter a promotion ledger, population review, parent-pool recipe, sign-merge operator, or selector registry. Ledger validation chains admitted records and rejects duplicate candidate artifacts. Population review validation recomputes deterministic candidate rankings, objective-vector metadata, and per-entry objective checksums from the ledger plus admissions before parent selection or selector-registry routing. Parent-pool recipe validation recomputes the review first, checks that all selected parents share one direct-parameter contract, and binds seed weights normalized from population fitness plus a deterministic relatedness checksum over the selected parent family. Sign-merge validation recomputes recipe validation, parent artifact checks, seed-weighted sign consensus, candidate bytes, relatedness fields, and receipt text; multi-parent candidate manifest validation then binds that receipt checksum, recipe checksum, relatedness summary, parent summaries, and candidate `.slm` fields. Multi-parent promotion validation binds the candidate manifest checksum and keeps the same pending runtime-smoke/eval route before multi-parent admission. Multi-parent admission validation binds the promotion template to runtime-smoke, provenance, and eval sidecars. Registry validation then binds either admission record family to a browser-served model route before optional selector consumption, and generated registry adapter-family receipt fields bind compatible f32/q8_0/q4_0 sidecars to the same entry without moving adapter validation out of Rust. Generated registry adapter-family receipt fields are also verified in the browser before use. That check binds selector metadata to the served receipt and adapter manifest text, including the entry quantization matched to adapter apply status; the apply path then checks the selected ADP1 artifact checksum while keeping the payload opaque until Rust validates the selected package. ## Future Expansion Path The first format path supports f32, q8_0, and q4_0 tiny byte-tokenizer fixtures, a tiny f32 BPE fixture with a checked runtime merge proof, a tied-output tiny fixture that omits `output.weight`, and real-shaped TinyLM-16M f32, q8_0, and q4_0 models. The first trained-source conversion path is raw f32 by design so quantization stays local and reviewable, and it now supports BPE source manifests that serialize into `BPE1` sections plus tied raw source bundles that omit `output.weight` while setting the v1 tied-output flag during conversion. Current `BPE1` support gives trained models a custom tokenizer table and merge table without external formats. The parent compatibility report is the first model-breeding assembly bead, the candidate lineage template is the second, the blend, task-delta, or sparse task-delta operator receipt is the third `.slm` output bead, the raw `ADP1`, sparse `ASP1`, and low-rank `ALR1` adapter-delta packages are parallel adapter beads, adapter-fuse is the bridge from raw ADP1 back to a normal `.slm` candidate, runtime f32/q8_0/q4_0 adapter apply is the browser-local assembly bead for a compatible loaded base plus raw, sparse, or low-rank sidecar, adapter-family receipts are the browser assembly menu bead for generated compatible ADP1/ASP1/ALR1 sidecar sets, browser-side adapter artifact checksum verification is the pre-transfer bead for selected ADP1/ASP1/ALR1 bytes, the candidate artifact manifest is the fourth `.slm` bead, the promotion template is the fifth for the two-parent path, the runtime-smoke sidecar is the sixth, the selector admission record is the seventh, the promotion ledger is the eighth, the population review is the ninth and now carries weighted objective-vector metadata, the parent-pool recipe is the tenth and now carries shared-family relatedness metadata, the sign-merge receipt is the eleventh offline multi-parent bead and echoes that metadata, the multi-parent candidate manifest is the twelfth and carries the relatedness summary, the multi-parent promotion template is the thirteenth for that path, the multi-parent admission record is the fourteenth, the selector registry is the served-model route bead for both admission families, and registry-carried f32/q8_0/q4_0 adapter families are the browser assembly route bead for compatible generated entries: together they prove which admitted artifacts share a direct-parameter contract, which planned candidate may proceed to an offline operator, which operator wrote a recomputable `.slm` or adapter artifact, which adapter package produced a recomputable `.slm` or runtime f32/q8_0/q4_0 assembly input, which generated sidecar set has one identity-bound receipt, which produced `.slm` still fits that lineage or sign-merge recipe, which candidate is waiting for runtime/eval proof, which evaluated candidate can enter promotion history, which objective contract selected the current frontier, which reviewed parent set has one relatedness identity and can produce a sign-aware candidate, which multi-parent candidate has runtime/eval evidence, which served route the browser may load, and which compatible sidecars the browser may transfer to Rust. Later versions can add larger reviewed BPE vocabularies, richer trained conversion metadata, embedded provenance sections, trained LoRA-style low-rank modules, richer compact adapter metadata, compact retention metadata, and paging metadata without changing the v1 parser contract. In the current browser bead, registry-carried f32/q8_0/q4_0 adapter families are transfer-eligible only after the served receipt and adapter manifests pass checksum and member matching in JavaScript; ADP1, ASP1, and ALR1 package validation and mutation remain in Rust. ================================================================================ END FILE: tinyrustlm/docs/slm-format.md ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/docs/testing.md BYTES: 45408 SHA256: FEEB5288862F939384B44320EA75AF0DEE06BDF76E1D919B9A543BEEB448C5A4 ================================================================================ # Testing ## Purpose Tests prove each low-level primitive before the runtime claims TinyLM-16M support. ## Constraints Tests use Rust's built-in test framework only. No external crates, Python fixtures, npm harness, or generated test code are required for unit tests. The workspace denies missing public Rust documentation, and release/test helpers run strict rustdoc checks for the runtime library plus the no-crate Rust tool binaries. ## Coverage Goals Changed code should target at least 75% automated coverage. Each new or changed method parameter should have a related automated test for its accepted behavior, rejection behavior, or boundary effect. Standalone test files should mirror the tested source filename with `_test` appended before the extension; inline Rust unit tests remain acceptable where the module already uses that pattern. ## Data Structures The required test surface covers byte tokenizer, UTF-8 prompt handling, byte and BPE bounded decode overflow, custom BPE section parsing, deterministic BPE merge/decode behavior, BPE validator rejection, tiny BPE `.slm` runtime generation with merged token diagnostics, BPE stochastic top-k above byte-tokenizer vocabulary size, TensorView and MutableTensorView shape/index contracts, dot product known output and mismatch rejection, RMSNorm, softmax, empty softmax rejection, matvec, matmul, SiLU, SwiGLU, q8 dequant, q4 dequant, block-size-aware q4 matvec, q8/q4 re-quantization helpers, RoPE, KV cache byte-budget and page-count reporting, `.slm` header parsing, invalid magic, checksum rejection, native `.slm` admission validation, parent compatibility report generation, candidate lineage template validation, direct-parameter blend, task-delta, sparse task-delta, crossover, and bounded mutation operator validation, raw ADP1, sparse ASP1, and low-rank ALR1 adapter-delta artifact validation, trained low-rank adapter source validation, adapter-fuse candidate validation, runtime f32/q8_0/q4_0 `ADP1`, `ASP1`, and `ALR1` adapter apply, runtime assembly diagnostics for adapter apply count plus model/adapter assembly checksums and KV-cache byte/page fields, candidate artifact manifest validation, multi-parent candidate manifest validation, candidate promotion template validation, multi-parent promotion template validation, multi-parent admission record validation, generated browser multi-parent bundle writing, runtime WASM manifest writing, generated registry-carried adapter-family writing, runtime-smoke sidecar validation, selector admission record validation, promotion ledger validation, selector registry validation, optional browser selector registry intake markers, browser-served runtime manifest verification, browser-served multi-parent selector registry routing, browser-served generated multi-parent artifact routing, browser f32/q8_0/q4_0 adapter sidecar routing, browser registry-carried f32/q8_0/q4_0 adapter-family routing, trained-source layout validation, source-weight constraint rejection, trained-source conversion, BPE trained-source manifest validation, BPE trained-source q8_0 conversion, tied-output trained-source manifest validation, tied-output trained-source f32/q8_0/q4_0 conversion, native eval-case parsing and execution, exact eval case-count validation, `.slm` provenance manifest validation, `.slm` quality-gate validation, per-case assistant-quality evidence validation, missing tensors, pre-resolved tensor indices, tied-output projection fallback, tied-output `.slm` validation without `output.weight`, missing-output rejection without the tied flag, tied-output runtime generation, greedy sampling, seeded temperature/top-k/top-p sampling, fixed-buffer stochastic candidate selection, runtime sampling configuration diagnostics, context-boundary acceptance and rejection, output-buffer overflow cleanup, reusable generation scratch/logits stability, allocation-free top-k diagnostic selection, EOS stopping, f32 tiny fixture generation, q8_0 tiny fixture generation, q4_0 tiny fixture generation, TinyLM-16M f32/q8_0/q4_0 smoke generation, Rust local-server request parsing and traversal rejection, Rust mini browser harness contract validation, WASM ABI invalid-prompt, invalid-sampling, step-token, adapter apply, and model-free handling, browser UI smoke generation, browser Step Token click-through, browser adapter sidecar click-through, conversation transcript rendering, desktop/mobile UI audit, malformed model UI handling, missing model UI handling, context overflow UI handling, repeated browser reload/reset/model-switch smoke, and benchmark-panel performance smoke. Model-breeding population coverage also includes population review validation with objective-vector checksum drift rejection, parent-pool recipe validation with relatedness checksum drift rejection, sign-merge candidate validation from reviewed parent-pool recipes through recomputable candidate receipts that echo relatedness fields, multi-parent candidate manifest validation from those receipts, multi-parent promotion template validation from those manifests, multi-parent admission record validation from runtime/eval evidence, selector-registry validation from mixed selector plus multi-parent admission records, and generated browser bundle validation from parent seeds through selector routing. Trained adapter source ALR1 coverage includes source-factor conversion for f32 and q8_0 bases, recomputed source-backed ALR1 manifests, base contract mismatch rejection, and ALR1 artifact checksum drift rejection. Registry adapter-family coverage adds selector tests for multiple adapter routes on one admitted entry, q8_0 registry adapter route admission, selector genome id and genome lineage checksum generation, selector species id and species-fit checksum generation, selector novelty id and behavior-sketch checksum generation, selector population id and population-review checksum generation, selector mate-selection id, status, parent count, and checksum generation, selector phenotype-evidence id, status, provenance-manifest checksum, and checksum generation, selector heritable-artifact id, status, and served-artifact checksum generation, scoped fitness-vector checksum generation, genome drift rejection, species drift rejection, novelty drift rejection, population drift rejection, mate-selection drift rejection, mate-selection parent-count drift rejection, phenotype-evidence drift rejection, heritable-artifact drift rejection, fitness drift rejection, apply-status-to-quantization matching, duplicate adapter route rejection, adapter auto-apply stack-count drift rejection, module-plan route generation, module-plan count drift rejection, module-plan resource-envelope drift rejection, module-plan profile drift rejection, module-plan execution-profile drift rejection, module-plan fetch-policy drift rejection, module-plan fetch-count limit generation/missing/drift rejection, module-plan runtime scratch budget drift/missing/malformed rejection, module-plan prompt byte-limit generation and drift rejection, module-plan output-limit generation and drift rejection, module-plan KV-cache byte-budget/page-count generation and drift rejection, module-plan context token limit generation and drift rejection, module-plan tokenizer checksum generation and drift rejection, module-plan sampler candidate cap generation and drift rejection, module-plan adapter-stack byte-budget generation and drift rejection, module-plan total-budget and total-limit drift rejection, generated bundle tests for f32/q8_0/q4_0 self ADP1, family ADP1, sparse ASP1, and source-backed low-rank ALR1 sidecars, ordered stack metadata, module-plan profile metadata, execution-profile metadata, fetch-policy metadata, fetch-count-limit metadata, runtime scratch metadata, prompt-limit metadata, output-limit metadata, tokenizer metadata, sampler-cap metadata, context metadata, KV-cache metadata, total-limit metadata, module byte-count metadata, module checksum metadata, module role metadata, module assembly-slot metadata, module phase metadata, module dependency metadata, and served `.module-plan.receipt` files, browser parsing of indexed adapter fields plus selector genome/species/novelty/population/mate-selection/phenotype/artifact/fitness provenance fields, `adapter-sidecar-registry-file` proof that the module plan is requested before the generated model while the Module Plan panel displays the verified kind/resource/execution/fetch/fetch-limit/plan-fetches/actual-fetches/actual-route-set/actual-module-bytes/tokenizer/sampler-cap/context/module/model-budget/adapter-budget/stack-budget/scratch-budget/prompt-limit/output-limit/KV-budget/KV-pages/total-budget/total-limit/bytes/checksums/slot/role/phase/dependency/trace/model/stack fields and the family ADP1 plus sparse ASP1 plus source-backed low-rank ALR1 stack is applied before generation, `combined-selector-assembly` proof that one generated `all` root starts on q4_0 then switches through q8_0 and f32 while verifying each module plan before model bytes, matching browser-owned actual fetch count to planned fetch count, matching browser-observed route-set checksum to declared route-set checksum, matching browser-observed actual module bytes to receipt-declared module byte rows, rendering registry-backed provenance genome/species/novelty/population/mate-selection/phenotype/artifact/fitness rows, and auto-applying each stack before generation, `module-plan-fetch-count-drift` proof that checksum-consistent fetch-count limit drift stops before generated model bytes, adapter-family receipts, adapter manifests, or stack artifacts, `module-plan-prompt-limit-drift` proof that checksum-consistent prompt-limit drift stops before generated model bytes, adapter-family receipts, adapter manifests, or stack artifacts, and source-root `prompt-limit` proof that oversized prompt bytes stop before WASM prompt transfer. Selector novelty, population, mate-selection, phenotype, and heritable-artifact coverage adds deterministic `entry.N.novelty_id`, `entry.N.novelty_strategy`, `entry.N.novelty_status`, `entry.N.novelty_checksum`, `entry.N.population_id`, `entry.N.population_strategy`, `entry.N.population_status`, `entry.N.population_checksum`, `entry.N.mate_selection_id`, `entry.N.mate_selection_strategy`, `entry.N.mate_selection_status`, `entry.N.mate_selection_parent_count`, `entry.N.mate_selection_checksum`, `entry.N.phenotype_evidence_id`, `entry.N.phenotype_evidence_strategy`, `entry.N.phenotype_evidence_status`, `entry.N.phenotype_evidence_checksum`, `entry.N.provenance_manifest_checksum`, `entry.N.heritable_artifact_id`, `entry.N.heritable_artifact_strategy`, `entry.N.heritable_artifact_status`, and `entry.N.heritable_artifact_checksum` generation, novelty, population, mate-selection, phenotype-evidence, and heritable-artifact drift rejection, parent-count contract rejection, generated bundle assertions, browser registry intake, the Model Provenance `Novelty`, `Population`, `Mate Selection`, `Phenotype`, and `Artifact` rows, and `combined-selector-assembly` proof that q4_0/q8_0/f32 entries render Genome, Species, Novelty, Population, Mate Selection, Phenotype, Artifact, Fitness, eval cases, and eval checksum together. Module-plan origin policy coverage adds selector validation for `module_plan_origin_policy=same-origin-loopback-local-v1`, generated bundle receipt metadata, the Module Plan `Origin` row, and `module-plan-origin-policy-drift` proof that checksum-consistent origin drift stops before generated model bytes or adapter stack routes. Module-plan WASM export-set coverage adds selector validation for `module_plan_wasm_export_set=tinyrustlm-generate-v1`, generated bundle receipt metadata, instantiated WASM export checks, the Module Plan `WASM ABI` row, and `module-plan-wasm-export-set-drift` proof that checksum-consistent export-set drift stops before generated model bytes or adapter stack routes. `combined-selector-cycle` also records release-before-reassembly evidence: the initial q4_0 pass uses the page's loaded model, and every later q8_0/f32/q4_0/q8_0/f32 pass must call `free_model` before the next generated stack validation begins. `combined-selector-route-soak` extends the same path to three q4_0/q8_0/f32 cycles and requires per-pass requests for every generated self-assembly file route. `combined-selector-route-extended-soak` raises that proof to five q4_0/q8_0/f32 cycles in one page. `combined-selector-route-stress-soak` raises it to eight q4_0/q8_0/f32 cycles in one page. `assembly-evidence-file-drift` complements `assembly-eval-case-drift` by leaving selector, module-plan, model, manifest, and assembly receipt bytes valid while mutating one fetched evidence file body; the smoke requires rejection before later evidence files, adapter-family receipt, adapter manifests, or stack adapter bytes are requested. ## Binary Formats The tiny test models use the same `.slm` v1 format with hidden size 8, one layer, two heads, head dimension 4, ffn size 16, and context 16. The byte-tokenizer f32/q8_0/q4_0 tiny fixtures use vocab 260 and must generate the same deterministic output. The tied-output tiny fixture also uses vocab 260, omits `output.weight`, and must generate through the `tok_embeddings.weight` projection route only because the v1 tied-output flag is set. The BPE tiny fixture uses vocab 262 and must prove prompt `the` merges into token `261` before generation. The TinyLM-16M f32, q8_0, and q4_0 smoke models use hidden size 512, four layers, eight heads, ffn size 2048, and context 512. ## Failure Cases Malformed headers, malformed tokenizer sections, BPE vocab/header drift, BPE merge outputs missing from the token table, BPE source tokenizer/shape disagreement, BPE source merge ids outside vocabulary, zero checksums, checksum mismatches, runtime WASM manifest drift, source checksum drift, source path traversal, non-finite source weights, source weight values outside the accepted range, tied source manifests that retain `output.weight`, tied-output/model-shape disagreement, untied source manifests that omit `output.weight`, zero-case eval files, undeclared eval-case keys, empty exact-case prompts or outputs, manifest checksum mismatches, manifest trained-quality overclaims, blend parent checksum drift, blend candidate byte drift, invalid blend weights, task-delta parent checksum drift, task-delta candidate byte drift, invalid task-delta weights, sparse task-delta candidate byte drift, invalid sparse delta weights, invalid sparse keep rates, crossover parent checksum drift, crossover candidate byte drift, invalid crossover seeds, invalid crossover keep rates, mutation parent checksum drift, mutation candidate byte drift, invalid mutation seeds, invalid mutation rates, invalid mutation magnitudes, adapter parent checksum drift, adapter byte drift, adapter manifest drift, adapter-fuse manifest drift, adapter-fused candidate byte drift, runtime adapter identity drift, runtime adapter checksum drift, runtime adapter non-finite deltas, runtime adapter fused-value overflow, q8/q4 adapter identity drift, runtime-smoke sidecar manifest drift, admission record evidence drift, promotion ledger entry drift, duplicate ledger candidates, duplicate ledger candidate checksums, selector registry entry drift, selector id mismatch, duplicate registry candidates, unserved registry model paths, pending quality eval templates, smoke-model assistant-quality claims, converted-trained assistant-quality claims without eval evidence or quality scope, assistant-quality sidecars without case totals, assistant-quality sidecars with mismatched per-case text, missing tensors, wrong dimensions, invalid tokenizer ids, generated decoded text above the 64 KiB result cap, invalid UTF-8 prompt bytes, null prompt pointers, zero prompt lengths, zero generation lengths, context overflow, and unloaded generation must fail with explicit error codes. Population-review, parent-pool-recipe, sign-merge, multi-parent candidate, multi-parent promotion, and multi-parent admission cases must also reject ledger drift, admission drift, objective-vector field drift, mixed direct-parameter contracts, parent relatedness checksum drift, parent order drift, parent checksum drift, candidate byte drift, receipt drift, manifest drift, promotion drift, runtime-smoke drift, eval drift, and overbroad route claims. ## Validation Rules Each parser test must provide concrete bytes, including checksum-bearing valid headers and deliberate checksum mismatches. Tokenizer tests must cover byte round trip, BPE ranked merge/decode behavior, and bounded decode failures that preserve the previous output string. Native validator tests must accept a generated fixture, accept a BPE tokenizer section when the model header vocab matches, reject BPE vocab drift, accept the checked-in tied-output fixture without `output.weight`, reject the same missing-output condition without the tied flag, and reject non-finite f32 payload values. Parent compatibility tests must accept matching parent layouts, reject q8_0/q4_0 direct-parameter pairs through quantization and tensor layout mismatch, reject tokenizer and shape mismatch, and reject output-head contract mismatch. Candidate lineage tests must write and validate a template from a passing compatibility report, reject failed compatibility reports, reject compatibility checksum drift, reject copied parent-field drift, and reject invalid candidate ids. Blend operator tests must write and validate weighted f32 and q8 candidates, prove receipt recomputation, reject parent checksum drift, reject candidate byte drift, and reject invalid blend weights. Task-delta operator tests must write and validate weighted f32 and q8 candidates, prove receipt recomputation for `base + weight * (target - base)`, reject parent checksum drift, reject candidate byte drift, and reject invalid signed task-delta weights. Sparse task-delta tests must write and validate f32 and q8 candidates, prove keep-all matches the target values, prove keep-zero preserves the base values, prove partial keep selects some deltas while preserving other base entries, reject candidate byte drift, and reject invalid sparse weights or keep rates. Crossover operator tests must write and validate seeded f32 and q8 candidates, prove seed changes alter candidate bytes and mask checksum, prove keep-zero selects parent 1, prove keep-all selects parent 0, reject parent checksum drift, reject candidate byte drift, and reject invalid seeds or keep rates. Mutation operator tests must write and validate seeded f32 and q8 candidates, prove seed, rate, magnitude, and reference-parent scale affect output or receipt fields, prove rate-zero and magnitude-zero boundaries preserve base values, reject parent checksum drift, reject candidate byte drift, and reject invalid seeds, rates, or magnitudes. Adapter-delta tests must write and validate f32 and q8 raw ADP1 task-delta packages, sparse ASP1 task-delta packages, and low-rank ALR1 task-delta packages, prove package and manifest recomputation, reject parent checksum drift, reject adapter byte drift, and reject adapter manifest drift. Trained adapter source tests must write and validate low-rank factor source fixtures, verify tied-output source shape handling, reject factor checksum drift, reject factor path escape, and reject non-finite factor payloads after checksum refresh. Adapter-fuse tests must fuse f32 and q8 raw adapter packages into normal `.slm` candidates, prove candidate and receipt recomputation, reject adapter manifest drift, and reject fused candidate byte drift. Runtime adapter tests must apply f32, q8_0, and q4_0 `ADP1` packages, sparse `ASP1` packages, and low-rank `ALR1` packages to loaded models, prove tensor mutation or compact zero-delta preservation, prove q8_0/q4_0 models remain compact after re-quantization, reject identity drift without mutation, reject checksum and non-finite payload drift, and prove `Runtime::apply_adapter_delta` resets generation diagnostics after success. Candidate artifact tests must write and validate a manifest from compatibility, lineage, and a candidate `.slm`, reject parent-contract mismatch, reject lineage checksum drift, reject candidate artifact drift, and reject manifest field drift. Candidate promotion tests must write and validate a promotion template, reject candidate manifest checksum drift, reject candidate artifact drift, reject promotion overclaims, and reject invalid promoter ids. Runtime-smoke sidecar tests must round-trip the sidecar and reject manifest drift. Selector admission tests must write and validate an admission record, reject runtime-smoke drift, reject eval sidecar drift, reject public-claim overreach, reject incomplete case totals, and reject invalid selector ids. Promotion ledger tests must write and validate a ledger from admission records, reject empty input, reject duplicate candidate ids, reject duplicate candidate checksums, reject entry drift, and reject unexpected ledger keys. Selector registry tests must write and validate a registry from admission records, reject empty input, reject selector id mismatch, reject duplicate candidates, reject unserved candidate paths, and reject registry entry drift. Runtime BPE tests must load the checked-in tiny BPE `.slm`, generate from prompt `the`, assert diagnostics show merged token output `256,261` with f32 quantization, and prove stochastic top_k 262 passes the fixed 1024-candidate sampler cap. Runtime tied-output tests must load the checked-in tiny tied-output `.slm` and generate locally through the token-embedding output projection path. Runtime output-buffer tests must prove `OutputBufferExceeded` writes the readable result message, clears token and generated-token state for full generation failures, and resets generated-count diagnostics to zero. Trained-source tests must validate a generated source fixture, convert it to f32, q8_0, and q4_0 `.slm` artifacts, reject source checksum drift, reject unsafe source paths, and reject non-finite source weights even when the source checksum is refreshed. BPE trained-source tests must generate `tiny-fixture-bpe`, verify `tokenizer=bpe-v1`, verify BPE token/merge records, convert the source into a q8_0 `.slm`, verify the output carries a `BPE1` tokenizer section, validate its converted-trained manifest, and reject BPE tokenizer/shape or merge-id drift. Tied trained-source tests must generate `tiny-fixture-tied`, verify `tied_output=true`, verify `tensor_count=11`, verify `output.weight` is absent, convert the source to f32, q8_0, and q4_0, verify each converted `.slm` carries the v1 tied-output flag, and validate every converted manifest. Eval-runner tests must parse valid exact cases, reject unsupported match modes, reject zero-case files, reject stray case keys outside the declared count, and the CLI smoke must produce an eval sidecar that passes assistant-quality only for the fixture scope. Manifest tests must round-trip generated fixture provenance, reject checksum drift, and reject trained-quality overclaims. Quality-gate tests must allow runtime-smoke evidence, reject deterministic-smoke assistant-quality claims, reject converted-trained assistant-quality claims without eval evidence, reject pending eval templates, reject passed eval sidecars that omit case evidence, reject sidecars with mismatched per-case actual text, and allow converted-trained artifacts only when the task-eval sidecar passes with a quality scope, positive case count, all cases passed, zero failed cases, and exact per-case matches. Model routing tests must prove loaded models expose pre-resolved tensor indices and tied-output projection flags route the output projection to token embeddings. The Rust mini browser harness must prove the optional selector registry path is local, checks for `admitted-records-only`, and keeps the checked-in smoke routes intact when no registry is present. Each math test must compare against known vectors with tight tolerances, and direct core-op tests must cover dot, matvec, matmul, RMSNorm, softmax, SiLU, SwiGLU, and shape or length rejection paths. Unit generation tests must use the tiny fixtures, not TinyLM-16M. Runtime smoke tests may load `tinylm16-f32.slm`, `tinylm16-q8.slm`, and `tinylm16-q4.slm` outside unit tests. Runtime tests must assert diagnostics show the loaded quantization mode for q8_0, q4_0, BPE, tied-output, and post-adapter f32/q8_0/q4_0 fixtures. Diagnostics tests must prove handwritten JSON escapes quotes, backslashes, control characters, line separators, and paragraph separators before browser parsing. Sparse receipt tests must also prove the implicit mask metadata is stable and useful: density and mask checksum fields change when the selected top-k positions change. Trained adapter source ALR1 tests must also prove `convert-adapter-source` and `validate-converted-adapter-source` rebuild the same package and manifest from source factors plus base `.slm` identity. Population-review tests must recompute ranking, frontier selection, weighted objective-vector metadata, and per-entry objective-vector checksums from ledger plus admissions; parent-pool recipe tests must recompute shared contract fields, seed weights, relatedness metric/scope/pair count/status, shared relatedness checksum, and per-parent relatedness group fields. Sign-merge tests must write and validate receipt text, accept path-preserving parent fixtures, echo recipe relatedness fields, reject single-parent recipes, reject parent order or checksum drift, and reject candidate byte drift. Multi-parent candidate manifest tests must write and validate text and path manifests, bind the sign-merge receipt checksum plus relatedness and candidate fields, reject receipt drift, reject manifest drift, and reject candidate byte drift. Multi-parent promotion tests must write and validate text and path templates, bind candidate manifest checksum, operator receipt checksum, recipe checksum, parent count, and candidate `.slm` fields, then reject manifest drift, promotion drift, and candidate byte drift. Multi-parent admission tests must write and validate text and path records, bind the promotion template, provenance manifest, runtime-smoke sidecar, eval sidecar, eval-case evidence checksum, candidate fields, parent-pool evidence checksums, and selector-route next gate, then reject runtime-smoke drift, eval drift, route overclaim, and incomplete case totals. Selector registry tests must validate multi-parent admission records, mixed selector plus multi-parent admission registries, `entry.N.eval_case_evidence_checksum`, `entry.N.genome_id`, `entry.N.genome_lineage_checksum`, `entry.N.species_id`, `entry.N.species_fit_checksum`, `entry.N.novelty_id`, `entry.N.novelty_checksum`, `entry.N.population_id`, `entry.N.population_checksum`, `entry.N.mate_selection_id`, `entry.N.mate_selection_parent_count`, `entry.N.mate_selection_checksum`, `entry.N.phenotype_evidence_id`, `entry.N.phenotype_evidence_checksum`, `entry.N.provenance_manifest_checksum`, `entry.N.fitness_vector_checksum`, f32/q8_0/q4_0 adapter route fields, indexed adapter-family fields, stack metadata fields, module-plan resource fields, module-plan fetch policy, module-plan fetch-count limit, module-plan context token limit, module-plan byte-count, checksum, role, slot, phase, and dependency fields, duplicate adapter-route rejection, apply-status-to-quantization matching, and unsupported admission-version rejection before browser selector intake. Browser bundle tests must write the app shell, WASM runtime, runtime WASM manifest, quantization-selected `multi-parent-sign-merge-f32`, `multi-parent-sign-merge-q8`, or `multi-parent-sign-merge-q4` `.slm` files, manifests, evidence sidecars, self ADP1, family ADP1, sparse ASP1, and source-backed low-rank ALR1 packages, their manifests, selector genome/species/novelty/population/mate-selection/phenotype/fitness fields, module-plan resource receipts with context token limit, fetch policy, fetch-count limit, byte counts, checksums, roles, assembly slots, phases, and dependencies, assembly receipts with eval-case checksums, adapter-family receipts, stack fields, and `models/selector.registry`; browser smoke must then load the served files with `multi-parent-registry-file`, verify the generated module-plan request and rendered Module Plan panel fields with `adapter-sidecar-registry-file`, auto-apply the registry-supplied family ADP1 plus sparse ASP1 plus source-backed low-rank ALR1 stack for generated f32/q8_0/q4_0 roots, verify registry-backed provenance genome, species, novelty, population, mate-selection, phenotype, fitness, eval cases, and eval checksum, run `assembly-eval-case-drift` when assembly digest matching changes, and apply an intercepted q8_0 registry sidecar with `adapter-sidecar-registry-q8`. Module-plan origin policy browser smoke must run `module-plan-origin-policy-drift` when generated selector origin fields, receipt origin validation, Module Plan `Origin` rendering, or same-origin browser assembly routes change. Fetched assembly evidence browser smoke must run `assembly-evidence-file-drift` when evidence-file integrity or `verifyAssemblyEvidenceFiles` changes, proving a single served evidence body drift stops startup before later evidence, adapter-family, adapter manifest, or stack artifact routes. Adapter-family receipt browser smoke must run `adapter-family-receipt-drift` when `loadAdapterFamilyReceipt`, adapter-family receipt text checks, or post-evidence auto-assembly sequencing changes, proving receipt byte drift stops before adapter manifests or stack artifacts while the accepted model remains loaded. Adapter manifest browser smoke must run `adapter-manifest-drift` when `validateAdapterManifest`, adapter manifest checksum checks, or post-receipt auto-assembly sequencing changes, proving same-byte manifest drift stops before later manifests or stack artifacts while the accepted model remains loaded. Adapter artifact browser smoke must run `adapter-artifact-drift` when adapter artifact checksum checks, fetched stack artifact byte transfer, or post-manifest auto-assembly sequencing changes, proving artifact byte drift stops before later stack artifacts or `apply_adapter_delta` while the accepted model remains loaded. Adapter stack preflight browser smoke must run `adapter-stack-prefetch-drift` when auto-applied stack artifact fetch order or pre-WASM transfer changes, proving later stack drift cannot leave an earlier adapter already applied. Adapter stack Rust validation browser smoke must run `adapter-stack-rust-validate-drift` when generated auto-stack semantic validation, checksum echo routing, or validation failure state changes, proving browser-valid stack bytes still stop at Rust validation before mutation. Adapter-family browser smoke must show the generated self ADP1, family ADP1, sparse ASP1, and low-rank ALR1 adapter labels, render the verified Module Plan panel including fetch limit, tokenizer, sampler cap, context, prompt limit, output limit, byte, checksum, slot, role, phase, and dependency summaries, request the receipt-declared family ADP1, sparse ASP1, and low-rank ALR1 stack routes, receive three pre-generation `apply_adapter_delta` calls plus `adapter_stack_applied(3)`, verify Rust diagnostics report `adapter_apply_count=3` with nonzero `last_adapter_checksum` and `assembly_state_checksum`, and verify f32/q8_0/q4_0 generation diagnostics are cleared before generation. `module-plan-context-token-drift` must pass when selector context-token binding or receipt validation changes, `module-plan-tokenizer-drift` must pass when selector tokenizer checksum binding or receipt validation changes, `module-plan-sampler-cap-drift` must pass when sampler-cap binding or receipt validation changes, `module-plan-fetch-count-drift` must pass when generated self-assembly route-count limits change, `module-plan-prompt-limit-drift` must pass when prompt transfer caps or receipt validation changes, source-root `prompt-limit` must pass when browser prompt-copy behavior changes, and `module-plan-output-limit-drift` must pass when generated-output caps or receipt validation changes. Public Rust API documentation is an acceptance gate. Run `cargo rustdoc -p tinyrustlm-runtime --lib -- -D missing_docs` and matching `cargo rustdoc --bin ... -- -D missing_docs` checks for `tinyrustlm-slm-pack`, `tinyrustlm-local-server`, and `tinyrustlm-browser-harness` before claiming public function documentation is complete. ## Future Expansion Path After unit tests pass, `tools/wasm-abi-smoke.js` loads the generated WASM and local q8_0 `.slm` file, sends invalid UTF-8 bytes and bad ABI arguments through `generate`, rejects invalid sampling config through `set_sampling_config`, restores greedy defaults, checks explicit error diagnostics, verifies valid generation still recovers, steps one more token through `generate_next_token`, reloads the tiny f32 fixture, validates a zero-delta `ADP1` package through `validate_adapter_delta`, applies the same package through `apply_adapter_delta`, verifies runtime assembly diagnostics increment and carry nonzero adapter/assembly checksums, then frees the model and verifies later generation returns `ModelNotLoaded` with assembly state cleared. The Rust mini browser harness checks the static app tree for required UI ids, local-only markers, WASM boundary markers, runtime WASM manifest route and fields, adapter stack and module-plan strategy markers, Rust WASM export definitions, local model routes, local adapter routes, manifest sidecars, trained-quality non-claims, provenance eval case fields, and optional loopback content types. The Rust local server is checked directly with loopback HTTP probes for the app, WASM, runtime manifest, model, and manifest routes. `tools/browser-smoke.js` exercises the static app with a local server and the generated WASM file. Single-model mode checks one generate action plus User/TinyRustLM transcript entries and the runtime manifest request; `runtime-manifest-drift` mode serves a valid-shaped runtime manifest with a mismatched checksum, proves boot stops before any model route is requested, and leaves runtime controls disabled. `step-token` mode checks disabled-before-context Step Token state, generate `e`, Step Token appends a second `e`, transcript continuation, console output, diagnostics, benchmark generated count, and local-only requests. `adapter-sidecar` mode switches to the selected tiny f32/q8_0/q4_0 fixture, generates one token, clicks Apply Adapter for the matching zero-delta `ADP1` sidecar, then verifies `adapter applied`, matching quantization diagnostics, cleared token/KV state, `adapter_apply_count=1`, nonzero adapter and assembly checksums, and local-only requests. `adapter-sidecar-registry-q8` mode serves a registry entry for the tiny q8_0 fixture with a matching quantized adapter apply status and eval-case checksum, then verifies the registry-supplied q8_0 sidecar reaches Rust and clears diagnostics. `adapter-sidecar-checksum-mismatch` mode serves a corrupted local ADP1 response and verifies the browser rejects it before calling `apply_adapter_delta` while preserving prior generation diagnostics. `multi-parent-registry` mode serves a local `models/selector.registry` fixture for `multi-parent-sign-merge-q8`, proves the selector contains only that registry option, loads the mapped q8_0 model through `../models/tinylm16-q8.slm`, renders registry-backed eval case proof, and keeps all requests on the loopback app origin. `multi-parent-registry-file` mode uses a `browser-multi-parent-bundle` root and proves the selected generated f32/q8_0/q4_0 entry loads from served `selector.registry`, `.module-plan.receipt`, `.slm`, `.slm.manifest`, assembly receipt, and evidence files. `adapter-sidecar-registry-file` mode uses that generated root, displays the registry-supplied adapter options and provenance eval checksum, requires the module-plan request before generated model load, verifies visible Module Plan fetch-limit, model/adapter/stack/scratch/output/KV/total budget rows plus ordered byte, checksum, slot, role, phase, dependency, and trace summaries, fetches the receipt-declared family ADP1 plus sparse ASP1 plus low-rank ALR1 stack, verifies Rust validates all three packages before any apply, and verifies Rust applies all three packages before generation while preserving the selected quantization mode and reporting assembly count/checksums. `combined-selector-assembly` mode uses a generated `all` root, confirms the q4_0 default, then switches through q4_0, q8_0, and f32 generated entries while checking each module-plan route precedes model bytes, each stack validates and auto-applies before generation, each runtime diagnostics payload reports `adapter_apply_count=3`, and each registry-backed entry displays the same eval-case checksum. `combined-selector-cycle` mode uses the same generated `all` root shape, repeats q4_0/q8_0/f32 switching for the requested cycle count, and requires each pass to add fresh Rust validation, apply, stack completion, reset diagnostics, runtime assembly diagnostics, and one-token generation evidence. `assembly-eval-case-drift` mode keeps selector, module-plan, and assembly receipt checksums internally aligned while changing the assembly eval-case digest, then proves evidence and adapter-family routes are not requested. `module-plan-fetch-policy-drift` mode keeps the drifted receipt checksum consistent, changes `module_plan_fetch_policy`, and proves the browser stops before the generated `.slm`, adapter-family, adapter-manifest, or stack artifact routes. `module-plan-fetch-count-drift` mode keeps the drifted receipt checksum consistent, changes `module_plan_fetch_count_limit`, and proves the browser stops before the generated `.slm`, adapter-family, adapter-manifest, or stack artifact routes. `module-plan-resource-drift` mode keeps the drifted receipt checksum consistent, changes the receipt adapter byte budget, and proves the browser stops before the generated `.slm` route. `module-plan-output-limit-drift` mode keeps the drifted receipt checksum consistent, changes `module_plan_output_byte_limit`, and proves the browser stops at module-plan validation. `module-plan-adapter-stack-budget-drift` mode keeps the drifted receipt checksum consistent, changes the exact stack payload budget, and proves the browser stops before generated model bytes, adapter-family receipt, adapter manifests, or stack artifact routes. `module-plan-count-drift` mode keeps the drifted receipt checksum consistent, changes receipt `module_count`, and proves the browser stops before the generated `.slm`, adapter-family, adapter-manifest, or stack artifact routes. `module-plan-graph-drift` mode keeps the drifted receipt checksum consistent, changes the receipt `module.0.path`, and proves the browser stops before the generated `.slm` route. `module-plan-stack-drift` mode keeps the drifted receipt checksum consistent, changes the receipt `module.4.adapter_path`, and proves the browser stops before the generated `.slm`, stack adapter, and stack adapter manifest routes. `module-plan-role-drift` mode keeps the drifted receipt checksum consistent, changes the receipt `module.4.role`, and proves the browser stops before the generated `.slm`, stack adapter, and stack adapter manifest routes. `module-plan-slot-drift` mode keeps the drifted receipt checksum consistent, changes the receipt `module.4.assembly_slot`, and proves the browser stops before the generated `.slm`, stack adapter, and stack adapter manifest routes. `module-plan-phase-drift` mode keeps the drifted receipt checksum consistent, changes the receipt `module.4.phase`, and proves the browser stops before the generated `.slm`, stack adapter, and stack adapter manifest routes. `module-plan-byte-drift` mode keeps the drifted receipt checksum consistent, changes the receipt `module.0.byte_count`, and proves the browser stops before the generated `.slm`, stack adapter, and stack adapter manifest routes. `module-plan-checksum-drift` mode keeps the drifted receipt checksum consistent, changes the receipt `module.4.checksum`, and proves the browser stops before the generated `.slm`, stack adapter, and stack adapter manifest routes. `module-plan-dependency-drift` mode keeps the drifted receipt checksum consistent, changes the receipt `module.4.depends_on`, and proves the browser stops before the generated `.slm`, stack adapter, and stack adapter manifest routes. `loop` mode reloads, runs q8 generation twice around reset, switches to q4, repeats generation and reset, and fails if a non-local HTTP origin is requested. `ui-audit` mode loads fresh desktop and mobile viewports, checks the product shell, footer identity, local-only notice, required panels, model controls, decoding controls, diagnostics/developer mirror, benchmark fields, Module Plan fallback budget, fetch limit, output limit, byte, checksum, slot, role, phase, dependency, and trace rows, Model Provenance fallback eval proof fields, empty/generated/cleared transcript state, Step Token state, Clear-button state, response preservation after Clear, layout overflow, generated output, default greedy sampling diagnostics, and local-only requests. `model-error` mode intercepts the local q8 model with invalid bytes and requires `invalid model magic` UI rendering plus recoverable model selection. `context-error` mode submits an over-context prompt and requires `context exceeded` UI rendering. `missing-model` mode returns a local 404 for the q8 model and requires readable fetch-error UI plus recoverable model selection. `endurance` mode repeats q8/q4 ready, generate, and reset cycles. `performance` mode runs multi-token q8/q4 generation and verifies benchmark prompt tokens, generated tokens, token speed, scratch bytes, quantization mode, reset recovery, and local-only requests. `performance-soak` mode repeats multi-token q8/q4 generation across cycles and requires every cycle to preserve benchmark fields, KV length, reset recovery, deterministic output, and local-only requests. Browser-owned Module Plan actual-checksum changes are covered by source-root `ui-audit`, generated-root `combined-selector-assembly`, and generated-root `adapter-sidecar-registry-file`. The generated smokes require `Actual Module Checksums` to equal the declared checksum summary after accepted model, manifest, assembly receipt, adapter-family receipt, and ADP1/ASP1/ALR1 stack payloads are observed. `module-plan-payload-checksum-drift` coherently rewrites the family ADP1 payload checksum through its manifest, adapter-family receipt, assembly receipt, selector registry, and module-plan receipt while leaving the module checksum row stale, then proves the browser stops after selector plus module-plan receipt and before generated model, assembly, adapter-family, manifest, or stack routes. For selector reuse changes, `combined-selector-cycle` specifically checks that `free_model(previous -> next) -> 0` appears once per post-initial pass and before the first `validate_adapter_delta` for the next assembled entry. For longer selector-route exercises, `combined-selector-route-soak`, `combined-selector-route-extended-soak`, and `combined-selector-route-stress-soak` specifically check repeated route counts for module plans, models, manifests, assembly receipts, evidence files, adapter-family receipts, adapter manifests, and stack artifacts. `module-plan-operator-receipt-drift` keeps the drifted module-plan receipt checksum consistent with the selector registry while changing `operator_receipt_checksum`, then proves the browser stops after the selector registry plus module-plan receipt and before generated model bytes, assembly evidence, adapter-family receipt, adapter manifests, or stack artifacts. `assembly-evidence-file-drift` mode leaves selector, module-plan, model, manifest, and assembly receipt bytes valid while changing one fetched evidence file body, then proves later evidence files, adapter-family routes, adapter manifests, and stack artifacts are not requested. `adapter-family-receipt-drift` mode leaves selector, module-plan, model, manifest, assembly receipt, and all evidence files valid while changing the adapter-family receipt text at the same byte length, then proves adapter manifests and stack artifacts are not requested. `adapter-manifest-drift` mode leaves that receipt chain valid while changing the family ADP1 manifest text at the same byte length, then proves later adapter manifests and stack artifacts are not requested. `adapter-artifact-drift` mode leaves manifests valid while changing the first family ADP1 artifact bytes, then proves sparse and low-rank artifacts are not requested and Rust adapter apply is not called. `adapter-stack-prefetch-drift` mode leaves manifests valid while changing the second sparse ASP1 artifact bytes, then proves family ADP1 and sparse ASP1 are fetched for preflight, low-rank ALR1 is not fetched, and Rust adapter apply is not called. `adapter-stack-rust-validate-drift` mode leaves selector, module-plan, assembly, adapter-family, manifest, and artifact checksums aligned while drifting family ADP1 identity, then proves all stack artifacts are fetched, `validate_adapter_delta` returns `shape mismatch`, and `apply_adapter_delta` is not called. ================================================================================ END FILE: tinyrustlm/docs/testing.md ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/docs/tokenizer.md BYTES: 3421 SHA256: B133955180A0AF4F260C81F6438E1C586A27A4863068AD4B6E82C32DCB14D18F ================================================================================ # Tokenizer ## Purpose The tokenizer layer proves prompt transfer and generation plumbing without external tokenizer libraries. Phase one uses a fixed byte tokenizer. Phase two adds a small custom BPE tokenizer section that is parsed from `.slm` bytes and selected during model load. ## Constraints No tokenizers crate, SentencePiece, Hugging Face tokenizer JSON, or external vocabulary files are used. Tokenizer metadata must live inside the `.slm` tokenizer section and be validated before runtime use. ## Data Structures `Tokenizer` is the runtime enum selected from the loaded model section. `ByteTokenizer` maps bytes `0..255` directly to token ids. `BOS = 256`, `EOS = 257`, `PAD = 258`, and `UNK = 259`. `CustomBpeTokenizer` stores a token table and a ranked merge table. Encoding begins with byte fallback tokens, repeatedly applies the lowest-rank available adjacent merge, then wraps the result with BOS and EOS. Decoding uses byte fallback for ids `0..255` and token-table bytes for merged ids. ## Binary Formats The phase-one tokenizer section uses `BTOK` magic, version `1`, declared vocab size `260`, and the four special token ids. The phase-two tokenizer section uses `BPE1` magic, version `1`, vocab size, four special token ids, token count, merge count, a variable token table, and fixed merge entries. Each token table entry stores `token_id`, byte length, and raw token bytes. Each merge entry stores `left`, `right`, `output`, and `rank`. ## Failure Cases Decode rejects unknown ids outside the selected tokenizer vocabulary. Encode rejects impossible oversized prompts. BPE section parsing rejects short sections, unsupported versions, vocab/header drift, duplicate token ids, empty token bytes, out-of-vocabulary merge ids, merge outputs missing from the token table, and trailing bytes. ## Validation Rules Encoding adds BOS and EOS. Decoding ignores BOS, EOS, and PAD, emits `?` for UNK, and validates the resulting bytes as UTF-8. The native `.slm` admission validator accepts both `BTOK` and `BPE1`. For BPE, the tokenizer vocab must match the model header, every token id must be unique and inside the vocabulary, and every merge output must reference a token table entry. The trained-source validator also accepts `tokenizer=bpe-v1` for BPE source shapes. Source manifests must declare BPE token and merge counts, token ids, token bytes as hex, merge ids, and ranks; conversion serializes that metadata into the `.slm` `BPE1` section before native admission validation runs. ## Current Runtime Proof The checked-in `tiny-test-model-bpe.slm` fixture uses the `BPE1` section with a two-step merge table: `t` + `h` becomes token `260`, then token `260` + `e` becomes token `261`. Runtime generation for prompt `the` records tokenizer output `256,261`, proving the loaded `.slm` selected the custom BPE path and merged the body token before generation. The trained-source tests also generate and convert a `tiny-fixture-bpe` source bundle into a q8_0 `.slm`, proving source tokenizer metadata survives conversion into the binary artifact. ## Future Expansion Path Current BPE support is end-to-end for a deterministic tiny fixture and for a converted source fixture. Future trained models can provide larger token and merge tables in the same `BPE1` layout, then add tests for real tokenizer corpora, normalization policy, and compatibility with trained model quality gates. ================================================================================ END FILE: tinyrustlm/docs/tokenizer.md ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/models/README.md BYTES: 37451 SHA256: 58B136954E3227CB9B15801DF742EE36511F44A505F65B4FA148001F8B26EAA8 ================================================================================ # TinyRustLM Models Static local `.slm` files belong here. Generate the local model artifacts with: ```powershell cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tiny-test-model.slm tiny-fixture cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tiny-test-model-q8.slm tiny-fixture-q8 cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tiny-test-model-q4.slm tiny-fixture-q4 cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tiny-test-model-bpe.slm tiny-fixture-bpe cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tiny-test-model-tied.slm tiny-fixture-tied cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tinylm16-f32.slm tinylm16-f32 cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tinylm16-q8.slm tinylm16-q8 cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tinylm16-q4.slm tinylm16-q4 ``` The packer writes checksum-bearing `.slm` files. Runtime loading rejects zero or mismatched checksums before tensor decoding, so regenerate the artifacts after any format, tensor writer, or checksum change. Validate any generated or converted `.slm` file before serving it: ```powershell cargo run -p tinyrustlm-slm-pack -- validate .\tinyrustlm\models\tinylm16-q8.slm cargo run -p tinyrustlm-slm-pack -- validate-manifest .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm.manifest ``` The validator checks the model header, tokenizer metadata, checksum, required tensor names and shapes, dtype-specific byte lengths, finite f32 payload values, and quantization scale ranges. It is an admission gate for model artifacts, not a trained-quality benchmark. Write a parent compatibility report before using two `.slm` files as a future assembly or model-breeding parent set: ```powershell cargo run -p tinyrustlm-slm-pack -- compatibility .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-self.compat cargo run -p tinyrustlm-slm-pack -- compatibility .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q4.slm cargo run -p tinyrustlm-slm-pack -- lineage-template .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage tinylm16-q8-self-candidate identity-parent-set browser-local-16m-budget cargo run -p tinyrustlm-slm-pack -- validate-lineage .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage cargo run -p tinyrustlm-slm-pack -- blend-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.operator cargo run -p tinyrustlm-slm-pack -- validate-blend-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.operator cargo run -p tinyrustlm-slm-pack -- delta-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-delta.slm .\target\model-breeding\tinylm16-q8-delta.operator 1000000 cargo run -p tinyrustlm-slm-pack -- validate-delta-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-delta.slm .\target\model-breeding\tinylm16-q8-delta.operator cargo run -p tinyrustlm-slm-pack -- sparse-delta-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-sparse-delta.slm .\target\model-breeding\tinylm16-q8-sparse-delta.operator 1000000 250000 cargo run -p tinyrustlm-slm-pack -- validate-sparse-delta-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-sparse-delta.slm .\target\model-breeding\tinylm16-q8-sparse-delta.operator cargo run -p tinyrustlm-slm-pack -- prune-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-prune.slm .\target\model-breeding\tinylm16-q8-prune.operator 750000 0 cargo run -p tinyrustlm-slm-pack -- validate-prune-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-prune.slm .\target\model-breeding\tinylm16-q8-prune.operator cargo run -p tinyrustlm-slm-pack -- federated-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-federated.slm .\target\model-breeding\tinylm16-q8-federated.operator 500000 cargo run -p tinyrustlm-slm-pack -- validate-federated-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-federated.slm .\target\model-breeding\tinylm16-q8-federated.operator cargo run -p tinyrustlm-slm-pack -- adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.delta .\target\model-breeding\tinylm16-q8.adapter.delta.manifest cargo run -p tinyrustlm-slm-pack -- validate-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.delta .\target\model-breeding\tinylm16-q8.adapter.delta.manifest cargo run -p tinyrustlm-slm-pack -- fuse-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.delta .\target\model-breeding\tinylm16-q8.adapter.delta.manifest .\target\model-breeding\tinylm16-q8-adapter-fused.slm .\target\model-breeding\tinylm16-q8-adapter-fuse.operator cargo run -p tinyrustlm-slm-pack -- validate-fuse-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.delta .\target\model-breeding\tinylm16-q8.adapter.delta.manifest .\target\model-breeding\tinylm16-q8-adapter-fused.slm .\target\model-breeding\tinylm16-q8-adapter-fuse.operator cargo run -p tinyrustlm-slm-pack -- sign-merge-candidate .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- validate-sign-merge-candidate .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- soup-candidate .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-soup.slm .\target\model-breeding\parent-pool-soup.operator --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- validate-soup-candidate .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-soup.slm .\target\model-breeding\parent-pool-soup.operator --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- multi-parent-candidate-manifest .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- validate-multi-parent-candidate .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- multi-parent-promotion-template .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate .\target\model-breeding\parent-pool-sign-merge.promotion --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- validate-multi-parent-promotion .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate .\target\model-breeding\parent-pool-sign-merge.promotion --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- multi-parent-admission-record .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate .\target\model-breeding\parent-pool-sign-merge.promotion .\target\model-breeding\parent-pool-sign-merge.slm.manifest .\target\model-breeding\parent-pool-sign-merge.runtime .\target\model-breeding\parent-pool-sign-merge.eval .\target\model-breeding\parent-pool-sign-merge.multi.admission --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- validate-multi-parent-admission .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate .\target\model-breeding\parent-pool-sign-merge.promotion .\target\model-breeding\parent-pool-sign-merge.slm.manifest .\target\model-breeding\parent-pool-sign-merge.runtime .\target\model-breeding\parent-pool-sign-merge.eval .\target\model-breeding\parent-pool-sign-merge.multi.admission --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- candidate-manifest .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-self.candidate cargo run -p tinyrustlm-slm-pack -- validate-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-self.candidate cargo run -p tinyrustlm-slm-pack -- promotion-template .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-self.candidate .\target\model-breeding\tinylm16-q8-self.promotion local-smoke-runner browser-local-runtime-smoke-and-eval cargo run -p tinyrustlm-slm-pack -- validate-promotion .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-self.candidate .\target\model-breeding\tinylm16-q8-self.promotion cargo run -p tinyrustlm-slm-pack -- manifest .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.slm.manifest deterministic-smoke cargo run -p tinyrustlm-slm-pack -- runtime-smoke .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.slm.manifest .\target\model-breeding\tinylm16-q8-blend.runtime cargo run -p tinyrustlm-slm-pack -- validate-runtime-smoke .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.slm.manifest .\target\model-breeding\tinylm16-q8-blend.runtime ``` The report records each parent checksum, model shape, tokenizer checksum, tensor layout checksum, quantization label, and output-head contract. Direct-parameter parent sets pass only when those contracts match exactly; q8_0 and q4_0 artifacts with the same shape remain separate lanes until a future source-conversion or distillation route writes a new admitted candidate. The checked browser adapter sidecars are `tiny-test-model-self.adp1`, `tiny-test-model-q8-self.adp1`, and `tiny-test-model-q4-self.adp1`, generated from each tiny fixture against itself so they are zero-delta ADP1 packages for the browser-local adapter route: ```powershell cargo run -p tinyrustlm-slm-pack -- compatibility .\tinyrustlm\models\tiny-test-model.slm .\tinyrustlm\models\tiny-test-model.slm .\target\model-breeding\tiny-f32-self.compat cargo run -p tinyrustlm-slm-pack -- lineage-template .\target\model-breeding\tiny-f32-self.compat .\target\model-breeding\tiny-f32-self-adapter.lineage tiny-f32-self-adapter adapter-delta-v1 tiny-f32-self cargo run -p tinyrustlm-slm-pack -- adapter-delta .\target\model-breeding\tiny-f32-self.compat .\target\model-breeding\tiny-f32-self-adapter.lineage .\tinyrustlm\models\tiny-test-model.slm .\tinyrustlm\models\tiny-test-model.slm .\tinyrustlm\models\tiny-test-model-self.adp1 .\tinyrustlm\models\tiny-test-model-self.adp1.manifest cargo run -p tinyrustlm-slm-pack -- validate-adapter-delta .\target\model-breeding\tiny-f32-self.compat .\target\model-breeding\tiny-f32-self-adapter.lineage .\tinyrustlm\models\tiny-test-model.slm .\tinyrustlm\models\tiny-test-model.slm .\tinyrustlm\models\tiny-test-model-self.adp1 .\tinyrustlm\models\tiny-test-model-self.adp1.manifest cargo run -p tinyrustlm-slm-pack -- compatibility .\tinyrustlm\models\tiny-test-model-q8.slm .\tinyrustlm\models\tiny-test-model-q8.slm .\target\model-breeding\tiny-q8-self.compat cargo run -p tinyrustlm-slm-pack -- lineage-template .\target\model-breeding\tiny-q8-self.compat .\target\model-breeding\tiny-q8-self-adapter.lineage tiny-q8-self-adapter adapter-delta-v1 tiny-q8-self cargo run -p tinyrustlm-slm-pack -- adapter-delta .\target\model-breeding\tiny-q8-self.compat .\target\model-breeding\tiny-q8-self-adapter.lineage .\tinyrustlm\models\tiny-test-model-q8.slm .\tinyrustlm\models\tiny-test-model-q8.slm .\tinyrustlm\models\tiny-test-model-q8-self.adp1 .\tinyrustlm\models\tiny-test-model-q8-self.adp1.manifest cargo run -p tinyrustlm-slm-pack -- validate-adapter-delta .\target\model-breeding\tiny-q8-self.compat .\target\model-breeding\tiny-q8-self-adapter.lineage .\tinyrustlm\models\tiny-test-model-q8.slm .\tinyrustlm\models\tiny-test-model-q8.slm .\tinyrustlm\models\tiny-test-model-q8-self.adp1 .\tinyrustlm\models\tiny-test-model-q8-self.adp1.manifest cargo run -p tinyrustlm-slm-pack -- compatibility .\tinyrustlm\models\tiny-test-model-q4.slm .\tinyrustlm\models\tiny-test-model-q4.slm .\target\model-breeding\tiny-q4-self.compat cargo run -p tinyrustlm-slm-pack -- lineage-template .\target\model-breeding\tiny-q4-self.compat .\target\model-breeding\tiny-q4-self-adapter.lineage tiny-q4-self-adapter adapter-delta-v1 tiny-q4-self cargo run -p tinyrustlm-slm-pack -- adapter-delta .\target\model-breeding\tiny-q4-self.compat .\target\model-breeding\tiny-q4-self-adapter.lineage .\tinyrustlm\models\tiny-test-model-q4.slm .\tinyrustlm\models\tiny-test-model-q4.slm .\tinyrustlm\models\tiny-test-model-q4-self.adp1 .\tinyrustlm\models\tiny-test-model-q4-self.adp1.manifest cargo run -p tinyrustlm-slm-pack -- validate-adapter-delta .\target\model-breeding\tiny-q4-self.compat .\target\model-breeding\tiny-q4-self-adapter.lineage .\tinyrustlm\models\tiny-test-model-q4.slm .\tinyrustlm\models\tiny-test-model-q4.slm .\tinyrustlm\models\tiny-test-model-q4-self.adp1 .\tinyrustlm\models\tiny-test-model-q4-self.adp1.manifest ``` The lineage template records a planned candidate id, operator id, resource budget, parent checksums, compatibility report checksum, and pending candidate artifact fields. It is the handoff point between parent selection and an offline operator. `blend-candidate` recomputes compatible parent tensors into f32 values, blends them by parts-per-million weights, writes a normal `.slm`, and records a receipt that `validate-blend-candidate` can reproduce exactly. `delta-candidate` uses the same gates, treats parent 0 as base and parent 1 as target, then writes `base + weight * (target - base)` candidates with signed parts-per-million weights and a receipt that `validate-delta-candidate` recomputes exactly. `sparse-delta-candidate` selects the largest absolute target-minus-base deltas by keep rate, applies the signed task-vector weight only to selected entries, keeps other entries at base values, and records a receipt that `validate-sparse-delta-candidate` recomputes exactly. `crossover-candidate` uses a deterministic seed and parent-0 keep rate to select each compatible tensor value from parent 0 or parent 1, then records selected counts, density, and a mask checksum that `validate-crossover-candidate` recomputes exactly. `mutation-candidate` treats parent 0 as the base layout, uses parent 1 as the compatible reference scale, applies deterministic bounded perturbations by seed/rate/magnitude, and records selection plus delta checksums that `validate-mutation-candidate` recomputes exactly. `prune-candidate` treats parent 0 as the base layout, uses parent 1 as compatible magnitude-ranking context, keeps base values selected by `keep_ppm` and optional `floor_ppm`, zeros the rest, and records mask plus output-value checksums that `validate-prune-candidate` recomputes exactly. `federated-candidate` treats parent 0 as the global/base artifact and parent 1 as a compatible local-update artifact, applies `local_update_weight_ppm` to `local_update - base`, and records local-update counts plus delta checksums that `validate-federated-candidate` recomputes exactly. `adapter-delta` uses the compatibility and lineage gates to write an `ADP1` raw f32 task-delta package plus a recomputable manifest; compatible f32, q8_0, and q4_0 packages can be applied by the browser runtime through `apply_adapter_delta`, while `fuse-adapter-delta` proves any validated package still matches its parents, fuses it into a normal `.slm` candidate, and records a receipt that `validate-fuse-adapter-delta` recomputes exactly. `sign-merge-candidate` starts later from a validated parent-pool recipe instead of a two-parent lineage file: it checks the matching ledger, review, admissions, and parent `.slm` files, uses parent 0 as the frontier base, applies seed-weighted positive or negative delta consensus for each parameter, writes a normal `.slm`, and records relatedness plus operator fields that `validate-sign-merge-candidate` recomputes exactly. `soup-candidate` uses the same parent-pool proof chain, averages every compatible tensor value by each parent's recipe `seed_weight_ppm`, writes a normal `.slm`, and records parent-weight, weighted-value, and frontier-change checksums that `validate-soup-candidate` recomputes exactly. The candidate artifact manifest is the next `.slm` handoff point for the existing two-parent lineage path, while `multi-parent-candidate-manifest` is the sign-merge or soup handoff point that binds the validated receipt, recipe checksum, relatedness summary, parent summaries, candidate `.slm` fields, and pending promotion route. `multi-parent-promotion-template` then binds that manifest checksum, receipt checksum, recipe checksum, parent count, and candidate `.slm` fields before runtime-smoke/eval handoff. `multi-parent-admission-record` binds the validated multi-parent promotion template to provenance, runtime-smoke, and passed eval sidecars. Both paths still reach validated runtime-smoke, eval, admission, ledger, and selector evidence before browser loading. Promotion ledgers chain admitted records into deterministic history before selector or population review. Population reviews now record the quality/frugality/quantization objective vector and per-entry objective checksum before parent-pool recipes consume the ranked candidates. Selector registries are the served-model handoff after admission: they accept selector admission records and multi-parent admission records when the candidate artifact path resolves under `tinyrustlm/models/`, then write browser routes such as `../models/admitted-q8.slm`. `tiny-test-model-bpe.slm` is the custom-tokenizer runtime fixture. It uses `BPE1`, vocab 262, and the deterministic `the` merge path so runtime diagnostics can prove the model selected BPE and produced tokenizer output `256,261` before generation. `tiny-test-model-tied.slm` is the tied-output runtime fixture. It intentionally omits `output.weight`, sets the v1 tied-output flag, and proves the loader and generator route output projection through `tok_embeddings.weight`. The validator must reject the same missing-output shape when the tied-output flag is absent. Generate or refresh a provenance sidecar with: ```powershell cargo run -p tinyrustlm-slm-pack -- manifest .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm.manifest deterministic-smoke ``` The sidecar is line-based and keeps model-admission claims honest. Current local artifacts are deterministic smoke models, so their manifests must say `source_kind=deterministic-smoke`, `quality_claim=runtime-execution-smoke-only`, and `trained_quality_claim=not-claimed`. Future converted trained models should use `source_kind=converted-trained`, which validates as structurally accepted but quality-pending until task evaluation and safety review exist. Validate and convert a raw trained-source fixture with: ```powershell cargo run -p tinyrustlm-slm-pack -- validate-source .\tinyrustlm\tests\fixtures\trained-source-tiny cargo run -p tinyrustlm-slm-pack -- convert-trained .\tinyrustlm\tests\fixtures\trained-source-tiny .\target\trained-source-smoke\tiny-converted-q8.slm q8_0 cargo run -p tinyrustlm-slm-pack -- quality-gate .\target\trained-source-smoke\tiny-converted-q8.slm .\target\trained-source-smoke\tiny-converted-q8.slm.manifest runtime-smoke cargo run -p tinyrustlm-slm-pack -- runtime-smoke .\target\trained-source-smoke\tiny-converted-q8.slm .\target\trained-source-smoke\tiny-converted-q8.slm.manifest .\target\trained-source-smoke\tiny-converted-q8.runtime cargo run -p tinyrustlm-runtime --bin tinyrustlm-eval -- .\target\trained-source-smoke\tiny-converted-q8.slm .\target\trained-source-smoke\tiny-converted-q8.slm.manifest .\tinyrustlm\tests\fixtures\assistant-quality-eval-cases.txt .\target\trained-source-smoke\tiny-converted-q8.eval cargo run -p tinyrustlm-slm-pack -- quality-gate .\target\trained-source-smoke\tiny-converted-q8.slm .\target\trained-source-smoke\tiny-converted-q8.slm.manifest assistant-quality .\target\trained-source-smoke\tiny-converted-q8.eval ``` After compatibility, lineage, candidate, and promotion sidecars exist for a converted-trained candidate, the selector admission command binds them to runtime-smoke and eval evidence: ```powershell cargo run -p tinyrustlm-slm-pack -- admission-record .\target\admission-smoke\tiny-converted-q8.compat .\target\admission-smoke\tiny-converted-q8.lineage .\target\admission-smoke\tiny-converted-q8.slm .\target\admission-smoke\tiny-converted-q8.candidate .\target\admission-smoke\tiny-converted-q8.promotion .\target\admission-smoke\tiny-converted-q8.slm.manifest .\target\admission-smoke\tiny-converted-q8.runtime .\target\admission-smoke\tiny-converted-q8.eval .\target\admission-smoke\tiny-converted-q8.admission browser-local-selector cargo run -p tinyrustlm-slm-pack -- validate-admission .\target\admission-smoke\tiny-converted-q8.compat .\target\admission-smoke\tiny-converted-q8.lineage .\target\admission-smoke\tiny-converted-q8.slm .\target\admission-smoke\tiny-converted-q8.candidate .\target\admission-smoke\tiny-converted-q8.promotion .\target\admission-smoke\tiny-converted-q8.slm.manifest .\target\admission-smoke\tiny-converted-q8.runtime .\target\admission-smoke\tiny-converted-q8.eval .\target\admission-smoke\tiny-converted-q8.admission cargo run -p tinyrustlm-slm-pack -- promotion-ledger .\target\admission-smoke\tiny-converted-q8.ledger .\target\admission-smoke\tiny-converted-q8.admission cargo run -p tinyrustlm-slm-pack -- validate-promotion-ledger .\target\admission-smoke\tiny-converted-q8.ledger .\target\admission-smoke\tiny-converted-q8.admission cargo run -p tinyrustlm-slm-pack -- selector-registry .\target\selector-smoke\selector.registry .\target\selector-smoke\admitted-q8.admission cargo run -p tinyrustlm-slm-pack -- validate-selector-registry .\target\selector-smoke\selector.registry .\target\selector-smoke\admitted-q8.admission ``` The registry commands expect the admitted candidate path to be browser-served. A target-only converted candidate should be staged under the local `tinyrustlm/models/` route, with its `.slm.manifest`, before writing a `selector.registry` for the browser selector. Generated f32/q8_0/q4_0 bundle registries may also carry local `../models/*.adp1` routes, adapter manifest routes, labels, apply status, and checksums for the same quantization entry. Single routes use the legacy adapter fields; adapter families use `adapter_count` plus indexed adapter fields. The browser transfers the selected sidecar to WASM, and Rust still validates `ADP1` identity and payloads before apply. For a runnable converted-trained browser root, use `browser-converted-trained-bundle`. It converts a reviewed source directory into `models/converted-trained-f32.slm`, `models/converted-trained-q8.slm`, `models/converted-trained-q4.slm`, or all three in one q4-defaulted selector root, writes matching `.slm.manifest` files, stages compatibility/lineage/candidate/promotion/runtime/eval/admission sidecars under `evidence/`, and writes `models/selector.registry`. Serve that root and run `converted-trained-registry-file` to prove the browser loads the selector, model, and manifest through file-backed routes. ```powershell cargo run -p tinyrustlm-slm-pack -- browser-converted-trained-bundle .\target\browser-converted-trained-file\tinyrustlm .\tinyrustlm\tests\fixtures\trained-source-tiny all cargo run -p tinyrustlm-local-server -- .\target\browser-converted-trained-file\tinyrustlm 8096 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8096/app/ 9290 converted-trained-q4 converted-trained-registry-file node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8096/app/ 9291 converted-trained-q8 converted-trained-registry-file node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8096/app/ 9292 converted-trained-f32 converted-trained-registry-file ``` Generate browser-served multi-parent bundles with registry-carried self and family adapter routes: ```powershell cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-multi-parent\tinyrustlm cargo run -p tinyrustlm-local-server -- .\target\browser-served-multi-parent\tinyrustlm 8090 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8090/app/ 9237 multi-parent-sign-merge-f32 multi-parent-registry-file node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8090/app/ 9239 multi-parent-sign-merge-f32 adapter-sidecar-registry-file cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-multi-parent-q8\tinyrustlm q8_0 cargo run -p tinyrustlm-local-server -- .\target\browser-served-multi-parent-q8\tinyrustlm 8093 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8093/app/ 9243 multi-parent-sign-merge-q8 adapter-sidecar-registry-file cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-multi-parent-q4\tinyrustlm q4_0 cargo run -p tinyrustlm-local-server -- .\target\browser-served-multi-parent-q4\tinyrustlm 8094 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8094/app/ 9244 multi-parent-sign-merge-q4 adapter-sidecar-registry-file cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-multi-parent-soup-q8\tinyrustlm q8_0 soup cargo run -p tinyrustlm-local-server -- .\target\browser-served-multi-parent-soup-q8\tinyrustlm 8097 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8097/app/ 9347 multi-parent-soup-q8 adapter-sidecar-registry-file node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8097/app/ 9349 multi-parent-soup-q8 multi-parent-registry-file cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-multi-parent-soup-all\tinyrustlm all soup cargo run -p tinyrustlm-local-server -- .\target\browser-served-multi-parent-soup-all\tinyrustlm 8098 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8098/app/ 9358 multi-parent-soup-q4 combined-selector-assembly node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8098/app/ 9359 multi-parent-soup-q4 combined-selector-cycle 2 cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-multi-parent-mixed\tinyrustlm all mixed cargo run -p tinyrustlm-local-server -- .\target\browser-served-multi-parent-mixed\tinyrustlm 8116 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8116/app/ 9387 multi-parent-sign-merge-q4 combined-selector-operator-family node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8116/app/ 9388 multi-parent-sign-merge-q4 combined-selector-operator-family-cycle 2 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8116/app/ 9389 multi-parent-sign-merge-q4 combined-selector-operator-family-route-soak 2 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8116/app/ 9390 multi-parent-sign-merge-q4 combined-selector-operator-family-reload-soak 2 ``` Generate a tied-output source bundle when the trained source intentionally shares token embeddings with the output projection: ```powershell cargo run -p tinyrustlm-slm-pack -- source-template .\target\trained-source-smoke\source-tiny-tied tiny-fixture-tied cargo run -p tinyrustlm-slm-pack -- validate-source .\target\trained-source-smoke\source-tiny-tied cargo run -p tinyrustlm-slm-pack -- convert-trained .\target\trained-source-smoke\source-tiny-tied .\target\trained-source-smoke\tiny-tied-converted-q8.slm q8_0 cargo run -p tinyrustlm-slm-pack -- validate .\target\trained-source-smoke\tiny-tied-converted-q8.slm ``` `convert-trained` reads `source.manifest` plus raw f32 tensor files under `tensors/`, rejects unsafe paths, checksum drift, wrong byte counts, wrong shapes, non-finite values, out-of-range weights, and all-zero tensors, then writes a checksum-bearing `.slm` plus a `converted-trained` manifest. A source manifest can declare `tied_output=true` only with a tied shape such as `tiny-fixture-tied` or `tinylm16-tied`; that layout omits `output.weight` and conversion sets the v1 tied-output flag. `tinyrustlm-eval` executes exact cases through the Rust runtime and writes a scoped eval sidecar. The checked-in eval cases prove only the tiny converted-source fixture scope; they are not a product assistant-quality claim. Check the explicit quality gate before making a claim about an artifact: ```powershell cargo run -p tinyrustlm-slm-pack -- quality-gate .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm.manifest runtime-smoke cargo run -p tinyrustlm-slm-pack -- runtime-smoke .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm.manifest .\target\model-breeding\tinylm16-q8-self.runtime cargo run -p tinyrustlm-slm-pack -- eval-template .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm.manifest .\tinyrustlm\models\tinylm16-q8.slm.eval assistant-quality ``` `runtime-smoke` proves only local runtime execution and can also write a durable sidecar. `assistant-quality` requires a converted-trained manifest plus a separate eval sidecar with matching model and manifest checksums, passed task evaluation, passed safety review, a non-placeholder quality scope, and `quality_decision=accepted-for-assistant-quality`. The generated eval template is intentionally `pending` and must fail `assistant-quality` until reviewed evidence replaces the placeholder fields. Current artifact SHA256 values: - `tiny-test-model.slm`: `17D79EE766578729D2B69090547E819E011D76115519514E19AC3754DE610A1A` - `tiny-test-model-q8.slm`: `6AF985853325EAA6D3EAAA8AADD3511DA9596EB542FB2D03A9BC9DC1F4377ADF` - `tiny-test-model-q4.slm`: `4004E2152F0B6382C6043A15084DE6DC4AE6AE6B6C5BA43ABDE8812ED0174CF6` - `tiny-test-model-bpe.slm`: `31B27903C1588A1F246281DEF8027094C0D3862635FA7D3761AA1327471F3E82` - `tiny-test-model-tied.slm`: `9D68DC80CD2CCC2366344B92A497629AF1D693350F92B3B0EE383D4B30E08B7C` - `tiny-test-model-self.adp1`: `DBEEB5875D00958179600C1CB353CA1FAB7604F3D755A5DA905BFFF7F45B8BA8` - `tiny-test-model-q8-self.adp1`: `7B4E998EFEAC9B9D7BB6F909FC99BC17CA81A905D5C19FA0970A8229BF67E5E8` - `tiny-test-model-q4-self.adp1`: `9BD044B950E0CED7B8C9785D0ECEB0E175B91861D1C845267BC0D690A0CC9C56` - `tinylm16-f32.slm`: `70E9765080247FE859506534E87330D73FF50B66B8A48DC627C307069BB0DC5B` - `tinylm16-q8.slm`: `C3919E6D7244890E9B3C2B5E40C37F8D322467D859C15B8155700F20408DB950` - `tinylm16-q4.slm`: `5AC2BD957113732BE9AB2AADFA2D2EFD54C3131E7E6C97BE424FAC6E72BB365B` Current manifest SHA256 values: - `tiny-test-model.slm.manifest`: `04A621560A3F24C8E8243A1D085CACB6944CAD0898967582500EDE6D885B1B81` - `tiny-test-model-q8.slm.manifest`: `85AC07502280F1D05B18A6932B83465C60CA59EE1B4D157A45C668380131294F` - `tiny-test-model-q4.slm.manifest`: `EB53E4A34D831571BE34B29049D07901E85411561E761DC2C9E37C60827B853F` - `tiny-test-model-bpe.slm.manifest`: `AE28DDD62E91834A1F7F6D29BE186CB9EA81A92FAEBC0A5AF3E5A4897DC15B52` - `tiny-test-model-tied.slm.manifest`: `469A78D503B010323709EEAF6731DC8AFE05F0DE442BC16BC63F58C636A1490C` - `tiny-test-model-self.adp1.manifest`: `78D72C47C6423F4E16E194DBB7F56F055071962FF611CC8C12E971C4C0FB75D0` - `tiny-test-model-q8-self.adp1.manifest`: `5680FD9A8676B818BCE3B90175AE75B574ACFE380B0B374A27ED46EA2C714AEB` - `tiny-test-model-q4-self.adp1.manifest`: `2060583F1243B373C8E3AEFECA5EFD763F09979E679249B9C087C1EC3DFF1880` - `tinylm16-f32.slm.manifest`: `D9CDEF0D7CE09979EF8D824BCF68555322B89A286DE197148CD2263F654E3010` - `tinylm16-q8.slm.manifest`: `21178B39642AE045CB26FE99B1595BC5B193AE563EC17F7545E478316CBFAA70` - `tinylm16-q4.slm.manifest`: `7B1C77776876EC9BE80DD00CEFB6C7AE877FD592FBF4FAD5029080B36B8D46CB` `tinylm16-f32.slm`, `tinylm16-q8.slm`, and `tinylm16-q4.slm` are deterministic real-shaped smoke models. The q4_0 artifact is 10,657,728 bytes and uses direct q4_0 matrix dispatch in the runtime. ================================================================================ END FILE: tinyrustlm/models/README.md ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/models/tinylm16-f32.slm.manifest BYTES: 540 SHA256: D9CDEF0D7CE09979EF8D824BCF68555322B89A286DE197148CD2263F654E3010 ================================================================================ tinyrustlm_slm_manifest_version=1 model_path=tinyrustlm\models\tinylm16-f32.slm model_bytes=68194944 slm_version=1 slm_checksum=0x73f4266ddbe6955f model_shape=vocab=260,hidden=512,layers=4,heads=8,kv_heads=8,head_dim=64,ffn=2048,context=512 tensor_count=39 parameter_count=17048064 quantization=f32 source_kind=deterministic-smoke quality_claim=runtime-execution-smoke-only trained_quality_claim=not-claimed admission_status=accepted-for-runtime-smoke required_next_gate=replace-with-trained-or-evaluated-model-before-product-quality-claim ================================================================================ END FILE: tinyrustlm/models/tinylm16-f32.slm.manifest ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/models/tinylm16-q4.slm.manifest BYTES: 540 SHA256: 7B1C77776876EC9BE80DD00CEFB6C7AE877FD592FBF4FAD5029080B36B8D46CB ================================================================================ tinyrustlm_slm_manifest_version=1 model_path=tinyrustlm\models\tinylm16-q4.slm model_bytes=10657728 slm_version=1 slm_checksum=0xcff6d706b2a04def model_shape=vocab=260,hidden=512,layers=4,heads=8,kv_heads=8,head_dim=64,ffn=2048,context=512 tensor_count=39 parameter_count=17048064 quantization=q4_0 source_kind=deterministic-smoke quality_claim=runtime-execution-smoke-only trained_quality_claim=not-claimed admission_status=accepted-for-runtime-smoke required_next_gate=replace-with-trained-or-evaluated-model-before-product-quality-claim ================================================================================ END FILE: tinyrustlm/models/tinylm16-q4.slm.manifest ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/models/tinylm16-q8.slm.manifest BYTES: 540 SHA256: 21178B39642AE045CB26FE99B1595BC5B193AE563EC17F7545E478316CBFAA70 ================================================================================ tinyrustlm_slm_manifest_version=1 model_path=tinyrustlm\models\tinylm16-q8.slm model_bytes=17160000 slm_version=1 slm_checksum=0xa1442f3f180c542b model_shape=vocab=260,hidden=512,layers=4,heads=8,kv_heads=8,head_dim=64,ffn=2048,context=512 tensor_count=39 parameter_count=17048064 quantization=q8_0 source_kind=deterministic-smoke quality_claim=runtime-execution-smoke-only trained_quality_claim=not-claimed admission_status=accepted-for-runtime-smoke required_next_gate=replace-with-trained-or-evaluated-model-before-product-quality-claim ================================================================================ END FILE: tinyrustlm/models/tinylm16-q8.slm.manifest ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/models/tiny-test-model.slm.manifest BYTES: 530 SHA256: 04A621560A3F24C8E8243A1D085CACB6944CAD0898967582500EDE6D885B1B81 ================================================================================ tinyrustlm_slm_manifest_version=1 model_path=tinyrustlm\models\tiny-test-model.slm model_bytes=20352 slm_version=1 slm_checksum=0x95d32408fe2b3d1a model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 tensor_count=12 parameter_count=4824 quantization=f32 source_kind=deterministic-smoke quality_claim=runtime-execution-smoke-only trained_quality_claim=not-claimed admission_status=accepted-for-runtime-smoke required_next_gate=replace-with-trained-or-evaluated-model-before-product-quality-claim ================================================================================ END FILE: tinyrustlm/models/tiny-test-model.slm.manifest ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/models/tiny-test-model-bpe.slm.manifest BYTES: 534 SHA256: AE28DDD62E91834A1F7F6D29BE186CB9EA81A92FAEBC0A5AF3E5A4897DC15B52 ================================================================================ tinyrustlm_slm_manifest_version=1 model_path=tinyrustlm\models\tiny-test-model-bpe.slm model_bytes=20544 slm_version=1 slm_checksum=0x277b7051f235a14f model_shape=vocab=262,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 tensor_count=12 parameter_count=4856 quantization=f32 source_kind=deterministic-smoke quality_claim=runtime-execution-smoke-only trained_quality_claim=not-claimed admission_status=accepted-for-runtime-smoke required_next_gate=replace-with-trained-or-evaluated-model-before-product-quality-claim ================================================================================ END FILE: tinyrustlm/models/tiny-test-model-bpe.slm.manifest ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/models/tiny-test-model-q4.slm.manifest BYTES: 533 SHA256: EB53E4A34D831571BE34B29049D07901E85411561E761DC2C9E37C60827B853F ================================================================================ tinyrustlm_slm_manifest_version=1 model_path=tinyrustlm\models\tiny-test-model-q4.slm model_bytes=6592 slm_version=1 slm_checksum=0x060d1082056cc6ca model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 tensor_count=12 parameter_count=4824 quantization=q4_0 source_kind=deterministic-smoke quality_claim=runtime-execution-smoke-only trained_quality_claim=not-claimed admission_status=accepted-for-runtime-smoke required_next_gate=replace-with-trained-or-evaluated-model-before-product-quality-claim ================================================================================ END FILE: tinyrustlm/models/tiny-test-model-q4.slm.manifest ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/models/tiny-test-model-q4-self.adp1.manifest BYTES: 2026 SHA256: 2060583F1243B373C8E3AEFECA5EFD763F09979E679249B9C087C1EC3DFF1880 ================================================================================ tinyrustlm_adapter_artifact_version=1 adapter_artifact_kind=raw-f32-task-delta-v1 adapter_status=artifact-written candidate_id=tiny-q4-self-adapter operator_id=adapter-delta-v1 operator_lane=offline-model-breeding-parent-set resource_budget=browser-q4-sidecar compatibility_report_checksum=0x942b253380e492a9 lineage_manifest_checksum=0xba628198f223155e compatibility_scope=direct-parameter-family parent_count=2 parent.0.compatibility_path=tinyrustlm/models/tiny-test-model-q4.slm parent.0.actual_path=tinyrustlm/models/tiny-test-model-q4.slm parent.0.model_bytes=6592 parent.0.slm_checksum=0x060d1082056cc6ca parent.0.model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 parent.0.quantization=q4_0 parent.0.output_contract=explicit-output parent.0.tokenizer_checksum=0x288f65d94c26743e parent.0.tensor_layout_checksum=0xbb67ecc9740ef6b7 parent.1.compatibility_path=tinyrustlm/models/tiny-test-model-q4.slm parent.1.actual_path=tinyrustlm/models/tiny-test-model-q4.slm parent.1.model_bytes=6592 parent.1.slm_checksum=0x060d1082056cc6ca parent.1.model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 parent.1.quantization=q4_0 parent.1.output_contract=explicit-output parent.1.tokenizer_checksum=0x288f65d94c26743e parent.1.tensor_layout_checksum=0xbb67ecc9740ef6b7 adapter_artifact_path=tinyrustlm/models/tiny-test-model-q4-self.adp1 adapter_artifact_bytes=20224 adapter_artifact_checksum=0x0bd71e0020bc6ebf adapter_tensor_count=12 adapter_parameter_count=4824 adapter_dtype=f32-delta adapter_model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 adapter_base_quantization=q4_0 adapter_output_contract=explicit-output adapter_tokenizer_checksum=0x288f65d94c26743e adapter_tensor_layout_checksum=0xbb67ecc9740ef6b7 adapter_base_contract=matches-parent-direct-parameter-contract adapter_apply_status=runtime-q8-q4-compatible-or-fuse-to-slm required_next_gate=fuse-to-slm-plus-candidate-manifest-plus-runtime-smoke-plus-eval ================================================================================ END FILE: tinyrustlm/models/tiny-test-model-q4-self.adp1.manifest ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/models/tiny-test-model-q8.slm.manifest BYTES: 533 SHA256: 85AC07502280F1D05B18A6932B83465C60CA59EE1B4D157A45C668380131294F ================================================================================ tinyrustlm_slm_manifest_version=1 model_path=tinyrustlm\models\tiny-test-model-q8.slm model_bytes=8832 slm_version=1 slm_checksum=0x481f1037d57ebcd3 model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 tensor_count=12 parameter_count=4824 quantization=q8_0 source_kind=deterministic-smoke quality_claim=runtime-execution-smoke-only trained_quality_claim=not-claimed admission_status=accepted-for-runtime-smoke required_next_gate=replace-with-trained-or-evaluated-model-before-product-quality-claim ================================================================================ END FILE: tinyrustlm/models/tiny-test-model-q8.slm.manifest ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/models/tiny-test-model-q8-self.adp1.manifest BYTES: 2026 SHA256: 5680FD9A8676B818BCE3B90175AE75B574ACFE380B0B374A27ED46EA2C714AEB ================================================================================ tinyrustlm_adapter_artifact_version=1 adapter_artifact_kind=raw-f32-task-delta-v1 adapter_status=artifact-written candidate_id=tiny-q8-self-adapter operator_id=adapter-delta-v1 operator_lane=offline-model-breeding-parent-set resource_budget=browser-q8-sidecar compatibility_report_checksum=0xf053c348a8ef095a lineage_manifest_checksum=0x69f4fed37b805029 compatibility_scope=direct-parameter-family parent_count=2 parent.0.compatibility_path=tinyrustlm/models/tiny-test-model-q8.slm parent.0.actual_path=tinyrustlm/models/tiny-test-model-q8.slm parent.0.model_bytes=8832 parent.0.slm_checksum=0x481f1037d57ebcd3 parent.0.model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 parent.0.quantization=q8_0 parent.0.output_contract=explicit-output parent.0.tokenizer_checksum=0x288f65d94c26743e parent.0.tensor_layout_checksum=0xd8fb6e636a8badd6 parent.1.compatibility_path=tinyrustlm/models/tiny-test-model-q8.slm parent.1.actual_path=tinyrustlm/models/tiny-test-model-q8.slm parent.1.model_bytes=8832 parent.1.slm_checksum=0x481f1037d57ebcd3 parent.1.model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 parent.1.quantization=q8_0 parent.1.output_contract=explicit-output parent.1.tokenizer_checksum=0x288f65d94c26743e parent.1.tensor_layout_checksum=0xd8fb6e636a8badd6 adapter_artifact_path=tinyrustlm/models/tiny-test-model-q8-self.adp1 adapter_artifact_bytes=20224 adapter_artifact_checksum=0x8194a8a671285019 adapter_tensor_count=12 adapter_parameter_count=4824 adapter_dtype=f32-delta adapter_model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 adapter_base_quantization=q8_0 adapter_output_contract=explicit-output adapter_tokenizer_checksum=0x288f65d94c26743e adapter_tensor_layout_checksum=0xd8fb6e636a8badd6 adapter_base_contract=matches-parent-direct-parameter-contract adapter_apply_status=runtime-q8-q4-compatible-or-fuse-to-slm required_next_gate=fuse-to-slm-plus-candidate-manifest-plus-runtime-smoke-plus-eval ================================================================================ END FILE: tinyrustlm/models/tiny-test-model-q8-self.adp1.manifest ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/models/tiny-test-model-self.adp1.manifest BYTES: 2004 SHA256: 78D72C47C6423F4E16E194DBB7F56F055071962FF611CC8C12E971C4C0FB75D0 ================================================================================ tinyrustlm_adapter_artifact_version=1 adapter_artifact_kind=raw-f32-task-delta-v1 adapter_status=artifact-written candidate_id=tiny-f32-self-adapter operator_id=adapter-delta-v1 operator_lane=offline-model-breeding-parent-set resource_budget=tiny-f32-self compatibility_report_checksum=0xdc2446eda24523ac lineage_manifest_checksum=0x268ff13bc828360a compatibility_scope=direct-parameter-family parent_count=2 parent.0.compatibility_path=tinyrustlm\models\tiny-test-model.slm parent.0.actual_path=tinyrustlm\models\tiny-test-model.slm parent.0.model_bytes=20352 parent.0.slm_checksum=0x95d32408fe2b3d1a parent.0.model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 parent.0.quantization=f32 parent.0.output_contract=explicit-output parent.0.tokenizer_checksum=0x288f65d94c26743e parent.0.tensor_layout_checksum=0x8da876d01ba1a9bb parent.1.compatibility_path=tinyrustlm\models\tiny-test-model.slm parent.1.actual_path=tinyrustlm\models\tiny-test-model.slm parent.1.model_bytes=20352 parent.1.slm_checksum=0x95d32408fe2b3d1a parent.1.model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 parent.1.quantization=f32 parent.1.output_contract=explicit-output parent.1.tokenizer_checksum=0x288f65d94c26743e parent.1.tensor_layout_checksum=0x8da876d01ba1a9bb adapter_artifact_path=tinyrustlm\models\tiny-test-model-self.adp1 adapter_artifact_bytes=20224 adapter_artifact_checksum=0xe9669ade4571fd42 adapter_tensor_count=12 adapter_parameter_count=4824 adapter_dtype=f32-delta adapter_model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 adapter_base_quantization=f32 adapter_output_contract=explicit-output adapter_tokenizer_checksum=0x288f65d94c26743e adapter_tensor_layout_checksum=0x8da876d01ba1a9bb adapter_base_contract=matches-parent-direct-parameter-contract adapter_apply_status=runtime-f32-compatible-or-fuse-to-slm required_next_gate=fuse-to-slm-plus-candidate-manifest-plus-runtime-smoke-plus-eval ================================================================================ END FILE: tinyrustlm/models/tiny-test-model-self.adp1.manifest ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/models/tiny-test-model-tied.slm.manifest BYTES: 535 SHA256: 469A78D503B010323709EEAF6731DC8AFE05F0DE442BC16BC63F58C636A1490C ================================================================================ tinyrustlm_slm_manifest_version=1 model_path=tinyrustlm\models\tiny-test-model-tied.slm model_bytes=11968 slm_version=1 slm_checksum=0x7d62cfbfde480fed model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16 tensor_count=11 parameter_count=2744 quantization=f32 source_kind=deterministic-smoke quality_claim=runtime-execution-smoke-only trained_quality_claim=not-claimed admission_status=accepted-for-runtime-smoke required_next_gate=replace-with-trained-or-evaluated-model-before-product-quality-claim ================================================================================ END FILE: tinyrustlm/models/tiny-test-model-tied.slm.manifest ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/README.md BYTES: 71074 SHA256: 625BA413419244D514A72DB0881094AB151F0728D475588159E018757D923937 ================================================================================ # TinyRustLM TinyRustLM is the zero-dependency client-side SLM runtime for GGUF.MiRust.com. The app target is a static browser UI plus a Rust-compiled WASM runtime that loads a local `.slm` model file, validates it, tokenizes prompts, and runs local inference without remote APIs or third-party runtime libraries. ## Current Milestone Implemented source slice: - Static browser shell in `app/`. - Handwritten JavaScript WASM/model loader. - Rust runtime crate with no dependencies. - Raw WASM exports for allocation, model load, adapter validation, adapter apply, prompt transfer, generation boundary, diagnostics, context reset, and model free. - Byte tokenizer, `.slm` parser, tensor views, math ops, q8/q4 helpers, RoPE, KV cache, sampler, and diagnostics source. - No-crate `slm_pack` source for generating a tiny fixture `.slm`. - Generated `runtime/tinyrustlm.wasm`. - Generated `models/tiny-test-model.slm`. - Generated `models/tiny-test-model-q8.slm` and `models/tiny-test-model-q4.slm`. - Generated `models/tiny-test-model-bpe.slm` custom BPE fixture. - Generated `models/tiny-test-model-tied.slm` tied-output fixture. - Generated `models/tinylm16-f32.slm`. - Generated `models/tinylm16-q8.slm`. - Generated `models/tinylm16-q4.slm`. - Generated `models/tiny-test-model-self.adp1`, `models/tiny-test-model-q8-self.adp1`, and `models/tiny-test-model-q4-self.adp1` plus manifests for the checked browser adapter sidecar routes. - Checksum-bearing `.slm` artifacts; the runtime rejects zero or mismatched checksums before tensor decoding. - Provenance `.slm.manifest` sidecars for every local model artifact, with deterministic-smoke status and explicit trained-quality non-claim. - Browser model provenance panel that fetches the selected local `.slm.manifest` after Rust accepts the model and renders source kind, admission status, quality claim, trained-quality claim, checksum, and required next gate. - Browser decoding controls for temperature, top-k, top-p, and deterministic seed, defaulting to greedy decoding for repeatable smoke tests. - Packer-side `runtime-smoke`, `eval-template`, and `quality-gate` commands that separate runtime execution proof from future assistant-quality admission. - Packer-side `compatibility` command that emits line-based parent-set reports for offline model-breeding and assembly work. - Packer-side `lineage-template` and `validate-lineage` commands that bind planned candidates to a passing parent compatibility report before an operator writes an artifact. - Packer-side `blend-candidate` / `validate-blend-candidate`, `delta-candidate` / `validate-delta-candidate`, `sparse-delta-candidate` / `validate-sparse-delta-candidate`, and `dare-candidate` / `validate-dare-candidate` commands that run direct-parameter weighted-average, task-delta, sparse task-delta, and DARE-style dropout/rescaled task-delta operators while binding recomputable receipts, including sparse mask and dropout mask metadata, to produced `.slm` artifacts. - Packer-side `adapter-delta` / `validate-adapter-delta`, `sparse-adapter-delta` / `validate-sparse-adapter-delta`, and `low-rank-adapter-delta` / `validate-low-rank-adapter-delta` commands that write lineage-bound raw ADP1, sparse ASP1, or low-rank ALR1 f32 task-delta adapter packages plus recomputable manifests. - Packer-side `adapter-source-template` and `validate-adapter-source` commands that write and validate reviewed trained low-rank adapter source bundles, plus `convert-adapter-source` and `validate-converted-adapter-source` commands that package those reviewed f32 factors into runtime ALR1 artifacts. - Packer-side `fuse-adapter-delta` and `validate-fuse-adapter-delta` commands that validate raw adapter packages and manifests, fuse them into normal `.slm` candidates, and bind recomputable adapter-fuse receipts. - Runtime-side f32/q8_0/q4_0 `ADP1`, `ASP1`, and `ALR1` adapter apply for already-loaded compatible models, with package identity validation, compact q8/q4 re-quantization, and generation/KV state reset after successful apply. - Browser Adapter Sidecar panel for the checked tiny f32/q8_0/q4_0 self-ADP1 routes, checking the local ADP1 artifact checksum before copying bytes into WASM and calling `apply_adapter_delta` without JavaScript parsing the package. - Packer-side `candidate-manifest` and `validate-candidate` commands that bind a validated candidate lineage to a validated `.slm` artifact before eval or promotion. - Packer-side `promotion-template` and `validate-promotion` commands that bind a candidate artifact manifest to pending runtime-smoke and eval proof before browser selector admission. - Packer-side `admission-record` and `validate-admission` commands that bind promotion, runtime-smoke sidecar, and passed eval sidecar evidence before a future browser selector can admit a candidate. - Packer-side `promotion-ledger` and `validate-promotion-ledger` commands that chain admitted candidate records into a deterministic promotion history before selector or population review. - Packer-side `population-review` and `validate-population-review` commands that rank promotion-ledger candidates into deterministic frontier and parent-pool routes with explicit quality/frugality/quantization objective-vector metadata. - Packer-side `parent-pool-recipe` and `validate-parent-pool-recipe` commands that turn a population review into a shared-contract parent set with normalized seed weights for sign-aware work. - Packer-side `sign-merge-candidate` and `validate-sign-merge-candidate` commands that consume a validated parent-pool recipe, ledger, review, admissions, and parent `.slm` files, then write a normal `.slm` candidate plus a recomputable sign-vote receipt. - Packer-side `multi-parent-candidate-manifest` and `validate-multi-parent-candidate` commands that bind validated sign-merge output to its receipt checksum, parent-pool recipe checksum, candidate `.slm` fields, and pending promotion route. - Packer-side `multi-parent-promotion-template` and `validate-multi-parent-promotion` commands that bind a validated multi-parent candidate manifest to pending runtime-smoke and eval proof before admission. - Packer-side `multi-parent-admission-record` and `validate-multi-parent-admission` commands that bind a validated multi-parent promotion template to runtime-smoke and passed eval evidence before selector-registry routing. - Packer-side `selector-registry` and `validate-selector-registry` commands that bind two-parent selector admissions or multi-parent admission records to browser-safe `../models/*.slm` selector routes, with deterministic selector genome id, genome lineage checksum, species id, species-fit checksum, novelty id, novelty checksum, population id, population-review checksum, mate-selection id/status/parent-count/checksum, phenotype-evidence id/status/checksum, provenance-manifest checksum, heritable-artifact id/status/checksum, scoped fitness-vector checksum, optional f32/q8_0/q4_0 adapter sidecar fields, indexed adapter-family fields, adapter-family receipt handles, and adapter auto-apply stack fields for generated bundles. - Packer-side `browser-multi-parent-bundle` command that writes a runnable TinyRustLM root with app shell, WASM runtime, generated f32/q8_0/q4_0 sign-merge `.slm` routes, manifests, selector registry carrying genome/species/novelty/population/mate-selection/phenotype/artifact/fitness evidence, module-plan receipt with `browser-constrained-v1` profile, `single-threaded-wasm-local-v1` execution profile, `local-no-store-v1` fetch policy, `same-origin-loopback-local-v1` origin policy, resource envelope, tokenizer checksum, fixed sampler candidate cap, `tinyrustlm-generate-v1` WASM export set, exact context token limit, exact adapter-stack byte budget, runtime scratch envelope, 4096-byte prompt envelope, 64 KiB output cap, KV-cache envelope, total budget/limit fields, and `module_plan_fetch_count_limit=32`, local self ADP1, family ADP1, sparse ASP1, and source-backed low-rank ALR1 sidecars, adapter manifests, adapter-family receipt, assembly receipt, and evidence chain. - Packer-side `browser-converted-trained-bundle` command that writes a runnable TinyRustLM root from a reviewed trained-source directory with a converted-trained f32, q8_0, q4_0, or combined all-quant `.slm` selector set, provenance manifests, evidence sidecars, selector admissions, and `models/selector.registry`. - Browser model selector optional intake from `models/selector.registry`, with smoke-model fallback when no admitted registry is present. - Browser smoke mode for a served multi-parent selector registry entry, proving `multi-parent-sign-merge-q8` routes through local `../models/*.slm` model and manifest paths, plus generated file-backed f32/q8_0/q4_0 bundle routes. - Browser smoke mode for generated served multi-parent bundles, proving `multi-parent-sign-merge-f32`, `multi-parent-sign-merge-q8`, and `multi-parent-sign-merge-q4` load through real `models/selector.registry`, `.module-plan.receipt`, `.slm`, `.slm.manifest`, assembly receipt, evidence, adapter receipt, adapter manifest file routes, and registry-backed provenance genome/species/novelty/population/mate-selection/phenotype/artifact/fitness rows. - Browser smoke mode for file-backed converted-trained bundles, proving `converted-trained-q4`, `converted-trained-q8`, and `converted-trained-f32` load through one real q4-defaulted `models/selector.registry` root with `.slm` and `.slm.manifest` routes while rendering converted-trained provenance fields. - Browser smoke mode for generated registry-carried adapter families, proving self ADP1, family ADP1, sparse ASP1, and source-backed low-rank ALR1 sidecars are offered from `models/selector.registry`, the served adapter-family receipt and all served adapter manifests are fetched and checksum-verified before the family choices are enabled, the receipt-declared family ADP1 plus sparse ASP1 plus source-backed ALR1 stack is validated and applied before generation, and Rust applies each package for f32/q8_0/q4_0 generated roots. - Packer-side raw-f32 trained-source layout validation and `convert-trained` command for converting checked source weights into f32/q8_0/q4_0 `.slm` artifacts, including explicit BPE tokenizer source manifests and tied-output source manifests that omit `output.weight`; trained adapter source validation and source-backed ALR1 conversion now add low-rank f32 factor-bundle intake for compact skill deltas. - Tiny trained-source fixture under `tests/fixtures/trained-source-tiny/` and scoped eval cases under `tests/fixtures/assistant-quality-eval-cases.txt`. - Native no-crate `tinyrustlm-eval` runner for executing scoped eval cases against a local `.slm` and writing an eval sidecar. - No-crate Rust local static server in `tools/local_server/`, plus the older no-dependency Node server script retained for narrow tooling fallback. - No-crate Rust mini browser harness in `tools/browser_harness/` for static app crawl, required UI contract, local-only asset policy, WASM boundary markers, model/manifest presence, and optional loopback route checks. - One-layer tiny f32 transformer forward path. - Greedy local generation over f32, q8_0, and q4_0 tiny fixtures. - Greedy local generation over the TinyLM-16M-shaped f32 model. - Greedy local generation over the TinyLM-16M-shaped q8_0 model using direct q8_0 matvec dispatch. - Greedy local generation over the TinyLM-16M-shaped q4_0 model using direct q4_0 matvec dispatch. - q8_0 and q4_0 tensors stay in native compact storage without full decoded f32 shadow copies; embedding rows and norm vectors dequantize into scratch on demand. - Model load pre-resolves top-level and per-layer tensor indices, and the checked-in tied-output fixture proves projection flags route output logits through token embeddings when `output.weight` is omitted. - Runtime generation allocates reusable scratch buffers and logits with the loaded model, then reuses them across prompt generation and single-token stepping; stochastic sampling uses a fixed candidate buffer instead of a vocab-sized per-token vector. - Generated result decoding is capped at 64 KiB; byte and BPE decode paths return `OutputBufferExceeded` before replacing `last_result`, and full `generate` failures clear stale token/cache diagnostics. - Runtime diagnostics with tokenizer output, logits summary, selected token, top-k candidates, KV cache length, quantization mode, active sampling configuration, adapter apply count, last adapter checksum, and assembly-state checksum. - Handwritten diagnostics JSON escaping for quotes, backslashes, control characters, line separators, and paragraph separators before browser parsing. - Browser model selector for TinyLM-16M q8_0, TinyLM-16M q4_0, TinyLM-16M f32, f32/q8_0/q4_0 tiny fixtures, the tiny BPE fixture, and the tiny tied-output fixture. - Browser conversation transcript that appends local User and TinyRustLM turns, keeps text insertion DOM-safe, persists across runtime Reset, and clears through the Clear control. - Browser Step Token control that calls `generate_next_token` after generation context exists, appends one decoded token to the response and latest TinyRustLM transcript turn, and records the action in the token console. - Browser product shell footer exposing TinyRustLM, GGUF.MiRust.com, browser-local Rust/WASM identity, and local `.slm` model scope. - Browser smoke tool for headless Chrome or Edge UI verification. - Browser UI audit mode for desktop/mobile structure, local-only notice, footer identity, model controls, panel coverage, diagnostics/developer mirror, benchmark fields, layout overflow, and local-only requests. - Browser smoke and UI audit assertions for transcript state, including empty ready state, disabled Clear button before generation, generated User/TinyRustLM entries, Clear-click transcript removal, and response preservation after clearing history. - Browser UI audit coverage for the model provenance panel, including deterministic-smoke source, runtime-smoke admission, runtime-execution-only quality claim, trained-quality non-claim, checksum, and required next gate. - WASM ABI smoke tool for invalid UTF-8, null pointer, invalid length, recovery-after-error, step-token, adapter apply, and model-free verification. - Visual Studio 2022 solution wrapper in `../TinyRustLM.sln`. The runtime now proves local generation for f32, q8_0, and q4_0 tiny fixtures, a custom BPE tiny fixture with merged token diagnostics, a tied-output tiny fixture without `output.weight`, and real-shaped TinyLM-16M f32, q8_0, and q4_0 models. Quantized runtime storage no longer carries full decoded f32 shadows for q8_0 or q4_0 tensors, and the generation loop uses model-load-time tensor indices instead of per-token layer-name formatting. The runtime can also apply compatible raw `ADP1`, sparse `ASP1`, or low-rank `ALR1` f32-delta packages to already-loaded f32, q8_0, and q4_0 models after validating package checksum, tensor identity, tokenizer checksum, tensor-layout checksum, finite deltas/factors, and fused values; q8_0/q4_0 apply re-quantizes the compact tensor rows or blocks and successful apply clears generation and KV state. Diagnostics now record runtime assembly state: model load seeds a nonzero `assembly_state_checksum`, each accepted adapter increments `adapter_apply_count`, records `last_adapter_checksum`, and folds the package into the assembly checksum, and model free clears the fields. The browser exposes the ADP1/ASP1/ALR1 lane through checked local tiny f32, q8_0, and q4_0 sidecars, `models/tiny-test-model-self.adp1`, `models/tiny-test-model-q8-self.adp1`, and `models/tiny-test-model-q4-self.adp1`, and through generated selector registries that carry compatible f32/q8_0/q4_0 `.adp1`, `.asp1`, or `.alr1` routes whose apply status matches the admitted entry quantization, plus local `.adapter-family.receipt` handles for compatible family sets; JavaScript checks selected artifact checksums before WASM transfer without parsing adapter payloads. The packer can validate and convert raw source-weight bundles into f32, q8_0, and q4_0 artifacts, including BPE source bundles whose token and merge tables become a real `BPE1` `.slm` tokenizer section, and tied source bundles where `tied_output=true` agrees with a tied shape name and conversion sets the v1 tied-output flag. `browser-converted-trained-bundle` now stages one converted source artifact plus provenance, compatibility, lineage, candidate, promotion, runtime, eval, admission, and selector-registry sidecars into a runnable root that the `converted-trained-registry-file` smoke loads from real local files. The packer can also write parent compatibility reports for offline assembly operators, binding each parent to shape, tokenizer checksum, output-head contract, quantization, tensor layout checksum, and `.slm` checksum. Candidate lineage templates then bind a planned candidate to that passing report before any operator writes a `.slm` or adapter artifact. The direct-parameter operator lane now includes `blend-candidate`, which blends compatible tensor values by parts-per-million parent weights, `delta-candidate`, which writes `base + weight * (target - base)` task-vector candidates with signed parts-per-million weights, `sparse-delta-candidate`, which selects the largest absolute target-minus-base deltas, applies the signed task-vector weight to selected entries, leaves other entries at the base value, and records density, nonzero-delta retention, and an implicit top-k mask checksum, and `dare-candidate`, which deterministically drops nonzero task deltas with a seeded SplitMix64 mask, rescales the kept deltas by inverse keep rate, and records mask/raw-delta/rescaled-delta checksums. These commands write normal `.slm` files and receipts that their validators recompute before later gates. The adapter lane now includes `adapter-delta`, which writes an `ADP1` raw f32 task-delta package plus a manifest bound to the same compatibility and lineage checksums, `sparse-adapter-delta`, which writes an `ASP1` sparse f32 task-delta package plus density, retention, and mask checksum manifest fields, `low-rank-adapter-delta`, which writes an `ALR1` low-rank matrix-delta package plus component-limit, factor-density, and residual-L1 manifest fields, `adapter_family` receipt generation inside the browser bundle to bind compatible f32/q8_0/q4_0 ADP1/ASP1/ALR1 sidecar manifests into one selector-carried menu, and `fuse-adapter-delta`, which validates a raw adapter package, adds its deltas to the base parent, writes a normal `.slm` candidate, and records a recomputable fuse receipt. Candidate artifact manifests bind a validated lineage to a validated `.slm` output and prove it still matches the direct-parameter parent contract before eval or promotion. Multi-parent candidate manifests bind validated sign-merge output to its receipt checksum, parent-pool recipe checksum, candidate `.slm` fields, and pending promotion route. Two-parent promotion templates bind candidate manifest checksums, and multi-parent promotion templates bind sign-merge candidate manifest checksums plus receipt checksums; both keep runtime-smoke, eval, browser selector, and public-claim status pending until later evidence exists. Multi-parent admission records then bind the validated sign-merge promotion template to runtime-smoke, provenance, and passed eval evidence. Runtime-smoke sidecars bind local execution proof to provenance manifests, selector admission records bind promotion, runtime-smoke, and passed eval evidence into one browser-selector artifact, promotion ledgers chain admitted records into a deterministic history, population reviews score that history into frontier and parent-pool routes, parent-pool recipes require the reviewed parents to share one direct-parameter contract and assign fitness-normalized seed weights, sign-merge receipts create offline multi-parent candidates from those recipes using seed-weighted sign consensus, and selector registries bind either admission record family to local served model routes with genome/species/novelty/population/mate-selection/phenotype/artifact/fitness provenance. `browser-multi-parent-bundle` now generates runnable f32/q8_0/q4_0 sign-merge TinyRustLM roots with app shell, WASM runtime, evidence files, selector registry, `.slm`, `.slm.manifest`, assembly receipt, self ADP1, family ADP1, sparse ASP1, and low-rank ALR1 sidecars, adapter manifest files, and an adapter-family receipt that the browser smoke loads without interception; the browser smoke also keeps an intercepted q8_0 registry-adapter route to prove fixture selector metadata reaches the same apply path. Generated all-root smokes assert Rust diagnostics report `adapter_apply_count=3` plus nonzero adapter and assembly checksums before generation, while the checked manual sidecar smoke asserts count 1 after apply. The browser selector can consume that registry when present and otherwise keeps the deterministic smoke list for regression coverage. The native eval runner can produce scoped fixture evidence for each converted mode. The project still needs real trained weights and broader review before it can claim product assistant quality. Generated bundle ALR1 stack members now come from reviewed adapter source templates converted through `convert-adapter-source`, so the browser route exercises source-backed ALR1 manifests while still leaving adapter payload validation to Rust. Before generated model bytes are fetched, JavaScript fetches the served `.module-plan.receipt`, recomputes its text checksum, and matches its `browser-constrained-v1` profile, `single-threaded-wasm-local-v1` execution profile, `module_plan_fetch_policy=local-no-store-v1`, `module_plan_origin_policy=same-origin-loopback-local-v1`, `module_plan_fetch_count_limit=32`, resource class, tokenizer checksum, `module_plan_sampler_candidate_cap=1024`, `module_plan_wasm_export_set=tinyrustlm-generate-v1`, admitted context token limit, admitted model byte budget, adapter-family byte budget, `module_plan_runtime_scratch_byte_budget=65536`, `module_plan_prompt_byte_limit=4096`, `module_plan_output_byte_limit=65536`, `module_plan_kv_cache_byte_budget`, `module_plan_kv_cache_page_count`, `module_plan_total_byte_budget`, `module_plan_total_byte_budget_limit=43454464`, model, manifest, assembly receipt, adapter-family receipt, and adapter-stack member routes against the selector entry. The browser also computes the planned generated-root fetch count from the module plan, evidence routes, and adapter stack manifests before fetching generated model bytes. The Module Plan panel renders that verified execution profile, fetch policy, origin policy, fetch limit, tokenizer, sampler cap, WASM ABI, context, scratch budget, prompt limit, output limit, KV budget, KV pages, total budget, and total limit beside the model and adapter budgets, while `module-plan-execution-profile-drift`, `module-plan-fetch-policy-drift`, `module-plan-origin-policy-drift`, `module-plan-fetch-count-drift`, `module-plan-tokenizer-drift`, `module-plan-sampler-cap-drift`, `module-plan-wasm-export-set-drift`, `module-plan-context-token-drift`, `module-plan-runtime-scratch-drift`, `module-plan-prompt-limit-drift`, `module-plan-output-limit-drift`, `module-plan-kv-cache-drift`, `module-plan-total-budget-drift`, and `module-plan-total-limit-drift` prove checksum-consistent execution-profile, fetch-policy, origin-policy, fetch-count, tokenizer, sampler-cap, WASM export-set, context-token, scratch-budget, prompt-limit, output-limit, KV-cache, total-budget, or total-limit drift stops before generated `.slm` or adapter routes. Before generated registry family options are enabled, JavaScript fetches the served `.adapter-family.receipt` and each served `.adp1.manifest`, `.asp1.manifest`, or `.alr1.manifest`, recomputes their text checksums, and matches each member against the selector's route, format-derived manifest kind, checksum, manifest byte-count, and shared base-quantization identity metadata. The receipt also declares the ordered auto-apply stack; JavaScript verifies stack indexes, paths, manifest paths, and aggregate byte budget before fetching and transferring the family ADP1 plus sparse ASP1 plus source-backed low-rank ALR1 packages. It still does not parse adapter bytes; Rust validates ADP1/ASP1/ALR1 browser routes and applies ADP1/ASP1/ALR1 packages after transfer, with `adapter-stack-rust-validate-drift` proving checksum-consistent bytes stop at Rust semantic validation before any `apply_adapter_delta` call. ## Build Commands Native tests: ```powershell cargo test --workspace ``` Strict Rust public API documentation checks: ```powershell cargo rustdoc -p tinyrustlm-runtime --lib -- -D missing_docs cargo rustdoc -p tinyrustlm-slm-pack --bin tinyrustlm-slm-pack -- -D missing_docs cargo rustdoc -p tinyrustlm-local-server --bin tinyrustlm-local-server -- -D missing_docs cargo rustdoc -p tinyrustlm-browser-harness --bin tinyrustlm-browser-harness -- -D missing_docs ``` WASM build: ```powershell rustup target add wasm32-unknown-unknown cargo build -p tinyrustlm-runtime --release --target wasm32-unknown-unknown Copy-Item .\target\wasm32-unknown-unknown\release\tinyrustlm_runtime.wasm .\tinyrustlm\runtime\tinyrustlm.wasm cargo run -p tinyrustlm-slm-pack -- runtime-wasm-manifest .\tinyrustlm\runtime\tinyrustlm.wasm .\tinyrustlm\runtime\tinyrustlm.wasm.manifest ``` Model packing: ```powershell cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tiny-test-model.slm tiny-fixture cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tiny-test-model-q8.slm tiny-fixture-q8 cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tiny-test-model-q4.slm tiny-fixture-q4 cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tiny-test-model-bpe.slm tiny-fixture-bpe cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tiny-test-model-tied.slm tiny-fixture-tied cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tinylm16-f32.slm tinylm16-f32 cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tinylm16-q8.slm tinylm16-q8 cargo run -p tinyrustlm-slm-pack -- .\tinyrustlm\models\tinylm16-q4.slm tinylm16-q4 ``` Model validation and provenance: ```powershell cargo run -p tinyrustlm-slm-pack -- validate .\tinyrustlm\models\tinylm16-q8.slm cargo run -p tinyrustlm-slm-pack -- compatibility .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-self.compat cargo run -p tinyrustlm-slm-pack -- lineage-template .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage tinylm16-q8-self-candidate identity-parent-set browser-local-16m-budget cargo run -p tinyrustlm-slm-pack -- validate-lineage .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage cargo run -p tinyrustlm-slm-pack -- blend-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.operator cargo run -p tinyrustlm-slm-pack -- validate-blend-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.operator cargo run -p tinyrustlm-slm-pack -- delta-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-delta.slm .\target\model-breeding\tinylm16-q8-delta.operator 1000000 cargo run -p tinyrustlm-slm-pack -- validate-delta-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-delta.slm .\target\model-breeding\tinylm16-q8-delta.operator cargo run -p tinyrustlm-slm-pack -- sparse-delta-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-sparse-delta.slm .\target\model-breeding\tinylm16-q8-sparse-delta.operator 1000000 250000 cargo run -p tinyrustlm-slm-pack -- validate-sparse-delta-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-sparse-delta.slm .\target\model-breeding\tinylm16-q8-sparse-delta.operator cargo run -p tinyrustlm-slm-pack -- dare-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-dare.slm .\target\model-breeding\tinylm16-q8-dare.operator 1000000 500000 29 cargo run -p tinyrustlm-slm-pack -- validate-dare-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8-dare.slm .\target\model-breeding\tinylm16-q8-dare.operator cargo run -p tinyrustlm-slm-pack -- adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.delta .\target\model-breeding\tinylm16-q8.adapter.delta.manifest cargo run -p tinyrustlm-slm-pack -- validate-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.delta .\target\model-breeding\tinylm16-q8.adapter.delta.manifest cargo run -p tinyrustlm-slm-pack -- sparse-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.sparse.asp1 .\target\model-breeding\tinylm16-q8.adapter.sparse.asp1.manifest 1000000 250000 cargo run -p tinyrustlm-slm-pack -- validate-sparse-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.sparse.asp1 .\target\model-breeding\tinylm16-q8.adapter.sparse.asp1.manifest cargo run -p tinyrustlm-slm-pack -- low-rank-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.lowrank.alr1 .\target\model-breeding\tinylm16-q8.adapter.lowrank.alr1.manifest 1 cargo run -p tinyrustlm-slm-pack -- validate-low-rank-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.lowrank.alr1 .\target\model-breeding\tinylm16-q8.adapter.lowrank.alr1.manifest cargo run -p tinyrustlm-slm-pack -- fuse-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.delta .\target\model-breeding\tinylm16-q8.adapter.delta.manifest .\target\model-breeding\tinylm16-q8-adapter-fused.slm .\target\model-breeding\tinylm16-q8-adapter-fuse.operator cargo run -p tinyrustlm-slm-pack -- validate-fuse-adapter-delta .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm .\target\model-breeding\tinylm16-q8.adapter.delta .\target\model-breeding\tinylm16-q8.adapter.delta.manifest .\target\model-breeding\tinylm16-q8-adapter-fused.slm .\target\model-breeding\tinylm16-q8-adapter-fuse.operator cargo run -p tinyrustlm-slm-pack -- sign-merge-candidate .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- validate-sign-merge-candidate .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- multi-parent-candidate-manifest .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- validate-multi-parent-candidate .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- multi-parent-promotion-template .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate .\target\model-breeding\parent-pool-sign-merge.promotion --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- validate-multi-parent-promotion .\target\model-breeding\population.ledger .\target\model-breeding\population.review .\target\model-breeding\parent-pool.recipe .\target\model-breeding\parent-pool-sign-merge.slm .\target\model-breeding\parent-pool-sign-merge.operator .\target\model-breeding\parent-pool-sign-merge.candidate .\target\model-breeding\parent-pool-sign-merge.promotion --parents .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm --admissions .\target\model-breeding\frontier.admission .\target\model-breeding\pool.admission cargo run -p tinyrustlm-slm-pack -- candidate-manifest .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-self.candidate cargo run -p tinyrustlm-slm-pack -- validate-candidate .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-self.candidate cargo run -p tinyrustlm-slm-pack -- promotion-template .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-self.candidate .\target\model-breeding\tinylm16-q8-self.promotion local-smoke-runner browser-local-runtime-smoke-and-eval cargo run -p tinyrustlm-slm-pack -- validate-promotion .\target\model-breeding\tinylm16-q8-self.compat .\target\model-breeding\tinylm16-q8-self.lineage .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-self.candidate .\target\model-breeding\tinylm16-q8-self.promotion cargo run -p tinyrustlm-slm-pack -- manifest .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.slm.manifest deterministic-smoke cargo run -p tinyrustlm-slm-pack -- validate-manifest .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.slm.manifest cargo run -p tinyrustlm-slm-pack -- quality-gate .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.slm.manifest runtime-smoke cargo run -p tinyrustlm-slm-pack -- runtime-smoke .\target\model-breeding\tinylm16-q8-blend.slm .\target\model-breeding\tinylm16-q8-blend.slm.manifest .\target\model-breeding\tinylm16-q8-blend.runtime cargo run -p tinyrustlm-slm-pack -- eval-template .\tinyrustlm\models\tinylm16-q8.slm .\tinyrustlm\models\tinylm16-q8.slm.manifest .\tinyrustlm\models\tinylm16-q8.slm.eval assistant-quality ``` The validator is a native no-crate admission gate for generated or future converted `.slm` files. It checks header bounds, checksum, byte-tokenizer metadata, required tensor names and shapes, dtype-specific payload lengths, quantization scale ranges, finite f32 payload values, and reports the model shape, tensor count, parameter count, quantization mode, and checksum. The compatibility command is the first parent-set gate for modular model assembly. It validates both `.slm` files, then writes a line-based report with parent checksums, shape, tokenizer checksum, tensor layout checksum, quantization, and output-head contract. A direct-parameter parent set passes only when those contracts match exactly; otherwise the report routes the pair through source conversion or distillation before any future candidate artifact is promoted. The lineage-template command is the second assembly bead. It accepts only a passing compatibility report, writes a planned candidate manifest with parent checksums, operator id, resource budget, compatibility report checksum, and pending candidate artifact fields, then `validate-lineage` proves the lineage file still matches its parent report. The direct-parameter operator command is the third assembly bead. `blend-candidate` accepts a passing compatibility report, a validated lineage, two parent `.slm` files whose checksums match the report, and a parent-0 weight in parts per million. `delta-candidate` accepts the same gate inputs, treats parent 0 as the base and parent 1 as the target, then writes `base + weight * (target - base)` using signed parts-per-million task-vector weights. `sparse-delta-candidate` uses the same base/target contract, selects the largest absolute target-minus-base deltas by keep rate, applies the signed task-vector weight only to selected entries, and records total, nonzero, selected, pruned, unchanged, density, nonzero-delta retention, and implicit top-k mask checksum fields. `dare-candidate` uses the same base/target contract, selects nonzero deltas with a deterministic seeded dropout mask, rescales kept deltas by inverse keep rate, and records total, nonzero, selected, dropped, unchanged, density, nonzero retention, dropout seed, mask checksum, raw delta checksum, and rescaled delta checksum fields. Each operator writes a normal `.slm` candidate plus a receipt that records compatibility checksum, lineage checksum, parent checksums, operator weights, candidate checksum, and the next candidate-manifest gate. `validate-blend-candidate`, `validate-delta-candidate`, `validate-sparse-delta-candidate`, and `validate-dare-candidate` recompute candidate bytes and receipts before an artifact can move forward. The adapter-delta commands are the parallel adapter assembly bead. `adapter-delta` accepts the same passing compatibility report, validated lineage, and base/target parents, then writes an `ADP1` binary package containing raw f32 tensor deltas in parent tensor order plus a line-based manifest with parent checksums, lineage checksum, tensor layout checksum, tokenizer checksum, adapter checksum, and next gate. `sparse-adapter-delta` writes an `ASP1` sparse f32 task-delta package with sorted `(value_index, delta)` pairs plus density, retention, and sparse mask checksum fields. `low-rank-adapter-delta` writes an `ALR1` low-rank matrix-delta package with deterministic cross-residual factors plus component-limit, factor-density, active-matrix, and residual-L1 manifest fields. `validate-adapter-delta`, `validate-sparse-adapter-delta`, and `validate-low-rank-adapter-delta` recompute the packages and manifests from the parents. `fuse-adapter-delta` validates a raw adapter package, fuses it into a normal `.slm` candidate with the base parent's dtype/layout, and writes an adapter-fuse receipt that `validate-fuse-adapter-delta` recomputes before candidate-manifest. Trained adapter source intake is the source-side companion for that lane. `adapter-source-template` writes a reviewable `adapter-source.manifest` plus raw little-endian f32 low-rank factor files under `factors/`; `validate-adapter-source` verifies the model shape, tied-output contract, target tensor names and hashes, factor ranks, safe relative factor paths, byte counts, checksums, finite bounded factor values, factor parameter counts, and reconstructed delta L1 fields. This gives future trained LoRA-style modules a durable source format before any package is converted into runtime `ALR1` bytes or attached to browser assembly evidence. The sign-merge command is the reviewed-population assembly bead. It accepts a validated parent-pool recipe plus the matching promotion ledger, population review, admission records, and parent `.slm` files. Parent 0 is the frontier base; the other parents cast seed-weighted positive and negative delta votes for each parameter. `sign-merge-candidate` keeps the base value on ties, otherwise applies the winning sign's weighted average delta, writes a normal `.slm`, and records recipe, relatedness metric/scope/pair count/checksum, ledger, review, admission, parent, sign-count, candidate checksum, and multi-parent candidate-manifest fields. `validate-sign-merge-candidate` recomputes candidate bytes and receipt before `multi-parent-candidate-manifest` binds the result to its receipt checksum, recipe checksum, relatedness summary, candidate `.slm` fields, and pending promotion route. `multi-parent-promotion-template` then binds that validated candidate manifest to pending runtime-smoke and eval status for the sign-merge path. The candidate-manifest command is the fourth assembly bead. It accepts only a validated lineage and a `.slm` artifact that passes native admission and matches the direct-parameter parent contract, then writes candidate checksum, shape, tokenizer checksum, tensor layout checksum, admission status, pending eval status, and the next promotion gate. `validate-candidate` proves the manifest still matches compatibility, lineage, and the candidate artifact. The promotion-template command is the fifth assembly bead. It accepts only a validated candidate artifact manifest, records the candidate manifest checksum, keeps runtime-smoke and eval statuses pending, and keeps browser selector plus public-claim admission closed until later promotion evidence exists. `validate-promotion` proves the promotion sidecar still matches compatibility, lineage, candidate, and candidate manifest inputs. The runtime-smoke command is the sixth assembly bead. It writes a line-based sidecar bound to the provenance manifest checksum, `.slm` checksum, source kind, model shape, and runtime-smoke decision. `admission-record` is the seventh bead: it accepts only a valid promotion template, a valid runtime-smoke sidecar, and a passed converted-trained eval sidecar, then records selector admission with public claims still bound to the declared eval scope. `promotion-ledger` is the eighth bead: it accepts admitted records, rejects duplicates, and writes a hash-chained promotion history for selector or population review. `population-review` is the ninth bead: it validates that ledger against the same admission records, ranks candidates by quality, artifact frugality, and quantization fit, writes a `fitness_objective_vector_*` contract plus per-entry objective checksums, marks the frontier candidate, and routes remaining candidates to the parent pool. `parent-pool-recipe` is the tenth bead: it validates the population review, requires a shared direct-parameter contract across selected parents, records fitness-normalized seed weights, and writes relatedness metric/scope/pair count/checksum plus per-parent relatedness group fields for sign-aware merge work. `sign-merge-candidate` is the eleventh bead: it validates that recipe and writes an offline multi-parent `.slm` candidate plus receipt that echoes the relatedness fields. `multi-parent-candidate-manifest` is the twelfth bead for that path: it validates the sign-merge receipt and writes the candidate manifest with the relatedness summary. `multi-parent-promotion-template` is the thirteenth bead for that path: it binds the candidate manifest checksum, receipt checksum, recipe checksum, parent count, and candidate `.slm` fields before runtime-smoke, eval, admission, ledger, and selector routing. `multi-parent-admission-record` is the fourteenth bead for that path: it binds the validated sign-merge promotion evidence to provenance, runtime-smoke, and passed eval sidecars. `selector-registry` remains the served-model route bead: it accepts selector admission records or multi-parent admission records whose candidate artifact path resolves under served `tinyrustlm/models/`, then writes a browser route such as `../models/admitted-q8.slm` plus genome/species/novelty/population/mate-selection/phenotype/artifact/fitness provenance. Registry generation is intentionally a served-model step. A converted candidate that lives only under `target/` can be admitted for evidence, but it enters a selector registry only after the admitted `.slm` and `.slm.manifest` are staged under the local `tinyrustlm/models/` route used by the browser server. The manifest sidecar is line-based, not JSON. It binds model byte count, `.slm` checksum, shape, tensor count, parameter count, quantization mode, source kind, admission status, and quality boundary. Current artifacts use `source_kind=deterministic-smoke`, `quality_claim=runtime-execution-smoke-only`, and `trained_quality_claim=not-claimed`. The browser app displays this sidecar in the Model Provenance panel after Rust accepts the selected `.slm` model, keeping the trained-quality boundary visible in the local UI. The quality gate is also line-based and no-crate. `quality-gate ... runtime-smoke` admits deterministic smoke or converted-trained artifacts only for runtime execution evidence. `quality-gate ... assistant-quality ` requires `source_kind=converted-trained`, a matching model checksum, a matching manifest checksum, passed task evaluation, declared quality scope, and `quality_decision=accepted-for-assistant-quality`. `eval-template` writes a bound pending template; pending templates intentionally fail `assistant-quality` until reviewed evidence replaces the placeholder fields. Trained source conversion: ```powershell cargo run -p tinyrustlm-slm-pack -- adapter-source-template .\target\trained-source-smoke\adapter-source-tiny tiny-fixture cargo run -p tinyrustlm-slm-pack -- validate-adapter-source .\target\trained-source-smoke\adapter-source-tiny cargo run -p tinyrustlm-slm-pack -- source-template .\tinyrustlm\tests\fixtures\trained-source-tiny tiny-fixture cargo run -p tinyrustlm-slm-pack -- validate-source .\tinyrustlm\tests\fixtures\trained-source-tiny cargo run -p tinyrustlm-slm-pack -- convert-trained .\tinyrustlm\tests\fixtures\trained-source-tiny .\target\trained-source-smoke\tiny-converted-f32.slm f32 cargo run -p tinyrustlm-slm-pack -- convert-trained .\tinyrustlm\tests\fixtures\trained-source-tiny .\target\trained-source-smoke\tiny-converted-q8.slm q8_0 cargo run -p tinyrustlm-slm-pack -- convert-trained .\tinyrustlm\tests\fixtures\trained-source-tiny .\target\trained-source-smoke\tiny-converted-q4.slm q4_0 cargo run -p tinyrustlm-slm-pack -- source-template .\target\trained-source-smoke\source-tiny-tied tiny-fixture-tied cargo run -p tinyrustlm-slm-pack -- validate-source .\target\trained-source-smoke\source-tiny-tied cargo run -p tinyrustlm-slm-pack -- convert-trained .\target\trained-source-smoke\source-tiny-tied .\target\trained-source-smoke\tiny-tied-converted-f32.slm f32 cargo run -p tinyrustlm-slm-pack -- convert-trained .\target\trained-source-smoke\source-tiny-tied .\target\trained-source-smoke\tiny-tied-converted-q8.slm q8_0 cargo run -p tinyrustlm-slm-pack -- convert-trained .\target\trained-source-smoke\source-tiny-tied .\target\trained-source-smoke\tiny-tied-converted-q4.slm q4_0 cargo run -p tinyrustlm-slm-pack -- source-template .\target\trained-source-smoke\source-tiny-bpe tiny-fixture-bpe cargo run -p tinyrustlm-slm-pack -- validate-source .\target\trained-source-smoke\source-tiny-bpe cargo run -p tinyrustlm-slm-pack -- convert-trained .\target\trained-source-smoke\source-tiny-bpe .\target\trained-source-smoke\tiny-bpe-converted-q8.slm q8_0 cargo run -p tinyrustlm-slm-pack -- quality-gate .\target\trained-source-smoke\tiny-converted-q8.slm .\target\trained-source-smoke\tiny-converted-q8.slm.manifest runtime-smoke cargo run -p tinyrustlm-slm-pack -- runtime-smoke .\target\trained-source-smoke\tiny-converted-q8.slm .\target\trained-source-smoke\tiny-converted-q8.slm.manifest .\target\trained-source-smoke\tiny-converted-q8.runtime cargo run -p tinyrustlm-runtime --bin tinyrustlm-eval -- .\target\trained-source-smoke\tiny-converted-q8.slm .\target\trained-source-smoke\tiny-converted-q8.slm.manifest .\tinyrustlm\tests\fixtures\assistant-quality-eval-cases.txt .\target\trained-source-smoke\tiny-converted-q8.eval cargo run -p tinyrustlm-slm-pack -- quality-gate .\target\trained-source-smoke\tiny-converted-q8.slm .\target\trained-source-smoke\tiny-converted-q8.slm.manifest assistant-quality .\target\trained-source-smoke\tiny-converted-q8.eval ``` Converted-trained candidates can produce selector admission records after the model-breeding sidecars exist: ```powershell cargo run -p tinyrustlm-slm-pack -- compatibility .\target\trained-source-smoke\tiny-converted-q8.slm .\target\trained-source-smoke\tiny-converted-q8.slm .\target\admission-smoke\tiny-converted-q8.compat cargo run -p tinyrustlm-slm-pack -- lineage-template .\target\admission-smoke\tiny-converted-q8.compat .\target\admission-smoke\tiny-converted-q8.lineage tiny-converted-q8-self direct-self-fit browser-local-constrained cargo run -p tinyrustlm-slm-pack -- candidate-manifest .\target\admission-smoke\tiny-converted-q8.compat .\target\admission-smoke\tiny-converted-q8.lineage .\target\trained-source-smoke\tiny-converted-q8.slm .\target\admission-smoke\tiny-converted-q8.candidate cargo run -p tinyrustlm-slm-pack -- promotion-template .\target\admission-smoke\tiny-converted-q8.compat .\target\admission-smoke\tiny-converted-q8.lineage .\target\trained-source-smoke\tiny-converted-q8.slm .\target\admission-smoke\tiny-converted-q8.candidate .\target\admission-smoke\tiny-converted-q8.promotion local-smoke-runner browser-local-runtime-smoke-and-eval cargo run -p tinyrustlm-slm-pack -- admission-record .\target\admission-smoke\tiny-converted-q8.compat .\target\admission-smoke\tiny-converted-q8.lineage .\target\trained-source-smoke\tiny-converted-q8.slm .\target\admission-smoke\tiny-converted-q8.candidate .\target\admission-smoke\tiny-converted-q8.promotion .\target\trained-source-smoke\tiny-converted-q8.slm.manifest .\target\trained-source-smoke\tiny-converted-q8.runtime .\target\trained-source-smoke\tiny-converted-q8.eval .\target\admission-smoke\tiny-converted-q8.admission browser-local-selector cargo run -p tinyrustlm-slm-pack -- validate-admission .\target\admission-smoke\tiny-converted-q8.compat .\target\admission-smoke\tiny-converted-q8.lineage .\target\trained-source-smoke\tiny-converted-q8.slm .\target\admission-smoke\tiny-converted-q8.candidate .\target\admission-smoke\tiny-converted-q8.promotion .\target\trained-source-smoke\tiny-converted-q8.slm.manifest .\target\trained-source-smoke\tiny-converted-q8.runtime .\target\trained-source-smoke\tiny-converted-q8.eval .\target\admission-smoke\tiny-converted-q8.admission cargo run -p tinyrustlm-slm-pack -- promotion-ledger .\target\admission-smoke\tiny-converted-q8.ledger .\target\admission-smoke\tiny-converted-q8.admission cargo run -p tinyrustlm-slm-pack -- validate-promotion-ledger .\target\admission-smoke\tiny-converted-q8.ledger .\target\admission-smoke\tiny-converted-q8.admission cargo run -p tinyrustlm-slm-pack -- population-review .\target\admission-smoke\tiny-converted-q8.ledger .\target\admission-smoke\tiny-converted-q8.population .\target\admission-smoke\tiny-converted-q8.admission cargo run -p tinyrustlm-slm-pack -- validate-population-review .\target\admission-smoke\tiny-converted-q8.ledger .\target\admission-smoke\tiny-converted-q8.population .\target\admission-smoke\tiny-converted-q8.admission cargo run -p tinyrustlm-slm-pack -- parent-pool-recipe .\target\admission-smoke\tiny-converted-q8.ledger .\target\admission-smoke\tiny-converted-q8.population .\target\admission-smoke\tiny-converted-q8.parents .\target\admission-smoke\tiny-converted-q8.admission cargo run -p tinyrustlm-slm-pack -- validate-parent-pool-recipe .\target\admission-smoke\tiny-converted-q8.ledger .\target\admission-smoke\tiny-converted-q8.population .\target\admission-smoke\tiny-converted-q8.parents .\target\admission-smoke\tiny-converted-q8.admission cargo run -p tinyrustlm-slm-pack -- selector-registry .\target\selector-smoke\selector.registry .\target\selector-smoke\admitted-q8.admission cargo run -p tinyrustlm-slm-pack -- validate-selector-registry .\target\selector-smoke\selector.registry .\target\selector-smoke\admitted-q8.admission ``` The source layout is line metadata plus raw little-endian f32 tensor files under `tensors/`. Validation requires safe relative paths, exact byte counts, matching source checksums, expected tensor names and shapes, finite f32 values, bounded absolute weights, nonzero tensor payloads, agreement between `model_shape` and `tied_output`, and agreement between BPE shape names and `tokenizer=bpe-v1`. BPE source bundles declare token and merge records directly in `source.manifest`; conversion writes those records into the `.slm` tokenizer section. Tied source bundles omit `output.weight` and converted `.slm` artifacts carry the v1 tied-output flag. `convert-trained` writes a converted-trained manifest automatically. The standing unit and Visual Studio gates convert the fixture to f32, q8_0, and q4_0 so each advertised output mode is admitted directly; tied-output source conversion is smoke-gated across f32, q8_0, and q4_0, and BPE source conversion is smoke-gated for q8_0. `tinyrustlm-eval` runs exact fixture cases through the runtime and writes a scoped eval sidecar. The checked-in cases prove only `tiny-converted-source-fixture-only`, not product assistant quality. Local static server using the no-crate Rust server: ```powershell cargo run -p tinyrustlm-local-server -- .\tinyrustlm 8080 ``` Rust mini browser contract harness: ```powershell cargo run -p tinyrustlm-browser-harness -- .\tinyrustlm cargo run -p tinyrustlm-browser-harness -- .\tinyrustlm --http http://127.0.0.1:8080/app/ ``` The legacy Node server remains available for comparison or ad hoc tool checks: ```powershell node .\tinyrustlm\tools\static-server.js .\tinyrustlm 8080 ``` Browser smoke verification: ```powershell node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9225 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9226 tinylm16q4 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9227 tinylm16q8 loop node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9228 tinylm16q8 model-error node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9229 tinylm16q8 context-error node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9230 tinylm16q8 missing-model node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9231 tinylm16q8 endurance 3 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9232 tinylm16q8 performance 4 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9233 tinylm16q8 performance-soak 3 4 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9234 tinylm16q8 ui-audit node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9235 tinylm16q8 step-token node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9236 multi-parent-sign-merge-q8 multi-parent-registry node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9266 tinylm16-blend-q8 blend-operator-registry node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9267 tinylm16q8 blend-operator-receipt-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9268 tinylm16-delta-q8 delta-operator-registry node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9269 tinylm16q8 delta-operator-receipt-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9270 tinylm16-sparse-delta-q8 sparse-delta-operator-registry node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9271 tinylm16q8 sparse-delta-operator-receipt-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9272 tinylm16-dare-q8 dare-operator-registry node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9273 tinylm16q8 dare-operator-receipt-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9260 tinylm16-prune-q8 prune-operator-registry node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9261 tinylm16q8 prune-operator-receipt-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9262 tinylm16-crossover-q8 crossover-operator-registry node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9263 tinylm16q8 crossover-operator-receipt-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9264 tinylm16-mutation-q8 mutation-operator-registry node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9265 tinylm16q8 mutation-operator-receipt-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9238 tinyf32 adapter-sidecar node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9240 tinyq8 adapter-sidecar node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9241 tinyq4 adapter-sidecar node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9242 tinyq8 adapter-sidecar-registry-q8 cargo run -p tinyrustlm-slm-pack -- browser-converted-trained-bundle .\target\browser-converted-trained-file\tinyrustlm .\tinyrustlm\tests\fixtures\trained-source-tiny all cargo run -p tinyrustlm-local-server -- .\target\browser-converted-trained-file\tinyrustlm 8096 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8096/app/ 9290 converted-trained-q4 converted-trained-registry-file node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8096/app/ 9291 converted-trained-q8 converted-trained-registry-file node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8096/app/ 9292 converted-trained-f32 converted-trained-registry-file cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-multi-parent\tinyrustlm cargo run -p tinyrustlm-local-server -- .\target\browser-served-multi-parent\tinyrustlm 8090 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8090/app/ 9237 multi-parent-sign-merge-f32 multi-parent-registry-file node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8090/app/ 9239 multi-parent-sign-merge-f32 adapter-sidecar-registry-file cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-multi-parent-q8\tinyrustlm q8_0 cargo run -p tinyrustlm-local-server -- .\target\browser-served-multi-parent-q8\tinyrustlm 8093 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8093/app/ 9243 multi-parent-sign-merge-q8 adapter-sidecar-registry-file cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-multi-parent-q4\tinyrustlm q4_0 cargo run -p tinyrustlm-local-server -- .\target\browser-served-multi-parent-q4\tinyrustlm 8094 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8094/app/ 9244 multi-parent-sign-merge-q4 adapter-sidecar-registry-file node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8094/app/ 9245 multi-parent-sign-merge-q4 adapter-stack-rust-validate-drift cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-multi-parent-all\tinyrustlm all cargo run -p tinyrustlm-local-server -- .\target\browser-served-multi-parent-all\tinyrustlm 8095 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9246 multi-parent-sign-merge-q4 combined-selector-cycle 2 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9247 multi-parent-sign-merge-q4 combined-selector-route-soak 3 node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9248 multi-parent-sign-merge-q4 combined-selector-route-extended-soak node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9249 multi-parent-sign-merge-q4 combined-selector-route-stress-soak node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9250 multi-parent-sign-merge-q4 module-plan-profile-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9251 multi-parent-sign-merge-q4 module-plan-execution-profile-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9252 multi-parent-sign-merge-q4 module-plan-fetch-policy-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9253 multi-parent-sign-merge-q4 module-plan-origin-policy-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9254 multi-parent-sign-merge-q4 module-plan-runtime-scratch-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9255 multi-parent-sign-merge-q4 module-plan-kv-cache-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9256 multi-parent-sign-merge-q4 module-plan-context-token-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9257 multi-parent-sign-merge-q4 module-plan-tokenizer-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9258 multi-parent-sign-merge-q4 module-plan-sampler-cap-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9259 multi-parent-sign-merge-q4 module-plan-count-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9260 multi-parent-sign-merge-q4 module-plan-total-budget-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9261 multi-parent-sign-merge-q4 module-plan-total-limit-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9262 multi-parent-sign-merge-q4 module-plan-wasm-export-set-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9263 multi-parent-sign-merge-q4 module-plan-prompt-limit-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8095/app/ 9264 multi-parent-sign-merge-q4 module-plan-fetch-count-drift node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8080/app/ 9265 tinylm16q8 prompt-limit ``` The combined selector cycle keeps one generated `all` root open, repeats q4_0/q8_0/f32 selection, releases the prior WASM model before each post-initial assembly, and proves each new entry validates and applies its ADP1/ASP1/ALR1 stack before generation. The route-soak smoke also requires each generated module-plan, model, manifest, assembly, evidence, adapter-family, adapter manifest, and ADP1/ASP1/ALR1 stack route to be requested once per pass; the app fetches local assembly resources with no-store cache behavior for that proof. The extended route-soak smoke raises that browser proof to five q4_0/q8_0/f32 cycles, so one page must complete fifteen generated assemblies with fresh route requests. The stress route-soak smoke raises the same proof to eight q4_0/q8_0/f32 cycles, so one page must complete twenty-four generated assemblies with fresh route requests. The profile-drift smoke keeps the selector checksum aligned with a mutated module-plan receipt and proves the browser stops before generated model or adapter routes when `module_plan_profile` is not `browser-constrained-v1`. The execution-profile drift smoke keeps the selector checksum aligned with a mutated module-plan receipt and proves the browser stops before generated model or adapter routes when `module_plan_execution_profile` is not `single-threaded-wasm-local-v1`. The fetch-policy drift smoke keeps the selector checksum aligned with a mutated module-plan receipt and proves the browser stops before generated model or adapter routes when `module_plan_fetch_policy` is not `local-no-store-v1`. The fetch-count drift smoke keeps the selector checksum aligned with a mutated module-plan receipt and proves the browser stops before generated model or adapter routes when `module_plan_fetch_count_limit` diverges from the selector-owned browser route-count envelope. The count-drift smoke keeps the selector checksum aligned with a mutated module-plan receipt and proves the browser stops before generated model or adapter routes when receipt `module_count` diverges from selector `module_plan_module_count`. The context-token drift smoke keeps the selector checksum aligned with a mutated module-plan receipt and proves the browser stops before generated model or adapter routes when `module_plan_context_token_limit` diverges from the admitted model shape. The tokenizer drift smoke keeps the selector checksum aligned with a mutated module-plan receipt and proves the browser stops before generated model or adapter routes when `module_plan_tokenizer_checksum` diverges from the admitted model tokenizer checksum. The sampler-cap drift smoke keeps the selector checksum aligned with a mutated module-plan receipt and proves the browser stops before generated model or adapter routes when `module_plan_sampler_candidate_cap` diverges from the fixed-buffer sampler envelope. The WASM export-set drift smoke keeps the selector checksum aligned with a mutated module-plan receipt and proves the browser stops before generated model or adapter routes when `module_plan_wasm_export_set` is not `tinyrustlm-generate-v1`. The prompt-limit drift smoke keeps the selector checksum aligned with a mutated module-plan receipt and proves the browser stops before generated model or adapter routes when `module_plan_prompt_byte_limit` diverges from the 4096-byte prompt envelope; source-root `prompt-limit` proves oversized prompt bytes are stopped before WASM prompt transfer. The KV-cache drift smoke keeps the selector checksum aligned with a mutated module-plan receipt and proves the browser stops before generated model or adapter routes when `module_plan_kv_cache_page_count` diverges from the selector-owned cache envelope. The total-limit drift smoke keeps the selector checksum aligned with a mutated module-plan receipt and proves the browser stops before generated model or adapter routes when `module_plan_total_byte_budget_limit` diverges from the selector-owned browser cap. WASM ABI boundary smoke: ```powershell node .\tinyrustlm\tools\wasm-abi-smoke.js ``` The ABI smoke also checks `set_sampling_config`, rejects invalid stochastic settings, restores greedy defaults, verifies diagnostics still report `temperature=0`, `top_k=1`, `top_p=1`, and `seed=1` after recovery generation, requires `generate_next_token` to return an explicit `ErrorCode` while exposing token text through `last_result`, validates a zero-delta f32 `ADP1` package through `validate_adapter_delta`, applies the same package through `apply_adapter_delta`, and requires `free_model` to clear loaded-model diagnostics before later generation returns `ModelNotLoaded`. Unit tests also cover sparse `ASP1` and low-rank `ALR1` adapter apply on loaded tensors across the current f32/q8_0/q4_0 boundary. Unit tests cover the 64 KiB generated-result cap for byte and BPE decode paths plus runtime `OutputBufferExceeded` diagnostics. The browser runtime ships only static HTML, CSS, JS, WASM, local `.slm` files, and checked tiny f32/q8_0/q4_0 `ADP1` sidecars. The current browser milestone defaults to `tinylm16-q8.slm` and keeps TinyLM-16M q4_0, f32, tiny byte-tokenizer fixtures, the tiny BPE fixture, the tiny tied-output fixture, and tiny f32/q8_0/q4_0 adapter routes available for regression checks. ## Current Fixture Behavior The tiny fixture is intentionally deterministic. Prompt `hi` generates local byte tokens that decode to: ```text eeeeeeeeeeeee ``` Diagnostics show `argmax=101`, selected token `101`, and active quantization mode `f32`, `q8_0`, or `q4_0` depending on the selected fixture. The TinyLM-16M f32, q8_0, and q4_0 fixtures are also deterministic. Prompt `hi` with `max_new_tokens=1` generates: ```text e ``` ## Current Local Server Start a local static server with: ```text cargo run -p tinyrustlm-local-server -- .\tinyrustlm 8080 ``` The Visual Studio F5 wrapper verifies whether a running server is actually TinyRustLM before reusing it. If port 8080 is occupied by another local service, the wrapper starts the Rust static server on the next free loopback port and opens that URL. ## Visual Studio Open `..\TinyRustLM.sln` in Visual Studio 2022. `Build Solution` invokes `tools/vs/Build-TinyRustLM.ps1`; `F5` invokes `tools/vs/Run-TinyRustLM.ps1`, reuses a verified TinyRustLM server or starts the local static server, and opens the app. The Visual Studio test helper can run browser hardening checks: ```powershell .\tools\vs\Test-TinyRustLM.ps1 -BrowserSmoke .\tools\vs\Test-TinyRustLM.ps1 -PerformanceSoak -PerformanceSoakCycles 3 -PerformanceSoakTokens 4 ``` ================================================================================ END FILE: tinyrustlm/README.md ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/Cargo.toml BYTES: 247 SHA256: 4A2A1F84E6DA1AFA204B4D6ECB984EA5A69238B023A5F39665330671E2E01E84 ================================================================================ [package] name = "tinyrustlm-runtime" version.workspace = true edition.workspace = true license.workspace = true authors.workspace = true repository.workspace = true [lib] crate-type = ["cdylib", "rlib"] [dependencies] [lints] workspace = true ================================================================================ END FILE: tinyrustlm/runtime/Cargo.toml ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/adapter.rs BYTES: 19168 SHA256: E45628BE16C7758C3A60C190FF866732A03BC442556BD35D81BD183D64B26DF6 ================================================================================ //! Runtime parser for adapter-delta packages. use crate::errors::ErrorCode; use crate::model_format::TensorEntry; const RAW_MAGIC: &[u8; 4] = b"ADP1"; const SPARSE_MAGIC: &[u8; 4] = b"ASP1"; const LOW_RANK_MAGIC: &[u8; 4] = b"ALR1"; const VERSION: u32 = 1; const HEADER_LEN: usize = 64; const ENTRY_LEN: usize = 64; const CHECKSUM_OFFSET: usize = 56; const SPARSE_PAIR_LEN: usize = 12; const LOW_RANK_HEADER_LEN: usize = 16; const LOW_RANK_MAX_COMPONENTS: usize = 8; /// Identity values the adapter package must match before it can be applied. pub(crate) struct AdapterExpected<'a> { pub(crate) flags: u32, pub(crate) tensors: &'a [TensorEntry], pub(crate) parameter_count: u64, pub(crate) tensor_layout_checksum: u64, pub(crate) tokenizer_checksum: u64, } /// Validated adapter payload ranges, aligned to the model tensor directory order. pub(crate) struct AdapterDelta { entries: Vec, } struct AdapterDeltaEntry { byte_offset: usize, element_count: usize, kind: AdapterDeltaPayloadKind, } impl AdapterDelta { /// Parses and validates an adapter package for a loaded model identity. pub(crate) fn parse(bytes: &[u8], expected: &AdapterExpected<'_>) -> Result { let format = validate_adapter_bytes(bytes)?; let tensor_count = read_u32(bytes, 12)? as usize; if tensor_count != expected.tensors.len() { return Err(ErrorCode::ShapeMismatch); } if read_u32(bytes, 16)? != expected.flags { return Err(ErrorCode::ShapeMismatch); } if read_u64(bytes, 24)? != expected.parameter_count { return Err(ErrorCode::ShapeMismatch); } if read_u64(bytes, 32)? != expected.tensor_layout_checksum { return Err(ErrorCode::ShapeMismatch); } if read_u64(bytes, 40)? != expected.tokenizer_checksum { return Err(ErrorCode::ShapeMismatch); } let data_offset = usize_from_u64(read_u64(bytes, 48)?)?; let mut entries = Vec::with_capacity(tensor_count); for (index, tensor) in expected.tensors.iter().enumerate() { let entry_offset = HEADER_LEN + index * ENTRY_LEN; validate_entry_identity(bytes, entry_offset, tensor, data_offset)?; let byte_offset = usize_from_u64(read_u64(bytes, entry_offset + 32)?)?; let byte_length = usize_from_u64(read_u64(bytes, entry_offset + 40)?)?; let element_count = usize_from_u64(read_u64(bytes, entry_offset + 48)?)?; let kind = match format { AdapterPackageFormat::RawF32 => { validate_finite_payload(bytes, byte_offset, element_count)?; AdapterDeltaPayloadKind::RawF32 } AdapterPackageFormat::SparseF32 => { let pair_count = validate_sparse_payload(bytes, byte_offset, byte_length, element_count)?; AdapterDeltaPayloadKind::SparseF32 { pair_count } } AdapterPackageFormat::LowRankF32 => { let (factor_rank, rows, cols) = low_rank_payload_shape(bytes, byte_offset, byte_length, element_count)?; AdapterDeltaPayloadKind::LowRankF32 { factor_rank, rows, cols, } } }; entries.push(AdapterDeltaEntry { byte_offset, element_count, kind, }); } Ok(Self { entries }) } pub(crate) fn entries(&self) -> impl Iterator + '_ { self.entries.iter().map(|entry| AdapterDeltaPayload { byte_offset: entry.byte_offset, element_count: entry.element_count, kind: entry.kind, }) } } /// The storage layout for one validated adapter payload. #[derive(Clone, Copy)] pub(crate) enum AdapterDeltaPayloadKind { /// Dense f32 deltas, one value for each tensor element. RawF32, /// Sparse f32 deltas, stored as sorted `(u64 index, f32 delta)` pairs. SparseF32 { /// Number of sparse pairs in the payload. pair_count: usize, }, /// Low-rank f32 matrix deltas, stored as component-major `A` and `B` factors. LowRankF32 { /// Number of outer-product components. factor_rank: usize, /// Matrix row count represented by the factors. rows: usize, /// Matrix column count represented by the factors. cols: usize, }, } /// One validated adapter payload. #[derive(Clone, Copy)] pub(crate) struct AdapterDeltaPayload { pub(crate) byte_offset: usize, pub(crate) element_count: usize, pub(crate) kind: AdapterDeltaPayloadKind, } /// Computes the checksum used by packer reports for tokenizer sections. pub(crate) fn section_checksum(bytes: &[u8], seed: u64) -> u64 { let mut acc = seed; for (index, byte) in bytes.iter().enumerate() { acc ^= u64::from(*byte).wrapping_add((index as u64) << 2); acc = acc.rotate_left(9).wrapping_mul(0x100000001b3); } acc } /// Computes the checksum used by packer reports for tensor layout identity. pub(crate) fn tensor_layout_checksum(tensors: &[TensorEntry]) -> u64 { let mut sorted = tensors.iter().collect::>(); sorted.sort_by_key(|tensor| tensor.name_hash); let mut acc = 0x74656e736f722d6cu64; for tensor in sorted { mix_u64(&mut acc, tensor.name_hash); mix_u64(&mut acc, u64::from(tensor.dtype)); mix_u64(&mut acc, u64::from(tensor.rank)); for dim in [tensor.dim0, tensor.dim1, tensor.dim2, tensor.dim3] { mix_u64(&mut acc, u64::from(dim)); } mix_u64(&mut acc, u64::from(tensor.block_size)); mix_u64(&mut acc, tensor.byte_length); } acc } pub(crate) fn parameter_count(tensors: &[TensorEntry]) -> Result { tensors.iter().try_fold(0u64, |acc, tensor| { acc.checked_add(tensor_element_count(tensor)? as u64) .ok_or(ErrorCode::InvalidLength) }) } pub(crate) fn read_f32(bytes: &[u8], offset: usize) -> Result { let end = offset.checked_add(4).ok_or(ErrorCode::InvalidLength)?; let slice = bytes.get(offset..end).ok_or(ErrorCode::InvalidHeader)?; Ok(f32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) } /// Reads one sparse `(value_index, delta)` pair from a validated sparse payload. pub(crate) fn read_sparse_delta_pair( bytes: &[u8], payload: AdapterDeltaPayload, pair_index: usize, ) -> Result<(usize, f32), ErrorCode> { let AdapterDeltaPayloadKind::SparseF32 { pair_count } = payload.kind else { return Err(ErrorCode::ShapeMismatch); }; if pair_index >= pair_count { return Err(ErrorCode::ShapeMismatch); } let offset = payload .byte_offset .checked_add( pair_index .checked_mul(SPARSE_PAIR_LEN) .ok_or(ErrorCode::InvalidLength)?, ) .ok_or(ErrorCode::InvalidLength)?; let value_index = usize_from_u64(read_u64(bytes, offset)?)?; let delta = read_f32(bytes, offset + 8)?; Ok((value_index, delta)) } /// Reconstructs one value from a validated low-rank payload. pub(crate) fn read_low_rank_delta_value( bytes: &[u8], payload: AdapterDeltaPayload, value_index: usize, ) -> Result { let AdapterDeltaPayloadKind::LowRankF32 { factor_rank, rows, cols, } = payload.kind else { return Err(ErrorCode::ShapeMismatch); }; if factor_rank == 0 { return Ok(0.0); } if value_index >= payload.element_count || rows == 0 || cols == 0 { return Err(ErrorCode::ShapeMismatch); } let row = value_index / cols; let col = value_index % cols; if row >= rows { return Err(ErrorCode::ShapeMismatch); } let a_offset = payload .byte_offset .checked_add(LOW_RANK_HEADER_LEN) .ok_or(ErrorCode::InvalidLength)?; let b_offset = a_offset .checked_add( factor_rank .checked_mul(rows) .and_then(|value| value.checked_mul(4)) .ok_or(ErrorCode::InvalidLength)?, ) .ok_or(ErrorCode::InvalidLength)?; let mut delta = 0.0f32; for component in 0..factor_rank { let a_index = component .checked_mul(rows) .and_then(|value| value.checked_add(row)) .ok_or(ErrorCode::InvalidLength)?; let b_index = component .checked_mul(cols) .and_then(|value| value.checked_add(col)) .ok_or(ErrorCode::InvalidLength)?; let a = read_f32( bytes, a_offset .checked_add(a_index.checked_mul(4).ok_or(ErrorCode::InvalidLength)?) .ok_or(ErrorCode::InvalidLength)?, )?; let b = read_f32( bytes, b_offset .checked_add(b_index.checked_mul(4).ok_or(ErrorCode::InvalidLength)?) .ok_or(ErrorCode::InvalidLength)?, )?; delta += a * b; } if !delta.is_finite() { return Err(ErrorCode::InvalidHeader); } Ok(delta) } fn validate_adapter_bytes(bytes: &[u8]) -> Result { let format = adapter_format(bytes)?; if read_u32(bytes, 4)? != VERSION { return Err(ErrorCode::UnsupportedModelVersion); } if read_u32(bytes, 8)? as usize != HEADER_LEN { return Err(ErrorCode::InvalidHeader); } let tensor_count = read_u32(bytes, 12)? as usize; if read_u32(bytes, 20)? as usize != ENTRY_LEN { return Err(ErrorCode::InvalidHeader); } let data_offset = usize_from_u64(read_u64(bytes, 48)?)?; let directory_end = HEADER_LEN .checked_add( tensor_count .checked_mul(ENTRY_LEN) .ok_or(ErrorCode::InvalidLength)?, ) .ok_or(ErrorCode::InvalidLength)?; if data_offset < directory_end || data_offset % 64 != 0 || data_offset > bytes.len() { return Err(ErrorCode::InvalidHeader); } if read_u64(bytes, CHECKSUM_OFFSET)? != adapter_checksum(bytes)? { return Err(ErrorCode::InvalidHeader); } for index in 0..tensor_count { let entry_offset = HEADER_LEN + index * ENTRY_LEN; let byte_offset = usize_from_u64(read_u64(bytes, entry_offset + 32)?)?; let byte_length = usize_from_u64(read_u64(bytes, entry_offset + 40)?)?; let element_count = usize_from_u64(read_u64(bytes, entry_offset + 48)?)?; match format { AdapterPackageFormat::RawF32 => { let expected_byte_length = element_count .checked_mul(4) .ok_or(ErrorCode::InvalidLength)?; if byte_length != expected_byte_length { return Err(ErrorCode::ShapeMismatch); } } AdapterPackageFormat::SparseF32 => { if byte_length % SPARSE_PAIR_LEN != 0 || byte_length / SPARSE_PAIR_LEN > element_count { return Err(ErrorCode::ShapeMismatch); } } AdapterPackageFormat::LowRankF32 => { low_rank_payload_shape(bytes, byte_offset, byte_length, element_count)?; } } let end = byte_offset .checked_add(byte_length) .ok_or(ErrorCode::InvalidLength)?; let payload = bytes .get(byte_offset..end) .ok_or(ErrorCode::InvalidHeader)?; if read_u64(bytes, entry_offset + 56)? != payload_checksum(payload) { return Err(ErrorCode::InvalidHeader); } } Ok(format) } #[derive(Clone, Copy)] enum AdapterPackageFormat { RawF32, SparseF32, LowRankF32, } fn adapter_format(bytes: &[u8]) -> Result { match bytes.get(0..4) { Some(magic) if magic == RAW_MAGIC => Ok(AdapterPackageFormat::RawF32), Some(magic) if magic == SPARSE_MAGIC => Ok(AdapterPackageFormat::SparseF32), Some(magic) if magic == LOW_RANK_MAGIC => Ok(AdapterPackageFormat::LowRankF32), _ => Err(ErrorCode::InvalidHeader), } } fn validate_entry_identity( bytes: &[u8], entry_offset: usize, tensor: &TensorEntry, data_offset: usize, ) -> Result<(), ErrorCode> { if read_u64(bytes, entry_offset)? != tensor.name_hash { return Err(ErrorCode::ShapeMismatch); } if read_u32(bytes, entry_offset + 8)? != tensor.rank { return Err(ErrorCode::ShapeMismatch); } for (dim_index, expected) in [tensor.dim0, tensor.dim1, tensor.dim2, tensor.dim3] .iter() .enumerate() { if read_u32(bytes, entry_offset + 12 + dim_index * 4)? != *expected { return Err(ErrorCode::ShapeMismatch); } } if read_u32(bytes, entry_offset + 28)? != 0 { return Err(ErrorCode::InvalidHeader); } let byte_offset = usize_from_u64(read_u64(bytes, entry_offset + 32)?)?; if byte_offset < data_offset || byte_offset % 64 != 0 { return Err(ErrorCode::InvalidHeader); } let element_count = read_u64(bytes, entry_offset + 48)?; if element_count != tensor_element_count(tensor)? as u64 { return Err(ErrorCode::ShapeMismatch); } Ok(()) } fn validate_finite_payload( bytes: &[u8], byte_offset: usize, element_count: usize, ) -> Result<(), ErrorCode> { for value_index in 0..element_count { let offset = byte_offset .checked_add(value_index.checked_mul(4).ok_or(ErrorCode::InvalidLength)?) .ok_or(ErrorCode::InvalidLength)?; if !read_f32(bytes, offset)?.is_finite() { return Err(ErrorCode::InvalidHeader); } } Ok(()) } fn validate_sparse_payload( bytes: &[u8], byte_offset: usize, byte_length: usize, element_count: usize, ) -> Result { let pair_count = byte_length / SPARSE_PAIR_LEN; let mut previous_index = None; for pair_index in 0..pair_count { let offset = byte_offset .checked_add( pair_index .checked_mul(SPARSE_PAIR_LEN) .ok_or(ErrorCode::InvalidLength)?, ) .ok_or(ErrorCode::InvalidLength)?; let value_index = usize_from_u64(read_u64(bytes, offset)?)?; if value_index >= element_count || previous_index.is_some_and(|previous| value_index <= previous) { return Err(ErrorCode::ShapeMismatch); } let delta = read_f32(bytes, offset + 8)?; if !delta.is_finite() { return Err(ErrorCode::InvalidHeader); } previous_index = Some(value_index); } Ok(pair_count) } fn low_rank_payload_shape( bytes: &[u8], byte_offset: usize, byte_length: usize, element_count: usize, ) -> Result<(usize, usize, usize), ErrorCode> { if byte_length == 0 { return Ok((0, 0, 0)); } if byte_length < LOW_RANK_HEADER_LEN { return Err(ErrorCode::ShapeMismatch); } let rows = usize_from_u64(u64::from(read_u32(bytes, byte_offset)?))?; let cols = usize_from_u64(u64::from(read_u32(bytes, byte_offset + 4)?))?; let factor_rank = usize_from_u64(u64::from(read_u32(bytes, byte_offset + 8)?))?; if read_u32(bytes, byte_offset + 12)? != 0 || rows == 0 || cols == 0 || factor_rank == 0 || factor_rank > LOW_RANK_MAX_COMPONENTS || factor_rank > rows.min(cols) || rows.checked_mul(cols).ok_or(ErrorCode::InvalidLength)? != element_count { return Err(ErrorCode::ShapeMismatch); } let factor_values = factor_rank .checked_mul(rows.checked_add(cols).ok_or(ErrorCode::InvalidLength)?) .ok_or(ErrorCode::InvalidLength)?; let expected_len = LOW_RANK_HEADER_LEN .checked_add( factor_values .checked_mul(4) .ok_or(ErrorCode::InvalidLength)?, ) .ok_or(ErrorCode::InvalidLength)?; if byte_length != expected_len { return Err(ErrorCode::ShapeMismatch); } for value_index in 0..factor_values { let offset = byte_offset .checked_add( LOW_RANK_HEADER_LEN .checked_add(value_index.checked_mul(4).ok_or(ErrorCode::InvalidLength)?) .ok_or(ErrorCode::InvalidLength)?, ) .ok_or(ErrorCode::InvalidLength)?; if !read_f32(bytes, offset)?.is_finite() { return Err(ErrorCode::InvalidHeader); } } Ok((factor_rank, rows, cols)) } fn adapter_checksum(bytes: &[u8]) -> Result { if bytes.len() < HEADER_LEN { return Err(ErrorCode::InvalidHeader); } let mut acc = 0x6164617074657231u64; for (index, byte) in bytes.iter().enumerate() { let value = if (CHECKSUM_OFFSET..CHECKSUM_OFFSET + 8).contains(&index) { 0 } else { *byte }; acc ^= u64::from(value).wrapping_add((index as u64) << 3); acc = acc.rotate_left(11).wrapping_mul(0x100000001b3); } Ok(acc) } fn payload_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x64656c7461663332u64; for (index, byte) in bytes.iter().enumerate() { acc ^= u64::from(*byte).wrapping_add((index as u64) << 1); acc = acc.rotate_left(7).wrapping_mul(0x100000001b3); } acc } fn tensor_element_count(entry: &TensorEntry) -> Result { let mut total = 1usize; for dim in [entry.dim0, entry.dim1, entry.dim2, entry.dim3] .into_iter() .take(entry.rank as usize) { if dim == 0 { return Err(ErrorCode::ShapeMismatch); } total = total .checked_mul(dim as usize) .ok_or(ErrorCode::InvalidLength)?; } Ok(total) } fn read_u32(bytes: &[u8], offset: usize) -> Result { let end = offset.checked_add(4).ok_or(ErrorCode::InvalidLength)?; let slice = bytes.get(offset..end).ok_or(ErrorCode::InvalidHeader)?; Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) } fn read_u64(bytes: &[u8], offset: usize) -> Result { let end = offset.checked_add(8).ok_or(ErrorCode::InvalidLength)?; let slice = bytes.get(offset..end).ok_or(ErrorCode::InvalidHeader)?; Ok(u64::from_le_bytes([ slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7], ])) } fn usize_from_u64(value: u64) -> Result { usize::try_from(value).map_err(|_| ErrorCode::InvalidLength) } fn mix_u64(acc: &mut u64, value: u64) { for byte in value.to_le_bytes() { *acc ^= u64::from(byte); *acc = acc.rotate_left(11).wrapping_mul(0x100000001b3); } } ================================================================================ END FILE: tinyrustlm/runtime/src/adapter.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/attention.rs BYTES: 942 SHA256: CE410F0EEDC858BAA0A01284CF6C330A3EEC11DB6A5B60D218AE1B7C1E77AD94 ================================================================================ //! Causal attention helpers. use crate::errors::ErrorCode; use crate::ops::{dot, softmax}; /// Computes causal attention for one query over cached keys and values. pub fn attend_single( query: &[f32], keys: &[&[f32]], values: &[&[f32]], out: &mut [f32], ) -> Result<(), ErrorCode> { if keys.len() != values.len() || query.is_empty() || out.len() != query.len() { return Err(ErrorCode::ShapeMismatch); } let mut scores = Vec::with_capacity(keys.len()); let scale = 1.0 / (query.len() as f32).sqrt(); for key in keys { scores.push(dot(query, key)? * scale); } softmax(&mut scores)?; out.fill(0.0); for (position, value) in values.iter().enumerate() { if value.len() != out.len() { return Err(ErrorCode::ShapeMismatch); } for index in 0..out.len() { out[index] += scores[position] * value[index]; } } Ok(()) } ================================================================================ END FILE: tinyrustlm/runtime/src/attention.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/bin/tinyrustlm-eval.rs BYTES: 1221 SHA256: 303E7E1B43056B3F491AE6B7646DE5322CB88A2837FBEFDF0BBA2FE14064DC63 ================================================================================ //! Native TinyRustLM eval runner. use std::env; use std::path::Path; use tinyrustlm_runtime::eval_runner::run_eval_to_sidecar; fn main() { if let Err(error) = run() { eprintln!("tinyrustlm-eval: {error}"); std::process::exit(1); } } fn run() -> Result<(), String> { let args: Vec = env::args().collect(); if args.len() != 5 { print_usage(); return Err("expected model, manifest, eval cases, and output eval paths".to_string()); } let outcome = run_eval_to_sidecar( Path::new(&args[1]), Path::new(&args[2]), Path::new(&args[3]), Path::new(&args[4]), ) .map_err(|error| error.to_string())?; println!( "TinyRustLM eval cases: {}", if outcome.passed { "PASS" } else { "FAIL" } ); println!("cases_passed: {}", outcome.cases_passed); println!("cases_failed: {}", outcome.cases_failed); println!("output_eval: {}", args[4]); if outcome.passed { Ok(()) } else { Err("one or more eval cases failed".to_string()) } } fn print_usage() { eprintln!( "usage: tinyrustlm-eval " ); } ================================================================================ END FILE: tinyrustlm/runtime/src/bin/tinyrustlm-eval.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/diagnostics.rs BYTES: 11301 SHA256: C03C756292DF8622F7684C64BAD3560B7B3D9929616DC5548F51AF4C10EE9522 ================================================================================ //! Diagnostics and benchmark counters. use crate::errors::ErrorCode; const ASSEMBLY_STATE_SEED: u64 = 0x6173_7365_6d62_6c79; const ASSEMBLY_MIX_PRIME: u64 = 0x100000001b3; /// Runtime diagnostics rendered for the browser UI. pub struct Diagnostics { /// Last model load time in milliseconds. pub model_load_time_ms: u32, /// Last prompt token count. pub prompt_token_count: u32, /// Last generated token count. pub generated_token_count: u32, /// Last measured tokens per second. pub tokens_per_second: f32, /// Peak scratch arena usage in bytes. pub peak_scratch_arena_usage: usize, /// Current KV cache length. pub kv_cache_length: usize, /// Allocated KV cache storage size in bytes. pub kv_cache_byte_budget: usize, /// Allocated KV cache storage expressed as 64 KiB WebAssembly pages. pub kv_cache_page_count: usize, /// Active quantization mode. pub active_quantization_mode: &'static str, /// Count of adapter packages applied to the currently loaded model. pub adapter_apply_count: u32, /// Last Rust-accepted adapter package checksum. pub last_adapter_checksum: u64, /// Compact Rust-owned digest of the loaded model plus applied adapter stack. pub assembly_state_checksum: u64, /// Last error code. pub last_error: ErrorCode, /// Whether a model is loaded. pub model_loaded: bool, /// Tokenizer output for developer mode. pub tokenizer_output: String, /// Last logits summary for developer mode. pub logits_summary: String, /// Last selected token for developer mode. pub selected_next_token: u32, /// Top candidate summary for developer mode. pub top_k_candidates: String, /// Sampling temperature currently used for generation. pub sampling_temperature: f32, /// Sampling top-k candidate cap currently used for generation. pub sampling_top_k: usize, /// Sampling top-p nucleus threshold currently used for generation. pub sampling_top_p: f32, /// Sampling seed currently used for deterministic stochastic decoding. pub sampling_seed: u64, } impl Default for Diagnostics { fn default() -> Self { Self { model_load_time_ms: 0, prompt_token_count: 0, generated_token_count: 0, tokens_per_second: 0.0, peak_scratch_arena_usage: 0, kv_cache_length: 0, kv_cache_byte_budget: 0, kv_cache_page_count: 0, active_quantization_mode: "none", adapter_apply_count: 0, last_adapter_checksum: 0, assembly_state_checksum: 0, last_error: ErrorCode::Ok, model_loaded: false, tokenizer_output: String::new(), logits_summary: String::new(), selected_next_token: 0, top_k_candidates: String::new(), sampling_temperature: 0.0, sampling_top_k: 1, sampling_top_p: 1.0, sampling_seed: 1, } } } impl Diagnostics { /// Clears generation-specific counters and developer fields. pub fn reset_generation(&mut self) { self.prompt_token_count = 0; self.generated_token_count = 0; self.tokens_per_second = 0.0; self.peak_scratch_arena_usage = 0; self.kv_cache_length = 0; self.tokenizer_output.clear(); self.logits_summary.clear(); self.selected_next_token = 0; self.top_k_candidates.clear(); } /// Records the model-specific KV cache allocation after a model load. pub fn record_kv_cache_allocation(&mut self, byte_budget: usize, page_count: usize) { self.kv_cache_byte_budget = byte_budget; self.kv_cache_page_count = page_count; } /// Clears KV cache allocation diagnostics when no model is loaded. pub fn reset_kv_cache_allocation(&mut self) { self.kv_cache_length = 0; self.kv_cache_byte_budget = 0; self.kv_cache_page_count = 0; } /// Records a freshly loaded model as the start of a runtime assembly state. pub fn record_model_loaded(&mut self, model_checksum: u64, quantization: &str) { self.adapter_apply_count = 0; self.last_adapter_checksum = 0; let mut digest = mix64(ASSEMBLY_STATE_SEED, model_checksum); digest = hash_bytes(digest, quantization.as_bytes()); self.assembly_state_checksum = mix64(digest, u64::from(self.adapter_apply_count)); } /// Records a Rust-validated adapter package that was applied to the loaded model. pub fn record_adapter_apply(&mut self, adapter_checksum: u64) { self.adapter_apply_count = self.adapter_apply_count.saturating_add(1); self.last_adapter_checksum = adapter_checksum; let with_adapter = mix64(self.assembly_state_checksum, adapter_checksum); self.assembly_state_checksum = mix64(with_adapter, u64::from(self.adapter_apply_count)); } /// Clears runtime assembly fields when no model is loaded. pub fn reset_runtime_assembly(&mut self) { self.adapter_apply_count = 0; self.last_adapter_checksum = 0; self.assembly_state_checksum = 0; } /// Records an error for the next diagnostics render. pub fn record_error(&mut self, error: ErrorCode) { self.last_error = error; } /// Renders diagnostics as JSON without using serde. pub fn render_json(&self, out: &mut Vec) { out.clear(); let text = format!( "{{\n \"model_load_time_ms\": {},\n \"prompt_token_count\": {},\n \"generated_token_count\": {},\n \"tokens_per_second\": {:.3},\n \"peak_scratch_arena_usage\": {},\n \"kv_cache_length\": {},\n \"kv_cache_byte_budget\": {},\n \"kv_cache_page_count\": {},\n \"active_quantization_mode\": \"{}\",\n \"adapter_apply_count\": {},\n \"last_adapter_checksum\": \"0x{:016x}\",\n \"assembly_state_checksum\": \"0x{:016x}\",\n \"model_loaded\": {},\n \"last_error\": \"{}\",\n \"tokenizer_output\": \"{}\",\n \"logits_summary\": \"{}\",\n \"selected_next_token\": {},\n \"top_k_candidates\": \"{}\",\n \"sampling_temperature\": {:.3},\n \"sampling_top_k\": {},\n \"sampling_top_p\": {:.3},\n \"sampling_seed\": {}\n}}", self.model_load_time_ms, self.prompt_token_count, self.generated_token_count, self.tokens_per_second, self.peak_scratch_arena_usage, self.kv_cache_length, self.kv_cache_byte_budget, self.kv_cache_page_count, self.active_quantization_mode, self.adapter_apply_count, self.last_adapter_checksum, self.assembly_state_checksum, if self.model_loaded { "true" } else { "false" }, self.last_error.message(), json_escape(&self.tokenizer_output), json_escape(&self.logits_summary), self.selected_next_token, json_escape(&self.top_k_candidates), self.sampling_temperature, self.sampling_top_k, self.sampling_top_p, self.sampling_seed, ); out.extend_from_slice(text.as_bytes()); } } fn hash_bytes(mut acc: u64, bytes: &[u8]) -> u64 { for byte in bytes { acc = mix64(acc, u64::from(*byte)); } acc } fn mix64(acc: u64, value: u64) -> u64 { let mixed = acc ^ value.wrapping_add(0x9e3779b97f4a7c15); mixed.rotate_left(17).wrapping_mul(ASSEMBLY_MIX_PRIME) ^ (mixed >> 31) } fn json_escape(input: &str) -> String { let mut escaped = String::with_capacity(input.len()); for ch in input.chars() { match ch { '"' => escaped.push_str("\\\""), '\\' => escaped.push_str("\\\\"), '\u{0008}' => escaped.push_str("\\b"), '\u{000C}' => escaped.push_str("\\f"), '\n' => escaped.push_str("\\n"), '\r' => escaped.push_str("\\r"), '\t' => escaped.push_str("\\t"), '\u{2028}' => escaped.push_str("\\u2028"), '\u{2029}' => escaped.push_str("\\u2029"), ch if ch <= '\u{001F}' => { escaped.push_str("\\u00"); escaped.push(hex_digit(((ch as u32) >> 4) as u8)); escaped.push(hex_digit((ch as u32 & 0x0F) as u8)); } _ => escaped.push(ch), } } escaped } fn hex_digit(value: u8) -> char { match value { 0..=9 => (b'0' + value) as char, _ => (b'A' + (value - 10)) as char, } } #[cfg(test)] mod tests { use super::Diagnostics; #[test] fn diagnostics_json_escapes_control_characters() { let mut diagnostics = Diagnostics::default(); diagnostics.tokenizer_output = "quote \" slash \\ bell \u{0007} next\nline".to_string(); diagnostics.logits_summary = "separator \u{2028} paragraph \u{2029}".to_string(); diagnostics.top_k_candidates = "tab\tform\u{000C}back\u{0008}".to_string(); let mut rendered = Vec::new(); diagnostics.render_json(&mut rendered); let text = core::str::from_utf8(&rendered).expect("diagnostics JSON is UTF-8"); assert!(text.contains("quote \\\" slash \\\\ bell \\u0007 next\\nline")); assert!(text.contains("separator \\u2028 paragraph \\u2029")); assert!(text.contains("tab\\tform\\fback\\b")); assert!(text.contains("\"kv_cache_byte_budget\": 0")); assert!(text.contains("\"kv_cache_page_count\": 0")); assert!(text.contains("\"adapter_apply_count\": 0")); assert!(text.contains("\"last_adapter_checksum\": \"0x0000000000000000\"")); assert!(text.contains("\"assembly_state_checksum\": \"0x0000000000000000\"")); } #[test] fn diagnostics_records_and_clears_kv_cache_allocation() { let mut diagnostics = Diagnostics::default(); diagnostics.record_kv_cache_allocation(131_072, 2); diagnostics.kv_cache_length = 7; diagnostics.reset_generation(); assert_eq!(diagnostics.kv_cache_length, 0); assert_eq!(diagnostics.kv_cache_byte_budget, 131_072); assert_eq!(diagnostics.kv_cache_page_count, 2); diagnostics.reset_kv_cache_allocation(); assert_eq!(diagnostics.kv_cache_byte_budget, 0); assert_eq!(diagnostics.kv_cache_page_count, 0); } #[test] fn diagnostics_records_runtime_assembly_state() { let mut diagnostics = Diagnostics::default(); diagnostics.record_model_loaded(0x1234_5678_9abc_def0, "q4_0"); let loaded_checksum = diagnostics.assembly_state_checksum; assert_ne!(loaded_checksum, 0); assert_eq!(diagnostics.adapter_apply_count, 0); assert_eq!(diagnostics.last_adapter_checksum, 0); diagnostics.record_adapter_apply(0x0fed_cba9_8765_4321); assert_eq!(diagnostics.adapter_apply_count, 1); assert_eq!(diagnostics.last_adapter_checksum, 0x0fed_cba9_8765_4321); assert_ne!(diagnostics.assembly_state_checksum, loaded_checksum); diagnostics.reset_runtime_assembly(); assert_eq!(diagnostics.adapter_apply_count, 0); assert_eq!(diagnostics.last_adapter_checksum, 0); assert_eq!(diagnostics.assembly_state_checksum, 0); } } ================================================================================ END FILE: tinyrustlm/runtime/src/diagnostics.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/errors.rs BYTES: 2622 SHA256: 93B775552F722B3C7DEDD5B6AC36F1E95149D1F52AFC8CE8674207BAE7DEBA6A ================================================================================ //! Runtime error codes. /// Explicit error values returned across the WASM ABI. #[repr(u32)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ErrorCode { /// Operation completed successfully. Ok = 0, /// A pointer argument was null when data was required. NullPointer = 1, /// A length argument was invalid or exceeded supported limits. InvalidLength = 2, /// Input bytes were not valid UTF-8. InvalidUtf8 = 3, /// The model file magic was not `SLM1`. InvalidModelMagic = 4, /// The model version is not supported by this runtime. UnsupportedModelVersion = 5, /// Header fields were malformed or out of range. InvalidHeader = 6, /// The tensor directory was malformed or out of range. InvalidTensorDirectory = 7, /// A required tensor was absent from the directory. MissingTensor = 8, /// Tensor dimensions did not match the model header or operation shape. ShapeMismatch = 9, /// The tensor dtype is not supported by the active runtime path. UnsupportedDType = 10, /// The prompt or generation would exceed the context window. ContextExceeded = 11, /// Generation was requested before a model was loaded. ModelNotLoaded = 12, /// Generation failed after validation. GenerationFailed = 13, /// The output buffer could not hold the requested result. OutputBufferExceeded = 14, } impl ErrorCode { /// Returns a stable human-readable message for this error code. pub fn message(self) -> &'static str { match self { ErrorCode::Ok => "ok", ErrorCode::NullPointer => "null pointer", ErrorCode::InvalidLength => "invalid length", ErrorCode::InvalidUtf8 => "invalid utf-8", ErrorCode::InvalidModelMagic => "invalid model magic", ErrorCode::UnsupportedModelVersion => "unsupported model version", ErrorCode::InvalidHeader => "invalid header", ErrorCode::InvalidTensorDirectory => "invalid tensor directory", ErrorCode::MissingTensor => "missing tensor", ErrorCode::ShapeMismatch => "shape mismatch", ErrorCode::UnsupportedDType => "unsupported dtype", ErrorCode::ContextExceeded => "context exceeded", ErrorCode::ModelNotLoaded => "model not loaded", ErrorCode::GenerationFailed => "generation failed", ErrorCode::OutputBufferExceeded => "output buffer exceeded", } } /// Converts this error into its ABI integer representation. pub fn as_u32(self) -> u32 { self as u32 } } ================================================================================ END FILE: tinyrustlm/runtime/src/errors.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/eval_runner.rs BYTES: 14645 SHA256: 4907408005ACFA229C9BA8E2007EB95612FCD07C5F0C3EA17C2CE5B45624CA1A ================================================================================ //! Native eval-case runner for TinyRustLM artifacts. use crate::errors::ErrorCode; use crate::generate::Runtime; use crate::model_format::{parse_slm, SlmHeader}; use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; const EVAL_CASES_VERSION: &str = "1"; const EVAL_MANIFEST_VERSION: &str = "1"; const GATE_ASSISTANT_QUALITY: &str = "assistant-quality"; /// Summary returned after running a local eval case file. pub struct EvalOutcome { /// Whether all declared cases passed. pub passed: bool, /// Number of cases that matched their expected output. pub cases_passed: usize, /// Number of cases that failed generation or exact matching. pub cases_failed: usize, } #[derive(Debug)] struct EvalCase { prompt: String, max_new_tokens: u32, expected_text: String, } #[derive(Debug)] struct EvalCases { scope: String, quality_boundary: String, safety_review_status: String, quality_decision: String, evaluator: String, eval_summary: String, cases: Vec, } struct CaseResult { expected: String, actual: String, passed: bool, error: String, } /// Runs a local model against eval cases and writes a quality-gate sidecar. pub fn run_eval_to_sidecar( model_path: &Path, manifest_path: &Path, cases_path: &Path, output_path: &Path, ) -> io::Result { let model_bytes = fs::read(model_path)?; let parsed = parse_slm(&model_bytes).map_err(error_to_io)?; let manifest_text = fs::read_to_string(manifest_path)?; let manifest_fields = parse_key_value(&manifest_text)?; let source_kind = require_nonempty(&manifest_fields, "source_kind")?; let cases_text = fs::read_to_string(cases_path)?; let eval_cases = parse_eval_cases(&cases_text)?; let mut runtime = Runtime::new(); let load_code = runtime.load_model(&model_bytes); if load_code != ErrorCode::Ok { return Err(io::Error::new( io::ErrorKind::InvalidData, format!("model load failed: {}", load_code.message()), )); } let mut results = Vec::with_capacity(eval_cases.cases.len()); let mut cases_passed = 0usize; for case in &eval_cases.cases { runtime.reset_context(); let code = runtime.generate(&case.prompt, case.max_new_tokens); if code == ErrorCode::Ok { let actual = std::str::from_utf8(runtime.last_result()) .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "result was not UTF-8"))? .to_string(); let passed = actual == case.expected_text; if passed { cases_passed += 1; } results.push(CaseResult { expected: case.expected_text.clone(), actual, passed, error: "ok".to_string(), }); } else { results.push(CaseResult { expected: case.expected_text.clone(), actual: String::new(), passed: false, error: code.message().to_string(), }); } } let cases_failed = eval_cases.cases.len().saturating_sub(cases_passed); let passed = cases_failed == 0; let sidecar = build_eval_sidecar( &parsed.header, source_kind, &manifest_text, cases_path, &eval_cases, &results, passed, ); if let Some(parent) = output_path.parent() { fs::create_dir_all(parent)?; } fs::write(output_path, sidecar)?; Ok(EvalOutcome { passed, cases_passed, cases_failed, }) } fn parse_eval_cases(text: &str) -> io::Result { let fields = parse_key_value(text)?; require_equal(&fields, "tinyrustlm_eval_cases_version", EVAL_CASES_VERSION)?; let scope = require_nonempty(&fields, "scope")?.to_string(); let quality_boundary = require_nonempty(&fields, "quality_boundary")?.to_string(); let safety_review_status = require_nonempty(&fields, "safety_review_status")?.to_string(); let quality_decision = require_nonempty(&fields, "quality_decision")?.to_string(); let evaluator = require_nonempty(&fields, "evaluator")?.to_string(); let eval_summary = require_nonempty(&fields, "eval_summary")?.to_string(); let case_count = parse_usize(require_nonempty(&fields, "case_count")?, "case_count")?; if case_count == 0 { return Err(invalid("case_count must be greater than zero")); } let mut cases = Vec::with_capacity(case_count); for index in 0..case_count { let prefix = format!("case.{index}"); require_equal(&fields, &format!("{prefix}.required_result"), "exact")?; let prompt = require_nonempty(&fields, &format!("{prefix}.prompt"))?.to_string(); let max_new_tokens = parse_u32( require_nonempty(&fields, &format!("{prefix}.max_new_tokens"))?, &format!("{prefix}.max_new_tokens"), )?; if max_new_tokens == 0 { return Err(invalid("case max_new_tokens must be greater than zero")); } let expected_text = require_nonempty(&fields, &format!("{prefix}.expected_text"))?.to_string(); cases.push(EvalCase { prompt, max_new_tokens, expected_text, }); } reject_extra_case_keys(&fields, case_count)?; Ok(EvalCases { scope, quality_boundary, safety_review_status, quality_decision, evaluator, eval_summary, cases, }) } fn build_eval_sidecar( header: &SlmHeader, source_kind: &str, manifest_text: &str, cases_path: &Path, eval_cases: &EvalCases, results: &[CaseResult], passed: bool, ) -> String { let mut text = String::new(); push_line( &mut text, "tinyrustlm_eval_manifest_version", EVAL_MANIFEST_VERSION, ); push_line(&mut text, "gate", GATE_ASSISTANT_QUALITY); push_line(&mut text, "source_kind", source_kind); push_line( &mut text, "manifest_checksum", &format!("0x{:016x}", text_checksum(manifest_text.as_bytes())), ); push_line( &mut text, "slm_checksum", &format!("0x{:016x}", header.checksum), ); push_line(&mut text, "model_shape", &shape_summary(header)); if passed { push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "task_eval_status", "pass"); push_line( &mut text, "safety_review_status", &eval_cases.safety_review_status, ); push_line(&mut text, "quality_decision", &eval_cases.quality_decision); } else { push_line(&mut text, "eval_status", "fail"); push_line(&mut text, "task_eval_status", "fail"); push_line(&mut text, "safety_review_status", "pending"); push_line(&mut text, "quality_decision", "pending"); } push_line(&mut text, "quality_scope", &eval_cases.scope); push_line(&mut text, "evaluator", &eval_cases.evaluator); push_line(&mut text, "eval_dataset", &cases_path.display().to_string()); push_line(&mut text, "eval_summary", &eval_cases.eval_summary); push_line(&mut text, "quality_boundary", &eval_cases.quality_boundary); push_line(&mut text, "case_count", &results.len().to_string()); push_line( &mut text, "cases_passed", &results .iter() .filter(|result| result.passed) .count() .to_string(), ); push_line( &mut text, "cases_failed", &results .iter() .filter(|result| !result.passed) .count() .to_string(), ); for (index, result) in results.iter().enumerate() { let prefix = format!("case.{index}"); push_line( &mut text, &format!("{prefix}.status"), if result.passed { "pass" } else { "fail" }, ); push_line(&mut text, &format!("{prefix}.expected"), &result.expected); push_line(&mut text, &format!("{prefix}.actual"), &result.actual); push_line(&mut text, &format!("{prefix}.error"), &result.error); } text } fn shape_summary(header: &SlmHeader) -> String { format!( "vocab={},hidden={},layers={},heads={},kv_heads={},head_dim={},ffn={},context={}", header.vocab_size, header.hidden_size, header.layer_count, header.head_count, header.kv_head_count, header.head_dim, header.ffn_size, header.max_context ) } fn parse_key_value(text: &str) -> io::Result> { let mut fields = HashMap::new(); for (line_index, raw_line) in text.lines().enumerate() { let line = raw_line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let Some((key, value)) = line.split_once('=') else { return Err(invalid(&format!("line {} is missing '='", line_index + 1))); }; let key = key.trim(); if key.is_empty() { return Err(invalid(&format!( "line {} has an empty key", line_index + 1 ))); } if fields .insert(key.to_string(), value.trim().to_string()) .is_some() { return Err(invalid(&format!("duplicate key {key}"))); } } Ok(fields) } fn reject_extra_case_keys(fields: &HashMap, case_count: usize) -> io::Result<()> { for key in fields.keys() { if let Some(rest) = key.strip_prefix("case.") { let Some((index_text, field_name)) = rest.split_once('.') else { return Err(invalid(&format!("case key {key} is malformed"))); }; let index = parse_usize(index_text, key)?; if index >= case_count { return Err(invalid(&format!( "case key {key} is outside declared case_count" ))); } match field_name { "prompt" | "max_new_tokens" | "expected_text" | "required_result" => {} _ => return Err(invalid(&format!("case key {key} has unknown field"))), } } } Ok(()) } fn require_value<'a>(fields: &'a HashMap, key: &str) -> io::Result<&'a str> { fields .get(key) .map(String::as_str) .ok_or_else(|| invalid(&format!("missing required key {key}"))) } fn require_nonempty<'a>(fields: &'a HashMap, key: &str) -> io::Result<&'a str> { let value = require_value(fields, key)?; if value.is_empty() { return Err(invalid(&format!("key {key} must not be empty"))); } Ok(value) } fn require_equal(fields: &HashMap, key: &str, expected: &str) -> io::Result<()> { let actual = require_nonempty(fields, key)?; if actual != expected { return Err(invalid(&format!( "key {key} was {actual}, expected {expected}" ))); } Ok(()) } fn parse_u32(value: &str, key: &str) -> io::Result { value .parse::() .map_err(|_| invalid(&format!("key {key} must be a u32"))) } fn parse_usize(value: &str, key: &str) -> io::Result { value .parse::() .map_err(|_| invalid(&format!("key {key} must be a usize"))) } fn push_line(text: &mut String, key: &str, value: &str) { text.push_str(key); text.push('='); text.push_str(&line_value(value)); text.push('\n'); } fn line_value(value: &str) -> String { value.replace(['\r', '\n'], " ") } fn text_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x4d595df4d0f33173u64; for (index, byte) in bytes.iter().enumerate() { acc ^= u64::from(*byte).wrapping_add((index as u64) << 2); acc = acc.rotate_left(9).wrapping_mul(0x100000001b3); } acc } fn error_to_io(error: ErrorCode) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, error.message()) } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } #[cfg(test)] mod tests { use super::*; #[test] fn parses_eval_cases() { let cases = parse_eval_cases( "tinyrustlm_eval_cases_version=1\nscope=tiny-fixture-runtime-eval-only\nquality_boundary=fixture evidence only\nsafety_review_status=pass\nquality_decision=accepted-for-assistant-quality\nevaluator=unit-test-evaluator\neval_summary=All cases are exact fixture checks\ncase_count=1\ncase.0.prompt=hi\ncase.0.max_new_tokens=1\ncase.0.expected_text=e\ncase.0.required_result=exact\n", ) .unwrap(); assert_eq!(cases.cases.len(), 1); assert_eq!(cases.cases[0].prompt, "hi"); assert_eq!(cases.cases[0].expected_text, "e"); } #[test] fn rejects_invalid_required_result() { let error = parse_eval_cases( "tinyrustlm_eval_cases_version=1\nscope=tiny-fixture-runtime-eval-only\nquality_boundary=fixture evidence only\nsafety_review_status=pass\nquality_decision=accepted-for-assistant-quality\nevaluator=unit-test-evaluator\neval_summary=All cases are exact fixture checks\ncase_count=1\ncase.0.prompt=hi\ncase.0.max_new_tokens=1\ncase.0.expected_text=e\ncase.0.required_result=contains\n", ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } #[test] fn rejects_zero_case_eval_files() { let error = parse_eval_cases( "tinyrustlm_eval_cases_version=1\nscope=tiny-fixture-runtime-eval-only\nquality_boundary=fixture evidence only\nsafety_review_status=pass\nquality_decision=accepted-for-assistant-quality\nevaluator=unit-test-evaluator\neval_summary=All cases are exact fixture checks\ncase_count=0\n", ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } #[test] fn rejects_case_keys_outside_declared_count() { let error = parse_eval_cases( "tinyrustlm_eval_cases_version=1\nscope=tiny-fixture-runtime-eval-only\nquality_boundary=fixture evidence only\nsafety_review_status=pass\nquality_decision=accepted-for-assistant-quality\nevaluator=unit-test-evaluator\neval_summary=All cases are exact fixture checks\ncase_count=1\ncase.0.prompt=hi\ncase.0.max_new_tokens=1\ncase.0.expected_text=e\ncase.0.required_result=exact\ncase.1.prompt=extra\n", ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } } ================================================================================ END FILE: tinyrustlm/runtime/src/eval_runner.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/ffn.rs BYTES: 784 SHA256: 9CAC43E21EB6F3A1B5B74C07A4483A11E2D652B49A87C7CD9305F23CBBF571A5 ================================================================================ //! Feed-forward network helpers. use crate::errors::ErrorCode; use crate::ops::{matvec_f32, swiglu}; /// Applies a f32 SwiGLU feed-forward block. pub fn ffn_f32( w1: &[f32], w2: &[f32], w3: &[f32], hidden: usize, ffn: usize, input: &[f32], scratch: &mut [f32], out: &mut [f32], ) -> Result<(), ErrorCode> { if scratch.len() < ffn * 3 || out.len() != hidden || input.len() != hidden { return Err(ErrorCode::ShapeMismatch); } let (gate, rest) = scratch.split_at_mut(ffn); let (up, activated) = rest.split_at_mut(ffn); matvec_f32(w1, ffn, hidden, input, gate)?; matvec_f32(w3, ffn, hidden, input, up)?; swiglu(gate, up, &mut activated[..ffn])?; matvec_f32(w2, hidden, ffn, &activated[..ffn], out)?; Ok(()) } ================================================================================ END FILE: tinyrustlm/runtime/src/ffn.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/generate.rs BYTES: 49984 SHA256: A9788F5E70B9960440E642CFA27F6A776F8149FEF666BBFCDD6E6AFD6405111F ================================================================================ //! Autoregressive generation state. use crate::diagnostics::Diagnostics; use crate::errors::ErrorCode; use crate::kv_cache::KvCache; use crate::model::{LayerTensorIndices, Model}; use crate::ops::{dot, rms_norm, softmax, swiglu}; use crate::rng::XorShift64; use crate::rope::apply_rope; use crate::sampler::{sample_with_rng, validate_config, SamplingConfig}; use crate::tokenizer::{Tokenizer, EOS}; use core::fmt::Write as _; const MAX_RESULT_BYTES: usize = 64 * 1024; const RUNTIME_ARTIFACT_CHECKSUM_SEED: u64 = 0xa55e_6d62_1ed0_0001; /// Runtime state shared by browser exports. pub struct Runtime { model: Option, kv_cache: Option, tokenizer: Tokenizer, tokens: Vec, generated_tokens: Vec, last_result: Vec, diagnostics_text: Vec, diagnostics: Diagnostics, sampling_config: SamplingConfig, rng: XorShift64, scratch: Option, logits: Vec, } impl Runtime { /// Creates a fresh runtime with no loaded model. pub fn new() -> Self { let mut runtime = Self { model: None, kv_cache: None, tokenizer: Tokenizer::default(), tokens: Vec::new(), generated_tokens: Vec::new(), last_result: Vec::new(), diagnostics_text: Vec::new(), diagnostics: Diagnostics::default(), sampling_config: SamplingConfig::default(), rng: XorShift64::new(SamplingConfig::default().seed), scratch: None, logits: Vec::new(), }; runtime.apply_sampling_to_diagnostics(); runtime.refresh_diagnostics(); runtime } /// Loads a validated `.slm` model. pub fn load_model(&mut self, bytes: &[u8]) -> ErrorCode { match Model::load(bytes) { Ok(model) => { let header = model.header(); let layer_count = header.layer_count as usize; let max_context = header.max_context as usize; let kv_head_count = header.kv_head_count as usize; let head_dim = header.head_dim as usize; let vocab_size = header.vocab_size as usize; let quantization_mode = model.quantization_mode(); let model_checksum = header.checksum; let scratch = match ForwardScratch::new(&model) { Ok(scratch) => scratch, Err(error) => { self.clear_model_state(); self.diagnostics.model_loaded = false; self.diagnostics.reset_runtime_assembly(); self.diagnostics.reset_kv_cache_allocation(); self.set_result(error.message()); return self.finish(error); } }; let cache = match KvCache::new(layer_count, max_context, kv_head_count, head_dim) { Ok(cache) => cache, Err(error) => { self.clear_model_state(); self.diagnostics.model_loaded = false; self.diagnostics.reset_runtime_assembly(); self.diagnostics.reset_kv_cache_allocation(); self.set_result(error.message()); return self.finish(error); } }; let kv_cache_byte_budget = cache.byte_budget(); let kv_cache_page_count = cache.page_count(); self.tokens.clear(); self.generated_tokens.clear(); self.tokenizer = model.tokenizer().clone(); self.model = Some(model); self.kv_cache = Some(cache); self.scratch = Some(scratch); self.logits = vec![0.0; vocab_size]; self.diagnostics.reset_generation(); self.diagnostics .record_kv_cache_allocation(kv_cache_byte_budget, kv_cache_page_count); self.diagnostics.model_loaded = true; self.diagnostics.active_quantization_mode = quantization_mode; self.diagnostics .record_model_loaded(model_checksum, quantization_mode); self.set_result("model loaded"); self.finish(ErrorCode::Ok) } Err(error) => { self.clear_model_state(); self.diagnostics.model_loaded = false; self.diagnostics.reset_runtime_assembly(); self.diagnostics.reset_kv_cache_allocation(); self.set_result(error.message()); self.finish(error) } } } /// Configures deterministic decoding. pub fn configure_sampling( &mut self, temperature: f32, top_k: u32, top_p: f32, seed: u32, ) -> ErrorCode { let config = SamplingConfig { temperature, top_k: top_k as usize, top_p, seed: seed as u64, }; if validate_config(config).is_err() { self.set_result(ErrorCode::InvalidLength.message()); return self.finish(ErrorCode::InvalidLength); } self.sampling_config = config; self.rng = XorShift64::new(self.sampling_config.seed); self.apply_sampling_to_diagnostics(); self.set_result("sampling configured"); self.finish(ErrorCode::Ok) } /// Validates an adapter-delta package against the loaded model without mutating tensors. pub fn validate_adapter_delta(&mut self, bytes: &[u8]) -> ErrorCode { let result = match self.model.as_ref() { Some(model) => model.validate_adapter_delta(bytes), None => Err(ErrorCode::ModelNotLoaded), }; match result { Ok(()) => { self.set_result("adapter validated"); self.finish(ErrorCode::Ok) } Err(error) => { self.set_result(error.message()); self.finish(error) } } } /// Applies a validated adapter-delta package to the loaded model. pub fn apply_adapter_delta(&mut self, bytes: &[u8]) -> ErrorCode { let adapter_checksum = runtime_artifact_checksum(bytes); let result = match self.model.as_mut() { Some(model) => model.apply_adapter_delta(bytes), None => Err(ErrorCode::ModelNotLoaded), }; match result { Ok(()) => { self.clear_generation_state(); self.diagnostics.record_adapter_apply(adapter_checksum); self.set_result("adapter applied"); self.finish(ErrorCode::Ok) } Err(error) => { self.set_result(error.message()); self.finish(error) } } } /// Generates text for a prompt with configured local decoding. pub fn generate(&mut self, prompt: &str, max_new_tokens: u32) -> ErrorCode { if self.model.is_none() { self.set_result(ErrorCode::ModelNotLoaded.message()); return self.finish(ErrorCode::ModelNotLoaded); } if max_new_tokens == 0 { return self.finish_generation_error(ErrorCode::InvalidLength); } self.clear_generation_state(); let encode_result = self.tokenizer.encode(prompt, &mut self.tokens); if let Err(error) = encode_result { return self.finish_generation_error(error); } let prompt_tokens = prompt_tokens_without_eos(&self.tokens); let prompt_count = prompt_tokens.len(); let prompt_context_len = prompt_tokens.len(); let result = { let model = self.model.as_ref().ok_or(ErrorCode::ModelNotLoaded); let cache = self.kv_cache.as_mut().ok_or(ErrorCode::ModelNotLoaded); let scratch = self.scratch.as_mut().ok_or(ErrorCode::ModelNotLoaded); match (model, cache, scratch) { (Ok(model), Ok(cache), Ok(scratch)) => run_generation( model, cache, prompt_tokens, max_new_tokens as usize, self.sampling_config, scratch, &mut self.logits, &mut self.generated_tokens, &mut self.diagnostics, ), (Err(error), _, _) | (_, Err(error), _) | (_, _, Err(error)) => Err(error), } }; match result { Ok(()) => { let mut decoded = String::new(); if let Err(error) = self.tokenizer.decode_with_limit( &self.generated_tokens, &mut decoded, MAX_RESULT_BYTES, ) { return self.finish_generation_error(error); } self.tokens.truncate(prompt_context_len); self.tokens.extend_from_slice(&self.generated_tokens); self.diagnostics.prompt_token_count = prompt_count as u32; self.diagnostics.generated_token_count = self.generated_tokens.len() as u32; self.set_result(&decoded); self.finish(ErrorCode::Ok) } Err(error) => self.finish_generation_error(error), } } /// Generates one token from the current context. pub fn generate_next_token(&mut self) -> ErrorCode { match self.generate_next_token_id() { Ok(next) => { if should_stop(next) { self.set_result(""); } else { let mut decoded = String::new(); if let Err(error) = self.tokenizer .decode_with_limit(&[next], &mut decoded, MAX_RESULT_BYTES) { self.set_result(error.message()); return self.finish(error); } self.set_result(&decoded); } self.finish(ErrorCode::Ok) } Err(error) => { self.set_result(error.message()); self.finish(error) } } } fn generate_next_token_id(&mut self) -> Result { let model = self.model.as_ref().ok_or(ErrorCode::ModelNotLoaded)?; let cache = self.kv_cache.as_mut().ok_or(ErrorCode::ModelNotLoaded)?; let scratch = self.scratch.as_mut().ok_or(ErrorCode::ModelNotLoaded)?; if self.tokens.is_empty() { return Err(ErrorCode::InvalidLength); } let position = cache.len(); if position >= model.header().max_context as usize { return Err(ErrorCode::ContextExceeded); } let token = *self.tokens.last().ok_or(ErrorCode::InvalidLength)? as usize; forward_token(model, cache, token, position, scratch, &mut self.logits)?; let next = sample_with_rng(&self.logits, self.sampling_config, &mut self.rng)? as u32; if next != EOS { self.tokens.push(next); self.generated_tokens.push(next); } self.diagnostics.generated_token_count = self.generated_tokens.len() as u32; self.diagnostics.kv_cache_length = cache.len(); self.diagnostics.peak_scratch_arena_usage = scratch.peak_bytes(); update_generation_details(&mut self.diagnostics, &self.logits, next); Ok(next) } /// Resets prompt and cache state. pub fn reset_context(&mut self) -> ErrorCode { self.clear_generation_state(); self.set_result("context reset"); self.finish(ErrorCode::Ok) } /// Frees the loaded model while keeping the runtime initialized. pub fn free_model(&mut self) -> ErrorCode { self.clear_model_state(); self.diagnostics.reset_generation(); self.diagnostics.reset_kv_cache_allocation(); self.diagnostics.model_loaded = false; self.diagnostics.active_quantization_mode = "none"; self.diagnostics.reset_runtime_assembly(); self.set_result("model freed"); self.finish(ErrorCode::Ok) } /// Records an ABI boundary error message. pub fn record_boundary_error(&mut self, error: ErrorCode) -> ErrorCode { self.set_result(error.message()); self.finish(error) } /// Returns the current result bytes. pub fn last_result(&self) -> &[u8] { &self.last_result } /// Returns current diagnostics bytes. pub fn diagnostics(&self) -> &[u8] { &self.diagnostics_text } fn set_result(&mut self, text: &str) { self.last_result.clear(); self.last_result.extend_from_slice(text.as_bytes()); } fn finish_generation_error(&mut self, error: ErrorCode) -> ErrorCode { self.clear_generation_state(); self.set_result(error.message()); self.finish(error) } fn finish(&mut self, code: ErrorCode) -> ErrorCode { self.diagnostics.record_error(code); self.refresh_diagnostics(); code } fn refresh_diagnostics(&mut self) { self.diagnostics.render_json(&mut self.diagnostics_text); } fn apply_sampling_to_diagnostics(&mut self) { self.diagnostics.sampling_temperature = self.sampling_config.temperature; self.diagnostics.sampling_top_k = self.sampling_config.top_k; self.diagnostics.sampling_top_p = self.sampling_config.top_p; self.diagnostics.sampling_seed = self.sampling_config.seed; } fn clear_model_state(&mut self) { self.model = None; self.kv_cache = None; self.scratch = None; self.logits.clear(); } fn clear_generation_state(&mut self) { self.tokens.clear(); self.generated_tokens.clear(); if let Some(cache) = self.kv_cache.as_mut() { cache.reset(); } self.diagnostics.reset_generation(); } } impl Default for Runtime { fn default() -> Self { Self::new() } } struct ForwardScratch { residual: Vec, normed: Vec, q: Vec, k: Vec, v: Vec, attention: Vec, projected: Vec, ffn_normed: Vec, norm_weight: Vec, ffn_scratch: Vec, ffn_out: Vec, scores: Vec, } impl ForwardScratch { fn new(model: &Model) -> Result { let header = model.header(); let hidden = header.hidden_size as usize; let ffn = header.ffn_size as usize; let max_context = header.max_context as usize; if header.head_count != header.kv_head_count { return Err(ErrorCode::ShapeMismatch); } Ok(Self { residual: vec![0.0; hidden], normed: vec![0.0; hidden], q: vec![0.0; hidden], k: vec![0.0; hidden], v: vec![0.0; hidden], attention: vec![0.0; hidden], projected: vec![0.0; hidden], ffn_normed: vec![0.0; hidden], norm_weight: vec![0.0; hidden], ffn_scratch: vec![0.0; ffn * 3], ffn_out: vec![0.0; hidden], scores: vec![0.0; max_context], }) } fn peak_bytes(&self) -> usize { (self.residual.len() + self.normed.len() + self.q.len() + self.k.len() + self.v.len() + self.attention.len() + self.projected.len() + self.ffn_normed.len() + self.norm_weight.len() + self.ffn_scratch.len() + self.ffn_out.len() + self.scores.len()) * core::mem::size_of::() } #[cfg(test)] fn buffer_addresses(&self) -> [usize; 12] { [ self.residual.as_ptr() as usize, self.normed.as_ptr() as usize, self.q.as_ptr() as usize, self.k.as_ptr() as usize, self.v.as_ptr() as usize, self.attention.as_ptr() as usize, self.projected.as_ptr() as usize, self.ffn_normed.as_ptr() as usize, self.norm_weight.as_ptr() as usize, self.ffn_scratch.as_ptr() as usize, self.ffn_out.as_ptr() as usize, self.scores.as_ptr() as usize, ] } } fn run_generation( model: &Model, cache: &mut KvCache, prompt_tokens: &[u32], max_new_tokens: usize, sampling_config: SamplingConfig, scratch: &mut ForwardScratch, logits: &mut [f32], generated_tokens: &mut Vec, diagnostics: &mut Diagnostics, ) -> Result<(), ErrorCode> { if prompt_tokens.is_empty() { return Err(ErrorCode::InvalidLength); } let max_context = model.header().max_context as usize; if prompt_tokens.len() >= max_context { return Err(ErrorCode::ContextExceeded); } cache.reset(); generated_tokens.clear(); diagnostics.tokenizer_output = token_list(prompt_tokens); let mut rng = XorShift64::new(sampling_config.seed); for (position, token) in prompt_tokens.iter().enumerate() { forward_token(model, cache, *token as usize, position, scratch, logits)?; } let mut position = prompt_tokens.len(); for _ in 0..max_new_tokens { if position >= max_context { break; } let next = sample_with_rng(logits, sampling_config, &mut rng)? as u32; update_generation_details(diagnostics, logits, next); if should_stop(next) { break; } generated_tokens.push(next); forward_token(model, cache, next as usize, position, scratch, logits)?; position += 1; } diagnostics.kv_cache_length = cache.len(); diagnostics.peak_scratch_arena_usage = scratch.peak_bytes(); diagnostics.tokens_per_second = 0.0; Ok(()) } fn runtime_artifact_checksum(bytes: &[u8]) -> u64 { let mut acc = RUNTIME_ARTIFACT_CHECKSUM_SEED; for (index, byte) in bytes.iter().enumerate() { acc ^= u64::from(*byte).wrapping_add((index as u64).rotate_left(5)); acc = acc.rotate_left(11).wrapping_mul(0x100000001b3); } acc } fn forward_token( model: &Model, cache: &mut KvCache, token: usize, position: usize, scratch: &mut ForwardScratch, logits: &mut [f32], ) -> Result<(), ErrorCode> { let header = model.header(); let hidden = header.hidden_size as usize; let layers = header.layer_count as usize; let heads = header.head_count as usize; let head_dim = header.head_dim as usize; let ffn = header.ffn_size as usize; let vocab = header.vocab_size as usize; if token >= vocab || logits.len() != vocab || heads * head_dim != hidden { return Err(ErrorCode::ShapeMismatch); } let top_level = model.top_level_indices(); model.copy_tensor_row_f32_by_index( top_level.tok_embeddings, token, hidden, &mut scratch.residual, )?; for layer in 0..layers { let layer_indices = model.layer_indices(layer)?; model.copy_tensor_f32_by_index(layer_indices.attention_norm, &mut scratch.norm_weight)?; rms_norm( &scratch.residual, &scratch.norm_weight, header.rms_norm_epsilon, &mut scratch.normed, )?; model.matvec_by_index( layer_indices.wq, hidden, hidden, &scratch.normed, &mut scratch.q, )?; model.matvec_by_index( layer_indices.wk, hidden, hidden, &scratch.normed, &mut scratch.k, )?; model.matvec_by_index( layer_indices.wv, hidden, hidden, &scratch.normed, &mut scratch.v, )?; for head in 0..heads { let start = head * head_dim; let end = start + head_dim; apply_rope(&mut scratch.q[start..end], position, header.rope_theta)?; apply_rope(&mut scratch.k[start..end], position, header.rope_theta)?; } cache.store_layer_at(layer, position, &scratch.k, &scratch.v)?; causal_attention( cache, layer, position, heads, head_dim, &scratch.q, &mut scratch.scores, &mut scratch.attention, )?; model.matvec_by_index( layer_indices.wo, hidden, hidden, &scratch.attention, &mut scratch.projected, )?; add_in_place(&mut scratch.residual, &scratch.projected)?; model.copy_tensor_f32_by_index(layer_indices.ffn_norm, &mut scratch.norm_weight)?; rms_norm( &scratch.residual, &scratch.norm_weight, header.rms_norm_epsilon, &mut scratch.ffn_normed, )?; ffn_model( model, layer_indices, hidden, ffn, &scratch.ffn_normed, &mut scratch.ffn_scratch, &mut scratch.ffn_out, )?; add_in_place(&mut scratch.residual, &scratch.ffn_out)?; } cache.commit_len(position + 1)?; model.copy_tensor_f32_by_index(top_level.norm, &mut scratch.norm_weight)?; rms_norm( &scratch.residual, &scratch.norm_weight, header.rms_norm_epsilon, &mut scratch.normed, )?; model.matvec_by_index( top_level.output_projection, vocab, hidden, &scratch.normed, logits, )?; Ok(()) } fn ffn_model( model: &Model, layer_indices: LayerTensorIndices, hidden: usize, ffn: usize, input: &[f32], scratch: &mut [f32], out: &mut [f32], ) -> Result<(), ErrorCode> { if scratch.len() < ffn * 3 || out.len() != hidden || input.len() != hidden { return Err(ErrorCode::ShapeMismatch); } let (gate, rest) = scratch.split_at_mut(ffn); let (up, activated) = rest.split_at_mut(ffn); model.matvec_by_index(layer_indices.w1, ffn, hidden, input, gate)?; model.matvec_by_index(layer_indices.w3, ffn, hidden, input, up)?; swiglu(gate, up, &mut activated[..ffn])?; model.matvec_by_index(layer_indices.w2, hidden, ffn, &activated[..ffn], out)?; Ok(()) } fn causal_attention( cache: &KvCache, layer: usize, position: usize, heads: usize, head_dim: usize, query: &[f32], scores: &mut [f32], out: &mut [f32], ) -> Result<(), ErrorCode> { out.fill(0.0); if scores.len() <= position { return Err(ErrorCode::ContextExceeded); } for head in 0..heads { let start = head * head_dim; let end = start + head_dim; let query_head = &query[start..end]; for past in 0..=position { let key_head = cache.key_head_at(layer, past, head)?; scores[past] = dot(query_head, key_head)? / (head_dim as f32).sqrt(); } softmax(&mut scores[..=position])?; for past in 0..=position { let value_head = cache.value_head_at(layer, past, head)?; for dim in 0..head_dim { out[start + dim] += scores[past] * value_head[dim]; } } } Ok(()) } fn add_in_place(left: &mut [f32], right: &[f32]) -> Result<(), ErrorCode> { if left.len() != right.len() { return Err(ErrorCode::ShapeMismatch); } for index in 0..left.len() { left[index] += right[index]; } Ok(()) } fn prompt_tokens_without_eos(tokens: &[u32]) -> &[u32] { if tokens.last().copied() == Some(EOS) { &tokens[..tokens.len() - 1] } else { tokens } } fn should_stop(token: u32) -> bool { token == EOS } fn token_list(tokens: &[u32]) -> String { let mut text = String::new(); for (index, token) in tokens.iter().enumerate() { if index > 0 { text.push(','); } text.push_str(&token.to_string()); } text } fn logits_summary(logits: &[f32]) -> String { if logits.is_empty() { return String::new(); } let mut min = logits[0]; let mut max = logits[0]; let mut max_index = 0usize; for (index, value) in logits.iter().enumerate() { min = min.min(*value); if *value > max { max = *value; max_index = index; } } let mut text = String::new(); let _ = write!( &mut text, "min={:.4}, max={:.4}, argmax={}", min, max, max_index ); text } fn top_k_summary(logits: &[f32], k: usize) -> String { const MAX_SUMMARY_CANDIDATES: usize = 8; let limit = k.min(MAX_SUMMARY_CANDIDATES).min(logits.len()); let mut tokens = [0usize; MAX_SUMMARY_CANDIDATES]; let mut values = [f32::NEG_INFINITY; MAX_SUMMARY_CANDIDATES]; let mut count = 0usize; for (token, value) in logits.iter().copied().enumerate() { if count < limit { let mut index = count; while index > 0 && value > values[index - 1] { values[index] = values[index - 1]; tokens[index] = tokens[index - 1]; index -= 1; } values[index] = value; tokens[index] = token; count += 1; } else if limit > 0 && value > values[limit - 1] { let mut index = limit - 1; while index > 0 && value > values[index - 1] { values[index] = values[index - 1]; tokens[index] = tokens[index - 1]; index -= 1; } values[index] = value; tokens[index] = token; } } let mut text = String::new(); for index in 0..count { if index > 0 { text.push_str(", "); } let _ = write!(&mut text, "{}:{:.4}", tokens[index], values[index]); } text } fn update_generation_details(diagnostics: &mut Diagnostics, logits: &[f32], selected: u32) { diagnostics.selected_next_token = selected; diagnostics.logits_summary = logits_summary(logits); diagnostics.top_k_candidates = top_k_summary(logits, 5); } #[cfg(test)] mod tests { use super::*; use crate::adapter::{parameter_count, section_checksum, tensor_layout_checksum}; use crate::model_format::TensorEntry; const ADAPTER_HEADER_LEN: usize = 64; const ADAPTER_ENTRY_LEN: usize = 64; const ADAPTER_CHECKSUM_OFFSET: usize = 56; const TOKENIZER_CHECKSUM_SEED: u64 = 0x746f6b656e697a65; fn build_zero_adapter_bytes(model: &Model, model_bytes: &[u8]) -> Vec { let tensors = &model.parsed().tensors; let data_offset = align_to_64(ADAPTER_HEADER_LEN + tensors.len() * ADAPTER_ENTRY_LEN); let mut cursor = data_offset; let mut offsets = Vec::with_capacity(tensors.len()); let mut lengths = Vec::with_capacity(tensors.len()); let mut payloads = Vec::with_capacity(tensors.len()); for tensor in tensors { cursor = align_to_64(cursor); offsets.push(cursor); let byte_length = tensor_element_count(tensor) * 4; lengths.push(byte_length); let payload = vec![0u8; byte_length]; cursor += byte_length; payloads.push(payload); } let tokenizer_checksum = tokenizer_checksum(model, model_bytes); let mut bytes = vec![0u8; cursor]; bytes[0..4].copy_from_slice(b"ADP1"); write_u32(&mut bytes, 4, 1); write_u32(&mut bytes, 8, ADAPTER_HEADER_LEN as u32); write_u32(&mut bytes, 12, tensors.len() as u32); write_u32(&mut bytes, 16, model.header().flags); write_u32(&mut bytes, 20, ADAPTER_ENTRY_LEN as u32); write_u64(&mut bytes, 24, parameter_count(tensors).unwrap()); write_u64(&mut bytes, 32, tensor_layout_checksum(tensors)); write_u64(&mut bytes, 40, tokenizer_checksum); write_u64(&mut bytes, 48, data_offset as u64); write_u64(&mut bytes, ADAPTER_CHECKSUM_OFFSET, 0); for (index, tensor) in tensors.iter().enumerate() { let entry = ADAPTER_HEADER_LEN + index * ADAPTER_ENTRY_LEN; write_u64(&mut bytes, entry, tensor.name_hash); write_u32(&mut bytes, entry + 8, tensor.rank); write_u32(&mut bytes, entry + 12, tensor.dim0); write_u32(&mut bytes, entry + 16, tensor.dim1); write_u32(&mut bytes, entry + 20, tensor.dim2); write_u32(&mut bytes, entry + 24, tensor.dim3); write_u32(&mut bytes, entry + 28, 0); write_u64(&mut bytes, entry + 32, offsets[index] as u64); write_u64(&mut bytes, entry + 40, lengths[index] as u64); write_u64(&mut bytes, entry + 48, tensor_element_count(tensor) as u64); write_u64( &mut bytes, entry + 56, adapter_payload_checksum(&payloads[index]), ); bytes[offsets[index]..offsets[index] + lengths[index]] .copy_from_slice(&payloads[index]); } let checksum = adapter_checksum(&bytes); write_u64(&mut bytes, ADAPTER_CHECKSUM_OFFSET, checksum); bytes } fn tokenizer_checksum(model: &Model, model_bytes: &[u8]) -> u64 { let start = model.header().tokenizer_offset as usize; let len = model.header().tokenizer_length as usize; section_checksum(&model_bytes[start..start + len], TOKENIZER_CHECKSUM_SEED) } fn tensor_element_count(entry: &TensorEntry) -> usize { [entry.dim0, entry.dim1, entry.dim2, entry.dim3] .into_iter() .take(entry.rank as usize) .fold(1usize, |acc, dim| acc * dim as usize) } fn align_to_64(value: usize) -> usize { (value + 63) & !63 } fn adapter_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x6164617074657231u64; for (index, byte) in bytes.iter().enumerate() { let value = if (ADAPTER_CHECKSUM_OFFSET..ADAPTER_CHECKSUM_OFFSET + 8).contains(&index) { 0 } else { *byte }; acc ^= u64::from(value).wrapping_add((index as u64) << 3); acc = acc.rotate_left(11).wrapping_mul(0x100000001b3); } acc } fn adapter_payload_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x64656c7461663332u64; for (index, byte) in bytes.iter().enumerate() { acc ^= u64::from(*byte).wrapping_add((index as u64) << 1); acc = acc.rotate_left(7).wrapping_mul(0x100000001b3); } acc } fn write_u32(bytes: &mut [u8], offset: usize, value: u32) { bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); } fn write_u64(bytes: &mut [u8], offset: usize, value: u64) { bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); } #[test] fn generation_stops_on_eos() { assert!(should_stop(EOS)); assert!(!should_stop(101)); } #[test] fn runtime_generates_from_tiny_fixture() { let mut runtime = Runtime::new(); assert_eq!( runtime.load_model(include_bytes!("../../models/tiny-test-model.slm")), ErrorCode::Ok ); assert_eq!(runtime.generate("hi", 16), ErrorCode::Ok); let text = core::str::from_utf8(runtime.last_result()).unwrap(); assert_eq!(text, "eeeeeeeeeeeee"); assert!(runtime .diagnostics() .windows(b"argmax=101".len()) .any(|window| window == b"argmax=101")); } #[test] fn runtime_generates_from_tiny_tied_output_fixture() { let mut runtime = Runtime::new(); assert_eq!( runtime.load_model(include_bytes!("../../models/tiny-test-model-tied.slm")), ErrorCode::Ok ); assert_eq!(runtime.generate("hi", 16), ErrorCode::Ok); let text = core::str::from_utf8(runtime.last_result()).unwrap(); assert_eq!(text, "eeeeeeeeeeeee"); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!(diagnostics.contains("\"active_quantization_mode\": \"f32\"")); assert!(diagnostics.contains("\"selected_next_token\": 101")); } #[test] fn runtime_generates_from_tiny_q8_fixture() { let mut runtime = Runtime::new(); assert_eq!( runtime.load_model(include_bytes!("../../models/tiny-test-model-q8.slm")), ErrorCode::Ok ); assert_eq!(runtime.generate("hi", 16), ErrorCode::Ok); let text = core::str::from_utf8(runtime.last_result()).unwrap(); assert_eq!(text, "eeeeeeeeeeeee"); assert!(runtime .diagnostics() .windows(b"\"active_quantization_mode\": \"q8_0\"".len()) .any(|window| window == b"\"active_quantization_mode\": \"q8_0\"")); } #[test] fn runtime_generates_from_tiny_q4_fixture() { let mut runtime = Runtime::new(); assert_eq!( runtime.load_model(include_bytes!("../../models/tiny-test-model-q4.slm")), ErrorCode::Ok ); assert_eq!(runtime.generate("hi", 16), ErrorCode::Ok); let text = core::str::from_utf8(runtime.last_result()).unwrap(); assert_eq!(text, "eeeeeeeeeeeee"); assert!(runtime .diagnostics() .windows(b"\"active_quantization_mode\": \"q4_0\"".len()) .any(|window| window == b"\"active_quantization_mode\": \"q4_0\"")); } #[test] fn runtime_generates_from_tiny_bpe_fixture() { let mut runtime = Runtime::new(); assert_eq!( runtime.load_model(include_bytes!("../../models/tiny-test-model-bpe.slm")), ErrorCode::Ok ); assert_eq!(runtime.generate("the", 1), ErrorCode::Ok); let text = core::str::from_utf8(runtime.last_result()).unwrap(); assert!(!text.is_empty()); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!( diagnostics.contains("\"prompt_token_count\": 2"), "{diagnostics}" ); assert!( diagnostics.contains("\"tokenizer_output\": \"256,261\""), "{diagnostics}" ); assert!( diagnostics.contains("\"active_quantization_mode\": \"f32\""), "{diagnostics}" ); } #[test] fn runtime_accepts_stochastic_bpe_top_k_above_byte_vocab() { let mut runtime = Runtime::new(); assert_eq!( runtime.load_model(include_bytes!("../../models/tiny-test-model-bpe.slm")), ErrorCode::Ok ); assert_eq!(runtime.configure_sampling(0.01, 262, 1.0, 7), ErrorCode::Ok); assert_eq!(runtime.generate("the", 1), ErrorCode::Ok); let text = core::str::from_utf8(runtime.last_result()).unwrap(); assert_eq!(text, "e"); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!( diagnostics.contains("\"sampling_top_k\": 262"), "{diagnostics}" ); assert!( diagnostics.contains("\"tokenizer_output\": \"256,261\""), "{diagnostics}" ); } #[test] fn runtime_reports_output_buffer_exceeded_without_stale_generation_state() { let mut runtime = Runtime::new(); runtime.tokens.push(101); runtime .generated_tokens .resize(MAX_RESULT_BYTES + 1, b'x' as u32); runtime.diagnostics.generated_token_count = runtime.generated_tokens.len() as u32; let mut decoded = String::new(); let error = runtime .tokenizer .decode_with_limit(&runtime.generated_tokens, &mut decoded, MAX_RESULT_BYTES) .unwrap_err(); assert_eq!(error, ErrorCode::OutputBufferExceeded); assert_eq!( runtime.finish_generation_error(error), ErrorCode::OutputBufferExceeded ); assert_eq!( core::str::from_utf8(runtime.last_result()).unwrap(), "output buffer exceeded" ); assert!(runtime.tokens.is_empty()); assert!(runtime.generated_tokens.is_empty()); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!(diagnostics.contains("\"last_error\": \"output buffer exceeded\"")); assert!(diagnostics.contains("\"generated_token_count\": 0")); } #[test] fn runtime_generate_next_token_continues_current_context() { let mut runtime = Runtime::new(); assert_eq!( runtime.load_model(include_bytes!("../../models/tiny-test-model-q8.slm")), ErrorCode::Ok ); assert_eq!(runtime.generate("hi", 1), ErrorCode::Ok); assert_eq!(runtime.tokens.last().copied(), Some(101)); assert_eq!(runtime.generate_next_token(), ErrorCode::Ok); let text = core::str::from_utf8(runtime.last_result()).unwrap(); assert_eq!(text, "e"); assert_eq!(runtime.tokens.last().copied(), Some(101)); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!(diagnostics.contains("\"last_error\": \"ok\"")); assert!(diagnostics.contains("\"generated_token_count\": 2")); assert!(diagnostics.contains("\"kv_cache_length\": 5")); assert!(diagnostics.contains("\"kv_cache_byte_budget\": 1024")); assert!(diagnostics.contains("\"kv_cache_page_count\": 1")); assert!(diagnostics.contains("\"selected_next_token\": 101")); assert!(diagnostics.contains("\"active_quantization_mode\": \"q8_0\"")); assert!(diagnostics.contains("\"adapter_apply_count\": 0")); assert!(!diagnostics.contains("\"assembly_state_checksum\": \"0x0000000000000000\"")); } #[test] fn runtime_adapter_apply_resets_generation_diagnostics() { let model_bytes = include_bytes!("../../models/tiny-test-model.slm"); let mut runtime = Runtime::new(); assert_eq!(runtime.load_model(model_bytes), ErrorCode::Ok); assert_eq!(runtime.generate("hi", 1), ErrorCode::Ok); assert!(core::str::from_utf8(runtime.diagnostics()) .unwrap() .contains("\"generated_token_count\": 1")); let adapter = { let model = runtime.model.as_ref().unwrap(); build_zero_adapter_bytes(model, model_bytes) }; assert_eq!(runtime.apply_adapter_delta(&adapter), ErrorCode::Ok); assert_eq!( core::str::from_utf8(runtime.last_result()).unwrap(), "adapter applied" ); assert!(runtime.tokens.is_empty()); assert_eq!(runtime.kv_cache.as_ref().map(KvCache::len), Some(0)); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!(diagnostics.contains("\"last_error\": \"ok\"")); assert!(diagnostics.contains("\"model_loaded\": true")); assert!(diagnostics.contains("\"active_quantization_mode\": \"f32\"")); assert!(diagnostics.contains("\"prompt_token_count\": 0")); assert!(diagnostics.contains("\"generated_token_count\": 0")); assert!(diagnostics.contains("\"kv_cache_length\": 0")); assert!(diagnostics.contains("\"kv_cache_byte_budget\": 1024")); assert!(diagnostics.contains("\"kv_cache_page_count\": 1")); assert!(diagnostics.contains("\"selected_next_token\": 0")); assert!(diagnostics.contains("\"adapter_apply_count\": 1")); assert!(!diagnostics.contains("\"last_adapter_checksum\": \"0x0000000000000000\"")); assert!(!diagnostics.contains("\"assembly_state_checksum\": \"0x0000000000000000\"")); } #[test] fn runtime_adapter_validate_preserves_generation_diagnostics() { let model_bytes = include_bytes!("../../models/tiny-test-model.slm"); let mut runtime = Runtime::new(); assert_eq!(runtime.load_model(model_bytes), ErrorCode::Ok); assert_eq!(runtime.generate("hi", 1), ErrorCode::Ok); let adapter = { let model = runtime.model.as_ref().unwrap(); build_zero_adapter_bytes(model, model_bytes) }; let tokens = runtime.tokens.clone(); let kv_len = runtime.kv_cache.as_ref().map(KvCache::len); assert_eq!(runtime.validate_adapter_delta(&adapter), ErrorCode::Ok); assert_eq!( core::str::from_utf8(runtime.last_result()).unwrap(), "adapter validated" ); assert_eq!(runtime.tokens, tokens); assert_eq!(runtime.kv_cache.as_ref().map(KvCache::len), kv_len); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!(diagnostics.contains("\"last_error\": \"ok\"")); assert!(diagnostics.contains("\"model_loaded\": true")); assert!(diagnostics.contains("\"active_quantization_mode\": \"f32\"")); assert!(diagnostics.contains("\"prompt_token_count\": 3")); assert!(diagnostics.contains("\"generated_token_count\": 1")); assert!(diagnostics.contains("\"kv_cache_length\": 4")); assert!(diagnostics.contains("\"adapter_apply_count\": 0")); assert!(diagnostics.contains("\"last_adapter_checksum\": \"0x0000000000000000\"")); } #[test] fn runtime_q8_adapter_apply_resets_generation_diagnostics() { let model_bytes = include_bytes!("../../models/tiny-test-model-q8.slm"); let mut runtime = Runtime::new(); assert_eq!(runtime.load_model(model_bytes), ErrorCode::Ok); assert_eq!(runtime.generate("hi", 1), ErrorCode::Ok); assert!(core::str::from_utf8(runtime.diagnostics()) .unwrap() .contains("\"generated_token_count\": 1")); let adapter = { let model = runtime.model.as_ref().unwrap(); build_zero_adapter_bytes(model, model_bytes) }; assert_eq!(runtime.apply_adapter_delta(&adapter), ErrorCode::Ok); assert_eq!( core::str::from_utf8(runtime.last_result()).unwrap(), "adapter applied" ); assert!(runtime.tokens.is_empty()); assert_eq!(runtime.kv_cache.as_ref().map(KvCache::len), Some(0)); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!(diagnostics.contains("\"last_error\": \"ok\"")); assert!(diagnostics.contains("\"model_loaded\": true")); assert!(diagnostics.contains("\"active_quantization_mode\": \"q8_0\"")); assert!(diagnostics.contains("\"prompt_token_count\": 0")); assert!(diagnostics.contains("\"generated_token_count\": 0")); assert!(diagnostics.contains("\"kv_cache_length\": 0")); assert!(diagnostics.contains("\"selected_next_token\": 0")); assert!(diagnostics.contains("\"adapter_apply_count\": 1")); assert!(!diagnostics.contains("\"last_adapter_checksum\": \"0x0000000000000000\"")); } #[test] fn runtime_accepts_last_prompt_slot_and_rejects_full_context_prompt() { let mut runtime = Runtime::new(); assert_eq!( runtime.load_model(include_bytes!("../../models/tiny-test-model-q8.slm")), ErrorCode::Ok ); assert_eq!(runtime.generate(&"a".repeat(14), 1), ErrorCode::Ok); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!(diagnostics.contains("\"prompt_token_count\": 15")); assert!(diagnostics.contains("\"generated_token_count\": 1")); assert!(diagnostics.contains("\"kv_cache_length\": 16")); assert_eq!( runtime.generate(&"a".repeat(15), 1), ErrorCode::ContextExceeded ); assert_eq!( core::str::from_utf8(runtime.last_result()).unwrap(), "context exceeded" ); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!(diagnostics.contains("\"last_error\": \"context exceeded\"")); assert!(diagnostics.contains("\"generated_token_count\": 0")); assert!(runtime.tokens.is_empty()); assert_eq!(runtime.kv_cache.as_ref().map(KvCache::len), Some(0)); } #[test] fn runtime_reuses_generation_buffers_across_generate_and_steps() { let mut runtime = Runtime::new(); assert_eq!( runtime.load_model(include_bytes!("../../models/tiny-test-model-q8.slm")), ErrorCode::Ok ); let loaded_buffers = generation_buffer_snapshot(&runtime); assert_eq!(runtime.generate("hi", 1), ErrorCode::Ok); assert_eq!(generation_buffer_snapshot(&runtime), loaded_buffers); assert_eq!(runtime.generate_next_token(), ErrorCode::Ok); assert_eq!(generation_buffer_snapshot(&runtime), loaded_buffers); assert_eq!(runtime.generate_next_token(), ErrorCode::Ok); assert_eq!(generation_buffer_snapshot(&runtime), loaded_buffers); } #[test] fn runtime_free_model_blocks_later_generation() { let mut runtime = Runtime::new(); assert_eq!( runtime.load_model(include_bytes!("../../models/tiny-test-model-q8.slm")), ErrorCode::Ok ); assert_eq!(runtime.generate("hi", 1), ErrorCode::Ok); assert_eq!(runtime.free_model(), ErrorCode::Ok); assert_eq!( core::str::from_utf8(runtime.last_result()).unwrap(), "model freed" ); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!(diagnostics.contains("\"last_error\": \"ok\"")); assert!(diagnostics.contains("\"model_loaded\": false")); assert!(diagnostics.contains("\"active_quantization_mode\": \"none\"")); assert!(diagnostics.contains("\"kv_cache_byte_budget\": 0")); assert!(diagnostics.contains("\"kv_cache_page_count\": 0")); assert!(diagnostics.contains("\"adapter_apply_count\": 0")); assert!(diagnostics.contains("\"last_adapter_checksum\": \"0x0000000000000000\"")); assert!(diagnostics.contains("\"assembly_state_checksum\": \"0x0000000000000000\"")); assert!(runtime.scratch.is_none()); assert!(runtime.logits.is_empty()); assert_eq!(runtime.generate_next_token(), ErrorCode::ModelNotLoaded); assert_eq!( core::str::from_utf8(runtime.last_result()).unwrap(), "model not loaded" ); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!(diagnostics.contains("\"last_error\": \"model not loaded\"")); assert!(diagnostics.contains("\"model_loaded\": false")); } #[test] fn top_k_summary_keeps_highest_candidates_without_sorting_vector() { assert_eq!( top_k_summary(&[0.1, 2.0, 1.5, 2.0, -1.0], 3), "1:2.0000, 3:2.0000, 2:1.5000" ); assert_eq!(top_k_summary(&[], 5), ""); assert_eq!(top_k_summary(&[1.0, 2.0], 0), ""); } #[test] fn model_reload_resets_generation_diagnostics() { let mut runtime = Runtime::new(); assert_eq!( runtime.load_model(include_bytes!("../../models/tiny-test-model-q8.slm")), ErrorCode::Ok ); assert_eq!(runtime.generate("hi", 1), ErrorCode::Ok); assert!(runtime .diagnostics() .windows(b"\"generated_token_count\": 1".len()) .any(|window| window == b"\"generated_token_count\": 1")); assert_eq!( runtime.load_model(include_bytes!("../../models/tiny-test-model-q4.slm")), ErrorCode::Ok ); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!(diagnostics.contains("\"active_quantization_mode\": \"q4_0\"")); assert!(diagnostics.contains("\"prompt_token_count\": 0")); assert!(diagnostics.contains("\"generated_token_count\": 0")); assert!(diagnostics.contains("\"kv_cache_length\": 0")); assert!(diagnostics.contains("\"tokenizer_output\": \"\"")); assert!(diagnostics.contains("\"selected_next_token\": 0")); assert!(diagnostics.contains("\"adapter_apply_count\": 0")); assert!(diagnostics.contains("\"last_adapter_checksum\": \"0x0000000000000000\"")); assert!(!diagnostics.contains("\"assembly_state_checksum\": \"0x0000000000000000\"")); } #[test] fn runtime_configures_sampling_diagnostics() { let mut runtime = Runtime::new(); assert_eq!(runtime.configure_sampling(0.75, 4, 0.9, 123), ErrorCode::Ok); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!(diagnostics.contains("\"sampling_temperature\": 0.750")); assert!(diagnostics.contains("\"sampling_top_k\": 4")); assert!(diagnostics.contains("\"sampling_top_p\": 0.900")); assert!(diagnostics.contains("\"sampling_seed\": 123")); assert_eq!( runtime.configure_sampling(1.0, 0, 1.0, 1), ErrorCode::InvalidLength ); let diagnostics = core::str::from_utf8(runtime.diagnostics()).unwrap(); assert!(diagnostics.contains("\"last_error\": \"invalid length\"")); } fn generation_buffer_snapshot(runtime: &Runtime) -> ([usize; 12], usize, usize) { let scratch = runtime.scratch.as_ref().expect("scratch loaded"); ( scratch.buffer_addresses(), runtime.logits.as_ptr() as usize, runtime.logits.capacity(), ) } } ================================================================================ END FILE: tinyrustlm/runtime/src/generate.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/kv_cache.rs BYTES: 6819 SHA256: 6E642AA8343C686AE8E8DFD1210A0068B8607D88E754EA3E3150D7867B731F5C ================================================================================ //! Key/value cache for autoregressive attention. use crate::errors::ErrorCode; /// Layer-major key/value cache. pub struct KvCache { layers: usize, max_context: usize, kv_heads: usize, head_dim: usize, len: usize, keys: Vec, values: Vec, } impl KvCache { /// Creates a new zero-initialized key/value cache. pub fn new( layers: usize, max_context: usize, kv_heads: usize, head_dim: usize, ) -> Result { if layers == 0 || max_context == 0 || kv_heads == 0 || head_dim == 0 { return Err(ErrorCode::ShapeMismatch); } let total = layers .checked_mul(max_context) .and_then(|v| v.checked_mul(kv_heads)) .and_then(|v| v.checked_mul(head_dim)) .ok_or(ErrorCode::InvalidLength)?; Ok(Self { layers, max_context, kv_heads, head_dim, len: 0, keys: vec![0.0; total], values: vec![0.0; total], }) } /// Returns the allocated key/value storage size in bytes for diagnostics. pub fn byte_budget(&self) -> usize { (self.keys.len() + self.values.len()) * core::mem::size_of::() } /// Returns the 64 KiB WebAssembly page count needed to hold the cache bytes. pub fn page_count(&self) -> usize { page_count_for_bytes(self.byte_budget()) } /// Returns the current token count in the cache. pub fn len(&self) -> usize { self.len } /// Returns whether the cache is empty. pub fn is_empty(&self) -> bool { self.len == 0 } /// Clears all cached positions. pub fn reset(&mut self) { self.len = 0; } /// Commits the visible cache length after all layers store a position. pub fn commit_len(&mut self, len: usize) -> Result<(), ErrorCode> { if len > self.max_context { return Err(ErrorCode::ContextExceeded); } self.len = len; Ok(()) } /// Appends a single position for one layer. pub fn append_layer( &mut self, layer: usize, key: &[f32], value: &[f32], ) -> Result<(), ErrorCode> { if layer >= self.layers || self.len >= self.max_context { return Err(ErrorCode::ContextExceeded); } let expected = self.kv_heads * self.head_dim; if key.len() != expected || value.len() != expected { return Err(ErrorCode::ShapeMismatch); } let base = self.offset(layer, self.len, 0, 0)?; self.keys[base..base + expected].copy_from_slice(key); self.values[base..base + expected].copy_from_slice(value); if layer + 1 == self.layers { self.len += 1; } Ok(()) } /// Stores a single layer at an explicit token position. pub fn store_layer_at( &mut self, layer: usize, position: usize, key: &[f32], value: &[f32], ) -> Result<(), ErrorCode> { if layer >= self.layers || position >= self.max_context { return Err(ErrorCode::ContextExceeded); } let expected = self.kv_heads * self.head_dim; if key.len() != expected || value.len() != expected { return Err(ErrorCode::ShapeMismatch); } let base = self.offset(layer, position, 0, 0)?; self.keys[base..base + expected].copy_from_slice(key); self.values[base..base + expected].copy_from_slice(value); Ok(()) } /// Reads a cached key vector for one layer and position. pub fn key(&self, layer: usize, position: usize) -> Result<&[f32], ErrorCode> { self.read(&self.keys, layer, position) } /// Reads a cached value vector for one layer and position. pub fn value(&self, layer: usize, position: usize) -> Result<&[f32], ErrorCode> { self.read(&self.values, layer, position) } /// Reads a cached key head at a position that has been stored. pub fn key_head_at( &self, layer: usize, position: usize, head: usize, ) -> Result<&[f32], ErrorCode> { self.read_head(&self.keys, layer, position, head) } /// Reads a cached value head at a position that has been stored. pub fn value_head_at( &self, layer: usize, position: usize, head: usize, ) -> Result<&[f32], ErrorCode> { self.read_head(&self.values, layer, position, head) } fn read<'a>( &self, store: &'a [f32], layer: usize, position: usize, ) -> Result<&'a [f32], ErrorCode> { if layer >= self.layers || position >= self.len { return Err(ErrorCode::ContextExceeded); } let expected = self.kv_heads * self.head_dim; let base = self.offset(layer, position, 0, 0)?; Ok(&store[base..base + expected]) } fn read_head<'a>( &self, store: &'a [f32], layer: usize, position: usize, head: usize, ) -> Result<&'a [f32], ErrorCode> { if layer >= self.layers || position >= self.max_context || head >= self.kv_heads { return Err(ErrorCode::ContextExceeded); } let base = self.offset(layer, position, head, 0)?; Ok(&store[base..base + self.head_dim]) } fn offset( &self, layer: usize, position: usize, head: usize, dim: usize, ) -> Result { if layer >= self.layers || position >= self.max_context || head >= self.kv_heads || dim >= self.head_dim { return Err(ErrorCode::ShapeMismatch); } Ok((((layer * self.max_context + position) * self.kv_heads + head) * self.head_dim) + dim) } } fn page_count_for_bytes(bytes: usize) -> usize { // Rounds the cache byte envelope up to WebAssembly page units for diagnostics. let page_bytes = 64 * 1024; (bytes + page_bytes - 1) / page_bytes } #[cfg(test)] mod tests { use super::*; #[test] fn kv_cache_append_read() { let mut cache = KvCache::new(1, 4, 2, 2).unwrap(); cache .append_layer(0, &[1.0, 2.0, 3.0, 4.0], &[5.0, 6.0, 7.0, 8.0]) .unwrap(); assert_eq!(cache.len(), 1); assert_eq!(cache.key(0, 0).unwrap(), &[1.0, 2.0, 3.0, 4.0]); assert_eq!(cache.value(0, 0).unwrap(), &[5.0, 6.0, 7.0, 8.0]); } #[test] fn kv_cache_reports_byte_budget_and_page_count_from_all_shape_parameters() { let cache = KvCache::new(2, 8192, 2, 4).unwrap(); assert_eq!(cache.byte_budget(), 2 * 8192 * 2 * 4 * 2 * 4); assert_eq!(cache.page_count(), 16); } } ================================================================================ END FILE: tinyrustlm/runtime/src/kv_cache.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/lib.rs BYTES: 1383 SHA256: 7FDFE094576F7CB4C63847E6594CBF9DFCD4130F48B6AE7EE95426043364D578 ================================================================================ //! TinyRustLM zero-dependency Rust runtime. //! //! The runtime is designed for browser-hosted WebAssembly without wasm-bindgen, //! JavaScript frameworks, tokenizer crates, inference frameworks, or remote //! APIs. Early milestones expose a strict memory boundary, byte tokenizer, //! `.slm` parser, math kernels, diagnostics, and deterministic sampling. mod adapter; /// Causal attention helpers. pub mod attention; /// Runtime diagnostics and benchmark counters. pub mod diagnostics; /// Error codes shared across Rust and the browser host. pub mod errors; /// Native evaluation runner for local model/case evidence. pub mod eval_runner; /// Feed-forward network helpers. pub mod ffn; /// Autoregressive generation state. pub mod generate; /// Key/value cache storage. pub mod kv_cache; /// WASM memory boundary helpers. pub mod memory; /// Loaded model metadata and tensor lookup. pub mod model; /// Custom `.slm` binary parser. pub mod model_format; /// Core math operations. pub mod ops; /// Quantization helpers. pub mod quant; /// Deterministic pseudo-random generator. pub mod rng; /// Rotary positional embedding helpers. pub mod rope; /// Sampling helpers. pub mod sampler; /// Tensor view types. pub mod tensor; /// Byte-level tokenizer. pub mod tokenizer; /// Exports consumed by the handwritten JavaScript bootstrap. pub mod wasm_exports; pub use errors::ErrorCode; ================================================================================ END FILE: tinyrustlm/runtime/src/lib.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/memory.rs BYTES: 1465 SHA256: 078BC01720160FB816D5ECFF493F4184417D985ACCF45EC9C5D0F0BC5874FA59 ================================================================================ //! WASM memory boundary helpers. #![allow(unsafe_code)] use crate::errors::ErrorCode; const MAX_TRANSFER_BYTES: usize = 128 * 1024 * 1024; /// Allocates a byte buffer in WASM linear memory and returns its pointer. /// /// The caller must pass the returned pointer and the same capacity to /// [`deallocate_bytes`] when the browser no longer needs the transfer buffer. pub fn allocate_bytes(len: usize) -> *mut u8 { if len == 0 || len > MAX_TRANSFER_BYTES { return core::ptr::null_mut(); } let mut bytes: Vec = Vec::with_capacity(len); let ptr = bytes.as_mut_ptr(); core::mem::forget(bytes); ptr } /// Releases a buffer previously returned by [`allocate_bytes`]. /// /// `ptr` must be the original pointer and `len` must be the original capacity. pub unsafe fn deallocate_bytes(ptr: *mut u8, len: usize) { if !ptr.is_null() && len > 0 && len <= MAX_TRANSFER_BYTES { let _ = Vec::from_raw_parts(ptr, 0, len); } } /// Validates a raw byte range and returns it as an immutable slice. /// /// The caller must ensure the pointer is valid for `len` bytes for the duration /// of the returned borrow. pub unsafe fn slice_from_raw<'a>(ptr: *const u8, len: usize) -> Result<&'a [u8], ErrorCode> { if ptr.is_null() { return Err(ErrorCode::NullPointer); } if len == 0 || len > MAX_TRANSFER_BYTES { return Err(ErrorCode::InvalidLength); } Ok(core::slice::from_raw_parts(ptr, len)) } ================================================================================ END FILE: tinyrustlm/runtime/src/memory.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/model.rs BYTES: 68445 SHA256: 2FA2149C17D301271316EAE29D214887597C63A313997C61CA5225F785C2373E ================================================================================ //! Loaded model metadata and tensor storage. use crate::adapter::{ parameter_count, read_f32, read_low_rank_delta_value, read_sparse_delta_pair, section_checksum, tensor_layout_checksum, AdapterDelta, AdapterDeltaPayload, AdapterDeltaPayloadKind, AdapterExpected, }; use crate::errors::ErrorCode; use crate::model_format::{ name_hash, parse_slm, ParsedSlm, SlmHeader, TensorEntry, DTYPE_F32, DTYPE_Q4_0, DTYPE_Q8_0, }; use crate::ops::matvec_f32; use crate::quant::{matvec_q4_0, matvec_q8_0, pack_q4_pair, quantize_q4_block, quantize_q8_row}; use crate::tokenizer::Tokenizer; use std::convert::TryInto; const FLAG_TIED_OUTPUT: u32 = 1; const TOKENIZER_CHECKSUM_SEED: u64 = 0x746f6b656e697a65; /// Loaded model directory and header. #[derive(Debug)] pub struct Model { parsed: ParsedSlm, tensors: Vec, tokenizer: Tokenizer, parameter_count: u64, tensor_layout_checksum: u64, tokenizer_checksum: u64, top_level_indices: TopLevelTensorIndices, layer_indices: Vec, } /// Pre-resolved indices for model-level tensors used during generation. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) struct TopLevelTensorIndices { /// Token embedding matrix index. pub(crate) tok_embeddings: usize, /// Final normalization weight index. pub(crate) norm: usize, /// Output projection matrix index, falling back to embeddings when tied. pub(crate) output_projection: usize, } /// Pre-resolved indices for one decoder layer's tensors. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) struct LayerTensorIndices { /// Attention RMSNorm weight index. pub(crate) attention_norm: usize, /// Feed-forward RMSNorm weight index. pub(crate) ffn_norm: usize, /// Query projection matrix index. pub(crate) wq: usize, /// Key projection matrix index. pub(crate) wk: usize, /// Value projection matrix index. pub(crate) wv: usize, /// Attention output projection matrix index. pub(crate) wo: usize, /// SwiGLU gate projection matrix index. pub(crate) w1: usize, /// Feed-forward down projection matrix index. pub(crate) w2: usize, /// SwiGLU up projection matrix index. pub(crate) w3: usize, } #[derive(Debug)] struct LoadedTensor { entry: TensorEntry, storage: TensorStorage, } #[derive(Debug)] enum TensorStorage { F32 { data: Vec, }, Q8 { weights: Vec, scales: Vec, }, Q4 { packed: Vec, scales: Vec, block_size: usize, }, } impl LoadedTensor { fn f32_data(&self) -> Result<&[f32], ErrorCode> { match &self.storage { TensorStorage::F32 { data } => Ok(data), TensorStorage::Q8 { .. } | TensorStorage::Q4 { .. } => Err(ErrorCode::UnsupportedDType), } } fn copy_f32(&self, out: &mut [f32]) -> Result<(), ErrorCode> { let expected = tensor_element_count(&self.entry)?; if out.len() != expected { return Err(ErrorCode::ShapeMismatch); } match &self.storage { TensorStorage::F32 { data } => { out.copy_from_slice(data); Ok(()) } TensorStorage::Q8 { weights, scales } => { let (rows, cols) = tensor_matrix_shape(&self.entry)?; for row in 0..rows { let scale = scales[row]; let start = row * cols; for col in 0..cols { out[start + col] = f32::from(weights[start + col]) * scale; } } Ok(()) } TensorStorage::Q4 { packed, scales, block_size, } => copy_q4_to_f32(packed, scales, *block_size, &self.entry, out), } } fn copy_row_f32(&self, row: usize, cols: usize, out: &mut [f32]) -> Result<(), ErrorCode> { let (rows, expected_cols) = tensor_matrix_shape(&self.entry)?; if row >= rows || cols != expected_cols || out.len() != cols { return Err(ErrorCode::ShapeMismatch); } match &self.storage { TensorStorage::F32 { data } => { let start = row.checked_mul(cols).ok_or(ErrorCode::InvalidLength)?; out.copy_from_slice(&data[start..start + cols]); Ok(()) } TensorStorage::Q8 { weights, scales } => { let start = row.checked_mul(cols).ok_or(ErrorCode::InvalidLength)?; let scale = scales[row]; for col in 0..cols { out[col] = f32::from(weights[start + col]) * scale; } Ok(()) } TensorStorage::Q4 { packed, scales, block_size, } => copy_q4_row_to_f32(packed, scales, *block_size, &self.entry, row, cols, out), } } fn matvec( &self, rows: usize, cols: usize, vector: &[f32], out: &mut [f32], ) -> Result<(), ErrorCode> { let expected = rows.checked_mul(cols).ok_or(ErrorCode::InvalidLength)?; if tensor_element_count(&self.entry)? != expected { return Err(ErrorCode::ShapeMismatch); } match &self.storage { TensorStorage::F32 { data } => matvec_f32(data, rows, cols, vector, out), TensorStorage::Q8 { weights, scales } => { matvec_q8_0(weights, scales, rows, cols, vector, out) } TensorStorage::Q4 { packed, scales, block_size, } => matvec_q4_0(packed, scales, *block_size, rows, cols, vector, out), } } fn validate_adapter_payload( &self, bytes: &[u8], payload: AdapterDeltaPayload, ) -> Result<(), ErrorCode> { if tensor_element_count(&self.entry)? != payload.element_count { return Err(ErrorCode::ShapeMismatch); } match payload.kind { AdapterDeltaPayloadKind::RawF32 => { for value_index in 0..payload.element_count { let value = self.f32_value_at(value_index)? + adapter_delta_value(bytes, payload, value_index)?; if !value.is_finite() { return Err(ErrorCode::InvalidHeader); } } } AdapterDeltaPayloadKind::SparseF32 { pair_count } => { for pair_index in 0..pair_count { let (value_index, delta) = read_sparse_delta_pair(bytes, payload, pair_index)?; let value = self.f32_value_at(value_index)? + delta; if !value.is_finite() { return Err(ErrorCode::InvalidHeader); } } } AdapterDeltaPayloadKind::LowRankF32 { .. } => { for value_index in 0..payload.element_count { let value = self.f32_value_at(value_index)? + read_low_rank_delta_value(bytes, payload, value_index)?; if !value.is_finite() { return Err(ErrorCode::InvalidHeader); } } } } Ok(()) } fn apply_adapter_payload( &mut self, bytes: &[u8], payload: AdapterDeltaPayload, ) -> Result<(), ErrorCode> { match &mut self.storage { TensorStorage::F32 { data } => apply_f32_adapter_payload(data, bytes, payload), TensorStorage::Q8 { weights, scales } => { apply_q8_adapter_payload(&self.entry, weights, scales, bytes, payload) } TensorStorage::Q4 { packed, scales, block_size, } => apply_q4_adapter_payload(&self.entry, packed, scales, *block_size, bytes, payload), } } fn f32_value_at(&self, value_index: usize) -> Result { match &self.storage { TensorStorage::F32 { data } => data .get(value_index) .copied() .ok_or(ErrorCode::ShapeMismatch), TensorStorage::Q8 { weights, scales } => { let (_rows, cols) = tensor_matrix_shape(&self.entry)?; let row = value_index / cols; let weight = weights.get(value_index).ok_or(ErrorCode::ShapeMismatch)?; let scale = scales.get(row).ok_or(ErrorCode::ShapeMismatch)?; Ok(f32::from(*weight) * *scale) } TensorStorage::Q4 { packed, scales, block_size, } => q4_value_at(packed, scales, *block_size, &self.entry, value_index), } } } impl Model { /// Parses and validates model bytes into a loaded model directory. pub fn load(bytes: &[u8]) -> Result { let parsed = parse_slm(bytes)?; let tokenizer_section = tokenizer_section(bytes, &parsed.header)?; let tokenizer = Tokenizer::from_section(tokenizer_section)?; let tokenizer_checksum = section_checksum(tokenizer_section, TOKENIZER_CHECKSUM_SEED); validate_required_tensors(&parsed)?; validate_required_shapes(&parsed)?; let tensors = load_tensors(bytes, &parsed)?; let parameter_count = parameter_count(&parsed.tensors)?; let tensor_layout_checksum = tensor_layout_checksum(&parsed.tensors); let top_level_indices = resolve_top_level_indices(&parsed)?; let layer_indices = resolve_layer_indices(&parsed)?; Ok(Self { parsed, tensors, tokenizer, parameter_count, tensor_layout_checksum, tokenizer_checksum, top_level_indices, layer_indices, }) } /// Returns a tensor entry by stable tensor name. pub fn tensor(&self, name: &str) -> Option { let hash = name_hash(name); self.parsed .tensors .iter() .copied() .find(|entry| entry.name_hash == hash) } /// Returns the parsed model view. pub fn parsed(&self) -> &ParsedSlm { &self.parsed } /// Returns parsed model header values. pub fn header(&self) -> &SlmHeader { &self.parsed.header } /// Returns the tokenizer parsed from the model tokenizer section. pub fn tokenizer(&self) -> &Tokenizer { &self.tokenizer } /// Returns pre-resolved top-level tensor indices used by generation. pub(crate) fn top_level_indices(&self) -> TopLevelTensorIndices { self.top_level_indices } /// Returns pre-resolved tensor indices for a decoder layer. pub(crate) fn layer_indices(&self, layer: usize) -> Result { self.layer_indices .get(layer) .copied() .ok_or(ErrorCode::MissingTensor) } /// Returns a loaded f32 tensor by stable tensor name. pub fn tensor_f32(&self, name: &str) -> Result<&[f32], ErrorCode> { self.loaded_tensor(name)?.f32_data() } /// Copies a named tensor into caller-owned f32 storage. pub fn copy_tensor_f32(&self, name: &str, out: &mut [f32]) -> Result<(), ErrorCode> { self.loaded_tensor(name)?.copy_f32(out) } /// Copies one row from a named tensor into caller-owned f32 storage. pub fn copy_tensor_row_f32( &self, name: &str, row: usize, cols: usize, out: &mut [f32], ) -> Result<(), ErrorCode> { self.loaded_tensor(name)?.copy_row_f32(row, cols, out) } /// Copies a pre-resolved tensor into caller-owned f32 storage. pub(crate) fn copy_tensor_f32_by_index( &self, index: usize, out: &mut [f32], ) -> Result<(), ErrorCode> { self.loaded_tensor_by_index(index)?.copy_f32(out) } /// Copies one row from a pre-resolved tensor into caller-owned f32 storage. pub(crate) fn copy_tensor_row_f32_by_index( &self, index: usize, row: usize, cols: usize, out: &mut [f32], ) -> Result<(), ErrorCode> { self.loaded_tensor_by_index(index)? .copy_row_f32(row, cols, out) } /// Computes a matrix-vector product for a named tensor using its native storage. pub fn matvec( &self, name: &str, rows: usize, cols: usize, vector: &[f32], out: &mut [f32], ) -> Result<(), ErrorCode> { let hash = name_hash(name); self.tensors .iter() .find(|tensor| tensor.entry.name_hash == hash) .ok_or(ErrorCode::MissingTensor)? .matvec(rows, cols, vector, out) } /// Computes a matrix-vector product for a pre-resolved tensor index. pub(crate) fn matvec_by_index( &self, index: usize, rows: usize, cols: usize, vector: &[f32], out: &mut [f32], ) -> Result<(), ErrorCode> { self.loaded_tensor_by_index(index)? .matvec(rows, cols, vector, out) } /// Returns a compact runtime quantization label for diagnostics. pub fn quantization_mode(&self) -> &'static str { let mut has_f32 = false; let mut has_q8 = false; let mut has_q4 = false; for tensor in &self.tensors { match tensor.entry.dtype { DTYPE_F32 => has_f32 = true, DTYPE_Q8_0 => has_q8 = true, DTYPE_Q4_0 => has_q4 = true, _ => {} } } match (has_f32, has_q8, has_q4) { (true, false, false) => "f32", (_, true, false) => "q8_0", (_, false, true) => "q4_0", (_, true, true) => "mixed", _ => "none", } } /// Validates an `ADP1`, `ASP1`, or `ALR1` adapter-delta package for this loaded model. pub fn validate_adapter_delta(&self, bytes: &[u8]) -> Result<(), ErrorCode> { let adapter = self.parse_adapter_delta(bytes)?; self.validate_adapter_payloads(bytes, &adapter) } /// Applies an `ADP1`, `ASP1`, or `ALR1` adapter-delta package to loaded tensors. pub fn apply_adapter_delta(&mut self, bytes: &[u8]) -> Result<(), ErrorCode> { let adapter = self.parse_adapter_delta(bytes)?; self.validate_adapter_payloads(bytes, &adapter)?; for (tensor, payload) in self.tensors.iter_mut().zip(adapter.entries()) { tensor.apply_adapter_payload(bytes, payload)?; } Ok(()) } fn parse_adapter_delta(&self, bytes: &[u8]) -> Result { let expected = AdapterExpected { flags: self.parsed.header.flags, tensors: &self.parsed.tensors, parameter_count: self.parameter_count, tensor_layout_checksum: self.tensor_layout_checksum, tokenizer_checksum: self.tokenizer_checksum, }; AdapterDelta::parse(bytes, &expected) } fn validate_adapter_payloads( &self, bytes: &[u8], adapter: &AdapterDelta, ) -> Result<(), ErrorCode> { for (tensor, payload) in self.tensors.iter().zip(adapter.entries()) { tensor.validate_adapter_payload(bytes, payload)?; } Ok(()) } fn loaded_tensor(&self, name: &str) -> Result<&LoadedTensor, ErrorCode> { let hash = name_hash(name); self.tensors .iter() .find(|tensor| tensor.entry.name_hash == hash) .ok_or(ErrorCode::MissingTensor) } fn loaded_tensor_by_index(&self, index: usize) -> Result<&LoadedTensor, ErrorCode> { self.tensors.get(index).ok_or(ErrorCode::MissingTensor) } } fn tokenizer_section<'a>(bytes: &'a [u8], header: &SlmHeader) -> Result<&'a [u8], ErrorCode> { let start = usize::try_from(header.tokenizer_offset).map_err(|_| ErrorCode::InvalidLength)?; let len = usize::try_from(header.tokenizer_length).map_err(|_| ErrorCode::InvalidLength)?; let end = start.checked_add(len).ok_or(ErrorCode::InvalidLength)?; bytes.get(start..end).ok_or(ErrorCode::InvalidHeader) } fn validate_required_tensors(parsed: &ParsedSlm) -> Result<(), ErrorCode> { let mut required = vec![name_hash("tok_embeddings.weight"), name_hash("norm.weight")]; if parsed.header.flags & FLAG_TIED_OUTPUT == 0 { required.push(name_hash("output.weight")); } for layer in 0..parsed.header.layer_count { for suffix in [ "attention_norm.weight", "ffn_norm.weight", "wq.weight", "wk.weight", "wv.weight", "wo.weight", "w1.weight", "w2.weight", "w3.weight", ] { required.push(name_hash(&format!("layers.{layer}.{suffix}"))); } } for hash in required { if !parsed.tensors.iter().any(|entry| entry.name_hash == hash) { return Err(ErrorCode::MissingTensor); } } Ok(()) } fn validate_required_shapes(parsed: &ParsedSlm) -> Result<(), ErrorCode> { let header = &parsed.header; require_shape( parsed, "tok_embeddings.weight", &[header.vocab_size, header.hidden_size], )?; require_shape(parsed, "norm.weight", &[header.hidden_size])?; if header.flags & FLAG_TIED_OUTPUT == 0 { require_shape( parsed, "output.weight", &[header.vocab_size, header.hidden_size], )?; } for layer in 0..header.layer_count { let prefix = format!("layers.{layer}"); require_shape( parsed, &format!("{prefix}.attention_norm.weight"), &[header.hidden_size], )?; require_shape( parsed, &format!("{prefix}.ffn_norm.weight"), &[header.hidden_size], )?; for suffix in ["wq.weight", "wk.weight", "wv.weight", "wo.weight"] { require_shape( parsed, &format!("{prefix}.{suffix}"), &[header.hidden_size, header.hidden_size], )?; } require_shape( parsed, &format!("{prefix}.w1.weight"), &[header.ffn_size, header.hidden_size], )?; require_shape( parsed, &format!("{prefix}.w2.weight"), &[header.hidden_size, header.ffn_size], )?; require_shape( parsed, &format!("{prefix}.w3.weight"), &[header.ffn_size, header.hidden_size], )?; } Ok(()) } fn resolve_top_level_indices(parsed: &ParsedSlm) -> Result { let tok_embeddings = find_tensor_index(parsed, "tok_embeddings.weight")?; let norm = find_tensor_index(parsed, "norm.weight")?; let output_projection = if parsed.header.flags & FLAG_TIED_OUTPUT != 0 { tok_embeddings } else { find_tensor_index(parsed, "output.weight")? }; Ok(TopLevelTensorIndices { tok_embeddings, norm, output_projection, }) } fn resolve_layer_indices(parsed: &ParsedSlm) -> Result, ErrorCode> { let mut layers = Vec::with_capacity(parsed.header.layer_count as usize); for layer in 0..parsed.header.layer_count { let prefix = format!("layers.{layer}"); layers.push(LayerTensorIndices { attention_norm: find_tensor_index(parsed, &format!("{prefix}.attention_norm.weight"))?, ffn_norm: find_tensor_index(parsed, &format!("{prefix}.ffn_norm.weight"))?, wq: find_tensor_index(parsed, &format!("{prefix}.wq.weight"))?, wk: find_tensor_index(parsed, &format!("{prefix}.wk.weight"))?, wv: find_tensor_index(parsed, &format!("{prefix}.wv.weight"))?, wo: find_tensor_index(parsed, &format!("{prefix}.wo.weight"))?, w1: find_tensor_index(parsed, &format!("{prefix}.w1.weight"))?, w2: find_tensor_index(parsed, &format!("{prefix}.w2.weight"))?, w3: find_tensor_index(parsed, &format!("{prefix}.w3.weight"))?, }); } Ok(layers) } fn find_tensor_index(parsed: &ParsedSlm, name: &str) -> Result { let hash = name_hash(name); parsed .tensors .iter() .position(|entry| entry.name_hash == hash) .ok_or(ErrorCode::MissingTensor) } fn require_shape(parsed: &ParsedSlm, name: &str, expected: &[u32]) -> Result<(), ErrorCode> { let hash = name_hash(name); let entry = parsed .tensors .iter() .find(|tensor| tensor.name_hash == hash) .ok_or(ErrorCode::MissingTensor)?; if !matches!(entry.dtype, DTYPE_F32 | DTYPE_Q8_0 | DTYPE_Q4_0) { return Err(ErrorCode::UnsupportedDType); } if tensor_dims(entry) != expected { return Err(ErrorCode::ShapeMismatch); } Ok(()) } fn load_tensors(bytes: &[u8], parsed: &ParsedSlm) -> Result, ErrorCode> { let mut tensors = Vec::with_capacity(parsed.tensors.len()); for entry in &parsed.tensors { let storage = match entry.dtype { DTYPE_F32 => load_f32_tensor(bytes, entry)?, DTYPE_Q8_0 => load_q8_tensor(bytes, entry)?, DTYPE_Q4_0 => load_q4_tensor(bytes, entry)?, _ => return Err(ErrorCode::UnsupportedDType), }; tensors.push(LoadedTensor { entry: *entry, storage, }); } Ok(tensors) } fn load_f32_tensor(bytes: &[u8], entry: &TensorEntry) -> Result { let element_count = tensor_element_count(entry)?; let expected_bytes = element_count .checked_mul(4) .ok_or(ErrorCode::InvalidLength)?; if entry.byte_length as usize != expected_bytes { return Err(ErrorCode::InvalidTensorDirectory); } let raw = tensor_bytes(bytes, entry.byte_offset, expected_bytes)?; let mut f32_data = Vec::with_capacity(element_count); for chunk in raw.chunks_exact(4) { let value = f32::from_le_bytes(chunk.try_into().map_err(|_| ErrorCode::InvalidHeader)?); f32_data.push(value); } Ok(TensorStorage::F32 { data: f32_data }) } fn load_q8_tensor(bytes: &[u8], entry: &TensorEntry) -> Result { let element_count = tensor_element_count(entry)?; if entry.byte_length as usize != element_count || entry.scale_offset == 0 { return Err(ErrorCode::InvalidTensorDirectory); } let (rows, _cols) = tensor_matrix_shape(entry)?; let raw = tensor_bytes(bytes, entry.byte_offset, element_count)?; let scales = scale_values(bytes, entry.scale_offset, rows)?; let mut weights = Vec::with_capacity(element_count); for value in raw { weights.push(*value as i8); } Ok(TensorStorage::Q8 { weights, scales }) } fn load_q4_tensor(bytes: &[u8], entry: &TensorEntry) -> Result { let element_count = tensor_element_count(entry)?; if element_count % 2 != 0 || entry.scale_offset == 0 || entry.block_size == 0 { return Err(ErrorCode::InvalidTensorDirectory); } let (rows, cols) = tensor_matrix_shape(entry)?; let block_size = entry.block_size as usize; if block_size == 0 || block_size % 2 != 0 || cols % block_size != 0 { return Err(ErrorCode::ShapeMismatch); } let packed_len = element_count / 2; if entry.byte_length as usize != packed_len { return Err(ErrorCode::InvalidTensorDirectory); } let blocks_per_row = cols / block_size; let raw = tensor_bytes(bytes, entry.byte_offset, packed_len)?; let packed = raw.to_vec(); let scales = scale_values( bytes, entry.scale_offset, rows.checked_mul(blocks_per_row) .ok_or(ErrorCode::InvalidLength)?, )?; Ok(TensorStorage::Q4 { packed, scales, block_size, }) } fn tensor_bytes(bytes: &[u8], offset: u64, len: usize) -> Result<&[u8], ErrorCode> { let start = usize::try_from(offset).map_err(|_| ErrorCode::InvalidLength)?; let end = start.checked_add(len).ok_or(ErrorCode::InvalidLength)?; bytes .get(start..end) .ok_or(ErrorCode::InvalidTensorDirectory) } fn scale_values(bytes: &[u8], offset: u64, count: usize) -> Result, ErrorCode> { let byte_len = count.checked_mul(4).ok_or(ErrorCode::InvalidLength)?; let raw = tensor_bytes(bytes, offset, byte_len)?; let mut scales = Vec::with_capacity(count); for chunk in raw.chunks_exact(4) { scales.push(f32::from_le_bytes( chunk.try_into().map_err(|_| ErrorCode::InvalidHeader)?, )); } Ok(scales) } fn copy_q4_to_f32( packed: &[u8], scales: &[f32], block_size: usize, entry: &TensorEntry, out: &mut [f32], ) -> Result<(), ErrorCode> { let (rows, cols) = tensor_matrix_shape(entry)?; for row in 0..rows { let start = row.checked_mul(cols).ok_or(ErrorCode::InvalidLength)?; copy_q4_row_to_f32( packed, scales, block_size, entry, row, cols, &mut out[start..start + cols], )?; } Ok(()) } fn copy_q4_row_to_f32( packed: &[u8], scales: &[f32], block_size: usize, entry: &TensorEntry, row: usize, cols: usize, out: &mut [f32], ) -> Result<(), ErrorCode> { let (rows, expected_cols) = tensor_matrix_shape(entry)?; if row >= rows || cols != expected_cols || out.len() != cols || block_size == 0 || block_size % 2 != 0 || cols % block_size != 0 { return Err(ErrorCode::ShapeMismatch); } let bytes_per_row = cols / 2; let blocks_per_row = cols / block_size; if packed.len() != rows .checked_mul(bytes_per_row) .ok_or(ErrorCode::InvalidLength)? || scales.len() != rows .checked_mul(blocks_per_row) .ok_or(ErrorCode::InvalidLength)? { return Err(ErrorCode::ShapeMismatch); } let row_byte_start = row .checked_mul(bytes_per_row) .ok_or(ErrorCode::InvalidLength)?; for byte_index in 0..bytes_per_row { let col = byte_index * 2; let scale = scales[row * blocks_per_row + col / block_size]; let pair = packed[row_byte_start + byte_index]; out[col] = f32::from(sign_extend_4(pair & 0x0f)) * scale; out[col + 1] = f32::from(sign_extend_4(pair >> 4)) * scale; } Ok(()) } fn apply_f32_adapter_payload( data: &mut [f32], bytes: &[u8], payload: AdapterDeltaPayload, ) -> Result<(), ErrorCode> { if data.len() != payload.element_count { return Err(ErrorCode::ShapeMismatch); } match payload.kind { AdapterDeltaPayloadKind::RawF32 => { for (value_index, value) in data.iter_mut().enumerate() { *value += adapter_delta_value(bytes, payload, value_index)?; } } AdapterDeltaPayloadKind::SparseF32 { pair_count } => { for pair_index in 0..pair_count { let (value_index, delta) = read_sparse_delta_pair(bytes, payload, pair_index)?; let value = data.get_mut(value_index).ok_or(ErrorCode::ShapeMismatch)?; *value += delta; } } AdapterDeltaPayloadKind::LowRankF32 { .. } => { for (value_index, value) in data.iter_mut().enumerate() { *value += read_low_rank_delta_value(bytes, payload, value_index)?; } } } Ok(()) } fn apply_q8_adapter_payload( entry: &TensorEntry, weights: &mut [i8], scales: &mut [f32], bytes: &[u8], payload: AdapterDeltaPayload, ) -> Result<(), ErrorCode> { let (rows, cols) = tensor_matrix_shape(entry)?; if payload.element_count != rows.checked_mul(cols).ok_or(ErrorCode::InvalidLength)? || weights.len() != payload.element_count || scales.len() != rows { return Err(ErrorCode::ShapeMismatch); } let mut row_values = vec![0.0f32; cols]; let mut row_weights = vec![0i8; cols]; match payload.kind { AdapterDeltaPayloadKind::RawF32 => { for row in 0..rows { let row_start = row.checked_mul(cols).ok_or(ErrorCode::InvalidLength)?; let base_scale = scales[row]; for col in 0..cols { let index = row_start + col; row_values[col] = f32::from(weights[index]) * base_scale + adapter_delta_value(bytes, payload, index)?; } scales[row] = quantize_q8_row(&row_values, &mut row_weights)?; weights[row_start..row_start + cols].copy_from_slice(&row_weights); } } AdapterDeltaPayloadKind::SparseF32 { pair_count } => { let mut pair_index = 0usize; for row in 0..rows { let row_start = row.checked_mul(cols).ok_or(ErrorCode::InvalidLength)?; let row_end = row_start .checked_add(cols) .ok_or(ErrorCode::InvalidLength)?; let base_scale = scales[row]; for col in 0..cols { row_values[col] = f32::from(weights[row_start + col]) * base_scale; } while pair_index < pair_count { let (value_index, delta) = read_sparse_delta_pair(bytes, payload, pair_index)?; if value_index >= row_end { break; } if value_index < row_start { return Err(ErrorCode::ShapeMismatch); } row_values[value_index - row_start] += delta; pair_index += 1; } scales[row] = quantize_q8_row(&row_values, &mut row_weights)?; weights[row_start..row_start + cols].copy_from_slice(&row_weights); } if pair_index != pair_count { return Err(ErrorCode::ShapeMismatch); } } AdapterDeltaPayloadKind::LowRankF32 { .. } => { for row in 0..rows { let row_start = row.checked_mul(cols).ok_or(ErrorCode::InvalidLength)?; let base_scale = scales[row]; for col in 0..cols { let index = row_start + col; row_values[col] = f32::from(weights[index]) * base_scale + read_low_rank_delta_value(bytes, payload, index)?; } scales[row] = quantize_q8_row(&row_values, &mut row_weights)?; weights[row_start..row_start + cols].copy_from_slice(&row_weights); } } } Ok(()) } fn apply_q4_adapter_payload( entry: &TensorEntry, packed: &mut [u8], scales: &mut [f32], block_size: usize, bytes: &[u8], payload: AdapterDeltaPayload, ) -> Result<(), ErrorCode> { let (rows, cols) = tensor_matrix_shape(entry)?; if block_size == 0 || block_size % 2 != 0 || cols % block_size != 0 || payload.element_count != rows.checked_mul(cols).ok_or(ErrorCode::InvalidLength)? { return Err(ErrorCode::ShapeMismatch); } let bytes_per_row = cols / 2; let blocks_per_row = cols / block_size; if packed.len() != rows .checked_mul(bytes_per_row) .ok_or(ErrorCode::InvalidLength)? || scales.len() != rows .checked_mul(blocks_per_row) .ok_or(ErrorCode::InvalidLength)? { return Err(ErrorCode::ShapeMismatch); } let mut block_weights = vec![0i8; block_size]; match payload.kind { AdapterDeltaPayloadKind::RawF32 => { let mut block_values = vec![0.0f32; block_size]; for row in 0..rows { for block in 0..blocks_per_row { let scale_index = row * blocks_per_row + block; let base_scale = scales[scale_index]; for block_col in 0..block_size { let col = block * block_size + block_col; let index = row * cols + col; let byte_index = row * bytes_per_row + col / 2; let byte = packed[byte_index]; let nibble = if col % 2 == 0 { byte & 0x0f } else { byte >> 4 }; block_values[block_col] = f32::from(sign_extend_4(nibble)) * base_scale + adapter_delta_value(bytes, payload, index)?; } scales[scale_index] = quantize_q4_block(&block_values, &mut block_weights)?; let byte_start = row * bytes_per_row + block * (block_size / 2); for pair in 0..block_size / 2 { packed[byte_start + pair] = pack_q4_pair(block_weights[pair * 2], block_weights[pair * 2 + 1]); } } } } AdapterDeltaPayloadKind::SparseF32 { pair_count } => { let mut row_values = vec![0.0f32; cols]; let mut pair_index = 0usize; for row in 0..rows { let row_start = row.checked_mul(cols).ok_or(ErrorCode::InvalidLength)?; let row_end = row_start .checked_add(cols) .ok_or(ErrorCode::InvalidLength)?; for col in 0..cols { let byte_index = row * bytes_per_row + col / 2; let byte = packed[byte_index]; let nibble = if col % 2 == 0 { byte & 0x0f } else { byte >> 4 }; let scale = scales[row * blocks_per_row + col / block_size]; row_values[col] = f32::from(sign_extend_4(nibble)) * scale; } while pair_index < pair_count { let (value_index, delta) = read_sparse_delta_pair(bytes, payload, pair_index)?; if value_index >= row_end { break; } if value_index < row_start { return Err(ErrorCode::ShapeMismatch); } row_values[value_index - row_start] += delta; pair_index += 1; } for block in 0..blocks_per_row { let scale_index = row * blocks_per_row + block; let value_start = block * block_size; scales[scale_index] = quantize_q4_block( &row_values[value_start..value_start + block_size], &mut block_weights, )?; let byte_start = row * bytes_per_row + block * (block_size / 2); for pair in 0..block_size / 2 { packed[byte_start + pair] = pack_q4_pair(block_weights[pair * 2], block_weights[pair * 2 + 1]); } } } if pair_index != pair_count { return Err(ErrorCode::ShapeMismatch); } } AdapterDeltaPayloadKind::LowRankF32 { .. } => { let mut block_values = vec![0.0f32; block_size]; for row in 0..rows { for block in 0..blocks_per_row { let scale_index = row * blocks_per_row + block; let base_scale = scales[scale_index]; for block_col in 0..block_size { let col = block * block_size + block_col; let index = row * cols + col; let byte_index = row * bytes_per_row + col / 2; let byte = packed[byte_index]; let nibble = if col % 2 == 0 { byte & 0x0f } else { byte >> 4 }; block_values[block_col] = f32::from(sign_extend_4(nibble)) * base_scale + read_low_rank_delta_value(bytes, payload, index)?; } scales[scale_index] = quantize_q4_block(&block_values, &mut block_weights)?; let byte_start = row * bytes_per_row + block * (block_size / 2); for pair in 0..block_size / 2 { packed[byte_start + pair] = pack_q4_pair(block_weights[pair * 2], block_weights[pair * 2 + 1]); } } } } } Ok(()) } fn q4_value_at( packed: &[u8], scales: &[f32], block_size: usize, entry: &TensorEntry, value_index: usize, ) -> Result { let (rows, cols) = tensor_matrix_shape(entry)?; if block_size == 0 || block_size % 2 != 0 || cols % block_size != 0 { return Err(ErrorCode::ShapeMismatch); } let element_count = rows.checked_mul(cols).ok_or(ErrorCode::InvalidLength)?; if value_index >= element_count { return Err(ErrorCode::ShapeMismatch); } let bytes_per_row = cols / 2; let blocks_per_row = cols / block_size; if packed.len() != rows .checked_mul(bytes_per_row) .ok_or(ErrorCode::InvalidLength)? || scales.len() != rows .checked_mul(blocks_per_row) .ok_or(ErrorCode::InvalidLength)? { return Err(ErrorCode::ShapeMismatch); } let row = value_index / cols; let col = value_index % cols; let byte = packed[row * bytes_per_row + col / 2]; let nibble = if col % 2 == 0 { byte & 0x0f } else { byte >> 4 }; let scale = scales[row * blocks_per_row + col / block_size]; Ok(f32::from(sign_extend_4(nibble)) * scale) } fn adapter_delta_value( bytes: &[u8], payload: AdapterDeltaPayload, value_index: usize, ) -> Result { if !matches!(payload.kind, AdapterDeltaPayloadKind::RawF32) { return Err(ErrorCode::ShapeMismatch); } if value_index >= payload.element_count { return Err(ErrorCode::ShapeMismatch); } let delta_offset = payload .byte_offset .checked_add(value_index.checked_mul(4).ok_or(ErrorCode::InvalidLength)?) .ok_or(ErrorCode::InvalidLength)?; read_f32(bytes, delta_offset) } fn tensor_dims(entry: &TensorEntry) -> Vec { [entry.dim0, entry.dim1, entry.dim2, entry.dim3] .into_iter() .take(entry.rank as usize) .collect() } fn tensor_element_count(entry: &TensorEntry) -> Result { let mut total = 1usize; for dim in tensor_dims(entry) { if dim == 0 { return Err(ErrorCode::ShapeMismatch); } total = total .checked_mul(dim as usize) .ok_or(ErrorCode::InvalidLength)?; } Ok(total) } fn tensor_matrix_shape(entry: &TensorEntry) -> Result<(usize, usize), ErrorCode> { let dims = tensor_dims(entry); if dims.is_empty() { return Err(ErrorCode::ShapeMismatch); } let rows = if dims.len() == 1 { 1 } else { dims[0] as usize }; let mut cols = 1usize; let col_dims = if dims.len() == 1 { &dims[..] } else { &dims[1..] }; for dim in col_dims { cols = cols .checked_mul(*dim as usize) .ok_or(ErrorCode::InvalidLength)?; } Ok((rows, cols)) } fn sign_extend_4(value: u8) -> i8 { let nibble = (value & 0x0f) as i8; if nibble >= 8 { nibble - 16 } else { nibble } } #[cfg(test)] mod tests { use super::*; use crate::model_format::{simple_checksum, HEADER_LEN, SLM_VERSION, TENSOR_ENTRY_LEN}; use crate::ops::matvec_f32; const ADAPTER_HEADER_LEN: usize = 64; const ADAPTER_ENTRY_LEN: usize = 64; const ADAPTER_CHECKSUM_OFFSET: usize = 56; const LOW_RANK_PAYLOAD_HEADER_LEN: usize = 16; fn valid_header_without_tensors() -> Vec { let tokenizer = { let mut bytes = Vec::new(); bytes.extend_from_slice(b"BTOK"); bytes.extend_from_slice(&1u32.to_le_bytes()); bytes.extend_from_slice(&260u32.to_le_bytes()); bytes.extend_from_slice(&256u32.to_le_bytes()); bytes.extend_from_slice(&257u32.to_le_bytes()); bytes.extend_from_slice(&258u32.to_le_bytes()); bytes.extend_from_slice(&259u32.to_le_bytes()); bytes }; let directory_offset = ((HEADER_LEN + tokenizer.len() + 63) & !63) as u64; let tensor_data_offset = ((directory_offset as usize + TENSOR_ENTRY_LEN + 63) & !63) as u64; let mut bytes = vec![0u8; tensor_data_offset as usize]; bytes[0..4].copy_from_slice(b"SLM1"); bytes[4..8].copy_from_slice(&SLM_VERSION.to_le_bytes()); bytes[8..12].copy_from_slice(&(HEADER_LEN as u32).to_le_bytes()); bytes[12..16].copy_from_slice(&1u32.to_le_bytes()); bytes[16..20].copy_from_slice(&0u32.to_le_bytes()); bytes[20..24].copy_from_slice(&260u32.to_le_bytes()); bytes[24..28].copy_from_slice(&4u32.to_le_bytes()); bytes[28..32].copy_from_slice(&8u32.to_le_bytes()); bytes[32..36].copy_from_slice(&1u32.to_le_bytes()); bytes[36..40].copy_from_slice(&2u32.to_le_bytes()); bytes[40..44].copy_from_slice(&2u32.to_le_bytes()); bytes[44..48].copy_from_slice(&4u32.to_le_bytes()); bytes[48..52].copy_from_slice(&16u32.to_le_bytes()); bytes[52..56].copy_from_slice(&16u32.to_le_bytes()); bytes[56..60].copy_from_slice(&10000.0f32.to_le_bytes()); bytes[60..64].copy_from_slice(&0.00001f32.to_le_bytes()); bytes[64..72].copy_from_slice(&(HEADER_LEN as u64).to_le_bytes()); bytes[72..80].copy_from_slice(&(tokenizer.len() as u64).to_le_bytes()); bytes[80..88].copy_from_slice(&directory_offset.to_le_bytes()); bytes[88..92].copy_from_slice(&0u32.to_le_bytes()); bytes[92..100].copy_from_slice(&tensor_data_offset.to_le_bytes()); bytes[100..108].copy_from_slice(&0u64.to_le_bytes()); bytes[HEADER_LEN..HEADER_LEN + tokenizer.len()].copy_from_slice(&tokenizer); let checksum = simple_checksum(&bytes); bytes[100..108].copy_from_slice(&checksum.to_le_bytes()); bytes } fn build_adapter_bytes(model: &Model, mut delta: F) -> Vec where F: FnMut(usize, usize, &TensorEntry) -> f32, { let tensors = &model.parsed().tensors; let data_offset = align_to_64(ADAPTER_HEADER_LEN + tensors.len() * ADAPTER_ENTRY_LEN); let mut cursor = data_offset; let mut offsets = Vec::with_capacity(tensors.len()); let mut lengths = Vec::with_capacity(tensors.len()); let mut payloads = Vec::with_capacity(tensors.len()); for (tensor_index, tensor) in tensors.iter().enumerate() { cursor = align_to_64(cursor); offsets.push(cursor); let element_count = tensor_element_count(tensor).unwrap(); let byte_length = element_count * 4; lengths.push(byte_length); let mut payload = vec![0u8; byte_length]; for value_index in 0..element_count { let value = delta(tensor_index, value_index, tensor); payload[value_index * 4..value_index * 4 + 4].copy_from_slice(&value.to_le_bytes()); } cursor += byte_length; payloads.push(payload); } let mut bytes = vec![0u8; cursor]; bytes[0..4].copy_from_slice(b"ADP1"); write_u32(&mut bytes, 4, 1); write_u32(&mut bytes, 8, ADAPTER_HEADER_LEN as u32); write_u32(&mut bytes, 12, tensors.len() as u32); write_u32(&mut bytes, 16, model.header().flags); write_u32(&mut bytes, 20, ADAPTER_ENTRY_LEN as u32); write_u64(&mut bytes, 24, model.parameter_count); write_u64(&mut bytes, 32, model.tensor_layout_checksum); write_u64(&mut bytes, 40, model.tokenizer_checksum); write_u64(&mut bytes, 48, data_offset as u64); write_u64(&mut bytes, ADAPTER_CHECKSUM_OFFSET, 0); for (index, tensor) in tensors.iter().enumerate() { let entry = ADAPTER_HEADER_LEN + index * ADAPTER_ENTRY_LEN; write_u64(&mut bytes, entry, tensor.name_hash); write_u32(&mut bytes, entry + 8, tensor.rank); write_u32(&mut bytes, entry + 12, tensor.dim0); write_u32(&mut bytes, entry + 16, tensor.dim1); write_u32(&mut bytes, entry + 20, tensor.dim2); write_u32(&mut bytes, entry + 24, tensor.dim3); write_u32(&mut bytes, entry + 28, 0); write_u64(&mut bytes, entry + 32, offsets[index] as u64); write_u64(&mut bytes, entry + 40, lengths[index] as u64); write_u64( &mut bytes, entry + 48, tensor_element_count(tensor).unwrap() as u64, ); write_u64( &mut bytes, entry + 56, adapter_payload_checksum(&payloads[index]), ); let start = offsets[index]; bytes[start..start + lengths[index]].copy_from_slice(&payloads[index]); } refresh_adapter_checksum(&mut bytes); bytes } fn build_sparse_adapter_bytes(model: &Model, mut delta: F) -> Vec where F: FnMut(usize, usize, &TensorEntry) -> Option, { let tensors = &model.parsed().tensors; let data_offset = align_to_64(ADAPTER_HEADER_LEN + tensors.len() * ADAPTER_ENTRY_LEN); let mut cursor = data_offset; let mut offsets = Vec::with_capacity(tensors.len()); let mut lengths = Vec::with_capacity(tensors.len()); let mut payloads = Vec::with_capacity(tensors.len()); for (tensor_index, tensor) in tensors.iter().enumerate() { cursor = align_to_64(cursor); offsets.push(cursor); let element_count = tensor_element_count(tensor).unwrap(); let mut payload = Vec::new(); for value_index in 0..element_count { if let Some(value) = delta(tensor_index, value_index, tensor) { payload.extend_from_slice(&(value_index as u64).to_le_bytes()); payload.extend_from_slice(&value.to_le_bytes()); } } lengths.push(payload.len()); cursor += payload.len(); payloads.push(payload); } let mut bytes = vec![0u8; cursor]; bytes[0..4].copy_from_slice(b"ASP1"); write_u32(&mut bytes, 4, 1); write_u32(&mut bytes, 8, ADAPTER_HEADER_LEN as u32); write_u32(&mut bytes, 12, tensors.len() as u32); write_u32(&mut bytes, 16, model.header().flags); write_u32(&mut bytes, 20, ADAPTER_ENTRY_LEN as u32); write_u64(&mut bytes, 24, model.parameter_count); write_u64(&mut bytes, 32, model.tensor_layout_checksum); write_u64(&mut bytes, 40, model.tokenizer_checksum); write_u64(&mut bytes, 48, data_offset as u64); write_u64(&mut bytes, ADAPTER_CHECKSUM_OFFSET, 0); for (index, tensor) in tensors.iter().enumerate() { let entry = ADAPTER_HEADER_LEN + index * ADAPTER_ENTRY_LEN; write_u64(&mut bytes, entry, tensor.name_hash); write_u32(&mut bytes, entry + 8, tensor.rank); write_u32(&mut bytes, entry + 12, tensor.dim0); write_u32(&mut bytes, entry + 16, tensor.dim1); write_u32(&mut bytes, entry + 20, tensor.dim2); write_u32(&mut bytes, entry + 24, tensor.dim3); write_u32(&mut bytes, entry + 28, 0); write_u64(&mut bytes, entry + 32, offsets[index] as u64); write_u64(&mut bytes, entry + 40, lengths[index] as u64); write_u64( &mut bytes, entry + 48, tensor_element_count(tensor).unwrap() as u64, ); write_u64( &mut bytes, entry + 56, adapter_payload_checksum(&payloads[index]), ); let start = offsets[index]; bytes[start..start + lengths[index]].copy_from_slice(&payloads[index]); } refresh_adapter_checksum(&mut bytes); bytes } fn build_low_rank_adapter_bytes(model: &Model, mut factors: F) -> Vec where F: FnMut(usize, &TensorEntry) -> Option<(usize, usize, Vec, Vec)>, { let tensors = &model.parsed().tensors; let data_offset = align_to_64(ADAPTER_HEADER_LEN + tensors.len() * ADAPTER_ENTRY_LEN); let mut cursor = data_offset; let mut offsets = Vec::with_capacity(tensors.len()); let mut lengths = Vec::with_capacity(tensors.len()); let mut payloads = Vec::with_capacity(tensors.len()); for (tensor_index, tensor) in tensors.iter().enumerate() { cursor = align_to_64(cursor); offsets.push(cursor); let payload = if let Some((rows, cols, a_values, b_values)) = factors(tensor_index, tensor) { let factor_rank = a_values.len() / rows; assert!(factor_rank > 0); assert_eq!(a_values.len(), factor_rank * rows); assert_eq!(b_values.len(), factor_rank * cols); assert_eq!(tensor_element_count(tensor).unwrap(), rows * cols); let mut payload = vec![0u8; LOW_RANK_PAYLOAD_HEADER_LEN + (a_values.len() + b_values.len()) * 4]; write_u32(&mut payload, 0, rows as u32); write_u32(&mut payload, 4, cols as u32); write_u32(&mut payload, 8, factor_rank as u32); write_u32(&mut payload, 12, 0); let mut offset = LOW_RANK_PAYLOAD_HEADER_LEN; for value in a_values.iter().chain(b_values.iter()) { payload[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); offset += 4; } payload } else { Vec::new() }; lengths.push(payload.len()); cursor += payload.len(); payloads.push(payload); } let mut bytes = vec![0u8; cursor]; bytes[0..4].copy_from_slice(b"ALR1"); write_u32(&mut bytes, 4, 1); write_u32(&mut bytes, 8, ADAPTER_HEADER_LEN as u32); write_u32(&mut bytes, 12, tensors.len() as u32); write_u32(&mut bytes, 16, model.header().flags); write_u32(&mut bytes, 20, ADAPTER_ENTRY_LEN as u32); write_u64(&mut bytes, 24, model.parameter_count); write_u64(&mut bytes, 32, model.tensor_layout_checksum); write_u64(&mut bytes, 40, model.tokenizer_checksum); write_u64(&mut bytes, 48, data_offset as u64); write_u64(&mut bytes, ADAPTER_CHECKSUM_OFFSET, 0); for (index, tensor) in tensors.iter().enumerate() { let entry = ADAPTER_HEADER_LEN + index * ADAPTER_ENTRY_LEN; write_u64(&mut bytes, entry, tensor.name_hash); write_u32(&mut bytes, entry + 8, tensor.rank); write_u32(&mut bytes, entry + 12, tensor.dim0); write_u32(&mut bytes, entry + 16, tensor.dim1); write_u32(&mut bytes, entry + 20, tensor.dim2); write_u32(&mut bytes, entry + 24, tensor.dim3); write_u32(&mut bytes, entry + 28, 0); write_u64(&mut bytes, entry + 32, offsets[index] as u64); write_u64(&mut bytes, entry + 40, lengths[index] as u64); write_u64( &mut bytes, entry + 48, tensor_element_count(tensor).unwrap() as u64, ); write_u64( &mut bytes, entry + 56, adapter_payload_checksum(&payloads[index]), ); let start = offsets[index]; bytes[start..start + lengths[index]].copy_from_slice(&payloads[index]); } refresh_adapter_checksum(&mut bytes); bytes } fn refresh_adapter_checksum(bytes: &mut [u8]) { write_u64(bytes, ADAPTER_CHECKSUM_OFFSET, 0); let checksum = adapter_checksum(bytes); write_u64(bytes, ADAPTER_CHECKSUM_OFFSET, checksum); } fn align_to_64(value: usize) -> usize { (value + 63) & !63 } fn adapter_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x6164617074657231u64; for (index, byte) in bytes.iter().enumerate() { let value = if (ADAPTER_CHECKSUM_OFFSET..ADAPTER_CHECKSUM_OFFSET + 8).contains(&index) { 0 } else { *byte }; acc ^= u64::from(value).wrapping_add((index as u64) << 3); acc = acc.rotate_left(11).wrapping_mul(0x100000001b3); } acc } fn adapter_payload_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x64656c7461663332u64; for (index, byte) in bytes.iter().enumerate() { acc ^= u64::from(*byte).wrapping_add((index as u64) << 1); acc = acc.rotate_left(7).wrapping_mul(0x100000001b3); } acc } fn write_u32(bytes: &mut [u8], offset: usize, value: u32) { bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); } fn write_u64(bytes: &mut [u8], offset: usize, value: u64) { bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); } #[test] fn missing_tensor_rejection() { let error = Model::load(&valid_header_without_tensors()).unwrap_err(); assert_eq!(error, ErrorCode::MissingTensor); } #[test] fn q8_named_matvec_matches_copied_reference() { let model = Model::load(include_bytes!("../../models/tiny-test-model-q8.slm")).unwrap(); let vector = [1.0f32; 8]; let mut direct = [0.0f32; 260]; let mut decoded = [0.0f32; 260]; model .matvec("output.weight", 260, 8, &vector, &mut direct) .unwrap(); let mut copied = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut copied).unwrap(); matvec_f32(&copied, 260, 8, &vector, &mut decoded).unwrap(); for index in 0..direct.len() { assert!((direct[index] - decoded[index]).abs() < 0.0001); } } #[test] fn q4_named_matvec_matches_copied_reference() { let model = Model::load(include_bytes!("../../models/tiny-test-model-q4.slm")).unwrap(); let vector = [1.0f32; 8]; let mut direct = [0.0f32; 260]; let mut decoded = [0.0f32; 260]; model .matvec("output.weight", 260, 8, &vector, &mut direct) .unwrap(); let mut copied = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut copied).unwrap(); matvec_f32(&copied, 260, 8, &vector, &mut decoded).unwrap(); for index in 0..direct.len() { assert!((direct[index] - decoded[index]).abs() < 0.0001); } } #[test] fn applies_f32_adapter_delta_to_loaded_tensor() { let mut model = Model::load(include_bytes!("../../models/tiny-test-model.slm")).unwrap(); let mut before = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut before).unwrap(); let adapter = build_adapter_bytes(&model, |_tensor_index, value_index, tensor| { if tensor.name_hash == name_hash("output.weight") && value_index == 0 { 0.25 } else { 0.0 } }); model.apply_adapter_delta(&adapter).unwrap(); let mut after = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut after).unwrap(); assert_eq!(after[0], before[0] + 0.25); assert_eq!(after[1], before[1]); } #[test] fn validates_f32_adapter_delta_without_mutating_tensor() { let model = Model::load(include_bytes!("../../models/tiny-test-model.slm")).unwrap(); let mut before = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut before).unwrap(); let adapter = build_adapter_bytes(&model, |_tensor_index, value_index, tensor| { if tensor.name_hash == name_hash("output.weight") && value_index == 0 { 0.25 } else { 0.0 } }); model.validate_adapter_delta(&adapter).unwrap(); let mut after = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut after).unwrap(); assert_eq!(after, before); } #[test] fn applies_sparse_adapter_delta_to_loaded_f32_tensor() { let mut model = Model::load(include_bytes!("../../models/tiny-test-model.slm")).unwrap(); let mut before = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut before).unwrap(); let adapter = build_sparse_adapter_bytes(&model, |_tensor_index, value_index, tensor| { if tensor.name_hash == name_hash("output.weight") && value_index == 0 { Some(0.25) } else { None } }); model.apply_adapter_delta(&adapter).unwrap(); let mut after = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut after).unwrap(); assert_eq!(after[0], before[0] + 0.25); assert_eq!(after[1], before[1]); } #[test] fn applies_low_rank_adapter_delta_to_loaded_f32_tensor() { let mut model = Model::load(include_bytes!("../../models/tiny-test-model.slm")).unwrap(); let mut before = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut before).unwrap(); let adapter = build_low_rank_adapter_bytes(&model, |_tensor_index, tensor| { if tensor.name_hash != name_hash("output.weight") { return None; } let (rows, cols) = tensor_matrix_shape(tensor).unwrap(); let mut a = vec![0.0f32; rows]; let b = vec![1.0f32; cols]; a[0] = 0.25; Some((rows, cols, a, b)) }); model.apply_adapter_delta(&adapter).unwrap(); let mut after = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut after).unwrap(); assert_eq!(after[0], before[0] + 0.25); assert_eq!(after[7], before[7] + 0.25); assert_eq!(after[8], before[8]); } #[test] fn adapter_identity_drift_rejects_without_mutating_tensor() { let mut model = Model::load(include_bytes!("../../models/tiny-test-model.slm")).unwrap(); let mut before = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut before).unwrap(); let mut adapter = build_adapter_bytes(&model, |_tensor_index, value_index, tensor| { if tensor.name_hash == name_hash("output.weight") && value_index == 0 { 0.25 } else { 0.0 } }); write_u32(&mut adapter, 16, model.header().flags ^ 1); refresh_adapter_checksum(&mut adapter); assert_eq!( model.apply_adapter_delta(&adapter).unwrap_err(), ErrorCode::ShapeMismatch ); let mut after = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut after).unwrap(); assert_eq!(after, before); } #[test] fn applies_q8_adapter_delta_to_loaded_compact_tensor() { let mut model = Model::load(include_bytes!("../../models/tiny-test-model-q8.slm")).unwrap(); let mut before = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut before).unwrap(); let adapter = build_adapter_bytes(&model, |_tensor_index, value_index, tensor| { if tensor.name_hash == name_hash("output.weight") && value_index < 8 { 1.0 } else { 0.0 } }); model.apply_adapter_delta(&adapter).unwrap(); let mut after = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut after).unwrap(); let before_sum = before[..8].iter().sum::(); let after_sum = after[..8].iter().sum::(); assert!(after_sum > before_sum + 4.0); assert_eq!(model.quantization_mode(), "q8_0"); assert_eq!( model.tensor_f32("output.weight").unwrap_err(), ErrorCode::UnsupportedDType ); } #[test] fn applies_sparse_adapter_delta_to_loaded_q8_tensor() { let mut model = Model::load(include_bytes!("../../models/tiny-test-model-q8.slm")).unwrap(); let mut before = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut before).unwrap(); let adapter = build_sparse_adapter_bytes(&model, |_tensor_index, value_index, tensor| { if tensor.name_hash == name_hash("output.weight") && value_index < 8 { Some(1.0) } else { None } }); model.apply_adapter_delta(&adapter).unwrap(); let mut after = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut after).unwrap(); let before_sum = before[..8].iter().sum::(); let after_sum = after[..8].iter().sum::(); assert!(after_sum > before_sum + 4.0); assert_eq!(model.quantization_mode(), "q8_0"); } #[test] fn applies_low_rank_adapter_delta_to_loaded_q8_tensor() { let mut model = Model::load(include_bytes!("../../models/tiny-test-model-q8.slm")).unwrap(); let mut before = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut before).unwrap(); let adapter = build_low_rank_adapter_bytes(&model, |_tensor_index, tensor| { if tensor.name_hash != name_hash("output.weight") { return None; } let (rows, cols) = tensor_matrix_shape(tensor).unwrap(); let mut a = vec![0.0f32; rows]; let b = vec![1.0f32; cols]; a[0] = 1.0; Some((rows, cols, a, b)) }); model.apply_adapter_delta(&adapter).unwrap(); let mut after = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut after).unwrap(); let before_sum = before[..8].iter().sum::(); let after_sum = after[..8].iter().sum::(); assert!(after_sum > before_sum + 4.0); assert_eq!(model.quantization_mode(), "q8_0"); } #[test] fn applies_q4_adapter_delta_to_loaded_compact_tensor() { let mut model = Model::load(include_bytes!("../../models/tiny-test-model-q4.slm")).unwrap(); let mut before = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut before).unwrap(); let adapter = build_adapter_bytes(&model, |_tensor_index, value_index, tensor| { if tensor.name_hash == name_hash("output.weight") && value_index < 8 { 1.0 } else { 0.0 } }); model.apply_adapter_delta(&adapter).unwrap(); let mut after = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut after).unwrap(); let before_sum = before[..8].iter().sum::(); let after_sum = after[..8].iter().sum::(); assert!(after_sum > before_sum + 3.0); assert_eq!(model.quantization_mode(), "q4_0"); assert_eq!( model.tensor_f32("output.weight").unwrap_err(), ErrorCode::UnsupportedDType ); } #[test] fn applies_sparse_adapter_delta_to_loaded_q4_tensor() { let mut model = Model::load(include_bytes!("../../models/tiny-test-model-q4.slm")).unwrap(); let mut before = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut before).unwrap(); let adapter = build_sparse_adapter_bytes(&model, |_tensor_index, value_index, tensor| { if tensor.name_hash == name_hash("output.weight") && value_index < 8 { Some(1.0) } else { None } }); model.apply_adapter_delta(&adapter).unwrap(); let mut after = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut after).unwrap(); let before_sum = before[..8].iter().sum::(); let after_sum = after[..8].iter().sum::(); assert!(after_sum > before_sum + 3.0); assert_eq!(model.quantization_mode(), "q4_0"); } #[test] fn q8_adapter_identity_drift_rejects_without_mutating_tensor() { let mut model = Model::load(include_bytes!("../../models/tiny-test-model-q8.slm")).unwrap(); let mut before = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut before).unwrap(); let mut adapter = build_adapter_bytes(&model, |_tensor_index, value_index, tensor| { if tensor.name_hash == name_hash("output.weight") && value_index < 8 { 1.0 } else { 0.0 } }); write_u32(&mut adapter, 16, model.header().flags ^ 1); refresh_adapter_checksum(&mut adapter); assert_eq!( model.apply_adapter_delta(&adapter).unwrap_err(), ErrorCode::ShapeMismatch ); let mut after = vec![0.0f32; 260 * 8]; model.copy_tensor_f32("output.weight", &mut after).unwrap(); assert_eq!(after, before); assert_eq!(model.quantization_mode(), "q8_0"); } #[test] fn quantized_tensor_f32_borrow_is_rejected() { let model = Model::load(include_bytes!("../../models/tiny-test-model-q8.slm")).unwrap(); assert_eq!( model.tensor_f32("output.weight").unwrap_err(), ErrorCode::UnsupportedDType ); } #[test] fn tied_output_projection_uses_embedding_tensor_index() { let mut parsed = parse_slm(include_bytes!("../../models/tiny-test-model.slm")).unwrap(); parsed.header.flags |= FLAG_TIED_OUTPUT; let top_level = resolve_top_level_indices(&parsed).unwrap(); assert_eq!(top_level.output_projection, top_level.tok_embeddings); assert_ne!(top_level.norm, top_level.output_projection); } #[test] fn tied_output_fixture_loads_without_output_tensor() { let model = Model::load(include_bytes!("../../models/tiny-test-model-tied.slm")).unwrap(); let top_level = model.top_level_indices(); assert!(model.tensor("output.weight").is_none()); assert_eq!(top_level.output_projection, top_level.tok_embeddings); assert_eq!( model.parsed().tensors[top_level.tok_embeddings].name_hash, name_hash("tok_embeddings.weight") ); } #[test] fn loaded_model_exposes_pre_resolved_tensor_indices() { let model = Model::load(include_bytes!("../../models/tiny-test-model.slm")).unwrap(); let top_level = model.top_level_indices(); let layer = model.layer_indices(0).unwrap(); assert_ne!(top_level.tok_embeddings, top_level.output_projection); assert_eq!( model.parsed().tensors[top_level.tok_embeddings].name_hash, name_hash("tok_embeddings.weight") ); assert_eq!( model.parsed().tensors[layer.wq].name_hash, name_hash("layers.0.wq.weight") ); assert_eq!( model.layer_indices(1).unwrap_err(), ErrorCode::MissingTensor ); } } ================================================================================ END FILE: tinyrustlm/runtime/src/model.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/model_format.rs BYTES: 11788 SHA256: B2041C774BB82009A57904A28EBEB5A08BB713FDAFCB30C5F83CCC6B4F8289D5 ================================================================================ //! Parser for the custom `.slm` binary format. use crate::errors::ErrorCode; use std::convert::TryInto; /// Supported `.slm` file magic. pub const SLM_MAGIC: [u8; 4] = *b"SLM1"; /// Supported `.slm` version. pub const SLM_VERSION: u32 = 1; /// Minimum header length for version 1. pub const HEADER_LEN: usize = 108; /// Tensor directory entry length including reserved padding. pub const TENSOR_ENTRY_LEN: usize = 64; /// Float32 tensor dtype. pub const DTYPE_F32: u32 = 1; /// Q8_0 tensor dtype. pub const DTYPE_Q8_0: u32 = 2; /// Q4_0 tensor dtype. pub const DTYPE_Q4_0: u32 = 3; /// Parsed `.slm` header. #[derive(Clone, Copy, Debug, PartialEq)] pub struct SlmHeader { /// Explicit format version. pub version: u32, /// Header length in bytes. pub header_length: u32, /// Model type identifier. pub model_type: u32, /// Format flags. pub flags: u32, /// Token vocabulary size. pub vocab_size: u32, /// Special token count. pub special_token_count: u32, /// Transformer hidden size. pub hidden_size: u32, /// Transformer layer count. pub layer_count: u32, /// Attention head count. pub head_count: u32, /// Key/value head count. pub kv_head_count: u32, /// Per-head dimension. pub head_dim: u32, /// Feed-forward intermediate size. pub ffn_size: u32, /// Maximum context length. pub max_context: u32, /// RoPE theta value. pub rope_theta: f32, /// RMSNorm epsilon. pub rms_norm_epsilon: f32, /// Tokenizer section offset. pub tokenizer_offset: u64, /// Tokenizer section length. pub tokenizer_length: u64, /// Tensor directory offset. pub tensor_directory_offset: u64, /// Tensor count. pub tensor_count: u32, /// Tensor data section offset. pub tensor_data_offset: u64, /// Simple custom checksum. pub checksum: u64, } /// Parsed tensor directory entry. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct TensorEntry { /// Stable hash of the tensor name. pub name_hash: u64, /// Tensor dtype. pub dtype: u32, /// Tensor rank. pub rank: u32, /// Dimension 0. pub dim0: u32, /// Dimension 1. pub dim1: u32, /// Dimension 2. pub dim2: u32, /// Dimension 3. pub dim3: u32, /// Byte offset relative to the file start. pub byte_offset: u64, /// Tensor byte length. pub byte_length: u64, /// Quantization scale offset when quantized. pub scale_offset: u64, /// Quantization block size when quantized. pub block_size: u32, } /// Parsed `.slm` view. #[derive(Debug)] pub struct ParsedSlm { /// Parsed header. pub header: SlmHeader, /// Parsed tensor directory entries. pub tensors: Vec, } /// Parses and validates an `.slm` byte slice. pub fn parse_slm(bytes: &[u8]) -> Result { if bytes.len() < HEADER_LEN { return Err(ErrorCode::InvalidHeader); } if bytes[0..4] != SLM_MAGIC { return Err(ErrorCode::InvalidModelMagic); } let header = SlmHeader { version: read_u32(bytes, 4)?, header_length: read_u32(bytes, 8)?, model_type: read_u32(bytes, 12)?, flags: read_u32(bytes, 16)?, vocab_size: read_u32(bytes, 20)?, special_token_count: read_u32(bytes, 24)?, hidden_size: read_u32(bytes, 28)?, layer_count: read_u32(bytes, 32)?, head_count: read_u32(bytes, 36)?, kv_head_count: read_u32(bytes, 40)?, head_dim: read_u32(bytes, 44)?, ffn_size: read_u32(bytes, 48)?, max_context: read_u32(bytes, 52)?, rope_theta: f32::from_bits(read_u32(bytes, 56)?), rms_norm_epsilon: f32::from_bits(read_u32(bytes, 60)?), tokenizer_offset: read_u64(bytes, 64)?, tokenizer_length: read_u64(bytes, 72)?, tensor_directory_offset: read_u64(bytes, 80)?, tensor_count: read_u32(bytes, 88)?, tensor_data_offset: read_u64(bytes, 92)?, checksum: read_u64(bytes, 100)?, }; validate_header(&header, bytes.len())?; validate_checksum(bytes, &header)?; let tensors = parse_tensor_directory(bytes, &header)?; validate_tensor_ranges(bytes.len(), &tensors)?; Ok(ParsedSlm { header, tensors }) } /// Computes the stable FNV-1a hash used for tensor names. pub fn name_hash(name: &str) -> u64 { let mut hash = 0xcbf29ce484222325u64; for byte in name.as_bytes() { hash ^= u64::from(*byte); hash = hash.wrapping_mul(0x100000001b3); } hash } /// Computes a simple checksum over model bytes. pub fn simple_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x9e3779b97f4a7c15u64; for (index, byte) in bytes.iter().enumerate() { let value = if (100..108).contains(&index) { 0 } else { *byte }; acc ^= u64::from(value).wrapping_add((index as u64) << 1); acc = acc.rotate_left(7).wrapping_mul(0x100000001b3); } acc } fn validate_header(header: &SlmHeader, file_len: usize) -> Result<(), ErrorCode> { if header.version != SLM_VERSION { return Err(ErrorCode::UnsupportedModelVersion); } if header.checksum == 0 { return Err(ErrorCode::InvalidHeader); } if header.header_length < HEADER_LEN as u32 || header.header_length as usize > file_len { return Err(ErrorCode::InvalidHeader); } if header.hidden_size == 0 || header.layer_count == 0 || header.head_count == 0 || header.kv_head_count == 0 || header.head_dim == 0 || header.ffn_size == 0 || header.max_context == 0 { return Err(ErrorCode::InvalidHeader); } if header.head_count.saturating_mul(header.head_dim) != header.hidden_size { return Err(ErrorCode::ShapeMismatch); } if header.tensor_data_offset % 64 != 0 { return Err(ErrorCode::InvalidHeader); } if !range_within(file_len, header.tokenizer_offset, header.tokenizer_length) { return Err(ErrorCode::InvalidHeader); } let directory_len = u64::from(header.tensor_count) * TENSOR_ENTRY_LEN as u64; if !range_within(file_len, header.tensor_directory_offset, directory_len) { return Err(ErrorCode::InvalidTensorDirectory); } Ok(()) } fn validate_checksum(bytes: &[u8], header: &SlmHeader) -> Result<(), ErrorCode> { if header.checksum != simple_checksum(bytes) { return Err(ErrorCode::InvalidHeader); } Ok(()) } fn parse_tensor_directory(bytes: &[u8], header: &SlmHeader) -> Result, ErrorCode> { let mut tensors = Vec::with_capacity(header.tensor_count as usize); let start = usize_from_u64(header.tensor_directory_offset)?; for index in 0..header.tensor_count as usize { let base = start + index * TENSOR_ENTRY_LEN; let entry = TensorEntry { name_hash: read_u64(bytes, base)?, dtype: read_u32(bytes, base + 8)?, rank: read_u32(bytes, base + 12)?, dim0: read_u32(bytes, base + 16)?, dim1: read_u32(bytes, base + 20)?, dim2: read_u32(bytes, base + 24)?, dim3: read_u32(bytes, base + 28)?, byte_offset: read_u64(bytes, base + 32)?, byte_length: read_u64(bytes, base + 40)?, scale_offset: read_u64(bytes, base + 48)?, block_size: read_u32(bytes, base + 56)?, }; if entry.rank == 0 || entry.rank > 4 { return Err(ErrorCode::InvalidTensorDirectory); } if !matches!(entry.dtype, DTYPE_F32 | DTYPE_Q8_0 | DTYPE_Q4_0) { return Err(ErrorCode::UnsupportedDType); } tensors.push(entry); } Ok(tensors) } fn validate_tensor_ranges(file_len: usize, tensors: &[TensorEntry]) -> Result<(), ErrorCode> { for tensor in tensors { if !range_within(file_len, tensor.byte_offset, tensor.byte_length) { return Err(ErrorCode::InvalidTensorDirectory); } if tensor.dtype != DTYPE_F32 && tensor.scale_offset != 0 && tensor.scale_offset >= file_len as u64 { return Err(ErrorCode::InvalidTensorDirectory); } } Ok(()) } fn read_u32(bytes: &[u8], offset: usize) -> Result { let end = offset.checked_add(4).ok_or(ErrorCode::InvalidHeader)?; let slice = bytes.get(offset..end).ok_or(ErrorCode::InvalidHeader)?; Ok(u32::from_le_bytes( slice.try_into().map_err(|_| ErrorCode::InvalidHeader)?, )) } fn read_u64(bytes: &[u8], offset: usize) -> Result { let end = offset.checked_add(8).ok_or(ErrorCode::InvalidHeader)?; let slice = bytes.get(offset..end).ok_or(ErrorCode::InvalidHeader)?; Ok(u64::from_le_bytes( slice.try_into().map_err(|_| ErrorCode::InvalidHeader)?, )) } fn range_within(file_len: usize, offset: u64, len: u64) -> bool { let Some(end) = offset.checked_add(len) else { return false; }; end <= file_len as u64 } fn usize_from_u64(value: u64) -> Result { usize::try_from(value).map_err(|_| ErrorCode::InvalidLength) } #[cfg(test)] mod tests { use super::*; fn valid_header_bytes(tensor_count: u32) -> Vec { let directory_offset = 128u64; let directory_len = tensor_count as usize * TENSOR_ENTRY_LEN; let tensor_data_offset = ((directory_offset as usize + directory_len + 63) & !63) as u64; let mut bytes = vec![0u8; tensor_data_offset as usize]; bytes[0..4].copy_from_slice(b"SLM1"); bytes[4..8].copy_from_slice(&SLM_VERSION.to_le_bytes()); bytes[8..12].copy_from_slice(&(HEADER_LEN as u32).to_le_bytes()); bytes[12..16].copy_from_slice(&1u32.to_le_bytes()); bytes[16..20].copy_from_slice(&0u32.to_le_bytes()); bytes[20..24].copy_from_slice(&260u32.to_le_bytes()); bytes[24..28].copy_from_slice(&4u32.to_le_bytes()); bytes[28..32].copy_from_slice(&8u32.to_le_bytes()); bytes[32..36].copy_from_slice(&1u32.to_le_bytes()); bytes[36..40].copy_from_slice(&2u32.to_le_bytes()); bytes[40..44].copy_from_slice(&2u32.to_le_bytes()); bytes[44..48].copy_from_slice(&4u32.to_le_bytes()); bytes[48..52].copy_from_slice(&16u32.to_le_bytes()); bytes[52..56].copy_from_slice(&16u32.to_le_bytes()); bytes[56..60].copy_from_slice(&10000.0f32.to_le_bytes()); bytes[60..64].copy_from_slice(&0.00001f32.to_le_bytes()); bytes[64..72].copy_from_slice(&(HEADER_LEN as u64).to_le_bytes()); bytes[72..80].copy_from_slice(&0u64.to_le_bytes()); bytes[80..88].copy_from_slice(&directory_offset.to_le_bytes()); bytes[88..92].copy_from_slice(&tensor_count.to_le_bytes()); bytes[92..100].copy_from_slice(&tensor_data_offset.to_le_bytes()); bytes[100..108].copy_from_slice(&0u64.to_le_bytes()); let checksum = simple_checksum(&bytes); bytes[100..108].copy_from_slice(&checksum.to_le_bytes()); bytes } #[test] fn slm_header_parse() { let parsed = parse_slm(&valid_header_bytes(0)).unwrap(); assert_eq!(parsed.header.hidden_size, 8); assert_eq!(parsed.header.layer_count, 1); assert_eq!(parsed.header.tensor_count, 0); } #[test] fn invalid_magic_rejection() { let mut bytes = vec![0; HEADER_LEN]; bytes[0..4].copy_from_slice(b"NOPE"); assert_eq!(parse_slm(&bytes).unwrap_err(), ErrorCode::InvalidModelMagic); } #[test] fn checksum_rejection() { let mut bytes = valid_header_bytes(0); bytes[20] ^= 1; assert_eq!(parse_slm(&bytes).unwrap_err(), ErrorCode::InvalidHeader); } } ================================================================================ END FILE: tinyrustlm/runtime/src/model_format.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/ops.rs BYTES: 6310 SHA256: 47D6FEDD08B4DC3059F36C3203C13E0ECA8F53F2F18DCDC46B20A4A4E5B1028B ================================================================================ //! Core math operations for CPU/WASM inference. use crate::errors::ErrorCode; /// Computes a dot product between equal-length slices. pub fn dot(a: &[f32], b: &[f32]) -> Result { if a.len() != b.len() { return Err(ErrorCode::ShapeMismatch); } let mut sum = 0.0f32; for index in 0..a.len() { sum += a[index] * b[index]; } Ok(sum) } /// Computes a row-major f32 matrix-vector product. pub fn matvec_f32( matrix: &[f32], rows: usize, cols: usize, vector: &[f32], out: &mut [f32], ) -> Result<(), ErrorCode> { if matrix.len() != rows.checked_mul(cols).ok_or(ErrorCode::InvalidLength)? || vector.len() != cols || out.len() != rows { return Err(ErrorCode::ShapeMismatch); } for row in 0..rows { let start = row * cols; out[row] = dot(&matrix[start..start + cols], vector)?; } Ok(()) } /// Computes a row-major f32 matrix-matrix product. pub fn matmul_f32( a: &[f32], a_rows: usize, a_cols: usize, b: &[f32], b_cols: usize, out: &mut [f32], ) -> Result<(), ErrorCode> { if a.len() != a_rows.checked_mul(a_cols).ok_or(ErrorCode::InvalidLength)? || b.len() != a_cols.checked_mul(b_cols).ok_or(ErrorCode::InvalidLength)? || out.len() != a_rows.checked_mul(b_cols).ok_or(ErrorCode::InvalidLength)? { return Err(ErrorCode::ShapeMismatch); } for row in 0..a_rows { for col in 0..b_cols { let mut sum = 0.0f32; for inner in 0..a_cols { sum += a[row * a_cols + inner] * b[inner * b_cols + col]; } out[row * b_cols + col] = sum; } } Ok(()) } /// Applies RMSNorm to `input` with per-channel `weight`. pub fn rms_norm( input: &[f32], weight: &[f32], epsilon: f32, out: &mut [f32], ) -> Result<(), ErrorCode> { if input.len() != weight.len() || input.len() != out.len() || input.is_empty() { return Err(ErrorCode::ShapeMismatch); } let mut mean_square = 0.0f32; for value in input { mean_square += value * value; } mean_square /= input.len() as f32; let scale = 1.0 / (mean_square + epsilon).sqrt(); for index in 0..input.len() { out[index] = input[index] * scale * weight[index]; } Ok(()) } /// Applies stable softmax in-place. pub fn softmax(values: &mut [f32]) -> Result<(), ErrorCode> { if values.is_empty() { return Err(ErrorCode::InvalidLength); } let mut max = f32::NEG_INFINITY; for value in values.iter() { max = max.max(*value); } let mut sum = 0.0f32; for value in values.iter_mut() { *value = (*value - max).exp(); sum += *value; } if sum == 0.0 || !sum.is_finite() { return Err(ErrorCode::GenerationFailed); } for value in values.iter_mut() { *value /= sum; } Ok(()) } /// Computes the SiLU activation. pub fn silu(value: f32) -> f32 { value / (1.0 + (-value).exp()) } /// Computes SwiGLU activation for paired slices. pub fn swiglu(gate: &[f32], up: &[f32], out: &mut [f32]) -> Result<(), ErrorCode> { if gate.len() != up.len() || up.len() != out.len() { return Err(ErrorCode::ShapeMismatch); } for index in 0..gate.len() { out[index] = silu(gate[index]) * up[index]; } Ok(()) } #[cfg(test)] mod tests { use super::*; fn assert_close(actual: f32, expected: f32) { assert!( (actual - expected).abs() < 0.0001, "expected {expected}, got {actual}" ); } #[test] fn dot_known_output() { let left = [1.0, -2.0, 0.5]; let right = [4.0, 3.0, -8.0]; assert_close(dot(&left, &right).unwrap(), -6.0); } #[test] fn dot_rejects_shape_mismatch() { assert_eq!(dot(&[1.0, 2.0], &[1.0]), Err(ErrorCode::ShapeMismatch)); } #[test] fn rmsnorm_known_vector() { let input = [1.0, 2.0, 3.0, 4.0]; let weight = [1.0, 1.0, 1.0, 1.0]; let mut out = [0.0; 4]; rms_norm(&input, &weight, 0.0, &mut out).unwrap(); assert_close(out[0], 0.36514837); } #[test] fn softmax_sum_is_one() { let mut values = [1.0, 2.0, 3.0]; softmax(&mut values).unwrap(); let sum: f32 = values.iter().sum(); assert_close(sum, 1.0); } #[test] fn softmax_rejects_empty_slice() { let mut values = []; assert_eq!(softmax(&mut values), Err(ErrorCode::InvalidLength)); } #[test] fn matvec_known_output() { let matrix = [1.0, 2.0, 3.0, 4.0]; let vector = [2.0, 3.0]; let mut out = [0.0; 2]; matvec_f32(&matrix, 2, 2, &vector, &mut out).unwrap(); assert_eq!(out, [8.0, 18.0]); } #[test] fn matvec_rejects_shape_mismatch() { let mut out = [0.0; 2]; assert_eq!( matvec_f32(&[1.0, 2.0, 3.0, 4.0], 2, 2, &[1.0], &mut out), Err(ErrorCode::ShapeMismatch) ); } #[test] fn matmul_known_output() { let a = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; let b = [7.0, 8.0, 9.0, 10.0, 11.0, 12.0]; let mut out = [0.0; 4]; matmul_f32(&a, 2, 3, &b, 2, &mut out).unwrap(); assert_eq!(out, [58.0, 64.0, 139.0, 154.0]); } #[test] fn matmul_rejects_shape_mismatch() { let mut out = [0.0; 4]; assert_eq!( matmul_f32(&[1.0, 2.0, 3.0], 1, 3, &[1.0, 2.0, 3.0], 2, &mut out), Err(ErrorCode::ShapeMismatch) ); } #[test] fn silu_known_values() { assert_close(silu(0.0), 0.0); assert_close(silu(1.0), 0.7310586); assert_close(silu(-1.0), -0.26894143); } #[test] fn swiglu_known_output() { let gate = [0.0, 1.0, -1.0]; let up = [2.0, 3.0, 4.0]; let mut out = [0.0; 3]; swiglu(&gate, &up, &mut out).unwrap(); assert_close(out[0], 0.0); assert_close(out[1], 2.1931758); assert_close(out[2], -1.0757657); } #[test] fn swiglu_rejects_shape_mismatch() { let mut out = [0.0; 2]; assert_eq!( swiglu(&[1.0, 2.0], &[1.0], &mut out), Err(ErrorCode::ShapeMismatch) ); } } ================================================================================ END FILE: tinyrustlm/runtime/src/ops.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/quant.rs BYTES: 5721 SHA256: 90E9F3103D39D00A75A1AC52756436D745EB0D24DE748AFFE5C3F462B183A914 ================================================================================ //! Quantization helpers for q8_0 and q4_0. use crate::errors::ErrorCode; /// Computes a q8_0 row-major matrix-vector product with one scale per row. pub fn matvec_q8_0( weights: &[i8], scales: &[f32], rows: usize, cols: usize, vector: &[f32], out: &mut [f32], ) -> Result<(), ErrorCode> { if weights.len() != rows.checked_mul(cols).ok_or(ErrorCode::InvalidLength)? || scales.len() != rows || vector.len() != cols || out.len() != rows { return Err(ErrorCode::ShapeMismatch); } for row in 0..rows { let mut sum = 0.0f32; let row_start = row * cols; for col in 0..cols { sum += f32::from(weights[row_start + col]) * scales[row] * vector[col]; } out[row] = sum; } Ok(()) } /// Quantizes one f32 row into signed q8_0 values and returns its scale. pub fn quantize_q8_row(row: &[f32], out: &mut [i8]) -> Result { if row.len() != out.len() { return Err(ErrorCode::ShapeMismatch); } let mut max_abs = 0.0f32; for value in row { if !value.is_finite() { return Err(ErrorCode::InvalidHeader); } max_abs = max_abs.max(value.abs()); } let scale = if max_abs == 0.0 { 1.0 } else { max_abs / 127.0 }; for (index, value) in row.iter().enumerate() { out[index] = (*value / scale).round().clamp(-127.0, 127.0) as i8; } Ok(scale) } /// Dequantizes a packed q4_0 block into signed f32 values. pub fn dequant_q4_0_block(packed: &[u8], scale: f32, out: &mut [f32]) -> Result<(), ErrorCode> { if out.len() != packed.len() * 2 { return Err(ErrorCode::ShapeMismatch); } for (index, byte) in packed.iter().enumerate() { let lo = sign_extend_4(byte & 0x0f); let hi = sign_extend_4(byte >> 4); out[index * 2] = f32::from(lo) * scale; out[index * 2 + 1] = f32::from(hi) * scale; } Ok(()) } /// Packs two signed q4_0 values into one byte using low nibble first. pub fn pack_q4_pair(a: i8, b: i8) -> u8 { ((b as u8) & 0x0f) << 4 | ((a as u8) & 0x0f) } /// Quantizes one f32 block into signed q4_0 values and returns its scale. pub fn quantize_q4_block(block: &[f32], out: &mut [i8]) -> Result { if block.len() != out.len() { return Err(ErrorCode::ShapeMismatch); } let mut max_abs = 0.0f32; for value in block { if !value.is_finite() { return Err(ErrorCode::InvalidHeader); } max_abs = max_abs.max(value.abs()); } let scale = if max_abs == 0.0 { 1.0 } else { max_abs / 7.0 }; for (index, value) in block.iter().enumerate() { out[index] = (*value / scale).round().clamp(-8.0, 7.0) as i8; } Ok(scale) } /// Computes a q4_0 row-major matrix-vector product with one scale per quantization block. pub fn matvec_q4_0( packed: &[u8], scales: &[f32], block_size: usize, rows: usize, cols: usize, vector: &[f32], out: &mut [f32], ) -> Result<(), ErrorCode> { if block_size == 0 || block_size % 2 != 0 || cols % block_size != 0 || vector.len() != cols || out.len() != rows { return Err(ErrorCode::ShapeMismatch); } let bytes_per_row = cols / 2; let blocks_per_row = cols / block_size; if packed.len() != rows .checked_mul(bytes_per_row) .ok_or(ErrorCode::InvalidLength)? || scales.len() != rows .checked_mul(blocks_per_row) .ok_or(ErrorCode::InvalidLength)? { return Err(ErrorCode::ShapeMismatch); } for row in 0..rows { let mut sum = 0.0f32; for col_byte in 0..bytes_per_row { let byte = packed[row * bytes_per_row + col_byte]; let col = col_byte * 2; let scale = scales[row * blocks_per_row + col / block_size]; sum += f32::from(sign_extend_4(byte & 0x0f)) * scale * vector[col]; sum += f32::from(sign_extend_4(byte >> 4)) * scale * vector[col + 1]; } out[row] = sum; } Ok(()) } fn sign_extend_4(value: u8) -> i8 { let nibble = (value & 0x0f) as i8; if nibble >= 8 { nibble - 16 } else { nibble } } #[cfg(test)] mod tests { use super::*; #[test] fn q8_dequant_known_output() { let weights = [1i8, -2, 3, 4]; let scales = [0.5, 1.0]; let vector = [2.0, 1.0]; let mut out = [0.0; 2]; matvec_q8_0(&weights, &scales, 2, 2, &vector, &mut out).unwrap(); assert_eq!(out, [0.0, 10.0]); } #[test] fn q8_quantize_row_produces_scale() { let mut out = [0i8; 2]; let scale = quantize_q8_row(&[1.0, -1.0], &mut out).unwrap(); assert!(scale > 0.0); assert_eq!(out, [127, -127]); } #[test] fn q4_dequant_known_output() { let packed = [0x1f, 0x80]; let mut out = [0.0; 4]; dequant_q4_0_block(&packed, 0.5, &mut out).unwrap(); assert_eq!(out, [-0.5, 0.5, 0.0, -4.0]); } #[test] fn q4_pack_and_quantize_block_produce_low_nibble_first_bytes() { assert_eq!(pack_q4_pair(-1, 1), 0x1f); let mut out = [0i8; 2]; let scale = quantize_q4_block(&[1.0, -1.0], &mut out).unwrap(); assert!(scale > 0.0); assert_eq!(out, [7, -7]); } #[test] fn q4_matvec_uses_block_scales() { let packed = [0x11, 0x22]; let scales = [1.0, 2.0]; let vector = [1.0, 1.0, 1.0, 1.0]; let mut out = [0.0]; matvec_q4_0(&packed, &scales, 2, 1, 4, &vector, &mut out).unwrap(); assert_eq!(out, [10.0]); } } ================================================================================ END FILE: tinyrustlm/runtime/src/quant.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/rng.rs BYTES: 763 SHA256: D5EA218FD5DB4859F8CC27C034E88507A03FDCDC86F04D5ACB17A4E984463377 ================================================================================ //! Deterministic pseudo-random generator for sampling. /// Small xorshift PRNG for deterministic text sampling. pub struct XorShift64 { state: u64, } impl XorShift64 { /// Creates a generator with a non-zero seed. pub fn new(seed: u64) -> Self { Self { state: if seed == 0 { 0x9e3779b97f4a7c15 } else { seed }, } } /// Returns the next u64 value. pub fn next_u64(&mut self) -> u64 { let mut x = self.state; x ^= x << 13; x ^= x >> 7; x ^= x << 17; self.state = x; x } /// Returns the next f32 value in `[0, 1)`. pub fn next_f32(&mut self) -> f32 { let value = self.next_u64() >> 40; (value as f32) / ((1u32 << 24) as f32) } } ================================================================================ END FILE: tinyrustlm/runtime/src/rng.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/rope.rs BYTES: 1055 SHA256: 8F760BF3B39F72C2270533C4B50F9F5769639AE02C5208B584F836898E73ACE6 ================================================================================ //! Rotary positional embedding helpers. use crate::errors::ErrorCode; /// Applies RoPE to an even-length vector in-place. pub fn apply_rope(vector: &mut [f32], position: usize, theta: f32) -> Result<(), ErrorCode> { if vector.len() % 2 != 0 || theta <= 0.0 { return Err(ErrorCode::ShapeMismatch); } let half = vector.len() / 2; for pair in 0..half { let even = pair * 2; let odd = even + 1; let freq = theta.powf(-(even as f32) / vector.len() as f32); let angle = position as f32 * freq; let cos = angle.cos(); let sin = angle.sin(); let x = vector[even]; let y = vector[odd]; vector[even] = x * cos - y * sin; vector[odd] = x * sin + y * cos; } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn rope_known_small_vector() { let mut vector = [1.0, 0.0]; apply_rope(&mut vector, 0, 10000.0).unwrap(); assert!((vector[0] - 1.0).abs() < 0.0001); assert!(vector[1].abs() < 0.0001); } } ================================================================================ END FILE: tinyrustlm/runtime/src/rope.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/sampler.rs BYTES: 6972 SHA256: 2FDB1BC4BA798258A4ADF2034B3ED931083377E4C276E3D1BF5AC46EEC26488F ================================================================================ //! Token sampling helpers. use crate::errors::ErrorCode; use crate::rng::XorShift64; /// Maximum stochastic candidates retained without heap allocation. pub const MAX_SAMPLING_CANDIDATES: usize = 1024; /// Sampling configuration. #[derive(Clone, Copy)] pub struct SamplingConfig { /// Temperature for stochastic sampling. pub temperature: f32, /// Maximum top-k candidate count. pub top_k: usize, /// Nucleus sampling probability. pub top_p: f32, /// Deterministic seed. pub seed: u64, } impl Default for SamplingConfig { fn default() -> Self { Self { temperature: 0.0, top_k: 1, top_p: 1.0, seed: 1, } } } impl SamplingConfig { /// Returns true when this configuration should select the greedy argmax. pub fn is_greedy(self) -> bool { self.temperature <= 0.0 || self.top_k == 1 } } /// Validates a sampling config against runtime fixed-buffer limits. pub fn validate_config(config: SamplingConfig) -> Result<(), ErrorCode> { if !config.temperature.is_finite() || config.temperature < 0.0 || !config.top_p.is_finite() || config.top_p <= 0.0 || config.top_p > 1.0 || config.top_k == 0 || config.top_k > MAX_SAMPLING_CANDIDATES { return Err(ErrorCode::InvalidLength); } Ok(()) } /// Selects the highest-logit token. pub fn greedy(logits: &[f32]) -> Result { if logits.is_empty() { return Err(ErrorCode::InvalidLength); } let mut best_index = 0usize; let mut best_value = logits[0]; for (index, value) in logits.iter().enumerate().skip(1) { if *value > best_value { best_value = *value; best_index = index; } } Ok(best_index) } /// Selects a token using deterministic greedy or seeded stochastic sampling. pub fn sample(logits: &[f32], config: SamplingConfig) -> Result { let mut rng = XorShift64::new(config.seed); sample_with_rng(logits, config, &mut rng) } /// Selects a token using temperature, top-k, top-p, and caller-owned RNG state. pub fn sample_with_rng( logits: &[f32], config: SamplingConfig, rng: &mut XorShift64, ) -> Result { if logits.is_empty() { return Err(ErrorCode::InvalidLength); } validate_config(config)?; if config.is_greedy() { return greedy(logits); } let limit = config.top_k.min(logits.len()); let mut tokens = [0usize; MAX_SAMPLING_CANDIDATES]; let mut weights = [f32::NEG_INFINITY; MAX_SAMPLING_CANDIDATES]; let mut count = 0usize; for (token, value) in logits.iter().copied().enumerate() { if count < limit { insert_candidate(&mut tokens, &mut weights, count, token, value); count += 1; } else if limit > 0 && value > weights[limit - 1] { insert_candidate(&mut tokens, &mut weights, limit - 1, token, value); } } let max_logit = weights[0]; let mut total = 0.0f32; for weight in weights.iter_mut().take(count) { let scaled = ((*weight - max_logit) / config.temperature).exp(); *weight = if scaled.is_finite() { scaled } else { 0.0 }; total += *weight; } if total <= 0.0 || !total.is_finite() { return greedy(logits); } let mut keep = count; if config.top_p < 1.0 { let mut cumulative = 0.0f32; let threshold = total * config.top_p; for (index, weight) in weights.iter().take(count).enumerate() { cumulative += *weight; if cumulative >= threshold { keep = index + 1; break; } } keep = keep.max(1); } let truncated_total = weights.iter().take(keep).sum::(); if truncated_total <= 0.0 || !truncated_total.is_finite() { return greedy(logits); } let threshold = rng.next_f32() * truncated_total; let mut cumulative = 0.0f32; for index in 0..keep { cumulative += weights[index]; if threshold <= cumulative { return Ok(tokens[index]); } } Ok(tokens[keep - 1]) } fn insert_candidate( tokens: &mut [usize; MAX_SAMPLING_CANDIDATES], weights: &mut [f32; MAX_SAMPLING_CANDIDATES], mut index: usize, token: usize, value: f32, ) { while index > 0 && value > weights[index - 1] { weights[index] = weights[index - 1]; tokens[index] = tokens[index - 1]; index -= 1; } weights[index] = value; tokens[index] = token; } #[cfg(test)] mod tests { use super::*; #[test] fn greedy_sampler_deterministic_selection() { assert_eq!(greedy(&[0.1, 2.0, 1.5]).unwrap(), 1); } #[test] fn stochastic_sampler_is_seeded_and_top_k_limited() { let config = SamplingConfig { temperature: 1.0, top_k: 2, top_p: 1.0, seed: 42, }; let logits = [0.0, 10.0, 9.0, 1.0]; let first = sample(&logits, config).unwrap(); let second = sample(&logits, config).unwrap(); assert_eq!(first, second); assert!(first == 1 || first == 2); } #[test] fn stochastic_sampler_accepts_fixed_candidate_cap_without_vocab_vector() { let config = SamplingConfig { temperature: 1.0, top_k: MAX_SAMPLING_CANDIDATES, top_p: 1.0, seed: 7, }; let mut logits = [0.0f32; MAX_SAMPLING_CANDIDATES + 4]; logits[3] = 10.0; logits[MAX_SAMPLING_CANDIDATES + 1] = 9.5; assert!(sample(&logits, config).is_ok()); } #[test] fn stochastic_sampler_accepts_bpe_vocab_above_byte_tokenizer_size() { let config = SamplingConfig { temperature: 0.01, top_k: 262, top_p: 1.0, seed: 7, }; let mut logits = [0.0f32; 262]; logits[261] = 5.0; assert_eq!(sample(&logits, config).unwrap(), 261); } #[test] fn top_p_can_collapse_to_the_highest_probability_token() { let config = SamplingConfig { temperature: 1.0, top_k: 4, top_p: 0.5, seed: 99, }; assert_eq!(sample(&[5.0, 1.0, 0.0, -1.0], config).unwrap(), 0); } #[test] fn sampler_rejects_invalid_stochastic_config() { let config = SamplingConfig { temperature: 1.0, top_k: 0, top_p: 1.0, seed: 1, }; assert_eq!(sample(&[1.0, 2.0], config), Err(ErrorCode::InvalidLength)); let oversized = SamplingConfig { temperature: 1.0, top_k: MAX_SAMPLING_CANDIDATES + 1, top_p: 1.0, seed: 1, }; assert_eq!( sample(&[1.0, 2.0], oversized), Err(ErrorCode::InvalidLength) ); } } ================================================================================ END FILE: tinyrustlm/runtime/src/sampler.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/tensor.rs BYTES: 3942 SHA256: 611ED2FEEA28B9E53D415291F9E1962B4EB6D56657437FB61AF16E994B710589 ================================================================================ //! Tensor view types. use crate::errors::ErrorCode; /// Borrowed immutable tensor view. pub struct TensorView<'a> { /// Flat tensor data. pub data: &'a [f32], /// Tensor shape. pub shape: &'a [usize], } impl<'a> TensorView<'a> { /// Creates a validated immutable tensor view. pub fn new(data: &'a [f32], shape: &'a [usize]) -> Result { let expected = element_count(shape)?; if expected != data.len() { return Err(ErrorCode::ShapeMismatch); } Ok(Self { data, shape }) } /// Returns a row-major flat index for the provided multidimensional index. pub fn flat_index(&self, index: &[usize]) -> Result { flat_index(self.shape, index) } } /// Borrowed mutable tensor view. pub struct MutableTensorView<'a> { /// Flat tensor data. pub data: &'a mut [f32], /// Tensor shape. pub shape: &'a [usize], } impl<'a> MutableTensorView<'a> { /// Creates a validated mutable tensor view. pub fn new(data: &'a mut [f32], shape: &'a [usize]) -> Result { let expected = element_count(shape)?; if expected != data.len() { return Err(ErrorCode::ShapeMismatch); } Ok(Self { data, shape }) } /// Returns a row-major flat index for the provided multidimensional index. pub fn flat_index(&self, index: &[usize]) -> Result { flat_index(self.shape, index) } } /// Computes the total element count for a shape. pub fn element_count(shape: &[usize]) -> Result { if shape.is_empty() { return Err(ErrorCode::ShapeMismatch); } let mut total = 1usize; for dim in shape { if *dim == 0 { return Err(ErrorCode::ShapeMismatch); } total = total.checked_mul(*dim).ok_or(ErrorCode::InvalidLength)?; } Ok(total) } fn flat_index(shape: &[usize], index: &[usize]) -> Result { if shape.len() != index.len() { return Err(ErrorCode::ShapeMismatch); } let mut stride = 1usize; let mut flat = 0usize; for axis in (0..shape.len()).rev() { if index[axis] >= shape[axis] { return Err(ErrorCode::ShapeMismatch); } flat += index[axis] * stride; stride *= shape[axis]; } Ok(flat) } #[cfg(test)] mod tests { use super::*; #[test] fn tensor_view_validates_shape_and_row_major_index() { let data = [0.0f32; 24]; let view = TensorView::new(&data, &[2, 3, 4]).expect("valid tensor view"); assert_eq!(view.flat_index(&[0, 0, 0]), Ok(0)); assert_eq!(view.flat_index(&[0, 1, 2]), Ok(6)); assert_eq!(view.flat_index(&[1, 2, 3]), Ok(23)); assert_eq!(view.flat_index(&[2, 0, 0]), Err(ErrorCode::ShapeMismatch)); assert_eq!(view.flat_index(&[0, 0]), Err(ErrorCode::ShapeMismatch)); } #[test] fn mutable_tensor_view_validates_shape_and_indexes_scratch() { let mut scratch = [0.0f32; 6]; let view = MutableTensorView::new(&mut scratch, &[2, 3]).expect("valid mutable view"); let index = view.flat_index(&[1, 2]).expect("flat index"); view.data[index] = 7.5; assert_eq!(scratch[5], 7.5); } #[test] fn tensor_views_reject_bad_shapes() { let data = [0.0f32; 4]; assert!(matches!( TensorView::new(&data, &[2, 3]), Err(ErrorCode::ShapeMismatch) )); assert!(matches!( TensorView::new(&data, &[0, 4]), Err(ErrorCode::ShapeMismatch) )); assert!(matches!( TensorView::new(&data, &[]), Err(ErrorCode::ShapeMismatch) )); } #[test] fn element_count_rejects_overflow() { assert_eq!( element_count(&[usize::MAX, 2]), Err(ErrorCode::InvalidLength) ); } } ================================================================================ END FILE: tinyrustlm/runtime/src/tensor.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/tokenizer.rs BYTES: 17504 SHA256: AB51E0EDA9F89E1567D5A3610DD97902390F8E8E9B22283137A089659FB13750 ================================================================================ //! Local tokenizers for TinyRustLM model files. use crate::errors::ErrorCode; use std::convert::TryInto; /// Beginning-of-sequence token. pub const BOS: u32 = 256; /// End-of-sequence token. pub const EOS: u32 = 257; /// Padding token. pub const PAD: u32 = 258; /// Unknown token. pub const UNK: u32 = 259; /// Vocabulary size for phase-one byte tokenization. pub const BYTE_VOCAB_SIZE: u32 = 260; /// Tokenizer selected from a loaded `.slm` tokenizer section. #[derive(Clone, Debug)] pub enum Tokenizer { /// Fixed byte-tokenizer path used by phase-one models. Byte(ByteTokenizer), /// Custom BPE tokenizer path used by phase-two models. Bpe(CustomBpeTokenizer), } impl Tokenizer { /// Parses a tokenizer section from `.slm` model bytes. /// /// `section` must point only at the tokenizer payload declared by the /// model header. The return value is the runtime tokenizer selected by /// the section magic. pub fn from_section(section: &[u8]) -> Result { match section.get(0..4) { Some(b"BTOK") => { ByteTokenizer::validate_section(section)?; Ok(Self::Byte(ByteTokenizer::new())) } Some(b"BPE1") => Ok(Self::Bpe(CustomBpeTokenizer::from_section(section)?)), _ => Err(ErrorCode::InvalidHeader), } } /// Encodes UTF-8 text into model token ids. /// /// `out` is cleared before tokens are written. The return value reports /// tokenizer validation or input-size failures. pub fn encode(&self, text: &str, out: &mut Vec) -> Result<(), ErrorCode> { match self { Self::Byte(tokenizer) => tokenizer.encode(text, out), Self::Bpe(tokenizer) => tokenizer.encode(text, out), } } /// Decodes model token ids into UTF-8 text. /// /// `out` is cleared before decoded text is written. Unknown token ids /// outside the tokenizer vocabulary return an explicit error. pub fn decode(&self, tokens: &[u32], out: &mut String) -> Result<(), ErrorCode> { self.decode_with_limit(tokens, out, usize::MAX) } /// Decodes model token ids while enforcing a maximum output byte count. /// /// `max_bytes` is the decoded UTF-8 byte budget. If decoded output would /// exceed the budget, `ErrorCode::OutputBufferExceeded` is returned and /// `out` is not replaced. pub fn decode_with_limit( &self, tokens: &[u32], out: &mut String, max_bytes: usize, ) -> Result<(), ErrorCode> { match self { Self::Byte(tokenizer) => tokenizer.decode_with_limit(tokens, out, max_bytes), Self::Bpe(tokenizer) => tokenizer.decode_with_limit(tokens, out, max_bytes), } } /// Returns a compact tokenizer label for diagnostics and tests. pub fn label(&self) -> &'static str { match self { Self::Byte(_) => "byte-v1", Self::Bpe(_) => "bpe-v1", } } } impl Default for Tokenizer { fn default() -> Self { Self::Byte(ByteTokenizer::new()) } } /// Phase-one byte tokenizer. #[derive(Clone, Copy, Debug, Default)] pub struct ByteTokenizer; impl ByteTokenizer { /// Creates a new byte tokenizer. pub fn new() -> Self { Self } /// Validates a phase-one `BTOK` tokenizer section. /// /// The return value is `Ok(())` when the section declares the fixed byte /// vocabulary and special-token ids used by this runtime. pub fn validate_section(section: &[u8]) -> Result<(), ErrorCode> { if section.len() < 28 { return Err(ErrorCode::InvalidHeader); } if section.get(0..4) != Some(b"BTOK") { return Err(ErrorCode::InvalidHeader); } if read_u32(section, 4)? != 1 || read_u32(section, 8)? != BYTE_VOCAB_SIZE || read_u32(section, 12)? != BOS || read_u32(section, 16)? != EOS || read_u32(section, 20)? != PAD || read_u32(section, 24)? != UNK { return Err(ErrorCode::InvalidHeader); } Ok(()) } /// Encodes UTF-8 text into byte tokens with BOS and EOS delimiters. pub fn encode(&self, text: &str, out: &mut Vec) -> Result<(), ErrorCode> { if text.as_bytes().len() + 2 > u32::MAX as usize { return Err(ErrorCode::InvalidLength); } out.clear(); out.push(BOS); for byte in text.as_bytes() { out.push(u32::from(*byte)); } out.push(EOS); Ok(()) } /// Decodes byte tokens into UTF-8 text while ignoring BOS, EOS, and PAD. pub fn decode(&self, tokens: &[u32], out: &mut String) -> Result<(), ErrorCode> { self.decode_with_limit(tokens, out, usize::MAX) } /// Decodes byte tokens into UTF-8 text with an output byte limit. pub fn decode_with_limit( &self, tokens: &[u32], out: &mut String, max_bytes: usize, ) -> Result<(), ErrorCode> { let mut bytes = Vec::with_capacity(tokens.len().min(max_bytes)); for token in tokens { match *token { 0..=255 => push_limited_byte(&mut bytes, *token as u8, max_bytes)?, BOS | EOS | PAD => {} UNK => push_limited_byte(&mut bytes, b'?', max_bytes)?, _ => return Err(ErrorCode::InvalidLength), } } let text = core::str::from_utf8(&bytes).map_err(|_| ErrorCode::InvalidUtf8)?; out.clear(); out.push_str(text); Ok(()) } } /// Custom phase-two BPE tokenizer with byte fallback. #[derive(Clone, Debug)] pub struct CustomBpeTokenizer { vocab_size: u32, bos: u32, eos: u32, pad: u32, unk: u32, tokens: Vec, merges: Vec, } #[derive(Clone, Debug)] struct BpeToken { id: u32, bytes: Vec, } #[derive(Clone, Copy, Debug)] struct BpeMerge { left: u32, right: u32, output: u32, rank: u32, } impl CustomBpeTokenizer { /// Parses a custom `BPE1` tokenizer section. /// /// The format is little-endian and self-contained: header, variable /// token table, and fixed merge table. The return value is a tokenizer /// with byte fallback and deterministic ranked merges. pub fn from_section(section: &[u8]) -> Result { if section.len() < 36 || section.get(0..4) != Some(b"BPE1") { return Err(ErrorCode::InvalidHeader); } if read_u32(section, 4)? != 1 { return Err(ErrorCode::UnsupportedModelVersion); } let vocab_size = read_u32(section, 8)?; let bos = read_u32(section, 12)?; let eos = read_u32(section, 16)?; let pad = read_u32(section, 20)?; let unk = read_u32(section, 24)?; let token_count = read_u32(section, 28)? as usize; let merge_count = read_u32(section, 32)? as usize; if vocab_size < BYTE_VOCAB_SIZE || bos >= vocab_size || eos >= vocab_size || pad >= vocab_size || unk >= vocab_size { return Err(ErrorCode::InvalidHeader); } let mut offset = 36usize; let mut tokens = Vec::with_capacity(token_count); for _ in 0..token_count { let id = read_u32(section, offset)?; let len = read_u32(section, offset + 4)? as usize; offset = offset.checked_add(8).ok_or(ErrorCode::InvalidLength)?; let end = offset.checked_add(len).ok_or(ErrorCode::InvalidLength)?; let bytes = section .get(offset..end) .ok_or(ErrorCode::InvalidHeader)? .to_vec(); if id < BYTE_VOCAB_SIZE || id >= vocab_size || bytes.is_empty() { return Err(ErrorCode::InvalidHeader); } if tokens.iter().any(|token: &BpeToken| token.id == id) { return Err(ErrorCode::InvalidHeader); } tokens.push(BpeToken { id, bytes }); offset = end; } let mut merges = Vec::with_capacity(merge_count); for _ in 0..merge_count { let end = offset.checked_add(16).ok_or(ErrorCode::InvalidLength)?; if end > section.len() { return Err(ErrorCode::InvalidHeader); } let left = read_u32(section, offset)?; let right = read_u32(section, offset + 4)?; let output = read_u32(section, offset + 8)?; let rank = read_u32(section, offset + 12)?; if left >= vocab_size || right >= vocab_size || output >= vocab_size || output < BYTE_VOCAB_SIZE { return Err(ErrorCode::InvalidHeader); } if !tokens.iter().any(|token| token.id == output) { return Err(ErrorCode::InvalidHeader); } merges.push(BpeMerge { left, right, output, rank, }); offset = end; } if offset != section.len() { return Err(ErrorCode::InvalidHeader); } Ok(Self { vocab_size, bos, eos, pad, unk, tokens, merges, }) } /// Encodes UTF-8 text with byte fallback and ranked BPE merges. /// /// The output always starts with BOS and ends with EOS when encoding /// succeeds. pub fn encode(&self, text: &str, out: &mut Vec) -> Result<(), ErrorCode> { if text.as_bytes().len() + 2 > u32::MAX as usize { return Err(ErrorCode::InvalidLength); } let mut merged: Vec = text .as_bytes() .iter() .map(|byte| u32::from(*byte)) .collect(); self.apply_merges(&mut merged); out.clear(); out.reserve(merged.len() + 2); out.push(self.bos); out.extend_from_slice(&merged); out.push(self.eos); Ok(()) } /// Decodes byte fallback and token-table ids into UTF-8 text. /// /// Special tokens are skipped, UNK decodes to `?`, and invalid token ids /// return an explicit error. pub fn decode(&self, tokens: &[u32], out: &mut String) -> Result<(), ErrorCode> { self.decode_with_limit(tokens, out, usize::MAX) } /// Decodes byte fallback and token-table ids with an output byte limit. pub fn decode_with_limit( &self, tokens: &[u32], out: &mut String, max_bytes: usize, ) -> Result<(), ErrorCode> { let mut bytes = Vec::with_capacity(tokens.len().min(max_bytes)); for token in tokens { if *token == self.bos || *token == self.eos || *token == self.pad { continue; } if *token == self.unk { push_limited_byte(&mut bytes, b'?', max_bytes)?; continue; } match *token { 0..=255 => push_limited_byte(&mut bytes, *token as u8, max_bytes)?, _ if *token < self.vocab_size => { let Some(entry) = self.tokens.iter().find(|entry| entry.id == *token) else { return Err(ErrorCode::InvalidLength); }; extend_limited_bytes(&mut bytes, &entry.bytes, max_bytes)?; } _ => return Err(ErrorCode::InvalidLength), } } let text = core::str::from_utf8(&bytes).map_err(|_| ErrorCode::InvalidUtf8)?; out.clear(); out.push_str(text); Ok(()) } fn apply_merges(&self, tokens: &mut Vec) { loop { let Some((index, merge)) = self.best_merge(tokens) else { break; }; tokens[index] = merge.output; tokens.remove(index + 1); } } fn best_merge(&self, tokens: &[u32]) -> Option<(usize, BpeMerge)> { if tokens.len() < 2 { return None; } let mut best: Option<(usize, BpeMerge)> = None; for index in 0..tokens.len() - 1 { let left = tokens[index]; let right = tokens[index + 1]; for merge in &self.merges { if merge.left == left && merge.right == right { match best { Some((_, current)) if current.rank <= merge.rank => {} _ => best = Some((index, *merge)), } } } } best } } fn push_limited_byte(bytes: &mut Vec, byte: u8, max_bytes: usize) -> Result<(), ErrorCode> { if bytes.len() >= max_bytes { return Err(ErrorCode::OutputBufferExceeded); } bytes.push(byte); Ok(()) } fn extend_limited_bytes( bytes: &mut Vec, source: &[u8], max_bytes: usize, ) -> Result<(), ErrorCode> { let next_len = bytes .len() .checked_add(source.len()) .ok_or(ErrorCode::OutputBufferExceeded)?; if next_len > max_bytes { return Err(ErrorCode::OutputBufferExceeded); } bytes.extend_from_slice(source); Ok(()) } fn read_u32(bytes: &[u8], offset: usize) -> Result { let end = offset.checked_add(4).ok_or(ErrorCode::InvalidLength)?; let slice = bytes.get(offset..end).ok_or(ErrorCode::InvalidHeader)?; Ok(u32::from_le_bytes( slice.try_into().map_err(|_| ErrorCode::InvalidHeader)?, )) } #[cfg(test)] mod tests { use super::*; fn tiny_bpe_section() -> Vec { let mut bytes = Vec::new(); bytes.extend_from_slice(b"BPE1"); bytes.extend_from_slice(&1u32.to_le_bytes()); bytes.extend_from_slice(&262u32.to_le_bytes()); bytes.extend_from_slice(&BOS.to_le_bytes()); bytes.extend_from_slice(&EOS.to_le_bytes()); bytes.extend_from_slice(&PAD.to_le_bytes()); bytes.extend_from_slice(&UNK.to_le_bytes()); bytes.extend_from_slice(&2u32.to_le_bytes()); bytes.extend_from_slice(&2u32.to_le_bytes()); bytes.extend_from_slice(&260u32.to_le_bytes()); bytes.extend_from_slice(&2u32.to_le_bytes()); bytes.extend_from_slice(b"th"); bytes.extend_from_slice(&261u32.to_le_bytes()); bytes.extend_from_slice(&3u32.to_le_bytes()); bytes.extend_from_slice(b"the"); bytes.extend_from_slice(&116u32.to_le_bytes()); bytes.extend_from_slice(&104u32.to_le_bytes()); bytes.extend_from_slice(&260u32.to_le_bytes()); bytes.extend_from_slice(&0u32.to_le_bytes()); bytes.extend_from_slice(&260u32.to_le_bytes()); bytes.extend_from_slice(&101u32.to_le_bytes()); bytes.extend_from_slice(&261u32.to_le_bytes()); bytes.extend_from_slice(&1u32.to_le_bytes()); bytes } #[test] fn byte_tokenizer_round_trip() { let tokenizer = ByteTokenizer::new(); let mut tokens = Vec::new(); tokenizer.encode("hello", &mut tokens).unwrap(); assert_eq!(tokens, [BOS, 104, 101, 108, 108, 111, EOS]); let mut decoded = String::new(); tokenizer.decode(&tokens, &mut decoded).unwrap(); assert_eq!(decoded, "hello"); } #[test] fn byte_tokenizer_decode_reports_output_buffer_limit() { let tokenizer = ByteTokenizer::new(); let mut decoded = String::from("previous"); assert_eq!( tokenizer .decode_with_limit(&[BOS, 104, 105, EOS], &mut decoded, 1) .unwrap_err(), ErrorCode::OutputBufferExceeded ); assert_eq!(decoded, "previous"); } #[test] fn utf8_prompt_handling() { let tokenizer = ByteTokenizer::new(); let mut tokens = Vec::new(); tokenizer.encode("local ai", &mut tokens).unwrap(); let mut decoded = String::new(); tokenizer.decode(&tokens, &mut decoded).unwrap(); assert_eq!(decoded, "local ai"); } #[test] fn custom_bpe_merges_and_decodes() { let tokenizer = Tokenizer::from_section(&tiny_bpe_section()).unwrap(); assert_eq!(tokenizer.label(), "bpe-v1"); let mut tokens = Vec::new(); tokenizer.encode("the", &mut tokens).unwrap(); assert_eq!(tokens, [BOS, 261, EOS]); let mut decoded = String::new(); tokenizer.decode(&tokens, &mut decoded).unwrap(); assert_eq!(decoded, "the"); } #[test] fn custom_bpe_decode_reports_output_buffer_limit() { let tokenizer = Tokenizer::from_section(&tiny_bpe_section()).unwrap(); let mut decoded = String::from("previous"); assert_eq!( tokenizer .decode_with_limit(&[BOS, 261, EOS], &mut decoded, 2) .unwrap_err(), ErrorCode::OutputBufferExceeded ); assert_eq!(decoded, "previous"); } #[test] fn custom_bpe_rejects_invalid_merge_output() { let mut section = tiny_bpe_section(); let output_offset = section.len() - 8; section[output_offset..output_offset + 4].copy_from_slice(&300u32.to_le_bytes()); assert_eq!( Tokenizer::from_section(§ion).unwrap_err(), ErrorCode::InvalidHeader ); } } ================================================================================ END FILE: tinyrustlm/runtime/src/tokenizer.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/src/wasm_exports.rs BYTES: 5227 SHA256: FB382F3A85D8232A9FB58AAF9F3F3612722FB578A2F1D327DB58E1BAF1753185 ================================================================================ //! Raw WebAssembly exports for handwritten JavaScript. #![allow(unsafe_code)] use crate::errors::ErrorCode; use crate::generate::Runtime; use crate::memory::{allocate_bytes, deallocate_bytes, slice_from_raw}; use std::sync::Mutex; static RUNTIME: Mutex> = Mutex::new(None); /// Allocates `len` bytes in WASM linear memory. #[no_mangle] pub extern "C" fn alloc(len: usize) -> *mut u8 { allocate_bytes(len) } /// Releases a buffer previously returned by [`alloc`]. #[no_mangle] pub unsafe extern "C" fn dealloc(ptr: *mut u8, len: usize) { deallocate_bytes(ptr, len); } /// Initializes runtime state. #[no_mangle] pub extern "C" fn init_runtime() -> u32 { match RUNTIME.lock() { Ok(mut runtime) => { *runtime = Some(Runtime::new()); ErrorCode::Ok.as_u32() } Err(_) => ErrorCode::GenerationFailed.as_u32(), } } /// Loads a model from bytes already copied into WASM memory. #[no_mangle] pub unsafe extern "C" fn load_model(ptr: *const u8, len: usize) -> u32 { let bytes = match slice_from_raw(ptr, len) { Ok(bytes) => bytes, Err(error) => return set_error(error), }; with_runtime_mut(|runtime| runtime.load_model(bytes)) } /// Applies an adapter-delta package from bytes already copied into WASM memory. #[no_mangle] pub unsafe extern "C" fn apply_adapter_delta(ptr: *const u8, len: usize) -> u32 { let bytes = match slice_from_raw(ptr, len) { Ok(bytes) => bytes, Err(error) => return set_error(error), }; with_runtime_mut(|runtime| runtime.apply_adapter_delta(bytes)) } /// Validates an adapter-delta package from bytes already copied into WASM memory. #[no_mangle] pub unsafe extern "C" fn validate_adapter_delta(ptr: *const u8, len: usize) -> u32 { let bytes = match slice_from_raw(ptr, len) { Ok(bytes) => bytes, Err(error) => return set_error(error), }; with_runtime_mut(|runtime| runtime.validate_adapter_delta(bytes)) } /// Generates text from a UTF-8 prompt copied into WASM memory. #[no_mangle] pub unsafe extern "C" fn generate(ptr: *const u8, len: usize, max_new_tokens: u32) -> u32 { let bytes = match slice_from_raw(ptr, len) { Ok(bytes) => bytes, Err(error) => return set_error(error), }; let prompt = match core::str::from_utf8(bytes) { Ok(prompt) => prompt, Err(_) => return set_error(ErrorCode::InvalidUtf8), }; with_runtime_mut(|runtime| runtime.generate(prompt, max_new_tokens)) } /// Configures decoding with temperature, top-k, top-p, and a deterministic seed. #[no_mangle] pub extern "C" fn set_sampling_config(temperature: f32, top_k: u32, top_p: f32, seed: u32) -> u32 { with_runtime_mut(|runtime| runtime.configure_sampling(temperature, top_k, top_p, seed)) } /// Generates a single token and writes its decoded text to the last-result buffer. #[no_mangle] pub extern "C" fn generate_next_token() -> u32 { with_runtime_mut(|runtime| runtime.generate_next_token()) } /// Returns a pointer to the last result bytes. #[no_mangle] pub extern "C" fn last_result_ptr() -> *const u8 { match RUNTIME.lock() { Ok(guard) => guard .as_ref() .map(|runtime| runtime.last_result().as_ptr()) .unwrap_or(core::ptr::null()), Err(_) => core::ptr::null(), } } /// Returns the byte length of the last result. #[no_mangle] pub extern "C" fn last_result_len() -> usize { match RUNTIME.lock() { Ok(guard) => guard .as_ref() .map(|runtime| runtime.last_result().len()) .unwrap_or(0), Err(_) => 0, } } /// Returns a pointer to diagnostics bytes. #[no_mangle] pub extern "C" fn get_diagnostics_ptr() -> *const u8 { match RUNTIME.lock() { Ok(guard) => guard .as_ref() .map(|runtime| runtime.diagnostics().as_ptr()) .unwrap_or(core::ptr::null()), Err(_) => core::ptr::null(), } } /// Returns the byte length of diagnostics. #[no_mangle] pub extern "C" fn get_diagnostics_len() -> usize { match RUNTIME.lock() { Ok(guard) => guard .as_ref() .map(|runtime| runtime.diagnostics().len()) .unwrap_or(0), Err(_) => 0, } } /// Resets the current context. #[no_mangle] pub extern "C" fn reset_context() -> u32 { with_runtime_mut(|runtime| runtime.reset_context()) } /// Frees the loaded model. #[no_mangle] pub extern "C" fn free_model() -> u32 { with_runtime_mut(|runtime| runtime.free_model()) } fn with_runtime_mut(operation: F) -> u32 where F: FnOnce(&mut Runtime) -> ErrorCode, { let Ok(mut guard) = RUNTIME.lock() else { return ErrorCode::GenerationFailed.as_u32(); }; match guard.as_mut() { Some(runtime) => operation(runtime).as_u32(), None => ErrorCode::ModelNotLoaded.as_u32(), } } fn set_error(error: ErrorCode) -> u32 { let Ok(mut guard) = RUNTIME.lock() else { return error.as_u32(); }; if guard.is_none() { *guard = Some(Runtime::new()); } if let Some(runtime) = guard.as_mut() { runtime.record_boundary_error(error); } error.as_u32() } ================================================================================ END FILE: tinyrustlm/runtime/src/wasm_exports.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/runtime/tinyrustlm.wasm.manifest BYTES: 264 SHA256: E9A1CD14425FCA92FCE26CBF3240BFF9F19D35BFE34E1D60F4FE667BF97E1BF3 ================================================================================ tinyrustlm_wasm_manifest_version=1 runtime_kind=tinyrustlm-rust-wasm runtime_status=validated-local-runtime runtime_wasm_path=../runtime/tinyrustlm.wasm runtime_wasm_bytes=141738 runtime_wasm_checksum=0xb91a94b0e82f73c0 required_next_gate=instantiate-wasm-runtime ================================================================================ END FILE: tinyrustlm/runtime/tinyrustlm.wasm.manifest ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt BYTES: 629 SHA256: F0999C05C19029FC240E11A7BCFC41DC7CC43874F9F81ED6F1111BA66D7B76A8 ================================================================================ # TinyRustLM assistant-quality fixture eval cases tinyrustlm_eval_cases_version=1 scope=tiny-converted-source-fixture-only quality_boundary=fixture-runtime-and-eval-plumbing-not-product-assistant-quality safety_review_status=pass quality_decision=accepted-for-assistant-quality evaluator=tinyrustlm-native-eval-runner eval_summary=All declared fixture cases must exactly match deterministic local generation output. case_count=2 case.0.prompt=hi case.0.max_new_tokens=1 case.0.expected_text=e case.0.required_result=exact case.1.prompt=local only case.1.max_new_tokens=4 case.1.expected_text=eeee case.1.required_result=exact ================================================================================ END FILE: tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tests/fixtures/expected-matmul.txt BYTES: 58 SHA256: 2A7C202A61829716681D84FCACB1F4C98245CD86A3B74F466EB83DA829078BC8 ================================================================================ matrix: [[1, 2], [3, 4]] vector: [2, 3] expected: [8, 18] ================================================================================ END FILE: tinyrustlm/tests/fixtures/expected-matmul.txt ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tests/fixtures/expected-rmsnorm.txt BYTES: 76 SHA256: F8AE7363B8D9B31FE9EC2A63CC4A7151738A03B5A1020F11FEA3FA5A67267C11 ================================================================================ input: [1, 2, 3, 4] weight: [1, 1, 1, 1] epsilon: 0 expected[0]: 0.36514837 ================================================================================ END FILE: tinyrustlm/tests/fixtures/expected-rmsnorm.txt ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tests/fixtures/expected-softmax.txt BYTES: 26 SHA256: 03D9687D8125EE74CFE3CFA4DB8FB76373AB4CB1B93DF5690733DA1166BBD108 ================================================================================ input: [1, 2, 3] sum: 1.0 ================================================================================ END FILE: tinyrustlm/tests/fixtures/expected-softmax.txt ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tests/fixtures/tokenizer-cases.txt BYTES: 41 SHA256: A51F68BCDED7FCD462B7398C1A0248E1F0DCF3568172D90E5E3564853AABEC76 ================================================================================ hello local ai TinyRustLM byte tokenizer ================================================================================ END FILE: tinyrustlm/tests/fixtures/tokenizer-cases.txt ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tests/fixtures/trained-source-tiny/source.manifest BYTES: 2598 SHA256: 1CE4EDEE82BECC2B84E5714AAC38A6A6C749AF6F9236DE4CC920F54DC9CDFF86 ================================================================================ tinyrustlm_trained_source_version=1 model_family=tinyrustlm layout=raw-f32-tensor-files-v1 model_shape=tiny-fixture tokenizer=byte-v1 source_dtype=f32 source_kind=trained-source-fixture source_id=tinyrustlm-local-source-fixture source_license=local-fixture-only source_dataset=tinyrustlm-local-conversion-fixture source_training_summary=Deterministic source-weight fixture for conversion path validation vocab_size=260 special_token_count=4 hidden_size=8 layer_count=1 head_count=2 kv_head_count=2 head_dim=4 ffn_size=16 max_context=16 tensor_count=12 tensor.0.name=tok_embeddings.weight tensor.0.rank=2 tensor.0.dims=260,8 tensor.0.file=tensors/tok_embeddings_weight.f32 tensor.0.bytes=8320 tensor.0.checksum=0xae0431d66c945a72 tensor.1.name=norm.weight tensor.1.rank=1 tensor.1.dims=8 tensor.1.file=tensors/norm_weight.f32 tensor.1.bytes=32 tensor.1.checksum=0x26bb47e968d5aebe tensor.2.name=output.weight tensor.2.rank=2 tensor.2.dims=260,8 tensor.2.file=tensors/output_weight.f32 tensor.2.bytes=8320 tensor.2.checksum=0xf585dc20893e92e5 tensor.3.name=layers.0.attention_norm.weight tensor.3.rank=1 tensor.3.dims=8 tensor.3.file=tensors/layers_0_attention_norm_weight.f32 tensor.3.bytes=32 tensor.3.checksum=0x26bb47e968d5aebe tensor.4.name=layers.0.ffn_norm.weight tensor.4.rank=1 tensor.4.dims=8 tensor.4.file=tensors/layers_0_ffn_norm_weight.f32 tensor.4.bytes=32 tensor.4.checksum=0x26bb47e968d5aebe tensor.5.name=layers.0.wq.weight tensor.5.rank=2 tensor.5.dims=8,8 tensor.5.file=tensors/layers_0_wq_weight.f32 tensor.5.bytes=256 tensor.5.checksum=0x33450782b169150f tensor.6.name=layers.0.wk.weight tensor.6.rank=2 tensor.6.dims=8,8 tensor.6.file=tensors/layers_0_wk_weight.f32 tensor.6.bytes=256 tensor.6.checksum=0x33450782b169150f tensor.7.name=layers.0.wv.weight tensor.7.rank=2 tensor.7.dims=8,8 tensor.7.file=tensors/layers_0_wv_weight.f32 tensor.7.bytes=256 tensor.7.checksum=0x33450782b169150f tensor.8.name=layers.0.wo.weight tensor.8.rank=2 tensor.8.dims=8,8 tensor.8.file=tensors/layers_0_wo_weight.f32 tensor.8.bytes=256 tensor.8.checksum=0x33450782b169150f tensor.9.name=layers.0.w1.weight tensor.9.rank=2 tensor.9.dims=16,8 tensor.9.file=tensors/layers_0_w1_weight.f32 tensor.9.bytes=512 tensor.9.checksum=0x1b83f3af9c72f176 tensor.10.name=layers.0.w2.weight tensor.10.rank=2 tensor.10.dims=8,16 tensor.10.file=tensors/layers_0_w2_weight.f32 tensor.10.bytes=512 tensor.10.checksum=0x1b83f3af9c72f176 tensor.11.name=layers.0.w3.weight tensor.11.rank=2 tensor.11.dims=16,8 tensor.11.file=tensors/layers_0_w3_weight.f32 tensor.11.bytes=512 tensor.11.checksum=0x1b83f3af9c72f176 ================================================================================ END FILE: tinyrustlm/tests/fixtures/trained-source-tiny/source.manifest ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/browser_harness/Cargo.toml BYTES: 216 SHA256: 8FFB2F97B8D492D39896BF4BEFC505E8D2B5677013D8E648679319D40C22BF19 ================================================================================ [package] name = "tinyrustlm-browser-harness" version.workspace = true edition.workspace = true license.workspace = true authors.workspace = true repository.workspace = true [dependencies] [lints] workspace = true ================================================================================ END FILE: tinyrustlm/tools/browser_harness/Cargo.toml ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/browser_harness/src/main.rs BYTES: 28776 SHA256: 0057706A7937857A13740E516A5D47461774F7AEF894D618C00CC6B44404C5EE ================================================================================ #![forbid(unsafe_code)] #![doc = "No-crate TinyRustLM mini browser contract harness."] use std::collections::BTreeMap; use std::env; use std::fs; use std::io::{Read, Write}; use std::net::TcpStream; use std::path::{Component, Path, PathBuf}; use std::process::ExitCode; use std::thread; use std::time::Duration; const DEFAULT_ROOT: &str = "tinyrustlm"; const PRIVACY_NOTICE: &str = "All inference runs locally in this browser. Prompts are not sent to a server."; const REQUIRED_IDS: &[&str] = &[ "runtimeStatus", "chatForm", "prompt", "maxTokens", "temperature", "topK", "topP", "seed", "generateButton", "stepTokenButton", "resetButton", "clearChatButton", "conversation", "response", "modelSelect", "adapterSelect", "applyAdapterButton", "adapterPanel", "adapterState", "loadPanel", "wasmState", "modelState", "errorState", "provenancePanel", "provenanceState", "provenanceSourceKind", "provenanceAdmission", "provenanceQualityClaim", "provenanceTrainedClaim", "provenanceGenome", "provenanceSpecies", "provenanceNovelty", "provenancePopulation", "provenanceMateSelection", "provenanceOperator", "provenanceSchedule", "provenancePhenotype", "provenanceArtifact", "provenanceFitness", "provenanceEvalCases", "provenanceEvalChecksum", "provenanceChecksum", "provenanceNextGate", "assemblyPanel", "assemblyState", "assemblyKind", "assemblyParents", "assemblyOperator", "assemblyLedger", "assemblyNextGate", "modulePlanPanel", "modulePlanState", "modulePlanKind", "modulePlanResource", "modulePlanExecution", "modulePlanFetch", "modulePlanOrigin", "modulePlanFetchLimit", "modulePlanPlannedFetchCount", "modulePlanRouteSetChecksumAlgorithm", "modulePlanRouteSetVersion", "modulePlanRouteSetChecksum", "modulePlanWasmPages", "modulePlanWasmExportSet", "modulePlanWasmTransferStrategy", "modulePlanModelReleaseStrategy", "modulePlanRuntimeResetStrategy", "modulePlanAdapterValidationStrategy", "modulePlanAdapterValidationCount", "modulePlanAdapterApplyCount", "modulePlanWasmHeapMinBytes", "modulePlanContextTokens", "modulePlanModules", "modulePlanModelBudget", "modulePlanAdapterBudget", "modulePlanAdapterStackBudget", "modulePlanScratchBudget", "modulePlanPromptLimit", "modulePlanOutputLimit", "modulePlanKvCacheBudget", "modulePlanKvCachePages", "modulePlanTotalBudget", "modulePlanTotalLimit", "modulePlanBytes", "modulePlanChecksums", "modulePlanSlots", "modulePlanRoles", "modulePlanPhases", "modulePlanDepends", "modulePlanTrace", "modulePlanModel", "modulePlanStack", "benchLoadMs", "benchPromptTokens", "benchGeneratedTokens", "benchTokensPerSecond", "benchScratch", "diagnostics", "console", "developer", "appFooter", ]; const REQUIRED_HTML_TEXT: &[&str] = &[ "TinyRustLM", "GGUF.MiRust.com", "Runtime Diagnostics", "Token Generation Console", "Developer Mode", "Model Provenance", "Assembly Evidence", "Module Plan", "Adapter Sidecar", "Conversation", "Local .slm models only", PRIVACY_NOTICE, ]; const REQUIRED_JS_EXPORTS: &[&str] = &[ ".alloc(", ".dealloc(", ".init_runtime(", ".load_model(", ".generate(", ".generate_next_token(", ".validate_adapter_delta(", ".apply_adapter_delta(", ".last_result_ptr(", ".last_result_len(", ".get_diagnostics_ptr(", ".get_diagnostics_len(", ".reset_context(", ".set_sampling_config(", ".free_model(", ]; const REQUIRED_WASM_EXPORTS: &[&str] = &[ "alloc", "dealloc", "init_runtime", "load_model", "generate", "set_sampling_config", "generate_next_token", "validate_adapter_delta", "apply_adapter_delta", "last_result_ptr", "last_result_len", "get_diagnostics_ptr", "get_diagnostics_len", "reset_context", "free_model", ]; const REQUIRED_MODEL_ROUTES: &[(&str, &str, &str)] = &[ ("tinylm16q8", "../models/tinylm16-q8.slm", "q8_0"), ("tinylm16q4", "../models/tinylm16-q4.slm", "q4_0"), ("tinylm16f32", "../models/tinylm16-f32.slm", "f32"), ("tinyf32", "../models/tiny-test-model.slm", "f32"), ("tinytied", "../models/tiny-test-model-tied.slm", "f32"), ("tinyq8", "../models/tiny-test-model-q8.slm", "q8_0"), ("tinyq4", "../models/tiny-test-model-q4.slm", "q4_0"), ("tinybpe", "../models/tiny-test-model-bpe.slm", "f32"), ]; const REQUIRED_MANIFEST_KEYS: &[&str] = &[ "tinyrustlm_slm_manifest_version", "model_path", "model_bytes", "slm_version", "slm_checksum", "model_shape", "tensor_count", "parameter_count", "quantization", "source_kind", "quality_claim", "trained_quality_claim", "admission_status", "required_next_gate", ]; const FORBIDDEN_REMOTE_MARKERS: &[&str] = &[ "http://", "https://", "//cdn", "unpkg", "jsdelivr", "cdnjs", "googleapis", "telemetry", "analytics", ]; fn main() -> ExitCode { match run() { Ok(report) => { println!("{report}"); ExitCode::SUCCESS } Err(error) => { eprintln!("TinyRustLM browser harness failed: {error}"); ExitCode::from(1) } } } fn run() -> Result { let config = Config::from_args(env::args().skip(1))?; let root = config.root.canonicalize().map_err(|source| { HarnessError::InvalidInput(format!("root {}: {source}", config.root.display())) })?; let mut checks = Vec::new(); audit_static_contract(&root, &mut checks)?; if let Some(url) = &config.http_app_url { audit_http_contract(url, &mut checks)?; } Ok(format!( "TinyRustLM browser harness passed: {} checks; root={}; http={}", checks.len(), root.display(), config.http_app_url.as_deref().unwrap_or("not-requested") )) } #[derive(Debug)] struct Config { root: PathBuf, http_app_url: Option, } impl Config { fn from_args(args: I) -> Result where I: Iterator, { let mut root = PathBuf::from(DEFAULT_ROOT); let mut http_app_url = None; let mut positional_root_seen = false; let mut args = args.peekable(); while let Some(arg) = args.next() { match arg.as_str() { "--http" => { let Some(value) = args.next() else { return Err(HarnessError::InvalidInput( "--http requires an app URL".to_string(), )); }; http_app_url = Some(value); } "--help" | "-h" => { return Err(HarnessError::InvalidInput( "usage: tinyrustlm-browser-harness [root] [--http http://127.0.0.1:8080/app/]".to_string(), )); } value if value.starts_with('-') => { return Err(HarnessError::InvalidInput(format!( "unexpected option '{value}'" ))); } value => { if positional_root_seen { return Err(HarnessError::InvalidInput(format!( "unexpected extra root '{value}'" ))); } root = PathBuf::from(value); positional_root_seen = true; } } } Ok(Self { root, http_app_url }) } } #[derive(Debug)] enum HarnessError { InvalidInput(String), Missing(String), Io(std::io::Error), Http(String), } impl std::fmt::Display for HarnessError { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { HarnessError::InvalidInput(message) => write!(formatter, "invalid input: {message}"), HarnessError::Missing(message) => write!(formatter, "missing contract: {message}"), HarnessError::Io(source) => write!(formatter, "{source}"), HarnessError::Http(message) => write!(formatter, "http check failed: {message}"), } } } impl From for HarnessError { fn from(source: std::io::Error) -> Self { HarnessError::Io(source) } } fn audit_static_contract(root: &Path, checks: &mut Vec) -> Result<(), HarnessError> { let index = read_utf8(root.join("app").join("index.html"))?; let js = read_utf8(root.join("app").join("app.js"))?; let css = read_utf8(root.join("app").join("app.css"))?; let wasm_exports = read_utf8(root.join("runtime").join("src").join("wasm_exports.rs"))?; require_no_remote_markers("index.html", &index)?; require_no_remote_markers("app.js", &js)?; require_no_remote_markers("app.css", &css)?; checks.push("static files contain no remote markers".to_string()); for id in REQUIRED_IDS { require_contains("index.html id", &index, &format!("id=\"{id}\""))?; } checks.push(format!("{} required UI ids", REQUIRED_IDS.len())); for text in REQUIRED_HTML_TEXT { require_contains("index.html text", &index, text)?; } checks.push(format!( "{} required visible text markers", REQUIRED_HTML_TEXT.len() )); require_contains("index.html stylesheet", &index, "href=\"./app.css\"")?; require_contains("index.html script", &index, "src=\"./app.js\"")?; checks.push("html asset links".to_string()); require_contains("app.js wasm path", &js, "../runtime/tinyrustlm.wasm")?; require_contains( "app.js wasm manifest path", &js, "../runtime/tinyrustlm.wasm.manifest", )?; require_contains("app.js wasm instantiate", &js, "WebAssembly.instantiate")?; require_contains("app.js local fetch", &js, "fetch(")?; require_contains("app.js manifest fetch", &js, "model.path")?; require_contains("app.js manifest fetch", &js, ".manifest")?; require_contains( "app.js selector registry fetch", &js, "../models/selector.registry", )?; require_contains( "app.js selector registry status", &js, "admitted-records-only", )?; require_contains( "app.js adapter sidecar route", &js, "../models/tiny-test-model-self.adp1", )?; require_contains( "app.js adapter stack strategy", &js, "receipt-declared-compatible-stack", )?; require_contains( "app.js module plan strategy", &js, "selector-entry-self-assembly", )?; require_contains( "app.js module plan resource class", &js, "browser-constrained-local-assembly", )?; require_contains("app.js module plan profile", &js, "browser-constrained-v1")?; require_contains( "app.js module plan execution profile", &js, "single-threaded-wasm-local-v1", )?; require_contains("app.js module plan fetch policy", &js, "local-no-store-v1")?; require_contains( "app.js module plan origin policy", &js, "same-origin-loopback-local-v1", )?; require_contains( "app.js module plan wasm export set", &js, "tinyrustlm-generate-v1", )?; for export in REQUIRED_JS_EXPORTS { require_contains("app.js wasm export", &js, export)?; } checks.push(format!( "{} required WASM boundary calls", REQUIRED_JS_EXPORTS.len() )); for export in REQUIRED_WASM_EXPORTS { require_wasm_export(&wasm_exports, export)?; } checks.push(format!( "{} required Rust WASM exports", REQUIRED_WASM_EXPORTS.len() )); for (key, route, quantization) in REQUIRED_MODEL_ROUTES { require_contains( "index.html model option", &index, &format!("value=\"{key}\""), )?; require_contains("app.js model route", &js, route)?; audit_model_and_manifest(root, route, quantization)?; } checks.push(format!( "{} local model routes and manifests", REQUIRED_MODEL_ROUTES.len() )); audit_runtime_wasm_manifest(root)?; checks.push("runtime WASM manifest".to_string()); require_contains("app.css responsive behavior", &css, "@media")?; require_contains("app.css status error state", &css, ".error")?; require_contains("app.css shell layout", &css, ".shell")?; checks.push("css layout and error-state markers".to_string()); Ok(()) } fn audit_runtime_wasm_manifest(root: &Path) -> Result<(), HarnessError> { let wasm_path = root.join("runtime").join("tinyrustlm.wasm"); let manifest_path = root.join("runtime").join("tinyrustlm.wasm.manifest"); if !wasm_path.is_file() { return Err(HarnessError::Missing(format!( "runtime WASM file {}", wasm_path.display() ))); } if !manifest_path.is_file() { return Err(HarnessError::Missing(format!( "runtime WASM manifest {}", manifest_path.display() ))); } let manifest_text = read_utf8(&manifest_path)?; require_no_remote_markers("runtime WASM manifest", &manifest_text)?; let fields = parse_manifest(&manifest_text); require_manifest_value(&fields, "tinyrustlm_wasm_manifest_version", "1")?; require_manifest_value(&fields, "runtime_kind", "tinyrustlm-rust-wasm")?; require_manifest_value(&fields, "runtime_status", "validated-local-runtime")?; require_manifest_value(&fields, "runtime_wasm_path", "../runtime/tinyrustlm.wasm")?; require_manifest_value( &fields, "runtime_wasm_bytes", &fs::metadata(&wasm_path)?.len().to_string(), )?; let checksum = fields .get("runtime_wasm_checksum") .ok_or_else(|| HarnessError::Missing("runtime_wasm_checksum".to_string()))?; if checksum.len() != 18 || !checksum.starts_with("0x") || !checksum[2..].bytes().all(|byte| byte.is_ascii_hexdigit()) { return Err(HarnessError::InvalidInput(format!( "invalid runtime_wasm_checksum {checksum}" ))); } require_manifest_value(&fields, "required_next_gate", "instantiate-wasm-runtime")?; Ok(()) } fn audit_model_and_manifest( root: &Path, app_relative_route: &str, expected_quantization: &str, ) -> Result<(), HarnessError> { let model_path = resolve_app_relative(root, app_relative_route)?; let manifest_path = PathBuf::from(format!("{}.manifest", model_path.display())); if !model_path.is_file() { return Err(HarnessError::Missing(format!( "model file {}", model_path.display() ))); } if !manifest_path.is_file() { return Err(HarnessError::Missing(format!( "manifest file {}", manifest_path.display() ))); } let manifest_text = read_utf8(&manifest_path)?; require_no_remote_markers("manifest", &manifest_text)?; let fields = parse_manifest(&manifest_text); for key in REQUIRED_MANIFEST_KEYS { if !fields.contains_key(*key) { return Err(HarnessError::Missing(format!( "manifest key {key} in {}", manifest_path.display() ))); } } require_manifest_value(&fields, "quantization", expected_quantization)?; require_manifest_value(&fields, "trained_quality_claim", "not-claimed")?; require_manifest_value( &fields, "required_next_gate", "replace-with-trained-or-evaluated-model-before-product-quality-claim", )?; let model_bytes = fs::metadata(&model_path)?.len().to_string(); require_manifest_value(&fields, "model_bytes", &model_bytes)?; Ok(()) } fn resolve_app_relative(root: &Path, route: &str) -> Result { if route.contains('\\') || route.contains(':') || route.starts_with('/') { return Err(HarnessError::InvalidInput(format!( "unsafe app route '{route}'" ))); } let app_root = root.join("app"); let mut out = app_root; for part in route.split('/') { match part { "" | "." => {} ".." => { if !out.pop() { return Err(HarnessError::InvalidInput(format!( "route escapes root '{route}'" ))); } } value => out.push(value), } } let canonical_root = root.canonicalize()?; let parent = out.parent().unwrap_or(root); let canonical_parent = parent.canonicalize()?; if !canonical_parent.starts_with(&canonical_root) { return Err(HarnessError::InvalidInput(format!( "route escapes root '{route}'" ))); } Ok(out) } fn audit_http_contract(app_url: &str, checks: &mut Vec) -> Result<(), HarnessError> { let parsed = HttpUrl::parse(app_url)?; if !parsed.path.ends_with("/app/") { return Err(HarnessError::Http(format!( "app URL must end in /app/, got {}", parsed.path ))); } let routes = [ ("GET", "/app/", "text/html"), ("HEAD", "/app/app.css", "text/css"), ("HEAD", "/app/app.js", "text/javascript"), ("HEAD", "/runtime/tinyrustlm.wasm", "application/wasm"), ("HEAD", "/runtime/tinyrustlm.wasm.manifest", "text/plain"), ( "HEAD", "/models/tinylm16-q8.slm", "application/octet-stream", ), ("HEAD", "/models/tinylm16-q8.slm.manifest", "text/plain"), ]; for (method, path, content_type) in routes { let response = http_request(&parsed.host, parsed.port, method, path)?; if response.status != 200 { return Err(HarnessError::Http(format!( "{method} {path} returned {}", response.status ))); } let actual_type = response .headers .get("content-type") .map(String::as_str) .unwrap_or(""); if !actual_type.starts_with(content_type) { return Err(HarnessError::Http(format!( "{method} {path} content-type '{actual_type}' did not start with '{content_type}'" ))); } if method == "GET" { let body = String::from_utf8_lossy(&response.body); require_contains("http app body", &body, "TinyRustLM")?; require_contains("http app body", &body, PRIVACY_NOTICE)?; } } checks.push("loopback HTTP app, asset, WASM, model, and manifest routes".to_string()); Ok(()) } #[derive(Debug, Eq, PartialEq)] struct HttpUrl { host: String, port: u16, path: String, } impl HttpUrl { fn parse(input: &str) -> Result { let Some(rest) = input.strip_prefix("http://") else { return Err(HarnessError::Http( "only http:// loopback URLs are supported".to_string(), )); }; let slash = rest .find('/') .ok_or_else(|| HarnessError::Http("missing URL path".to_string()))?; let authority = &rest[..slash]; let path = &rest[slash..]; let (host, port) = match authority.rsplit_once(':') { Some((host, port_text)) => { let port = port_text .parse::() .map_err(|_| HarnessError::Http(format!("invalid port '{port_text}'")))?; (host.to_string(), port) } None => (authority.to_string(), 80), }; if host != "127.0.0.1" && host != "localhost" { return Err(HarnessError::Http(format!( "non-loopback host '{host}' is forbidden" ))); } Ok(Self { host, port, path: path.to_string(), }) } } #[derive(Debug)] struct HttpResponse { status: u16, headers: BTreeMap, body: Vec, } fn http_request( host: &str, port: u16, method: &str, path: &str, ) -> Result { let mut last_socket_error = None; for _attempt in 0..3 { match http_request_once(host, port, method, path) { Ok(response) => return Ok(response), Err(HarnessError::Io(error)) if matches!( error.kind(), std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted ) => { last_socket_error = Some(error.to_string()); thread::sleep(Duration::from_millis(75)); } Err(error) => return Err(error), } } Err(HarnessError::Http(format!( "{method} {path} loopback socket closed repeatedly: {}", last_socket_error.unwrap_or_else(|| "unknown socket error".to_string()) ))) } fn http_request_once( host: &str, port: u16, method: &str, path: &str, ) -> Result { let mut stream = TcpStream::connect((host, port)).map_err(|source| { HarnessError::Http(format!( "connect {host}:{port} for {method} {path}: {source}" )) })?; stream.set_read_timeout(Some(Duration::from_secs(5)))?; stream.set_write_timeout(Some(Duration::from_secs(5)))?; let request = format!("{method} {path} HTTP/1.1\r\nHost: {host}:{port}\r\nConnection: close\r\n\r\n"); stream.write_all(request.as_bytes())?; stream.flush()?; let mut bytes = Vec::new(); let mut buffer = [0u8; 8192]; loop { match stream.read(&mut buffer) { Ok(0) => break, Ok(len) => bytes.extend_from_slice(&buffer[..len]), Err(error) if matches!( error.kind(), std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted ) && !bytes.is_empty() => { break; } Err(error) => return Err(HarnessError::Io(error)), } } parse_http_response(&bytes) } fn parse_http_response(bytes: &[u8]) -> Result { let split = find_header_split(bytes) .ok_or_else(|| HarnessError::Http("response missing header terminator".to_string()))?; let headers_text = String::from_utf8_lossy(&bytes[..split]); let body = bytes[split + 4..].to_vec(); let mut lines = headers_text.lines(); let status_line = lines .next() .ok_or_else(|| HarnessError::Http("missing response status".to_string()))?; let mut status_parts = status_line.split_whitespace(); let version = status_parts.next().unwrap_or(""); if !version.starts_with("HTTP/") { return Err(HarnessError::Http(format!( "invalid status line '{status_line}'" ))); } let status = status_parts .next() .ok_or_else(|| HarnessError::Http("missing status code".to_string()))? .parse::() .map_err(|_| HarnessError::Http(format!("invalid status line '{status_line}'")))?; let mut headers = BTreeMap::new(); for line in lines { if let Some((key, value)) = line.split_once(':') { headers.insert( key.trim().to_ascii_lowercase(), value.trim().to_ascii_lowercase(), ); } } Ok(HttpResponse { status, headers, body, }) } fn find_header_split(bytes: &[u8]) -> Option { bytes.windows(4).position(|window| window == b"\r\n\r\n") } fn parse_manifest(text: &str) -> BTreeMap { let mut fields = BTreeMap::new(); for line in text.lines() { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') { continue; } if let Some((key, value)) = trimmed.split_once('=') { fields.insert(key.trim().to_string(), value.trim().to_string()); } } fields } fn read_utf8(path: impl AsRef) -> Result { let path = path.as_ref(); fs::read_to_string(path).map_err(|source| { if source.kind() == std::io::ErrorKind::NotFound { HarnessError::Missing(format!("file {}", path.display())) } else { HarnessError::Io(source) } }) } fn require_contains(label: &str, haystack: &str, needle: &str) -> Result<(), HarnessError> { if haystack.contains(needle) { Ok(()) } else { Err(HarnessError::Missing(format!("{label} '{needle}'"))) } } fn require_wasm_export(source: &str, name: &str) -> Result<(), HarnessError> { let safe_export = format!("pub extern \"C\" fn {name}"); let unsafe_export = format!("pub unsafe extern \"C\" fn {name}"); if source.contains(&safe_export) || source.contains(&unsafe_export) { Ok(()) } else { Err(HarnessError::Missing(format!( "wasm_exports.rs export '{name}'" ))) } } fn require_no_remote_markers(label: &str, text: &str) -> Result<(), HarnessError> { let lowered = text.to_ascii_lowercase(); for marker in FORBIDDEN_REMOTE_MARKERS { if lowered.contains(marker) { return Err(HarnessError::Missing(format!( "{label} contains forbidden remote marker '{marker}'" ))); } } Ok(()) } fn require_manifest_value( fields: &BTreeMap, key: &str, expected: &str, ) -> Result<(), HarnessError> { match fields.get(key) { Some(actual) if actual == expected => Ok(()), Some(actual) => Err(HarnessError::Missing(format!( "manifest {key} expected '{expected}' but got '{actual}'" ))), None => Err(HarnessError::Missing(format!("manifest key {key}"))), } } #[allow(dead_code)] fn assert_safe_relative_path(path: &Path) -> Result<(), HarnessError> { if path.is_absolute() { return Err(HarnessError::InvalidInput(format!( "absolute path {}", path.display() ))); } for component in path.components() { match component { Component::Normal(_) => {} _ => { return Err(HarnessError::InvalidInput(format!( "unsafe path {}", path.display() ))) } } } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn parses_loopback_http_url() { let parsed = HttpUrl::parse("http://127.0.0.1:8080/app/").expect("url"); assert_eq!( parsed, HttpUrl { host: "127.0.0.1".to_string(), port: 8080, path: "/app/".to_string(), } ); } #[test] fn rejects_remote_http_url() { assert!(matches!( HttpUrl::parse("http://example.com:8080/app/"), Err(HarnessError::Http(_)) )); } #[test] fn parses_manifest_fields() { let fields = parse_manifest("a=1\n# skip\nb = two\n"); assert_eq!(fields.get("a").map(String::as_str), Some("1")); assert_eq!(fields.get("b").map(String::as_str), Some("two")); } #[test] fn parses_http_response() { let response = parse_http_response(b"HTTP/1.1 200 OK\r\ncontent-type: text/html\r\n\r\n") .expect("response"); assert_eq!(response.status, 200); assert_eq!( response.headers.get("content-type").map(String::as_str), Some("text/html") ); assert_eq!(response.body, b""); } #[test] fn rejects_remote_markers() { assert!(require_no_remote_markers("x", "fetch('https://example.test')").is_err()); } #[test] fn detects_safe_and_unsafe_wasm_exports() { let source = r#" #[no_mangle] pub extern "C" fn alloc(len: usize) -> *mut u8 { core::ptr::null_mut() } #[no_mangle] pub unsafe extern "C" fn load_model(ptr: *const u8, len: usize) -> u32 { 0 } "#; assert!(require_wasm_export(source, "alloc").is_ok()); assert!(require_wasm_export(source, "load_model").is_ok()); assert!(require_wasm_export(source, "missing").is_err()); } } ================================================================================ END FILE: tinyrustlm/tools/browser_harness/src/main.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/browser-smoke.js BYTES: 422100 SHA256: 85502011F5E8E364EEA9CA4454615FE32C79882C439852AB765C8C5F1E20312B ================================================================================ #!/usr/bin/env node "use strict"; const childProcess = require("child_process"); const fs = require("fs"); const http = require("http"); const https = require("https"); const os = require("os"); const path = require("path"); const appUrl = process.argv[2] || "http://127.0.0.1:8080/app/"; const port = Number(process.argv[3] || 9223); const smokeMode = process.argv[5] || "single"; const combinedSelectorOperatorFamilyRouteSoakMode = smokeMode === "combined-selector-operator-family-route-soak"; const combinedSelectorOperatorFamilyReloadSoakMode = smokeMode === "combined-selector-operator-family-reload-soak"; const combinedSelectorRouteSoakMode = combinedSelectorOperatorFamilyRouteSoakMode || smokeMode === "combined-selector-route-soak" || smokeMode === "combined-selector-route-extended-soak" || smokeMode === "combined-selector-route-stress-soak"; const convertedTrainedRegistrySmokeMode = smokeMode === "converted-trained-registry"; const convertedTrainedRegistryFileSmokeMode = smokeMode === "converted-trained-registry-file"; const convertedTrainedRegistryAnySmokeMode = convertedTrainedRegistrySmokeMode || convertedTrainedRegistryFileSmokeMode; const q4DefaultSmokeModes = new Set([ "adapter-manifest-budget", "adapter-family-receipt-drift", "adapter-manifest-drift", "source-backed-alr1-manifest-drift", "adapter-artifact-drift", "module-plan-payload-checksum-drift", "adapter-stack-prefetch-drift", "adapter-stack-rust-validate-drift", "module-plan-profile-drift", "module-plan-execution-profile-drift", "module-plan-fetch-policy-drift", "module-plan-origin-policy-drift", "module-plan-wasm-memory-drift", "module-plan-wasm-export-set-drift", "module-plan-wasm-transfer-drift", "module-plan-model-release-drift", "module-plan-runtime-reset-drift", "module-plan-adapter-validation-drift", "module-plan-adapter-validation-count-drift", "module-plan-adapter-apply-count-drift", "module-plan-wasm-heap-drift", "module-plan-context-token-drift", "module-plan-sampler-cap-drift", "module-plan-tokenizer-drift", "module-plan-resource-drift", "module-plan-runtime-scratch-drift", "module-plan-output-limit-drift", "module-plan-prompt-limit-drift", "module-plan-fetch-count-drift", "module-plan-planned-fetch-count-drift", "module-plan-route-set-algorithm-drift", "module-plan-route-set-version-drift", "module-plan-route-set-drift", "module-plan-operator-receipt-drift", "module-plan-kv-cache-drift", "module-plan-adapter-stack-budget-drift", "module-plan-total-budget-drift", "module-plan-total-limit-drift", "module-plan-count-drift", "module-plan-graph-drift", "module-plan-stack-drift", "module-plan-role-drift", "module-plan-slot-drift", "module-plan-phase-drift", "module-plan-byte-drift", "module-plan-checksum-drift", "module-plan-dependency-drift", "assembly-eval-case-drift", "assembly-evidence-file-drift", "combined-selector-assembly", "combined-selector-operator-family", "combined-selector-operator-family-cycle", "combined-selector-operator-family-route-soak", "combined-selector-operator-family-reload-soak", "combined-selector-cycle", "combined-selector-reload-soak" ]); const compactOperatorRegistryModels = { "multi-parent-registry": "multi-parent-sign-merge-q8", "blend-operator-registry": "tinylm16-blend-q8", "delta-operator-registry": "tinylm16-delta-q8", "sparse-delta-operator-registry": "tinylm16-sparse-delta-q8", "dare-operator-registry": "tinylm16-dare-q8", "prune-operator-registry": "tinylm16-prune-q8", "crossover-operator-registry": "tinylm16-crossover-q8", "mutation-operator-registry": "tinylm16-mutation-q8" }; const compactOperatorRegistrySmokeModes = new Set(Object.keys(compactOperatorRegistryModels)); const compactOperatorReceiptDriftSmokeModes = new Set([ "selector-operator-receipt-drift", "blend-operator-receipt-drift", "delta-operator-receipt-drift", "sparse-delta-operator-receipt-drift", "dare-operator-receipt-drift", "prune-operator-receipt-drift", "crossover-operator-receipt-drift", "mutation-operator-receipt-drift" ]); const expectedModel = process.argv[4] || compactOperatorRegistryModels[smokeMode] || (convertedTrainedRegistryAnySmokeMode ? "converted-trained-q8" : smokeMode === "adapter-sidecar-registry-q8" ? "tinyq8" : q4DefaultSmokeModes.has(smokeMode) || combinedSelectorRouteSoakMode ? "multi-parent-sign-merge-q4" : smokeMode === "multi-parent-registry-file" || smokeMode === "adapter-sidecar-registry-file" ? "multi-parent-sign-merge-f32" : smokeMode === "adapter-sidecar" || smokeMode === "adapter-sidecar-checksum-mismatch" ? "tinyf32" : "tinylm16q8"); const enduranceCycles = Math.max(2, Math.min(20, Number.parseInt(process.argv[6] || "4", 10) || 4)); const performanceTokens = Math.max(2, Math.min(8, Number.parseInt(process.argv[6] || "4", 10) || 4)); const performanceSoakCycles = Math.max(2, Math.min(10, Number.parseInt(process.argv[6] || "3", 10) || 3)); const performanceSoakTokens = Math.max(2, Math.min(8, Number.parseInt(process.argv[7] || "4", 10) || 4)); const combinedSelectorDefaultCycles = smokeMode === "combined-selector-route-stress-soak" ? "8" : smokeMode === "combined-selector-route-extended-soak" ? "5" : smokeMode === "combined-selector-route-soak" ? "3" : "2"; const combinedSelectorMinCycles = smokeMode === "combined-selector-route-stress-soak" ? 8 : smokeMode === "combined-selector-route-extended-soak" ? 5 : smokeMode === "combined-selector-route-soak" ? 3 : 2; const combinedSelectorCycles = Math.max(combinedSelectorMinCycles, Math.min(10, Number.parseInt(process.argv[6] || combinedSelectorDefaultCycles, 10) || Number.parseInt(combinedSelectorDefaultCycles, 10))); const combinedSelectorReloads = Math.max(2, Math.min(6, Number.parseInt(process.argv[6] || "2", 10) || 2)); const checksumMask64 = (1n << 64n) - 1n; const checksumPrime64 = 0x100000001b3n; function combinedSelectorModelsFor(modelKey, mode = smokeMode) { // Selects the generated operator family while preserving q4-first frugal switching order. if ( mode === "combined-selector-operator-family" || mode === "combined-selector-operator-family-cycle" || mode === "combined-selector-operator-family-route-soak" || mode === "combined-selector-operator-family-reload-soak" ) { return [ "multi-parent-sign-merge-q4", "multi-parent-soup-q4", "multi-parent-sign-merge-q8", "multi-parent-soup-q8", "multi-parent-sign-merge-f32", "multi-parent-soup-f32" ]; } const prefix = String(modelKey || "").startsWith("multi-parent-soup-") ? "multi-parent-soup" : "multi-parent-sign-merge"; return [`${prefix}-q4`, `${prefix}-q8`, `${prefix}-f32`]; } const combinedSelectorModels = combinedSelectorModelsFor(expectedModel); function isGeneratedMultiParentModel(modelKey) { // Groups generated parent-pool bundles whose evidence is validated before browser use. return modelKey.startsWith("multi-parent-sign-merge-") || modelKey.startsWith("multi-parent-soup-"); } function expectedOperatorKindForModel(modelKey) { if (modelKey.startsWith("multi-parent-soup-")) { return "seed-weighted-parent-pool-soup"; } if (modelKey.startsWith("multi-parent-sign-merge-")) { return "sign-aware-parent-pool-merge"; } return ""; } function expectedEvolutionScheduleForModel(modelKey) { // Mirrors the parent-pool recipe family order written into generated selector entries. if (modelKey.startsWith("multi-parent-soup-")) { return { familyIndex: 1, familyCommand: "soup-candidate" }; } if (modelKey.startsWith("multi-parent-sign-merge-")) { return { familyIndex: 0, familyCommand: "sign-merge-candidate" }; } return null; } const expectedQuantization = { tinylm16q8: "q8_0", tinylm16q4: "q4_0", tinylm16f32: "f32", tinyf32: "f32", tinytied: "f32", tinyq8: "q8_0", tinyq4: "q4_0", tinybpe: "f32", "tinylm16-blend-q8": "q8_0", "tinylm16-delta-q8": "q8_0", "tinylm16-sparse-delta-q8": "q8_0", "tinylm16-dare-q8": "q8_0", "tinylm16-prune-q8": "q8_0", "tinylm16-crossover-q8": "q8_0", "tinylm16-mutation-q8": "q8_0", "converted-trained-f32": "f32", "converted-trained-q8": "q8_0", "converted-trained-q4": "q4_0", "multi-parent-sign-merge-q8": "q8_0", "multi-parent-sign-merge-q4": "q4_0", "multi-parent-sign-merge-f32": "f32", "multi-parent-soup-q8": "q8_0", "multi-parent-soup-q4": "q4_0", "multi-parent-soup-f32": "f32" }; const expectedModelLabels = { "tinylm16-blend-q8": "TinyLM-16M q8 blend candidate", "tinylm16-delta-q8": "TinyLM-16M q8 delta candidate", "tinylm16-sparse-delta-q8": "TinyLM-16M q8 sparse-delta candidate", "tinylm16-dare-q8": "TinyLM-16M q8 DARE candidate", "tinylm16-prune-q8": "TinyLM-16M q8 prune candidate", "tinylm16-crossover-q8": "TinyLM-16M q8 crossover candidate", "tinylm16-mutation-q8": "TinyLM-16M q8 mutation candidate", "converted-trained-f32": "Converted trained-source f32", "converted-trained-q8": "Converted trained-source q8_0", "converted-trained-q4": "Converted trained-source q4_0", "multi-parent-sign-merge-q8": "multi-parent-sign-merge-q8 q8_0", "multi-parent-sign-merge-q4": "multi-parent-sign-merge-q4 q4_0", "multi-parent-sign-merge-f32": "multi-parent-sign-merge-f32 f32", "multi-parent-soup-q8": "multi-parent-soup-q8 q8_0", "multi-parent-soup-q4": "multi-parent-soup-q4 q4_0", "multi-parent-soup-f32": "multi-parent-soup-f32 f32" }; const expectedModelRoutes = { tinyq8: "/models/tiny-test-model-q8.slm", tinyq4: "/models/tiny-test-model-q4.slm", "tinylm16-blend-q8": "/models/tinylm16-q8.slm", "tinylm16-delta-q8": "/models/tinylm16-q8.slm", "tinylm16-sparse-delta-q8": "/models/tinylm16-q8.slm", "tinylm16-dare-q8": "/models/tinylm16-q8.slm", "tinylm16-prune-q8": "/models/tinylm16-q8.slm", "tinylm16-crossover-q8": "/models/tinylm16-q8.slm", "tinylm16-mutation-q8": "/models/tinylm16-q8.slm", "converted-trained-f32": "/models/converted-trained-f32.slm", "converted-trained-q8": "/models/converted-trained-q8.slm", "converted-trained-q4": "/models/converted-trained-q4.slm", "multi-parent-sign-merge-q8": "/models/multi-parent-sign-merge-q8.slm", "multi-parent-sign-merge-q4": "/models/multi-parent-sign-merge-q4.slm", "multi-parent-sign-merge-f32": "/models/multi-parent-sign-merge-f32.slm", "multi-parent-soup-q8": "/models/multi-parent-soup-q8.slm", "multi-parent-soup-q4": "/models/multi-parent-soup-q4.slm", "multi-parent-soup-f32": "/models/multi-parent-soup-f32.slm" }; const expectedAdapterLabels = { tinyf32: ["Tiny Fixture f32 self ADP1"], tinyq8: ["Tiny Fixture q8_0 self ADP1"], tinyq4: ["Tiny Fixture q4_0 self ADP1"], "multi-parent-sign-merge-f32": [ "Multi-parent sign-merge f32 self ADP1", "Multi-parent sign-merge f32 family ADP1", "Multi-parent sign-merge f32 sparse ASP1", "Multi-parent sign-merge f32 source-backed ALR1" ], "multi-parent-sign-merge-q8": [ "Multi-parent sign-merge q8_0 self ADP1", "Multi-parent sign-merge q8_0 family ADP1", "Multi-parent sign-merge q8_0 sparse ASP1", "Multi-parent sign-merge q8_0 source-backed ALR1" ], "multi-parent-sign-merge-q4": [ "Multi-parent sign-merge q4_0 self ADP1", "Multi-parent sign-merge q4_0 family ADP1", "Multi-parent sign-merge q4_0 sparse ASP1", "Multi-parent sign-merge q4_0 source-backed ALR1" ], "multi-parent-soup-q8": [ "Multi-parent weighted soup q8_0 self ADP1", "Multi-parent weighted soup q8_0 family ADP1", "Multi-parent weighted soup q8_0 sparse ASP1", "Multi-parent weighted soup q8_0 source-backed ALR1" ], "multi-parent-soup-q4": [ "Multi-parent weighted soup q4_0 self ADP1", "Multi-parent weighted soup q4_0 family ADP1", "Multi-parent weighted soup q4_0 sparse ASP1", "Multi-parent weighted soup q4_0 source-backed ALR1" ], "multi-parent-soup-f32": [ "Multi-parent weighted soup f32 self ADP1", "Multi-parent weighted soup f32 family ADP1", "Multi-parent weighted soup f32 sparse ASP1", "Multi-parent weighted soup f32 source-backed ALR1" ] }; const expectedAdapterRoutes = { tinyf32: "/models/tiny-test-model-self.adp1", tinyq8: "/models/tiny-test-model-q8-self.adp1", tinyq4: "/models/tiny-test-model-q4-self.adp1", "multi-parent-sign-merge-q8": "/models/multi-parent-sign-merge-q8-sparse.asp1", "multi-parent-sign-merge-q4": "/models/multi-parent-sign-merge-q4-sparse.asp1", "multi-parent-sign-merge-f32": "/models/multi-parent-sign-merge-f32-sparse.asp1", "multi-parent-soup-q8": "/models/multi-parent-soup-q8-sparse.asp1", "multi-parent-soup-q4": "/models/multi-parent-soup-q4-sparse.asp1", "multi-parent-soup-f32": "/models/multi-parent-soup-f32-sparse.asp1" }; const expectedAdapterStackRoutes = { "multi-parent-sign-merge-q8": [ "/models/multi-parent-sign-merge-q8-family.adp1", "/models/multi-parent-sign-merge-q8-sparse.asp1", "/models/multi-parent-sign-merge-q8-low-rank.alr1" ], "multi-parent-sign-merge-q4": [ "/models/multi-parent-sign-merge-q4-family.adp1", "/models/multi-parent-sign-merge-q4-sparse.asp1", "/models/multi-parent-sign-merge-q4-low-rank.alr1" ], "multi-parent-sign-merge-f32": [ "/models/multi-parent-sign-merge-f32-family.adp1", "/models/multi-parent-sign-merge-f32-sparse.asp1", "/models/multi-parent-sign-merge-f32-low-rank.alr1" ], "multi-parent-soup-q8": [ "/models/multi-parent-soup-q8-family.adp1", "/models/multi-parent-soup-q8-sparse.asp1", "/models/multi-parent-soup-q8-low-rank.alr1" ], "multi-parent-soup-q4": [ "/models/multi-parent-soup-q4-family.adp1", "/models/multi-parent-soup-q4-sparse.asp1", "/models/multi-parent-soup-q4-low-rank.alr1" ], "multi-parent-soup-f32": [ "/models/multi-parent-soup-f32-family.adp1", "/models/multi-parent-soup-f32-sparse.asp1", "/models/multi-parent-soup-f32-low-rank.alr1" ] }; const expectedAdapterFamilyReceiptRoutes = { "multi-parent-sign-merge-q8": "/models/multi-parent-sign-merge-q8.adapter-family.receipt", "multi-parent-sign-merge-q4": "/models/multi-parent-sign-merge-q4.adapter-family.receipt", "multi-parent-sign-merge-f32": "/models/multi-parent-sign-merge-f32.adapter-family.receipt", "multi-parent-soup-q8": "/models/multi-parent-soup-q8.adapter-family.receipt", "multi-parent-soup-q4": "/models/multi-parent-soup-q4.adapter-family.receipt", "multi-parent-soup-f32": "/models/multi-parent-soup-f32.adapter-family.receipt" }; const expectedAssemblyReceiptRoutes = { "multi-parent-sign-merge-q8": "/models/multi-parent-sign-merge-q8.assembly.receipt", "multi-parent-sign-merge-q4": "/models/multi-parent-sign-merge-q4.assembly.receipt", "multi-parent-sign-merge-f32": "/models/multi-parent-sign-merge-f32.assembly.receipt", "multi-parent-soup-q8": "/models/multi-parent-soup-q8.assembly.receipt", "multi-parent-soup-q4": "/models/multi-parent-soup-q4.assembly.receipt", "multi-parent-soup-f32": "/models/multi-parent-soup-f32.assembly.receipt" }; const expectedModulePlanRoutes = { "multi-parent-sign-merge-q8": "/models/multi-parent-sign-merge-q8.module-plan.receipt", "multi-parent-sign-merge-q4": "/models/multi-parent-sign-merge-q4.module-plan.receipt", "multi-parent-sign-merge-f32": "/models/multi-parent-sign-merge-f32.module-plan.receipt", "multi-parent-soup-q8": "/models/multi-parent-soup-q8.module-plan.receipt", "multi-parent-soup-q4": "/models/multi-parent-soup-q4.module-plan.receipt", "multi-parent-soup-f32": "/models/multi-parent-soup-f32.module-plan.receipt" }; const expectedModulePlanExecutionProfile = "single-threaded-wasm-local-v1"; const expectedModulePlanFetchPolicy = "local-no-store-v1"; const expectedModulePlanOriginPolicy = "same-origin-loopback-local-v1"; const expectedModulePlanFetchLimit = "32 fetches"; const expectedModulePlanFetchLimitCount = 32; const expectedModulePlanPlannedFetches = "21 fetches"; const expectedModulePlanActualFetches = 21; const expectedModulePlanRouteSetVersion = "1"; const expectedModulePlanRouteSetChecksumAlgorithm = "tinyrustlm-text-checksum-v1"; const expectedModulePlanWasmMemoryInitialPages = "17"; const expectedModulePlanWasmExportSet = "tinyrustlm-generate-v1"; const expectedModulePlanWasmTransferStrategy = "copy-then-release-v1"; const expectedModulePlanModelReleaseStrategy = "free-before-reassembly-v1"; const expectedModulePlanRuntimeResetStrategy = "reset-context-before-assembly-v1"; const expectedModulePlanAdapterValidationStrategy = "rust-validate-before-apply-v1"; const expectedModulePlanAdapterValidationCount = "3"; const expectedModulePlanAdapterValidationCountValue = 3; const expectedModulePlanAdapterApplyCount = "3"; const expectedModulePlanAdapterApplyCountValue = 3; const expectedModulePlanWasmHeapMinBytes = "65536 bytes"; const expectedModulePlanContextTokens = "16 tokens"; const expectedModulePlanSamplerCap = "1024 candidates"; const expectedModulePlanAdapterStackBudget = "22144 bytes"; const expectedModulePlanPromptLimit = "4096 bytes"; const expectedModulePlanOutputLimit = "65536 bytes"; const expectedModulePlanKvCacheBudget = "1024 bytes"; const expectedModulePlanKvCachePages = "1"; const expectedModulePlanModelBudgets = { "multi-parent-sign-merge-q8": "8832 bytes", "multi-parent-sign-merge-q4": "6592 bytes", "multi-parent-sign-merge-f32": "20352 bytes", "multi-parent-soup-q8": "8832 bytes", "multi-parent-soup-q4": "6592 bytes", "multi-parent-soup-f32": "20352 bytes" }; const expectedModulePlanTotalBudgets = { "multi-parent-sign-merge-q8": "175670 bytes", "multi-parent-sign-merge-q4": "173430 bytes", "multi-parent-sign-merge-f32": "187204 bytes" }; const expectedModulePlanTotalLimits = { "multi-parent-sign-merge-q8": "43454464 bytes", "multi-parent-sign-merge-q4": "43454464 bytes", "multi-parent-sign-merge-f32": "43454464 bytes", "multi-parent-soup-q8": "43454464 bytes", "multi-parent-soup-q4": "43454464 bytes", "multi-parent-soup-f32": "43454464 bytes" }; const expectedModulePlanBytes = { "multi-parent-sign-merge-q8": "0: 8832 bytes, 1: 607 bytes, 2: 1896 bytes, 3: 5999 bytes, 4: 20224 bytes, 5: 832 bytes, 6: 1088 bytes", "multi-parent-sign-merge-q4": "0: 6592 bytes, 1: 607 bytes, 2: 1896 bytes, 3: 5999 bytes, 4: 20224 bytes, 5: 832 bytes, 6: 1088 bytes", "multi-parent-sign-merge-f32": "0: 20352 bytes, 1: 608 bytes, 2: 1909 bytes, 3: 5999 bytes, 4: 20224 bytes, 5: 832 bytes, 6: 1088 bytes" }; const expectedModulePlanChecksums = { "multi-parent-sign-merge-q8": "0: 0x0132bc82d5a0d7d6, 1: 0x855c8c30e39227c5, 2: 0x88f5f52063d8d332, 3: 0x0988468dc4daf944, 4: 0x8194a8a671285019, 5: 0x6fa5d29bee9b7cfb, 6: 0x1ed9d08142edfda9", "multi-parent-sign-merge-q4": "0: 0x1a6808e3098d1ce0, 1: 0xfa5ea1108910598f, 2: 0xec65527ba6a0a24d, 3: 0x6c3f07949496907d, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6, 6: 0xcaf46ccfc262fad2", "multi-parent-sign-merge-f32": "0: 0x8a0e6c4c01998199, 1: 0xc2b257b1f036bfcb, 2: 0xd6d39c383538e5c3, 3: 0xe958c9dabb3565f0, 4: 0xe9669ade4571fd42, 5: 0x34008cedc028ed5c, 6: 0x1c64143141c223b5" }; const expectedModulePlanRoles = "0: runtime-model, 1: model-provenance-manifest, 2: assembly-evidence, 3: adapter-family, 4: adapter-stack-family-delta, 5: adapter-stack-sparse-delta, 6: adapter-stack-low-rank-delta"; const expectedModulePlanSlots = "0: runtime-model, 1: model-manifest, 2: assembly-receipt, 3: adapter-family-receipt, 4: adapter-stack-0, 5: adapter-stack-1, 6: adapter-stack-2"; const expectedModulePlanPhases = "0: load-model-bytes, 1: verify-model-manifest, 2: verify-assembly-evidence, 3: verify-adapter-family, 4: apply-adapter-stack-0, 5: apply-adapter-stack-1, 6: apply-adapter-stack-2"; const expectedModulePlanDependencies = "0: runtime-wasm, 1: module.0, 2: module.1, 3: module.2, 4: module.3, 5: module.4, 6: module.5"; const expectedModulePlanTrace = "0: plan verified, 1: model accepted, 2: manifest verified, 3: assembly evidence verified, 4: adapter family verified, 5: adapter stack applied, 6: ready"; function modulePlanByteSummaryTotal(summary) { // Computes the receipt-declared module byte total from the rendered Module Plan row. const matches = String(summary || "").matchAll(/\b\d+: (\d+) bytes\b/g); let total = 0; let count = 0; for (const match of matches) { total += Number.parseInt(match[1], 10); count += 1; } return count > 0 ? `${total} bytes` : null; } function byteCountFromLabel(label) { // Parses rendered byte labels so path-flexible generated roots can still prove budget math. const match = String(label || "").match(/^(\d+) bytes$/); return match ? Number.parseInt(match[1], 10) : null; } function modulePlanExpectedTotalBudget(result) { // Recomputes the browser-local total budget from rendered module bytes and fixed envelopes. const moduleBytes = byteCountFromLabel(modulePlanByteSummaryTotal(result.modulePlanBytes)); const scratchBytes = byteCountFromLabel(result.modulePlanScratchBudget); const promptBytes = byteCountFromLabel(result.modulePlanPromptLimit); const outputBytes = byteCountFromLabel(result.modulePlanOutputLimit); const kvBytes = byteCountFromLabel(result.modulePlanKvCacheBudget); if ([moduleBytes, scratchBytes, promptBytes, outputBytes, kvBytes].some((value) => value === null)) { return null; } return `${moduleBytes + scratchBytes + promptBytes + outputBytes + kvBytes} bytes`; } const expectedAssemblyEvidenceRoutes = { "multi-parent-sign-merge-q8": multiParentEvidenceRoutes("multi-parent-sign-merge-q8"), "multi-parent-sign-merge-q4": multiParentEvidenceRoutes("multi-parent-sign-merge-q4"), "multi-parent-sign-merge-f32": multiParentEvidenceRoutes("multi-parent-sign-merge-f32"), "multi-parent-soup-q8": multiParentEvidenceRoutes("multi-parent-soup-q8"), "multi-parent-soup-q4": multiParentEvidenceRoutes("multi-parent-soup-q4"), "multi-parent-soup-f32": multiParentEvidenceRoutes("multi-parent-soup-f32") }; const expectedAdapterManifestRoutes = { "multi-parent-sign-merge-q8": [ "/models/multi-parent-sign-merge-q8-self.adp1.manifest", "/models/multi-parent-sign-merge-q8-family.adp1.manifest", "/models/multi-parent-sign-merge-q8-sparse.asp1.manifest", "/models/multi-parent-sign-merge-q8-low-rank.alr1.manifest" ], "multi-parent-sign-merge-q4": [ "/models/multi-parent-sign-merge-q4-self.adp1.manifest", "/models/multi-parent-sign-merge-q4-family.adp1.manifest", "/models/multi-parent-sign-merge-q4-sparse.asp1.manifest", "/models/multi-parent-sign-merge-q4-low-rank.alr1.manifest" ], "multi-parent-sign-merge-f32": [ "/models/multi-parent-sign-merge-f32-self.adp1.manifest", "/models/multi-parent-sign-merge-f32-family.adp1.manifest", "/models/multi-parent-sign-merge-f32-sparse.asp1.manifest", "/models/multi-parent-sign-merge-f32-low-rank.alr1.manifest" ], "multi-parent-soup-q8": [ "/models/multi-parent-soup-q8-self.adp1.manifest", "/models/multi-parent-soup-q8-family.adp1.manifest", "/models/multi-parent-soup-q8-sparse.asp1.manifest", "/models/multi-parent-soup-q8-low-rank.alr1.manifest" ], "multi-parent-soup-q4": [ "/models/multi-parent-soup-q4-self.adp1.manifest", "/models/multi-parent-soup-q4-family.adp1.manifest", "/models/multi-parent-soup-q4-sparse.asp1.manifest", "/models/multi-parent-soup-q4-low-rank.alr1.manifest" ], "multi-parent-soup-f32": [ "/models/multi-parent-soup-f32-self.adp1.manifest", "/models/multi-parent-soup-f32-family.adp1.manifest", "/models/multi-parent-soup-f32-sparse.asp1.manifest", "/models/multi-parent-soup-f32-low-rank.alr1.manifest" ] }; const expectedAdapterApplyIndexes = { tinyf32: 0, "multi-parent-sign-merge-q8": 2, "multi-parent-sign-merge-q4": 2, "multi-parent-sign-merge-f32": 2, "multi-parent-soup-q8": 2, "multi-parent-soup-q4": 2, "multi-parent-soup-f32": 2 }; function multiParentEvidenceRoutes(modelKey) { // Chooses the generated evidence filename family from the model id stem. const evidencePrefix = modelKey.startsWith("multi-parent-soup-") ? "soup" : "sign-merge"; return [ `/evidence/${modelKey}/population.ledger`, `/evidence/${modelKey}/population.review`, `/evidence/${modelKey}/parent-pool.recipe`, `/evidence/${modelKey}/${evidencePrefix}.operator`, `/evidence/${modelKey}/${evidencePrefix}.candidate`, `/evidence/${modelKey}/${evidencePrefix}.promotion`, `/evidence/${modelKey}/${evidencePrefix}.runtime`, `/evidence/${modelKey}/${evidencePrefix}.eval`, `/evidence/${modelKey}/${evidencePrefix}.multi.admission` ]; } function expectedLabelForModel(modelKey) { if (modelKey === "multi-parent-sign-merge-q8" && smokeMode === "multi-parent-registry") { return "Multi-parent sign-merge q8_0"; } return expectedModelLabels[modelKey] || modelKey; } function expectedRouteForModel(modelKey) { if (modelKey === "multi-parent-sign-merge-q8" && smokeMode === "multi-parent-registry") { return "/models/tinylm16-q8.slm"; } return expectedModelRoutes[modelKey]; } function networkIncludesPath(networkRequests, expectedPath) { return networkRequests.some((requestUrl) => { try { return new URL(requestUrl).pathname === expectedPath; } catch (_error) { return requestUrl === expectedPath; } }); } function requestUrlPathEquals(requestUrl, expectedPath) { try { return new URL(requestUrl).pathname === expectedPath; } catch (_error) { return requestUrl === expectedPath; } } // Normalizes browser request URLs so route-budget checks can reason about paths only. function requestUrlPath(requestUrl) { try { return new URL(requestUrl).pathname; } catch (_error) { return requestUrl; } } function networkPathIndex(networkRequests, expectedPath) { return networkRequests.findIndex((requestUrl) => { try { return new URL(requestUrl).pathname === expectedPath; } catch (_error) { return requestUrl === expectedPath; } }); } function networkPathCount(networkRequests, expectedPath) { return networkRequests.filter((requestUrl) => requestUrlPathEquals(requestUrl, expectedPath)).length; } const chromeCandidates = [ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe", "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" ]; function findBrowser() { for (const candidate of chromeCandidates) { if (fs.existsSync(candidate)) { return candidate; } } throw new Error("Chrome or Edge executable was not found"); } function get(url) { return new Promise((resolve, reject) => { http.get(url, (response) => { let data = ""; response.setEncoding("utf8"); response.on("data", (chunk) => { data += chunk; }); response.on("end", () => resolve(data)); }).on("error", reject); }); } function getBuffer(url) { return new Promise((resolve, reject) => { const parsed = new URL(url); const client = parsed.protocol === "https:" ? https : http; const request = client.get(parsed, (response) => { const chunks = []; response.on("data", (chunk) => { chunks.push(Buffer.from(chunk)); }); response.on("end", () => { if (response.statusCode !== 200) { reject(new Error(`HTTP ${response.statusCode} while fetching ${url}`)); return; } resolve(Buffer.concat(chunks)); }); }); request.on("error", reject); }); } async function getText(url) { return (await getBuffer(url)).toString("utf8"); } function rotateLeft64(value, bits) { return ((value << bits) | (value >> (64n - bits))) & checksumMask64; } function textChecksumHex(text) { const bytes = Buffer.from(text, "utf8"); let acc = 0x4d595df4d0f33173n; for (let index = 0; index < bytes.length; index += 1) { acc ^= BigInt(bytes[index]) + (BigInt(index) << 2n); acc = (rotateLeft64(acc, 9n) * checksumPrime64) & checksumMask64; } return `0x${acc.toString(16).padStart(16, "0")}`; } function hex64(value) { return `0x${value.toString(16).padStart(16, "0")}`; } function isHex64(value) { return /^0x[0-9a-fA-F]{16}$/.test(String(value || "")); } function isFitnessVectorSummary(value) { // Matches the compact browser text rendered from selector fitness vector metadata. const parts = String(value || "").split(" / "); return parts.length === 2 && parts[0] === "eval-bound" && isHex64(parts[1]); } function isSpeciesFitSummary(value) { // Matches the compact browser text rendered from selector species-fit metadata. const parts = String(value || "").split(" / "); return parts.length === 3 && parts[0] === "browser-fit-bound" && isHex64(parts[1]) && isHex64(parts[2]); } function isNoveltySummary(value) { // Matches the compact browser text rendered from selector novelty sketch metadata. const parts = String(value || "").split(" / "); return parts.length === 3 && parts[0] === "behavior-sketch-bound" && isHex64(parts[1]) && isHex64(parts[2]); } function isPopulationSummary(value) { // Matches the compact browser text rendered from selector population review metadata. const parts = String(value || "").split(" / "); return parts.length === 3 && parts[0] === "population-review-bound" && isHex64(parts[1]) && isHex64(parts[2]); } function isMateSelectionSummary(value) { // Matches the compact browser text rendered from selector mate-selection metadata. const parts = String(value || "").split(" / "); return ( parts.length === 4 && (parts[0] === "parent-pool-bound" || parts[0] === "admission-only") && /^[1-9][0-9]* parents$/.test(parts[1]) && isHex64(parts[2]) && isHex64(parts[3]) ); } function isPhenotypeEvidenceSummary(value) { // Matches the compact browser text rendered from selector phenotype evidence metadata. const parts = String(value || "").split(" / "); return parts.length === 3 && parts[0] === "runtime-eval-bound" && isHex64(parts[1]) && isHex64(parts[2]); } function isHeritableArtifactSummary(value) { // Matches the compact browser text rendered from selector heritable artifact metadata. const parts = String(value || "").split(" / "); return parts.length === 3 && parts[0] === "served-artifact-bound" && isHex64(parts[1]) && isHex64(parts[2]); } function isOperatorReceiptSummary(value, operatorKind) { // Matches the compact browser text rendered from selector operator receipt metadata. const parts = String(value || "").split(" / "); return parts.length === 3 && parts[0] === "receipt-bound" && parts[1] === operatorKind && isHex64(parts[2]); } function isEvolutionScheduleSummary(value, expectedSchedule) { // Matches the compact browser text rendered from parent-pool evolution schedule metadata. const parts = String(value || "").split(" / "); return Boolean(expectedSchedule) && parts.length === 4 && parts[0] === "planned" && parts[1] === `family ${expectedSchedule.familyIndex}` && parts[2] === expectedSchedule.familyCommand && isHex64(parts[3]); } function isNonZeroHex64(value) { return isHex64(value) && String(value) !== "0x0000000000000000"; } function adapterArtifactChecksumValue(bytes) { if (!bytes || bytes.length < 64) { throw new Error("adapter artifact bytes were too short"); } let acc = 0x6164617074657231n; for (let index = 0; index < bytes.length; index += 1) { const value = index >= 56 && index < 64 ? 0 : bytes[index]; acc ^= BigInt(value) + (BigInt(index) << 3n); acc = (rotateLeft64(acc, 11n) * checksumPrime64) & checksumMask64; } return acc; } function adapterArtifactChecksumHex(bytes) { return hex64(adapterArtifactChecksumValue(bytes)); } function writeU64Le(bytes, offset, value) { let remaining = BigInt(value); for (let index = 0; index < 8; index += 1) { bytes[offset + index] = Number(remaining & 0xffn); remaining >>= 8n; } } function adapterIdentityDriftBytes(bytes) { const body = Buffer.from(bytes); if (body.length < 64) { throw new Error("adapter artifact bytes were too short"); } body[16] ^= 0x01; writeU64Le(body, 56, adapterArtifactChecksumValue(body)); return body; } function replaceLineValue(text, key, value) { const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const pattern = new RegExp(`^${escapedKey}=.*$`, "m"); if (!pattern.test(text)) { throw new Error(`${key} field was not found`); } return text.replace(pattern, `${key}=${value}`); } function driftModulePlanResourceEnvelope(receiptText) { const original = "module_plan_adapter_byte_budget=1048576"; const drifted = "module_plan_adapter_byte_budget=1048575"; if (!receiptText.includes(original)) { throw new Error("module plan adapter byte budget field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanRuntimeScratchBudget(receiptText) { const original = "module_plan_runtime_scratch_byte_budget=65536"; const drifted = "module_plan_runtime_scratch_byte_budget=65535"; if (!receiptText.includes(original)) { throw new Error("module plan runtime scratch byte budget field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanOutputByteLimit(receiptText) { // Mutates the declared output cap so the browser validates it before fetching generated bytes. const original = "module_plan_output_byte_limit=65536"; const drifted = "module_plan_output_byte_limit=65535"; if (!receiptText.includes(original)) { throw new Error("module plan output byte limit field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanPromptByteLimit(receiptText) { // Mutates the declared prompt cap so input-transfer validation is receipt-bound. const original = "module_plan_prompt_byte_limit=4096"; const drifted = "module_plan_prompt_byte_limit=4095"; if (!receiptText.includes(original)) { throw new Error("module plan prompt byte limit field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanFetchCountLimit(receiptText) { // Mutates the route cap so request-count envelopes are checked before model fetches. const original = "module_plan_fetch_count_limit=32"; const drifted = "module_plan_fetch_count_limit=31"; if (!receiptText.includes(original)) { throw new Error("module plan fetch count limit field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanPlannedFetchCount(receiptText) { // Mutates the exact generated route count so route-count planning is receipt-bound. const original = `module_plan_planned_fetch_count=${expectedModulePlanActualFetches}`; const drifted = "module_plan_planned_fetch_count=20"; if (!receiptText.includes(original)) { throw new Error("module plan planned fetch count field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanRouteSetVersion(receiptText) { // Mutates the route-set recipe version so route-list validation is version-bound. const original = `module_plan_route_set_version=${expectedModulePlanRouteSetVersion}`; const drifted = "module_plan_route_set_version=2"; if (!receiptText.includes(original)) { throw new Error("module plan route set version field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanRouteSetChecksumAlgorithm(receiptText) { // Mutates the route-set hash label so checksum validation is algorithm-bound. const original = `module_plan_route_set_checksum_algorithm=${expectedModulePlanRouteSetChecksumAlgorithm}`; const drifted = "module_plan_route_set_checksum_algorithm=legacy-text-checksum-v0"; if (!receiptText.includes(original)) { throw new Error("module plan route set checksum algorithm field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanRouteSetChecksum(receiptText) { // Mutates the route-set checksum so route-list validation is receipt-bound. const match = receiptText.match(/^module_plan_route_set_checksum=(0x[0-9a-fA-F]{16})$/m); if (!match) { throw new Error("module plan route set checksum field was not found"); } const drifted = match[1].toLowerCase() === "0x000000000000001d" ? "module_plan_route_set_checksum=0x000000000000001e" : "module_plan_route_set_checksum=0x000000000000001d"; return receiptText.replace(match[0], drifted); } function driftModulePlanOperatorReceiptChecksum(receiptText) { // Mutates the operator receipt checksum while preserving the receipt route. const match = receiptText.match(/^operator_receipt_checksum=(0x[0-9a-fA-F]{16})$/m); if (!match) { throw new Error("module plan operator receipt checksum field was not found"); } const drifted = match[1].toLowerCase() === "0x000000000000001d" ? "operator_receipt_checksum=0x000000000000001e" : "operator_receipt_checksum=0x000000000000001d"; return receiptText.replace(match[0], drifted); } function driftModulePlanKvCachePageCount(receiptText) { // Mutates only the KV page count so the smoke isolates cache-envelope validation. const original = `module_plan_kv_cache_page_count=${expectedModulePlanKvCachePages}`; const drifted = "module_plan_kv_cache_page_count=2"; if (!receiptText.includes(original)) { throw new Error("module plan KV cache page count field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanAdapterStackBudget(receiptText) { const original = "module_plan_adapter_stack_byte_budget=22144"; const drifted = "module_plan_adapter_stack_byte_budget=22143"; if (!receiptText.includes(original)) { throw new Error("module plan adapter stack byte budget field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanTotalBudget(receiptText) { const totalMatch = receiptText.match(/^module_plan_total_byte_budget=(\d+)$/m); if (!totalMatch) { throw new Error("module plan total byte budget field was not found"); } const total = Number.parseInt(totalMatch[1], 10); if (!Number.isSafeInteger(total) || total < 2) { throw new Error("module plan total byte budget field was invalid"); } return receiptText.replace(totalMatch[0], `module_plan_total_byte_budget=${total - 1}`); } function driftModulePlanTotalLimit(receiptText) { const limitMatch = receiptText.match(/^module_plan_total_byte_budget_limit=(\d+)$/m); if (!limitMatch) { throw new Error("module plan total byte budget limit field was not found"); } const limit = Number.parseInt(limitMatch[1], 10); if (!Number.isSafeInteger(limit) || limit < 2) { throw new Error("module plan total byte budget limit field was invalid"); } return receiptText.replace(limitMatch[0], `module_plan_total_byte_budget_limit=${limit - 1}`); } // Mutates only receipt cardinality so selector-declared module counts must remain authoritative. function driftModulePlanCount(receiptText) { const countMatch = receiptText.match(/^module_count=(\d+)$/m); if (!countMatch) { throw new Error("module plan module count field was not found"); } const count = Number.parseInt(countMatch[1], 10); if (!Number.isSafeInteger(count) || count < 2) { throw new Error("module plan module count field was invalid"); } return receiptText.replace(countMatch[0], `module_count=${count - 1}`); } function driftModulePlanWasmMemory(receiptText) { const original = `module_plan_wasm_memory_initial_pages=${expectedModulePlanWasmMemoryInitialPages}`; const drifted = "module_plan_wasm_memory_initial_pages=18"; if (!receiptText.includes(original)) { throw new Error("module plan WASM memory initial pages field was not found"); } return receiptText.replace(original, drifted); } // Mutates only the named ABI set so the smoke isolates Rust/WASM export validation. function driftModulePlanWasmExportSet(receiptText) { const original = `module_plan_wasm_export_set=${expectedModulePlanWasmExportSet}`; const drifted = "module_plan_wasm_export_set=tinyrustlm-extra-v1"; if (!receiptText.includes(original)) { throw new Error("module plan WASM export set field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanWasmTransferStrategy(receiptText) { const original = `module_plan_wasm_transfer_strategy=${expectedModulePlanWasmTransferStrategy}`; const drifted = "module_plan_wasm_transfer_strategy=copy-keep-v1"; if (!receiptText.includes(original)) { throw new Error("module plan WASM transfer strategy field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanModelReleaseStrategy(receiptText) { const original = `module_plan_model_release_strategy=${expectedModulePlanModelReleaseStrategy}`; const drifted = "module_plan_model_release_strategy=keep-resident-v1"; if (!receiptText.includes(original)) { throw new Error("module plan model release strategy field was not found"); } return receiptText.replace(original, drifted); } // Mutates only the reset strategy so drift stays isolated to runtime-context reset binding. function driftModulePlanRuntimeResetStrategy(receiptText) { const original = `module_plan_runtime_reset_strategy=${expectedModulePlanRuntimeResetStrategy}`; const drifted = "module_plan_runtime_reset_strategy=skip-reset-v1"; if (!receiptText.includes(original)) { throw new Error("module plan runtime reset strategy field was not found"); } return receiptText.replace(original, drifted); } // Mutates only the adapter validation strategy so the smoke isolates Rust pre-apply validation binding. function driftModulePlanAdapterValidationStrategy(receiptText) { const original = `module_plan_adapter_validation_strategy=${expectedModulePlanAdapterValidationStrategy}`; const drifted = "module_plan_adapter_validation_strategy=apply-without-rust-validate-v1"; if (!receiptText.includes(original)) { throw new Error("module plan adapter validation strategy field was not found"); } return receiptText.replace(original, drifted); } // Mutates only the adapter validation count so the smoke isolates Rust validation cardinality. function driftModulePlanAdapterValidationCount(receiptText) { const original = `module_plan_adapter_validation_count=${expectedModulePlanAdapterValidationCount}`; const drifted = "module_plan_adapter_validation_count=2"; if (!receiptText.includes(original)) { throw new Error("module plan adapter validation count field was not found"); } return receiptText.replace(original, drifted); } // Mutates only the adapter apply count so the smoke isolates planned stack cardinality. function driftModulePlanAdapterApplyCount(receiptText) { const original = `module_plan_adapter_apply_count=${expectedModulePlanAdapterApplyCount}`; const drifted = "module_plan_adapter_apply_count=2"; if (!receiptText.includes(original)) { throw new Error("module plan adapter apply count field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanWasmHeapMinBytes(receiptText) { const original = "module_plan_wasm_heap_min_bytes=65536"; const drifted = "module_plan_wasm_heap_min_bytes=65535"; if (!receiptText.includes(original)) { throw new Error("module plan WASM heap min bytes field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanContextTokenLimit(receiptText) { const original = "module_plan_context_token_limit=16"; const drifted = "module_plan_context_token_limit=15"; if (!receiptText.includes(original)) { throw new Error("module plan context token limit field was not found"); } return receiptText.replace(original, drifted); } // Mutates only the sampler cap so the smoke isolates fixed-buffer sampler metadata. function driftModulePlanSamplerCandidateCap(receiptText) { const original = "module_plan_sampler_candidate_cap=1024"; const drifted = "module_plan_sampler_candidate_cap=1025"; if (!receiptText.includes(original)) { throw new Error("module plan sampler candidate cap field was not found"); } return receiptText.replace(original, drifted); } // Mutates only tokenizer identity so the smoke isolates module-plan tokenizer binding. function driftModulePlanTokenizerChecksum(receiptText) { const checksumPattern = /^module_plan_tokenizer_checksum=0x[0-9a-fA-F]{16}$/m; if (!checksumPattern.test(receiptText)) { throw new Error("module plan tokenizer checksum field was not found"); } return receiptText.replace(checksumPattern, "module_plan_tokenizer_checksum=0x00000000000000f1"); } function driftModulePlanProfile(receiptText) { const original = "module_plan_profile=browser-constrained-v1"; const drifted = "module_plan_profile=desktop-expanded-v1"; if (!receiptText.includes(original)) { throw new Error("module plan profile field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanExecutionProfile(receiptText) { const original = `module_plan_execution_profile=${expectedModulePlanExecutionProfile}`; const drifted = "module_plan_execution_profile=worker-pooled-wasm-v1"; if (!receiptText.includes(original)) { throw new Error("module plan execution profile field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanFetchPolicy(receiptText) { const original = `module_plan_fetch_policy=${expectedModulePlanFetchPolicy}`; const drifted = "module_plan_fetch_policy=cache-default-v1"; if (!receiptText.includes(original)) { throw new Error("module plan fetch policy field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanOriginPolicy(receiptText) { const original = `module_plan_origin_policy=${expectedModulePlanOriginPolicy}`; const drifted = "module_plan_origin_policy=cross-origin-network-v1"; if (!receiptText.includes(original)) { throw new Error("module plan origin policy field was not found"); } return receiptText.replace(original, drifted); } function driftModulePlanGraph(receiptText) { const pathMatch = receiptText.match(/^module\.0\.path=([^\r\n]+)$/m); if (!pathMatch) { throw new Error("module plan model graph path field was not found"); } const originalPath = pathMatch[1]; const driftedPath = originalPath.endsWith(".slm") ? originalPath.slice(0, -4) + "-graph-drift.slm" : originalPath + "-graph-drift"; return receiptText.replace(pathMatch[0], `module.0.path=${driftedPath}`); } function driftModulePlanStackMember(receiptText) { const pathMatch = receiptText.match(/^module\.4\.adapter_path=([^\r\n]+)$/m); if (!pathMatch) { throw new Error("module plan stack member path field was not found"); } const originalPath = pathMatch[1]; const driftedPath = originalPath.endsWith(".adp1") ? originalPath.slice(0, -5) + "-stack-drift.adp1" : originalPath + "-stack-drift"; return receiptText.replace(pathMatch[0], `module.4.adapter_path=${driftedPath}`); } function driftModulePlanRole(receiptText) { const roleMatch = receiptText.match(/^module\.4\.role=([^\r\n]+)$/m); if (!roleMatch) { throw new Error("module plan stack member role field was not found"); } return receiptText.replace(roleMatch[0], "module.4.role=adapter-stack-role-drift"); } function driftModulePlanSlot(receiptText) { const slotMatch = receiptText.match(/^module\.4\.assembly_slot=([^\r\n]+)$/m); if (!slotMatch) { throw new Error("module plan stack member assembly slot field was not found"); } return receiptText.replace(slotMatch[0], "module.4.assembly_slot=adapter-stack-slot-drift"); } function driftModulePlanPhase(receiptText) { const phaseMatch = receiptText.match(/^module\.4\.phase=([^\r\n]+)$/m); if (!phaseMatch) { throw new Error("module plan stack member phase field was not found"); } return receiptText.replace(phaseMatch[0], "module.4.phase=adapter-stack-phase-drift"); } function driftModulePlanByteCount(receiptText) { const byteMatch = receiptText.match(/^module\.0\.byte_count=([0-9]+)$/m); if (!byteMatch) { throw new Error("module plan model byte count field was not found"); } const byteCount = Number.parseInt(byteMatch[1], 10); const drifted = Number.isSafeInteger(byteCount) && byteCount > 1 ? byteCount - 1 : byteCount + 1; return receiptText.replace(byteMatch[0], `module.0.byte_count=${drifted}`); } function driftModulePlanChecksum(receiptText) { const checksumMatch = receiptText.match(/^module\.4\.checksum=(0x[0-9a-fA-F]{16})$/m); if (!checksumMatch) { throw new Error("module plan stack member checksum field was not found"); } const checksum = BigInt(checksumMatch[1]); const drifted = `0x${(checksum ^ 1n).toString(16).padStart(16, "0")}`; return receiptText.replace(checksumMatch[0], `module.4.checksum=${drifted}`); } function driftModulePlanDependency(receiptText) { const dependencyMatch = receiptText.match(/^module\.4\.depends_on=([^\r\n]+)$/m); if (!dependencyMatch) { throw new Error("module plan stack member dependency field was not found"); } return receiptText.replace(dependencyMatch[0], "module.4.depends_on=module.2"); } function driftAssemblyEvalCaseEvidenceChecksum(receiptText) { const checksumMatch = receiptText.match(/^eval_case_evidence_checksum=(0x[0-9a-fA-F]{16})$/m); if (!checksumMatch) { throw new Error("assembly eval case evidence checksum field was not found"); } const checksum = BigInt(checksumMatch[1]); const drifted = `0x${(checksum ^ 1n).toString(16).padStart(16, "0")}`; return receiptText.replace(checksumMatch[0], `eval_case_evidence_checksum=${drifted}`); } function driftAssemblyEvidenceFileText(evidenceText) { return `${evidenceText.replace(/\s*$/, "")}\nproof_drift=assembly-evidence-file-drift\n`; } function driftAdapterFamilyReceiptText(receiptText) { const candidateMatch = receiptText.match(/^candidate_id=([^\r\n]+)$/m); if (!candidateMatch) { throw new Error("adapter-family receipt candidate id field was not found"); } const candidateId = candidateMatch[1]; const finalChar = candidateId[candidateId.length - 1] || "0"; const driftedFinalChar = finalChar === "x" ? "y" : "x"; return receiptText.replace(candidateMatch[0], `candidate_id=${candidateId.slice(0, -1)}${driftedFinalChar}`); } function driftAdapterManifestText(manifestText) { const original = "adapter_status=artifact-written"; const drifted = "adapter_status=artifact-drifted"; if (!manifestText.includes(original)) { throw new Error("adapter manifest status field was not found"); } if (Buffer.byteLength(original, "utf8") !== Buffer.byteLength(drifted, "utf8")) { throw new Error("adapter manifest drift replacement changed byte length"); } return manifestText.replace(original, drifted); } // Mutates only the source-backed ALR1 base contract while preserving manifest byte length. function driftSourceBackedAlr1ManifestText(manifestText) { const original = "adapter_source_base_contract=matches-reviewed-adapter-source-base-contract"; const drifted = "adapter_source_base_contract=mismats-reviewed-adapter-source-base-contract"; if (!manifestText.includes(original)) { throw new Error("source-backed ALR1 source base contract field was not found"); } if (Buffer.byteLength(original, "utf8") !== Buffer.byteLength(drifted, "utf8")) { throw new Error("source-backed ALR1 drift replacement changed byte length"); } return manifestText.replace(original, drifted); } function updateRegistryModulePlanChecksum(registryText, candidateId, checksum) { const candidateMatch = registryText.match(new RegExp(`^entry\\.(\\d+)\\.candidate_id=${candidateId}$`, "m")); if (!candidateMatch) { throw new Error(`selector registry entry was not found for ${candidateId}`); } const prefix = `entry.${candidateMatch[1]}`; const checksumPattern = new RegExp(`^${prefix}\\.module_plan_checksum=0x[0-9a-fA-F]{16}$`, "m"); if (!checksumPattern.test(registryText)) { throw new Error(`module plan checksum field was not found for ${candidateId}`); } return registryText.replace(checksumPattern, `${prefix}.module_plan_checksum=${checksum}`); } function updateRegistryAssemblyReceiptChecksum(registryText, candidateId, checksum) { const candidateMatch = registryText.match(new RegExp(`^entry\\.(\\d+)\\.candidate_id=${candidateId}$`, "m")); if (!candidateMatch) { throw new Error(`selector registry entry was not found for ${candidateId}`); } const prefix = `entry.${candidateMatch[1]}`; const checksumPattern = new RegExp(`^${prefix}\\.assembly_receipt_checksum=0x[0-9a-fA-F]{16}$`, "m"); if (!checksumPattern.test(registryText)) { throw new Error(`assembly receipt checksum field was not found for ${candidateId}`); } return registryText.replace(checksumPattern, `${prefix}.assembly_receipt_checksum=${checksum}`); } function updateRegistryAdapterFamilyReceiptChecksum(registryText, candidateId, checksum) { const candidateMatch = registryText.match(new RegExp(`^entry\\.(\\d+)\\.candidate_id=${candidateId}$`, "m")); if (!candidateMatch) { throw new Error(`selector registry entry was not found for ${candidateId}`); } const prefix = `entry.${candidateMatch[1]}`; return replaceLineValue(registryText, `${prefix}.adapter_family_receipt_checksum`, checksum); } function updateRegistryAdapterChecksums(registryText, candidateId, adapterIndex, artifactChecksum, manifestChecksum) { const candidateMatch = registryText.match(new RegExp(`^entry\\.(\\d+)\\.candidate_id=${candidateId}$`, "m")); if (!candidateMatch) { throw new Error(`selector registry entry was not found for ${candidateId}`); } const prefix = `entry.${candidateMatch[1]}.adapter.${adapterIndex}`; let updated = replaceLineValue(registryText, `${prefix}.artifact_checksum`, artifactChecksum); updated = replaceLineValue(updated, `${prefix}.manifest_checksum`, manifestChecksum); return updated; } // Updates only an adapter manifest checksum in the selector registry. function updateRegistryAdapterManifestChecksum(registryText, candidateId, adapterIndex, manifestChecksum) { const candidateMatch = registryText.match(new RegExp(`^entry\\.(\\d+)\\.candidate_id=${candidateId}$`, "m")); if (!candidateMatch) { throw new Error(`selector registry entry was not found for ${candidateId}`); } const prefix = `entry.${candidateMatch[1]}.adapter.${adapterIndex}`; return replaceLineValue(registryText, `${prefix}.manifest_checksum`, manifestChecksum); } // Mutates generated selector operator receipt byte echoes before browser registry intake. function driftGeneratedSelectorOperatorReceiptBytes(registryText) { let changed = false; const updated = registryText.replace( /^entry\.(\d+)\.operator_receipt_candidate_artifact_bytes=(\d+)$/gm, (_line, entryIndex, byteText) => { const byteCount = Number(byteText); if (!Number.isSafeInteger(byteCount) || byteCount < 1) { throw new Error(`operator receipt byte count was invalid for entry ${entryIndex}`); } changed = true; return `entry.${entryIndex}.operator_receipt_candidate_artifact_bytes=${byteCount + 1}`; } ); if (!changed) { throw new Error("selector registry operator receipt byte fields were not found"); } return updated; } // Mutates generated selector operator kinds while preserving receipt byte echoes. function driftGeneratedSelectorOperatorReceiptKind(registryText) { let changed = false; const updated = registryText.replace( /^entry\.(\d+)\.operator_receipt_operator_kind=(seed-weighted-parent-pool-soup|sign-aware-parent-pool-merge)$/gm, (_line, entryIndex, operatorKind) => { changed = true; const replacement = operatorKind === "seed-weighted-parent-pool-soup" ? "sign-aware-parent-pool-merge" : "seed-weighted-parent-pool-soup"; return `entry.${entryIndex}.operator_receipt_operator_kind=${replacement}`; } ); if (!changed) { throw new Error("selector registry operator receipt kind fields were not found"); } return updated; } function updateModulePlanAssemblyReceiptChecksum(receiptText, checksum) { let updated = receiptText; for (const key of ["assembly_receipt_checksum", "module.2.checksum"]) { const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const checksumPattern = new RegExp(`^${escapedKey}=0x[0-9a-fA-F]{16}$`, "m"); if (!checksumPattern.test(updated)) { throw new Error(`module plan ${key} field was not found`); } updated = updated.replace(checksumPattern, `${key}=${checksum}`); } return updated; } function updateModulePlanAdapterFamilyReceiptChecksum(receiptText, checksum) { let updated = receiptText; for (const key of ["adapter_family_receipt_checksum", "module.3.checksum"]) { updated = replaceLineValue(updated, key, checksum); } return updated; } function updateModulePlanAdapterStackChecksums(receiptText, moduleIndex, artifactChecksum, manifestChecksum) { let updated = replaceLineValue(receiptText, `module.${moduleIndex}.checksum`, artifactChecksum); updated = replaceLineValue(updated, `module.${moduleIndex}.artifact_checksum`, artifactChecksum); updated = replaceLineValue(updated, `module.${moduleIndex}.manifest_checksum`, manifestChecksum); return updated; } // Updates only an adapter module manifest checksum in the module plan. function updateModulePlanAdapterManifestChecksum(receiptText, moduleIndex, manifestChecksum) { return replaceLineValue(receiptText, `module.${moduleIndex}.manifest_checksum`, manifestChecksum); } function updateAssemblyAdapterFamilyReceiptChecksum(receiptText, checksum) { return replaceLineValue(receiptText, "adapter_family_receipt_checksum", checksum); } function updateAdapterFamilyMemberChecksums(receiptText, adapterIndex, artifactChecksum, manifestChecksum) { let updated = replaceLineValue(receiptText, `adapter.${adapterIndex}.artifact_checksum`, artifactChecksum); updated = replaceLineValue(updated, `adapter.${adapterIndex}.manifest_checksum`, manifestChecksum); return updated; } // Updates only an adapter-family member manifest checksum. function updateAdapterFamilyMemberManifestChecksum(receiptText, adapterIndex, manifestChecksum) { return replaceLineValue(receiptText, `adapter.${adapterIndex}.manifest_checksum`, manifestChecksum); } function updateAdapterManifestArtifactChecksum(manifestText, artifactChecksum) { return replaceLineValue(manifestText, "adapter_artifact_checksum", artifactChecksum); } function fulfillTextRequest(client, requestId, text) { const body = Buffer.from(text, "utf8"); return client.send("Fetch.fulfillRequest", { requestId, responseCode: 200, responseHeaders: [ { name: "content-type", value: "text/plain; charset=utf-8" }, { name: "content-length", value: String(body.length) } ], body: body.toString("base64") }); } function fulfillBinaryRequest(client, requestId, body) { return client.send("Fetch.fulfillRequest", { requestId, responseCode: 200, responseHeaders: [ { name: "content-type", value: "application/octet-stream" }, { name: "content-length", value: String(body.length) } ], body: body.toString("base64") }); } function isStaleFetchInterception(error) { const message = error && error.message ? error.message : String(error || ""); return message.includes('"code":-32602') && message.includes("Invalid InterceptionId"); } async function continuePausedRequest(client, requestId) { try { return await client.send("Fetch.continueRequest", { requestId }); } catch (error) { if (isStaleFetchInterception(error)) { return null; } throw error; } } function parseEvaluateValue(result) { if (result && result.exceptionDetails) { const details = result.exceptionDetails; const text = details.exception && details.exception.description ? details.exception.description : details.text || "browser evaluation failed"; throw new Error(text); } const remote = result && result.result ? result.result : {}; if (!Object.prototype.hasOwnProperty.call(remote, "value") && typeof remote.description === "string") { const description = remote.description.trim(); if (description.startsWith("{") || description.startsWith("[")) { return JSON.parse(description); } } const value = remote.value; return typeof value === "string" ? JSON.parse(value) : value; } function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function waitForTarget() { const endpoint = `http://127.0.0.1:${port}/json/list`; for (let attempt = 0; attempt < 120; attempt += 1) { try { const targets = JSON.parse(await get(endpoint)); const appTarget = targets.find((target) => target.url && target.url.includes("/app/")); if (appTarget) { return appTarget; } if (targets[0]) { return targets[0]; } } catch (_error) { await sleep(100); } } throw new Error("Timed out waiting for a browser debugging target"); } function connectWebSocket(url) { return new Promise((resolve, reject) => { const socket = new WebSocket(url); socket.addEventListener("open", () => resolve(socket), { once: true }); socket.addEventListener("error", reject, { once: true }); }); } function cdpClient(socket) { let nextId = 1; const pending = new Map(); const listeners = new Map(); socket.addEventListener("message", (event) => { const message = JSON.parse(event.data); if (message.method && listeners.has(message.method)) { for (const listener of listeners.get(message.method)) { listener(message.params || {}); } } if (!message.id || !pending.has(message.id)) { return; } const callbacks = pending.get(message.id); pending.delete(message.id); if (message.error) { callbacks.reject(new Error(JSON.stringify(message.error))); return; } callbacks.resolve(message.result); }); return { send(method, params) { const id = nextId; nextId += 1; socket.send(JSON.stringify({ id, method, params })); return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); }); }, on(method, listener) { if (!listeners.has(method)) { listeners.set(method, []); } listeners.get(method).push(listener); } }; } async function runPageSmoke(client, modelKey) { const expression = ` (async () => { const expectedModel = ${JSON.stringify(modelKey)}; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); for (let index = 0; index < 600; index += 1) { if (byId("generateButton") && !byId("generateButton").disabled) { break; } await sleep(100); } if (byId("modelSelect").value !== expectedModel) { byId("modelSelect").value = expectedModel; byId("modelSelect").dispatchEvent(new Event("change", { bubbles: true })); for (let index = 0; index < 600; index += 1) { if (byId("modelSelect").value === expectedModel && !byId("generateButton").disabled && byId("runtimeStatus").textContent === "Ready") { break; } await sleep(100); } } byId("maxTokens").value = "1"; byId("prompt").value = "hi"; byId("generateButton").click(); for (let index = 0; index < 600; index += 1) { if (byId("response").textContent.trim().length > 0) { break; } await sleep(100); } return JSON.stringify({ runtimeStatus: byId("runtimeStatus").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, response: byId("response").textContent, conversationText: byId("conversation").textContent, conversationItems: Array.from(document.querySelectorAll("#conversation .message")).map((node) => ({ role: node.querySelector(".message-role") ? node.querySelector(".message-role").textContent.trim() : "", text: node.querySelector(".message-text") ? node.querySelector(".message-text").textContent : "", isError: node.classList.contains("error") })), console: byId("console").textContent, diagnostics: byId("diagnostics").textContent, benchLoadMs: byId("benchLoadMs").textContent, benchPromptTokens: byId("benchPromptTokens").textContent, benchGeneratedTokens: byId("benchGeneratedTokens").textContent, benchTokensPerSecond: byId("benchTokensPerSecond").textContent, benchScratch: byId("benchScratch").textContent, selectedModel: byId("modelSelect").value, provenanceSourceKind: byId("provenanceSourceKind").textContent, provenanceAdmission: byId("provenanceAdmission").textContent, provenanceQualityClaim: byId("provenanceQualityClaim").textContent, provenanceTrainedClaim: byId("provenanceTrainedClaim").textContent, provenanceNextGate: byId("provenanceNextGate").textContent, provenanceOperator: byId("provenanceOperator").textContent, provenanceSchedule: byId("provenanceSchedule").textContent, modelOptions: Array.from(byId("modelSelect").options).map((option) => ({ value: option.value, label: option.textContent.trim() })), stepTokenDisabled: byId("stepTokenButton").disabled }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 90000 }); return parseEvaluateValue(result); } async function runPageStepTokenSmoke(client, modelKey) { const expression = ` (async () => { const expectedModel = ${JSON.stringify(modelKey)}; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch (_error) { return {}; } }; for (let index = 0; index < 600; index += 1) { if (byId("generateButton") && !byId("generateButton").disabled && byId("runtimeStatus").textContent === "Ready") { break; } await sleep(100); } if (byId("modelSelect").value !== expectedModel) { byId("modelSelect").value = expectedModel; byId("modelSelect").dispatchEvent(new Event("change", { bubbles: true })); for (let index = 0; index < 600; index += 1) { if (byId("modelSelect").value === expectedModel && !byId("generateButton").disabled && byId("runtimeStatus").textContent === "Ready") { break; } await sleep(100); } } const readyStepDisabled = byId("stepTokenButton").disabled; byId("maxTokens").value = "1"; byId("prompt").value = "hi"; byId("generateButton").click(); for (let index = 0; index < 600; index += 1) { if (byId("response").textContent === "e" || byId("errorState").textContent !== "none") { break; } await sleep(100); } const afterGenerateStepDisabled = byId("stepTokenButton").disabled; byId("stepTokenButton").click(); for (let index = 0; index < 600; index += 1) { if (byId("response").textContent === "ee" || byId("errorState").textContent !== "none") { break; } await sleep(100); } return JSON.stringify({ runtimeStatus: byId("runtimeStatus").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, response: byId("response").textContent, conversationItems: Array.from(document.querySelectorAll("#conversation .message")).map((node) => ({ role: node.querySelector(".message-role") ? node.querySelector(".message-role").textContent.trim() : "", text: node.querySelector(".message-text") ? node.querySelector(".message-text").textContent : "", isError: node.classList.contains("error") })), console: byId("console").textContent, diagnostics: parseDiagnostics(), diagnosticsText: byId("diagnostics").textContent, benchPromptTokens: byId("benchPromptTokens").textContent, benchGeneratedTokens: byId("benchGeneratedTokens").textContent, selectedModel: byId("modelSelect").value, readyStepDisabled, afterGenerateStepDisabled, stepTokenDisabled: byId("stepTokenButton").disabled, generateDisabled: byId("generateButton").disabled, resetDisabled: byId("resetButton").disabled, modelSelectDisabled: byId("modelSelect").disabled }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 120000 }); return parseEvaluateValue(result); } async function runPageAdapterSidecarSmoke(client, modelKey, expectAutoAssembly) { const expression = ` (async () => { const expectedModel = ${JSON.stringify(modelKey)}; const expectAutoAssembly = ${expectAutoAssembly ? "true" : "false"}; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch (_error) { return {}; } }; for (let index = 0; index < 600; index += 1) { const ready = byId("generateButton") && !byId("generateButton").disabled && byId("runtimeStatus").textContent === "Ready"; const assembled = byId("adapterState") && byId("adapterState").textContent === "applied"; if (ready && (!expectAutoAssembly || assembled)) { break; } await sleep(100); } const initialSelectedModel = byId("modelSelect").value; const modelOptions = Array.from(byId("modelSelect").options).map((option) => ({ value: option.value, label: option.textContent.trim() })); if (byId("modelSelect").value !== expectedModel) { byId("modelSelect").value = expectedModel; byId("modelSelect").dispatchEvent(new Event("change", { bubbles: true })); for (let index = 0; index < 600; index += 1) { const ready = byId("modelSelect").value === expectedModel && !byId("generateButton").disabled && byId("runtimeStatus").textContent === "Ready"; const assembled = byId("adapterState") && byId("adapterState").textContent === "applied"; if (ready && (!expectAutoAssembly || assembled)) { break; } await sleep(100); } } const adapterOptions = Array.from(byId("adapterSelect").options).map((option) => ({ value: option.value, label: option.textContent.trim() })); const selectedAdapterBeforeApply = byId("adapterSelect").value; const adapterSelectDisabledBefore = byId("adapterSelect").disabled; const applyDisabledBefore = byId("applyAdapterButton").disabled; const adapterStateBeforeGenerate = byId("adapterState").textContent; const diagnosticsBeforeGenerate = parseDiagnostics(); const consoleBeforeGenerate = byId("console").textContent; const autoAppliedBeforeGenerate = adapterStateBeforeGenerate === "applied"; byId("maxTokens").value = "1"; byId("prompt").value = "hi"; byId("generateButton").click(); for (let index = 0; index < 600; index += 1) { if (byId("response").textContent === "e" || byId("errorState").textContent !== "none") { break; } await sleep(100); } const afterGenerateDiagnostics = parseDiagnostics(); const stepDisabledAfterGenerate = byId("stepTokenButton").disabled; let beforeApplyDiagnostics = afterGenerateDiagnostics; let stepDisabledBeforeApply = stepDisabledAfterGenerate; let afterApplyDiagnostics = diagnosticsBeforeGenerate; if (!expectAutoAssembly) { byId("applyAdapterButton").click(); for (let index = 0; index < 600; index += 1) { if (byId("adapterState").textContent === "applied" || byId("errorState").textContent !== "none") { break; } await sleep(100); } afterApplyDiagnostics = parseDiagnostics(); } return JSON.stringify({ runtimeStatus: byId("runtimeStatus").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, response: byId("response").textContent, console: byId("console").textContent, initialSelectedModel, selectedModel: byId("modelSelect").value, modelOptions, adapterState: byId("adapterState").textContent, provenanceGenome: byId("provenanceGenome").textContent, provenanceSpecies: byId("provenanceSpecies").textContent, provenanceNovelty: byId("provenanceNovelty").textContent, provenancePopulation: byId("provenancePopulation").textContent, provenanceMateSelection: byId("provenanceMateSelection").textContent, provenanceOperator: byId("provenanceOperator").textContent, provenanceSchedule: byId("provenanceSchedule").textContent, provenancePhenotype: byId("provenancePhenotype").textContent, provenanceArtifact: byId("provenanceArtifact").textContent, provenanceFitness: byId("provenanceFitness").textContent, provenanceEvalCases: byId("provenanceEvalCases").textContent, provenanceEvalChecksum: byId("provenanceEvalChecksum").textContent, assemblyState: byId("assemblyState").textContent, assemblyKind: byId("assemblyKind").textContent, assemblyParents: byId("assemblyParents").textContent, assemblyOperator: byId("assemblyOperator").textContent, assemblyLedger: byId("assemblyLedger").textContent, assemblyNextGate: byId("assemblyNextGate").textContent, modulePlanState: byId("modulePlanState").textContent, modulePlanKind: byId("modulePlanKind").textContent, modulePlanResource: byId("modulePlanResource").textContent, modulePlanExecution: byId("modulePlanExecution").textContent, modulePlanFetch: byId("modulePlanFetch").textContent, modulePlanOrigin: byId("modulePlanOrigin").textContent, modulePlanFetchLimit: byId("modulePlanFetchLimit").textContent, modulePlanPlannedFetchCount: byId("modulePlanPlannedFetchCount").textContent, modulePlanActualFetchCount: byId("modulePlanActualFetchCount").textContent, modulePlanRouteSetChecksumAlgorithm: byId("modulePlanRouteSetChecksumAlgorithm").textContent, modulePlanRouteSetVersion: byId("modulePlanRouteSetVersion").textContent, modulePlanRouteSetChecksum: byId("modulePlanRouteSetChecksum").textContent, modulePlanActualRouteSetChecksum: byId("modulePlanActualRouteSetChecksum").textContent, modulePlanWasmPages: byId("modulePlanWasmPages").textContent, modulePlanWasmExportSet: byId("modulePlanWasmExportSet").textContent, modulePlanWasmTransferStrategy: byId("modulePlanWasmTransferStrategy").textContent, modulePlanModelReleaseStrategy: byId("modulePlanModelReleaseStrategy").textContent, modulePlanRuntimeResetStrategy: byId("modulePlanRuntimeResetStrategy").textContent, modulePlanAdapterValidationStrategy: byId("modulePlanAdapterValidationStrategy").textContent, modulePlanAdapterValidationCount: byId("modulePlanAdapterValidationCount").textContent, modulePlanAdapterApplyCount: byId("modulePlanAdapterApplyCount").textContent, modulePlanWasmHeapMinBytes: byId("modulePlanWasmHeapMinBytes").textContent, modulePlanContextTokens: byId("modulePlanContextTokens").textContent, modulePlanSamplerCap: byId("modulePlanSamplerCap").textContent, modulePlanTokenizer: byId("modulePlanTokenizer").textContent, modulePlanModules: byId("modulePlanModules").textContent, modulePlanModelBudget: byId("modulePlanModelBudget").textContent, modulePlanAdapterBudget: byId("modulePlanAdapterBudget").textContent, modulePlanAdapterStackBudget: byId("modulePlanAdapterStackBudget").textContent, modulePlanScratchBudget: byId("modulePlanScratchBudget").textContent, modulePlanPromptLimit: byId("modulePlanPromptLimit").textContent, modulePlanOutputLimit: byId("modulePlanOutputLimit").textContent, modulePlanKvCacheBudget: byId("modulePlanKvCacheBudget").textContent, modulePlanKvCachePages: byId("modulePlanKvCachePages").textContent, modulePlanTotalBudget: byId("modulePlanTotalBudget").textContent, modulePlanTotalLimit: byId("modulePlanTotalLimit").textContent, modulePlanBytes: byId("modulePlanBytes").textContent, modulePlanActualModuleBytes: byId("modulePlanActualModuleBytes").textContent, modulePlanChecksums: byId("modulePlanChecksums").textContent, modulePlanActualModuleChecksums: byId("modulePlanActualModuleChecksums").textContent, modulePlanSlots: byId("modulePlanSlots").textContent, modulePlanRoles: byId("modulePlanRoles").textContent, modulePlanPhases: byId("modulePlanPhases").textContent, modulePlanDepends: byId("modulePlanDepends").textContent, modulePlanTrace: byId("modulePlanTrace").textContent, modulePlanModel: byId("modulePlanModel").textContent, modulePlanStack: byId("modulePlanStack").textContent, adapterOptions, selectedAdapterBeforeApply, adapterSelectDisabledBefore, applyDisabledBefore, adapterStateBeforeGenerate, autoAppliedBeforeGenerate, diagnosticsBeforeGenerate, consoleBeforeGenerate, afterGenerateDiagnostics, stepDisabledAfterGenerate, stepDisabledBeforeApply, stepDisabledAfterApply: byId("stepTokenButton").disabled, generateDisabledAfterApply: byId("generateButton").disabled, applyDisabledAfterApply: byId("applyAdapterButton").disabled, beforeApplyDiagnostics, afterApplyDiagnostics, diagnosticsText: byId("diagnostics").textContent }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 120000 }); return parseEvaluateValue(result); } // Drives repeated q4/q8/f32 browser assemblies; cycles is bounded so route-soak modes stay finite. async function runPageCombinedSelectorAssemblySmoke(client, cycles) { const cycleCount = Math.max(1, Math.min(10, Number.parseInt(String(cycles || 1), 10) || 1)); const expression = ` (async () => { const expectedModels = ${JSON.stringify(combinedSelectorModels)}; const cycles = ${cycleCount}; const expectedSequence = []; for (let cycle = 0; cycle < cycles; cycle += 1) { for (const modelKey of expectedModels) { expectedSequence.push(modelKey); } } const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); const countOccurrences = (text, needle) => text.split(needle).length - 1; const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch (_error) { return {}; } }; const waitForReadyAssembly = async (modelKey) => { for (let index = 0; index < 900; index += 1) { const modelSelect = byId("modelSelect"); const generateButton = byId("generateButton"); const runtimeStatus = byId("runtimeStatus"); const adapterState = byId("adapterState"); const ready = modelSelect && modelSelect.value === modelKey && generateButton && !generateButton.disabled && runtimeStatus && runtimeStatus.textContent === "Ready"; const assembled = adapterState && adapterState.textContent === "applied"; if (ready && assembled) { return true; } await sleep(100); } return false; }; for (let index = 0; index < 900; index += 1) { if (byId("modelSelect") && byId("runtimeStatus") && byId("adapterState")) { break; } await sleep(100); } if (!byId("modelSelect")) { throw new Error("modelSelect missing before combined selector assembly smoke"); } for (let index = 0; index < 900; index += 1) { const options = Array.from(byId("modelSelect").options).map((option) => option.value); if ( expectedModels.every((modelKey) => options.includes(modelKey)) && byId("runtimeStatus").textContent === "Ready" && byId("adapterState").textContent === "applied" ) { break; } await sleep(100); } const initialSelectedModel = byId("modelSelect").value; const modelOptions = Array.from(byId("modelSelect").options).map((option) => ({ value: option.value, label: option.textContent.trim() })); const steps = []; let previousConsoleText = ""; for (let stepIndex = 0; stepIndex < expectedSequence.length; stepIndex += 1) { const modelKey = expectedSequence[stepIndex]; const consoleBeforeSelect = byId("console").textContent; if (byId("modelSelect").value !== modelKey) { byId("modelSelect").value = modelKey; byId("modelSelect").dispatchEvent(new Event("change", { bubbles: true })); } await waitForReadyAssembly(modelKey); const adapterOptions = Array.from(byId("adapterSelect").options).map((option) => ({ value: option.value, label: option.textContent.trim() })); const selectedAdapterBeforeApply = byId("adapterSelect").value; const adapterSelectDisabledBefore = byId("adapterSelect").disabled; const applyDisabledBefore = byId("applyAdapterButton").disabled; const adapterStateBeforeGenerate = byId("adapterState").textContent; const diagnosticsBeforeGenerate = parseDiagnostics(); const consoleBeforeGenerate = byId("console").textContent; const consoleDeltaBeforeGenerate = consoleBeforeGenerate.startsWith(previousConsoleText) ? consoleBeforeGenerate.slice(previousConsoleText.length) : consoleBeforeGenerate; const firstValidateIndexSincePreviousStep = consoleDeltaBeforeGenerate.indexOf("validate_adapter_delta"); const lastFreeIndexSincePreviousStep = consoleDeltaBeforeGenerate.lastIndexOf("free_model("); byId("maxTokens").value = "1"; byId("prompt").value = "hi"; byId("generateButton").click(); for (let index = 0; index < 900; index += 1) { const diagnostics = parseDiagnostics(); if ( byId("response").textContent === "e" && diagnostics.generated_token_count === 1 && byId("errorState").textContent === "none" ) { break; } if (byId("errorState").textContent !== "none") { break; } await sleep(100); } steps.push({ modelKey, cycleIndex: Math.floor(stepIndex / expectedModels.length), passIndex: stepIndex, runtimeStatus: byId("runtimeStatus").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, response: byId("response").textContent, console: byId("console").textContent, consoleBeforeSelect, initialSelectedModel, selectedModel: byId("modelSelect").value, modelOptions, adapterState: byId("adapterState").textContent, provenanceGenome: byId("provenanceGenome").textContent, provenanceSpecies: byId("provenanceSpecies").textContent, provenanceNovelty: byId("provenanceNovelty").textContent, provenancePopulation: byId("provenancePopulation").textContent, provenanceMateSelection: byId("provenanceMateSelection").textContent, provenanceOperator: byId("provenanceOperator").textContent, provenanceSchedule: byId("provenanceSchedule").textContent, provenancePhenotype: byId("provenancePhenotype").textContent, provenanceArtifact: byId("provenanceArtifact").textContent, provenanceFitness: byId("provenanceFitness").textContent, provenanceEvalCases: byId("provenanceEvalCases").textContent, provenanceEvalChecksum: byId("provenanceEvalChecksum").textContent, assemblyState: byId("assemblyState").textContent, assemblyKind: byId("assemblyKind").textContent, assemblyParents: byId("assemblyParents").textContent, assemblyOperator: byId("assemblyOperator").textContent, assemblyLedger: byId("assemblyLedger").textContent, assemblyNextGate: byId("assemblyNextGate").textContent, modulePlanState: byId("modulePlanState").textContent, modulePlanKind: byId("modulePlanKind").textContent, modulePlanResource: byId("modulePlanResource").textContent, modulePlanExecution: byId("modulePlanExecution").textContent, modulePlanFetch: byId("modulePlanFetch").textContent, modulePlanOrigin: byId("modulePlanOrigin").textContent, modulePlanFetchLimit: byId("modulePlanFetchLimit").textContent, modulePlanPlannedFetchCount: byId("modulePlanPlannedFetchCount").textContent, modulePlanActualFetchCount: byId("modulePlanActualFetchCount").textContent, modulePlanRouteSetChecksumAlgorithm: byId("modulePlanRouteSetChecksumAlgorithm").textContent, modulePlanRouteSetVersion: byId("modulePlanRouteSetVersion").textContent, modulePlanRouteSetChecksum: byId("modulePlanRouteSetChecksum").textContent, modulePlanActualRouteSetChecksum: byId("modulePlanActualRouteSetChecksum").textContent, modulePlanWasmPages: byId("modulePlanWasmPages").textContent, modulePlanWasmExportSet: byId("modulePlanWasmExportSet").textContent, modulePlanWasmTransferStrategy: byId("modulePlanWasmTransferStrategy").textContent, modulePlanModelReleaseStrategy: byId("modulePlanModelReleaseStrategy").textContent, modulePlanRuntimeResetStrategy: byId("modulePlanRuntimeResetStrategy").textContent, modulePlanAdapterValidationStrategy: byId("modulePlanAdapterValidationStrategy").textContent, modulePlanAdapterValidationCount: byId("modulePlanAdapterValidationCount").textContent, modulePlanAdapterApplyCount: byId("modulePlanAdapterApplyCount").textContent, modulePlanWasmHeapMinBytes: byId("modulePlanWasmHeapMinBytes").textContent, modulePlanContextTokens: byId("modulePlanContextTokens").textContent, modulePlanSamplerCap: byId("modulePlanSamplerCap").textContent, modulePlanTokenizer: byId("modulePlanTokenizer").textContent, modulePlanModules: byId("modulePlanModules").textContent, modulePlanModelBudget: byId("modulePlanModelBudget").textContent, modulePlanAdapterBudget: byId("modulePlanAdapterBudget").textContent, modulePlanAdapterStackBudget: byId("modulePlanAdapterStackBudget").textContent, modulePlanScratchBudget: byId("modulePlanScratchBudget").textContent, modulePlanPromptLimit: byId("modulePlanPromptLimit").textContent, modulePlanOutputLimit: byId("modulePlanOutputLimit").textContent, modulePlanKvCacheBudget: byId("modulePlanKvCacheBudget").textContent, modulePlanKvCachePages: byId("modulePlanKvCachePages").textContent, modulePlanTotalBudget: byId("modulePlanTotalBudget").textContent, modulePlanTotalLimit: byId("modulePlanTotalLimit").textContent, modulePlanBytes: byId("modulePlanBytes").textContent, modulePlanActualModuleBytes: byId("modulePlanActualModuleBytes").textContent, modulePlanChecksums: byId("modulePlanChecksums").textContent, modulePlanActualModuleChecksums: byId("modulePlanActualModuleChecksums").textContent, modulePlanSlots: byId("modulePlanSlots").textContent, modulePlanRoles: byId("modulePlanRoles").textContent, modulePlanPhases: byId("modulePlanPhases").textContent, modulePlanDepends: byId("modulePlanDepends").textContent, modulePlanTrace: byId("modulePlanTrace").textContent, modulePlanModel: byId("modulePlanModel").textContent, modulePlanStack: byId("modulePlanStack").textContent, adapterOptions, selectedAdapterBeforeApply, adapterSelectDisabledBefore, applyDisabledBefore, adapterStateBeforeGenerate, autoAppliedBeforeGenerate: adapterStateBeforeGenerate === "applied", diagnosticsBeforeGenerate, consoleBeforeGenerate, consoleDeltaBeforeGenerate, freeCallsBeforeGenerate: countOccurrences(consoleBeforeGenerate, "free_model("), freeCallsSincePreviousStep: countOccurrences(consoleDeltaBeforeGenerate, "free_model("), firstValidateIndexSincePreviousStep, lastFreeIndexSincePreviousStep, validateCallsBeforeGenerate: countOccurrences(consoleBeforeGenerate, "validate_adapter_delta"), applyCallsBeforeGenerate: countOccurrences(consoleBeforeGenerate, "apply_adapter_delta"), validateCallsSincePreviousStep: countOccurrences(consoleDeltaBeforeGenerate, "validate_adapter_delta"), applyCallsSincePreviousStep: countOccurrences(consoleDeltaBeforeGenerate, "apply_adapter_delta"), stackCompletionsSincePreviousStep: countOccurrences(consoleDeltaBeforeGenerate, "adapter_stack_applied(3)"), afterGenerateDiagnostics: parseDiagnostics(), stepDisabledAfterGenerate: byId("stepTokenButton").disabled, stepDisabledBeforeApply: byId("stepTokenButton").disabled, stepDisabledAfterApply: byId("stepTokenButton").disabled, generateDisabledAfterApply: byId("generateButton").disabled, applyDisabledAfterApply: byId("applyAdapterButton").disabled, beforeApplyDiagnostics: parseDiagnostics(), afterApplyDiagnostics: diagnosticsBeforeGenerate, diagnosticsText: byId("diagnostics").textContent }); previousConsoleText = byId("console").textContent; } return JSON.stringify({ initialSelectedModel, modelOptions, finalSelectedModel: byId("modelSelect").value, cycles, expectedSequence, steps }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 240000 }); return parseEvaluateValue(result); } // Runs one full q4/q8/f32 generated assembly pass after each page reload. async function runCombinedSelectorReloadSoak(client, reloads) { const reloadCount = Math.max(2, Math.min(6, Number.parseInt(String(reloads || 2), 10) || 2)); const results = []; for (let reloadIndex = 0; reloadIndex < reloadCount; reloadIndex += 1) { const pageUrl = new URL(appUrl); pageUrl.searchParams.set("reload_soak", String(reloadIndex)); await client.send("Page.navigate", { url: pageUrl.toString() }); let pageResult = null; for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); pageResult = await runPageCombinedSelectorAssemblySmoke(client); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } if (pageResult) { pageResult.reloadIndex = reloadIndex; } results.push(pageResult); } return { reloads: reloadCount, results }; } async function runPageAdapterLoadStateSmoke(client, modelKey) { const expression = ` (async () => { const expectedModel = ${JSON.stringify(modelKey)}; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch (_error) { return {}; } }; for (let index = 0; index < 600; index += 1) { const adapterState = byId("adapterState") ? byId("adapterState").textContent : ""; const status = byId("runtimeStatus") ? byId("runtimeStatus").textContent : ""; const ready = byId("generateButton") && !byId("generateButton").disabled && status === "Ready"; if (status === "Adapter load failed") { break; } if (ready && adapterState !== "waiting" && adapterState !== "loading") { break; } await sleep(100); } const initialSelectedModel = byId("modelSelect").value; if (byId("modelSelect").value !== expectedModel) { byId("modelSelect").value = expectedModel; byId("modelSelect").dispatchEvent(new Event("change", { bubbles: true })); for (let index = 0; index < 600; index += 1) { const adapterState = byId("adapterState") ? byId("adapterState").textContent : ""; const status = byId("runtimeStatus") ? byId("runtimeStatus").textContent : ""; const ready = byId("modelSelect").value === expectedModel && !byId("generateButton").disabled && status === "Ready"; if (status === "Adapter load failed") { break; } if (ready && adapterState !== "waiting" && adapterState !== "loading") { break; } await sleep(100); } } const adapterOptions = Array.from(byId("adapterSelect").options).map((option) => ({ value: option.value, label: option.textContent.trim() })); return JSON.stringify({ runtimeStatus: byId("runtimeStatus").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, response: byId("response").textContent, console: byId("console").textContent, initialSelectedModel, selectedModel: byId("modelSelect").value, adapterState: byId("adapterState").textContent, assemblyState: byId("assemblyState").textContent, assemblyKind: byId("assemblyKind").textContent, assemblyParents: byId("assemblyParents").textContent, assemblyNextGate: byId("assemblyNextGate").textContent, modulePlanTrace: byId("modulePlanTrace").textContent, adapterOptions, selectedAdapter: byId("adapterSelect").value, adapterSelectDisabled: byId("adapterSelect").disabled, applyDisabled: byId("applyAdapterButton").disabled, generateDisabled: byId("generateButton").disabled, stepTokenDisabled: byId("stepTokenButton").disabled, resetDisabled: byId("resetButton").disabled, modelSelectDisabled: byId("modelSelect").disabled, diagnostics: parseDiagnostics() }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 120000 }); return parseEvaluateValue(result); } async function runPageLoopSmoke(client) { const expression = ` (async () => { const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); const steps = []; const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch (_error) { return {}; } }; const snapshot = (label) => ({ label, runtimeStatus: byId("runtimeStatus").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, response: byId("response").textContent, console: byId("console").textContent, diagnostics: parseDiagnostics(), diagnosticsText: byId("diagnostics").textContent, benchLoadMs: byId("benchLoadMs").textContent, benchGeneratedTokens: byId("benchGeneratedTokens").textContent, selectedModel: byId("modelSelect").value, generateDisabled: byId("generateButton").disabled, stepTokenDisabled: byId("stepTokenButton").disabled, resetDisabled: byId("resetButton").disabled, modelSelectDisabled: byId("modelSelect").disabled }); const waitReady = async () => { for (let index = 0; index < 600; index += 1) { if (byId("generateButton") && !byId("generateButton").disabled && byId("runtimeStatus").textContent === "Ready") { return; } await sleep(100); } }; const selectModel = async (modelKey, label) => { if (byId("modelSelect").value !== modelKey) { byId("modelSelect").value = modelKey; byId("modelSelect").dispatchEvent(new Event("change", { bubbles: true })); } await waitReady(); steps.push(snapshot(label)); }; const generate = async (label) => { byId("response").textContent = ""; byId("maxTokens").value = "1"; byId("prompt").value = "hi"; byId("generateButton").click(); for (let index = 0; index < 600; index += 1) { if (byId("response").textContent.trim().length > 0) { break; } await sleep(100); } steps.push(snapshot(label)); }; const reset = async (label) => { byId("resetButton").click(); for (let index = 0; index < 200; index += 1) { if (byId("console").textContent === "context reset") { break; } await sleep(50); } steps.push(snapshot(label)); }; await waitReady(); steps.push(snapshot("reload-ready")); await selectModel("tinylm16q8", "q8-ready"); await generate("q8-generate-1"); await reset("q8-reset"); await generate("q8-generate-2"); await selectModel("tinylm16q4", "q4-ready"); await generate("q4-generate-1"); await reset("q4-reset"); await generate("q4-generate-2"); return JSON.stringify({ steps }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 180000 }); return parseEvaluateValue(result); } async function runPageModelErrorSmoke(client, modelKey) { const expression = ` (async () => { const expectedModel = ${JSON.stringify(modelKey || "")}; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch (_error) { return {}; } }; if (expectedModel) { for (let index = 0; index < 600; index += 1) { if (byId("modelSelect")) { break; } await sleep(100); } if (byId("modelSelect") && byId("modelSelect").value !== expectedModel) { byId("modelSelect").value = expectedModel; byId("modelSelect").dispatchEvent(new Event("change", { bubbles: true })); } } for (let index = 0; index < 600; index += 1) { const status = byId("runtimeStatus") ? byId("runtimeStatus").textContent : "Booting"; if (status !== "Booting" && status !== "Loading runtime" && status !== "Loading local model") { break; } await sleep(100); } return JSON.stringify({ runtimeStatus: byId("runtimeStatus").textContent, wasmState: byId("wasmState").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, diagnostics: parseDiagnostics(), diagnosticsText: byId("diagnostics").textContent, response: byId("response").textContent, console: byId("console").textContent, modulePlanState: byId("modulePlanState").textContent, modulePlanExecution: byId("modulePlanExecution").textContent, modulePlanFetch: byId("modulePlanFetch").textContent, modulePlanOrigin: byId("modulePlanOrigin").textContent, modulePlanFetchLimit: byId("modulePlanFetchLimit").textContent, modulePlanPlannedFetchCount: byId("modulePlanPlannedFetchCount").textContent, modulePlanActualFetchCount: byId("modulePlanActualFetchCount").textContent, modulePlanRouteSetChecksumAlgorithm: byId("modulePlanRouteSetChecksumAlgorithm").textContent, modulePlanRouteSetVersion: byId("modulePlanRouteSetVersion").textContent, modulePlanRouteSetChecksum: byId("modulePlanRouteSetChecksum").textContent, modulePlanActualRouteSetChecksum: byId("modulePlanActualRouteSetChecksum").textContent, modulePlanWasmPages: byId("modulePlanWasmPages").textContent, modulePlanWasmExportSet: byId("modulePlanWasmExportSet").textContent, modulePlanWasmTransferStrategy: byId("modulePlanWasmTransferStrategy").textContent, modulePlanModelReleaseStrategy: byId("modulePlanModelReleaseStrategy").textContent, modulePlanRuntimeResetStrategy: byId("modulePlanRuntimeResetStrategy").textContent, modulePlanAdapterValidationStrategy: byId("modulePlanAdapterValidationStrategy").textContent, modulePlanAdapterValidationCount: byId("modulePlanAdapterValidationCount").textContent, modulePlanAdapterApplyCount: byId("modulePlanAdapterApplyCount").textContent, modulePlanWasmHeapMinBytes: byId("modulePlanWasmHeapMinBytes").textContent, modulePlanContextTokens: byId("modulePlanContextTokens").textContent, modulePlanSamplerCap: byId("modulePlanSamplerCap").textContent, modulePlanTokenizer: byId("modulePlanTokenizer").textContent, selectedModel: byId("modelSelect").value, generateDisabled: byId("generateButton").disabled, stepTokenDisabled: byId("stepTokenButton").disabled, resetDisabled: byId("resetButton").disabled, modelSelectDisabled: byId("modelSelect").disabled }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 90000 }); return parseEvaluateValue(result); } async function runPageAssemblyEvalCaseDriftSmoke(client) { const expression = ` (async () => { const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch (_error) { return {}; } }; for (let index = 0; index < 800; index += 1) { const status = byId("runtimeStatus") ? byId("runtimeStatus").textContent : "Booting"; const assemblyState = byId("assemblyState") ? byId("assemblyState").textContent : ""; if ( status === "Model load failed" || assemblyState.includes("assembly eval case evidence checksum mismatch") ) { break; } await sleep(100); } return JSON.stringify({ runtimeStatus: byId("runtimeStatus").textContent, wasmState: byId("wasmState").textContent, modelState: byId("modelState").textContent, assemblyState: byId("assemblyState").textContent, modulePlanState: byId("modulePlanState").textContent, modulePlanTrace: byId("modulePlanTrace").textContent, adapterState: byId("adapterState").textContent, errorState: byId("errorState").textContent, diagnostics: parseDiagnostics(), diagnosticsText: byId("diagnostics").textContent, response: byId("response").textContent, console: byId("console").textContent, selectedModel: byId("modelSelect").value, generateDisabled: byId("generateButton").disabled, stepTokenDisabled: byId("stepTokenButton").disabled, resetDisabled: byId("resetButton").disabled, modelSelectDisabled: byId("modelSelect").disabled }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 120000 }); return parseEvaluateValue(result); } async function runPageMissingModelSmoke(client) { const expression = ` (async () => { const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch (_error) { return {}; } }; for (let index = 0; index < 600; index += 1) { const status = byId("runtimeStatus") ? byId("runtimeStatus").textContent : "Booting"; if (status !== "Booting" && status !== "Loading runtime" && status !== "Loading local model") { break; } await sleep(100); } return JSON.stringify({ runtimeStatus: byId("runtimeStatus").textContent, wasmState: byId("wasmState").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, diagnostics: parseDiagnostics(), diagnosticsText: byId("diagnostics").textContent, response: byId("response").textContent, console: byId("console").textContent, selectedModel: byId("modelSelect").value, generateDisabled: byId("generateButton").disabled, stepTokenDisabled: byId("stepTokenButton").disabled, resetDisabled: byId("resetButton").disabled, modelSelectDisabled: byId("modelSelect").disabled }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 90000 }); return parseEvaluateValue(result); } async function runPageContextErrorSmoke(client) { const expression = ` (async () => { const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch (_error) { return {}; } }; for (let index = 0; index < 600; index += 1) { if (byId("generateButton") && !byId("generateButton").disabled && byId("runtimeStatus").textContent === "Ready") { break; } await sleep(100); } byId("response").textContent = ""; byId("maxTokens").value = "1"; byId("prompt").value = "a".repeat(512); byId("generateButton").click(); for (let index = 0; index < 600; index += 1) { if (byId("errorState").textContent === "context exceeded" || byId("response").textContent.trim().length > 0) { break; } await sleep(100); } return JSON.stringify({ runtimeStatus: byId("runtimeStatus").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, response: byId("response").textContent, console: byId("console").textContent, diagnostics: parseDiagnostics(), diagnosticsText: byId("diagnostics").textContent, selectedModel: byId("modelSelect").value, generateDisabled: byId("generateButton").disabled, stepTokenDisabled: byId("stepTokenButton").disabled, resetDisabled: byId("resetButton").disabled, modelSelectDisabled: byId("modelSelect").disabled }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 90000 }); return parseEvaluateValue(result); } async function runPageEnduranceSmoke(client, cycles) { const expression = ` (async () => { const cycles = ${JSON.stringify(cycles)}; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); const steps = []; const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch (_error) { return {}; } }; const snapshot = (label) => ({ label, runtimeStatus: byId("runtimeStatus").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, response: byId("response").textContent, console: byId("console").textContent, diagnostics: parseDiagnostics(), diagnosticsText: byId("diagnostics").textContent, benchGeneratedTokens: byId("benchGeneratedTokens").textContent, selectedModel: byId("modelSelect").value, generateDisabled: byId("generateButton").disabled, stepTokenDisabled: byId("stepTokenButton").disabled, resetDisabled: byId("resetButton").disabled, modelSelectDisabled: byId("modelSelect").disabled }); const waitReady = async () => { for (let index = 0; index < 600; index += 1) { if (byId("generateButton") && !byId("generateButton").disabled && byId("runtimeStatus").textContent === "Ready") { return; } await sleep(100); } }; const selectModel = async (modelKey, label) => { if (byId("modelSelect").value !== modelKey) { byId("modelSelect").value = modelKey; byId("modelSelect").dispatchEvent(new Event("change", { bubbles: true })); } await waitReady(); steps.push(snapshot(label)); }; const generate = async (label) => { byId("response").textContent = ""; byId("maxTokens").value = "1"; byId("prompt").value = "hi"; byId("generateButton").click(); for (let index = 0; index < 600; index += 1) { if (byId("response").textContent.trim().length > 0) { break; } await sleep(100); } steps.push(snapshot(label)); }; const reset = async (label) => { byId("resetButton").click(); for (let index = 0; index < 200; index += 1) { if (byId("console").textContent === "context reset") { break; } await sleep(50); } steps.push(snapshot(label)); }; await waitReady(); for (let cycle = 1; cycle <= cycles; cycle += 1) { await selectModel("tinylm16q8", "cycle-" + cycle + "-q8-ready"); await generate("cycle-" + cycle + "-q8-generate"); await reset("cycle-" + cycle + "-q8-reset"); await selectModel("tinylm16q4", "cycle-" + cycle + "-q4-ready"); await generate("cycle-" + cycle + "-q4-generate"); await reset("cycle-" + cycle + "-q4-reset"); } return JSON.stringify({ cycles, steps }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 300000 }); return parseEvaluateValue(result); } async function runPagePerformanceSmoke(client, maxTokens) { const expression = ` (async () => { const maxTokens = ${JSON.stringify(maxTokens)}; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); const steps = []; const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch (_error) { return {}; } }; const parseBenchmarkNumber = (id) => { const text = byId(id).textContent || ""; const value = Number.parseFloat(text.replace(/[^0-9.]/g, "")); return Number.isFinite(value) ? value : 0; }; const snapshot = (label, elapsedMs) => ({ label, elapsedMs, runtimeStatus: byId("runtimeStatus").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, response: byId("response").textContent, console: byId("console").textContent, diagnostics: parseDiagnostics(), diagnosticsText: byId("diagnostics").textContent, benchLoadMs: byId("benchLoadMs").textContent, benchPromptTokens: byId("benchPromptTokens").textContent, benchGeneratedTokens: byId("benchGeneratedTokens").textContent, benchTokensPerSecond: byId("benchTokensPerSecond").textContent, benchScratch: byId("benchScratch").textContent, benchLoadMsValue: parseBenchmarkNumber("benchLoadMs"), benchPromptTokensValue: parseBenchmarkNumber("benchPromptTokens"), benchGeneratedTokensValue: parseBenchmarkNumber("benchGeneratedTokens"), benchTokensPerSecondValue: parseBenchmarkNumber("benchTokensPerSecond"), benchScratchValue: parseBenchmarkNumber("benchScratch"), selectedModel: byId("modelSelect").value, generateDisabled: byId("generateButton").disabled, stepTokenDisabled: byId("stepTokenButton").disabled, resetDisabled: byId("resetButton").disabled, modelSelectDisabled: byId("modelSelect").disabled }); const waitReady = async () => { for (let index = 0; index < 600; index += 1) { if (byId("generateButton") && !byId("generateButton").disabled && byId("runtimeStatus").textContent === "Ready") { return; } await sleep(100); } }; const selectModel = async (modelKey, label) => { if (byId("modelSelect").value !== modelKey) { byId("modelSelect").value = modelKey; byId("modelSelect").dispatchEvent(new Event("change", { bubbles: true })); } await waitReady(); steps.push(snapshot(label, 0)); }; const generate = async (label, prompt) => { byId("response").textContent = ""; byId("maxTokens").value = String(maxTokens); byId("prompt").value = prompt; const started = performance.now(); byId("generateButton").click(); for (let index = 0; index < 600; index += 1) { if (byId("response").textContent.trim().length >= maxTokens || byId("errorState").textContent !== "none") { break; } await sleep(100); } steps.push(snapshot(label, Math.round(performance.now() - started))); }; const reset = async (label) => { byId("resetButton").click(); for (let index = 0; index < 200; index += 1) { if (byId("console").textContent === "context reset") { break; } await sleep(50); } steps.push(snapshot(label, 0)); }; await waitReady(); await selectModel("tinylm16q8", "q8-performance-ready"); await generate("q8-performance-generate", "hi"); await reset("q8-performance-reset"); await selectModel("tinylm16q4", "q4-performance-ready"); await generate("q4-performance-generate", "hi"); await reset("q4-performance-reset"); return JSON.stringify({ maxTokens, steps }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 240000 }); return parseEvaluateValue(result); } async function runPagePerformanceSoak(client, cycles, maxTokens) { const expression = ` (async () => { const cycles = ${JSON.stringify(cycles)}; const maxTokens = ${JSON.stringify(maxTokens)}; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); const steps = []; const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch (_error) { return {}; } }; const parseBenchmarkNumber = (id) => { const text = byId(id).textContent || ""; const value = Number.parseFloat(text.replace(/[^0-9.]/g, "")); return Number.isFinite(value) ? value : 0; }; const snapshot = (label, elapsedMs) => ({ label, elapsedMs, runtimeStatus: byId("runtimeStatus").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, response: byId("response").textContent, console: byId("console").textContent, diagnostics: parseDiagnostics(), diagnosticsText: byId("diagnostics").textContent, benchLoadMs: byId("benchLoadMs").textContent, benchPromptTokens: byId("benchPromptTokens").textContent, benchGeneratedTokens: byId("benchGeneratedTokens").textContent, benchTokensPerSecond: byId("benchTokensPerSecond").textContent, benchScratch: byId("benchScratch").textContent, benchLoadMsValue: parseBenchmarkNumber("benchLoadMs"), benchPromptTokensValue: parseBenchmarkNumber("benchPromptTokens"), benchGeneratedTokensValue: parseBenchmarkNumber("benchGeneratedTokens"), benchTokensPerSecondValue: parseBenchmarkNumber("benchTokensPerSecond"), benchScratchValue: parseBenchmarkNumber("benchScratch"), selectedModel: byId("modelSelect").value, generateDisabled: byId("generateButton").disabled, stepTokenDisabled: byId("stepTokenButton").disabled, resetDisabled: byId("resetButton").disabled, modelSelectDisabled: byId("modelSelect").disabled }); const waitReady = async () => { for (let index = 0; index < 600; index += 1) { if (byId("generateButton") && !byId("generateButton").disabled && byId("runtimeStatus").textContent === "Ready") { return; } await sleep(100); } }; const selectModel = async (modelKey, label) => { if (byId("modelSelect").value !== modelKey) { byId("modelSelect").value = modelKey; byId("modelSelect").dispatchEvent(new Event("change", { bubbles: true })); } await waitReady(); steps.push(snapshot(label, 0)); }; const generate = async (label, prompt) => { byId("response").textContent = ""; byId("maxTokens").value = String(maxTokens); byId("prompt").value = prompt; const started = performance.now(); byId("generateButton").click(); for (let index = 0; index < 600; index += 1) { if (byId("response").textContent.trim().length >= maxTokens || byId("errorState").textContent !== "none") { break; } await sleep(100); } steps.push(snapshot(label, Math.round(performance.now() - started))); }; const reset = async (label) => { byId("resetButton").click(); for (let index = 0; index < 200; index += 1) { if (byId("console").textContent === "context reset") { break; } await sleep(50); } steps.push(snapshot(label, 0)); }; await waitReady(); for (let cycle = 1; cycle <= cycles; cycle += 1) { await selectModel("tinylm16q8", "cycle-" + cycle + "-q8-performance-ready"); await generate("cycle-" + cycle + "-q8-performance-generate", "hi"); await reset("cycle-" + cycle + "-q8-performance-reset"); await selectModel("tinylm16q4", "cycle-" + cycle + "-q4-performance-ready"); await generate("cycle-" + cycle + "-q4-performance-generate", "hi"); await reset("cycle-" + cycle + "-q4-performance-reset"); } return JSON.stringify({ cycles, maxTokens, steps }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 600000 }); return parseEvaluateValue(result); } async function runPageUiAudit(client) { const expression = ` (async () => { const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const byId = (id) => document.getElementById(id); const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch (_error) { return {}; } }; const parseBenchmarkNumber = (id) => { const text = byId(id).textContent || ""; const value = Number.parseFloat(text.replace(/[^0-9.]/g, "")); return Number.isFinite(value) ? value : 0; }; const textList = (selector) => Array.from(document.querySelectorAll(selector)).map((node) => node.textContent.trim()); const badRects = () => Array.from(document.querySelectorAll(".topbar,.notice,.panel,.footnote,button,textarea,select,input")) .map((node) => { const rect = node.getBoundingClientRect(); return { tag: node.tagName.toLowerCase(), id: node.id || "", className: typeof node.className === "string" ? node.className : "", width: Math.round(rect.width), height: Math.round(rect.height) }; }) .filter((rect) => rect.width < 1 || rect.height < 1); const collect = (label) => { const diagnostics = parseDiagnostics(); return { label, title: document.title, lang: document.documentElement.lang, h1: document.querySelector("h1") ? document.querySelector("h1").textContent.trim() : "", eyebrow: document.querySelector(".eyebrow") ? document.querySelector(".eyebrow").textContent.trim() : "", notice: document.querySelector(".notice") ? document.querySelector(".notice").textContent.trim() : "", footer: byId("appFooter") ? byId("appFooter").textContent.replace(/\\s+/g, " ").trim() : "", headings: textList(".panel h2"), labels: textList("label"), modelOptions: Array.from(byId("modelSelect").options).map((option) => option.textContent.trim()), runtimeStatus: byId("runtimeStatus").textContent, wasmState: byId("wasmState").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, response: byId("response").textContent, conversationText: byId("conversation").textContent, conversationItems: Array.from(document.querySelectorAll("#conversation .message")).map((node) => ({ role: node.querySelector(".message-role") ? node.querySelector(".message-role").textContent.trim() : "", text: node.querySelector(".message-text") ? node.querySelector(".message-text").textContent : "", isError: node.classList.contains("error") })), console: byId("console").textContent, diagnostics, diagnosticsText: byId("diagnostics").textContent, developerText: byId("developer").textContent, provenanceState: byId("provenanceState").textContent, provenanceSourceKind: byId("provenanceSourceKind").textContent, provenanceAdmission: byId("provenanceAdmission").textContent, provenanceQualityClaim: byId("provenanceQualityClaim").textContent, provenanceTrainedClaim: byId("provenanceTrainedClaim").textContent, provenanceGenome: byId("provenanceGenome").textContent, provenanceSpecies: byId("provenanceSpecies").textContent, provenanceNovelty: byId("provenanceNovelty").textContent, provenancePopulation: byId("provenancePopulation").textContent, provenanceMateSelection: byId("provenanceMateSelection").textContent, provenanceOperator: byId("provenanceOperator").textContent, provenanceSchedule: byId("provenanceSchedule").textContent, provenancePhenotype: byId("provenancePhenotype").textContent, provenanceArtifact: byId("provenanceArtifact").textContent, provenanceFitness: byId("provenanceFitness").textContent, provenanceEvalCases: byId("provenanceEvalCases").textContent, provenanceEvalChecksum: byId("provenanceEvalChecksum").textContent, provenanceChecksum: byId("provenanceChecksum").textContent, provenanceNextGate: byId("provenanceNextGate").textContent, assemblyState: byId("assemblyState").textContent, assemblyKind: byId("assemblyKind").textContent, assemblyParents: byId("assemblyParents").textContent, assemblyOperator: byId("assemblyOperator").textContent, assemblyLedger: byId("assemblyLedger").textContent, assemblyNextGate: byId("assemblyNextGate").textContent, modulePlanState: byId("modulePlanState").textContent, modulePlanKind: byId("modulePlanKind").textContent, modulePlanResource: byId("modulePlanResource").textContent, modulePlanExecution: byId("modulePlanExecution").textContent, modulePlanFetch: byId("modulePlanFetch").textContent, modulePlanOrigin: byId("modulePlanOrigin").textContent, modulePlanFetchLimit: byId("modulePlanFetchLimit").textContent, modulePlanPlannedFetchCount: byId("modulePlanPlannedFetchCount").textContent, modulePlanActualFetchCount: byId("modulePlanActualFetchCount").textContent, modulePlanRouteSetChecksumAlgorithm: byId("modulePlanRouteSetChecksumAlgorithm").textContent, modulePlanRouteSetVersion: byId("modulePlanRouteSetVersion").textContent, modulePlanRouteSetChecksum: byId("modulePlanRouteSetChecksum").textContent, modulePlanActualRouteSetChecksum: byId("modulePlanActualRouteSetChecksum").textContent, modulePlanWasmPages: byId("modulePlanWasmPages").textContent, modulePlanWasmExportSet: byId("modulePlanWasmExportSet").textContent, modulePlanWasmTransferStrategy: byId("modulePlanWasmTransferStrategy").textContent, modulePlanModelReleaseStrategy: byId("modulePlanModelReleaseStrategy").textContent, modulePlanRuntimeResetStrategy: byId("modulePlanRuntimeResetStrategy").textContent, modulePlanAdapterValidationStrategy: byId("modulePlanAdapterValidationStrategy").textContent, modulePlanAdapterValidationCount: byId("modulePlanAdapterValidationCount").textContent, modulePlanAdapterApplyCount: byId("modulePlanAdapterApplyCount").textContent, modulePlanWasmHeapMinBytes: byId("modulePlanWasmHeapMinBytes").textContent, modulePlanContextTokens: byId("modulePlanContextTokens").textContent, modulePlanSamplerCap: byId("modulePlanSamplerCap").textContent, modulePlanTokenizer: byId("modulePlanTokenizer").textContent, modulePlanModules: byId("modulePlanModules").textContent, modulePlanModelBudget: byId("modulePlanModelBudget").textContent, modulePlanAdapterBudget: byId("modulePlanAdapterBudget").textContent, modulePlanAdapterStackBudget: byId("modulePlanAdapterStackBudget").textContent, modulePlanScratchBudget: byId("modulePlanScratchBudget").textContent, modulePlanPromptLimit: byId("modulePlanPromptLimit").textContent, modulePlanOutputLimit: byId("modulePlanOutputLimit").textContent, modulePlanKvCacheBudget: byId("modulePlanKvCacheBudget").textContent, modulePlanKvCachePages: byId("modulePlanKvCachePages").textContent, modulePlanTotalBudget: byId("modulePlanTotalBudget").textContent, modulePlanTotalLimit: byId("modulePlanTotalLimit").textContent, modulePlanBytes: byId("modulePlanBytes").textContent, modulePlanActualModuleBytes: byId("modulePlanActualModuleBytes").textContent, modulePlanChecksums: byId("modulePlanChecksums").textContent, modulePlanActualModuleChecksums: byId("modulePlanActualModuleChecksums").textContent, modulePlanSlots: byId("modulePlanSlots").textContent, modulePlanRoles: byId("modulePlanRoles").textContent, modulePlanPhases: byId("modulePlanPhases").textContent, modulePlanDepends: byId("modulePlanDepends").textContent, modulePlanTrace: byId("modulePlanTrace").textContent, modulePlanModel: byId("modulePlanModel").textContent, modulePlanStack: byId("modulePlanStack").textContent, benchLoadMs: byId("benchLoadMs").textContent, benchPromptTokens: byId("benchPromptTokens").textContent, benchGeneratedTokens: byId("benchGeneratedTokens").textContent, benchTokensPerSecond: byId("benchTokensPerSecond").textContent, benchScratch: byId("benchScratch").textContent, benchLoadMsValue: parseBenchmarkNumber("benchLoadMs"), benchPromptTokensValue: parseBenchmarkNumber("benchPromptTokens"), benchGeneratedTokensValue: parseBenchmarkNumber("benchGeneratedTokens"), benchScratchValue: parseBenchmarkNumber("benchScratch"), selectedModel: byId("modelSelect").value, temperatureValue: byId("temperature").value, topKValue: byId("topK").value, topPValue: byId("topP").value, seedValue: byId("seed").value, generateDisabled: byId("generateButton").disabled, stepTokenDisabled: byId("stepTokenButton").disabled, resetDisabled: byId("resetButton").disabled, clearChatDisabled: byId("clearChatButton").disabled, modelSelectDisabled: byId("modelSelect").disabled, panelCount: document.querySelectorAll(".panel").length, badRects: badRects(), viewportWidth: window.innerWidth, viewportHeight: window.innerHeight, scrollWidth: document.documentElement.scrollWidth, bodyScrollWidth: document.body.scrollWidth, gridDisplay: window.getComputedStyle(document.querySelector(".grid")).display }; }; const waitReady = async () => { for (let index = 0; index < 600; index += 1) { if (byId("generateButton") && !byId("generateButton").disabled && byId("runtimeStatus").textContent === "Ready") { return; } await sleep(100); } }; await waitReady(); const before = collect("ready"); byId("response").textContent = ""; byId("maxTokens").value = "1"; byId("prompt").value = "hi"; byId("generateButton").click(); for (let index = 0; index < 600; index += 1) { if (byId("response").textContent.trim().length > 0 || byId("errorState").textContent !== "none") { break; } await sleep(100); } const after = collect("generated"); byId("clearChatButton").click(); await sleep(50); const cleared = collect("cleared"); return JSON.stringify({ before, after, cleared }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 180000 }); return parseEvaluateValue(result); } async function removeProfile(profile) { for (let attempt = 0; attempt < 100; attempt += 1) { try { fs.rmSync(profile, { force: true, recursive: true }); return; } catch (error) { if (attempt === 99) { throw error; } await sleep(100); } } } function waitForExit(process) { if (process.exitCode !== null || process.signalCode !== null) { return Promise.resolve(); } return new Promise((resolve) => { process.once("exit", resolve); setTimeout(resolve, 10000); }); } function killProcessTree(process) { if (process.pid) { try { childProcess.execFileSync("taskkill.exe", ["/PID", String(process.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }); return; } catch (_error) { process.kill(); return; } } process.kill(); } function killProfileProcesses(profile) { if (process.platform !== "win32") { return; } const marker = path.basename(profile).replace(/'/g, "''"); const command = `$marker = '${marker}'; Get-CimInstance Win32_Process | Where-Object { ($_.Name -eq 'chrome.exe' -or $_.Name -eq 'msedge.exe') -and $_.CommandLine -like \"*$marker*\" } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`; try { childProcess.execFileSync("powershell.exe", ["-NoProfile", "-Command", command], { stdio: "ignore", windowsHide: true }); } catch (_error) { // Best-effort cleanup for detached Chrome children. } } function assertSmoke(result, modelKey, networkRequests) { const failures = []; const quantization = expectedQuantization[modelKey]; if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (result.runtimeStatus !== "Ready") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (result.errorState !== "none") { failures.push(`error state was ${result.errorState}`); } if (result.response !== "e") { failures.push(`response was ${JSON.stringify(result.response)}`); } if (result.stepTokenDisabled) { failures.push("step-token control stayed disabled after generation"); } if (!Array.isArray(result.conversationItems) || result.conversationItems.length !== 2) { failures.push(`conversation item count was ${result.conversationItems ? result.conversationItems.length : "missing"}`); } else { if (result.conversationItems[0].role !== "User" || result.conversationItems[0].text !== "hi") { failures.push(`conversation user item was ${JSON.stringify(result.conversationItems[0])}`); } if (result.conversationItems[1].role !== "TinyRustLM" || result.conversationItems[1].text !== "e" || result.conversationItems[1].isError) { failures.push(`conversation assistant item was ${JSON.stringify(result.conversationItems[1])}`); } } if (!result.diagnostics.includes("argmax=101")) { failures.push("diagnostics did not include argmax=101"); } if (quantization && !result.diagnostics.includes(`"active_quantization_mode": "${quantization}"`)) { failures.push(`diagnostics did not report ${quantization} mode`); } if (networkRequests && !networkIncludesPath(networkRequests, "/runtime/tinyrustlm.wasm.manifest")) { failures.push("runtime WASM manifest route was not requested"); } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertMultiParentRegistrySmoke(result, modelKey, networkRequests) { assertSmoke(result, modelKey, networkRequests); const failures = []; if (!Array.isArray(result.modelOptions) || result.modelOptions.length !== 1) { failures.push(`model options were ${JSON.stringify(result.modelOptions)}`); } else { const option = result.modelOptions[0]; if (option.value !== modelKey) { failures.push(`registry option value was ${option.value}`); } const expectedLabel = expectedLabelForModel(modelKey); if (option.label !== expectedLabel) { failures.push(`registry option label was ${option.label}`); } } if (!networkRequests.some((requestUrl) => requestUrl.includes("/models/selector.registry"))) { failures.push("selector registry route was not requested"); } const expectedRoute = expectedRouteForModel(modelKey) || "/models/tinylm16-q8.slm"; if (!networkRequests.some((requestUrl) => requestUrl.includes(expectedRoute))) { failures.push("registry model route was not requested"); } const expectedOperatorKind = expectedRegistryOperatorKindForModel(modelKey); if ( expectedOperatorKind && !isOperatorReceiptSummary(result.provenanceOperator, expectedOperatorKind) ) { failures.push(`provenance operator was ${result.provenanceOperator}`); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } // Confirms a registry-served converted-trained artifact keeps its browser-visible claim boundary. function assertConvertedTrainedRegistrySmoke(result, modelKey, networkRequests) { assertSmoke(result, modelKey, networkRequests); const failures = []; const modelOptionValues = Array.isArray(result.modelOptions) ? result.modelOptions.map((option) => option.value) : []; if (!modelOptionValues.includes(modelKey)) { failures.push(`registry options were ${JSON.stringify(result.modelOptions)}`); } const matchingOption = Array.isArray(result.modelOptions) ? result.modelOptions.find((option) => option.value === modelKey) : undefined; if (matchingOption && matchingOption.label !== expectedLabelForModel(modelKey)) { failures.push(`registry option label was ${matchingOption.label}`); } if (!networkRequests.some((requestUrl) => requestUrl.includes("/models/selector.registry"))) { failures.push("selector registry route was not requested"); } const expectedRoute = expectedRouteForModel(modelKey) || "/models/converted-trained-q8.slm"; if (!networkIncludesPath(networkRequests, expectedRoute)) { failures.push("converted-trained model route was not requested"); } if (result.provenanceSourceKind !== "converted-trained") { failures.push(`provenance source kind was ${result.provenanceSourceKind}`); } if (result.provenanceAdmission !== "structure-accepted-quality-pending") { failures.push(`provenance admission was ${result.provenanceAdmission}`); } if (result.provenanceQualityClaim !== "runtime-compatible-not-quality-verified") { failures.push(`provenance quality claim was ${result.provenanceQualityClaim}`); } if (result.provenanceTrainedClaim !== "pending-evaluation") { failures.push(`provenance trained claim was ${result.provenanceTrainedClaim}`); } if (result.provenanceNextGate !== "task-eval-and-safety-review-before-assistant-quality-claim") { failures.push(`provenance next gate was ${result.provenanceNextGate}`); } if (!networkIncludesPath(networkRequests, `${expectedRoute}.manifest`)) { failures.push("converted-trained manifest route was not requested"); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } // Confirms selector receipt drift removes generated entries before browser model selection. function assertSelectorOperatorReceiptDriftSmoke( result, networkRequests, rejectedModelKey = "multi-parent-sign-merge-q8" ) { assertSmoke(result, "tinylm16q8", networkRequests); const failures = []; const modelOptionValues = Array.isArray(result.modelOptions) ? result.modelOptions.map((option) => option.value) : []; if (modelOptionValues.includes(rejectedModelKey)) { failures.push("operator receipt drift registry entry was accepted"); } if (!modelOptionValues.includes("tinylm16q8") || !modelOptionValues.includes("tinylm16q4")) { failures.push(`fallback model options were ${JSON.stringify(result.modelOptions)}`); } if (result.provenanceOperator !== "unavailable") { failures.push(`fallback provenance operator was ${result.provenanceOperator}`); } if (!networkRequests.some((requestUrl) => requestUrl.includes("/models/selector.registry"))) { failures.push("selector registry route was not requested"); } if (!networkRequests.some((requestUrl) => requestUrl.includes("/models/tinylm16-q8.slm"))) { failures.push("fallback q8 model route was not requested"); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } // Confirms generated selector operator receipt drift prevents generated route intake. function assertGeneratedSelectorOperatorReceiptDriftSmoke(result, modelKey, networkRequests) { assertSmoke(result, "tinylm16q8", networkRequests); const failures = []; const modelOptionValues = Array.isArray(result.modelOptions) ? result.modelOptions.map((option) => option.value) : []; const generatedModels = isGeneratedMultiParentModel(modelKey) ? combinedSelectorModelsFor(modelKey) : [ "multi-parent-sign-merge-q4", "multi-parent-sign-merge-q8", "multi-parent-sign-merge-f32", "multi-parent-soup-q4", "multi-parent-soup-q8", "multi-parent-soup-f32" ]; for (const generatedModel of generatedModels) { if (modelOptionValues.includes(generatedModel)) { failures.push(`generated operator receipt drift entry was accepted: ${generatedModel}`); } const generatedRoutes = [ expectedModelRoutes[generatedModel], expectedModulePlanRoutes[generatedModel], expectedAssemblyReceiptRoutes[generatedModel], expectedAdapterFamilyReceiptRoutes[generatedModel], ...(expectedAdapterStackRoutes[generatedModel] || []) ].filter(Boolean); for (const generatedRoute of generatedRoutes) { if (networkIncludesPath(networkRequests, generatedRoute)) { failures.push(`generated route was requested after operator receipt drift: ${generatedRoute}`); } } } if (!modelOptionValues.includes("tinylm16q8") || !modelOptionValues.includes("tinylm16q4")) { failures.push(`fallback model options were ${JSON.stringify(result.modelOptions)}`); } if (result.provenanceOperator !== "unavailable") { failures.push(`fallback provenance operator was ${result.provenanceOperator}`); } if (!networkIncludesPath(networkRequests, "/models/selector.registry")) { failures.push("selector registry route was not requested"); } if (!networkIncludesPath(networkRequests, "/models/tinylm16-q8.slm")) { failures.push("fallback q8 model route was not requested"); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertSelectorBudgetSmoke(result, networkRequests) { assertSmoke(result, "tinylm16q8", networkRequests); const failures = []; const modelOptionValues = Array.isArray(result.modelOptions) ? result.modelOptions.map((option) => option.value) : []; if (modelOptionValues.includes("oversized-browser-parent")) { failures.push("oversized registry entry was accepted"); } if (!modelOptionValues.includes("tinylm16q8") || !modelOptionValues.includes("tinylm16q4")) { failures.push(`fallback model options were ${JSON.stringify(result.modelOptions)}`); } if (!networkRequests.some((requestUrl) => requestUrl.includes("/models/selector.registry"))) { failures.push("selector registry route was not requested"); } if (networkRequests.some((requestUrl) => requestUrl.includes("/models/oversized-browser-parent.slm"))) { failures.push("oversized model route was requested"); } if (!networkRequests.some((requestUrl) => requestUrl.includes("/models/tinylm16-q8.slm"))) { failures.push("fallback q8 model route was not requested"); } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertSidecarBudgetContractSmoke(result, networkRequests) { assertSmoke(result, "tinylm16q8", networkRequests); const failures = []; const modelOptionValues = Array.isArray(result.modelOptions) ? result.modelOptions.map((option) => option.value) : []; if (modelOptionValues.includes("sidecar-budget-contract-parent")) { failures.push("sidecar-budget registry entry was accepted"); } if (!modelOptionValues.includes("tinylm16q8") || !modelOptionValues.includes("tinylm16q4")) { failures.push(`fallback model options were ${JSON.stringify(result.modelOptions)}`); } if (!networkRequests.some((requestUrl) => requestUrl.includes("/models/selector.registry"))) { failures.push("selector registry route was not requested"); } if (networkRequests.some((requestUrl) => requestUrl.includes("/models/sidecar-budget-contract-parent.slm"))) { failures.push("sidecar-budget model route was requested"); } if (!networkRequests.some((requestUrl) => requestUrl.includes("/models/tinylm16-q8.slm"))) { failures.push("fallback q8 model route was not requested"); } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertRuntimeManifestDriftSmoke(result, networkRequests) { const failures = []; if (result.runtimeStatus !== "Boot failed") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (result.wasmState !== "waiting") { failures.push(`wasm state was ${result.wasmState}`); } if (result.modelState !== "boot error") { failures.push(`model state was ${result.modelState}`); } if (!String(result.errorState || "").includes("WASM runtime checksum mismatch")) { failures.push(`error state was ${result.errorState}`); } if (result.generateDisabled !== true || result.resetDisabled !== true) { failures.push("runtime controls were enabled after manifest drift"); } if (!networkIncludesPath(networkRequests, "/runtime/tinyrustlm.wasm.manifest")) { failures.push("runtime WASM manifest route was not requested"); } if (!networkIncludesPath(networkRequests, "/runtime/tinyrustlm.wasm")) { failures.push("runtime WASM route was not requested"); } if (networkRequests.some((requestUrl) => requestUrl.includes("/models/tinylm16-q8.slm"))) { failures.push("model route was requested after runtime manifest drift"); } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanDriftSmoke(result, modelKey, networkRequests, driftLabel, expectedErrorText) { const failures = []; if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (result.runtimeStatus !== "Model load failed") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (result.modelState !== "fetch error") { failures.push(`model state was ${result.modelState}`); } if (!String(result.errorState || "").includes(expectedErrorText)) { failures.push(`error state was ${result.errorState}`); } if (!result.generateDisabled || !result.resetDisabled || !result.stepTokenDisabled) { failures.push(`runtime controls were enabled after ${driftLabel}`); } if (result.modelSelectDisabled) { failures.push(`model selector was disabled after ${driftLabel}`); } if (!networkIncludesPath(networkRequests, "/models/selector.registry")) { failures.push("selector registry route was not requested"); } const expectedModulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!expectedModulePlanRoute || !networkIncludesPath(networkRequests, expectedModulePlanRoute)) { failures.push(`module plan route was not requested: ${expectedModulePlanRoute}`); } const expectedModelRoute = expectedRouteForModel(modelKey); const modulePlanRequestIndex = expectedModulePlanRoute ? networkRequests.findIndex((requestUrl) => requestUrl.includes(expectedModulePlanRoute)) : -1; const modelRequestIndex = expectedModelRoute ? networkRequests.findIndex((requestUrl) => requestUrl.includes(expectedModelRoute)) : -1; if (expectedModelRoute && modelRequestIndex > modulePlanRequestIndex) { failures.push(`generated model route was requested after ${driftLabel}`); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanResourceDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan resource drift", "Module plan module plan adapter byte budget mismatch" ); } function assertModulePlanRuntimeScratchDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan runtime scratch drift", "Module plan module plan runtime scratch byte budget mismatch" ); } function assertModulePlanOutputLimitDriftSmoke(result, modelKey, networkRequests) { // Checks that output-limit drift stops at module-plan validation. assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan output limit drift", "Module plan module plan output byte limit mismatch" ); } function assertModulePlanPromptLimitDriftSmoke(result, modelKey, networkRequests) { // Checks that prompt-limit drift stops at module-plan validation. assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan prompt limit drift", "Module plan module plan prompt byte limit mismatch" ); } function assertModulePlanFetchCountDriftSmoke(result, modelKey, networkRequests) { // Checks that fetch-count drift stops before generated route assembly begins. assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan fetch count drift", "Module plan module plan fetch count limit mismatch" ); } function assertModulePlanPlannedFetchCountDriftSmoke(result, modelKey, networkRequests) { // Checks that planned-fetch drift stops before generated route assembly begins. assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan planned fetch count drift", "Module plan module plan planned fetch count mismatch" ); } function assertModulePlanRouteSetVersionDriftSmoke(result, modelKey, networkRequests) { // Checks that route-set version drift stops before generated route assembly begins. assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan route set version drift", "Module plan route set version mismatch" ); } function assertModulePlanRouteSetAlgorithmDriftSmoke(result, modelKey, networkRequests) { // Checks that route-set algorithm drift stops before generated route assembly begins. assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan route set checksum algorithm drift", "Module plan route set checksum algorithm mismatch" ); } function assertModulePlanRouteSetDriftSmoke(result, modelKey, networkRequests) { // Checks that route-set drift stops before generated route assembly begins. assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan route set drift", "Module plan route set checksum mismatch" ); } function assertModulePlanOperatorReceiptDriftSmoke(result, modelKey, networkRequests) { // Checks that module-plan/operator-receipt checksum drift stops before model fetches. assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan operator receipt drift", "module plan operator receipt checksum mismatch" ); } function assertModulePlanKvCacheDriftSmoke(result, modelKey, networkRequests) { // Verifies KV drift stops at module-plan validation before generated artifact fetches. assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan KV cache drift", "Module plan KV cache page count mismatch" ); } function assertModulePlanAdapterStackBudgetDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan adapter stack budget drift", "Module plan module plan adapter stack byte budget mismatch" ); } function assertModulePlanTotalBudgetDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan total budget drift", "Module plan module plan total byte budget mismatch" ); } function assertModulePlanTotalLimitDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan total limit drift", "Module plan module plan total byte budget limit mismatch" ); } // Asserts receipt cardinality drift stops before generated model or adapter routes are fetched. function assertModulePlanCountDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan count drift", "Module plan module count mismatch" ); const failures = []; const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (adapterFamilyRoute && networkIncludesPath(networkRequests, adapterFamilyRoute)) { failures.push(`adapter family route was requested after module plan count drift: ${adapterFamilyRoute}`); } const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; for (const stackRoute of stackRoutes) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after module plan count drift: ${stackRoute}`); } } const manifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const manifestRoute of manifestRoutes) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after module plan count drift: ${manifestRoute}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanWasmMemoryDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan WASM memory drift", "Module plan WASM memory initial pages mismatch" ); } function assertModulePlanWasmExportSetDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan WASM export-set drift", "Module plan WASM export set mismatch" ); } function assertModulePlanWasmTransferDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan WASM transfer strategy drift", "Module plan WASM transfer strategy mismatch" ); } function assertModulePlanModelReleaseDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan model release strategy drift", "Module plan model release strategy mismatch" ); } function assertModulePlanRuntimeResetDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan runtime reset strategy drift", "Module plan runtime reset strategy mismatch" ); } function assertModulePlanAdapterValidationDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan adapter validation strategy drift", "Module plan adapter validation strategy mismatch" ); } function assertModulePlanAdapterValidationCountDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan adapter validation count drift", "Module plan adapter validation count mismatch" ); } function assertModulePlanAdapterApplyCountDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan adapter apply count drift", "Module plan adapter apply count mismatch" ); } function assertModulePlanWasmHeapDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan WASM heap drift", "Module plan WASM heap min bytes mismatch" ); } function assertModulePlanContextTokenDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan context token drift", "Module plan context token limit mismatch" ); } function assertModulePlanSamplerCapDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan sampler cap drift", "Module plan sampler candidate cap mismatch" ); } function assertModulePlanTokenizerDriftSmoke(result, modelKey, networkRequests) { // Verifies tokenizer drift stops at module-plan validation before generated model fetches. assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan tokenizer drift", "Module plan tokenizer checksum mismatch" ); } function assertModulePlanProfileDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan profile drift", "Module plan field module_plan_profile was" ); const failures = []; const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (adapterFamilyRoute && networkIncludesPath(networkRequests, adapterFamilyRoute)) { failures.push(`adapter family route was requested after module plan profile drift: ${adapterFamilyRoute}`); } const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; for (const stackRoute of stackRoutes) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after module plan profile drift: ${stackRoute}`); } } const manifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const manifestRoute of manifestRoutes) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after module plan profile drift: ${manifestRoute}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanExecutionProfileDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan execution profile drift", "Module plan field module_plan_execution_profile was" ); const failures = []; const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (adapterFamilyRoute && networkIncludesPath(networkRequests, adapterFamilyRoute)) { failures.push(`adapter family route was requested after module plan execution profile drift: ${adapterFamilyRoute}`); } const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; for (const stackRoute of stackRoutes) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after module plan execution profile drift: ${stackRoute}`); } } const manifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const manifestRoute of manifestRoutes) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after module plan execution profile drift: ${manifestRoute}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanFetchPolicyDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan fetch policy drift", "Module plan field module_plan_fetch_policy was" ); const failures = []; const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (adapterFamilyRoute && networkIncludesPath(networkRequests, adapterFamilyRoute)) { failures.push(`adapter family route was requested after module plan fetch policy drift: ${adapterFamilyRoute}`); } const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; for (const stackRoute of stackRoutes) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after module plan fetch policy drift: ${stackRoute}`); } } const manifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const manifestRoute of manifestRoutes) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after module plan fetch policy drift: ${manifestRoute}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanOriginPolicyDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan origin policy drift", "Module plan field module_plan_origin_policy was" ); const failures = []; const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (adapterFamilyRoute && networkIncludesPath(networkRequests, adapterFamilyRoute)) { failures.push(`adapter family route was requested after module plan origin policy drift: ${adapterFamilyRoute}`); } const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; for (const stackRoute of stackRoutes) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after module plan origin policy drift: ${stackRoute}`); } } const manifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const manifestRoute of manifestRoutes) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after module plan origin policy drift: ${manifestRoute}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanGraphDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan graph drift", "Module plan field module.0.path was" ); } function assertModulePlanStackDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan stack drift", "Module plan field module.4.adapter_path was" ); const failures = []; const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; for (const stackRoute of stackRoutes) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after module plan stack drift: ${stackRoute}`); } } const manifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const manifestRoute of manifestRoutes) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after module plan stack drift: ${manifestRoute}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanRoleDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan role drift", "Module plan field module.4.role was" ); const failures = []; const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; for (const stackRoute of stackRoutes) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after module plan role drift: ${stackRoute}`); } } const manifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const manifestRoute of manifestRoutes) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after module plan role drift: ${manifestRoute}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanSlotDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan slot drift", "Module plan field module.4.assembly_slot was" ); const failures = []; const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; for (const stackRoute of stackRoutes) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after module plan slot drift: ${stackRoute}`); } } const manifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const manifestRoute of manifestRoutes) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after module plan slot drift: ${manifestRoute}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanPhaseDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan phase drift", "Module plan field module.4.phase was" ); const failures = []; const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; for (const stackRoute of stackRoutes) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after module plan phase drift: ${stackRoute}`); } } const manifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const manifestRoute of manifestRoutes) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after module plan phase drift: ${manifestRoute}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanByteDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan byte drift", "Module plan field module.0.byte_count was" ); const failures = []; const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; for (const stackRoute of stackRoutes) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after module plan byte drift: ${stackRoute}`); } } const manifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const manifestRoute of manifestRoutes) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after module plan byte drift: ${manifestRoute}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanChecksumDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan checksum drift", "module plan adapter module checksum mismatch" ); const failures = []; const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; for (const stackRoute of stackRoutes) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after module plan checksum drift: ${stackRoute}`); } } const manifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const manifestRoute of manifestRoutes) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after module plan checksum drift: ${manifestRoute}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertStepTokenSmoke(result, modelKey, networkRequests) { const failures = []; const quantization = expectedQuantization[modelKey]; if (!quantization) { failures.push(`unknown expected model ${modelKey}`); } if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (result.runtimeStatus !== "Ready") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (result.errorState !== "none") { failures.push(`error state was ${result.errorState}`); } if (!result.readyStepDisabled) { failures.push("step-token control was enabled before generation context existed"); } if (result.afterGenerateStepDisabled) { failures.push("step-token control stayed disabled after the first generation"); } if (result.stepTokenDisabled) { failures.push("step-token control was disabled after stepping"); } if (result.generateDisabled || result.resetDisabled || result.modelSelectDisabled) { failures.push("primary controls were unexpectedly disabled after stepping"); } if (result.response !== "ee") { failures.push(`response was ${JSON.stringify(result.response)}`); } if (!Array.isArray(result.conversationItems) || result.conversationItems.length !== 2) { failures.push(`conversation item count was ${result.conversationItems ? result.conversationItems.length : "missing"}`); } else { if (result.conversationItems[0].role !== "User" || result.conversationItems[0].text !== "hi") { failures.push(`conversation user item was ${JSON.stringify(result.conversationItems[0])}`); } if (result.conversationItems[1].role !== "TinyRustLM" || result.conversationItems[1].text !== "ee" || result.conversationItems[1].isError) { failures.push(`conversation assistant item was ${JSON.stringify(result.conversationItems[1])}`); } } if (!String(result.console).includes("generate(max_new_tokens=1, temperature=0, top_k=1, top_p=1, seed=1) -> 0")) { failures.push("console did not include the initial generate call"); } if (!String(result.console).includes("generate_next_token(temperature=0, top_k=1, top_p=1, seed=1) -> 0")) { failures.push("console did not include the step-token call"); } if (!result.diagnostics || result.diagnostics.last_error !== "ok") { failures.push("diagnostics last_error was not ok"); } if (result.diagnostics && result.diagnostics.generated_token_count !== 2) { failures.push(`generated token count was ${result.diagnostics.generated_token_count}`); } if (result.diagnostics && result.diagnostics.prompt_token_count !== 3) { failures.push(`prompt token count was ${result.diagnostics.prompt_token_count}`); } if (result.diagnostics && result.diagnostics.kv_cache_length !== 5) { failures.push(`kv cache length was ${result.diagnostics.kv_cache_length}`); } if (result.diagnostics && result.diagnostics.selected_next_token !== 101) { failures.push(`selected token was ${result.diagnostics.selected_next_token}`); } if (quantization && (!result.diagnostics || result.diagnostics.active_quantization_mode !== quantization)) { failures.push(`diagnostics did not report ${quantization} mode`); } if (result.benchPromptTokens !== "3 tokens") { failures.push(`benchmark prompt tokens were ${result.benchPromptTokens}`); } if (result.benchGeneratedTokens !== "2 tokens") { failures.push(`benchmark generated tokens were ${result.benchGeneratedTokens}`); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanDependencyDriftSmoke(result, modelKey, networkRequests) { assertModulePlanDriftSmoke( result, modelKey, networkRequests, "module plan dependency drift", "Module plan field module.4.depends_on was" ); const failures = []; const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; for (const stackRoute of stackRoutes) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after module plan dependency drift: ${stackRoute}`); } } const manifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const manifestRoute of manifestRoutes) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after module plan dependency drift: ${manifestRoute}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertAssemblyEvalCaseDriftSmoke(result, modelKey, networkRequests) { const failures = []; if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (result.runtimeStatus !== "Model load failed") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (result.modelState !== "assembly evidence rejected") { failures.push(`model state was ${result.modelState}`); } if (!String(result.errorState || "").includes("assembly eval case evidence checksum mismatch")) { failures.push(`error state was ${result.errorState}`); } if (!String(result.assemblyState || "").includes("assembly eval case evidence checksum mismatch")) { failures.push(`assembly state was ${result.assemblyState}`); } if (result.adapterState !== "assembly evidence rejected") { failures.push(`adapter state was ${result.adapterState}`); } if (!String(result.modulePlanTrace || "").includes("assembly evidence rejected")) { failures.push(`module plan trace was ${result.modulePlanTrace}`); } if (String(result.modulePlanTrace || "").includes("ready")) { failures.push(`module plan trace reached ready after assembly drift: ${result.modulePlanTrace}`); } if (!result.generateDisabled || !result.resetDisabled || !result.stepTokenDisabled) { failures.push("runtime controls were enabled after assembly eval-case drift"); } if (result.modelSelectDisabled) { failures.push("model selector was disabled after assembly eval-case drift"); } if (!result.diagnostics || result.diagnostics.model_loaded !== false) { failures.push(`diagnostics model_loaded was ${JSON.stringify(result.diagnostics)}`); } if (!networkIncludesPath(networkRequests, "/models/selector.registry")) { failures.push("selector registry route was not requested"); } const expectedModulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!expectedModulePlanRoute || !networkIncludesPath(networkRequests, expectedModulePlanRoute)) { failures.push(`module plan route was not requested: ${expectedModulePlanRoute}`); } const expectedModelRoute = expectedRouteForModel(modelKey); if (expectedModelRoute && !networkIncludesPath(networkRequests, expectedModelRoute)) { failures.push(`generated model route was not requested: ${expectedModelRoute}`); } const expectedAssemblyReceiptRoute = expectedAssemblyReceiptRoutes[modelKey]; if (!expectedAssemblyReceiptRoute || !networkIncludesPath(networkRequests, expectedAssemblyReceiptRoute)) { failures.push(`assembly receipt route was not requested: ${expectedAssemblyReceiptRoute}`); } for (const evidenceRoute of expectedAssemblyEvidenceRoutes[modelKey] || []) { if (networkIncludesPath(networkRequests, evidenceRoute)) { failures.push(`assembly evidence route was requested after eval-case drift: ${evidenceRoute}`); } } const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (adapterFamilyRoute && networkIncludesPath(networkRequests, adapterFamilyRoute)) { failures.push(`adapter family receipt route was requested after assembly drift: ${adapterFamilyRoute}`); } for (const stackRoute of expectedAdapterStackRoutes[modelKey] || []) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after assembly drift: ${stackRoute}`); } } for (const manifestRoute of expectedAdapterManifestRoutes[modelKey] || []) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after assembly drift: ${manifestRoute}`); } } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertAssemblyEvidenceFileDriftSmoke(result, modelKey, networkRequests) { const failures = []; if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (result.runtimeStatus !== "Model load failed") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (result.modelState !== "assembly evidence rejected") { failures.push(`model state was ${result.modelState}`); } const errorState = String(result.errorState || ""); if (!errorState.includes("assembly evidence") || !errorState.includes("checksum mismatch")) { failures.push(`error state was ${result.errorState}`); } const assemblyState = String(result.assemblyState || ""); if (!assemblyState.includes("assembly evidence") || !assemblyState.includes("checksum mismatch")) { failures.push(`assembly state was ${result.assemblyState}`); } if (result.adapterState !== "assembly evidence rejected") { failures.push(`adapter state was ${result.adapterState}`); } if (!String(result.modulePlanTrace || "").includes("assembly evidence rejected")) { failures.push(`module plan trace was ${result.modulePlanTrace}`); } if (String(result.modulePlanTrace || "").includes("ready")) { failures.push(`module plan trace reached ready after assembly evidence-file drift: ${result.modulePlanTrace}`); } if (!result.generateDisabled || !result.resetDisabled || !result.stepTokenDisabled) { failures.push("runtime controls were enabled after assembly evidence-file drift"); } if (result.modelSelectDisabled) { failures.push("model selector was disabled after assembly evidence-file drift"); } if (!result.diagnostics || result.diagnostics.model_loaded !== false) { failures.push(`diagnostics model_loaded was ${JSON.stringify(result.diagnostics)}`); } if (!networkIncludesPath(networkRequests, "/models/selector.registry")) { failures.push("selector registry route was not requested"); } const expectedModulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!expectedModulePlanRoute || !networkIncludesPath(networkRequests, expectedModulePlanRoute)) { failures.push(`module plan route was not requested: ${expectedModulePlanRoute}`); } const expectedModelRoute = expectedRouteForModel(modelKey); if (expectedModelRoute && !networkIncludesPath(networkRequests, expectedModelRoute)) { failures.push(`generated model route was not requested: ${expectedModelRoute}`); } const expectedManifestRoute = expectedModelRoute ? `${expectedModelRoute}.manifest` : ""; if (expectedManifestRoute && !networkIncludesPath(networkRequests, expectedManifestRoute)) { failures.push(`model manifest route was not requested: ${expectedManifestRoute}`); } const expectedAssemblyReceiptRoute = expectedAssemblyReceiptRoutes[modelKey]; if (!expectedAssemblyReceiptRoute || !networkIncludesPath(networkRequests, expectedAssemblyReceiptRoute)) { failures.push(`assembly receipt route was not requested: ${expectedAssemblyReceiptRoute}`); } const evidenceRoutes = expectedAssemblyEvidenceRoutes[modelKey] || []; const driftedEvidenceRoute = evidenceRoutes[0]; if (!driftedEvidenceRoute || !networkIncludesPath(networkRequests, driftedEvidenceRoute)) { failures.push(`drifted assembly evidence route was not requested: ${driftedEvidenceRoute}`); } for (const evidenceRoute of evidenceRoutes.slice(1)) { if (networkIncludesPath(networkRequests, evidenceRoute)) { failures.push(`later assembly evidence route was requested after evidence-file drift: ${evidenceRoute}`); } } const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (adapterFamilyRoute && networkIncludesPath(networkRequests, adapterFamilyRoute)) { failures.push(`adapter family receipt route was requested after assembly evidence-file drift: ${adapterFamilyRoute}`); } for (const stackRoute of expectedAdapterStackRoutes[modelKey] || []) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after assembly evidence-file drift: ${stackRoute}`); } } for (const manifestRoute of expectedAdapterManifestRoutes[modelKey] || []) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after assembly evidence-file drift: ${manifestRoute}`); } } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertAdapterFamilyReceiptDriftSmoke(result, modelKey, networkRequests) { const failures = []; if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (result.runtimeStatus !== "Ready") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (!String(result.modelState || "").startsWith("loaded")) { failures.push(`model state was ${result.modelState}`); } if (result.errorState !== "none") { failures.push(`error state was ${result.errorState}`); } if (!String(result.adapterState || "").includes("adapter family receipt checksum mismatch")) { failures.push(`adapter state was ${result.adapterState}`); } if (result.assemblyState !== "loaded") { failures.push(`assembly state was ${result.assemblyState}`); } if (result.assemblyKind !== "browser-local-assembly-evidence") { failures.push(`assembly kind was ${result.assemblyKind}`); } if (!String(result.modulePlanTrace || "").includes("assembly evidence verified")) { failures.push(`module plan trace did not reach assembly verification: ${result.modulePlanTrace}`); } if (String(result.modulePlanTrace || "").includes("adapter family verified")) { failures.push(`module plan trace reached adapter family verification after receipt drift: ${result.modulePlanTrace}`); } if (String(result.modulePlanTrace || "").includes("ready")) { failures.push(`module plan trace reached ready after adapter-family receipt drift: ${result.modulePlanTrace}`); } if (result.generateDisabled || result.resetDisabled || result.modelSelectDisabled) { failures.push("primary controls were disabled after adapter-family receipt drift"); } if (!result.stepTokenDisabled) { failures.push("step-token control was enabled before generation context"); } if (!result.adapterSelectDisabled || !result.applyDisabled) { failures.push("adapter controls were enabled after adapter-family receipt drift"); } if (!result.diagnostics || result.diagnostics.model_loaded !== true) { failures.push(`diagnostics model_loaded was ${JSON.stringify(result.diagnostics)}`); } if (String(result.console || "").includes("apply_adapter_delta")) { failures.push("console included apply_adapter_delta"); } if (!String(result.console || "").includes("adapter family receipt checksum mismatch")) { failures.push("console did not include adapter-family receipt checksum mismatch"); } if (!networkIncludesPath(networkRequests, "/models/selector.registry")) { failures.push("selector registry route was not requested"); } const expectedModulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!expectedModulePlanRoute || !networkIncludesPath(networkRequests, expectedModulePlanRoute)) { failures.push(`module plan route was not requested: ${expectedModulePlanRoute}`); } const expectedModelRoute = expectedRouteForModel(modelKey); if (expectedModelRoute && !networkIncludesPath(networkRequests, expectedModelRoute)) { failures.push(`generated model route was not requested: ${expectedModelRoute}`); } const expectedManifestRoute = expectedModelRoute ? `${expectedModelRoute}.manifest` : ""; if (expectedManifestRoute && !networkIncludesPath(networkRequests, expectedManifestRoute)) { failures.push(`model manifest route was not requested: ${expectedManifestRoute}`); } const expectedAssemblyReceiptRoute = expectedAssemblyReceiptRoutes[modelKey]; if (!expectedAssemblyReceiptRoute || !networkIncludesPath(networkRequests, expectedAssemblyReceiptRoute)) { failures.push(`assembly receipt route was not requested: ${expectedAssemblyReceiptRoute}`); } for (const evidenceRoute of expectedAssemblyEvidenceRoutes[modelKey] || []) { if (!networkIncludesPath(networkRequests, evidenceRoute)) { failures.push(`assembly evidence route was not requested before adapter-family receipt drift: ${evidenceRoute}`); } } const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (!adapterFamilyRoute || !networkIncludesPath(networkRequests, adapterFamilyRoute)) { failures.push(`adapter family receipt route was not requested: ${adapterFamilyRoute}`); } for (const manifestRoute of expectedAdapterManifestRoutes[modelKey] || []) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after adapter-family receipt drift: ${manifestRoute}`); } } for (const stackRoute of expectedAdapterStackRoutes[modelKey] || []) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after adapter-family receipt drift: ${stackRoute}`); } } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertAdapterManifestDriftSmoke(result, modelKey, networkRequests) { const failures = []; if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (result.runtimeStatus !== "Ready") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (!String(result.modelState || "").startsWith("loaded")) { failures.push(`model state was ${result.modelState}`); } if (result.errorState !== "none") { failures.push(`error state was ${result.errorState}`); } if (!String(result.adapterState || "").includes("adapter 1 manifest checksum mismatch")) { failures.push(`adapter state was ${result.adapterState}`); } if (result.assemblyState !== "loaded") { failures.push(`assembly state was ${result.assemblyState}`); } if (result.assemblyKind !== "browser-local-assembly-evidence") { failures.push(`assembly kind was ${result.assemblyKind}`); } if (!String(result.modulePlanTrace || "").includes("assembly evidence verified")) { failures.push(`module plan trace did not reach assembly verification: ${result.modulePlanTrace}`); } if (String(result.modulePlanTrace || "").includes("adapter family verified")) { failures.push(`module plan trace reached adapter family verification after manifest drift: ${result.modulePlanTrace}`); } if (String(result.modulePlanTrace || "").includes("ready")) { failures.push(`module plan trace reached ready after adapter manifest drift: ${result.modulePlanTrace}`); } if (result.generateDisabled || result.resetDisabled || result.modelSelectDisabled) { failures.push("primary controls were disabled after adapter manifest drift"); } if (!result.stepTokenDisabled) { failures.push("step-token control was enabled before generation context"); } if (!result.adapterSelectDisabled || !result.applyDisabled) { failures.push("adapter controls were enabled after adapter manifest drift"); } if (!result.diagnostics || result.diagnostics.model_loaded !== true) { failures.push(`diagnostics model_loaded was ${JSON.stringify(result.diagnostics)}`); } if (String(result.console || "").includes("apply_adapter_delta")) { failures.push("console included apply_adapter_delta"); } if (!String(result.console || "").includes("adapter 1 manifest checksum mismatch")) { failures.push("console did not include adapter manifest checksum mismatch"); } if (!networkIncludesPath(networkRequests, "/models/selector.registry")) { failures.push("selector registry route was not requested"); } const expectedModulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!expectedModulePlanRoute || !networkIncludesPath(networkRequests, expectedModulePlanRoute)) { failures.push(`module plan route was not requested: ${expectedModulePlanRoute}`); } const expectedModelRoute = expectedRouteForModel(modelKey); if (expectedModelRoute && !networkIncludesPath(networkRequests, expectedModelRoute)) { failures.push(`generated model route was not requested: ${expectedModelRoute}`); } const expectedManifestRoute = expectedModelRoute ? `${expectedModelRoute}.manifest` : ""; if (expectedManifestRoute && !networkIncludesPath(networkRequests, expectedManifestRoute)) { failures.push(`model manifest route was not requested: ${expectedManifestRoute}`); } const expectedAssemblyReceiptRoute = expectedAssemblyReceiptRoutes[modelKey]; if (!expectedAssemblyReceiptRoute || !networkIncludesPath(networkRequests, expectedAssemblyReceiptRoute)) { failures.push(`assembly receipt route was not requested: ${expectedAssemblyReceiptRoute}`); } for (const evidenceRoute of expectedAssemblyEvidenceRoutes[modelKey] || []) { if (!networkIncludesPath(networkRequests, evidenceRoute)) { failures.push(`assembly evidence route was not requested before adapter manifest drift: ${evidenceRoute}`); } } const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (!adapterFamilyRoute || !networkIncludesPath(networkRequests, adapterFamilyRoute)) { failures.push(`adapter family receipt route was not requested: ${adapterFamilyRoute}`); } const expectedManifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; const selfManifestRoute = expectedManifestRoutes[0]; const driftedManifestRoute = expectedManifestRoutes[1]; if (!selfManifestRoute || !networkIncludesPath(networkRequests, selfManifestRoute)) { failures.push(`self adapter manifest route was not requested: ${selfManifestRoute}`); } if (!driftedManifestRoute || !networkIncludesPath(networkRequests, driftedManifestRoute)) { failures.push(`drifted adapter manifest route was not requested: ${driftedManifestRoute}`); } for (const manifestRoute of expectedManifestRoutes.slice(2)) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`later adapter manifest route was requested after adapter manifest drift: ${manifestRoute}`); } } for (const stackRoute of expectedAdapterStackRoutes[modelKey] || []) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after adapter manifest drift: ${stackRoute}`); } } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } // Verifies source-backed ALR1 contract drift fails before adapter stack artifacts are fetched. function assertSourceBackedAlr1ManifestDriftSmoke(result, modelKey, networkRequests) { const failures = []; if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (result.runtimeStatus !== "Ready") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (!String(result.modelState || "").startsWith("loaded")) { failures.push(`model state was ${result.modelState}`); } if (result.errorState !== "none") { failures.push(`error state was ${result.errorState}`); } if (!String(result.adapterState || "").includes("adapter_source_base_contract")) { failures.push(`adapter state was ${result.adapterState}`); } if (result.assemblyState !== "loaded") { failures.push(`assembly state was ${result.assemblyState}`); } if (result.assemblyKind !== "browser-local-assembly-evidence") { failures.push(`assembly kind was ${result.assemblyKind}`); } if (!String(result.modulePlanTrace || "").includes("assembly evidence verified")) { failures.push(`module plan trace did not reach assembly verification: ${result.modulePlanTrace}`); } if (String(result.modulePlanTrace || "").includes("adapter family verified")) { failures.push(`module plan trace reached adapter family verification after source-backed ALR1 drift: ${result.modulePlanTrace}`); } if (String(result.modulePlanTrace || "").includes("ready")) { failures.push(`module plan trace reached ready after source-backed ALR1 drift: ${result.modulePlanTrace}`); } if (result.generateDisabled || result.resetDisabled || result.modelSelectDisabled) { failures.push("primary controls were disabled after source-backed ALR1 drift"); } if (!result.stepTokenDisabled) { failures.push("step-token control was enabled before generation context"); } if (!result.adapterSelectDisabled || !result.applyDisabled) { failures.push("adapter controls were enabled after source-backed ALR1 drift"); } if (!result.diagnostics || result.diagnostics.model_loaded !== true) { failures.push(`diagnostics model_loaded was ${JSON.stringify(result.diagnostics)}`); } const consoleText = String(result.console || ""); if (consoleText.includes("apply_adapter_delta")) { failures.push("console included apply_adapter_delta"); } if (!consoleText.includes("adapter_source_base_contract")) { failures.push("console did not include adapter_source_base_contract"); } if (!networkIncludesPath(networkRequests, "/models/selector.registry")) { failures.push("selector registry route was not requested"); } const expectedModulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!expectedModulePlanRoute || !networkIncludesPath(networkRequests, expectedModulePlanRoute)) { failures.push(`module plan route was not requested: ${expectedModulePlanRoute}`); } const expectedModelRoute = expectedRouteForModel(modelKey); if (expectedModelRoute && !networkIncludesPath(networkRequests, expectedModelRoute)) { failures.push(`generated model route was not requested: ${expectedModelRoute}`); } const expectedManifestRoute = expectedModelRoute ? `${expectedModelRoute}.manifest` : ""; if (expectedManifestRoute && !networkIncludesPath(networkRequests, expectedManifestRoute)) { failures.push(`model manifest route was not requested: ${expectedManifestRoute}`); } const expectedAssemblyReceiptRoute = expectedAssemblyReceiptRoutes[modelKey]; if (!expectedAssemblyReceiptRoute || !networkIncludesPath(networkRequests, expectedAssemblyReceiptRoute)) { failures.push(`assembly receipt route was not requested: ${expectedAssemblyReceiptRoute}`); } for (const evidenceRoute of expectedAssemblyEvidenceRoutes[modelKey] || []) { if (!networkIncludesPath(networkRequests, evidenceRoute)) { failures.push(`assembly evidence route was not requested before source-backed ALR1 drift: ${evidenceRoute}`); } } const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (!adapterFamilyRoute || !networkIncludesPath(networkRequests, adapterFamilyRoute)) { failures.push(`adapter family receipt route was not requested: ${adapterFamilyRoute}`); } const expectedManifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const manifestRoute of expectedManifestRoutes) { if (!networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was not requested before source-backed ALR1 drift: ${manifestRoute}`); } } for (const stackRoute of expectedAdapterStackRoutes[modelKey] || []) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after source-backed ALR1 drift: ${stackRoute}`); } } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertAdapterArtifactDriftSmoke(result, modelKey, networkRequests) { assertAdapterStackArtifactDriftSmoke(result, modelKey, networkRequests, 0, "adapter artifact drift"); } function assertAdapterStackPrefetchDriftSmoke(result, modelKey, networkRequests) { assertAdapterStackArtifactDriftSmoke(result, modelKey, networkRequests, 1, "adapter stack prefetch drift"); } function assertAdapterStackRustValidateDriftSmoke(result, modelKey, networkRequests) { const failures = []; if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (result.runtimeStatus !== "Adapter load failed") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (!String(result.modelState || "").startsWith("loaded")) { failures.push(`model state was ${result.modelState}`); } if (!String(result.errorState || "").includes("shape mismatch")) { failures.push(`error state was ${result.errorState}`); } if (!String(result.adapterState || "").includes("shape mismatch")) { failures.push(`adapter state was ${result.adapterState}`); } if (result.assemblyState !== "loaded") { failures.push(`assembly state was ${result.assemblyState}`); } if (result.assemblyKind !== "browser-local-assembly-evidence") { failures.push(`assembly kind was ${result.assemblyKind}`); } if (!String(result.modulePlanTrace || "").includes("adapter family verified")) { failures.push(`module plan trace did not reach adapter-family verification: ${result.modulePlanTrace}`); } if (String(result.modulePlanTrace || "").includes("adapter stack applied")) { failures.push(`module plan trace reached adapter stack after Rust validation drift: ${result.modulePlanTrace}`); } if (String(result.modulePlanTrace || "").includes("ready")) { failures.push(`module plan trace reached ready after Rust validation drift: ${result.modulePlanTrace}`); } if (result.generateDisabled || result.resetDisabled || result.modelSelectDisabled) { failures.push("primary controls were disabled after Rust validation drift"); } if (!result.stepTokenDisabled) { failures.push("step-token control was enabled before generation context"); } if (result.adapterSelectDisabled || result.applyDisabled) { failures.push("adapter controls were disabled after Rust validation drift"); } if (!result.diagnostics || result.diagnostics.model_loaded !== true) { failures.push(`diagnostics model_loaded was ${JSON.stringify(result.diagnostics)}`); } const consoleText = String(result.console || ""); if (!consoleText.includes("validate_adapter_delta")) { failures.push("console did not include validate_adapter_delta"); } if (!consoleText.includes("shape mismatch")) { failures.push("console did not include shape mismatch"); } if (consoleText.includes("apply_adapter_delta")) { failures.push("console included apply_adapter_delta"); } if (!networkIncludesPath(networkRequests, "/models/selector.registry")) { failures.push("selector registry route was not requested"); } const expectedModulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!expectedModulePlanRoute || !networkIncludesPath(networkRequests, expectedModulePlanRoute)) { failures.push(`module plan route was not requested: ${expectedModulePlanRoute}`); } const expectedModelRoute = expectedRouteForModel(modelKey); if (expectedModelRoute && !networkIncludesPath(networkRequests, expectedModelRoute)) { failures.push(`generated model route was not requested: ${expectedModelRoute}`); } const expectedManifestRoute = expectedModelRoute ? `${expectedModelRoute}.manifest` : ""; if (expectedManifestRoute && !networkIncludesPath(networkRequests, expectedManifestRoute)) { failures.push(`model manifest route was not requested: ${expectedManifestRoute}`); } const expectedAssemblyReceiptRoute = expectedAssemblyReceiptRoutes[modelKey]; if (!expectedAssemblyReceiptRoute || !networkIncludesPath(networkRequests, expectedAssemblyReceiptRoute)) { failures.push(`assembly receipt route was not requested: ${expectedAssemblyReceiptRoute}`); } for (const evidenceRoute of expectedAssemblyEvidenceRoutes[modelKey] || []) { if (!networkIncludesPath(networkRequests, evidenceRoute)) { failures.push(`assembly evidence route was not requested before Rust validation drift: ${evidenceRoute}`); } } const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (!adapterFamilyRoute || !networkIncludesPath(networkRequests, adapterFamilyRoute)) { failures.push(`adapter family receipt route was not requested: ${adapterFamilyRoute}`); } for (const manifestRoute of expectedAdapterManifestRoutes[modelKey] || []) { if (!networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was not requested before Rust validation drift: ${manifestRoute}`); } } for (const stackRoute of expectedAdapterStackRoutes[modelKey] || []) { if (!networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was not requested before Rust validation drift: ${stackRoute}`); } } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertAdapterStackArtifactDriftSmoke(result, modelKey, networkRequests, driftedStackIndex, driftLabel) { const failures = []; if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (result.runtimeStatus !== "Adapter load failed") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (!String(result.modelState || "").startsWith("loaded")) { failures.push(`model state was ${result.modelState}`); } if (!String(result.errorState || "").includes("adapter artifact checksum mismatch")) { failures.push(`error state was ${result.errorState}`); } if (!String(result.adapterState || "").includes("adapter artifact checksum mismatch")) { failures.push(`adapter state was ${result.adapterState}`); } if (result.assemblyState !== "loaded") { failures.push(`assembly state was ${result.assemblyState}`); } if (result.assemblyKind !== "browser-local-assembly-evidence") { failures.push(`assembly kind was ${result.assemblyKind}`); } if (!String(result.modulePlanTrace || "").includes("adapter family verified")) { failures.push(`module plan trace did not reach adapter-family verification: ${result.modulePlanTrace}`); } if (String(result.modulePlanTrace || "").includes("adapter stack applied")) { failures.push(`module plan trace reached adapter stack after ${driftLabel}: ${result.modulePlanTrace}`); } if (String(result.modulePlanTrace || "").includes("ready")) { failures.push(`module plan trace reached ready after ${driftLabel}: ${result.modulePlanTrace}`); } if (result.generateDisabled || result.resetDisabled || result.modelSelectDisabled) { failures.push(`primary controls were disabled after ${driftLabel}`); } if (!result.stepTokenDisabled) { failures.push("step-token control was enabled before generation context"); } if (result.adapterSelectDisabled || result.applyDisabled) { failures.push(`adapter controls were disabled after ${driftLabel}`); } if (!result.diagnostics || result.diagnostics.model_loaded !== true) { failures.push(`diagnostics model_loaded was ${JSON.stringify(result.diagnostics)}`); } if (String(result.console || "").includes("apply_adapter_delta")) { failures.push("console included apply_adapter_delta"); } if (!String(result.console || "").includes("adapter artifact checksum mismatch")) { failures.push("console did not include adapter artifact checksum mismatch"); } if (!networkIncludesPath(networkRequests, "/models/selector.registry")) { failures.push("selector registry route was not requested"); } const expectedModulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!expectedModulePlanRoute || !networkIncludesPath(networkRequests, expectedModulePlanRoute)) { failures.push(`module plan route was not requested: ${expectedModulePlanRoute}`); } const expectedModelRoute = expectedRouteForModel(modelKey); if (expectedModelRoute && !networkIncludesPath(networkRequests, expectedModelRoute)) { failures.push(`generated model route was not requested: ${expectedModelRoute}`); } const expectedManifestRoute = expectedModelRoute ? `${expectedModelRoute}.manifest` : ""; if (expectedManifestRoute && !networkIncludesPath(networkRequests, expectedManifestRoute)) { failures.push(`model manifest route was not requested: ${expectedManifestRoute}`); } const expectedAssemblyReceiptRoute = expectedAssemblyReceiptRoutes[modelKey]; if (!expectedAssemblyReceiptRoute || !networkIncludesPath(networkRequests, expectedAssemblyReceiptRoute)) { failures.push(`assembly receipt route was not requested: ${expectedAssemblyReceiptRoute}`); } for (const evidenceRoute of expectedAssemblyEvidenceRoutes[modelKey] || []) { if (!networkIncludesPath(networkRequests, evidenceRoute)) { failures.push(`assembly evidence route was not requested before ${driftLabel}: ${evidenceRoute}`); } } const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (!adapterFamilyRoute || !networkIncludesPath(networkRequests, adapterFamilyRoute)) { failures.push(`adapter family receipt route was not requested: ${adapterFamilyRoute}`); } for (const manifestRoute of expectedAdapterManifestRoutes[modelKey] || []) { if (!networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was not requested before ${driftLabel}: ${manifestRoute}`); } } const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; const driftedStackRoute = stackRoutes[driftedStackIndex]; if (!driftedStackRoute || !networkIncludesPath(networkRequests, driftedStackRoute)) { failures.push(`drifted adapter stack route was not requested: ${driftedStackRoute}`); } for (const stackRoute of stackRoutes.slice(0, driftedStackIndex + 1)) { if (!networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was not requested before ${driftLabel}: ${stackRoute}`); } } for (const stackRoute of stackRoutes.slice(driftedStackIndex + 1)) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`later adapter stack route was requested after ${driftLabel}: ${stackRoute}`); } } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModulePlanPayloadChecksumDriftSmoke(result, modelKey, networkRequests) { // Verifies coherent payload checksum drift remains bound by the module-plan checksum row. const failures = []; if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (result.runtimeStatus !== "Model load failed") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (result.modelState !== "fetch error") { failures.push(`model state was ${result.modelState}`); } if (!String(result.errorState || "").includes("module plan adapter module checksum mismatch")) { failures.push(`error state was ${result.errorState}`); } if (result.adapterState !== "model not loaded") { failures.push(`adapter state was ${result.adapterState}`); } if (result.assemblyState !== "model not loaded") { failures.push(`assembly state was ${result.assemblyState}`); } if (result.assemblyKind !== "unavailable") { failures.push(`assembly kind was ${result.assemblyKind}`); } if (String(result.modulePlanTrace || "") !== "module plan adapter module checksum mismatch") { failures.push(`module plan trace was ${result.modulePlanTrace}`); } if (!result.generateDisabled || !result.resetDisabled || !result.stepTokenDisabled) { failures.push("runtime controls were enabled after payload checksum drift"); } if (result.modelSelectDisabled) { failures.push("model selector was disabled after payload checksum drift"); } if (!result.adapterSelectDisabled || !result.applyDisabled) { failures.push("adapter controls were enabled after payload checksum drift"); } if (!result.diagnostics || result.diagnostics.model_loaded !== false) { failures.push(`diagnostics model_loaded was ${JSON.stringify(result.diagnostics)}`); } const consoleText = String(result.console || ""); if (consoleText.includes("apply_adapter_delta")) { failures.push("console included apply_adapter_delta"); } if (!networkIncludesPath(networkRequests, "/models/selector.registry")) { failures.push("selector registry route was not requested"); } const expectedModulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!expectedModulePlanRoute || !networkIncludesPath(networkRequests, expectedModulePlanRoute)) { failures.push(`module plan route was not requested: ${expectedModulePlanRoute}`); } const expectedModelRoute = expectedRouteForModel(modelKey); if (expectedModelRoute && networkIncludesPath(networkRequests, expectedModelRoute)) { failures.push(`generated model route was requested after payload checksum drift: ${expectedModelRoute}`); } const expectedManifestRoute = expectedModelRoute ? `${expectedModelRoute}.manifest` : ""; if (expectedManifestRoute && networkIncludesPath(networkRequests, expectedManifestRoute)) { failures.push(`model manifest route was requested after payload checksum drift: ${expectedManifestRoute}`); } const expectedAssemblyReceiptRoute = expectedAssemblyReceiptRoutes[modelKey]; if (expectedAssemblyReceiptRoute && networkIncludesPath(networkRequests, expectedAssemblyReceiptRoute)) { failures.push(`assembly receipt route was requested after payload checksum drift: ${expectedAssemblyReceiptRoute}`); } for (const evidenceRoute of expectedAssemblyEvidenceRoutes[modelKey] || []) { if (networkIncludesPath(networkRequests, evidenceRoute)) { failures.push(`assembly evidence route was requested after payload checksum drift: ${evidenceRoute}`); } } const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (adapterFamilyRoute && networkIncludesPath(networkRequests, adapterFamilyRoute)) { failures.push(`adapter family receipt route was requested after payload checksum drift: ${adapterFamilyRoute}`); } for (const manifestRoute of expectedAdapterManifestRoutes[modelKey] || []) { if (networkIncludesPath(networkRequests, manifestRoute)) { failures.push(`adapter manifest route was requested after payload checksum drift: ${manifestRoute}`); } } const stackRoutes = expectedAdapterStackRoutes[modelKey] || []; for (const stackRoute of stackRoutes) { if (networkIncludesPath(networkRequests, stackRoute)) { failures.push(`adapter stack route was requested after payload checksum drift: ${stackRoute}`); } } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertRuntimeAssemblyDiagnostics(diagnostics, expectedApplyCount, label, failures) { const source = diagnostics || {}; if (source.adapter_apply_count !== expectedApplyCount) { failures.push(`${label} adapter apply count was ${source.adapter_apply_count}`); } if (expectedApplyCount === 0) { if (source.last_adapter_checksum !== "0x0000000000000000") { failures.push(`${label} adapter checksum was ${source.last_adapter_checksum}`); } } else if (!isNonZeroHex64(source.last_adapter_checksum)) { failures.push(`${label} adapter checksum was ${source.last_adapter_checksum}`); } if (!isNonZeroHex64(source.assembly_state_checksum)) { failures.push(`${label} assembly checksum was ${source.assembly_state_checksum}`); } } function assertModulePlanRuntimeResetBeforeAssembly(result, modelKey, failures) { // Keeps generated model loads from carrying prompt state into verified assembly/adapters. const consoleText = String(result.consoleBeforeGenerate || result.console || ""); const resetIndex = consoleText.indexOf(`reset_context(${modelKey}) -> 0`); if (resetIndex < 0) { failures.push(`module plan runtime reset log was missing for ${modelKey}`); return; } const assemblyMarkers = [ consoleText.indexOf("validate_adapter_delta"), consoleText.indexOf("apply_adapter_delta"), consoleText.indexOf("adapter_stack_applied") ].filter((index) => index >= 0); if (assemblyMarkers.length > 0 && resetIndex > Math.min(...assemblyMarkers)) { failures.push(`module plan runtime reset happened after assembly work for ${modelKey}`); } } function assertAdapterSidecarSmoke(result, modelKey, networkRequests, expectAutoAssembly, options = {}) { const failures = []; const checkExactModulePlanSummaries = options.checkExactModulePlanSummaries !== false; if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (result.runtimeStatus !== "Ready") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (!String(result.modelState || "").startsWith("loaded")) { failures.push(`model state was ${result.modelState}`); } if (result.errorState !== "none") { failures.push(`error state was ${result.errorState}`); } const expectedLabels = expectedAdapterLabels[modelKey] || ["Tiny Fixture f32 self ADP1"]; if (!Array.isArray(result.adapterOptions) || result.adapterOptions.length !== expectedLabels.length) { failures.push(`adapter options were ${JSON.stringify(result.adapterOptions)}`); } else { for (let index = 0; index < expectedLabels.length; index += 1) { if (result.adapterOptions[index].label !== expectedLabels[index]) { failures.push(`adapter option ${index} label was ${result.adapterOptions[index].label}`); } } } const expectedApplyIndex = expectedAdapterApplyIndexes[modelKey] || 0; if (result.selectedAdapterBeforeApply !== String(expectedApplyIndex)) { failures.push(`selected adapter index was ${result.selectedAdapterBeforeApply}`); } const modelOptionValues = Array.isArray(result.modelOptions) ? result.modelOptions.map((option) => option.value) : []; const combinedModelFamily = combinedSelectorModelsFor(modelKey); const hasCombinedGeneratedOptions = combinedModelFamily.every((option) => modelOptionValues.includes(option)); if (hasCombinedGeneratedOptions && result.initialSelectedModel !== combinedModelFamily[0]) { failures.push(`combined selector default was ${result.initialSelectedModel}`); } if (result.adapterSelectDisabledBefore || result.applyDisabledBefore) { failures.push("adapter controls were disabled before apply"); } if (result.generateDisabledAfterApply || result.applyDisabledAfterApply) { failures.push("primary adapter controls were disabled after apply"); } if (result.adapterState !== "applied") { failures.push(`adapter state was ${result.adapterState}`); } const expectedMode = expectedQuantization[modelKey] || "f32"; if (expectAutoAssembly) { const consoleBeforeGenerate = String(result.consoleBeforeGenerate || ""); const validateCalls = consoleBeforeGenerate.match(/validate_adapter_delta/g) || []; const applyCalls = String(result.consoleBeforeGenerate || "").match(/apply_adapter_delta/g) || []; const expectedStackRoutes = expectedAdapterStackRoutes[modelKey] || []; if (validateCalls.length < Math.max(1, expectedStackRoutes.length)) { failures.push("pre-generation console did not include validate_adapter_delta"); } const observedValidateCount = Number.isInteger(result.validateCallsSincePreviousStep) ? result.validateCallsSincePreviousStep : validateCalls.length; if (expectedStackRoutes.length > 1 && observedValidateCount !== expectedModulePlanAdapterValidationCountValue) { failures.push(`pre-generation validate count was ${observedValidateCount}`); } if (applyCalls.length < Math.max(1, expectedStackRoutes.length)) { failures.push("pre-generation console did not include apply_adapter_delta"); } const lastApply = consoleBeforeGenerate.lastIndexOf("apply_adapter_delta"); const lastValidate = consoleBeforeGenerate.lastIndexOf("validate_adapter_delta"); if (lastApply < 0 || lastValidate < 0 || lastValidate > lastApply) { failures.push("pre-generation adapter validation did not finish before apply"); } if (expectedStackRoutes.length > 1 && !String(result.consoleBeforeGenerate || "").includes(`adapter_stack_applied(${expectedStackRoutes.length})`)) { failures.push("pre-generation console did not include adapter stack completion"); } if (!result.autoAppliedBeforeGenerate) { failures.push(`auto assembly state before generation was ${result.adapterStateBeforeGenerate}`); } if (result.response !== "e") { failures.push(`response was ${JSON.stringify(result.response)}`); } if (result.stepDisabledAfterGenerate) { failures.push("step-token control was disabled after assembled generation"); } const reset = result.diagnosticsBeforeGenerate || {}; if (reset.last_error !== "ok" || reset.active_quantization_mode !== expectedMode) { failures.push(`auto-assembly diagnostics were ${JSON.stringify(reset)}`); } if (reset.generated_token_count !== 0 || reset.kv_cache_length !== 0 || reset.selected_next_token !== 0) { failures.push(`auto-assembly reset diagnostics were ${JSON.stringify(reset)}`); } assertRuntimeAssemblyDiagnostics( reset, expectedModulePlanAdapterApplyCountValue, "auto-assembly reset diagnostics", failures ); const generated = result.afterGenerateDiagnostics || {}; if (generated.generated_token_count !== 1 || generated.kv_cache_length < 1) { failures.push(`assembled generation diagnostics were ${JSON.stringify(generated)}`); } if (generated.active_quantization_mode !== expectedMode) { failures.push(`assembled generation quantization mode was ${generated.active_quantization_mode}`); } assertRuntimeAssemblyDiagnostics( generated, expectedModulePlanAdapterApplyCountValue, "assembled generation diagnostics", failures ); } else { if (!String(result.console || "").includes("apply_adapter_delta")) { failures.push("console did not include apply_adapter_delta"); } if (result.stepDisabledBeforeApply) { failures.push("step-token control was disabled before adapter apply"); } if (!result.stepDisabledAfterApply) { failures.push("step-token control stayed enabled after adapter apply"); } if (result.response !== "adapter applied") { failures.push(`response was ${JSON.stringify(result.response)}`); } const before = result.beforeApplyDiagnostics || {}; const after = result.afterApplyDiagnostics || {}; if (before.generated_token_count !== 1 || before.kv_cache_length < 1) { failures.push(`pre-apply diagnostics were ${JSON.stringify(before)}`); } if (after.last_error !== "ok") { failures.push(`post-apply last_error was ${after.last_error}`); } if (after.active_quantization_mode !== expectedMode) { failures.push(`post-apply quantization mode was ${after.active_quantization_mode}`); } if (after.generated_token_count !== 0 || after.kv_cache_length !== 0 || after.selected_next_token !== 0) { failures.push(`post-apply reset diagnostics were ${JSON.stringify(after)}`); } assertRuntimeAssemblyDiagnostics(after, 1, "post-apply diagnostics", failures); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } const expectsEvalProof = isGeneratedMultiParentModel(modelKey) || result.provenanceGenome !== "unavailable" || result.provenanceSpecies !== "unavailable" || result.provenanceNovelty !== "unavailable" || result.provenancePopulation !== "unavailable" || result.provenanceMateSelection !== "unavailable" || result.provenanceSchedule !== "unavailable" || result.provenancePhenotype !== "unavailable" || result.provenanceArtifact !== "unavailable" || result.provenanceFitness !== "unavailable" || result.provenanceEvalCases !== "unavailable" || result.provenanceEvalChecksum !== "unavailable"; if (expectsEvalProof) { if (!isHex64(result.provenanceGenome)) { failures.push(`provenance genome was ${result.provenanceGenome}`); } if (!isSpeciesFitSummary(result.provenanceSpecies)) { failures.push(`provenance species was ${result.provenanceSpecies}`); } if (!isNoveltySummary(result.provenanceNovelty)) { failures.push(`provenance novelty was ${result.provenanceNovelty}`); } if (!isPopulationSummary(result.provenancePopulation)) { failures.push(`provenance population was ${result.provenancePopulation}`); } if (!isMateSelectionSummary(result.provenanceMateSelection)) { failures.push(`provenance mate selection was ${result.provenanceMateSelection}`); } if ( isGeneratedMultiParentModel(modelKey) && !String(result.provenanceMateSelection || "").startsWith("parent-pool-bound / 3 parents / ") ) { failures.push(`provenance mate selection route was ${result.provenanceMateSelection}`); } const expectedOperatorKind = expectedOperatorKindForModel(modelKey); if ( isGeneratedMultiParentModel(modelKey) && !isOperatorReceiptSummary(result.provenanceOperator, expectedOperatorKind) ) { failures.push(`provenance operator was ${result.provenanceOperator}`); } const expectedSchedule = expectedEvolutionScheduleForModel(modelKey); if ( isGeneratedMultiParentModel(modelKey) && !isEvolutionScheduleSummary(result.provenanceSchedule, expectedSchedule) ) { failures.push(`provenance schedule was ${result.provenanceSchedule}`); } if (!isPhenotypeEvidenceSummary(result.provenancePhenotype)) { failures.push(`provenance phenotype was ${result.provenancePhenotype}`); } if (!isHeritableArtifactSummary(result.provenanceArtifact)) { failures.push(`provenance artifact was ${result.provenanceArtifact}`); } if (!isFitnessVectorSummary(result.provenanceFitness)) { failures.push(`provenance fitness was ${result.provenanceFitness}`); } if (result.provenanceEvalCases !== "1 passed") { failures.push(`provenance eval cases were ${result.provenanceEvalCases}`); } if (!isHex64(result.provenanceEvalChecksum)) { failures.push(`provenance eval checksum was ${result.provenanceEvalChecksum}`); } } else if ( result.provenanceGenome !== "unavailable" || result.provenanceSpecies !== "unavailable" || result.provenanceNovelty !== "unavailable" || result.provenancePopulation !== "unavailable" || result.provenanceMateSelection !== "unavailable" || result.provenanceSchedule !== "unavailable" || result.provenancePhenotype !== "unavailable" || result.provenanceArtifact !== "unavailable" || result.provenanceFitness !== "unavailable" || result.provenanceEvalCases !== "unavailable" || result.provenanceEvalChecksum !== "unavailable" ) { failures.push( `manual model eval proof was ${result.provenanceGenome}/${result.provenanceSpecies}/${result.provenanceNovelty}/${result.provenancePopulation}/${result.provenanceMateSelection}/${result.provenanceSchedule}/${result.provenancePhenotype}/${result.provenanceArtifact}/${result.provenanceFitness}/${result.provenanceEvalCases}/${result.provenanceEvalChecksum}` ); } const expectedAdapterRoute = expectedAdapterRoutes[modelKey] || "/models/tiny-test-model-self.adp1"; if (!networkIncludesPath(networkRequests, expectedAdapterRoute)) { failures.push("adapter sidecar route was not requested"); } for (const expectedStackRoute of expectedAdapterStackRoutes[modelKey] || []) { if (!networkIncludesPath(networkRequests, expectedStackRoute)) { failures.push(`adapter stack route was not requested: ${expectedStackRoute}`); } } const expectedReceiptRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (expectedReceiptRoute && !networkRequests.some((requestUrl) => requestUrl.includes(expectedReceiptRoute))) { failures.push("adapter family receipt route was not requested"); } const expectedAssemblyReceiptRoute = expectedAssemblyReceiptRoutes[modelKey]; if (expectedAssemblyReceiptRoute) { if (!networkRequests.some((requestUrl) => requestUrl.includes(expectedAssemblyReceiptRoute))) { failures.push("assembly receipt route was not requested"); } if (result.assemblyState !== "loaded") { failures.push(`assembly state was ${result.assemblyState}`); } if (result.assemblyKind !== "browser-local-assembly-evidence") { failures.push(`assembly kind was ${result.assemblyKind}`); } if (result.assemblyParents !== "3") { failures.push(`assembly parents were ${result.assemblyParents}`); } if (!/^0x[0-9a-fA-F]{16}$/.test(String(result.assemblyOperator || ""))) { failures.push(`assembly operator checksum was ${result.assemblyOperator}`); } if (!/^0x[0-9a-fA-F]{16}$/.test(String(result.assemblyLedger || ""))) { failures.push(`assembly ledger checksum was ${result.assemblyLedger}`); } if (result.assemblyNextGate !== "browser-selector-registry-route-binding") { failures.push(`assembly next gate was ${result.assemblyNextGate}`); } for (const expectedEvidenceRoute of expectedAssemblyEvidenceRoutes[modelKey] || []) { if (!networkRequests.some((requestUrl) => requestUrl.includes(expectedEvidenceRoute))) { failures.push(`assembly evidence route was not requested: ${expectedEvidenceRoute}`); } } } const expectedModulePlanRoute = expectedModulePlanRoutes[modelKey]; if (expectedModulePlanRoute && !networkRequests.some((requestUrl) => requestUrl.includes(expectedModulePlanRoute))) { failures.push("module plan route was not requested"); } if (expectedModulePlanRoute) { if (result.modulePlanState !== "loaded") { failures.push(`module plan state was ${result.modulePlanState}`); } if (result.modulePlanKind !== "browser-local-module-plan") { failures.push(`module plan kind was ${result.modulePlanKind}`); } if (result.modulePlanResource !== "browser-constrained-local-assembly") { failures.push(`module plan resource was ${result.modulePlanResource}`); } if (result.modulePlanExecution !== expectedModulePlanExecutionProfile) { failures.push(`module plan execution profile was ${result.modulePlanExecution}`); } if (result.modulePlanFetch !== expectedModulePlanFetchPolicy) { failures.push(`module plan fetch policy was ${result.modulePlanFetch}`); } if (result.modulePlanOrigin !== expectedModulePlanOriginPolicy) { failures.push(`module plan origin policy was ${result.modulePlanOrigin}`); } if (result.modulePlanFetchLimit !== expectedModulePlanFetchLimit) { failures.push(`module plan fetch limit was ${result.modulePlanFetchLimit}`); } if (result.modulePlanPlannedFetchCount !== expectedModulePlanPlannedFetches) { failures.push(`module plan planned fetch count was ${result.modulePlanPlannedFetchCount}`); } if (result.modulePlanActualFetchCount !== expectedModulePlanPlannedFetches) { failures.push(`module plan actual fetch count was ${result.modulePlanActualFetchCount}`); } if (result.modulePlanRouteSetVersion !== expectedModulePlanRouteSetVersion) { failures.push(`module plan route set version was ${result.modulePlanRouteSetVersion}`); } if (result.modulePlanRouteSetChecksumAlgorithm !== expectedModulePlanRouteSetChecksumAlgorithm) { failures.push(`module plan route set checksum algorithm was ${result.modulePlanRouteSetChecksumAlgorithm}`); } if (!isNonZeroHex64(result.modulePlanRouteSetChecksum)) { failures.push(`module plan route set checksum was ${result.modulePlanRouteSetChecksum}`); } if (result.modulePlanActualRouteSetChecksum !== result.modulePlanRouteSetChecksum) { failures.push(`module plan actual route set checksum was ${result.modulePlanActualRouteSetChecksum}`); } if (result.modulePlanWasmPages !== expectedModulePlanWasmMemoryInitialPages) { failures.push(`module plan WASM pages was ${result.modulePlanWasmPages}`); } if (result.modulePlanWasmExportSet !== expectedModulePlanWasmExportSet) { failures.push(`module plan WASM ABI was ${result.modulePlanWasmExportSet}`); } if (result.modulePlanWasmTransferStrategy !== expectedModulePlanWasmTransferStrategy) { failures.push(`module plan WASM transfer strategy was ${result.modulePlanWasmTransferStrategy}`); } if (result.modulePlanModelReleaseStrategy !== expectedModulePlanModelReleaseStrategy) { failures.push(`module plan model release strategy was ${result.modulePlanModelReleaseStrategy}`); } if (result.modulePlanRuntimeResetStrategy !== expectedModulePlanRuntimeResetStrategy) { failures.push(`module plan runtime reset strategy was ${result.modulePlanRuntimeResetStrategy}`); } if (result.modulePlanAdapterValidationStrategy !== expectedModulePlanAdapterValidationStrategy) { failures.push(`module plan adapter validation strategy was ${result.modulePlanAdapterValidationStrategy}`); } if (result.modulePlanAdapterValidationCount !== expectedModulePlanAdapterValidationCount) { failures.push(`module plan adapter validation count was ${result.modulePlanAdapterValidationCount}`); } if (result.modulePlanAdapterApplyCount !== expectedModulePlanAdapterApplyCount) { failures.push(`module plan adapter apply count was ${result.modulePlanAdapterApplyCount}`); } assertModulePlanRuntimeResetBeforeAssembly(result, modelKey, failures); if (result.modulePlanWasmHeapMinBytes !== expectedModulePlanWasmHeapMinBytes) { failures.push(`module plan WASM heap floor was ${result.modulePlanWasmHeapMinBytes}`); } if (result.modulePlanContextTokens !== expectedModulePlanContextTokens) { failures.push(`module plan context tokens was ${result.modulePlanContextTokens}`); } if (result.modulePlanSamplerCap !== expectedModulePlanSamplerCap) { failures.push(`module plan sampler cap was ${result.modulePlanSamplerCap}`); } if (!isNonZeroHex64(result.modulePlanTokenizer)) { failures.push(`module plan tokenizer checksum was ${result.modulePlanTokenizer}`); } const expectedModuleCount = String(4 + (expectedAdapterStackRoutes[modelKey] || []).length); if (result.modulePlanModules !== expectedModuleCount) { failures.push(`module plan module count was ${result.modulePlanModules}`); } const expectedModelBudget = expectedModulePlanModelBudgets[modelKey]; if (expectedModelBudget && result.modulePlanModelBudget !== expectedModelBudget) { failures.push(`module plan model budget was ${result.modulePlanModelBudget}`); } if (result.modulePlanAdapterBudget !== "1048576 bytes") { failures.push(`module plan adapter budget was ${result.modulePlanAdapterBudget}`); } if (result.modulePlanAdapterStackBudget !== expectedModulePlanAdapterStackBudget) { failures.push(`module plan adapter stack budget was ${result.modulePlanAdapterStackBudget}`); } if (result.modulePlanScratchBudget !== "65536 bytes") { failures.push(`module plan scratch budget was ${result.modulePlanScratchBudget}`); } if (result.modulePlanPromptLimit !== expectedModulePlanPromptLimit) { failures.push(`module plan prompt limit was ${result.modulePlanPromptLimit}`); } if (result.modulePlanOutputLimit !== "65536 bytes") { failures.push(`module plan output limit was ${result.modulePlanOutputLimit}`); } if (result.modulePlanKvCacheBudget !== expectedModulePlanKvCacheBudget) { failures.push(`module plan KV cache budget was ${result.modulePlanKvCacheBudget}`); } if (result.modulePlanKvCachePages !== expectedModulePlanKvCachePages) { failures.push(`module plan KV cache pages was ${result.modulePlanKvCachePages}`); } if (checkExactModulePlanSummaries) { const expectedTotalBudget = expectedModulePlanTotalBudgets[modelKey]; if (expectedTotalBudget && result.modulePlanTotalBudget !== expectedTotalBudget) { failures.push(`module plan total budget was ${result.modulePlanTotalBudget}`); } const expectedTotalLimit = expectedModulePlanTotalLimits[modelKey]; if (expectedTotalLimit && result.modulePlanTotalLimit !== expectedTotalLimit) { failures.push(`module plan total limit was ${result.modulePlanTotalLimit}`); } const expectedBytes = expectedModulePlanBytes[modelKey]; if (expectedBytes && result.modulePlanBytes !== expectedBytes) { failures.push(`module plan bytes were ${result.modulePlanBytes}`); } const expectedChecksums = expectedModulePlanChecksums[modelKey]; if (expectedChecksums && result.modulePlanChecksums !== expectedChecksums) { failures.push(`module plan checksums were ${result.modulePlanChecksums}`); } } else { if (!/^\d+ bytes$/.test(String(result.modulePlanTotalBudget || ""))) { failures.push(`module plan total budget was ${result.modulePlanTotalBudget}`); } if (!/^\d+ bytes$/.test(String(result.modulePlanTotalLimit || ""))) { failures.push(`module plan total limit was ${result.modulePlanTotalLimit}`); } if (!/^0: \d+ bytes, 1: \d+ bytes, 2: \d+ bytes, 3: \d+ bytes, 4: \d+ bytes, 5: \d+ bytes, 6: \d+ bytes$/.test(String(result.modulePlanBytes || ""))) { failures.push(`module plan bytes were ${result.modulePlanBytes}`); } if (!/^0: 0x[0-9a-fA-F]{16}, 1: 0x[0-9a-fA-F]{16}, 2: 0x[0-9a-fA-F]{16}, 3: 0x[0-9a-fA-F]{16}, 4: 0x[0-9a-fA-F]{16}, 5: 0x[0-9a-fA-F]{16}, 6: 0x[0-9a-fA-F]{16}$/.test(String(result.modulePlanChecksums || ""))) { failures.push(`module plan checksums were ${result.modulePlanChecksums}`); } } const expectedActualModuleBytes = modulePlanByteSummaryTotal(result.modulePlanBytes); if (!expectedActualModuleBytes) { failures.push(`module plan actual module bytes could not be derived from ${result.modulePlanBytes}`); } else if (result.modulePlanActualModuleBytes !== expectedActualModuleBytes) { failures.push(`module plan actual module bytes were ${result.modulePlanActualModuleBytes}`); } const expectedRenderedTotalBudget = modulePlanExpectedTotalBudget(result); if (!expectedRenderedTotalBudget) { failures.push(`module plan total budget could not be derived from ${result.modulePlanBytes}`); } else if (result.modulePlanTotalBudget !== expectedRenderedTotalBudget) { failures.push(`module plan total budget was ${result.modulePlanTotalBudget}`); } if (result.modulePlanActualModuleChecksums !== result.modulePlanChecksums) { failures.push(`module plan actual module checksums were ${result.modulePlanActualModuleChecksums}`); } if (result.modulePlanSlots !== expectedModulePlanSlots) { failures.push(`module plan slots were ${result.modulePlanSlots}`); } if (result.modulePlanRoles !== expectedModulePlanRoles) { failures.push(`module plan roles were ${result.modulePlanRoles}`); } if (result.modulePlanPhases !== expectedModulePlanPhases) { failures.push(`module plan phases were ${result.modulePlanPhases}`); } if (result.modulePlanDepends !== expectedModulePlanDependencies) { failures.push(`module plan dependencies were ${result.modulePlanDepends}`); } if (result.modulePlanTrace !== expectedModulePlanTrace) { failures.push(`module plan trace was ${result.modulePlanTrace}`); } const expectedModelRoute = expectedRouteForModel(modelKey); if (expectedModelRoute && result.modulePlanModel !== `..${expectedModelRoute}`) { failures.push(`module plan model route was ${result.modulePlanModel}`); } for (const expectedStackRoute of expectedAdapterStackRoutes[modelKey] || []) { if (!String(result.modulePlanStack || "").includes(`..${expectedStackRoute}`)) { failures.push(`module plan stack did not include ${expectedStackRoute}: ${result.modulePlanStack}`); } } } const expectedManifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; for (const expectedManifestRoute of expectedManifestRoutes) { if (!networkRequests.some((requestUrl) => requestUrl.includes(expectedManifestRoute))) { failures.push(`adapter manifest route was not requested: ${expectedManifestRoute}`); } } const expectedModelRoute = expectedRouteForModel(modelKey); if (expectedModelRoute && !networkRequests.some((requestUrl) => requestUrl.includes(expectedModelRoute))) { failures.push("adapter model route was not requested"); } if (isGeneratedMultiParentModel(modelKey) && !networkRequests.some((requestUrl) => requestUrl.includes("/models/selector.registry"))) { failures.push("selector registry route was not requested"); } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function combinedSelectorSequence(cycles) { const sequence = []; for (let cycle = 0; cycle < cycles; cycle += 1) { for (const modelKey of combinedSelectorModels) { sequence.push(modelKey); } } return sequence; } function assertCombinedSelectorSequenceSmoke(result, networkRequests, expectedSequence, failures, options = {}) { const checkActualFetchBudget = options.checkActualFetchBudget !== false; if (result.initialSelectedModel !== combinedSelectorModels[0]) { failures.push(`combined selector default was ${result.initialSelectedModel}`); } const optionValues = Array.isArray(result.modelOptions) ? result.modelOptions.map((option) => option.value) : []; for (const modelKey of combinedSelectorModels) { if (!optionValues.includes(modelKey)) { failures.push(`combined selector option was missing: ${modelKey}`); } } if (optionValues.length !== combinedSelectorModels.length) { failures.push(`combined selector options were ${JSON.stringify(result.modelOptions)}`); } if (!Array.isArray(result.steps) || result.steps.length !== expectedSequence.length) { failures.push(`combined selector steps were ${JSON.stringify(result.steps)}`); } else { for (let index = 0; index < expectedSequence.length; index += 1) { const modelKey = expectedSequence[index]; const step = result.steps[index]; if (!step || step.modelKey !== modelKey) { failures.push(`combined selector step ${index} was ${JSON.stringify(step)}`); continue; } try { assertAdapterSidecarSmoke(step, modelKey, networkRequests, true, options); } catch (error) { failures.push(`${modelKey}: ${error.message}`); } const planRoute = expectedModulePlanRoutes[modelKey]; const modelRoute = expectedRouteForModel(modelKey); const planIndex = networkPathIndex(networkRequests, planRoute); const modelIndex = networkPathIndex(networkRequests, modelRoute); if (planIndex < 0) { failures.push(`module plan route was not requested for ${modelKey}: ${planRoute}`); } if (modelIndex < 0) { failures.push(`model route was not requested for ${modelKey}: ${modelRoute}`); } if (planIndex >= 0 && modelIndex >= 0 && planIndex > modelIndex) { failures.push(`model bytes were requested before module plan for ${modelKey}`); } for (const stackRoute of expectedAdapterStackRoutes[modelKey] || []) { const stackIndex = networkPathIndex(networkRequests, stackRoute); if (stackIndex < 0) { failures.push(`adapter stack route was not requested for ${modelKey}: ${stackRoute}`); } else if (planIndex >= 0 && stackIndex < planIndex) { failures.push(`adapter stack route was requested before module plan for ${modelKey}: ${stackRoute}`); } } } } if (checkActualFetchBudget) { for (const modelKey of combinedSelectorModels) { const passes = expectedSequence.filter((expectedModel) => expectedModel === modelKey).length; if (passes > 0) { assertModulePlanActualFetchBudget(modelKey, networkRequests, passes, failures); } } } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } } function assertCombinedSelectorAssemblySmoke(result, networkRequests) { // Fresh all-root bundles regenerate receipt and evidence checksums, so prove the self-assembly shape. const failures = []; assertCombinedSelectorSequenceSmoke(result, networkRequests, combinedSelectorSequence(1), failures, { checkExactModulePlanSummaries: false }); if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertCombinedSelectorOperatorFamilySmoke(result, networkRequests) { // Proves one selector registry can self-assemble both parent-pool operator families. const failures = []; assertCombinedSelectorSequenceSmoke(result, networkRequests, combinedSelectorSequence(1), failures, { checkExactModulePlanSummaries: false }); const stepKeys = Array.isArray(result.steps) ? result.steps.map((step) => step.modelKey) : []; if (!stepKeys.some((modelKey) => modelKey.startsWith("multi-parent-sign-merge-"))) { failures.push("mixed selector did not assemble a sign-merge entry"); } if (!stepKeys.some((modelKey) => modelKey.startsWith("multi-parent-soup-"))) { failures.push("mixed selector did not assemble a soup entry"); } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertCombinedSelectorOperatorFamilyCycleSmoke(result, networkRequests, cycles) { // Reuses the cycle proof across both parent-pool families in one selector lifetime. assertCombinedSelectorCycleSmoke(result, networkRequests, cycles); const failures = []; const stepKeys = Array.isArray(result.steps) ? result.steps.map((step) => step.modelKey) : []; const signMergeSteps = stepKeys.filter((modelKey) => modelKey.startsWith("multi-parent-sign-merge-")).length; const soupSteps = stepKeys.filter((modelKey) => modelKey.startsWith("multi-parent-soup-")).length; const expectedFamilySteps = 3 * cycles; if (signMergeSteps !== expectedFamilySteps) { failures.push(`sign-merge cycle steps were ${signMergeSteps}; expected ${expectedFamilySteps}`); } if (soupSteps !== expectedFamilySteps) { failures.push(`soup cycle steps were ${soupSteps}; expected ${expectedFamilySteps}`); } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertCombinedSelectorCycleSmoke(result, networkRequests, cycles) { const failures = []; const expectedSequence = combinedSelectorSequence(cycles); assertCombinedSelectorSequenceSmoke(result, networkRequests, expectedSequence, failures, { checkExactModulePlanSummaries: false }); if (result.cycles !== cycles) { failures.push(`combined selector cycle count was ${result.cycles}`); } if (Array.isArray(result.expectedSequence) && result.expectedSequence.join("|") !== expectedSequence.join("|")) { failures.push(`combined selector expected sequence was ${JSON.stringify(result.expectedSequence)}`); } if (Array.isArray(result.steps)) { for (let index = 0; index < result.steps.length; index += 1) { const step = result.steps[index]; const expectedModel = expectedSequence[index]; if (!step || step.modelKey !== expectedModel) { continue; } const expectedStackCount = (expectedAdapterStackRoutes[expectedModel] || []).length; if (step.passIndex !== index) { failures.push(`${expectedModel} pass index was ${step.passIndex}`); } if (step.cycleIndex !== Math.floor(index / combinedSelectorModels.length)) { failures.push(`${expectedModel} cycle index was ${step.cycleIndex}`); } if (index === 0) { if (step.freeCallsSincePreviousStep !== 0) { failures.push(`${expectedModel} initial free delta was ${step.freeCallsSincePreviousStep}`); } } else { if (step.freeCallsSincePreviousStep !== 1) { failures.push(`${expectedModel} free delta was ${step.freeCallsSincePreviousStep}`); } if (step.lastFreeIndexSincePreviousStep < 0) { failures.push(`${expectedModel} did not record free_model before assembly`); } if ( step.firstValidateIndexSincePreviousStep >= 0 && step.lastFreeIndexSincePreviousStep > step.firstValidateIndexSincePreviousStep ) { failures.push(`${expectedModel} free_model was recorded after validation`); } } if (step.validateCallsSincePreviousStep !== expectedModulePlanAdapterValidationCountValue) { failures.push(`${expectedModel} validation delta was ${step.validateCallsSincePreviousStep}`); } if (step.applyCallsSincePreviousStep < expectedStackCount) { failures.push(`${expectedModel} apply delta was ${step.applyCallsSincePreviousStep}`); } if (step.stackCompletionsSincePreviousStep < 1) { failures.push(`${expectedModel} stack completion delta was ${step.stackCompletionsSincePreviousStep}`); } } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function expectedSelfAssemblyRoutes(modelKey) { const modelRoute = expectedRouteForModel(modelKey); return [ expectedModulePlanRoutes[modelKey], modelRoute, modelRoute ? `${modelRoute}.manifest` : null, expectedAssemblyReceiptRoutes[modelKey], ...(expectedAssemblyEvidenceRoutes[modelKey] || []), expectedAdapterFamilyReceiptRoutes[modelKey], ...(expectedAdapterManifestRoutes[modelKey] || []), ...(expectedAdapterStackRoutes[modelKey] || []) ].filter(Boolean); } // Counts actual generated self-assembly requests owned by one module-plan model key. function modulePlanGovernedRequestCount(networkRequests, modelKey) { return networkRequests.filter((requestUrl) => { const pathname = requestUrlPath(requestUrl); return ( pathname === `/models/${modelKey}.module-plan.receipt` || pathname === `/models/${modelKey}.slm` || pathname === `/models/${modelKey}.slm.manifest` || pathname === `/models/${modelKey}.assembly.receipt` || pathname === `/models/${modelKey}.adapter-family.receipt` || pathname.startsWith(`/models/${modelKey}-`) || pathname.startsWith(`/evidence/${modelKey}/`) ); }).length; } // Binds the exact planned route count and 32-fetch envelope to observed generated routes. function assertModulePlanActualFetchBudget(modelKey, networkRequests, passes, failures) { const expectedPerPass = expectedSelfAssemblyRoutes(modelKey).length; if (expectedPerPass !== expectedModulePlanActualFetches) { failures.push(`${modelKey} expected route fixture count was ${expectedPerPass}`); } const expectedTotal = expectedPerPass * passes; const plannedTotal = expectedModulePlanActualFetches * passes; if (expectedTotal !== plannedTotal) { failures.push(`${modelKey} planned governed request count was ${plannedTotal}; expected ${expectedTotal}`); } const observedTotal = modulePlanGovernedRequestCount(networkRequests, modelKey); if (observedTotal !== expectedTotal) { failures.push(`${modelKey} governed request count was ${observedTotal}; expected ${expectedTotal}`); } const allowedTotal = expectedModulePlanFetchLimitCount * passes; if (observedTotal > allowedTotal) { failures.push(`${modelKey} governed request count ${observedTotal} exceeded ${allowedTotal}`); } } function assertCombinedSelectorRouteSoakSmoke(result, networkRequests, cycles) { assertCombinedSelectorCycleSmoke(result, networkRequests, cycles); const failures = []; for (const modelKey of combinedSelectorModels) { for (const route of expectedSelfAssemblyRoutes(modelKey)) { const count = networkPathCount(networkRequests, route); if (count < cycles) { failures.push(`${modelKey} route ${route} was requested ${count} times for ${cycles} passes`); } } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } // Checks that independent page lifetimes rebuild generated assembly from local receipts. function assertCombinedSelectorReloadSoakSmoke(result, networkRequests, reloads) { const failures = []; if (result.reloads !== reloads) { failures.push(`combined selector reload count was ${result.reloads}`); } if (!Array.isArray(result.results) || result.results.length !== reloads) { failures.push(`combined selector reload results were ${JSON.stringify(result.results)}`); } else { for (let reloadIndex = 0; reloadIndex < reloads; reloadIndex += 1) { const pageResult = result.results[reloadIndex]; if (!pageResult || pageResult.reloadIndex !== reloadIndex) { failures.push(`reload ${reloadIndex} result was ${JSON.stringify(pageResult)}`); continue; } assertCombinedSelectorSequenceSmoke( pageResult, networkRequests, combinedSelectorSequence(1), failures, { checkExactModulePlanSummaries: false, checkActualFetchBudget: false } ); } } for (const modelKey of combinedSelectorModels) { assertModulePlanActualFetchBudget(modelKey, networkRequests, reloads, failures); } for (const route of ["/runtime/tinyrustlm.wasm.manifest", "/models/selector.registry"]) { const count = networkPathCount(networkRequests, route); if (count < reloads) { failures.push(`reload route ${route} was requested ${count} times for ${reloads} page lifetimes`); } } for (const modelKey of combinedSelectorModels) { for (const route of expectedSelfAssemblyRoutes(modelKey)) { const count = networkPathCount(networkRequests, route); if (count < reloads) { failures.push(`${modelKey} route ${route} was requested ${count} times for ${reloads} page lifetimes`); } } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertCombinedSelectorOperatorFamilyReloadSoakSmoke(result, networkRequests, reloads) { // Extends reload proof across both parent-pool operator families in every page lifetime. assertCombinedSelectorReloadSoakSmoke(result, networkRequests, reloads); const failures = []; const pageResults = Array.isArray(result.results) ? result.results : []; for (let reloadIndex = 0; reloadIndex < pageResults.length; reloadIndex += 1) { const stepKeys = Array.isArray(pageResults[reloadIndex].steps) ? pageResults[reloadIndex].steps.map((step) => step.modelKey) : []; const signMergeSteps = stepKeys.filter((modelKey) => modelKey.startsWith("multi-parent-sign-merge-")).length; const soupSteps = stepKeys.filter((modelKey) => modelKey.startsWith("multi-parent-soup-")).length; if (signMergeSteps !== 3) { failures.push(`reload ${reloadIndex} sign-merge steps were ${signMergeSteps}`); } if (soupSteps !== 3) { failures.push(`reload ${reloadIndex} soup steps were ${soupSteps}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertAdapterChecksumMismatchSmoke(result, modelKey, networkRequests) { const failures = []; if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (!String(result.modelState || "").startsWith("loaded")) { failures.push(`model state was ${result.modelState}`); } if (result.runtimeStatus !== "Adapter load failed") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (result.adapterState !== "adapter artifact checksum mismatch") { failures.push(`adapter state was ${result.adapterState}`); } if (result.errorState !== "adapter artifact checksum mismatch") { failures.push(`error state was ${result.errorState}`); } if (result.response !== "e") { failures.push(`response was ${JSON.stringify(result.response)}`); } if (String(result.console || "").includes("apply_adapter_delta")) { failures.push("console included apply_adapter_delta"); } if (!String(result.console || "").includes("adapter artifact checksum mismatch")) { failures.push("console did not include checksum mismatch"); } const before = result.beforeApplyDiagnostics || {}; const after = result.afterApplyDiagnostics || {}; if (before.generated_token_count !== 1 || before.kv_cache_length < 1) { failures.push(`pre-apply diagnostics were ${JSON.stringify(before)}`); } if (after.generated_token_count !== 1 || after.kv_cache_length < 1) { failures.push(`post-failure diagnostics were ${JSON.stringify(after)}`); } if (result.stepDisabledAfterApply) { failures.push("step-token control was disabled after adapter load failure"); } if (result.generateDisabledAfterApply || result.applyDisabledAfterApply) { failures.push("primary adapter controls were disabled after checksum mismatch"); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } const expectedAdapterRoute = expectedAdapterRoutes[modelKey] || "/models/tiny-test-model-self.adp1"; if (!networkIncludesPath(networkRequests, expectedAdapterRoute)) { failures.push("adapter sidecar route was not requested"); } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertAdapterManifestBudgetSmoke(result, modelKey, networkRequests) { const failures = []; if (result.selectedModel !== modelKey) { failures.push(`selected model was ${result.selectedModel}`); } if (!String(result.modelState || "").startsWith("loaded")) { failures.push(`model state was ${result.modelState}`); } if (result.runtimeStatus !== "Ready") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (result.errorState !== "none") { failures.push(`error state was ${result.errorState}`); } if (!String(result.adapterState || "").includes("Adapter manifest byte budget exceeded")) { failures.push(`adapter state was ${result.adapterState}`); } if (result.assemblyState !== "loaded") { failures.push(`assembly state was ${result.assemblyState}`); } if (result.assemblyKind !== "browser-local-assembly-evidence") { failures.push(`assembly kind was ${result.assemblyKind}`); } if (result.generateDisabled) { failures.push("generate control was disabled after manifest budget rejection"); } if (!result.adapterSelectDisabled || !result.applyDisabled) { failures.push("adapter controls were enabled after manifest budget rejection"); } if (String(result.console || "").includes("apply_adapter_delta")) { failures.push("console included apply_adapter_delta"); } if (!String(result.console || "").includes("Adapter manifest byte budget exceeded")) { failures.push("console did not include manifest budget rejection"); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } const expectedManifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; const sparseManifestRoute = expectedManifestRoutes[expectedManifestRoutes.length - 1]; if (!sparseManifestRoute || !networkRequests.some((requestUrl) => requestUrl.includes(sparseManifestRoute))) { failures.push(`adapter sparse manifest route was not requested: ${sparseManifestRoute}`); } const expectedAdapterRoute = expectedAdapterRoutes[modelKey]; if (expectedAdapterRoute && networkIncludesPath(networkRequests, expectedAdapterRoute)) { failures.push("adapter artifact route was requested after manifest budget rejection"); } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertStepHealthy(step) { const failures = []; if (step.runtimeStatus !== "Ready") { failures.push(`${step.label} runtime status was ${step.runtimeStatus}`); } if (step.errorState !== "none") { failures.push(`${step.label} error state was ${step.errorState}`); } if (step.generateDisabled || step.resetDisabled || step.modelSelectDisabled) { failures.push(`${step.label} controls were unexpectedly disabled`); } if (Object.prototype.hasOwnProperty.call(step, "stepTokenDisabled")) { const label = String(step.label || ""); if (label.includes("generate") && step.stepTokenDisabled) { failures.push(`${step.label} step-token control was disabled after generation`); } if ((label.includes("ready") || label.includes("reset") || label === "reload-ready") && !step.stepTokenDisabled) { failures.push(`${step.label} step-token control was enabled without generation context`); } } if (!step.diagnostics || step.diagnostics.last_error !== "ok") { failures.push(`${step.label} diagnostics last_error was not ok`); } return failures; } function assertLoopSmoke(result, networkRequests) { const failures = []; const steps = Array.isArray(result.steps) ? result.steps : []; const byLabel = new Map(steps.map((step) => [step.label, step])); for (const label of [ "reload-ready", "q8-ready", "q8-generate-1", "q8-reset", "q8-generate-2", "q4-ready", "q4-generate-1", "q4-reset", "q4-generate-2" ]) { if (!byLabel.has(label)) { failures.push(`missing loop step ${label}`); } } for (const step of steps) { failures.push(...assertStepHealthy(step)); } for (const label of ["q8-generate-1", "q8-generate-2"]) { const step = byLabel.get(label); if (step) { if (step.selectedModel !== "tinylm16q8") { failures.push(`${label} selected model was ${step.selectedModel}`); } if (step.response !== "e") { failures.push(`${label} response was ${JSON.stringify(step.response)}`); } if (step.diagnostics.active_quantization_mode !== "q8_0") { failures.push(`${label} quantization was ${step.diagnostics.active_quantization_mode}`); } if (step.diagnostics.selected_next_token !== 101) { failures.push(`${label} selected token was ${step.diagnostics.selected_next_token}`); } } } for (const label of ["q4-generate-1", "q4-generate-2"]) { const step = byLabel.get(label); if (step) { if (step.selectedModel !== "tinylm16q4") { failures.push(`${label} selected model was ${step.selectedModel}`); } if (step.response !== "e") { failures.push(`${label} response was ${JSON.stringify(step.response)}`); } if (step.diagnostics.active_quantization_mode !== "q4_0") { failures.push(`${label} quantization was ${step.diagnostics.active_quantization_mode}`); } if (step.diagnostics.selected_next_token !== 101) { failures.push(`${label} selected token was ${step.diagnostics.selected_next_token}`); } } } for (const label of ["q8-reset", "q4-reset"]) { const step = byLabel.get(label); if (step) { if (step.console !== "context reset") { failures.push(`${label} console was ${JSON.stringify(step.console)}`); } if (step.diagnostics.generated_token_count !== 0) { failures.push(`${label} generated count was ${step.diagnostics.generated_token_count}`); } } } for (const label of ["reload-ready", "q8-ready", "q4-ready"]) { const step = byLabel.get(label); if (step) { if (step.diagnostics.prompt_token_count !== 0) { failures.push(`${label} prompt count was ${step.diagnostics.prompt_token_count}`); } if (step.diagnostics.generated_token_count !== 0) { failures.push(`${label} generated count was ${step.diagnostics.generated_token_count}`); } if (step.diagnostics.kv_cache_length !== 0) { failures.push(`${label} kv cache length was ${step.diagnostics.kv_cache_length}`); } } } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertModelErrorSmoke(result, networkRequests) { const failures = []; if (result.runtimeStatus !== "Model rejected") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (!String(result.modelState).startsWith("error 4")) { failures.push(`model state was ${result.modelState}`); } if (result.errorState !== "invalid model magic") { failures.push(`error state was ${result.errorState}`); } if (!result.diagnostics || result.diagnostics.last_error !== "invalid model magic") { failures.push("diagnostics did not report invalid model magic"); } if (result.diagnostics && result.diagnostics.model_loaded !== false) { failures.push("diagnostics reported model_loaded true"); } if (!result.generateDisabled || !result.resetDisabled) { failures.push("generate/reset controls were not disabled after rejected model"); } if (!result.stepTokenDisabled) { failures.push("step-token control was not disabled after rejected model"); } if (result.modelSelectDisabled) { failures.push("model selector was disabled after rejected model"); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } async function runPagePromptLimitSmoke(client) { const expression = ` (async () => { const byId = (id) => document.getElementById(id); const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const parseDiagnostics = () => { try { return JSON.parse(byId("diagnostics").textContent); } catch { return null; } }; for (let index = 0; index < 600; index += 1) { if (!byId("generateButton").disabled && byId("runtimeStatus").textContent === "Ready") { break; } await sleep(100); } byId("prompt").value = "a".repeat(4097); byId("generateButton").click(); await sleep(100); return JSON.stringify({ runtimeStatus: byId("runtimeStatus").textContent, modelState: byId("modelState").textContent, errorState: byId("errorState").textContent, response: byId("response").textContent, console: byId("console").textContent, diagnostics: parseDiagnostics(), stepTokenDisabled: byId("stepTokenButton").disabled, generateDisabled: byId("generateButton").disabled, resetDisabled: byId("resetButton").disabled, modelSelectDisabled: byId("modelSelect").disabled }); })() `; const result = await client.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true, timeout: 120000 }); return parseEvaluateValue(result); } function assertMissingModelSmoke(result, networkRequests) { const failures = []; if (result.runtimeStatus !== "Model load failed") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (result.modelState !== "fetch error") { failures.push(`model state was ${result.modelState}`); } if (!String(result.errorState).includes("Unable to fetch local .slm model (404)")) { failures.push(`error state was ${result.errorState}`); } if (result.selectedModel !== "tinylm16q8") { failures.push(`selected model was ${result.selectedModel}`); } if (!result.generateDisabled || !result.resetDisabled) { failures.push("generate/reset controls were not disabled after missing model"); } if (!result.stepTokenDisabled) { failures.push("step-token control was not disabled after missing model"); } if (result.modelSelectDisabled) { failures.push("model selector was disabled after missing model"); } if (result.diagnostics && result.diagnostics.model_loaded !== false) { failures.push("diagnostics reported model_loaded true"); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (!networkRequests.some((requestUrl) => requestUrl.includes("/models/tinylm16-q8.slm"))) { failures.push("missing model route was not requested"); } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertContextErrorSmoke(result, networkRequests) { const failures = []; if (result.runtimeStatus !== "Ready") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (result.errorState !== "context exceeded") { failures.push(`error state was ${result.errorState}`); } if (result.response !== "context exceeded") { failures.push(`response was ${JSON.stringify(result.response)}`); } if (!String(result.console).includes("generate(max_new_tokens=1, temperature=0, top_k=1, top_p=1, seed=1) -> 11")) { failures.push(`console did not include context exceeded code: ${JSON.stringify(result.console)}`); } if (!result.diagnostics || result.diagnostics.last_error !== "context exceeded") { failures.push("diagnostics did not report context exceeded"); } if (result.diagnostics && result.diagnostics.generated_token_count !== 0) { failures.push(`generated count was ${result.diagnostics.generated_token_count}`); } if (result.diagnostics && result.diagnostics.kv_cache_length !== 0) { failures.push(`kv cache length was ${result.diagnostics.kv_cache_length}`); } if (result.generateDisabled || result.resetDisabled || result.modelSelectDisabled) { failures.push("controls were unexpectedly disabled after context error"); } if (!result.stepTokenDisabled) { failures.push("step-token control was enabled after context error"); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertPromptLimitSmoke(result, networkRequests) { const failures = []; if (result.runtimeStatus !== "Ready") { failures.push(`runtime status was ${result.runtimeStatus}`); } if (!String(result.modelState || "").startsWith("loaded")) { failures.push(`model state was ${result.modelState}`); } if (result.errorState !== "prompt byte limit exceeded") { failures.push(`error state was ${result.errorState}`); } if (result.response !== "prompt byte limit exceeded") { failures.push(`response was ${JSON.stringify(result.response)}`); } if (result.console !== "prompt byte limit exceeded") { failures.push(`console was ${JSON.stringify(result.console)}`); } if (result.diagnostics && result.diagnostics.prompt_token_count !== 0) { failures.push(`prompt tokens were ${result.diagnostics.prompt_token_count}`); } if (result.diagnostics && result.diagnostics.generated_token_count !== 0) { failures.push(`generated count was ${result.diagnostics.generated_token_count}`); } if (result.generateDisabled || result.resetDisabled || result.modelSelectDisabled) { failures.push("controls were unexpectedly disabled after prompt byte limit"); } if (!result.stepTokenDisabled) { failures.push("step-token control was enabled after prompt byte limit"); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertEnduranceSmoke(result, networkRequests) { const failures = []; const steps = Array.isArray(result.steps) ? result.steps : []; const cycles = Number(result.cycles || 0); if (cycles < 2) { failures.push(`cycle count was ${cycles}`); } if (steps.length !== cycles * 6) { failures.push(`expected ${cycles * 6} endurance steps, got ${steps.length}`); } for (const step of steps) { failures.push(...assertStepHealthy(step)); if (step.label.includes("-generate")) { const expectedMode = step.label.includes("-q8-") ? "q8_0" : "q4_0"; const expectedModel = step.label.includes("-q8-") ? "tinylm16q8" : "tinylm16q4"; if (step.selectedModel !== expectedModel) { failures.push(`${step.label} selected model was ${step.selectedModel}`); } if (step.response !== "e") { failures.push(`${step.label} response was ${JSON.stringify(step.response)}`); } if (step.diagnostics.active_quantization_mode !== expectedMode) { failures.push(`${step.label} quantization was ${step.diagnostics.active_quantization_mode}`); } if (step.diagnostics.generated_token_count !== 1) { failures.push(`${step.label} generated count was ${step.diagnostics.generated_token_count}`); } if (step.diagnostics.selected_next_token !== 101) { failures.push(`${step.label} selected token was ${step.diagnostics.selected_next_token}`); } } if (step.label.includes("-reset")) { if (step.console !== "context reset") { failures.push(`${step.label} console was ${JSON.stringify(step.console)}`); } if (step.diagnostics.prompt_token_count !== 0) { failures.push(`${step.label} prompt count was ${step.diagnostics.prompt_token_count}`); } if (step.diagnostics.generated_token_count !== 0) { failures.push(`${step.label} generated count was ${step.diagnostics.generated_token_count}`); } if (step.diagnostics.kv_cache_length !== 0) { failures.push(`${step.label} kv cache length was ${step.diagnostics.kv_cache_length}`); } } } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertPerformanceSmoke(result, networkRequests) { const failures = []; const steps = Array.isArray(result.steps) ? result.steps : []; const maxTokens = Number(result.maxTokens || 0); const byLabel = new Map(steps.map((step) => [step.label, step])); if (maxTokens < 2) { failures.push(`maxTokens was ${maxTokens}`); } for (const label of [ "q8-performance-ready", "q8-performance-generate", "q8-performance-reset", "q4-performance-ready", "q4-performance-generate", "q4-performance-reset" ]) { if (!byLabel.has(label)) { failures.push(`missing performance step ${label}`); } } for (const step of steps) { failures.push(...assertStepHealthy(step)); } for (const label of ["q8-performance-generate", "q4-performance-generate"]) { const step = byLabel.get(label); if (!step) { continue; } const expectedModel = label.startsWith("q8") ? "tinylm16q8" : "tinylm16q4"; const expectedMode = label.startsWith("q8") ? "q8_0" : "q4_0"; const expectedResponse = "e".repeat(maxTokens); if (step.selectedModel !== expectedModel) { failures.push(`${label} selected model was ${step.selectedModel}`); } if (step.response !== expectedResponse) { failures.push(`${label} response was ${JSON.stringify(step.response)}`); } if (step.diagnostics.active_quantization_mode !== expectedMode) { failures.push(`${label} quantization was ${step.diagnostics.active_quantization_mode}`); } if (step.diagnostics.prompt_token_count !== 3) { failures.push(`${label} prompt tokens were ${step.diagnostics.prompt_token_count}`); } if (step.diagnostics.generated_token_count !== maxTokens) { failures.push(`${label} generated tokens were ${step.diagnostics.generated_token_count}`); } if (step.diagnostics.kv_cache_length !== maxTokens + 3) { failures.push(`${label} kv cache length was ${step.diagnostics.kv_cache_length}`); } if (step.diagnostics.selected_next_token !== 101) { failures.push(`${label} selected token was ${step.diagnostics.selected_next_token}`); } if (step.benchPromptTokensValue !== 3) { failures.push(`${label} benchmark prompt tokens were ${step.benchPromptTokens}`); } if (step.benchGeneratedTokensValue !== maxTokens) { failures.push(`${label} benchmark generated tokens were ${step.benchGeneratedTokens}`); } if (!(step.benchTokensPerSecondValue > 0)) { failures.push(`${label} benchmark token speed was ${step.benchTokensPerSecond}`); } if (!(step.benchScratchValue > 0)) { failures.push(`${label} scratch bytes were ${step.benchScratch}`); } if (!(step.elapsedMs > 0)) { failures.push(`${label} elapsedMs was ${step.elapsedMs}`); } } for (const label of ["q8-performance-reset", "q4-performance-reset"]) { const step = byLabel.get(label); if (!step) { continue; } if (step.console !== "context reset") { failures.push(`${label} console was ${JSON.stringify(step.console)}`); } if (step.diagnostics.prompt_token_count !== 0) { failures.push(`${label} prompt count was ${step.diagnostics.prompt_token_count}`); } if (step.diagnostics.generated_token_count !== 0) { failures.push(`${label} generated count was ${step.diagnostics.generated_token_count}`); } if (step.diagnostics.kv_cache_length !== 0) { failures.push(`${label} kv cache length was ${step.diagnostics.kv_cache_length}`); } } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertPerformanceSoak(result, networkRequests) { const failures = []; const steps = Array.isArray(result.steps) ? result.steps : []; const cycles = Number(result.cycles || 0); const maxTokens = Number(result.maxTokens || 0); const expectedResponse = "e".repeat(maxTokens); const generationCounts = { q8: 0, q4: 0 }; const minSpeeds = { q8: Number.POSITIVE_INFINITY, q4: Number.POSITIVE_INFINITY }; if (cycles < 2) { failures.push(`cycle count was ${cycles}`); } if (maxTokens < 2) { failures.push(`maxTokens was ${maxTokens}`); } if (steps.length !== cycles * 6) { failures.push(`expected ${cycles * 6} performance-soak steps, got ${steps.length}`); } for (let cycle = 1; cycle <= cycles; cycle += 1) { for (const mode of ["q8", "q4"]) { for (const phase of ["ready", "generate", "reset"]) { const label = `cycle-${cycle}-${mode}-performance-${phase}`; if (!steps.some((step) => step.label === label)) { failures.push(`missing performance-soak step ${label}`); } } } } for (const step of steps) { failures.push(...assertStepHealthy(step)); const isQ8 = step.label.includes("-q8-"); const expectedModel = isQ8 ? "tinylm16q8" : "tinylm16q4"; const expectedMode = isQ8 ? "q8_0" : "q4_0"; const key = isQ8 ? "q8" : "q4"; if (step.selectedModel !== expectedModel) { failures.push(`${step.label} selected model was ${step.selectedModel}`); } if (step.diagnostics.active_quantization_mode !== expectedMode) { failures.push(`${step.label} quantization was ${step.diagnostics.active_quantization_mode}`); } if (step.label.includes("-generate")) { generationCounts[key] += 1; minSpeeds[key] = Math.min(minSpeeds[key], step.benchTokensPerSecondValue); if (step.response !== expectedResponse) { failures.push(`${step.label} response was ${JSON.stringify(step.response)}`); } if (step.diagnostics.prompt_token_count !== 3) { failures.push(`${step.label} prompt tokens were ${step.diagnostics.prompt_token_count}`); } if (step.diagnostics.generated_token_count !== maxTokens) { failures.push(`${step.label} generated tokens were ${step.diagnostics.generated_token_count}`); } if (step.diagnostics.kv_cache_length !== maxTokens + 3) { failures.push(`${step.label} kv cache length was ${step.diagnostics.kv_cache_length}`); } if (step.diagnostics.selected_next_token !== 101) { failures.push(`${step.label} selected token was ${step.diagnostics.selected_next_token}`); } if (step.benchPromptTokensValue !== 3) { failures.push(`${step.label} benchmark prompt tokens were ${step.benchPromptTokens}`); } if (step.benchGeneratedTokensValue !== maxTokens) { failures.push(`${step.label} benchmark generated tokens were ${step.benchGeneratedTokens}`); } if (!(step.benchTokensPerSecondValue > 0)) { failures.push(`${step.label} benchmark token speed was ${step.benchTokensPerSecond}`); } if (!(step.benchScratchValue > 0)) { failures.push(`${step.label} scratch bytes were ${step.benchScratch}`); } if (!(step.elapsedMs > 0)) { failures.push(`${step.label} elapsedMs was ${step.elapsedMs}`); } } if (step.label.includes("-reset")) { if (step.console !== "context reset") { failures.push(`${step.label} console was ${JSON.stringify(step.console)}`); } if (step.diagnostics.prompt_token_count !== 0) { failures.push(`${step.label} prompt count was ${step.diagnostics.prompt_token_count}`); } if (step.diagnostics.generated_token_count !== 0) { failures.push(`${step.label} generated count was ${step.diagnostics.generated_token_count}`); } if (step.diagnostics.kv_cache_length !== 0) { failures.push(`${step.label} kv cache length was ${step.diagnostics.kv_cache_length}`); } } } if (generationCounts.q8 !== cycles) { failures.push(`q8 generation count was ${generationCounts.q8}`); } if (generationCounts.q4 !== cycles) { failures.push(`q4 generation count was ${generationCounts.q4}`); } if (!(minSpeeds.q8 > 0)) { failures.push(`q8 minimum token speed was ${minSpeeds.q8}`); } if (!(minSpeeds.q4 > 0)) { failures.push(`q4 minimum token speed was ${minSpeeds.q4}`); } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function assertUiSnapshot(snapshot, phase, viewportName) { const failures = []; const requiredHeadings = [ "Conversation", "Response", "Model Loading", "Model Provenance", "Assembly Evidence", "Module Plan", "Benchmark", "Runtime Diagnostics", "Token Generation Console", "Developer Mode" ]; const requiredLabels = ["Prompt", "Max Tokens", "Temperature", "Top K", "Top P", "Seed", "Model"]; const requiredOptions = [ "TinyLM-16M q8_0", "TinyLM-16M q4_0", "TinyLM-16M f32", "Tiny Fixture f32", "Tiny Fixture tied-output f32", "Tiny Fixture q8_0", "Tiny Fixture q4_0", "Tiny Fixture BPE f32" ]; const prefix = `${viewportName} ${phase}`; if (snapshot.title !== "TinyRustLM") { failures.push(`${prefix} title was ${snapshot.title}`); } if (snapshot.lang !== "en") { failures.push(`${prefix} lang was ${snapshot.lang}`); } if (snapshot.h1 !== "TinyRustLM") { failures.push(`${prefix} h1 was ${snapshot.h1}`); } if (snapshot.eyebrow !== "GGUF.MiRust.com") { failures.push(`${prefix} eyebrow was ${snapshot.eyebrow}`); } if (snapshot.notice !== "All inference runs locally in this browser. Prompts are not sent to a server.") { failures.push(`${prefix} local-only notice was ${snapshot.notice}`); } if (!snapshot.footer.includes("TinyRustLM") || !snapshot.footer.includes("GGUF.MiRust.com") || !snapshot.footer.includes("Rust/WASM")) { failures.push(`${prefix} footer did not expose product, site, and Rust/WASM identity`); } for (const heading of requiredHeadings) { if (!snapshot.headings.includes(heading)) { failures.push(`${prefix} missing heading ${heading}`); } } for (const label of requiredLabels) { if (!snapshot.labels.includes(label)) { failures.push(`${prefix} missing label ${label}`); } } for (const option of requiredOptions) { if (!snapshot.modelOptions.includes(option)) { failures.push(`${prefix} missing model option ${option}`); } } if (snapshot.panelCount < 8) { failures.push(`${prefix} panel count was ${snapshot.panelCount}`); } if (snapshot.runtimeStatus !== "Ready") { failures.push(`${prefix} runtime status was ${snapshot.runtimeStatus}`); } if (snapshot.errorState !== "none") { failures.push(`${prefix} error state was ${snapshot.errorState}`); } if (snapshot.generateDisabled || snapshot.resetDisabled || snapshot.modelSelectDisabled) { failures.push(`${prefix} controls were unexpectedly disabled`); } if (phase === "ready") { if (!snapshot.clearChatDisabled) { failures.push(`${prefix} clear chat control was enabled before transcript content`); } if (!snapshot.stepTokenDisabled) { failures.push(`${prefix} step-token control was enabled before generation context`); } if (Array.isArray(snapshot.conversationItems) && snapshot.conversationItems.length !== 0) { failures.push(`${prefix} conversation was not empty before generation`); } } if (phase === "generated") { if (snapshot.clearChatDisabled) { failures.push(`${prefix} clear chat control stayed disabled after transcript content`); } if (snapshot.stepTokenDisabled) { failures.push(`${prefix} step-token control stayed disabled after generation`); } if (!Array.isArray(snapshot.conversationItems) || snapshot.conversationItems.length !== 2) { failures.push(`${prefix} conversation item count was ${snapshot.conversationItems ? snapshot.conversationItems.length : "missing"}`); } else { if (snapshot.conversationItems[0].role !== "User" || snapshot.conversationItems[0].text !== "hi") { failures.push(`${prefix} conversation user item was ${JSON.stringify(snapshot.conversationItems[0])}`); } if (snapshot.conversationItems[1].role !== "TinyRustLM" || snapshot.conversationItems[1].text !== "e" || snapshot.conversationItems[1].isError) { failures.push(`${prefix} conversation assistant item was ${JSON.stringify(snapshot.conversationItems[1])}`); } } } if (phase === "cleared") { if (!snapshot.clearChatDisabled) { failures.push(`${prefix} clear chat control stayed enabled after transcript clear`); } if (snapshot.stepTokenDisabled) { failures.push(`${prefix} step-token control was disabled after transcript clear`); } if (Array.isArray(snapshot.conversationItems) && snapshot.conversationItems.length !== 0) { failures.push(`${prefix} conversation was not empty after transcript clear`); } } if (snapshot.selectedModel !== "tinylm16q8") { failures.push(`${prefix} selected model was ${snapshot.selectedModel}`); } if (snapshot.temperatureValue !== "0" || snapshot.topKValue !== "1" || snapshot.topPValue !== "1" || snapshot.seedValue !== "1") { failures.push(`${prefix} sampling controls were ${snapshot.temperatureValue}/${snapshot.topKValue}/${snapshot.topPValue}/${snapshot.seedValue}`); } if (snapshot.scrollWidth > snapshot.viewportWidth + 1 || snapshot.bodyScrollWidth > snapshot.viewportWidth + 1) { failures.push(`${prefix} horizontal overflow ${snapshot.scrollWidth}/${snapshot.bodyScrollWidth} > ${snapshot.viewportWidth}`); } if (Array.isArray(snapshot.badRects) && snapshot.badRects.length > 0) { failures.push(`${prefix} zero-sized UI controls: ${JSON.stringify(snapshot.badRects)}`); } if (!snapshot.diagnosticsText.includes('"active_quantization_mode": "q8_0"')) { failures.push(`${prefix} diagnostics did not report q8_0`); } if (!snapshot.developerText.includes('"active_quantization_mode": "q8_0"')) { failures.push(`${prefix} developer panel did not mirror diagnostics`); } if (!snapshot.diagnostics || snapshot.diagnostics.sampling_temperature !== 0 || snapshot.diagnostics.sampling_top_k !== 1 || snapshot.diagnostics.sampling_top_p !== 1 || snapshot.diagnostics.sampling_seed !== 1) { failures.push(`${prefix} diagnostics sampling defaults were not greedy`); } if (snapshot.provenanceState !== "loaded") { failures.push(`${prefix} provenance state was ${snapshot.provenanceState}`); } if (snapshot.provenanceSourceKind !== "deterministic-smoke") { failures.push(`${prefix} provenance source was ${snapshot.provenanceSourceKind}`); } if (snapshot.provenanceAdmission !== "accepted-for-runtime-smoke") { failures.push(`${prefix} provenance admission was ${snapshot.provenanceAdmission}`); } if (snapshot.provenanceQualityClaim !== "runtime-execution-smoke-only") { failures.push(`${prefix} provenance quality claim was ${snapshot.provenanceQualityClaim}`); } if (snapshot.provenanceTrainedClaim !== "not-claimed") { failures.push(`${prefix} provenance trained claim was ${snapshot.provenanceTrainedClaim}`); } if (snapshot.provenanceGenome !== "unavailable") { failures.push(`${prefix} provenance genome was ${snapshot.provenanceGenome}`); } if (snapshot.provenanceSpecies !== "unavailable") { failures.push(`${prefix} provenance species was ${snapshot.provenanceSpecies}`); } if (snapshot.provenanceNovelty !== "unavailable") { failures.push(`${prefix} provenance novelty was ${snapshot.provenanceNovelty}`); } if (snapshot.provenancePopulation !== "unavailable") { failures.push(`${prefix} provenance population was ${snapshot.provenancePopulation}`); } if (snapshot.provenanceMateSelection !== "unavailable") { failures.push(`${prefix} provenance mate selection was ${snapshot.provenanceMateSelection}`); } if (snapshot.provenanceOperator !== "unavailable") { failures.push(`${prefix} provenance operator was ${snapshot.provenanceOperator}`); } if (snapshot.provenanceSchedule !== "unavailable") { failures.push(`${prefix} provenance schedule was ${snapshot.provenanceSchedule}`); } if (snapshot.provenancePhenotype !== "unavailable") { failures.push(`${prefix} provenance phenotype was ${snapshot.provenancePhenotype}`); } if (snapshot.provenanceArtifact !== "unavailable") { failures.push(`${prefix} provenance artifact was ${snapshot.provenanceArtifact}`); } if (snapshot.provenanceFitness !== "unavailable") { failures.push(`${prefix} provenance fitness was ${snapshot.provenanceFitness}`); } if (snapshot.provenanceEvalCases !== "unavailable") { failures.push(`${prefix} provenance eval cases were ${snapshot.provenanceEvalCases}`); } if (snapshot.provenanceEvalChecksum !== "unavailable") { failures.push(`${prefix} provenance eval checksum was ${snapshot.provenanceEvalChecksum}`); } if (!String(snapshot.provenanceChecksum).startsWith("0x")) { failures.push(`${prefix} provenance checksum was ${snapshot.provenanceChecksum}`); } if (snapshot.provenanceNextGate !== "replace-with-trained-or-evaluated-model-before-product-quality-claim") { failures.push(`${prefix} provenance next gate was ${snapshot.provenanceNextGate}`); } if (snapshot.modulePlanState !== "none") { failures.push(`${prefix} module plan state was ${snapshot.modulePlanState}`); } if (snapshot.modulePlanStack !== "unavailable") { failures.push(`${prefix} module plan stack was ${snapshot.modulePlanStack}`); } if (snapshot.modulePlanModelBudget !== "unavailable") { failures.push(`${prefix} module plan model budget was ${snapshot.modulePlanModelBudget}`); } if (snapshot.modulePlanAdapterBudget !== "unavailable") { failures.push(`${prefix} module plan adapter budget was ${snapshot.modulePlanAdapterBudget}`); } if (snapshot.modulePlanAdapterStackBudget !== "unavailable") { failures.push(`${prefix} module plan adapter stack budget was ${snapshot.modulePlanAdapterStackBudget}`); } if (snapshot.modulePlanScratchBudget !== "unavailable") { failures.push(`${prefix} module plan scratch budget was ${snapshot.modulePlanScratchBudget}`); } if (snapshot.modulePlanPromptLimit !== "unavailable") { failures.push(`${prefix} module plan prompt limit was ${snapshot.modulePlanPromptLimit}`); } if (snapshot.modulePlanOutputLimit !== "unavailable") { failures.push(`${prefix} module plan output limit was ${snapshot.modulePlanOutputLimit}`); } if (snapshot.modulePlanKvCacheBudget !== "unavailable") { failures.push(`${prefix} module plan KV cache budget was ${snapshot.modulePlanKvCacheBudget}`); } if (snapshot.modulePlanKvCachePages !== "unavailable") { failures.push(`${prefix} module plan KV cache pages was ${snapshot.modulePlanKvCachePages}`); } if (snapshot.modulePlanTotalBudget !== "unavailable") { failures.push(`${prefix} module plan total budget was ${snapshot.modulePlanTotalBudget}`); } if (snapshot.modulePlanTotalLimit !== "unavailable") { failures.push(`${prefix} module plan total limit was ${snapshot.modulePlanTotalLimit}`); } if (snapshot.modulePlanExecution !== "unavailable") { failures.push(`${prefix} module plan execution profile was ${snapshot.modulePlanExecution}`); } if (snapshot.modulePlanFetch !== "unavailable") { failures.push(`${prefix} module plan fetch policy was ${snapshot.modulePlanFetch}`); } if (snapshot.modulePlanOrigin !== "unavailable") { failures.push(`${prefix} module plan origin policy was ${snapshot.modulePlanOrigin}`); } if (snapshot.modulePlanFetchLimit !== "unavailable") { failures.push(`${prefix} module plan fetch limit was ${snapshot.modulePlanFetchLimit}`); } if (snapshot.modulePlanPlannedFetchCount !== "unavailable") { failures.push(`${prefix} module plan planned fetch count was ${snapshot.modulePlanPlannedFetchCount}`); } if (snapshot.modulePlanActualFetchCount !== "unavailable") { failures.push(`${prefix} module plan actual fetch count was ${snapshot.modulePlanActualFetchCount}`); } if (snapshot.modulePlanRouteSetVersion !== "unavailable") { failures.push(`${prefix} module plan route set version was ${snapshot.modulePlanRouteSetVersion}`); } if (snapshot.modulePlanRouteSetChecksumAlgorithm !== "unavailable") { failures.push(`${prefix} module plan route set checksum algorithm was ${snapshot.modulePlanRouteSetChecksumAlgorithm}`); } if (snapshot.modulePlanRouteSetChecksum !== "unavailable") { failures.push(`${prefix} module plan route set checksum was ${snapshot.modulePlanRouteSetChecksum}`); } if (snapshot.modulePlanActualRouteSetChecksum !== "unavailable") { failures.push(`${prefix} module plan actual route set checksum was ${snapshot.modulePlanActualRouteSetChecksum}`); } if (snapshot.modulePlanWasmPages !== "unavailable") { failures.push(`${prefix} module plan WASM pages was ${snapshot.modulePlanWasmPages}`); } if (snapshot.modulePlanWasmExportSet !== "unavailable") { failures.push(`${prefix} module plan WASM ABI was ${snapshot.modulePlanWasmExportSet}`); } if (snapshot.modulePlanWasmTransferStrategy !== "unavailable") { failures.push(`${prefix} module plan WASM transfer strategy was ${snapshot.modulePlanWasmTransferStrategy}`); } if (snapshot.modulePlanModelReleaseStrategy !== "unavailable") { failures.push(`${prefix} module plan model release strategy was ${snapshot.modulePlanModelReleaseStrategy}`); } if (snapshot.modulePlanRuntimeResetStrategy !== "unavailable") { failures.push(`${prefix} module plan runtime reset strategy was ${snapshot.modulePlanRuntimeResetStrategy}`); } if (snapshot.modulePlanAdapterValidationStrategy !== "unavailable") { failures.push(`${prefix} module plan adapter validation strategy was ${snapshot.modulePlanAdapterValidationStrategy}`); } if (snapshot.modulePlanAdapterValidationCount !== "unavailable") { failures.push(`${prefix} module plan adapter validation count was ${snapshot.modulePlanAdapterValidationCount}`); } if (snapshot.modulePlanAdapterApplyCount !== "unavailable") { failures.push(`${prefix} module plan adapter apply count was ${snapshot.modulePlanAdapterApplyCount}`); } if (snapshot.modulePlanWasmHeapMinBytes !== "unavailable") { failures.push(`${prefix} module plan WASM heap floor was ${snapshot.modulePlanWasmHeapMinBytes}`); } if (snapshot.modulePlanContextTokens !== "unavailable") { failures.push(`${prefix} module plan context tokens was ${snapshot.modulePlanContextTokens}`); } if (snapshot.modulePlanSamplerCap !== "unavailable") { failures.push(`${prefix} module plan sampler cap was ${snapshot.modulePlanSamplerCap}`); } if (snapshot.modulePlanTokenizer !== "unavailable") { failures.push(`${prefix} module plan tokenizer was ${snapshot.modulePlanTokenizer}`); } if (snapshot.modulePlanBytes !== "unavailable") { failures.push(`${prefix} module plan bytes were ${snapshot.modulePlanBytes}`); } if (snapshot.modulePlanActualModuleBytes !== "unavailable") { failures.push(`${prefix} module plan actual module bytes were ${snapshot.modulePlanActualModuleBytes}`); } if (snapshot.modulePlanChecksums !== "unavailable") { failures.push(`${prefix} module plan checksums were ${snapshot.modulePlanChecksums}`); } if (snapshot.modulePlanActualModuleChecksums !== "unavailable") { failures.push(`${prefix} module plan actual module checksums were ${snapshot.modulePlanActualModuleChecksums}`); } if (snapshot.modulePlanSlots !== "unavailable") { failures.push(`${prefix} module plan slots were ${snapshot.modulePlanSlots}`); } if (snapshot.modulePlanRoles !== "unavailable") { failures.push(`${prefix} module plan roles were ${snapshot.modulePlanRoles}`); } if (snapshot.modulePlanPhases !== "unavailable") { failures.push(`${prefix} module plan phases were ${snapshot.modulePlanPhases}`); } if (snapshot.modulePlanDepends !== "unavailable") { failures.push(`${prefix} module plan dependencies were ${snapshot.modulePlanDepends}`); } if (snapshot.modulePlanTrace !== "unavailable") { failures.push(`${prefix} module plan trace was ${snapshot.modulePlanTrace}`); } if (!(snapshot.benchLoadMsValue > 0)) { failures.push(`${prefix} benchmark load value was ${snapshot.benchLoadMs}`); } return failures; } function assertUiAudit(result, networkRequests) { const failures = []; const viewports = [ ["desktop", result.desktop], ["mobile", result.mobile] ]; for (const [viewportName, audit] of viewports) { if (!audit || !audit.before || !audit.after || !audit.cleared) { failures.push(`${viewportName} audit was missing`); continue; } failures.push(...assertUiSnapshot(audit.before, "ready", viewportName)); failures.push(...assertUiSnapshot(audit.after, "generated", viewportName)); failures.push(...assertUiSnapshot(audit.cleared, "cleared", viewportName)); if (audit.after.response !== "e") { failures.push(`${viewportName} generated response was ${JSON.stringify(audit.after.response)}`); } if (audit.cleared.response !== "e") { failures.push(`${viewportName} response changed after transcript clear: ${JSON.stringify(audit.cleared.response)}`); } if (!String(audit.after.console).includes("generate(max_new_tokens=1, temperature=0, top_k=1, top_p=1, seed=1) -> 0")) { failures.push(`${viewportName} console did not show successful generation`); } if (!audit.after.diagnostics || audit.after.diagnostics.last_error !== "ok") { failures.push(`${viewportName} diagnostics last_error was not ok`); } if (audit.after.diagnostics.generated_token_count !== 1) { failures.push(`${viewportName} generated token count was ${audit.after.diagnostics.generated_token_count}`); } if (audit.after.diagnostics.prompt_token_count !== 3) { failures.push(`${viewportName} prompt token count was ${audit.after.diagnostics.prompt_token_count}`); } if (audit.after.diagnostics.kv_cache_length !== 4) { failures.push(`${viewportName} kv cache length was ${audit.after.diagnostics.kv_cache_length}`); } if (audit.after.diagnostics.selected_next_token !== 101) { failures.push(`${viewportName} selected next token was ${audit.after.diagnostics.selected_next_token}`); } if (!String(audit.after.diagnostics.tokenizer_output || "").includes("104")) { failures.push(`${viewportName} tokenizer output did not include prompt byte tokens`); } if (!String(audit.after.diagnostics.logits_summary || "").includes("argmax=101")) { failures.push(`${viewportName} logits summary did not include argmax=101`); } if (!String(audit.after.diagnostics.top_k_candidates || "").includes("101:")) { failures.push(`${viewportName} top-k candidates did not include token 101`); } if (audit.after.benchPromptTokensValue !== 3) { failures.push(`${viewportName} benchmark prompt tokens were ${audit.after.benchPromptTokens}`); } if (audit.after.benchGeneratedTokensValue !== 1) { failures.push(`${viewportName} benchmark generated tokens were ${audit.after.benchGeneratedTokens}`); } if (!(audit.after.benchScratchValue > 0)) { failures.push(`${viewportName} benchmark scratch was ${audit.after.benchScratch}`); } } const allowedOrigin = new URL(appUrl).origin; for (const requestUrl of networkRequests) { if (!requestUrl.startsWith("http://") && !requestUrl.startsWith("https://")) { continue; } const origin = new URL(requestUrl).origin; if (origin !== allowedOrigin) { failures.push(`remote request observed: ${requestUrl}`); } } if (failures.length > 0) { throw new Error(failures.join("; ")); } } function installMalformedModelInterceptor(client) { client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; if (requestUrl.includes("/models/tinylm16-q8.slm")) { const malformed = Buffer.alloc(108); malformed.write("NOPE", 0, "ascii"); client.send("Fetch.fulfillRequest", { requestId: params.requestId, responseCode: 200, responseHeaders: [ { name: "content-type", value: "application/octet-stream" }, { name: "content-length", value: String(malformed.length) } ], body: malformed.toString("base64") }).catch((error) => { console.error(error); }); return; } client.send("Fetch.continueRequest", { requestId: params.requestId }).catch((error) => { console.error(error); }); }); } function installMissingModelInterceptor(client) { client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; if (requestUrl.includes("/models/tinylm16-q8.slm")) { const body = Buffer.from("missing model for browser smoke", "utf8"); client.send("Fetch.fulfillRequest", { requestId: params.requestId, responseCode: 404, responseHeaders: [ { name: "content-type", value: "text/plain; charset=utf-8" }, { name: "content-length", value: String(body.length) } ], body: body.toString("base64") }).catch((error) => { console.error(error); }); return; } client.send("Fetch.continueRequest", { requestId: params.requestId }).catch((error) => { console.error(error); }); }); } function installCorruptAdapterInterceptor(client) { client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; if (requestUrl.includes("/models/tiny-test-model-self.adp1")) { const adapterPath = path.join(__dirname, "..", "models", "tiny-test-model-self.adp1"); const body = Buffer.from(fs.readFileSync(adapterPath)); body[body.length - 1] ^= 0xff; client.send("Fetch.fulfillRequest", { requestId: params.requestId, responseCode: 200, responseHeaders: [ { name: "content-type", value: "application/octet-stream" }, { name: "content-length", value: String(body.length) } ], body: body.toString("base64") }).catch((error) => { console.error(error); }); return; } client.send("Fetch.continueRequest", { requestId: params.requestId }).catch((error) => { console.error(error); }); }); } function installAdapterManifestBudgetInterceptor(client) { client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; if (requestUrl.includes("-sparse.asp1.manifest")) { const body = Buffer.alloc((64 * 1024) + 1, "a", "utf8"); client.send("Fetch.fulfillRequest", { requestId: params.requestId, responseCode: 200, responseHeaders: [ { name: "content-type", value: "text/plain; charset=utf-8" }, { name: "content-length", value: String(body.length) } ], body: body.toString("base64") }).catch((error) => { console.error(error); }); return; } client.send("Fetch.continueRequest", { requestId: params.requestId }).catch((error) => { console.error(error); }); }); } function registryOperatorFixtureForMode(mode, candidateArtifactBytes = "17160000") { // Supplies compact selector entries for operator receipt provenance smokes. if (mode === "blend-operator-registry" || mode === "blend-operator-receipt-drift") { return { candidateId: "tinylm16-blend-q8", displayName: "TinyLM-16M q8 blend candidate", mateSelectionStatus: "admission-only", mateSelectionParentCount: "1", operatorPath: "tinyrustlm/models/tinylm16-q8-blend.operator", operatorChecksum: "0x00000000000000b4", operatorId: "blend-q8", operatorKind: "direct-parameter-weighted-average", candidateArtifactBytes }; } if (mode === "delta-operator-registry" || mode === "delta-operator-receipt-drift") { return { candidateId: "tinylm16-delta-q8", displayName: "TinyLM-16M q8 delta candidate", mateSelectionStatus: "admission-only", mateSelectionParentCount: "1", operatorPath: "tinyrustlm/models/tinylm16-q8-delta.operator", operatorChecksum: "0x00000000000000b5", operatorId: "delta-q8", operatorKind: "direct-parameter-task-delta", candidateArtifactBytes }; } if (mode === "sparse-delta-operator-registry" || mode === "sparse-delta-operator-receipt-drift") { return { candidateId: "tinylm16-sparse-delta-q8", displayName: "TinyLM-16M q8 sparse-delta candidate", mateSelectionStatus: "admission-only", mateSelectionParentCount: "1", operatorPath: "tinyrustlm/models/tinylm16-q8-sparse-delta.operator", operatorChecksum: "0x00000000000000b6", operatorId: "sparse-delta-q8", operatorKind: "sparse-direct-parameter-task-delta", candidateArtifactBytes }; } if (mode === "dare-operator-registry" || mode === "dare-operator-receipt-drift") { return { candidateId: "tinylm16-dare-q8", displayName: "TinyLM-16M q8 DARE candidate", mateSelectionStatus: "admission-only", mateSelectionParentCount: "1", operatorPath: "tinyrustlm/models/tinylm16-q8-dare.operator", operatorChecksum: "0x00000000000000b7", operatorId: "dare-q8", operatorKind: "dropout-rescaled-task-delta", candidateArtifactBytes }; } if (mode === "prune-operator-registry" || mode === "prune-operator-receipt-drift") { return { candidateId: "tinylm16-prune-q8", displayName: "TinyLM-16M q8 prune candidate", mateSelectionStatus: "admission-only", mateSelectionParentCount: "1", operatorPath: "tinyrustlm/models/tinylm16-q8-prune.operator", operatorChecksum: "0x00000000000000b1", operatorId: "prune-q8", operatorKind: "deterministic-magnitude-parameter-pruning", candidateArtifactBytes }; } if (mode === "crossover-operator-registry" || mode === "crossover-operator-receipt-drift") { return { candidateId: "tinylm16-crossover-q8", displayName: "TinyLM-16M q8 crossover candidate", mateSelectionStatus: "admission-only", mateSelectionParentCount: "1", operatorPath: "tinyrustlm/models/tinylm16-q8-crossover.operator", operatorChecksum: "0x00000000000000b2", operatorId: "crossover-q8", operatorKind: "deterministic-direct-parameter-crossover", candidateArtifactBytes }; } if (mode === "mutation-operator-registry" || mode === "mutation-operator-receipt-drift") { return { candidateId: "tinylm16-mutation-q8", displayName: "TinyLM-16M q8 mutation candidate", mateSelectionStatus: "admission-only", mateSelectionParentCount: "1", operatorPath: "tinyrustlm/models/tinylm16-q8-mutation.operator", operatorChecksum: "0x00000000000000b3", operatorId: "mutation-q8", operatorKind: "deterministic-bounded-parameter-mutation", candidateArtifactBytes }; } return { candidateId: "multi-parent-sign-merge-q8", displayName: "Multi-parent sign-merge q8_0", mateSelectionStatus: "parent-pool-bound", mateSelectionParentCount: "3", operatorPath: "tinyrustlm/models/tinylm16-q8-federated.operator", operatorChecksum: "0x00000000000000b0", operatorId: "federated-local-update-q8", operatorKind: "federated-local-update-average", candidateArtifactBytes }; } function expectedRegistryOperatorKindForModel(modelKey) { // Matches the operator kind expected from the compact selector fixture. if (modelKey === "tinylm16-blend-q8") { return "direct-parameter-weighted-average"; } if (modelKey === "tinylm16-delta-q8") { return "direct-parameter-task-delta"; } if (modelKey === "tinylm16-sparse-delta-q8") { return "sparse-direct-parameter-task-delta"; } if (modelKey === "tinylm16-dare-q8") { return "dropout-rescaled-task-delta"; } if (modelKey === "tinylm16-prune-q8") { return "deterministic-magnitude-parameter-pruning"; } if (modelKey === "tinylm16-crossover-q8") { return "deterministic-direct-parameter-crossover"; } if (modelKey === "tinylm16-mutation-q8") { return "deterministic-bounded-parameter-mutation"; } if (modelKey === "multi-parent-sign-merge-q8" && smokeMode === "multi-parent-registry") { return "federated-local-update-average"; } return ""; } // Serves a compact registry fixture that exercises selector provenance and operator receipt rendering. function installMultiParentRegistryInterceptor(client, fixture = registryOperatorFixtureForMode(smokeMode)) { client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; if (requestUrl.includes("/models/selector.registry")) { const body = Buffer.from([ "tinyrustlm_selector_registry_version=1", "selector_id=browser-local-selector", "registry_scope=browser-local-model-selector", "registry_status=admitted-records-only", "selector_model_byte_budget=33554432", "selector_registry_text_byte_budget=262144", "manifest_text_byte_budget=65536", "receipt_text_byte_budget=131072", "evidence_text_byte_budget=131072", "entry_count=1", "admission_set_checksum=0x0000000000000049", `entry.0.candidate_id=${fixture.candidateId}`, `entry.0.display_name=${fixture.displayName}`, "entry.0.model_path=../models/tinylm16-q8.slm", "entry.0.manifest_path=../models/tinylm16-q8.slm.manifest", "entry.0.artifact_path=tinyrustlm/models/tinylm16-q8.slm", "entry.0.max_tokens=8", "entry.0.model_bytes=17160000", "entry.0.slm_checksum=0xa1442f3f180c542b", "entry.0.model_shape=vocab=260,hidden=512,layers=4,heads=8,kv_heads=8,head_dim=64,ffn=2048,context=512", "entry.0.quantization=q8_0", "entry.0.output_contract=separate-output-weight", "entry.0.genome_id=0x00000000000000a1", "entry.0.genome_strategy=selector-admission-genome-v1", "entry.0.genome_lineage_status=admission-bound", "entry.0.genome_lineage_checksum=0x00000000000000a2", "entry.0.species_id=0x00000000000000a3", "entry.0.species_strategy=selector-speciation-fit-v1", "entry.0.species_fit_status=browser-fit-bound", "entry.0.species_fit_checksum=0x00000000000000a4", "entry.0.novelty_id=0x00000000000000a6", "entry.0.novelty_strategy=selector-novelty-sketch-v1", "entry.0.novelty_status=behavior-sketch-bound", "entry.0.novelty_checksum=0x00000000000000a7", "entry.0.population_id=0x00000000000000a8", "entry.0.population_strategy=selector-population-review-route-v1", "entry.0.population_status=population-review-bound", "entry.0.population_checksum=0x00000000000000a9", "entry.0.mate_selection_id=0x00000000000000aa", "entry.0.mate_selection_strategy=selector-mate-selection-route-v1", `entry.0.mate_selection_status=${fixture.mateSelectionStatus}`, `entry.0.mate_selection_parent_count=${fixture.mateSelectionParentCount}`, "entry.0.mate_selection_checksum=0x00000000000000ab", "entry.0.operator_receipt_status=receipt-bound", `entry.0.operator_receipt_path=${fixture.operatorPath}`, `entry.0.operator_receipt_checksum=${fixture.operatorChecksum}`, `entry.0.operator_receipt_operator_id=${fixture.operatorId}`, `entry.0.operator_receipt_operator_kind=${fixture.operatorKind}`, "entry.0.operator_receipt_candidate_slm_checksum=0xa1442f3f180c542b", `entry.0.operator_receipt_candidate_artifact_bytes=${fixture.candidateArtifactBytes}`, "entry.0.phenotype_evidence_id=0x00000000000000ac", "entry.0.phenotype_evidence_strategy=selector-phenotype-evidence-v1", "entry.0.phenotype_evidence_status=runtime-eval-bound", "entry.0.phenotype_evidence_checksum=0x00000000000000ad", "entry.0.heritable_artifact_id=0x00000000000000ae", "entry.0.heritable_artifact_strategy=selector-heritable-artifact-v1", "entry.0.heritable_artifact_status=served-artifact-bound", "entry.0.heritable_artifact_checksum=0x00000000000000af", "entry.0.admission_checksum=0x0000000000000050", "entry.0.promotion_manifest_checksum=0x0000000000000051", "entry.0.provenance_manifest_checksum=0x0000000000000055", "entry.0.runtime_smoke_manifest_checksum=0x0000000000000052", "entry.0.eval_manifest_checksum=0x0000000000000053", "entry.0.eval_case_evidence_checksum=0x0000000000000054", "entry.0.quality_scope=tiny-fixture-runtime-eval-only", "entry.0.quality_boundary=fixture-runtime-and-eval-plumbing-not-product-assistant-quality", "entry.0.eval_dataset=tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", "entry.0.cases_passed=1", "entry.0.fitness_vector_status=eval-bound", "entry.0.fitness_vector_checksum=0x00000000000000a5", "entry.0.selector_status=admitted", "entry.0.public_claim_status=bound-to-eval-scope", "required_next_gate=browser-loads-selector-registry-entry-models", "" ].join("\n"), "utf8"); client.send("Fetch.fulfillRequest", { requestId: params.requestId, responseCode: 200, responseHeaders: [ { name: "content-type", value: "text/plain; charset=utf-8" }, { name: "content-length", value: String(body.length) } ], body: body.toString("base64") }).catch((error) => { console.error(error); }); return; } client.send("Fetch.continueRequest", { requestId: params.requestId }).catch((error) => { console.error(error); }); }); } // Builds the manifest body for the converted-trained browser provenance smoke. function convertedTrainedRegistryManifestText() { return [ "tinyrustlm_slm_manifest_version=1", "model_path=tinyrustlm\\models\\converted-trained-q8.slm", "model_bytes=8832", "slm_version=1", "slm_checksum=0x481f1037d57ebcd3", "model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16", "tensor_count=12", "parameter_count=4824", "quantization=q8_0", "source_kind=converted-trained", "quality_claim=runtime-compatible-not-quality-verified", "trained_quality_claim=pending-evaluation", "admission_status=structure-accepted-quality-pending", "required_next_gate=task-eval-and-safety-review-before-assistant-quality-claim", "" ].join("\n"); } // Builds a compact selector registry that routes a local converted-trained q8 artifact. function convertedTrainedRegistryText() { return [ "tinyrustlm_selector_registry_version=1", "selector_id=browser-local-selector", "registry_scope=browser-local-model-selector", "registry_status=admitted-records-only", "selector_model_byte_budget=33554432", "selector_registry_text_byte_budget=262144", "manifest_text_byte_budget=65536", "receipt_text_byte_budget=131072", "evidence_text_byte_budget=131072", "entry_count=1", "admission_set_checksum=0x0000000000000071", "entry.0.candidate_id=converted-trained-q8", "entry.0.display_name=Converted trained-source q8_0", "entry.0.model_path=../models/converted-trained-q8.slm", "entry.0.manifest_path=../models/converted-trained-q8.slm.manifest", "entry.0.artifact_path=tinyrustlm/models/converted-trained-q8.slm", "entry.0.max_tokens=8", "entry.0.model_bytes=8832", "entry.0.slm_checksum=0x481f1037d57ebcd3", "entry.0.tokenizer_checksum=0x289d76790aca3acb", "entry.0.model_shape=vocab=260,hidden=8,layers=1,heads=2,kv_heads=2,head_dim=4,ffn=16,context=16", "entry.0.quantization=q8_0", "entry.0.output_contract=separate-output-weight", "entry.0.genome_id=0x0000000000000171", "entry.0.genome_strategy=selector-admission-genome-v1", "entry.0.genome_lineage_status=admission-bound", "entry.0.genome_lineage_checksum=0x0000000000000172", "entry.0.species_id=0x0000000000000173", "entry.0.species_strategy=selector-speciation-fit-v1", "entry.0.species_fit_status=browser-fit-bound", "entry.0.species_fit_checksum=0x0000000000000174", "entry.0.novelty_id=0x0000000000000176", "entry.0.novelty_strategy=selector-novelty-sketch-v1", "entry.0.novelty_status=behavior-sketch-bound", "entry.0.novelty_checksum=0x0000000000000177", "entry.0.population_id=0x0000000000000178", "entry.0.population_strategy=selector-population-review-route-v1", "entry.0.population_status=population-review-bound", "entry.0.population_checksum=0x0000000000000179", "entry.0.mate_selection_id=0x000000000000017a", "entry.0.mate_selection_strategy=selector-mate-selection-route-v1", "entry.0.mate_selection_status=admission-only", "entry.0.mate_selection_parent_count=1", "entry.0.mate_selection_checksum=0x000000000000017b", "entry.0.phenotype_evidence_id=0x000000000000017c", "entry.0.phenotype_evidence_strategy=selector-phenotype-evidence-v1", "entry.0.phenotype_evidence_status=runtime-eval-bound", "entry.0.phenotype_evidence_checksum=0x000000000000017d", "entry.0.heritable_artifact_id=0x000000000000017e", "entry.0.heritable_artifact_strategy=selector-heritable-artifact-v1", "entry.0.heritable_artifact_status=served-artifact-bound", "entry.0.heritable_artifact_checksum=0x000000000000017f", "entry.0.admission_checksum=0x0000000000000072", "entry.0.promotion_manifest_checksum=0x0000000000000073", "entry.0.provenance_manifest_checksum=0x0000000000000077", "entry.0.runtime_smoke_manifest_checksum=0x0000000000000074", "entry.0.eval_manifest_checksum=0x0000000000000075", "entry.0.eval_case_evidence_checksum=0x0000000000000076", "entry.0.quality_scope=tiny-fixture-runtime-eval-only", "entry.0.quality_boundary=fixture-runtime-and-eval-plumbing-not-product-assistant-quality", "entry.0.eval_dataset=tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", "entry.0.cases_passed=1", "entry.0.fitness_vector_status=eval-bound", "entry.0.fitness_vector_checksum=0x0000000000000175", "entry.0.selector_status=admitted", "entry.0.public_claim_status=bound-to-eval-scope", "required_next_gate=browser-loads-selector-registry-entry-models", "" ].join("\n"); } // Serves a local converted-trained model route by reusing the checked tiny q8 bytes with a converted-trained manifest. function installConvertedTrainedRegistryInterceptor(client) { client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; (async () => { if (requestUrlPathEquals(requestUrl, "/models/selector.registry")) { await fulfillTextRequest(client, params.requestId, convertedTrainedRegistryText()); return; } if (requestUrlPathEquals(requestUrl, "/models/converted-trained-q8.slm.manifest")) { await fulfillTextRequest(client, params.requestId, convertedTrainedRegistryManifestText()); return; } if (requestUrlPathEquals(requestUrl, "/models/converted-trained-q8.slm")) { const sourceUrl = new URL("/models/tiny-test-model-q8.slm", requestUrl).toString(); await fulfillBinaryRequest(client, params.requestId, await getBuffer(sourceUrl)); return; } await continuePausedRequest(client, params.requestId); })().catch((error) => { console.error(error); continuePausedRequest(client, params.requestId).catch((continueError) => { console.error(continueError); }); }); }); } // Serves a selector registry whose operator receipt byte echo no longer matches the model entry. function installSelectorOperatorReceiptDriftInterceptor( client, fixture = registryOperatorFixtureForMode(smokeMode, "17159999") ) { client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; if (requestUrl.includes("/models/selector.registry")) { const body = Buffer.from([ "tinyrustlm_selector_registry_version=1", "selector_id=browser-local-selector", "registry_scope=browser-local-model-selector", "registry_status=admitted-records-only", "selector_model_byte_budget=33554432", "selector_registry_text_byte_budget=262144", "manifest_text_byte_budget=65536", "receipt_text_byte_budget=131072", "evidence_text_byte_budget=131072", "entry_count=1", "admission_set_checksum=0x0000000000000049", `entry.0.candidate_id=${fixture.candidateId}`, `entry.0.display_name=${fixture.displayName}`, "entry.0.model_path=../models/tinylm16-q8.slm", "entry.0.manifest_path=../models/tinylm16-q8.slm.manifest", "entry.0.artifact_path=tinyrustlm/models/tinylm16-q8.slm", "entry.0.max_tokens=8", "entry.0.model_bytes=17160000", "entry.0.slm_checksum=0xa1442f3f180c542b", "entry.0.model_shape=vocab=260,hidden=512,layers=4,heads=8,kv_heads=8,head_dim=64,ffn=2048,context=512", "entry.0.quantization=q8_0", "entry.0.output_contract=separate-output-weight", "entry.0.genome_id=0x00000000000000a1", "entry.0.genome_strategy=selector-admission-genome-v1", "entry.0.genome_lineage_status=admission-bound", "entry.0.genome_lineage_checksum=0x00000000000000a2", "entry.0.species_id=0x00000000000000a3", "entry.0.species_strategy=selector-speciation-fit-v1", "entry.0.species_fit_status=browser-fit-bound", "entry.0.species_fit_checksum=0x00000000000000a4", "entry.0.novelty_id=0x00000000000000a6", "entry.0.novelty_strategy=selector-novelty-sketch-v1", "entry.0.novelty_status=behavior-sketch-bound", "entry.0.novelty_checksum=0x00000000000000a7", "entry.0.population_id=0x00000000000000a8", "entry.0.population_strategy=selector-population-review-route-v1", "entry.0.population_status=population-review-bound", "entry.0.population_checksum=0x00000000000000a9", "entry.0.mate_selection_id=0x00000000000000aa", "entry.0.mate_selection_strategy=selector-mate-selection-route-v1", `entry.0.mate_selection_status=${fixture.mateSelectionStatus}`, `entry.0.mate_selection_parent_count=${fixture.mateSelectionParentCount}`, "entry.0.mate_selection_checksum=0x00000000000000ab", "entry.0.operator_receipt_status=receipt-bound", `entry.0.operator_receipt_path=${fixture.operatorPath}`, `entry.0.operator_receipt_checksum=${fixture.operatorChecksum}`, `entry.0.operator_receipt_operator_id=${fixture.operatorId}`, `entry.0.operator_receipt_operator_kind=${fixture.operatorKind}`, "entry.0.operator_receipt_candidate_slm_checksum=0xa1442f3f180c542b", `entry.0.operator_receipt_candidate_artifact_bytes=${fixture.candidateArtifactBytes}`, "entry.0.phenotype_evidence_id=0x00000000000000ac", "entry.0.phenotype_evidence_strategy=selector-phenotype-evidence-v1", "entry.0.phenotype_evidence_status=runtime-eval-bound", "entry.0.phenotype_evidence_checksum=0x00000000000000ad", "entry.0.heritable_artifact_id=0x00000000000000ae", "entry.0.heritable_artifact_strategy=selector-heritable-artifact-v1", "entry.0.heritable_artifact_status=served-artifact-bound", "entry.0.heritable_artifact_checksum=0x00000000000000af", "entry.0.admission_checksum=0x0000000000000050", "entry.0.promotion_manifest_checksum=0x0000000000000051", "entry.0.provenance_manifest_checksum=0x0000000000000055", "entry.0.runtime_smoke_manifest_checksum=0x0000000000000052", "entry.0.eval_manifest_checksum=0x0000000000000053", "entry.0.eval_case_evidence_checksum=0x0000000000000054", "entry.0.quality_scope=tiny-fixture-runtime-eval-only", "entry.0.quality_boundary=fixture-runtime-and-eval-plumbing-not-product-assistant-quality", "entry.0.eval_dataset=tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", "entry.0.cases_passed=1", "entry.0.fitness_vector_status=eval-bound", "entry.0.fitness_vector_checksum=0x00000000000000a5", "entry.0.selector_status=admitted", "entry.0.public_claim_status=bound-to-eval-scope", "required_next_gate=browser-loads-selector-registry-entry-models", "" ].join("\n"), "utf8"); client.send("Fetch.fulfillRequest", { requestId: params.requestId, responseCode: 200, responseHeaders: [ { name: "content-type", value: "text/plain; charset=utf-8" }, { name: "content-length", value: String(body.length) } ], body: body.toString("base64") }).catch((error) => { console.error(error); }); return; } client.send("Fetch.continueRequest", { requestId: params.requestId }).catch((error) => { console.error(error); }); }); } // Serves generated roots with a caller-selected selector receipt mutation and static q8 fallback. function installGeneratedSelectorOperatorReceiptDriftInterceptor( client, driftRegistryText = driftGeneratedSelectorOperatorReceiptBytes ) { const fallbackModelPath = path.join(__dirname, "..", "models", "tinylm16-q8.slm"); const fallbackManifestPath = path.join(__dirname, "..", "models", "tinylm16-q8.slm.manifest"); client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; (async () => { if (requestUrlPathEquals(requestUrl, "/models/selector.registry")) { const registryText = await getText(requestUrl); await fulfillTextRequest( client, params.requestId, driftRegistryText(registryText) ); return; } if (requestUrlPathEquals(requestUrl, "/models/tinylm16-q8.slm")) { await fulfillBinaryRequest(client, params.requestId, Buffer.from(fs.readFileSync(fallbackModelPath))); return; } if (requestUrlPathEquals(requestUrl, "/models/tinylm16-q8.slm.manifest")) { await fulfillTextRequest(client, params.requestId, fs.readFileSync(fallbackManifestPath, "utf8")); return; } await continuePausedRequest(client, params.requestId); })().catch((error) => { console.error(error); continuePausedRequest(client, params.requestId).catch((continueError) => { console.error(continueError); }); }); }); } function installSelectorBudgetRegistryInterceptor(client) { client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; if (requestUrl.includes("/models/selector.registry")) { const body = Buffer.from([ "tinyrustlm_selector_registry_version=1", "selector_id=browser-local-selector", "registry_scope=browser-local-model-selector", "registry_status=admitted-records-only", "selector_model_byte_budget=33554432", "selector_registry_text_byte_budget=262144", "manifest_text_byte_budget=65536", "receipt_text_byte_budget=131072", "evidence_text_byte_budget=131072", "entry_count=1", "admission_set_checksum=0x0000000000000081", "entry.0.candidate_id=oversized-browser-parent", "entry.0.display_name=Oversized browser parent q4_0", "entry.0.model_path=../models/oversized-browser-parent.slm", "entry.0.manifest_path=../models/oversized-browser-parent.slm.manifest", "entry.0.artifact_path=tinyrustlm/models/oversized-browser-parent.slm", "entry.0.max_tokens=8", "entry.0.model_bytes=33554433", "entry.0.slm_checksum=0x0000000000000082", "entry.0.model_shape=vocab=260,hidden=512,layers=4,heads=8,kv_heads=8,head_dim=64,ffn=2048,context=512", "entry.0.quantization=q4_0", "entry.0.output_contract=separate-output-weight", "entry.0.genome_id=0x00000000000000b1", "entry.0.genome_strategy=selector-admission-genome-v1", "entry.0.genome_lineage_status=admission-bound", "entry.0.genome_lineage_checksum=0x00000000000000b2", "entry.0.species_id=0x00000000000000b3", "entry.0.species_strategy=selector-speciation-fit-v1", "entry.0.species_fit_status=browser-fit-bound", "entry.0.species_fit_checksum=0x00000000000000b4", "entry.0.novelty_id=0x00000000000000b6", "entry.0.novelty_strategy=selector-novelty-sketch-v1", "entry.0.novelty_status=behavior-sketch-bound", "entry.0.novelty_checksum=0x00000000000000b7", "entry.0.population_id=0x00000000000000b8", "entry.0.population_strategy=selector-population-review-route-v1", "entry.0.population_status=population-review-bound", "entry.0.population_checksum=0x00000000000000b9", "entry.0.mate_selection_id=0x00000000000000ba", "entry.0.mate_selection_strategy=selector-mate-selection-route-v1", "entry.0.mate_selection_status=parent-pool-bound", "entry.0.mate_selection_parent_count=3", "entry.0.mate_selection_checksum=0x00000000000000bb", "entry.0.phenotype_evidence_id=0x00000000000000bc", "entry.0.phenotype_evidence_strategy=selector-phenotype-evidence-v1", "entry.0.phenotype_evidence_status=runtime-eval-bound", "entry.0.phenotype_evidence_checksum=0x00000000000000bd", "entry.0.heritable_artifact_id=0x00000000000000be", "entry.0.heritable_artifact_strategy=selector-heritable-artifact-v1", "entry.0.heritable_artifact_status=served-artifact-bound", "entry.0.heritable_artifact_checksum=0x00000000000000bf", "entry.0.admission_checksum=0x0000000000000083", "entry.0.promotion_manifest_checksum=0x0000000000000084", "entry.0.provenance_manifest_checksum=0x0000000000000088", "entry.0.runtime_smoke_manifest_checksum=0x0000000000000085", "entry.0.eval_manifest_checksum=0x0000000000000086", "entry.0.eval_case_evidence_checksum=0x0000000000000087", "entry.0.quality_scope=tiny-fixture-runtime-eval-only", "entry.0.quality_boundary=fixture-runtime-and-eval-plumbing-not-product-assistant-quality", "entry.0.eval_dataset=tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", "entry.0.cases_passed=1", "entry.0.fitness_vector_status=eval-bound", "entry.0.fitness_vector_checksum=0x00000000000000b5", "entry.0.selector_status=admitted", "entry.0.public_claim_status=bound-to-eval-scope", "required_next_gate=browser-loads-selector-registry-entry-models", "" ].join("\n"), "utf8"); client.send("Fetch.fulfillRequest", { requestId: params.requestId, responseCode: 200, responseHeaders: [ { name: "content-type", value: "text/plain; charset=utf-8" }, { name: "content-length", value: String(body.length) } ], body: body.toString("base64") }).catch((error) => { console.error(error); }); return; } client.send("Fetch.continueRequest", { requestId: params.requestId }).catch((error) => { console.error(error); }); }); } function installSidecarBudgetContractRegistryInterceptor(client) { client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; if (requestUrl.includes("/models/selector.registry")) { const body = Buffer.from([ "tinyrustlm_selector_registry_version=1", "selector_id=browser-local-selector", "registry_scope=browser-local-model-selector", "registry_status=admitted-records-only", "selector_model_byte_budget=33554432", "selector_registry_text_byte_budget=262144", "manifest_text_byte_budget=65537", "receipt_text_byte_budget=131072", "evidence_text_byte_budget=131072", "entry_count=1", "admission_set_checksum=0x0000000000000091", "entry.0.candidate_id=sidecar-budget-contract-parent", "entry.0.display_name=Sidecar budget contract parent q4_0", "entry.0.model_path=../models/sidecar-budget-contract-parent.slm", "entry.0.manifest_path=../models/sidecar-budget-contract-parent.slm.manifest", "entry.0.artifact_path=tinyrustlm/models/sidecar-budget-contract-parent.slm", "entry.0.max_tokens=8", "entry.0.model_bytes=6592", "entry.0.slm_checksum=0x0000000000000092", "entry.0.model_shape=vocab=260,hidden=16,layers=1,heads=2,kv_heads=2,head_dim=8,ffn=32,context=32", "entry.0.quantization=q4_0", "entry.0.output_contract=separate-output-weight", "entry.0.genome_id=0x00000000000000c1", "entry.0.genome_strategy=selector-admission-genome-v1", "entry.0.genome_lineage_status=admission-bound", "entry.0.genome_lineage_checksum=0x00000000000000c2", "entry.0.species_id=0x00000000000000c3", "entry.0.species_strategy=selector-speciation-fit-v1", "entry.0.species_fit_status=browser-fit-bound", "entry.0.species_fit_checksum=0x00000000000000c4", "entry.0.novelty_id=0x00000000000000c6", "entry.0.novelty_strategy=selector-novelty-sketch-v1", "entry.0.novelty_status=behavior-sketch-bound", "entry.0.novelty_checksum=0x00000000000000c7", "entry.0.population_id=0x00000000000000c8", "entry.0.population_strategy=selector-population-review-route-v1", "entry.0.population_status=population-review-bound", "entry.0.population_checksum=0x00000000000000c9", "entry.0.mate_selection_id=0x00000000000000ca", "entry.0.mate_selection_strategy=selector-mate-selection-route-v1", "entry.0.mate_selection_status=parent-pool-bound", "entry.0.mate_selection_parent_count=3", "entry.0.mate_selection_checksum=0x00000000000000cb", "entry.0.phenotype_evidence_id=0x00000000000000cc", "entry.0.phenotype_evidence_strategy=selector-phenotype-evidence-v1", "entry.0.phenotype_evidence_status=runtime-eval-bound", "entry.0.phenotype_evidence_checksum=0x00000000000000cd", "entry.0.heritable_artifact_id=0x00000000000000ce", "entry.0.heritable_artifact_strategy=selector-heritable-artifact-v1", "entry.0.heritable_artifact_status=served-artifact-bound", "entry.0.heritable_artifact_checksum=0x00000000000000cf", "entry.0.admission_checksum=0x0000000000000093", "entry.0.promotion_manifest_checksum=0x0000000000000094", "entry.0.provenance_manifest_checksum=0x0000000000000098", "entry.0.runtime_smoke_manifest_checksum=0x0000000000000095", "entry.0.eval_manifest_checksum=0x0000000000000096", "entry.0.eval_case_evidence_checksum=0x0000000000000097", "entry.0.quality_scope=tiny-fixture-runtime-eval-only", "entry.0.quality_boundary=fixture-runtime-and-eval-plumbing-not-product-assistant-quality", "entry.0.eval_dataset=tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", "entry.0.cases_passed=1", "entry.0.fitness_vector_status=eval-bound", "entry.0.fitness_vector_checksum=0x00000000000000c5", "entry.0.selector_status=admitted", "entry.0.public_claim_status=bound-to-eval-scope", "required_next_gate=browser-loads-selector-registry-entry-models", "" ].join("\n"), "utf8"); client.send("Fetch.fulfillRequest", { requestId: params.requestId, responseCode: 200, responseHeaders: [ { name: "content-type", value: "text/plain; charset=utf-8" }, { name: "content-length", value: String(body.length) } ], body: body.toString("base64") }).catch((error) => { console.error(error); }); return; } client.send("Fetch.continueRequest", { requestId: params.requestId }).catch((error) => { console.error(error); }); }); } function installRuntimeManifestDriftInterceptor(client) { const runtimeWasmPath = path.join(__dirname, "..", "runtime", "tinyrustlm.wasm"); const runtimeWasmBytes = fs.statSync(runtimeWasmPath).size; client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; if (requestUrl.includes("/runtime/tinyrustlm.wasm.manifest")) { const body = Buffer.from([ "tinyrustlm_wasm_manifest_version=1", "runtime_kind=tinyrustlm-rust-wasm", "runtime_status=validated-local-runtime", "runtime_wasm_path=../runtime/tinyrustlm.wasm", `runtime_wasm_bytes=${runtimeWasmBytes}`, "runtime_wasm_checksum=0x0000000000000001", "required_next_gate=instantiate-wasm-runtime", "" ].join("\n"), "utf8"); client.send("Fetch.fulfillRequest", { requestId: params.requestId, responseCode: 200, responseHeaders: [ { name: "content-type", value: "text/plain; charset=utf-8" }, { name: "content-length", value: String(body.length) } ], body: body.toString("base64") }).catch((error) => { console.error(error); }); return; } client.send("Fetch.continueRequest", { requestId: params.requestId }).catch((error) => { console.error(error); }); }); } function installModulePlanDriftInterceptor(client, modelKey, driftReceiptText) { const modulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!modulePlanRoute) { throw new Error(`no module plan route is known for ${modelKey}`); } client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; (async () => { if (requestUrl.includes("/models/selector.registry")) { const registryText = await getText(requestUrl); const receiptUrl = new URL(modulePlanRoute, requestUrl).toString(); const receiptText = await getText(receiptUrl); const driftedReceiptText = driftReceiptText(receiptText); const driftedRegistryText = updateRegistryModulePlanChecksum( registryText, modelKey, textChecksumHex(driftedReceiptText) ); await fulfillTextRequest(client, params.requestId, driftedRegistryText); return; } if (requestUrl.includes(modulePlanRoute)) { const receiptText = await getText(requestUrl); await fulfillTextRequest(client, params.requestId, driftReceiptText(receiptText)); return; } await continuePausedRequest(client, params.requestId); })().catch((error) => { console.error(error); continuePausedRequest(client, params.requestId).catch((continueError) => { console.error(continueError); }); }); }); } function installModulePlanResourceDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanResourceEnvelope); } function installModulePlanRuntimeScratchDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanRuntimeScratchBudget); } function installModulePlanOutputLimitDriftInterceptor(client, modelKey) { // Routes output-limit drift through the shared module-plan receipt interceptor. installModulePlanDriftInterceptor(client, modelKey, driftModulePlanOutputByteLimit); } function installModulePlanPromptLimitDriftInterceptor(client, modelKey) { // Routes prompt-limit drift through the shared module-plan receipt interceptor. installModulePlanDriftInterceptor(client, modelKey, driftModulePlanPromptByteLimit); } function installModulePlanFetchCountDriftInterceptor(client, modelKey) { // Routes fetch-count drift through the shared module-plan receipt interceptor. installModulePlanDriftInterceptor(client, modelKey, driftModulePlanFetchCountLimit); } function installModulePlanPlannedFetchCountDriftInterceptor(client, modelKey) { // Routes planned-fetch drift through the shared module-plan receipt interceptor. installModulePlanDriftInterceptor(client, modelKey, driftModulePlanPlannedFetchCount); } function installModulePlanRouteSetVersionDriftInterceptor(client, modelKey) { // Routes route-set version drift through the shared module-plan receipt interceptor. installModulePlanDriftInterceptor(client, modelKey, driftModulePlanRouteSetVersion); } function installModulePlanRouteSetAlgorithmDriftInterceptor(client, modelKey) { // Routes route-set algorithm drift through the shared module-plan receipt interceptor. installModulePlanDriftInterceptor(client, modelKey, driftModulePlanRouteSetChecksumAlgorithm); } function installModulePlanRouteSetDriftInterceptor(client, modelKey) { // Routes route-set drift through the shared module-plan receipt interceptor. installModulePlanDriftInterceptor(client, modelKey, driftModulePlanRouteSetChecksum); } function installModulePlanOperatorReceiptDriftInterceptor(client, modelKey) { // Routes operator-receipt drift through checksum-consistent module-plan interception. installModulePlanDriftInterceptor(client, modelKey, driftModulePlanOperatorReceiptChecksum); } function installModulePlanKvCacheDriftInterceptor(client, modelKey) { // Wires the KV drift mutation into the shared module-plan interception path. installModulePlanDriftInterceptor(client, modelKey, driftModulePlanKvCachePageCount); } function installModulePlanAdapterStackBudgetDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanAdapterStackBudget); } function installModulePlanTotalBudgetDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanTotalBudget); } function installModulePlanTotalLimitDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanTotalLimit); } // Hooks count drift into checksum-consistent module-plan receipt interception. function installModulePlanCountDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanCount); } function installModulePlanWasmMemoryDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanWasmMemory); } function installModulePlanWasmExportSetDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanWasmExportSet); } function installModulePlanWasmTransferDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanWasmTransferStrategy); } function installModulePlanModelReleaseDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanModelReleaseStrategy); } function installModulePlanRuntimeResetDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanRuntimeResetStrategy); } function installModulePlanAdapterValidationDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanAdapterValidationStrategy); } function installModulePlanAdapterValidationCountDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanAdapterValidationCount); } function installModulePlanAdapterApplyCountDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanAdapterApplyCount); } function installModulePlanWasmHeapDriftInterceptor(client, modelKey) { // Routes the allocator floor through checksum-consistent module-plan interception. installModulePlanDriftInterceptor(client, modelKey, driftModulePlanWasmHeapMinBytes); } function installModulePlanContextTokenDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanContextTokenLimit); } function installModulePlanSamplerCapDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanSamplerCandidateCap); } function installModulePlanTokenizerDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanTokenizerChecksum); } function installModulePlanProfileDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanProfile); } function installModulePlanExecutionProfileDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanExecutionProfile); } function installModulePlanFetchPolicyDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanFetchPolicy); } function installModulePlanOriginPolicyDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanOriginPolicy); } function installModulePlanGraphDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanGraph); } function installModulePlanStackDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanStackMember); } function installModulePlanRoleDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanRole); } function installModulePlanSlotDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanSlot); } function installModulePlanPhaseDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanPhase); } function installModulePlanByteDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanByteCount); } function installModulePlanChecksumDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanChecksum); } function installModulePlanDependencyDriftInterceptor(client, modelKey) { installModulePlanDriftInterceptor(client, modelKey, driftModulePlanDependency); } function installAssemblyEvalCaseDriftInterceptor(client, modelKey) { const assemblyReceiptRoute = expectedAssemblyReceiptRoutes[modelKey]; const modulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!assemblyReceiptRoute || !modulePlanRoute) { throw new Error(`no generated assembly route is known for ${modelKey}`); } async function driftedAssemblyText(requestUrl) { const receiptUrl = new URL(assemblyReceiptRoute, requestUrl).toString(); return driftAssemblyEvalCaseEvidenceChecksum(await getText(receiptUrl)); } async function driftedModulePlanText(requestUrl, assemblyChecksum) { const modulePlanUrl = new URL(modulePlanRoute, requestUrl).toString(); return updateModulePlanAssemblyReceiptChecksum(await getText(modulePlanUrl), assemblyChecksum); } client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; (async () => { if (requestUrl.includes("/models/selector.registry")) { const registryText = await getText(requestUrl); const assemblyText = await driftedAssemblyText(requestUrl); const assemblyChecksum = textChecksumHex(assemblyText); const modulePlanText = await driftedModulePlanText(requestUrl, assemblyChecksum); let driftedRegistryText = updateRegistryAssemblyReceiptChecksum( registryText, modelKey, assemblyChecksum ); driftedRegistryText = updateRegistryModulePlanChecksum( driftedRegistryText, modelKey, textChecksumHex(modulePlanText) ); await fulfillTextRequest(client, params.requestId, driftedRegistryText); return; } if (requestUrl.includes(modulePlanRoute)) { const assemblyText = await driftedAssemblyText(requestUrl); const modulePlanText = await driftedModulePlanText(requestUrl, textChecksumHex(assemblyText)); await fulfillTextRequest(client, params.requestId, modulePlanText); return; } if (requestUrl.includes(assemblyReceiptRoute)) { await fulfillTextRequest(client, params.requestId, await driftedAssemblyText(requestUrl)); return; } await continuePausedRequest(client, params.requestId); })().catch((error) => { console.error(error); continuePausedRequest(client, params.requestId).catch((continueError) => { console.error(continueError); }); }); }); } function installAssemblyEvidenceFileDriftInterceptor(client, modelKey) { const evidenceRoute = (expectedAssemblyEvidenceRoutes[modelKey] || [])[0]; if (!evidenceRoute) { throw new Error(`no generated assembly evidence route is known for ${modelKey}`); } client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; (async () => { if (requestUrl.includes(evidenceRoute)) { const evidenceText = await getText(requestUrl); await fulfillTextRequest(client, params.requestId, driftAssemblyEvidenceFileText(evidenceText)); return; } await continuePausedRequest(client, params.requestId); })().catch((error) => { console.error(error); continuePausedRequest(client, params.requestId).catch((continueError) => { console.error(continueError); }); }); }); } function installAdapterFamilyReceiptDriftInterceptor(client, modelKey) { const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; if (!adapterFamilyRoute) { throw new Error(`no generated adapter-family receipt route is known for ${modelKey}`); } client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; (async () => { if (requestUrl.includes(adapterFamilyRoute)) { const receiptText = await getText(requestUrl); await fulfillTextRequest(client, params.requestId, driftAdapterFamilyReceiptText(receiptText)); return; } await continuePausedRequest(client, params.requestId); })().catch((error) => { console.error(error); continuePausedRequest(client, params.requestId).catch((continueError) => { console.error(continueError); }); }); }); } function installAdapterManifestDriftInterceptor(client, modelKey) { const adapterManifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; const adapterManifestRoute = adapterManifestRoutes[1]; if (!adapterManifestRoute) { throw new Error(`no generated family adapter manifest route is known for ${modelKey}`); } client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; (async () => { if (requestUrl.includes(adapterManifestRoute)) { const manifestText = await getText(requestUrl); await fulfillTextRequest(client, params.requestId, driftAdapterManifestText(manifestText)); return; } await continuePausedRequest(client, params.requestId); })().catch((error) => { console.error(error); continuePausedRequest(client, params.requestId).catch((continueError) => { console.error(continueError); }); }); }); } // Installs a coherent ALR1 manifest drift that reaches the source-backed contract comparison. function installSourceBackedAlr1ManifestDriftInterceptor(client, modelKey) { const adapterIndex = 3; const moduleIndex = 6; const adapterManifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; const adapterManifestRoute = adapterManifestRoutes[adapterIndex]; const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; const assemblyReceiptRoute = expectedAssemblyReceiptRoutes[modelKey]; const modulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!adapterManifestRoute || !adapterFamilyRoute || !assemblyReceiptRoute || !modulePlanRoute) { throw new Error(`generated source-backed ALR1 drift routes were incomplete for ${modelKey}`); } let driftPromise = null; // Builds every drifted text artifact from a single source contract mutation. async function buildDrift(requestUrl) { const manifestText = driftSourceBackedAlr1ManifestText( await getText(new URL(adapterManifestRoute, requestUrl).toString()) ); const manifestChecksum = textChecksumHex(manifestText); const adapterFamilyText = updateAdapterFamilyMemberManifestChecksum( await getText(new URL(adapterFamilyRoute, requestUrl).toString()), adapterIndex, manifestChecksum ); const adapterFamilyChecksum = textChecksumHex(adapterFamilyText); const assemblyReceiptText = updateAssemblyAdapterFamilyReceiptChecksum( await getText(new URL(assemblyReceiptRoute, requestUrl).toString()), adapterFamilyChecksum ); const assemblyReceiptChecksum = textChecksumHex(assemblyReceiptText); let modulePlanText = await getText(new URL(modulePlanRoute, requestUrl).toString()); modulePlanText = updateModulePlanAssemblyReceiptChecksum(modulePlanText, assemblyReceiptChecksum); modulePlanText = updateModulePlanAdapterFamilyReceiptChecksum(modulePlanText, adapterFamilyChecksum); modulePlanText = updateModulePlanAdapterManifestChecksum(modulePlanText, moduleIndex, manifestChecksum); const modulePlanChecksum = textChecksumHex(modulePlanText); let registryText = await getText(new URL("/models/selector.registry", requestUrl).toString()); registryText = updateRegistryAdapterManifestChecksum( registryText, modelKey, adapterIndex, manifestChecksum ); registryText = updateRegistryAdapterFamilyReceiptChecksum( registryText, modelKey, adapterFamilyChecksum ); registryText = updateRegistryAssemblyReceiptChecksum( registryText, modelKey, assemblyReceiptChecksum ); registryText = updateRegistryModulePlanChecksum( registryText, modelKey, modulePlanChecksum ); return { manifestText, adapterFamilyText, assemblyReceiptText, modulePlanText, registryText }; } // Reuses one coherent drift bundle across all paused fetches in the smoke run. function driftFor(requestUrl) { if (!driftPromise) { driftPromise = buildDrift(requestUrl); } return driftPromise; } client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; (async () => { if (requestUrlPathEquals(requestUrl, "/models/selector.registry")) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).registryText); return; } if (requestUrlPathEquals(requestUrl, modulePlanRoute)) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).modulePlanText); return; } if (requestUrlPathEquals(requestUrl, assemblyReceiptRoute)) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).assemblyReceiptText); return; } if (requestUrlPathEquals(requestUrl, adapterFamilyRoute)) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).adapterFamilyText); return; } if (requestUrlPathEquals(requestUrl, adapterManifestRoute)) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).manifestText); return; } await continuePausedRequest(client, params.requestId); })().catch((error) => { console.error(error); continuePausedRequest(client, params.requestId).catch((continueError) => { console.error(continueError); }); }); }); } function installAdapterArtifactDriftInterceptor(client, modelKey) { installAdapterStackArtifactDriftInterceptor(client, modelKey, 0); } function installAdapterStackPrefetchDriftInterceptor(client, modelKey) { installAdapterStackArtifactDriftInterceptor(client, modelKey, 1); } function installAdapterStackRustValidateDriftInterceptor(client, modelKey) { const adapterIndex = 1; const stackIndex = 0; const moduleIndex = 4; const adapterStackRoutes = expectedAdapterStackRoutes[modelKey] || []; const adapterManifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; const adapterStackRoute = adapterStackRoutes[stackIndex]; const adapterManifestRoute = adapterManifestRoutes[adapterIndex]; const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; const assemblyReceiptRoute = expectedAssemblyReceiptRoutes[modelKey]; const modulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!adapterStackRoute || !adapterManifestRoute || !adapterFamilyRoute || !assemblyReceiptRoute || !modulePlanRoute) { throw new Error(`generated semantic adapter drift routes were incomplete for ${modelKey}`); } let driftPromise = null; async function buildDrift(requestUrl) { const artifactBytes = adapterIdentityDriftBytes( await getBuffer(new URL(adapterStackRoute, requestUrl).toString()) ); const artifactChecksum = adapterArtifactChecksumHex(artifactBytes); const manifestText = updateAdapterManifestArtifactChecksum( await getText(new URL(adapterManifestRoute, requestUrl).toString()), artifactChecksum ); const manifestChecksum = textChecksumHex(manifestText); const adapterFamilyText = updateAdapterFamilyMemberChecksums( await getText(new URL(adapterFamilyRoute, requestUrl).toString()), adapterIndex, artifactChecksum, manifestChecksum ); const adapterFamilyChecksum = textChecksumHex(adapterFamilyText); const assemblyReceiptText = updateAssemblyAdapterFamilyReceiptChecksum( await getText(new URL(assemblyReceiptRoute, requestUrl).toString()), adapterFamilyChecksum ); const assemblyReceiptChecksum = textChecksumHex(assemblyReceiptText); let modulePlanText = await getText(new URL(modulePlanRoute, requestUrl).toString()); modulePlanText = updateModulePlanAssemblyReceiptChecksum(modulePlanText, assemblyReceiptChecksum); modulePlanText = updateModulePlanAdapterFamilyReceiptChecksum(modulePlanText, adapterFamilyChecksum); modulePlanText = updateModulePlanAdapterStackChecksums( modulePlanText, moduleIndex, artifactChecksum, manifestChecksum ); const modulePlanChecksum = textChecksumHex(modulePlanText); let registryText = await getText(new URL("/models/selector.registry", requestUrl).toString()); registryText = updateRegistryAdapterChecksums( registryText, modelKey, adapterIndex, artifactChecksum, manifestChecksum ); registryText = updateRegistryAdapterFamilyReceiptChecksum( registryText, modelKey, adapterFamilyChecksum ); registryText = updateRegistryAssemblyReceiptChecksum( registryText, modelKey, assemblyReceiptChecksum ); registryText = updateRegistryModulePlanChecksum( registryText, modelKey, modulePlanChecksum ); return { artifactBytes, manifestText, adapterFamilyText, assemblyReceiptText, modulePlanText, registryText }; } function driftFor(requestUrl) { if (!driftPromise) { driftPromise = buildDrift(requestUrl); } return driftPromise; } client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; (async () => { if (requestUrlPathEquals(requestUrl, "/models/selector.registry")) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).registryText); return; } if (requestUrlPathEquals(requestUrl, modulePlanRoute)) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).modulePlanText); return; } if (requestUrlPathEquals(requestUrl, assemblyReceiptRoute)) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).assemblyReceiptText); return; } if (requestUrlPathEquals(requestUrl, adapterFamilyRoute)) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).adapterFamilyText); return; } if (requestUrlPathEquals(requestUrl, adapterManifestRoute)) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).manifestText); return; } if (requestUrlPathEquals(requestUrl, adapterStackRoute)) { await fulfillBinaryRequest(client, params.requestId, (await driftFor(requestUrl)).artifactBytes); return; } await continuePausedRequest(client, params.requestId); })().catch((error) => { console.error(error); continuePausedRequest(client, params.requestId).catch((continueError) => { console.error(continueError); }); }); }); } function installModulePlanPayloadChecksumDriftInterceptor(client, modelKey) { const adapterIndex = 1; const stackIndex = 0; const moduleIndex = 4; const adapterStackRoutes = expectedAdapterStackRoutes[modelKey] || []; const adapterManifestRoutes = expectedAdapterManifestRoutes[modelKey] || []; const adapterStackRoute = adapterStackRoutes[stackIndex]; const adapterManifestRoute = adapterManifestRoutes[adapterIndex]; const adapterFamilyRoute = expectedAdapterFamilyReceiptRoutes[modelKey]; const assemblyReceiptRoute = expectedAssemblyReceiptRoutes[modelKey]; const modulePlanRoute = expectedModulePlanRoutes[modelKey]; if (!adapterStackRoute || !adapterManifestRoute || !adapterFamilyRoute || !assemblyReceiptRoute || !modulePlanRoute) { throw new Error(`generated payload checksum drift routes were incomplete for ${modelKey}`); } let driftPromise = null; // Builds a coherent payload drift while leaving module.N.checksum as the stale plan value. async function buildDrift(requestUrl) { const artifactBytes = Buffer.from(await getBuffer(new URL(adapterStackRoute, requestUrl).toString())); artifactBytes[artifactBytes.length - 1] ^= 0xff; const artifactChecksum = adapterArtifactChecksumHex(artifactBytes); const manifestText = updateAdapterManifestArtifactChecksum( await getText(new URL(adapterManifestRoute, requestUrl).toString()), artifactChecksum ); const manifestChecksum = textChecksumHex(manifestText); const adapterFamilyText = updateAdapterFamilyMemberChecksums( await getText(new URL(adapterFamilyRoute, requestUrl).toString()), adapterIndex, artifactChecksum, manifestChecksum ); const adapterFamilyChecksum = textChecksumHex(adapterFamilyText); const assemblyReceiptText = updateAssemblyAdapterFamilyReceiptChecksum( await getText(new URL(assemblyReceiptRoute, requestUrl).toString()), adapterFamilyChecksum ); const assemblyReceiptChecksum = textChecksumHex(assemblyReceiptText); let modulePlanText = await getText(new URL(modulePlanRoute, requestUrl).toString()); modulePlanText = updateModulePlanAssemblyReceiptChecksum(modulePlanText, assemblyReceiptChecksum); modulePlanText = updateModulePlanAdapterFamilyReceiptChecksum(modulePlanText, adapterFamilyChecksum); modulePlanText = updateModulePlanAdapterManifestChecksum(modulePlanText, moduleIndex, manifestChecksum); const modulePlanChecksum = textChecksumHex(modulePlanText); let registryText = await getText(new URL("/models/selector.registry", requestUrl).toString()); registryText = updateRegistryAdapterChecksums( registryText, modelKey, adapterIndex, artifactChecksum, manifestChecksum ); registryText = updateRegistryAdapterFamilyReceiptChecksum( registryText, modelKey, adapterFamilyChecksum ); registryText = updateRegistryAssemblyReceiptChecksum( registryText, modelKey, assemblyReceiptChecksum ); registryText = updateRegistryModulePlanChecksum( registryText, modelKey, modulePlanChecksum ); return { artifactBytes, manifestText, adapterFamilyText, assemblyReceiptText, modulePlanText, registryText }; } function driftFor(requestUrl) { if (!driftPromise) { driftPromise = buildDrift(requestUrl); } return driftPromise; } client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; (async () => { if (requestUrlPathEquals(requestUrl, "/models/selector.registry")) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).registryText); return; } if (requestUrlPathEquals(requestUrl, modulePlanRoute)) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).modulePlanText); return; } if (requestUrlPathEquals(requestUrl, assemblyReceiptRoute)) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).assemblyReceiptText); return; } if (requestUrlPathEquals(requestUrl, adapterFamilyRoute)) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).adapterFamilyText); return; } if (requestUrlPathEquals(requestUrl, adapterManifestRoute)) { await fulfillTextRequest(client, params.requestId, (await driftFor(requestUrl)).manifestText); return; } if (requestUrlPathEquals(requestUrl, adapterStackRoute)) { await fulfillBinaryRequest(client, params.requestId, (await driftFor(requestUrl)).artifactBytes); return; } await continuePausedRequest(client, params.requestId); })().catch((error) => { console.error(error); continuePausedRequest(client, params.requestId).catch((continueError) => { console.error(continueError); }); }); }); } function installAdapterStackArtifactDriftInterceptor(client, modelKey, stackIndex) { const adapterStackRoutes = expectedAdapterStackRoutes[modelKey] || []; const adapterStackRoute = adapterStackRoutes[stackIndex]; if (!adapterStackRoute) { throw new Error(`no generated adapter stack route is known for ${modelKey}`); } client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; (async () => { if (requestUrlPathEquals(requestUrl, adapterStackRoute)) { const body = Buffer.from(await getBuffer(requestUrl)); body[body.length - 1] ^= 0xff; await fulfillBinaryRequest(client, params.requestId, body); return; } await continuePausedRequest(client, params.requestId); })().catch((error) => { console.error(error); continuePausedRequest(client, params.requestId).catch((continueError) => { console.error(continueError); }); }); }); } function installQuantizedAdapterRegistryInterceptor(client) { client.on("Fetch.requestPaused", (params) => { const requestUrl = params.request && params.request.url ? params.request.url : ""; if (requestUrl.includes("/models/selector.registry")) { const body = Buffer.from([ "tinyrustlm_selector_registry_version=1", "selector_id=browser-local-selector", "registry_scope=browser-local-model-selector", "registry_status=admitted-records-only", "selector_model_byte_budget=33554432", "selector_registry_text_byte_budget=262144", "manifest_text_byte_budget=65536", "receipt_text_byte_budget=131072", "evidence_text_byte_budget=131072", "entry_count=1", "admission_set_checksum=0x0000000000000061", "entry.0.candidate_id=tinyq8", "entry.0.display_name=Tiny Fixture q8_0", "entry.0.model_path=../models/tiny-test-model-q8.slm", "entry.0.manifest_path=../models/tiny-test-model-q8.slm.manifest", "entry.0.artifact_path=tinyrustlm/models/tiny-test-model-q8.slm", "entry.0.max_tokens=8", "entry.0.model_bytes=8832", "entry.0.slm_checksum=0x6bde8aa244a5c10d", "entry.0.model_shape=vocab=260,hidden=16,layers=1,heads=2,kv_heads=2,head_dim=8,ffn=32,context=32", "entry.0.quantization=q8_0", "entry.0.output_contract=separate-output-weight", "entry.0.genome_id=0x00000000000000d1", "entry.0.genome_strategy=selector-admission-genome-v1", "entry.0.genome_lineage_status=admission-bound", "entry.0.genome_lineage_checksum=0x00000000000000d2", "entry.0.species_id=0x00000000000000d3", "entry.0.species_strategy=selector-speciation-fit-v1", "entry.0.species_fit_status=browser-fit-bound", "entry.0.species_fit_checksum=0x00000000000000d4", "entry.0.novelty_id=0x00000000000000d6", "entry.0.novelty_strategy=selector-novelty-sketch-v1", "entry.0.novelty_status=behavior-sketch-bound", "entry.0.novelty_checksum=0x00000000000000d7", "entry.0.population_id=0x00000000000000d8", "entry.0.population_strategy=selector-population-review-route-v1", "entry.0.population_status=population-review-bound", "entry.0.population_checksum=0x00000000000000d9", "entry.0.mate_selection_id=0x00000000000000da", "entry.0.mate_selection_strategy=selector-mate-selection-route-v1", "entry.0.mate_selection_status=admission-only", "entry.0.mate_selection_parent_count=1", "entry.0.mate_selection_checksum=0x00000000000000db", "entry.0.phenotype_evidence_id=0x00000000000000dc", "entry.0.phenotype_evidence_strategy=selector-phenotype-evidence-v1", "entry.0.phenotype_evidence_status=runtime-eval-bound", "entry.0.phenotype_evidence_checksum=0x00000000000000dd", "entry.0.heritable_artifact_id=0x00000000000000de", "entry.0.heritable_artifact_strategy=selector-heritable-artifact-v1", "entry.0.heritable_artifact_status=served-artifact-bound", "entry.0.heritable_artifact_checksum=0x00000000000000df", "entry.0.admission_checksum=0x0000000000000062", "entry.0.promotion_manifest_checksum=0x0000000000000063", "entry.0.provenance_manifest_checksum=0x0000000000000067", "entry.0.runtime_smoke_manifest_checksum=0x0000000000000064", "entry.0.eval_manifest_checksum=0x0000000000000065", "entry.0.eval_case_evidence_checksum=0x0000000000000066", "entry.0.quality_scope=tiny-fixture-runtime-eval-only", "entry.0.quality_boundary=fixture-runtime-and-eval-plumbing-not-product-assistant-quality", "entry.0.eval_dataset=tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", "entry.0.cases_passed=1", "entry.0.fitness_vector_status=eval-bound", "entry.0.fitness_vector_checksum=0x00000000000000d5", "entry.0.selector_status=admitted", "entry.0.public_claim_status=bound-to-eval-scope", "entry.0.adapter_path=../models/tiny-test-model-q8-self.adp1", "entry.0.adapter_manifest_path=../models/tiny-test-model-q8-self.adp1.manifest", "entry.0.adapter_label=Tiny Fixture q8_0 self ADP1", "entry.0.adapter_apply_status=runtime-q8-q4-compatible-or-fuse-to-slm", "entry.0.adapter_artifact_checksum=0x8194a8a671285019", "entry.0.adapter_manifest_checksum=0x536f9b488db9822b", "required_next_gate=browser-loads-selector-registry-entry-models", "" ].join("\n"), "utf8"); client.send("Fetch.fulfillRequest", { requestId: params.requestId, responseCode: 200, responseHeaders: [ { name: "content-type", value: "text/plain; charset=utf-8" }, { name: "content-length", value: String(body.length) } ], body: body.toString("base64") }).catch((error) => { console.error(error); }); return; } client.send("Fetch.continueRequest", { requestId: params.requestId }).catch((error) => { console.error(error); }); }); } async function main() { const browser = findBrowser(); const profile = path.join(os.tmpdir(), `tinyrustlm-browser-smoke-${process.pid}`); await removeProfile(profile); const browserProcess = childProcess.spawn(browser, [ "--headless=new", "--disable-gpu", "--disable-application-cache", "--disable-background-networking", "--disable-component-update", "--disable-extensions", "--disable-sync", "--disk-cache-size=1", "--media-cache-size=1", "--no-default-browser-check", "--no-first-run", `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, appUrl ], { stdio: "ignore", windowsHide: true }); try { const target = await waitForTarget(); const socket = await connectWebSocket(target.webSocketDebuggerUrl); const client = cdpClient(socket); const networkRequests = []; client.on("Network.requestWillBeSent", (params) => { if (params.request && params.request.url) { networkRequests.push(params.request.url); } }); await client.send("Page.enable", {}); await client.send("Runtime.enable", {}); await client.send("Network.enable", {}); if (smokeMode === "model-error" || smokeMode === "missing-model" || convertedTrainedRegistrySmokeMode || compactOperatorRegistrySmokeModes.has(smokeMode) || compactOperatorReceiptDriftSmokeModes.has(smokeMode) || smokeMode === "generated-selector-operator-receipt-drift" || smokeMode === "generated-selector-operator-kind-drift" || smokeMode === "selector-budget" || smokeMode === "sidecar-budget-contract" || smokeMode === "runtime-manifest-drift" || smokeMode === "module-plan-profile-drift" || smokeMode === "module-plan-execution-profile-drift" || smokeMode === "module-plan-fetch-policy-drift" || smokeMode === "module-plan-origin-policy-drift" || smokeMode === "module-plan-wasm-memory-drift" || smokeMode === "module-plan-wasm-export-set-drift" || smokeMode === "module-plan-wasm-heap-drift" || smokeMode === "module-plan-context-token-drift" || smokeMode === "module-plan-sampler-cap-drift" || smokeMode === "module-plan-tokenizer-drift" || smokeMode === "module-plan-resource-drift" || smokeMode === "module-plan-runtime-scratch-drift" || smokeMode === "module-plan-output-limit-drift" || smokeMode === "module-plan-prompt-limit-drift" || smokeMode === "module-plan-fetch-count-drift" || smokeMode === "module-plan-planned-fetch-count-drift" || smokeMode === "module-plan-route-set-algorithm-drift" || smokeMode === "module-plan-route-set-version-drift" || smokeMode === "module-plan-route-set-drift" || smokeMode === "module-plan-operator-receipt-drift" || smokeMode === "module-plan-kv-cache-drift" || smokeMode === "module-plan-adapter-stack-budget-drift" || smokeMode === "module-plan-total-budget-drift" || smokeMode === "module-plan-total-limit-drift" || smokeMode === "module-plan-count-drift" || smokeMode === "module-plan-graph-drift" || smokeMode === "module-plan-stack-drift" || smokeMode === "module-plan-role-drift" || smokeMode === "module-plan-slot-drift" || smokeMode === "module-plan-phase-drift" || smokeMode === "module-plan-byte-drift" || smokeMode === "module-plan-checksum-drift" || smokeMode === "module-plan-dependency-drift" || smokeMode === "assembly-eval-case-drift" || smokeMode === "assembly-evidence-file-drift" || smokeMode === "adapter-family-receipt-drift" || smokeMode === "adapter-manifest-drift" || smokeMode === "source-backed-alr1-manifest-drift" || smokeMode === "adapter-artifact-drift" || smokeMode === "module-plan-payload-checksum-drift" || smokeMode === "adapter-stack-prefetch-drift" || smokeMode === "adapter-stack-rust-validate-drift" || smokeMode === "adapter-sidecar-registry-q8" || smokeMode === "adapter-sidecar-checksum-mismatch" || smokeMode === "adapter-manifest-budget") { if (smokeMode === "model-error") { installMalformedModelInterceptor(client); } else if (smokeMode === "missing-model") { installMissingModelInterceptor(client); } else if (smokeMode === "runtime-manifest-drift") { installRuntimeManifestDriftInterceptor(client); } else if (smokeMode === "module-plan-profile-drift") { installModulePlanProfileDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-execution-profile-drift") { installModulePlanExecutionProfileDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-fetch-policy-drift") { installModulePlanFetchPolicyDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-origin-policy-drift") { installModulePlanOriginPolicyDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-wasm-memory-drift") { installModulePlanWasmMemoryDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-wasm-export-set-drift") { installModulePlanWasmExportSetDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-wasm-heap-drift") { installModulePlanWasmHeapDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-context-token-drift") { installModulePlanContextTokenDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-sampler-cap-drift") { installModulePlanSamplerCapDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-tokenizer-drift") { installModulePlanTokenizerDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-resource-drift") { installModulePlanResourceDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-runtime-scratch-drift") { installModulePlanRuntimeScratchDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-output-limit-drift") { installModulePlanOutputLimitDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-prompt-limit-drift") { installModulePlanPromptLimitDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-fetch-count-drift") { installModulePlanFetchCountDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-planned-fetch-count-drift") { installModulePlanPlannedFetchCountDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-route-set-algorithm-drift") { installModulePlanRouteSetAlgorithmDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-route-set-version-drift") { installModulePlanRouteSetVersionDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-route-set-drift") { installModulePlanRouteSetDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-operator-receipt-drift") { installModulePlanOperatorReceiptDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-kv-cache-drift") { installModulePlanKvCacheDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-adapter-stack-budget-drift") { installModulePlanAdapterStackBudgetDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-total-budget-drift") { installModulePlanTotalBudgetDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-total-limit-drift") { installModulePlanTotalLimitDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-count-drift") { installModulePlanCountDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-graph-drift") { installModulePlanGraphDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-stack-drift") { installModulePlanStackDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-role-drift") { installModulePlanRoleDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-slot-drift") { installModulePlanSlotDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-phase-drift") { installModulePlanPhaseDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-byte-drift") { installModulePlanByteDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-checksum-drift") { installModulePlanChecksumDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-dependency-drift") { installModulePlanDependencyDriftInterceptor(client, expectedModel); } else if (smokeMode === "assembly-eval-case-drift") { installAssemblyEvalCaseDriftInterceptor(client, expectedModel); } else if (smokeMode === "assembly-evidence-file-drift") { installAssemblyEvidenceFileDriftInterceptor(client, expectedModel); } else if (smokeMode === "adapter-family-receipt-drift") { installAdapterFamilyReceiptDriftInterceptor(client, expectedModel); } else if (smokeMode === "adapter-manifest-drift") { installAdapterManifestDriftInterceptor(client, expectedModel); } else if (smokeMode === "source-backed-alr1-manifest-drift") { installSourceBackedAlr1ManifestDriftInterceptor(client, expectedModel); } else if (smokeMode === "adapter-artifact-drift") { installAdapterArtifactDriftInterceptor(client, expectedModel); } else if (smokeMode === "module-plan-payload-checksum-drift") { installModulePlanPayloadChecksumDriftInterceptor(client, expectedModel); } else if (smokeMode === "adapter-stack-prefetch-drift") { installAdapterStackPrefetchDriftInterceptor(client, expectedModel); } else if (smokeMode === "adapter-stack-rust-validate-drift") { installAdapterStackRustValidateDriftInterceptor(client, expectedModel); } else if (smokeMode === "adapter-sidecar-checksum-mismatch") { installCorruptAdapterInterceptor(client); } else if (smokeMode === "adapter-manifest-budget") { installAdapterManifestBudgetInterceptor(client); } else if (smokeMode === "adapter-sidecar-registry-q8") { installQuantizedAdapterRegistryInterceptor(client); } else if (convertedTrainedRegistrySmokeMode) { installConvertedTrainedRegistryInterceptor(client); } else if (smokeMode === "selector-budget") { installSelectorBudgetRegistryInterceptor(client); } else if (smokeMode === "sidecar-budget-contract") { installSidecarBudgetContractRegistryInterceptor(client); } else if (compactOperatorReceiptDriftSmokeModes.has(smokeMode)) { installSelectorOperatorReceiptDriftInterceptor(client); } else if (smokeMode === "generated-selector-operator-receipt-drift") { installGeneratedSelectorOperatorReceiptDriftInterceptor(client); } else if (smokeMode === "generated-selector-operator-kind-drift") { installGeneratedSelectorOperatorReceiptDriftInterceptor( client, driftGeneratedSelectorOperatorReceiptKind ); } else { installMultiParentRegistryInterceptor(client); } await client.send("Fetch.enable", { patterns: [ { urlPattern: "*", requestStage: "Request" } ] }); } if (smokeMode === "module-plan-wasm-transfer-drift") { installModulePlanWasmTransferDriftInterceptor(client, expectedModel); await client.send("Fetch.enable", { patterns: [ { urlPattern: "*", requestStage: "Request" } ] }); } if (smokeMode === "module-plan-model-release-drift") { installModulePlanModelReleaseDriftInterceptor(client, expectedModel); await client.send("Fetch.enable", { patterns: [ { urlPattern: "*", requestStage: "Request" } ] }); } if (smokeMode === "module-plan-runtime-reset-drift") { installModulePlanRuntimeResetDriftInterceptor(client, expectedModel); await client.send("Fetch.enable", { patterns: [ { urlPattern: "*", requestStage: "Request" } ] }); } if (smokeMode === "module-plan-adapter-validation-drift") { installModulePlanAdapterValidationDriftInterceptor(client, expectedModel); await client.send("Fetch.enable", { patterns: [ { urlPattern: "*", requestStage: "Request" } ] }); } if (smokeMode === "module-plan-adapter-validation-count-drift") { installModulePlanAdapterValidationCountDriftInterceptor(client, expectedModel); await client.send("Fetch.enable", { patterns: [ { urlPattern: "*", requestStage: "Request" } ] }); } if (smokeMode === "module-plan-adapter-apply-count-drift") { installModulePlanAdapterApplyCountDriftInterceptor(client, expectedModel); await client.send("Fetch.enable", { patterns: [ { urlPattern: "*", requestStage: "Request" } ] }); } let result = null; if (smokeMode === "loop") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageLoopSmoke(client); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertLoopSmoke(result, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "endurance") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageEnduranceSmoke(client, enduranceCycles); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertEnduranceSmoke(result, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "performance") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPagePerformanceSmoke(client, performanceTokens); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertPerformanceSmoke(result, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "performance-soak") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPagePerformanceSoak(client, performanceSoakCycles, performanceSoakTokens); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertPerformanceSoak(result, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "ui-audit") { await client.send("Emulation.setDeviceMetricsOverride", { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false }); await client.send("Page.navigate", { url: appUrl }); let desktop = null; for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(1000); desktop = await runPageUiAudit(client); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } await client.send("Emulation.setDeviceMetricsOverride", { width: 390, height: 844, deviceScaleFactor: 1, mobile: true }); await client.send("Page.navigate", { url: appUrl }); let mobile = null; for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(1000); mobile = await runPageUiAudit(client); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } result = { desktop, mobile, networkRequests }; assertUiAudit(result, networkRequests); } else if (smokeMode === "step-token") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageStepTokenSmoke(client, expectedModel); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertStepTokenSmoke(result, expectedModel, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "combined-selector-assembly" || smokeMode === "combined-selector-operator-family") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageCombinedSelectorAssemblySmoke(client); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } if (smokeMode === "combined-selector-operator-family") { assertCombinedSelectorOperatorFamilySmoke(result, networkRequests); } else { assertCombinedSelectorAssemblySmoke(result, networkRequests); } result.networkRequests = networkRequests; } else if (smokeMode === "combined-selector-cycle" || smokeMode === "combined-selector-operator-family-cycle" || combinedSelectorRouteSoakMode) { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageCombinedSelectorAssemblySmoke(client, combinedSelectorCycles); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } if (combinedSelectorRouteSoakMode) { assertCombinedSelectorRouteSoakSmoke(result, networkRequests, combinedSelectorCycles); } else if (smokeMode === "combined-selector-operator-family-cycle") { assertCombinedSelectorOperatorFamilyCycleSmoke(result, networkRequests, combinedSelectorCycles); } else { assertCombinedSelectorCycleSmoke(result, networkRequests, combinedSelectorCycles); } result.networkRequests = networkRequests; } else if (smokeMode === "combined-selector-reload-soak" || combinedSelectorOperatorFamilyReloadSoakMode) { result = await runCombinedSelectorReloadSoak(client, combinedSelectorReloads); if (combinedSelectorOperatorFamilyReloadSoakMode) { assertCombinedSelectorOperatorFamilyReloadSoakSmoke(result, networkRequests, combinedSelectorReloads); } else { assertCombinedSelectorReloadSoakSmoke(result, networkRequests, combinedSelectorReloads); } result.networkRequests = networkRequests; } else if (smokeMode === "adapter-sidecar" || smokeMode === "adapter-sidecar-registry-file" || smokeMode === "adapter-sidecar-registry-q8" || smokeMode === "adapter-sidecar-checksum-mismatch") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageAdapterSidecarSmoke( client, expectedModel, smokeMode === "adapter-sidecar-registry-file" ); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } if (smokeMode === "adapter-sidecar-checksum-mismatch") { assertAdapterChecksumMismatchSmoke(result, expectedModel, networkRequests); } else { assertAdapterSidecarSmoke( result, expectedModel, networkRequests, smokeMode === "adapter-sidecar-registry-file" ); } result.networkRequests = networkRequests; } else if (smokeMode === "adapter-manifest-budget") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageAdapterLoadStateSmoke(client, expectedModel); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertAdapterManifestBudgetSmoke(result, expectedModel, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "adapter-family-receipt-drift" || smokeMode === "adapter-manifest-drift" || smokeMode === "source-backed-alr1-manifest-drift" || smokeMode === "adapter-artifact-drift" || smokeMode === "module-plan-payload-checksum-drift" || smokeMode === "adapter-stack-prefetch-drift" || smokeMode === "adapter-stack-rust-validate-drift") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageAdapterLoadStateSmoke(client, expectedModel); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } if (smokeMode === "adapter-family-receipt-drift") { assertAdapterFamilyReceiptDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "adapter-manifest-drift") { assertAdapterManifestDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "source-backed-alr1-manifest-drift") { assertSourceBackedAlr1ManifestDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "adapter-stack-prefetch-drift") { assertAdapterStackPrefetchDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "adapter-stack-rust-validate-drift") { assertAdapterStackRustValidateDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-payload-checksum-drift") { assertModulePlanPayloadChecksumDriftSmoke(result, expectedModel, networkRequests); } else { assertAdapterArtifactDriftSmoke(result, expectedModel, networkRequests); } result.networkRequests = networkRequests; } else if (smokeMode === "selector-budget" || smokeMode === "sidecar-budget-contract" || compactOperatorReceiptDriftSmokeModes.has(smokeMode) || smokeMode === "generated-selector-operator-receipt-drift" || smokeMode === "generated-selector-operator-kind-drift") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageSmoke( client, smokeMode === "generated-selector-operator-receipt-drift" || smokeMode === "generated-selector-operator-kind-drift" ? "tinylm16q8" : expectedModel ); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } if (smokeMode === "selector-budget") { assertSelectorBudgetSmoke(result, networkRequests); } else if (smokeMode === "sidecar-budget-contract") { assertSidecarBudgetContractSmoke(result, networkRequests); } else if (smokeMode === "generated-selector-operator-receipt-drift" || smokeMode === "generated-selector-operator-kind-drift") { assertGeneratedSelectorOperatorReceiptDriftSmoke(result, expectedModel, networkRequests); } else { assertSelectorOperatorReceiptDriftSmoke( result, networkRequests, registryOperatorFixtureForMode(smokeMode).candidateId ); } result.networkRequests = networkRequests; } else if (convertedTrainedRegistryAnySmokeMode || compactOperatorRegistrySmokeModes.has(smokeMode) || smokeMode === "multi-parent-registry-file") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageSmoke(client, expectedModel); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } if (convertedTrainedRegistryAnySmokeMode) { assertConvertedTrainedRegistrySmoke(result, expectedModel, networkRequests); } else { assertMultiParentRegistrySmoke(result, expectedModel, networkRequests); } result.networkRequests = networkRequests; } else if (smokeMode === "runtime-manifest-drift") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageModelErrorSmoke(client, expectedModel); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertRuntimeManifestDriftSmoke(result, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "assembly-eval-case-drift") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageAssemblyEvalCaseDriftSmoke(client); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertAssemblyEvalCaseDriftSmoke(result, expectedModel, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "assembly-evidence-file-drift") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageAssemblyEvalCaseDriftSmoke(client); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertAssemblyEvidenceFileDriftSmoke(result, expectedModel, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "module-plan-wasm-transfer-drift") { networkRequests.length = 0; await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageModelErrorSmoke(client, expectedModel); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertModulePlanWasmTransferDriftSmoke(result, expectedModel, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "module-plan-model-release-drift") { networkRequests.length = 0; await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageModelErrorSmoke(client, expectedModel); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertModulePlanModelReleaseDriftSmoke(result, expectedModel, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "module-plan-runtime-reset-drift") { networkRequests.length = 0; await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageModelErrorSmoke(client, expectedModel); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertModulePlanRuntimeResetDriftSmoke(result, expectedModel, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "module-plan-adapter-validation-drift") { networkRequests.length = 0; await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageModelErrorSmoke(client, expectedModel); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertModulePlanAdapterValidationDriftSmoke(result, expectedModel, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "module-plan-adapter-validation-count-drift") { networkRequests.length = 0; await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageModelErrorSmoke(client, expectedModel); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertModulePlanAdapterValidationCountDriftSmoke(result, expectedModel, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "module-plan-adapter-apply-count-drift") { networkRequests.length = 0; await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageModelErrorSmoke(client, expectedModel); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertModulePlanAdapterApplyCountDriftSmoke(result, expectedModel, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "module-plan-profile-drift" || smokeMode === "module-plan-execution-profile-drift" || smokeMode === "module-plan-fetch-policy-drift" || smokeMode === "module-plan-origin-policy-drift" || smokeMode === "module-plan-wasm-memory-drift" || smokeMode === "module-plan-wasm-export-set-drift" || smokeMode === "module-plan-wasm-heap-drift" || smokeMode === "module-plan-context-token-drift" || smokeMode === "module-plan-sampler-cap-drift" || smokeMode === "module-plan-tokenizer-drift" || smokeMode === "module-plan-resource-drift" || smokeMode === "module-plan-runtime-scratch-drift" || smokeMode === "module-plan-output-limit-drift" || smokeMode === "module-plan-prompt-limit-drift" || smokeMode === "module-plan-fetch-count-drift" || smokeMode === "module-plan-planned-fetch-count-drift" || smokeMode === "module-plan-route-set-algorithm-drift" || smokeMode === "module-plan-route-set-version-drift" || smokeMode === "module-plan-route-set-drift" || smokeMode === "module-plan-operator-receipt-drift" || smokeMode === "module-plan-kv-cache-drift" || smokeMode === "module-plan-adapter-stack-budget-drift" || smokeMode === "module-plan-total-budget-drift" || smokeMode === "module-plan-total-limit-drift" || smokeMode === "module-plan-count-drift" || smokeMode === "module-plan-graph-drift" || smokeMode === "module-plan-stack-drift" || smokeMode === "module-plan-role-drift" || smokeMode === "module-plan-slot-drift" || smokeMode === "module-plan-phase-drift" || smokeMode === "module-plan-byte-drift" || smokeMode === "module-plan-checksum-drift" || smokeMode === "module-plan-dependency-drift") { networkRequests.length = 0; await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageModelErrorSmoke(client, expectedModel); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } if (smokeMode === "module-plan-profile-drift") { assertModulePlanProfileDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-execution-profile-drift") { assertModulePlanExecutionProfileDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-fetch-policy-drift") { assertModulePlanFetchPolicyDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-origin-policy-drift") { assertModulePlanOriginPolicyDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-wasm-memory-drift") { assertModulePlanWasmMemoryDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-wasm-export-set-drift") { assertModulePlanWasmExportSetDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-wasm-heap-drift") { assertModulePlanWasmHeapDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-context-token-drift") { assertModulePlanContextTokenDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-sampler-cap-drift") { assertModulePlanSamplerCapDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-tokenizer-drift") { assertModulePlanTokenizerDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-resource-drift") { assertModulePlanResourceDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-runtime-scratch-drift") { assertModulePlanRuntimeScratchDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-output-limit-drift") { assertModulePlanOutputLimitDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-prompt-limit-drift") { assertModulePlanPromptLimitDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-fetch-count-drift") { assertModulePlanFetchCountDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-planned-fetch-count-drift") { assertModulePlanPlannedFetchCountDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-route-set-algorithm-drift") { assertModulePlanRouteSetAlgorithmDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-route-set-version-drift") { assertModulePlanRouteSetVersionDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-route-set-drift") { assertModulePlanRouteSetDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-operator-receipt-drift") { assertModulePlanOperatorReceiptDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-kv-cache-drift") { assertModulePlanKvCacheDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-adapter-stack-budget-drift") { assertModulePlanAdapterStackBudgetDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-total-budget-drift") { assertModulePlanTotalBudgetDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-total-limit-drift") { assertModulePlanTotalLimitDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-count-drift") { assertModulePlanCountDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-graph-drift") { assertModulePlanGraphDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-stack-drift") { assertModulePlanStackDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-role-drift") { assertModulePlanRoleDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-slot-drift") { assertModulePlanSlotDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-phase-drift") { assertModulePlanPhaseDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-byte-drift") { assertModulePlanByteDriftSmoke(result, expectedModel, networkRequests); } else if (smokeMode === "module-plan-checksum-drift") { assertModulePlanChecksumDriftSmoke(result, expectedModel, networkRequests); } else { assertModulePlanDependencyDriftSmoke(result, expectedModel, networkRequests); } result.networkRequests = networkRequests; } else if (smokeMode === "model-error") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageModelErrorSmoke(client); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertModelErrorSmoke(result, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "missing-model") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageMissingModelSmoke(client); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertMissingModelSmoke(result, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "context-error") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageContextErrorSmoke(client); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertContextErrorSmoke(result, networkRequests); result.networkRequests = networkRequests; } else if (smokeMode === "prompt-limit") { await client.send("Page.reload", { ignoreCache: true }); for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPagePromptLimitSmoke(client); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertPromptLimitSmoke(result, networkRequests); result.networkRequests = networkRequests; } else { for (let attempt = 0; attempt < 3; attempt += 1) { try { await sleep(500); result = await runPageSmoke(client, expectedModel); break; } catch (error) { if (!error.message.includes("Execution context was destroyed") || attempt === 2) { throw error; } } } assertSmoke(result, expectedModel, networkRequests); result.networkRequests = networkRequests; } console.log(JSON.stringify(result, null, 2)); socket.close(); } finally { killProcessTree(browserProcess); killProfileProcesses(profile); await waitForExit(browserProcess); try { await removeProfile(profile); } catch (error) { console.error(`notice: unable to remove temporary browser profile ${profile}: ${error.message}`); } } } main().catch((error) => { console.error(error); process.exit(1); }); ================================================================================ END FILE: tinyrustlm/tools/browser-smoke.js ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/local_server/Cargo.toml BYTES: 213 SHA256: E4B7809225A0468192D7790341A8B68538300A9789B5E2A08C20F92A8EADB010 ================================================================================ [package] name = "tinyrustlm-local-server" version.workspace = true edition.workspace = true license.workspace = true authors.workspace = true repository.workspace = true [dependencies] [lints] workspace = true ================================================================================ END FILE: tinyrustlm/tools/local_server/Cargo.toml ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/local_server/src/main.rs BYTES: 12090 SHA256: 8CA1CC5026792D2F1CB45883A82DB089E2561CA00BA43B3245B7CA246A996102 ================================================================================ #![forbid(unsafe_code)] #![doc = "No-crate local static server for TinyRustLM browser development."] use std::env; use std::fs::File; use std::io::{self, Read, Write}; use std::net::{TcpListener, TcpStream}; use std::path::{Component, Path, PathBuf}; use std::process::ExitCode; use std::time::Duration; const DEFAULT_ROOT: &str = "tinyrustlm"; const DEFAULT_PORT: u16 = 8080; const READ_LIMIT: usize = 8192; fn main() -> ExitCode { match run() { Ok(()) => ExitCode::SUCCESS, Err(ServerError::PortInUse(port)) => { eprintln!("Port {port} is already in use on 127.0.0.1."); ExitCode::from(2) } Err(error) => { eprintln!("TinyRustLM Rust static server failed: {error}"); ExitCode::from(1) } } } fn run() -> Result<(), ServerError> { let config = Config::from_env(env::args().skip(1))?; let root = config.root.canonicalize().map_err(|source| { ServerError::InvalidRoot(format!("{} ({source})", config.root.display())) })?; let listener = TcpListener::bind(("127.0.0.1", config.port)).map_err(|source| { if source.kind() == io::ErrorKind::AddrInUse { ServerError::PortInUse(config.port) } else { ServerError::Io(source) } })?; println!( "TinyRustLM Rust static server listening at http://127.0.0.1:{}/app/", config.port ); for stream in listener.incoming() { match stream { Ok(mut stream) => { if let Err(error) = handle_stream(&root, &mut stream) { let _ = write_response( &mut stream, 500, "internal server error", "text/plain; charset=utf-8", false, ); eprintln!("TinyRustLM request failed: {error}"); } } Err(error) => eprintln!("TinyRustLM connection failed: {error}"), } } Ok(()) } #[derive(Debug)] struct Config { root: PathBuf, port: u16, } impl Config { fn from_env(mut args: I) -> Result where I: Iterator, { let root = args .next() .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from(DEFAULT_ROOT)); let port = match args.next() { Some(value) => value .parse::() .map_err(|_| ServerError::InvalidPort(value))?, None => DEFAULT_PORT, }; if let Some(extra) = args.next() { return Err(ServerError::UnexpectedArgument(extra)); } Ok(Self { root, port }) } } #[derive(Debug)] enum ServerError { BadRequest(String), Forbidden, InvalidPort(String), InvalidRoot(String), Io(io::Error), PortInUse(u16), UnexpectedArgument(String), } impl std::fmt::Display for ServerError { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ServerError::BadRequest(message) => write!(formatter, "bad request: {message}"), ServerError::Forbidden => write!(formatter, "forbidden path"), ServerError::InvalidPort(port) => write!(formatter, "invalid port '{port}'"), ServerError::InvalidRoot(root) => write!(formatter, "invalid root '{root}'"), ServerError::Io(source) => write!(formatter, "{source}"), ServerError::PortInUse(port) => write!(formatter, "port {port} is in use"), ServerError::UnexpectedArgument(value) => { write!(formatter, "unexpected extra argument '{value}'") } } } } impl From for ServerError { fn from(source: io::Error) -> Self { ServerError::Io(source) } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum Method { Get, Head, } fn handle_stream(root: &Path, stream: &mut TcpStream) -> Result<(), ServerError> { stream.set_read_timeout(Some(Duration::from_secs(5)))?; stream.set_write_timeout(Some(Duration::from_secs(5)))?; let request = read_request(stream)?; let Some(line) = request.lines().next() else { write_response( stream, 400, "bad request", "text/plain; charset=utf-8", false, )?; return Ok(()); }; let parsed = match parse_request_line(line) { Ok(parsed) => parsed, Err(_) => { write_response( stream, 400, "bad request", "text/plain; charset=utf-8", false, )?; return Ok(()); } }; let method = match parsed.method { "GET" => Method::Get, "HEAD" => Method::Head, _ => { write_response( stream, 405, "method not allowed", "text/plain; charset=utf-8", false, )?; return Ok(()); } }; match resolve_path(root, parsed.target) { Ok(path) => serve_file(stream, method, &path), Err(ServerError::Forbidden) => { write_response(stream, 403, "forbidden", "text/plain; charset=utf-8", false) } Err(ServerError::BadRequest(_)) => write_response( stream, 400, "bad request", "text/plain; charset=utf-8", false, ), Err(error) => Err(error), } } fn read_request(stream: &mut TcpStream) -> Result { let mut buffer = [0u8; READ_LIMIT]; let len = stream.read(&mut buffer)?; if len == 0 { return Err(ServerError::BadRequest("empty request".to_string())); } String::from_utf8(buffer[..len].to_vec()) .map_err(|_| ServerError::BadRequest("request is not utf-8".to_string())) } #[derive(Debug, Eq, PartialEq)] struct RequestLine<'a> { method: &'a str, target: &'a str, } fn parse_request_line(line: &str) -> Result, ServerError> { let mut parts = line.split_whitespace(); let method = parts .next() .ok_or_else(|| ServerError::BadRequest("missing method".to_string()))?; let target = parts .next() .ok_or_else(|| ServerError::BadRequest("missing target".to_string()))?; let version = parts .next() .ok_or_else(|| ServerError::BadRequest("missing version".to_string()))?; if parts.next().is_some() || !version.starts_with("HTTP/") { return Err(ServerError::BadRequest("invalid request line".to_string())); } Ok(RequestLine { method, target }) } fn resolve_path(root: &Path, target: &str) -> Result { let path_part = target.split('?').next().unwrap_or(target); let decoded = percent_decode(path_part)?; let mut relative = decoded.trim_start_matches('/').to_string(); if relative.is_empty() || relative.ends_with('/') { relative.push_str("index.html"); } if relative.contains('\\') || relative.contains(':') { return Err(ServerError::Forbidden); } let relative_path = Path::new(&relative); if relative_path.is_absolute() { return Err(ServerError::Forbidden); } for component in relative_path.components() { match component { Component::Normal(_) => {} _ => return Err(ServerError::Forbidden), } } Ok(root.join(relative_path)) } fn percent_decode(input: &str) -> Result { let bytes = input.as_bytes(); let mut out = Vec::with_capacity(bytes.len()); let mut index = 0; while index < bytes.len() { match bytes[index] { b'%' => { if index + 2 >= bytes.len() { return Err(ServerError::BadRequest( "incomplete percent escape".to_string(), )); } let high = hex_value(bytes[index + 1]) .ok_or_else(|| ServerError::BadRequest("bad percent escape".to_string()))?; let low = hex_value(bytes[index + 2]) .ok_or_else(|| ServerError::BadRequest("bad percent escape".to_string()))?; out.push((high << 4) | low); index += 3; } value => { out.push(value); index += 1; } } } String::from_utf8(out) .map_err(|_| ServerError::BadRequest("decoded path is not utf-8".to_string())) } fn hex_value(value: u8) -> Option { match value { b'0'..=b'9' => Some(value - b'0'), b'a'..=b'f' => Some(value - b'a' + 10), b'A'..=b'F' => Some(value - b'A' + 10), _ => None, } } fn serve_file(stream: &mut TcpStream, method: Method, path: &Path) -> Result<(), ServerError> { let metadata = match path.metadata() { Ok(metadata) if metadata.is_file() => metadata, _ => { write_response(stream, 404, "not found", "text/plain; charset=utf-8", false)?; return Ok(()); } }; let mime = content_type(path); write!( stream, "HTTP/1.1 200 OK\r\ncontent-type: {mime}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", metadata.len() )?; if method == Method::Head { stream.flush()?; return Ok(()); } let mut file = File::open(path)?; let mut buffer = [0u8; 64 * 1024]; loop { let len = file.read(&mut buffer)?; if len == 0 { break; } stream.write_all(&buffer[..len])?; } stream.flush()?; Ok(()) } fn write_response( stream: &mut TcpStream, code: u16, body: &str, content_type: &str, head_only: bool, ) -> Result<(), ServerError> { let reason = match code { 400 => "Bad Request", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 500 => "Internal Server Error", _ => "OK", }; write!( stream, "HTTP/1.1 {code} {reason}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", body.len() )?; if !head_only { stream.write_all(body.as_bytes())?; } stream.flush()?; Ok(()) } fn content_type(path: &Path) -> &'static str { match path.extension().and_then(|ext| ext.to_str()).unwrap_or("") { "css" => "text/css; charset=utf-8", "html" => "text/html; charset=utf-8", "js" => "text/javascript; charset=utf-8", "json" => "application/json; charset=utf-8", "manifest" => "text/plain; charset=utf-8", "md" => "text/plain; charset=utf-8", "slm" => "application/octet-stream", "txt" => "text/plain; charset=utf-8", "wasm" => "application/wasm", _ => "application/octet-stream", } } #[cfg(test)] mod tests { use super::*; #[test] fn parses_get_request_line() { let line = parse_request_line("GET /app/ HTTP/1.1").expect("request line"); assert_eq!(line.method, "GET"); assert_eq!(line.target, "/app/"); } #[test] fn resolves_directory_to_index() { let root = Path::new("tinyrustlm"); let path = resolve_path(root, "/app/").expect("path"); assert!(path.ends_with(Path::new("app").join("index.html"))); } #[test] fn rejects_traversal() { let root = Path::new("tinyrustlm"); assert!(matches!( resolve_path(root, "/../Cargo.toml"), Err(ServerError::Forbidden) )); } #[test] fn decodes_percent_paths() { assert_eq!(percent_decode("/app/app%2Ejs").unwrap(), "/app/app.js"); } #[test] fn reports_wasm_content_type() { assert_eq!( content_type(Path::new("runtime/tinyrustlm.wasm")), "application/wasm" ); } } ================================================================================ END FILE: tinyrustlm/tools/local_server/src/main.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/Cargo.toml BYTES: 209 SHA256: 77FC3EF97599491B8E67404EDF8CC0645A0032AF84D157B8E153AE84E6DC8AF8 ================================================================================ [package] name = "tinyrustlm-slm-pack" version.workspace = true edition.workspace = true license.workspace = true authors.workspace = true repository.workspace = true [dependencies] [lints] workspace = true ================================================================================ END FILE: tinyrustlm/tools/slm_pack/Cargo.toml ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/adapter.rs BYTES: 113011 SHA256: 8F76A24981BF676CCEB162CF9718BFB1EE1B2FBB85418E6DBC671E8343D89C52 ================================================================================ //! Offline adapter/delta artifacts for modular model-breeding candidates. use std::cmp::Ordering; use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::blend::{ hex64, invalid, output_specs, parse_manifest, parse_model_values, parse_passing_compatibility, push_line, push_parent_lines, require_equal, require_key, require_parent_report, require_report_equal, require_same_tensor_spec, same_shape, ParsedModel, }; use crate::build_model_file_from_values_with_flags; use crate::lineage; use crate::slm_validate::{self, ValidationReport}; use crate::writer::{align_to_64, write_f32, write_u32, write_u64}; const ADAPTER_ARTIFACT_VERSION: &str = "1"; const ADAPTER_BINARY_VERSION: u32 = 1; const ADAPTER_ARTIFACT_KIND: &str = "raw-f32-task-delta-v1"; const SPARSE_ADAPTER_ARTIFACT_KIND: &str = "sparse-f32-task-delta-v1"; const LOW_RANK_ADAPTER_ARTIFACT_KIND: &str = "low-rank-f32-task-delta-v1"; const ADAPTER_STATUS: &str = "artifact-written"; const ADAPTER_DTYPE: &str = "f32-delta"; const SPARSE_ADAPTER_DTYPE: &str = "sparse-f32-delta"; const LOW_RANK_ADAPTER_DTYPE: &str = "low-rank-f32-delta"; const ADAPTER_BASE_CONTRACT: &str = "matches-parent-direct-parameter-contract"; const ADAPTER_APPLY_STATUS_F32: &str = "runtime-f32-compatible-or-fuse-to-slm"; const ADAPTER_APPLY_STATUS_QUANTIZED: &str = "runtime-q8-q4-compatible-or-fuse-to-slm"; const LOW_RANK_APPLY_STATUS_F32: &str = "runtime-f32-compatible-low-rank"; const LOW_RANK_APPLY_STATUS_QUANTIZED: &str = "runtime-q8-q4-compatible-low-rank"; const REQUIRED_NEXT_GATE: &str = "fuse-to-slm-plus-candidate-manifest-plus-runtime-smoke-plus-eval"; const SPARSE_REQUIRED_NEXT_GATE: &str = "runtime-smoke-plus-eval-plus-selector-adapter-family-or-expand-to-adp1"; const LOW_RANK_REQUIRED_NEXT_GATE: &str = "runtime-smoke-plus-eval-plus-selector-adapter-family-route"; const ADAPTER_FUSE_VERSION: &str = "1"; const FUSE_OPERATOR_KIND: &str = "adapter-delta-fuse-to-slm"; const FUSE_OPERATOR_STATUS: &str = "candidate-written"; const FUSE_OPERATOR_OUTPUT_STATUS: &str = "slm-validated"; const FUSE_APPLY_STATUS: &str = "fused-to-slm-candidate"; const FUSE_MANIFEST_STATUS: &str = "validated"; const FUSE_REQUIRED_NEXT_GATE: &str = "candidate-manifest-plus-runtime-smoke-plus-eval"; const HEADER_LEN: usize = 64; const ENTRY_LEN: usize = 64; const CHECKSUM_OFFSET: usize = 56; const MAGIC: &[u8; 4] = b"ADP1"; const SPARSE_MAGIC: &[u8; 4] = b"ASP1"; const LOW_RANK_MAGIC: &[u8; 4] = b"ALR1"; const SPARSE_PAIR_LEN: usize = 12; const LOW_RANK_HEADER_LEN: usize = 16; const DEFAULT_LOW_RANK_COMPONENTS: &str = "1"; const MAX_LOW_RANK_COMPONENTS: usize = 8; const DEFAULT_SPARSE_KEEP_PPM: &str = "1000000"; const DEFAULT_DELTA_WEIGHT_PPM: &str = "1000000"; const MIN_DELTA_WEIGHT_PPM: i64 = -1_000_000; const MAX_DELTA_WEIGHT_PPM: i64 = 2_000_000; const PPM_DENOMINATOR: u32 = 1_000_000; /// One reviewed trained-source low-rank tensor to pack into an ALR1 package. pub(crate) struct LowRankSourceTensor<'a> { /// Stable tensor name hash. pub(crate) name_hash: u64, /// Logical tensor rank. pub(crate) rank: u32, /// Padded logical tensor dimensions. pub(crate) dims: [u32; 4], /// Matrix row count represented by A factors. pub(crate) rows: usize, /// Matrix column count represented by B factors. pub(crate) cols: usize, /// Number of low-rank components. pub(crate) factor_rank: usize, /// Row-major A factors with shape rows x factor_rank. pub(crate) a_values: &'a [f32], /// Row-major B factors with shape factor_rank x cols. pub(crate) b_values: &'a [f32], } /// Writes a raw f32 task-delta adapter artifact plus a recomputable manifest. pub(crate) fn write_artifact_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, output_adapter: &Path, output_manifest: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let (adapter, manifest) = build_artifact_bytes_and_manifest( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &output_adapter.display().to_string(), )?; if let Some(parent) = output_adapter.parent() { fs::create_dir_all(parent)?; } fs::write(output_adapter, adapter)?; if let Some(parent) = output_manifest.parent() { fs::create_dir_all(parent)?; } fs::write(output_manifest, manifest)?; println!( "SLM adapter-delta artifact written: {}", output_adapter.display() ); println!( "SLM adapter-delta manifest written: {}", output_manifest.display() ); Ok(()) } /// Validates an adapter artifact and manifest by recomputing both from parents. pub(crate) fn validate_artifact_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, adapter: &Path, manifest: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let adapter_bytes = fs::read(adapter)?; let manifest_text = fs::read_to_string(manifest)?; validate_artifact_text( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &adapter_bytes, &adapter.display().to_string(), &manifest_text, )?; println!("SLM adapter-delta validation: PASS"); println!("adapter: {}", adapter.display()); println!("manifest: {}", manifest.display()); Ok(()) } /// Writes a sparse f32 task-delta adapter artifact plus a recomputable manifest. pub(crate) fn write_sparse_artifact_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, output_adapter: &Path, output_manifest: &Path, delta_weight_ppm: Option<&str>, keep_ppm: Option<&str>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let (adapter, manifest) = build_sparse_artifact_bytes_and_manifest( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &output_adapter.display().to_string(), delta_weight_ppm, keep_ppm, )?; if let Some(parent) = output_adapter.parent() { fs::create_dir_all(parent)?; } fs::write(output_adapter, adapter)?; if let Some(parent) = output_manifest.parent() { fs::create_dir_all(parent)?; } fs::write(output_manifest, manifest)?; println!( "SLM sparse adapter-delta artifact written: {}", output_adapter.display() ); println!( "SLM sparse adapter-delta manifest written: {}", output_manifest.display() ); Ok(()) } /// Validates a sparse adapter artifact and manifest by recomputing both from parents. pub(crate) fn validate_sparse_artifact_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, adapter: &Path, manifest: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let adapter_bytes = fs::read(adapter)?; let manifest_text = fs::read_to_string(manifest)?; validate_sparse_artifact_text( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &adapter_bytes, &adapter.display().to_string(), &manifest_text, )?; println!("SLM sparse adapter-delta validation: PASS"); println!("adapter: {}", adapter.display()); println!("manifest: {}", manifest.display()); Ok(()) } /// Writes a low-rank f32 task-delta adapter artifact plus a recomputable manifest. pub(crate) fn write_low_rank_artifact_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, output_adapter: &Path, output_manifest: &Path, rank_limit: Option<&str>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let (adapter, manifest) = build_low_rank_artifact_bytes_and_manifest( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &output_adapter.display().to_string(), rank_limit, )?; if let Some(parent) = output_adapter.parent() { fs::create_dir_all(parent)?; } fs::write(output_adapter, adapter)?; if let Some(parent) = output_manifest.parent() { fs::create_dir_all(parent)?; } fs::write(output_manifest, manifest)?; println!( "SLM low-rank adapter-delta artifact written: {}", output_adapter.display() ); println!( "SLM low-rank adapter-delta manifest written: {}", output_manifest.display() ); Ok(()) } /// Validates a low-rank adapter artifact and manifest by recomputing both from parents. pub(crate) fn validate_low_rank_artifact_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, adapter: &Path, manifest: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let adapter_bytes = fs::read(adapter)?; let manifest_text = fs::read_to_string(manifest)?; validate_low_rank_artifact_text( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &adapter_bytes, &adapter.display().to_string(), &manifest_text, )?; println!("SLM low-rank adapter-delta validation: PASS"); println!("adapter: {}", adapter.display()); println!("manifest: {}", manifest.display()); Ok(()) } /// Fuses a validated adapter/delta artifact into a normal `.slm` candidate. pub(crate) fn fuse_artifact_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, adapter: &Path, adapter_manifest: &Path, output_slm: &Path, output_receipt: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let adapter_bytes = fs::read(adapter)?; let adapter_manifest_text = fs::read_to_string(adapter_manifest)?; let (candidate, receipt) = build_fused_candidate_bytes_and_receipt( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &adapter_bytes, &adapter.display().to_string(), &adapter_manifest_text, &output_slm.display().to_string(), )?; if let Some(parent) = output_slm.parent() { fs::create_dir_all(parent)?; } fs::write(output_slm, candidate)?; if let Some(parent) = output_receipt.parent() { fs::create_dir_all(parent)?; } fs::write(output_receipt, receipt)?; println!( "SLM adapter-fused candidate written: {}", output_slm.display() ); println!( "SLM adapter-fuse operator receipt written: {}", output_receipt.display() ); Ok(()) } /// Validates an adapter-fused `.slm` candidate by recomputing it from parents. pub(crate) fn validate_fused_candidate_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, adapter: &Path, adapter_manifest: &Path, candidate_slm: &Path, receipt: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let adapter_bytes = fs::read(adapter)?; let adapter_manifest_text = fs::read_to_string(adapter_manifest)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; validate_fused_candidate_text( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &adapter_bytes, &adapter.display().to_string(), &adapter_manifest_text, &candidate_bytes, &candidate_slm.display().to_string(), &receipt_text, )?; println!("SLM adapter-fused candidate validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("receipt: {}", receipt.display()); Ok(()) } fn validate_artifact_text( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, adapter_bytes: &[u8], adapter_path: &str, manifest_text: &str, ) -> io::Result<()> { let manifest = parse_manifest(manifest_text, "adapter-delta manifest")?; require_equal( &manifest, "tinyrustlm_adapter_artifact_version", ADAPTER_ARTIFACT_VERSION, )?; require_equal(&manifest, "adapter_artifact_kind", ADAPTER_ARTIFACT_KIND)?; let (expected_adapter, expected_manifest) = build_artifact_bytes_and_manifest( compatibility_text, lineage_text, base_bytes, base_path, target_bytes, target_path, adapter_path, )?; if adapter_bytes != expected_adapter { return Err(invalid( "adapter-delta artifact bytes do not match recomputed parent deltas", )); } if manifest_text != expected_manifest { return Err(invalid( "adapter-delta manifest fields do not match recomputed output", )); } Ok(()) } fn validate_sparse_artifact_text( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, adapter_bytes: &[u8], adapter_path: &str, manifest_text: &str, ) -> io::Result<()> { let manifest = parse_manifest(manifest_text, "sparse adapter-delta manifest")?; require_equal( &manifest, "tinyrustlm_adapter_artifact_version", ADAPTER_ARTIFACT_VERSION, )?; require_equal( &manifest, "adapter_artifact_kind", SPARSE_ADAPTER_ARTIFACT_KIND, )?; let delta_weight_ppm = require_key(&manifest, "adapter_delta_weight_ppm")?; let keep_ppm = require_key(&manifest, "adapter_sparse_keep_ppm")?; let (expected_adapter, expected_manifest) = build_sparse_artifact_bytes_and_manifest( compatibility_text, lineage_text, base_bytes, base_path, target_bytes, target_path, adapter_path, Some(delta_weight_ppm), Some(keep_ppm), )?; if adapter_bytes != expected_adapter { return Err(invalid( "sparse adapter-delta artifact bytes do not match recomputed parent deltas", )); } if manifest_text != expected_manifest { return Err(invalid( "sparse adapter-delta manifest fields do not match recomputed output", )); } Ok(()) } fn validate_low_rank_artifact_text( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, adapter_bytes: &[u8], adapter_path: &str, manifest_text: &str, ) -> io::Result<()> { let manifest = parse_manifest(manifest_text, "low-rank adapter-delta manifest")?; require_equal( &manifest, "tinyrustlm_adapter_artifact_version", ADAPTER_ARTIFACT_VERSION, )?; require_equal( &manifest, "adapter_artifact_kind", LOW_RANK_ADAPTER_ARTIFACT_KIND, )?; let rank_limit = require_key(&manifest, "adapter_low_rank_component_limit")?; let (expected_adapter, expected_manifest) = build_low_rank_artifact_bytes_and_manifest( compatibility_text, lineage_text, base_bytes, base_path, target_bytes, target_path, adapter_path, Some(rank_limit), )?; if adapter_bytes != expected_adapter { return Err(invalid( "low-rank adapter-delta artifact bytes do not match recomputed parent deltas", )); } if manifest_text != expected_manifest { return Err(invalid( "low-rank adapter-delta manifest fields do not match recomputed output", )); } Ok(()) } fn validate_fused_candidate_text( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, adapter_bytes: &[u8], adapter_path: &str, adapter_manifest_text: &str, candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, ) -> io::Result<()> { let receipt = parse_manifest(receipt_text, "adapter-fuse operator receipt")?; require_equal( &receipt, "tinyrustlm_adapter_fuse_version", ADAPTER_FUSE_VERSION, )?; require_equal(&receipt, "operator_kind", FUSE_OPERATOR_KIND)?; require_equal(&receipt, "operator_status", FUSE_OPERATOR_STATUS)?; require_equal(&receipt, "adapter_artifact_kind", ADAPTER_ARTIFACT_KIND)?; require_equal(&receipt, "adapter_manifest_status", FUSE_MANIFEST_STATUS)?; require_equal(&receipt, "adapter_apply_status", FUSE_APPLY_STATUS)?; require_equal(&receipt, "candidate_parent_contract", ADAPTER_BASE_CONTRACT)?; require_equal( &receipt, "operator_output_status", FUSE_OPERATOR_OUTPUT_STATUS, )?; let (expected_candidate, expected_receipt) = build_fused_candidate_bytes_and_receipt( compatibility_text, lineage_text, base_bytes, base_path, target_bytes, target_path, adapter_bytes, adapter_path, adapter_manifest_text, candidate_path, )?; if candidate_bytes != expected_candidate { return Err(invalid( "adapter-fused candidate bytes do not match recomputed output", )); } if receipt_text != expected_receipt { return Err(invalid( "adapter-fuse operator receipt fields do not match recomputed output", )); } Ok(()) } fn build_fused_candidate_bytes_and_receipt( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, adapter_bytes: &[u8], adapter_path: &str, adapter_manifest_text: &str, candidate_path: &str, ) -> io::Result<(Vec, String)> { validate_artifact_text( compatibility_text, lineage_text, base_bytes, base_path, target_bytes, target_path, adapter_bytes, adapter_path, adapter_manifest_text, )?; lineage::validate_text(compatibility_text, lineage_text)?; let compatibility = parse_passing_compatibility(compatibility_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let base_report = slm_validate::validate_bytes(base_bytes, base_path)?; let target_report = slm_validate::validate_bytes(target_bytes, target_path)?; require_parent_report(&compatibility, 0, &base_report)?; require_parent_report(&compatibility, 1, &target_report)?; let base = parse_model_values(base_bytes)?; let adapter_deltas = read_adapter_deltas(adapter_bytes, &base, &base_report)?; let output_values = fused_values(&base, &adapter_deltas)?; let output_tensors = output_specs(&base); let candidate = build_model_file_from_values_with_flags( &base.shape, &output_tensors, &base.tokenizer, &output_values, base.flags, )?; let candidate_report = slm_validate::validate_bytes(&candidate, candidate_path)?; require_report_equal( &compatibility, "parent.0.model_shape", &candidate_report.shape_summary(), )?; require_report_equal( &compatibility, "parent.0.quantization", candidate_report.quantization_label(), )?; require_report_equal( &compatibility, "parent.0.output_contract", candidate_report.output_contract_label(), )?; require_report_equal( &compatibility, "parent.0.tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), )?; require_report_equal( &compatibility, "parent.0.tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), )?; let receipt = build_fuse_receipt_text( &compatibility, &lineage_fields, lineage_text, base_path, target_path, &base_report, &target_report, adapter_path, adapter_manifest_text, adapter_bytes, &candidate_report, )?; Ok((candidate, receipt)) } fn build_artifact_bytes_and_manifest( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, adapter_path: &str, ) -> io::Result<(Vec, String)> { lineage::validate_text(compatibility_text, lineage_text)?; let compatibility = parse_passing_compatibility(compatibility_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let base_report = slm_validate::validate_bytes(base_bytes, base_path)?; let target_report = slm_validate::validate_bytes(target_bytes, target_path)?; require_parent_report(&compatibility, 0, &base_report)?; require_parent_report(&compatibility, 1, &target_report)?; let base = parse_model_values(base_bytes)?; let target = parse_model_values(target_bytes)?; let adapter = build_adapter_bytes(&base, &target, &base_report)?; validate_adapter_bytes(&adapter)?; let manifest = build_manifest_text( &compatibility, &lineage_fields, lineage_text, base_path, target_path, &base_report, &target_report, adapter_path, &adapter, )?; Ok((adapter, manifest)) } fn build_sparse_artifact_bytes_and_manifest( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, adapter_path: &str, delta_weight_ppm: Option<&str>, keep_ppm: Option<&str>, ) -> io::Result<(Vec, String)> { lineage::validate_text(compatibility_text, lineage_text)?; let compatibility = parse_passing_compatibility(compatibility_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let base_report = slm_validate::validate_bytes(base_bytes, base_path)?; let target_report = slm_validate::validate_bytes(target_bytes, target_path)?; require_parent_report(&compatibility, 0, &base_report)?; require_parent_report(&compatibility, 1, &target_report)?; let delta_weight = parse_delta_weight_ppm(delta_weight_ppm.unwrap_or(DEFAULT_DELTA_WEIGHT_PPM))?; let keep = parse_keep_ppm(keep_ppm.unwrap_or(DEFAULT_SPARSE_KEEP_PPM))?; let base = parse_model_values(base_bytes)?; let target = parse_model_values(target_bytes)?; let (adapter, stats) = build_sparse_adapter_bytes(&base, &target, &base_report, delta_weight, keep)?; validate_sparse_adapter_bytes(&adapter)?; let manifest = build_sparse_manifest_text( &compatibility, &lineage_fields, lineage_text, base_path, target_path, &base_report, &target_report, adapter_path, &adapter, delta_weight, keep, stats, )?; Ok((adapter, manifest)) } fn build_low_rank_artifact_bytes_and_manifest( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, adapter_path: &str, rank_limit: Option<&str>, ) -> io::Result<(Vec, String)> { lineage::validate_text(compatibility_text, lineage_text)?; let compatibility = parse_passing_compatibility(compatibility_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let base_report = slm_validate::validate_bytes(base_bytes, base_path)?; let target_report = slm_validate::validate_bytes(target_bytes, target_path)?; require_parent_report(&compatibility, 0, &base_report)?; require_parent_report(&compatibility, 1, &target_report)?; let rank_limit = parse_low_rank_components(rank_limit.unwrap_or(DEFAULT_LOW_RANK_COMPONENTS))?; let base = parse_model_values(base_bytes)?; let target = parse_model_values(target_bytes)?; let (adapter, stats) = build_low_rank_adapter_bytes(&base, &target, &base_report, rank_limit)?; validate_low_rank_adapter_bytes(&adapter)?; let manifest = build_low_rank_manifest_text( &compatibility, &lineage_fields, lineage_text, base_path, target_path, &base_report, &target_report, adapter_path, &adapter, rank_limit, stats, )?; Ok((adapter, manifest)) } fn build_adapter_bytes( base: &ParsedModel, target: &ParsedModel, base_report: &ValidationReport, ) -> io::Result> { validate_parent_models(base, target)?; let tensor_count = base.tensors.len(); let directory_offset = HEADER_LEN; let data_offset = align_to_64(directory_offset + tensor_count * ENTRY_LEN); let mut tensor_offsets = Vec::with_capacity(tensor_count); let mut tensor_lengths = Vec::with_capacity(tensor_count); let mut tensor_checksums = Vec::with_capacity(tensor_count); let mut delta_values = Vec::with_capacity(tensor_count); let mut cursor = data_offset; for (base_tensor, target_tensor) in base.tensors.iter().zip(target.tensors.iter()) { require_same_tensor_spec(&base_tensor.spec, &target_tensor.spec)?; cursor = align_to_64(cursor); tensor_offsets.push(cursor); let mut deltas = Vec::with_capacity(base_tensor.values.len()); for (base_value, target_value) in base_tensor.values.iter().zip(target_tensor.values.iter()) { deltas.push(target_value - base_value); } let byte_length = deltas .len() .checked_mul(4) .ok_or_else(|| invalid("adapter tensor byte length overflow"))?; tensor_lengths.push(byte_length); cursor = cursor .checked_add(byte_length) .ok_or_else(|| invalid("adapter payload length overflow"))?; let mut payload = vec![0u8; byte_length]; for (index, value) in deltas.iter().enumerate() { write_f32(&mut payload, index * 4, *value)?; } tensor_checksums.push(payload_checksum(&payload)); delta_values.push(deltas); } let mut bytes = vec![0u8; cursor]; bytes[0..4].copy_from_slice(MAGIC); write_u32(&mut bytes, 4, ADAPTER_BINARY_VERSION)?; write_u32(&mut bytes, 8, HEADER_LEN as u32)?; write_u32(&mut bytes, 12, tensor_count as u32)?; write_u32(&mut bytes, 16, base.flags)?; write_u32(&mut bytes, 20, ENTRY_LEN as u32)?; write_u64(&mut bytes, 24, base_report.parameter_count() as u64)?; write_u64(&mut bytes, 32, base_report.tensor_layout_checksum())?; write_u64(&mut bytes, 40, base_report.tokenizer_checksum())?; write_u64(&mut bytes, 48, data_offset as u64)?; write_u64(&mut bytes, CHECKSUM_OFFSET, 0)?; for (index, tensor) in base.tensors.iter().enumerate() { let entry = directory_offset + index * ENTRY_LEN; write_u64(&mut bytes, entry, tensor.spec.name_hash)?; write_u32(&mut bytes, entry + 8, tensor.spec.rank)?; write_u32(&mut bytes, entry + 12, tensor.spec.dims[0])?; write_u32(&mut bytes, entry + 16, tensor.spec.dims[1])?; write_u32(&mut bytes, entry + 20, tensor.spec.dims[2])?; write_u32(&mut bytes, entry + 24, tensor.spec.dims[3])?; write_u32(&mut bytes, entry + 28, 0)?; write_u64(&mut bytes, entry + 32, tensor_offsets[index] as u64)?; write_u64(&mut bytes, entry + 40, tensor_lengths[index] as u64)?; write_u64(&mut bytes, entry + 48, tensor.spec.element_count() as u64)?; write_u64(&mut bytes, entry + 56, tensor_checksums[index])?; let start = tensor_offsets[index]; for (value_index, value) in delta_values[index].iter().enumerate() { write_f32(&mut bytes, start + value_index * 4, *value)?; } } let checksum = adapter_checksum(&bytes)?; write_u64(&mut bytes, CHECKSUM_OFFSET, checksum)?; Ok(bytes) } fn build_sparse_adapter_bytes( base: &ParsedModel, target: &ParsedModel, base_report: &ValidationReport, delta_weight_ppm: i64, keep_ppm: u32, ) -> io::Result<(Vec, SparseStats)> { validate_parent_models(base, target)?; let tensor_count = base.tensors.len(); let directory_offset = HEADER_LEN; let data_offset = align_to_64(directory_offset + tensor_count * ENTRY_LEN); let mut ranked = Vec::new(); let mut total_parameter_count = 0u64; for (tensor_index, (base_tensor, target_tensor)) in base.tensors.iter().zip(target.tensors.iter()).enumerate() { require_same_tensor_spec(&base_tensor.spec, &target_tensor.spec)?; total_parameter_count += base_tensor.values.len() as u64; for (value_index, (base_value, target_value)) in base_tensor .values .iter() .zip(target_tensor.values.iter()) .enumerate() { let delta = target_value - base_value; let magnitude = delta.abs(); if magnitude > 0.0 { ranked.push(RankedDelta { magnitude, tensor_index, value_index, delta, }); } } } ranked.sort_by(compare_ranked_delta); let requested_keep = keep_count(total_parameter_count, keep_ppm)?; let kept_parameter_count = requested_keep.min(ranked.len() as u64); let delta_weight = delta_weight_ppm as f32 / PPM_DENOMINATOR as f32; let selected = ranked .iter() .take(kept_parameter_count as usize) .collect::>(); let mut selected_by_tensor = vec![Vec::<(usize, f32)>::new(); tensor_count]; for entry in &selected { selected_by_tensor[entry.tensor_index] .push((entry.value_index, entry.delta * delta_weight)); } for pairs in &mut selected_by_tensor { pairs.sort_by_key(|(value_index, _)| *value_index); } let mut tensor_offsets = Vec::with_capacity(tensor_count); let mut tensor_lengths = Vec::with_capacity(tensor_count); let mut tensor_checksums = Vec::with_capacity(tensor_count); let mut payloads = Vec::with_capacity(tensor_count); let mut cursor = data_offset; for pairs in &selected_by_tensor { cursor = align_to_64(cursor); tensor_offsets.push(cursor); let byte_length = pairs .len() .checked_mul(SPARSE_PAIR_LEN) .ok_or_else(|| invalid("sparse adapter tensor byte length overflow"))?; tensor_lengths.push(byte_length); cursor = cursor .checked_add(byte_length) .ok_or_else(|| invalid("sparse adapter payload length overflow"))?; let mut payload = vec![0u8; byte_length]; for (pair_index, (value_index, delta)) in pairs.iter().enumerate() { let offset = pair_index * SPARSE_PAIR_LEN; write_u64(&mut payload, offset, *value_index as u64)?; write_f32(&mut payload, offset + 8, *delta)?; } tensor_checksums.push(payload_checksum(&payload)); payloads.push(payload); } let mut bytes = vec![0u8; cursor]; bytes[0..4].copy_from_slice(SPARSE_MAGIC); write_u32(&mut bytes, 4, ADAPTER_BINARY_VERSION)?; write_u32(&mut bytes, 8, HEADER_LEN as u32)?; write_u32(&mut bytes, 12, tensor_count as u32)?; write_u32(&mut bytes, 16, base.flags)?; write_u32(&mut bytes, 20, ENTRY_LEN as u32)?; write_u64(&mut bytes, 24, base_report.parameter_count() as u64)?; write_u64(&mut bytes, 32, base_report.tensor_layout_checksum())?; write_u64(&mut bytes, 40, base_report.tokenizer_checksum())?; write_u64(&mut bytes, 48, data_offset as u64)?; write_u64(&mut bytes, CHECKSUM_OFFSET, 0)?; for (index, tensor) in base.tensors.iter().enumerate() { let entry = directory_offset + index * ENTRY_LEN; write_u64(&mut bytes, entry, tensor.spec.name_hash)?; write_u32(&mut bytes, entry + 8, tensor.spec.rank)?; write_u32(&mut bytes, entry + 12, tensor.spec.dims[0])?; write_u32(&mut bytes, entry + 16, tensor.spec.dims[1])?; write_u32(&mut bytes, entry + 20, tensor.spec.dims[2])?; write_u32(&mut bytes, entry + 24, tensor.spec.dims[3])?; write_u32(&mut bytes, entry + 28, 0)?; write_u64(&mut bytes, entry + 32, tensor_offsets[index] as u64)?; write_u64(&mut bytes, entry + 40, tensor_lengths[index] as u64)?; write_u64(&mut bytes, entry + 48, tensor.spec.element_count() as u64)?; write_u64(&mut bytes, entry + 56, tensor_checksums[index])?; let start = tensor_offsets[index]; bytes[start..start + tensor_lengths[index]].copy_from_slice(&payloads[index]); } let checksum = adapter_checksum(&bytes)?; write_u64(&mut bytes, CHECKSUM_OFFSET, checksum)?; let nonzero_delta_count = ranked.len() as u64; let stats = SparseStats { total_parameter_count, nonzero_delta_count, kept_parameter_count, pruned_parameter_count: total_parameter_count - kept_parameter_count, unchanged_parameter_count: total_parameter_count - nonzero_delta_count, pruned_nonzero_delta_count: nonzero_delta_count - kept_parameter_count, density_ppm: ratio_ppm(kept_parameter_count, total_parameter_count)?, nonzero_delta_retention_ppm: ratio_ppm(kept_parameter_count, nonzero_delta_count)?, mask_checksum: sparse_mask_checksum(&selected, total_parameter_count), }; Ok((bytes, stats)) } fn build_low_rank_adapter_bytes( base: &ParsedModel, target: &ParsedModel, base_report: &ValidationReport, rank_limit: usize, ) -> io::Result<(Vec, LowRankStats)> { validate_parent_models(base, target)?; let tensor_count = base.tensors.len(); let directory_offset = HEADER_LEN; let data_offset = align_to_64(directory_offset + tensor_count * ENTRY_LEN); let mut tensor_offsets = Vec::with_capacity(tensor_count); let mut tensor_lengths = Vec::with_capacity(tensor_count); let mut tensor_checksums = Vec::with_capacity(tensor_count); let mut payloads = Vec::with_capacity(tensor_count); let mut cursor = data_offset; let mut stats = LowRankStats::default(); for (base_tensor, target_tensor) in base.tensors.iter().zip(target.tensors.iter()) { require_same_tensor_spec(&base_tensor.spec, &target_tensor.spec)?; cursor = align_to_64(cursor); tensor_offsets.push(cursor); let (payload, tensor_stats) = build_low_rank_tensor_payload(base_tensor, target_tensor, rank_limit)?; tensor_lengths.push(payload.len()); cursor = cursor .checked_add(payload.len()) .ok_or_else(|| invalid("low-rank adapter payload length overflow"))?; tensor_checksums.push(payload_checksum(&payload)); stats.add(tensor_stats)?; payloads.push(payload); } let mut bytes = vec![0u8; cursor]; bytes[0..4].copy_from_slice(LOW_RANK_MAGIC); write_u32(&mut bytes, 4, ADAPTER_BINARY_VERSION)?; write_u32(&mut bytes, 8, HEADER_LEN as u32)?; write_u32(&mut bytes, 12, tensor_count as u32)?; write_u32(&mut bytes, 16, base.flags)?; write_u32(&mut bytes, 20, ENTRY_LEN as u32)?; write_u64(&mut bytes, 24, base_report.parameter_count() as u64)?; write_u64(&mut bytes, 32, base_report.tensor_layout_checksum())?; write_u64(&mut bytes, 40, base_report.tokenizer_checksum())?; write_u64(&mut bytes, 48, data_offset as u64)?; write_u64(&mut bytes, CHECKSUM_OFFSET, 0)?; for (index, tensor) in base.tensors.iter().enumerate() { let entry = directory_offset + index * ENTRY_LEN; write_u64(&mut bytes, entry, tensor.spec.name_hash)?; write_u32(&mut bytes, entry + 8, tensor.spec.rank)?; write_u32(&mut bytes, entry + 12, tensor.spec.dims[0])?; write_u32(&mut bytes, entry + 16, tensor.spec.dims[1])?; write_u32(&mut bytes, entry + 20, tensor.spec.dims[2])?; write_u32(&mut bytes, entry + 24, tensor.spec.dims[3])?; write_u32(&mut bytes, entry + 28, 0)?; write_u64(&mut bytes, entry + 32, tensor_offsets[index] as u64)?; write_u64(&mut bytes, entry + 40, tensor_lengths[index] as u64)?; write_u64(&mut bytes, entry + 48, tensor.spec.element_count() as u64)?; write_u64(&mut bytes, entry + 56, tensor_checksums[index])?; let start = tensor_offsets[index]; bytes[start..start + tensor_lengths[index]].copy_from_slice(&payloads[index]); } let checksum = adapter_checksum(&bytes)?; write_u64(&mut bytes, CHECKSUM_OFFSET, checksum)?; Ok((bytes, stats)) } /// Builds an ALR1 package from reviewed trained-source low-rank factors. pub(crate) fn build_low_rank_source_adapter_bytes( base: &ParsedModel, base_report: &ValidationReport, source_tensors: &[LowRankSourceTensor<'_>], ) -> io::Result> { let mut source_by_hash = HashMap::new(); for (index, source) in source_tensors.iter().enumerate() { if source_by_hash.insert(source.name_hash, index).is_some() { return Err(invalid("low-rank source tensor hashes must be unique")); } } let tensor_count = base.tensors.len(); let directory_offset = HEADER_LEN; let data_offset = align_to_64(directory_offset + tensor_count * ENTRY_LEN); let mut tensor_offsets = Vec::with_capacity(tensor_count); let mut tensor_lengths = Vec::with_capacity(tensor_count); let mut tensor_checksums = Vec::with_capacity(tensor_count); let mut payloads = Vec::with_capacity(tensor_count); let mut cursor = data_offset; for tensor in &base.tensors { cursor = align_to_64(cursor); tensor_offsets.push(cursor); let payload = if let Some(source_index) = source_by_hash.get(&tensor.spec.name_hash) { build_low_rank_source_tensor_payload(tensor, &source_tensors[*source_index])? } else { Vec::new() }; tensor_lengths.push(payload.len()); cursor = cursor .checked_add(payload.len()) .ok_or_else(|| invalid("low-rank source adapter payload length overflow"))?; tensor_checksums.push(payload_checksum(&payload)); payloads.push(payload); } let mut bytes = vec![0u8; cursor]; bytes[0..4].copy_from_slice(LOW_RANK_MAGIC); write_u32(&mut bytes, 4, ADAPTER_BINARY_VERSION)?; write_u32(&mut bytes, 8, HEADER_LEN as u32)?; write_u32(&mut bytes, 12, tensor_count as u32)?; write_u32(&mut bytes, 16, base.flags)?; write_u32(&mut bytes, 20, ENTRY_LEN as u32)?; write_u64(&mut bytes, 24, base_report.parameter_count())?; write_u64(&mut bytes, 32, base_report.tensor_layout_checksum())?; write_u64(&mut bytes, 40, base_report.tokenizer_checksum())?; write_u64(&mut bytes, 48, data_offset as u64)?; write_u64(&mut bytes, CHECKSUM_OFFSET, 0)?; for (index, tensor) in base.tensors.iter().enumerate() { let entry = directory_offset + index * ENTRY_LEN; write_u64(&mut bytes, entry, tensor.spec.name_hash)?; write_u32(&mut bytes, entry + 8, tensor.spec.rank)?; write_u32(&mut bytes, entry + 12, tensor.spec.dims[0])?; write_u32(&mut bytes, entry + 16, tensor.spec.dims[1])?; write_u32(&mut bytes, entry + 20, tensor.spec.dims[2])?; write_u32(&mut bytes, entry + 24, tensor.spec.dims[3])?; write_u32(&mut bytes, entry + 28, 0)?; write_u64(&mut bytes, entry + 32, tensor_offsets[index] as u64)?; write_u64(&mut bytes, entry + 40, tensor_lengths[index] as u64)?; write_u64(&mut bytes, entry + 48, tensor.spec.element_count() as u64)?; write_u64(&mut bytes, entry + 56, tensor_checksums[index])?; let start = tensor_offsets[index]; bytes[start..start + tensor_lengths[index]].copy_from_slice(&payloads[index]); } let checksum = adapter_checksum(&bytes)?; write_u64(&mut bytes, CHECKSUM_OFFSET, checksum)?; Ok(bytes) } fn build_low_rank_source_tensor_payload( tensor: &crate::blend::ParsedTensor, source: &LowRankSourceTensor<'_>, ) -> io::Result> { if tensor.spec.name_hash != source.name_hash || tensor.spec.rank != source.rank || tensor.spec.dims != source.dims { return Err(invalid( "low-rank source tensor identity does not match base model", )); } let (rows, cols) = low_rank_matrix_shape(&tensor.spec)?; if rows != source.rows || cols != source.cols { return Err(invalid( "low-rank source tensor matrix shape does not match base model", )); } if source.factor_rank == 0 || source.factor_rank > MAX_LOW_RANK_COMPONENTS || source.factor_rank > rows.min(cols) { return Err(invalid("low-rank source factor rank is out of range")); } let expected_a = rows .checked_mul(source.factor_rank) .ok_or_else(|| invalid("low-rank source A factor length overflow"))?; let expected_b = source .factor_rank .checked_mul(cols) .ok_or_else(|| invalid("low-rank source B factor length overflow"))?; if source.a_values.len() != expected_a || source.b_values.len() != expected_b { return Err(invalid("low-rank source factor lengths do not match shape")); } for value in source.a_values.iter().chain(source.b_values.iter()) { if !value.is_finite() { return Err(invalid("low-rank source factor is not finite")); } } let factor_values = source .factor_rank .checked_mul( rows.checked_add(cols) .ok_or_else(|| invalid("low-rank source shape overflow"))?, ) .ok_or_else(|| invalid("low-rank source factor count overflow"))?; let byte_length = LOW_RANK_HEADER_LEN .checked_add( factor_values .checked_mul(4) .ok_or_else(|| invalid("low-rank source payload byte length overflow"))?, ) .ok_or_else(|| invalid("low-rank source payload byte length overflow"))?; let mut payload = vec![0u8; byte_length]; write_u32(&mut payload, 0, rows as u32)?; write_u32(&mut payload, 4, cols as u32)?; write_u32(&mut payload, 8, source.factor_rank as u32)?; write_u32(&mut payload, 12, 0)?; let mut offset = LOW_RANK_HEADER_LEN; for component in 0..source.factor_rank { for row in 0..rows { write_f32( &mut payload, offset, source.a_values[row * source.factor_rank + component], )?; offset += 4; } } for component in 0..source.factor_rank { for col in 0..cols { write_f32( &mut payload, offset, source.b_values[component * cols + col], )?; offset += 4; } } Ok(payload) } fn build_low_rank_tensor_payload( base_tensor: &crate::blend::ParsedTensor, target_tensor: &crate::blend::ParsedTensor, rank_limit: usize, ) -> io::Result<(Vec, LowRankTensorStats)> { let element_count = base_tensor.spec.element_count(); let mut stats = LowRankTensorStats { parameter_count: element_count as u64, ..LowRankTensorStats::default() }; if base_tensor.spec.rank < 2 { return Ok((Vec::new(), stats)); } let (rows, cols) = low_rank_matrix_shape(&base_tensor.spec)?; let mut residual = Vec::with_capacity(element_count); let mut initial_l1 = 0.0f64; for (base_value, target_value) in base_tensor.values.iter().zip(target_tensor.values.iter()) { let delta = target_value - base_value; initial_l1 += f64::from(delta.abs()); residual.push(delta); } stats.matrix_tensor_count = 1; stats.matrix_parameter_count = element_count as u64; stats.initial_l1_microunits = l1_microunits(initial_l1)?; let components = low_rank_components(&mut residual, rows, cols, rank_limit.min(rows.min(cols)))?; if components.is_empty() { stats.residual_l1_microunits = stats.initial_l1_microunits; return Ok((Vec::new(), stats)); } let factor_values = components .len() .checked_mul( rows.checked_add(cols) .ok_or_else(|| invalid("low-rank shape overflow"))?, ) .ok_or_else(|| invalid("low-rank factor count overflow"))?; let byte_length = LOW_RANK_HEADER_LEN .checked_add( factor_values .checked_mul(4) .ok_or_else(|| invalid("low-rank payload byte length overflow"))?, ) .ok_or_else(|| invalid("low-rank payload byte length overflow"))?; let mut payload = vec![0u8; byte_length]; write_u32(&mut payload, 0, rows as u32)?; write_u32(&mut payload, 4, cols as u32)?; write_u32(&mut payload, 8, components.len() as u32)?; write_u32(&mut payload, 12, 0)?; let mut offset = LOW_RANK_HEADER_LEN; for component in &components { for value in &component.a { write_f32(&mut payload, offset, *value)?; offset += 4; } } for component in &components { for value in &component.b { write_f32(&mut payload, offset, *value)?; offset += 4; } } let residual_l1 = residual .iter() .fold(0.0f64, |acc, value| acc + f64::from(value.abs())); stats.active_tensor_count = 1; stats.component_count = components.len() as u64; stats.factor_parameter_count = factor_values as u64; stats.residual_l1_microunits = l1_microunits(residual_l1)?; Ok((payload, stats)) } fn build_manifest_text( compatibility: &HashMap, lineage_fields: &HashMap, lineage_text: &str, base_path: &str, target_path: &str, base_report: &ValidationReport, target_report: &ValidationReport, adapter_path: &str, adapter_bytes: &[u8], ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_adapter_artifact_version", ADAPTER_ARTIFACT_VERSION, ); push_line(&mut text, "adapter_artifact_kind", ADAPTER_ARTIFACT_KIND); push_line(&mut text, "adapter_status", ADAPTER_STATUS); push_line( &mut text, "candidate_id", require_key(lineage_fields, "candidate_id")?, ); push_line( &mut text, "operator_id", require_key(lineage_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(lineage_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(lineage_fields, "resource_budget")?, ); push_line( &mut text, "compatibility_report_checksum", require_key(lineage_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(compatibility, "compatibility_scope")?, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, compatibility, 0, base_path, base_report)?; push_parent_lines(&mut text, compatibility, 1, target_path, target_report)?; push_line(&mut text, "adapter_artifact_path", adapter_path); push_line( &mut text, "adapter_artifact_bytes", &adapter_bytes.len().to_string(), ); push_line( &mut text, "adapter_artifact_checksum", &hex64(read_u64(adapter_bytes, CHECKSUM_OFFSET)?), ); push_line( &mut text, "adapter_tensor_count", &base_report.tensor_count().to_string(), ); push_line( &mut text, "adapter_parameter_count", &base_report.parameter_count().to_string(), ); push_line(&mut text, "adapter_dtype", ADAPTER_DTYPE); push_line( &mut text, "adapter_model_shape", &base_report.shape_summary(), ); push_line( &mut text, "adapter_base_quantization", base_report.quantization_label(), ); push_line( &mut text, "adapter_output_contract", base_report.output_contract_label(), ); push_line( &mut text, "adapter_tokenizer_checksum", &hex64(base_report.tokenizer_checksum()), ); push_line( &mut text, "adapter_tensor_layout_checksum", &hex64(base_report.tensor_layout_checksum()), ); push_line(&mut text, "adapter_base_contract", ADAPTER_BASE_CONTRACT); push_line( &mut text, "adapter_apply_status", adapter_apply_status(base_report), ); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } fn build_sparse_manifest_text( compatibility: &HashMap, lineage_fields: &HashMap, lineage_text: &str, base_path: &str, target_path: &str, base_report: &ValidationReport, target_report: &ValidationReport, adapter_path: &str, adapter_bytes: &[u8], delta_weight_ppm: i64, keep_ppm: u32, stats: SparseStats, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_adapter_artifact_version", ADAPTER_ARTIFACT_VERSION, ); push_line( &mut text, "adapter_artifact_kind", SPARSE_ADAPTER_ARTIFACT_KIND, ); push_line(&mut text, "adapter_status", ADAPTER_STATUS); push_line( &mut text, "candidate_id", require_key(lineage_fields, "candidate_id")?, ); push_line( &mut text, "operator_id", require_key(lineage_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(lineage_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(lineage_fields, "resource_budget")?, ); push_line( &mut text, "compatibility_report_checksum", require_key(lineage_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(compatibility, "compatibility_scope")?, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, compatibility, 0, base_path, base_report)?; push_parent_lines(&mut text, compatibility, 1, target_path, target_report)?; push_line(&mut text, "adapter_artifact_path", adapter_path); push_line( &mut text, "adapter_artifact_bytes", &adapter_bytes.len().to_string(), ); push_line( &mut text, "adapter_artifact_checksum", &hex64(read_u64(adapter_bytes, CHECKSUM_OFFSET)?), ); push_line( &mut text, "adapter_tensor_count", &base_report.tensor_count().to_string(), ); push_line( &mut text, "adapter_parameter_count", &base_report.parameter_count().to_string(), ); push_line(&mut text, "adapter_dtype", SPARSE_ADAPTER_DTYPE); push_line( &mut text, "adapter_model_shape", &base_report.shape_summary(), ); push_line( &mut text, "adapter_base_quantization", base_report.quantization_label(), ); push_line( &mut text, "adapter_output_contract", base_report.output_contract_label(), ); push_line( &mut text, "adapter_tokenizer_checksum", &hex64(base_report.tokenizer_checksum()), ); push_line( &mut text, "adapter_tensor_layout_checksum", &hex64(base_report.tensor_layout_checksum()), ); push_line(&mut text, "adapter_base_contract", ADAPTER_BASE_CONTRACT); push_line(&mut text, "adapter_delta_weight_unit", "parts-per-million"); push_line( &mut text, "adapter_delta_weight_ppm", &delta_weight_ppm.to_string(), ); push_line(&mut text, "adapter_sparse_keep_unit", "parts-per-million"); push_line(&mut text, "adapter_sparse_keep_ppm", &keep_ppm.to_string()); push_line( &mut text, "adapter_sparse_pair_width_bytes", &SPARSE_PAIR_LEN.to_string(), ); push_line( &mut text, "adapter_sparse_selection_metric", "absolute-target-minus-base-delta", ); push_line( &mut text, "adapter_sparse_selection_scope", "global-compatible-parent-tensors", ); push_line( &mut text, "adapter_sparse_tie_break", "tensor-index-then-value-index", ); push_line( &mut text, "adapter_sparse_total_parameter_count", &stats.total_parameter_count.to_string(), ); push_line( &mut text, "adapter_sparse_nonzero_delta_count", &stats.nonzero_delta_count.to_string(), ); push_line( &mut text, "adapter_sparse_kept_parameter_count", &stats.kept_parameter_count.to_string(), ); push_line( &mut text, "adapter_sparse_pruned_parameter_count", &stats.pruned_parameter_count.to_string(), ); push_line( &mut text, "adapter_sparse_unchanged_parameter_count", &stats.unchanged_parameter_count.to_string(), ); push_line( &mut text, "adapter_sparse_pruned_nonzero_delta_count", &stats.pruned_nonzero_delta_count.to_string(), ); push_line( &mut text, "adapter_sparse_density_ppm", &stats.density_ppm.to_string(), ); push_line( &mut text, "adapter_sparse_nonzero_delta_retention_ppm", &stats.nonzero_delta_retention_ppm.to_string(), ); push_line( &mut text, "adapter_sparse_mask_checksum", &hex64(stats.mask_checksum), ); push_line( &mut text, "adapter_apply_status", adapter_apply_status(base_report), ); push_line(&mut text, "required_next_gate", SPARSE_REQUIRED_NEXT_GATE); Ok(text) } fn build_low_rank_manifest_text( compatibility: &HashMap, lineage_fields: &HashMap, lineage_text: &str, base_path: &str, target_path: &str, base_report: &ValidationReport, target_report: &ValidationReport, adapter_path: &str, adapter_bytes: &[u8], rank_limit: usize, stats: LowRankStats, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_adapter_artifact_version", ADAPTER_ARTIFACT_VERSION, ); push_line( &mut text, "adapter_artifact_kind", LOW_RANK_ADAPTER_ARTIFACT_KIND, ); push_line(&mut text, "adapter_status", ADAPTER_STATUS); push_line( &mut text, "candidate_id", require_key(lineage_fields, "candidate_id")?, ); push_line( &mut text, "operator_id", require_key(lineage_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(lineage_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(lineage_fields, "resource_budget")?, ); push_line( &mut text, "compatibility_report_checksum", require_key(lineage_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(compatibility, "compatibility_scope")?, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, compatibility, 0, base_path, base_report)?; push_parent_lines(&mut text, compatibility, 1, target_path, target_report)?; push_line(&mut text, "adapter_artifact_path", adapter_path); push_line( &mut text, "adapter_artifact_bytes", &adapter_bytes.len().to_string(), ); push_line( &mut text, "adapter_artifact_checksum", &hex64(read_u64(adapter_bytes, CHECKSUM_OFFSET)?), ); push_line( &mut text, "adapter_tensor_count", &base_report.tensor_count().to_string(), ); push_line( &mut text, "adapter_parameter_count", &base_report.parameter_count().to_string(), ); push_line(&mut text, "adapter_dtype", LOW_RANK_ADAPTER_DTYPE); push_line( &mut text, "adapter_model_shape", &base_report.shape_summary(), ); push_line( &mut text, "adapter_base_quantization", base_report.quantization_label(), ); push_line( &mut text, "adapter_output_contract", base_report.output_contract_label(), ); push_line( &mut text, "adapter_tokenizer_checksum", &hex64(base_report.tokenizer_checksum()), ); push_line( &mut text, "adapter_tensor_layout_checksum", &hex64(base_report.tensor_layout_checksum()), ); push_line(&mut text, "adapter_base_contract", ADAPTER_BASE_CONTRACT); push_line(&mut text, "adapter_low_rank_format", "ALR1"); push_line( &mut text, "adapter_low_rank_component_limit", &rank_limit.to_string(), ); push_line( &mut text, "adapter_low_rank_component_cap", &MAX_LOW_RANK_COMPONENTS.to_string(), ); push_line( &mut text, "adapter_low_rank_payload_header_bytes", &LOW_RANK_HEADER_LEN.to_string(), ); push_line(&mut text, "adapter_low_rank_factor_dtype", "f32"); push_line( &mut text, "adapter_low_rank_selection", "deterministic-cross-residual", ); push_line( &mut text, "adapter_low_rank_scope", "compatible-parent-matrix-tensors", ); push_line( &mut text, "adapter_low_rank_matrix_tensor_count", &stats.matrix_tensor_count.to_string(), ); push_line( &mut text, "adapter_low_rank_active_tensor_count", &stats.active_tensor_count.to_string(), ); push_line( &mut text, "adapter_low_rank_component_count", &stats.component_count.to_string(), ); push_line( &mut text, "adapter_low_rank_total_parameter_count", &stats.parameter_count.to_string(), ); push_line( &mut text, "adapter_low_rank_matrix_parameter_count", &stats.matrix_parameter_count.to_string(), ); push_line( &mut text, "adapter_low_rank_factor_parameter_count", &stats.factor_parameter_count.to_string(), ); push_line( &mut text, "adapter_low_rank_factor_density_ppm", &ratio_ppm(stats.factor_parameter_count, stats.matrix_parameter_count)?.to_string(), ); push_line( &mut text, "adapter_low_rank_initial_l1_microunits", &stats.initial_l1_microunits.to_string(), ); push_line( &mut text, "adapter_low_rank_residual_l1_microunits", &stats.residual_l1_microunits.to_string(), ); push_line( &mut text, "adapter_apply_status", low_rank_adapter_apply_status(base_report), ); push_line(&mut text, "required_next_gate", LOW_RANK_REQUIRED_NEXT_GATE); Ok(text) } fn adapter_apply_status(base_report: &ValidationReport) -> &'static str { if base_report.quantization_label() == "f32" { ADAPTER_APPLY_STATUS_F32 } else { ADAPTER_APPLY_STATUS_QUANTIZED } } /// Returns the runtime apply-status label for an ALR1 package over a base model. pub(crate) fn low_rank_adapter_apply_status(base_report: &ValidationReport) -> &'static str { if base_report.quantization_label() == "f32" { LOW_RANK_APPLY_STATUS_F32 } else { LOW_RANK_APPLY_STATUS_QUANTIZED } } /// Reads the stored ALR1 package checksum from the fixed header field. pub(crate) fn low_rank_adapter_checksum(adapter_bytes: &[u8]) -> io::Result { read_u64(adapter_bytes, CHECKSUM_OFFSET) } fn build_fuse_receipt_text( compatibility: &HashMap, lineage_fields: &HashMap, lineage_text: &str, base_path: &str, target_path: &str, base_report: &ValidationReport, target_report: &ValidationReport, adapter_path: &str, adapter_manifest_text: &str, adapter_bytes: &[u8], candidate_report: &ValidationReport, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_adapter_fuse_version", ADAPTER_FUSE_VERSION, ); push_line(&mut text, "operator_kind", FUSE_OPERATOR_KIND); push_line(&mut text, "operator_status", FUSE_OPERATOR_STATUS); push_line( &mut text, "candidate_id", require_key(lineage_fields, "candidate_id")?, ); push_line( &mut text, "operator_id", require_key(lineage_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(lineage_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(lineage_fields, "resource_budget")?, ); push_line( &mut text, "compatibility_report_checksum", require_key(lineage_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(compatibility, "compatibility_scope")?, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, compatibility, 0, base_path, base_report)?; push_parent_lines(&mut text, compatibility, 1, target_path, target_report)?; push_line(&mut text, "adapter_artifact_kind", ADAPTER_ARTIFACT_KIND); push_line(&mut text, "adapter_source_parent_index", "0"); push_line(&mut text, "adapter_target_parent_index", "1"); push_line(&mut text, "adapter_artifact_path", adapter_path); push_line( &mut text, "adapter_manifest_checksum", &hex64(lineage::text_checksum(adapter_manifest_text.as_bytes())), ); push_line( &mut text, "adapter_artifact_bytes", &adapter_bytes.len().to_string(), ); push_line( &mut text, "adapter_artifact_checksum", &hex64(read_u64(adapter_bytes, CHECKSUM_OFFSET)?), ); push_line( &mut text, "adapter_tensor_count", &base_report.tensor_count().to_string(), ); push_line( &mut text, "adapter_parameter_count", &base_report.parameter_count().to_string(), ); push_line(&mut text, "adapter_dtype", ADAPTER_DTYPE); push_line( &mut text, "adapter_model_shape", &base_report.shape_summary(), ); push_line( &mut text, "adapter_base_quantization", base_report.quantization_label(), ); push_line( &mut text, "adapter_output_contract", base_report.output_contract_label(), ); push_line( &mut text, "adapter_tokenizer_checksum", &hex64(base_report.tokenizer_checksum()), ); push_line( &mut text, "adapter_tensor_layout_checksum", &hex64(base_report.tensor_layout_checksum()), ); push_line(&mut text, "adapter_base_contract", ADAPTER_BASE_CONTRACT); push_line(&mut text, "adapter_manifest_status", FUSE_MANIFEST_STATUS); push_line(&mut text, "adapter_apply_status", FUSE_APPLY_STATUS); push_line( &mut text, "candidate_artifact_path", candidate_report.path(), ); push_line( &mut text, "candidate_artifact_bytes", &candidate_report.file_bytes().to_string(), ); push_line( &mut text, "candidate_slm_version", &candidate_report.slm_version().to_string(), ); push_line( &mut text, "candidate_slm_checksum", &hex64(candidate_report.checksum()), ); push_line( &mut text, "candidate_model_shape", &candidate_report.shape_summary(), ); push_line( &mut text, "candidate_tensor_count", &candidate_report.tensor_count().to_string(), ); push_line( &mut text, "candidate_parameter_count", &candidate_report.parameter_count().to_string(), ); push_line( &mut text, "candidate_quantization", candidate_report.quantization_label(), ); push_line( &mut text, "candidate_output_contract", candidate_report.output_contract_label(), ); push_line( &mut text, "candidate_tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), ); push_line( &mut text, "candidate_tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), ); push_line( &mut text, "candidate_parent_contract", ADAPTER_BASE_CONTRACT, ); push_line( &mut text, "operator_output_status", FUSE_OPERATOR_OUTPUT_STATUS, ); push_line(&mut text, "required_next_gate", FUSE_REQUIRED_NEXT_GATE); Ok(text) } fn read_adapter_deltas( bytes: &[u8], base: &ParsedModel, base_report: &ValidationReport, ) -> io::Result>> { validate_adapter_bytes(bytes)?; let tensor_count = read_u32(bytes, 12)? as usize; if tensor_count != base.tensors.len() { return Err(invalid( "adapter tensor count does not match base parent tensor count", )); } if read_u32(bytes, 16)? != base.flags { return Err(invalid( "adapter output flags do not match base parent output flags", )); } if read_u64(bytes, 24)? != base_report.parameter_count() as u64 { return Err(invalid( "adapter parameter count does not match base parent parameter count", )); } if read_u64(bytes, 32)? != base_report.tensor_layout_checksum() { return Err(invalid( "adapter tensor layout checksum does not match base parent", )); } if read_u64(bytes, 40)? != base_report.tokenizer_checksum() { return Err(invalid( "adapter tokenizer checksum does not match base parent", )); } let data_offset = read_u64(bytes, 48)? as usize; let mut output = Vec::with_capacity(tensor_count); for (index, tensor) in base.tensors.iter().enumerate() { let entry = HEADER_LEN + index * ENTRY_LEN; if read_u64(bytes, entry)? != tensor.spec.name_hash { return Err(invalid( "adapter tensor name hash does not match base parent", )); } if read_u32(bytes, entry + 8)? != tensor.spec.rank { return Err(invalid("adapter tensor rank does not match base parent")); } for dim_index in 0..4 { if read_u32(bytes, entry + 12 + dim_index * 4)? != tensor.spec.dims[dim_index] { return Err(invalid("adapter tensor dims do not match base parent")); } } if read_u32(bytes, entry + 28)? != 0 { return Err(invalid("adapter tensor reserved field is not zero")); } let byte_offset = read_u64(bytes, entry + 32)? as usize; if byte_offset < data_offset || byte_offset % 64 != 0 { return Err(invalid("adapter tensor payload offset is invalid")); } let byte_length = read_u64(bytes, entry + 40)? as usize; let element_count = read_u64(bytes, entry + 48)? as usize; if element_count != tensor.spec.element_count() { return Err(invalid( "adapter tensor element count does not match base parent", )); } let expected_byte_length = element_count .checked_mul(4) .ok_or_else(|| invalid("adapter tensor byte length overflow"))?; if byte_length != expected_byte_length { return Err(invalid( "adapter tensor byte length does not match element count", )); } let mut values = Vec::with_capacity(element_count); for value_index in 0..element_count { let value = read_f32(bytes, byte_offset + value_index * 4)?; if !value.is_finite() { return Err(invalid("adapter tensor delta is not finite")); } values.push(value); } output.push(values); } Ok(output) } fn fused_values(base: &ParsedModel, adapter_deltas: &[Vec]) -> io::Result>> { if adapter_deltas.len() != base.tensors.len() { return Err(invalid("adapter deltas do not match base tensor count")); } let mut output = Vec::with_capacity(base.tensors.len()); for (tensor, deltas) in base.tensors.iter().zip(adapter_deltas.iter()) { if tensor.values.len() != deltas.len() { return Err(invalid( "adapter delta tensor length does not match base tensor length", )); } let values = tensor .values .iter() .zip(deltas.iter()) .map(|(base_value, delta)| base_value + delta) .collect::>(); output.push(values); } Ok(output) } fn validate_parent_models(base: &ParsedModel, target: &ParsedModel) -> io::Result<()> { if !same_shape(&base.shape, &target.shape) { return Err(invalid("adapter parents have different model shapes")); } if base.flags != target.flags { return Err(invalid("adapter parents have different output flags")); } if base.tokenizer.bytes != target.tokenizer.bytes { return Err(invalid("adapter parents have different tokenizer bytes")); } if base.tensors.len() != target.tensors.len() { return Err(invalid("adapter parents have different tensor counts")); } Ok(()) } fn validate_adapter_bytes(bytes: &[u8]) -> io::Result<()> { if bytes.get(0..4) != Some(MAGIC) { return Err(invalid("adapter artifact has invalid magic")); } let version = read_u32(bytes, 4)?; if version != ADAPTER_BINARY_VERSION { return Err(invalid("adapter artifact has unsupported version")); } let header_len = read_u32(bytes, 8)? as usize; if header_len != HEADER_LEN { return Err(invalid("adapter artifact has invalid header length")); } let tensor_count = read_u32(bytes, 12)? as usize; let entry_len = read_u32(bytes, 20)? as usize; if entry_len != ENTRY_LEN { return Err(invalid("adapter artifact has invalid entry length")); } let data_offset = read_u64(bytes, 48)? as usize; let directory_end = HEADER_LEN .checked_add( tensor_count .checked_mul(ENTRY_LEN) .ok_or_else(|| invalid("adapter directory length overflow"))?, ) .ok_or_else(|| invalid("adapter directory end overflow"))?; if data_offset < directory_end || data_offset % 64 != 0 { return Err(invalid("adapter artifact has invalid data offset")); } if read_u64(bytes, CHECKSUM_OFFSET)? != adapter_checksum(bytes)? { return Err(invalid("adapter artifact checksum mismatch")); } for index in 0..tensor_count { let entry = HEADER_LEN + index * ENTRY_LEN; let byte_offset = read_u64(bytes, entry + 32)? as usize; let byte_length = read_u64(bytes, entry + 40)? as usize; let element_count = read_u64(bytes, entry + 48)? as usize; let expected_byte_length = element_count .checked_mul(4) .ok_or_else(|| invalid("adapter tensor byte length overflow"))?; if byte_length != expected_byte_length { return Err(invalid( "adapter tensor byte length does not match element count", )); } let end = byte_offset .checked_add(byte_length) .ok_or_else(|| invalid("adapter tensor payload end overflow"))?; let payload = bytes .get(byte_offset..end) .ok_or_else(|| invalid("adapter tensor payload escapes artifact"))?; if read_u64(bytes, entry + 56)? != payload_checksum(payload) { return Err(invalid("adapter tensor payload checksum mismatch")); } } Ok(()) } fn validate_sparse_adapter_bytes(bytes: &[u8]) -> io::Result<()> { if bytes.get(0..4) != Some(SPARSE_MAGIC) { return Err(invalid("sparse adapter artifact has invalid magic")); } let version = read_u32(bytes, 4)?; if version != ADAPTER_BINARY_VERSION { return Err(invalid("sparse adapter artifact has unsupported version")); } let header_len = read_u32(bytes, 8)? as usize; if header_len != HEADER_LEN { return Err(invalid("sparse adapter artifact has invalid header length")); } let tensor_count = read_u32(bytes, 12)? as usize; let entry_len = read_u32(bytes, 20)? as usize; if entry_len != ENTRY_LEN { return Err(invalid("sparse adapter artifact has invalid entry length")); } let data_offset = read_u64(bytes, 48)? as usize; let directory_end = HEADER_LEN .checked_add( tensor_count .checked_mul(ENTRY_LEN) .ok_or_else(|| invalid("sparse adapter directory length overflow"))?, ) .ok_or_else(|| invalid("sparse adapter directory end overflow"))?; if data_offset < directory_end || data_offset % 64 != 0 { return Err(invalid("sparse adapter artifact has invalid data offset")); } if read_u64(bytes, CHECKSUM_OFFSET)? != adapter_checksum(bytes)? { return Err(invalid("sparse adapter artifact checksum mismatch")); } for index in 0..tensor_count { let entry = HEADER_LEN + index * ENTRY_LEN; let byte_offset = read_u64(bytes, entry + 32)? as usize; let byte_length = read_u64(bytes, entry + 40)? as usize; let element_count = read_u64(bytes, entry + 48)? as usize; if byte_length % SPARSE_PAIR_LEN != 0 || byte_length / SPARSE_PAIR_LEN > element_count { return Err(invalid( "sparse adapter tensor byte length does not match sparse pairs", )); } let end = byte_offset .checked_add(byte_length) .ok_or_else(|| invalid("sparse adapter tensor payload end overflow"))?; let payload = bytes .get(byte_offset..end) .ok_or_else(|| invalid("sparse adapter tensor payload escapes artifact"))?; if read_u64(bytes, entry + 56)? != payload_checksum(payload) { return Err(invalid("sparse adapter tensor payload checksum mismatch")); } let mut previous_index = None; for pair_index in 0..byte_length / SPARSE_PAIR_LEN { let pair_offset = byte_offset + pair_index * SPARSE_PAIR_LEN; let value_index = read_u64(bytes, pair_offset)? as usize; if value_index >= element_count || previous_index.is_some_and(|previous| value_index <= previous) { return Err(invalid("sparse adapter tensor value index is invalid")); } let delta = read_f32(bytes, pair_offset + 8)?; if !delta.is_finite() { return Err(invalid("sparse adapter tensor delta is not finite")); } previous_index = Some(value_index); } } Ok(()) } /// Validates the standalone ALR1 binary structure and checksums. pub(crate) fn validate_low_rank_adapter_bytes(bytes: &[u8]) -> io::Result<()> { if bytes.get(0..4) != Some(LOW_RANK_MAGIC) { return Err(invalid("low-rank adapter artifact has invalid magic")); } let version = read_u32(bytes, 4)?; if version != ADAPTER_BINARY_VERSION { return Err(invalid("low-rank adapter artifact has unsupported version")); } let header_len = read_u32(bytes, 8)? as usize; if header_len != HEADER_LEN { return Err(invalid( "low-rank adapter artifact has invalid header length", )); } let tensor_count = read_u32(bytes, 12)? as usize; let entry_len = read_u32(bytes, 20)? as usize; if entry_len != ENTRY_LEN { return Err(invalid( "low-rank adapter artifact has invalid entry length", )); } let data_offset = read_u64(bytes, 48)? as usize; let directory_end = HEADER_LEN .checked_add( tensor_count .checked_mul(ENTRY_LEN) .ok_or_else(|| invalid("low-rank adapter directory length overflow"))?, ) .ok_or_else(|| invalid("low-rank adapter directory end overflow"))?; if data_offset < directory_end || data_offset % 64 != 0 { return Err(invalid("low-rank adapter artifact has invalid data offset")); } if read_u64(bytes, CHECKSUM_OFFSET)? != adapter_checksum(bytes)? { return Err(invalid("low-rank adapter artifact checksum mismatch")); } for index in 0..tensor_count { let entry = HEADER_LEN + index * ENTRY_LEN; let byte_offset = read_u64(bytes, entry + 32)? as usize; let byte_length = read_u64(bytes, entry + 40)? as usize; let element_count = read_u64(bytes, entry + 48)? as usize; let end = byte_offset .checked_add(byte_length) .ok_or_else(|| invalid("low-rank adapter tensor payload end overflow"))?; let payload = bytes .get(byte_offset..end) .ok_or_else(|| invalid("low-rank adapter tensor payload escapes artifact"))?; if read_u64(bytes, entry + 56)? != payload_checksum(payload) { return Err(invalid("low-rank adapter tensor payload checksum mismatch")); } validate_low_rank_payload(bytes, byte_offset, byte_length, element_count)?; } Ok(()) } fn validate_low_rank_payload( bytes: &[u8], byte_offset: usize, byte_length: usize, element_count: usize, ) -> io::Result<()> { if byte_length == 0 { return Ok(()); } if byte_length < LOW_RANK_HEADER_LEN { return Err(invalid("low-rank adapter payload is too short")); } let rows = read_u32(bytes, byte_offset)? as usize; let cols = read_u32(bytes, byte_offset + 4)? as usize; let factor_rank = read_u32(bytes, byte_offset + 8)? as usize; if read_u32(bytes, byte_offset + 12)? != 0 || rows == 0 || cols == 0 || factor_rank == 0 || factor_rank > MAX_LOW_RANK_COMPONENTS || factor_rank > rows.min(cols) || rows .checked_mul(cols) .ok_or_else(|| invalid("low-rank adapter shape overflow"))? != element_count { return Err(invalid("low-rank adapter payload shape is invalid")); } let factor_values = factor_rank .checked_mul( rows.checked_add(cols) .ok_or_else(|| invalid("low-rank adapter factor count overflow"))?, ) .ok_or_else(|| invalid("low-rank adapter factor count overflow"))?; let expected_byte_length = LOW_RANK_HEADER_LEN .checked_add( factor_values .checked_mul(4) .ok_or_else(|| invalid("low-rank adapter payload length overflow"))?, ) .ok_or_else(|| invalid("low-rank adapter payload length overflow"))?; if byte_length != expected_byte_length { return Err(invalid( "low-rank adapter tensor byte length does not match factors", )); } for value_index in 0..factor_values { let value = read_f32(bytes, byte_offset + LOW_RANK_HEADER_LEN + value_index * 4)?; if !value.is_finite() { return Err(invalid("low-rank adapter factor is not finite")); } } Ok(()) } fn adapter_checksum(bytes: &[u8]) -> io::Result { if bytes.len() < HEADER_LEN { return Err(invalid("adapter artifact is too short")); } let mut acc = 0x6164617074657231u64; for (index, byte) in bytes.iter().enumerate() { let value = if (CHECKSUM_OFFSET..CHECKSUM_OFFSET + 8).contains(&index) { 0 } else { *byte }; acc ^= u64::from(value).wrapping_add((index as u64) << 3); acc = acc.rotate_left(11).wrapping_mul(0x100000001b3); } Ok(acc) } fn payload_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x64656c7461663332u64; for (index, byte) in bytes.iter().enumerate() { acc ^= u64::from(*byte).wrapping_add((index as u64) << 1); acc = acc.rotate_left(7).wrapping_mul(0x100000001b3); } acc } fn compare_ranked_delta(left: &RankedDelta, right: &RankedDelta) -> Ordering { right .magnitude .partial_cmp(&left.magnitude) .unwrap_or(Ordering::Equal) .then_with(|| left.tensor_index.cmp(&right.tensor_index)) .then_with(|| left.value_index.cmp(&right.value_index)) } fn keep_count(total_parameter_count: u64, keep_ppm: u32) -> io::Result { if total_parameter_count == 0 || keep_ppm == 0 { return Ok(0); } let numerator = u128::from(total_parameter_count) * u128::from(keep_ppm) + u128::from(PPM_DENOMINATOR - 1); let count = numerator / u128::from(PPM_DENOMINATOR); u64::try_from(count).map_err(|_| invalid("sparse adapter keep count overflowed u64")) } fn ratio_ppm(numerator: u64, denominator: u64) -> io::Result { if denominator == 0 { return Ok(0); } let ppm = u128::from(numerator) * u128::from(PPM_DENOMINATOR) / u128::from(denominator); u64::try_from(ppm).map_err(|_| invalid("sparse adapter ratio overflowed u64")) } fn sparse_mask_checksum(selected: &[&RankedDelta], total_parameter_count: u64) -> u64 { let mut acc = 0x6173_7031_6d61_736bu64; mix_sparse_value(&mut acc, total_parameter_count); mix_sparse_value(&mut acc, selected.len() as u64); for entry in selected { mix_sparse_value(&mut acc, entry.tensor_index as u64); mix_sparse_value(&mut acc, entry.value_index as u64); } acc } fn mix_sparse_value(acc: &mut u64, value: u64) { *acc ^= value.wrapping_add(0x9e37_79b9_7f4a_7c15); *acc = acc.rotate_left(11).wrapping_mul(0x1000_0000_01b3); } fn low_rank_matrix_shape(spec: &crate::tensor_writer::TensorSpec) -> io::Result<(usize, usize)> { if spec.rank < 2 { return Err(invalid("low-rank adapter requires a matrix tensor")); } let rows = spec.dims[0] as usize; if rows == 0 { return Err(invalid("low-rank adapter matrix row count is zero")); } let mut cols = 1usize; for dim in spec.dims.iter().take(spec.rank as usize).skip(1) { if *dim == 0 { return Err(invalid("low-rank adapter matrix column dimension is zero")); } cols = cols .checked_mul(*dim as usize) .ok_or_else(|| invalid("low-rank adapter matrix column count overflow"))?; } Ok((rows, cols)) } fn low_rank_components( residual: &mut [f32], rows: usize, cols: usize, rank_limit: usize, ) -> io::Result> { let mut components = Vec::new(); for _ in 0..rank_limit { let mut pivot_index = None; let mut pivot_magnitude = 0.0f32; for (index, value) in residual.iter().enumerate() { if !value.is_finite() { return Err(invalid("low-rank adapter residual is not finite")); } let magnitude = value.abs(); if magnitude > pivot_magnitude { pivot_magnitude = magnitude; pivot_index = Some(index); } } let Some(pivot_index) = pivot_index else { break; }; if pivot_magnitude == 0.0 { break; } let pivot = residual[pivot_index]; let pivot_row = pivot_index / cols; let pivot_col = pivot_index % cols; let mut a = vec![0.0f32; rows]; let mut b = vec![0.0f32; cols]; for row in 0..rows { a[row] = residual[row * cols + pivot_col]; } for col in 0..cols { b[col] = residual[pivot_row * cols + col] / pivot; if !b[col].is_finite() { return Err(invalid("low-rank adapter factor is not finite")); } } for row in 0..rows { for col in 0..cols { let index = row * cols + col; residual[index] -= a[row] * b[col]; if !residual[index].is_finite() { return Err(invalid("low-rank adapter residual update is not finite")); } } } components.push(LowRankComponent { a, b }); } Ok(components) } fn l1_microunits(value: f64) -> io::Result { let scaled = (value * 1_000_000.0).round(); if !scaled.is_finite() || scaled < 0.0 || scaled > u64::MAX as f64 { return Err(invalid("low-rank adapter L1 value overflow")); } Ok(scaled as u64) } fn parse_low_rank_components(value: &str) -> io::Result { let rank = value .parse::() .map_err(|_| invalid("low-rank adapter component limit must be an integer"))?; if rank == 0 || rank > MAX_LOW_RANK_COMPONENTS { return Err(invalid("low-rank adapter component limit is out of range")); } Ok(rank) } fn parse_delta_weight_ppm(value: &str) -> io::Result { let weight = value .parse::() .map_err(|_| invalid("sparse adapter weight must be an integer parts-per-million value"))?; if !(MIN_DELTA_WEIGHT_PPM..=MAX_DELTA_WEIGHT_PPM).contains(&weight) { return Err(invalid( "sparse adapter weight must be between -1000000 and 2000000", )); } Ok(weight) } fn parse_keep_ppm(value: &str) -> io::Result { let keep = value .parse::() .map_err(|_| invalid("sparse adapter keep must be an integer parts-per-million value"))?; if keep > PPM_DENOMINATOR { return Err(invalid("sparse adapter keep must be between 0 and 1000000")); } Ok(keep) } struct RankedDelta { magnitude: f32, tensor_index: usize, value_index: usize, delta: f32, } #[derive(Clone, Copy)] struct SparseStats { total_parameter_count: u64, nonzero_delta_count: u64, kept_parameter_count: u64, pruned_parameter_count: u64, unchanged_parameter_count: u64, pruned_nonzero_delta_count: u64, density_ppm: u64, nonzero_delta_retention_ppm: u64, mask_checksum: u64, } struct LowRankComponent { a: Vec, b: Vec, } #[derive(Clone, Copy, Default)] struct LowRankStats { parameter_count: u64, matrix_tensor_count: u64, active_tensor_count: u64, component_count: u64, matrix_parameter_count: u64, factor_parameter_count: u64, initial_l1_microunits: u64, residual_l1_microunits: u64, } impl LowRankStats { fn add(&mut self, tensor: LowRankTensorStats) -> io::Result<()> { self.parameter_count = checked_add_low_rank(self.parameter_count, tensor.parameter_count)?; self.matrix_tensor_count = checked_add_low_rank(self.matrix_tensor_count, tensor.matrix_tensor_count)?; self.active_tensor_count = checked_add_low_rank(self.active_tensor_count, tensor.active_tensor_count)?; self.component_count = checked_add_low_rank(self.component_count, tensor.component_count)?; self.matrix_parameter_count = checked_add_low_rank(self.matrix_parameter_count, tensor.matrix_parameter_count)?; self.factor_parameter_count = checked_add_low_rank(self.factor_parameter_count, tensor.factor_parameter_count)?; self.initial_l1_microunits = checked_add_low_rank(self.initial_l1_microunits, tensor.initial_l1_microunits)?; self.residual_l1_microunits = checked_add_low_rank(self.residual_l1_microunits, tensor.residual_l1_microunits)?; Ok(()) } } #[derive(Clone, Copy, Default)] struct LowRankTensorStats { parameter_count: u64, matrix_tensor_count: u64, active_tensor_count: u64, component_count: u64, matrix_parameter_count: u64, factor_parameter_count: u64, initial_l1_microunits: u64, residual_l1_microunits: u64, } fn checked_add_low_rank(left: u64, right: u64) -> io::Result { left.checked_add(right) .ok_or_else(|| invalid("low-rank adapter statistic overflow")) } fn read_u32(bytes: &[u8], offset: usize) -> io::Result { let end = offset .checked_add(4) .ok_or_else(|| invalid("u32 offset overflow"))?; let slice = bytes .get(offset..end) .ok_or_else(|| invalid("unexpected end while reading u32"))?; Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) } fn read_u64(bytes: &[u8], offset: usize) -> io::Result { let end = offset .checked_add(8) .ok_or_else(|| invalid("u64 offset overflow"))?; let slice = bytes .get(offset..end) .ok_or_else(|| invalid("unexpected end while reading u64"))?; Ok(u64::from_le_bytes([ slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7], ])) } fn read_f32(bytes: &[u8], offset: usize) -> io::Result { let end = offset .checked_add(4) .ok_or_else(|| invalid("f32 offset overflow"))?; let slice = bytes .get(offset..end) .ok_or_else(|| invalid("unexpected end while reading f32"))?; Ok(f32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) } #[cfg(test)] mod tests { use super::*; use crate::compatibility; use crate::tensor_writer::{tiny_fixture_tensors, tiny_fixture_tensors_with_dtype, DTYPE_Q8_0}; use crate::tokenizer_writer::ByteTokenizerSection; use crate::{build_model_file, build_model_file_from_values_with_flags, fixture_value}; #[test] fn writes_and_validates_f32_adapter_delta_artifact() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "adapter-f32", "adapter-delta-v1", "tiny") .unwrap(); let (adapter, manifest) = build_artifact_bytes_and_manifest( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "adapter.delta", ) .unwrap(); validate_artifact_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.delta", &manifest, ) .unwrap(); assert_eq!(adapter.get(0..4), Some(&MAGIC[..])); assert!(manifest.contains("adapter_artifact_kind=raw-f32-task-delta-v1")); assert!(manifest.contains("adapter_apply_status=runtime-f32-compatible-or-fuse-to-slm")); } #[test] fn writes_and_validates_q8_adapter_delta_artifact() { let base = tiny_q8_bytes(); let target = tiny_q8_bytes(); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "adapter-q8", "adapter-delta-v1", "tiny") .unwrap(); let (adapter, manifest) = build_artifact_bytes_and_manifest( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "adapter.delta", ) .unwrap(); validate_adapter_bytes(&adapter).unwrap(); validate_artifact_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.delta", &manifest, ) .unwrap(); assert!(manifest.contains("adapter_base_quantization=q8_0")); assert!(manifest.contains("adapter_apply_status=runtime-q8-q4-compatible-or-fuse-to-slm")); } #[test] fn writes_and_validates_sparse_f32_adapter_delta_artifact() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text( &compatibility, "sparse-adapter-f32", "sparse-adapter-delta-v1", "tiny", ) .unwrap(); let (adapter, manifest) = build_sparse_artifact_bytes_and_manifest( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "adapter.asp1", Some("1000000"), Some("250000"), ) .unwrap(); let (raw_adapter, _) = build_artifact_bytes_and_manifest( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "adapter.adp1", ) .unwrap(); validate_sparse_artifact_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.asp1", &manifest, ) .unwrap(); assert_eq!(adapter.get(0..4), Some(&SPARSE_MAGIC[..])); assert!(adapter.len() < raw_adapter.len()); assert!(manifest.contains("adapter_artifact_kind=sparse-f32-task-delta-v1")); assert!(manifest.contains("adapter_sparse_keep_ppm=250000")); assert!(manifest.contains("adapter_sparse_pair_width_bytes=12")); assert!(manifest.contains("adapter_sparse_mask_checksum=")); } #[test] fn writes_and_validates_sparse_q8_adapter_delta_artifact() { let base = tiny_q8_bytes(); let target = tiny_q8_bytes(); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text( &compatibility, "sparse-adapter-q8", "sparse-adapter-delta-v1", "tiny", ) .unwrap(); let (adapter, manifest) = build_sparse_artifact_bytes_and_manifest( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "adapter.asp1", None, None, ) .unwrap(); validate_sparse_adapter_bytes(&adapter).unwrap(); validate_sparse_artifact_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.asp1", &manifest, ) .unwrap(); assert!(manifest.contains("adapter_base_quantization=q8_0")); assert!(manifest.contains("adapter_sparse_kept_parameter_count=0")); assert!(manifest.contains("adapter_apply_status=runtime-q8-q4-compatible-or-fuse-to-slm")); } #[test] fn writes_and_validates_low_rank_f32_adapter_delta_artifact() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text( &compatibility, "low-rank-adapter-f32", "low-rank-adapter-delta-v1", "tiny", ) .unwrap(); let (adapter, manifest) = build_low_rank_artifact_bytes_and_manifest( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "adapter.alr1", Some("1"), ) .unwrap(); validate_low_rank_artifact_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.alr1", &manifest, ) .unwrap(); assert_eq!(adapter.get(0..4), Some(&LOW_RANK_MAGIC[..])); assert!(manifest.contains("adapter_artifact_kind=low-rank-f32-task-delta-v1")); assert!(manifest.contains("adapter_low_rank_format=ALR1")); assert!(manifest.contains("adapter_low_rank_component_limit=1")); assert!(manifest.contains("adapter_apply_status=runtime-f32-compatible-low-rank")); } #[test] fn writes_and_validates_low_rank_q8_adapter_delta_artifact() { let base = tiny_q8_bytes(); let target = tiny_q8_bytes(); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text( &compatibility, "low-rank-adapter-q8", "low-rank-adapter-delta-v1", "tiny", ) .unwrap(); let (adapter, manifest) = build_low_rank_artifact_bytes_and_manifest( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "adapter.alr1", None, ) .unwrap(); validate_low_rank_adapter_bytes(&adapter).unwrap(); validate_low_rank_artifact_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.alr1", &manifest, ) .unwrap(); assert!(manifest.contains("adapter_base_quantization=q8_0")); assert!(manifest.contains("adapter_low_rank_component_count=0")); assert!(manifest.contains("adapter_apply_status=runtime-q8-q4-compatible-low-rank")); } #[test] fn fuses_f32_adapter_delta_into_slm_candidate() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "adapter-f32", "adapter-delta-v1", "tiny") .unwrap(); let (adapter, manifest) = build_artifact_bytes_and_manifest( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "adapter.delta", ) .unwrap(); let (candidate, receipt) = build_fused_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.delta", &manifest, "candidate.slm", ) .unwrap(); validate_fused_candidate_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.delta", &manifest, &candidate, "candidate.slm", &receipt, ) .unwrap(); assert!(receipt.contains("adapter_apply_status=fused-to-slm-candidate")); assert!( receipt.contains("required_next_gate=candidate-manifest-plus-runtime-smoke-plus-eval") ); let candidate_model = parse_model_values(&candidate).unwrap(); let target_model = parse_model_values(&target).unwrap(); for (candidate_tensor, target_tensor) in candidate_model .tensors .iter() .zip(target_model.tensors.iter()) { require_same_tensor_spec(&candidate_tensor.spec, &target_tensor.spec).unwrap(); for (candidate_value, target_value) in candidate_tensor .values .iter() .zip(target_tensor.values.iter()) { assert!((candidate_value - target_value).abs() < 0.000001); } } } #[test] fn fuses_q8_adapter_delta_into_slm_candidate() { let base = tiny_q8_bytes(); let target = tiny_q8_bytes(); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "adapter-q8", "adapter-delta-v1", "tiny") .unwrap(); let (adapter, manifest) = build_artifact_bytes_and_manifest( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "adapter.delta", ) .unwrap(); let (candidate, receipt) = build_fused_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.delta", &manifest, "candidate.slm", ) .unwrap(); slm_validate::validate_bytes(&candidate, "candidate.slm").unwrap(); validate_fused_candidate_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.delta", &manifest, &candidate, "candidate.slm", &receipt, ) .unwrap(); assert!(receipt.contains("candidate_quantization=q8_0")); } #[test] fn rejects_parent_checksum_drift() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "adapter-f32", "adapter-delta-v1", "tiny") .unwrap(); let changed_base = tiny_f32_scaled_bytes(2.0); let error = build_artifact_bytes_and_manifest( &compatibility, &lineage, &changed_base, "base.slm", &target, "target.slm", "adapter.delta", ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("parent.0.slm_checksum")); } #[test] fn validation_rejects_adapter_byte_drift() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "adapter-f32", "adapter-delta-v1", "tiny") .unwrap(); let (mut adapter, manifest) = build_artifact_bytes_and_manifest( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "adapter.delta", ) .unwrap(); let last = adapter.len() - 1; adapter[last] ^= 0x01; let error = validate_artifact_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.delta", &manifest, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("artifact bytes")); } #[test] fn validation_rejects_manifest_drift() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "adapter-f32", "adapter-delta-v1", "tiny") .unwrap(); let (adapter, manifest) = build_artifact_bytes_and_manifest( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "adapter.delta", ) .unwrap(); let changed_manifest = manifest.replace( "adapter_apply_status=runtime-f32-compatible-or-fuse-to-slm", "adapter_apply_status=fused", ); let error = validate_artifact_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.delta", &changed_manifest, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("manifest fields")); } #[test] fn fuse_rejects_adapter_manifest_drift() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "adapter-f32", "adapter-delta-v1", "tiny") .unwrap(); let (adapter, manifest) = build_artifact_bytes_and_manifest( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "adapter.delta", ) .unwrap(); let changed_manifest = manifest.replace( "adapter_apply_status=runtime-f32-compatible-or-fuse-to-slm", "adapter_apply_status=fused", ); let error = build_fused_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.delta", &changed_manifest, "candidate.slm", ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("manifest fields")); } #[test] fn validation_rejects_fused_candidate_drift() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "adapter-f32", "adapter-delta-v1", "tiny") .unwrap(); let (adapter, manifest) = build_artifact_bytes_and_manifest( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "adapter.delta", ) .unwrap(); let (mut candidate, receipt) = build_fused_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.delta", &manifest, "candidate.slm", ) .unwrap(); let last = candidate.len() - 1; candidate[last] ^= 0x01; let error = validate_fused_candidate_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &adapter, "adapter.delta", &manifest, &candidate, "candidate.slm", &receipt, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate bytes")); } fn tiny_f32_scaled_bytes(scale: f32) -> Vec { let tensors = tiny_fixture_tensors(); let values = tensors .iter() .map(|tensor| { (0..tensor.element_count()) .map(|index| fixture_value(tensor, index) * scale) .collect::>() }) .collect::>(); build_model_file_from_values_with_flags( &crate::tensor_writer::ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } fn tiny_q8_bytes() -> Vec { build_model_file( &crate::tensor_writer::ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), &ByteTokenizerSection::phase_one(), ) .unwrap() } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/adapter.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/adapter_family.rs BYTES: 42274 SHA256: 9A7AE9A7B9C5E1CAE1DBF3110D7A28F102CBC8A53615EE554431093727510618 ================================================================================ //! Browser-local adapter family receipts for ADP1/ASP1/ALR1 sidecars. use std::collections::{HashMap, HashSet}; use std::fs; use std::io; use std::path::Path; use crate::blend::{hex64, invalid, parse_manifest, push_line, require_equal, require_key}; use crate::provenance; use crate::selector::{self, RegistryAdapterFamilyRoute, RegistryAdapterRoute}; const ADAPTER_FAMILY_RECEIPT_VERSION: &str = "1"; const ADAPTER_FAMILY_KIND: &str = "browser-local-adapter-family"; const ADAPTER_FAMILY_STATUS: &str = "validated"; const ADAPTER_FAMILY_STRATEGY: &str = "single-adapter-selection"; const ADAPTER_AUTO_APPLY_STATUS: &str = "enabled"; const ADAPTER_AUTO_APPLY_STRATEGY: &str = "receipt-preferred-compatible"; const ADAPTER_AUTO_APPLY_STACK_STATUS: &str = "enabled"; const ADAPTER_AUTO_APPLY_STACK_STRATEGY: &str = "receipt-declared-compatible-stack"; const ADAPTER_AUTO_APPLY_BYTE_BUDGET: u64 = 1024 * 1024; const ADAPTER_ARTIFACT_VERSION: &str = "1"; const ADAPTER_ARTIFACT_KIND: &str = "raw-f32-task-delta-v1"; const SPARSE_ADAPTER_ARTIFACT_KIND: &str = "sparse-f32-task-delta-v1"; const LOW_RANK_ADAPTER_ARTIFACT_KIND: &str = "low-rank-f32-task-delta-v1"; const SOURCE_LOW_RANK_ADAPTER_ARTIFACT_KIND: &str = "trained-source-low-rank-f32-v1"; const ADAPTER_STATUS: &str = "artifact-written"; const ADAPTER_DTYPE: &str = "f32-delta"; const SPARSE_ADAPTER_DTYPE: &str = "sparse-f32-delta"; const LOW_RANK_ADAPTER_DTYPE: &str = "low-rank-f32-delta"; const SOURCE_LOW_RANK_ADAPTER_DTYPE: &str = "low-rank-f32-source-delta"; const SOURCE_LOW_RANK_ADAPTER_SOURCE_MANIFEST: &str = "adapter-source.manifest"; const SOURCE_LOW_RANK_ADAPTER_SOURCE_LAYOUT: &str = "low-rank-f32-factor-files-v1"; const SOURCE_LOW_RANK_ADAPTER_SOURCE_FORMAT: &str = "trained-low-rank-factors-v1"; const SOURCE_LOW_RANK_ADAPTER_BASE_CONTRACT: &str = "matches-parent-direct-parameter-contract"; const SOURCE_LOW_RANK_ADAPTER_SOURCE_BASE_CONTRACT: &str = "matches-reviewed-adapter-source-base-contract"; const ADAPTER_APPLY_STATUS_F32: &str = "runtime-f32-compatible-or-fuse-to-slm"; const ADAPTER_APPLY_STATUS_QUANTIZED: &str = "runtime-q8-q4-compatible-or-fuse-to-slm"; const LOW_RANK_APPLY_STATUS_F32: &str = "runtime-f32-compatible-low-rank"; const LOW_RANK_APPLY_STATUS_QUANTIZED: &str = "runtime-q8-q4-compatible-low-rank"; const REQUIRED_NEXT_GATE: &str = "browser-loads-selector-registry-adapter-family"; const SHARED_IDENTITY_KEYS: &[&str] = &[ "adapter_tensor_count", "adapter_parameter_count", "adapter_model_shape", "adapter_base_quantization", "adapter_output_contract", "adapter_tokenizer_checksum", "adapter_tensor_layout_checksum", "adapter_base_contract", ]; const SOURCE_BACKED_RECEIPT_FIELDS: &[(&str, &str)] = &[ ("adapter_source_manifest", "source_manifest"), ( "adapter_source_manifest_checksum", "source_manifest_checksum", ), ("adapter_source_layout", "source_layout"), ("adapter_source_format", "source_format"), ("adapter_source_base_contract", "source_base_contract"), ]; /// One adapter manifest and its registry route for a family receipt. pub(crate) struct AdapterFamilyInput<'a> { /// The browser selector route for this adapter. pub(crate) route: &'a RegistryAdapterRoute, /// Local manifest path that proves the adapter route fields. pub(crate) manifest_path: &'a Path, } struct AdapterFamilyMember<'a> { route: &'a RegistryAdapterRoute, manifest_text: String, fields: HashMap, } /// Writes a deterministic adapter-family receipt and returns its registry route. pub(crate) fn write_receipt_path( candidate_id: &str, label: &str, receipt_route_path: &str, output_receipt: &Path, inputs: &[AdapterFamilyInput<'_>], ) -> io::Result { let receipt = build_receipt_text(candidate_id, label, receipt_route_path, inputs)?; if let Some(parent) = output_receipt.parent() { fs::create_dir_all(parent)?; } fs::write(output_receipt, &receipt)?; let route = RegistryAdapterFamilyRoute { candidate_id: candidate_id.to_string(), receipt_path: receipt_route_path.to_string(), label: label.to_string(), status: "receipt-validated".to_string(), strategy: ADAPTER_FAMILY_STRATEGY.to_string(), receipt_checksum: hex64(provenance::text_checksum(receipt.as_bytes())), adapter_count: inputs.len(), auto_apply_status: ADAPTER_AUTO_APPLY_STATUS.to_string(), auto_apply_strategy: ADAPTER_AUTO_APPLY_STRATEGY.to_string(), auto_apply_stack_status: ADAPTER_AUTO_APPLY_STACK_STATUS.to_string(), auto_apply_stack_strategy: ADAPTER_AUTO_APPLY_STACK_STRATEGY.to_string(), auto_apply_stack_count: auto_apply_stack_indexes(inputs.len()).len(), auto_apply_byte_budget: ADAPTER_AUTO_APPLY_BYTE_BUDGET, }; selector::validate_registry_adapter_family_route(&route)?; println!( "SLM adapter-family receipt written: {}", output_receipt.display() ); Ok(route) } /// Validates a receipt by recomputing it from its adapter manifests. pub(crate) fn validate_receipt_path( receipt: &Path, inputs: &[AdapterFamilyInput<'_>], ) -> io::Result<()> { let receipt_text = fs::read_to_string(receipt)?; validate_receipt_text(&receipt_text, inputs)?; println!("SLM adapter-family receipt validation: PASS"); println!("receipt: {}", receipt.display()); Ok(()) } fn validate_receipt_text(receipt_text: &str, inputs: &[AdapterFamilyInput<'_>]) -> io::Result<()> { let receipt = parse_manifest(receipt_text, "adapter-family receipt")?; require_equal( &receipt, "tinyrustlm_adapter_family_receipt_version", ADAPTER_FAMILY_RECEIPT_VERSION, )?; require_equal(&receipt, "adapter_family_kind", ADAPTER_FAMILY_KIND)?; require_equal(&receipt, "adapter_family_status", ADAPTER_FAMILY_STATUS)?; require_equal(&receipt, "adapter_family_strategy", ADAPTER_FAMILY_STRATEGY)?; let candidate_id = require_key(&receipt, "candidate_id")?; let label = require_key(&receipt, "adapter_family_label")?; let receipt_route_path = require_key(&receipt, "adapter_family_receipt_path")?; let expected = build_receipt_text(candidate_id, label, receipt_route_path, inputs)?; if receipt_text != expected { return Err(invalid( "adapter-family receipt fields do not match recomputed manifests", )); } Ok(()) } fn build_receipt_text( candidate_id: &str, label: &str, receipt_route_path: &str, inputs: &[AdapterFamilyInput<'_>], ) -> io::Result { validate_candidate_id(candidate_id)?; validate_label(label, "adapter family label")?; validate_receipt_route_path(receipt_route_path)?; let members = collect_members(candidate_id, inputs)?; let first = members .first() .ok_or_else(|| invalid("adapter family requires at least two members"))?; let mut text = String::new(); push_line( &mut text, "tinyrustlm_adapter_family_receipt_version", ADAPTER_FAMILY_RECEIPT_VERSION, ); push_line(&mut text, "adapter_family_kind", ADAPTER_FAMILY_KIND); push_line(&mut text, "adapter_family_status", ADAPTER_FAMILY_STATUS); push_line(&mut text, "candidate_id", candidate_id); push_line(&mut text, "adapter_family_label", label); push_line(&mut text, "adapter_family_receipt_path", receipt_route_path); push_line( &mut text, "adapter_family_strategy", ADAPTER_FAMILY_STRATEGY, ); push_line(&mut text, "adapter_count", &members.len().to_string()); let preferred_index = preferred_member_index(&members); let preferred = &members[preferred_index]; let auto_apply_indexes = auto_apply_stack_indexes(members.len()); push_line( &mut text, "adapter_family_preferred_adapter_index", &preferred_index.to_string(), ); push_line( &mut text, "adapter_family_preferred_adapter_path", preferred.route.adapter_path.as_str(), ); push_line( &mut text, "adapter_family_preferred_manifest_path", preferred.route.manifest_path.as_str(), ); push_line( &mut text, "adapter_family_auto_apply_stack_status", ADAPTER_AUTO_APPLY_STACK_STATUS, ); push_line( &mut text, "adapter_family_auto_apply_stack_strategy", ADAPTER_AUTO_APPLY_STACK_STRATEGY, ); push_line( &mut text, "adapter_family_auto_apply_stack_count", &auto_apply_indexes.len().to_string(), ); for (stack_index, adapter_index) in auto_apply_indexes.iter().enumerate() { let member = &members[*adapter_index]; let prefix = format!("adapter_family_auto_apply_stack.{stack_index}"); push_line( &mut text, &format!("{prefix}.adapter_index"), &adapter_index.to_string(), ); push_line( &mut text, &format!("{prefix}.adapter_path"), member.route.adapter_path.as_str(), ); push_line( &mut text, &format!("{prefix}.manifest_path"), member.route.manifest_path.as_str(), ); } for key in SHARED_IDENTITY_KEYS { push_line( &mut text, &format!("family.{key}"), require_key(&first.fields, key)?, ); } for (index, member) in members.iter().enumerate() { push_member_lines(&mut text, index, member)?; } push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } fn collect_members<'a>( candidate_id: &str, inputs: &'a [AdapterFamilyInput<'a>], ) -> io::Result>> { if inputs.len() < 2 || inputs.len() > 16 { return Err(invalid("adapter family member count must be 2 through 16")); } let mut seen_adapter_paths = HashSet::new(); let mut seen_manifest_paths = HashSet::new(); let mut members = Vec::with_capacity(inputs.len()); for input in inputs { selector::validate_registry_adapter_route(input.route)?; if input.route.candidate_id != candidate_id { return Err(invalid( "adapter family route candidate_id must match the receipt candidate_id", )); } if !seen_adapter_paths.insert(input.route.adapter_path.as_str()) { return Err(invalid("duplicate adapter family adapter path")); } if !seen_manifest_paths.insert(input.route.manifest_path.as_str()) { return Err(invalid("duplicate adapter family manifest path")); } let manifest_text = fs::read_to_string(input.manifest_path)?; let fields = parse_manifest(&manifest_text, "adapter family member manifest")?; validate_member_manifest(input.route, &manifest_text, &fields)?; members.push(AdapterFamilyMember { route: input.route, manifest_text, fields, }); } validate_shared_identity(&members)?; Ok(members) } fn validate_member_manifest( route: &RegistryAdapterRoute, manifest_text: &str, fields: &HashMap, ) -> io::Result<()> { require_equal( fields, "tinyrustlm_adapter_artifact_version", ADAPTER_ARTIFACT_VERSION, )?; let format = adapter_format_for_route(&route.adapter_path)?; let artifact_kind = validate_kind_dtype_pair(fields, &format)?; require_equal(fields, "adapter_status", ADAPTER_STATUS)?; if artifact_kind == SOURCE_LOW_RANK_ADAPTER_ARTIFACT_KIND { validate_source_backed_low_rank_manifest(fields)?; } let base_quantization = require_key(fields, "adapter_base_quantization")?; validate_apply_status_for_quantization(&format, &route.apply_status, &base_quantization)?; require_equal(fields, "adapter_apply_status", &route.apply_status)?; require_equal( fields, "adapter_artifact_checksum", &route.artifact_checksum, )?; let manifest_checksum = hex64(provenance::text_checksum(manifest_text.as_bytes())); if route.manifest_checksum != manifest_checksum { return Err(invalid( "adapter family route manifest checksum does not match manifest text", )); } for key in SHARED_IDENTITY_KEYS { require_key(fields, key)?; } Ok(()) } struct AdapterManifestFormat { kind_dtype_pairs: &'static [(&'static str, &'static str)], apply_status_f32: &'static str, apply_status_quantized: &'static str, } fn adapter_format_for_route(adapter_path: &str) -> io::Result { if adapter_path.ends_with(".adp1") { return Ok(AdapterManifestFormat { kind_dtype_pairs: &[(ADAPTER_ARTIFACT_KIND, ADAPTER_DTYPE)], apply_status_f32: ADAPTER_APPLY_STATUS_F32, apply_status_quantized: ADAPTER_APPLY_STATUS_QUANTIZED, }); } if adapter_path.ends_with(".asp1") { return Ok(AdapterManifestFormat { kind_dtype_pairs: &[(SPARSE_ADAPTER_ARTIFACT_KIND, SPARSE_ADAPTER_DTYPE)], apply_status_f32: ADAPTER_APPLY_STATUS_F32, apply_status_quantized: ADAPTER_APPLY_STATUS_QUANTIZED, }); } if adapter_path.ends_with(".alr1") { return Ok(AdapterManifestFormat { kind_dtype_pairs: &[ (LOW_RANK_ADAPTER_ARTIFACT_KIND, LOW_RANK_ADAPTER_DTYPE), ( SOURCE_LOW_RANK_ADAPTER_ARTIFACT_KIND, SOURCE_LOW_RANK_ADAPTER_DTYPE, ), ], apply_status_f32: LOW_RANK_APPLY_STATUS_F32, apply_status_quantized: LOW_RANK_APPLY_STATUS_QUANTIZED, }); } Err(invalid("adapter family member route format is invalid")) } fn validate_apply_status_for_quantization( format: &AdapterManifestFormat, status: &str, quantization: &str, ) -> io::Result<()> { let expected = match quantization { "f32" => format.apply_status_f32, "q8_0" | "q4_0" => format.apply_status_quantized, _ => return Err(invalid("adapter family base quantization is invalid")), }; if status != expected { return Err(invalid( "adapter family apply status does not match base quantization", )); } Ok(()) } /// Validates that an adapter manifest uses one route-allowed kind/dtype pair. fn validate_kind_dtype_pair<'a>( fields: &'a HashMap, format: &AdapterManifestFormat, ) -> io::Result<&'a str> { let artifact_kind = require_key(fields, "adapter_artifact_kind")?; let dtype = require_key(fields, "adapter_dtype")?; if !format .kind_dtype_pairs .iter() .any(|(kind, accepted_dtype)| artifact_kind == *kind && dtype == *accepted_dtype) { return Err(invalid("adapter family member kind/dtype pair is invalid")); } Ok(artifact_kind) } /// Requires source-backed ALR1 manifests to carry reviewed-source provenance fields. fn validate_source_backed_low_rank_manifest(fields: &HashMap) -> io::Result<()> { require_equal( fields, "adapter_base_contract", SOURCE_LOW_RANK_ADAPTER_BASE_CONTRACT, )?; require_equal( fields, "adapter_source_manifest", SOURCE_LOW_RANK_ADAPTER_SOURCE_MANIFEST, )?; require_hex64_field(fields, "adapter_source_manifest_checksum")?; require_equal( fields, "adapter_source_layout", SOURCE_LOW_RANK_ADAPTER_SOURCE_LAYOUT, )?; require_equal( fields, "adapter_source_format", SOURCE_LOW_RANK_ADAPTER_SOURCE_FORMAT, )?; require_equal( fields, "adapter_source_base_contract", SOURCE_LOW_RANK_ADAPTER_SOURCE_BASE_CONTRACT, )?; Ok(()) } /// Reads a manifest field that must be a 64-bit hexadecimal checksum. fn require_hex64_field(fields: &HashMap, key: &str) -> io::Result<()> { let value = require_key(fields, key)?; let is_hex = value.len() == 18 && value.starts_with("0x") && value[2..].bytes().all(|byte| byte.is_ascii_hexdigit()); if !is_hex { return Err(invalid(&format!( "manifest key {key} must be a hex64 value" ))); } Ok(()) } fn validate_shared_identity(members: &[AdapterFamilyMember<'_>]) -> io::Result<()> { let first = members .first() .ok_or_else(|| invalid("adapter family requires at least two members"))?; for member in members.iter().skip(1) { for key in SHARED_IDENTITY_KEYS { if require_key(&member.fields, key)? != require_key(&first.fields, key)? { return Err(invalid(&format!( "adapter family members must share one {key}" ))); } } } Ok(()) } fn preferred_member_index(members: &[AdapterFamilyMember<'_>]) -> usize { members .iter() .position(|member| member.route.adapter_path.ends_with(".asp1")) .unwrap_or(0) } fn auto_apply_stack_indexes(member_count: usize) -> Vec { if member_count >= 3 { (1..member_count).collect() } else { (0..member_count).collect() } } fn push_member_lines( text: &mut String, index: usize, member: &AdapterFamilyMember<'_>, ) -> io::Result<()> { let prefix = format!("adapter.{index}"); push_line( text, &format!("{prefix}.path"), member.route.adapter_path.as_str(), ); push_line( text, &format!("{prefix}.manifest_path"), member.route.manifest_path.as_str(), ); push_line( text, &format!("{prefix}.label"), member.route.label.as_str(), ); push_line( text, &format!("{prefix}.apply_status"), member.route.apply_status.as_str(), ); push_line( text, &format!("{prefix}.artifact_checksum"), member.route.artifact_checksum.as_str(), ); push_line( text, &format!("{prefix}.manifest_checksum"), member.route.manifest_checksum.as_str(), ); push_line( text, &format!("{prefix}.manifest_bytes"), &member.manifest_text.len().to_string(), ); push_line( text, &format!("{prefix}.kind"), require_key(&member.fields, "adapter_artifact_kind")?, ); push_line( text, &format!("{prefix}.dtype"), require_key(&member.fields, "adapter_dtype")?, ); push_source_backed_member_lines(text, &prefix, member)?; for key in SHARED_IDENTITY_KEYS { push_line( text, &format!("{prefix}.{key}"), require_key(&member.fields, key)?, ); } Ok(()) } /// Echoes source-backed ALR1 provenance fields into the family receipt. fn push_source_backed_member_lines( text: &mut String, prefix: &str, member: &AdapterFamilyMember<'_>, ) -> io::Result<()> { if require_key(&member.fields, "adapter_artifact_kind")? != SOURCE_LOW_RANK_ADAPTER_ARTIFACT_KIND { return Ok(()); } for (manifest_key, receipt_key) in SOURCE_BACKED_RECEIPT_FIELDS { push_line( text, &format!("{prefix}.{receipt_key}"), require_key(&member.fields, manifest_key)?, ); } Ok(()) } fn validate_candidate_id(candidate_id: &str) -> io::Result<()> { if candidate_id.is_empty() || candidate_id.len() > 160 || !candidate_id .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')) { return Err(invalid("adapter family candidate_id is invalid")); } Ok(()) } fn validate_label(label: &str, label_name: &str) -> io::Result<()> { if label.trim().is_empty() || label.contains('\r') || label.contains('\n') || label.len() > 160 { return Err(invalid(&format!("{label_name} is invalid"))); } Ok(()) } fn validate_receipt_route_path(path: &str) -> io::Result<()> { let normalized = path.replace('\\', "/"); let Some(rest) = normalized.strip_prefix("../models/") else { return Err(invalid( "adapter family receipt route must point at served ../models receipt artifacts", )); }; if rest.is_empty() || !rest.ends_with(".adapter-family.receipt") || rest.contains(':') || rest.contains('\\') || rest.contains("//") { return Err(invalid("adapter family receipt route is invalid")); } for part in rest.split('/') { if part.is_empty() || part == "." || part == ".." { return Err(invalid("adapter family receipt route is invalid")); } } Ok(()) } #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; #[test] fn writes_and_validates_adapter_family_receipt() { let dir = unique_dir("family"); fs::create_dir_all(&dir).unwrap(); let first_manifest = member_manifest("0x00000000000000aa", "0x00000000000000f1"); let second_manifest = sparse_member_manifest("0x00000000000000bb", "0x00000000000000f1"); let first_manifest_path = dir.join("first.adp1.manifest"); let second_manifest_path = dir.join("second.asp1.manifest"); fs::write(&first_manifest_path, &first_manifest).unwrap(); fs::write(&second_manifest_path, &second_manifest).unwrap(); let first = route( "../models/first.adp1", "First ADP1", "0x00000000000000aa", &first_manifest, ); let second = route( "../models/second.asp1", "Second ASP1", "0x00000000000000bb", &second_manifest, ); let inputs = [ AdapterFamilyInput { route: &first, manifest_path: &first_manifest_path, }, AdapterFamilyInput { route: &second, manifest_path: &second_manifest_path, }, ]; let receipt_path = dir.join("candidate.adapter-family.receipt"); let receipt_route = write_receipt_path( "candidate-a", "Candidate ADP1 family", "../models/candidate.adapter-family.receipt", &receipt_path, &inputs, ) .unwrap(); validate_receipt_path(&receipt_path, &inputs).unwrap(); let receipt = fs::read_to_string(&receipt_path).unwrap(); assert!(receipt.contains("adapter_family_kind=browser-local-adapter-family")); assert!(receipt.contains("adapter_family_preferred_adapter_index=1")); assert!(receipt.contains("adapter_family_preferred_adapter_path=../models/second.asp1")); assert!(receipt .contains("adapter_family_preferred_manifest_path=../models/second.asp1.manifest")); assert!(receipt.contains("adapter_family_auto_apply_stack_status=enabled")); assert!(receipt.contains( "adapter_family_auto_apply_stack_strategy=receipt-declared-compatible-stack" )); assert!(receipt.contains("adapter_family_auto_apply_stack_count=2")); assert!(receipt.contains("adapter_family_auto_apply_stack.0.adapter_index=0")); assert!( receipt.contains("adapter_family_auto_apply_stack.0.adapter_path=../models/first.adp1") ); assert!(receipt.contains("adapter_family_auto_apply_stack.1.adapter_index=1")); assert!(receipt .contains("adapter_family_auto_apply_stack.1.adapter_path=../models/second.asp1")); assert!(receipt.contains("adapter.1.path=../models/second.asp1")); assert!(receipt.contains("family.adapter_tensor_layout_checksum=0x00000000000000f1")); assert_eq!(receipt_route.adapter_count, 2); assert_eq!(receipt_route.auto_apply_stack_count, 2); assert_eq!(receipt_route.status, "receipt-validated"); fs::remove_dir_all(dir).unwrap(); } #[test] fn writes_and_validates_quantized_adapter_family_receipt() { let dir = unique_dir("quantized-family"); fs::create_dir_all(&dir).unwrap(); let first_manifest = member_manifest_with_quantization( "0x00000000000000aa", "0x00000000000000f1", "q8_0", ADAPTER_APPLY_STATUS_QUANTIZED, ); let second_manifest = member_manifest_with_quantization( "0x00000000000000bb", "0x00000000000000f1", "q8_0", ADAPTER_APPLY_STATUS_QUANTIZED, ); let first_manifest_path = dir.join("first-q8.adp1.manifest"); let second_manifest_path = dir.join("second-q8.adp1.manifest"); fs::write(&first_manifest_path, &first_manifest).unwrap(); fs::write(&second_manifest_path, &second_manifest).unwrap(); let first = route_with_apply_status( "../models/first-q8.adp1", "First q8 ADP1", "0x00000000000000aa", &first_manifest, ADAPTER_APPLY_STATUS_QUANTIZED, ); let second = route_with_apply_status( "../models/second-q8.adp1", "Second q8 ADP1", "0x00000000000000bb", &second_manifest, ADAPTER_APPLY_STATUS_QUANTIZED, ); let inputs = [ AdapterFamilyInput { route: &first, manifest_path: &first_manifest_path, }, AdapterFamilyInput { route: &second, manifest_path: &second_manifest_path, }, ]; let receipt_path = dir.join("candidate-q8.adapter-family.receipt"); write_receipt_path( "candidate-a", "Candidate q8 ADP1 family", "../models/candidate-q8.adapter-family.receipt", &receipt_path, &inputs, ) .unwrap(); validate_receipt_path(&receipt_path, &inputs).unwrap(); let receipt = fs::read_to_string(&receipt_path).unwrap(); assert!(receipt.contains("family.adapter_base_quantization=q8_0")); assert!(receipt.contains("adapter_family_preferred_adapter_index=0")); assert!(receipt.contains("adapter_family_auto_apply_stack_count=2")); assert!(receipt.contains("adapter.1.apply_status=runtime-q8-q4-compatible-or-fuse-to-slm")); fs::remove_dir_all(dir).unwrap(); } #[test] fn writes_and_validates_low_rank_adapter_family_member() { let dir = unique_dir("low-rank-family"); fs::create_dir_all(&dir).unwrap(); let first_manifest = member_manifest("0x00000000000000aa", "0x00000000000000f1"); let second_manifest = member_manifest_with_format( "0x00000000000000bb", "0x00000000000000f1", "f32", LOW_RANK_APPLY_STATUS_F32, LOW_RANK_ADAPTER_ARTIFACT_KIND, LOW_RANK_ADAPTER_DTYPE, ); let first_manifest_path = dir.join("first.adp1.manifest"); let second_manifest_path = dir.join("second.alr1.manifest"); fs::write(&first_manifest_path, &first_manifest).unwrap(); fs::write(&second_manifest_path, &second_manifest).unwrap(); let first = route( "../models/first.adp1", "First ADP1", "0x00000000000000aa", &first_manifest, ); let second = route_with_apply_status( "../models/second.alr1", "Second ALR1", "0x00000000000000bb", &second_manifest, LOW_RANK_APPLY_STATUS_F32, ); let inputs = [ AdapterFamilyInput { route: &first, manifest_path: &first_manifest_path, }, AdapterFamilyInput { route: &second, manifest_path: &second_manifest_path, }, ]; let receipt_path = dir.join("candidate-low-rank.adapter-family.receipt"); write_receipt_path( "candidate-a", "Candidate ALR1 family", "../models/candidate-low-rank.adapter-family.receipt", &receipt_path, &inputs, ) .unwrap(); validate_receipt_path(&receipt_path, &inputs).unwrap(); let receipt = fs::read_to_string(&receipt_path).unwrap(); assert!(receipt.contains("adapter.1.path=../models/second.alr1")); assert!(receipt.contains("adapter.1.apply_status=runtime-f32-compatible-low-rank")); fs::remove_dir_all(dir).unwrap(); } #[test] fn writes_and_validates_source_backed_low_rank_adapter_family_member() { let dir = unique_dir("source-low-rank-family"); fs::create_dir_all(&dir).unwrap(); let first_manifest = member_manifest("0x00000000000000aa", "0x00000000000000f1"); let second_manifest = source_low_rank_member_manifest( "0x00000000000000bc", "0x00000000000000f1", "f32", LOW_RANK_APPLY_STATUS_F32, ); let first_manifest_path = dir.join("first.adp1.manifest"); let second_manifest_path = dir.join("source.alr1.manifest"); fs::write(&first_manifest_path, &first_manifest).unwrap(); fs::write(&second_manifest_path, &second_manifest).unwrap(); let first = route( "../models/first.adp1", "First ADP1", "0x00000000000000aa", &first_manifest, ); let second = route_with_apply_status( "../models/source.alr1", "Source ALR1", "0x00000000000000bc", &second_manifest, LOW_RANK_APPLY_STATUS_F32, ); let inputs = [ AdapterFamilyInput { route: &first, manifest_path: &first_manifest_path, }, AdapterFamilyInput { route: &second, manifest_path: &second_manifest_path, }, ]; let receipt_path = dir.join("candidate-source-low-rank.adapter-family.receipt"); write_receipt_path( "candidate-a", "Candidate source ALR1 family", "../models/candidate-source-low-rank.adapter-family.receipt", &receipt_path, &inputs, ) .unwrap(); validate_receipt_path(&receipt_path, &inputs).unwrap(); let receipt = fs::read_to_string(&receipt_path).unwrap(); assert!(receipt.contains("adapter.1.path=../models/source.alr1")); assert!(receipt.contains("adapter.1.kind=trained-source-low-rank-f32-v1")); assert!(receipt.contains("adapter.1.dtype=low-rank-f32-source-delta")); assert!(receipt.contains("adapter.1.source_manifest=adapter-source.manifest")); assert!(receipt.contains("adapter.1.source_manifest_checksum=0x00000000000000d1")); assert!(receipt.contains("adapter.1.source_layout=low-rank-f32-factor-files-v1")); assert!(receipt.contains("adapter.1.source_format=trained-low-rank-factors-v1")); assert!(receipt.contains( "adapter.1.source_base_contract=matches-reviewed-adapter-source-base-contract" )); fs::remove_dir_all(dir).unwrap(); } #[test] fn rejects_source_backed_low_rank_member_with_dtype_pair_drift() { // Exercises the ALR1 kind/dtype pair gate with a source-backed kind and plain dtype. let dir = unique_dir("source-low-rank-dtype-drift"); fs::create_dir_all(&dir).unwrap(); let first_manifest = member_manifest("0x00000000000000aa", "0x00000000000000f1"); let second_manifest = source_low_rank_member_manifest( "0x00000000000000bc", "0x00000000000000f1", "f32", LOW_RANK_APPLY_STATUS_F32, ) .replace( "adapter_dtype=low-rank-f32-source-delta", "adapter_dtype=low-rank-f32-delta", ); let first_manifest_path = dir.join("first.adp1.manifest"); let second_manifest_path = dir.join("source.alr1.manifest"); fs::write(&first_manifest_path, &first_manifest).unwrap(); fs::write(&second_manifest_path, &second_manifest).unwrap(); let first = route( "../models/first.adp1", "First ADP1", "0x00000000000000aa", &first_manifest, ); let second = route_with_apply_status( "../models/source.alr1", "Source ALR1", "0x00000000000000bc", &second_manifest, LOW_RANK_APPLY_STATUS_F32, ); let inputs = [ AdapterFamilyInput { route: &first, manifest_path: &first_manifest_path, }, AdapterFamilyInput { route: &second, manifest_path: &second_manifest_path, }, ]; let error = build_receipt_text( "candidate-a", "Candidate source ALR1 family", "../models/candidate-source-low-rank.adapter-family.receipt", &inputs, ) .unwrap_err(); assert!(error.to_string().contains("kind/dtype pair")); fs::remove_dir_all(dir).unwrap(); } #[test] fn rejects_source_backed_low_rank_member_with_source_checksum_drift() { // Exercises the source manifest checksum gate before receipt lines are emitted. let dir = unique_dir("source-low-rank-source-checksum-drift"); fs::create_dir_all(&dir).unwrap(); let first_manifest = member_manifest("0x00000000000000aa", "0x00000000000000f1"); let second_manifest = source_low_rank_member_manifest( "0x00000000000000bc", "0x00000000000000f1", "f32", LOW_RANK_APPLY_STATUS_F32, ) .replace( "adapter_source_manifest_checksum=0x00000000000000d1", "adapter_source_manifest_checksum=source-drift", ); let first_manifest_path = dir.join("first.adp1.manifest"); let second_manifest_path = dir.join("source.alr1.manifest"); fs::write(&first_manifest_path, &first_manifest).unwrap(); fs::write(&second_manifest_path, &second_manifest).unwrap(); let first = route( "../models/first.adp1", "First ADP1", "0x00000000000000aa", &first_manifest, ); let second = route_with_apply_status( "../models/source.alr1", "Source ALR1", "0x00000000000000bc", &second_manifest, LOW_RANK_APPLY_STATUS_F32, ); let inputs = [ AdapterFamilyInput { route: &first, manifest_path: &first_manifest_path, }, AdapterFamilyInput { route: &second, manifest_path: &second_manifest_path, }, ]; let error = build_receipt_text( "candidate-a", "Candidate source ALR1 family", "../models/candidate-source-low-rank.adapter-family.receipt", &inputs, ) .unwrap_err(); assert!(error .to_string() .contains("adapter_source_manifest_checksum")); fs::remove_dir_all(dir).unwrap(); } #[test] fn rejects_identity_drift_between_family_members() { let dir = unique_dir("identity-drift"); fs::create_dir_all(&dir).unwrap(); let first_manifest = member_manifest("0x00000000000000aa", "0x00000000000000f1"); let second_manifest = member_manifest("0x00000000000000bb", "0x00000000000000f2"); let first_manifest_path = dir.join("first.adp1.manifest"); let second_manifest_path = dir.join("second.adp1.manifest"); fs::write(&first_manifest_path, &first_manifest).unwrap(); fs::write(&second_manifest_path, &second_manifest).unwrap(); let first = route( "../models/first.adp1", "First ADP1", "0x00000000000000aa", &first_manifest, ); let second = route( "../models/second.adp1", "Second ADP1", "0x00000000000000bb", &second_manifest, ); let inputs = [ AdapterFamilyInput { route: &first, manifest_path: &first_manifest_path, }, AdapterFamilyInput { route: &second, manifest_path: &second_manifest_path, }, ]; let error = build_receipt_text( "candidate-a", "Candidate ADP1 family", "../models/candidate.adapter-family.receipt", &inputs, ) .unwrap_err(); assert!(error.to_string().contains("adapter_tensor_layout_checksum")); fs::remove_dir_all(dir).unwrap(); } fn route( adapter_path: &str, label: &str, artifact_checksum: &str, manifest_text: &str, ) -> RegistryAdapterRoute { route_with_apply_status( adapter_path, label, artifact_checksum, manifest_text, ADAPTER_APPLY_STATUS_F32, ) } fn route_with_apply_status( adapter_path: &str, label: &str, artifact_checksum: &str, manifest_text: &str, apply_status: &str, ) -> RegistryAdapterRoute { RegistryAdapterRoute { candidate_id: "candidate-a".to_string(), adapter_path: adapter_path.to_string(), manifest_path: format!("{adapter_path}.manifest"), label: label.to_string(), apply_status: apply_status.to_string(), artifact_checksum: artifact_checksum.to_string(), manifest_checksum: hex64(provenance::text_checksum(manifest_text.as_bytes())), } } fn member_manifest(artifact_checksum: &str, layout_checksum: &str) -> String { member_manifest_with_quantization( artifact_checksum, layout_checksum, "f32", ADAPTER_APPLY_STATUS_F32, ) } fn sparse_member_manifest(artifact_checksum: &str, layout_checksum: &str) -> String { member_manifest_with_format( artifact_checksum, layout_checksum, "f32", ADAPTER_APPLY_STATUS_F32, SPARSE_ADAPTER_ARTIFACT_KIND, SPARSE_ADAPTER_DTYPE, ) } fn member_manifest_with_quantization( artifact_checksum: &str, layout_checksum: &str, base_quantization: &str, apply_status: &str, ) -> String { member_manifest_with_format( artifact_checksum, layout_checksum, base_quantization, apply_status, ADAPTER_ARTIFACT_KIND, ADAPTER_DTYPE, ) } fn source_low_rank_member_manifest( artifact_checksum: &str, layout_checksum: &str, base_quantization: &str, apply_status: &str, ) -> String { // Builds a valid source-backed low-rank adapter manifest for receipt tests. let mut text = member_manifest_with_format( artifact_checksum, layout_checksum, base_quantization, apply_status, SOURCE_LOW_RANK_ADAPTER_ARTIFACT_KIND, SOURCE_LOW_RANK_ADAPTER_DTYPE, ); push_line( &mut text, "adapter_source_manifest", SOURCE_LOW_RANK_ADAPTER_SOURCE_MANIFEST, ); push_line( &mut text, "adapter_source_manifest_checksum", "0x00000000000000d1", ); push_line( &mut text, "adapter_source_layout", SOURCE_LOW_RANK_ADAPTER_SOURCE_LAYOUT, ); push_line( &mut text, "adapter_source_format", SOURCE_LOW_RANK_ADAPTER_SOURCE_FORMAT, ); push_line( &mut text, "adapter_source_base_contract", SOURCE_LOW_RANK_ADAPTER_SOURCE_BASE_CONTRACT, ); text } fn member_manifest_with_format( artifact_checksum: &str, layout_checksum: &str, base_quantization: &str, apply_status: &str, artifact_kind: &str, dtype: &str, ) -> String { let mut text = String::new(); push_line( &mut text, "tinyrustlm_adapter_artifact_version", ADAPTER_ARTIFACT_VERSION, ); push_line(&mut text, "adapter_artifact_kind", artifact_kind); push_line(&mut text, "adapter_status", ADAPTER_STATUS); push_line(&mut text, "adapter_artifact_checksum", artifact_checksum); push_line(&mut text, "adapter_tensor_count", "12"); push_line(&mut text, "adapter_parameter_count", "1024"); push_line(&mut text, "adapter_dtype", dtype); push_line(&mut text, "adapter_model_shape", "tiny-fixture"); push_line(&mut text, "adapter_base_quantization", base_quantization); push_line(&mut text, "adapter_output_contract", "untied-output"); push_line( &mut text, "adapter_tokenizer_checksum", "0x00000000000000e1", ); push_line(&mut text, "adapter_tensor_layout_checksum", layout_checksum); push_line( &mut text, "adapter_base_contract", "matches-parent-direct-parameter-contract", ); push_line(&mut text, "adapter_apply_status", apply_status); text } fn unique_dir(label: &str) -> PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-adapter-family-{label}-{nanos}")) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/adapter_family.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/admission.rs BYTES: 45722 SHA256: 8A001B0351CB03F73C4E01381DA4C0847C08503C0F2EA3B1EEC69883BB28D130 ================================================================================ //! Browser-selector admission records for evaluated model-breeding candidates. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::candidate; use crate::lineage; use crate::promotion; use crate::provenance; use crate::slm_validate; const ADMISSION_VERSION: &str = "1"; const DEFAULT_SELECTOR_ID: &str = "browser-local-selector"; const ADMISSION_STATUS: &str = "admitted-for-browser-selector"; const PROMOTION_STATUS: &str = "runtime-smoke-and-eval-passed"; const RUNTIME_SMOKE_STATUS: &str = "pass"; const EVAL_STATUS: &str = "pass"; const QUALITY_GATE: &str = "assistant-quality"; const PROMOTION_DECISION: &str = "accepted-for-browser-selector"; const BROWSER_SELECTOR_STATUS: &str = "admitted"; const PUBLIC_CLAIM_STATUS: &str = "bound-to-eval-scope"; const REQUIRED_NEXT_GATE: &str = "browser-selector-loads-only-admission-record-artifacts"; const OPERATOR_RECEIPT_PREFIX: &str = "operator_receipt_"; const PROMOTION_KEYS: [&str; 8] = [ "candidate_id", "promotion_scope", "promoter_id", "operator_id", "operator_lane", "resource_budget", "compatibility_report_checksum", "lineage_manifest_checksum", ]; const CANDIDATE_KEYS: [&str; 11] = [ "candidate_artifact_path", "candidate_artifact_bytes", "candidate_slm_version", "candidate_slm_checksum", "candidate_model_shape", "candidate_tensor_count", "candidate_parameter_count", "candidate_quantization", "candidate_output_contract", "candidate_tokenizer_checksum", "candidate_tensor_layout_checksum", ]; const OPERATOR_RECEIPT_KEYS: [&str; 7] = [ "operator_receipt_status", "operator_receipt_path", "operator_receipt_checksum", "operator_receipt_operator_id", "operator_receipt_operator_kind", "operator_receipt_candidate_slm_checksum", "operator_receipt_candidate_artifact_bytes", ]; /// Default selector id used when the admission CLI caller omits one. pub(crate) const DEFAULT_ADMISSION_SELECTOR_ID: &str = DEFAULT_SELECTOR_ID; struct Evidence { promotion: HashMap, eval: HashMap, } /// Writes a browser-selector admission record after runtime-smoke and eval evidence pass. pub(crate) fn write_record_path( compatibility: &Path, lineage_manifest: &Path, candidate_slm: &Path, candidate_manifest: &Path, promotion_manifest: &Path, provenance_manifest: &Path, runtime_smoke: &Path, eval_manifest: &Path, output: &Path, selector_id: &str, operator_receipt: Option<&Path>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let candidate_bytes = fs::read(candidate_slm)?; let candidate_manifest_text = fs::read_to_string(candidate_manifest)?; let promotion_text = fs::read_to_string(promotion_manifest)?; let provenance_text = fs::read_to_string(provenance_manifest)?; let runtime_smoke_text = fs::read_to_string(runtime_smoke)?; let eval_text = fs::read_to_string(eval_manifest)?; let operator_receipt_text = read_operator_receipt_binding(operator_receipt)?; let operator_receipt_binding = operator_receipt_text .as_ref() .map(|(path, text)| (path.as_str(), text.as_str())); let admission = build_record_text_with_operator_receipt_text( &compatibility_text, &lineage_text, &candidate_bytes, &candidate_slm.display().to_string(), &candidate_manifest_text, &promotion_text, &provenance_text, &runtime_smoke_text, &eval_text, selector_id, operator_receipt_binding, )?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, admission)?; println!( "SLM selector admission record written: {}", output.display() ); Ok(()) } /// Validates a browser-selector admission record against all model-breeding evidence. pub(crate) fn validate_record_path( compatibility: &Path, lineage_manifest: &Path, candidate_slm: &Path, candidate_manifest: &Path, promotion_manifest: &Path, provenance_manifest: &Path, runtime_smoke: &Path, eval_manifest: &Path, admission: &Path, operator_receipt: Option<&Path>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let candidate_bytes = fs::read(candidate_slm)?; let candidate_manifest_text = fs::read_to_string(candidate_manifest)?; let promotion_text = fs::read_to_string(promotion_manifest)?; let provenance_text = fs::read_to_string(provenance_manifest)?; let runtime_smoke_text = fs::read_to_string(runtime_smoke)?; let eval_text = fs::read_to_string(eval_manifest)?; let admission_text = fs::read_to_string(admission)?; let operator_receipt_text = read_operator_receipt_binding(operator_receipt)?; let operator_receipt_binding = operator_receipt_text .as_ref() .map(|(path, text)| (path.as_str(), text.as_str())); validate_record_text_with_operator_receipt_text( &compatibility_text, &lineage_text, &candidate_bytes, &candidate_slm.display().to_string(), &candidate_manifest_text, &promotion_text, &provenance_text, &runtime_smoke_text, &eval_text, &admission_text, operator_receipt_binding, )?; println!("SLM selector admission validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("admission: {}", admission.display()); Ok(()) } pub(crate) fn build_record_text( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, candidate_manifest_text: &str, promotion_text: &str, provenance_text: &str, runtime_smoke_text: &str, eval_text: &str, selector_id: &str, ) -> io::Result { build_record_text_with_operator_receipt_text( compatibility_text, lineage_text, candidate_bytes, candidate_path, candidate_manifest_text, promotion_text, provenance_text, runtime_smoke_text, eval_text, selector_id, None, ) } /// Builds selector admission text while optionally preserving two-parent producer receipt provenance. pub(crate) fn build_record_text_with_operator_receipt_text( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, candidate_manifest_text: &str, promotion_text: &str, provenance_text: &str, runtime_smoke_text: &str, eval_text: &str, selector_id: &str, operator_receipt: Option<(&str, &str)>, ) -> io::Result { validate_slug(selector_id, "selector_id")?; let evidence = validate_evidence_with_operator_receipt_text( compatibility_text, lineage_text, candidate_bytes, candidate_path, candidate_manifest_text, promotion_text, provenance_text, runtime_smoke_text, eval_text, operator_receipt, )?; let mut text = String::new(); push_line( &mut text, "tinyrustlm_selector_admission_version", ADMISSION_VERSION, ); for key in PROMOTION_KEYS { push_line(&mut text, key, require_key(&evidence.promotion, key)?); } push_line(&mut text, "selector_id", selector_id); push_line(&mut text, "admission_status", ADMISSION_STATUS); push_line(&mut text, "promotion_status", PROMOTION_STATUS); push_line( &mut text, "candidate_manifest_checksum", require_key(&evidence.promotion, "candidate_manifest_checksum")?, ); push_line( &mut text, "promotion_manifest_checksum", &hex64(lineage::text_checksum(promotion_text.as_bytes())), ); push_operator_receipt_lines(&mut text, &evidence.promotion)?; push_line( &mut text, "provenance_manifest_checksum", &hex64(provenance::text_checksum(provenance_text.as_bytes())), ); push_line( &mut text, "runtime_smoke_manifest_checksum", &hex64(provenance::text_checksum(runtime_smoke_text.as_bytes())), ); push_line( &mut text, "eval_manifest_checksum", &hex64(provenance::text_checksum(eval_text.as_bytes())), ); push_line( &mut text, "eval_case_evidence_checksum", &provenance::eval_case_evidence_checksum(&evidence.eval)?, ); for key in CANDIDATE_KEYS { push_line(&mut text, key, require_key(&evidence.promotion, key)?); } push_line(&mut text, "runtime_smoke_status", RUNTIME_SMOKE_STATUS); push_line(&mut text, "eval_status", EVAL_STATUS); push_line(&mut text, "quality_gate", QUALITY_GATE); push_line( &mut text, "quality_scope", require_key(&evidence.eval, "quality_scope")?, ); push_line( &mut text, "quality_boundary", require_key(&evidence.eval, "quality_boundary")?, ); push_line( &mut text, "eval_dataset", require_key(&evidence.eval, "eval_dataset")?, ); push_line( &mut text, "case_count", require_key(&evidence.eval, "case_count")?, ); push_line( &mut text, "cases_passed", require_key(&evidence.eval, "cases_passed")?, ); push_line( &mut text, "cases_failed", require_key(&evidence.eval, "cases_failed")?, ); push_line(&mut text, "promotion_decision", PROMOTION_DECISION); push_line( &mut text, "browser_selector_status", BROWSER_SELECTOR_STATUS, ); push_line(&mut text, "public_claim_status", PUBLIC_CLAIM_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } #[allow(dead_code)] fn validate_record_text( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, candidate_manifest_text: &str, promotion_text: &str, provenance_text: &str, runtime_smoke_text: &str, eval_text: &str, admission_text: &str, ) -> io::Result<()> { validate_record_text_with_operator_receipt_text( compatibility_text, lineage_text, candidate_bytes, candidate_path, candidate_manifest_text, promotion_text, provenance_text, runtime_smoke_text, eval_text, admission_text, None, ) } /// Validates selector admission text while recomputing optional producer receipt provenance. pub(crate) fn validate_record_text_with_operator_receipt_text( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, candidate_manifest_text: &str, promotion_text: &str, provenance_text: &str, runtime_smoke_text: &str, eval_text: &str, admission_text: &str, operator_receipt: Option<(&str, &str)>, ) -> io::Result<()> { let evidence = validate_evidence_with_operator_receipt_text( compatibility_text, lineage_text, candidate_bytes, candidate_path, candidate_manifest_text, promotion_text, provenance_text, runtime_smoke_text, eval_text, operator_receipt, )?; let admission = parse_manifest(admission_text, "admission")?; require_equal( &admission, "tinyrustlm_selector_admission_version", ADMISSION_VERSION, )?; for key in PROMOTION_KEYS { require_equal(&admission, key, require_key(&evidence.promotion, key)?)?; } validate_slug(require_key(&admission, "selector_id")?, "selector_id")?; require_equal(&admission, "admission_status", ADMISSION_STATUS)?; require_equal(&admission, "promotion_status", PROMOTION_STATUS)?; require_equal( &admission, "candidate_manifest_checksum", require_key(&evidence.promotion, "candidate_manifest_checksum")?, )?; require_equal( &admission, "promotion_manifest_checksum", &hex64(lineage::text_checksum(promotion_text.as_bytes())), )?; require_operator_receipt_lines(&evidence.promotion, &admission)?; require_equal( &admission, "provenance_manifest_checksum", &hex64(provenance::text_checksum(provenance_text.as_bytes())), )?; require_equal( &admission, "runtime_smoke_manifest_checksum", &hex64(provenance::text_checksum(runtime_smoke_text.as_bytes())), )?; require_equal( &admission, "eval_manifest_checksum", &hex64(provenance::text_checksum(eval_text.as_bytes())), )?; require_equal( &admission, "eval_case_evidence_checksum", &provenance::eval_case_evidence_checksum(&evidence.eval)?, )?; for key in CANDIDATE_KEYS { require_equal(&admission, key, require_key(&evidence.promotion, key)?)?; } require_equal(&admission, "runtime_smoke_status", RUNTIME_SMOKE_STATUS)?; require_equal(&admission, "eval_status", EVAL_STATUS)?; require_equal(&admission, "quality_gate", QUALITY_GATE)?; require_equal( &admission, "quality_scope", require_key(&evidence.eval, "quality_scope")?, )?; require_equal( &admission, "quality_boundary", require_key(&evidence.eval, "quality_boundary")?, )?; require_equal( &admission, "eval_dataset", require_key(&evidence.eval, "eval_dataset")?, )?; require_equal( &admission, "case_count", require_key(&evidence.eval, "case_count")?, )?; require_equal( &admission, "cases_passed", require_key(&evidence.eval, "cases_passed")?, )?; require_equal( &admission, "cases_failed", require_key(&evidence.eval, "cases_failed")?, )?; require_equal(&admission, "promotion_decision", PROMOTION_DECISION)?; require_equal( &admission, "browser_selector_status", BROWSER_SELECTOR_STATUS, )?; require_equal(&admission, "public_claim_status", PUBLIC_CLAIM_STATUS)?; require_equal(&admission, "required_next_gate", REQUIRED_NEXT_GATE)?; Ok(()) } /// Validates the self-contained selector-facing fields in an admission record. pub(crate) fn validate_record_summary_text( admission_text: &str, ) -> io::Result> { let admission = parse_manifest(admission_text, "admission")?; require_equal( &admission, "tinyrustlm_selector_admission_version", ADMISSION_VERSION, )?; for key in PROMOTION_KEYS { require_key(&admission, key)?; } validate_slug(require_key(&admission, "selector_id")?, "selector_id")?; require_equal(&admission, "admission_status", ADMISSION_STATUS)?; require_equal(&admission, "promotion_status", PROMOTION_STATUS)?; for key in [ "candidate_manifest_checksum", "promotion_manifest_checksum", "provenance_manifest_checksum", "runtime_smoke_manifest_checksum", "eval_manifest_checksum", "eval_case_evidence_checksum", ] { require_hex64(&admission, key)?; } for key in CANDIDATE_KEYS { require_key(&admission, key)?; } validate_operator_receipt_summary(&admission)?; require_positive_usize(&admission, "candidate_artifact_bytes")?; require_positive_usize(&admission, "candidate_slm_version")?; require_hex64(&admission, "candidate_slm_checksum")?; require_positive_usize(&admission, "candidate_tensor_count")?; require_positive_usize(&admission, "candidate_parameter_count")?; require_hex64(&admission, "candidate_tokenizer_checksum")?; require_hex64(&admission, "candidate_tensor_layout_checksum")?; require_equal(&admission, "runtime_smoke_status", RUNTIME_SMOKE_STATUS)?; require_equal(&admission, "eval_status", EVAL_STATUS)?; require_equal(&admission, "quality_gate", QUALITY_GATE)?; for key in ["quality_scope", "quality_boundary", "eval_dataset"] { require_key(&admission, key)?; } let case_count = require_positive_usize(&admission, "case_count")?; let cases_passed = require_usize(&admission, "cases_passed")?; let cases_failed = require_usize(&admission, "cases_failed")?; if cases_passed != case_count || cases_failed != 0 { return Err(invalid( "admission case totals must show every declared case passed and zero failed cases", )); } require_equal(&admission, "promotion_decision", PROMOTION_DECISION)?; require_equal( &admission, "browser_selector_status", BROWSER_SELECTOR_STATUS, )?; require_equal(&admission, "public_claim_status", PUBLIC_CLAIM_STATUS)?; require_equal(&admission, "required_next_gate", REQUIRED_NEXT_GATE)?; Ok(admission) } // Recomputes every upstream admission prerequisite, including optional operator receipt binding. fn validate_evidence_with_operator_receipt_text( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, candidate_manifest_text: &str, promotion_text: &str, provenance_text: &str, runtime_smoke_text: &str, eval_text: &str, operator_receipt: Option<(&str, &str)>, ) -> io::Result { candidate::validate_manifest_text_with_operator_receipt_text( compatibility_text, lineage_text, candidate_bytes, candidate_path, candidate_manifest_text, operator_receipt, )?; promotion::validate_text_with_operator_receipt_text( compatibility_text, lineage_text, candidate_bytes, candidate_path, candidate_manifest_text, promotion_text, operator_receipt, )?; let report = slm_validate::validate_bytes(candidate_bytes, candidate_path)?; let runtime_smoke = provenance::validate_runtime_smoke_text(&report, provenance_text, runtime_smoke_text)?; provenance::validate_quality_gate(&report, provenance_text, QUALITY_GATE, Some(eval_text))?; let promotion = parse_manifest(promotion_text, "promotion")?; let eval = provenance::parse_manifest(eval_text)?; require_equal(&runtime_smoke, "runtime_smoke_status", RUNTIME_SMOKE_STATUS)?; require_equal(&eval, "eval_status", EVAL_STATUS)?; require_equal(&eval, "task_eval_status", EVAL_STATUS)?; require_equal(&eval, "cases_failed", "0")?; Ok(Evidence { promotion, eval }) } // Reads an optional operator receipt once while preserving its display path for validation. fn read_operator_receipt_binding( operator_receipt: Option<&Path>, ) -> io::Result> { operator_receipt .map(|path| { let text = fs::read_to_string(path)?; Ok((path.display().to_string(), text)) }) .transpose() } fn push_operator_receipt_lines( text: &mut String, promotion: &HashMap, ) -> io::Result<()> { if promotion.contains_key("operator_receipt_status") { for key in OPERATOR_RECEIPT_KEYS { push_line(text, key, require_key(promotion, key)?); } } Ok(()) } fn require_operator_receipt_lines( promotion: &HashMap, admission: &HashMap, ) -> io::Result<()> { if promotion.contains_key("operator_receipt_status") { for key in OPERATOR_RECEIPT_KEYS { require_equal(admission, key, require_key(promotion, key)?)?; } return Ok(()); } reject_unbound_operator_receipt_fields(admission) } fn validate_operator_receipt_summary(admission: &HashMap) -> io::Result<()> { if admission.contains_key("operator_receipt_status") { require_equal(admission, "operator_receipt_status", "receipt-bound")?; require_key(admission, "operator_receipt_path")?; require_hex64(admission, "operator_receipt_checksum")?; require_key(admission, "operator_receipt_operator_id")?; require_key(admission, "operator_receipt_operator_kind")?; require_hex64(admission, "operator_receipt_candidate_slm_checksum")?; require_positive_usize(admission, "operator_receipt_candidate_artifact_bytes")?; return Ok(()); } reject_unbound_operator_receipt_fields(admission) } fn reject_unbound_operator_receipt_fields(fields: &HashMap) -> io::Result<()> { if let Some(key) = fields .keys() .find(|key| key.starts_with(OPERATOR_RECEIPT_PREFIX)) { return Err(invalid(&format!( "admission has operator receipt field {key} without a bound promotion receipt" ))); } Ok(()) } fn parse_manifest(text: &str, label: &str) -> io::Result> { let mut fields = HashMap::new(); for (line_index, raw_line) in text.lines().enumerate() { let line = raw_line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let Some((key, value)) = line.split_once('=') else { return Err(invalid(&format!( "{label} line {} is missing '='", line_index + 1 ))); }; let key = key.trim(); let value = value.trim(); validate_key(key, label, line_index + 1)?; validate_value(value, key)?; if fields.insert(key.to_string(), value.to_string()).is_some() { return Err(invalid(&format!("duplicate {label} key {key}"))); } } Ok(fields) } fn validate_key(key: &str, label: &str, line_number: usize) -> io::Result<()> { if key.is_empty() || !key .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_')) { return Err(invalid(&format!( "{label} line {line_number} has an invalid key" ))); } Ok(()) } fn validate_value(value: &str, key: &str) -> io::Result<()> { if value.is_empty() || value.contains('\n') || value.contains('\r') { return Err(invalid(&format!("{key} has an invalid value"))); } Ok(()) } fn validate_slug(value: &str, key: &str) -> io::Result<()> { validate_value(value, key)?; if value.len() > 96 || !value .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) { return Err(invalid(&format!("{key} must be an ASCII slug"))); } Ok(()) } fn require_key<'a>(fields: &'a HashMap, key: &str) -> io::Result<&'a str> { fields .get(key) .map(String::as_str) .ok_or_else(|| invalid(&format!("manifest missing required key {key}"))) } fn require_equal(fields: &HashMap, key: &str, expected: &str) -> io::Result<()> { let actual = require_key(fields, key)?; if actual != expected { return Err(invalid(&format!( "manifest key {key} was {actual}, expected {expected}" ))); } Ok(()) } fn require_hex64(fields: &HashMap, key: &str) -> io::Result<()> { let value = require_key(fields, key)?; let Some(hex) = value.strip_prefix("0x") else { return Err(invalid(&format!( "manifest key {key} must be a hex checksum" ))); }; if hex.len() != 16 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { return Err(invalid(&format!( "manifest key {key} must be a hex checksum" ))); } Ok(()) } fn require_positive_usize(fields: &HashMap, key: &str) -> io::Result { let value = require_usize(fields, key)?; if value == 0 { return Err(invalid(&format!( "manifest key {key} must be greater than zero" ))); } Ok(value) } fn require_usize(fields: &HashMap, key: &str) -> io::Result { let value = require_key(fields, key)?; value .parse::() .map_err(|_| invalid(&format!("manifest key {key} must be a usize"))) } fn push_line(text: &mut String, key: &str, value: &str) { text.push_str(key); text.push('='); text.push_str(value); text.push('\n'); } fn hex64(value: u64) -> String { format!("0x{value:016x}") } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } #[cfg(test)] mod tests { use super::*; use crate::build_model_file; use crate::compatibility; use crate::tensor_writer::{tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_Q8_0}; use crate::tokenizer_writer::ByteTokenizerSection; use std::fs; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; #[test] fn writes_and_validates_selector_admission_record() { let fixture = AdmissionFixture::new(); let admission = fixture.admission(); validate_record_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &fixture.candidate_manifest, &fixture.promotion, &fixture.provenance_manifest, &fixture.runtime_smoke, &fixture.eval, &admission, ) .unwrap(); assert!(admission.contains("admission_status=admitted-for-browser-selector")); assert!(admission.contains("eval_case_evidence_checksum=0x")); assert!(admission.contains("browser_selector_status=admitted")); assert!(admission.contains("public_claim_status=bound-to-eval-scope")); } #[test] fn writes_and_validates_operator_receipt_bound_admission_record() { let fixture = AdmissionFixture::new(); let receipt = operator_receipt_text(&fixture.lineage, &fixture.candidate, "candidate.slm"); let (candidate_manifest, promotion) = receipt_bound_candidate_and_promotion( &fixture, "candidate.slm", "candidate.operator", &receipt, ); let admission = build_record_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &candidate_manifest, &promotion, &fixture.provenance_manifest, &fixture.runtime_smoke, &fixture.eval, DEFAULT_SELECTOR_ID, Some(("candidate.operator", &receipt)), ) .unwrap(); validate_record_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &candidate_manifest, &promotion, &fixture.provenance_manifest, &fixture.runtime_smoke, &fixture.eval, &admission, Some(("candidate.operator", &receipt)), ) .unwrap(); validate_record_summary_text(&admission).unwrap(); assert!(admission.contains("operator_receipt_status=receipt-bound")); assert!(admission.contains(&format!( "operator_receipt_checksum={}", hex64(lineage::text_checksum(receipt.as_bytes())) ))); assert!(admission .contains("operator_receipt_operator_kind=deterministic-bounded-parameter-mutation")); } #[test] fn path_functions_accept_bound_operator_receipt_input() { let dir = unique_temp_dir("admission-operator-receipt"); fs::create_dir_all(&dir).unwrap(); let candidate = tiny_fixture_q8_bytes(); let compatibility_path = dir.join("parents.compat"); let lineage_path = dir.join("candidate.lineage"); let candidate_path = dir.join("candidate.slm"); let receipt_path = dir.join("candidate.operator"); let candidate_manifest_path = dir.join("candidate.candidate"); let promotion_path = dir.join("candidate.promotion"); let provenance_path = dir.join("candidate.manifest"); let runtime_path = dir.join("candidate.runtime"); let eval_path = dir.join("candidate.eval"); let admission_path = dir.join("candidate.admission"); let compatibility = compatibility::compatibility_text_for_bytes( &candidate, "left.slm", &candidate, "right.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, "tiny-q8-candidate", "operator-a", "fit") .unwrap(); let receipt = operator_receipt_text(&lineage, &candidate, &candidate_path.display().to_string()); fs::write(&compatibility_path, compatibility).unwrap(); fs::write(&lineage_path, lineage).unwrap(); fs::write(&candidate_path, &candidate).unwrap(); fs::write(&receipt_path, receipt).unwrap(); candidate::write_manifest_path( &compatibility_path, &lineage_path, &candidate_path, &candidate_manifest_path, Some(&receipt_path), ) .unwrap(); promotion::write_template_path( &compatibility_path, &lineage_path, &candidate_path, &candidate_manifest_path, &promotion_path, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, Some(&receipt_path), ) .unwrap(); let report = slm_validate::validate_bytes(&candidate, &candidate_path.display().to_string()) .unwrap(); let provenance_manifest = provenance::build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = provenance::parse_manifest(&provenance_manifest).unwrap(); let runtime_smoke = provenance::build_runtime_smoke_text(&report, &provenance_manifest, &manifest_fields) .unwrap(); let eval = passing_eval_text(&report, &provenance_manifest); fs::write(&provenance_path, provenance_manifest).unwrap(); fs::write(&runtime_path, runtime_smoke).unwrap(); fs::write(&eval_path, eval).unwrap(); write_record_path( &compatibility_path, &lineage_path, &candidate_path, &candidate_manifest_path, &promotion_path, &provenance_path, &runtime_path, &eval_path, &admission_path, DEFAULT_SELECTOR_ID, Some(&receipt_path), ) .unwrap(); validate_record_path( &compatibility_path, &lineage_path, &candidate_path, &candidate_manifest_path, &promotion_path, &provenance_path, &runtime_path, &eval_path, &admission_path, Some(&receipt_path), ) .unwrap(); let admission = fs::read_to_string(&admission_path).unwrap(); assert!(admission.contains(&format!("operator_receipt_path={}", receipt_path.display()))); fs::remove_dir_all(&dir).unwrap(); } #[test] fn rejects_runtime_smoke_drift() { let fixture = AdmissionFixture::new(); let admission = fixture.admission(); let changed_smoke = fixture.runtime_smoke.replace( "runtime_smoke_decision=accepted-for-runtime-smoke", "runtime_smoke_decision=pending", ); let error = validate_record_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &fixture.candidate_manifest, &fixture.promotion, &fixture.provenance_manifest, &changed_smoke, &fixture.eval, &admission, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("runtime_smoke_decision")); } #[test] fn validation_rejects_bound_admission_without_operator_receipt_input() { let fixture = AdmissionFixture::new(); let receipt = operator_receipt_text(&fixture.lineage, &fixture.candidate, "candidate.slm"); let (candidate_manifest, promotion) = receipt_bound_candidate_and_promotion( &fixture, "candidate.slm", "candidate.operator", &receipt, ); let admission = build_record_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &candidate_manifest, &promotion, &fixture.provenance_manifest, &fixture.runtime_smoke, &fixture.eval, DEFAULT_SELECTOR_ID, Some(("candidate.operator", &receipt)), ) .unwrap(); let error = validate_record_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &candidate_manifest, &promotion, &fixture.provenance_manifest, &fixture.runtime_smoke, &fixture.eval, &admission, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator receipt binding")); } #[test] fn validation_rejects_operator_receipt_admission_checksum_drift() { let fixture = AdmissionFixture::new(); let receipt = operator_receipt_text(&fixture.lineage, &fixture.candidate, "candidate.slm"); let expected_checksum = hex64(lineage::text_checksum(receipt.as_bytes())); let (candidate_manifest, promotion) = receipt_bound_candidate_and_promotion( &fixture, "candidate.slm", "candidate.operator", &receipt, ); let admission = build_record_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &candidate_manifest, &promotion, &fixture.provenance_manifest, &fixture.runtime_smoke, &fixture.eval, DEFAULT_SELECTOR_ID, Some(("candidate.operator", &receipt)), ) .unwrap(); let drifted_admission = admission.replace( &format!("operator_receipt_checksum={expected_checksum}"), "operator_receipt_checksum=0x0000000000000000", ); let error = validate_record_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &candidate_manifest, &promotion, &fixture.provenance_manifest, &fixture.runtime_smoke, &fixture.eval, &drifted_admission, Some(("candidate.operator", &receipt)), ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator_receipt_checksum")); } #[test] fn rejects_eval_manifest_drift() { let fixture = AdmissionFixture::new(); let admission = fixture.admission(); let changed_eval = fixture .eval .replace("case.0.actual=e\n", "case.0.actual=x\n"); let error = validate_record_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &fixture.candidate_manifest, &fixture.promotion, &fixture.provenance_manifest, &fixture.runtime_smoke, &changed_eval, &admission, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("actual text did not match")); } #[test] fn rejects_admission_overclaim() { let fixture = AdmissionFixture::new(); let admission = fixture.admission().replace( "public_claim_status=bound-to-eval-scope", "public_claim_status=unbounded", ); let error = validate_record_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &fixture.candidate_manifest, &fixture.promotion, &fixture.provenance_manifest, &fixture.runtime_smoke, &fixture.eval, &admission, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("public_claim_status")); } #[test] fn rejects_invalid_selector_id() { let fixture = AdmissionFixture::new(); let error = build_record_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &fixture.candidate_manifest, &fixture.promotion, &fixture.provenance_manifest, &fixture.runtime_smoke, &fixture.eval, "bad selector", ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("selector_id")); } #[test] fn summary_rejects_incomplete_case_totals() { let fixture = AdmissionFixture::new(); let admission = fixture .admission() .replace("cases_passed=1", "cases_passed=0"); let error = validate_record_summary_text(&admission).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("case totals")); } struct AdmissionFixture { compatibility: String, lineage: String, candidate: Vec, candidate_manifest: String, promotion: String, provenance_manifest: String, runtime_smoke: String, eval: String, } impl AdmissionFixture { fn new() -> Self { let candidate = tiny_fixture_q8_bytes(); let compatibility = compatibility::compatibility_text_for_bytes( &candidate, "left.slm", &candidate, "right.slm", ) .unwrap(); let lineage = lineage::build_template_text( &compatibility, "tiny-q8-candidate", "operator-a", "fit", ) .unwrap(); let candidate_manifest = candidate::build_manifest_text( &compatibility, &lineage, &candidate, "candidate.slm", ) .unwrap(); let promotion = promotion::build_template_text( &compatibility, &lineage, &candidate, "candidate.slm", &candidate_manifest, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, ) .unwrap(); let report = slm_validate::validate_bytes(&candidate, "candidate.slm").unwrap(); let provenance_manifest = provenance::build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = provenance::parse_manifest(&provenance_manifest).unwrap(); let runtime_smoke = provenance::build_runtime_smoke_text( &report, &provenance_manifest, &manifest_fields, ) .unwrap(); let eval = passing_eval_text(&report, &provenance_manifest); Self { compatibility, lineage, candidate, candidate_manifest, promotion, provenance_manifest, runtime_smoke, eval, } } fn admission(&self) -> String { build_record_text( &self.compatibility, &self.lineage, &self.candidate, "candidate.slm", &self.candidate_manifest, &self.promotion, &self.provenance_manifest, &self.runtime_smoke, &self.eval, DEFAULT_SELECTOR_ID, ) .unwrap() } } fn passing_eval_text(report: &slm_validate::ValidationReport, manifest: &str) -> String { let mut text = String::new(); push_line(&mut text, "tinyrustlm_eval_manifest_version", "1"); push_line(&mut text, "gate", QUALITY_GATE); push_line(&mut text, "source_kind", "converted-trained"); push_line( &mut text, "manifest_checksum", &hex64(provenance::text_checksum(manifest.as_bytes())), ); push_line(&mut text, "slm_checksum", &hex64(report.checksum())); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "task_eval_status", "pass"); push_line(&mut text, "safety_review_status", "pass"); push_line( &mut text, "quality_decision", "accepted-for-assistant-quality", ); push_line(&mut text, "quality_scope", "tiny-fixture-runtime-eval-only"); push_line(&mut text, "evaluator", "local-reviewed-eval"); push_line( &mut text, "eval_dataset", "tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", ); push_line( &mut text, "eval_summary", "Reviewed task and safety evidence passed for declared scope", ); push_line( &mut text, "quality_boundary", "fixture-runtime-and-eval-plumbing-not-product-assistant-quality", ); push_line(&mut text, "case_count", "1"); push_line(&mut text, "cases_passed", "1"); push_line(&mut text, "cases_failed", "0"); push_line(&mut text, "case.0.status", "pass"); push_line(&mut text, "case.0.expected", "e"); push_line(&mut text, "case.0.actual", "e"); push_line(&mut text, "case.0.error", "ok"); text } fn receipt_bound_candidate_and_promotion( fixture: &AdmissionFixture, candidate_path: &str, receipt_path: &str, receipt: &str, ) -> (String, String) { let candidate_manifest = candidate::build_manifest_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, candidate_path, Some((receipt_path, receipt)), ) .unwrap(); let promotion = promotion::build_template_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, candidate_path, &candidate_manifest, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, Some((receipt_path, receipt)), ) .unwrap(); (candidate_manifest, promotion) } fn operator_receipt_text(lineage_text: &str, candidate: &[u8], candidate_path: &str) -> String { let lineage_fields = parse_manifest(lineage_text, "lineage").unwrap(); let report = slm_validate::validate_bytes(candidate, candidate_path).unwrap(); let mut text = String::new(); push_line(&mut text, "tinyrustlm_operator_receipt_version", "1"); push_line( &mut text, "operator_kind", "deterministic-bounded-parameter-mutation", ); push_line(&mut text, "operator_status", "operator-output-written"); push_line( &mut text, "candidate_id", require_key(&lineage_fields, "candidate_id").unwrap(), ); push_line( &mut text, "operator_id", require_key(&lineage_fields, "operator_id").unwrap(), ); push_line(&mut text, "candidate_artifact_path", report.path()); push_line( &mut text, "candidate_artifact_bytes", &report.file_bytes().to_string(), ); push_line( &mut text, "candidate_slm_checksum", &hex64(report.checksum()), ); push_line( &mut text, "required_next_gate", "candidate-manifest-plus-promotion-plus-admission", ); text } fn unique_temp_dir(label: &str) -> PathBuf { let nonce = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-admission-{label}-{nonce}")) } fn tiny_fixture_q8_bytes() -> Vec { build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), &ByteTokenizerSection::phase_one(), ) .unwrap() } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/admission.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/blend.rs BYTES: 35061 SHA256: 19E0776F91717ABE5715E07DC730ED3C66A46C0FF649026EF9CF57354C36FC8F ================================================================================ //! Offline direct-parameter blend operator for model-breeding candidates. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::build_model_file_from_values_with_flags; use crate::lineage; use crate::slm_validate::{self, ValidationReport}; use crate::tensor_writer::{ModelShape, TensorSpec, DTYPE_F32, DTYPE_Q4_0, DTYPE_Q8_0}; use crate::tokenizer_writer::TokenizerSection; const BLEND_OPERATOR_VERSION: &str = "1"; const COMPATIBILITY_VERSION: &str = "1"; const OPERATOR_KIND: &str = "direct-parameter-weighted-average"; const OPERATOR_STATUS: &str = "candidate-written"; const OPERATOR_OUTPUT_STATUS: &str = "slm-validated"; const PARENT_CONTRACT: &str = "matches-parent-direct-parameter-contract"; const REQUIRED_NEXT_GATE: &str = "candidate-manifest-plus-runtime-smoke-plus-eval"; pub(crate) const PPM_DENOMINATOR: u32 = 1_000_000; /// Writes a blended candidate `.slm` plus a recomputable operator receipt. pub(crate) fn write_candidate_path( compatibility: &Path, lineage_manifest: &Path, left_parent: &Path, right_parent: &Path, output_slm: &Path, output_receipt: &Path, parent0_weight_ppm: &str, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let left_bytes = fs::read(left_parent)?; let right_bytes = fs::read(right_parent)?; let weight = parse_weight_ppm(parent0_weight_ppm)?; let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility_text, &lineage_text, &left_bytes, &left_parent.display().to_string(), &right_bytes, &right_parent.display().to_string(), &output_slm.display().to_string(), weight, )?; if let Some(parent) = output_slm.parent() { fs::create_dir_all(parent)?; } fs::write(output_slm, candidate)?; if let Some(parent) = output_receipt.parent() { fs::create_dir_all(parent)?; } fs::write(output_receipt, receipt)?; println!("SLM blended candidate written: {}", output_slm.display()); println!( "SLM blend operator receipt written: {}", output_receipt.display() ); Ok(()) } /// Validates a blended candidate and receipt by recomputing the operator output. pub(crate) fn validate_candidate_path( compatibility: &Path, lineage_manifest: &Path, left_parent: &Path, right_parent: &Path, candidate_slm: &Path, receipt: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let left_bytes = fs::read(left_parent)?; let right_bytes = fs::read(right_parent)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; validate_candidate_text( &compatibility_text, &lineage_text, &left_bytes, &left_parent.display().to_string(), &right_bytes, &right_parent.display().to_string(), &candidate_bytes, &candidate_slm.display().to_string(), &receipt_text, )?; println!("SLM blend candidate validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("receipt: {}", receipt.display()); Ok(()) } fn validate_candidate_text( compatibility_text: &str, lineage_text: &str, left_bytes: &[u8], left_path: &str, right_bytes: &[u8], right_path: &str, candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, ) -> io::Result<()> { let receipt = parse_manifest(receipt_text, "blend operator receipt")?; require_equal( &receipt, "tinyrustlm_blend_operator_version", BLEND_OPERATOR_VERSION, )?; let weight = parse_weight_ppm(require_key(&receipt, "parent.0.weight_ppm")?)?; require_equal( &receipt, "parent.1.weight_ppm", &(PPM_DENOMINATOR - weight).to_string(), )?; let (expected_candidate, expected_receipt) = build_candidate_bytes_and_receipt( compatibility_text, lineage_text, left_bytes, left_path, right_bytes, right_path, candidate_path, weight, )?; if candidate_bytes != expected_candidate { return Err(invalid( "blended candidate bytes do not match the operator receipt", )); } if receipt_text != expected_receipt { return Err(invalid( "blend operator receipt fields do not match recomputed output", )); } Ok(()) } fn build_candidate_bytes_and_receipt( compatibility_text: &str, lineage_text: &str, left_bytes: &[u8], left_path: &str, right_bytes: &[u8], right_path: &str, candidate_path: &str, parent0_weight_ppm: u32, ) -> io::Result<(Vec, String)> { lineage::validate_text(compatibility_text, lineage_text)?; let compatibility = parse_passing_compatibility(compatibility_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let left_report = slm_validate::validate_bytes(left_bytes, left_path)?; let right_report = slm_validate::validate_bytes(right_bytes, right_path)?; require_parent_report(&compatibility, 0, &left_report)?; require_parent_report(&compatibility, 1, &right_report)?; let left = parse_model_values(left_bytes)?; let right = parse_model_values(right_bytes)?; let output_values = blend_values(&left, &right, parent0_weight_ppm)?; let output_tensors = output_specs(&left); let candidate = build_model_file_from_values_with_flags( &left.shape, &output_tensors, &left.tokenizer, &output_values, left.flags, )?; let candidate_report = slm_validate::validate_bytes(&candidate, candidate_path)?; require_report_equal( &compatibility, "parent.0.model_shape", &candidate_report.shape_summary(), )?; require_report_equal( &compatibility, "parent.0.quantization", candidate_report.quantization_label(), )?; require_report_equal( &compatibility, "parent.0.output_contract", candidate_report.output_contract_label(), )?; require_report_equal( &compatibility, "parent.0.tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), )?; require_report_equal( &compatibility, "parent.0.tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), )?; let receipt = build_receipt_text( &compatibility, &lineage_fields, lineage_text, left_path, right_path, &left_report, &right_report, &candidate_report, parent0_weight_ppm, )?; Ok((candidate, receipt)) } fn build_receipt_text( compatibility: &HashMap, lineage_fields: &HashMap, lineage_text: &str, left_path: &str, right_path: &str, left_report: &ValidationReport, right_report: &ValidationReport, candidate_report: &ValidationReport, parent0_weight_ppm: u32, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_blend_operator_version", BLEND_OPERATOR_VERSION, ); push_line(&mut text, "operator_kind", OPERATOR_KIND); push_line(&mut text, "operator_status", OPERATOR_STATUS); push_line( &mut text, "candidate_id", require_key(lineage_fields, "candidate_id")?, ); push_line( &mut text, "operator_id", require_key(lineage_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(lineage_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(lineage_fields, "resource_budget")?, ); push_line( &mut text, "compatibility_report_checksum", require_key(lineage_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(compatibility, "compatibility_scope")?, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, compatibility, 0, left_path, left_report)?; push_parent_lines(&mut text, compatibility, 1, right_path, right_report)?; push_line(&mut text, "blend_weight_unit", "parts-per-million"); push_line( &mut text, "parent.0.weight_ppm", &parent0_weight_ppm.to_string(), ); push_line( &mut text, "parent.1.weight_ppm", &(PPM_DENOMINATOR - parent0_weight_ppm).to_string(), ); push_line( &mut text, "candidate_artifact_path", candidate_report.path(), ); push_line( &mut text, "candidate_artifact_bytes", &candidate_report.file_bytes().to_string(), ); push_line( &mut text, "candidate_slm_version", &candidate_report.slm_version().to_string(), ); push_line( &mut text, "candidate_slm_checksum", &hex64(candidate_report.checksum()), ); push_line( &mut text, "candidate_model_shape", &candidate_report.shape_summary(), ); push_line( &mut text, "candidate_tensor_count", &candidate_report.tensor_count().to_string(), ); push_line( &mut text, "candidate_parameter_count", &candidate_report.parameter_count().to_string(), ); push_line( &mut text, "candidate_quantization", candidate_report.quantization_label(), ); push_line( &mut text, "candidate_output_contract", candidate_report.output_contract_label(), ); push_line( &mut text, "candidate_tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), ); push_line( &mut text, "candidate_tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), ); push_line(&mut text, "candidate_parent_contract", PARENT_CONTRACT); push_line(&mut text, "operator_output_status", OPERATOR_OUTPUT_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } pub(crate) fn push_parent_lines( text: &mut String, compatibility: &HashMap, index: usize, actual_path: &str, report: &ValidationReport, ) -> io::Result<()> { let prefix = format!("parent.{index}"); push_line( text, &format!("{prefix}.compatibility_path"), require_key(compatibility, &format!("{prefix}.path"))?, ); push_line(text, &format!("{prefix}.actual_path"), actual_path); push_line( text, &format!("{prefix}.model_bytes"), &report.file_bytes().to_string(), ); push_line( text, &format!("{prefix}.slm_checksum"), &hex64(report.checksum()), ); push_line( text, &format!("{prefix}.model_shape"), &report.shape_summary(), ); push_line( text, &format!("{prefix}.quantization"), report.quantization_label(), ); push_line( text, &format!("{prefix}.output_contract"), report.output_contract_label(), ); push_line( text, &format!("{prefix}.tokenizer_checksum"), &hex64(report.tokenizer_checksum()), ); push_line( text, &format!("{prefix}.tensor_layout_checksum"), &hex64(report.tensor_layout_checksum()), ); Ok(()) } fn blend_values( left: &ParsedModel, right: &ParsedModel, parent0_weight_ppm: u32, ) -> io::Result>> { if !same_shape(&left.shape, &right.shape) { return Err(invalid("blend parents have different model shapes")); } if left.flags != right.flags { return Err(invalid("blend parents have different output flags")); } if left.tokenizer.bytes != right.tokenizer.bytes { return Err(invalid("blend parents have different tokenizer bytes")); } let right_by_hash = right .tensors .iter() .enumerate() .map(|(index, tensor)| (tensor.spec.name_hash, index)) .collect::>(); let left_weight = parent0_weight_ppm as f32 / PPM_DENOMINATOR as f32; let right_weight = 1.0 - left_weight; let mut output = Vec::with_capacity(left.tensors.len()); for left_tensor in &left.tensors { let Some(right_index) = right_by_hash.get(&left_tensor.spec.name_hash) else { return Err(invalid( "right parent is missing a tensor from the left parent", )); }; let right_tensor = &right.tensors[*right_index]; require_same_tensor_spec(&left_tensor.spec, &right_tensor.spec)?; let values = left_tensor .values .iter() .zip(right_tensor.values.iter()) .map(|(left_value, right_value)| { left_value.mul_add(left_weight, right_value * right_weight) }) .collect::>(); output.push(values); } Ok(output) } pub(crate) fn output_specs(model: &ParsedModel) -> Vec { model .tensors .iter() .map(|tensor| TensorSpec { name_hash: tensor.spec.name_hash, dtype: tensor.spec.dtype, rank: tensor.spec.rank, dims: tensor.spec.dims, seed: 0, block_size: tensor.spec.block_size, }) .collect() } pub(crate) fn require_parent_report( compatibility: &HashMap, index: usize, report: &ValidationReport, ) -> io::Result<()> { let prefix = format!("parent.{index}"); require_report_equal( compatibility, &format!("{prefix}.model_bytes"), &report.file_bytes().to_string(), )?; require_report_equal( compatibility, &format!("{prefix}.slm_version"), &report.slm_version().to_string(), )?; require_report_equal( compatibility, &format!("{prefix}.slm_checksum"), &hex64(report.checksum()), )?; require_report_equal( compatibility, &format!("{prefix}.model_shape"), &report.shape_summary(), )?; require_report_equal( compatibility, &format!("{prefix}.tensor_count"), &report.tensor_count().to_string(), )?; require_report_equal( compatibility, &format!("{prefix}.parameter_count"), &report.parameter_count().to_string(), )?; require_report_equal( compatibility, &format!("{prefix}.quantization"), report.quantization_label(), )?; require_report_equal( compatibility, &format!("{prefix}.output_contract"), report.output_contract_label(), )?; require_report_equal( compatibility, &format!("{prefix}.tokenizer_checksum"), &hex64(report.tokenizer_checksum()), )?; require_report_equal( compatibility, &format!("{prefix}.tensor_layout_checksum"), &hex64(report.tensor_layout_checksum()), )?; Ok(()) } pub(crate) fn parse_passing_compatibility(text: &str) -> io::Result> { let fields = parse_manifest(text, "compatibility")?; require_equal( &fields, "tinyrustlm_parent_compatibility_version", COMPATIBILITY_VERSION, )?; require_equal(&fields, "compatibility_result", "pass")?; require_equal(&fields, "compatible_parent_set", "true")?; require_equal(&fields, "parent_count", "2")?; require_equal(&fields, "compatibility_reasons", "all-compatible")?; require_equal( &fields, "decision", "accepted-parent-set-for-offline-operators", )?; Ok(fields) } pub(crate) struct ParsedModel { pub(crate) shape: ModelShape, pub(crate) flags: u32, pub(crate) tokenizer: TokenizerSection, pub(crate) tensors: Vec, } pub(crate) struct ParsedTensor { pub(crate) spec: TensorSpec, pub(crate) values: Vec, } struct Header { flags: u32, vocab_size: u32, special_token_count: u32, hidden_size: u32, layer_count: u32, head_count: u32, kv_head_count: u32, head_dim: u32, ffn_size: u32, max_context: u32, tokenizer_offset: u64, tokenizer_length: u64, tensor_directory_offset: u64, tensor_count: u32, } struct TensorEntry { spec: TensorSpec, byte_offset: u64, byte_length: u64, scale_offset: u64, } pub(crate) fn parse_model_values(bytes: &[u8]) -> io::Result { let header = parse_header(bytes)?; let tokenizer = tokenizer_section(bytes, &header)?; let entries = parse_tensor_entries(bytes, &header)?; let mut tensors = Vec::with_capacity(entries.len()); for entry in entries { let values = read_tensor_values(bytes, &entry)?; tensors.push(ParsedTensor { spec: entry.spec, values, }); } Ok(ParsedModel { shape: ModelShape { vocab_size: header.vocab_size, special_token_count: header.special_token_count, hidden_size: header.hidden_size, layer_count: header.layer_count, head_count: header.head_count, kv_head_count: header.kv_head_count, head_dim: header.head_dim, ffn_size: header.ffn_size, max_context: header.max_context, }, flags: header.flags, tokenizer, tensors, }) } fn parse_header(bytes: &[u8]) -> io::Result
    { if bytes.get(0..4) != Some(b"SLM1") { return Err(invalid("blend parent has invalid SLM magic")); } Ok(Header { flags: read_u32(bytes, 16)?, vocab_size: read_u32(bytes, 20)?, special_token_count: read_u32(bytes, 24)?, hidden_size: read_u32(bytes, 28)?, layer_count: read_u32(bytes, 32)?, head_count: read_u32(bytes, 36)?, kv_head_count: read_u32(bytes, 40)?, head_dim: read_u32(bytes, 44)?, ffn_size: read_u32(bytes, 48)?, max_context: read_u32(bytes, 52)?, tokenizer_offset: read_u64(bytes, 64)?, tokenizer_length: read_u64(bytes, 72)?, tensor_directory_offset: read_u64(bytes, 80)?, tensor_count: read_u32(bytes, 88)?, }) } fn tokenizer_section(bytes: &[u8], header: &Header) -> io::Result { let start = as_usize(header.tokenizer_offset)?; let len = as_usize(header.tokenizer_length)?; let end = start .checked_add(len) .ok_or_else(|| invalid("tokenizer range overflow"))?; let tokenizer = bytes .get(start..end) .ok_or_else(|| invalid("tokenizer range escapes blend parent"))?; Ok(TokenizerSection { bytes: tokenizer.to_vec(), }) } fn parse_tensor_entries(bytes: &[u8], header: &Header) -> io::Result> { let start = as_usize(header.tensor_directory_offset)?; let mut tensors = Vec::with_capacity(header.tensor_count as usize); for index in 0..header.tensor_count as usize { let base = start .checked_add(index * 64) .ok_or_else(|| invalid("tensor directory offset overflow"))?; let spec = TensorSpec { name_hash: read_u64(bytes, base)?, dtype: read_u32(bytes, base + 8)?, rank: read_u32(bytes, base + 12)?, dims: [ read_u32(bytes, base + 16)?, read_u32(bytes, base + 20)?, read_u32(bytes, base + 24)?, read_u32(bytes, base + 28)?, ], seed: 0, block_size: read_u32(bytes, base + 56)?, }; tensors.push(TensorEntry { spec, byte_offset: read_u64(bytes, base + 32)?, byte_length: read_u64(bytes, base + 40)?, scale_offset: read_u64(bytes, base + 48)?, }); } Ok(tensors) } fn read_tensor_values(bytes: &[u8], entry: &TensorEntry) -> io::Result> { match entry.spec.dtype { DTYPE_F32 => read_f32_values(bytes, entry), DTYPE_Q8_0 => read_q8_values(bytes, entry), DTYPE_Q4_0 => read_q4_values(bytes, entry), _ => Err(invalid("blend parent uses unsupported tensor dtype")), } } fn read_f32_values(bytes: &[u8], entry: &TensorEntry) -> io::Result> { let start = as_usize(entry.byte_offset)?; let len = as_usize(entry.byte_length)?; let payload = bytes .get(start..start + len) .ok_or_else(|| invalid("f32 tensor payload escapes blend parent"))?; let mut values = Vec::with_capacity(payload.len() / 4); for chunk in payload.chunks_exact(4) { values.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])); } Ok(values) } fn read_q8_values(bytes: &[u8], entry: &TensorEntry) -> io::Result> { let rows = entry.spec.rows(); let cols = entry.spec.cols_per_row(); let start = as_usize(entry.byte_offset)?; let scale_start = as_usize(entry.scale_offset)?; let payload = bytes .get(start..start + rows * cols) .ok_or_else(|| invalid("q8 tensor payload escapes blend parent"))?; let scales = bytes .get(scale_start..scale_start + rows * 4) .ok_or_else(|| invalid("q8 scale payload escapes blend parent"))?; let mut values = Vec::with_capacity(rows * cols); for row in 0..rows { let scale = read_f32_at(scales, row * 4)?; for col in 0..cols { let quantized = payload[row * cols + col] as i8; values.push(quantized as f32 * scale); } } Ok(values) } fn read_q4_values(bytes: &[u8], entry: &TensorEntry) -> io::Result> { let rows = entry.spec.rows(); let cols = entry.spec.cols_per_row(); let block = entry.spec.block_size as usize; if block == 0 || cols % block != 0 { return Err(invalid("q4 tensor block layout is invalid for blending")); } let blocks_per_row = cols / block; let start = as_usize(entry.byte_offset)?; let scale_start = as_usize(entry.scale_offset)?; let payload_len = rows .checked_mul(cols) .and_then(|elements| elements.checked_div(2)) .ok_or_else(|| invalid("q4 tensor payload length overflow"))?; let payload = bytes .get(start..start + payload_len) .ok_or_else(|| invalid("q4 tensor payload escapes blend parent"))?; let scale_len = rows .checked_mul(blocks_per_row) .and_then(|scales| scales.checked_mul(4)) .ok_or_else(|| invalid("q4 scale payload length overflow"))?; let scales = bytes .get(scale_start..scale_start + scale_len) .ok_or_else(|| invalid("q4 scale payload escapes blend parent"))?; let mut values = Vec::with_capacity(rows * cols); for row in 0..rows { for block_index in 0..blocks_per_row { let scale = read_f32_at(scales, (row * blocks_per_row + block_index) * 4)?; for col in 0..block { let absolute_col = block_index * block + col; let byte = payload[(row * cols + absolute_col) / 2]; let nibble = if absolute_col % 2 == 0 { byte & 0x0f } else { byte >> 4 }; values.push(sign_extend_q4(nibble) as f32 * scale); } } } Ok(values) } pub(crate) fn require_same_tensor_spec(left: &TensorSpec, right: &TensorSpec) -> io::Result<()> { if left.name_hash != right.name_hash || left.dtype != right.dtype || left.rank != right.rank || left.dims != right.dims || left.block_size != right.block_size { return Err(invalid("blend parents have different tensor layouts")); } Ok(()) } pub(crate) fn same_shape(left: &ModelShape, right: &ModelShape) -> bool { left.vocab_size == right.vocab_size && left.special_token_count == right.special_token_count && left.hidden_size == right.hidden_size && left.layer_count == right.layer_count && left.head_count == right.head_count && left.kv_head_count == right.kv_head_count && left.head_dim == right.head_dim && left.ffn_size == right.ffn_size && left.max_context == right.max_context } pub(crate) fn parse_manifest(text: &str, label: &str) -> io::Result> { let mut fields = HashMap::new(); for (line_index, raw_line) in text.lines().enumerate() { let line = raw_line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let Some((key, value)) = line.split_once('=') else { return Err(invalid(&format!( "{label} line {} is missing '='", line_index + 1 ))); }; let key = key.trim(); let value = value.trim(); if key.is_empty() || !key .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_')) { return Err(invalid(&format!( "{label} line {} has an invalid key", line_index + 1 ))); } if value.is_empty() || value.contains('\n') || value.contains('\r') { return Err(invalid(&format!("{key} has an invalid value"))); } if fields.insert(key.to_string(), value.to_string()).is_some() { return Err(invalid(&format!("duplicate {label} key {key}"))); } } Ok(fields) } fn parse_weight_ppm(value: &str) -> io::Result { let weight = value .parse::() .map_err(|_| invalid("blend weight must be an integer parts-per-million value"))?; if weight > PPM_DENOMINATOR { return Err(invalid("blend weight must be between 0 and 1000000")); } Ok(weight) } pub(crate) fn require_key<'a>( fields: &'a HashMap, key: &str, ) -> io::Result<&'a str> { fields .get(key) .map(String::as_str) .ok_or_else(|| invalid(&format!("manifest missing required key {key}"))) } pub(crate) fn require_equal( fields: &HashMap, key: &str, expected: &str, ) -> io::Result<()> { let actual = require_key(fields, key)?; if actual != expected { return Err(invalid(&format!( "manifest key {key} was {actual}, expected {expected}" ))); } Ok(()) } pub(crate) fn require_report_equal( fields: &HashMap, key: &str, expected: &str, ) -> io::Result<()> { let actual = require_key(fields, key)?; if actual != expected { return Err(invalid(&format!( "operator expected {key} {actual}, current artifact has {expected}" ))); } Ok(()) } fn read_u32(bytes: &[u8], offset: usize) -> io::Result { let end = offset .checked_add(4) .ok_or_else(|| invalid("u32 offset overflow"))?; let slice = bytes .get(offset..end) .ok_or_else(|| invalid("unexpected end while reading u32"))?; Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) } fn read_u64(bytes: &[u8], offset: usize) -> io::Result { let end = offset .checked_add(8) .ok_or_else(|| invalid("u64 offset overflow"))?; let slice = bytes .get(offset..end) .ok_or_else(|| invalid("unexpected end while reading u64"))?; Ok(u64::from_le_bytes([ slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7], ])) } fn read_f32_at(bytes: &[u8], offset: usize) -> io::Result { let end = offset .checked_add(4) .ok_or_else(|| invalid("f32 offset overflow"))?; let slice = bytes .get(offset..end) .ok_or_else(|| invalid("unexpected end while reading f32"))?; Ok(f32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) } fn sign_extend_q4(nibble: u8) -> i8 { if nibble & 0x08 != 0 { (nibble as i8) - 16 } else { nibble as i8 } } fn as_usize(value: u64) -> io::Result { usize::try_from(value).map_err(|_| invalid("value does not fit in usize")) } pub(crate) fn push_line(text: &mut String, key: &str, value: &str) { text.push_str(key); text.push('='); text.push_str(value); text.push('\n'); } pub(crate) fn hex64(value: u64) -> String { format!("0x{value:016x}") } pub(crate) fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } #[cfg(test)] mod tests { use super::*; use crate::compatibility; use crate::tensor_writer::{tiny_fixture_tensors, tiny_fixture_tensors_with_dtype, DTYPE_Q8_0}; use crate::tokenizer_writer::ByteTokenizerSection; use crate::{build_model_file, build_model_file_from_values_with_flags, fixture_value}; #[test] fn writes_and_validates_weighted_f32_blend_candidate() { let left = tiny_f32_scaled_bytes(1.0); let right = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "blend-f32", "average-v1", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", "candidate.slm", 250_000, ) .unwrap(); validate_candidate_text( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); let parsed = parse_model_values(&candidate).unwrap(); assert_eq!(parsed.tensors[0].values[0], 0.3125); assert!(receipt.contains("operator_kind=direct-parameter-weighted-average")); assert!(receipt.contains("parent.0.weight_ppm=250000")); assert!(receipt.contains("parent.1.weight_ppm=750000")); } #[test] fn writes_and_validates_q8_blend_candidate() { let left = tiny_q8_bytes(); let right = tiny_q8_bytes(); let compatibility = compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "blend-q8", "average-v1", "tiny").unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", "candidate.slm", 500_000, ) .unwrap(); slm_validate::validate_bytes(&candidate, "candidate.slm").unwrap(); validate_candidate_text( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); assert!(receipt.contains("candidate_quantization=q8_0")); } #[test] fn rejects_parent_checksum_drift() { let left = tiny_f32_scaled_bytes(1.0); let right = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "blend-f32", "average-v1", "tiny") .unwrap(); let changed_left = tiny_f32_scaled_bytes(2.0); let error = build_candidate_bytes_and_receipt( &compatibility, &lineage, &changed_left, "left.slm", &right, "right.slm", "candidate.slm", 500_000, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("parent.0.slm_checksum")); } #[test] fn validation_rejects_candidate_drift() { let left = tiny_f32_scaled_bytes(1.0); let right = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "blend-f32", "average-v1", "tiny") .unwrap(); let (mut candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", "candidate.slm", 500_000, ) .unwrap(); let last = candidate.len() - 1; candidate[last] ^= 0x01; let error = validate_candidate_text( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", &candidate, "candidate.slm", &receipt, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate bytes")); } #[test] fn rejects_invalid_blend_weight() { let error = parse_weight_ppm("1000001").unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } fn tiny_f32_scaled_bytes(scale: f32) -> Vec { let tensors = tiny_fixture_tensors(); let values = tensors .iter() .map(|tensor| { (0..tensor.element_count()) .map(|index| fixture_value(tensor, index) * scale) .collect::>() }) .collect::>(); build_model_file_from_values_with_flags( &ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } fn tiny_q8_bytes() -> Vec { build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), &ByteTokenizerSection::phase_one(), ) .unwrap() } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/blend.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/browser_bundle.rs BYTES: 121254 SHA256: 6F558D24C1BB64BAAF92AF506FACED65BA92F350712507D0EEB5D7A287DBBEC8 ================================================================================ //! Browser-served model-breeding smoke bundles. use std::fs; use std::io; use std::path::{Path, PathBuf}; use crate::adapter; use crate::adapter_family; use crate::admission; use crate::blend::{hex64, push_line}; use crate::build_model_file_from_values_with_flags; use crate::candidate; use crate::compatibility; use crate::fixture_value; use crate::ledger; use crate::lineage; use crate::multi_admission; use crate::multi_candidate; use crate::multi_promotion; use crate::parent_pool; use crate::population; use crate::promotion; use crate::provenance; use crate::selector; use crate::sign_merge; use crate::slm_validate::{self, ValidationReport}; use crate::soup; use crate::tensor_writer::{ tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_F32, DTYPE_Q4_0, DTYPE_Q8_0, }; use crate::tokenizer_writer::ByteTokenizerSection; use crate::trained_adapter_source; use crate::trained_source; const ASSEMBLY_RECEIPT_KIND: &str = "browser-local-assembly-evidence"; const ASSEMBLY_RECEIPT_STATUS: &str = "validated"; const ASSEMBLY_REGISTRY_STATUS: &str = "receipt-validated"; const MODULE_PLAN_KIND: &str = "browser-local-module-plan"; const MODULE_PLAN_STATUS: &str = "validated"; const MODULE_PLAN_REGISTRY_STATUS: &str = "receipt-validated"; const MODULE_PLAN_STRATEGY: &str = "selector-entry-self-assembly"; const MODULE_PLAN_RESOURCE_CLASS: &str = "browser-constrained-local-assembly"; const MODULE_PLAN_PROFILE: &str = "browser-constrained-v1"; const MODULE_PLAN_EXECUTION_PROFILE: &str = "single-threaded-wasm-local-v1"; const MODULE_PLAN_FETCH_POLICY: &str = "local-no-store-v1"; const MODULE_PLAN_ORIGIN_POLICY: &str = "same-origin-loopback-local-v1"; const MODULE_PLAN_FETCH_COUNT_LIMIT: u64 = 32; const MODULE_PLAN_ROUTE_SET_VERSION: &str = "1"; const MODULE_PLAN_ROUTE_SET_CHECKSUM_ALGORITHM: &str = "tinyrustlm-text-checksum-v1"; const MODULE_PLAN_ASSEMBLY_EVIDENCE_FILE_COUNT: u64 = 9; const MODULE_PLAN_WASM_MEMORY_INITIAL_PAGES: u64 = 17; const MODULE_PLAN_WASM_EXPORT_SET: &str = "tinyrustlm-generate-v1"; const MODULE_PLAN_WASM_TRANSFER_STRATEGY: &str = "copy-then-release-v1"; const MODULE_PLAN_MODEL_RELEASE_STRATEGY: &str = "free-before-reassembly-v1"; const MODULE_PLAN_RUNTIME_RESET_STRATEGY: &str = "reset-context-before-assembly-v1"; const MODULE_PLAN_ADAPTER_VALIDATION_STRATEGY: &str = "rust-validate-before-apply-v1"; const MODULE_PLAN_WASM_HEAP_MIN_BYTES: u64 = 64 * 1024; const MODULE_PLAN_SAMPLER_CANDIDATE_CAP: u64 = 1024; const MODULE_PLAN_PROMPT_BYTE_LIMIT: u64 = 4 * 1024; const MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET: u64 = 64 * 1024; const MODULE_PLAN_OUTPUT_BYTE_LIMIT: u64 = 64 * 1024; const MODULE_PLAN_KV_CACHE_BYTE_BUDGET_LIMIT: u64 = 8 * 1024 * 1024; const MODULE_PLAN_TOTAL_BYTE_BUDGET_LIMIT: u64 = 32 * 1024 * 1024 + 1024 * 1024 + MODULE_PLAN_KV_CACHE_BYTE_BUDGET_LIMIT + 64 * 1024 + 128 * 1024 + 128 * 1024 + MODULE_PLAN_PROMPT_BYTE_LIMIT + MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET + MODULE_PLAN_OUTPUT_BYTE_LIMIT; const SOURCE_KIND: &str = "converted-trained"; const APP_FILES: [&str; 3] = ["index.html", "app.css", "app.js"]; const RUNTIME_WASM_FILE: &str = "tinyrustlm.wasm"; const RUNTIME_WASM_MANIFEST_FILE: &str = "tinyrustlm.wasm.manifest"; const RUNTIME_WASM_KIND: &str = "tinyrustlm-rust-wasm"; const RUNTIME_WASM_STATUS: &str = "validated-local-runtime"; const RUNTIME_WASM_NEXT_GATE: &str = "instantiate-wasm-runtime"; struct ParentRecord { model_path: PathBuf, admission_path: PathBuf, } struct BundleAdapterRoute { route: selector::RegistryAdapterRoute, artifact_path: PathBuf, manifest_path: PathBuf, } #[derive(Clone, Copy)] enum BundleAdapterKind { RawAdp1, SparseAsp1, SourceLowRankAlr1, } #[derive(Clone, Copy)] enum BundleOperator { SignMerge, Soup, } impl BundleOperator { // Parses the optional bundle operator flag while keeping the old sign-merge default explicit. fn from_name(name: &str) -> io::Result { match name { "sign-merge" => Ok(Self::SignMerge), "soup" => Ok(Self::Soup), _ => Err(io::Error::new( io::ErrorKind::InvalidInput, "browser-multi-parent-bundle operator must be sign-merge, soup, or mixed", )), } } // Supplies the generated model id stem used by selector registries and browser smoke keys. fn id_prefix(self) -> &'static str { match self { Self::SignMerge => "multi-parent-sign-merge", Self::Soup => "multi-parent-soup", } } // Supplies the human-readable label stem for generated browser selector entries. fn label_prefix(self) -> &'static str { match self { Self::SignMerge => "Multi-parent sign-merge", Self::Soup => "Multi-parent weighted soup", } } // Supplies the evidence filename prefix so receipts can route sign-merge and soup separately. fn evidence_prefix(self) -> &'static str { match self { Self::SignMerge => "sign-merge", Self::Soup => "soup", } } // Records the assembly strategy string that the browser validates against receipt evidence. fn assembly_strategy(self) -> &'static str { match self { Self::SignMerge => "multi-parent-sign-merge", Self::Soup => "multi-parent-weighted-soup", } } // Builds the operator-scoped evidence filename for receipts that share the same suffixes. fn evidence_file(self, suffix: &str) -> String { format!("{}.{}", self.evidence_prefix(), suffix) } // Lists the evidence files whose relative routes participate in module-plan route checksums. fn evidence_files(self) -> Vec { vec![ "population.ledger".to_string(), "population.review".to_string(), "parent-pool.recipe".to_string(), self.evidence_file("operator"), self.evidence_file("candidate"), self.evidence_file("promotion"), self.evidence_file("runtime"), self.evidence_file("eval"), self.evidence_file("multi.admission"), ] } // Dispatches bundle candidate generation to the selected parent-pool operator implementation. fn write_candidate_path( self, ledger_path: &Path, review_path: &Path, recipe_path: &Path, candidate_path: &Path, receipt_path: &Path, parent_paths: &[String], admission_paths: &[String], ) -> io::Result<()> { match self { Self::SignMerge => sign_merge::write_candidate_path( ledger_path, review_path, recipe_path, candidate_path, receipt_path, parent_paths, admission_paths, ), Self::Soup => soup::write_candidate_path( ledger_path, review_path, recipe_path, candidate_path, receipt_path, parent_paths, admission_paths, ), } } } struct BundleSpec { id: String, operator: BundleOperator, quantization: String, dtype: u32, model_file: String, self_adapter_file: String, self_adapter_label: String, family_adapter_file: String, family_adapter_label: String, sparse_adapter_file: String, sparse_adapter_label: String, low_rank_adapter_file: String, low_rank_adapter_label: String, adapter_family_receipt_file: String, adapter_family_label: String, assembly_receipt_file: String, assembly_label: String, module_plan_receipt_file: String, module_plan_label: String, } impl BundleSpec { // Derives all generated filenames and labels from the quantization lane and operator family. fn from_quantization(quantization: &str, operator: BundleOperator) -> io::Result { let dtype = match quantization { "f32" => DTYPE_F32, "q8_0" => DTYPE_Q8_0, "q4_0" => DTYPE_Q4_0, _ => { return Err(io::Error::new( io::ErrorKind::InvalidInput, "browser-multi-parent-bundle quantization must be f32, q8_0, or q4_0", )) } }; let suffix = match quantization { "f32" => "f32", "q8_0" => "q8", "q4_0" => "q4", _ => unreachable!(), }; let id = format!("{}-{suffix}", operator.id_prefix()); let label_prefix = operator.label_prefix(); Ok(Self { model_file: format!("{id}.slm"), self_adapter_file: format!("{id}-self.adp1"), self_adapter_label: format!("{label_prefix} {quantization} self ADP1"), family_adapter_file: format!("{id}-family.adp1"), family_adapter_label: format!("{label_prefix} {quantization} family ADP1"), sparse_adapter_file: format!("{id}-sparse.asp1"), sparse_adapter_label: format!("{label_prefix} {quantization} sparse ASP1"), low_rank_adapter_file: format!("{id}-low-rank.alr1"), low_rank_adapter_label: format!("{label_prefix} {quantization} source-backed ALR1"), adapter_family_receipt_file: format!("{id}.adapter-family.receipt"), adapter_family_label: format!("{label_prefix} {quantization} adapter family"), assembly_receipt_file: format!("{id}.assembly.receipt"), assembly_label: format!("{label_prefix} {quantization} assembly evidence"), module_plan_receipt_file: format!("{id}.module-plan.receipt"), module_plan_label: format!("{label_prefix} {quantization} module plan"), id, operator, quantization: quantization.to_string(), dtype, }) } } struct StagedBundleModule { admission_path: PathBuf, adapter_routes: Vec, adapter_family_route: selector::RegistryAdapterFamilyRoute, assembly_route: selector::RegistryAssemblyRoute, module_plan_route: selector::RegistryModulePlanRoute, candidate_path: PathBuf, quantization: String, } /// Writes a browser-loadable multi-parent selector registry bundle for one or all quantization modes. #[cfg(test)] pub(crate) fn write_bundle_path_with_quantization( root: &Path, quantization: &str, ) -> io::Result<()> { write_bundle_path_with_quantization_and_operator(root, quantization, "sign-merge") } /// Writes a browser-loadable multi-parent selector bundle for the selected parent-pool operator. pub(crate) fn write_bundle_path_with_quantization_and_operator( root: &Path, quantization: &str, operator: &str, ) -> io::Result<()> { let operators = bundle_operators(operator)?; let quantizations = bundle_quantizations(quantization)?; let models = root.join("models"); fs::create_dir_all(&models)?; copy_browser_surface(root)?; let mut modules = Vec::with_capacity(quantizations.len() * operators.len()); for operator in operators { for quantization in &quantizations { let spec = BundleSpec::from_quantization(quantization, operator)?; modules.push(write_bundle_module(root, &models, &spec)?); } } let registry_path = models.join("selector.registry"); let admission_paths = modules .iter() .map(|module| display_path(&module.admission_path)) .collect::>(); let adapter_routes = modules .iter() .flat_map(|module| module.adapter_routes.iter().cloned()) .collect::>(); let adapter_family_routes = modules .iter() .map(|module| module.adapter_family_route.clone()) .collect::>(); let assembly_routes = modules .iter() .map(|module| module.assembly_route.clone()) .collect::>(); let module_plan_routes = modules .iter() .map(|module| module.module_plan_route.clone()) .collect::>(); selector::write_registry_with_module_plan_routes_path( ®istry_path, &admission_paths, &adapter_routes, &adapter_family_routes, &assembly_routes, &module_plan_routes, )?; selector::validate_registry_path(®istry_path, &admission_paths)?; let quantization_labels = modules .iter() .map(|module| module.quantization.as_str()) .collect::>() .join(","); println!("SLM browser multi-parent bundle root: {}", root.display()); println!( "SLM browser multi-parent registry: {}", registry_path.display() ); println!("SLM browser multi-parent model count: {}", modules.len()); for module in &modules { println!( "SLM browser multi-parent model: {}", module.candidate_path.display() ); } println!("SLM browser multi-parent quantizations: {quantization_labels}"); Ok(()) } /// Writes a browser-loadable converted-trained selector bundle from a reviewed source directory. pub(crate) fn write_converted_trained_bundle_path( root: &Path, source_dir: &Path, quantization: &str, ) -> io::Result<()> { let quantizations = converted_trained_quantizations(quantization)?; let models = root.join("models"); let evidence_root = root.join("evidence"); fs::create_dir_all(&models)?; fs::create_dir_all(&evidence_root)?; copy_browser_surface(root)?; let mut admission_paths = Vec::with_capacity(quantizations.len()); let mut candidate_paths = Vec::with_capacity(quantizations.len()); for entry_quantization in quantizations { let (admission_path, candidate_path) = write_converted_trained_bundle_entry( &models, &evidence_root, source_dir, entry_quantization, )?; admission_paths.push(admission_path); candidate_paths.push(candidate_path); } let registry_path = models.join("selector.registry"); selector::write_registry_path(®istry_path, &admission_paths)?; selector::validate_registry_path(®istry_path, &admission_paths)?; println!( "SLM browser converted-trained bundle root: {}", root.display() ); println!( "SLM browser converted-trained registry: {}", registry_path.display() ); for candidate_path in candidate_paths { println!( "SLM browser converted-trained model: {}", candidate_path.display() ); } Ok(()) } fn write_converted_trained_bundle_entry( models: &Path, evidence_root: &Path, source_dir: &Path, quantization: &str, ) -> io::Result<(String, PathBuf)> { // Stages one converted source artifact and the evidence chain consumed by selector.registry. let candidate_id = converted_trained_candidate_id(quantization)?; let evidence = evidence_root.join(candidate_id); fs::create_dir_all(&evidence)?; let model_file = format!("{candidate_id}.slm"); let candidate_path = models.join(&model_file); let provenance_path = models.join(format!("{model_file}.manifest")); let compatibility_path = evidence.join("converted-trained.compat"); let lineage_path = evidence.join("converted-trained.lineage"); let candidate_manifest_path = evidence.join("converted-trained.candidate"); let promotion_path = evidence.join("converted-trained.promotion"); let runtime_path = evidence.join("converted-trained.runtime"); let eval_path = evidence.join("converted-trained.eval"); let admission_path = evidence.join("converted-trained.admission"); trained_source::convert_trained_path(source_dir, &candidate_path, quantization)?; provenance::validate_manifest_path(&candidate_path, &provenance_path)?; compatibility::report_path(&candidate_path, &candidate_path, Some(&compatibility_path))?; lineage::write_template_path( &compatibility_path, &lineage_path, candidate_id, "trained-source-conversion", "browser-file-backed-converted-trained", )?; candidate::write_manifest_path( &compatibility_path, &lineage_path, &candidate_path, &candidate_manifest_path, None, )?; promotion::write_template_path( &compatibility_path, &lineage_path, &candidate_path, &candidate_manifest_path, &promotion_path, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, None, )?; provenance::write_runtime_smoke_for_path(&candidate_path, &provenance_path, &runtime_path)?; let candidate_bytes = fs::read(&candidate_path)?; let report = slm_validate::validate_bytes(&candidate_bytes, &display_path(&candidate_path))?; let provenance_text = fs::read_to_string(&provenance_path)?; fs::write(&eval_path, passing_eval_text(&report, &provenance_text))?; provenance::quality_gate_path( &candidate_path, &provenance_path, "assistant-quality", Some(&eval_path), )?; admission::write_record_path( &compatibility_path, &lineage_path, &candidate_path, &candidate_manifest_path, &promotion_path, &provenance_path, &runtime_path, &eval_path, &admission_path, admission::DEFAULT_ADMISSION_SELECTOR_ID, None, )?; Ok((display_path(&admission_path), candidate_path)) } fn converted_trained_quantizations(quantization: &str) -> io::Result> { // Expands the converted-trained CLI selector into one or all browser model entries. match quantization { "f32" => Ok(vec!["f32"]), "q8_0" => Ok(vec!["q8_0"]), "q4_0" => Ok(vec!["q4_0"]), "all" => Ok(vec!["f32", "q8_0", "q4_0"]), _ => Err(io::Error::new( io::ErrorKind::InvalidInput, "browser-converted-trained-bundle quantization must be f32, q8_0, q4_0, or all", )), } } fn converted_trained_candidate_id(quantization: &str) -> io::Result<&'static str> { // Keeps generated browser model ids aligned with the quantization lane they stage. match quantization { "f32" => Ok("converted-trained-f32"), "q8_0" => Ok("converted-trained-q8"), "q4_0" => Ok("converted-trained-q4"), _ => Err(io::Error::new( io::ErrorKind::InvalidInput, "converted-trained candidate quantization must be f32, q8_0, or q4_0", )), } } fn bundle_operators(operator: &str) -> io::Result> { // Expands the CLI operator selector into one or more browser-visible families. if operator == "mixed" { return Ok(vec![BundleOperator::SignMerge, BundleOperator::Soup]); } Ok(vec![BundleOperator::from_name(operator)?]) } fn bundle_quantizations(quantization: &str) -> io::Result> { match quantization { "f32" => Ok(vec!["f32"]), "q8_0" => Ok(vec!["q8_0"]), "q4_0" => Ok(vec!["q4_0"]), "all" => Ok(vec!["f32", "q8_0", "q4_0"]), _ => Err(io::Error::new( io::ErrorKind::InvalidInput, "browser-multi-parent-bundle quantization must be f32, q8_0, q4_0, or all", )), } } fn write_bundle_module( root: &Path, models: &Path, spec: &BundleSpec, ) -> io::Result { let evidence = root.join("evidence").join(&spec.id); let parents = evidence.join("parents"); let admissions = evidence.join("admissions"); fs::create_dir_all(&parents)?; fs::create_dir_all(&admissions)?; let parent_specs = [ (spec.id.as_str(), 0.0f32), ("multi-parent-synthetic-beta", 0.000_001f32), ("multi-parent-synthetic-gamma", 0.000_002f32), ]; let mut parent_records = Vec::with_capacity(parent_specs.len()); for (candidate_id, offset) in parent_specs { let model_path = parents.join(format!("{candidate_id}.slm")); let bytes = tiny_fixture_bytes_with_offset(spec.dtype, offset)?; fs::write(&model_path, &bytes)?; let admission_text = parent_admission_text(candidate_id, &display_path(&model_path), &bytes)?; let admission_path = admissions.join(format!("{candidate_id}.admission")); fs::write(&admission_path, admission_text)?; parent_records.push(ParentRecord { model_path, admission_path, }); } let admission_paths = paths_as_strings(parent_records.iter().map(|record| &record.admission_path)); let parent_paths = paths_as_strings(parent_records.iter().map(|record| &record.model_path)); let ledger_path = evidence.join("population.ledger"); let review_path = evidence.join("population.review"); let recipe_path = evidence.join("parent-pool.recipe"); let candidate_path = models.join(&spec.model_file); let receipt_path = evidence.join(spec.operator.evidence_file("operator")); let multi_candidate_path = evidence.join(spec.operator.evidence_file("candidate")); let promotion_path = evidence.join(spec.operator.evidence_file("promotion")); let provenance_path = models.join(format!("{}.manifest", spec.model_file)); let runtime_path = evidence.join(spec.operator.evidence_file("runtime")); let eval_path = evidence.join(spec.operator.evidence_file("eval")); let multi_admission_path = evidence.join(spec.operator.evidence_file("multi.admission")); ledger::write_ledger_path(&ledger_path, &admission_paths)?; population::write_review_path(&ledger_path, &review_path, &admission_paths)?; parent_pool::write_recipe_path(&ledger_path, &review_path, &recipe_path, &admission_paths)?; spec.operator.write_candidate_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &parent_paths, &admission_paths, )?; multi_candidate::write_manifest_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &multi_candidate_path, &parent_paths, &admission_paths, )?; multi_promotion::write_template_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &multi_candidate_path, &promotion_path, &parent_paths, &admission_paths, )?; provenance::write_manifest_for_path(&candidate_path, &provenance_path, SOURCE_KIND)?; provenance::write_runtime_smoke_for_path(&candidate_path, &provenance_path, &runtime_path)?; let candidate_bytes = fs::read(&candidate_path)?; let report = slm_validate::validate_bytes(&candidate_bytes, &display_path(&candidate_path))?; let provenance_text = fs::read_to_string(&provenance_path)?; let eval_text = passing_eval_text(&report, &provenance_text); fs::write(&eval_path, eval_text)?; provenance::quality_gate_path( &candidate_path, &provenance_path, "assistant-quality", Some(&eval_path), )?; multi_admission::write_record_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &multi_candidate_path, &promotion_path, &provenance_path, &runtime_path, &eval_path, &multi_admission_path, &parent_paths, &admission_paths, )?; let bundle_adapter_routes = write_bundle_adapter_routes(&spec, &candidate_path, &models, &evidence)?; let adapter_routes = bundle_adapter_routes .iter() .map(|route| route.route.clone()) .collect::>(); let adapter_family_inputs = bundle_adapter_routes .iter() .map(|route| adapter_family::AdapterFamilyInput { route: &route.route, manifest_path: &route.manifest_path, }) .collect::>(); let adapter_family_receipt_path = models.join(&spec.adapter_family_receipt_file); let adapter_family_route = adapter_family::write_receipt_path( &spec.id, &spec.adapter_family_label, &format!("../models/{}", spec.adapter_family_receipt_file), &adapter_family_receipt_path, &adapter_family_inputs, )?; adapter_family::validate_receipt_path(&adapter_family_receipt_path, &adapter_family_inputs)?; let assembly_receipt_path = models.join(&spec.assembly_receipt_file); let assembly_route = write_bundle_assembly_receipt( &spec, &assembly_receipt_path, &report, &ledger_path, &review_path, &recipe_path, &receipt_path, &multi_candidate_path, &promotion_path, &provenance_path, &runtime_path, &eval_path, &multi_admission_path, &adapter_family_route, )?; let module_plan_receipt_path = models.join(&spec.module_plan_receipt_file); let module_plan_route = write_bundle_module_plan_receipt( &spec, &module_plan_receipt_path, &report, &provenance_path, &receipt_path, &assembly_receipt_path, &adapter_family_receipt_path, &bundle_adapter_routes, &adapter_family_route, &assembly_route, )?; Ok(StagedBundleModule { admission_path: multi_admission_path, adapter_routes, adapter_family_route, assembly_route, module_plan_route, candidate_path, quantization: spec.quantization.clone(), }) } fn write_bundle_module_plan_receipt( spec: &BundleSpec, receipt_path: &Path, report: &ValidationReport, provenance_manifest_path: &Path, operator_receipt_path: &Path, assembly_receipt_path: &Path, adapter_family_receipt_path: &Path, bundle_adapter_routes: &[BundleAdapterRoute], adapter_family_route: &selector::RegistryAdapterFamilyRoute, assembly_route: &selector::RegistryAssemblyRoute, ) -> io::Result { let route = format!("../models/{}", spec.module_plan_receipt_file); let model_path = format!("../models/{}", spec.model_file); let manifest_path = format!("../models/{}.manifest", spec.model_file); let model_checksum = hex64(report.checksum()); let tokenizer_checksum = hex64(report.tokenizer_checksum()); let model_byte_budget = u64::try_from(report.file_bytes()) .map_err(|_| invalid("module plan model byte budget overflow"))?; let adapter_byte_budget = adapter_family_route.auto_apply_byte_budget; let context_token_limit = u64::from(report.context_token_limit()); let kv_cache_byte_budget = report.kv_cache_byte_budget()?; let kv_cache_page_count = report.kv_cache_page_count()?; if kv_cache_byte_budget > MODULE_PLAN_KV_CACHE_BYTE_BUDGET_LIMIT { return Err(invalid("module plan kv cache byte budget exceeds limit")); } let manifest_byte_count = file_byte_count(provenance_manifest_path)?; let assembly_receipt_byte_count = file_byte_count(assembly_receipt_path)?; let adapter_family_receipt_byte_count = file_byte_count(adapter_family_receipt_path)?; let manifest_checksum = text_file_checksum(provenance_manifest_path)?; let operator_receipt_file = spec.operator.evidence_file("operator"); let operator_receipt_route = evidence_route(spec, &operator_receipt_file); let operator_receipt_checksum = text_file_checksum(operator_receipt_path)?; let stack_indexes = bundle_auto_apply_stack_indexes(bundle_adapter_routes.len()); let adapter_validation_count = u64::try_from(stack_indexes.len()) .map_err(|_| invalid("module plan adapter validation count overflow"))?; let adapter_apply_count = adapter_validation_count; let adapter_manifest_fetch_count = u64::try_from(adapter_family_route.adapter_count) .map_err(|_| invalid("module plan planned fetch count overflow"))?; let module_count = 4usize .checked_add(stack_indexes.len()) .ok_or_else(|| invalid("module plan count overflow"))?; if module_count != 4 + adapter_family_route.auto_apply_stack_count { return Err(invalid( "module plan adapter stack count must match adapter family route", )); } let stack_byte_counts = module_plan_stack_byte_counts(&stack_indexes, bundle_adapter_routes)?; let adapter_stack_byte_budget = stack_byte_counts .iter() .try_fold(0u64, |total, byte_count| { total .checked_add(*byte_count) .ok_or_else(|| invalid("module plan adapter stack byte budget overflow")) })?; let wasm_heap_min_bytes = module_plan_wasm_heap_min_bytes( model_byte_budget, adapter_stack_byte_budget, MODULE_PLAN_PROMPT_BYTE_LIMIT, ); let total_byte_budget = module_plan_total_byte_budget( model_byte_budget, kv_cache_byte_budget, manifest_byte_count, assembly_receipt_byte_count, adapter_family_receipt_byte_count, &stack_byte_counts, )?; let planned_fetch_count = module_plan_planned_fetch_count(module_count, adapter_manifest_fetch_count)?; let route_set_checksum = module_plan_route_set_checksum( spec, &route, &model_path, &manifest_path, &assembly_route.receipt_path, &adapter_family_route.receipt_path, bundle_adapter_routes, &stack_indexes, )?; let mut text = String::new(); push_line(&mut text, "tinyrustlm_module_plan_version", "1"); push_line(&mut text, "module_plan_kind", MODULE_PLAN_KIND); push_line(&mut text, "module_plan_status", MODULE_PLAN_STATUS); push_line(&mut text, "module_plan_strategy", MODULE_PLAN_STRATEGY); push_line(&mut text, "candidate_id", &spec.id); push_line(&mut text, "module_plan_label", &spec.module_plan_label); push_line(&mut text, "module_plan_path", &route); push_line( &mut text, "module_plan_resource_class", MODULE_PLAN_RESOURCE_CLASS, ); push_line(&mut text, "module_plan_profile", MODULE_PLAN_PROFILE); push_line( &mut text, "module_plan_execution_profile", MODULE_PLAN_EXECUTION_PROFILE, ); push_line( &mut text, "module_plan_fetch_policy", MODULE_PLAN_FETCH_POLICY, ); push_line( &mut text, "module_plan_origin_policy", MODULE_PLAN_ORIGIN_POLICY, ); push_line( &mut text, "module_plan_fetch_count_limit", &MODULE_PLAN_FETCH_COUNT_LIMIT.to_string(), ); push_line( &mut text, "module_plan_planned_fetch_count", &planned_fetch_count.to_string(), ); push_line( &mut text, "module_plan_route_set_version", MODULE_PLAN_ROUTE_SET_VERSION, ); push_line( &mut text, "module_plan_route_set_checksum_algorithm", MODULE_PLAN_ROUTE_SET_CHECKSUM_ALGORITHM, ); push_line( &mut text, "module_plan_route_set_checksum", &route_set_checksum, ); push_line(&mut text, "operator_receipt_path", &operator_receipt_route); push_line( &mut text, "operator_receipt_checksum", &operator_receipt_checksum, ); // The page count mirrors the runtime's exported linear-memory size before init. push_line( &mut text, "module_plan_wasm_memory_initial_pages", &MODULE_PLAN_WASM_MEMORY_INITIAL_PAGES.to_string(), ); push_line( &mut text, "module_plan_wasm_export_set", MODULE_PLAN_WASM_EXPORT_SET, ); push_line( &mut text, "module_plan_wasm_transfer_strategy", MODULE_PLAN_WASM_TRANSFER_STRATEGY, ); push_line( &mut text, "module_plan_model_release_strategy", MODULE_PLAN_MODEL_RELEASE_STRATEGY, ); push_line( &mut text, "module_plan_runtime_reset_strategy", MODULE_PLAN_RUNTIME_RESET_STRATEGY, ); push_line( &mut text, "module_plan_adapter_validation_strategy", MODULE_PLAN_ADAPTER_VALIDATION_STRATEGY, ); push_line( &mut text, "module_plan_adapter_validation_count", &adapter_validation_count.to_string(), ); push_line( &mut text, "module_plan_adapter_apply_count", &adapter_apply_count.to_string(), ); push_line( &mut text, "module_plan_wasm_heap_min_bytes", &wasm_heap_min_bytes.to_string(), ); push_line( &mut text, "module_plan_context_token_limit", &context_token_limit.to_string(), ); push_line( &mut text, "module_plan_sampler_candidate_cap", &MODULE_PLAN_SAMPLER_CANDIDATE_CAP.to_string(), ); push_line( &mut text, "module_plan_tokenizer_checksum", &tokenizer_checksum, ); push_line( &mut text, "module_plan_prompt_byte_limit", &MODULE_PLAN_PROMPT_BYTE_LIMIT.to_string(), ); push_line( &mut text, "module_plan_model_byte_budget", &model_byte_budget.to_string(), ); push_line( &mut text, "module_plan_adapter_byte_budget", &adapter_byte_budget.to_string(), ); push_line( &mut text, "module_plan_adapter_stack_byte_budget", &adapter_stack_byte_budget.to_string(), ); push_line( &mut text, "module_plan_runtime_scratch_byte_budget", &MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET.to_string(), ); push_line( &mut text, "module_plan_output_byte_limit", &MODULE_PLAN_OUTPUT_BYTE_LIMIT.to_string(), ); push_line( &mut text, "module_plan_kv_cache_byte_budget", &kv_cache_byte_budget.to_string(), ); push_line( &mut text, "module_plan_kv_cache_page_count", &kv_cache_page_count.to_string(), ); push_line( &mut text, "module_plan_total_byte_budget", &total_byte_budget.to_string(), ); push_line( &mut text, "module_plan_total_byte_budget_limit", &MODULE_PLAN_TOTAL_BYTE_BUDGET_LIMIT.to_string(), ); push_line(&mut text, "model_path", &model_path); push_line(&mut text, "manifest_path", &manifest_path); push_line(&mut text, "quantization", &spec.quantization); push_line(&mut text, "model_checksum", &model_checksum); push_line(&mut text, "manifest_checksum", &manifest_checksum); push_line( &mut text, "assembly_receipt_path", &assembly_route.receipt_path, ); push_line( &mut text, "assembly_receipt_checksum", &assembly_route.receipt_checksum, ); push_line( &mut text, "adapter_family_receipt_path", &adapter_family_route.receipt_path, ); push_line( &mut text, "adapter_family_receipt_checksum", &adapter_family_route.receipt_checksum, ); push_line( &mut text, "adapter_auto_apply_stack_count", &stack_indexes.len().to_string(), ); push_line(&mut text, "module_count", &module_count.to_string()); push_module_plan_line( &mut text, 0, "model", "runtime-model", "runtime-model", "load-model-bytes", "runtime-wasm", &model_path, &model_checksum, model_byte_budget, ); push_module_plan_line( &mut text, 1, "model-manifest", "model-manifest", "model-provenance-manifest", "verify-model-manifest", "module.0", &manifest_path, &manifest_checksum, manifest_byte_count, ); push_module_plan_line( &mut text, 2, "assembly-receipt", "assembly-receipt", "assembly-evidence", "verify-assembly-evidence", "module.1", &assembly_route.receipt_path, &assembly_route.receipt_checksum, assembly_receipt_byte_count, ); push_module_plan_line( &mut text, 3, "adapter-family-receipt", "adapter-family-receipt", "adapter-family", "verify-adapter-family", "module.2", &adapter_family_route.receipt_path, &adapter_family_route.receipt_checksum, adapter_family_receipt_byte_count, ); for (stack_position, adapter_index) in stack_indexes.iter().enumerate() { let module_index = stack_position + 4; let bundle_route = &bundle_adapter_routes[*adapter_index]; let route = &bundle_route.route; let prefix = format!("module.{module_index}"); let depends_on = if stack_position == 0 { "module.3".to_string() } else { format!("module.{}", module_index - 1) }; let artifact_byte_count = stack_byte_counts[stack_position]; push_line(&mut text, &format!("{prefix}.kind"), "adapter-stack-member"); push_line( &mut text, &format!("{prefix}.assembly_slot"), &format!("adapter-stack-{stack_position}"), ); push_line( &mut text, &format!("{prefix}.role"), module_plan_adapter_role(&route.adapter_path), ); push_line( &mut text, &format!("{prefix}.phase"), &format!("apply-adapter-stack-{stack_position}"), ); push_line(&mut text, &format!("{prefix}.depends_on"), &depends_on); push_line( &mut text, &format!("{prefix}.byte_count"), &artifact_byte_count.to_string(), ); push_line( &mut text, &format!("{prefix}.checksum"), &route.artifact_checksum, ); push_line( &mut text, &format!("{prefix}.adapter_index"), &adapter_index.to_string(), ); push_line( &mut text, &format!("{prefix}.adapter_path"), &route.adapter_path, ); push_line( &mut text, &format!("{prefix}.manifest_path"), &route.manifest_path, ); push_line( &mut text, &format!("{prefix}.artifact_checksum"), &route.artifact_checksum, ); push_line( &mut text, &format!("{prefix}.manifest_checksum"), &route.manifest_checksum, ); } fs::write(receipt_path, &text)?; Ok(selector::RegistryModulePlanRoute { candidate_id: spec.id.clone(), receipt_path: route, label: spec.module_plan_label.clone(), status: MODULE_PLAN_REGISTRY_STATUS.to_string(), kind: MODULE_PLAN_KIND.to_string(), strategy: MODULE_PLAN_STRATEGY.to_string(), resource_class: MODULE_PLAN_RESOURCE_CLASS.to_string(), profile: MODULE_PLAN_PROFILE.to_string(), execution_profile: MODULE_PLAN_EXECUTION_PROFILE.to_string(), fetch_policy: MODULE_PLAN_FETCH_POLICY.to_string(), origin_policy: MODULE_PLAN_ORIGIN_POLICY.to_string(), fetch_count_limit: MODULE_PLAN_FETCH_COUNT_LIMIT, planned_fetch_count, route_set_version: MODULE_PLAN_ROUTE_SET_VERSION.to_string(), route_set_checksum_algorithm: MODULE_PLAN_ROUTE_SET_CHECKSUM_ALGORITHM.to_string(), route_set_checksum, operator_receipt_path: operator_receipt_route, operator_receipt_checksum, wasm_memory_initial_pages: MODULE_PLAN_WASM_MEMORY_INITIAL_PAGES, wasm_export_set: MODULE_PLAN_WASM_EXPORT_SET.to_string(), wasm_transfer_strategy: MODULE_PLAN_WASM_TRANSFER_STRATEGY.to_string(), model_release_strategy: MODULE_PLAN_MODEL_RELEASE_STRATEGY.to_string(), runtime_reset_strategy: MODULE_PLAN_RUNTIME_RESET_STRATEGY.to_string(), adapter_validation_strategy: MODULE_PLAN_ADAPTER_VALIDATION_STRATEGY.to_string(), adapter_validation_count, adapter_apply_count, wasm_heap_min_bytes, context_token_limit, sampler_candidate_cap: MODULE_PLAN_SAMPLER_CANDIDATE_CAP, tokenizer_checksum, prompt_byte_limit: MODULE_PLAN_PROMPT_BYTE_LIMIT, model_byte_budget, adapter_byte_budget, adapter_stack_byte_budget, runtime_scratch_byte_budget: MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET, output_byte_limit: MODULE_PLAN_OUTPUT_BYTE_LIMIT, kv_cache_byte_budget, kv_cache_page_count, total_byte_budget, total_byte_budget_limit: MODULE_PLAN_TOTAL_BYTE_BUDGET_LIMIT, receipt_checksum: hex64(provenance::text_checksum(text.as_bytes())), module_count, }) } // Computes the exact staged adapter artifact bytes used by module-plan totals. fn module_plan_stack_byte_counts( stack_indexes: &[usize], bundle_adapter_routes: &[BundleAdapterRoute], ) -> io::Result> { let mut byte_counts = Vec::with_capacity(stack_indexes.len()); for adapter_index in stack_indexes { byte_counts.push(file_byte_count( &bundle_adapter_routes[*adapter_index].artifact_path, )?); } Ok(byte_counts) } fn module_plan_wasm_heap_min_bytes( model_byte_budget: u64, adapter_stack_byte_budget: u64, prompt_byte_limit: u64, ) -> u64 { // Mirrors the browser allocation probe floor before generated bytes enter WASM. MODULE_PLAN_WASM_HEAP_MIN_BYTES .max(model_byte_budget) .max(adapter_stack_byte_budget) .max(prompt_byte_limit) } fn module_plan_planned_fetch_count( module_count: usize, adapter_manifest_fetch_count: u64, ) -> io::Result { // Counts generated self-assembly fetches across the receipt, modules, // evidence files, and adapter manifests. let module_count = u64::try_from(module_count) .map_err(|_| invalid("module plan planned fetch count overflow"))?; module_count .checked_add(1) .and_then(|value| value.checked_add(MODULE_PLAN_ASSEMBLY_EVIDENCE_FILE_COUNT)) .and_then(|value| value.checked_add(adapter_manifest_fetch_count)) .ok_or_else(|| invalid("module plan planned fetch count overflow")) } fn module_plan_route_set_checksum( spec: &BundleSpec, module_plan_path: &str, model_path: &str, manifest_path: &str, assembly_path: &str, adapter_family_path: &str, bundle_adapter_routes: &[BundleAdapterRoute], stack_indexes: &[usize], ) -> io::Result { // Mirrors the browser's generated self-assembly fetch classes in route order. let evidence_files = spec.operator.evidence_files(); let evidence_count = u64::try_from(evidence_files.len()) .map_err(|_| invalid("module plan route set evidence count overflow"))?; if evidence_count != MODULE_PLAN_ASSEMBLY_EVIDENCE_FILE_COUNT { return Err(invalid("module plan route set evidence count mismatch")); } let mut routes = Vec::new(); module_plan_push_route(&mut routes, "module-plan-receipt", module_plan_path); module_plan_push_route(&mut routes, "model", model_path); module_plan_push_route(&mut routes, "model-manifest", manifest_path); module_plan_push_route(&mut routes, "assembly-receipt", assembly_path); for file_name in evidence_files { module_plan_push_route( &mut routes, "assembly-evidence", &evidence_route(spec, &file_name), ); } module_plan_push_route(&mut routes, "adapter-family-receipt", adapter_family_path); for bundle_route in bundle_adapter_routes { module_plan_push_route( &mut routes, "adapter-manifest", &bundle_route.route.manifest_path, ); } for adapter_index in stack_indexes { let Some(bundle_route) = bundle_adapter_routes.get(*adapter_index) else { return Err(invalid("module plan route set adapter index is invalid")); }; module_plan_push_route( &mut routes, "adapter-stack-artifact", &bundle_route.route.adapter_path, ); } Ok(module_plan_checksum_for_routes(&routes)) } fn module_plan_push_route(routes: &mut Vec<(String, String)>, kind: &str, path: &str) { // Stores route metadata as owned text so generated evidence paths remain stable. routes.push((kind.to_string(), path.to_string())); } fn module_plan_checksum_for_routes(routes: &[(String, String)]) -> String { // Hashes the canonical route-list text used by selector and browser validation. let mut text = String::new(); push_line( &mut text, "route_set_version", MODULE_PLAN_ROUTE_SET_VERSION, ); push_line( &mut text, "route_set_checksum_algorithm", MODULE_PLAN_ROUTE_SET_CHECKSUM_ALGORITHM, ); push_line(&mut text, "route_count", &routes.len().to_string()); for (index, (kind, path)) in routes.iter().enumerate() { push_line(&mut text, &format!("route.{index}.kind"), kind); push_line(&mut text, &format!("route.{index}.path"), path); } hex64(provenance::text_checksum(text.as_bytes())) } // Builds the browser-local assembly envelope from exact staged modules plus runtime scratch. fn module_plan_total_byte_budget( model_byte_budget: u64, kv_cache_byte_budget: u64, manifest_byte_count: u64, assembly_receipt_byte_count: u64, adapter_family_receipt_byte_count: u64, stack_byte_counts: &[u64], ) -> io::Result { let mut total = model_byte_budget; for byte_count in [ manifest_byte_count, assembly_receipt_byte_count, adapter_family_receipt_byte_count, kv_cache_byte_budget, MODULE_PLAN_PROMPT_BYTE_LIMIT, MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET, MODULE_PLAN_OUTPUT_BYTE_LIMIT, ] { total = total .checked_add(byte_count) .ok_or_else(|| invalid("module plan total byte budget overflow"))?; } for byte_count in stack_byte_counts { total = total .checked_add(*byte_count) .ok_or_else(|| invalid("module plan total byte budget overflow"))?; } Ok(total) } fn push_module_plan_line( text: &mut String, module_index: usize, kind: &str, assembly_slot: &str, role: &str, phase: &str, depends_on: &str, path: &str, checksum: &str, byte_count: u64, ) { let prefix = format!("module.{module_index}"); push_line(text, &format!("{prefix}.kind"), kind); push_line(text, &format!("{prefix}.assembly_slot"), assembly_slot); push_line(text, &format!("{prefix}.role"), role); push_line(text, &format!("{prefix}.phase"), phase); push_line(text, &format!("{prefix}.depends_on"), depends_on); push_line( text, &format!("{prefix}.byte_count"), &byte_count.to_string(), ); push_line(text, &format!("{prefix}.path"), path); push_line(text, &format!("{prefix}.checksum"), checksum); } fn module_plan_adapter_role(adapter_path: &str) -> &'static str { if adapter_path.ends_with("-sparse.asp1") { "adapter-stack-sparse-delta" } else if adapter_path.ends_with("-low-rank.alr1") { "adapter-stack-low-rank-delta" } else if adapter_path.ends_with("-family.adp1") { "adapter-stack-family-delta" } else if adapter_path.ends_with("-self.adp1") { "adapter-stack-self-delta" } else { "adapter-stack-delta" } } fn bundle_auto_apply_stack_indexes(member_count: usize) -> Vec { if member_count >= 3 { (1..member_count).collect() } else { (0..member_count).collect() } } fn write_bundle_assembly_receipt( spec: &BundleSpec, receipt_path: &Path, report: &ValidationReport, ledger_path: &Path, review_path: &Path, recipe_path: &Path, operator_receipt_path: &Path, candidate_manifest_path: &Path, promotion_manifest_path: &Path, provenance_manifest_path: &Path, runtime_smoke_path: &Path, eval_path: &Path, admission_path: &Path, adapter_family_route: &selector::RegistryAdapterFamilyRoute, ) -> io::Result { let route = format!("../models/{}", spec.assembly_receipt_file); let eval_text = fs::read_to_string(eval_path)?; let eval_fields = provenance::parse_manifest(&eval_text)?; let eval_case_evidence_checksum = provenance::eval_case_evidence_checksum(&eval_fields)?; let mut text = String::new(); push_line(&mut text, "tinyrustlm_assembly_receipt_version", "1"); push_line(&mut text, "assembly_kind", ASSEMBLY_RECEIPT_KIND); push_line(&mut text, "assembly_status", ASSEMBLY_RECEIPT_STATUS); push_line( &mut text, "assembly_strategy", spec.operator.assembly_strategy(), ); push_line(&mut text, "candidate_id", &spec.id); push_line(&mut text, "assembly_label", &spec.assembly_label); push_line(&mut text, "assembly_receipt_path", &route); push_line( &mut text, "model_path", &format!("../models/{}", spec.model_file), ); push_line( &mut text, "manifest_path", &format!("../models/{}.manifest", spec.model_file), ); push_line(&mut text, "slm_checksum", &hex64(report.checksum())); push_line( &mut text, "manifest_checksum", &text_file_checksum(provenance_manifest_path)?, ); push_line(&mut text, "parent_count", "3"); push_line( &mut text, "promotion_ledger_path", &evidence_route(spec, "population.ledger"), ); push_line( &mut text, "promotion_ledger_checksum", &text_file_checksum(ledger_path)?, ); push_line( &mut text, "population_review_path", &evidence_route(spec, "population.review"), ); push_line( &mut text, "population_review_checksum", &text_file_checksum(review_path)?, ); push_line( &mut text, "parent_pool_recipe_path", &evidence_route(spec, "parent-pool.recipe"), ); push_line( &mut text, "parent_pool_recipe_checksum", &text_file_checksum(recipe_path)?, ); push_line( &mut text, "operator_receipt_path", &evidence_route(spec, &spec.operator.evidence_file("operator")), ); push_line( &mut text, "operator_receipt_checksum", &text_file_checksum(operator_receipt_path)?, ); push_line( &mut text, "candidate_manifest_path", &evidence_route(spec, &spec.operator.evidence_file("candidate")), ); push_line( &mut text, "candidate_manifest_checksum", &text_file_checksum(candidate_manifest_path)?, ); push_line( &mut text, "promotion_manifest_path", &evidence_route(spec, &spec.operator.evidence_file("promotion")), ); push_line( &mut text, "promotion_manifest_checksum", &text_file_checksum(promotion_manifest_path)?, ); push_line( &mut text, "runtime_smoke_path", &evidence_route(spec, &spec.operator.evidence_file("runtime")), ); push_line( &mut text, "runtime_smoke_manifest_checksum", &text_file_checksum(runtime_smoke_path)?, ); push_line( &mut text, "eval_path", &evidence_route(spec, &spec.operator.evidence_file("eval")), ); push_line( &mut text, "eval_manifest_checksum", &text_file_checksum(eval_path)?, ); push_line( &mut text, "eval_case_evidence_checksum", &eval_case_evidence_checksum, ); push_line( &mut text, "admission_path", &evidence_route(spec, &spec.operator.evidence_file("multi.admission")), ); push_line( &mut text, "admission_checksum", &text_file_checksum(admission_path)?, ); push_line( &mut text, "adapter_family_receipt_path", &format!("../models/{}", spec.adapter_family_receipt_file), ); push_line( &mut text, "adapter_family_receipt_checksum", &adapter_family_route.receipt_checksum, ); push_line( &mut text, "required_next_gate", "browser-selector-registry-route-binding", ); fs::write(receipt_path, &text)?; Ok(selector::RegistryAssemblyRoute { candidate_id: spec.id.clone(), receipt_path: route, label: spec.assembly_label.clone(), status: ASSEMBLY_REGISTRY_STATUS.to_string(), kind: ASSEMBLY_RECEIPT_KIND.to_string(), receipt_checksum: hex64(provenance::text_checksum(text.as_bytes())), }) } fn write_bundle_adapter_route( spec: &BundleSpec, candidate_path: &Path, models: &Path, evidence: &Path, route_id: &str, adapter_file: &str, adapter_label: &str, adapter_kind: BundleAdapterKind, ) -> io::Result { let adapter_path = models.join(adapter_file); let adapter_manifest_path = models.join(format!("{adapter_file}.manifest")); match adapter_kind { BundleAdapterKind::RawAdp1 => { let (compatibility_path, lineage_path) = write_bundle_adapter_lineage( spec, candidate_path, evidence, route_id, "adapter-delta-v1", )?; adapter::write_artifact_path( &compatibility_path, &lineage_path, candidate_path, candidate_path, &adapter_path, &adapter_manifest_path, )?; adapter::validate_artifact_path( &compatibility_path, &lineage_path, candidate_path, candidate_path, &adapter_path, &adapter_manifest_path, )?; } BundleAdapterKind::SparseAsp1 => { let (compatibility_path, lineage_path) = write_bundle_adapter_lineage( spec, candidate_path, evidence, route_id, "sparse-adapter-delta-v1", )?; adapter::write_sparse_artifact_path( &compatibility_path, &lineage_path, candidate_path, candidate_path, &adapter_path, &adapter_manifest_path, Some("1000000"), Some("250000"), )?; adapter::validate_sparse_artifact_path( &compatibility_path, &lineage_path, candidate_path, candidate_path, &adapter_path, &adapter_manifest_path, )?; } BundleAdapterKind::SourceLowRankAlr1 => { let source_dir = evidence.join(format!("{route_id}.source")); trained_adapter_source::write_adapter_source_template_path( &source_dir, "tiny-fixture", )?; trained_adapter_source::convert_adapter_source_path( &source_dir, candidate_path, &adapter_path, &adapter_manifest_path, )?; trained_adapter_source::validate_converted_adapter_source_path( &source_dir, candidate_path, &adapter_path, &adapter_manifest_path, )?; } } let manifest_text = fs::read_to_string(&adapter_manifest_path)?; let fields = provenance::parse_manifest(&manifest_text)?; let apply_status = manifest_field(&fields, "adapter_apply_status")?.to_string(); let artifact_checksum = manifest_field(&fields, "adapter_artifact_checksum")?.to_string(); Ok(BundleAdapterRoute { route: selector::RegistryAdapterRoute { candidate_id: spec.id.clone(), adapter_path: format!("../models/{adapter_file}"), manifest_path: format!("../models/{adapter_file}.manifest"), label: adapter_label.to_string(), apply_status, artifact_checksum, manifest_checksum: hex64(provenance::text_checksum(manifest_text.as_bytes())), }, artifact_path: adapter_path, manifest_path: adapter_manifest_path, }) } fn write_bundle_adapter_lineage( spec: &BundleSpec, candidate_path: &Path, evidence: &Path, route_id: &str, lineage_operator: &str, ) -> io::Result<(PathBuf, PathBuf)> { let compatibility_path = evidence.join(format!("{route_id}.compat")); let lineage_path = evidence.join(format!("{route_id}.lineage")); compatibility::report_path(candidate_path, candidate_path, Some(&compatibility_path))?; lineage::write_template_path( &compatibility_path, &lineage_path, &format!("{}-{route_id}", spec.id), lineage_operator, "browser-registry-sidecar", )?; Ok((compatibility_path, lineage_path)) } fn write_bundle_adapter_routes( spec: &BundleSpec, candidate_path: &Path, models: &Path, evidence: &Path, ) -> io::Result> { let route_specs = [ ( "self-adapter", spec.self_adapter_file.as_str(), spec.self_adapter_label.as_str(), BundleAdapterKind::RawAdp1, ), ( "family-adapter", spec.family_adapter_file.as_str(), spec.family_adapter_label.as_str(), BundleAdapterKind::RawAdp1, ), ( "sparse-adapter", spec.sparse_adapter_file.as_str(), spec.sparse_adapter_label.as_str(), BundleAdapterKind::SparseAsp1, ), ( "low-rank-adapter", spec.low_rank_adapter_file.as_str(), spec.low_rank_adapter_label.as_str(), BundleAdapterKind::SourceLowRankAlr1, ), ]; let mut routes = Vec::with_capacity(route_specs.len()); for (route_id, adapter_file, adapter_label, adapter_kind) in route_specs { let route = write_bundle_adapter_route( spec, candidate_path, models, evidence, route_id, adapter_file, adapter_label, adapter_kind, )?; routes.push(route); } Ok(routes) } fn evidence_route(spec: &BundleSpec, file_name: &str) -> String { format!("../evidence/{}/{file_name}", spec.id) } fn text_file_checksum(path: &Path) -> io::Result { let text = fs::read_to_string(path)?; Ok(hex64(provenance::text_checksum(text.as_bytes()))) } fn file_byte_count(path: &Path) -> io::Result { Ok(fs::metadata(path)?.len()) } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } fn copy_browser_surface(root: &Path) -> io::Result<()> { let source_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join(".."); let app_source = source_root.join("app"); let runtime_source = source_root.join("runtime"); let app_target = root.join("app"); let runtime_target = root.join("runtime"); fs::create_dir_all(&app_target)?; fs::create_dir_all(&runtime_target)?; for file_name in APP_FILES { fs::copy(app_source.join(file_name), app_target.join(file_name))?; } let runtime_bytes = fs::read(runtime_source.join(RUNTIME_WASM_FILE))?; fs::write(runtime_target.join(RUNTIME_WASM_FILE), &runtime_bytes)?; fs::write( runtime_target.join(RUNTIME_WASM_MANIFEST_FILE), runtime_wasm_manifest_text(&runtime_bytes), )?; Ok(()) } pub(crate) fn write_runtime_wasm_manifest_path( wasm_path: &Path, manifest_path: &Path, ) -> io::Result<()> { let runtime_bytes = fs::read(wasm_path)?; fs::write(manifest_path, runtime_wasm_manifest_text(&runtime_bytes)) } fn runtime_wasm_manifest_text(runtime_bytes: &[u8]) -> String { let mut text = String::new(); push_line(&mut text, "tinyrustlm_wasm_manifest_version", "1"); push_line(&mut text, "runtime_kind", RUNTIME_WASM_KIND); push_line(&mut text, "runtime_status", RUNTIME_WASM_STATUS); push_line(&mut text, "runtime_wasm_path", "../runtime/tinyrustlm.wasm"); push_line( &mut text, "runtime_wasm_bytes", &runtime_bytes.len().to_string(), ); push_line( &mut text, "runtime_wasm_checksum", &hex64(provenance::text_checksum(runtime_bytes)), ); push_line(&mut text, "required_next_gate", RUNTIME_WASM_NEXT_GATE); text } fn parent_admission_text( candidate_id: &str, candidate_path: &str, bytes: &[u8], ) -> io::Result { let compatibility = compatibility::compatibility_text_for_bytes(bytes, candidate_path, bytes, candidate_path)?; let lineage = lineage::build_template_text( &compatibility, candidate_id, "seed-parent", "browser-bundle", )?; let candidate_manifest = candidate::build_manifest_text(&compatibility, &lineage, bytes, candidate_path)?; let promotion = promotion::build_template_text( &compatibility, &lineage, bytes, candidate_path, &candidate_manifest, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, )?; let report = slm_validate::validate_bytes(bytes, candidate_path)?; let provenance_manifest = provenance::build_manifest_text(&report, SOURCE_KIND)?; let manifest_fields = provenance::parse_manifest(&provenance_manifest)?; let runtime_smoke = provenance::build_runtime_smoke_text(&report, &provenance_manifest, &manifest_fields)?; let eval = passing_eval_text(&report, &provenance_manifest); admission::build_record_text( &compatibility, &lineage, bytes, candidate_path, &candidate_manifest, &promotion, &provenance_manifest, &runtime_smoke, &eval, admission::DEFAULT_ADMISSION_SELECTOR_ID, ) } fn tiny_fixture_bytes_with_offset(dtype: u32, offset: f32) -> io::Result> { let tensors = tiny_fixture_tensors_with_dtype(dtype); let values: Vec> = tensors .iter() .map(|tensor| { (0..tensor.element_count()) .map(|elem| fixture_value(tensor, elem) + offset) .collect() }) .collect(); build_model_file_from_values_with_flags( &ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) } fn passing_eval_text(report: &ValidationReport, manifest: &str) -> String { let mut text = String::new(); push_line(&mut text, "tinyrustlm_eval_manifest_version", "1"); push_line(&mut text, "gate", "assistant-quality"); push_line(&mut text, "source_kind", SOURCE_KIND); push_line( &mut text, "manifest_checksum", &hex64(provenance::text_checksum(manifest.as_bytes())), ); push_line(&mut text, "slm_checksum", &hex64(report.checksum())); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "task_eval_status", "pass"); push_line(&mut text, "safety_review_status", "pass"); push_line( &mut text, "quality_decision", "accepted-for-assistant-quality", ); push_line(&mut text, "quality_scope", "tiny-fixture-runtime-eval-only"); push_line(&mut text, "evaluator", "local-reviewed-eval"); push_line( &mut text, "eval_dataset", "tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", ); push_line( &mut text, "eval_summary", "Reviewed task and safety evidence passed for declared scope", ); push_line( &mut text, "quality_boundary", "fixture-runtime-and-eval-plumbing-not-product-assistant-quality", ); push_line(&mut text, "case_count", "1"); push_line(&mut text, "cases_passed", "1"); push_line(&mut text, "cases_failed", "0"); push_line(&mut text, "case.0.status", "pass"); push_line(&mut text, "case.0.expected", "e"); push_line(&mut text, "case.0.actual", "e"); push_line(&mut text, "case.0.error", "ok"); text } fn paths_as_strings<'a>(paths: impl Iterator) -> Vec { paths.map(|path| display_path(path)).collect() } fn display_path(path: &Path) -> String { path.display().to_string() } fn manifest_field<'a>( fields: &'a std::collections::HashMap, key: &str, ) -> io::Result<&'a str> { fields.get(key).map(String::as_str).ok_or_else(|| { io::Error::new( io::ErrorKind::InvalidData, format!("manifest missing {key}"), ) }) } #[cfg(test)] mod tests { use super::*; use std::time::{SystemTime, UNIX_EPOCH}; fn assert_module_plan(root: &std::path::Path, id: &str, quantization: &str, registry: &str) { assert_module_plan_with_operator(root, id, quantization, registry, "sign-merge"); } fn assert_module_plan_with_operator( root: &std::path::Path, id: &str, quantization: &str, registry: &str, evidence_prefix: &str, ) { let file_name = format!("{id}.module-plan.receipt"); let module_plan = fs::read_to_string(root.join("models").join(&file_name)).unwrap(); let checksum = hex64(provenance::text_checksum(module_plan.as_bytes())); let model_path = root.join("models").join(format!("{id}.slm")); let model_bytes_body = fs::read(&model_path).unwrap(); let report = slm_validate::validate_bytes(&model_bytes_body, &display_path(&model_path)).unwrap(); let tokenizer_checksum = hex64(report.tokenizer_checksum()); let model_bytes = fs::metadata(root.join("models").join(format!("{id}.slm"))) .unwrap() .len(); let manifest_bytes = fs::metadata(root.join("models").join(format!("{id}.slm.manifest"))) .unwrap() .len(); let assembly_receipt_bytes = fs::metadata(root.join("models").join(format!("{id}.assembly.receipt"))) .unwrap() .len(); let adapter_family_receipt_bytes = fs::metadata( root.join("models") .join(format!("{id}.adapter-family.receipt")), ) .unwrap() .len(); let operator_receipt_checksum = text_file_checksum( &root .join("evidence") .join(id) .join(format!("{evidence_prefix}.operator")), ) .unwrap(); let family_adapter_bytes = fs::metadata(root.join("models").join(format!("{id}-family.adp1"))) .unwrap() .len(); let sparse_adapter_bytes = fs::metadata(root.join("models").join(format!("{id}-sparse.asp1"))) .unwrap() .len(); let low_rank_adapter_bytes = fs::metadata(root.join("models").join(format!("{id}-low-rank.alr1"))) .unwrap() .len(); let kv_cache_bytes = 1024u64; let adapter_stack_byte_budget = family_adapter_bytes + sparse_adapter_bytes + low_rank_adapter_bytes; let total_byte_budget = model_bytes + manifest_bytes + assembly_receipt_bytes + adapter_family_receipt_bytes + adapter_stack_byte_budget + kv_cache_bytes + MODULE_PLAN_PROMPT_BYTE_LIMIT + MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET + MODULE_PLAN_OUTPUT_BYTE_LIMIT; assert!(registry.contains(&format!("module_plan_path=../models/{file_name}"))); assert!(registry.contains(&format!("module_plan_checksum={checksum}"))); assert!(registry.contains("module_plan_status=receipt-validated")); assert!(registry.contains("module_plan_kind=browser-local-module-plan")); assert!(registry.contains("module_plan_strategy=selector-entry-self-assembly")); assert!(registry.contains("module_plan_resource_class=browser-constrained-local-assembly")); assert!(registry.contains("module_plan_profile=browser-constrained-v1")); assert!(registry.contains("module_plan_execution_profile=single-threaded-wasm-local-v1")); assert!(registry.contains("module_plan_fetch_policy=local-no-store-v1")); assert!(registry.contains("module_plan_origin_policy=same-origin-loopback-local-v1")); assert!(registry.contains("module_plan_fetch_count_limit=32")); assert!(registry.contains("module_plan_planned_fetch_count=21")); assert!(registry.contains("module_plan_route_set_version=1")); assert!(registry .contains("module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1")); assert!(registry.contains("module_plan_route_set_checksum=0x")); assert!(registry.contains(&format!( "module_plan_operator_receipt_path=../evidence/{id}/{evidence_prefix}.operator" ))); assert!(registry.contains(&format!( "module_plan_operator_receipt_checksum={operator_receipt_checksum}" ))); assert!(registry.contains("module_plan_wasm_memory_initial_pages=17")); assert!(registry.contains("module_plan_wasm_export_set=tinyrustlm-generate-v1")); assert!(registry.contains("module_plan_wasm_transfer_strategy=copy-then-release-v1")); assert!(registry.contains("module_plan_model_release_strategy=free-before-reassembly-v1")); assert!(registry .contains("module_plan_runtime_reset_strategy=reset-context-before-assembly-v1")); assert!(registry .contains("module_plan_adapter_validation_strategy=rust-validate-before-apply-v1")); assert!(registry.contains("module_plan_adapter_validation_count=3")); assert!(registry.contains("module_plan_adapter_apply_count=3")); assert!(registry.contains("module_plan_wasm_heap_min_bytes=65536")); assert!(registry.contains("module_plan_context_token_limit=16")); assert!(registry.contains("module_plan_sampler_candidate_cap=1024")); assert!(registry.contains(&format!( "module_plan_tokenizer_checksum={tokenizer_checksum}" ))); assert!(registry.contains("module_plan_prompt_byte_limit=4096")); assert!(registry.contains(&format!("module_plan_model_byte_budget={model_bytes}"))); assert!(registry.contains("module_plan_adapter_byte_budget=1048576")); assert!(registry.contains(&format!( "module_plan_adapter_stack_byte_budget={adapter_stack_byte_budget}" ))); assert!(registry.contains("module_plan_runtime_scratch_byte_budget=65536")); assert!(registry.contains("module_plan_output_byte_limit=65536")); assert!(registry.contains("module_plan_kv_cache_byte_budget=1024")); assert!(registry.contains("module_plan_kv_cache_page_count=1")); assert!(registry.contains(&format!( "module_plan_total_byte_budget={total_byte_budget}" ))); assert!(registry.contains(&format!( "module_plan_total_byte_budget_limit={MODULE_PLAN_TOTAL_BYTE_BUDGET_LIMIT}" ))); assert!(registry.contains("module_plan_module_count=7")); assert!(module_plan.contains("tinyrustlm_module_plan_version=1")); assert!(module_plan.contains("module_plan_kind=browser-local-module-plan")); assert!(module_plan.contains("module_plan_status=validated")); assert!(module_plan.contains("module_plan_strategy=selector-entry-self-assembly")); assert!(module_plan.contains(&format!("candidate_id={id}"))); assert!(module_plan.contains(&format!("module_plan_path=../models/{file_name}"))); assert!( module_plan.contains("module_plan_resource_class=browser-constrained-local-assembly") ); assert!(module_plan.contains("module_plan_profile=browser-constrained-v1")); assert!(module_plan.contains("module_plan_execution_profile=single-threaded-wasm-local-v1")); assert!(module_plan.contains("module_plan_fetch_policy=local-no-store-v1")); assert!(module_plan.contains("module_plan_origin_policy=same-origin-loopback-local-v1")); assert!(module_plan.contains("module_plan_fetch_count_limit=32")); assert!(module_plan.contains("module_plan_planned_fetch_count=21")); assert!(module_plan.contains("module_plan_route_set_version=1")); assert!(module_plan .contains("module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1")); assert!(module_plan.contains("module_plan_route_set_checksum=0x")); assert!(module_plan.contains(&format!( "operator_receipt_path=../evidence/{id}/{evidence_prefix}.operator" ))); assert!(module_plan.contains(&format!( "operator_receipt_checksum={operator_receipt_checksum}" ))); assert!(module_plan.contains("module_plan_wasm_memory_initial_pages=17")); assert!(module_plan.contains("module_plan_wasm_export_set=tinyrustlm-generate-v1")); assert!(module_plan.contains("module_plan_wasm_transfer_strategy=copy-then-release-v1")); assert!( module_plan.contains("module_plan_model_release_strategy=free-before-reassembly-v1") ); assert!(module_plan .contains("module_plan_runtime_reset_strategy=reset-context-before-assembly-v1")); assert!(module_plan .contains("module_plan_adapter_validation_strategy=rust-validate-before-apply-v1")); assert!(module_plan.contains("module_plan_adapter_validation_count=3")); assert!(module_plan.contains("module_plan_adapter_apply_count=3")); assert!(module_plan.contains("module_plan_wasm_heap_min_bytes=65536")); assert!(module_plan.contains("module_plan_context_token_limit=16")); assert!(module_plan.contains("module_plan_sampler_candidate_cap=1024")); assert!(module_plan.contains(&format!( "module_plan_tokenizer_checksum={tokenizer_checksum}" ))); assert!(module_plan.contains("module_plan_prompt_byte_limit=4096")); assert!(module_plan.contains(&format!("module_plan_model_byte_budget={model_bytes}"))); assert!(module_plan.contains("module_plan_adapter_byte_budget=1048576")); assert!(module_plan.contains(&format!( "module_plan_adapter_stack_byte_budget={adapter_stack_byte_budget}" ))); assert!(module_plan.contains("module_plan_runtime_scratch_byte_budget=65536")); assert!(module_plan.contains("module_plan_output_byte_limit=65536")); assert!(module_plan.contains("module_plan_kv_cache_byte_budget=1024")); assert!(module_plan.contains("module_plan_kv_cache_page_count=1")); assert!(module_plan.contains(&format!( "module_plan_total_byte_budget={total_byte_budget}" ))); assert!(module_plan.contains(&format!( "module_plan_total_byte_budget_limit={MODULE_PLAN_TOTAL_BYTE_BUDGET_LIMIT}" ))); assert!(module_plan.contains(&format!("model_path=../models/{id}.slm"))); assert!(module_plan.contains(&format!("manifest_path=../models/{id}.slm.manifest"))); assert!(module_plan.contains(&format!("quantization={quantization}"))); assert!(module_plan.contains("adapter_auto_apply_stack_count=3")); assert!(module_plan.contains("module_count=7")); assert!(module_plan.contains("module.0.kind=model")); assert!(module_plan.contains("module.0.assembly_slot=runtime-model")); assert!(module_plan.contains("module.0.role=runtime-model")); assert!(module_plan.contains("module.0.phase=load-model-bytes")); assert!(module_plan.contains("module.0.depends_on=runtime-wasm")); assert!(module_plan.contains(&format!("module.0.byte_count={model_bytes}"))); assert!(module_plan.contains("module.1.kind=model-manifest")); assert!(module_plan.contains("module.1.assembly_slot=model-manifest")); assert!(module_plan.contains("module.1.role=model-provenance-manifest")); assert!(module_plan.contains("module.1.phase=verify-model-manifest")); assert!(module_plan.contains("module.1.depends_on=module.0")); assert!(module_plan.contains(&format!("module.1.byte_count={manifest_bytes}"))); assert!(module_plan.contains("module.2.kind=assembly-receipt")); assert!(module_plan.contains("module.2.assembly_slot=assembly-receipt")); assert!(module_plan.contains("module.2.role=assembly-evidence")); assert!(module_plan.contains("module.2.phase=verify-assembly-evidence")); assert!(module_plan.contains("module.2.depends_on=module.1")); assert!(module_plan.contains(&format!("module.2.byte_count={assembly_receipt_bytes}"))); assert!(module_plan.contains("module.3.kind=adapter-family-receipt")); assert!(module_plan.contains("module.3.assembly_slot=adapter-family-receipt")); assert!(module_plan.contains("module.3.role=adapter-family")); assert!(module_plan.contains("module.3.phase=verify-adapter-family")); assert!(module_plan.contains("module.3.depends_on=module.2")); assert!(module_plan.contains(&format!( "module.3.byte_count={adapter_family_receipt_bytes}" ))); assert!(module_plan.contains("module.4.kind=adapter-stack-member")); assert!(module_plan.contains("module.4.assembly_slot=adapter-stack-0")); assert!(module_plan.contains("module.4.role=adapter-stack-family-delta")); assert!(module_plan.contains("module.4.phase=apply-adapter-stack-0")); assert!(module_plan.contains("module.4.depends_on=module.3")); assert!(module_plan.contains(&format!("module.4.byte_count={family_adapter_bytes}"))); assert!(module_plan.contains("module.4.checksum=0x")); assert!(module_plan.contains("module.4.adapter_index=1")); assert!(module_plan.contains(&format!("module.4.adapter_path=../models/{id}-family.adp1"))); assert!(module_plan.contains("module.5.kind=adapter-stack-member")); assert!(module_plan.contains("module.5.assembly_slot=adapter-stack-1")); assert!(module_plan.contains("module.5.role=adapter-stack-sparse-delta")); assert!(module_plan.contains("module.5.phase=apply-adapter-stack-1")); assert!(module_plan.contains("module.5.depends_on=module.4")); assert!(module_plan.contains(&format!("module.5.byte_count={sparse_adapter_bytes}"))); assert!(module_plan.contains("module.5.checksum=0x")); assert!(module_plan.contains("module.5.adapter_index=2")); assert!(module_plan.contains(&format!("module.5.adapter_path=../models/{id}-sparse.asp1"))); assert!(module_plan.contains("module.6.kind=adapter-stack-member")); assert!(module_plan.contains("module.6.assembly_slot=adapter-stack-2")); assert!(module_plan.contains("module.6.role=adapter-stack-low-rank-delta")); assert!(module_plan.contains("module.6.phase=apply-adapter-stack-2")); assert!(module_plan.contains("module.6.depends_on=module.5")); assert!(module_plan.contains(&format!("module.6.byte_count={low_rank_adapter_bytes}"))); assert!(module_plan.contains("module.6.checksum=0x")); assert!(module_plan.contains("module.6.adapter_index=3")); assert!(module_plan.contains(&format!( "module.6.adapter_path=../models/{id}-low-rank.alr1" ))); } fn assert_source_backed_alr1_receipt_fields(family_receipt: &str, id: &str) { // Confirms the source-backed low-rank adapter member carries source provenance echoes. assert!(family_receipt.contains(&format!("adapter.3.path=../models/{id}-low-rank.alr1"))); assert!(family_receipt.contains("adapter.3.kind=trained-source-low-rank-f32-v1")); assert!(family_receipt.contains("adapter.3.dtype=low-rank-f32-source-delta")); assert!(family_receipt.contains("adapter.3.source_manifest=adapter-source.manifest")); assert!(family_receipt.contains("adapter.3.source_manifest_checksum=0x")); assert!(family_receipt.contains("adapter.3.source_layout=low-rank-f32-factor-files-v1")); assert!(family_receipt.contains("adapter.3.source_format=trained-low-rank-factors-v1")); assert!(family_receipt.contains( "adapter.3.source_base_contract=matches-reviewed-adapter-source-base-contract" )); } fn assert_registry_breeding_fields(registry: &str, prefix: &str) { // Checks the ModelBreeder-inspired registry fields that route genome, species, population, mate-selection, phenotype, artifact, and fitness evidence. assert!(registry.contains(&format!("{prefix}.genome_id=0x"))); assert!(registry.contains(&format!( "{prefix}.genome_strategy=selector-admission-genome-v1" ))); assert!(registry.contains(&format!("{prefix}.genome_lineage_status=admission-bound"))); assert!(registry.contains(&format!("{prefix}.genome_lineage_checksum=0x"))); assert!(registry.contains(&format!("{prefix}.species_id=0x"))); assert!(registry.contains(&format!( "{prefix}.species_strategy=selector-speciation-fit-v1" ))); assert!(registry.contains(&format!("{prefix}.species_fit_status=browser-fit-bound"))); assert!(registry.contains(&format!("{prefix}.species_fit_checksum=0x"))); assert!(registry.contains(&format!("{prefix}.novelty_id=0x"))); assert!(registry.contains(&format!( "{prefix}.novelty_strategy=selector-novelty-sketch-v1" ))); assert!(registry.contains(&format!("{prefix}.novelty_status=behavior-sketch-bound"))); assert!(registry.contains(&format!("{prefix}.novelty_checksum=0x"))); assert!(registry.contains(&format!("{prefix}.population_id=0x"))); assert!(registry.contains(&format!( "{prefix}.population_strategy=selector-population-review-route-v1" ))); assert!(registry.contains(&format!( "{prefix}.population_status=population-review-bound" ))); assert!(registry.contains(&format!("{prefix}.population_checksum=0x"))); assert!(registry.contains(&format!("{prefix}.mate_selection_id=0x"))); assert!(registry.contains(&format!( "{prefix}.mate_selection_strategy=selector-mate-selection-route-v1" ))); assert!(registry.contains(&format!("{prefix}.mate_selection_status=parent-pool-bound"))); assert!(registry.contains(&format!("{prefix}.mate_selection_parent_count=3"))); assert!(registry.contains(&format!("{prefix}.mate_selection_checksum=0x"))); assert!(registry.contains(&format!("{prefix}.phenotype_evidence_id=0x"))); assert!(registry.contains(&format!( "{prefix}.phenotype_evidence_strategy=selector-phenotype-evidence-v1" ))); assert!(registry.contains(&format!( "{prefix}.phenotype_evidence_status=runtime-eval-bound" ))); assert!(registry.contains(&format!("{prefix}.phenotype_evidence_checksum=0x"))); assert!(registry.contains(&format!("{prefix}.heritable_artifact_id=0x"))); assert!(registry.contains(&format!( "{prefix}.heritable_artifact_strategy=selector-heritable-artifact-v1" ))); assert!(registry.contains(&format!( "{prefix}.heritable_artifact_status=served-artifact-bound" ))); assert!(registry.contains(&format!("{prefix}.heritable_artifact_checksum=0x"))); assert!(registry.contains(&format!("{prefix}.fitness_vector_status=eval-bound"))); assert!(registry.contains(&format!("{prefix}.fitness_vector_checksum=0x"))); } #[test] fn writes_browser_converted_trained_bundle_from_source() { let temp = unique_dir("converted-trained"); let source = temp.join("source"); let root = temp.join("tinyrustlm"); trained_source::write_source_template_path(&source, "tiny-fixture").unwrap(); write_converted_trained_bundle_path(&root, &source, "q8_0").unwrap(); let registry = fs::read_to_string(root.join("models").join("selector.registry")).unwrap(); assert!(registry.contains("entry.0.candidate_id=converted-trained-q8")); assert!(registry.contains("entry.0.display_name=Converted trained-source q8_0")); assert!(registry.contains("entry.0.model_path=../models/converted-trained-q8.slm")); assert!( registry.contains("entry.0.manifest_path=../models/converted-trained-q8.slm.manifest") ); assert!(registry.contains("entry.0.quantization=q8_0")); assert!(registry.contains("entry.0.mate_selection_status=admission-only")); assert!(registry.contains("entry.0.mate_selection_parent_count=1")); assert!(registry.contains("entry.0.quality_scope=tiny-fixture-runtime-eval-only")); assert!(registry.contains("entry.0.public_claim_status=bound-to-eval-scope")); assert!(registry.contains("entry.0.genome_strategy=selector-admission-genome-v1")); assert!(registry.contains("entry.0.species_strategy=selector-speciation-fit-v1")); assert!(registry.contains("entry.0.novelty_strategy=selector-novelty-sketch-v1")); assert!( registry.contains("entry.0.population_strategy=selector-population-review-route-v1") ); assert!( registry.contains("entry.0.phenotype_evidence_strategy=selector-phenotype-evidence-v1") ); assert!( registry.contains("entry.0.heritable_artifact_strategy=selector-heritable-artifact-v1") ); assert!(registry.contains("entry.0.fitness_vector_status=eval-bound")); let manifest = fs::read_to_string( root.join("models") .join("converted-trained-q8.slm.manifest"), ) .unwrap(); assert!(manifest.contains("source_kind=converted-trained")); assert!(manifest.contains("quality_claim=runtime-compatible-not-quality-verified")); assert!(manifest.contains("trained_quality_claim=pending-evaluation")); assert!(root .join("models") .join("converted-trained-q8.slm") .exists()); assert!(root .join("evidence") .join("converted-trained-q8") .join("converted-trained.admission") .exists()); assert!(root.join("app").join("app.js").exists()); assert_runtime_manifest(&root); fs::remove_dir_all(temp).unwrap(); } #[test] fn rejects_browser_converted_trained_bundle_unknown_quantization() { let temp = unique_dir("converted-trained-quantization"); let source = temp.join("source"); let root = temp.join("tinyrustlm"); trained_source::write_source_template_path(&source, "tiny-fixture").unwrap(); let error = write_converted_trained_bundle_path(&root, &source, "bf16").unwrap_err(); assert!(error.to_string().contains( "browser-converted-trained-bundle quantization must be f32, q8_0, q4_0, or all" )); fs::remove_dir_all(temp).unwrap(); } #[test] fn writes_all_browser_converted_trained_bundle_from_source() { let temp = unique_dir("converted-trained-all"); let source = temp.join("source"); let root = temp.join("tinyrustlm"); trained_source::write_source_template_path(&source, "tiny-fixture").unwrap(); write_converted_trained_bundle_path(&root, &source, "all").unwrap(); let registry = fs::read_to_string(root.join("models").join("selector.registry")).unwrap(); assert!(registry.contains("entry_count=3")); assert!(registry.contains("selector_default_candidate_id=converted-trained-q4")); assert!(registry.contains("selector_default_quantization=q4_0")); for (candidate_id, quantization) in [ ("converted-trained-f32", "f32"), ("converted-trained-q8", "q8_0"), ("converted-trained-q4", "q4_0"), ] { assert!(registry.contains(&format!("candidate_id={candidate_id}"))); assert!(registry.contains(&format!("model_path=../models/{candidate_id}.slm"))); assert!(registry.contains(&format!( "manifest_path=../models/{candidate_id}.slm.manifest" ))); assert!(registry.contains(&format!("quantization={quantization}"))); let manifest = fs::read_to_string( root.join("models") .join(format!("{candidate_id}.slm.manifest")), ) .unwrap(); assert!(manifest.contains("source_kind=converted-trained")); assert!(manifest.contains(&format!("quantization={quantization}"))); assert!(root .join("models") .join(format!("{candidate_id}.slm")) .exists()); assert!(root .join("evidence") .join(candidate_id) .join("converted-trained.admission") .exists()); } assert!(root.join("app").join("app.js").exists()); assert_runtime_manifest(&root); fs::remove_dir_all(temp).unwrap(); } #[test] fn writes_browser_multi_parent_bundle() { let root = unique_dir("bundle").join("tinyrustlm"); write_bundle_path_with_quantization(&root, "f32").unwrap(); let registry = fs::read_to_string(root.join("models").join("selector.registry")).unwrap(); assert!(registry.contains("entry.0.candidate_id=multi-parent-sign-merge-f32")); assert!(registry.contains("selector_model_byte_budget=33554432")); assert!(registry.contains("selector_registry_text_byte_budget=262144")); assert!(registry.contains("manifest_text_byte_budget=65536")); assert!(registry.contains("receipt_text_byte_budget=131072")); assert!(registry.contains("evidence_text_byte_budget=131072")); assert!(registry.contains("entry.0.model_path=../models/multi-parent-sign-merge-f32.slm")); assert!(registry.contains("entry.0.eval_case_evidence_checksum=0x")); assert_registry_breeding_fields(®istry, "entry.0"); assert!(registry .contains("entry.0.adapter_path=../models/multi-parent-sign-merge-f32-self.adp1")); assert!(registry.contains("entry.0.adapter_label=Multi-parent sign-merge f32 self ADP1")); assert!(registry.contains("entry.0.adapter_count=4")); assert!(registry .contains("entry.0.adapter.1.path=../models/multi-parent-sign-merge-f32-family.adp1")); assert!( registry.contains("entry.0.adapter.1.label=Multi-parent sign-merge f32 family ADP1") ); assert!(registry .contains("entry.0.adapter.2.path=../models/multi-parent-sign-merge-f32-sparse.asp1")); assert!( registry.contains("entry.0.adapter.2.label=Multi-parent sign-merge f32 sparse ASP1") ); assert!(registry.contains( "entry.0.adapter.3.path=../models/multi-parent-sign-merge-f32-low-rank.alr1" )); assert!(registry .contains("entry.0.adapter.3.label=Multi-parent sign-merge f32 source-backed ALR1")); assert!(registry.contains( "entry.0.adapter_family_receipt_path=../models/multi-parent-sign-merge-f32.adapter-family.receipt" )); assert!(registry.contains("entry.0.adapter_family_status=receipt-validated")); assert!(registry.contains("entry.0.adapter_family_adapter_count=4")); assert!(registry.contains("entry.0.adapter_auto_apply_status=enabled")); assert!( registry.contains("entry.0.adapter_auto_apply_strategy=receipt-preferred-compatible") ); assert!(registry.contains("entry.0.adapter_auto_apply_stack_status=enabled")); assert!(registry.contains( "entry.0.adapter_auto_apply_stack_strategy=receipt-declared-compatible-stack" )); assert!(registry.contains("entry.0.adapter_auto_apply_stack_count=3")); assert!(registry.contains("entry.0.adapter_auto_apply_byte_budget=1048576")); let family_receipt = fs::read_to_string( root.join("models") .join("multi-parent-sign-merge-f32.adapter-family.receipt"), ) .unwrap(); assert!(family_receipt.contains("adapter_family_preferred_adapter_index=2")); assert!(family_receipt.contains( "adapter_family_preferred_adapter_path=../models/multi-parent-sign-merge-f32-sparse.asp1" )); assert!(family_receipt.contains("adapter_family_auto_apply_stack_count=3")); assert!(family_receipt.contains("adapter_family_auto_apply_stack.0.adapter_index=1")); assert!(family_receipt.contains( "adapter_family_auto_apply_stack.0.adapter_path=../models/multi-parent-sign-merge-f32-family.adp1" )); assert!(family_receipt.contains("adapter_family_auto_apply_stack.1.adapter_index=2")); assert!(family_receipt.contains( "adapter_family_auto_apply_stack.1.adapter_path=../models/multi-parent-sign-merge-f32-sparse.asp1" )); assert!(family_receipt.contains("adapter_family_auto_apply_stack.2.adapter_index=3")); assert!(family_receipt.contains( "adapter_family_auto_apply_stack.2.adapter_path=../models/multi-parent-sign-merge-f32-low-rank.alr1" )); assert_source_backed_alr1_receipt_fields(&family_receipt, "multi-parent-sign-merge-f32"); assert!(registry.contains( "entry.0.assembly_receipt_path=../models/multi-parent-sign-merge-f32.assembly.receipt" )); assert!(registry.contains("entry.0.assembly_status=receipt-validated")); assert!(registry.contains("entry.0.assembly_kind=browser-local-assembly-evidence")); let assembly_receipt = fs::read_to_string( root.join("models") .join("multi-parent-sign-merge-f32.assembly.receipt"), ) .unwrap(); let assembly_checksum = hex64(provenance::text_checksum(assembly_receipt.as_bytes())); assert!(registry.contains(&format!( "entry.0.assembly_receipt_checksum={assembly_checksum}" ))); assert!(assembly_receipt.contains("parent_count=3")); assert!(assembly_receipt.contains("eval_case_evidence_checksum=0x")); assert!(assembly_receipt.contains("operator_receipt_checksum=0x")); assert!( assembly_receipt.contains("required_next_gate=browser-selector-registry-route-binding") ); assert_module_plan(&root, "multi-parent-sign-merge-f32", "f32", ®istry); assert!(root .join("models") .join("multi-parent-sign-merge-f32.slm.manifest") .exists()); assert!(root .join("models") .join("multi-parent-sign-merge-f32-self.adp1") .exists()); assert!(root .join("models") .join("multi-parent-sign-merge-f32-self.adp1.manifest") .exists()); assert!(root .join("models") .join("multi-parent-sign-merge-f32-family.adp1") .exists()); assert!(root .join("models") .join("multi-parent-sign-merge-f32-family.adp1.manifest") .exists()); assert!(root .join("models") .join("multi-parent-sign-merge-f32-sparse.asp1") .exists()); assert!(root .join("models") .join("multi-parent-sign-merge-f32-sparse.asp1.manifest") .exists()); assert!(root .join("models") .join("multi-parent-sign-merge-f32-low-rank.alr1") .exists()); assert!(root .join("models") .join("multi-parent-sign-merge-f32-low-rank.alr1.manifest") .exists()); let sparse_manifest = fs::read_to_string( root.join("models") .join("multi-parent-sign-merge-f32-sparse.asp1.manifest"), ) .unwrap(); assert!(sparse_manifest.contains("adapter_artifact_kind=sparse-f32-task-delta-v1")); let low_rank_manifest = fs::read_to_string( root.join("models") .join("multi-parent-sign-merge-f32-low-rank.alr1.manifest"), ) .unwrap(); assert!(low_rank_manifest.contains("adapter_artifact_kind=trained-source-low-rank-f32-v1")); assert!(low_rank_manifest.contains("adapter_dtype=low-rank-f32-source-delta")); assert!(low_rank_manifest.contains("adapter_source_manifest_checksum=0x")); assert!(low_rank_manifest.contains( "adapter_source_base_contract=matches-reviewed-adapter-source-base-contract" )); assert!(root .join("models") .join("multi-parent-sign-merge-f32.adapter-family.receipt") .exists()); assert!(root.join("app").join("index.html").exists()); assert!(root.join("app").join("app.css").exists()); assert!(root.join("app").join("app.js").exists()); assert!(root.join("runtime").join("tinyrustlm.wasm").exists()); assert_runtime_manifest(&root); fs::remove_dir_all(root.parent().unwrap()).unwrap(); } #[test] fn writes_quantized_browser_multi_parent_bundles() { for (quantization, suffix) in [("q8_0", "q8"), ("q4_0", "q4")] { let root = unique_dir(suffix).join("tinyrustlm"); write_bundle_path_with_quantization(&root, quantization).unwrap(); let id = format!("multi-parent-sign-merge-{suffix}"); let registry = fs::read_to_string(root.join("models").join("selector.registry")).unwrap(); assert!(registry.contains(&format!("entry.0.candidate_id={id}"))); assert!(registry.contains("selector_model_byte_budget=33554432")); assert!(registry.contains("selector_registry_text_byte_budget=262144")); assert!(registry.contains("manifest_text_byte_budget=65536")); assert!(registry.contains("receipt_text_byte_budget=131072")); assert!(registry.contains("evidence_text_byte_budget=131072")); assert!(registry.contains(&format!("entry.0.quantization={quantization}"))); assert!(registry.contains(&format!("entry.0.model_path=../models/{id}.slm"))); assert!(registry.contains("entry.0.eval_case_evidence_checksum=0x")); assert_registry_breeding_fields(®istry, "entry.0"); assert!(registry.contains(&format!("entry.0.adapter_path=../models/{id}-self.adp1"))); assert!(registry .contains("entry.0.adapter_apply_status=runtime-q8-q4-compatible-or-fuse-to-slm")); assert!(registry.contains(&format!( "entry.0.adapter.1.path=../models/{id}-family.adp1" ))); assert!(registry.contains(&format!( "entry.0.adapter.2.path=../models/{id}-sparse.asp1" ))); assert!(registry.contains(&format!( "entry.0.adapter_family_receipt_path=../models/{id}.adapter-family.receipt" ))); assert!(registry.contains("entry.0.adapter_family_adapter_count=4")); assert!(registry.contains("entry.0.adapter_auto_apply_status=enabled")); assert!(registry .contains("entry.0.adapter_auto_apply_strategy=receipt-preferred-compatible")); assert!(registry.contains("entry.0.adapter_auto_apply_stack_status=enabled")); assert!(registry.contains( "entry.0.adapter_auto_apply_stack_strategy=receipt-declared-compatible-stack" )); assert!(registry.contains("entry.0.adapter_auto_apply_stack_count=3")); assert!(registry.contains("entry.0.adapter_auto_apply_byte_budget=1048576")); assert!(registry.contains(&format!( "entry.0.assembly_receipt_path=../models/{id}.assembly.receipt" ))); let family_receipt = fs::read_to_string( root.join("models") .join(format!("{id}.adapter-family.receipt")), ) .unwrap(); assert!(family_receipt .contains(&format!("family.adapter_base_quantization={quantization}"))); assert!(family_receipt.contains("adapter_family_preferred_adapter_index=2")); assert!(family_receipt.contains(&format!( "adapter_family_preferred_adapter_path=../models/{id}-sparse.asp1" ))); assert!(family_receipt.contains("adapter_family_auto_apply_stack_count=3")); assert!(family_receipt.contains("adapter_family_auto_apply_stack.0.adapter_index=1")); assert!(family_receipt.contains(&format!( "adapter_family_auto_apply_stack.0.adapter_path=../models/{id}-family.adp1" ))); assert!(family_receipt.contains("adapter_family_auto_apply_stack.1.adapter_index=2")); assert!(family_receipt.contains(&format!( "adapter_family_auto_apply_stack.1.adapter_path=../models/{id}-sparse.asp1" ))); assert!(family_receipt.contains("adapter_family_auto_apply_stack.2.adapter_index=3")); assert!(family_receipt.contains(&format!( "adapter_family_auto_apply_stack.2.adapter_path=../models/{id}-low-rank.alr1" ))); assert_source_backed_alr1_receipt_fields(&family_receipt, &id); assert_module_plan(&root, &id, quantization, ®istry); let assembly_receipt = fs::read_to_string(root.join("models").join(format!("{id}.assembly.receipt"))) .unwrap(); assert!(assembly_receipt.contains(&format!( "promotion_ledger_path=../evidence/{id}/population.ledger" ))); assert!(assembly_receipt.contains("eval_case_evidence_checksum=0x")); assert!(root.join("models").join(format!("{id}.slm")).exists()); assert!(root .join("models") .join(format!("{id}-family.adp1.manifest")) .exists()); assert!(root .join("models") .join(format!("{id}-sparse.asp1.manifest")) .exists()); assert!(root .join("models") .join(format!("{id}-low-rank.alr1.manifest")) .exists()); assert_runtime_manifest(&root); fs::remove_dir_all(root.parent().unwrap()).unwrap(); } } #[test] fn writes_browser_multi_parent_soup_bundle() { let root = unique_dir("soup-bundle").join("tinyrustlm"); write_bundle_path_with_quantization_and_operator(&root, "q8_0", "soup").unwrap(); let id = "multi-parent-soup-q8"; let registry = fs::read_to_string(root.join("models").join("selector.registry")).unwrap(); assert!(registry.contains(&format!("entry.0.candidate_id={id}"))); assert!(registry.contains(&format!("entry.0.model_path=../models/{id}.slm"))); assert!(registry.contains(&format!( "entry.0.adapter_label=Multi-parent weighted soup q8_0 self ADP1" ))); assert!(registry.contains(&format!( "entry.0.module_plan_operator_receipt_path=../evidence/{id}/soup.operator" ))); assert!(registry.contains("entry.0.operator_receipt_status=receipt-bound")); assert!(registry.contains(&format!( "entry.0.operator_receipt_path={}", display_path(&root.join("evidence").join(id).join("soup.operator")) ))); assert!(registry.contains(&format!("entry.0.operator_receipt_operator_id={id}"))); assert!(registry .contains("entry.0.operator_receipt_operator_kind=seed-weighted-parent-pool-soup")); assert!(registry.contains("entry.0.operator_receipt_candidate_slm_checksum=0x")); assert!(registry.contains("entry.0.operator_receipt_candidate_artifact_bytes=")); assert_module_plan_with_operator(&root, id, "q8_0", ®istry, "soup"); let operator_receipt = fs::read_to_string(root.join("evidence").join(id).join("soup.operator")).unwrap(); assert!(operator_receipt.contains("operator_kind=seed-weighted-parent-pool-soup")); assert!(operator_receipt.contains("soup_merge_rule=seed-weighted-direct-parameter-average")); assert!(operator_receipt.contains("soup_parent_weight_checksum=0x")); let candidate_manifest = fs::read_to_string(root.join("evidence").join(id).join("soup.candidate")).unwrap(); assert!(candidate_manifest.contains("operator_kind=seed-weighted-parent-pool-soup")); assert!(candidate_manifest.contains("soup_weighted_value_checksum=0x")); assert!(!candidate_manifest.contains("sign_selection_rule=")); let assembly_receipt = fs::read_to_string(root.join("models").join(format!("{id}.assembly.receipt"))).unwrap(); assert!(assembly_receipt.contains("assembly_strategy=multi-parent-weighted-soup")); for file_name in [ "soup.operator", "soup.candidate", "soup.promotion", "soup.runtime", "soup.eval", "soup.multi.admission", ] { assert!(assembly_receipt.contains(&format!("../evidence/{id}/{file_name}"))); } assert!(root .join("evidence") .join(id) .join("soup.multi.admission") .exists()); assert!(root.join("app").join("app.js").exists()); assert_runtime_manifest(&root); fs::remove_dir_all(root.parent().unwrap()).unwrap(); } #[test] fn writes_combined_browser_multi_parent_bundle() { let root = unique_dir("combined").join("tinyrustlm"); write_bundle_path_with_quantization(&root, "all").unwrap(); let registry = fs::read_to_string(root.join("models").join("selector.registry")).unwrap(); assert!(registry.contains("entry_count=3")); assert!(registry.contains("selector_model_byte_budget=33554432")); assert!(registry.contains("selector_registry_text_byte_budget=262144")); assert!(registry.contains("manifest_text_byte_budget=65536")); assert!(registry.contains("receipt_text_byte_budget=131072")); assert!(registry.contains("evidence_text_byte_budget=131072")); assert!(registry.contains("selector_default_strategy=browser-frugal-quantized")); assert!(registry.contains("selector_default_candidate_id=multi-parent-sign-merge-q4")); assert!(registry.contains("selector_default_quantization=q4_0")); for (index, quantization, suffix) in [(0, "f32", "f32"), (1, "q8_0", "q8"), (2, "q4_0", "q4")] { let id = format!("multi-parent-sign-merge-{suffix}"); assert!(registry.contains(&format!("entry.{index}.candidate_id={id}"))); assert!(registry.contains(&format!("entry.{index}.quantization={quantization}"))); assert!(registry.contains(&format!("entry.{index}.model_path=../models/{id}.slm"))); assert_registry_breeding_fields(®istry, &format!("entry.{index}")); assert!(registry.contains(&format!("entry.{index}.adapter_count=4"))); assert!(registry.contains(&format!( "entry.{index}.adapter.2.path=../models/{id}-sparse.asp1" ))); assert!(registry.contains(&format!( "entry.{index}.adapter.3.path=../models/{id}-low-rank.alr1" ))); assert!(registry.contains(&format!( "entry.{index}.adapter_family_receipt_path=../models/{id}.adapter-family.receipt" ))); assert!(registry.contains(&format!("entry.{index}.adapter_auto_apply_status=enabled"))); assert!(registry.contains(&format!( "entry.{index}.adapter_auto_apply_strategy=receipt-preferred-compatible" ))); assert!(registry.contains(&format!( "entry.{index}.adapter_auto_apply_stack_status=enabled" ))); assert!(registry.contains(&format!( "entry.{index}.adapter_auto_apply_stack_strategy=receipt-declared-compatible-stack" ))); assert!(registry.contains(&format!("entry.{index}.adapter_auto_apply_stack_count=3"))); assert!(registry.contains(&format!( "entry.{index}.adapter_auto_apply_byte_budget=1048576" ))); assert!(registry.contains(&format!( "entry.{index}.assembly_receipt_path=../models/{id}.assembly.receipt" ))); let family_receipt = fs::read_to_string( root.join("models") .join(format!("{id}.adapter-family.receipt")), ) .unwrap(); assert!(family_receipt.contains("adapter_family_preferred_adapter_index=2")); assert!(family_receipt.contains(&format!( "adapter_family_preferred_adapter_path=../models/{id}-sparse.asp1" ))); assert!(family_receipt.contains("adapter_family_auto_apply_stack_count=3")); assert!(family_receipt.contains(&format!( "adapter_family_auto_apply_stack.0.adapter_path=../models/{id}-family.adp1" ))); assert!(family_receipt.contains(&format!( "adapter_family_auto_apply_stack.1.adapter_path=../models/{id}-sparse.asp1" ))); assert!(family_receipt.contains(&format!( "adapter_family_auto_apply_stack.2.adapter_path=../models/{id}-low-rank.alr1" ))); assert_source_backed_alr1_receipt_fields(&family_receipt, &id); assert_module_plan(&root, &id, quantization, ®istry); assert!(root.join("models").join(format!("{id}.slm")).exists()); assert!(root .join("evidence") .join(&id) .join("sign-merge.multi.admission") .exists()); } assert!(root.join("app").join("app.js").exists()); assert!(root.join("runtime").join("tinyrustlm.wasm").exists()); assert_runtime_manifest(&root); fs::remove_dir_all(root.parent().unwrap()).unwrap(); } #[test] fn writes_combined_browser_multi_parent_soup_bundle() { // Exercises the soup operator across the all-quantization bundle path. let root = unique_dir("combined-soup").join("tinyrustlm"); write_bundle_path_with_quantization_and_operator(&root, "all", "soup").unwrap(); let registry = fs::read_to_string(root.join("models").join("selector.registry")).unwrap(); assert!(registry.contains("entry_count=3")); assert!(registry.contains("selector_default_strategy=browser-frugal-quantized")); assert!(registry.contains("selector_default_candidate_id=multi-parent-soup-q4")); assert!(registry.contains("selector_default_quantization=q4_0")); for (index, quantization, suffix) in [(0, "f32", "f32"), (1, "q8_0", "q8"), (2, "q4_0", "q4")] { let id = format!("multi-parent-soup-{suffix}"); assert!(registry.contains(&format!("entry.{index}.candidate_id={id}"))); assert!(registry.contains(&format!("entry.{index}.quantization={quantization}"))); assert!(registry.contains(&format!("entry.{index}.model_path=../models/{id}.slm"))); assert!(registry.contains(&format!( "entry.{index}.adapter_label=Multi-parent weighted soup {quantization} self ADP1" ))); assert!(registry.contains(&format!( "entry.{index}.module_plan_operator_receipt_path=../evidence/{id}/soup.operator" ))); assert!(registry.contains(&format!("entry.{index}.operator_receipt_operator_id={id}"))); assert!(registry.contains(&format!( "entry.{index}.operator_receipt_operator_kind=seed-weighted-parent-pool-soup" ))); assert_module_plan_with_operator(&root, &id, quantization, ®istry, "soup"); let operator_receipt = fs::read_to_string(root.join("evidence").join(&id).join("soup.operator")).unwrap(); assert!(operator_receipt.contains("operator_kind=seed-weighted-parent-pool-soup")); assert!( operator_receipt.contains("soup_merge_rule=seed-weighted-direct-parameter-average") ); let assembly_receipt = fs::read_to_string(root.join("models").join(format!("{id}.assembly.receipt"))) .unwrap(); assert!(assembly_receipt.contains("assembly_strategy=multi-parent-weighted-soup")); assert!(assembly_receipt.contains(&format!("../evidence/{id}/soup.operator"))); assert!(assembly_receipt.contains(&format!("../evidence/{id}/soup.multi.admission"))); assert!(root .join("evidence") .join(&id) .join("soup.multi.admission") .exists()); assert!(!root .join("evidence") .join(&id) .join("sign-merge.multi.admission") .exists()); } assert!(root.join("app").join("app.js").exists()); assert!(root.join("runtime").join("tinyrustlm.wasm").exists()); assert_runtime_manifest(&root); fs::remove_dir_all(root.parent().unwrap()).unwrap(); } #[test] fn writes_combined_browser_multi_parent_mixed_operator_bundle() { // Exercises the mixed operator selector path across both generated parent-pool families. let root = unique_dir("combined-mixed").join("tinyrustlm"); write_bundle_path_with_quantization_and_operator(&root, "all", "mixed").unwrap(); let registry = fs::read_to_string(root.join("models").join("selector.registry")).unwrap(); assert!(registry.contains("entry_count=6")); assert!(registry.contains("selector_default_strategy=browser-frugal-quantized")); assert!(registry.contains("selector_default_candidate_id=multi-parent-sign-merge-q4")); assert!(registry.contains("selector_default_quantization=q4_0")); for ( index, quantization, suffix, family, evidence_prefix, operator_kind, assembly_strategy, ) in [ ( 0, "f32", "f32", "multi-parent-sign-merge", "sign-merge", "sign-aware-parent-pool-merge", "multi-parent-sign-merge", ), ( 1, "q8_0", "q8", "multi-parent-sign-merge", "sign-merge", "sign-aware-parent-pool-merge", "multi-parent-sign-merge", ), ( 2, "q4_0", "q4", "multi-parent-sign-merge", "sign-merge", "sign-aware-parent-pool-merge", "multi-parent-sign-merge", ), ( 3, "f32", "f32", "multi-parent-soup", "soup", "seed-weighted-parent-pool-soup", "multi-parent-weighted-soup", ), ( 4, "q8_0", "q8", "multi-parent-soup", "soup", "seed-weighted-parent-pool-soup", "multi-parent-weighted-soup", ), ( 5, "q4_0", "q4", "multi-parent-soup", "soup", "seed-weighted-parent-pool-soup", "multi-parent-weighted-soup", ), ] { let id = format!("{family}-{suffix}"); assert!(registry.contains(&format!("entry.{index}.candidate_id={id}"))); assert!(registry.contains(&format!("entry.{index}.quantization={quantization}"))); assert!(registry.contains(&format!( "entry.{index}.module_plan_operator_receipt_path=../evidence/{id}/{evidence_prefix}.operator" ))); assert!(registry.contains(&format!( "entry.{index}.operator_receipt_operator_kind={operator_kind}" ))); assert_module_plan_with_operator(&root, &id, quantization, ®istry, evidence_prefix); let assembly_receipt = fs::read_to_string(root.join("models").join(format!("{id}.assembly.receipt"))) .unwrap(); assert!(assembly_receipt.contains(&format!("assembly_strategy={assembly_strategy}"))); assert!(assembly_receipt.contains(&format!( "../evidence/{id}/{evidence_prefix}.multi.admission" ))); assert!(root .join("evidence") .join(&id) .join(format!("{evidence_prefix}.multi.admission")) .exists()); } assert!(root.join("app").join("app.js").exists()); assert!(root.join("runtime").join("tinyrustlm.wasm").exists()); assert_runtime_manifest(&root); fs::remove_dir_all(root.parent().unwrap()).unwrap(); } #[test] fn writes_standalone_runtime_manifest() { let root = unique_dir("runtime-manifest"); fs::create_dir_all(&root).unwrap(); let wasm_path = root.join("tinyrustlm.wasm"); let manifest_path = root.join("tinyrustlm.wasm.manifest"); fs::write(&wasm_path, [0x00, 0x61, 0x73, 0x6d]).unwrap(); write_runtime_wasm_manifest_path(&wasm_path, &manifest_path).unwrap(); let manifest = fs::read_to_string(&manifest_path).unwrap(); assert!(manifest.contains("tinyrustlm_wasm_manifest_version=1")); assert!(manifest.contains("runtime_kind=tinyrustlm-rust-wasm")); assert!(manifest.contains("runtime_status=validated-local-runtime")); assert!(manifest.contains("runtime_wasm_path=../runtime/tinyrustlm.wasm")); assert!(manifest.contains("runtime_wasm_bytes=4")); assert!(manifest.contains(&format!( "runtime_wasm_checksum={}", hex64(provenance::text_checksum(&[0x00, 0x61, 0x73, 0x6d])) ))); assert!(manifest.contains("required_next_gate=instantiate-wasm-runtime")); fs::remove_dir_all(root).unwrap(); } fn assert_runtime_manifest(root: &Path) { let wasm_path = root.join("runtime").join("tinyrustlm.wasm"); let manifest_path = root.join("runtime").join("tinyrustlm.wasm.manifest"); let wasm_bytes = fs::read(&wasm_path).unwrap(); let manifest = fs::read_to_string(&manifest_path).unwrap(); assert!(manifest.contains("tinyrustlm_wasm_manifest_version=1")); assert!(manifest.contains("runtime_kind=tinyrustlm-rust-wasm")); assert!(manifest.contains("runtime_status=validated-local-runtime")); assert!(manifest.contains("runtime_wasm_path=../runtime/tinyrustlm.wasm")); assert!(manifest.contains(&format!("runtime_wasm_bytes={}", wasm_bytes.len()))); assert!(manifest.contains(&format!( "runtime_wasm_checksum={}", hex64(provenance::text_checksum(&wasm_bytes)) ))); assert!(manifest.contains("required_next_gate=instantiate-wasm-runtime")); } fn unique_dir(label: &str) -> PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-browser-bundle-{label}-{nanos}")) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/browser_bundle.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/candidate.rs BYTES: 37185 SHA256: 0482D43F9C0437C39B6F3C56D679F6ACDC7C8E0CE8FD524135C62E44B550B232 ================================================================================ //! Candidate artifact manifests for offline model-breeding output gates. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::lineage; use crate::slm_validate::{self, ValidationReport}; const CANDIDATE_ARTIFACT_VERSION: &str = "1"; const ARTIFACT_KIND_SLM: &str = "slm"; const CANDIDATE_STATUS_ARTIFACT_WRITTEN: &str = "artifact-written"; const CANDIDATE_ARTIFACT_STATUS: &str = "written"; const CANDIDATE_ADMISSION_STATUS: &str = "slm-validated"; const CANDIDATE_PARENT_CONTRACT: &str = "matches-parent-direct-parameter-contract"; const CANDIDATE_EVAL_STATUS: &str = "pending"; const REQUIRED_NEXT_GATE: &str = "candidate-runtime-smoke-plus-eval-plus-provenance-promotion"; const OPERATOR_RECEIPT_STATUS_BOUND: &str = "receipt-bound"; const OPERATOR_RECEIPT_PREFIX: &str = "operator_receipt_"; const PARENT_KEYS: [&str; 9] = [ "path", "slm_checksum", "model_shape", "tensor_count", "parameter_count", "quantization", "output_contract", "tokenizer_checksum", "tensor_layout_checksum", ]; // Keeps caller-supplied receipt text paired with the path recorded in the manifest. #[derive(Clone, Copy)] struct OperatorReceiptBinding<'a> { path: &'a str, text: &'a str, } // Holds receipt fields after they have been checked against lineage and candidate bytes. struct ValidatedOperatorReceipt { checksum: String, operator_id: String, operator_kind: String, candidate_slm_checksum: String, candidate_artifact_bytes: String, } /// Writes a candidate artifact manifest bound to compatibility, lineage, a validated `.slm`, and optionally its producer receipt. pub(crate) fn write_manifest_path( compatibility: &Path, lineage_manifest: &Path, candidate_slm: &Path, output: &Path, operator_receipt: Option<&Path>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let candidate_bytes = fs::read(candidate_slm)?; let operator_receipt_text = read_operator_receipt_binding(operator_receipt)?; let operator_receipt_binding = operator_receipt_text .as_ref() .map(|(path, text)| OperatorReceiptBinding { path: path.as_str(), text: text.as_str(), }); let manifest = build_manifest_text_with_operator_receipt( &compatibility_text, &lineage_text, &candidate_bytes, &candidate_slm.display().to_string(), operator_receipt_binding, )?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, manifest)?; println!( "SLM candidate artifact manifest written: {}", output.display() ); Ok(()) } /// Validates a candidate artifact manifest against compatibility, lineage, a `.slm`, and optionally its producer receipt. pub(crate) fn validate_manifest_path( compatibility: &Path, lineage_manifest: &Path, candidate_slm: &Path, manifest: &Path, operator_receipt: Option<&Path>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let candidate_bytes = fs::read(candidate_slm)?; let manifest_text = fs::read_to_string(manifest)?; let operator_receipt_text = read_operator_receipt_binding(operator_receipt)?; let operator_receipt_binding = operator_receipt_text .as_ref() .map(|(path, text)| OperatorReceiptBinding { path: path.as_str(), text: text.as_str(), }); validate_manifest_text_with_operator_receipt( &compatibility_text, &lineage_text, &candidate_bytes, &candidate_slm.display().to_string(), &manifest_text, operator_receipt_binding, )?; println!("SLM candidate artifact validation: PASS"); println!("lineage: {}", lineage_manifest.display()); println!("candidate: {}", candidate_slm.display()); println!("manifest: {}", manifest.display()); Ok(()) } /// Builds a candidate artifact manifest bound to compatibility, lineage, and `.slm` bytes. pub(crate) fn build_manifest_text( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, ) -> io::Result { build_manifest_text_with_operator_receipt_text( compatibility_text, lineage_text, candidate_bytes, candidate_path, None, ) } /// Builds candidate artifact manifest text while optionally binding a producer receipt path and text. pub(crate) fn build_manifest_text_with_operator_receipt_text( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, operator_receipt: Option<(&str, &str)>, ) -> io::Result { let operator_receipt = operator_receipt.map(|(path, text)| OperatorReceiptBinding { path, text }); build_manifest_text_with_operator_receipt( compatibility_text, lineage_text, candidate_bytes, candidate_path, operator_receipt, ) } // Builds the same candidate manifest while optionally checksum-binding the producer receipt. fn build_manifest_text_with_operator_receipt( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, operator_receipt: Option>, ) -> io::Result { lineage::validate_text(compatibility_text, lineage_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let report = slm_validate::validate_bytes(candidate_bytes, candidate_path)?; validate_candidate_contract(&lineage_fields, &report)?; let validated_operator_receipt = operator_receipt .as_ref() .map(|binding| validate_operator_receipt(binding, &lineage_fields, &report)) .transpose()?; let mut text = String::new(); push_line( &mut text, "tinyrustlm_candidate_artifact_version", CANDIDATE_ARTIFACT_VERSION, ); push_line( &mut text, "candidate_id", require_key(&lineage_fields, "candidate_id")?, ); push_line( &mut text, "candidate_status", CANDIDATE_STATUS_ARTIFACT_WRITTEN, ); push_line(&mut text, "artifact_kind", ARTIFACT_KIND_SLM); push_line( &mut text, "operator_id", require_key(&lineage_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(&lineage_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(&lineage_fields, "resource_budget")?, ); if let (Some(binding), Some(receipt)) = (operator_receipt, validated_operator_receipt.as_ref()) { push_operator_receipt_lines(&mut text, binding, receipt); } push_line( &mut text, "compatibility_report_checksum", require_key(&lineage_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(&lineage_fields, "compatibility_scope")?, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, &lineage_fields, 0)?; push_parent_lines(&mut text, &lineage_fields, 1)?; push_candidate_lines(&mut text, &report); push_line( &mut text, "candidate_artifact_status", CANDIDATE_ARTIFACT_STATUS, ); push_line( &mut text, "candidate_admission_status", CANDIDATE_ADMISSION_STATUS, ); push_line( &mut text, "candidate_parent_contract", CANDIDATE_PARENT_CONTRACT, ); push_line(&mut text, "candidate_eval_status", CANDIDATE_EVAL_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } /// Validates candidate artifact manifest text against compatibility, lineage, and `.slm` bytes. #[allow(dead_code)] pub(crate) fn validate_manifest_text( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, manifest_text: &str, ) -> io::Result<()> { validate_manifest_text_with_operator_receipt_text( compatibility_text, lineage_text, candidate_bytes, candidate_path, manifest_text, None, ) } /// Validates candidate artifact manifest text while optionally recomputing its producer receipt binding. pub(crate) fn validate_manifest_text_with_operator_receipt_text( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, manifest_text: &str, operator_receipt: Option<(&str, &str)>, ) -> io::Result<()> { let operator_receipt = operator_receipt.map(|(path, text)| OperatorReceiptBinding { path, text }); validate_manifest_text_with_operator_receipt( compatibility_text, lineage_text, candidate_bytes, candidate_path, manifest_text, operator_receipt, ) } // Validates candidate manifests and recomputes optional producer-receipt bindings. fn validate_manifest_text_with_operator_receipt( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, manifest_text: &str, operator_receipt: Option>, ) -> io::Result<()> { lineage::validate_text(compatibility_text, lineage_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let manifest = parse_manifest(manifest_text, "candidate artifact manifest")?; let report = slm_validate::validate_bytes(candidate_bytes, candidate_path)?; validate_candidate_contract(&lineage_fields, &report)?; let validated_operator_receipt = operator_receipt .as_ref() .map(|binding| validate_operator_receipt(binding, &lineage_fields, &report)) .transpose()?; require_equal( &manifest, "tinyrustlm_candidate_artifact_version", CANDIDATE_ARTIFACT_VERSION, )?; require_equal( &manifest, "candidate_id", require_key(&lineage_fields, "candidate_id")?, )?; require_equal( &manifest, "candidate_status", CANDIDATE_STATUS_ARTIFACT_WRITTEN, )?; require_equal(&manifest, "artifact_kind", ARTIFACT_KIND_SLM)?; require_equal( &manifest, "operator_id", require_key(&lineage_fields, "operator_id")?, )?; require_equal( &manifest, "operator_lane", require_key(&lineage_fields, "operator_lane")?, )?; require_equal( &manifest, "resource_budget", require_key(&lineage_fields, "resource_budget")?, )?; if let (Some(binding), Some(receipt)) = (operator_receipt, validated_operator_receipt.as_ref()) { require_operator_receipt_lines(&manifest, binding, receipt)?; } else { reject_unbound_operator_receipt_fields(&manifest)?; } require_equal( &manifest, "compatibility_report_checksum", require_key(&lineage_fields, "compatibility_report_checksum")?, )?; require_equal( &manifest, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), )?; require_equal( &manifest, "compatibility_scope", require_key(&lineage_fields, "compatibility_scope")?, )?; require_equal(&manifest, "parent_count", "2")?; require_parent_lines(&lineage_fields, &manifest, 0)?; require_parent_lines(&lineage_fields, &manifest, 1)?; require_candidate_lines(&manifest, &report)?; require_equal( &manifest, "candidate_artifact_status", CANDIDATE_ARTIFACT_STATUS, )?; require_equal( &manifest, "candidate_admission_status", CANDIDATE_ADMISSION_STATUS, )?; require_equal( &manifest, "candidate_parent_contract", CANDIDATE_PARENT_CONTRACT, )?; require_equal(&manifest, "candidate_eval_status", CANDIDATE_EVAL_STATUS)?; require_equal(&manifest, "required_next_gate", REQUIRED_NEXT_GATE)?; Ok(()) } // Reads an optional operator receipt once while preserving the display path for manifest output. fn read_operator_receipt_binding( operator_receipt: Option<&Path>, ) -> io::Result> { operator_receipt .map(|path| { let text = fs::read_to_string(path)?; Ok((path.display().to_string(), text)) }) .transpose() } // Checks the receipt identity fields before its checksum is allowed into the candidate manifest. fn validate_operator_receipt( binding: &OperatorReceiptBinding<'_>, lineage_fields: &HashMap, report: &ValidationReport, ) -> io::Result { let receipt_fields = parse_manifest(binding.text, "operator receipt")?; require_equal( &receipt_fields, "candidate_id", require_key(lineage_fields, "candidate_id")?, )?; require_equal( &receipt_fields, "operator_id", require_key(lineage_fields, "operator_id")?, )?; require_equal( &receipt_fields, "candidate_artifact_bytes", &report.file_bytes().to_string(), )?; require_equal( &receipt_fields, "candidate_slm_checksum", &hex64(report.checksum()), )?; Ok(ValidatedOperatorReceipt { checksum: hex64(lineage::text_checksum(binding.text.as_bytes())), operator_id: require_key(&receipt_fields, "operator_id")?.to_string(), operator_kind: require_key(&receipt_fields, "operator_kind")?.to_string(), candidate_slm_checksum: require_key(&receipt_fields, "candidate_slm_checksum")?.to_string(), candidate_artifact_bytes: require_key(&receipt_fields, "candidate_artifact_bytes")? .to_string(), }) } // Records the producer receipt binding as manifest fields that can be recomputed later. fn push_operator_receipt_lines( text: &mut String, binding: OperatorReceiptBinding<'_>, receipt: &ValidatedOperatorReceipt, ) { push_line( text, "operator_receipt_status", OPERATOR_RECEIPT_STATUS_BOUND, ); push_line(text, "operator_receipt_path", binding.path); push_line(text, "operator_receipt_checksum", &receipt.checksum); push_line(text, "operator_receipt_operator_id", &receipt.operator_id); push_line( text, "operator_receipt_operator_kind", &receipt.operator_kind, ); push_line( text, "operator_receipt_candidate_slm_checksum", &receipt.candidate_slm_checksum, ); push_line( text, "operator_receipt_candidate_artifact_bytes", &receipt.candidate_artifact_bytes, ); } // Recomputes every stored producer receipt field during candidate manifest validation. fn require_operator_receipt_lines( manifest: &HashMap, binding: OperatorReceiptBinding<'_>, receipt: &ValidatedOperatorReceipt, ) -> io::Result<()> { require_equal( manifest, "operator_receipt_status", OPERATOR_RECEIPT_STATUS_BOUND, )?; require_equal(manifest, "operator_receipt_path", binding.path)?; require_equal(manifest, "operator_receipt_checksum", &receipt.checksum)?; require_equal( manifest, "operator_receipt_operator_id", &receipt.operator_id, )?; require_equal( manifest, "operator_receipt_operator_kind", &receipt.operator_kind, )?; require_equal( manifest, "operator_receipt_candidate_slm_checksum", &receipt.candidate_slm_checksum, )?; require_equal( manifest, "operator_receipt_candidate_artifact_bytes", &receipt.candidate_artifact_bytes, )?; Ok(()) } // Keeps bound manifests from validating unless the caller supplies the referenced receipt. fn reject_unbound_operator_receipt_fields(manifest: &HashMap) -> io::Result<()> { if let Some(key) = manifest .keys() .find(|key| key.starts_with(OPERATOR_RECEIPT_PREFIX)) { return Err(invalid(&format!( "operator receipt binding requires an input receipt for {key}" ))); } Ok(()) } fn validate_candidate_contract( lineage_fields: &HashMap, report: &ValidationReport, ) -> io::Result<()> { require_report_equal( lineage_fields, "parent.0.model_shape", &report.shape_summary(), )?; require_report_equal( lineage_fields, "parent.0.tensor_count", &report.tensor_count().to_string(), )?; require_report_equal( lineage_fields, "parent.0.parameter_count", &report.parameter_count().to_string(), )?; require_report_equal( lineage_fields, "parent.0.quantization", report.quantization_label(), )?; require_report_equal( lineage_fields, "parent.0.output_contract", report.output_contract_label(), )?; require_report_equal( lineage_fields, "parent.0.tokenizer_checksum", &hex64(report.tokenizer_checksum()), )?; require_report_equal( lineage_fields, "parent.0.tensor_layout_checksum", &hex64(report.tensor_layout_checksum()), )?; Ok(()) } fn push_parent_lines( text: &mut String, lineage_fields: &HashMap, index: usize, ) -> io::Result<()> { for key in PARENT_KEYS { let full_key = format!("parent.{index}.{key}"); push_line(text, &full_key, require_key(lineage_fields, &full_key)?); } Ok(()) } fn require_parent_lines( lineage_fields: &HashMap, manifest: &HashMap, index: usize, ) -> io::Result<()> { for key in PARENT_KEYS { let full_key = format!("parent.{index}.{key}"); require_equal(manifest, &full_key, require_key(lineage_fields, &full_key)?)?; } Ok(()) } fn push_candidate_lines(text: &mut String, report: &ValidationReport) { push_line(text, "candidate_artifact_path", report.path()); push_line( text, "candidate_artifact_bytes", &report.file_bytes().to_string(), ); push_line( text, "candidate_slm_version", &report.slm_version().to_string(), ); push_line(text, "candidate_slm_checksum", &hex64(report.checksum())); push_line(text, "candidate_model_shape", &report.shape_summary()); push_line( text, "candidate_tensor_count", &report.tensor_count().to_string(), ); push_line( text, "candidate_parameter_count", &report.parameter_count().to_string(), ); push_line(text, "candidate_quantization", report.quantization_label()); push_line( text, "candidate_output_contract", report.output_contract_label(), ); push_line( text, "candidate_tokenizer_checksum", &hex64(report.tokenizer_checksum()), ); push_line( text, "candidate_tensor_layout_checksum", &hex64(report.tensor_layout_checksum()), ); } fn require_candidate_lines( manifest: &HashMap, report: &ValidationReport, ) -> io::Result<()> { require_equal(manifest, "candidate_artifact_path", report.path())?; require_equal( manifest, "candidate_artifact_bytes", &report.file_bytes().to_string(), )?; require_equal( manifest, "candidate_slm_version", &report.slm_version().to_string(), )?; require_equal( manifest, "candidate_slm_checksum", &hex64(report.checksum()), )?; require_equal(manifest, "candidate_model_shape", &report.shape_summary())?; require_equal( manifest, "candidate_tensor_count", &report.tensor_count().to_string(), )?; require_equal( manifest, "candidate_parameter_count", &report.parameter_count().to_string(), )?; require_equal( manifest, "candidate_quantization", report.quantization_label(), )?; require_equal( manifest, "candidate_output_contract", report.output_contract_label(), )?; require_equal( manifest, "candidate_tokenizer_checksum", &hex64(report.tokenizer_checksum()), )?; require_equal( manifest, "candidate_tensor_layout_checksum", &hex64(report.tensor_layout_checksum()), )?; Ok(()) } fn parse_manifest(text: &str, label: &str) -> io::Result> { let mut fields = HashMap::new(); for (line_index, raw_line) in text.lines().enumerate() { let line = raw_line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let Some((key, value)) = line.split_once('=') else { return Err(invalid(&format!( "{label} line {} is missing '='", line_index + 1 ))); }; let key = key.trim(); let value = value.trim(); validate_key(key, label, line_index + 1)?; validate_value(value, key)?; if fields.insert(key.to_string(), value.to_string()).is_some() { return Err(invalid(&format!("duplicate {label} key {key}"))); } } Ok(fields) } fn validate_key(key: &str, label: &str, line_number: usize) -> io::Result<()> { if key.is_empty() || !key .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_')) { return Err(invalid(&format!( "{label} line {line_number} has an invalid key" ))); } Ok(()) } fn validate_value(value: &str, key: &str) -> io::Result<()> { if value.is_empty() || value.contains('\n') || value.contains('\r') { return Err(invalid(&format!("{key} has an invalid value"))); } Ok(()) } fn require_key<'a>(fields: &'a HashMap, key: &str) -> io::Result<&'a str> { fields .get(key) .map(String::as_str) .ok_or_else(|| invalid(&format!("manifest missing required key {key}"))) } fn require_equal(fields: &HashMap, key: &str, expected: &str) -> io::Result<()> { let actual = require_key(fields, key)?; if actual != expected { return Err(invalid(&format!( "manifest key {key} was {actual}, expected {expected}" ))); } Ok(()) } fn require_report_equal( fields: &HashMap, key: &str, expected: &str, ) -> io::Result<()> { let actual = require_key(fields, key)?; if actual != expected { return Err(invalid(&format!( "candidate artifact contract expected {key} {actual}, candidate had {expected}" ))); } Ok(()) } fn push_line(text: &mut String, key: &str, value: &str) { text.push_str(key); text.push('='); text.push_str(value); text.push('\n'); } fn hex64(value: u64) -> String { format!("0x{value:016x}") } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } #[cfg(test)] mod tests { use super::*; use crate::build_model_file; use crate::compatibility; use crate::tensor_writer::{ tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_F32, DTYPE_Q8_0, }; use crate::tokenizer_writer::ByteTokenizerSection; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; #[test] fn writes_and_validates_candidate_artifact_manifest() { let compatibility = passing_compatibility_text(); let lineage = lineage_text(&compatibility); let candidate = tiny_fixture_q8_bytes(); let manifest = build_manifest_text(&compatibility, &lineage, &candidate, "candidate.slm").unwrap(); validate_manifest_text( &compatibility, &lineage, &candidate, "candidate.slm", &manifest, ) .unwrap(); assert!(manifest.contains("candidate_status=artifact-written")); assert!(manifest.contains("candidate_admission_status=slm-validated")); assert!( manifest.contains("candidate_parent_contract=matches-parent-direct-parameter-contract") ); assert!(manifest.contains( "required_next_gate=candidate-runtime-smoke-plus-eval-plus-provenance-promotion" )); } #[test] fn writes_and_validates_operator_receipt_binding() { let compatibility = passing_compatibility_text(); let lineage = lineage_text(&compatibility); let candidate = tiny_fixture_q8_bytes(); let receipt = operator_receipt_text(&lineage, &candidate, "candidate.slm"); let manifest = build_manifest_text_with_operator_receipt( &compatibility, &lineage, &candidate, "candidate.slm", Some(OperatorReceiptBinding { path: "candidate.operator", text: &receipt, }), ) .unwrap(); validate_manifest_text_with_operator_receipt( &compatibility, &lineage, &candidate, "candidate.slm", &manifest, Some(OperatorReceiptBinding { path: "candidate.operator", text: &receipt, }), ) .unwrap(); assert!(manifest.contains("operator_receipt_status=receipt-bound")); assert!(manifest.contains("operator_receipt_path=candidate.operator")); assert!(manifest.contains(&format!( "operator_receipt_checksum={}", hex64(lineage::text_checksum(receipt.as_bytes())) ))); assert!(manifest .contains("operator_receipt_operator_kind=deterministic-bounded-parameter-mutation")); } #[test] fn path_functions_accept_unbound_and_bound_operator_receipt_inputs() { let dir = unique_temp_dir("operator-receipt-path"); fs::create_dir_all(&dir).unwrap(); let compatibility = passing_compatibility_text(); let lineage = lineage_text(&compatibility); let candidate = tiny_fixture_q8_bytes(); let compatibility_path = dir.join("parents.compat"); let lineage_path = dir.join("candidate.lineage"); let candidate_path = dir.join("candidate.slm"); let receipt_path = dir.join("candidate.operator"); let unbound_manifest_path = dir.join("unbound.candidate"); let bound_manifest_path = dir.join("bound.candidate"); let receipt = operator_receipt_text(&lineage, &candidate, &candidate_path.display().to_string()); fs::write(&compatibility_path, compatibility).unwrap(); fs::write(&lineage_path, lineage).unwrap(); fs::write(&candidate_path, candidate).unwrap(); fs::write(&receipt_path, receipt).unwrap(); write_manifest_path( &compatibility_path, &lineage_path, &candidate_path, &unbound_manifest_path, None, ) .unwrap(); validate_manifest_path( &compatibility_path, &lineage_path, &candidate_path, &unbound_manifest_path, None, ) .unwrap(); write_manifest_path( &compatibility_path, &lineage_path, &candidate_path, &bound_manifest_path, Some(&receipt_path), ) .unwrap(); validate_manifest_path( &compatibility_path, &lineage_path, &candidate_path, &bound_manifest_path, Some(&receipt_path), ) .unwrap(); let bound_manifest = fs::read_to_string(&bound_manifest_path).unwrap(); assert!( bound_manifest.contains(&format!("operator_receipt_path={}", receipt_path.display())) ); fs::remove_dir_all(&dir).unwrap(); } #[test] fn rejects_candidate_artifact_that_breaks_parent_contract() { let compatibility = passing_compatibility_text(); let lineage = lineage_text(&compatibility); let candidate = tiny_fixture_f32_bytes(); let error = build_manifest_text(&compatibility, &lineage, &candidate, "candidate.slm").unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate artifact contract")); } #[test] fn validation_rejects_lineage_checksum_drift() { let compatibility = passing_compatibility_text(); let lineage = lineage_text(&compatibility); let candidate = tiny_fixture_q8_bytes(); let manifest = build_manifest_text(&compatibility, &lineage, &candidate, "candidate.slm").unwrap(); let changed_lineage = format!("{lineage}# checksum-affecting note\n"); let error = validate_manifest_text( &compatibility, &changed_lineage, &candidate, "candidate.slm", &manifest, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("lineage_manifest_checksum")); } #[test] fn validation_rejects_candidate_artifact_drift() { let compatibility = passing_compatibility_text(); let lineage = lineage_text(&compatibility); let candidate = tiny_fixture_q8_bytes(); let manifest = build_manifest_text(&compatibility, &lineage, &candidate, "candidate.slm").unwrap(); let changed_candidate = tiny_fixture_f32_bytes(); let error = validate_manifest_text( &compatibility, &lineage, &changed_candidate, "candidate.slm", &manifest, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate artifact contract")); } #[test] fn validation_rejects_manifest_field_drift() { let compatibility = passing_compatibility_text(); let lineage = lineage_text(&compatibility); let candidate = tiny_fixture_q8_bytes(); let manifest = build_manifest_text(&compatibility, &lineage, &candidate, "candidate.slm") .unwrap() .replace( "candidate_eval_status=pending", "candidate_eval_status=pass", ); let error = validate_manifest_text( &compatibility, &lineage, &candidate, "candidate.slm", &manifest, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate_eval_status")); } #[test] fn validation_rejects_operator_receipt_checksum_drift() { let compatibility = passing_compatibility_text(); let lineage = lineage_text(&compatibility); let candidate = tiny_fixture_q8_bytes(); let receipt = operator_receipt_text(&lineage, &candidate, "candidate.slm"); let manifest = build_manifest_text_with_operator_receipt( &compatibility, &lineage, &candidate, "candidate.slm", Some(OperatorReceiptBinding { path: "candidate.operator", text: &receipt, }), ) .unwrap(); let drifted_receipt = format!("{receipt}# checksum drift\n"); let error = validate_manifest_text_with_operator_receipt( &compatibility, &lineage, &candidate, "candidate.slm", &manifest, Some(OperatorReceiptBinding { path: "candidate.operator", text: &drifted_receipt, }), ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator_receipt_checksum")); } #[test] fn validation_rejects_bound_manifest_without_operator_receipt_input() { let compatibility = passing_compatibility_text(); let lineage = lineage_text(&compatibility); let candidate = tiny_fixture_q8_bytes(); let receipt = operator_receipt_text(&lineage, &candidate, "candidate.slm"); let manifest = build_manifest_text_with_operator_receipt( &compatibility, &lineage, &candidate, "candidate.slm", Some(OperatorReceiptBinding { path: "candidate.operator", text: &receipt, }), ) .unwrap(); let error = validate_manifest_text( &compatibility, &lineage, &candidate, "candidate.slm", &manifest, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator receipt binding")); } #[test] fn build_rejects_operator_receipt_candidate_checksum_drift() { let compatibility = passing_compatibility_text(); let lineage = lineage_text(&compatibility); let candidate = tiny_fixture_q8_bytes(); let receipt = operator_receipt_text(&lineage, &candidate, "candidate.slm"); let report = slm_validate::validate_bytes(&candidate, "candidate.slm").unwrap(); let bad_receipt = receipt.replace( &format!("candidate_slm_checksum={}", hex64(report.checksum())), "candidate_slm_checksum=0x0000000000000000", ); let error = build_manifest_text_with_operator_receipt( &compatibility, &lineage, &candidate, "candidate.slm", Some(OperatorReceiptBinding { path: "candidate.operator", text: &bad_receipt, }), ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate_slm_checksum")); } fn passing_compatibility_text() -> String { let left = tiny_fixture_q8_bytes(); let right = tiny_fixture_q8_bytes(); compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm").unwrap() } fn lineage_text(compatibility: &str) -> String { lineage::build_template_text(compatibility, "tiny-q8-candidate", "operator-a", "fit") .unwrap() } fn operator_receipt_text(lineage_text: &str, candidate: &[u8], candidate_path: &str) -> String { let lineage_fields = parse_manifest(lineage_text, "lineage").unwrap(); let report = slm_validate::validate_bytes(candidate, candidate_path).unwrap(); let mut text = String::new(); push_line( &mut text, "operator_kind", "deterministic-bounded-parameter-mutation", ); push_line( &mut text, "candidate_id", require_key(&lineage_fields, "candidate_id").unwrap(), ); push_line( &mut text, "operator_id", require_key(&lineage_fields, "operator_id").unwrap(), ); push_line(&mut text, "candidate_artifact_path", report.path()); push_line( &mut text, "candidate_artifact_bytes", &report.file_bytes().to_string(), ); push_line( &mut text, "candidate_slm_checksum", &hex64(report.checksum()), ); push_line( &mut text, "required_next_gate", "candidate-manifest-plus-runtime-smoke-plus-eval", ); text } fn unique_temp_dir(label: &str) -> PathBuf { let nonce = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-candidate-{label}-{nonce}")) } fn tiny_fixture_q8_bytes() -> Vec { build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), &ByteTokenizerSection::phase_one(), ) .unwrap() } fn tiny_fixture_f32_bytes() -> Vec { build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(DTYPE_F32), &ByteTokenizerSection::phase_one(), ) .unwrap() } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/candidate.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/compatibility.rs BYTES: 9166 SHA256: 29E4BCE5FDCCE6E1045D0B559AB9E05785E8485BA8637317B7C131727A5D5C87 ================================================================================ //! Parent `.slm` compatibility reports for future offline assembly operators. use std::fs; use std::io; use std::path::Path; use crate::slm_validate::{self, ValidationReport}; const COMPATIBILITY_VERSION: &str = "1"; const COMPATIBILITY_SCOPE: &str = "direct-parameter-family"; /// Validates two `.slm` files and either writes or prints a parent compatibility report. pub(crate) fn report_path(left: &Path, right: &Path, output: Option<&Path>) -> io::Result<()> { let left_bytes = fs::read(left)?; let right_bytes = fs::read(right)?; let text = compatibility_text_for_bytes( &left_bytes, &left.display().to_string(), &right_bytes, &right.display().to_string(), )?; if let Some(output_path) = output { if let Some(parent) = output_path.parent() { fs::create_dir_all(parent)?; } fs::write(output_path, text)?; println!( "SLM parent compatibility report written: {}", output_path.display() ); } else { print!("{text}"); } Ok(()) } pub(crate) fn compatibility_text_for_bytes( left_bytes: &[u8], left_path: &str, right_bytes: &[u8], right_path: &str, ) -> io::Result { let left = slm_validate::validate_bytes(left_bytes, left_path)?; let right = slm_validate::validate_bytes(right_bytes, right_path)?; Ok(build_compatibility_text(&left, &right)) } fn build_compatibility_text(left: &ValidationReport, right: &ValidationReport) -> String { let reasons = incompatibility_reasons(left, right); let compatible = reasons.is_empty(); let mut text = String::new(); push_line( &mut text, "tinyrustlm_parent_compatibility_version", COMPATIBILITY_VERSION, ); push_line(&mut text, "compatibility_scope", COMPATIBILITY_SCOPE); push_line( &mut text, "compatibility_result", if compatible { "pass" } else { "fail" }, ); push_line( &mut text, "compatible_parent_set", if compatible { "true" } else { "false" }, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, 0, left); push_parent_lines(&mut text, 1, right); push_line(&mut text, "compatibility_reasons", &reason_text(&reasons)); push_line( &mut text, "operator_lane", "offline-model-breeding-parent-set", ); push_line( &mut text, "decision", if compatible { "accepted-parent-set-for-offline-operators" } else { "use-distillation-or-source-conversion-route" }, ); push_line( &mut text, "candidate_gate", "slm-validate-plus-manifest-plus-runtime-smoke-plus-eval", ); text } fn push_parent_lines(text: &mut String, index: usize, report: &ValidationReport) { let prefix = format!("parent.{index}"); push_line(text, &format!("{prefix}.path"), report.path()); push_line( text, &format!("{prefix}.model_bytes"), &report.file_bytes().to_string(), ); push_line( text, &format!("{prefix}.slm_version"), &report.slm_version().to_string(), ); push_line( text, &format!("{prefix}.slm_checksum"), &hex64(report.checksum()), ); push_line( text, &format!("{prefix}.model_shape"), &report.shape_summary(), ); push_line( text, &format!("{prefix}.tensor_count"), &report.tensor_count().to_string(), ); push_line( text, &format!("{prefix}.parameter_count"), &report.parameter_count().to_string(), ); push_line( text, &format!("{prefix}.quantization"), report.quantization_label(), ); push_line( text, &format!("{prefix}.output_contract"), report.output_contract_label(), ); push_line( text, &format!("{prefix}.flags"), &format!("0x{:08x}", report.flags()), ); push_line( text, &format!("{prefix}.tokenizer_checksum"), &hex64(report.tokenizer_checksum()), ); push_line( text, &format!("{prefix}.tensor_layout_checksum"), &hex64(report.tensor_layout_checksum()), ); } fn incompatibility_reasons(left: &ValidationReport, right: &ValidationReport) -> Vec<&'static str> { let mut reasons = Vec::new(); if left.slm_version() != right.slm_version() { reasons.push("slm-version-mismatch"); } if left.shape_summary() != right.shape_summary() { reasons.push("model-shape-mismatch"); } if left.tokenizer_checksum() != right.tokenizer_checksum() { reasons.push("tokenizer-mismatch"); } if left.output_contract_label() != right.output_contract_label() { reasons.push("output-contract-mismatch"); } if left.quantization_label() != right.quantization_label() { reasons.push("quantization-mismatch"); } if left.tensor_count() != right.tensor_count() { reasons.push("tensor-count-mismatch"); } if left.parameter_count() != right.parameter_count() { reasons.push("parameter-count-mismatch"); } if left.tensor_layout_checksum() != right.tensor_layout_checksum() { reasons.push("tensor-layout-mismatch"); } reasons } fn reason_text(reasons: &[&'static str]) -> String { if reasons.is_empty() { "all-compatible".to_string() } else { reasons.join(";") } } fn push_line(text: &mut String, key: &str, value: &str) { text.push_str(key); text.push('='); text.push_str(value); text.push('\n'); } fn hex64(value: u64) -> String { format!("0x{value:016x}") } #[cfg(test)] mod tests { use super::*; use crate::tensor_writer::{ tensors_for_shape, tiny_fixture_tensors, tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_F32, DTYPE_Q8_0, }; use crate::tokenizer_writer::{ByteTokenizerSection, TokenizerSection}; use crate::{build_model_file, build_model_file_with_flags}; const FLAG_TIED_OUTPUT: u32 = 1; #[test] fn accepts_matching_parent_layouts() { let left = tiny_fixture_bytes(); let right = tiny_fixture_bytes(); let text = compatibility_text_for_bytes(&left, "parent-a.slm", &right, "parent-b.slm").unwrap(); assert!(text.contains("compatibility_result=pass")); assert!(text.contains("compatible_parent_set=true")); assert!(text.contains("compatibility_reasons=all-compatible")); assert!(text.contains("decision=accepted-parent-set-for-offline-operators")); } #[test] fn rejects_quantization_layout_mismatch_for_direct_parameter_lane() { let left = tiny_fixture_bytes(); let right = build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), &ByteTokenizerSection::phase_one(), ) .unwrap(); let text = compatibility_text_for_bytes(&left, "parent-a.slm", &right, "parent-q8.slm").unwrap(); assert!(text.contains("compatibility_result=fail")); assert!(text.contains("compatible_parent_set=false")); assert!(text.contains("quantization-mismatch")); assert!(text.contains("tensor-layout-mismatch")); assert!(text.contains("decision=use-distillation-or-source-conversion-route")); } #[test] fn rejects_tokenizer_and_shape_mismatch() { let left = tiny_fixture_bytes(); let bpe_shape = ModelShape { vocab_size: 262, ..ModelShape::tiny_fixture() }; let right = build_model_file( &bpe_shape, &tensors_for_shape(&bpe_shape, DTYPE_F32), &TokenizerSection::tiny_bpe_demo(), ) .unwrap(); let text = compatibility_text_for_bytes(&left, "parent-a.slm", &right, "parent-bpe.slm").unwrap(); assert!(text.contains("compatibility_result=fail")); assert!(text.contains("model-shape-mismatch")); assert!(text.contains("tokenizer-mismatch")); } #[test] fn rejects_output_contract_mismatch() { let left = tiny_fixture_bytes(); let right = build_model_file_with_flags( &ModelShape::tiny_fixture(), &crate::tensor_writer::tiny_fixture_tied_tensors(), &ByteTokenizerSection::phase_one(), FLAG_TIED_OUTPUT, ) .unwrap(); let text = compatibility_text_for_bytes(&left, "parent-a.slm", &right, "parent-tied.slm").unwrap(); assert!(text.contains("compatibility_result=fail")); assert!(text.contains("output-contract-mismatch")); assert!(text.contains("tensor-count-mismatch")); assert!(text.contains("tensor-layout-mismatch")); } fn tiny_fixture_bytes() -> Vec { build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors(), &ByteTokenizerSection::phase_one(), ) .unwrap() } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/compatibility.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/crossover.rs BYTES: 34880 SHA256: 2AD77765C01313021C9BEF7A14203B7FADD3CFBEFDAB7CA359246E40770EA0F9 ================================================================================ //! Offline deterministic direct-parameter crossover operator for model-breeding candidates. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::blend::{ hex64, invalid, output_specs, parse_manifest, parse_model_values, parse_passing_compatibility, push_line, push_parent_lines, require_equal, require_key, require_parent_report, require_report_equal, require_same_tensor_spec, same_shape, ParsedModel, PPM_DENOMINATOR, }; use crate::build_model_file_from_values_with_flags; use crate::lineage; use crate::slm_validate::{self, ValidationReport}; const CROSSOVER_OPERATOR_VERSION: &str = "1"; const OPERATOR_KIND: &str = "deterministic-direct-parameter-crossover"; const OPERATOR_STATUS: &str = "candidate-written"; const OPERATOR_OUTPUT_STATUS: &str = "slm-validated"; const PARENT_CONTRACT: &str = "matches-parent-direct-parameter-contract"; const REQUIRED_NEXT_GATE: &str = "candidate-manifest-plus-runtime-smoke-plus-eval"; const DEFAULT_CROSSOVER_SEED: &str = "1469598103934665603"; const DEFAULT_PARENT0_KEEP_PPM: &str = "500000"; const SELECTION_METRIC: &str = "splitmix64-tensor-element-threshold"; const SELECTION_SCOPE: &str = "compatible-parent-tensor-values"; const TIE_BREAK: &str = "parent0-when-threshold-equal"; /// Writes a crossover candidate `.slm` plus a recomputable operator receipt. pub(crate) fn write_candidate_path( compatibility: &Path, lineage_manifest: &Path, left_parent: &Path, right_parent: &Path, output_slm: &Path, output_receipt: &Path, crossover_seed: Option<&str>, parent0_keep_ppm: Option<&str>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let left_bytes = fs::read(left_parent)?; let right_bytes = fs::read(right_parent)?; let seed = parse_crossover_seed(crossover_seed.unwrap_or(DEFAULT_CROSSOVER_SEED))?; let keep = parse_parent0_keep_ppm(parent0_keep_ppm.unwrap_or(DEFAULT_PARENT0_KEEP_PPM))?; let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility_text, &lineage_text, &left_bytes, &left_parent.display().to_string(), &right_bytes, &right_parent.display().to_string(), &output_slm.display().to_string(), seed, keep, )?; if let Some(parent) = output_slm.parent() { fs::create_dir_all(parent)?; } fs::write(output_slm, candidate)?; if let Some(parent) = output_receipt.parent() { fs::create_dir_all(parent)?; } fs::write(output_receipt, receipt)?; println!("SLM crossover candidate written: {}", output_slm.display()); println!( "SLM crossover operator receipt written: {}", output_receipt.display() ); Ok(()) } /// Validates a crossover candidate and receipt by recomputing the operator output. pub(crate) fn validate_candidate_path( compatibility: &Path, lineage_manifest: &Path, left_parent: &Path, right_parent: &Path, candidate_slm: &Path, receipt: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let left_bytes = fs::read(left_parent)?; let right_bytes = fs::read(right_parent)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; validate_candidate_text( &compatibility_text, &lineage_text, &left_bytes, &left_parent.display().to_string(), &right_bytes, &right_parent.display().to_string(), &candidate_bytes, &candidate_slm.display().to_string(), &receipt_text, )?; println!("SLM crossover candidate validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("receipt: {}", receipt.display()); Ok(()) } /// Recomputes crossover output from receipt fields and compares both artifacts. fn validate_candidate_text( compatibility_text: &str, lineage_text: &str, left_bytes: &[u8], left_path: &str, right_bytes: &[u8], right_path: &str, candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, ) -> io::Result<()> { let receipt = parse_manifest(receipt_text, "crossover operator receipt")?; require_equal( &receipt, "tinyrustlm_crossover_operator_version", CROSSOVER_OPERATOR_VERSION, )?; require_equal(&receipt, "operator_kind", OPERATOR_KIND)?; require_equal(&receipt, "crossover_parent0_keep_unit", "parts-per-million")?; require_equal(&receipt, "crossover_selection_metric", SELECTION_METRIC)?; require_equal(&receipt, "crossover_selection_scope", SELECTION_SCOPE)?; require_equal(&receipt, "crossover_tie_break", TIE_BREAK)?; let seed = parse_crossover_seed(require_key(&receipt, "crossover_seed")?)?; let keep = parse_parent0_keep_ppm(require_key(&receipt, "crossover_parent0_keep_ppm")?)?; require_equal( &receipt, "crossover_parent1_keep_ppm", &(PPM_DENOMINATOR - keep).to_string(), )?; let (expected_candidate, expected_receipt) = build_candidate_bytes_and_receipt( compatibility_text, lineage_text, left_bytes, left_path, right_bytes, right_path, candidate_path, seed, keep, )?; if candidate_bytes != expected_candidate { return Err(invalid( "crossover candidate bytes do not match the operator receipt", )); } if receipt_text != expected_receipt { return Err(invalid( "crossover operator receipt fields do not match recomputed output", )); } Ok(()) } /// Builds the crossover `.slm` bytes and the receipt that can reproduce them. fn build_candidate_bytes_and_receipt( compatibility_text: &str, lineage_text: &str, left_bytes: &[u8], left_path: &str, right_bytes: &[u8], right_path: &str, candidate_path: &str, crossover_seed: u64, parent0_keep_ppm: u32, ) -> io::Result<(Vec, String)> { lineage::validate_text(compatibility_text, lineage_text)?; let compatibility = parse_passing_compatibility(compatibility_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let left_report = slm_validate::validate_bytes(left_bytes, left_path)?; let right_report = slm_validate::validate_bytes(right_bytes, right_path)?; require_parent_report(&compatibility, 0, &left_report)?; require_parent_report(&compatibility, 1, &right_report)?; let left = parse_model_values(left_bytes)?; let right = parse_model_values(right_bytes)?; let (output_values, crossover_stats) = crossover_values(&left, &right, crossover_seed, parent0_keep_ppm)?; let output_tensors = output_specs(&left); let candidate = build_model_file_from_values_with_flags( &left.shape, &output_tensors, &left.tokenizer, &output_values, left.flags, )?; let candidate_report = slm_validate::validate_bytes(&candidate, candidate_path)?; require_report_equal( &compatibility, "parent.0.model_shape", &candidate_report.shape_summary(), )?; require_report_equal( &compatibility, "parent.0.quantization", candidate_report.quantization_label(), )?; require_report_equal( &compatibility, "parent.0.output_contract", candidate_report.output_contract_label(), )?; require_report_equal( &compatibility, "parent.0.tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), )?; require_report_equal( &compatibility, "parent.0.tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), )?; let receipt = build_receipt_text( &compatibility, &lineage_fields, lineage_text, left_path, right_path, &left_report, &right_report, &candidate_report, crossover_seed, parent0_keep_ppm, crossover_stats, )?; Ok((candidate, receipt)) } /// Formats the manifest-style receipt for a deterministic crossover candidate. #[allow(clippy::too_many_arguments)] fn build_receipt_text( compatibility: &HashMap, lineage_fields: &HashMap, lineage_text: &str, left_path: &str, right_path: &str, left_report: &ValidationReport, right_report: &ValidationReport, candidate_report: &ValidationReport, crossover_seed: u64, parent0_keep_ppm: u32, crossover_stats: CrossoverStats, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_crossover_operator_version", CROSSOVER_OPERATOR_VERSION, ); push_line(&mut text, "operator_kind", OPERATOR_KIND); push_line(&mut text, "operator_status", OPERATOR_STATUS); push_line( &mut text, "candidate_id", require_key(lineage_fields, "candidate_id")?, ); push_line( &mut text, "operator_id", require_key(lineage_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(lineage_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(lineage_fields, "resource_budget")?, ); push_line( &mut text, "compatibility_report_checksum", require_key(lineage_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(compatibility, "compatibility_scope")?, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, compatibility, 0, left_path, left_report)?; push_parent_lines(&mut text, compatibility, 1, right_path, right_report)?; push_line(&mut text, "crossover_seed", &crossover_seed.to_string()); push_line( &mut text, "crossover_parent0_keep_unit", "parts-per-million", ); push_line( &mut text, "crossover_parent0_keep_ppm", &parent0_keep_ppm.to_string(), ); push_line( &mut text, "crossover_parent1_keep_ppm", &(PPM_DENOMINATOR - parent0_keep_ppm).to_string(), ); push_line(&mut text, "crossover_selection_metric", SELECTION_METRIC); push_line(&mut text, "crossover_selection_scope", SELECTION_SCOPE); push_line(&mut text, "crossover_tie_break", TIE_BREAK); push_line( &mut text, "crossover_total_parameter_count", &crossover_stats.total_parameter_count.to_string(), ); push_line( &mut text, "crossover_parent0_parameter_count", &crossover_stats.parent0_parameter_count.to_string(), ); push_line( &mut text, "crossover_parent1_parameter_count", &crossover_stats.parent1_parameter_count.to_string(), ); push_line( &mut text, "crossover_parent0_density_ppm", &crossover_stats.parent0_density_ppm.to_string(), ); push_line( &mut text, "crossover_parent1_density_ppm", &crossover_stats.parent1_density_ppm.to_string(), ); push_line( &mut text, "crossover_mask_checksum", &hex64(crossover_stats.mask_checksum), ); push_line( &mut text, "candidate_artifact_path", candidate_report.path(), ); push_line( &mut text, "candidate_artifact_bytes", &candidate_report.file_bytes().to_string(), ); push_line( &mut text, "candidate_slm_version", &candidate_report.slm_version().to_string(), ); push_line( &mut text, "candidate_slm_checksum", &hex64(candidate_report.checksum()), ); push_line( &mut text, "candidate_model_shape", &candidate_report.shape_summary(), ); push_line( &mut text, "candidate_tensor_count", &candidate_report.tensor_count().to_string(), ); push_line( &mut text, "candidate_parameter_count", &candidate_report.parameter_count().to_string(), ); push_line( &mut text, "candidate_quantization", candidate_report.quantization_label(), ); push_line( &mut text, "candidate_output_contract", candidate_report.output_contract_label(), ); push_line( &mut text, "candidate_tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), ); push_line( &mut text, "candidate_tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), ); push_line(&mut text, "candidate_parent_contract", PARENT_CONTRACT); push_line(&mut text, "operator_output_status", OPERATOR_OUTPUT_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } /// Selects each compatible tensor value from either parent and returns selection stats. fn crossover_values( left: &ParsedModel, right: &ParsedModel, crossover_seed: u64, parent0_keep_ppm: u32, ) -> io::Result<(Vec>, CrossoverStats)> { if !same_shape(&left.shape, &right.shape) { return Err(invalid("crossover parents have different model shapes")); } if left.flags != right.flags { return Err(invalid("crossover parents have different output flags")); } if left.tokenizer.bytes != right.tokenizer.bytes { return Err(invalid("crossover parents have different tokenizer bytes")); } let right_by_hash = right .tensors .iter() .enumerate() .map(|(index, tensor)| (tensor.spec.name_hash, index)) .collect::>(); let mut output = Vec::with_capacity(left.tensors.len()); let mut stats = CrossoverStats { total_parameter_count: 0, parent0_parameter_count: 0, parent1_parameter_count: 0, parent0_density_ppm: 0, parent1_density_ppm: 0, mask_checksum: crossover_mask_seed(crossover_seed, parent0_keep_ppm), }; for (tensor_index, left_tensor) in left.tensors.iter().enumerate() { let Some(right_index) = right_by_hash.get(&left_tensor.spec.name_hash) else { return Err(invalid( "right parent is missing a tensor from the left parent", )); }; let right_tensor = &right.tensors[*right_index]; require_same_tensor_spec(&left_tensor.spec, &right_tensor.spec)?; let mut values = Vec::with_capacity(left_tensor.values.len()); for (value_index, (left_value, right_value)) in left_tensor .values .iter() .zip(right_tensor.values.iter()) .enumerate() { let choose_left = choose_parent0(crossover_seed, tensor_index, value_index, parent0_keep_ppm); stats.total_parameter_count += 1; if choose_left { stats.parent0_parameter_count += 1; values.push(*left_value); } else { stats.parent1_parameter_count += 1; values.push(*right_value); } mix_mask_value(&mut stats.mask_checksum, tensor_index as u64); mix_mask_value(&mut stats.mask_checksum, value_index as u64); mix_mask_value(&mut stats.mask_checksum, if choose_left { 0 } else { 1 }); } output.push(values); } stats.parent0_density_ppm = ratio_ppm(stats.parent0_parameter_count, stats.total_parameter_count)?; stats.parent1_density_ppm = ratio_ppm(stats.parent1_parameter_count, stats.total_parameter_count)?; mix_mask_value(&mut stats.mask_checksum, stats.total_parameter_count); mix_mask_value(&mut stats.mask_checksum, stats.parent0_parameter_count); mix_mask_value(&mut stats.mask_checksum, stats.parent1_parameter_count); Ok((output, stats)) } /// Applies the keep threshold with fixed behavior for the two boundary values. fn choose_parent0( crossover_seed: u64, tensor_index: usize, value_index: usize, parent0_keep_ppm: u32, ) -> bool { if parent0_keep_ppm == 0 { return false; } if parent0_keep_ppm >= PPM_DENOMINATOR { return true; } draw_ppm(crossover_seed, tensor_index, value_index) <= parent0_keep_ppm } /// Produces a parts-per-million draw from stable tensor and element coordinates. fn draw_ppm(crossover_seed: u64, tensor_index: usize, value_index: usize) -> u32 { let mixed = splitmix64( crossover_seed ^ ((tensor_index as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15)) ^ ((value_index as u64).wrapping_mul(0xbf58_476d_1ce4_e5b9)), ); (mixed % u64::from(PPM_DENOMINATOR) + 1) as u32 } /// Scrambles a u64 using the SplitMix64 finalizer pattern. fn splitmix64(mut value: u64) -> u64 { value = value.wrapping_add(0x9e37_79b9_7f4a_7c15); value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); value ^ (value >> 31) } /// Starts the crossover mask checksum from operator parameters. fn crossover_mask_seed(crossover_seed: u64, parent0_keep_ppm: u32) -> u64 { let mut acc = 0x6372_6f73_736f_7631u64; mix_mask_value(&mut acc, crossover_seed); mix_mask_value(&mut acc, u64::from(parent0_keep_ppm)); acc } /// Folds one mask value into a compact deterministic checksum. fn mix_mask_value(acc: &mut u64, value: u64) { *acc ^= value.wrapping_add(0x9e37_79b9_7f4a_7c15); *acc = acc.rotate_left(11).wrapping_mul(0x1000_0000_01b3); } /// Converts a count ratio into integer parts-per-million. fn ratio_ppm(numerator: u64, denominator: u64) -> io::Result { if denominator == 0 { return Ok(0); } let ppm = u128::from(numerator) * u128::from(PPM_DENOMINATOR) / u128::from(denominator); u64::try_from(ppm).map_err(|_| invalid("crossover ratio overflowed u64")) } /// Parses the deterministic crossover seed from a CLI or receipt field. fn parse_crossover_seed(value: &str) -> io::Result { value .parse::() .map_err(|_| invalid("crossover seed must be an unsigned 64-bit integer")) } /// Parses parent-zero retention as an integer parts-per-million value. fn parse_parent0_keep_ppm(value: &str) -> io::Result { let keep = value.parse::().map_err(|_| { invalid("crossover parent0 keep must be an integer parts-per-million value") })?; if keep > PPM_DENOMINATOR { return Err(invalid( "crossover parent0 keep must be between 0 and 1000000", )); } Ok(keep) } /// Holds deterministic crossover selection counts and checksum metadata. #[derive(Clone, Copy)] struct CrossoverStats { total_parameter_count: u64, parent0_parameter_count: u64, parent1_parameter_count: u64, parent0_density_ppm: u64, parent1_density_ppm: u64, mask_checksum: u64, } #[cfg(test)] mod tests { use super::*; use crate::compatibility; use crate::tensor_writer::{tiny_fixture_tensors, tiny_fixture_tensors_with_dtype, DTYPE_Q8_0}; use crate::tokenizer_writer::ByteTokenizerSection; use crate::{build_model_file_from_values_with_flags, fixture_value}; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; // Exercises the seed and keep parameters through candidate writing and receipt validation. #[test] fn writes_and_validates_seeded_f32_crossover_candidate() { let left = tiny_f32_scaled_bytes(1.0); let right = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "cross-f32", "crossover-v1", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", "candidate.slm", 7, 500_000, ) .unwrap(); validate_candidate_text( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); let left_values = parse_model_values(&left).unwrap(); let right_values = parse_model_values(&right).unwrap(); let candidate_values = parse_model_values(&candidate).unwrap(); let mut selected_left = 0usize; let mut selected_right = 0usize; for ((candidate_tensor, left_tensor), right_tensor) in candidate_values .tensors .iter() .zip(left_values.tensors.iter()) .zip(right_values.tensors.iter()) { for ((candidate_value, left_value), right_value) in candidate_tensor .values .iter() .zip(left_tensor.values.iter()) .zip(right_tensor.values.iter()) { if candidate_value == left_value { selected_left += 1; } if candidate_value == right_value { selected_right += 1; } } } assert!(selected_left > 0); assert!(selected_right > 0); assert!(receipt.contains("operator_kind=deterministic-direct-parameter-crossover")); assert!(receipt.contains("crossover_seed=7")); assert!(receipt.contains("crossover_parent0_keep_ppm=500000")); assert!(receipt.contains("crossover_mask_checksum=")); } // Exercises all path-level inputs plus default seed and keep parameters. #[test] fn path_writer_uses_default_seed_and_keep_then_validates() { let dir = unique_dir("path-defaults"); fs::create_dir_all(&dir).unwrap(); let left_path = dir.join("left.slm"); let right_path = dir.join("right.slm"); let compatibility_path = dir.join("parents.compat"); let lineage_path = dir.join("candidate.lineage"); let candidate_path = dir.join("candidate.slm"); let receipt_path = dir.join("candidate.operator"); let left = tiny_f32_scaled_bytes(1.0); let right = tiny_f32_scaled_bytes(3.0); fs::write(&left_path, &left).unwrap(); fs::write(&right_path, &right).unwrap(); let compatibility = compatibility::compatibility_text_for_bytes( &left, &left_path.display().to_string(), &right, &right_path.display().to_string(), ) .unwrap(); fs::write(&compatibility_path, &compatibility).unwrap(); let lineage = lineage::build_template_text(&compatibility, "cross-path", "crossover-v1", "tiny") .unwrap(); fs::write(&lineage_path, &lineage).unwrap(); write_candidate_path( &compatibility_path, &lineage_path, &left_path, &right_path, &candidate_path, &receipt_path, None, None, ) .unwrap(); validate_candidate_path( &compatibility_path, &lineage_path, &left_path, &right_path, &candidate_path, &receipt_path, ) .unwrap(); let receipt = fs::read_to_string(receipt_path).unwrap(); assert!(receipt.contains("crossover_seed=1469598103934665603")); assert!(receipt.contains("crossover_parent0_keep_ppm=500000")); } // Covers the parent0_keep_ppm lower boundary where every value comes from parent 1. #[test] fn keep_zero_uses_right_parent_values() { let left = tiny_f32_scaled_bytes(1.0); let right = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "cross-zero", "crossover-v1", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", "candidate.slm", 13, 0, ) .unwrap(); let candidate_values = parse_model_values(&candidate).unwrap(); let right_values = parse_model_values(&right).unwrap(); for (candidate_tensor, right_tensor) in candidate_values .tensors .iter() .zip(right_values.tensors.iter()) { assert_eq!(candidate_tensor.values, right_tensor.values); } assert!(receipt.contains("crossover_parent0_parameter_count=0")); assert!(receipt.contains("crossover_parent1_density_ppm=1000000")); } // Covers the parent0_keep_ppm upper boundary where every value comes from parent 0. #[test] fn keep_all_uses_left_parent_values() { let left = tiny_f32_scaled_bytes(1.0); let right = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "cross-all", "crossover-v1", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", "candidate.slm", 13, 1_000_000, ) .unwrap(); let candidate_values = parse_model_values(&candidate).unwrap(); let left_values = parse_model_values(&left).unwrap(); for (candidate_tensor, left_tensor) in candidate_values .tensors .iter() .zip(left_values.tensors.iter()) { assert_eq!(candidate_tensor.values, left_tensor.values); } assert!(receipt.contains("crossover_parent1_parameter_count=0")); assert!(receipt.contains("crossover_parent0_density_ppm=1000000")); } // Confirms crossover_seed changes the selected mask and the produced candidate. #[test] fn crossover_seed_changes_selection_mask() { let left = tiny_f32_scaled_bytes(1.0); let right = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "cross-seed", "crossover-v1", "tiny") .unwrap(); let (candidate_a, receipt_a) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", "candidate-a.slm", 1, 500_000, ) .unwrap(); let (candidate_b, receipt_b) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", "candidate-b.slm", 2, 500_000, ) .unwrap(); let receipt_a_fields = parse_manifest(&receipt_a, "crossover receipt a").unwrap(); let receipt_b_fields = parse_manifest(&receipt_b, "crossover receipt b").unwrap(); assert_ne!(candidate_a, candidate_b); assert_ne!( receipt_a_fields.get("crossover_mask_checksum"), receipt_b_fields.get("crossover_mask_checksum") ); } // Validates q8 parents keep their quantization route through crossover output. #[test] fn writes_and_validates_q8_crossover_candidate() { let left = tiny_q8_scaled_bytes(1.0); let right = tiny_q8_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "cross-q8", "crossover-v1", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", "candidate.slm", 42, 500_000, ) .unwrap(); slm_validate::validate_bytes(&candidate, "candidate.slm").unwrap(); validate_candidate_text( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); assert!(receipt.contains("candidate_quantization=q8_0")); } // Confirms parent parameters are tied to compatibility receipts by checksum. #[test] fn rejects_parent_checksum_drift() { let left = tiny_f32_scaled_bytes(1.0); let right = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "cross-drift", "crossover-v1", "tiny") .unwrap(); let changed_left = tiny_f32_scaled_bytes(2.0); let error = build_candidate_bytes_and_receipt( &compatibility, &lineage, &changed_left, "left.slm", &right, "right.slm", "candidate.slm", 7, 500_000, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("parent.0.slm_checksum")); } // Confirms validation catches candidate bytes that no longer match the receipt. #[test] fn validation_rejects_candidate_drift() { let left = tiny_f32_scaled_bytes(1.0); let right = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "cross-drift", "crossover-v1", "tiny") .unwrap(); let (mut candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", "candidate.slm", 7, 500_000, ) .unwrap(); let last = candidate.len() - 1; candidate[last] ^= 0x01; let error = validate_candidate_text( &compatibility, &lineage, &left, "left.slm", &right, "right.slm", &candidate, "candidate.slm", &receipt, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate bytes")); } // Covers parser behavior for the seed and parent0_keep_ppm inputs. #[test] fn rejects_invalid_crossover_parameters() { assert_eq!( parse_crossover_seed("18446744073709551616") .unwrap_err() .kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_crossover_seed("-1").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_crossover_seed("seed").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_parent0_keep_ppm("1000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_parent0_keep_ppm("-1").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_parent0_keep_ppm("half").unwrap_err().kind(), io::ErrorKind::InvalidData ); } // Builds a tiny f32 model with all fixture values multiplied by scale. fn tiny_f32_scaled_bytes(scale: f32) -> Vec { build_tiny_bytes(tiny_fixture_tensors(), |tensor, index, _tensor_index| { fixture_value(tensor, index) * scale }) } // Builds a tiny q8 model with all fixture values multiplied by scale. fn tiny_q8_scaled_bytes(scale: f32) -> Vec { build_tiny_bytes( tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), |tensor, index, _tensor_index| fixture_value(tensor, index) * scale, ) } // Packs a tiny fixture model from caller-supplied tensor values. fn build_tiny_bytes(tensors: Vec, mut value: F) -> Vec where F: FnMut(&crate::tensor_writer::TensorSpec, usize, usize) -> f32, { let values = tensors .iter() .enumerate() .map(|(tensor_index, tensor)| { (0..tensor.element_count()) .map(|index| value(tensor, index, tensor_index)) .collect::>() }) .collect::>(); build_model_file_from_values_with_flags( &crate::tensor_writer::ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } // Creates an isolated temp directory for path-level operator tests. fn unique_dir(label: &str) -> PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-crossover-{label}-{nanos}")) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/crossover.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/dare.rs BYTES: 44917 SHA256: 2228F76A58AC5DCF39B2D4E69CAE24AA14212AA8959E2C9DD4A9382B68CFDBF9 ================================================================================ //! Offline DARE-style dropout/rescaled task-delta operator for model-breeding candidates. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::blend::{ hex64, invalid, output_specs, parse_manifest, parse_model_values, parse_passing_compatibility, push_line, push_parent_lines, require_equal, require_key, require_parent_report, require_report_equal, require_same_tensor_spec, same_shape, ParsedModel, PPM_DENOMINATOR, }; use crate::build_model_file_from_values_with_flags; use crate::lineage; use crate::slm_validate::{self, ValidationReport}; const DARE_OPERATOR_VERSION: &str = "1"; const OPERATOR_KIND: &str = "dropout-rescaled-task-delta"; const OPERATOR_STATUS: &str = "candidate-written"; const OPERATOR_OUTPUT_STATUS: &str = "slm-validated"; const PARENT_CONTRACT: &str = "matches-parent-direct-parameter-contract"; const REQUIRED_NEXT_GATE: &str = "candidate-manifest-plus-runtime-smoke-plus-eval"; const DEFAULT_DELTA_WEIGHT_PPM: &str = "1000000"; const DEFAULT_KEEP_PPM: &str = "500000"; const DEFAULT_DROPOUT_SEED: &str = "1469598103934665603"; const MIN_DELTA_WEIGHT_PPM: i64 = -1_000_000; const MAX_DELTA_WEIGHT_PPM: i64 = 2_000_000; const SELECTION_METRIC: &str = "splitmix64-nonzero-delta-threshold"; const SELECTION_SCOPE: &str = "nonzero-target-minus-base-deltas"; const TIE_BREAK: &str = "select-when-threshold-equal"; const RESCALE_STRATEGY: &str = "inverse-keep-rate"; /// Writes a DARE task-delta candidate `.slm` plus a recomputable receipt. pub(crate) fn write_candidate_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, output_slm: &Path, output_receipt: &Path, delta_weight_ppm: Option<&str>, keep_ppm: Option<&str>, dropout_seed: Option<&str>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let weight = parse_delta_weight_ppm(delta_weight_ppm.unwrap_or(DEFAULT_DELTA_WEIGHT_PPM))?; let keep = parse_keep_ppm(keep_ppm.unwrap_or(DEFAULT_KEEP_PPM))?; let seed = parse_dropout_seed(dropout_seed.unwrap_or(DEFAULT_DROPOUT_SEED))?; let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &output_slm.display().to_string(), weight, keep, seed, )?; if let Some(parent) = output_slm.parent() { fs::create_dir_all(parent)?; } fs::write(output_slm, candidate)?; if let Some(parent) = output_receipt.parent() { fs::create_dir_all(parent)?; } fs::write(output_receipt, receipt)?; println!("SLM DARE candidate written: {}", output_slm.display()); println!( "SLM DARE operator receipt written: {}", output_receipt.display() ); Ok(()) } /// Validates a DARE candidate and receipt by replaying the masked task delta. pub(crate) fn validate_candidate_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, candidate_slm: &Path, receipt: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; validate_candidate_text( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &candidate_bytes, &candidate_slm.display().to_string(), &receipt_text, )?; println!("SLM DARE candidate validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("receipt: {}", receipt.display()); Ok(()) } /// Recomputes DARE output from receipt parameters and compares both artifacts. fn validate_candidate_text( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, ) -> io::Result<()> { let receipt = parse_manifest(receipt_text, "DARE operator receipt")?; require_equal( &receipt, "tinyrustlm_dare_operator_version", DARE_OPERATOR_VERSION, )?; require_equal(&receipt, "operator_kind", OPERATOR_KIND)?; require_equal(&receipt, "base_parent_index", "0")?; require_equal(&receipt, "target_parent_index", "1")?; require_equal(&receipt, "delta_weight_unit", "parts-per-million")?; require_equal(&receipt, "dare_keep_unit", "parts-per-million")?; require_equal(&receipt, "dare_drop_unit", "parts-per-million")?; require_equal(&receipt, "dare_selection_metric", SELECTION_METRIC)?; require_equal(&receipt, "dare_selection_scope", SELECTION_SCOPE)?; require_equal(&receipt, "dare_tie_break", TIE_BREAK)?; require_equal(&receipt, "dare_rescale_strategy", RESCALE_STRATEGY)?; let weight = parse_delta_weight_ppm(require_key(&receipt, "delta_weight_ppm")?)?; let keep = parse_keep_ppm(require_key(&receipt, "dare_keep_ppm")?)?; let seed = parse_dropout_seed(require_key(&receipt, "dare_dropout_seed")?)?; require_equal( &receipt, "dare_drop_ppm", &(PPM_DENOMINATOR - keep).to_string(), )?; require_equal( &receipt, "dare_rescale_multiplier_ppm", &rescale_multiplier_ppm(keep).to_string(), )?; let (expected_candidate, expected_receipt) = build_candidate_bytes_and_receipt( compatibility_text, lineage_text, base_bytes, base_path, target_bytes, target_path, candidate_path, weight, keep, seed, )?; if candidate_bytes != expected_candidate { return Err(invalid( "DARE candidate bytes do not match the operator receipt", )); } if receipt_text != expected_receipt { return Err(invalid( "DARE operator receipt fields do not match recomputed output", )); } Ok(()) } /// Builds the DARE `.slm` bytes and the receipt that can reproduce them. fn build_candidate_bytes_and_receipt( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, candidate_path: &str, delta_weight_ppm: i64, keep_ppm: u32, dropout_seed: u64, ) -> io::Result<(Vec, String)> { lineage::validate_text(compatibility_text, lineage_text)?; let compatibility = parse_passing_compatibility(compatibility_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let base_report = slm_validate::validate_bytes(base_bytes, base_path)?; let target_report = slm_validate::validate_bytes(target_bytes, target_path)?; require_parent_report(&compatibility, 0, &base_report)?; require_parent_report(&compatibility, 1, &target_report)?; let base = parse_model_values(base_bytes)?; let target = parse_model_values(target_bytes)?; let (output_values, dare_stats) = dare_values(&base, &target, delta_weight_ppm, keep_ppm, dropout_seed)?; let output_tensors = output_specs(&base); let candidate = build_model_file_from_values_with_flags( &base.shape, &output_tensors, &base.tokenizer, &output_values, base.flags, )?; let candidate_report = slm_validate::validate_bytes(&candidate, candidate_path)?; require_report_equal( &compatibility, "parent.0.model_shape", &candidate_report.shape_summary(), )?; require_report_equal( &compatibility, "parent.0.quantization", candidate_report.quantization_label(), )?; require_report_equal( &compatibility, "parent.0.output_contract", candidate_report.output_contract_label(), )?; require_report_equal( &compatibility, "parent.0.tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), )?; require_report_equal( &compatibility, "parent.0.tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), )?; let receipt = build_receipt_text( &compatibility, &lineage_fields, lineage_text, base_path, target_path, &base_report, &target_report, &candidate_report, delta_weight_ppm, keep_ppm, dropout_seed, dare_stats, )?; Ok((candidate, receipt)) } /// Formats the manifest-style receipt for a DARE operator output. #[allow(clippy::too_many_arguments)] fn build_receipt_text( compatibility: &HashMap, lineage_fields: &HashMap, lineage_text: &str, base_path: &str, target_path: &str, base_report: &ValidationReport, target_report: &ValidationReport, candidate_report: &ValidationReport, delta_weight_ppm: i64, keep_ppm: u32, dropout_seed: u64, dare_stats: DareStats, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_dare_operator_version", DARE_OPERATOR_VERSION, ); push_line(&mut text, "operator_kind", OPERATOR_KIND); push_line(&mut text, "operator_status", OPERATOR_STATUS); push_line( &mut text, "candidate_id", require_key(lineage_fields, "candidate_id")?, ); push_line( &mut text, "operator_id", require_key(lineage_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(lineage_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(lineage_fields, "resource_budget")?, ); push_line( &mut text, "compatibility_report_checksum", require_key(lineage_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(compatibility, "compatibility_scope")?, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, compatibility, 0, base_path, base_report)?; push_parent_lines(&mut text, compatibility, 1, target_path, target_report)?; push_line(&mut text, "base_parent_index", "0"); push_line(&mut text, "target_parent_index", "1"); push_line(&mut text, "delta_weight_unit", "parts-per-million"); push_line(&mut text, "delta_weight_ppm", &delta_weight_ppm.to_string()); push_line(&mut text, "dare_keep_unit", "parts-per-million"); push_line(&mut text, "dare_keep_ppm", &keep_ppm.to_string()); push_line(&mut text, "dare_drop_unit", "parts-per-million"); push_line( &mut text, "dare_drop_ppm", &(PPM_DENOMINATOR - keep_ppm).to_string(), ); push_line(&mut text, "dare_dropout_seed", &dropout_seed.to_string()); push_line(&mut text, "dare_selection_metric", SELECTION_METRIC); push_line(&mut text, "dare_selection_scope", SELECTION_SCOPE); push_line(&mut text, "dare_tie_break", TIE_BREAK); push_line(&mut text, "dare_rescale_strategy", RESCALE_STRATEGY); push_line( &mut text, "dare_rescale_multiplier_ppm", &rescale_multiplier_ppm(keep_ppm).to_string(), ); push_line( &mut text, "dare_total_parameter_count", &dare_stats.total_parameter_count.to_string(), ); push_line( &mut text, "dare_nonzero_delta_count", &dare_stats.nonzero_delta_count.to_string(), ); push_line( &mut text, "dare_selected_delta_count", &dare_stats.selected_delta_count.to_string(), ); push_line( &mut text, "dare_dropped_delta_count", &dare_stats.dropped_delta_count.to_string(), ); push_line( &mut text, "dare_unchanged_parameter_count", &dare_stats.unchanged_parameter_count.to_string(), ); push_line( &mut text, "dare_selection_density_ppm", &dare_stats.selection_density_ppm.to_string(), ); push_line( &mut text, "dare_nonzero_delta_retention_ppm", &dare_stats.nonzero_delta_retention_ppm.to_string(), ); push_line( &mut text, "dare_mask_checksum", &hex64(dare_stats.mask_checksum), ); push_line( &mut text, "dare_raw_delta_checksum", &hex64(dare_stats.raw_delta_checksum), ); push_line( &mut text, "dare_rescaled_delta_checksum", &hex64(dare_stats.rescaled_delta_checksum), ); push_line( &mut text, "candidate_artifact_path", candidate_report.path(), ); push_line( &mut text, "candidate_artifact_bytes", &candidate_report.file_bytes().to_string(), ); push_line( &mut text, "candidate_slm_version", &candidate_report.slm_version().to_string(), ); push_line( &mut text, "candidate_slm_checksum", &hex64(candidate_report.checksum()), ); push_line( &mut text, "candidate_model_shape", &candidate_report.shape_summary(), ); push_line( &mut text, "candidate_tensor_count", &candidate_report.tensor_count().to_string(), ); push_line( &mut text, "candidate_parameter_count", &candidate_report.parameter_count().to_string(), ); push_line( &mut text, "candidate_quantization", candidate_report.quantization_label(), ); push_line( &mut text, "candidate_output_contract", candidate_report.output_contract_label(), ); push_line( &mut text, "candidate_tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), ); push_line( &mut text, "candidate_tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), ); push_line(&mut text, "candidate_parent_contract", PARENT_CONTRACT); push_line(&mut text, "operator_output_status", OPERATOR_OUTPUT_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } /// Applies deterministic dropout to nonzero task deltas and rescales kept deltas. fn dare_values( base: &ParsedModel, target: &ParsedModel, delta_weight_ppm: i64, keep_ppm: u32, dropout_seed: u64, ) -> io::Result<(Vec>, DareStats)> { if !same_shape(&base.shape, &target.shape) { return Err(invalid("DARE parents have different model shapes")); } if base.flags != target.flags { return Err(invalid("DARE parents have different output flags")); } if base.tokenizer.bytes != target.tokenizer.bytes { return Err(invalid("DARE parents have different tokenizer bytes")); } let target_by_hash = target .tensors .iter() .enumerate() .map(|(index, tensor)| (tensor.spec.name_hash, index)) .collect::>(); let mut output = Vec::with_capacity(base.tensors.len()); let mut stats = DareStats { total_parameter_count: 0, nonzero_delta_count: 0, selected_delta_count: 0, dropped_delta_count: 0, unchanged_parameter_count: 0, selection_density_ppm: 0, nonzero_delta_retention_ppm: 0, mask_checksum: dare_mask_seed(dropout_seed, delta_weight_ppm, keep_ppm), raw_delta_checksum: dare_raw_delta_seed(dropout_seed, delta_weight_ppm, keep_ppm), rescaled_delta_checksum: dare_rescaled_delta_seed(dropout_seed, delta_weight_ppm, keep_ppm), }; for (tensor_index, base_tensor) in base.tensors.iter().enumerate() { let Some(target_index) = target_by_hash.get(&base_tensor.spec.name_hash) else { return Err(invalid( "target parent is missing a tensor from the base parent", )); }; let target_tensor = &target.tensors[*target_index]; require_same_tensor_spec(&base_tensor.spec, &target_tensor.spec)?; let mut values = Vec::with_capacity(base_tensor.values.len()); for (value_index, (base_value, target_value)) in base_tensor .values .iter() .zip(target_tensor.values.iter()) .enumerate() { stats.total_parameter_count += 1; let raw_delta = *target_value - *base_value; if raw_delta == 0.0 { stats.unchanged_parameter_count += 1; values.push(*base_value); continue; } stats.nonzero_delta_count += 1; let selected = choose_delta(dropout_seed, tensor_index, value_index, keep_ppm); mix_mask_value(&mut stats.mask_checksum, tensor_index as u64); mix_mask_value(&mut stats.mask_checksum, value_index as u64); mix_mask_value(&mut stats.mask_checksum, if selected { 1 } else { 0 }); mix_delta_value(&mut stats.raw_delta_checksum, tensor_index as u64); mix_delta_value(&mut stats.raw_delta_checksum, value_index as u64); mix_delta_value( &mut stats.raw_delta_checksum, u64::from(raw_delta.to_bits()), ); if selected { stats.selected_delta_count += 1; let applied_delta = rescaled_delta(raw_delta, delta_weight_ppm, keep_ppm)?; let output_value = *base_value + applied_delta; if !output_value.is_finite() { return Err(invalid("DARE output produced a non-finite value")); } mix_delta_value(&mut stats.rescaled_delta_checksum, tensor_index as u64); mix_delta_value(&mut stats.rescaled_delta_checksum, value_index as u64); mix_delta_value( &mut stats.rescaled_delta_checksum, u64::from(applied_delta.to_bits()), ); mix_delta_value( &mut stats.rescaled_delta_checksum, u64::from(output_value.to_bits()), ); values.push(output_value); } else { stats.dropped_delta_count += 1; values.push(*base_value); } } output.push(values); } stats.selection_density_ppm = ratio_ppm(stats.selected_delta_count, stats.total_parameter_count)?; stats.nonzero_delta_retention_ppm = ratio_ppm(stats.selected_delta_count, stats.nonzero_delta_count)?; mix_mask_value(&mut stats.mask_checksum, stats.total_parameter_count); mix_mask_value(&mut stats.mask_checksum, stats.nonzero_delta_count); mix_mask_value(&mut stats.mask_checksum, stats.selected_delta_count); mix_delta_value(&mut stats.raw_delta_checksum, stats.nonzero_delta_count); mix_delta_value( &mut stats.rescaled_delta_checksum, stats.selected_delta_count, ); Ok((output, stats)) } /// Applies the keep threshold with stable behavior at the two boundary values. fn choose_delta(dropout_seed: u64, tensor_index: usize, value_index: usize, keep_ppm: u32) -> bool { if keep_ppm == 0 { return false; } if keep_ppm >= PPM_DENOMINATOR { return true; } draw_ppm(dropout_seed, tensor_index, value_index) <= keep_ppm } /// Rescales a kept delta by delta_weight divided by the retained fraction. fn rescaled_delta(raw_delta: f32, delta_weight_ppm: i64, keep_ppm: u32) -> io::Result { if keep_ppm == 0 || delta_weight_ppm == 0 { return Ok(0.0); } let scaled = f64::from(raw_delta) * delta_weight_ppm as f64 / f64::from(keep_ppm); if !scaled.is_finite() || scaled.abs() > f64::from(f32::MAX) { return Err(invalid("DARE rescaled delta overflowed finite f32 range")); } Ok(scaled as f32) } /// Reports the keep-rate inverse as an integer parts-per-million multiplier. fn rescale_multiplier_ppm(keep_ppm: u32) -> u64 { if keep_ppm == 0 { return 0; } u64::from(PPM_DENOMINATOR) * u64::from(PPM_DENOMINATOR) / u64::from(keep_ppm) } /// Produces a parts-per-million draw from stable tensor and element coordinates. fn draw_ppm(dropout_seed: u64, tensor_index: usize, value_index: usize) -> u32 { let mixed = splitmix64(coordinate_seed(dropout_seed, tensor_index, value_index)); (mixed % u64::from(PPM_DENOMINATOR) + 1) as u32 } /// Mixes the operator seed with tensor and element coordinates. fn coordinate_seed(dropout_seed: u64, tensor_index: usize, value_index: usize) -> u64 { dropout_seed ^ ((tensor_index as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15)) ^ ((value_index as u64).wrapping_mul(0xbf58_476d_1ce4_e5b9)) } /// Scrambles a u64 using the SplitMix64 finalizer pattern. fn splitmix64(mut value: u64) -> u64 { value = value.wrapping_add(0x9e37_79b9_7f4a_7c15); value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); value ^ (value >> 31) } /// Starts the DARE mask checksum from all operator parameters. fn dare_mask_seed(dropout_seed: u64, delta_weight_ppm: i64, keep_ppm: u32) -> u64 { let mut acc = 0x6461_7265_6d73_6b31u64; mix_mask_value(&mut acc, dropout_seed); mix_mask_value(&mut acc, delta_weight_ppm as u64); mix_mask_value(&mut acc, u64::from(keep_ppm)); acc } /// Starts the raw task-delta checksum from all operator parameters. fn dare_raw_delta_seed(dropout_seed: u64, delta_weight_ppm: i64, keep_ppm: u32) -> u64 { let mut acc = 0x6461_7265_7261_7731u64; mix_delta_value(&mut acc, dropout_seed); mix_delta_value(&mut acc, delta_weight_ppm as u64); mix_delta_value(&mut acc, u64::from(keep_ppm)); acc } /// Starts the rescaled delta checksum from all operator parameters. fn dare_rescaled_delta_seed(dropout_seed: u64, delta_weight_ppm: i64, keep_ppm: u32) -> u64 { let mut acc = 0x6461_7265_7363_6c31u64; mix_delta_value(&mut acc, dropout_seed); mix_delta_value(&mut acc, delta_weight_ppm as u64); mix_delta_value(&mut acc, u64::from(keep_ppm)); acc } /// Folds one mask value into a compact deterministic checksum. fn mix_mask_value(acc: &mut u64, value: u64) { *acc ^= value.wrapping_add(0x9e37_79b9_7f4a_7c15); *acc = acc.rotate_left(11).wrapping_mul(0x1000_0000_01b3); } /// Folds one delta value into a compact deterministic checksum. fn mix_delta_value(acc: &mut u64, value: u64) { *acc ^= value.wrapping_add(0xbf58_476d_1ce4_e5b9); *acc = acc.rotate_left(7).wrapping_mul(0x94d0_49bb_1331_11eb); } /// Converts a count ratio into integer parts-per-million. fn ratio_ppm(numerator: u64, denominator: u64) -> io::Result { if denominator == 0 { return Ok(0); } let ppm = u128::from(numerator) * u128::from(PPM_DENOMINATOR) / u128::from(denominator); u64::try_from(ppm).map_err(|_| invalid("DARE ratio overflowed u64")) } /// Parses DARE task-delta weight as a signed parts-per-million value. fn parse_delta_weight_ppm(value: &str) -> io::Result { let weight = value .parse::() .map_err(|_| invalid("DARE weight must be an integer parts-per-million value"))?; if !(MIN_DELTA_WEIGHT_PPM..=MAX_DELTA_WEIGHT_PPM).contains(&weight) { return Err(invalid("DARE weight must be between -1000000 and 2000000")); } Ok(weight) } /// Parses DARE retained-delta rate as an integer parts-per-million value. fn parse_keep_ppm(value: &str) -> io::Result { let keep = value .parse::() .map_err(|_| invalid("DARE keep must be an integer parts-per-million value"))?; if keep > PPM_DENOMINATOR { return Err(invalid("DARE keep must be between 0 and 1000000")); } Ok(keep) } /// Parses the deterministic DARE dropout seed. fn parse_dropout_seed(value: &str) -> io::Result { value .parse::() .map_err(|_| invalid("DARE dropout seed must be an unsigned integer")) } /// Holds deterministic DARE selection counts and checksum metadata. #[derive(Clone, Copy)] struct DareStats { total_parameter_count: u64, nonzero_delta_count: u64, selected_delta_count: u64, dropped_delta_count: u64, unchanged_parameter_count: u64, selection_density_ppm: u64, nonzero_delta_retention_ppm: u64, mask_checksum: u64, raw_delta_checksum: u64, rescaled_delta_checksum: u64, } #[cfg(test)] mod tests { use super::*; use crate::compatibility; use crate::tensor_writer::{tiny_fixture_tensors, tiny_fixture_tensors_with_dtype, DTYPE_Q8_0}; use crate::tokenizer_writer::ByteTokenizerSection; use crate::{build_model_file_from_values_with_flags, fixture_value}; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; // Exercises weight, keep rate, and seed through candidate writing and receipt validation. #[test] fn writes_and_validates_seeded_f32_dare_candidate() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "dare-f32", "dare-v1", "tiny").unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", 1_000_000, 500_000, 7, ) .unwrap(); validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); assert!(any_value_differs(&candidate, &base)); assert!(some_values_equal(&candidate, &base)); assert!(receipt.contains("operator_kind=dropout-rescaled-task-delta")); assert!(receipt.contains("delta_weight_ppm=1000000")); assert!(receipt.contains("dare_keep_ppm=500000")); assert!(receipt.contains("dare_dropout_seed=7")); assert!(receipt.contains("dare_mask_checksum=")); assert!(receipt.contains("dare_rescaled_delta_checksum=")); } // Exercises all path-level inputs plus default weight, keep, and seed parameters. #[test] fn path_writer_uses_default_parameters_then_validates() { let dir = unique_dir("path-defaults"); fs::create_dir_all(&dir).unwrap(); let base_path = dir.join("base.slm"); let target_path = dir.join("target.slm"); let compatibility_path = dir.join("parents.compat"); let lineage_path = dir.join("candidate.lineage"); let candidate_path = dir.join("candidate.slm"); let receipt_path = dir.join("candidate.operator"); let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(2.0); fs::write(&base_path, &base).unwrap(); fs::write(&target_path, &target).unwrap(); let compatibility = compatibility::compatibility_text_for_bytes( &base, &base_path.display().to_string(), &target, &target_path.display().to_string(), ) .unwrap(); fs::write(&compatibility_path, &compatibility).unwrap(); let lineage = lineage::build_template_text(&compatibility, "dare-path", "dare-v1", "tiny").unwrap(); fs::write(&lineage_path, &lineage).unwrap(); write_candidate_path( &compatibility_path, &lineage_path, &base_path, &target_path, &candidate_path, &receipt_path, None, None, None, ) .unwrap(); validate_candidate_path( &compatibility_path, &lineage_path, &base_path, &target_path, &candidate_path, &receipt_path, ) .unwrap(); let receipt = fs::read_to_string(receipt_path).unwrap(); assert!(receipt.contains("delta_weight_ppm=1000000")); assert!(receipt.contains("dare_keep_ppm=500000")); assert!(receipt.contains("dare_dropout_seed=1469598103934665603")); } // Covers keep_ppm lower boundary where all nonzero deltas are dropped. #[test] fn keep_zero_preserves_base_values() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "dare-zero", "dare-v1", "tiny").unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", 1_000_000, 0, 11, ) .unwrap(); assert_same_values(&candidate, &base); assert!(receipt.contains("dare_keep_ppm=0")); assert!(receipt.contains("dare_selected_delta_count=0")); assert!(receipt.contains("dare_nonzero_delta_retention_ppm=0")); assert!(receipt.contains("dare_rescale_multiplier_ppm=0")); } // Covers keep_ppm upper boundary where full-weight DARE matches the target. #[test] fn keep_full_and_full_weight_matches_target_values() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "dare-full", "dare-v1", "tiny").unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", 1_000_000, 1_000_000, 13, ) .unwrap(); assert_close_values(&candidate, &target); assert!(receipt.contains("dare_keep_ppm=1000000")); assert!(receipt.contains("dare_drop_ppm=0")); assert!(receipt.contains("dare_nonzero_delta_retention_ppm=1000000")); } // Confirms dropout_seed changes the kept delta mask. #[test] fn dropout_seed_changes_selection_mask() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "dare-seed", "dare-v1", "tiny").unwrap(); let (candidate_a, receipt_a) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "a.slm", 1_000_000, 500_000, 1, ) .unwrap(); let (candidate_b, receipt_b) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "b.slm", 1_000_000, 500_000, 2, ) .unwrap(); let fields_a = parse_manifest(&receipt_a, "receipt a").unwrap(); let fields_b = parse_manifest(&receipt_b, "receipt b").unwrap(); assert_ne!(candidate_a, candidate_b); assert_ne!( fields_a.get("dare_mask_checksum"), fields_b.get("dare_mask_checksum") ); } // Confirms delta_weight_ppm changes the rescaled delta and candidate bytes. #[test] fn delta_weight_changes_rescaled_candidate_values() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "dare-weight", "dare-v1", "tiny").unwrap(); let (small, small_receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "small.slm", 500_000, 500_000, 7, ) .unwrap(); let (large, large_receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "large.slm", 1_000_000, 500_000, 7, ) .unwrap(); let small_fields = parse_manifest(&small_receipt, "small receipt").unwrap(); let large_fields = parse_manifest(&large_receipt, "large receipt").unwrap(); assert_ne!(small, large); assert_ne!( small_fields.get("dare_rescaled_delta_checksum"), large_fields.get("dare_rescaled_delta_checksum") ); } // Covers the accepted negative delta_weight_ppm boundary direction. #[test] fn negative_weight_extrapolates_away_from_target() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let expected = tiny_f32_scaled_bytes(0.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "dare-negative", "dare-v1", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", -500_000, 1_000_000, 7, ) .unwrap(); assert_close_values(&candidate, &expected); assert!(receipt.contains("delta_weight_ppm=-500000")); assert!(receipt.contains("dare_keep_ppm=1000000")); } // Validates q8 parents keep their quantization route through DARE output. #[test] fn writes_and_validates_q8_dare_candidate() { let base = tiny_q8_scaled_bytes(1.0); let target = tiny_q8_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "dare-q8", "dare-v1", "tiny").unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", 500_000, 500_000, 42, ) .unwrap(); slm_validate::validate_bytes(&candidate, "candidate.slm").unwrap(); validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); assert!(receipt.contains("candidate_quantization=q8_0")); } // Confirms base parameters are tied to compatibility receipts by checksum. #[test] fn rejects_parent_checksum_drift() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "dare-drift", "dare-v1", "tiny").unwrap(); let changed_base = tiny_f32_scaled_bytes(2.0); let error = build_candidate_bytes_and_receipt( &compatibility, &lineage, &changed_base, "base.slm", &target, "target.slm", "candidate.slm", 1_000_000, 500_000, 7, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("parent.0.slm_checksum")); } // Confirms validation catches candidate bytes that no longer match the receipt. #[test] fn validation_rejects_candidate_drift() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "dare-drift", "dare-v1", "tiny").unwrap(); let (mut candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", 1_000_000, 500_000, 7, ) .unwrap(); let last = candidate.len() - 1; candidate[last] ^= 0x01; let error = validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &candidate, "candidate.slm", &receipt, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate bytes")); } // Covers parser behavior for weight, keep, and seed inputs. #[test] fn rejects_invalid_dare_parameters() { assert_eq!( parse_delta_weight_ppm("-1000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_delta_weight_ppm("2000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_delta_weight_ppm("1.5").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_keep_ppm("1000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_keep_ppm("-1").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_keep_ppm("half").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_dropout_seed("18446744073709551616") .unwrap_err() .kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_dropout_seed("-1").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_dropout_seed("seed").unwrap_err().kind(), io::ErrorKind::InvalidData ); } // Compares decoded tensor values between two `.slm` byte buffers exactly. fn assert_same_values(candidate: &[u8], expected: &[u8]) { let candidate_values = parse_model_values(candidate).unwrap(); let expected_values = parse_model_values(expected).unwrap(); for (candidate_tensor, expected_tensor) in candidate_values .tensors .iter() .zip(expected_values.tensors.iter()) { assert_eq!(candidate_tensor.values, expected_tensor.values); } } // Compares decoded tensor values with a small tolerance for f32 recomputation. fn assert_close_values(candidate: &[u8], expected: &[u8]) { let candidate_values = parse_model_values(candidate).unwrap(); let expected_values = parse_model_values(expected).unwrap(); for (candidate_tensor, expected_tensor) in candidate_values .tensors .iter() .zip(expected_values.tensors.iter()) { for (candidate_value, expected_value) in candidate_tensor .values .iter() .zip(expected_tensor.values.iter()) { assert!((candidate_value - expected_value).abs() <= 0.000001); } } } // Detects whether any decoded tensor value differs between two `.slm` buffers. fn any_value_differs(candidate: &[u8], expected: &[u8]) -> bool { let candidate_values = parse_model_values(candidate).unwrap(); let expected_values = parse_model_values(expected).unwrap(); candidate_values .tensors .iter() .zip(expected_values.tensors.iter()) .any(|(candidate_tensor, expected_tensor)| { candidate_tensor.values != expected_tensor.values }) } // Detects whether any decoded tensor value is preserved between two `.slm` buffers. fn some_values_equal(candidate: &[u8], expected: &[u8]) -> bool { let candidate_values = parse_model_values(candidate).unwrap(); let expected_values = parse_model_values(expected).unwrap(); candidate_values .tensors .iter() .zip(expected_values.tensors.iter()) .any(|(candidate_tensor, expected_tensor)| { candidate_tensor .values .iter() .zip(expected_tensor.values.iter()) .any(|(candidate_value, expected_value)| candidate_value == expected_value) }) } // Builds a tiny f32 model with all fixture values multiplied by scale. fn tiny_f32_scaled_bytes(scale: f32) -> Vec { build_tiny_bytes(tiny_fixture_tensors(), |tensor, index, _tensor_index| { fixture_value(tensor, index) * scale }) } // Builds a tiny q8 model with all fixture values multiplied by scale. fn tiny_q8_scaled_bytes(scale: f32) -> Vec { build_tiny_bytes( tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), |tensor, index, _tensor_index| fixture_value(tensor, index) * scale, ) } // Packs a tiny fixture model from caller-supplied tensor values. fn build_tiny_bytes(tensors: Vec, mut value: F) -> Vec where F: FnMut(&crate::tensor_writer::TensorSpec, usize, usize) -> f32, { let values = tensors .iter() .enumerate() .map(|(tensor_index, tensor)| { (0..tensor.element_count()) .map(|index| value(tensor, index, tensor_index)) .collect::>() }) .collect::>(); build_model_file_from_values_with_flags( &crate::tensor_writer::ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } // Creates an isolated temp directory for path-level operator tests. fn unique_dir(label: &str) -> PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-dare-{label}-{nanos}")) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/dare.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/delta.rs BYTES: 19698 SHA256: 1AD6CFF9FA117EC615FCA429F45D16927E9690C959BE486E7742A2A00B5B87D2 ================================================================================ //! Offline direct-parameter task-delta operator for model-breeding candidates. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::blend::{ hex64, invalid, output_specs, parse_manifest, parse_model_values, parse_passing_compatibility, push_line, push_parent_lines, require_equal, require_key, require_parent_report, require_report_equal, require_same_tensor_spec, same_shape, ParsedModel, PPM_DENOMINATOR, }; use crate::build_model_file_from_values_with_flags; use crate::lineage; use crate::slm_validate::{self, ValidationReport}; const DELTA_OPERATOR_VERSION: &str = "1"; const OPERATOR_KIND: &str = "direct-parameter-task-delta"; const OPERATOR_STATUS: &str = "candidate-written"; const OPERATOR_OUTPUT_STATUS: &str = "slm-validated"; const PARENT_CONTRACT: &str = "matches-parent-direct-parameter-contract"; const REQUIRED_NEXT_GATE: &str = "candidate-manifest-plus-runtime-smoke-plus-eval"; const MIN_DELTA_WEIGHT_PPM: i64 = -1_000_000; const MAX_DELTA_WEIGHT_PPM: i64 = 2_000_000; /// Writes a task-delta candidate `.slm` plus a recomputable operator receipt. pub(crate) fn write_candidate_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, output_slm: &Path, output_receipt: &Path, delta_weight_ppm: &str, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let weight = parse_delta_weight_ppm(delta_weight_ppm)?; let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &output_slm.display().to_string(), weight, )?; if let Some(parent) = output_slm.parent() { fs::create_dir_all(parent)?; } fs::write(output_slm, candidate)?; if let Some(parent) = output_receipt.parent() { fs::create_dir_all(parent)?; } fs::write(output_receipt, receipt)?; println!("SLM task-delta candidate written: {}", output_slm.display()); println!( "SLM task-delta operator receipt written: {}", output_receipt.display() ); Ok(()) } /// Validates a task-delta candidate and receipt by recomputing the operator output. pub(crate) fn validate_candidate_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, candidate_slm: &Path, receipt: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; validate_candidate_text( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &candidate_bytes, &candidate_slm.display().to_string(), &receipt_text, )?; println!("SLM task-delta candidate validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("receipt: {}", receipt.display()); Ok(()) } fn validate_candidate_text( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, ) -> io::Result<()> { let receipt = parse_manifest(receipt_text, "task-delta operator receipt")?; require_equal( &receipt, "tinyrustlm_delta_operator_version", DELTA_OPERATOR_VERSION, )?; require_equal(&receipt, "delta_weight_unit", "parts-per-million")?; require_equal(&receipt, "base_parent_index", "0")?; require_equal(&receipt, "target_parent_index", "1")?; let weight = parse_delta_weight_ppm(require_key(&receipt, "delta_weight_ppm")?)?; require_equal( &receipt, "base_coefficient_ppm", &(i64::from(PPM_DENOMINATOR) - weight).to_string(), )?; require_equal( &receipt, "target_delta_coefficient_ppm", &weight.to_string(), )?; let (expected_candidate, expected_receipt) = build_candidate_bytes_and_receipt( compatibility_text, lineage_text, base_bytes, base_path, target_bytes, target_path, candidate_path, weight, )?; if candidate_bytes != expected_candidate { return Err(invalid( "task-delta candidate bytes do not match the operator receipt", )); } if receipt_text != expected_receipt { return Err(invalid( "task-delta operator receipt fields do not match recomputed output", )); } Ok(()) } fn build_candidate_bytes_and_receipt( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, candidate_path: &str, delta_weight_ppm: i64, ) -> io::Result<(Vec, String)> { lineage::validate_text(compatibility_text, lineage_text)?; let compatibility = parse_passing_compatibility(compatibility_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let base_report = slm_validate::validate_bytes(base_bytes, base_path)?; let target_report = slm_validate::validate_bytes(target_bytes, target_path)?; require_parent_report(&compatibility, 0, &base_report)?; require_parent_report(&compatibility, 1, &target_report)?; let base = parse_model_values(base_bytes)?; let target = parse_model_values(target_bytes)?; let output_values = delta_values(&base, &target, delta_weight_ppm)?; let output_tensors = output_specs(&base); let candidate = build_model_file_from_values_with_flags( &base.shape, &output_tensors, &base.tokenizer, &output_values, base.flags, )?; let candidate_report = slm_validate::validate_bytes(&candidate, candidate_path)?; require_report_equal( &compatibility, "parent.0.model_shape", &candidate_report.shape_summary(), )?; require_report_equal( &compatibility, "parent.0.quantization", candidate_report.quantization_label(), )?; require_report_equal( &compatibility, "parent.0.output_contract", candidate_report.output_contract_label(), )?; require_report_equal( &compatibility, "parent.0.tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), )?; require_report_equal( &compatibility, "parent.0.tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), )?; let receipt = build_receipt_text( &compatibility, &lineage_fields, lineage_text, base_path, target_path, &base_report, &target_report, &candidate_report, delta_weight_ppm, )?; Ok((candidate, receipt)) } fn build_receipt_text( compatibility: &HashMap, lineage_fields: &HashMap, lineage_text: &str, base_path: &str, target_path: &str, base_report: &ValidationReport, target_report: &ValidationReport, candidate_report: &ValidationReport, delta_weight_ppm: i64, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_delta_operator_version", DELTA_OPERATOR_VERSION, ); push_line(&mut text, "operator_kind", OPERATOR_KIND); push_line(&mut text, "operator_status", OPERATOR_STATUS); push_line( &mut text, "candidate_id", require_key(lineage_fields, "candidate_id")?, ); push_line( &mut text, "operator_id", require_key(lineage_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(lineage_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(lineage_fields, "resource_budget")?, ); push_line( &mut text, "compatibility_report_checksum", require_key(lineage_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(compatibility, "compatibility_scope")?, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, compatibility, 0, base_path, base_report)?; push_parent_lines(&mut text, compatibility, 1, target_path, target_report)?; push_line(&mut text, "delta_weight_unit", "parts-per-million"); push_line(&mut text, "base_parent_index", "0"); push_line(&mut text, "target_parent_index", "1"); push_line(&mut text, "delta_weight_ppm", &delta_weight_ppm.to_string()); push_line( &mut text, "base_coefficient_ppm", &(i64::from(PPM_DENOMINATOR) - delta_weight_ppm).to_string(), ); push_line( &mut text, "target_delta_coefficient_ppm", &delta_weight_ppm.to_string(), ); push_line( &mut text, "candidate_artifact_path", candidate_report.path(), ); push_line( &mut text, "candidate_artifact_bytes", &candidate_report.file_bytes().to_string(), ); push_line( &mut text, "candidate_slm_version", &candidate_report.slm_version().to_string(), ); push_line( &mut text, "candidate_slm_checksum", &hex64(candidate_report.checksum()), ); push_line( &mut text, "candidate_model_shape", &candidate_report.shape_summary(), ); push_line( &mut text, "candidate_tensor_count", &candidate_report.tensor_count().to_string(), ); push_line( &mut text, "candidate_parameter_count", &candidate_report.parameter_count().to_string(), ); push_line( &mut text, "candidate_quantization", candidate_report.quantization_label(), ); push_line( &mut text, "candidate_output_contract", candidate_report.output_contract_label(), ); push_line( &mut text, "candidate_tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), ); push_line( &mut text, "candidate_tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), ); push_line(&mut text, "candidate_parent_contract", PARENT_CONTRACT); push_line(&mut text, "operator_output_status", OPERATOR_OUTPUT_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } fn delta_values( base: &ParsedModel, target: &ParsedModel, delta_weight_ppm: i64, ) -> io::Result>> { if !same_shape(&base.shape, &target.shape) { return Err(invalid("task-delta parents have different model shapes")); } if base.flags != target.flags { return Err(invalid("task-delta parents have different output flags")); } if base.tokenizer.bytes != target.tokenizer.bytes { return Err(invalid("task-delta parents have different tokenizer bytes")); } let target_by_hash = target .tensors .iter() .enumerate() .map(|(index, tensor)| (tensor.spec.name_hash, index)) .collect::>(); let delta_weight = delta_weight_ppm as f32 / PPM_DENOMINATOR as f32; let mut output = Vec::with_capacity(base.tensors.len()); for base_tensor in &base.tensors { let Some(target_index) = target_by_hash.get(&base_tensor.spec.name_hash) else { return Err(invalid( "target parent is missing a tensor from the base parent", )); }; let target_tensor = &target.tensors[*target_index]; require_same_tensor_spec(&base_tensor.spec, &target_tensor.spec)?; let values = base_tensor .values .iter() .zip(target_tensor.values.iter()) .map(|(base_value, target_value)| { base_value + (target_value - base_value) * delta_weight }) .collect::>(); output.push(values); } Ok(output) } fn parse_delta_weight_ppm(value: &str) -> io::Result { let weight = value .parse::() .map_err(|_| invalid("task-delta weight must be an integer parts-per-million value"))?; if !(MIN_DELTA_WEIGHT_PPM..=MAX_DELTA_WEIGHT_PPM).contains(&weight) { return Err(invalid( "task-delta weight must be between -1000000 and 2000000", )); } Ok(weight) } #[cfg(test)] mod tests { use super::*; use crate::compatibility; use crate::tensor_writer::{tiny_fixture_tensors, tiny_fixture_tensors_with_dtype, DTYPE_Q8_0}; use crate::tokenizer_writer::ByteTokenizerSection; use crate::{build_model_file, build_model_file_from_values_with_flags, fixture_value}; #[test] fn writes_and_validates_weighted_f32_task_delta_candidate() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "delta-f32", "task-vector-v1", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", 500_000, ) .unwrap(); validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); let parsed = parse_model_values(&candidate).unwrap(); assert_eq!(parsed.tensors[0].values[0], 0.25); assert!(receipt.contains("operator_kind=direct-parameter-task-delta")); assert!(receipt.contains("delta_weight_ppm=500000")); assert!(receipt.contains("base_coefficient_ppm=500000")); } #[test] fn writes_and_validates_q8_task_delta_candidate() { let base = tiny_q8_bytes(); let target = tiny_q8_bytes(); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "delta-q8", "task-vector-v1", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", 1_000_000, ) .unwrap(); slm_validate::validate_bytes(&candidate, "candidate.slm").unwrap(); validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); assert!(receipt.contains("candidate_quantization=q8_0")); } #[test] fn rejects_parent_checksum_drift() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "delta-f32", "task-vector-v1", "tiny") .unwrap(); let changed_base = tiny_f32_scaled_bytes(2.0); let error = build_candidate_bytes_and_receipt( &compatibility, &lineage, &changed_base, "base.slm", &target, "target.slm", "candidate.slm", 1_000_000, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("parent.0.slm_checksum")); } #[test] fn validation_rejects_candidate_drift() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "delta-f32", "task-vector-v1", "tiny") .unwrap(); let (mut candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", 1_000_000, ) .unwrap(); let last = candidate.len() - 1; candidate[last] ^= 0x01; let error = validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &candidate, "candidate.slm", &receipt, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate bytes")); } #[test] fn rejects_invalid_task_delta_weight() { assert_eq!( parse_delta_weight_ppm("-1000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_delta_weight_ppm("2000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_delta_weight_ppm("1.5").unwrap_err().kind(), io::ErrorKind::InvalidData ); } fn tiny_f32_scaled_bytes(scale: f32) -> Vec { let tensors = tiny_fixture_tensors(); let values = tensors .iter() .map(|tensor| { (0..tensor.element_count()) .map(|index| fixture_value(tensor, index) * scale) .collect::>() }) .collect::>(); build_model_file_from_values_with_flags( &crate::tensor_writer::ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } fn tiny_q8_bytes() -> Vec { build_model_file( &crate::tensor_writer::ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), &ByteTokenizerSection::phase_one(), ) .unwrap() } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/delta.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/federated.rs BYTES: 33302 SHA256: 2E8E856E6BB0D9B194F308385B3F4148FA9368CA23F99FE1C9327CC113661009 ================================================================================ //! Offline federated/local-update operator for model-breeding candidates. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::blend::{ hex64, invalid, output_specs, parse_manifest, parse_model_values, parse_passing_compatibility, push_line, push_parent_lines, require_equal, require_key, require_parent_report, require_report_equal, require_same_tensor_spec, same_shape, ParsedModel, PPM_DENOMINATOR, }; use crate::build_model_file_from_values_with_flags; use crate::lineage; use crate::slm_validate::{self, ValidationReport}; const FEDERATED_OPERATOR_VERSION: &str = "1"; const OPERATOR_KIND: &str = "federated-local-update-average"; const OPERATOR_STATUS: &str = "candidate-written"; const OPERATOR_OUTPUT_STATUS: &str = "slm-validated"; const PARENT_CONTRACT: &str = "matches-parent-direct-parameter-contract"; const REQUIRED_NEXT_GATE: &str = "candidate-manifest-plus-runtime-smoke-plus-eval"; const DEFAULT_LOCAL_UPDATE_WEIGHT_PPM: &str = "1000000"; const UPDATE_STRATEGY: &str = "single-client-fedavg-v1"; const UPDATE_SCOPE: &str = "compatible-direct-parameter-delta"; /// Writes a federated local-update candidate `.slm` plus a recomputable receipt. pub(crate) fn write_candidate_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, local_update_parent: &Path, output_slm: &Path, output_receipt: &Path, local_update_weight_ppm: Option<&str>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let local_update_bytes = fs::read(local_update_parent)?; let weight = parse_local_update_weight_ppm( local_update_weight_ppm.unwrap_or(DEFAULT_LOCAL_UPDATE_WEIGHT_PPM), )?; let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &local_update_bytes, &local_update_parent.display().to_string(), &output_slm.display().to_string(), weight, )?; if let Some(parent) = output_slm.parent() { fs::create_dir_all(parent)?; } fs::write(output_slm, candidate)?; if let Some(parent) = output_receipt.parent() { fs::create_dir_all(parent)?; } fs::write(output_receipt, receipt)?; println!( "SLM federated local-update candidate written: {}", output_slm.display() ); println!( "SLM federated operator receipt written: {}", output_receipt.display() ); Ok(()) } /// Validates a federated local-update candidate by replaying the receipt. pub(crate) fn validate_candidate_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, local_update_parent: &Path, candidate_slm: &Path, receipt: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let local_update_bytes = fs::read(local_update_parent)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; validate_candidate_text( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &local_update_bytes, &local_update_parent.display().to_string(), &candidate_bytes, &candidate_slm.display().to_string(), &receipt_text, )?; println!("SLM federated local-update candidate validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("receipt: {}", receipt.display()); Ok(()) } /// Recomputes federated output from receipt fields and compares both artifacts. fn validate_candidate_text( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, local_update_bytes: &[u8], local_update_path: &str, candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, ) -> io::Result<()> { let receipt = parse_manifest(receipt_text, "federated operator receipt")?; require_equal( &receipt, "tinyrustlm_federated_operator_version", FEDERATED_OPERATOR_VERSION, )?; require_equal(&receipt, "operator_kind", OPERATOR_KIND)?; require_equal(&receipt, "base_parent_index", "0")?; require_equal(&receipt, "local_update_parent_index", "1")?; require_equal(&receipt, "local_update_weight_unit", "parts-per-million")?; require_equal(&receipt, "local_update_strategy", UPDATE_STRATEGY)?; require_equal(&receipt, "local_update_scope", UPDATE_SCOPE)?; let weight = parse_local_update_weight_ppm(require_key(&receipt, "local_update_weight_ppm")?)?; require_equal( &receipt, "base_coefficient_ppm", &(PPM_DENOMINATOR - weight).to_string(), )?; require_equal( &receipt, "local_update_coefficient_ppm", &weight.to_string(), )?; let (expected_candidate, expected_receipt) = build_candidate_bytes_and_receipt( compatibility_text, lineage_text, base_bytes, base_path, local_update_bytes, local_update_path, candidate_path, weight, )?; if candidate_bytes != expected_candidate { return Err(invalid( "federated candidate bytes do not match the operator receipt", )); } if receipt_text != expected_receipt { return Err(invalid( "federated operator receipt fields do not match recomputed output", )); } Ok(()) } /// Builds the federated `.slm` bytes and receipt from compatible parent bytes. fn build_candidate_bytes_and_receipt( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, local_update_bytes: &[u8], local_update_path: &str, candidate_path: &str, local_update_weight_ppm: u32, ) -> io::Result<(Vec, String)> { lineage::validate_text(compatibility_text, lineage_text)?; let compatibility = parse_passing_compatibility(compatibility_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let base_report = slm_validate::validate_bytes(base_bytes, base_path)?; let local_update_report = slm_validate::validate_bytes(local_update_bytes, local_update_path)?; require_parent_report(&compatibility, 0, &base_report)?; require_parent_report(&compatibility, 1, &local_update_report)?; let base = parse_model_values(base_bytes)?; let local_update = parse_model_values(local_update_bytes)?; let (output_values, stats) = federated_values(&base, &local_update, local_update_weight_ppm)?; let output_tensors = output_specs(&base); let candidate = build_model_file_from_values_with_flags( &base.shape, &output_tensors, &base.tokenizer, &output_values, base.flags, )?; let candidate_report = slm_validate::validate_bytes(&candidate, candidate_path)?; require_report_equal( &compatibility, "parent.0.model_shape", &candidate_report.shape_summary(), )?; require_report_equal( &compatibility, "parent.0.quantization", candidate_report.quantization_label(), )?; require_report_equal( &compatibility, "parent.0.output_contract", candidate_report.output_contract_label(), )?; require_report_equal( &compatibility, "parent.0.tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), )?; require_report_equal( &compatibility, "parent.0.tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), )?; let receipt = build_receipt_text( &compatibility, &lineage_fields, lineage_text, base_path, local_update_path, &base_report, &local_update_report, &candidate_report, local_update_weight_ppm, stats, )?; Ok((candidate, receipt)) } /// Formats the receipt fields that make a local-update candidate replayable. #[allow(clippy::too_many_arguments)] fn build_receipt_text( compatibility: &HashMap, lineage_fields: &HashMap, lineage_text: &str, base_path: &str, local_update_path: &str, base_report: &ValidationReport, local_update_report: &ValidationReport, candidate_report: &ValidationReport, local_update_weight_ppm: u32, stats: FederatedStats, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_federated_operator_version", FEDERATED_OPERATOR_VERSION, ); push_line(&mut text, "operator_kind", OPERATOR_KIND); push_line(&mut text, "operator_status", OPERATOR_STATUS); push_line( &mut text, "candidate_id", require_key(lineage_fields, "candidate_id")?, ); push_line( &mut text, "operator_id", require_key(lineage_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(lineage_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(lineage_fields, "resource_budget")?, ); push_line( &mut text, "compatibility_report_checksum", require_key(lineage_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(compatibility, "compatibility_scope")?, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, compatibility, 0, base_path, base_report)?; push_parent_lines( &mut text, compatibility, 1, local_update_path, local_update_report, )?; push_line(&mut text, "base_parent_index", "0"); push_line(&mut text, "local_update_parent_index", "1"); push_line(&mut text, "local_update_strategy", UPDATE_STRATEGY); push_line(&mut text, "local_update_scope", UPDATE_SCOPE); push_line(&mut text, "local_update_weight_unit", "parts-per-million"); push_line( &mut text, "local_update_weight_ppm", &local_update_weight_ppm.to_string(), ); push_line( &mut text, "base_coefficient_ppm", &(PPM_DENOMINATOR - local_update_weight_ppm).to_string(), ); push_line( &mut text, "local_update_coefficient_ppm", &local_update_weight_ppm.to_string(), ); push_line( &mut text, "local_update_total_parameter_count", &stats.total_parameter_count.to_string(), ); push_line( &mut text, "local_update_changed_parameter_count", &stats.changed_parameter_count.to_string(), ); push_line( &mut text, "local_update_changed_density_ppm", &stats.changed_density_ppm.to_string(), ); push_line( &mut text, "local_update_delta_checksum", &hex64(stats.delta_checksum), ); push_line( &mut text, "local_update_weighted_delta_checksum", &hex64(stats.weighted_delta_checksum), ); push_line( &mut text, "candidate_artifact_path", candidate_report.path(), ); push_line( &mut text, "candidate_artifact_bytes", &candidate_report.file_bytes().to_string(), ); push_line( &mut text, "candidate_slm_version", &candidate_report.slm_version().to_string(), ); push_line( &mut text, "candidate_slm_checksum", &hex64(candidate_report.checksum()), ); push_line( &mut text, "candidate_model_shape", &candidate_report.shape_summary(), ); push_line( &mut text, "candidate_tensor_count", &candidate_report.tensor_count().to_string(), ); push_line( &mut text, "candidate_parameter_count", &candidate_report.parameter_count().to_string(), ); push_line( &mut text, "candidate_quantization", candidate_report.quantization_label(), ); push_line( &mut text, "candidate_output_contract", candidate_report.output_contract_label(), ); push_line( &mut text, "candidate_tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), ); push_line( &mut text, "candidate_tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), ); push_line(&mut text, "candidate_parent_contract", PARENT_CONTRACT); push_line(&mut text, "operator_output_status", OPERATOR_OUTPUT_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } /// Applies `base + weight * (local_update - base)` across compatible tensors. fn federated_values( base: &ParsedModel, local_update: &ParsedModel, local_update_weight_ppm: u32, ) -> io::Result<(Vec>, FederatedStats)> { if !same_shape(&base.shape, &local_update.shape) { return Err(invalid("federated parents have different model shapes")); } if base.flags != local_update.flags { return Err(invalid("federated parents have different output flags")); } if base.tokenizer.bytes != local_update.tokenizer.bytes { return Err(invalid("federated parents have different tokenizer bytes")); } let update_by_hash = local_update .tensors .iter() .enumerate() .map(|(index, tensor)| (tensor.spec.name_hash, index)) .collect::>(); let update_weight = local_update_weight_ppm as f32 / PPM_DENOMINATOR as f32; let mut output = Vec::with_capacity(base.tensors.len()); let mut stats = FederatedStats { total_parameter_count: 0, changed_parameter_count: 0, changed_density_ppm: 0, delta_checksum: checksum_seed(0x6665_6464_656c_7631, local_update_weight_ppm), weighted_delta_checksum: checksum_seed(0x6665_6477_656c_7631, local_update_weight_ppm), }; for (tensor_index, base_tensor) in base.tensors.iter().enumerate() { let Some(update_index) = update_by_hash.get(&base_tensor.spec.name_hash) else { return Err(invalid( "local update parent is missing a tensor from the base parent", )); }; let update_tensor = &local_update.tensors[*update_index]; require_same_tensor_spec(&base_tensor.spec, &update_tensor.spec)?; let mut values = Vec::with_capacity(base_tensor.values.len()); for (value_index, (base_value, update_value)) in base_tensor .values .iter() .zip(update_tensor.values.iter()) .enumerate() { let raw_delta = *update_value - *base_value; let weighted_delta = raw_delta * update_weight; let value = *base_value + weighted_delta; if !value.is_finite() { return Err(invalid( "federated local update produced a non-finite value", )); } stats.total_parameter_count += 1; if value != *base_value { stats.changed_parameter_count += 1; } mix_checksum(&mut stats.delta_checksum, tensor_index as u64); mix_checksum(&mut stats.delta_checksum, value_index as u64); mix_checksum(&mut stats.delta_checksum, u64::from(raw_delta.to_bits())); mix_checksum(&mut stats.weighted_delta_checksum, tensor_index as u64); mix_checksum(&mut stats.weighted_delta_checksum, value_index as u64); mix_checksum( &mut stats.weighted_delta_checksum, u64::from(weighted_delta.to_bits()), ); mix_checksum( &mut stats.weighted_delta_checksum, u64::from(value.to_bits()), ); values.push(value); } output.push(values); } stats.changed_density_ppm = ratio_ppm(stats.changed_parameter_count, stats.total_parameter_count)?; mix_checksum(&mut stats.delta_checksum, stats.total_parameter_count); mix_checksum(&mut stats.delta_checksum, stats.changed_parameter_count); mix_checksum( &mut stats.weighted_delta_checksum, stats.changed_parameter_count, ); Ok((output, stats)) } /// Starts a compact checksum from the operator kind and local-update weight. fn checksum_seed(seed: u64, local_update_weight_ppm: u32) -> u64 { let mut acc = seed; mix_checksum(&mut acc, u64::from(local_update_weight_ppm)); acc } /// Folds one u64 into a deterministic receipt checksum. fn mix_checksum(acc: &mut u64, value: u64) { *acc ^= value.wrapping_add(0x9e37_79b9_7f4a_7c15); *acc = acc.rotate_left(9).wrapping_mul(0x1000_0000_01b3); } /// Converts a count ratio into integer parts-per-million. fn ratio_ppm(numerator: u64, denominator: u64) -> io::Result { if denominator == 0 { return Ok(0); } let ppm = u128::from(numerator) * u128::from(PPM_DENOMINATOR) / u128::from(denominator); u64::try_from(ppm).map_err(|_| invalid("federated ratio overflowed u64")) } /// Parses local update weight as an integer parts-per-million value. fn parse_local_update_weight_ppm(value: &str) -> io::Result { let weight = value .parse::() .map_err(|_| invalid("local update weight must be an integer parts-per-million value"))?; if weight > PPM_DENOMINATOR { return Err(invalid("local update weight must be between 0 and 1000000")); } Ok(weight) } /// Holds receipt metadata for the federated local-update delta. #[derive(Clone, Copy)] struct FederatedStats { total_parameter_count: u64, changed_parameter_count: u64, changed_density_ppm: u64, delta_checksum: u64, weighted_delta_checksum: u64, } #[cfg(test)] mod tests { use super::*; use crate::compatibility; use crate::tensor_writer::{tiny_fixture_tensors, tiny_fixture_tensors_with_dtype, DTYPE_Q8_0}; use crate::tokenizer_writer::ByteTokenizerSection; use crate::{build_model_file_from_values_with_flags, fixture_value}; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; // Exercises lineage, compatibility, both parent byte inputs, and update weight. #[test] fn writes_and_validates_weighted_f32_federated_candidate() { let base = tiny_f32_scaled_bytes(1.0); let local_update = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes( &base, "base.slm", &local_update, "local.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, "fed-f32", "federated-v1", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &local_update, "local.slm", "candidate.slm", 250_000, ) .unwrap(); validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &local_update, "local.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); assert_ne!( parse_model_values(&candidate).unwrap().tensors[0].values, parse_model_values(&base).unwrap().tensors[0].values ); assert!(receipt.contains("operator_kind=federated-local-update-average")); assert!(receipt.contains("local_update_strategy=single-client-fedavg-v1")); assert!(receipt.contains("local_update_weight_ppm=250000")); assert!(receipt.contains("base_coefficient_ppm=750000")); assert!(receipt.contains("local_update_delta_checksum=")); assert!(receipt.contains("local_update_weighted_delta_checksum=")); } // Exercises path-level IO and the default local_update_weight_ppm parameter. #[test] fn path_writer_uses_default_weight_then_validates() { let dir = unique_dir("path-defaults"); fs::create_dir_all(&dir).unwrap(); let base_path = dir.join("base.slm"); let local_path = dir.join("local.slm"); let compatibility_path = dir.join("parents.compat"); let lineage_path = dir.join("candidate.lineage"); let candidate_path = dir.join("candidate.slm"); let receipt_path = dir.join("candidate.operator"); let base = tiny_f32_scaled_bytes(1.0); let local_update = tiny_f32_scaled_bytes(2.0); fs::write(&base_path, &base).unwrap(); fs::write(&local_path, &local_update).unwrap(); let compatibility = compatibility::compatibility_text_for_bytes( &base, &base_path.display().to_string(), &local_update, &local_path.display().to_string(), ) .unwrap(); fs::write(&compatibility_path, &compatibility).unwrap(); let lineage = lineage::build_template_text(&compatibility, "fed-path", "federated-v1", "tiny") .unwrap(); fs::write(&lineage_path, &lineage).unwrap(); write_candidate_path( &compatibility_path, &lineage_path, &base_path, &local_path, &candidate_path, &receipt_path, None, ) .unwrap(); validate_candidate_path( &compatibility_path, &lineage_path, &base_path, &local_path, &candidate_path, &receipt_path, ) .unwrap(); let receipt = fs::read_to_string(receipt_path).unwrap(); assert!(receipt.contains("local_update_weight_ppm=1000000")); assert_same_values(&fs::read(candidate_path).unwrap(), &local_update); } // Covers the local_update_weight_ppm lower boundary where the base is preserved. #[test] fn weight_zero_preserves_base_values() { let base = tiny_f32_scaled_bytes(1.0); let local_update = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes( &base, "base.slm", &local_update, "local.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, "fed-zero", "federated-v1", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &local_update, "local.slm", "candidate.slm", 0, ) .unwrap(); assert_same_values(&candidate, &base); assert!(receipt.contains("base_coefficient_ppm=1000000")); assert!(receipt.contains("local_update_changed_parameter_count=0")); assert!(receipt.contains("local_update_changed_density_ppm=0")); } // Covers the upper boundary where the local update becomes the candidate. #[test] fn weight_full_uses_local_update_values() { let base = tiny_f32_scaled_bytes(1.0); let local_update = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes( &base, "base.slm", &local_update, "local.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, "fed-full", "federated-v1", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &local_update, "local.slm", "candidate.slm", 1_000_000, ) .unwrap(); assert_same_values(&candidate, &local_update); let receipt_fields = parse_manifest(&receipt, "federated full update receipt").unwrap(); assert!(receipt.contains("base_coefficient_ppm=0")); let changed = receipt_fields .get("local_update_changed_parameter_count") .unwrap() .parse::() .unwrap(); let total = receipt_fields .get("local_update_total_parameter_count") .unwrap() .parse::() .unwrap(); assert!(changed > 0); assert!(changed <= total); } // Confirms local_update_weight_ppm changes the candidate values and checksum. #[test] fn local_update_weight_changes_candidate_values() { let base = tiny_f32_scaled_bytes(1.0); let local_update = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes( &base, "base.slm", &local_update, "local.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, "fed-weight", "federated-v1", "tiny") .unwrap(); let (small, small_receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &local_update, "local.slm", "small.slm", 250_000, ) .unwrap(); let (large, large_receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &local_update, "local.slm", "large.slm", 750_000, ) .unwrap(); let small_fields = parse_manifest(&small_receipt, "small fed receipt").unwrap(); let large_fields = parse_manifest(&large_receipt, "large fed receipt").unwrap(); assert_ne!(small, large); assert_ne!( small_fields.get("local_update_weighted_delta_checksum"), large_fields.get("local_update_weighted_delta_checksum") ); } // Validates q8 parents keep their quantization route through federated output. #[test] fn writes_and_validates_q8_federated_candidate() { let base = tiny_q8_scaled_bytes(1.0); let local_update = tiny_q8_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes( &base, "base.slm", &local_update, "local.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, "fed-q8", "federated-v1", "tiny").unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &local_update, "local.slm", "candidate.slm", 500_000, ) .unwrap(); slm_validate::validate_bytes(&candidate, "candidate.slm").unwrap(); validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &local_update, "local.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); assert!(receipt.contains("candidate_quantization=q8_0")); } // Confirms base parameters are tied to compatibility reports by checksum. #[test] fn rejects_parent_checksum_drift() { let base = tiny_f32_scaled_bytes(1.0); let local_update = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes( &base, "base.slm", &local_update, "local.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, "fed-drift", "federated-v1", "tiny") .unwrap(); let changed_base = tiny_f32_scaled_bytes(3.0); let error = build_candidate_bytes_and_receipt( &compatibility, &lineage, &changed_base, "base.slm", &local_update, "local.slm", "candidate.slm", 500_000, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("parent.0.slm_checksum")); } // Confirms validation catches candidate bytes that no longer match the receipt. #[test] fn validation_rejects_candidate_drift() { let base = tiny_f32_scaled_bytes(1.0); let local_update = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes( &base, "base.slm", &local_update, "local.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, "fed-drift", "federated-v1", "tiny") .unwrap(); let (mut candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &local_update, "local.slm", "candidate.slm", 500_000, ) .unwrap(); let last = candidate.len() - 1; candidate[last] ^= 0x01; let error = validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &local_update, "local.slm", &candidate, "candidate.slm", &receipt, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate bytes")); } // Covers parser behavior for local_update_weight_ppm. #[test] fn rejects_invalid_local_update_weight() { assert_eq!( parse_local_update_weight_ppm("1000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_local_update_weight_ppm("-1").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_local_update_weight_ppm("half").unwrap_err().kind(), io::ErrorKind::InvalidData ); } // Compares decoded tensor values between two `.slm` byte buffers. fn assert_same_values(candidate: &[u8], expected: &[u8]) { let candidate_values = parse_model_values(candidate).unwrap(); let expected_values = parse_model_values(expected).unwrap(); for (candidate_tensor, expected_tensor) in candidate_values .tensors .iter() .zip(expected_values.tensors.iter()) { assert_eq!(candidate_tensor.values, expected_tensor.values); } } // Builds a tiny f32 model with all fixture values multiplied by scale. fn tiny_f32_scaled_bytes(scale: f32) -> Vec { build_tiny_bytes(tiny_fixture_tensors(), |tensor, index, _tensor_index| { fixture_value(tensor, index) * scale }) } // Builds a tiny q8 model with all fixture values multiplied by scale. fn tiny_q8_scaled_bytes(scale: f32) -> Vec { build_tiny_bytes( tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), |tensor, index, _tensor_index| fixture_value(tensor, index) * scale, ) } // Packs a tiny fixture model from caller-supplied tensor values. fn build_tiny_bytes(tensors: Vec, mut value: F) -> Vec where F: FnMut(&crate::tensor_writer::TensorSpec, usize, usize) -> f32, { let values = tensors .iter() .enumerate() .map(|(tensor_index, tensor)| { (0..tensor.element_count()) .map(|index| value(tensor, index, tensor_index)) .collect::>() }) .collect::>(); build_model_file_from_values_with_flags( &crate::tensor_writer::ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } // Creates an isolated temp directory for path-level operator tests. fn unique_dir(label: &str) -> PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-federated-{label}-{nanos}")) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/federated.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/ledger.rs BYTES: 17539 SHA256: 0AC47CFF5021A553545B9D0E9393FC13793BB0268D8E23B9D442FD35BD410CA2 ================================================================================ //! Promotion ledgers for admitted model-breeding candidates. use std::collections::{HashMap, HashSet}; use std::fs; use std::io; use std::path::Path; use crate::admission; use crate::provenance; const LEDGER_VERSION: &str = "1"; const LEDGER_SCOPE: &str = "model-breeding-promotion-history"; const LEDGER_STATUS: &str = "admitted-records-only"; const ENTRY_STATUS: &str = "promoted-and-admitted"; const ZERO_CHECKSUM: &str = "0x0000000000000000"; const REQUIRED_NEXT_GATE: &str = "selector-registry-or-offline-population-review"; const ENTRY_KEYS: [&str; 32] = [ "candidate_id", "selector_id", "admission_status", "promotion_status", "operator_id", "operator_lane", "resource_budget", "candidate_artifact_path", "candidate_artifact_bytes", "candidate_slm_checksum", "candidate_model_shape", "candidate_quantization", "candidate_output_contract", "candidate_tokenizer_checksum", "candidate_tensor_layout_checksum", "candidate_manifest_checksum", "promotion_manifest_checksum", "provenance_manifest_checksum", "runtime_smoke_manifest_checksum", "eval_manifest_checksum", "eval_case_evidence_checksum", "runtime_smoke_status", "eval_status", "quality_gate", "quality_scope", "quality_boundary", "eval_dataset", "case_count", "cases_passed", "promotion_decision", "browser_selector_status", "public_claim_status", ]; /// Writes a promotion ledger from one or more selector admission records. pub(crate) fn write_ledger_path(output: &Path, admission_paths: &[String]) -> io::Result<()> { let admission_texts = read_admissions(admission_paths, "promotion-ledger")?; let ledger = build_ledger_text(&admission_texts)?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, ledger)?; println!("SLM promotion ledger written: {}", output.display()); Ok(()) } /// Validates a promotion ledger against its selector admission records. pub(crate) fn validate_ledger_path(ledger: &Path, admission_paths: &[String]) -> io::Result<()> { let admission_texts = read_admissions(admission_paths, "validate-promotion-ledger")?; let ledger_text = fs::read_to_string(ledger)?; validate_ledger_text(&ledger_text, &admission_texts)?; println!("SLM promotion ledger validation: PASS"); println!("ledger: {}", ledger.display()); println!("admissions: {}", admission_paths.len()); Ok(()) } fn read_admissions(admission_paths: &[String], command: &str) -> io::Result> { if admission_paths.is_empty() { return Err(invalid(&format!( "{command} requires at least one admission record" ))); } admission_paths .iter() .map(|path| fs::read_to_string(Path::new(path))) .collect() } pub(crate) fn build_ledger_text(admission_texts: &[String]) -> io::Result { if admission_texts.is_empty() { return Err(invalid( "promotion ledger requires at least one admission record", )); } let mut candidate_ids = HashSet::new(); let mut slm_checksums = HashSet::new(); let mut admission_checksums = Vec::with_capacity(admission_texts.len()); let mut entries = String::new(); let mut previous_checksum = ZERO_CHECKSUM.to_string(); for (index, admission_text) in admission_texts.iter().enumerate() { let fields = admission::validate_record_summary_text(admission_text)?; let candidate_id = require_key(&fields, "candidate_id")?.to_string(); if !candidate_ids.insert(candidate_id.clone()) { return Err(invalid(&format!( "duplicate promotion ledger candidate_id {candidate_id}" ))); } let slm_checksum = require_key(&fields, "candidate_slm_checksum")?.to_string(); if !slm_checksums.insert(slm_checksum.clone()) { return Err(invalid(&format!( "duplicate promotion ledger candidate checksum {slm_checksum}" ))); } let admission_checksum = hex64(provenance::text_checksum(admission_text.as_bytes())); admission_checksums.push(admission_checksum.clone()); let mut payload = String::new(); push_entry_lines( &mut payload, "", index, &fields, &admission_checksum, &previous_checksum, None, )?; let entry_checksum = hex64(provenance::text_checksum(payload.as_bytes())); let prefix = format!("entry.{index}"); push_entry_lines( &mut entries, &prefix, index, &fields, &admission_checksum, &previous_checksum, Some(&entry_checksum), )?; previous_checksum = entry_checksum; } let mut text = String::new(); push_line( &mut text, "tinyrustlm_promotion_ledger_version", LEDGER_VERSION, ); push_line(&mut text, "ledger_scope", LEDGER_SCOPE); push_line(&mut text, "ledger_status", LEDGER_STATUS); push_line(&mut text, "entry_count", &admission_texts.len().to_string()); push_line( &mut text, "admission_set_checksum", &admission_set_checksum(&admission_checksums), ); push_line(&mut text, "ledger_chain_checksum", &previous_checksum); text.push_str(&entries); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } pub(crate) fn validate_ledger_text( ledger_text: &str, admission_texts: &[String], ) -> io::Result<()> { let expected_text = build_ledger_text(admission_texts)?; let expected = parse_manifest(&expected_text, "expected promotion ledger")?; let actual = parse_manifest(ledger_text, "promotion ledger")?; require_equal( &actual, "tinyrustlm_promotion_ledger_version", LEDGER_VERSION, )?; require_equal(&actual, "ledger_scope", LEDGER_SCOPE)?; require_equal(&actual, "ledger_status", LEDGER_STATUS)?; require_equal(&actual, "required_next_gate", REQUIRED_NEXT_GATE)?; for (key, expected_value) in &expected { require_equal(&actual, key, expected_value)?; } for key in actual.keys() { if !expected.contains_key(key) { return Err(invalid(&format!("unexpected promotion ledger key {key}"))); } } Ok(()) } fn push_entry_lines( text: &mut String, prefix: &str, sequence: usize, fields: &HashMap, admission_checksum: &str, previous_checksum: &str, entry_checksum: Option<&str>, ) -> io::Result<()> { push_prefixed_line(text, prefix, "sequence", &sequence.to_string()); for key in ENTRY_KEYS { push_prefixed_line(text, prefix, key, require_key(fields, key)?); } push_prefixed_line(text, prefix, "admission_checksum", admission_checksum); push_prefixed_line(text, prefix, "previous_entry_checksum", previous_checksum); push_prefixed_line(text, prefix, "ledger_entry_status", ENTRY_STATUS); if let Some(entry_checksum) = entry_checksum { push_prefixed_line(text, prefix, "entry_checksum", entry_checksum); } Ok(()) } fn push_prefixed_line(text: &mut String, prefix: &str, key: &str, value: &str) { if prefix.is_empty() { push_line(text, key, value); } else { push_line(text, &format!("{prefix}.{key}"), value); } } fn admission_set_checksum(admission_checksums: &[String]) -> String { let mut source = String::new(); for admission_checksum in admission_checksums { push_line(&mut source, "admission_checksum", admission_checksum); } hex64(provenance::text_checksum(source.as_bytes())) } fn parse_manifest(text: &str, label: &str) -> io::Result> { let mut fields = HashMap::new(); for (line_index, raw_line) in text.lines().enumerate() { let line = raw_line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let Some((key, value)) = line.split_once('=') else { return Err(invalid(&format!( "{label} line {} is missing '='", line_index + 1 ))); }; let key = key.trim(); let value = value.trim(); validate_key(key, label, line_index + 1)?; if value.is_empty() || value.contains('\r') || value.contains('\n') { return Err(invalid(&format!("{label} key {key} has an invalid value"))); } if fields.insert(key.to_string(), value.to_string()).is_some() { return Err(invalid(&format!("duplicate {label} key {key}"))); } } Ok(fields) } fn validate_key(key: &str, label: &str, line_number: usize) -> io::Result<()> { if key.is_empty() || !key .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_')) { return Err(invalid(&format!( "{label} line {line_number} has an invalid key" ))); } Ok(()) } fn require_key<'a>(fields: &'a HashMap, key: &str) -> io::Result<&'a str> { fields .get(key) .map(String::as_str) .ok_or_else(|| invalid(&format!("manifest missing required key {key}"))) } fn require_equal(fields: &HashMap, key: &str, expected: &str) -> io::Result<()> { let actual = require_key(fields, key)?; if actual != expected { return Err(invalid(&format!( "promotion ledger key {key} was {actual}, expected {expected}" ))); } Ok(()) } fn push_line(text: &mut String, key: &str, value: &str) { text.push_str(key); text.push('='); text.push_str(value); text.push('\n'); } fn hex64(value: u64) -> String { format!("0x{value:016x}") } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } #[cfg(test)] mod tests { use super::*; use crate::build_model_file; use crate::candidate; use crate::compatibility; use crate::lineage; use crate::promotion; use crate::slm_validate; use crate::tensor_writer::{ tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_F32, DTYPE_Q8_0, }; use crate::tokenizer_writer::ByteTokenizerSection; #[test] fn writes_and_validates_promotion_ledger_from_admissions() { let first = fixture_admission( "tiny-q8-candidate", "target/promotion-ledger/tiny-q8.slm", DTYPE_Q8_0, ); let second = fixture_admission( "tiny-f32-candidate", "target/promotion-ledger/tiny-f32.slm", DTYPE_F32, ); let ledger = build_ledger_text(&[first.clone(), second.clone()]).unwrap(); validate_ledger_text(&ledger, &[first, second]).unwrap(); assert!(ledger.contains("ledger_status=admitted-records-only")); assert!(ledger.contains("entry_count=2")); assert!(ledger.contains("entry.0.ledger_entry_status=promoted-and-admitted")); assert!(ledger.contains("entry.1.previous_entry_checksum=0x")); } #[test] fn rejects_empty_ledger_input() { let error = build_ledger_text(&[]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("at least one admission")); } #[test] fn rejects_duplicate_candidate_id() { let left = fixture_admission("candidate-a", "target/ledger/a.slm", DTYPE_Q8_0); let right = fixture_admission("candidate-a", "target/ledger/b.slm", DTYPE_F32); let error = build_ledger_text(&[left, right]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error .to_string() .contains("duplicate promotion ledger candidate_id")); } #[test] fn rejects_duplicate_candidate_checksum() { let left = fixture_admission("candidate-a", "target/ledger/a.slm", DTYPE_Q8_0); let right = fixture_admission("candidate-b", "target/ledger/b.slm", DTYPE_Q8_0); let error = build_ledger_text(&[left, right]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error .to_string() .contains("duplicate promotion ledger candidate checksum")); } #[test] fn rejects_ledger_entry_drift() { let admission = fixture_admission("candidate-a", "target/ledger/a.slm", DTYPE_Q8_0); let ledger = build_ledger_text(&[admission.clone()]).unwrap().replace( "entry.0.ledger_entry_status=promoted-and-admitted", "entry.0.ledger_entry_status=pending", ); let error = validate_ledger_text(&ledger, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("ledger_entry_status")); } #[test] fn rejects_unexpected_ledger_key() { let admission = fixture_admission("candidate-a", "target/ledger/a.slm", DTYPE_Q8_0); let mut ledger = build_ledger_text(&[admission.clone()]).unwrap(); ledger.push_str("entry.0.extra=yes\n"); let error = validate_ledger_text(&ledger, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error .to_string() .contains("unexpected promotion ledger key")); } fn fixture_admission(candidate_id: &str, candidate_path: &str, dtype: u32) -> String { let candidate = tiny_fixture_bytes(dtype); let compatibility = compatibility::compatibility_text_for_bytes( &candidate, "left.slm", &candidate, "right.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, candidate_id, "operator-a", "fit") .unwrap(); let candidate_manifest = candidate::build_manifest_text(&compatibility, &lineage, &candidate, candidate_path) .unwrap(); let promotion = promotion::build_template_text( &compatibility, &lineage, &candidate, candidate_path, &candidate_manifest, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, ) .unwrap(); let report = slm_validate::validate_bytes(&candidate, candidate_path).unwrap(); let provenance_manifest = provenance::build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = provenance::parse_manifest(&provenance_manifest).unwrap(); let runtime_smoke = provenance::build_runtime_smoke_text(&report, &provenance_manifest, &manifest_fields) .unwrap(); let eval = passing_eval_text(&report, &provenance_manifest); admission::build_record_text( &compatibility, &lineage, &candidate, candidate_path, &candidate_manifest, &promotion, &provenance_manifest, &runtime_smoke, &eval, admission::DEFAULT_ADMISSION_SELECTOR_ID, ) .unwrap() } fn passing_eval_text(report: &slm_validate::ValidationReport, manifest: &str) -> String { let mut text = String::new(); push_line(&mut text, "tinyrustlm_eval_manifest_version", "1"); push_line(&mut text, "gate", "assistant-quality"); push_line(&mut text, "source_kind", "converted-trained"); push_line( &mut text, "manifest_checksum", &hex64(provenance::text_checksum(manifest.as_bytes())), ); push_line(&mut text, "slm_checksum", &hex64(report.checksum())); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "task_eval_status", "pass"); push_line(&mut text, "safety_review_status", "pass"); push_line( &mut text, "quality_decision", "accepted-for-assistant-quality", ); push_line(&mut text, "quality_scope", "tiny-fixture-runtime-eval-only"); push_line(&mut text, "evaluator", "local-reviewed-eval"); push_line( &mut text, "eval_dataset", "tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", ); push_line( &mut text, "eval_summary", "Reviewed task and safety evidence passed for declared scope", ); push_line( &mut text, "quality_boundary", "fixture-runtime-and-eval-plumbing-not-product-assistant-quality", ); push_line(&mut text, "case_count", "1"); push_line(&mut text, "cases_passed", "1"); push_line(&mut text, "cases_failed", "0"); push_line(&mut text, "case.0.status", "pass"); push_line(&mut text, "case.0.expected", "e"); push_line(&mut text, "case.0.actual", "e"); push_line(&mut text, "case.0.error", "ok"); text } fn tiny_fixture_bytes(dtype: u32) -> Vec { build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(dtype), &ByteTokenizerSection::phase_one(), ) .unwrap() } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/ledger.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/lineage.rs BYTES: 14361 SHA256: 69B7B590E2C5965D21F9A0BDBC8EE36CF13953A4B8059E6DD00F692DBEC8EFEE ================================================================================ //! Candidate lineage manifests for future offline assembly operators. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; const LINEAGE_VERSION: &str = "1"; const COMPATIBILITY_VERSION: &str = "1"; const CANDIDATE_STATUS_PLANNED: &str = "planned"; const CANDIDATE_ARTIFACT_STATUS: &str = "not-written"; const REQUIRED_NEXT_GATE: &str = "operator-output-slm-validation-plus-manifest-plus-runtime-smoke-plus-eval"; const PARENT_KEYS: [&str; 9] = [ "path", "slm_checksum", "model_shape", "tensor_count", "parameter_count", "quantization", "output_contract", "tokenizer_checksum", "tensor_layout_checksum", ]; /// Writes a candidate lineage template from a passing parent compatibility report. pub(crate) fn write_template_path( compatibility: &Path, output: &Path, candidate_id: &str, operator_id: &str, resource_budget: &str, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let text = build_template_text( &compatibility_text, candidate_id, operator_id, resource_budget, )?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, text)?; println!( "SLM candidate lineage template written: {}", output.display() ); Ok(()) } /// Validates a candidate lineage manifest against its parent compatibility report. pub(crate) fn validate_path(compatibility: &Path, lineage: &Path) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage)?; validate_text(&compatibility_text, &lineage_text)?; println!("SLM candidate lineage validation: PASS"); println!("compatibility: {}", compatibility.display()); println!("lineage: {}", lineage.display()); Ok(()) } /// Builds a candidate lineage template from a passing compatibility report. pub(crate) fn build_template_text( compatibility_text: &str, candidate_id: &str, operator_id: &str, resource_budget: &str, ) -> io::Result { let compatibility = parse_passing_compatibility(compatibility_text)?; validate_slug(candidate_id, "candidate_id")?; validate_slug(operator_id, "operator_id")?; validate_value(resource_budget, "resource_budget")?; let mut text = String::new(); push_line( &mut text, "tinyrustlm_candidate_lineage_version", LINEAGE_VERSION, ); push_line(&mut text, "candidate_id", candidate_id); push_line(&mut text, "candidate_status", CANDIDATE_STATUS_PLANNED); push_line(&mut text, "operator_id", operator_id); push_line( &mut text, "operator_lane", require_key(&compatibility, "operator_lane")?, ); push_line(&mut text, "resource_budget", resource_budget); push_line( &mut text, "compatibility_report_checksum", &hex64(text_checksum(compatibility_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(&compatibility, "compatibility_scope")?, ); push_line(&mut text, "compatibility_result", "pass"); push_line(&mut text, "compatible_parent_set", "true"); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, &compatibility, 0)?; push_parent_lines(&mut text, &compatibility, 1)?; push_line( &mut text, "candidate_artifact_status", CANDIDATE_ARTIFACT_STATUS, ); push_line(&mut text, "candidate_artifact_path", "pending"); push_line(&mut text, "candidate_slm_checksum", "pending"); push_line(&mut text, "candidate_manifest_path", "pending"); push_line(&mut text, "candidate_eval_path", "pending"); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } /// Validates candidate lineage text against its parent compatibility report. pub(crate) fn validate_text(compatibility_text: &str, lineage_text: &str) -> io::Result<()> { let compatibility = parse_passing_compatibility(compatibility_text)?; let lineage = parse_manifest(lineage_text, "lineage")?; require_equal( &lineage, "tinyrustlm_candidate_lineage_version", LINEAGE_VERSION, )?; validate_slug(require_key(&lineage, "candidate_id")?, "candidate_id")?; require_equal(&lineage, "candidate_status", CANDIDATE_STATUS_PLANNED)?; validate_slug(require_key(&lineage, "operator_id")?, "operator_id")?; require_equal( &lineage, "operator_lane", require_key(&compatibility, "operator_lane")?, )?; validate_value(require_key(&lineage, "resource_budget")?, "resource_budget")?; require_equal( &lineage, "compatibility_report_checksum", &hex64(text_checksum(compatibility_text.as_bytes())), )?; require_equal( &lineage, "compatibility_scope", require_key(&compatibility, "compatibility_scope")?, )?; require_equal(&lineage, "compatibility_result", "pass")?; require_equal(&lineage, "compatible_parent_set", "true")?; require_equal(&lineage, "parent_count", "2")?; require_parent_lines(&compatibility, &lineage, 0)?; require_parent_lines(&compatibility, &lineage, 1)?; require_equal( &lineage, "candidate_artifact_status", CANDIDATE_ARTIFACT_STATUS, )?; require_equal(&lineage, "candidate_artifact_path", "pending")?; require_equal(&lineage, "candidate_slm_checksum", "pending")?; require_equal(&lineage, "candidate_manifest_path", "pending")?; require_equal(&lineage, "candidate_eval_path", "pending")?; require_equal(&lineage, "required_next_gate", REQUIRED_NEXT_GATE)?; Ok(()) } fn parse_passing_compatibility(text: &str) -> io::Result> { let fields = parse_manifest(text, "compatibility")?; require_equal( &fields, "tinyrustlm_parent_compatibility_version", COMPATIBILITY_VERSION, )?; require_equal(&fields, "compatibility_result", "pass")?; require_equal(&fields, "compatible_parent_set", "true")?; require_equal(&fields, "compatibility_reasons", "all-compatible")?; require_equal(&fields, "parent_count", "2")?; require_equal( &fields, "decision", "accepted-parent-set-for-offline-operators", )?; require_key(&fields, "compatibility_scope")?; require_key(&fields, "operator_lane")?; for index in 0..2 { for key in PARENT_KEYS { let full_key = format!("parent.{index}.{key}"); require_key(&fields, &full_key)?; } } Ok(fields) } fn push_parent_lines( text: &mut String, compatibility: &HashMap, index: usize, ) -> io::Result<()> { for key in PARENT_KEYS { let compatibility_key = format!("parent.{index}.{key}"); let lineage_key = format!("parent.{index}.{key}"); push_line( text, &lineage_key, require_key(compatibility, &compatibility_key)?, ); } Ok(()) } fn require_parent_lines( compatibility: &HashMap, lineage: &HashMap, index: usize, ) -> io::Result<()> { for key in PARENT_KEYS { let full_key = format!("parent.{index}.{key}"); require_equal(lineage, &full_key, require_key(compatibility, &full_key)?)?; } Ok(()) } fn parse_manifest(text: &str, label: &str) -> io::Result> { let mut fields = HashMap::new(); for (line_index, raw_line) in text.lines().enumerate() { let line = raw_line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let Some((key, value)) = line.split_once('=') else { return Err(invalid(&format!( "{label} line {} is missing '='", line_index + 1 ))); }; let key = key.trim(); let value = value.trim(); validate_key(key, label, line_index + 1)?; validate_value(value, key)?; if fields.insert(key.to_string(), value.to_string()).is_some() { return Err(invalid(&format!("duplicate {label} key {key}"))); } } Ok(fields) } fn validate_key(key: &str, label: &str, line_number: usize) -> io::Result<()> { if key.is_empty() || !key .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_')) { return Err(invalid(&format!( "{label} line {line_number} has an invalid key" ))); } Ok(()) } fn validate_value(value: &str, key: &str) -> io::Result<()> { if value.is_empty() || value.contains('\n') || value.contains('\r') { return Err(invalid(&format!("{key} has an invalid value"))); } Ok(()) } fn validate_slug(value: &str, key: &str) -> io::Result<()> { validate_value(value, key)?; if value.len() > 96 || !value .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) { return Err(invalid(&format!("{key} must be an ASCII slug"))); } Ok(()) } fn require_key<'a>(fields: &'a HashMap, key: &str) -> io::Result<&'a str> { fields .get(key) .map(String::as_str) .ok_or_else(|| invalid(&format!("manifest missing required key {key}"))) } fn require_equal(fields: &HashMap, key: &str, expected: &str) -> io::Result<()> { let actual = require_key(fields, key)?; if actual != expected { return Err(invalid(&format!( "manifest key {key} was {actual}, expected {expected}" ))); } Ok(()) } fn push_line(text: &mut String, key: &str, value: &str) { text.push_str(key); text.push('='); text.push_str(value); text.push('\n'); } /// Returns the stable checksum used to bind line-based model-breeding manifests. pub(crate) fn text_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x6c696e6561676531u64; for (index, byte) in bytes.iter().enumerate() { acc ^= u64::from(*byte).wrapping_add((index as u64) << 2); acc = acc.rotate_left(9).wrapping_mul(0x100000001b3); } acc } fn hex64(value: u64) -> String { format!("0x{value:016x}") } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } #[cfg(test)] mod tests { use super::*; use crate::build_model_file; use crate::compatibility; use crate::tensor_writer::{ tiny_fixture_tensors, tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_Q8_0, }; use crate::tokenizer_writer::ByteTokenizerSection; #[test] fn writes_and_validates_lineage_template_for_compatible_parents() { let compatibility = passing_compatibility_text(); let lineage = build_template_text( &compatibility, "tiny-q8-candidate", "identity-parent-set", "browser-local-16m-budget", ) .unwrap(); validate_text(&compatibility, &lineage).unwrap(); assert!(lineage.contains("candidate_status=planned")); assert!(lineage.contains("candidate_artifact_status=not-written")); assert!(lineage.contains("parent.0.tensor_layout_checksum=")); assert!(lineage.contains("required_next_gate=operator-output-slm-validation-plus-manifest-plus-runtime-smoke-plus-eval")); } #[test] fn rejects_failed_compatibility_report() { let left = tiny_fixture_q8_bytes(); let right = build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors(), &ByteTokenizerSection::phase_one(), ) .unwrap(); let compatibility = compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm") .unwrap(); let error = build_template_text( &compatibility, "tiny-q8-candidate", "identity-parent-set", "fit", ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } #[test] fn validation_rejects_compatibility_checksum_drift() { let compatibility = passing_compatibility_text(); let lineage = build_template_text( &compatibility, "tiny-q8-candidate", "identity-parent-set", "fit", ) .unwrap(); let changed = compatibility.replace("left.slm", "other-left.slm"); let error = validate_text(&changed, &lineage).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("compatibility_report_checksum")); } #[test] fn validation_rejects_parent_drift() { let compatibility = passing_compatibility_text(); let lineage = build_template_text( &compatibility, "tiny-q8-candidate", "identity-parent-set", "fit", ) .unwrap() .replace("parent.1.quantization=q8_0", "parent.1.quantization=f32"); let error = validate_text(&compatibility, &lineage).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("parent.1.quantization")); } #[test] fn rejects_non_slug_candidate_id() { let compatibility = passing_compatibility_text(); let error = build_template_text( &compatibility, "bad candidate", "identity-parent-set", "fit", ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate_id")); } fn passing_compatibility_text() -> String { let left = tiny_fixture_q8_bytes(); let right = tiny_fixture_q8_bytes(); compatibility::compatibility_text_for_bytes(&left, "left.slm", &right, "right.slm").unwrap() } fn tiny_fixture_q8_bytes() -> Vec { build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), &ByteTokenizerSection::phase_one(), ) .unwrap() } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/lineage.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/main.rs BYTES: 143968 SHA256: FCF15CE35EFEC3F274FA79AF4E7A3C79970C604C4F3E8BCA38A8AF4BBB6E54AB ================================================================================ //! TinyRustLM `.slm` packing utility. mod adapter; mod adapter_family; mod admission; mod blend; mod browser_bundle; mod candidate; mod compatibility; mod crossover; mod dare; mod delta; mod federated; mod ledger; mod lineage; mod multi_admission; mod multi_candidate; mod multi_promotion; mod mutation; mod parent_pool; mod population; mod promotion; mod provenance; mod prune; mod quant_writer; mod selector; mod sign_merge; mod slm_validate; mod soup; mod sparse_delta; mod tensor_writer; mod tokenizer_writer; mod trained_adapter_source; mod trained_source; mod writer; use std::env; use std::fs::File; use std::io::{self, Write}; use std::path::Path; use quant_writer::{pack_q4_pair, quantize_q4_block, quantize_q8_row}; use tensor_writer::{ tiny_fixture_tensors, tiny_fixture_tensors_with_dtype, tiny_fixture_tied_tensors, tinylm16_f32_tensors, tinylm16_q4_tensors, tinylm16_q8_tensors, ModelShape, TensorSpec, DTYPE_F32, DTYPE_Q4_0, DTYPE_Q8_0, }; use tokenizer_writer::{ByteTokenizerSection, TokenizerSection}; use writer::{align_to_64, write_f32, write_u32, write_u64}; const HEADER_LEN: usize = 108; const TENSOR_ENTRY_LEN: usize = 64; const FLAG_TIED_OUTPUT: u32 = 1; fn main() { if let Err(error) = run() { eprintln!("tinyrustlm-slm-pack: {error}"); std::process::exit(1); } } fn run() -> io::Result<()> { let mut args = env::args().skip(1); let Some(output) = args.next() else { print_usage(); return Ok(()); }; if output == "validate" { let Some(input) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate requires an input .slm path", )); }; return slm_validate::validate_path(Path::new(&input)); } if output == "browser-multi-parent-bundle" { let Some(root) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "browser-multi-parent-bundle requires an output tinyrustlm root", )); }; let quantization = args.next().unwrap_or_else(|| "f32".to_string()); let operator = args.next().unwrap_or_else(|| "sign-merge".to_string()); return browser_bundle::write_bundle_path_with_quantization_and_operator( Path::new(&root), &quantization, &operator, ); } if output == "browser-converted-trained-bundle" { let Some(root) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "browser-converted-trained-bundle requires an output tinyrustlm root", )); }; let Some(source_dir) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "browser-converted-trained-bundle requires an input source directory", )); }; let quantization = args.next().unwrap_or_else(|| "q8_0".to_string()); return browser_bundle::write_converted_trained_bundle_path( Path::new(&root), Path::new(&source_dir), &quantization, ); } if output == "runtime-wasm-manifest" { let Some(wasm_path) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "runtime-wasm-manifest requires an input WASM path", )); }; let Some(manifest_path) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "runtime-wasm-manifest requires an output manifest path", )); }; return browser_bundle::write_runtime_wasm_manifest_path( Path::new(&wasm_path), Path::new(&manifest_path), ); } if output == "compatibility" { let Some(left) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "compatibility requires a left parent .slm path", )); }; let Some(right) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "compatibility requires a right parent .slm path", )); }; let output_report = args.next(); return compatibility::report_path( Path::new(&left), Path::new(&right), output_report.as_deref().map(Path::new), ); } if output == "lineage-template" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "lineage-template requires an input compatibility report path", )); }; let Some(output_lineage) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "lineage-template requires an output lineage path", )); }; let Some(candidate_id) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "lineage-template requires a candidate id", )); }; let Some(operator_id) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "lineage-template requires an operator id", )); }; let resource_budget = args .next() .unwrap_or_else(|| "browser-local-constrained".to_string()); return lineage::write_template_path( Path::new(&compatibility_report), Path::new(&output_lineage), &candidate_id, &operator_id, &resource_budget, ); } if output == "validate-lineage" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-lineage requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-lineage requires an input lineage path", )); }; return lineage::validate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), ); } if output == "blend-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "blend-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "blend-candidate requires an input lineage path", )); }; let Some(left_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "blend-candidate requires a left parent .slm path", )); }; let Some(right_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "blend-candidate requires a right parent .slm path", )); }; let Some(output_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "blend-candidate requires an output candidate .slm path", )); }; let Some(output_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "blend-candidate requires an output operator receipt path", )); }; let parent0_weight_ppm = args.next().unwrap_or_else(|| "500000".to_string()); return blend::write_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&left_parent), Path::new(&right_parent), Path::new(&output_slm), Path::new(&output_receipt), &parent0_weight_ppm, ); } if output == "validate-blend-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-blend-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-blend-candidate requires an input lineage path", )); }; let Some(left_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-blend-candidate requires a left parent .slm path", )); }; let Some(right_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-blend-candidate requires a right parent .slm path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-blend-candidate requires a candidate .slm path", )); }; let Some(receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-blend-candidate requires an input operator receipt path", )); }; return blend::validate_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&left_parent), Path::new(&right_parent), Path::new(&candidate_slm), Path::new(&receipt), ); } if output == "crossover-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "crossover-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "crossover-candidate requires an input lineage path", )); }; let Some(left_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "crossover-candidate requires a left parent .slm path", )); }; let Some(right_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "crossover-candidate requires a right parent .slm path", )); }; let Some(output_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "crossover-candidate requires an output candidate .slm path", )); }; let Some(output_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "crossover-candidate requires an output operator receipt path", )); }; let crossover_seed = args.next(); let parent0_keep_ppm = args.next(); return crossover::write_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&left_parent), Path::new(&right_parent), Path::new(&output_slm), Path::new(&output_receipt), crossover_seed.as_deref(), parent0_keep_ppm.as_deref(), ); } if output == "validate-crossover-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-crossover-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-crossover-candidate requires an input lineage path", )); }; let Some(left_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-crossover-candidate requires a left parent .slm path", )); }; let Some(right_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-crossover-candidate requires a right parent .slm path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-crossover-candidate requires a candidate .slm path", )); }; let Some(receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-crossover-candidate requires an input operator receipt path", )); }; return crossover::validate_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&left_parent), Path::new(&right_parent), Path::new(&candidate_slm), Path::new(&receipt), ); } if output == "mutation-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "mutation-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "mutation-candidate requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "mutation-candidate requires a base parent .slm path", )); }; let Some(reference_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "mutation-candidate requires a reference parent .slm path", )); }; let Some(output_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "mutation-candidate requires an output candidate .slm path", )); }; let Some(output_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "mutation-candidate requires an output operator receipt path", )); }; let mutation_seed = args.next(); let mutation_rate_ppm = args.next(); let mutation_magnitude_ppm = args.next(); return mutation::write_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&reference_parent), Path::new(&output_slm), Path::new(&output_receipt), mutation_seed.as_deref(), mutation_rate_ppm.as_deref(), mutation_magnitude_ppm.as_deref(), ); } if output == "validate-mutation-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-mutation-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-mutation-candidate requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-mutation-candidate requires a base parent .slm path", )); }; let Some(reference_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-mutation-candidate requires a reference parent .slm path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-mutation-candidate requires a candidate .slm path", )); }; let Some(receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-mutation-candidate requires an input operator receipt path", )); }; return mutation::validate_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&reference_parent), Path::new(&candidate_slm), Path::new(&receipt), ); } if output == "prune-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "prune-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "prune-candidate requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "prune-candidate requires a base parent .slm path", )); }; let Some(reference_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "prune-candidate requires a reference parent .slm path", )); }; let Some(output_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "prune-candidate requires an output candidate .slm path", )); }; let Some(output_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "prune-candidate requires an output operator receipt path", )); }; let keep_ppm = args.next(); let floor_ppm = args.next(); return prune::write_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&reference_parent), Path::new(&output_slm), Path::new(&output_receipt), keep_ppm.as_deref(), floor_ppm.as_deref(), ); } if output == "validate-prune-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-prune-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-prune-candidate requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-prune-candidate requires a base parent .slm path", )); }; let Some(reference_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-prune-candidate requires a reference parent .slm path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-prune-candidate requires a candidate .slm path", )); }; let Some(receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-prune-candidate requires an input operator receipt path", )); }; return prune::validate_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&reference_parent), Path::new(&candidate_slm), Path::new(&receipt), ); } if output == "federated-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "federated-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "federated-candidate requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "federated-candidate requires a base parent .slm path", )); }; let Some(local_update_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "federated-candidate requires a local-update parent .slm path", )); }; let Some(output_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "federated-candidate requires an output candidate .slm path", )); }; let Some(output_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "federated-candidate requires an output operator receipt path", )); }; let local_update_weight_ppm = args.next(); return federated::write_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&local_update_parent), Path::new(&output_slm), Path::new(&output_receipt), local_update_weight_ppm.as_deref(), ); } if output == "validate-federated-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-federated-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-federated-candidate requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-federated-candidate requires a base parent .slm path", )); }; let Some(local_update_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-federated-candidate requires a local-update parent .slm path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-federated-candidate requires a candidate .slm path", )); }; let Some(receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-federated-candidate requires an input operator receipt path", )); }; return federated::validate_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&local_update_parent), Path::new(&candidate_slm), Path::new(&receipt), ); } if output == "delta-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "delta-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "delta-candidate requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "delta-candidate requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "delta-candidate requires a target parent .slm path", )); }; let Some(output_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "delta-candidate requires an output candidate .slm path", )); }; let Some(output_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "delta-candidate requires an output operator receipt path", )); }; let delta_weight_ppm = args.next().unwrap_or_else(|| "1000000".to_string()); return delta::write_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&output_slm), Path::new(&output_receipt), &delta_weight_ppm, ); } if output == "validate-delta-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-delta-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-delta-candidate requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-delta-candidate requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-delta-candidate requires a target parent .slm path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-delta-candidate requires a candidate .slm path", )); }; let Some(receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-delta-candidate requires an input operator receipt path", )); }; return delta::validate_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&candidate_slm), Path::new(&receipt), ); } if output == "sparse-delta-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sparse-delta-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sparse-delta-candidate requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sparse-delta-candidate requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sparse-delta-candidate requires a target parent .slm path", )); }; let Some(output_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sparse-delta-candidate requires an output candidate .slm path", )); }; let Some(output_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sparse-delta-candidate requires an output operator receipt path", )); }; let delta_weight_ppm = args.next(); let keep_ppm = args.next(); return sparse_delta::write_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&output_slm), Path::new(&output_receipt), delta_weight_ppm.as_deref(), keep_ppm.as_deref(), ); } if output == "validate-sparse-delta-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sparse-delta-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sparse-delta-candidate requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sparse-delta-candidate requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sparse-delta-candidate requires a target parent .slm path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sparse-delta-candidate requires a candidate .slm path", )); }; let Some(receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sparse-delta-candidate requires an input operator receipt path", )); }; return sparse_delta::validate_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&candidate_slm), Path::new(&receipt), ); } if output == "dare-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "dare-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "dare-candidate requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "dare-candidate requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "dare-candidate requires a target parent .slm path", )); }; let Some(output_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "dare-candidate requires an output candidate .slm path", )); }; let Some(output_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "dare-candidate requires an output operator receipt path", )); }; let delta_weight_ppm = args.next(); let keep_ppm = args.next(); let dropout_seed = args.next(); return dare::write_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&output_slm), Path::new(&output_receipt), delta_weight_ppm.as_deref(), keep_ppm.as_deref(), dropout_seed.as_deref(), ); } if output == "validate-dare-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-dare-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-dare-candidate requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-dare-candidate requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-dare-candidate requires a target parent .slm path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-dare-candidate requires a candidate .slm path", )); }; let Some(receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-dare-candidate requires an input operator receipt path", )); }; return dare::validate_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&candidate_slm), Path::new(&receipt), ); } if output == "adapter-delta" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "adapter-delta requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "adapter-delta requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "adapter-delta requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "adapter-delta requires a target parent .slm path", )); }; let Some(output_adapter) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "adapter-delta requires an output adapter artifact path", )); }; let Some(output_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "adapter-delta requires an output adapter manifest path", )); }; return adapter::write_artifact_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&output_adapter), Path::new(&output_manifest), ); } if output == "validate-adapter-delta" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-adapter-delta requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-adapter-delta requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-adapter-delta requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-adapter-delta requires a target parent .slm path", )); }; let Some(adapter_artifact) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-adapter-delta requires an input adapter artifact path", )); }; let Some(adapter_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-adapter-delta requires an input adapter manifest path", )); }; return adapter::validate_artifact_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&adapter_artifact), Path::new(&adapter_manifest), ); } if output == "sparse-adapter-delta" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sparse-adapter-delta requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sparse-adapter-delta requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sparse-adapter-delta requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sparse-adapter-delta requires a target parent .slm path", )); }; let Some(output_adapter) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sparse-adapter-delta requires an output adapter artifact path", )); }; let Some(output_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sparse-adapter-delta requires an output adapter manifest path", )); }; let delta_weight_ppm = args.next(); let keep_ppm = args.next(); return adapter::write_sparse_artifact_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&output_adapter), Path::new(&output_manifest), delta_weight_ppm.as_deref(), keep_ppm.as_deref(), ); } if output == "validate-sparse-adapter-delta" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sparse-adapter-delta requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sparse-adapter-delta requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sparse-adapter-delta requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sparse-adapter-delta requires a target parent .slm path", )); }; let Some(adapter_artifact) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sparse-adapter-delta requires an input adapter artifact path", )); }; let Some(adapter_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sparse-adapter-delta requires an input adapter manifest path", )); }; return adapter::validate_sparse_artifact_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&adapter_artifact), Path::new(&adapter_manifest), ); } if output == "low-rank-adapter-delta" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "low-rank-adapter-delta requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "low-rank-adapter-delta requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "low-rank-adapter-delta requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "low-rank-adapter-delta requires a target parent .slm path", )); }; let Some(output_adapter) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "low-rank-adapter-delta requires an output adapter artifact path", )); }; let Some(output_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "low-rank-adapter-delta requires an output adapter manifest path", )); }; let rank_limit = args.next(); return adapter::write_low_rank_artifact_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&output_adapter), Path::new(&output_manifest), rank_limit.as_deref(), ); } if output == "validate-low-rank-adapter-delta" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-low-rank-adapter-delta requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-low-rank-adapter-delta requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-low-rank-adapter-delta requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-low-rank-adapter-delta requires a target parent .slm path", )); }; let Some(adapter_artifact) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-low-rank-adapter-delta requires an input adapter artifact path", )); }; let Some(adapter_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-low-rank-adapter-delta requires an input adapter manifest path", )); }; return adapter::validate_low_rank_artifact_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&adapter_artifact), Path::new(&adapter_manifest), ); } if output == "fuse-adapter-delta" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "fuse-adapter-delta requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "fuse-adapter-delta requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "fuse-adapter-delta requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "fuse-adapter-delta requires a target parent .slm path", )); }; let Some(adapter_artifact) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "fuse-adapter-delta requires an input adapter artifact path", )); }; let Some(adapter_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "fuse-adapter-delta requires an input adapter manifest path", )); }; let Some(output_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "fuse-adapter-delta requires an output .slm path", )); }; let Some(output_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "fuse-adapter-delta requires an output operator receipt path", )); }; return adapter::fuse_artifact_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&adapter_artifact), Path::new(&adapter_manifest), Path::new(&output_slm), Path::new(&output_receipt), ); } if output == "validate-fuse-adapter-delta" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-fuse-adapter-delta requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-fuse-adapter-delta requires an input lineage path", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-fuse-adapter-delta requires a base parent .slm path", )); }; let Some(target_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-fuse-adapter-delta requires a target parent .slm path", )); }; let Some(adapter_artifact) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-fuse-adapter-delta requires an input adapter artifact path", )); }; let Some(adapter_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-fuse-adapter-delta requires an input adapter manifest path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-fuse-adapter-delta requires a candidate .slm path", )); }; let Some(receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-fuse-adapter-delta requires an input operator receipt path", )); }; return adapter::validate_fused_candidate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&base_parent), Path::new(&target_parent), Path::new(&adapter_artifact), Path::new(&adapter_manifest), Path::new(&candidate_slm), Path::new(&receipt), ); } if output == "candidate-manifest" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "candidate-manifest requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "candidate-manifest requires an input lineage path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "candidate-manifest requires a candidate .slm path", )); }; let Some(output_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "candidate-manifest requires an output candidate manifest path", )); }; let operator_receipt = args.next(); return candidate::write_manifest_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&candidate_slm), Path::new(&output_manifest), operator_receipt.as_deref().map(Path::new), ); } if output == "validate-candidate" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-candidate requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-candidate requires an input lineage path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-candidate requires a candidate .slm path", )); }; let Some(candidate_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-candidate requires an input candidate manifest path", )); }; let operator_receipt = args.next(); return candidate::validate_manifest_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&candidate_slm), Path::new(&candidate_manifest), operator_receipt.as_deref().map(Path::new), ); } if output == "promotion-template" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "promotion-template requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "promotion-template requires an input lineage path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "promotion-template requires a candidate .slm path", )); }; let Some(candidate_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "promotion-template requires an input candidate manifest path", )); }; let Some(output_promotion) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "promotion-template requires an output promotion path", )); }; let promoter_id = args .next() .unwrap_or_else(|| "local-smoke-runner".to_string()); let promotion_scope = args .next() .unwrap_or_else(|| promotion::DEFAULT_PROMOTION_SCOPE.to_string()); let operator_receipt = args.next(); if args.next().is_some() { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "promotion-template received too many arguments", )); } return promotion::write_template_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&candidate_slm), Path::new(&candidate_manifest), Path::new(&output_promotion), &promoter_id, &promotion_scope, operator_receipt.as_deref().map(Path::new), ); } if output == "validate-promotion" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-promotion requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-promotion requires an input lineage path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-promotion requires a candidate .slm path", )); }; let Some(candidate_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-promotion requires an input candidate manifest path", )); }; let Some(promotion_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-promotion requires an input promotion path", )); }; let operator_receipt = args.next(); if args.next().is_some() { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-promotion received too many arguments", )); } return promotion::validate_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&candidate_slm), Path::new(&candidate_manifest), Path::new(&promotion_manifest), operator_receipt.as_deref().map(Path::new), ); } if output == "admission-record" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "admission-record requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "admission-record requires an input lineage path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "admission-record requires a candidate .slm path", )); }; let Some(candidate_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "admission-record requires an input candidate manifest path", )); }; let Some(promotion_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "admission-record requires an input promotion path", )); }; let Some(provenance_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "admission-record requires an input provenance manifest path", )); }; let Some(runtime_smoke) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "admission-record requires an input runtime-smoke sidecar path", )); }; let Some(eval_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "admission-record requires an input evaluation manifest path", )); }; let Some(output_admission) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "admission-record requires an output admission path", )); }; let selector_id = args .next() .unwrap_or_else(|| admission::DEFAULT_ADMISSION_SELECTOR_ID.to_string()); let operator_receipt = args.next(); if args.next().is_some() { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "admission-record received too many arguments", )); } return admission::write_record_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&candidate_slm), Path::new(&candidate_manifest), Path::new(&promotion_manifest), Path::new(&provenance_manifest), Path::new(&runtime_smoke), Path::new(&eval_manifest), Path::new(&output_admission), &selector_id, operator_receipt.as_deref().map(Path::new), ); } if output == "validate-admission" { let Some(compatibility_report) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-admission requires an input compatibility report path", )); }; let Some(lineage_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-admission requires an input lineage path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-admission requires a candidate .slm path", )); }; let Some(candidate_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-admission requires an input candidate manifest path", )); }; let Some(promotion_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-admission requires an input promotion path", )); }; let Some(provenance_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-admission requires an input provenance manifest path", )); }; let Some(runtime_smoke) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-admission requires an input runtime-smoke sidecar path", )); }; let Some(eval_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-admission requires an input evaluation manifest path", )); }; let Some(admission_record) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-admission requires an input admission path", )); }; let operator_receipt = args.next(); if args.next().is_some() { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-admission received too many arguments", )); } return admission::validate_record_path( Path::new(&compatibility_report), Path::new(&lineage_manifest), Path::new(&candidate_slm), Path::new(&candidate_manifest), Path::new(&promotion_manifest), Path::new(&provenance_manifest), Path::new(&runtime_smoke), Path::new(&eval_manifest), Path::new(&admission_record), operator_receipt.as_deref().map(Path::new), ); } if output == "selector-registry" { let Some(output_registry) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "selector-registry requires an output registry path", )); }; let admission_records: Vec = args.collect(); return selector::write_registry_path(Path::new(&output_registry), &admission_records); } if output == "promotion-ledger" { let Some(output_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "promotion-ledger requires an output ledger path", )); }; let admission_records: Vec = args.collect(); return ledger::write_ledger_path(Path::new(&output_ledger), &admission_records); } if output == "validate-promotion-ledger" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-promotion-ledger requires an input ledger path", )); }; let admission_records: Vec = args.collect(); return ledger::validate_ledger_path(Path::new(&input_ledger), &admission_records); } if output == "population-review" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "population-review requires an input ledger path", )); }; let Some(output_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "population-review requires an output review path", )); }; let admission_records: Vec = args.collect(); return population::write_review_path( Path::new(&input_ledger), Path::new(&output_review), &admission_records, ); } if output == "validate-population-review" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-population-review requires an input ledger path", )); }; let Some(input_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-population-review requires an input review path", )); }; let admission_records: Vec = args.collect(); return population::validate_review_path( Path::new(&input_ledger), Path::new(&input_review), &admission_records, ); } if output == "parent-pool-recipe" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "parent-pool-recipe requires an input ledger path", )); }; let Some(input_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "parent-pool-recipe requires an input review path", )); }; let Some(output_recipe) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "parent-pool-recipe requires an output recipe path", )); }; let admission_records: Vec = args.collect(); return parent_pool::write_recipe_path( Path::new(&input_ledger), Path::new(&input_review), Path::new(&output_recipe), &admission_records, ); } if output == "validate-parent-pool-recipe" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-parent-pool-recipe requires an input ledger path", )); }; let Some(input_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-parent-pool-recipe requires an input review path", )); }; let Some(input_recipe) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-parent-pool-recipe requires an input recipe path", )); }; let admission_records: Vec = args.collect(); return parent_pool::validate_recipe_path( Path::new(&input_ledger), Path::new(&input_review), Path::new(&input_recipe), &admission_records, ); } if output == "sign-merge-candidate" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sign-merge-candidate requires an input ledger path", )); }; let Some(input_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sign-merge-candidate requires an input review path", )); }; let Some(input_recipe) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sign-merge-candidate requires an input parent-pool recipe path", )); }; let Some(output_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sign-merge-candidate requires an output candidate .slm path", )); }; let Some(output_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "sign-merge-candidate requires an output operator receipt path", )); }; let (parent_paths, admission_records) = split_parent_admission_args("sign-merge-candidate", args.collect())?; return sign_merge::write_candidate_path( Path::new(&input_ledger), Path::new(&input_review), Path::new(&input_recipe), Path::new(&output_slm), Path::new(&output_receipt), &parent_paths, &admission_records, ); } if output == "validate-sign-merge-candidate" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sign-merge-candidate requires an input ledger path", )); }; let Some(input_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sign-merge-candidate requires an input review path", )); }; let Some(input_recipe) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sign-merge-candidate requires an input parent-pool recipe path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sign-merge-candidate requires a candidate .slm path", )); }; let Some(input_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-sign-merge-candidate requires an input operator receipt path", )); }; let (parent_paths, admission_records) = split_parent_admission_args("validate-sign-merge-candidate", args.collect())?; return sign_merge::validate_candidate_path( Path::new(&input_ledger), Path::new(&input_review), Path::new(&input_recipe), Path::new(&candidate_slm), Path::new(&input_receipt), &parent_paths, &admission_records, ); } if output == "soup-candidate" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "soup-candidate requires an input ledger path", )); }; let Some(input_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "soup-candidate requires an input review path", )); }; let Some(input_recipe) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "soup-candidate requires an input parent-pool recipe path", )); }; let Some(output_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "soup-candidate requires an output candidate .slm path", )); }; let Some(output_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "soup-candidate requires an output operator receipt path", )); }; let (parent_paths, admission_records) = split_parent_admission_args("soup-candidate", args.collect())?; return soup::write_candidate_path( Path::new(&input_ledger), Path::new(&input_review), Path::new(&input_recipe), Path::new(&output_slm), Path::new(&output_receipt), &parent_paths, &admission_records, ); } if output == "validate-soup-candidate" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-soup-candidate requires an input ledger path", )); }; let Some(input_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-soup-candidate requires an input review path", )); }; let Some(input_recipe) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-soup-candidate requires an input parent-pool recipe path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-soup-candidate requires a candidate .slm path", )); }; let Some(input_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-soup-candidate requires an input operator receipt path", )); }; let (parent_paths, admission_records) = split_parent_admission_args("validate-soup-candidate", args.collect())?; return soup::validate_candidate_path( Path::new(&input_ledger), Path::new(&input_review), Path::new(&input_recipe), Path::new(&candidate_slm), Path::new(&input_receipt), &parent_paths, &admission_records, ); } if output == "multi-parent-candidate-manifest" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-candidate-manifest requires an input ledger path", )); }; let Some(input_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-candidate-manifest requires an input review path", )); }; let Some(input_recipe) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-candidate-manifest requires an input parent-pool recipe path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-candidate-manifest requires a candidate .slm path", )); }; let Some(input_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-candidate-manifest requires an input operator receipt path", )); }; let Some(output_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-candidate-manifest requires an output candidate manifest path", )); }; let (parent_paths, admission_records) = split_parent_admission_args("multi-parent-candidate-manifest", args.collect())?; return multi_candidate::write_manifest_path( Path::new(&input_ledger), Path::new(&input_review), Path::new(&input_recipe), Path::new(&candidate_slm), Path::new(&input_receipt), Path::new(&output_manifest), &parent_paths, &admission_records, ); } if output == "validate-multi-parent-candidate" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-candidate requires an input ledger path", )); }; let Some(input_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-candidate requires an input review path", )); }; let Some(input_recipe) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-candidate requires an input parent-pool recipe path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-candidate requires a candidate .slm path", )); }; let Some(input_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-candidate requires an input operator receipt path", )); }; let Some(input_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-candidate requires an input candidate manifest path", )); }; let (parent_paths, admission_records) = split_parent_admission_args("validate-multi-parent-candidate", args.collect())?; return multi_candidate::validate_manifest_path( Path::new(&input_ledger), Path::new(&input_review), Path::new(&input_recipe), Path::new(&candidate_slm), Path::new(&input_receipt), Path::new(&input_manifest), &parent_paths, &admission_records, ); } if output == "multi-parent-promotion-template" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-promotion-template requires an input ledger path", )); }; let Some(input_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-promotion-template requires an input review path", )); }; let Some(input_recipe) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-promotion-template requires an input parent-pool recipe path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-promotion-template requires a candidate .slm path", )); }; let Some(input_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-promotion-template requires an input operator receipt path", )); }; let Some(input_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-promotion-template requires an input candidate manifest path", )); }; let Some(output_promotion) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-promotion-template requires an output promotion path", )); }; let (parent_paths, admission_records) = split_parent_admission_args("multi-parent-promotion-template", args.collect())?; return multi_promotion::write_template_path( Path::new(&input_ledger), Path::new(&input_review), Path::new(&input_recipe), Path::new(&candidate_slm), Path::new(&input_receipt), Path::new(&input_manifest), Path::new(&output_promotion), &parent_paths, &admission_records, ); } if output == "validate-multi-parent-promotion" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-promotion requires an input ledger path", )); }; let Some(input_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-promotion requires an input review path", )); }; let Some(input_recipe) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-promotion requires an input parent-pool recipe path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-promotion requires a candidate .slm path", )); }; let Some(input_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-promotion requires an input operator receipt path", )); }; let Some(input_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-promotion requires an input candidate manifest path", )); }; let Some(input_promotion) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-promotion requires an input promotion path", )); }; let (parent_paths, admission_records) = split_parent_admission_args("validate-multi-parent-promotion", args.collect())?; return multi_promotion::validate_template_path( Path::new(&input_ledger), Path::new(&input_review), Path::new(&input_recipe), Path::new(&candidate_slm), Path::new(&input_receipt), Path::new(&input_manifest), Path::new(&input_promotion), &parent_paths, &admission_records, ); } if output == "multi-parent-admission-record" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-admission-record requires an input ledger path", )); }; let Some(input_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-admission-record requires an input review path", )); }; let Some(input_recipe) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-admission-record requires an input parent-pool recipe path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-admission-record requires a candidate .slm path", )); }; let Some(input_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-admission-record requires an input operator receipt path", )); }; let Some(input_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-admission-record requires an input candidate manifest path", )); }; let Some(input_promotion) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-admission-record requires an input promotion path", )); }; let Some(input_provenance) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-admission-record requires an input provenance manifest path", )); }; let Some(input_runtime) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-admission-record requires an input runtime-smoke sidecar path", )); }; let Some(input_eval) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-admission-record requires an input evaluation manifest path", )); }; let Some(output_admission) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "multi-parent-admission-record requires an output admission path", )); }; let (parent_paths, admission_records) = split_parent_admission_args("multi-parent-admission-record", args.collect())?; return multi_admission::write_record_path( Path::new(&input_ledger), Path::new(&input_review), Path::new(&input_recipe), Path::new(&candidate_slm), Path::new(&input_receipt), Path::new(&input_manifest), Path::new(&input_promotion), Path::new(&input_provenance), Path::new(&input_runtime), Path::new(&input_eval), Path::new(&output_admission), &parent_paths, &admission_records, ); } if output == "validate-multi-parent-admission" { let Some(input_ledger) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-admission requires an input ledger path", )); }; let Some(input_review) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-admission requires an input review path", )); }; let Some(input_recipe) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-admission requires an input parent-pool recipe path", )); }; let Some(candidate_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-admission requires a candidate .slm path", )); }; let Some(input_receipt) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-admission requires an input operator receipt path", )); }; let Some(input_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-admission requires an input candidate manifest path", )); }; let Some(input_promotion) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-admission requires an input promotion path", )); }; let Some(input_provenance) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-admission requires an input provenance manifest path", )); }; let Some(input_runtime) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-admission requires an input runtime-smoke sidecar path", )); }; let Some(input_eval) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-admission requires an input evaluation manifest path", )); }; let Some(input_admission) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-multi-parent-admission requires an input admission path", )); }; let (parent_paths, admission_records) = split_parent_admission_args("validate-multi-parent-admission", args.collect())?; return multi_admission::validate_record_path( Path::new(&input_ledger), Path::new(&input_review), Path::new(&input_recipe), Path::new(&candidate_slm), Path::new(&input_receipt), Path::new(&input_manifest), Path::new(&input_promotion), Path::new(&input_provenance), Path::new(&input_runtime), Path::new(&input_eval), Path::new(&input_admission), &parent_paths, &admission_records, ); } if output == "validate-selector-registry" { let Some(input_registry) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-selector-registry requires an input registry path", )); }; let admission_records: Vec = args.collect(); return selector::validate_registry_path(Path::new(&input_registry), &admission_records); } if output == "manifest" { let Some(input) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "manifest requires an input .slm path", )); }; let Some(manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "manifest requires an output manifest path", )); }; let source_kind = args .next() .unwrap_or_else(|| "deterministic-smoke".to_string()); return provenance::write_manifest_for_path( Path::new(&input), Path::new(&manifest), &source_kind, ); } if output == "validate-manifest" { let Some(input) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-manifest requires an input .slm path", )); }; let Some(manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-manifest requires a manifest path", )); }; return provenance::validate_manifest_path(Path::new(&input), Path::new(&manifest)); } if output == "runtime-smoke" { let Some(input) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "runtime-smoke requires an input .slm path", )); }; let Some(manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "runtime-smoke requires an input manifest path", )); }; let Some(runtime_smoke) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "runtime-smoke requires an output sidecar path", )); }; return provenance::write_runtime_smoke_for_path( Path::new(&input), Path::new(&manifest), Path::new(&runtime_smoke), ); } if output == "validate-runtime-smoke" { let Some(input) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-runtime-smoke requires an input .slm path", )); }; let Some(manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-runtime-smoke requires an input manifest path", )); }; let Some(runtime_smoke) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-runtime-smoke requires an input sidecar path", )); }; return provenance::validate_runtime_smoke_path( Path::new(&input), Path::new(&manifest), Path::new(&runtime_smoke), ); } if output == "eval-template" { let Some(input) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "eval-template requires an input .slm path", )); }; let Some(manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "eval-template requires an input manifest path", )); }; let Some(eval_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "eval-template requires an output evaluation manifest path", )); }; let gate = args .next() .unwrap_or_else(|| "assistant-quality".to_string()); return provenance::write_eval_template_for_path( Path::new(&input), Path::new(&manifest), Path::new(&eval_manifest), &gate, ); } if output == "quality-gate" { let Some(input) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "quality-gate requires an input .slm path", )); }; let Some(manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "quality-gate requires an input manifest path", )); }; let Some(gate) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "quality-gate requires runtime-smoke or assistant-quality", )); }; let eval_manifest = args.next(); return provenance::quality_gate_path( Path::new(&input), Path::new(&manifest), &gate, eval_manifest.as_deref().map(Path::new), ); } if output == "source-template" { let Some(output_dir) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "source-template requires an output source directory", )); }; let shape_name = args.next().unwrap_or_else(|| "tiny-fixture".to_string()); return trained_source::write_source_template_path(Path::new(&output_dir), &shape_name); } if output == "adapter-source-template" { let Some(output_dir) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "adapter-source-template requires an output adapter source directory", )); }; let shape_name = args.next().unwrap_or_else(|| "tiny-fixture".to_string()); return trained_adapter_source::write_adapter_source_template_path( Path::new(&output_dir), &shape_name, ); } if output == "validate-source" { let Some(input_dir) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-source requires an input source directory", )); }; return trained_source::validate_source_path(Path::new(&input_dir)); } if output == "validate-adapter-source" { let Some(input_dir) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-adapter-source requires an input adapter source directory", )); }; return trained_adapter_source::validate_adapter_source_path(Path::new(&input_dir)); } if output == "convert-adapter-source" { let Some(input_dir) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "convert-adapter-source requires an input adapter source directory", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "convert-adapter-source requires a base parent .slm path", )); }; let Some(output_adapter) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "convert-adapter-source requires an output ALR1 adapter path", )); }; let Some(output_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "convert-adapter-source requires an output ALR1 manifest path", )); }; return trained_adapter_source::convert_adapter_source_path( Path::new(&input_dir), Path::new(&base_parent), Path::new(&output_adapter), Path::new(&output_manifest), ); } if output == "validate-converted-adapter-source" { let Some(input_dir) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-converted-adapter-source requires an input adapter source directory", )); }; let Some(base_parent) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-converted-adapter-source requires a base parent .slm path", )); }; let Some(input_adapter) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-converted-adapter-source requires an input ALR1 adapter path", )); }; let Some(input_manifest) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "validate-converted-adapter-source requires an input ALR1 manifest path", )); }; return trained_adapter_source::validate_converted_adapter_source_path( Path::new(&input_dir), Path::new(&base_parent), Path::new(&input_adapter), Path::new(&input_manifest), ); } if output == "convert-trained" { let Some(input_dir) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "convert-trained requires an input source directory", )); }; let Some(output_slm) = args.next() else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, "convert-trained requires an output .slm path", )); }; let output_quantization = args.next().unwrap_or_else(|| "f32".to_string()); return trained_source::convert_trained_path( Path::new(&input_dir), Path::new(&output_slm), &output_quantization, ); } let mode = args.next().unwrap_or_else(|| "tiny-fixture".to_string()); let (shape, tensors, tokenizer, flags) = match mode.as_str() { "tiny-fixture" => ( ModelShape::tiny_fixture(), tiny_fixture_tensors(), ByteTokenizerSection::phase_one(), 0, ), "tiny-fixture-tied" => ( ModelShape::tiny_fixture(), tiny_fixture_tied_tensors(), ByteTokenizerSection::phase_one(), FLAG_TIED_OUTPUT, ), "tiny-fixture-q8" => ( ModelShape::tiny_fixture(), tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), ByteTokenizerSection::phase_one(), 0, ), "tiny-fixture-q4" => ( ModelShape::tiny_fixture(), tiny_fixture_tensors_with_dtype(DTYPE_Q4_0), ByteTokenizerSection::phase_one(), 0, ), "tiny-fixture-bpe" => { let shape = ModelShape { vocab_size: 262, ..ModelShape::tiny_fixture() }; let tensors = tensor_writer::tensors_for_shape(&shape, DTYPE_F32); (shape, tensors, TokenizerSection::tiny_bpe_demo(), 0) } "tinylm16-f32" => ( ModelShape::tinylm16(), tinylm16_f32_tensors(), ByteTokenizerSection::phase_one(), 0, ), "tinylm16-q8" => ( ModelShape::tinylm16(), tinylm16_q8_tensors(), ByteTokenizerSection::phase_one(), 0, ), "tinylm16-q4" => ( ModelShape::tinylm16(), tinylm16_q4_tensors(), ByteTokenizerSection::phase_one(), 0, ), _ => { return Err(io::Error::new( io::ErrorKind::InvalidInput, "supported modes: tiny-fixture, tiny-fixture-tied, tiny-fixture-q8, tiny-fixture-q4, tiny-fixture-bpe, tinylm16-f32, tinylm16-q8, tinylm16-q4", )); } }; let bytes = if flags == 0 { build_model_file(&shape, &tensors, &tokenizer)? } else { build_model_file_with_flags(&shape, &tensors, &tokenizer, flags)? }; let path = Path::new(&output); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } let mut file = File::create(path)?; file.write_all(&bytes)?; Ok(()) } fn split_parent_admission_args( command: &str, rest: Vec, ) -> io::Result<(Vec, Vec)> { let Some(parent_marker) = rest.iter().position(|arg| arg == "--parents") else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, format!("{command} requires --parents before parent .slm paths"), )); }; let Some(admission_marker) = rest.iter().position(|arg| arg == "--admissions") else { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, format!("{command} requires --admissions before admission records"), )); }; if parent_marker != 0 || admission_marker <= parent_marker + 1 { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, format!("{command} requires --parents [...parent.slm]"), )); } if admission_marker + 1 >= rest.len() { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, format!("{command} requires --admissions [...input.admission]"), )); } let parents = rest[parent_marker + 1..admission_marker].to_vec(); let admissions = rest[admission_marker + 1..].to_vec(); if parents.len() < 2 { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, format!("{command} requires at least two parent .slm paths"), )); } if admissions .iter() .any(|arg| arg == "--parents" || arg == "--admissions") { print_usage(); return Err(io::Error::new( io::ErrorKind::InvalidInput, format!("{command} received duplicate list markers"), )); } Ok((parents, admissions)) } fn print_usage() { eprintln!( "usage: tinyrustlm-slm-pack [tiny-fixture|tiny-fixture-tied|tiny-fixture-q8|tiny-fixture-q4|tiny-fixture-bpe|tinylm16-f32|tinylm16-q8|tinylm16-q4]\n tinyrustlm-slm-pack validate \n tinyrustlm-slm-pack browser-multi-parent-bundle [f32|q8_0|q4_0|all] [sign-merge|soup|mixed]\n tinyrustlm-slm-pack browser-converted-trained-bundle [f32|q8_0|q4_0|all]\n tinyrustlm-slm-pack runtime-wasm-manifest \n tinyrustlm-slm-pack compatibility [output.compat]\n tinyrustlm-slm-pack lineage-template [resource-budget]\n tinyrustlm-slm-pack validate-lineage \n tinyrustlm-slm-pack blend-candidate [parent0-weight-ppm]\n tinyrustlm-slm-pack validate-blend-candidate \n tinyrustlm-slm-pack crossover-candidate [crossover-seed] [parent0-keep-ppm]\n tinyrustlm-slm-pack validate-crossover-candidate \n tinyrustlm-slm-pack delta-candidate [delta-weight-ppm]\n tinyrustlm-slm-pack validate-delta-candidate \n tinyrustlm-slm-pack sparse-delta-candidate [delta-weight-ppm] [keep-ppm]\n tinyrustlm-slm-pack validate-sparse-delta-candidate \n tinyrustlm-slm-pack adapter-delta \n tinyrustlm-slm-pack validate-adapter-delta \n tinyrustlm-slm-pack sparse-adapter-delta [delta-weight-ppm] [keep-ppm]\n tinyrustlm-slm-pack validate-sparse-adapter-delta \n tinyrustlm-slm-pack fuse-adapter-delta \n tinyrustlm-slm-pack validate-fuse-adapter-delta \n tinyrustlm-slm-pack candidate-manifest \n tinyrustlm-slm-pack validate-candidate \n tinyrustlm-slm-pack promotion-template [promoter-id] [promotion-scope]\n tinyrustlm-slm-pack validate-promotion \n tinyrustlm-slm-pack admission-record [selector-id]\n tinyrustlm-slm-pack validate-admission \n tinyrustlm-slm-pack promotion-ledger [...input.admission]\n tinyrustlm-slm-pack validate-promotion-ledger [...input.admission]\n tinyrustlm-slm-pack selector-registry [...input.admission]\n tinyrustlm-slm-pack validate-selector-registry [...input.admission]\n tinyrustlm-slm-pack manifest [deterministic-smoke|converted-trained]\n tinyrustlm-slm-pack validate-manifest \n tinyrustlm-slm-pack runtime-smoke \n tinyrustlm-slm-pack validate-runtime-smoke \n tinyrustlm-slm-pack eval-template [assistant-quality]\n tinyrustlm-slm-pack quality-gate [input.eval]\n tinyrustlm-slm-pack source-template [tiny-fixture|tiny-fixture-tied|tiny-fixture-bpe|tinylm16|tinylm16-tied]\n tinyrustlm-slm-pack validate-source \n tinyrustlm-slm-pack convert-trained [f32|q8_0|q4_0]" ); eprintln!( " tinyrustlm-slm-pack candidate-manifest [input.operator]\n tinyrustlm-slm-pack validate-candidate [input.operator]" ); eprintln!( " tinyrustlm-slm-pack promotion-template [promoter-id] [promotion-scope] [input.operator]\n tinyrustlm-slm-pack validate-promotion [input.operator]" ); eprintln!( " tinyrustlm-slm-pack admission-record [selector-id] [input.operator]\n tinyrustlm-slm-pack validate-admission [input.operator]" ); eprintln!( " tinyrustlm-slm-pack adapter-source-template [tiny-fixture|tiny-fixture-tied|tinylm16|tinylm16-tied]\n tinyrustlm-slm-pack validate-adapter-source \n tinyrustlm-slm-pack convert-adapter-source \n tinyrustlm-slm-pack validate-converted-adapter-source " ); eprintln!( " tinyrustlm-slm-pack mutation-candidate [mutation-seed] [mutation-rate-ppm] [mutation-magnitude-ppm]\n tinyrustlm-slm-pack validate-mutation-candidate " ); eprintln!( " tinyrustlm-slm-pack prune-candidate [keep-ppm] [floor-ppm]\n tinyrustlm-slm-pack validate-prune-candidate " ); eprintln!( " tinyrustlm-slm-pack federated-candidate [local-update-weight-ppm]\n tinyrustlm-slm-pack validate-federated-candidate " ); eprintln!( " tinyrustlm-slm-pack dare-candidate [delta-weight-ppm] [keep-ppm] [dropout-seed]\n tinyrustlm-slm-pack validate-dare-candidate " ); eprintln!( " tinyrustlm-slm-pack low-rank-adapter-delta [rank-limit]\n tinyrustlm-slm-pack validate-low-rank-adapter-delta " ); eprintln!( " tinyrustlm-slm-pack population-review [...input.admission]\n tinyrustlm-slm-pack validate-population-review [...input.admission]" ); eprintln!( " tinyrustlm-slm-pack parent-pool-recipe [...input.admission]\n tinyrustlm-slm-pack validate-parent-pool-recipe [...input.admission]" ); eprintln!( " tinyrustlm-slm-pack sign-merge-candidate --parents [...parent.slm] --admissions [...input.admission]\n tinyrustlm-slm-pack validate-sign-merge-candidate --parents [...parent.slm] --admissions [...input.admission]" ); eprintln!( " tinyrustlm-slm-pack soup-candidate --parents [...parent.slm] --admissions [...input.admission]\n tinyrustlm-slm-pack validate-soup-candidate --parents [...parent.slm] --admissions [...input.admission]" ); eprintln!( " tinyrustlm-slm-pack multi-parent-candidate-manifest --parents [...parent.slm] --admissions [...input.admission]\n tinyrustlm-slm-pack validate-multi-parent-candidate --parents [...parent.slm] --admissions [...input.admission]" ); eprintln!( " tinyrustlm-slm-pack multi-parent-promotion-template --parents [...parent.slm] --admissions [...input.admission]\n tinyrustlm-slm-pack validate-multi-parent-promotion --parents [...parent.slm] --admissions [...input.admission]" ); eprintln!( " tinyrustlm-slm-pack multi-parent-admission-record --parents [...parent.slm] --admissions [...input.admission]\n tinyrustlm-slm-pack validate-multi-parent-admission --parents [...parent.slm] --admissions [...input.admission]" ); } pub(crate) fn build_model_file( shape: &ModelShape, tensors: &[TensorSpec], tokenizer: &ByteTokenizerSection, ) -> io::Result> { build_model_file_with_flags(shape, tensors, tokenizer, 0) } pub(crate) fn build_model_file_with_flags( shape: &ModelShape, tensors: &[TensorSpec], tokenizer: &ByteTokenizerSection, flags: u32, ) -> io::Result> { let tokenizer_offset = HEADER_LEN as u64; let tokenizer_length = tokenizer.bytes.len() as u64; let tensor_directory_offset = align_to_64(HEADER_LEN + tokenizer.bytes.len()) as u64; let tensor_data_offset = align_to_64(tensor_directory_offset as usize + tensors.len() * TENSOR_ENTRY_LEN) as u64; let mut tensor_offsets = Vec::with_capacity(tensors.len()); let mut scale_offsets = Vec::with_capacity(tensors.len()); let mut cursor = tensor_data_offset as usize; for tensor in tensors { cursor = align_to_64(cursor); tensor_offsets.push(cursor as u64); cursor += tensor.byte_len(); let scale_len = tensor.scale_byte_len(); if scale_len > 0 { cursor = align_to_64(cursor); scale_offsets.push(cursor as u64); cursor += scale_len; } else { scale_offsets.push(0); } } let mut bytes = vec![0u8; cursor]; bytes[0..4].copy_from_slice(b"SLM1"); write_u32(&mut bytes, 4, 1)?; write_u32(&mut bytes, 8, HEADER_LEN as u32)?; write_u32(&mut bytes, 12, 1)?; write_u32(&mut bytes, 16, flags)?; write_u32(&mut bytes, 20, shape.vocab_size)?; write_u32(&mut bytes, 24, shape.special_token_count)?; write_u32(&mut bytes, 28, shape.hidden_size)?; write_u32(&mut bytes, 32, shape.layer_count)?; write_u32(&mut bytes, 36, shape.head_count)?; write_u32(&mut bytes, 40, shape.kv_head_count)?; write_u32(&mut bytes, 44, shape.head_dim)?; write_u32(&mut bytes, 48, shape.ffn_size)?; write_u32(&mut bytes, 52, shape.max_context)?; write_f32(&mut bytes, 56, 10000.0)?; write_f32(&mut bytes, 60, 0.00001)?; write_u64(&mut bytes, 64, tokenizer_offset)?; write_u64(&mut bytes, 72, tokenizer_length)?; write_u64(&mut bytes, 80, tensor_directory_offset)?; write_u32(&mut bytes, 88, tensors.len() as u32)?; write_u64(&mut bytes, 92, tensor_data_offset)?; write_u64(&mut bytes, 100, 0)?; let tokenizer_start = tokenizer_offset as usize; bytes[tokenizer_start..tokenizer_start + tokenizer.bytes.len()] .copy_from_slice(&tokenizer.bytes); for (index, tensor) in tensors.iter().enumerate() { let entry = tensor_directory_offset as usize + index * TENSOR_ENTRY_LEN; write_u64(&mut bytes, entry, tensor.name_hash)?; write_u32(&mut bytes, entry + 8, tensor.dtype)?; write_u32(&mut bytes, entry + 12, tensor.rank)?; write_u32(&mut bytes, entry + 16, tensor.dims[0])?; write_u32(&mut bytes, entry + 20, tensor.dims[1])?; write_u32(&mut bytes, entry + 24, tensor.dims[2])?; write_u32(&mut bytes, entry + 28, tensor.dims[3])?; write_u64(&mut bytes, entry + 32, tensor_offsets[index])?; write_u64(&mut bytes, entry + 40, tensor.byte_len() as u64)?; write_u64(&mut bytes, entry + 48, scale_offsets[index])?; write_u32(&mut bytes, entry + 56, tensor.block_size)?; write_tensor_payload( &mut bytes, tensor, tensor_offsets[index], scale_offsets[index], )?; } let checksum = simple_checksum(&bytes); write_u64(&mut bytes, 100, checksum)?; Ok(bytes) } pub(crate) fn build_model_file_from_values_with_flags( shape: &ModelShape, tensors: &[TensorSpec], tokenizer: &ByteTokenizerSection, values: &[Vec], flags: u32, ) -> io::Result> { if tensors.len() != values.len() { return Err(io::Error::new( io::ErrorKind::InvalidInput, "tensor specs and source value lists must have the same length", )); } for (tensor, tensor_values) in tensors.iter().zip(values.iter()) { if tensor.element_count() != tensor_values.len() { return Err(io::Error::new( io::ErrorKind::InvalidInput, "source tensor value count does not match tensor shape", )); } } let tokenizer_offset = HEADER_LEN as u64; let tokenizer_length = tokenizer.bytes.len() as u64; let tensor_directory_offset = align_to_64(HEADER_LEN + tokenizer.bytes.len()) as u64; let tensor_data_offset = align_to_64(tensor_directory_offset as usize + tensors.len() * TENSOR_ENTRY_LEN) as u64; let mut tensor_offsets = Vec::with_capacity(tensors.len()); let mut scale_offsets = Vec::with_capacity(tensors.len()); let mut cursor = tensor_data_offset as usize; for tensor in tensors { cursor = align_to_64(cursor); tensor_offsets.push(cursor as u64); cursor += tensor.byte_len(); let scale_len = tensor.scale_byte_len(); if scale_len > 0 { cursor = align_to_64(cursor); scale_offsets.push(cursor as u64); cursor += scale_len; } else { scale_offsets.push(0); } } let mut bytes = vec![0u8; cursor]; bytes[0..4].copy_from_slice(b"SLM1"); write_u32(&mut bytes, 4, 1)?; write_u32(&mut bytes, 8, HEADER_LEN as u32)?; write_u32(&mut bytes, 12, 1)?; write_u32(&mut bytes, 16, flags)?; write_u32(&mut bytes, 20, shape.vocab_size)?; write_u32(&mut bytes, 24, shape.special_token_count)?; write_u32(&mut bytes, 28, shape.hidden_size)?; write_u32(&mut bytes, 32, shape.layer_count)?; write_u32(&mut bytes, 36, shape.head_count)?; write_u32(&mut bytes, 40, shape.kv_head_count)?; write_u32(&mut bytes, 44, shape.head_dim)?; write_u32(&mut bytes, 48, shape.ffn_size)?; write_u32(&mut bytes, 52, shape.max_context)?; write_f32(&mut bytes, 56, 10000.0)?; write_f32(&mut bytes, 60, 0.00001)?; write_u64(&mut bytes, 64, tokenizer_offset)?; write_u64(&mut bytes, 72, tokenizer_length)?; write_u64(&mut bytes, 80, tensor_directory_offset)?; write_u32(&mut bytes, 88, tensors.len() as u32)?; write_u64(&mut bytes, 92, tensor_data_offset)?; write_u64(&mut bytes, 100, 0)?; let tokenizer_start = tokenizer_offset as usize; bytes[tokenizer_start..tokenizer_start + tokenizer.bytes.len()] .copy_from_slice(&tokenizer.bytes); for (index, tensor) in tensors.iter().enumerate() { let entry = tensor_directory_offset as usize + index * TENSOR_ENTRY_LEN; write_u64(&mut bytes, entry, tensor.name_hash)?; write_u32(&mut bytes, entry + 8, tensor.dtype)?; write_u32(&mut bytes, entry + 12, tensor.rank)?; write_u32(&mut bytes, entry + 16, tensor.dims[0])?; write_u32(&mut bytes, entry + 20, tensor.dims[1])?; write_u32(&mut bytes, entry + 24, tensor.dims[2])?; write_u32(&mut bytes, entry + 28, tensor.dims[3])?; write_u64(&mut bytes, entry + 32, tensor_offsets[index])?; write_u64(&mut bytes, entry + 40, tensor.byte_len() as u64)?; write_u64(&mut bytes, entry + 48, scale_offsets[index])?; write_u32(&mut bytes, entry + 56, tensor.block_size)?; write_tensor_payload_from_values( &mut bytes, tensor, &values[index], tensor_offsets[index], scale_offsets[index], )?; } let checksum = simple_checksum(&bytes); write_u64(&mut bytes, 100, checksum)?; Ok(bytes) } fn simple_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x9e3779b97f4a7c15u64; for (index, byte) in bytes.iter().enumerate() { let value = if (100..108).contains(&index) { 0 } else { *byte }; acc ^= u64::from(value).wrapping_add((index as u64) << 1); acc = acc.rotate_left(7).wrapping_mul(0x100000001b3); } acc } fn write_tensor_payload( bytes: &mut [u8], tensor: &TensorSpec, tensor_offset: u64, scale_offset: u64, ) -> io::Result<()> { match tensor.dtype { DTYPE_F32 => write_f32_tensor(bytes, tensor, tensor_offset), DTYPE_Q8_0 => write_q8_tensor(bytes, tensor, tensor_offset, scale_offset), DTYPE_Q4_0 => write_q4_tensor(bytes, tensor, tensor_offset, scale_offset), _ => Err(io::Error::new( io::ErrorKind::InvalidInput, "unsupported tensor dtype", )), } } fn write_f32_tensor(bytes: &mut [u8], tensor: &TensorSpec, tensor_offset: u64) -> io::Result<()> { let start = tensor_offset as usize; for elem in 0..tensor.element_count() { write_f32(bytes, start + elem * 4, fixture_value(tensor, elem))?; } Ok(()) } fn write_q8_tensor( bytes: &mut [u8], tensor: &TensorSpec, tensor_offset: u64, scale_offset: u64, ) -> io::Result<()> { let rows = tensor.rows(); let cols = tensor.cols_per_row(); let start = tensor_offset as usize; let scale_start = scale_offset as usize; let mut row_values = vec![0.0; cols]; let mut quantized = vec![0i8; cols]; for row in 0..rows { for col in 0..cols { row_values[col] = fixture_value(tensor, row * cols + col); } let scale = quantize_q8_row(&row_values, &mut quantized); write_f32(bytes, scale_start + row * 4, scale)?; for col in 0..cols { bytes[start + row * cols + col] = quantized[col] as u8; } } Ok(()) } fn write_q4_tensor( bytes: &mut [u8], tensor: &TensorSpec, tensor_offset: u64, scale_offset: u64, ) -> io::Result<()> { let rows = tensor.rows(); let cols = tensor.cols_per_row(); let block = tensor.block_size as usize; if block == 0 || block % 2 != 0 || cols % block != 0 { return Err(io::Error::new( io::ErrorKind::InvalidInput, "q4 tensor columns must divide into even blocks", )); } let blocks_per_row = cols / block; let start = tensor_offset as usize; let scale_start = scale_offset as usize; let mut block_values = vec![0.0; block]; let mut quantized = vec![0i8; block]; for row in 0..rows { for block_index in 0..blocks_per_row { let value_start = row * cols + block_index * block; for col in 0..block { block_values[col] = fixture_value(tensor, value_start + col); } let scale = quantize_q4_block(&block_values, &mut quantized); write_f32( bytes, scale_start + (row * blocks_per_row + block_index) * 4, scale, )?; let byte_start = start + (row * cols + block_index * block) / 2; for pair in 0..(block / 2) { bytes[byte_start + pair] = pack_q4_pair(quantized[pair * 2], quantized[pair * 2 + 1]); } } } Ok(()) } pub(crate) fn fixture_value(tensor: &TensorSpec, elem: usize) -> f32 { match tensor.seed { 1 => 0.125, 2 | 4 | 5 => 1.0, 3 => output_fixture_value(tensor, elem), 6 | 7 | 8 | 9 => square_identity_value(tensor, elem, 0.25), 10 | 12 => 0.0625, 11 => 0.0625, 13 => tied_embedding_fixture_value(tensor, elem), _ => 0.0, } } fn write_tensor_payload_from_values( bytes: &mut [u8], tensor: &TensorSpec, values: &[f32], tensor_offset: u64, scale_offset: u64, ) -> io::Result<()> { match tensor.dtype { DTYPE_F32 => write_f32_tensor_from_values(bytes, values, tensor_offset), DTYPE_Q8_0 => { write_q8_tensor_from_values(bytes, tensor, values, tensor_offset, scale_offset) } DTYPE_Q4_0 => { write_q4_tensor_from_values(bytes, tensor, values, tensor_offset, scale_offset) } _ => Err(io::Error::new( io::ErrorKind::InvalidInput, "unsupported tensor dtype", )), } } fn write_f32_tensor_from_values( bytes: &mut [u8], values: &[f32], tensor_offset: u64, ) -> io::Result<()> { let start = tensor_offset as usize; for (elem, value) in values.iter().enumerate() { write_f32(bytes, start + elem * 4, *value)?; } Ok(()) } fn write_q8_tensor_from_values( bytes: &mut [u8], tensor: &TensorSpec, values: &[f32], tensor_offset: u64, scale_offset: u64, ) -> io::Result<()> { let rows = tensor.rows(); let cols = tensor.cols_per_row(); let start = tensor_offset as usize; let scale_start = scale_offset as usize; let mut quantized = vec![0i8; cols]; for row in 0..rows { let row_start = row * cols; let scale = quantize_q8_row(&values[row_start..row_start + cols], &mut quantized); write_f32(bytes, scale_start + row * 4, scale)?; for col in 0..cols { bytes[start + row * cols + col] = quantized[col] as u8; } } Ok(()) } fn write_q4_tensor_from_values( bytes: &mut [u8], tensor: &TensorSpec, values: &[f32], tensor_offset: u64, scale_offset: u64, ) -> io::Result<()> { let rows = tensor.rows(); let cols = tensor.cols_per_row(); let block = tensor.block_size as usize; if block == 0 || block % 2 != 0 || cols % block != 0 { return Err(io::Error::new( io::ErrorKind::InvalidInput, "q4 tensor columns must divide into even blocks", )); } let blocks_per_row = cols / block; let start = tensor_offset as usize; let scale_start = scale_offset as usize; let mut quantized = vec![0i8; block]; for row in 0..rows { for block_index in 0..blocks_per_row { let value_start = row * cols + block_index * block; let block_values = &values[value_start..value_start + block]; let scale = quantize_q4_block(block_values, &mut quantized); write_f32( bytes, scale_start + (row * blocks_per_row + block_index) * 4, scale, )?; let byte_start = start + (row * cols + block_index * block) / 2; for pair in 0..(block / 2) { bytes[byte_start + pair] = pack_q4_pair(quantized[pair * 2], quantized[pair * 2 + 1]); } } } Ok(()) } fn output_fixture_value(tensor: &TensorSpec, elem: usize) -> f32 { let hidden = tensor.dims[1] as usize; let row = elem / hidden; match row { 101 => 1.0, 257 => 0.25, _ => -0.01, } } fn tied_embedding_fixture_value(tensor: &TensorSpec, elem: usize) -> f32 { let hidden = tensor.dims[1] as usize; let row = elem / hidden; match row { 101 => 1.0, 257 => 0.25, _ => 0.125, } } fn square_identity_value(tensor: &TensorSpec, elem: usize, scale: f32) -> f32 { let rows = tensor.dims[0] as usize; let cols = tensor.dims[1] as usize; if rows == cols && elem / cols == elem % cols { scale } else { 0.0 } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/main.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/multi_admission.rs BYTES: 43245 SHA256: 01F9D85FBAA0C8A49BB54899C2EB991C9D8BE7FA756740CAC61C2BA4453301DD ================================================================================ //! Selector-admission records for evaluated multi-parent parent-pool candidates. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::admission; use crate::blend::{hex64, invalid, parse_manifest, push_line, require_equal, require_key}; use crate::multi_promotion; use crate::provenance; use crate::slm_validate; const ADMISSION_VERSION: &str = "1"; const ADMISSION_KIND: &str = "multi-parent-sign-merge"; const ADMISSION_STATUS: &str = "admitted-for-browser-selector"; const PROMOTION_STATUS: &str = "runtime-smoke-and-eval-passed"; const RUNTIME_SMOKE_STATUS: &str = "pass"; const EVAL_STATUS: &str = "pass"; const QUALITY_GATE: &str = "assistant-quality"; const PROMOTION_DECISION: &str = "accepted-for-browser-selector"; const BROWSER_SELECTOR_STATUS: &str = "admitted"; const PUBLIC_CLAIM_STATUS: &str = "bound-to-eval-scope"; const REQUIRED_NEXT_GATE: &str = "multi-parent-selector-registry-route-binding"; const OPERATOR_RECEIPT_STATUS: &str = "receipt-bound"; const PROMOTION_KEYS: [&str; 11] = [ "promotion_kind", "promoter_id", "promotion_scope", "operator_receipt_checksum", "parent_pool_recipe_checksum", "population_review_checksum", "promotion_ledger_checksum", "admission_set_checksum", "frontier_candidate_id", "frontier_candidate_slm_checksum", "parent_count", ]; const CANDIDATE_KEYS: [&str; 11] = [ "candidate_artifact_path", "candidate_artifact_bytes", "candidate_slm_version", "candidate_slm_checksum", "candidate_model_shape", "candidate_tensor_count", "candidate_parameter_count", "candidate_quantization", "candidate_output_contract", "candidate_tokenizer_checksum", "candidate_tensor_layout_checksum", ]; const SCHEDULE_KEYS: [&str; 12] = [ "evolution_recipe_version", "evolution_recipe_strategy", "evolution_recipe_status", "evolution_selection_source", "evolution_relatedness_contract_checksum", "evolution_schedule_checksum_algorithm", "evolution_schedule_checksum", "scheduled_operator_family_index", "scheduled_operator_family_kind", "scheduled_operator_family_command", "scheduled_operator_family_selection_rule", "scheduled_operator_family_output_gate", ]; struct Evidence { promotion: HashMap, eval: HashMap, } /// Writes a selector-admission record for a validated multi-parent candidate. pub(crate) fn write_record_path( ledger: &Path, review: &Path, recipe: &Path, candidate_slm: &Path, receipt: &Path, candidate_manifest: &Path, promotion_manifest: &Path, provenance_manifest: &Path, runtime_smoke: &Path, eval_manifest: &Path, output: &Path, parent_paths: &[String], admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_texts(admission_paths, "multi-parent-admission admissions")?; let parent_bytes = read_bytes(parent_paths, "multi-parent-admission parents")?; let ledger_text = fs::read_to_string(ledger)?; let review_text = fs::read_to_string(review)?; let recipe_text = fs::read_to_string(recipe)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; let candidate_manifest_text = fs::read_to_string(candidate_manifest)?; let promotion_text = fs::read_to_string(promotion_manifest)?; let provenance_text = fs::read_to_string(provenance_manifest)?; let runtime_smoke_text = fs::read_to_string(runtime_smoke)?; let eval_text = fs::read_to_string(eval_manifest)?; let receipt_path = receipt.display().to_string(); let admission = build_record_text( &ledger_text, &review_text, &recipe_text, &parent_bytes, &candidate_bytes, &candidate_slm.display().to_string(), &receipt_path, &receipt_text, &candidate_manifest_text, &promotion_text, &provenance_text, &runtime_smoke_text, &eval_text, &admission_texts, admission::DEFAULT_ADMISSION_SELECTOR_ID, )?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, admission)?; println!( "SLM multi-parent selector admission record written: {}", output.display() ); Ok(()) } /// Validates a multi-parent selector-admission record against its evidence chain. pub(crate) fn validate_record_path( ledger: &Path, review: &Path, recipe: &Path, candidate_slm: &Path, receipt: &Path, candidate_manifest: &Path, promotion_manifest: &Path, provenance_manifest: &Path, runtime_smoke: &Path, eval_manifest: &Path, admission: &Path, parent_paths: &[String], admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_texts( admission_paths, "validate-multi-parent-admission admissions", )?; let parent_bytes = read_bytes(parent_paths, "validate-multi-parent-admission parents")?; let ledger_text = fs::read_to_string(ledger)?; let review_text = fs::read_to_string(review)?; let recipe_text = fs::read_to_string(recipe)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; let candidate_manifest_text = fs::read_to_string(candidate_manifest)?; let promotion_text = fs::read_to_string(promotion_manifest)?; let provenance_text = fs::read_to_string(provenance_manifest)?; let runtime_smoke_text = fs::read_to_string(runtime_smoke)?; let eval_text = fs::read_to_string(eval_manifest)?; let admission_text = fs::read_to_string(admission)?; let receipt_path = receipt.display().to_string(); validate_record_text( &ledger_text, &review_text, &recipe_text, &parent_bytes, &candidate_bytes, &candidate_slm.display().to_string(), &receipt_path, &receipt_text, &candidate_manifest_text, &promotion_text, &provenance_text, &runtime_smoke_text, &eval_text, &admission_texts, &admission_text, )?; println!("SLM multi-parent selector admission validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("admission: {}", admission.display()); Ok(()) } fn read_texts(paths: &[String], label: &str) -> io::Result> { if paths.is_empty() { return Err(invalid(&format!("{label} require at least one input"))); } paths .iter() .map(|path| fs::read_to_string(Path::new(path))) .collect() } fn read_bytes(paths: &[String], label: &str) -> io::Result)>> { if paths.len() < 2 { return Err(invalid(&format!( "{label} require at least two parent models" ))); } paths .iter() .map(|path| Ok((path.clone(), fs::read(Path::new(path))?))) .collect() } pub(crate) fn build_record_text( ledger_text: &str, review_text: &str, recipe_text: &str, parent_bytes: &[(String, Vec)], candidate_bytes: &[u8], candidate_path: &str, receipt_path: &str, receipt_text: &str, candidate_manifest_text: &str, promotion_text: &str, provenance_text: &str, runtime_smoke_text: &str, eval_text: &str, admission_texts: &[String], selector_id: &str, ) -> io::Result { validate_slug(selector_id, "selector_id")?; let evidence = validate_evidence( ledger_text, review_text, recipe_text, parent_bytes, candidate_bytes, candidate_path, receipt_text, candidate_manifest_text, promotion_text, provenance_text, runtime_smoke_text, eval_text, admission_texts, )?; render_record_text( &evidence, promotion_text, provenance_text, runtime_smoke_text, eval_text, selector_id, receipt_path, receipt_text, ) } fn validate_record_text( ledger_text: &str, review_text: &str, recipe_text: &str, parent_bytes: &[(String, Vec)], candidate_bytes: &[u8], candidate_path: &str, receipt_path: &str, receipt_text: &str, candidate_manifest_text: &str, promotion_text: &str, provenance_text: &str, runtime_smoke_text: &str, eval_text: &str, admission_texts: &[String], admission_text: &str, ) -> io::Result<()> { let evidence = validate_evidence( ledger_text, review_text, recipe_text, parent_bytes, candidate_bytes, candidate_path, receipt_text, candidate_manifest_text, promotion_text, provenance_text, runtime_smoke_text, eval_text, admission_texts, )?; let admission = validate_record_summary_text(admission_text)?; let selector_id = require_key(&admission, "selector_id")?; let expected = render_record_text( &evidence, promotion_text, provenance_text, runtime_smoke_text, eval_text, selector_id, receipt_path, receipt_text, )?; if admission_text != expected { return Err(invalid( "multi-parent admission fields do not match recomputed output", )); } Ok(()) } /// Validates the self-contained fields in a multi-parent admission record. pub(crate) fn validate_record_summary_text( admission_text: &str, ) -> io::Result> { let admission = parse_manifest(admission_text, "multi-parent admission")?; require_equal( &admission, "tinyrustlm_multi_parent_selector_admission_version", ADMISSION_VERSION, )?; require_equal(&admission, "admission_kind", ADMISSION_KIND)?; validate_slug(require_key(&admission, "selector_id")?, "selector_id")?; require_equal(&admission, "admission_status", ADMISSION_STATUS)?; require_equal(&admission, "promotion_status", PROMOTION_STATUS)?; for key in PROMOTION_KEYS { require_key(&admission, key)?; } for key in SCHEDULE_KEYS { require_key(&admission, key)?; } require_hex64(&admission, "evolution_relatedness_contract_checksum")?; require_hex64(&admission, "evolution_schedule_checksum")?; require_usize(&admission, "scheduled_operator_family_index")?; for key in [ "scheduled_operator_family_kind", "scheduled_operator_family_command", "scheduled_operator_family_selection_rule", "scheduled_operator_family_output_gate", ] { validate_slug(require_key(&admission, key)?, key)?; } require_key(&admission, "candidate_id")?; require_hex64(&admission, "candidate_manifest_checksum")?; require_hex64(&admission, "promotion_manifest_checksum")?; require_hex64(&admission, "provenance_manifest_checksum")?; require_hex64(&admission, "runtime_smoke_manifest_checksum")?; require_hex64(&admission, "eval_manifest_checksum")?; require_hex64(&admission, "eval_case_evidence_checksum")?; require_hex64(&admission, "operator_receipt_checksum")?; require_hex64(&admission, "parent_pool_recipe_checksum")?; require_hex64(&admission, "population_review_checksum")?; require_hex64(&admission, "promotion_ledger_checksum")?; require_hex64(&admission, "admission_set_checksum")?; require_hex64(&admission, "frontier_candidate_slm_checksum")?; require_positive_usize(&admission, "parent_count")?; for key in CANDIDATE_KEYS { require_key(&admission, key)?; } require_key(&admission, "candidate_parent_contract")?; require_key(&admission, "candidate_admission_status")?; require_positive_usize(&admission, "candidate_artifact_bytes")?; require_positive_usize(&admission, "candidate_slm_version")?; require_hex64(&admission, "candidate_slm_checksum")?; if admission.contains_key("operator_receipt_status") { require_equal( &admission, "operator_receipt_status", OPERATOR_RECEIPT_STATUS, )?; require_key(&admission, "operator_receipt_path")?; validate_slug( require_key(&admission, "operator_receipt_operator_id")?, "operator_receipt_operator_id", )?; validate_slug( require_key(&admission, "operator_receipt_operator_kind")?, "operator_receipt_operator_kind", )?; require_equal( &admission, "scheduled_operator_family_kind", require_key(&admission, "operator_receipt_operator_kind")?, )?; require_hex64(&admission, "operator_receipt_candidate_slm_checksum")?; require_equal( &admission, "operator_receipt_candidate_slm_checksum", require_key(&admission, "candidate_slm_checksum")?, )?; require_positive_usize(&admission, "operator_receipt_candidate_artifact_bytes")?; require_equal( &admission, "operator_receipt_candidate_artifact_bytes", require_key(&admission, "candidate_artifact_bytes")?, )?; } require_positive_usize(&admission, "candidate_tensor_count")?; require_positive_usize(&admission, "candidate_parameter_count")?; require_hex64(&admission, "candidate_tokenizer_checksum")?; require_hex64(&admission, "candidate_tensor_layout_checksum")?; require_equal(&admission, "runtime_smoke_status", RUNTIME_SMOKE_STATUS)?; require_equal(&admission, "eval_status", EVAL_STATUS)?; require_equal(&admission, "quality_gate", QUALITY_GATE)?; for key in ["quality_scope", "quality_boundary", "eval_dataset"] { require_key(&admission, key)?; } let case_count = require_positive_usize(&admission, "case_count")?; let cases_passed = require_usize(&admission, "cases_passed")?; let cases_failed = require_usize(&admission, "cases_failed")?; if cases_passed != case_count || cases_failed != 0 { return Err(invalid( "admission case totals must show every declared case passed and zero failed cases", )); } require_equal(&admission, "promotion_decision", PROMOTION_DECISION)?; require_equal( &admission, "browser_selector_status", BROWSER_SELECTOR_STATUS, )?; require_equal(&admission, "public_claim_status", PUBLIC_CLAIM_STATUS)?; require_equal(&admission, "required_next_gate", REQUIRED_NEXT_GATE)?; Ok(admission) } fn validate_evidence( ledger_text: &str, review_text: &str, recipe_text: &str, parent_bytes: &[(String, Vec)], candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, candidate_manifest_text: &str, promotion_text: &str, provenance_text: &str, runtime_smoke_text: &str, eval_text: &str, admission_texts: &[String], ) -> io::Result { multi_promotion::validate_template_text( ledger_text, review_text, recipe_text, parent_bytes, candidate_bytes, candidate_path, receipt_text, candidate_manifest_text, promotion_text, admission_texts, )?; let report = slm_validate::validate_bytes(candidate_bytes, candidate_path)?; let runtime_smoke = provenance::validate_runtime_smoke_text(&report, provenance_text, runtime_smoke_text)?; provenance::validate_quality_gate(&report, provenance_text, QUALITY_GATE, Some(eval_text))?; let promotion = parse_manifest(promotion_text, "multi-parent promotion")?; let eval = provenance::parse_manifest(eval_text)?; require_equal(&runtime_smoke, "runtime_smoke_status", RUNTIME_SMOKE_STATUS)?; require_equal(&eval, "eval_status", EVAL_STATUS)?; require_equal(&eval, "task_eval_status", EVAL_STATUS)?; require_equal(&eval, "cases_failed", "0")?; Ok(Evidence { promotion, eval }) } fn render_record_text( evidence: &Evidence, promotion_text: &str, provenance_text: &str, runtime_smoke_text: &str, eval_text: &str, selector_id: &str, receipt_path: &str, receipt_text: &str, ) -> io::Result { let mut text = String::new(); let receipt = parse_manifest(receipt_text, "multi-parent operator receipt")?; push_line( &mut text, "tinyrustlm_multi_parent_selector_admission_version", ADMISSION_VERSION, ); push_line(&mut text, "admission_kind", ADMISSION_KIND); push_line(&mut text, "selector_id", selector_id); push_line(&mut text, "admission_status", ADMISSION_STATUS); push_line(&mut text, "promotion_status", PROMOTION_STATUS); for key in PROMOTION_KEYS { push_line(&mut text, key, require_key(&evidence.promotion, key)?); } for key in SCHEDULE_KEYS { push_line(&mut text, key, require_key(&evidence.promotion, key)?); } push_operator_receipt_lines(&mut text, receipt_path, &receipt, &evidence.promotion)?; push_line( &mut text, "candidate_id", require_key(&evidence.promotion, "frontier_candidate_id")?, ); push_line( &mut text, "candidate_manifest_checksum", require_key(&evidence.promotion, "candidate_manifest_checksum")?, ); push_line( &mut text, "promotion_manifest_checksum", &hex64(provenance::text_checksum(promotion_text.as_bytes())), ); push_line( &mut text, "provenance_manifest_checksum", &hex64(provenance::text_checksum(provenance_text.as_bytes())), ); push_line( &mut text, "runtime_smoke_manifest_checksum", &hex64(provenance::text_checksum(runtime_smoke_text.as_bytes())), ); push_line( &mut text, "eval_manifest_checksum", &hex64(provenance::text_checksum(eval_text.as_bytes())), ); push_line( &mut text, "eval_case_evidence_checksum", &provenance::eval_case_evidence_checksum(&evidence.eval)?, ); for key in CANDIDATE_KEYS { push_line(&mut text, key, require_key(&evidence.promotion, key)?); } push_line( &mut text, "candidate_parent_contract", require_key(&evidence.promotion, "candidate_parent_contract")?, ); push_line( &mut text, "candidate_admission_status", require_key(&evidence.promotion, "candidate_admission_status")?, ); push_line(&mut text, "runtime_smoke_status", RUNTIME_SMOKE_STATUS); push_line(&mut text, "eval_status", EVAL_STATUS); push_line(&mut text, "quality_gate", QUALITY_GATE); push_line( &mut text, "quality_scope", require_key(&evidence.eval, "quality_scope")?, ); push_line( &mut text, "quality_boundary", require_key(&evidence.eval, "quality_boundary")?, ); push_line( &mut text, "eval_dataset", require_key(&evidence.eval, "eval_dataset")?, ); push_line( &mut text, "case_count", require_key(&evidence.eval, "case_count")?, ); push_line( &mut text, "cases_passed", require_key(&evidence.eval, "cases_passed")?, ); push_line( &mut text, "cases_failed", require_key(&evidence.eval, "cases_failed")?, ); push_line(&mut text, "promotion_decision", PROMOTION_DECISION); push_line( &mut text, "browser_selector_status", BROWSER_SELECTOR_STATUS, ); push_line(&mut text, "public_claim_status", PUBLIC_CLAIM_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } // Carries parent-pool operator identity into selector registries for browser provenance display. fn push_operator_receipt_lines( text: &mut String, receipt_path: &str, receipt: &HashMap, promotion: &HashMap, ) -> io::Result<()> { let operator_id = receipt .get("operator_id") .or_else(|| receipt.get("frontier_candidate_id")) .map(String::as_str) .ok_or_else(|| invalid("multi-parent operator receipt missing operator identity"))?; push_line(text, "operator_receipt_status", OPERATOR_RECEIPT_STATUS); push_line(text, "operator_receipt_path", receipt_path); push_line(text, "operator_receipt_operator_id", operator_id); push_line( text, "operator_receipt_operator_kind", require_key(receipt, "operator_kind")?, ); push_line( text, "operator_receipt_candidate_slm_checksum", require_key(promotion, "candidate_slm_checksum")?, ); push_line( text, "operator_receipt_candidate_artifact_bytes", require_key(promotion, "candidate_artifact_bytes")?, ); Ok(()) } fn validate_slug(value: &str, key: &str) -> io::Result<()> { if value.is_empty() || value.len() > 96 || !value .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) { return Err(invalid(&format!("{key} must be an ASCII slug"))); } Ok(()) } fn require_hex64(fields: &HashMap, key: &str) -> io::Result<()> { let value = require_key(fields, key)?; let Some(hex) = value.strip_prefix("0x") else { return Err(invalid(&format!( "manifest key {key} must be a hex checksum" ))); }; if hex.len() != 16 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { return Err(invalid(&format!( "manifest key {key} must be a hex checksum" ))); } Ok(()) } fn require_positive_usize(fields: &HashMap, key: &str) -> io::Result { let value = require_usize(fields, key)?; if value == 0 { return Err(invalid(&format!( "manifest key {key} must be greater than zero" ))); } Ok(value) } fn require_usize(fields: &HashMap, key: &str) -> io::Result { let value = require_key(fields, key)?; value .parse::() .map_err(|_| invalid(&format!("manifest key {key} must be a usize"))) } #[cfg(test)] mod tests { use super::*; use crate::build_model_file_from_values_with_flags; use crate::candidate; use crate::compatibility; use crate::fixture_value; use crate::ledger; use crate::lineage; use crate::multi_candidate; use crate::parent_pool; use crate::population; use crate::promotion; use crate::sign_merge; use crate::tensor_writer::{tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_F32}; use crate::tokenizer_writer::ByteTokenizerSection; use std::time::{SystemTime, UNIX_EPOCH}; struct Fixture { ledger: String, review: String, recipe: String, parents: Vec<(String, Vec)>, admissions: Vec, candidate: Vec, receipt: String, manifest: String, promotion: String, provenance_manifest: String, runtime_smoke: String, eval: String, } #[test] fn writes_and_validates_multi_parent_selector_admission_record() { let fixture = fixture(); let admission = fixture.admission(); validate_record_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", "candidate.operator", &fixture.receipt, &fixture.manifest, &fixture.promotion, &fixture.provenance_manifest, &fixture.runtime_smoke, &fixture.eval, &fixture.admissions, &admission, ) .unwrap(); assert!(admission.contains("admission_kind=multi-parent-sign-merge")); assert!(admission.contains("candidate_id=tiny-alpha-candidate")); assert!(admission.contains("parent_count=3")); assert!(admission.contains("operator_receipt_status=receipt-bound")); assert!(admission.contains("operator_receipt_path=candidate.operator")); assert!(admission.contains("operator_receipt_operator_kind=sign-aware-parent-pool-merge")); assert!(admission.contains("evolution_schedule_checksum=0x")); assert!(admission.contains("scheduled_operator_family_index=0")); assert!(admission.contains("scheduled_operator_family_command=sign-merge-candidate")); assert!(admission.contains("eval_case_evidence_checksum=0x")); assert!(admission.contains("browser_selector_status=admitted")); assert!( admission.contains("required_next_gate=multi-parent-selector-registry-route-binding") ); } #[test] fn rejects_runtime_smoke_drift() { let fixture = fixture(); let admission = fixture.admission(); let changed_smoke = fixture.runtime_smoke.replace( "runtime_smoke_decision=accepted-for-runtime-smoke", "runtime_smoke_decision=pending", ); let error = validate_record_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", "candidate.operator", &fixture.receipt, &fixture.manifest, &fixture.promotion, &fixture.provenance_manifest, &changed_smoke, &fixture.eval, &fixture.admissions, &admission, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("runtime_smoke_decision")); } #[test] fn rejects_eval_manifest_drift() { let fixture = fixture(); let admission = fixture.admission(); let changed_eval = fixture .eval .replace("case.0.actual=e\n", "case.0.actual=x\n"); let error = validate_record_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", "candidate.operator", &fixture.receipt, &fixture.manifest, &fixture.promotion, &fixture.provenance_manifest, &fixture.runtime_smoke, &changed_eval, &fixture.admissions, &admission, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("actual text did not match")); } #[test] fn rejects_admission_overclaim() { let fixture = fixture(); let admission = fixture.admission().replace( "required_next_gate=multi-parent-selector-registry-route-binding", "required_next_gate=browser-loads-selector-registry-entry-models", ); let error = validate_record_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", "candidate.operator", &fixture.receipt, &fixture.manifest, &fixture.promotion, &fixture.provenance_manifest, &fixture.runtime_smoke, &fixture.eval, &fixture.admissions, &admission, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("required_next_gate")); } #[test] fn summary_rejects_operator_receipt_candidate_byte_drift() { let fixture = fixture(); let admission = fixture.admission(); let fields = parse_manifest(&admission, "multi-parent admission").unwrap(); let candidate_bytes = require_key(&fields, "candidate_artifact_bytes").unwrap(); let drifted_bytes = (candidate_bytes.parse::().unwrap() + 1).to_string(); let admission = admission.replace( &format!("operator_receipt_candidate_artifact_bytes={candidate_bytes}"), &format!("operator_receipt_candidate_artifact_bytes={drifted_bytes}"), ); let error = validate_record_summary_text(&admission).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error .to_string() .contains("operator_receipt_candidate_artifact_bytes")); } #[test] fn summary_rejects_scheduled_operator_kind_drift() { let fixture = fixture(); let admission = fixture.admission().replace( "scheduled_operator_family_kind=sign-aware-parent-pool-merge", "scheduled_operator_family_kind=seed-weighted-parent-pool-soup", ); let error = validate_record_summary_text(&admission).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("scheduled_operator_family_kind")); } #[test] fn summary_rejects_incomplete_case_totals() { let fixture = fixture(); let admission = fixture .admission() .replace("cases_passed=1\n", "cases_passed=0\n"); let error = validate_record_summary_text(&admission).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("case totals")); } #[test] fn writes_and_validates_multi_parent_selector_admission_paths() { let dir = unique_dir("paths"); std::fs::create_dir_all(&dir).unwrap(); let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.005); let gamma_bytes = tiny_fixture_f32_bytes_with_offset(0.002); let alpha = fixture_admission( "tiny-alpha-candidate", "target/multi-admission/path-alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/multi-admission/path-beta.slm", &beta_bytes, ); let gamma = fixture_admission( "tiny-gamma-candidate", "target/multi-admission/path-gamma.slm", &gamma_bytes, ); let alpha_slm = dir.join("alpha.slm"); let beta_slm = dir.join("beta.slm"); let gamma_slm = dir.join("gamma.slm"); let alpha_admission = dir.join("alpha.admission"); let beta_admission = dir.join("beta.admission"); let gamma_admission = dir.join("gamma.admission"); let ledger_path = dir.join("pool.ledger"); let review_path = dir.join("pool.review"); let recipe_path = dir.join("pool.recipe"); let candidate_path = dir.join("candidate.slm"); let receipt_path = dir.join("candidate.operator"); let manifest_path = dir.join("candidate.multi"); let promotion_path = dir.join("candidate.multi.promotion"); let provenance_path = dir.join("candidate.manifest"); let runtime_path = dir.join("candidate.runtime"); let eval_path = dir.join("candidate.eval"); let admission_path = dir.join("candidate.multi.admission"); std::fs::write(&alpha_slm, alpha_bytes).unwrap(); std::fs::write(&beta_slm, beta_bytes).unwrap(); std::fs::write(&gamma_slm, gamma_bytes).unwrap(); std::fs::write(&alpha_admission, alpha).unwrap(); std::fs::write(&beta_admission, beta).unwrap(); std::fs::write(&gamma_admission, gamma).unwrap(); let admissions = vec![ alpha_admission.to_string_lossy().to_string(), beta_admission.to_string_lossy().to_string(), gamma_admission.to_string_lossy().to_string(), ]; let parents = vec![ alpha_slm.to_string_lossy().to_string(), beta_slm.to_string_lossy().to_string(), gamma_slm.to_string_lossy().to_string(), ]; ledger::write_ledger_path(&ledger_path, &admissions).unwrap(); population::write_review_path(&ledger_path, &review_path, &admissions).unwrap(); parent_pool::write_recipe_path(&ledger_path, &review_path, &recipe_path, &admissions) .unwrap(); sign_merge::write_candidate_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &parents, &admissions, ) .unwrap(); multi_candidate::write_manifest_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &manifest_path, &parents, &admissions, ) .unwrap(); multi_promotion::write_template_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &manifest_path, &promotion_path, &parents, &admissions, ) .unwrap(); provenance::write_manifest_for_path(&candidate_path, &provenance_path, "converted-trained") .unwrap(); provenance::write_runtime_smoke_for_path(&candidate_path, &provenance_path, &runtime_path) .unwrap(); let report = slm_validate::validate_bytes( &std::fs::read(&candidate_path).unwrap(), &candidate_path.display().to_string(), ) .unwrap(); let provenance_manifest = std::fs::read_to_string(&provenance_path).unwrap(); std::fs::write(&eval_path, passing_eval_text(&report, &provenance_manifest)).unwrap(); write_record_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &manifest_path, &promotion_path, &provenance_path, &runtime_path, &eval_path, &admission_path, &parents, &admissions, ) .unwrap(); validate_record_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &manifest_path, &promotion_path, &provenance_path, &runtime_path, &eval_path, &admission_path, &parents, &admissions, ) .unwrap(); let admission = std::fs::read_to_string(admission_path).unwrap(); assert!(admission.contains("selector_id=browser-local-selector")); assert!(admission.contains("scheduled_operator_family_kind=sign-aware-parent-pool-merge")); assert!(admission.contains("admission_status=admitted-for-browser-selector")); } impl Fixture { fn admission(&self) -> String { build_record_text( &self.ledger, &self.review, &self.recipe, &self.parents, &self.candidate, "candidate.slm", "candidate.operator", &self.receipt, &self.manifest, &self.promotion, &self.provenance_manifest, &self.runtime_smoke, &self.eval, &self.admissions, admission::DEFAULT_ADMISSION_SELECTOR_ID, ) .unwrap() } } fn fixture() -> Fixture { let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.003); let gamma_bytes = tiny_fixture_f32_bytes_with_offset(0.006); let alpha = fixture_admission( "tiny-alpha-candidate", "target/multi-admission/alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/multi-admission/beta.slm", &beta_bytes, ); let gamma = fixture_admission( "tiny-gamma-candidate", "target/multi-admission/gamma.slm", &gamma_bytes, ); let admissions = vec![alpha, beta, gamma]; let ledger = ledger::build_ledger_text(&admissions).unwrap(); let review = population::build_review_text(&ledger, &admissions).unwrap(); let recipe = parent_pool::build_recipe_text(&ledger, &review, &admissions).unwrap(); let parents = vec![ ("alpha.slm".to_string(), alpha_bytes), ("beta.slm".to_string(), beta_bytes), ("gamma.slm".to_string(), gamma_bytes), ]; let (candidate, receipt) = sign_merge::build_candidate_bytes_and_receipt( &ledger, &review, &recipe, &parents, "candidate.slm", &admissions, ) .unwrap(); let manifest = multi_candidate::build_manifest_text( &ledger, &review, &recipe, &parents, &candidate, "candidate.slm", &receipt, &admissions, ) .unwrap(); let promotion = multi_promotion::build_template_text( &ledger, &review, &recipe, &parents, &candidate, "candidate.slm", &receipt, &manifest, &admissions, ) .unwrap(); let report = slm_validate::validate_bytes(&candidate, "candidate.slm").unwrap(); let provenance_manifest = provenance::build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = provenance::parse_manifest(&provenance_manifest).unwrap(); let runtime_smoke = provenance::build_runtime_smoke_text(&report, &provenance_manifest, &manifest_fields) .unwrap(); let eval = passing_eval_text(&report, &provenance_manifest); Fixture { ledger, review, recipe, parents, admissions, candidate, receipt, manifest, promotion, provenance_manifest, runtime_smoke, eval, } } fn fixture_admission(candidate_id: &str, candidate_path: &str, candidate: &[u8]) -> String { let compatibility = compatibility::compatibility_text_for_bytes( candidate, "left.slm", candidate, "right.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, candidate_id, "operator-a", "fit") .unwrap(); let candidate_manifest = candidate::build_manifest_text(&compatibility, &lineage, candidate, candidate_path) .unwrap(); let promotion = promotion::build_template_text( &compatibility, &lineage, candidate, candidate_path, &candidate_manifest, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, ) .unwrap(); let report = slm_validate::validate_bytes(candidate, candidate_path).unwrap(); let provenance_manifest = provenance::build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = provenance::parse_manifest(&provenance_manifest).unwrap(); let runtime_smoke = provenance::build_runtime_smoke_text(&report, &provenance_manifest, &manifest_fields) .unwrap(); let eval = passing_eval_text(&report, &provenance_manifest); admission::build_record_text( &compatibility, &lineage, candidate, candidate_path, &candidate_manifest, &promotion, &provenance_manifest, &runtime_smoke, &eval, admission::DEFAULT_ADMISSION_SELECTOR_ID, ) .unwrap() } fn passing_eval_text(report: &slm_validate::ValidationReport, manifest: &str) -> String { let mut text = String::new(); push_line(&mut text, "tinyrustlm_eval_manifest_version", "1"); push_line(&mut text, "gate", "assistant-quality"); push_line(&mut text, "source_kind", "converted-trained"); push_line( &mut text, "manifest_checksum", &hex64(provenance::text_checksum(manifest.as_bytes())), ); push_line(&mut text, "slm_checksum", &hex64(report.checksum())); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "task_eval_status", "pass"); push_line(&mut text, "safety_review_status", "pass"); push_line( &mut text, "quality_decision", "accepted-for-assistant-quality", ); push_line(&mut text, "quality_scope", "tiny-fixture-runtime-eval-only"); push_line(&mut text, "evaluator", "local-reviewed-eval"); push_line( &mut text, "eval_dataset", "tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", ); push_line( &mut text, "eval_summary", "Reviewed task and safety evidence passed for declared scope", ); push_line( &mut text, "quality_boundary", "fixture-runtime-and-eval-plumbing-not-product-assistant-quality", ); push_line(&mut text, "case_count", "1"); push_line(&mut text, "cases_passed", "1"); push_line(&mut text, "cases_failed", "0"); push_line(&mut text, "case.0.status", "pass"); push_line(&mut text, "case.0.expected", "e"); push_line(&mut text, "case.0.actual", "e"); push_line(&mut text, "case.0.error", "ok"); text } fn tiny_fixture_f32_bytes_with_offset(offset: f32) -> Vec { let tensors = tiny_fixture_tensors_with_dtype(DTYPE_F32); let values: Vec> = tensors .iter() .map(|tensor| { (0..tensor.element_count()) .map(|elem| fixture_value(tensor, elem) + offset) .collect() }) .collect(); build_model_file_from_values_with_flags( &ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } fn unique_dir(label: &str) -> std::path::PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-multi-admission-{label}-{nanos}")) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/multi_admission.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/multi_candidate.rs BYTES: 39031 SHA256: 0AD36F832C4111B2CB3F4029A9D39C1BD99E04E9FAFAA078C6FD3B6D8A055D3F ================================================================================ //! Candidate manifests for validated parent-pool operator outputs. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::blend::{hex64, invalid, parse_manifest, push_line, require_equal, require_key}; use crate::provenance; use crate::sign_merge; use crate::slm_validate::{self, ValidationReport}; use crate::soup; const MANIFEST_VERSION: &str = "1"; const MANIFEST_SCOPE: &str = "offline-model-breeding-multi-parent-candidate"; const MANIFEST_STATUS: &str = "validated-parent-pool-operator-output"; const ARTIFACT_KIND: &str = "slm"; const CANDIDATE_STATUS: &str = "artifact-written"; const CANDIDATE_ARTIFACT_STATUS: &str = "written"; const CANDIDATE_ADMISSION_STATUS: &str = "slm-validated"; const CANDIDATE_EVAL_STATUS: &str = "pending"; const PROMOTION_STATUS: &str = "pending"; const REQUIRED_NEXT_GATE: &str = "multi-parent-promotion-template-plus-runtime-smoke-plus-eval"; const RECEIPT_KEYS: [&str; 33] = [ "operator_kind", "operator_status", "operator_output_status", "recipe_kind", "parent_pool_recipe_checksum", "evolution_recipe_version", "evolution_recipe_strategy", "evolution_recipe_status", "evolution_selection_source", "evolution_relatedness_contract_checksum", "evolution_schedule_checksum_algorithm", "evolution_schedule_checksum", "scheduled_operator_family_index", "scheduled_operator_family_kind", "scheduled_operator_family_command", "scheduled_operator_family_selection_rule", "scheduled_operator_family_output_gate", "population_review_checksum", "promotion_ledger_checksum", "admission_set_checksum", "frontier_candidate_id", "frontier_candidate_slm_checksum", "parent_contract_status", "contract_model_shape", "contract_quantization", "contract_output_contract", "contract_tokenizer_checksum", "contract_tensor_layout_checksum", "relatedness_metric", "relatedness_scope", "relatedness_pair_count", "relatedness_all_pairs_status", "relatedness_contract_checksum", ]; const PARENT_KEYS: [&str; 26] = [ "rank", "role", "selection_status", "source_review_entry", "source_ledger_entry", "candidate_id", "selector_id", "operator_id", "resource_budget", "recipe_candidate_artifact_path", "actual_path", "model_bytes", "slm_version", "slm_checksum", "model_shape", "tensor_count", "parameter_count", "quantization", "output_contract", "tokenizer_checksum", "tensor_layout_checksum", "relatedness_group", "relatedness_contract_checksum", "population_fitness_ppm", "seed_weight_ppm", "next_route", ]; const SIGN_KEYS: [&str; 12] = [ "base_parent_index", "sign_selection_rule", "delta_merge_rule", "sign_total_parameter_count", "sign_participating_parent_count", "sign_delta_observation_count", "sign_nonzero_delta_observation_count", "sign_zero_delta_observation_count", "sign_positive_parameter_count", "sign_negative_parameter_count", "sign_neutral_parameter_count", "sign_selected_delta_observation_count", ]; const SOUP_KEYS: [&str; 9] = [ "base_parent_index", "soup_merge_rule", "soup_weight_source", "soup_weight_unit", "soup_total_parameter_count", "soup_parent_weight_checksum", "soup_weighted_value_checksum", "soup_changed_from_frontier_count", "soup_changed_from_frontier_density_ppm", ]; #[derive(Clone, Copy)] enum ParentPoolOperator { SignMerge, Soup, } impl ParentPoolOperator { // Classifies a parent-pool receipt so recomputation uses the owning operator module. fn from_receipt(receipt: &HashMap) -> io::Result { match require_key(receipt, "operator_kind")? { "sign-aware-parent-pool-merge" => Ok(Self::SignMerge), "seed-weighted-parent-pool-soup" => Ok(Self::Soup), other => Err(invalid(&format!( "unsupported multi-parent operator_kind: {other}" ))), } } // Checks version and kind fields that identify the concrete parent-pool operator. fn validate_identity(self, receipt: &HashMap) -> io::Result<()> { match self { Self::SignMerge => { require_equal(receipt, "tinyrustlm_sign_merge_operator_version", "1")?; require_equal(receipt, "operator_kind", "sign-aware-parent-pool-merge")?; } Self::Soup => { require_equal(receipt, "tinyrustlm_soup_operator_version", "1")?; require_equal(receipt, "operator_kind", "seed-weighted-parent-pool-soup")?; } } Ok(()) } // Recomputes candidate bytes and receipt text through the operator that produced them. fn validate_candidate_text( self, ledger_text: &str, review_text: &str, recipe_text: &str, parent_bytes: &[(String, Vec)], candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, admission_texts: &[String], ) -> io::Result<()> { match self { Self::SignMerge => sign_merge::validate_candidate_text( ledger_text, review_text, recipe_text, parent_bytes, candidate_bytes, candidate_path, receipt_text, admission_texts, ), Self::Soup => soup::validate_candidate_text( ledger_text, review_text, recipe_text, parent_bytes, candidate_bytes, candidate_path, receipt_text, admission_texts, ), } } } /// Writes a manifest for a parent-pool candidate after recomputing its full input chain. pub(crate) fn write_manifest_path( ledger: &Path, review: &Path, recipe: &Path, candidate_slm: &Path, receipt: &Path, output: &Path, parent_paths: &[String], admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_texts(admission_paths, "multi-parent-candidate admissions")?; let parent_bytes = read_bytes(parent_paths, "multi-parent-candidate parents")?; let ledger_text = fs::read_to_string(ledger)?; let review_text = fs::read_to_string(review)?; let recipe_text = fs::read_to_string(recipe)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; let manifest = build_manifest_text( &ledger_text, &review_text, &recipe_text, &parent_bytes, &candidate_bytes, &candidate_slm.display().to_string(), &receipt_text, &admission_texts, )?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, manifest)?; println!( "SLM multi-parent candidate manifest written: {}", output.display() ); Ok(()) } /// Validates a multi-parent candidate manifest against the parent-pool operator evidence chain. pub(crate) fn validate_manifest_path( ledger: &Path, review: &Path, recipe: &Path, candidate_slm: &Path, receipt: &Path, manifest: &Path, parent_paths: &[String], admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_texts( admission_paths, "validate-multi-parent-candidate admissions", )?; let parent_bytes = read_bytes(parent_paths, "validate-multi-parent-candidate parents")?; let ledger_text = fs::read_to_string(ledger)?; let review_text = fs::read_to_string(review)?; let recipe_text = fs::read_to_string(recipe)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; let manifest_text = fs::read_to_string(manifest)?; validate_manifest_text( &ledger_text, &review_text, &recipe_text, &parent_bytes, &candidate_bytes, &candidate_slm.display().to_string(), &receipt_text, &manifest_text, &admission_texts, )?; println!("SLM multi-parent candidate manifest validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("receipt: {}", receipt.display()); println!("manifest: {}", manifest.display()); Ok(()) } fn read_texts(paths: &[String], label: &str) -> io::Result> { if paths.is_empty() { return Err(invalid(&format!("{label} require at least one input"))); } paths .iter() .map(|path| fs::read_to_string(Path::new(path))) .collect() } fn read_bytes(paths: &[String], label: &str) -> io::Result)>> { if paths.len() < 2 { return Err(invalid(&format!( "{label} require at least two parent models" ))); } paths .iter() .map(|path| Ok((path.clone(), fs::read(Path::new(path))?))) .collect() } pub(crate) fn build_manifest_text( ledger_text: &str, review_text: &str, recipe_text: &str, parent_bytes: &[(String, Vec)], candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, admission_texts: &[String], ) -> io::Result { let receipt = parse_manifest(receipt_text, "parent-pool operator receipt")?; let operator = ParentPoolOperator::from_receipt(&receipt)?; operator.validate_candidate_text( ledger_text, review_text, recipe_text, parent_bytes, candidate_bytes, candidate_path, receipt_text, admission_texts, )?; let recipe = parse_manifest(recipe_text, "parent-pool recipe")?; let report = slm_validate::validate_bytes(candidate_bytes, candidate_path)?; validate_receipt_and_recipe( operator, &receipt, &recipe, &report, receipt_text, recipe_text, )?; let parent_count = parse_parent_count(&receipt)?; let mut text = String::new(); push_line( &mut text, "tinyrustlm_multi_parent_candidate_manifest_version", MANIFEST_VERSION, ); push_line(&mut text, "candidate_manifest_scope", MANIFEST_SCOPE); push_line(&mut text, "candidate_manifest_status", MANIFEST_STATUS); push_line(&mut text, "candidate_status", CANDIDATE_STATUS); push_line(&mut text, "artifact_kind", ARTIFACT_KIND); for key in RECEIPT_KEYS { push_line(&mut text, key, require_key(&receipt, key)?); } push_line( &mut text, "operator_receipt_checksum", &hex64(provenance::text_checksum(receipt_text.as_bytes())), ); push_line(&mut text, "parent_count", &parent_count.to_string()); for index in 0..parent_count { push_parent_lines(&mut text, &receipt, index)?; } push_operator_specific_lines(&mut text, operator, &receipt)?; push_candidate_lines(&mut text, &report); push_line( &mut text, "candidate_parent_contract", require_key(&receipt, "candidate_parent_contract")?, ); push_line( &mut text, "candidate_artifact_status", CANDIDATE_ARTIFACT_STATUS, ); push_line( &mut text, "candidate_admission_status", CANDIDATE_ADMISSION_STATUS, ); push_line(&mut text, "candidate_eval_status", CANDIDATE_EVAL_STATUS); push_line(&mut text, "promotion_status", PROMOTION_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } pub(crate) fn validate_manifest_text( ledger_text: &str, review_text: &str, recipe_text: &str, parent_bytes: &[(String, Vec)], candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, manifest_text: &str, admission_texts: &[String], ) -> io::Result<()> { let manifest = parse_manifest(manifest_text, "multi-parent candidate manifest")?; require_equal( &manifest, "tinyrustlm_multi_parent_candidate_manifest_version", MANIFEST_VERSION, )?; require_equal(&manifest, "candidate_manifest_status", MANIFEST_STATUS)?; let expected = build_manifest_text( ledger_text, review_text, recipe_text, parent_bytes, candidate_bytes, candidate_path, receipt_text, admission_texts, )?; if manifest_text != expected { return Err(invalid( "multi-parent candidate manifest fields do not match recomputed output", )); } Ok(()) } fn validate_receipt_and_recipe( operator: ParentPoolOperator, receipt: &HashMap, recipe: &HashMap, report: &ValidationReport, receipt_text: &str, recipe_text: &str, ) -> io::Result<()> { operator.validate_identity(receipt)?; require_equal(receipt, "operator_status", "candidate-written")?; require_equal(receipt, "operator_output_status", "slm-validated")?; require_equal( receipt, "candidate_parent_contract", "matches-parent-pool-direct-parameter-contract", )?; require_equal( receipt, "required_next_gate", "multi-parent-candidate-manifest-plus-runtime-smoke-plus-eval", )?; require_equal(recipe, "tinyrustlm_parent_pool_recipe_version", "1")?; require_equal(recipe, "recipe_kind", "sign-aware-parent-pool-v1")?; for key in [ "relatedness_metric", "relatedness_scope", "relatedness_pair_count", "relatedness_all_pairs_status", "relatedness_contract_checksum", "evolution_recipe_version", "evolution_recipe_strategy", "evolution_recipe_status", "evolution_selection_source", "evolution_relatedness_contract_checksum", "evolution_schedule_checksum_algorithm", "evolution_schedule_checksum", ] { require_equal(receipt, key, require_key(recipe, key)?)?; } validate_scheduled_family_fields(operator, receipt, recipe)?; require_equal( receipt, "parent_pool_recipe_checksum", &hex64(provenance::text_checksum(recipe_text.as_bytes())), )?; require_equal(receipt, "candidate_artifact_path", report.path())?; require_equal(receipt, "candidate_slm_checksum", &hex64(report.checksum()))?; require_equal( receipt, "candidate_tensor_layout_checksum", &hex64(report.tensor_layout_checksum()), )?; require_key(receipt, "candidate_artifact_bytes")?; require_key(receipt, "candidate_model_shape")?; require_key(receipt, "candidate_quantization")?; require_key(receipt, "candidate_output_contract")?; require_key(receipt, "candidate_tokenizer_checksum")?; validate_operator_specific_fields(operator, receipt)?; require_key(receipt, "parent_count")?; require_key(receipt, "operator_kind")?; require_key(receipt, "operator_status")?; require_key(receipt, "operator_output_status")?; if receipt_text.is_empty() { return Err(invalid("parent-pool operator receipt is empty")); } Ok(()) } // Confirms that the receipt points at the same scheduled operator family as the recipe. fn validate_scheduled_family_fields( operator: ParentPoolOperator, receipt: &HashMap, recipe: &HashMap, ) -> io::Result<()> { let index = require_key(receipt, "scheduled_operator_family_index")? .parse::() .map_err(|_| invalid("scheduled_operator_family_index must be an integer"))?; let family_count = require_key(recipe, "evolution_operator_family_count")? .parse::() .map_err(|_| invalid("evolution_operator_family_count must be an integer"))?; if index >= family_count { return Err(invalid( "scheduled operator family index is outside the recipe family count", )); } let (expected_kind, expected_command, expected_selection_rule) = match operator { ParentPoolOperator::SignMerge => ( "sign-aware-parent-pool-merge", "sign-merge-candidate", "seed-weighted-delta-sign-consensus", ), ParentPoolOperator::Soup => ( "seed-weighted-parent-pool-soup", "soup-candidate", "seed-weighted-direct-parameter-average", ), }; require_equal(receipt, "scheduled_operator_family_kind", expected_kind)?; require_equal( receipt, "scheduled_operator_family_command", expected_command, )?; require_equal( receipt, "scheduled_operator_family_selection_rule", expected_selection_rule, )?; require_equal( receipt, "scheduled_operator_family_output_gate", "multi-parent-candidate-manifest-plus-runtime-smoke-plus-eval", )?; let prefix = format!("evolution_operator_family.{index}"); require_equal(recipe, &format!("{prefix}.operator_kind"), expected_kind)?; require_equal(recipe, &format!("{prefix}.command"), expected_command)?; require_equal( recipe, &format!("{prefix}.selection_rule"), expected_selection_rule, )?; require_equal( recipe, &format!("{prefix}.output_gate"), "multi-parent-candidate-manifest-plus-runtime-smoke-plus-eval", )?; Ok(()) } fn push_operator_specific_lines( text: &mut String, operator: ParentPoolOperator, receipt: &HashMap, ) -> io::Result<()> { match operator { ParentPoolOperator::SignMerge => { for key in SIGN_KEYS { push_line(text, key, require_key(receipt, key)?); } push_line( text, "sign_rejected_delta_observation_count", require_key(receipt, "sign_rejected_delta_observation_count")?, ); } ParentPoolOperator::Soup => { for key in SOUP_KEYS { push_line(text, key, require_key(receipt, key)?); } } } Ok(()) } fn validate_operator_specific_fields( operator: ParentPoolOperator, receipt: &HashMap, ) -> io::Result<()> { match operator { ParentPoolOperator::SignMerge => { for key in SIGN_KEYS { require_key(receipt, key)?; } require_key(receipt, "sign_rejected_delta_observation_count")?; } ParentPoolOperator::Soup => { for key in SOUP_KEYS { require_key(receipt, key)?; } } } Ok(()) } fn parse_parent_count(receipt: &HashMap) -> io::Result { let parent_count = require_key(receipt, "parent_count")? .parse::() .map_err(|_| invalid("multi-parent candidate parent_count must be an integer"))?; if parent_count < 2 { return Err(invalid( "multi-parent candidate manifest requires at least two parents", )); } Ok(parent_count) } fn push_parent_lines( text: &mut String, receipt: &HashMap, index: usize, ) -> io::Result<()> { for key in PARENT_KEYS { let full_key = format!("parent.{index}.{key}"); push_line(text, &full_key, require_key(receipt, &full_key)?); } Ok(()) } fn push_candidate_lines(text: &mut String, report: &ValidationReport) { push_line(text, "candidate_artifact_path", report.path()); push_line( text, "candidate_artifact_bytes", &report.file_bytes().to_string(), ); push_line( text, "candidate_slm_version", &report.slm_version().to_string(), ); push_line(text, "candidate_slm_checksum", &hex64(report.checksum())); push_line(text, "candidate_model_shape", &report.shape_summary()); push_line( text, "candidate_tensor_count", &report.tensor_count().to_string(), ); push_line( text, "candidate_parameter_count", &report.parameter_count().to_string(), ); push_line(text, "candidate_quantization", report.quantization_label()); push_line( text, "candidate_output_contract", report.output_contract_label(), ); push_line( text, "candidate_tokenizer_checksum", &hex64(report.tokenizer_checksum()), ); push_line( text, "candidate_tensor_layout_checksum", &hex64(report.tensor_layout_checksum()), ); } #[cfg(test)] mod tests { use super::*; use crate::admission; use crate::build_model_file_from_values_with_flags; use crate::candidate; use crate::compatibility; use crate::fixture_value; use crate::ledger; use crate::lineage; use crate::parent_pool; use crate::population; use crate::promotion; use crate::soup; use crate::tensor_writer::{tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_F32}; use crate::tokenizer_writer::ByteTokenizerSection; use std::time::{SystemTime, UNIX_EPOCH}; struct Fixture { ledger: String, review: String, recipe: String, parents: Vec<(String, Vec)>, admissions: Vec, candidate: Vec, receipt: String, } #[test] fn writes_and_validates_multi_parent_candidate_manifest_text() { let fixture = fixture(); let manifest = build_manifest_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &fixture.receipt, &fixture.admissions, ) .unwrap(); validate_manifest_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &fixture.receipt, &manifest, &fixture.admissions, ) .unwrap(); assert!( manifest.contains("candidate_manifest_status=validated-parent-pool-operator-output") ); assert!(manifest.contains("operator_receipt_checksum=0x")); assert!(manifest.contains("operator_kind=sign-aware-parent-pool-merge")); assert!(manifest.contains("evolution_schedule_checksum=0x")); assert!(manifest.contains("scheduled_operator_family_index=0")); assert!(manifest.contains("scheduled_operator_family_command=sign-merge-candidate")); assert!(manifest.contains("sign_selection_rule=seed-weighted-delta-sign-consensus")); assert!(manifest.contains("candidate_eval_status=pending")); assert!(manifest.contains("promotion_status=pending")); assert!(manifest.contains( "required_next_gate=multi-parent-promotion-template-plus-runtime-smoke-plus-eval" )); } #[test] fn writes_and_validates_multi_parent_soup_candidate_manifest_text() { let fixture = soup_fixture(); let manifest = build_manifest_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &fixture.receipt, &fixture.admissions, ) .unwrap(); validate_manifest_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &fixture.receipt, &manifest, &fixture.admissions, ) .unwrap(); assert!( manifest.contains("candidate_manifest_status=validated-parent-pool-operator-output") ); assert!(manifest.contains("operator_kind=seed-weighted-parent-pool-soup")); assert!(manifest.contains("evolution_schedule_checksum=0x")); assert!(manifest.contains("scheduled_operator_family_index=1")); assert!(manifest.contains("scheduled_operator_family_command=soup-candidate")); assert!(manifest.contains("soup_merge_rule=seed-weighted-direct-parameter-average")); assert!(manifest.contains("soup_parent_weight_checksum=0x")); assert!(manifest.contains("soup_weighted_value_checksum=0x")); assert!(!manifest.contains("sign_selection_rule=")); } #[test] fn rejects_unsupported_parent_pool_operator_kind() { let fixture = soup_fixture(); let receipt = fixture.receipt.replace( "operator_kind=seed-weighted-parent-pool-soup", "operator_kind=unknown-parent-pool-operator", ); let error = build_manifest_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &receipt, &fixture.admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator_kind")); } #[test] fn rejects_soup_receipt_version_drift() { let fixture = soup_fixture(); let receipt = fixture.receipt.replace( "tinyrustlm_soup_operator_version=1", "tinyrustlm_soup_operator_version=2", ); let error = build_manifest_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &receipt, &fixture.admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error .to_string() .contains("tinyrustlm_soup_operator_version")); } #[test] fn validation_rejects_manifest_drift() { let fixture = fixture(); let manifest = build_manifest_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &fixture.receipt, &fixture.admissions, ) .unwrap() .replace( "candidate_eval_status=pending", "candidate_eval_status=pass", ); let error = validate_manifest_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &fixture.receipt, &manifest, &fixture.admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("manifest fields")); } #[test] fn validation_rejects_receipt_drift() { let fixture = fixture(); let manifest = build_manifest_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &fixture.receipt, &fixture.admissions, ) .unwrap(); let receipt = fixture.receipt.replace( "operator_status=candidate-written", "operator_status=manual", ); let error = validate_manifest_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &receipt, &manifest, &fixture.admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("receipt fields")); } #[test] fn rejects_candidate_that_breaks_receipt_contract() { let fixture = fixture(); let mut candidate = fixture.candidate.clone(); let last = candidate.len() - 1; candidate[last] ^= 0x01; let error = build_manifest_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &candidate, "candidate.slm", &fixture.receipt, &fixture.admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate bytes")); } #[test] fn writes_and_validates_multi_parent_candidate_manifest_paths() { let dir = unique_dir("paths"); std::fs::create_dir_all(&dir).unwrap(); let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.005); let gamma_bytes = tiny_fixture_f32_bytes_with_offset(0.002); let alpha = fixture_admission( "tiny-alpha-candidate", "target/multi-candidate/path-alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/multi-candidate/path-beta.slm", &beta_bytes, ); let gamma = fixture_admission( "tiny-gamma-candidate", "target/multi-candidate/path-gamma.slm", &gamma_bytes, ); let alpha_slm = dir.join("alpha.slm"); let beta_slm = dir.join("beta.slm"); let gamma_slm = dir.join("gamma.slm"); let alpha_admission = dir.join("alpha.admission"); let beta_admission = dir.join("beta.admission"); let gamma_admission = dir.join("gamma.admission"); let ledger_path = dir.join("pool.ledger"); let review_path = dir.join("pool.review"); let recipe_path = dir.join("pool.recipe"); let candidate_path = dir.join("candidate.slm"); let receipt_path = dir.join("candidate.operator"); let manifest_path = dir.join("candidate.multi"); std::fs::write(&alpha_slm, alpha_bytes).unwrap(); std::fs::write(&beta_slm, beta_bytes).unwrap(); std::fs::write(&gamma_slm, gamma_bytes).unwrap(); std::fs::write(&alpha_admission, alpha).unwrap(); std::fs::write(&beta_admission, beta).unwrap(); std::fs::write(&gamma_admission, gamma).unwrap(); let admissions = vec![ alpha_admission.to_string_lossy().to_string(), beta_admission.to_string_lossy().to_string(), gamma_admission.to_string_lossy().to_string(), ]; let parents = vec![ alpha_slm.to_string_lossy().to_string(), beta_slm.to_string_lossy().to_string(), gamma_slm.to_string_lossy().to_string(), ]; ledger::write_ledger_path(&ledger_path, &admissions).unwrap(); population::write_review_path(&ledger_path, &review_path, &admissions).unwrap(); parent_pool::write_recipe_path(&ledger_path, &review_path, &recipe_path, &admissions) .unwrap(); sign_merge::write_candidate_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &parents, &admissions, ) .unwrap(); write_manifest_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &manifest_path, &parents, &admissions, ) .unwrap(); validate_manifest_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &manifest_path, &parents, &admissions, ) .unwrap(); let manifest = std::fs::read_to_string(manifest_path).unwrap(); assert!(manifest.contains("parent_count=3")); slm_validate::validate_path(&candidate_path).unwrap(); } fn fixture() -> Fixture { fixture_with_operator(false) } fn soup_fixture() -> Fixture { fixture_with_operator(true) } fn fixture_with_operator(use_soup: bool) -> Fixture { let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.003); let gamma_bytes = tiny_fixture_f32_bytes_with_offset(0.006); let alpha = fixture_admission( "tiny-alpha-candidate", "target/multi-candidate/alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/multi-candidate/beta.slm", &beta_bytes, ); let gamma = fixture_admission( "tiny-gamma-candidate", "target/multi-candidate/gamma.slm", &gamma_bytes, ); let admissions = vec![alpha, beta, gamma]; let ledger = ledger::build_ledger_text(&admissions).unwrap(); let review = population::build_review_text(&ledger, &admissions).unwrap(); let recipe = parent_pool::build_recipe_text(&ledger, &review, &admissions).unwrap(); let parents = vec![ ("alpha.slm".to_string(), alpha_bytes), ("beta.slm".to_string(), beta_bytes), ("gamma.slm".to_string(), gamma_bytes), ]; let (candidate, receipt) = if use_soup { soup::build_candidate_bytes_and_receipt( &ledger, &review, &recipe, &parents, "candidate.slm", &admissions, ) .unwrap() } else { sign_merge::build_candidate_bytes_and_receipt( &ledger, &review, &recipe, &parents, "candidate.slm", &admissions, ) .unwrap() }; Fixture { ledger, review, recipe, parents, admissions, candidate, receipt, } } fn fixture_admission(candidate_id: &str, candidate_path: &str, candidate: &[u8]) -> String { let compatibility = compatibility::compatibility_text_for_bytes( candidate, "left.slm", candidate, "right.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, candidate_id, "operator-a", "fit") .unwrap(); let candidate_manifest = candidate::build_manifest_text(&compatibility, &lineage, candidate, candidate_path) .unwrap(); let promotion = promotion::build_template_text( &compatibility, &lineage, candidate, candidate_path, &candidate_manifest, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, ) .unwrap(); let report = slm_validate::validate_bytes(candidate, candidate_path).unwrap(); let provenance_manifest = provenance::build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = provenance::parse_manifest(&provenance_manifest).unwrap(); let runtime_smoke = provenance::build_runtime_smoke_text(&report, &provenance_manifest, &manifest_fields) .unwrap(); let eval = passing_eval_text(&report, &provenance_manifest); admission::build_record_text( &compatibility, &lineage, candidate, candidate_path, &candidate_manifest, &promotion, &provenance_manifest, &runtime_smoke, &eval, admission::DEFAULT_ADMISSION_SELECTOR_ID, ) .unwrap() } fn passing_eval_text(report: &slm_validate::ValidationReport, manifest: &str) -> String { let mut text = String::new(); push_line(&mut text, "tinyrustlm_eval_manifest_version", "1"); push_line(&mut text, "gate", "assistant-quality"); push_line(&mut text, "source_kind", "converted-trained"); push_line( &mut text, "manifest_checksum", &hex64(provenance::text_checksum(manifest.as_bytes())), ); push_line(&mut text, "slm_checksum", &hex64(report.checksum())); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "task_eval_status", "pass"); push_line(&mut text, "safety_review_status", "pass"); push_line( &mut text, "quality_decision", "accepted-for-assistant-quality", ); push_line(&mut text, "quality_scope", "tiny-fixture-runtime-eval-only"); push_line(&mut text, "evaluator", "local-reviewed-eval"); push_line( &mut text, "eval_dataset", "tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", ); push_line( &mut text, "eval_summary", "Reviewed task and safety evidence passed for declared scope", ); push_line( &mut text, "quality_boundary", "fixture-runtime-and-eval-plumbing-not-product-assistant-quality", ); push_line(&mut text, "case_count", "1"); push_line(&mut text, "cases_passed", "1"); push_line(&mut text, "cases_failed", "0"); push_line(&mut text, "case.0.status", "pass"); push_line(&mut text, "case.0.expected", "e"); push_line(&mut text, "case.0.actual", "e"); push_line(&mut text, "case.0.error", "ok"); text } fn tiny_fixture_f32_bytes_with_offset(offset: f32) -> Vec { let tensors = tiny_fixture_tensors_with_dtype(DTYPE_F32); let values: Vec> = tensors .iter() .map(|tensor| { (0..tensor.element_count()) .map(|elem| fixture_value(tensor, elem) + offset) .collect() }) .collect(); build_model_file_from_values_with_flags( &ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } fn unique_dir(label: &str) -> std::path::PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-multi-candidate-{label}-{nanos}")) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/multi_candidate.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/multi_promotion.rs BYTES: 25581 SHA256: 60CDDEF2EF0D07C64CA0E9CCF546ED7A726D6B44B3B7220946AC7A8C2C143DBF ================================================================================ //! Promotion templates for validated multi-parent parent-pool candidates. use std::fs; use std::io; use std::path::Path; use crate::blend::{hex64, invalid, parse_manifest, push_line, require_equal, require_key}; use crate::multi_candidate; use crate::promotion; use crate::provenance; const PROMOTION_VERSION: &str = "1"; const PROMOTION_KIND: &str = "multi-parent-sign-merge"; const PROMOTION_STATUS: &str = "pending-runtime-smoke-and-eval"; const PROMOTER_ID: &str = "local-smoke-runner"; const RUNTIME_SMOKE_STATUS: &str = "pending"; const EVAL_STATUS: &str = "pending"; const PROMOTION_DECISION: &str = "pending"; const BROWSER_SELECTOR_STATUS: &str = "not-admitted"; const PUBLIC_CLAIM_STATUS: &str = "not-admitted"; const REQUIRED_NEXT_GATE: &str = "run-runtime-smoke-and-eval-before-multi-parent-admission"; const CANDIDATE_KEYS: [&str; 11] = [ "candidate_artifact_path", "candidate_artifact_bytes", "candidate_slm_version", "candidate_slm_checksum", "candidate_model_shape", "candidate_tensor_count", "candidate_parameter_count", "candidate_quantization", "candidate_output_contract", "candidate_tokenizer_checksum", "candidate_tensor_layout_checksum", ]; const SCHEDULE_KEYS: [&str; 12] = [ "evolution_recipe_version", "evolution_recipe_strategy", "evolution_recipe_status", "evolution_selection_source", "evolution_relatedness_contract_checksum", "evolution_schedule_checksum_algorithm", "evolution_schedule_checksum", "scheduled_operator_family_index", "scheduled_operator_family_kind", "scheduled_operator_family_command", "scheduled_operator_family_selection_rule", "scheduled_operator_family_output_gate", ]; /// Writes a promotion template for a validated multi-parent candidate manifest. pub(crate) fn write_template_path( ledger: &Path, review: &Path, recipe: &Path, candidate_slm: &Path, receipt: &Path, candidate_manifest: &Path, output: &Path, parent_paths: &[String], admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_texts(admission_paths, "multi-parent-promotion admissions")?; let parent_bytes = read_bytes(parent_paths, "multi-parent-promotion parents")?; let ledger_text = fs::read_to_string(ledger)?; let review_text = fs::read_to_string(review)?; let recipe_text = fs::read_to_string(recipe)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; let candidate_manifest_text = fs::read_to_string(candidate_manifest)?; let promotion_text = build_template_text( &ledger_text, &review_text, &recipe_text, &parent_bytes, &candidate_bytes, &candidate_slm.display().to_string(), &receipt_text, &candidate_manifest_text, &admission_texts, )?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, promotion_text)?; println!( "SLM multi-parent promotion template written: {}", output.display() ); Ok(()) } /// Validates a multi-parent promotion template against its complete evidence chain. pub(crate) fn validate_template_path( ledger: &Path, review: &Path, recipe: &Path, candidate_slm: &Path, receipt: &Path, candidate_manifest: &Path, promotion: &Path, parent_paths: &[String], admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_texts( admission_paths, "validate-multi-parent-promotion admissions", )?; let parent_bytes = read_bytes(parent_paths, "validate-multi-parent-promotion parents")?; let ledger_text = fs::read_to_string(ledger)?; let review_text = fs::read_to_string(review)?; let recipe_text = fs::read_to_string(recipe)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; let candidate_manifest_text = fs::read_to_string(candidate_manifest)?; let promotion_text = fs::read_to_string(promotion)?; validate_template_text( &ledger_text, &review_text, &recipe_text, &parent_bytes, &candidate_bytes, &candidate_slm.display().to_string(), &receipt_text, &candidate_manifest_text, &promotion_text, &admission_texts, )?; println!("SLM multi-parent promotion validation: PASS"); println!("candidate_manifest: {}", candidate_manifest.display()); println!("promotion: {}", promotion.display()); Ok(()) } fn read_texts(paths: &[String], label: &str) -> io::Result> { if paths.is_empty() { return Err(invalid(&format!("{label} require at least one input"))); } paths .iter() .map(|path| fs::read_to_string(Path::new(path))) .collect() } fn read_bytes(paths: &[String], label: &str) -> io::Result)>> { if paths.len() < 2 { return Err(invalid(&format!( "{label} require at least two parent models" ))); } paths .iter() .map(|path| Ok((path.clone(), fs::read(Path::new(path))?))) .collect() } pub(crate) fn build_template_text( ledger_text: &str, review_text: &str, recipe_text: &str, parent_bytes: &[(String, Vec)], candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, candidate_manifest_text: &str, admission_texts: &[String], ) -> io::Result { multi_candidate::validate_manifest_text( ledger_text, review_text, recipe_text, parent_bytes, candidate_bytes, candidate_path, receipt_text, candidate_manifest_text, admission_texts, )?; let candidate_fields = parse_manifest(candidate_manifest_text, "multi-parent candidate manifest")?; let mut text = String::new(); push_line( &mut text, "tinyrustlm_multi_parent_promotion_version", PROMOTION_VERSION, ); push_line(&mut text, "promotion_kind", PROMOTION_KIND); push_line(&mut text, "promotion_status", PROMOTION_STATUS); push_line(&mut text, "promoter_id", PROMOTER_ID); push_line( &mut text, "promotion_scope", promotion::DEFAULT_PROMOTION_SCOPE, ); push_line( &mut text, "candidate_manifest_checksum", &hex64(provenance::text_checksum( candidate_manifest_text.as_bytes(), )), ); push_line( &mut text, "operator_receipt_checksum", require_key(&candidate_fields, "operator_receipt_checksum")?, ); push_line( &mut text, "parent_pool_recipe_checksum", require_key(&candidate_fields, "parent_pool_recipe_checksum")?, ); push_line( &mut text, "population_review_checksum", require_key(&candidate_fields, "population_review_checksum")?, ); push_line( &mut text, "promotion_ledger_checksum", require_key(&candidate_fields, "promotion_ledger_checksum")?, ); push_line( &mut text, "admission_set_checksum", require_key(&candidate_fields, "admission_set_checksum")?, ); push_line( &mut text, "frontier_candidate_id", require_key(&candidate_fields, "frontier_candidate_id")?, ); push_line( &mut text, "frontier_candidate_slm_checksum", require_key(&candidate_fields, "frontier_candidate_slm_checksum")?, ); push_line( &mut text, "parent_count", require_key(&candidate_fields, "parent_count")?, ); push_line( &mut text, "operator_kind", require_key(&candidate_fields, "operator_kind")?, ); push_line( &mut text, "operator_output_status", require_key(&candidate_fields, "operator_output_status")?, ); for key in SCHEDULE_KEYS { push_line(&mut text, key, require_key(&candidate_fields, key)?); } for key in CANDIDATE_KEYS { push_line(&mut text, key, require_key(&candidate_fields, key)?); } push_line( &mut text, "candidate_parent_contract", require_key(&candidate_fields, "candidate_parent_contract")?, ); push_line( &mut text, "candidate_admission_status", require_key(&candidate_fields, "candidate_admission_status")?, ); push_line(&mut text, "runtime_smoke_status", RUNTIME_SMOKE_STATUS); push_line(&mut text, "eval_status", EVAL_STATUS); push_line(&mut text, "promotion_decision", PROMOTION_DECISION); push_line( &mut text, "browser_selector_status", BROWSER_SELECTOR_STATUS, ); push_line(&mut text, "public_claim_status", PUBLIC_CLAIM_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } pub(crate) fn validate_template_text( ledger_text: &str, review_text: &str, recipe_text: &str, parent_bytes: &[(String, Vec)], candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, candidate_manifest_text: &str, promotion_text: &str, admission_texts: &[String], ) -> io::Result<()> { let promotion = parse_manifest(promotion_text, "multi-parent promotion")?; require_equal( &promotion, "tinyrustlm_multi_parent_promotion_version", PROMOTION_VERSION, )?; require_equal(&promotion, "promotion_kind", PROMOTION_KIND)?; require_equal(&promotion, "promotion_status", PROMOTION_STATUS)?; let expected = build_template_text( ledger_text, review_text, recipe_text, parent_bytes, candidate_bytes, candidate_path, receipt_text, candidate_manifest_text, admission_texts, )?; if promotion_text != expected { return Err(invalid( "multi-parent promotion fields do not match recomputed output", )); } Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::admission; use crate::build_model_file_from_values_with_flags; use crate::candidate; use crate::compatibility; use crate::fixture_value; use crate::ledger; use crate::lineage; use crate::parent_pool; use crate::population; use crate::promotion; use crate::sign_merge; use crate::slm_validate; use crate::tensor_writer::{tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_F32}; use crate::tokenizer_writer::ByteTokenizerSection; use std::time::{SystemTime, UNIX_EPOCH}; struct Fixture { ledger: String, review: String, recipe: String, parents: Vec<(String, Vec)>, admissions: Vec, candidate: Vec, receipt: String, manifest: String, } #[test] fn writes_and_validates_multi_parent_promotion_template_text() { let fixture = fixture(); let promotion = build_template_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &fixture.receipt, &fixture.manifest, &fixture.admissions, ) .unwrap(); validate_template_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &fixture.receipt, &fixture.manifest, &promotion, &fixture.admissions, ) .unwrap(); assert!(promotion.contains("promotion_kind=multi-parent-sign-merge")); assert!(promotion.contains("candidate_manifest_checksum=0x")); assert!(promotion.contains("evolution_schedule_checksum=0x")); assert!(promotion.contains("scheduled_operator_family_index=0")); assert!(promotion.contains("scheduled_operator_family_command=sign-merge-candidate")); assert!(promotion.contains("runtime_smoke_status=pending")); assert!(promotion.contains( "required_next_gate=run-runtime-smoke-and-eval-before-multi-parent-admission" )); } #[test] fn validation_rejects_candidate_manifest_drift() { let fixture = fixture(); let promotion = fixture.promotion(); let manifest = fixture.manifest.replace( "candidate_eval_status=pending", "candidate_eval_status=pass", ); let error = validate_template_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &fixture.receipt, &manifest, &promotion, &fixture.admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("manifest fields")); } #[test] fn validation_rejects_promotion_drift() { let fixture = fixture(); let promotion = fixture .promotion() .replace("promotion_decision=pending", "promotion_decision=accepted"); let error = validate_template_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &fixture.candidate, "candidate.slm", &fixture.receipt, &fixture.manifest, &promotion, &fixture.admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("promotion fields")); } #[test] fn rejects_candidate_drift() { let fixture = fixture(); let mut candidate = fixture.candidate.clone(); let last = candidate.len() - 1; candidate[last] ^= 0x01; let error = build_template_text( &fixture.ledger, &fixture.review, &fixture.recipe, &fixture.parents, &candidate, "candidate.slm", &fixture.receipt, &fixture.manifest, &fixture.admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate bytes")); } #[test] fn writes_and_validates_multi_parent_promotion_template_paths() { let dir = unique_dir("paths"); std::fs::create_dir_all(&dir).unwrap(); let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.005); let gamma_bytes = tiny_fixture_f32_bytes_with_offset(0.002); let alpha = fixture_admission( "tiny-alpha-candidate", "target/multi-promotion/path-alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/multi-promotion/path-beta.slm", &beta_bytes, ); let gamma = fixture_admission( "tiny-gamma-candidate", "target/multi-promotion/path-gamma.slm", &gamma_bytes, ); let alpha_slm = dir.join("alpha.slm"); let beta_slm = dir.join("beta.slm"); let gamma_slm = dir.join("gamma.slm"); let alpha_admission = dir.join("alpha.admission"); let beta_admission = dir.join("beta.admission"); let gamma_admission = dir.join("gamma.admission"); let ledger_path = dir.join("pool.ledger"); let review_path = dir.join("pool.review"); let recipe_path = dir.join("pool.recipe"); let candidate_path = dir.join("candidate.slm"); let receipt_path = dir.join("candidate.operator"); let manifest_path = dir.join("candidate.multi"); let promotion_path = dir.join("candidate.multi.promotion"); std::fs::write(&alpha_slm, alpha_bytes).unwrap(); std::fs::write(&beta_slm, beta_bytes).unwrap(); std::fs::write(&gamma_slm, gamma_bytes).unwrap(); std::fs::write(&alpha_admission, alpha).unwrap(); std::fs::write(&beta_admission, beta).unwrap(); std::fs::write(&gamma_admission, gamma).unwrap(); let admissions = vec![ alpha_admission.to_string_lossy().to_string(), beta_admission.to_string_lossy().to_string(), gamma_admission.to_string_lossy().to_string(), ]; let parents = vec![ alpha_slm.to_string_lossy().to_string(), beta_slm.to_string_lossy().to_string(), gamma_slm.to_string_lossy().to_string(), ]; ledger::write_ledger_path(&ledger_path, &admissions).unwrap(); population::write_review_path(&ledger_path, &review_path, &admissions).unwrap(); parent_pool::write_recipe_path(&ledger_path, &review_path, &recipe_path, &admissions) .unwrap(); sign_merge::write_candidate_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &parents, &admissions, ) .unwrap(); multi_candidate::write_manifest_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &manifest_path, &parents, &admissions, ) .unwrap(); write_template_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &manifest_path, &promotion_path, &parents, &admissions, ) .unwrap(); validate_template_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &manifest_path, &promotion_path, &parents, &admissions, ) .unwrap(); let promotion = std::fs::read_to_string(promotion_path).unwrap(); assert!(promotion.contains("parent_count=3")); assert!(promotion.contains("scheduled_operator_family_kind=sign-aware-parent-pool-merge")); assert!(promotion.contains("browser_selector_status=not-admitted")); } impl Fixture { fn promotion(&self) -> String { build_template_text( &self.ledger, &self.review, &self.recipe, &self.parents, &self.candidate, "candidate.slm", &self.receipt, &self.manifest, &self.admissions, ) .unwrap() } } fn fixture() -> Fixture { let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.003); let gamma_bytes = tiny_fixture_f32_bytes_with_offset(0.006); let alpha = fixture_admission( "tiny-alpha-candidate", "target/multi-promotion/alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/multi-promotion/beta.slm", &beta_bytes, ); let gamma = fixture_admission( "tiny-gamma-candidate", "target/multi-promotion/gamma.slm", &gamma_bytes, ); let admissions = vec![alpha, beta, gamma]; let ledger = ledger::build_ledger_text(&admissions).unwrap(); let review = population::build_review_text(&ledger, &admissions).unwrap(); let recipe = parent_pool::build_recipe_text(&ledger, &review, &admissions).unwrap(); let parents = vec![ ("alpha.slm".to_string(), alpha_bytes), ("beta.slm".to_string(), beta_bytes), ("gamma.slm".to_string(), gamma_bytes), ]; let (candidate, receipt) = sign_merge::build_candidate_bytes_and_receipt( &ledger, &review, &recipe, &parents, "candidate.slm", &admissions, ) .unwrap(); let manifest = multi_candidate::build_manifest_text( &ledger, &review, &recipe, &parents, &candidate, "candidate.slm", &receipt, &admissions, ) .unwrap(); Fixture { ledger, review, recipe, parents, admissions, candidate, receipt, manifest, } } fn fixture_admission(candidate_id: &str, candidate_path: &str, candidate: &[u8]) -> String { let compatibility = compatibility::compatibility_text_for_bytes( candidate, "left.slm", candidate, "right.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, candidate_id, "operator-a", "fit") .unwrap(); let candidate_manifest = candidate::build_manifest_text(&compatibility, &lineage, candidate, candidate_path) .unwrap(); let promotion = promotion::build_template_text( &compatibility, &lineage, candidate, candidate_path, &candidate_manifest, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, ) .unwrap(); let report = slm_validate::validate_bytes(candidate, candidate_path).unwrap(); let provenance_manifest = provenance::build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = provenance::parse_manifest(&provenance_manifest).unwrap(); let runtime_smoke = provenance::build_runtime_smoke_text(&report, &provenance_manifest, &manifest_fields) .unwrap(); let eval = passing_eval_text(&report, &provenance_manifest); admission::build_record_text( &compatibility, &lineage, candidate, candidate_path, &candidate_manifest, &promotion, &provenance_manifest, &runtime_smoke, &eval, admission::DEFAULT_ADMISSION_SELECTOR_ID, ) .unwrap() } fn passing_eval_text(report: &slm_validate::ValidationReport, manifest: &str) -> String { let mut text = String::new(); push_line(&mut text, "tinyrustlm_eval_manifest_version", "1"); push_line(&mut text, "gate", "assistant-quality"); push_line(&mut text, "source_kind", "converted-trained"); push_line( &mut text, "manifest_checksum", &hex64(provenance::text_checksum(manifest.as_bytes())), ); push_line(&mut text, "slm_checksum", &hex64(report.checksum())); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "task_eval_status", "pass"); push_line(&mut text, "safety_review_status", "pass"); push_line( &mut text, "quality_decision", "accepted-for-assistant-quality", ); push_line(&mut text, "quality_scope", "tiny-fixture-runtime-eval-only"); push_line(&mut text, "evaluator", "local-reviewed-eval"); push_line( &mut text, "eval_dataset", "tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", ); push_line( &mut text, "eval_summary", "Reviewed task and safety evidence passed for declared scope", ); push_line( &mut text, "quality_boundary", "fixture-runtime-and-eval-plumbing-not-product-assistant-quality", ); push_line(&mut text, "case_count", "1"); push_line(&mut text, "cases_passed", "1"); push_line(&mut text, "cases_failed", "0"); push_line(&mut text, "case.0.status", "pass"); push_line(&mut text, "case.0.expected", "e"); push_line(&mut text, "case.0.actual", "e"); push_line(&mut text, "case.0.error", "ok"); text } fn tiny_fixture_f32_bytes_with_offset(offset: f32) -> Vec { let tensors = tiny_fixture_tensors_with_dtype(DTYPE_F32); let values: Vec> = tensors .iter() .map(|tensor| { (0..tensor.element_count()) .map(|elem| fixture_value(tensor, elem) + offset) .collect() }) .collect(); build_model_file_from_values_with_flags( &ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } fn unique_dir(label: &str) -> std::path::PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-multi-promotion-{label}-{nanos}")) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/multi_promotion.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/mutation.rs BYTES: 42944 SHA256: 7252937956E25EB7581BFAF2303A7857F88730CD11062A5645112567043C3B65 ================================================================================ //! Offline deterministic bounded mutation operator for model-breeding candidates. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::blend::{ hex64, invalid, output_specs, parse_manifest, parse_model_values, parse_passing_compatibility, push_line, push_parent_lines, require_equal, require_key, require_parent_report, require_report_equal, require_same_tensor_spec, same_shape, ParsedModel, PPM_DENOMINATOR, }; use crate::build_model_file_from_values_with_flags; use crate::lineage; use crate::slm_validate::{self, ValidationReport}; const MUTATION_OPERATOR_VERSION: &str = "1"; const OPERATOR_KIND: &str = "deterministic-bounded-parameter-mutation"; const OPERATOR_STATUS: &str = "candidate-written"; const OPERATOR_OUTPUT_STATUS: &str = "slm-validated"; const PARENT_CONTRACT: &str = "matches-parent-direct-parameter-contract"; const REQUIRED_NEXT_GATE: &str = "candidate-manifest-plus-runtime-smoke-plus-eval"; const DEFAULT_MUTATION_SEED: &str = "1099511628211"; const DEFAULT_MUTATION_RATE_PPM: &str = "10000"; const DEFAULT_MUTATION_MAGNITUDE_PPM: &str = "50000"; const SELECTION_METRIC: &str = "splitmix64-tensor-element-threshold"; const SELECTION_SCOPE: &str = "compatible-base-tensor-values"; const TIE_BREAK: &str = "mutate-when-threshold-equal"; const VALUE_SCALE: &str = "max-abs-parent-value-or-one"; /// Writes a bounded mutation candidate `.slm` plus a recomputable operator receipt. pub(crate) fn write_candidate_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, reference_parent: &Path, output_slm: &Path, output_receipt: &Path, mutation_seed: Option<&str>, mutation_rate_ppm: Option<&str>, mutation_magnitude_ppm: Option<&str>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let reference_bytes = fs::read(reference_parent)?; let seed = parse_mutation_seed(mutation_seed.unwrap_or(DEFAULT_MUTATION_SEED))?; let rate = parse_mutation_rate_ppm(mutation_rate_ppm.unwrap_or(DEFAULT_MUTATION_RATE_PPM))?; let magnitude = parse_mutation_magnitude_ppm( mutation_magnitude_ppm.unwrap_or(DEFAULT_MUTATION_MAGNITUDE_PPM), )?; let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &reference_bytes, &reference_parent.display().to_string(), &output_slm.display().to_string(), seed, rate, magnitude, )?; if let Some(parent) = output_slm.parent() { fs::create_dir_all(parent)?; } fs::write(output_slm, candidate)?; if let Some(parent) = output_receipt.parent() { fs::create_dir_all(parent)?; } fs::write(output_receipt, receipt)?; println!("SLM mutation candidate written: {}", output_slm.display()); println!( "SLM mutation operator receipt written: {}", output_receipt.display() ); Ok(()) } /// Validates a mutation candidate and receipt by recomputing the operator output. pub(crate) fn validate_candidate_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, reference_parent: &Path, candidate_slm: &Path, receipt: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let reference_bytes = fs::read(reference_parent)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; validate_candidate_text( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &reference_bytes, &reference_parent.display().to_string(), &candidate_bytes, &candidate_slm.display().to_string(), &receipt_text, )?; println!("SLM mutation candidate validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("receipt: {}", receipt.display()); Ok(()) } /// Recomputes mutation output from receipt fields and compares both artifacts. fn validate_candidate_text( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, reference_bytes: &[u8], reference_path: &str, candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, ) -> io::Result<()> { let receipt = parse_manifest(receipt_text, "mutation operator receipt")?; require_equal( &receipt, "tinyrustlm_mutation_operator_version", MUTATION_OPERATOR_VERSION, )?; require_equal(&receipt, "operator_kind", OPERATOR_KIND)?; require_equal(&receipt, "base_parent_index", "0")?; require_equal(&receipt, "reference_parent_index", "1")?; require_equal(&receipt, "mutation_rate_unit", "parts-per-million")?; require_equal( &receipt, "mutation_magnitude_unit", "parts-per-million-of-value-scale", )?; require_equal(&receipt, "mutation_selection_metric", SELECTION_METRIC)?; require_equal(&receipt, "mutation_selection_scope", SELECTION_SCOPE)?; require_equal(&receipt, "mutation_tie_break", TIE_BREAK)?; require_equal(&receipt, "mutation_value_scale", VALUE_SCALE)?; let seed = parse_mutation_seed(require_key(&receipt, "mutation_seed")?)?; let rate = parse_mutation_rate_ppm(require_key(&receipt, "mutation_rate_ppm")?)?; let magnitude = parse_mutation_magnitude_ppm(require_key(&receipt, "mutation_magnitude_ppm")?)?; let (expected_candidate, expected_receipt) = build_candidate_bytes_and_receipt( compatibility_text, lineage_text, base_bytes, base_path, reference_bytes, reference_path, candidate_path, seed, rate, magnitude, )?; if candidate_bytes != expected_candidate { return Err(invalid( "mutation candidate bytes do not match the operator receipt", )); } if receipt_text != expected_receipt { return Err(invalid( "mutation operator receipt fields do not match recomputed output", )); } Ok(()) } /// Builds the mutation `.slm` bytes and the receipt that can reproduce them. fn build_candidate_bytes_and_receipt( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, reference_bytes: &[u8], reference_path: &str, candidate_path: &str, mutation_seed: u64, mutation_rate_ppm: u32, mutation_magnitude_ppm: u32, ) -> io::Result<(Vec, String)> { lineage::validate_text(compatibility_text, lineage_text)?; let compatibility = parse_passing_compatibility(compatibility_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let base_report = slm_validate::validate_bytes(base_bytes, base_path)?; let reference_report = slm_validate::validate_bytes(reference_bytes, reference_path)?; require_parent_report(&compatibility, 0, &base_report)?; require_parent_report(&compatibility, 1, &reference_report)?; let base = parse_model_values(base_bytes)?; let reference = parse_model_values(reference_bytes)?; let (output_values, mutation_stats) = mutation_values( &base, &reference, mutation_seed, mutation_rate_ppm, mutation_magnitude_ppm, )?; let output_tensors = output_specs(&base); let candidate = build_model_file_from_values_with_flags( &base.shape, &output_tensors, &base.tokenizer, &output_values, base.flags, )?; let candidate_report = slm_validate::validate_bytes(&candidate, candidate_path)?; require_report_equal( &compatibility, "parent.0.model_shape", &candidate_report.shape_summary(), )?; require_report_equal( &compatibility, "parent.0.quantization", candidate_report.quantization_label(), )?; require_report_equal( &compatibility, "parent.0.output_contract", candidate_report.output_contract_label(), )?; require_report_equal( &compatibility, "parent.0.tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), )?; require_report_equal( &compatibility, "parent.0.tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), )?; let receipt = build_receipt_text( &compatibility, &lineage_fields, lineage_text, base_path, reference_path, &base_report, &reference_report, &candidate_report, mutation_seed, mutation_rate_ppm, mutation_magnitude_ppm, mutation_stats, )?; Ok((candidate, receipt)) } /// Formats the manifest-style receipt for a deterministic mutation candidate. #[allow(clippy::too_many_arguments)] fn build_receipt_text( compatibility: &HashMap, lineage_fields: &HashMap, lineage_text: &str, base_path: &str, reference_path: &str, base_report: &ValidationReport, reference_report: &ValidationReport, candidate_report: &ValidationReport, mutation_seed: u64, mutation_rate_ppm: u32, mutation_magnitude_ppm: u32, mutation_stats: MutationStats, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_mutation_operator_version", MUTATION_OPERATOR_VERSION, ); push_line(&mut text, "operator_kind", OPERATOR_KIND); push_line(&mut text, "operator_status", OPERATOR_STATUS); push_line( &mut text, "candidate_id", require_key(lineage_fields, "candidate_id")?, ); push_line( &mut text, "operator_id", require_key(lineage_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(lineage_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(lineage_fields, "resource_budget")?, ); push_line( &mut text, "compatibility_report_checksum", require_key(lineage_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(compatibility, "compatibility_scope")?, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, compatibility, 0, base_path, base_report)?; push_parent_lines( &mut text, compatibility, 1, reference_path, reference_report, )?; push_line(&mut text, "base_parent_index", "0"); push_line(&mut text, "reference_parent_index", "1"); push_line(&mut text, "mutation_seed", &mutation_seed.to_string()); push_line(&mut text, "mutation_rate_unit", "parts-per-million"); push_line( &mut text, "mutation_rate_ppm", &mutation_rate_ppm.to_string(), ); push_line( &mut text, "mutation_magnitude_unit", "parts-per-million-of-value-scale", ); push_line( &mut text, "mutation_magnitude_ppm", &mutation_magnitude_ppm.to_string(), ); push_line(&mut text, "mutation_selection_metric", SELECTION_METRIC); push_line(&mut text, "mutation_selection_scope", SELECTION_SCOPE); push_line(&mut text, "mutation_tie_break", TIE_BREAK); push_line(&mut text, "mutation_value_scale", VALUE_SCALE); push_line( &mut text, "mutation_total_parameter_count", &mutation_stats.total_parameter_count.to_string(), ); push_line( &mut text, "mutation_selected_parameter_count", &mutation_stats.selected_parameter_count.to_string(), ); push_line( &mut text, "mutation_changed_parameter_count", &mutation_stats.changed_parameter_count.to_string(), ); push_line( &mut text, "mutation_selection_density_ppm", &mutation_stats.selection_density_ppm.to_string(), ); push_line( &mut text, "mutation_mask_checksum", &hex64(mutation_stats.mask_checksum), ); push_line( &mut text, "mutation_delta_checksum", &hex64(mutation_stats.delta_checksum), ); push_line( &mut text, "candidate_artifact_path", candidate_report.path(), ); push_line( &mut text, "candidate_artifact_bytes", &candidate_report.file_bytes().to_string(), ); push_line( &mut text, "candidate_slm_version", &candidate_report.slm_version().to_string(), ); push_line( &mut text, "candidate_slm_checksum", &hex64(candidate_report.checksum()), ); push_line( &mut text, "candidate_model_shape", &candidate_report.shape_summary(), ); push_line( &mut text, "candidate_tensor_count", &candidate_report.tensor_count().to_string(), ); push_line( &mut text, "candidate_parameter_count", &candidate_report.parameter_count().to_string(), ); push_line( &mut text, "candidate_quantization", candidate_report.quantization_label(), ); push_line( &mut text, "candidate_output_contract", candidate_report.output_contract_label(), ); push_line( &mut text, "candidate_tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), ); push_line( &mut text, "candidate_tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), ); push_line(&mut text, "candidate_parent_contract", PARENT_CONTRACT); push_line(&mut text, "operator_output_status", OPERATOR_OUTPUT_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } /// Mutates selected compatible tensor values and returns output values plus receipt stats. fn mutation_values( base: &ParsedModel, reference: &ParsedModel, mutation_seed: u64, mutation_rate_ppm: u32, mutation_magnitude_ppm: u32, ) -> io::Result<(Vec>, MutationStats)> { if !same_shape(&base.shape, &reference.shape) { return Err(invalid("mutation parents have different model shapes")); } if base.flags != reference.flags { return Err(invalid("mutation parents have different output flags")); } if base.tokenizer.bytes != reference.tokenizer.bytes { return Err(invalid("mutation parents have different tokenizer bytes")); } let reference_by_hash = reference .tensors .iter() .enumerate() .map(|(index, tensor)| (tensor.spec.name_hash, index)) .collect::>(); let mut output = Vec::with_capacity(base.tensors.len()); let mut stats = MutationStats { total_parameter_count: 0, selected_parameter_count: 0, changed_parameter_count: 0, selection_density_ppm: 0, mask_checksum: mutation_mask_seed(mutation_seed, mutation_rate_ppm, mutation_magnitude_ppm), delta_checksum: mutation_delta_seed( mutation_seed, mutation_rate_ppm, mutation_magnitude_ppm, ), }; for (tensor_index, base_tensor) in base.tensors.iter().enumerate() { let Some(reference_index) = reference_by_hash.get(&base_tensor.spec.name_hash) else { return Err(invalid( "reference parent is missing a tensor from the base parent", )); }; let reference_tensor = &reference.tensors[*reference_index]; require_same_tensor_spec(&base_tensor.spec, &reference_tensor.spec)?; let mut values = Vec::with_capacity(base_tensor.values.len()); for (value_index, (base_value, reference_value)) in base_tensor .values .iter() .zip(reference_tensor.values.iter()) .enumerate() { let selected = choose_mutation(mutation_seed, tensor_index, value_index, mutation_rate_ppm); stats.total_parameter_count += 1; mix_mask_value(&mut stats.mask_checksum, tensor_index as u64); mix_mask_value(&mut stats.mask_checksum, value_index as u64); mix_mask_value(&mut stats.mask_checksum, if selected { 1 } else { 0 }); if selected { stats.selected_parameter_count += 1; let delta = mutation_delta( mutation_seed, tensor_index, value_index, *base_value, *reference_value, mutation_magnitude_ppm, )?; let mutated = *base_value + delta; if !mutated.is_finite() { return Err(invalid("mutation produced a non-finite tensor value")); } if mutated != *base_value { stats.changed_parameter_count += 1; } mix_delta_value(&mut stats.delta_checksum, tensor_index as u64); mix_delta_value(&mut stats.delta_checksum, value_index as u64); mix_delta_value(&mut stats.delta_checksum, u64::from(delta.to_bits())); mix_delta_value(&mut stats.delta_checksum, u64::from(mutated.to_bits())); values.push(mutated); } else { values.push(*base_value); } } output.push(values); } stats.selection_density_ppm = ratio_ppm(stats.selected_parameter_count, stats.total_parameter_count)?; mix_mask_value(&mut stats.mask_checksum, stats.total_parameter_count); mix_mask_value(&mut stats.mask_checksum, stats.selected_parameter_count); mix_delta_value(&mut stats.delta_checksum, stats.changed_parameter_count); Ok((output, stats)) } /// Applies the mutation-rate threshold with fixed behavior for boundary values. fn choose_mutation( mutation_seed: u64, tensor_index: usize, value_index: usize, mutation_rate_ppm: u32, ) -> bool { if mutation_rate_ppm == 0 { return false; } if mutation_rate_ppm >= PPM_DENOMINATOR { return true; } draw_ppm(mutation_seed, tensor_index, value_index) <= mutation_rate_ppm } /// Computes a bounded signed perturbation for a selected tensor value. fn mutation_delta( mutation_seed: u64, tensor_index: usize, value_index: usize, base_value: f32, reference_value: f32, mutation_magnitude_ppm: u32, ) -> io::Result { if mutation_magnitude_ppm == 0 { return Ok(0.0); } let scale = base_value.abs().max(reference_value.abs()).max(1.0); let magnitude = mutation_magnitude_ppm as f32 / PPM_DENOMINATOR as f32; let unit = draw_unit(mutation_seed, tensor_index, value_index); let sign = if draw_sign(mutation_seed, tensor_index, value_index) { 1.0 } else { -1.0 }; let delta = sign * scale * magnitude * unit; if !delta.is_finite() { return Err(invalid("mutation delta overflowed finite f32 range")); } Ok(delta) } /// Produces a parts-per-million draw from stable tensor and element coordinates. fn draw_ppm(mutation_seed: u64, tensor_index: usize, value_index: usize) -> u32 { let mixed = splitmix64(coordinate_seed(mutation_seed, tensor_index, value_index)); (mixed % u64::from(PPM_DENOMINATOR) + 1) as u32 } /// Produces a unit interval multiplier from the same deterministic coordinate key. fn draw_unit(mutation_seed: u64, tensor_index: usize, value_index: usize) -> f32 { let mixed = splitmix64( coordinate_seed(mutation_seed, tensor_index, value_index) ^ 0xd134_2543_de82_ef95, ); (mixed % u64::from(PPM_DENOMINATOR) + 1) as f32 / PPM_DENOMINATOR as f32 } /// Chooses the deterministic sign for one mutation coordinate. fn draw_sign(mutation_seed: u64, tensor_index: usize, value_index: usize) -> bool { (splitmix64(coordinate_seed(mutation_seed, tensor_index, value_index) ^ 0x94d0_49bb_1331_11eb) & 1) == 1 } /// Mixes the operator seed with tensor and element coordinates. fn coordinate_seed(mutation_seed: u64, tensor_index: usize, value_index: usize) -> u64 { mutation_seed ^ ((tensor_index as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15)) ^ ((value_index as u64).wrapping_mul(0xbf58_476d_1ce4_e5b9)) } /// Scrambles a u64 using the SplitMix64 finalizer pattern. fn splitmix64(mut value: u64) -> u64 { value = value.wrapping_add(0x9e37_79b9_7f4a_7c15); value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); value ^ (value >> 31) } /// Starts the mutation selection-mask checksum from operator parameters. fn mutation_mask_seed( mutation_seed: u64, mutation_rate_ppm: u32, mutation_magnitude_ppm: u32, ) -> u64 { let mut acc = 0x6d75_7461_7465_7631u64; mix_mask_value(&mut acc, mutation_seed); mix_mask_value(&mut acc, u64::from(mutation_rate_ppm)); mix_mask_value(&mut acc, u64::from(mutation_magnitude_ppm)); acc } /// Starts the mutation delta checksum from operator parameters. fn mutation_delta_seed( mutation_seed: u64, mutation_rate_ppm: u32, mutation_magnitude_ppm: u32, ) -> u64 { let mut acc = 0x6465_6c74_616d_7631u64; mix_delta_value(&mut acc, mutation_seed); mix_delta_value(&mut acc, u64::from(mutation_rate_ppm)); mix_delta_value(&mut acc, u64::from(mutation_magnitude_ppm)); acc } /// Folds one mask value into a compact deterministic checksum. fn mix_mask_value(acc: &mut u64, value: u64) { *acc ^= value.wrapping_add(0x9e37_79b9_7f4a_7c15); *acc = acc.rotate_left(11).wrapping_mul(0x1000_0000_01b3); } /// Folds one selected delta value into a compact deterministic checksum. fn mix_delta_value(acc: &mut u64, value: u64) { *acc ^= value.wrapping_add(0xbf58_476d_1ce4_e5b9); *acc = acc.rotate_left(7).wrapping_mul(0x94d0_49bb_1331_11eb); } /// Converts a count ratio into integer parts-per-million. fn ratio_ppm(numerator: u64, denominator: u64) -> io::Result { if denominator == 0 { return Ok(0); } let ppm = u128::from(numerator) * u128::from(PPM_DENOMINATOR) / u128::from(denominator); u64::try_from(ppm).map_err(|_| invalid("mutation ratio overflowed u64")) } /// Parses the deterministic mutation seed from a CLI or receipt field. fn parse_mutation_seed(value: &str) -> io::Result { value .parse::() .map_err(|_| invalid("mutation seed must be an unsigned 64-bit integer")) } /// Parses mutation rate as an integer parts-per-million value. fn parse_mutation_rate_ppm(value: &str) -> io::Result { let rate = value .parse::() .map_err(|_| invalid("mutation rate must be an integer parts-per-million value"))?; if rate > PPM_DENOMINATOR { return Err(invalid("mutation rate must be between 0 and 1000000")); } Ok(rate) } /// Parses mutation magnitude as an integer parts-per-million value. fn parse_mutation_magnitude_ppm(value: &str) -> io::Result { let magnitude = value .parse::() .map_err(|_| invalid("mutation magnitude must be an integer parts-per-million value"))?; if magnitude > PPM_DENOMINATOR { return Err(invalid("mutation magnitude must be between 0 and 1000000")); } Ok(magnitude) } /// Holds deterministic mutation selection counts and checksum metadata. #[derive(Clone, Copy)] struct MutationStats { total_parameter_count: u64, selected_parameter_count: u64, changed_parameter_count: u64, selection_density_ppm: u64, mask_checksum: u64, delta_checksum: u64, } #[cfg(test)] mod tests { use super::*; use crate::compatibility; use crate::tensor_writer::{tiny_fixture_tensors, tiny_fixture_tensors_with_dtype, DTYPE_Q8_0}; use crate::tokenizer_writer::ByteTokenizerSection; use crate::{build_model_file_from_values_with_flags, fixture_value}; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; // Exercises seed, rate, and magnitude through candidate writing and receipt validation. #[test] fn writes_and_validates_seeded_f32_mutation_candidate() { let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "mut-f32", "mutation-v1", "tiny").unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "candidate.slm", 7, 1_000_000, 100_000, ) .unwrap(); validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); assert_ne!( parse_model_values(&candidate).unwrap().tensors[0].values, parse_model_values(&base).unwrap().tensors[0].values ); assert!(receipt.contains("operator_kind=deterministic-bounded-parameter-mutation")); assert!(receipt.contains("mutation_seed=7")); assert!(receipt.contains("mutation_rate_ppm=1000000")); assert!(receipt.contains("mutation_magnitude_ppm=100000")); assert!(receipt.contains("mutation_mask_checksum=")); assert!(receipt.contains("mutation_delta_checksum=")); } // Exercises all path-level inputs plus default seed, rate, and magnitude parameters. #[test] fn path_writer_uses_default_parameters_then_validates() { let dir = unique_dir("path-defaults"); fs::create_dir_all(&dir).unwrap(); let base_path = dir.join("base.slm"); let reference_path = dir.join("reference.slm"); let compatibility_path = dir.join("parents.compat"); let lineage_path = dir.join("candidate.lineage"); let candidate_path = dir.join("candidate.slm"); let receipt_path = dir.join("candidate.operator"); let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); fs::write(&base_path, &base).unwrap(); fs::write(&reference_path, &reference).unwrap(); let compatibility = compatibility::compatibility_text_for_bytes( &base, &base_path.display().to_string(), &reference, &reference_path.display().to_string(), ) .unwrap(); fs::write(&compatibility_path, &compatibility).unwrap(); let lineage = lineage::build_template_text(&compatibility, "mut-path", "mutation-v1", "tiny") .unwrap(); fs::write(&lineage_path, &lineage).unwrap(); write_candidate_path( &compatibility_path, &lineage_path, &base_path, &reference_path, &candidate_path, &receipt_path, None, None, None, ) .unwrap(); validate_candidate_path( &compatibility_path, &lineage_path, &base_path, &reference_path, &candidate_path, &receipt_path, ) .unwrap(); let receipt = fs::read_to_string(receipt_path).unwrap(); assert!(receipt.contains("mutation_seed=1099511628211")); assert!(receipt.contains("mutation_rate_ppm=10000")); assert!(receipt.contains("mutation_magnitude_ppm=50000")); } // Covers the mutation_rate_ppm lower boundary where the base is preserved. #[test] fn rate_zero_preserves_base_values() { let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "mut-rate-zero", "mutation-v1", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "candidate.slm", 13, 0, 1_000_000, ) .unwrap(); assert_same_values(&candidate, &base); assert!(receipt.contains("mutation_selected_parameter_count=0")); assert!(receipt.contains("mutation_selection_density_ppm=0")); } // Covers the mutation_magnitude_ppm lower boundary while selection still occurs. #[test] fn magnitude_zero_preserves_base_values() { let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "mut-mag-zero", "mutation-v1", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "candidate.slm", 13, 1_000_000, 0, ) .unwrap(); assert_same_values(&candidate, &base); assert!(receipt.contains("mutation_selection_density_ppm=1000000")); assert!(receipt.contains("mutation_changed_parameter_count=0")); } // Confirms mutation_seed changes the selected mask and produced candidate. #[test] fn mutation_seed_changes_selection_mask() { let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "mut-seed", "mutation-v1", "tiny") .unwrap(); let (candidate_a, receipt_a) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "candidate-a.slm", 1, 500_000, 100_000, ) .unwrap(); let (candidate_b, receipt_b) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "candidate-b.slm", 2, 500_000, 100_000, ) .unwrap(); let receipt_a_fields = parse_manifest(&receipt_a, "mutation receipt a").unwrap(); let receipt_b_fields = parse_manifest(&receipt_b, "mutation receipt b").unwrap(); assert_ne!(candidate_a, candidate_b); assert_ne!( receipt_a_fields.get("mutation_mask_checksum"), receipt_b_fields.get("mutation_mask_checksum") ); } // Confirms mutation_magnitude_ppm changes the bounded perturbation size. #[test] fn mutation_magnitude_changes_candidate_values() { let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "mut-mag", "mutation-v1", "tiny").unwrap(); let (small, small_receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "small.slm", 7, 1_000_000, 1, ) .unwrap(); let (large, large_receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "large.slm", 7, 1_000_000, 250_000, ) .unwrap(); let small_fields = parse_manifest(&small_receipt, "small mutation receipt").unwrap(); let large_fields = parse_manifest(&large_receipt, "large mutation receipt").unwrap(); assert_ne!(small, large); assert_ne!( small_fields.get("mutation_delta_checksum"), large_fields.get("mutation_delta_checksum") ); } // Confirms the compatible reference parent participates in the perturbation scale. #[test] fn reference_parent_scale_changes_candidate_values() { let base = tiny_f32_scaled_bytes(1.0); let small_reference = tiny_f32_scaled_bytes(2.0); let large_reference = tiny_f32_scaled_bytes(5.0); let small_compatibility = compatibility::compatibility_text_for_bytes( &base, "base.slm", &small_reference, "small-ref.slm", ) .unwrap(); let large_compatibility = compatibility::compatibility_text_for_bytes( &base, "base.slm", &large_reference, "large-ref.slm", ) .unwrap(); let small_lineage = lineage::build_template_text(&small_compatibility, "mut-ref-a", "mutation-v1", "tiny") .unwrap(); let large_lineage = lineage::build_template_text(&large_compatibility, "mut-ref-b", "mutation-v1", "tiny") .unwrap(); let (small_candidate, _) = build_candidate_bytes_and_receipt( &small_compatibility, &small_lineage, &base, "base.slm", &small_reference, "small-ref.slm", "small-candidate.slm", 99, 1_000_000, 100_000, ) .unwrap(); let (large_candidate, _) = build_candidate_bytes_and_receipt( &large_compatibility, &large_lineage, &base, "base.slm", &large_reference, "large-ref.slm", "large-candidate.slm", 99, 1_000_000, 100_000, ) .unwrap(); assert_ne!(small_candidate, large_candidate); } // Validates q8 parents keep their quantization route through mutation output. #[test] fn writes_and_validates_q8_mutation_candidate() { let base = tiny_q8_scaled_bytes(1.0); let reference = tiny_q8_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "mut-q8", "mutation-v1", "tiny").unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "candidate.slm", 42, 1_000_000, 250_000, ) .unwrap(); slm_validate::validate_bytes(&candidate, "candidate.slm").unwrap(); validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); assert!(receipt.contains("candidate_quantization=q8_0")); } // Confirms base parameters are tied to compatibility receipts by checksum. #[test] fn rejects_parent_checksum_drift() { let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "mut-drift", "mutation-v1", "tiny") .unwrap(); let changed_base = tiny_f32_scaled_bytes(3.0); let error = build_candidate_bytes_and_receipt( &compatibility, &lineage, &changed_base, "base.slm", &reference, "ref.slm", "candidate.slm", 7, 1_000_000, 100_000, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("parent.0.slm_checksum")); } // Confirms validation catches candidate bytes that no longer match the receipt. #[test] fn validation_rejects_candidate_drift() { let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "mut-drift", "mutation-v1", "tiny") .unwrap(); let (mut candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "candidate.slm", 7, 1_000_000, 100_000, ) .unwrap(); let last = candidate.len() - 1; candidate[last] ^= 0x01; let error = validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", &candidate, "candidate.slm", &receipt, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate bytes")); } // Covers parser behavior for seed, rate, and magnitude inputs. #[test] fn rejects_invalid_mutation_parameters() { assert_eq!( parse_mutation_seed("18446744073709551616") .unwrap_err() .kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_mutation_seed("-1").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_mutation_seed("seed").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_mutation_rate_ppm("1000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_mutation_rate_ppm("-1").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_mutation_rate_ppm("half").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_mutation_magnitude_ppm("1000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_mutation_magnitude_ppm("-1").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_mutation_magnitude_ppm("wide").unwrap_err().kind(), io::ErrorKind::InvalidData ); } // Compares decoded tensor values between two `.slm` byte buffers. fn assert_same_values(candidate: &[u8], expected: &[u8]) { let candidate_values = parse_model_values(candidate).unwrap(); let expected_values = parse_model_values(expected).unwrap(); for (candidate_tensor, expected_tensor) in candidate_values .tensors .iter() .zip(expected_values.tensors.iter()) { assert_eq!(candidate_tensor.values, expected_tensor.values); } } // Builds a tiny f32 model with all fixture values multiplied by scale. fn tiny_f32_scaled_bytes(scale: f32) -> Vec { build_tiny_bytes(tiny_fixture_tensors(), |tensor, index, _tensor_index| { fixture_value(tensor, index) * scale }) } // Builds a tiny q8 model with all fixture values multiplied by scale. fn tiny_q8_scaled_bytes(scale: f32) -> Vec { build_tiny_bytes( tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), |tensor, index, _tensor_index| fixture_value(tensor, index) * scale, ) } // Packs a tiny fixture model from caller-supplied tensor values. fn build_tiny_bytes(tensors: Vec, mut value: F) -> Vec where F: FnMut(&crate::tensor_writer::TensorSpec, usize, usize) -> f32, { let values = tensors .iter() .enumerate() .map(|(tensor_index, tensor)| { (0..tensor.element_count()) .map(|index| value(tensor, index, tensor_index)) .collect::>() }) .collect::>(); build_model_file_from_values_with_flags( &crate::tensor_writer::ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } // Creates an isolated temp directory for path-level operator tests. fn unique_dir(label: &str) -> PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-mutation-{label}-{nanos}")) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/mutation.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/parent_pool.rs BYTES: 42417 SHA256: C3ADE55E0A95AD132A16B59200C751906DEFD7492377FCF0F02DBEE4942CAB8D ================================================================================ //! Offline parent-pool recipes built from population reviews. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::blend::{hex64, invalid, parse_manifest, push_line, require_equal, require_key}; use crate::population; use crate::provenance; const RECIPE_VERSION: &str = "1"; const RECIPE_ID: &str = "browser-local-parent-pool-recipe"; const RECIPE_SCOPE: &str = "offline-model-breeding-parent-pool-recipe"; const RECIPE_STATUS: &str = "population-reviewed"; const RECIPE_BASIS: &str = "population-review-plus-promotion-ledger"; const RECIPE_KIND: &str = "sign-aware-parent-pool-v1"; const PARENT_SELECTION: &str = "all-reviewed-candidates"; const SEED_WEIGHT_FORMULA: &str = "population-fitness-normalized-ppm"; const PARENT_CONTRACT_STATUS: &str = "shared-direct-parameter-contract"; const RELATEDNESS_METRIC: &str = "shared-direct-parameter-contract-v1"; const RELATEDNESS_SCOPE: &str = "selected-parent-pool"; const RELATEDNESS_ALL_PAIRS_STATUS: &str = "shared-direct-parameter-contract"; const RELATEDNESS_GROUP: &str = "direct-parameter-family.0"; const EVOLUTION_RECIPE_VERSION: &str = "1"; const EVOLUTION_RECIPE_STRATEGY: &str = "population-based-parent-pool-replay-v1"; const EVOLUTION_RECIPE_STATUS: &str = "operator-family-planned"; const EVOLUTION_SELECTION_SOURCE: &str = "population-fitness-normalized-seed-weights"; const EVOLUTION_SCHEDULE_CHECKSUM_ALGORITHM: &str = "tinyrustlm-text-checksum-v1"; const FRONTIER_ROLE: &str = "frontier"; const POOL_ROLE: &str = "parent-pool"; const SELECTED_STATUS: &str = "selected-for-parent-pool-recipe"; const REQUIRED_NEXT_GATE: &str = "lineage-template-or-sign-aware-merge-candidate"; const PPM_DENOMINATOR: u64 = 1_000_000; struct EvolutionOperatorFamily { operator_kind: &'static str, command: &'static str, selection_rule: &'static str, output_gate: &'static str, } const EVOLUTION_OPERATOR_FAMILIES: [EvolutionOperatorFamily; 2] = [ EvolutionOperatorFamily { operator_kind: "sign-aware-parent-pool-merge", command: "sign-merge-candidate", selection_rule: "seed-weighted-delta-sign-consensus", output_gate: "multi-parent-candidate-manifest-plus-runtime-smoke-plus-eval", }, EvolutionOperatorFamily { operator_kind: "seed-weighted-parent-pool-soup", command: "soup-candidate", selection_rule: "seed-weighted-direct-parameter-average", output_gate: "multi-parent-candidate-manifest-plus-runtime-smoke-plus-eval", }, ]; struct ParentEntry { rank: usize, review_index: usize, ledger_index: usize, role: &'static str, candidate_id: String, selector_id: String, operator_id: String, resource_budget: String, candidate_artifact_path: String, candidate_artifact_bytes: String, candidate_slm_checksum: String, candidate_model_shape: String, candidate_quantization: String, candidate_output_contract: String, candidate_tokenizer_checksum: String, candidate_tensor_layout_checksum: String, population_fitness_ppm: u64, next_route: String, seed_weight_ppm: u64, } struct ParentContract { model_shape: String, quantization: String, output_contract: String, tokenizer_checksum: String, tensor_layout_checksum: String, } /// Writes a deterministic parent-pool recipe from a population review. pub(crate) fn write_recipe_path( ledger: &Path, review: &Path, output: &Path, admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_admissions(admission_paths, "parent-pool-recipe")?; let ledger_text = fs::read_to_string(ledger)?; let review_text = fs::read_to_string(review)?; let recipe = build_recipe_text(&ledger_text, &review_text, &admission_texts)?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, recipe)?; println!("SLM parent-pool recipe written: {}", output.display()); Ok(()) } /// Validates a parent-pool recipe against its review, ledger, and admission records. pub(crate) fn validate_recipe_path( ledger: &Path, review: &Path, recipe: &Path, admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_admissions(admission_paths, "validate-parent-pool-recipe")?; let ledger_text = fs::read_to_string(ledger)?; let review_text = fs::read_to_string(review)?; let recipe_text = fs::read_to_string(recipe)?; validate_recipe_text(&ledger_text, &review_text, &recipe_text, &admission_texts)?; println!("SLM parent-pool recipe validation: PASS"); println!("ledger: {}", ledger.display()); println!("review: {}", review.display()); println!("recipe: {}", recipe.display()); println!("admissions: {}", admission_paths.len()); Ok(()) } fn read_admissions(admission_paths: &[String], command: &str) -> io::Result> { if admission_paths.is_empty() { return Err(invalid(&format!( "{command} requires at least one admission record" ))); } admission_paths .iter() .map(|path| fs::read_to_string(Path::new(path))) .collect() } /// Builds the replayable parent-pool recipe that downstream multi-parent operators consume. pub(crate) fn build_recipe_text( ledger_text: &str, review_text: &str, admission_texts: &[String], ) -> io::Result { population::validate_review_text(ledger_text, review_text, admission_texts)?; let ledger_fields = parse_manifest(ledger_text, "promotion ledger")?; let review_fields = parse_manifest(review_text, "population review")?; let parent_count = parse_usize( require_key(&review_fields, "reviewed_candidate_count")?, "reviewed_candidate_count", )?; let mut parents = parent_entries(&review_fields, &ledger_fields, parent_count)?; let contract = require_shared_contract(&parents)?; assign_seed_weights(&mut parents)?; let relatedness_pair_count = relatedness_pair_count(parents.len())?; let relatedness_contract_checksum = relatedness_contract_checksum(&contract, &parents); let mut text = String::new(); push_line( &mut text, "tinyrustlm_parent_pool_recipe_version", RECIPE_VERSION, ); push_line(&mut text, "recipe_id", RECIPE_ID); push_line(&mut text, "recipe_scope", RECIPE_SCOPE); push_line(&mut text, "recipe_status", RECIPE_STATUS); push_line(&mut text, "recipe_basis", RECIPE_BASIS); push_line(&mut text, "recipe_kind", RECIPE_KIND); push_line(&mut text, "parent_selection", PARENT_SELECTION); push_line(&mut text, "seed_weight_formula", SEED_WEIGHT_FORMULA); push_line(&mut text, "parent_contract_status", PARENT_CONTRACT_STATUS); push_line( &mut text, "population_review_checksum", &hex64(provenance::text_checksum(review_text.as_bytes())), ); push_line( &mut text, "promotion_ledger_checksum", require_key(&review_fields, "promotion_ledger_checksum")?, ); push_line( &mut text, "admission_set_checksum", require_key(&review_fields, "admission_set_checksum")?, ); push_line( &mut text, "frontier_candidate_id", require_key(&review_fields, "frontier_candidate_id")?, ); push_line( &mut text, "frontier_candidate_slm_checksum", require_key(&review_fields, "frontier_candidate_slm_checksum")?, ); push_line(&mut text, "parent_count", &parents.len().to_string()); push_line(&mut text, "contract_model_shape", &contract.model_shape); push_line(&mut text, "contract_quantization", &contract.quantization); push_line( &mut text, "contract_output_contract", &contract.output_contract, ); push_line( &mut text, "contract_tokenizer_checksum", &contract.tokenizer_checksum, ); push_line( &mut text, "contract_tensor_layout_checksum", &contract.tensor_layout_checksum, ); push_line(&mut text, "relatedness_metric", RELATEDNESS_METRIC); push_line(&mut text, "relatedness_scope", RELATEDNESS_SCOPE); push_line( &mut text, "relatedness_pair_count", &relatedness_pair_count.to_string(), ); push_line( &mut text, "relatedness_all_pairs_status", RELATEDNESS_ALL_PAIRS_STATUS, ); push_line( &mut text, "relatedness_contract_checksum", &relatedness_contract_checksum, ); for (index, parent) in parents.iter().enumerate() { push_parent_lines(&mut text, index, parent, &relatedness_contract_checksum); } let evolution_schedule_text = build_evolution_schedule_text(&parents, &relatedness_contract_checksum); text.push_str(&evolution_schedule_text); push_line( &mut text, "evolution_schedule_checksum_algorithm", EVOLUTION_SCHEDULE_CHECKSUM_ALGORITHM, ); push_line( &mut text, "evolution_schedule_checksum", &hex64(provenance::text_checksum( evolution_schedule_text.as_bytes(), )), ); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } pub(crate) fn validate_recipe_text( ledger_text: &str, review_text: &str, recipe_text: &str, admission_texts: &[String], ) -> io::Result<()> { let expected_text = build_recipe_text(ledger_text, review_text, admission_texts)?; let expected = parse_manifest(&expected_text, "expected parent-pool recipe")?; let actual = parse_manifest(recipe_text, "parent-pool recipe")?; require_equal( &actual, "tinyrustlm_parent_pool_recipe_version", RECIPE_VERSION, )?; require_equal(&actual, "recipe_id", RECIPE_ID)?; require_equal(&actual, "recipe_scope", RECIPE_SCOPE)?; require_equal(&actual, "recipe_status", RECIPE_STATUS)?; require_equal(&actual, "recipe_basis", RECIPE_BASIS)?; require_equal(&actual, "recipe_kind", RECIPE_KIND)?; require_equal(&actual, "required_next_gate", REQUIRED_NEXT_GATE)?; for (key, expected_value) in &expected { require_equal(&actual, key, expected_value)?; } for key in actual.keys() { if !expected.contains_key(key) { return Err(invalid(&format!("unexpected parent-pool recipe key {key}"))); } } Ok(()) } fn parent_entries( review_fields: &HashMap, ledger_fields: &HashMap, parent_count: usize, ) -> io::Result> { if parent_count == 0 { return Err(invalid("parent-pool recipe requires at least one parent")); } let mut parents = Vec::with_capacity(parent_count); for review_index in 0..parent_count { let rank = parse_usize( require_review_entry_key(review_fields, review_index, "rank")?, "parent rank", )?; if rank != review_index + 1 { return Err(invalid(&format!( "parent-pool recipe rank {} was {rank}", review_index + 1 ))); } let ledger_index = parse_source_ledger_entry(require_review_entry_key( review_fields, review_index, "source_ledger_entry", )?)?; let role = if review_index == 0 { FRONTIER_ROLE } else { POOL_ROLE }; let candidate_id = review_entry_value(review_fields, review_index, "candidate_id")?; require_matching_ledger_value(ledger_fields, ledger_index, "candidate_id", &candidate_id)?; let candidate_slm_checksum = review_entry_value(review_fields, review_index, "candidate_slm_checksum")?; require_matching_ledger_value( ledger_fields, ledger_index, "candidate_slm_checksum", &candidate_slm_checksum, )?; let candidate_model_shape = review_entry_value(review_fields, review_index, "candidate_model_shape")?; require_matching_ledger_value( ledger_fields, ledger_index, "candidate_model_shape", &candidate_model_shape, )?; let candidate_quantization = review_entry_value(review_fields, review_index, "candidate_quantization")?; require_matching_ledger_value( ledger_fields, ledger_index, "candidate_quantization", &candidate_quantization, )?; let population_fitness_ppm = parse_u64( require_review_entry_key(review_fields, review_index, "population_fitness_ppm")?, "population_fitness_ppm", )?; parents.push(ParentEntry { rank, review_index, ledger_index, role, candidate_id, selector_id: review_entry_value(review_fields, review_index, "selector_id")?, operator_id: review_entry_value(review_fields, review_index, "operator_id")?, resource_budget: review_entry_value(review_fields, review_index, "resource_budget")?, candidate_artifact_path: review_entry_value( review_fields, review_index, "candidate_artifact_path", )?, candidate_artifact_bytes: review_entry_value( review_fields, review_index, "candidate_artifact_bytes", )?, candidate_slm_checksum, candidate_model_shape, candidate_quantization, candidate_output_contract: ledger_entry_value( ledger_fields, ledger_index, "candidate_output_contract", )?, candidate_tokenizer_checksum: ledger_entry_value( ledger_fields, ledger_index, "candidate_tokenizer_checksum", )?, candidate_tensor_layout_checksum: ledger_entry_value( ledger_fields, ledger_index, "candidate_tensor_layout_checksum", )?, population_fitness_ppm, next_route: review_entry_value(review_fields, review_index, "next_route")?, seed_weight_ppm: 0, }); } Ok(parents) } fn require_shared_contract(parents: &[ParentEntry]) -> io::Result { let first = parents .first() .ok_or_else(|| invalid("parent-pool recipe requires at least one parent"))?; for parent in parents.iter().skip(1) { if parent.candidate_model_shape != first.candidate_model_shape || parent.candidate_quantization != first.candidate_quantization || parent.candidate_output_contract != first.candidate_output_contract || parent.candidate_tokenizer_checksum != first.candidate_tokenizer_checksum || parent.candidate_tensor_layout_checksum != first.candidate_tensor_layout_checksum { return Err(invalid( "parent-pool recipe parents must share one direct-parameter contract", )); } } Ok(ParentContract { model_shape: first.candidate_model_shape.clone(), quantization: first.candidate_quantization.clone(), output_contract: first.candidate_output_contract.clone(), tokenizer_checksum: first.candidate_tokenizer_checksum.clone(), tensor_layout_checksum: first.candidate_tensor_layout_checksum.clone(), }) } fn assign_seed_weights(parents: &mut [ParentEntry]) -> io::Result<()> { let total_fitness: u128 = parents .iter() .map(|parent| u128::from(parent.population_fitness_ppm)) .sum(); if total_fitness == 0 { return Err(invalid( "parent-pool recipe requires positive population fitness", )); } let mut assigned = 0u64; let last_index = parents.len() - 1; for (index, parent) in parents.iter_mut().enumerate() { if index == last_index { parent.seed_weight_ppm = PPM_DENOMINATOR .checked_sub(assigned) .ok_or_else(|| invalid("parent-pool seed weights exceeded 1000000 ppm"))?; } else { let weight = ((u128::from(parent.population_fitness_ppm) * u128::from(PPM_DENOMINATOR)) / total_fitness) .try_into() .map_err(|_| invalid("parent-pool seed weight exceeded supported ppm range"))?; parent.seed_weight_ppm = weight; assigned = assigned .checked_add(weight) .ok_or_else(|| invalid("parent-pool seed weight overflow"))?; } } Ok(()) } fn relatedness_pair_count(parent_count: usize) -> io::Result { let count = parent_count as u128; let pair_count = count .checked_mul(count.saturating_sub(1)) .ok_or_else(|| invalid("parent-pool relatedness pair count overflow"))? / 2; pair_count .try_into() .map_err(|_| invalid("parent-pool relatedness pair count exceeded supported range")) } fn relatedness_contract_checksum(contract: &ParentContract, parents: &[ParentEntry]) -> String { let mut text = String::new(); push_line(&mut text, "relatedness_metric", RELATEDNESS_METRIC); push_line(&mut text, "relatedness_scope", RELATEDNESS_SCOPE); push_line(&mut text, "parent_count", &parents.len().to_string()); push_line(&mut text, "contract_model_shape", &contract.model_shape); push_line(&mut text, "contract_quantization", &contract.quantization); push_line( &mut text, "contract_output_contract", &contract.output_contract, ); push_line( &mut text, "contract_tokenizer_checksum", &contract.tokenizer_checksum, ); push_line( &mut text, "contract_tensor_layout_checksum", &contract.tensor_layout_checksum, ); for (index, parent) in parents.iter().enumerate() { let prefix = format!("parent.{index}"); push_line( &mut text, &format!("{prefix}.rank"), &parent.rank.to_string(), ); push_line(&mut text, &format!("{prefix}.role"), parent.role); push_line( &mut text, &format!("{prefix}.candidate_id"), &parent.candidate_id, ); push_line( &mut text, &format!("{prefix}.selector_id"), &parent.selector_id, ); push_line( &mut text, &format!("{prefix}.operator_id"), &parent.operator_id, ); push_line( &mut text, &format!("{prefix}.candidate_slm_checksum"), &parent.candidate_slm_checksum, ); } hex64(provenance::text_checksum(text.as_bytes())) } fn push_parent_lines( text: &mut String, index: usize, parent: &ParentEntry, relatedness_contract_checksum: &str, ) { let prefix = format!("parent.{index}"); push_line(text, &format!("{prefix}.rank"), &parent.rank.to_string()); push_line(text, &format!("{prefix}.role"), parent.role); push_line(text, &format!("{prefix}.selection_status"), SELECTED_STATUS); push_line( text, &format!("{prefix}.source_review_entry"), &format!("entry.{}", parent.review_index), ); push_line( text, &format!("{prefix}.source_ledger_entry"), &format!("entry.{}", parent.ledger_index), ); push_line( text, &format!("{prefix}.candidate_id"), &parent.candidate_id, ); push_line(text, &format!("{prefix}.selector_id"), &parent.selector_id); push_line(text, &format!("{prefix}.operator_id"), &parent.operator_id); push_line( text, &format!("{prefix}.resource_budget"), &parent.resource_budget, ); push_line( text, &format!("{prefix}.candidate_artifact_path"), &parent.candidate_artifact_path, ); push_line( text, &format!("{prefix}.candidate_artifact_bytes"), &parent.candidate_artifact_bytes, ); push_line( text, &format!("{prefix}.candidate_slm_checksum"), &parent.candidate_slm_checksum, ); push_line( text, &format!("{prefix}.candidate_model_shape"), &parent.candidate_model_shape, ); push_line( text, &format!("{prefix}.candidate_quantization"), &parent.candidate_quantization, ); push_line( text, &format!("{prefix}.candidate_output_contract"), &parent.candidate_output_contract, ); push_line( text, &format!("{prefix}.candidate_tokenizer_checksum"), &parent.candidate_tokenizer_checksum, ); push_line( text, &format!("{prefix}.candidate_tensor_layout_checksum"), &parent.candidate_tensor_layout_checksum, ); push_line( text, &format!("{prefix}.relatedness_group"), RELATEDNESS_GROUP, ); push_line( text, &format!("{prefix}.relatedness_contract_checksum"), relatedness_contract_checksum, ); push_line( text, &format!("{prefix}.population_fitness_ppm"), &parent.population_fitness_ppm.to_string(), ); push_line( text, &format!("{prefix}.seed_weight_ppm"), &parent.seed_weight_ppm.to_string(), ); push_line(text, &format!("{prefix}.next_route"), &parent.next_route); } // Captures the planned multi-parent operator families and the seed weights they will replay. fn build_evolution_schedule_text( parents: &[ParentEntry], relatedness_contract_checksum: &str, ) -> String { let mut text = String::new(); push_line( &mut text, "evolution_recipe_version", EVOLUTION_RECIPE_VERSION, ); push_line( &mut text, "evolution_recipe_strategy", EVOLUTION_RECIPE_STRATEGY, ); push_line( &mut text, "evolution_recipe_status", EVOLUTION_RECIPE_STATUS, ); push_line( &mut text, "evolution_selection_source", EVOLUTION_SELECTION_SOURCE, ); push_line( &mut text, "evolution_parent_count", &parents.len().to_string(), ); push_line( &mut text, "evolution_relatedness_contract_checksum", relatedness_contract_checksum, ); push_line( &mut text, "evolution_operator_family_count", &EVOLUTION_OPERATOR_FAMILIES.len().to_string(), ); for (index, family) in EVOLUTION_OPERATOR_FAMILIES.iter().enumerate() { let prefix = format!("evolution_operator_family.{index}"); push_line( &mut text, &format!("{prefix}.operator_kind"), family.operator_kind, ); push_line(&mut text, &format!("{prefix}.command"), family.command); push_line( &mut text, &format!("{prefix}.selection_rule"), family.selection_rule, ); push_line( &mut text, &format!("{prefix}.output_gate"), family.output_gate, ); } for (index, parent) in parents.iter().enumerate() { let prefix = format!("evolution_parent.{index}"); push_line( &mut text, &format!("{prefix}.candidate_id"), &parent.candidate_id, ); push_line( &mut text, &format!("{prefix}.seed_weight_ppm"), &parent.seed_weight_ppm.to_string(), ); push_line( &mut text, &format!("{prefix}.population_fitness_ppm"), &parent.population_fitness_ppm.to_string(), ); } text } fn require_matching_ledger_value( fields: &HashMap, ledger_index: usize, key: &str, expected: &str, ) -> io::Result<()> { let actual = ledger_entry_value(fields, ledger_index, key)?; if actual != expected { return Err(invalid(&format!( "parent-pool recipe ledger entry {ledger_index} key {key} was {actual}, expected {expected}" ))); } Ok(()) } fn require_review_entry_key<'a>( fields: &'a HashMap, entry_index: usize, key: &str, ) -> io::Result<&'a str> { require_key(fields, &format!("entry.{entry_index}.{key}")) } fn review_entry_value( fields: &HashMap, entry_index: usize, key: &str, ) -> io::Result { Ok(require_review_entry_key(fields, entry_index, key)?.to_string()) } fn ledger_entry_value( fields: &HashMap, entry_index: usize, key: &str, ) -> io::Result { Ok(require_key(fields, &format!("entry.{entry_index}.{key}"))?.to_string()) } fn parse_source_ledger_entry(value: &str) -> io::Result { let Some(index) = value.strip_prefix("entry.") else { return Err(invalid( "parent-pool source_ledger_entry must start with entry.", )); }; parse_usize(index, "source_ledger_entry") } fn parse_usize(value: &str, label: &str) -> io::Result { value.parse::().map_err(|_| { invalid(&format!( "parent-pool recipe {label} must be an unsigned integer" )) }) } fn parse_u64(value: &str, label: &str) -> io::Result { value.parse::().map_err(|_| { invalid(&format!( "parent-pool recipe {label} must be an unsigned integer" )) }) } #[cfg(test)] mod tests { use super::*; use crate::admission; use crate::build_model_file_from_values_with_flags; use crate::candidate; use crate::compatibility; use crate::fixture_value; use crate::ledger; use crate::lineage; use crate::promotion; use crate::slm_validate; use crate::tensor_writer::{ tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_F32, DTYPE_Q8_0, }; use crate::tokenizer_writer::ByteTokenizerSection; use std::time::{SystemTime, UNIX_EPOCH}; #[test] fn writes_ranked_parent_pool_recipe_from_population_review() { let alpha = fixture_admission( "tiny-alpha-candidate", "target/parent-pool/tiny-alpha.slm", tiny_fixture_f32_bytes_with_offset(0.0), ); let beta = fixture_admission( "tiny-beta-candidate", "target/parent-pool/tiny-beta.slm", tiny_fixture_f32_bytes_with_offset(0.002), ); let ledger = ledger::build_ledger_text(&[beta.clone(), alpha.clone()]).unwrap(); let review = population::build_review_text(&ledger, &[beta.clone(), alpha.clone()]).unwrap(); let recipe = build_recipe_text(&ledger, &review, &[beta, alpha]).unwrap(); assert!(recipe.contains("recipe_kind=sign-aware-parent-pool-v1")); assert!(recipe.contains("frontier_candidate_id=tiny-alpha-candidate")); assert!(recipe.contains("parent_count=2")); assert!(recipe.contains("relatedness_metric=shared-direct-parameter-contract-v1")); assert!(recipe.contains("relatedness_scope=selected-parent-pool")); assert!(recipe.contains("relatedness_pair_count=1")); assert!(recipe.contains("relatedness_all_pairs_status=shared-direct-parameter-contract")); assert!(recipe.contains("relatedness_contract_checksum=0x")); assert!(recipe.contains("parent.0.role=frontier")); assert!(recipe.contains("parent.1.role=parent-pool")); assert!(recipe.contains("parent.0.relatedness_group=direct-parameter-family.0")); assert!(recipe.contains("parent.1.relatedness_contract_checksum=0x")); assert!(recipe.contains("parent.0.seed_weight_ppm=500000")); assert!(recipe.contains("parent.1.seed_weight_ppm=500000")); assert!(recipe.contains("evolution_recipe_strategy=population-based-parent-pool-replay-v1")); assert!(recipe.contains("evolution_operator_family_count=2")); assert!(recipe .contains("evolution_operator_family.0.operator_kind=sign-aware-parent-pool-merge")); assert!(recipe.contains("evolution_operator_family.0.command=sign-merge-candidate")); assert!(recipe .contains("evolution_operator_family.1.operator_kind=seed-weighted-parent-pool-soup")); assert!(recipe.contains("evolution_operator_family.1.command=soup-candidate")); assert!(recipe.contains("evolution_parent.0.seed_weight_ppm=500000")); assert!(recipe.contains("evolution_parent.1.seed_weight_ppm=500000")); assert!( recipe.contains("evolution_schedule_checksum_algorithm=tinyrustlm-text-checksum-v1") ); assert!(recipe.contains("evolution_schedule_checksum=0x")); } #[test] fn validates_parent_pool_recipe_text() { let alpha = fixture_admission( "tiny-alpha-candidate", "target/parent-pool/validate-alpha.slm", tiny_fixture_f32_bytes_with_offset(0.0), ); let beta = fixture_admission( "tiny-beta-candidate", "target/parent-pool/validate-beta.slm", tiny_fixture_f32_bytes_with_offset(0.003), ); let ledger = ledger::build_ledger_text(&[alpha.clone(), beta.clone()]).unwrap(); let review = population::build_review_text(&ledger, &[alpha.clone(), beta.clone()]).unwrap(); let recipe = build_recipe_text(&ledger, &review, &[alpha.clone(), beta.clone()]).unwrap(); validate_recipe_text(&ledger, &review, &recipe, &[alpha, beta]).unwrap(); } #[test] fn rejects_parent_pool_recipe_drift() { let alpha = fixture_admission( "tiny-alpha-candidate", "target/parent-pool/drift-alpha.slm", tiny_fixture_f32_bytes_with_offset(0.0), ); let beta = fixture_admission( "tiny-beta-candidate", "target/parent-pool/drift-beta.slm", tiny_fixture_f32_bytes_with_offset(0.004), ); let ledger = ledger::build_ledger_text(&[alpha.clone(), beta.clone()]).unwrap(); let review = population::build_review_text(&ledger, &[alpha.clone(), beta.clone()]).unwrap(); let recipe = build_recipe_text(&ledger, &review, &[alpha.clone(), beta.clone()]) .unwrap() .replace( "frontier_candidate_id=tiny-alpha-candidate", "frontier_candidate_id=tiny-beta-candidate", ); let error = validate_recipe_text(&ledger, &review, &recipe, &[alpha, beta]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("frontier_candidate_id")); } #[test] fn rejects_relatedness_checksum_drift() { let alpha = fixture_admission( "tiny-alpha-candidate", "target/parent-pool/relatedness-alpha.slm", tiny_fixture_f32_bytes_with_offset(0.0), ); let beta = fixture_admission( "tiny-beta-candidate", "target/parent-pool/relatedness-beta.slm", tiny_fixture_f32_bytes_with_offset(0.0045), ); let ledger = ledger::build_ledger_text(&[alpha.clone(), beta.clone()]).unwrap(); let review = population::build_review_text(&ledger, &[alpha.clone(), beta.clone()]).unwrap(); let recipe = build_recipe_text(&ledger, &review, &[alpha.clone(), beta.clone()]).unwrap(); let fields = parse_manifest(&recipe, "parent-pool recipe").unwrap(); let checksum = require_key(&fields, "relatedness_contract_checksum").unwrap(); let tampered_recipe = recipe.replace( &format!("relatedness_contract_checksum={checksum}"), "relatedness_contract_checksum=0x0000000000000000", ); let error = validate_recipe_text(&ledger, &review, &tampered_recipe, &[alpha, beta]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("relatedness_contract_checksum")); } #[test] fn rejects_evolution_schedule_checksum_drift() { let alpha = fixture_admission( "tiny-alpha-candidate", "target/parent-pool/evolution-alpha.slm", tiny_fixture_f32_bytes_with_offset(0.0), ); let beta = fixture_admission( "tiny-beta-candidate", "target/parent-pool/evolution-beta.slm", tiny_fixture_f32_bytes_with_offset(0.0048), ); let ledger = ledger::build_ledger_text(&[alpha.clone(), beta.clone()]).unwrap(); let review = population::build_review_text(&ledger, &[alpha.clone(), beta.clone()]).unwrap(); let recipe = build_recipe_text(&ledger, &review, &[alpha.clone(), beta.clone()]).unwrap(); let fields = parse_manifest(&recipe, "parent-pool recipe").unwrap(); let checksum = require_key(&fields, "evolution_schedule_checksum").unwrap(); let tampered_recipe = recipe.replace( &format!("evolution_schedule_checksum={checksum}"), "evolution_schedule_checksum=0x0000000000000000", ); let error = validate_recipe_text(&ledger, &review, &tampered_recipe, &[alpha, beta]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("evolution_schedule_checksum")); } #[test] fn rejects_population_review_drift_before_recipe() { let alpha = fixture_admission( "tiny-alpha-candidate", "target/parent-pool/review-drift-alpha.slm", tiny_fixture_f32_bytes_with_offset(0.0), ); let beta = fixture_admission( "tiny-beta-candidate", "target/parent-pool/review-drift-beta.slm", tiny_fixture_f32_bytes_with_offset(0.005), ); let ledger = ledger::build_ledger_text(&[alpha.clone(), beta.clone()]).unwrap(); let review = population::build_review_text(&ledger, &[alpha.clone(), beta.clone()]) .unwrap() .replace( "entry.0.population_fitness_ppm=970000", "entry.0.population_fitness_ppm=1", ); let error = build_recipe_text(&ledger, &review, &[alpha, beta]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } #[test] fn rejects_mixed_direct_parameter_contracts() { let f32 = fixture_admission( "tiny-f32-candidate", "target/parent-pool/mixed-f32.slm", tiny_fixture_f32_bytes_with_offset(0.0), ); let q8 = fixture_admission( "tiny-q8-candidate", "target/parent-pool/mixed-q8.slm", tiny_fixture_q8_bytes(), ); let ledger = ledger::build_ledger_text(&[f32.clone(), q8.clone()]).unwrap(); let review = population::build_review_text(&ledger, &[f32.clone(), q8.clone()]).unwrap(); let error = build_recipe_text(&ledger, &review, &[f32, q8]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("direct-parameter contract")); } #[test] fn writes_and_validates_parent_pool_recipe_paths() { let dir = unique_dir("paths"); std::fs::create_dir_all(&dir).unwrap(); let alpha = fixture_admission( "tiny-alpha-candidate", "target/parent-pool/path-alpha.slm", tiny_fixture_f32_bytes_with_offset(0.0), ); let beta = fixture_admission( "tiny-beta-candidate", "target/parent-pool/path-beta.slm", tiny_fixture_f32_bytes_with_offset(0.006), ); let alpha_path = dir.join("alpha.admission"); let beta_path = dir.join("beta.admission"); let ledger_path = dir.join("pool.ledger"); let review_path = dir.join("pool.review"); let recipe_path = dir.join("pool.recipe"); std::fs::write(&alpha_path, alpha).unwrap(); std::fs::write(&beta_path, beta).unwrap(); let admissions = vec![ alpha_path.to_string_lossy().to_string(), beta_path.to_string_lossy().to_string(), ]; ledger::write_ledger_path(&ledger_path, &admissions).unwrap(); population::write_review_path(&ledger_path, &review_path, &admissions).unwrap(); write_recipe_path(&ledger_path, &review_path, &recipe_path, &admissions).unwrap(); validate_recipe_path(&ledger_path, &review_path, &recipe_path, &admissions).unwrap(); let recipe = std::fs::read_to_string(recipe_path).unwrap(); assert!(recipe.contains("recipe_status=population-reviewed")); assert!(recipe.contains("parent_contract_status=shared-direct-parameter-contract")); } fn fixture_admission(candidate_id: &str, candidate_path: &str, candidate: Vec) -> String { let compatibility = compatibility::compatibility_text_for_bytes( &candidate, "left.slm", &candidate, "right.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, candidate_id, "operator-a", "fit") .unwrap(); let candidate_manifest = candidate::build_manifest_text(&compatibility, &lineage, &candidate, candidate_path) .unwrap(); let promotion = promotion::build_template_text( &compatibility, &lineage, &candidate, candidate_path, &candidate_manifest, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, ) .unwrap(); let report = slm_validate::validate_bytes(&candidate, candidate_path).unwrap(); let provenance_manifest = provenance::build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = provenance::parse_manifest(&provenance_manifest).unwrap(); let runtime_smoke = provenance::build_runtime_smoke_text(&report, &provenance_manifest, &manifest_fields) .unwrap(); let eval = passing_eval_text(&report, &provenance_manifest); admission::build_record_text( &compatibility, &lineage, &candidate, candidate_path, &candidate_manifest, &promotion, &provenance_manifest, &runtime_smoke, &eval, admission::DEFAULT_ADMISSION_SELECTOR_ID, ) .unwrap() } fn passing_eval_text(report: &slm_validate::ValidationReport, manifest: &str) -> String { let mut text = String::new(); push_line(&mut text, "tinyrustlm_eval_manifest_version", "1"); push_line(&mut text, "gate", "assistant-quality"); push_line(&mut text, "source_kind", "converted-trained"); push_line( &mut text, "manifest_checksum", &hex64(provenance::text_checksum(manifest.as_bytes())), ); push_line(&mut text, "slm_checksum", &hex64(report.checksum())); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "task_eval_status", "pass"); push_line(&mut text, "safety_review_status", "pass"); push_line( &mut text, "quality_decision", "accepted-for-assistant-quality", ); push_line(&mut text, "quality_scope", "tiny-fixture-runtime-eval-only"); push_line(&mut text, "evaluator", "local-reviewed-eval"); push_line( &mut text, "eval_dataset", "tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", ); push_line( &mut text, "eval_summary", "Reviewed task and safety evidence passed for declared scope", ); push_line( &mut text, "quality_boundary", "fixture-runtime-and-eval-plumbing-not-product-assistant-quality", ); push_line(&mut text, "case_count", "1"); push_line(&mut text, "cases_passed", "1"); push_line(&mut text, "cases_failed", "0"); push_line(&mut text, "case.0.status", "pass"); push_line(&mut text, "case.0.expected", "e"); push_line(&mut text, "case.0.actual", "e"); push_line(&mut text, "case.0.error", "ok"); text } fn tiny_fixture_f32_bytes_with_offset(offset: f32) -> Vec { let tensors = tiny_fixture_tensors_with_dtype(DTYPE_F32); let values: Vec> = tensors .iter() .map(|tensor| { (0..tensor.element_count()) .map(|elem| fixture_value(tensor, elem) + offset) .collect() }) .collect(); build_model_file_from_values_with_flags( &ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } fn tiny_fixture_q8_bytes() -> Vec { let tensors = tiny_fixture_tensors_with_dtype(DTYPE_Q8_0); let values: Vec> = tensors .iter() .map(|tensor| { (0..tensor.element_count()) .map(|elem| fixture_value(tensor, elem)) .collect() }) .collect(); build_model_file_from_values_with_flags( &ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } fn unique_dir(label: &str) -> std::path::PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::path::Path::new("target") .join("parent-pool-tests") .join(format!("{label}-{}-{nanos}", std::process::id())) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/parent_pool.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/population.rs BYTES: 32311 SHA256: 48310799260A95B602BC3580E4FD11A2590BD7875A2AB0859B2C0CBA669B0648 ================================================================================ //! Offline population reviews for admitted model-breeding candidates. use std::cmp::Ordering; use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::blend::{hex64, invalid, parse_manifest, push_line, require_equal, require_key}; use crate::ledger; use crate::provenance; const REVIEW_VERSION: &str = "1"; const REVIEW_ID: &str = "browser-local-population-review"; const REVIEW_SCOPE: &str = "offline-model-breeding-population-review"; const REVIEW_STATUS: &str = "ledger-reviewed"; const REVIEW_BASIS: &str = "promotion-ledger-plus-admission-records"; const RANKING_FORMULA: &str = "quality700-frugality200-quantization100"; const RANKING_TIE_BREAK: &str = "fitness-desc-cases-passed-desc-model-bytes-asc-candidate-id-asc"; const FITNESS_OBJECTIVE_VECTOR_VERSION: &str = "1"; const FITNESS_OBJECTIVE_VECTOR_KIND: &str = "weighted-quality-frugality-quantization-v1"; const FITNESS_OBJECTIVE_WEIGHT_UNIT: &str = "ppm"; const FRONTIER_DECISION: &str = "frontier-candidate"; const POOL_DECISION: &str = "candidate-kept-for-population"; const FRONTIER_ROUTE: &str = "selector-registry"; const POOL_ROUTE: &str = "population-parent-pool"; const REQUIRED_NEXT_GATE: &str = "selector-registry-or-parent-selection"; const PPM_DENOMINATOR: u64 = 1_000_000; const QUALITY_WEIGHT: u64 = 700; const FRUGALITY_WEIGHT: u64 = 200; const QUANTIZATION_WEIGHT: u64 = 100; const WEIGHT_DENOMINATOR: u64 = 1_000; const QUALITY_WEIGHT_PPM: u64 = (QUALITY_WEIGHT * PPM_DENOMINATOR) / WEIGHT_DENOMINATOR; const FRUGALITY_WEIGHT_PPM: u64 = (FRUGALITY_WEIGHT * PPM_DENOMINATOR) / WEIGHT_DENOMINATOR; const QUANTIZATION_WEIGHT_PPM: u64 = (QUANTIZATION_WEIGHT * PPM_DENOMINATOR) / WEIGHT_DENOMINATOR; struct FitnessObjective { name: &'static str, source: &'static str, weight_ppm: u64, } const FITNESS_OBJECTIVES: [FitnessObjective; 3] = [ FitnessObjective { name: "quality", source: "cases-passed-over-case-count", weight_ppm: QUALITY_WEIGHT_PPM, }, FitnessObjective { name: "frugality", source: "minimum-artifact-bytes-over-candidate-artifact-bytes", weight_ppm: FRUGALITY_WEIGHT_PPM, }, FitnessObjective { name: "quantization_fit", source: "quantization-label-fit", weight_ppm: QUANTIZATION_WEIGHT_PPM, }, ]; struct LedgerEntry { ledger_index: usize, candidate_id: String, selector_id: String, operator_id: String, operator_lane: String, resource_budget: String, candidate_artifact_path: String, candidate_artifact_bytes: u64, candidate_slm_checksum: String, candidate_model_shape: String, candidate_quantization: String, quality_scope: String, eval_dataset: String, case_count: u64, cases_passed: u64, } struct RankedEntry { entry: LedgerEntry, quality_ppm: u64, frugality_ppm: u64, quantization_fit_ppm: u64, population_fitness_ppm: u64, } /// Writes a deterministic population review from a promotion ledger and admissions. pub(crate) fn write_review_path( ledger: &Path, output: &Path, admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_admissions(admission_paths, "population-review")?; let ledger_text = fs::read_to_string(ledger)?; let review = build_review_text(&ledger_text, &admission_texts)?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, review)?; println!("SLM population review written: {}", output.display()); Ok(()) } /// Validates a population review against its ledger and admission records. pub(crate) fn validate_review_path( ledger: &Path, review: &Path, admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_admissions(admission_paths, "validate-population-review")?; let ledger_text = fs::read_to_string(ledger)?; let review_text = fs::read_to_string(review)?; validate_review_text(&ledger_text, &review_text, &admission_texts)?; println!("SLM population review validation: PASS"); println!("ledger: {}", ledger.display()); println!("review: {}", review.display()); println!("admissions: {}", admission_paths.len()); Ok(()) } fn read_admissions(admission_paths: &[String], command: &str) -> io::Result> { if admission_paths.is_empty() { return Err(invalid(&format!( "{command} requires at least one admission record" ))); } admission_paths .iter() .map(|path| fs::read_to_string(Path::new(path))) .collect() } pub(crate) fn build_review_text( ledger_text: &str, admission_texts: &[String], ) -> io::Result { ledger::validate_ledger_text(ledger_text, admission_texts)?; let ledger_fields = parse_manifest(ledger_text, "promotion ledger")?; let entry_count = parse_usize(require_key(&ledger_fields, "entry_count")?, "entry_count")?; let entries = ledger_entries(&ledger_fields, entry_count)?; let min_bytes = entries .iter() .map(|entry| entry.candidate_artifact_bytes) .min() .ok_or_else(|| invalid("population review requires at least one ledger entry"))?; let mut ranked = entries .into_iter() .map(|entry| rank_entry(entry, min_bytes)) .collect::>>()?; ranked.sort_by(compare_ranked_entries); let frontier = ranked .first() .ok_or_else(|| invalid("population review requires at least one ranked entry"))?; let mut text = String::new(); push_line( &mut text, "tinyrustlm_population_review_version", REVIEW_VERSION, ); push_line(&mut text, "review_id", REVIEW_ID); push_line(&mut text, "review_scope", REVIEW_SCOPE); push_line(&mut text, "review_status", REVIEW_STATUS); push_line(&mut text, "review_basis", REVIEW_BASIS); push_line( &mut text, "promotion_ledger_checksum", &hex64(provenance::text_checksum(ledger_text.as_bytes())), ); push_line( &mut text, "ledger_scope", require_key(&ledger_fields, "ledger_scope")?, ); push_line( &mut text, "ledger_status", require_key(&ledger_fields, "ledger_status")?, ); push_line(&mut text, "ledger_entry_count", &entry_count.to_string()); push_line( &mut text, "admission_set_checksum", require_key(&ledger_fields, "admission_set_checksum")?, ); push_line( &mut text, "ledger_chain_checksum", require_key(&ledger_fields, "ledger_chain_checksum")?, ); push_line(&mut text, "ranking_formula", RANKING_FORMULA); push_line(&mut text, "ranking_tie_break", RANKING_TIE_BREAK); text.push_str(&fitness_objective_vector_contract_text()); push_line( &mut text, "fitness_objective_vector_checksum", &fitness_objective_vector_checksum(), ); push_line( &mut text, "reviewed_candidate_count", &ranked.len().to_string(), ); push_line( &mut text, "frontier_candidate_id", &frontier.entry.candidate_id, ); push_line( &mut text, "frontier_candidate_slm_checksum", &frontier.entry.candidate_slm_checksum, ); push_line( &mut text, "frontier_population_fitness_ppm", &frontier.population_fitness_ppm.to_string(), ); for (rank_index, ranked_entry) in ranked.iter().enumerate() { push_ranked_entry(&mut text, rank_index, ranked_entry); } push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } pub(crate) fn validate_review_text( ledger_text: &str, review_text: &str, admission_texts: &[String], ) -> io::Result<()> { let expected_text = build_review_text(ledger_text, admission_texts)?; let expected = parse_manifest(&expected_text, "expected population review")?; let actual = parse_manifest(review_text, "population review")?; require_equal( &actual, "tinyrustlm_population_review_version", REVIEW_VERSION, )?; require_equal(&actual, "review_id", REVIEW_ID)?; require_equal(&actual, "review_scope", REVIEW_SCOPE)?; require_equal(&actual, "review_status", REVIEW_STATUS)?; require_equal(&actual, "review_basis", REVIEW_BASIS)?; require_equal(&actual, "required_next_gate", REQUIRED_NEXT_GATE)?; for (key, expected_value) in &expected { require_equal(&actual, key, expected_value)?; } for key in actual.keys() { if !expected.contains_key(key) { return Err(invalid(&format!("unexpected population review key {key}"))); } } Ok(()) } fn ledger_entries( ledger_fields: &HashMap, entry_count: usize, ) -> io::Result> { if entry_count == 0 { return Err(invalid( "population review requires at least one ledger entry", )); } let mut entries = Vec::with_capacity(entry_count); for ledger_index in 0..entry_count { let sequence = parse_usize( require_entry_key(ledger_fields, ledger_index, "sequence")?, "ledger entry sequence", )?; if sequence != ledger_index { return Err(invalid(&format!( "population review ledger entry {ledger_index} sequence was {sequence}" ))); } let candidate_artifact_bytes = parse_positive_u64( require_entry_key(ledger_fields, ledger_index, "candidate_artifact_bytes")?, "candidate_artifact_bytes", )?; let case_count = parse_positive_u64( require_entry_key(ledger_fields, ledger_index, "case_count")?, "case_count", )?; let cases_passed = parse_u64( require_entry_key(ledger_fields, ledger_index, "cases_passed")?, "cases_passed", )?; if cases_passed > case_count { return Err(invalid( "population review cases_passed cannot exceed case_count", )); } entries.push(LedgerEntry { ledger_index, candidate_id: entry_value(ledger_fields, ledger_index, "candidate_id")?, selector_id: entry_value(ledger_fields, ledger_index, "selector_id")?, operator_id: entry_value(ledger_fields, ledger_index, "operator_id")?, operator_lane: entry_value(ledger_fields, ledger_index, "operator_lane")?, resource_budget: entry_value(ledger_fields, ledger_index, "resource_budget")?, candidate_artifact_path: entry_value( ledger_fields, ledger_index, "candidate_artifact_path", )?, candidate_artifact_bytes, candidate_slm_checksum: entry_value( ledger_fields, ledger_index, "candidate_slm_checksum", )?, candidate_model_shape: entry_value( ledger_fields, ledger_index, "candidate_model_shape", )?, candidate_quantization: entry_value( ledger_fields, ledger_index, "candidate_quantization", )?, quality_scope: entry_value(ledger_fields, ledger_index, "quality_scope")?, eval_dataset: entry_value(ledger_fields, ledger_index, "eval_dataset")?, case_count, cases_passed, }); } Ok(entries) } fn rank_entry(entry: LedgerEntry, min_bytes: u64) -> io::Result { let quality_ppm = ppm_ratio(entry.cases_passed, entry.case_count, "quality")?; let frugality_ppm = ppm_ratio(min_bytes, entry.candidate_artifact_bytes, "frugality")?; let quantization_fit_ppm = quantization_fit_ppm(&entry.candidate_quantization); let weighted_sum = u128::from(quality_ppm) * u128::from(QUALITY_WEIGHT) + u128::from(frugality_ppm) * u128::from(FRUGALITY_WEIGHT) + u128::from(quantization_fit_ppm) * u128::from(QUANTIZATION_WEIGHT); let population_fitness_ppm = (weighted_sum / u128::from(WEIGHT_DENOMINATOR)) .try_into() .map_err(|_| invalid("population review fitness score exceeded supported ppm range"))?; Ok(RankedEntry { entry, quality_ppm, frugality_ppm, quantization_fit_ppm, population_fitness_ppm, }) } fn compare_ranked_entries(left: &RankedEntry, right: &RankedEntry) -> Ordering { right .population_fitness_ppm .cmp(&left.population_fitness_ppm) .then_with(|| right.entry.cases_passed.cmp(&left.entry.cases_passed)) .then_with(|| { left.entry .candidate_artifact_bytes .cmp(&right.entry.candidate_artifact_bytes) }) .then_with(|| left.entry.candidate_id.cmp(&right.entry.candidate_id)) } fn push_ranked_entry(text: &mut String, rank_index: usize, ranked_entry: &RankedEntry) { let prefix = format!("entry.{rank_index}"); let rank = (rank_index + 1).to_string(); let source_entry = format!("entry.{}", ranked_entry.entry.ledger_index); let candidate_artifact_bytes = ranked_entry.entry.candidate_artifact_bytes.to_string(); let case_count = ranked_entry.entry.case_count.to_string(); let cases_passed = ranked_entry.entry.cases_passed.to_string(); let quality_ppm = ranked_entry.quality_ppm.to_string(); let frugality_ppm = ranked_entry.frugality_ppm.to_string(); let quantization_fit_ppm = ranked_entry.quantization_fit_ppm.to_string(); let population_fitness_ppm = ranked_entry.population_fitness_ppm.to_string(); let fitness_objective_vector_checksum = ranked_entry_fitness_objective_vector_checksum(rank_index, ranked_entry); let decision = if rank_index == 0 { FRONTIER_DECISION } else { POOL_DECISION }; let next_route = if rank_index == 0 { FRONTIER_ROUTE } else { POOL_ROUTE }; push_line(text, &format!("{prefix}.rank"), &rank); push_line( text, &format!("{prefix}.source_ledger_entry"), &source_entry, ); push_line( text, &format!("{prefix}.candidate_id"), &ranked_entry.entry.candidate_id, ); push_line( text, &format!("{prefix}.selector_id"), &ranked_entry.entry.selector_id, ); push_line( text, &format!("{prefix}.operator_id"), &ranked_entry.entry.operator_id, ); push_line( text, &format!("{prefix}.operator_lane"), &ranked_entry.entry.operator_lane, ); push_line( text, &format!("{prefix}.resource_budget"), &ranked_entry.entry.resource_budget, ); push_line( text, &format!("{prefix}.candidate_artifact_path"), &ranked_entry.entry.candidate_artifact_path, ); push_line( text, &format!("{prefix}.candidate_artifact_bytes"), &candidate_artifact_bytes, ); push_line( text, &format!("{prefix}.candidate_slm_checksum"), &ranked_entry.entry.candidate_slm_checksum, ); push_line( text, &format!("{prefix}.candidate_model_shape"), &ranked_entry.entry.candidate_model_shape, ); push_line( text, &format!("{prefix}.candidate_quantization"), &ranked_entry.entry.candidate_quantization, ); push_line( text, &format!("{prefix}.quality_scope"), &ranked_entry.entry.quality_scope, ); push_line( text, &format!("{prefix}.eval_dataset"), &ranked_entry.entry.eval_dataset, ); push_line(text, &format!("{prefix}.case_count"), &case_count); push_line(text, &format!("{prefix}.cases_passed"), &cases_passed); push_line(text, &format!("{prefix}.quality_ppm"), &quality_ppm); push_line(text, &format!("{prefix}.frugality_ppm"), &frugality_ppm); push_line( text, &format!("{prefix}.quantization_fit_ppm"), &quantization_fit_ppm, ); push_line( text, &format!("{prefix}.population_fitness_ppm"), &population_fitness_ppm, ); push_line( text, &format!("{prefix}.fitness_objective_vector_checksum"), &fitness_objective_vector_checksum, ); push_line(text, &format!("{prefix}.review_decision"), decision); push_line(text, &format!("{prefix}.next_route"), next_route); } fn fitness_objective_vector_contract_text() -> String { let mut text = String::new(); push_line( &mut text, "fitness_objective_vector_version", FITNESS_OBJECTIVE_VECTOR_VERSION, ); push_line( &mut text, "fitness_objective_vector_kind", FITNESS_OBJECTIVE_VECTOR_KIND, ); push_line( &mut text, "fitness_objective_weight_unit", FITNESS_OBJECTIVE_WEIGHT_UNIT, ); push_line( &mut text, "fitness_objective_weight_sum_ppm", &fitness_objective_weight_sum_ppm().to_string(), ); push_line( &mut text, "fitness_objective_count", &FITNESS_OBJECTIVES.len().to_string(), ); for (index, objective) in FITNESS_OBJECTIVES.iter().enumerate() { let prefix = format!("fitness_objective.{index}"); push_line(&mut text, &format!("{prefix}.name"), objective.name); push_line(&mut text, &format!("{prefix}.source"), objective.source); push_line( &mut text, &format!("{prefix}.weight_ppm"), &objective.weight_ppm.to_string(), ); } text } fn fitness_objective_vector_checksum() -> String { let contract = fitness_objective_vector_contract_text(); hex64(provenance::text_checksum(contract.as_bytes())) } fn ranked_entry_fitness_objective_vector_checksum( rank_index: usize, ranked_entry: &RankedEntry, ) -> String { let mut text = fitness_objective_vector_contract_text(); push_line( &mut text, "fitness_objective_vector_checksum", &fitness_objective_vector_checksum(), ); push_line(&mut text, "entry.rank", &(rank_index + 1).to_string()); push_line( &mut text, "entry.source_ledger_entry", &format!("entry.{}", ranked_entry.entry.ledger_index), ); push_line( &mut text, "entry.candidate_id", &ranked_entry.entry.candidate_id, ); push_line( &mut text, "entry.candidate_slm_checksum", &ranked_entry.entry.candidate_slm_checksum, ); push_line( &mut text, "entry.quality_ppm", &ranked_entry.quality_ppm.to_string(), ); push_line( &mut text, "entry.frugality_ppm", &ranked_entry.frugality_ppm.to_string(), ); push_line( &mut text, "entry.quantization_fit_ppm", &ranked_entry.quantization_fit_ppm.to_string(), ); push_line( &mut text, "entry.population_fitness_ppm", &ranked_entry.population_fitness_ppm.to_string(), ); hex64(provenance::text_checksum(text.as_bytes())) } fn fitness_objective_weight_sum_ppm() -> u64 { FITNESS_OBJECTIVES .iter() .map(|objective| objective.weight_ppm) .sum() } fn require_entry_key<'a>( fields: &'a HashMap, entry_index: usize, key: &str, ) -> io::Result<&'a str> { require_key(fields, &format!("entry.{entry_index}.{key}")) } fn entry_value( fields: &HashMap, entry_index: usize, key: &str, ) -> io::Result { Ok(require_entry_key(fields, entry_index, key)?.to_string()) } fn quantization_fit_ppm(quantization: &str) -> u64 { match quantization { "q4_0" => PPM_DENOMINATOR, "q8_0" => 850_000, "f32" => 700_000, _ => 500_000, } } fn ppm_ratio(numerator: u64, denominator: u64, label: &str) -> io::Result { if denominator == 0 { return Err(invalid(&format!( "population review {label} denominator must be positive" ))); } ((u128::from(numerator) * u128::from(PPM_DENOMINATOR)) / u128::from(denominator)) .try_into() .map_err(|_| invalid("population review ppm value exceeded supported range")) } fn parse_positive_u64(value: &str, label: &str) -> io::Result { let parsed = parse_u64(value, label)?; if parsed == 0 { return Err(invalid(&format!( "population review {label} must be positive" ))); } Ok(parsed) } fn parse_u64(value: &str, label: &str) -> io::Result { value.parse::().map_err(|_| { invalid(&format!( "population review {label} must be an unsigned integer" )) }) } fn parse_usize(value: &str, label: &str) -> io::Result { value.parse::().map_err(|_| { invalid(&format!( "population review {label} must be an unsigned integer" )) }) } #[cfg(test)] mod tests { use super::*; use crate::admission; use crate::build_model_file; use crate::candidate; use crate::compatibility; use crate::lineage; use crate::promotion; use crate::slm_validate; use crate::tensor_writer::{ tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_F32, DTYPE_Q8_0, }; use crate::tokenizer_writer::ByteTokenizerSection; use std::time::{SystemTime, UNIX_EPOCH}; #[test] fn ranks_quantized_candidate_as_frontier() { let q8 = fixture_admission( "tiny-q8-candidate", "target/population-review/tiny-q8.slm", DTYPE_Q8_0, ); let f32 = fixture_admission( "tiny-f32-candidate", "target/population-review/tiny-f32.slm", DTYPE_F32, ); let ledger = ledger::build_ledger_text(&[f32.clone(), q8.clone()]).unwrap(); let review = build_review_text(&ledger, &[f32, q8]).unwrap(); assert!(review.contains("frontier_candidate_id=tiny-q8-candidate")); assert!(review .contains("fitness_objective_vector_kind=weighted-quality-frugality-quantization-v1")); assert!(review.contains("fitness_objective_weight_sum_ppm=1000000")); assert!(review.contains("fitness_objective.0.weight_ppm=700000")); assert!(review.contains("entry.0.candidate_id=tiny-q8-candidate")); assert!(review.contains("entry.0.fitness_objective_vector_checksum=0x")); assert!(review.contains("entry.0.review_decision=frontier-candidate")); assert!(review.contains("entry.0.next_route=selector-registry")); assert!(review.contains("entry.1.review_decision=candidate-kept-for-population")); assert!(review.contains("entry.1.next_route=population-parent-pool")); } #[test] fn validates_population_review_text() { let q8 = fixture_admission( "tiny-q8-candidate", "target/population-review/validate-q8.slm", DTYPE_Q8_0, ); let f32 = fixture_admission( "tiny-f32-candidate", "target/population-review/validate-f32.slm", DTYPE_F32, ); let ledger = ledger::build_ledger_text(&[q8.clone(), f32.clone()]).unwrap(); let review = build_review_text(&ledger, &[q8.clone(), f32.clone()]).unwrap(); validate_review_text(&ledger, &review, &[q8, f32]).unwrap(); } #[test] fn rejects_population_review_drift() { let q8 = fixture_admission( "tiny-q8-candidate", "target/population-review/drift-q8.slm", DTYPE_Q8_0, ); let f32 = fixture_admission( "tiny-f32-candidate", "target/population-review/drift-f32.slm", DTYPE_F32, ); let ledger = ledger::build_ledger_text(&[q8.clone(), f32.clone()]).unwrap(); let review = build_review_text(&ledger, &[q8.clone(), f32.clone()]) .unwrap() .replace( "frontier_candidate_id=tiny-q8-candidate", "frontier_candidate_id=tiny-f32-candidate", ); let error = validate_review_text(&ledger, &review, &[q8, f32]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("frontier_candidate_id")); } #[test] fn rejects_objective_vector_checksum_drift() { let q8 = fixture_admission( "tiny-q8-candidate", "target/population-review/objective-drift-q8.slm", DTYPE_Q8_0, ); let f32 = fixture_admission( "tiny-f32-candidate", "target/population-review/objective-drift-f32.slm", DTYPE_F32, ); let ledger = ledger::build_ledger_text(&[q8.clone(), f32.clone()]).unwrap(); let review = build_review_text(&ledger, &[q8.clone(), f32.clone()]) .unwrap() .replace( "fitness_objective.0.weight_ppm=700000", "fitness_objective.0.weight_ppm=1", ); let error = validate_review_text(&ledger, &review, &[q8, f32]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("fitness_objective.0.weight_ppm")); } #[test] fn rejects_population_review_when_ledger_drifted() { let q8 = fixture_admission( "tiny-q8-candidate", "target/population-review/ledger-drift-q8.slm", DTYPE_Q8_0, ); let f32 = fixture_admission( "tiny-f32-candidate", "target/population-review/ledger-drift-f32.slm", DTYPE_F32, ); let ledger = ledger::build_ledger_text(&[q8.clone(), f32.clone()]) .unwrap() .replace("entry.0.sequence=0", "entry.0.sequence=9"); let error = build_review_text(&ledger, &[q8, f32]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("sequence")); } #[test] fn writes_and_validates_population_review_paths() { let dir = unique_dir("paths"); std::fs::create_dir_all(&dir).unwrap(); let q8 = fixture_admission( "tiny-q8-candidate", "target/population-review/path-q8.slm", DTYPE_Q8_0, ); let f32 = fixture_admission( "tiny-f32-candidate", "target/population-review/path-f32.slm", DTYPE_F32, ); let q8_path = dir.join("q8.admission"); let f32_path = dir.join("f32.admission"); let ledger_path = dir.join("population.ledger"); let review_path = dir.join("population.review"); std::fs::write(&q8_path, q8).unwrap(); std::fs::write(&f32_path, f32).unwrap(); let admissions = vec![ q8_path.to_string_lossy().to_string(), f32_path.to_string_lossy().to_string(), ]; ledger::write_ledger_path(&ledger_path, &admissions).unwrap(); write_review_path(&ledger_path, &review_path, &admissions).unwrap(); validate_review_path(&ledger_path, &review_path, &admissions).unwrap(); let review = std::fs::read_to_string(review_path).unwrap(); assert!(review.contains("review_status=ledger-reviewed")); assert!(review.contains("frontier_candidate_id=tiny-q8-candidate")); } #[test] fn rejects_empty_review_inputs() { let error = build_review_text("", &[]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error .to_string() .contains("promotion ledger requires at least one admission record")); } fn fixture_admission(candidate_id: &str, candidate_path: &str, dtype: u32) -> String { let candidate = tiny_fixture_bytes(dtype); let compatibility = compatibility::compatibility_text_for_bytes( &candidate, "left.slm", &candidate, "right.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, candidate_id, "operator-a", "fit") .unwrap(); let candidate_manifest = candidate::build_manifest_text(&compatibility, &lineage, &candidate, candidate_path) .unwrap(); let promotion = promotion::build_template_text( &compatibility, &lineage, &candidate, candidate_path, &candidate_manifest, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, ) .unwrap(); let report = slm_validate::validate_bytes(&candidate, candidate_path).unwrap(); let provenance_manifest = provenance::build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = provenance::parse_manifest(&provenance_manifest).unwrap(); let runtime_smoke = provenance::build_runtime_smoke_text(&report, &provenance_manifest, &manifest_fields) .unwrap(); let eval = passing_eval_text(&report, &provenance_manifest); admission::build_record_text( &compatibility, &lineage, &candidate, candidate_path, &candidate_manifest, &promotion, &provenance_manifest, &runtime_smoke, &eval, admission::DEFAULT_ADMISSION_SELECTOR_ID, ) .unwrap() } fn passing_eval_text(report: &slm_validate::ValidationReport, manifest: &str) -> String { let mut text = String::new(); push_line(&mut text, "tinyrustlm_eval_manifest_version", "1"); push_line(&mut text, "gate", "assistant-quality"); push_line(&mut text, "source_kind", "converted-trained"); push_line( &mut text, "manifest_checksum", &hex64(provenance::text_checksum(manifest.as_bytes())), ); push_line(&mut text, "slm_checksum", &hex64(report.checksum())); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "task_eval_status", "pass"); push_line(&mut text, "safety_review_status", "pass"); push_line( &mut text, "quality_decision", "accepted-for-assistant-quality", ); push_line(&mut text, "quality_scope", "tiny-fixture-runtime-eval-only"); push_line(&mut text, "evaluator", "local-reviewed-eval"); push_line( &mut text, "eval_dataset", "tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", ); push_line( &mut text, "eval_summary", "Reviewed task and safety evidence passed for declared scope", ); push_line( &mut text, "quality_boundary", "fixture-runtime-and-eval-plumbing-not-product-assistant-quality", ); push_line(&mut text, "case_count", "1"); push_line(&mut text, "cases_passed", "1"); push_line(&mut text, "cases_failed", "0"); push_line(&mut text, "case.0.status", "pass"); push_line(&mut text, "case.0.expected", "e"); push_line(&mut text, "case.0.actual", "e"); push_line(&mut text, "case.0.error", "ok"); text } fn tiny_fixture_bytes(dtype: u32) -> Vec { build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(dtype), &ByteTokenizerSection::phase_one(), ) .unwrap() } fn unique_dir(label: &str) -> std::path::PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::path::Path::new("target") .join("population-review-tests") .join(format!("{label}-{}-{nanos}", std::process::id())) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/population.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/promotion.rs BYTES: 30059 SHA256: 0CE7B5F1D64495B5932402740C710EE2C8E684E0321762EA6BF7602154AB6F84 ================================================================================ //! Candidate promotion sidecars for runtime-smoke and eval handoff. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::candidate; use crate::lineage; const PROMOTION_VERSION: &str = "1"; const PROMOTION_STATUS: &str = "pending-runtime-smoke-and-eval"; /// Default promotion scope recorded by promotion templates when the CLI caller omits one. pub(crate) const DEFAULT_PROMOTION_SCOPE: &str = "browser-local-runtime-smoke-and-eval"; const RUNTIME_SMOKE_STATUS: &str = "pending"; const EVAL_STATUS: &str = "pending"; const PROMOTION_DECISION: &str = "pending"; const BROWSER_SELECTOR_STATUS: &str = "not-admitted"; const PUBLIC_CLAIM_STATUS: &str = "not-admitted"; const REQUIRED_NEXT_GATE: &str = "run-runtime-smoke-and-eval-sidecars-before-browser-selector"; const OPERATOR_RECEIPT_PREFIX: &str = "operator_receipt_"; const CANDIDATE_KEYS: [&str; 11] = [ "candidate_artifact_path", "candidate_artifact_bytes", "candidate_slm_version", "candidate_slm_checksum", "candidate_model_shape", "candidate_tensor_count", "candidate_parameter_count", "candidate_quantization", "candidate_output_contract", "candidate_tokenizer_checksum", "candidate_tensor_layout_checksum", ]; const OPERATOR_RECEIPT_KEYS: [&str; 7] = [ "operator_receipt_status", "operator_receipt_path", "operator_receipt_checksum", "operator_receipt_operator_id", "operator_receipt_operator_kind", "operator_receipt_candidate_slm_checksum", "operator_receipt_candidate_artifact_bytes", ]; /// Writes a candidate promotion template from validated candidate artifact inputs. pub(crate) fn write_template_path( compatibility: &Path, lineage_manifest: &Path, candidate_slm: &Path, candidate_manifest: &Path, output: &Path, promoter_id: &str, promotion_scope: &str, operator_receipt: Option<&Path>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let candidate_bytes = fs::read(candidate_slm)?; let candidate_manifest_text = fs::read_to_string(candidate_manifest)?; let operator_receipt_text = read_operator_receipt_binding(operator_receipt)?; let operator_receipt_binding = operator_receipt_text .as_ref() .map(|(path, text)| (path.as_str(), text.as_str())); let promotion_text = build_template_text_with_operator_receipt_text( &compatibility_text, &lineage_text, &candidate_bytes, &candidate_slm.display().to_string(), &candidate_manifest_text, promoter_id, promotion_scope, operator_receipt_binding, )?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, promotion_text)?; println!( "SLM candidate promotion template written: {}", output.display() ); Ok(()) } /// Validates a candidate promotion sidecar against compatibility, lineage, candidate, and manifest. pub(crate) fn validate_path( compatibility: &Path, lineage_manifest: &Path, candidate_slm: &Path, candidate_manifest: &Path, promotion: &Path, operator_receipt: Option<&Path>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let candidate_bytes = fs::read(candidate_slm)?; let candidate_manifest_text = fs::read_to_string(candidate_manifest)?; let promotion_text = fs::read_to_string(promotion)?; let operator_receipt_text = read_operator_receipt_binding(operator_receipt)?; let operator_receipt_binding = operator_receipt_text .as_ref() .map(|(path, text)| (path.as_str(), text.as_str())); validate_text_with_operator_receipt_text( &compatibility_text, &lineage_text, &candidate_bytes, &candidate_slm.display().to_string(), &candidate_manifest_text, &promotion_text, operator_receipt_binding, )?; println!("SLM candidate promotion validation: PASS"); println!("candidate_manifest: {}", candidate_manifest.display()); println!("promotion: {}", promotion.display()); Ok(()) } pub(crate) fn build_template_text( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, candidate_manifest_text: &str, promoter_id: &str, promotion_scope: &str, ) -> io::Result { build_template_text_with_operator_receipt_text( compatibility_text, lineage_text, candidate_bytes, candidate_path, candidate_manifest_text, promoter_id, promotion_scope, None, ) } /// Builds promotion text while optionally preserving the candidate manifest's producer receipt binding. pub(crate) fn build_template_text_with_operator_receipt_text( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, candidate_manifest_text: &str, promoter_id: &str, promotion_scope: &str, operator_receipt: Option<(&str, &str)>, ) -> io::Result { candidate::validate_manifest_text_with_operator_receipt_text( compatibility_text, lineage_text, candidate_bytes, candidate_path, candidate_manifest_text, operator_receipt, )?; validate_slug(promoter_id, "promoter_id")?; validate_value(promotion_scope, "promotion_scope")?; let candidate_fields = parse_manifest(candidate_manifest_text, "candidate artifact manifest")?; let mut text = String::new(); push_line( &mut text, "tinyrustlm_candidate_promotion_version", PROMOTION_VERSION, ); push_line( &mut text, "candidate_id", require_key(&candidate_fields, "candidate_id")?, ); push_line(&mut text, "promotion_status", PROMOTION_STATUS); push_line(&mut text, "promoter_id", promoter_id); push_line(&mut text, "promotion_scope", promotion_scope); push_line( &mut text, "operator_id", require_key(&candidate_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(&candidate_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(&candidate_fields, "resource_budget")?, ); push_line( &mut text, "compatibility_report_checksum", require_key(&candidate_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", require_key(&candidate_fields, "lineage_manifest_checksum")?, ); push_line( &mut text, "candidate_manifest_checksum", &hex64(lineage::text_checksum(candidate_manifest_text.as_bytes())), ); push_operator_receipt_lines(&mut text, &candidate_fields)?; push_candidate_lines(&mut text, &candidate_fields)?; push_line( &mut text, "candidate_admission_status", require_key(&candidate_fields, "candidate_admission_status")?, ); push_line( &mut text, "candidate_parent_contract", require_key(&candidate_fields, "candidate_parent_contract")?, ); push_line(&mut text, "runtime_smoke_status", RUNTIME_SMOKE_STATUS); push_line(&mut text, "eval_status", EVAL_STATUS); push_line(&mut text, "promotion_decision", PROMOTION_DECISION); push_line( &mut text, "browser_selector_status", BROWSER_SELECTOR_STATUS, ); push_line(&mut text, "public_claim_status", PUBLIC_CLAIM_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } #[allow(dead_code)] pub(crate) fn validate_text( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, candidate_manifest_text: &str, promotion_text: &str, ) -> io::Result<()> { validate_text_with_operator_receipt_text( compatibility_text, lineage_text, candidate_bytes, candidate_path, candidate_manifest_text, promotion_text, None, ) } /// Validates promotion text while optionally recomputing the producer receipt binding it carries. pub(crate) fn validate_text_with_operator_receipt_text( compatibility_text: &str, lineage_text: &str, candidate_bytes: &[u8], candidate_path: &str, candidate_manifest_text: &str, promotion_text: &str, operator_receipt: Option<(&str, &str)>, ) -> io::Result<()> { candidate::validate_manifest_text_with_operator_receipt_text( compatibility_text, lineage_text, candidate_bytes, candidate_path, candidate_manifest_text, operator_receipt, )?; let candidate_fields = parse_manifest(candidate_manifest_text, "candidate artifact manifest")?; let promotion = parse_manifest(promotion_text, "promotion")?; require_equal( &promotion, "tinyrustlm_candidate_promotion_version", PROMOTION_VERSION, )?; require_equal( &promotion, "candidate_id", require_key(&candidate_fields, "candidate_id")?, )?; require_equal(&promotion, "promotion_status", PROMOTION_STATUS)?; validate_slug(require_key(&promotion, "promoter_id")?, "promoter_id")?; validate_value( require_key(&promotion, "promotion_scope")?, "promotion_scope", )?; require_equal( &promotion, "operator_id", require_key(&candidate_fields, "operator_id")?, )?; require_equal( &promotion, "operator_lane", require_key(&candidate_fields, "operator_lane")?, )?; require_equal( &promotion, "resource_budget", require_key(&candidate_fields, "resource_budget")?, )?; require_equal( &promotion, "compatibility_report_checksum", require_key(&candidate_fields, "compatibility_report_checksum")?, )?; require_equal( &promotion, "lineage_manifest_checksum", require_key(&candidate_fields, "lineage_manifest_checksum")?, )?; require_equal( &promotion, "candidate_manifest_checksum", &hex64(lineage::text_checksum(candidate_manifest_text.as_bytes())), )?; require_operator_receipt_lines(&candidate_fields, &promotion)?; require_candidate_lines(&candidate_fields, &promotion)?; require_equal( &promotion, "candidate_admission_status", require_key(&candidate_fields, "candidate_admission_status")?, )?; require_equal( &promotion, "candidate_parent_contract", require_key(&candidate_fields, "candidate_parent_contract")?, )?; require_equal(&promotion, "runtime_smoke_status", RUNTIME_SMOKE_STATUS)?; require_equal(&promotion, "eval_status", EVAL_STATUS)?; require_equal(&promotion, "promotion_decision", PROMOTION_DECISION)?; require_equal( &promotion, "browser_selector_status", BROWSER_SELECTOR_STATUS, )?; require_equal(&promotion, "public_claim_status", PUBLIC_CLAIM_STATUS)?; require_equal(&promotion, "required_next_gate", REQUIRED_NEXT_GATE)?; Ok(()) } fn read_operator_receipt_binding( operator_receipt: Option<&Path>, ) -> io::Result> { operator_receipt .map(|path| { let text = fs::read_to_string(path)?; Ok((path.display().to_string(), text)) }) .transpose() } fn push_operator_receipt_lines( text: &mut String, candidate_fields: &HashMap, ) -> io::Result<()> { if candidate_fields.contains_key("operator_receipt_status") { for key in OPERATOR_RECEIPT_KEYS { push_line(text, key, require_key(candidate_fields, key)?); } } Ok(()) } fn require_operator_receipt_lines( candidate_fields: &HashMap, promotion: &HashMap, ) -> io::Result<()> { if candidate_fields.contains_key("operator_receipt_status") { for key in OPERATOR_RECEIPT_KEYS { require_equal(promotion, key, require_key(candidate_fields, key)?)?; } return Ok(()); } reject_unbound_operator_receipt_fields(promotion) } fn reject_unbound_operator_receipt_fields(promotion: &HashMap) -> io::Result<()> { if let Some(key) = promotion .keys() .find(|key| key.starts_with(OPERATOR_RECEIPT_PREFIX)) { return Err(invalid(&format!( "promotion has operator receipt field {key} without a bound candidate receipt" ))); } Ok(()) } fn push_candidate_lines( text: &mut String, candidate_fields: &HashMap, ) -> io::Result<()> { for key in CANDIDATE_KEYS { push_line(text, key, require_key(candidate_fields, key)?); } Ok(()) } fn require_candidate_lines( candidate_fields: &HashMap, promotion: &HashMap, ) -> io::Result<()> { for key in CANDIDATE_KEYS { require_equal(promotion, key, require_key(candidate_fields, key)?)?; } Ok(()) } fn parse_manifest(text: &str, label: &str) -> io::Result> { let mut fields = HashMap::new(); for (line_index, raw_line) in text.lines().enumerate() { let line = raw_line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let Some((key, value)) = line.split_once('=') else { return Err(invalid(&format!( "{label} line {} is missing '='", line_index + 1 ))); }; let key = key.trim(); let value = value.trim(); validate_key(key, label, line_index + 1)?; validate_value(value, key)?; if fields.insert(key.to_string(), value.to_string()).is_some() { return Err(invalid(&format!("duplicate {label} key {key}"))); } } Ok(fields) } fn validate_key(key: &str, label: &str, line_number: usize) -> io::Result<()> { if key.is_empty() || !key .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_')) { return Err(invalid(&format!( "{label} line {line_number} has an invalid key" ))); } Ok(()) } fn validate_value(value: &str, key: &str) -> io::Result<()> { if value.is_empty() || value.contains('\n') || value.contains('\r') { return Err(invalid(&format!("{key} has an invalid value"))); } Ok(()) } fn validate_slug(value: &str, key: &str) -> io::Result<()> { validate_value(value, key)?; if value.len() > 96 || !value .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) { return Err(invalid(&format!("{key} must be an ASCII slug"))); } Ok(()) } fn require_key<'a>(fields: &'a HashMap, key: &str) -> io::Result<&'a str> { fields .get(key) .map(String::as_str) .ok_or_else(|| invalid(&format!("manifest missing required key {key}"))) } fn require_equal(fields: &HashMap, key: &str, expected: &str) -> io::Result<()> { let actual = require_key(fields, key)?; if actual != expected { return Err(invalid(&format!( "manifest key {key} was {actual}, expected {expected}" ))); } Ok(()) } fn push_line(text: &mut String, key: &str, value: &str) { text.push_str(key); text.push('='); text.push_str(value); text.push('\n'); } fn hex64(value: u64) -> String { format!("0x{value:016x}") } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } #[cfg(test)] mod tests { use super::*; use crate::build_model_file; use crate::candidate; use crate::compatibility; use crate::lineage; use crate::slm_validate; use crate::tensor_writer::{ tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_F32, DTYPE_Q8_0, }; use crate::tokenizer_writer::ByteTokenizerSection; use std::fs; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; #[test] fn writes_and_validates_promotion_template() { let fixture = PromotionFixture::new(); let promotion = build_template_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &fixture.candidate_manifest, "local-smoke-runner", DEFAULT_PROMOTION_SCOPE, ) .unwrap(); validate_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &fixture.candidate_manifest, &promotion, ) .unwrap(); assert!(promotion.contains("promotion_status=pending-runtime-smoke-and-eval")); assert!(promotion.contains("runtime_smoke_status=pending")); assert!(promotion.contains("browser_selector_status=not-admitted")); } #[test] fn writes_and_validates_operator_receipt_bound_promotion_template() { let fixture = PromotionFixture::new(); let receipt = operator_receipt_text(&fixture.lineage, &fixture.candidate, "candidate.slm"); let candidate_manifest = candidate::build_manifest_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", Some(("candidate.operator", &receipt)), ) .unwrap(); let promotion = build_template_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &candidate_manifest, "local-smoke-runner", DEFAULT_PROMOTION_SCOPE, Some(("candidate.operator", &receipt)), ) .unwrap(); validate_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &candidate_manifest, &promotion, Some(("candidate.operator", &receipt)), ) .unwrap(); assert!(promotion.contains("operator_receipt_status=receipt-bound")); assert!(promotion.contains(&format!( "operator_receipt_checksum={}", hex64(lineage::text_checksum(receipt.as_bytes())) ))); assert!(promotion .contains("operator_receipt_operator_kind=deterministic-bounded-parameter-mutation")); } #[test] fn path_functions_accept_bound_operator_receipt_input() { let fixture = PromotionFixture::new(); let dir = unique_temp_dir("promotion-operator-receipt"); fs::create_dir_all(&dir).unwrap(); let compatibility_path = dir.join("parents.compat"); let lineage_path = dir.join("candidate.lineage"); let candidate_path = dir.join("candidate.slm"); let receipt_path = dir.join("candidate.operator"); let candidate_manifest_path = dir.join("candidate.candidate"); let promotion_path = dir.join("candidate.promotion"); let receipt = operator_receipt_text( &fixture.lineage, &fixture.candidate, &candidate_path.display().to_string(), ); fs::write(&compatibility_path, &fixture.compatibility).unwrap(); fs::write(&lineage_path, &fixture.lineage).unwrap(); fs::write(&candidate_path, &fixture.candidate).unwrap(); fs::write(&receipt_path, receipt).unwrap(); candidate::write_manifest_path( &compatibility_path, &lineage_path, &candidate_path, &candidate_manifest_path, Some(&receipt_path), ) .unwrap(); write_template_path( &compatibility_path, &lineage_path, &candidate_path, &candidate_manifest_path, &promotion_path, "local-smoke-runner", DEFAULT_PROMOTION_SCOPE, Some(&receipt_path), ) .unwrap(); validate_path( &compatibility_path, &lineage_path, &candidate_path, &candidate_manifest_path, &promotion_path, Some(&receipt_path), ) .unwrap(); let promotion = fs::read_to_string(&promotion_path).unwrap(); assert!(promotion.contains(&format!("operator_receipt_path={}", receipt_path.display()))); fs::remove_dir_all(&dir).unwrap(); } #[test] fn validation_rejects_candidate_manifest_checksum_drift() { let fixture = PromotionFixture::new(); let promotion = fixture.promotion(); let changed_manifest = format!("{}# checksum-affecting note\n", fixture.candidate_manifest); let error = validate_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &changed_manifest, &promotion, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate_manifest_checksum")); } #[test] fn validation_rejects_candidate_artifact_drift() { let fixture = PromotionFixture::new(); let promotion = fixture.promotion(); let changed_candidate = tiny_fixture_f32_bytes(); let error = validate_text( &fixture.compatibility, &fixture.lineage, &changed_candidate, "candidate.slm", &fixture.candidate_manifest, &promotion, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate artifact contract")); } #[test] fn validation_rejects_bound_promotion_without_operator_receipt_input() { let fixture = PromotionFixture::new(); let receipt = operator_receipt_text(&fixture.lineage, &fixture.candidate, "candidate.slm"); let candidate_manifest = candidate::build_manifest_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", Some(("candidate.operator", &receipt)), ) .unwrap(); let promotion = build_template_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &candidate_manifest, "local-smoke-runner", DEFAULT_PROMOTION_SCOPE, Some(("candidate.operator", &receipt)), ) .unwrap(); let error = validate_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &candidate_manifest, &promotion, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator receipt binding")); } #[test] fn validation_rejects_operator_receipt_promotion_checksum_drift() { let fixture = PromotionFixture::new(); let receipt = operator_receipt_text(&fixture.lineage, &fixture.candidate, "candidate.slm"); let expected_checksum = hex64(lineage::text_checksum(receipt.as_bytes())); let candidate_manifest = candidate::build_manifest_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", Some(("candidate.operator", &receipt)), ) .unwrap(); let promotion = build_template_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &candidate_manifest, "local-smoke-runner", DEFAULT_PROMOTION_SCOPE, Some(("candidate.operator", &receipt)), ) .unwrap(); let drifted_promotion = promotion.replace( &format!("operator_receipt_checksum={expected_checksum}"), "operator_receipt_checksum=0x0000000000000000", ); let error = validate_text_with_operator_receipt_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &candidate_manifest, &drifted_promotion, Some(("candidate.operator", &receipt)), ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator_receipt_checksum")); } #[test] fn validation_rejects_promotion_overclaim() { let fixture = PromotionFixture::new(); let promotion = fixture .promotion() .replace("promotion_decision=pending", "promotion_decision=accepted"); let error = validate_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &fixture.candidate_manifest, &promotion, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("promotion_decision")); } #[test] fn rejects_invalid_promoter_id() { let fixture = PromotionFixture::new(); let error = build_template_text( &fixture.compatibility, &fixture.lineage, &fixture.candidate, "candidate.slm", &fixture.candidate_manifest, "bad promoter", DEFAULT_PROMOTION_SCOPE, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("promoter_id")); } struct PromotionFixture { compatibility: String, lineage: String, candidate: Vec, candidate_manifest: String, } impl PromotionFixture { fn new() -> Self { let candidate = tiny_fixture_q8_bytes(); let compatibility = compatibility::compatibility_text_for_bytes( &candidate, "left.slm", &candidate, "right.slm", ) .unwrap(); let lineage = lineage::build_template_text( &compatibility, "tiny-q8-candidate", "operator-a", "fit", ) .unwrap(); let candidate_manifest = candidate::build_manifest_text( &compatibility, &lineage, &candidate, "candidate.slm", ) .unwrap(); Self { compatibility, lineage, candidate, candidate_manifest, } } fn promotion(&self) -> String { build_template_text( &self.compatibility, &self.lineage, &self.candidate, "candidate.slm", &self.candidate_manifest, "local-smoke-runner", DEFAULT_PROMOTION_SCOPE, ) .unwrap() } } fn tiny_fixture_q8_bytes() -> Vec { build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), &ByteTokenizerSection::phase_one(), ) .unwrap() } fn tiny_fixture_f32_bytes() -> Vec { build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(DTYPE_F32), &ByteTokenizerSection::phase_one(), ) .unwrap() } fn operator_receipt_text(lineage_text: &str, candidate: &[u8], candidate_path: &str) -> String { let lineage_fields = parse_manifest(lineage_text, "lineage").unwrap(); let report = slm_validate::validate_bytes(candidate, candidate_path).unwrap(); let mut text = String::new(); push_line(&mut text, "tinyrustlm_operator_receipt_version", "1"); push_line( &mut text, "operator_kind", "deterministic-bounded-parameter-mutation", ); push_line(&mut text, "operator_status", "operator-output-written"); push_line( &mut text, "candidate_id", require_key(&lineage_fields, "candidate_id").unwrap(), ); push_line( &mut text, "operator_id", require_key(&lineage_fields, "operator_id").unwrap(), ); push_line(&mut text, "candidate_artifact_path", report.path()); push_line( &mut text, "candidate_artifact_bytes", &report.file_bytes().to_string(), ); push_line( &mut text, "candidate_slm_checksum", &hex64(report.checksum()), ); push_line( &mut text, "required_next_gate", "candidate-manifest-plus-promotion-plus-runtime-smoke-plus-eval", ); text } fn unique_temp_dir(label: &str) -> PathBuf { let nonce = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-promotion-{label}-{nonce}")) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/promotion.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/provenance.rs BYTES: 31007 SHA256: 8112D2AF17A7DC3552A0F9D874B8766A3448A926B33E7262E982ACF069213D22 ================================================================================ //! Provenance sidecar generation and validation for `.slm` artifacts. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::slm_validate::{self, ValidationReport}; const MANIFEST_VERSION: &str = "1"; const EVAL_MANIFEST_VERSION: &str = "1"; const RUNTIME_SMOKE_VERSION: &str = "1"; const GATE_RUNTIME_SMOKE: &str = "runtime-smoke"; const GATE_ASSISTANT_QUALITY: &str = "assistant-quality"; const RUNTIME_SMOKE_DECISION: &str = "accepted-for-runtime-smoke"; const RUNTIME_SMOKE_NEXT_GATE: &str = "promotion-eval-and-selector-admission"; struct SourcePolicy { quality_claim: &'static str, trained_quality_claim: &'static str, admission_status: &'static str, required_next_gate: &'static str, } /// Writes a line-based provenance manifest for a validated `.slm` file. pub fn write_manifest_for_path(input: &Path, output: &Path, source_kind: &str) -> io::Result<()> { let bytes = fs::read(input)?; let report = slm_validate::validate_bytes(&bytes, &input.display().to_string())?; let manifest = build_manifest_text(&report, source_kind)?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, manifest)?; println!("SLM manifest written: {}", output.display()); Ok(()) } /// Validates a provenance manifest against a local `.slm` file. pub fn validate_manifest_path(input: &Path, manifest: &Path) -> io::Result<()> { let bytes = fs::read(input)?; let report = slm_validate::validate_bytes(&bytes, &input.display().to_string())?; let manifest_text = fs::read_to_string(manifest)?; validate_manifest_text(&report, &manifest_text)?; println!("SLM manifest validation: PASS"); println!("model: {}", report.path()); println!("manifest: {}", manifest.display()); println!( "source_kind: {}", require_key(&parse_manifest(&manifest_text)?, "source_kind")? ); Ok(()) } /// Writes a pending evaluation sidecar template bound to a validated model and manifest. pub fn write_eval_template_for_path( input: &Path, manifest: &Path, output: &Path, gate: &str, ) -> io::Result<()> { let bytes = fs::read(input)?; let report = slm_validate::validate_bytes(&bytes, &input.display().to_string())?; let manifest_text = fs::read_to_string(manifest)?; let fields = validate_manifest_text(&report, &manifest_text)?; let eval_text = build_eval_template_text(&report, &manifest_text, &fields, gate)?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, eval_text)?; println!("SLM evaluation template written: {}", output.display()); Ok(()) } /// Validates a requested quality gate against model, provenance, and optional evaluation evidence. pub fn quality_gate_path( input: &Path, manifest: &Path, gate: &str, eval_manifest: Option<&Path>, ) -> io::Result<()> { let bytes = fs::read(input)?; let report = slm_validate::validate_bytes(&bytes, &input.display().to_string())?; let manifest_text = fs::read_to_string(manifest)?; let eval_text = match eval_manifest { Some(path) => Some(fs::read_to_string(path)?), None => None, }; validate_quality_gate(&report, &manifest_text, gate, eval_text.as_deref())?; println!("SLM quality gate: PASS"); println!("model: {}", report.path()); println!("manifest: {}", manifest.display()); println!("gate: {gate}"); if let Some(path) = eval_manifest { println!("evaluation_manifest: {}", path.display()); } Ok(()) } /// Writes a runtime-smoke sidecar bound to a validated model and provenance manifest. pub(crate) fn write_runtime_smoke_for_path( input: &Path, manifest: &Path, output: &Path, ) -> io::Result<()> { let bytes = fs::read(input)?; let report = slm_validate::validate_bytes(&bytes, &input.display().to_string())?; let manifest_text = fs::read_to_string(manifest)?; let manifest_fields = validate_manifest_text(&report, &manifest_text)?; validate_quality_gate(&report, &manifest_text, GATE_RUNTIME_SMOKE, None)?; let smoke_text = build_runtime_smoke_text(&report, &manifest_text, &manifest_fields)?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, smoke_text)?; println!("SLM runtime-smoke sidecar written: {}", output.display()); Ok(()) } /// Validates a runtime-smoke sidecar against a local model and provenance manifest. pub(crate) fn validate_runtime_smoke_path( input: &Path, manifest: &Path, runtime_smoke: &Path, ) -> io::Result<()> { let bytes = fs::read(input)?; let report = slm_validate::validate_bytes(&bytes, &input.display().to_string())?; let manifest_text = fs::read_to_string(manifest)?; let runtime_smoke_text = fs::read_to_string(runtime_smoke)?; validate_runtime_smoke_text(&report, &manifest_text, &runtime_smoke_text)?; println!("SLM runtime-smoke validation: PASS"); println!("model: {}", report.path()); println!("manifest: {}", manifest.display()); println!("runtime_smoke: {}", runtime_smoke.display()); Ok(()) } pub(crate) fn build_manifest_text( report: &ValidationReport, source_kind: &str, ) -> io::Result { let policy = policy_for_source_kind(source_kind)?; let mut text = String::new(); push_line( &mut text, "tinyrustlm_slm_manifest_version", MANIFEST_VERSION, ); push_line(&mut text, "model_path", report.path()); push_line(&mut text, "model_bytes", &report.file_bytes().to_string()); push_line(&mut text, "slm_version", &report.slm_version().to_string()); push_line( &mut text, "slm_checksum", &format!("0x{:016x}", report.checksum()), ); push_line(&mut text, "model_shape", &report.shape_summary()); push_line( &mut text, "tensor_count", &report.tensor_count().to_string(), ); push_line( &mut text, "parameter_count", &report.parameter_count().to_string(), ); push_line(&mut text, "quantization", report.quantization_label()); push_line(&mut text, "source_kind", source_kind); push_line(&mut text, "quality_claim", policy.quality_claim); push_line( &mut text, "trained_quality_claim", policy.trained_quality_claim, ); push_line(&mut text, "admission_status", policy.admission_status); push_line(&mut text, "required_next_gate", policy.required_next_gate); Ok(text) } fn validate_manifest_text( report: &ValidationReport, text: &str, ) -> io::Result> { let fields = parse_manifest(text)?; require_equal(&fields, "tinyrustlm_slm_manifest_version", MANIFEST_VERSION)?; require_equal(&fields, "model_bytes", &report.file_bytes().to_string())?; require_equal(&fields, "slm_version", &report.slm_version().to_string())?; require_equal( &fields, "slm_checksum", &format!("0x{:016x}", report.checksum()), )?; require_equal(&fields, "model_shape", &report.shape_summary())?; require_equal(&fields, "tensor_count", &report.tensor_count().to_string())?; require_equal( &fields, "parameter_count", &report.parameter_count().to_string(), )?; require_equal(&fields, "quantization", report.quantization_label())?; let source_kind = require_key(&fields, "source_kind")?; let policy = policy_for_source_kind(source_kind)?; require_equal(&fields, "quality_claim", policy.quality_claim)?; require_equal( &fields, "trained_quality_claim", policy.trained_quality_claim, )?; require_equal(&fields, "admission_status", policy.admission_status)?; require_equal(&fields, "required_next_gate", policy.required_next_gate)?; require_key(&fields, "model_path")?; Ok(fields) } pub(crate) fn build_runtime_smoke_text( report: &ValidationReport, manifest_text: &str, manifest_fields: &HashMap, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_runtime_smoke_version", RUNTIME_SMOKE_VERSION, ); push_line(&mut text, "gate", GATE_RUNTIME_SMOKE); push_line( &mut text, "source_kind", require_key(manifest_fields, "source_kind")?, ); push_line(&mut text, "model_path", report.path()); push_line( &mut text, "manifest_checksum", &format!("0x{:016x}", text_checksum(manifest_text.as_bytes())), ); push_line( &mut text, "slm_checksum", &format!("0x{:016x}", report.checksum()), ); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "runtime_smoke_status", "pass"); push_line(&mut text, "runtime_smoke_decision", RUNTIME_SMOKE_DECISION); push_line(&mut text, "required_next_gate", RUNTIME_SMOKE_NEXT_GATE); Ok(text) } pub(crate) fn validate_runtime_smoke_text( report: &ValidationReport, manifest_text: &str, runtime_smoke_text: &str, ) -> io::Result> { let manifest_fields = validate_manifest_text(report, manifest_text)?; validate_quality_gate(report, manifest_text, GATE_RUNTIME_SMOKE, None)?; let fields = parse_manifest(runtime_smoke_text)?; require_equal( &fields, "tinyrustlm_runtime_smoke_version", RUNTIME_SMOKE_VERSION, )?; require_equal(&fields, "gate", GATE_RUNTIME_SMOKE)?; require_equal( &fields, "source_kind", require_key(&manifest_fields, "source_kind")?, )?; require_key(&fields, "model_path")?; require_equal( &fields, "manifest_checksum", &format!("0x{:016x}", text_checksum(manifest_text.as_bytes())), )?; require_equal( &fields, "slm_checksum", &format!("0x{:016x}", report.checksum()), )?; require_equal(&fields, "model_shape", &report.shape_summary())?; require_equal(&fields, "runtime_smoke_status", "pass")?; require_equal(&fields, "runtime_smoke_decision", RUNTIME_SMOKE_DECISION)?; require_equal(&fields, "required_next_gate", RUNTIME_SMOKE_NEXT_GATE)?; Ok(fields) } fn build_eval_template_text( report: &ValidationReport, manifest_text: &str, manifest_fields: &HashMap, gate: &str, ) -> io::Result { if gate != GATE_ASSISTANT_QUALITY { return Err(invalid( "eval-template currently supports assistant-quality", )); } let mut text = String::new(); push_line( &mut text, "tinyrustlm_eval_manifest_version", EVAL_MANIFEST_VERSION, ); push_line(&mut text, "gate", gate); push_line( &mut text, "source_kind", require_key(manifest_fields, "source_kind")?, ); push_line( &mut text, "manifest_checksum", &format!("0x{:016x}", text_checksum(manifest_text.as_bytes())), ); push_line( &mut text, "slm_checksum", &format!("0x{:016x}", report.checksum()), ); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "eval_status", "pending"); push_line(&mut text, "task_eval_status", "pending"); push_line(&mut text, "safety_review_status", "pending"); push_line(&mut text, "quality_decision", "pending"); push_line(&mut text, "quality_scope", "pending"); push_line(&mut text, "evaluator", "not-reviewed"); push_line(&mut text, "eval_dataset", "not-provided"); push_line(&mut text, "eval_summary", "not-reviewed"); Ok(text) } pub(crate) fn validate_quality_gate( report: &ValidationReport, manifest_text: &str, gate: &str, eval_text: Option<&str>, ) -> io::Result<()> { let manifest_fields = validate_manifest_text(report, manifest_text)?; let source_kind = require_key(&manifest_fields, "source_kind")?; match gate { GATE_RUNTIME_SMOKE => validate_runtime_smoke_gate(source_kind), GATE_ASSISTANT_QUALITY => { let eval_text = eval_text .ok_or_else(|| invalid("assistant-quality gate requires an evaluation manifest"))?; validate_assistant_quality_gate(report, manifest_text, source_kind, eval_text) } _ => Err(invalid( "quality gate must be runtime-smoke or assistant-quality", )), } } fn validate_runtime_smoke_gate(source_kind: &str) -> io::Result<()> { match source_kind { "deterministic-smoke" | "converted-trained" => Ok(()), _ => Err(invalid("runtime-smoke gate requires a known source_kind")), } } fn validate_assistant_quality_gate( report: &ValidationReport, manifest_text: &str, source_kind: &str, eval_text: &str, ) -> io::Result<()> { if source_kind != "converted-trained" { return Err(invalid( "assistant-quality gate requires source_kind=converted-trained", )); } let fields = parse_manifest(eval_text)?; require_equal( &fields, "tinyrustlm_eval_manifest_version", EVAL_MANIFEST_VERSION, )?; require_equal(&fields, "gate", GATE_ASSISTANT_QUALITY)?; require_equal(&fields, "source_kind", "converted-trained")?; require_equal( &fields, "manifest_checksum", &format!("0x{:016x}", text_checksum(manifest_text.as_bytes())), )?; require_equal( &fields, "slm_checksum", &format!("0x{:016x}", report.checksum()), )?; require_equal(&fields, "model_shape", &report.shape_summary())?; require_equal(&fields, "eval_status", "pass")?; require_equal(&fields, "task_eval_status", "pass")?; require_equal(&fields, "safety_review_status", "pass")?; require_equal( &fields, "quality_decision", "accepted-for-assistant-quality", )?; require_evidence_field(&fields, "quality_scope")?; require_evidence_field(&fields, "evaluator")?; require_evidence_field(&fields, "eval_dataset")?; require_evidence_field(&fields, "eval_summary")?; require_evidence_field(&fields, "quality_boundary")?; validate_eval_case_evidence(&fields)?; Ok(()) } pub(crate) fn parse_manifest(text: &str) -> io::Result> { let mut fields = HashMap::new(); for (line_index, raw_line) in text.lines().enumerate() { let line = raw_line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let Some((key, value)) = line.split_once('=') else { return Err(invalid(&format!( "manifest line {} is missing '='", line_index + 1 ))); }; let key = key.trim(); let value = value.trim(); if key.is_empty() || value.is_empty() { return Err(invalid(&format!( "manifest line {} has an empty key or value", line_index + 1 ))); } if fields.insert(key.to_string(), value.to_string()).is_some() { return Err(invalid(&format!("duplicate manifest key {key}"))); } } Ok(fields) } pub(crate) fn eval_case_evidence_checksum(fields: &HashMap) -> io::Result { let case_count = require_positive_usize(fields, "case_count")?; let mut text = String::new(); for key in ["case_count", "cases_passed", "cases_failed"] { push_line(&mut text, key, require_key(fields, key)?); } for index in 0..case_count { let prefix = format!("case.{index}"); for suffix in ["status", "expected", "actual", "error"] { let key = format!("{prefix}.{suffix}"); push_line(&mut text, &key, require_key(fields, &key)?); } } Ok(format!("0x{:016x}", text_checksum(text.as_bytes()))) } fn validate_eval_case_evidence(fields: &HashMap) -> io::Result<()> { let case_count = require_positive_usize(fields, "case_count")?; let cases_passed = require_usize(fields, "cases_passed")?; let cases_failed = require_usize(fields, "cases_failed")?; if cases_passed != case_count || cases_failed != 0 { return Err(invalid( "evaluation case totals must show every declared case passed and zero failed cases", )); } for index in 0..case_count { let prefix = format!("case.{index}"); require_equal(fields, &format!("{prefix}.status"), "pass")?; let expected = require_nonempty_field(fields, &format!("{prefix}.expected"))?; let actual = require_nonempty_field(fields, &format!("{prefix}.actual"))?; if actual != expected { return Err(invalid(&format!( "evaluation case {index} actual text did not match expected text" ))); } require_equal(fields, &format!("{prefix}.error"), "ok")?; } reject_extra_eval_case_keys(fields, case_count)?; Ok(()) } fn reject_extra_eval_case_keys( fields: &HashMap, case_count: usize, ) -> io::Result<()> { for key in fields.keys() { if let Some(rest) = key.strip_prefix("case.") { let Some((index_text, field_name)) = rest.split_once('.') else { return Err(invalid(&format!("evaluation case key {key} is malformed"))); }; let index = parse_usize(index_text, key)?; if index >= case_count { return Err(invalid(&format!( "evaluation case key {key} is outside declared case_count" ))); } match field_name { "status" | "expected" | "actual" | "error" => {} _ => { return Err(invalid(&format!( "evaluation case key {key} has unknown field" ))) } } } } Ok(()) } fn require_positive_usize(fields: &HashMap, key: &str) -> io::Result { let value = require_usize(fields, key)?; if value == 0 { return Err(invalid(&format!( "evaluation field {key} must be greater than zero" ))); } Ok(value) } fn require_usize(fields: &HashMap, key: &str) -> io::Result { let value = require_key(fields, key)?; parse_usize(value, key) } fn parse_usize(value: &str, key: &str) -> io::Result { value .parse::() .map_err(|_| invalid(&format!("evaluation field {key} must be a usize"))) } fn require_nonempty_field<'a>( fields: &'a HashMap, key: &str, ) -> io::Result<&'a str> { let value = require_key(fields, key)?; if value.is_empty() { return Err(invalid(&format!( "evaluation field {key} must not be empty" ))); } Ok(value) } fn require_evidence_field(fields: &HashMap, key: &str) -> io::Result<()> { let value = require_key(fields, key)?; if value == "pending" || value == "not-reviewed" || value == "not-provided" || value.len() < 8 { return Err(invalid(&format!( "evaluation field {key} must contain reviewed evidence" ))); } Ok(()) } fn require_key<'a>(fields: &'a HashMap, key: &str) -> io::Result<&'a str> { fields .get(key) .map(String::as_str) .ok_or_else(|| invalid(&format!("manifest missing required key {key}"))) } fn require_equal(fields: &HashMap, key: &str, expected: &str) -> io::Result<()> { let actual = require_key(fields, key)?; if actual != expected { return Err(invalid(&format!( "manifest key {key} was {actual}, expected {expected}" ))); } Ok(()) } fn policy_for_source_kind(source_kind: &str) -> io::Result { match source_kind { "deterministic-smoke" => Ok(SourcePolicy { quality_claim: "runtime-execution-smoke-only", trained_quality_claim: "not-claimed", admission_status: "accepted-for-runtime-smoke", required_next_gate: "replace-with-trained-or-evaluated-model-before-product-quality-claim", }), "converted-trained" => Ok(SourcePolicy { quality_claim: "runtime-compatible-not-quality-verified", trained_quality_claim: "pending-evaluation", admission_status: "structure-accepted-quality-pending", required_next_gate: "task-eval-and-safety-review-before-assistant-quality-claim", }), _ => Err(invalid( "source_kind must be deterministic-smoke or converted-trained", )), } } fn push_line(text: &mut String, key: &str, value: &str) { text.push_str(key); text.push('='); text.push_str(value); text.push('\n'); } pub(crate) fn text_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x4d595df4d0f33173u64; for (index, byte) in bytes.iter().enumerate() { acc ^= u64::from(*byte).wrapping_add((index as u64) << 2); acc = acc.rotate_left(9).wrapping_mul(0x100000001b3); } acc } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } #[cfg(test)] mod tests { use super::*; use crate::build_model_file; use crate::tensor_writer::{tiny_fixture_tensors, ModelShape}; use crate::tokenizer_writer::ByteTokenizerSection; #[test] fn manifest_round_trip_matches_generated_fixture() { let report = fixture_report(); let manifest = build_manifest_text(&report, "deterministic-smoke").unwrap(); validate_manifest_text(&report, &manifest).unwrap(); assert!(manifest.contains("source_kind=deterministic-smoke")); assert!(manifest.contains("trained_quality_claim=not-claimed")); } #[test] fn manifest_rejects_checksum_mismatch() { let report = fixture_report(); let manifest = build_manifest_text(&report, "deterministic-smoke") .unwrap() .replace( &format!("slm_checksum=0x{:016x}", report.checksum()), "slm_checksum=0x0000000000000001", ); let error = validate_manifest_text(&report, &manifest).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } #[test] fn manifest_rejects_trained_quality_overclaim() { let report = fixture_report(); let manifest = build_manifest_text(&report, "converted-trained") .unwrap() .replace( "trained_quality_claim=pending-evaluation", "trained_quality_claim=claimed", ); let error = validate_manifest_text(&report, &manifest).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } #[test] fn quality_gate_allows_runtime_smoke_manifest() { let report = fixture_report(); let manifest = build_manifest_text(&report, "deterministic-smoke").unwrap(); validate_quality_gate(&report, &manifest, GATE_RUNTIME_SMOKE, None).unwrap(); } #[test] fn runtime_smoke_sidecar_round_trip_matches_manifest() { let report = fixture_report(); let manifest = build_manifest_text(&report, "deterministic-smoke").unwrap(); let manifest_fields = parse_manifest(&manifest).unwrap(); let runtime_smoke = build_runtime_smoke_text(&report, &manifest, &manifest_fields).unwrap(); validate_runtime_smoke_text(&report, &manifest, &runtime_smoke).unwrap(); assert!(runtime_smoke.contains("runtime_smoke_status=pass")); assert!(runtime_smoke.contains("runtime_smoke_decision=accepted-for-runtime-smoke")); } #[test] fn runtime_smoke_sidecar_rejects_manifest_drift() { let report = fixture_report(); let manifest = build_manifest_text(&report, "deterministic-smoke").unwrap(); let manifest_fields = parse_manifest(&manifest).unwrap(); let runtime_smoke = build_runtime_smoke_text(&report, &manifest, &manifest_fields).unwrap(); let changed_manifest = manifest.replace( "quality_claim=runtime-execution-smoke-only", "quality_claim=runtime-compatible-not-quality-verified", ); let error = validate_runtime_smoke_text(&report, &changed_manifest, &runtime_smoke).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("quality_claim")); } #[test] fn quality_gate_rejects_smoke_assistant_quality_claim() { let report = fixture_report(); let manifest = build_manifest_text(&report, "deterministic-smoke").unwrap(); let eval = passing_eval_text(&report, &manifest, "converted-trained"); let error = validate_quality_gate(&report, &manifest, GATE_ASSISTANT_QUALITY, Some(&eval)) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } #[test] fn quality_gate_rejects_converted_trained_without_eval() { let report = fixture_report(); let manifest = build_manifest_text(&report, "converted-trained").unwrap(); let error = validate_quality_gate(&report, &manifest, GATE_ASSISTANT_QUALITY, None).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } #[test] fn quality_gate_rejects_pending_eval_template() { let report = fixture_report(); let manifest = build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = validate_manifest_text(&report, &manifest).unwrap(); let eval = build_eval_template_text(&report, &manifest, &manifest_fields, GATE_ASSISTANT_QUALITY) .unwrap(); let error = validate_quality_gate(&report, &manifest, GATE_ASSISTANT_QUALITY, Some(&eval)) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } #[test] fn quality_gate_allows_converted_trained_with_passed_eval() { let report = fixture_report(); let manifest = build_manifest_text(&report, "converted-trained").unwrap(); let eval = passing_eval_text(&report, &manifest, "converted-trained"); validate_quality_gate(&report, &manifest, GATE_ASSISTANT_QUALITY, Some(&eval)).unwrap(); } #[test] fn eval_case_checksum_tracks_case_body() { let report = fixture_report(); let manifest = build_manifest_text(&report, "converted-trained").unwrap(); let eval = passing_eval_text(&report, &manifest, "converted-trained"); let fields = parse_manifest(&eval).unwrap(); let checksum = eval_case_evidence_checksum(&fields).unwrap(); let changed_eval = eval.replace("case.0.error=ok", "case.0.error=reviewed"); let changed_fields = parse_manifest(&changed_eval).unwrap(); let changed_checksum = eval_case_evidence_checksum(&changed_fields).unwrap(); assert!(checksum.starts_with("0x")); assert_ne!(checksum, changed_checksum); } #[test] fn quality_gate_rejects_passed_eval_without_case_evidence() { let report = fixture_report(); let manifest = build_manifest_text(&report, "converted-trained").unwrap(); let eval = passing_eval_text(&report, &manifest, "converted-trained") .lines() .filter(|line| { !line.starts_with("case_count=") && !line.starts_with("cases_passed=") && !line.starts_with("cases_failed=") && !line.starts_with("case.0.") }) .collect::>() .join("\n"); let error = validate_quality_gate(&report, &manifest, GATE_ASSISTANT_QUALITY, Some(&eval)) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } #[test] fn quality_gate_rejects_passed_eval_with_mismatched_case_text() { let report = fixture_report(); let manifest = build_manifest_text(&report, "converted-trained").unwrap(); let eval = passing_eval_text(&report, &manifest, "converted-trained") .replace("case.0.actual=e\n", "case.0.actual=x\n"); let error = validate_quality_gate(&report, &manifest, GATE_ASSISTANT_QUALITY, Some(&eval)) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } fn fixture_report() -> ValidationReport { let bytes = build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors(), &ByteTokenizerSection::phase_one(), ) .unwrap(); slm_validate::validate_bytes(&bytes, "memory.slm").unwrap() } fn passing_eval_text(report: &ValidationReport, manifest: &str, source_kind: &str) -> String { let mut text = String::new(); push_line( &mut text, "tinyrustlm_eval_manifest_version", EVAL_MANIFEST_VERSION, ); push_line(&mut text, "gate", GATE_ASSISTANT_QUALITY); push_line(&mut text, "source_kind", source_kind); push_line( &mut text, "manifest_checksum", &format!("0x{:016x}", text_checksum(manifest.as_bytes())), ); push_line( &mut text, "slm_checksum", &format!("0x{:016x}", report.checksum()), ); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "task_eval_status", "pass"); push_line(&mut text, "safety_review_status", "pass"); push_line( &mut text, "quality_decision", "accepted-for-assistant-quality", ); push_line(&mut text, "quality_scope", "tiny-fixture-runtime-eval-only"); push_line(&mut text, "evaluator", "local-reviewed-eval"); push_line( &mut text, "eval_dataset", "tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", ); push_line( &mut text, "eval_summary", "Reviewed task and safety evidence passed for declared scope", ); push_line( &mut text, "quality_boundary", "fixture-runtime-and-eval-plumbing-not-product-assistant-quality", ); push_line(&mut text, "case_count", "1"); push_line(&mut text, "cases_passed", "1"); push_line(&mut text, "cases_failed", "0"); push_line(&mut text, "case.0.status", "pass"); push_line(&mut text, "case.0.expected", "e"); push_line(&mut text, "case.0.actual", "e"); push_line(&mut text, "case.0.error", "ok"); text } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/provenance.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/prune.rs BYTES: 40374 SHA256: 5D2325C53FDCCDFB3CFA5B167CF535F25670DF29C6C6840AFFA91AE2DC7A349D ================================================================================ //! Offline deterministic magnitude pruning operator for model-breeding candidates. use std::cmp::Ordering; use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::blend::{ hex64, invalid, output_specs, parse_manifest, parse_model_values, parse_passing_compatibility, push_line, push_parent_lines, require_equal, require_key, require_parent_report, require_report_equal, require_same_tensor_spec, same_shape, ParsedModel, PPM_DENOMINATOR, }; use crate::build_model_file_from_values_with_flags; use crate::lineage; use crate::slm_validate::{self, ValidationReport}; const PRUNE_OPERATOR_VERSION: &str = "1"; const OPERATOR_KIND: &str = "deterministic-magnitude-parameter-pruning"; const OPERATOR_STATUS: &str = "candidate-written"; const OPERATOR_OUTPUT_STATUS: &str = "slm-validated"; const PARENT_CONTRACT: &str = "matches-parent-direct-parameter-contract"; const REQUIRED_NEXT_GATE: &str = "candidate-manifest-plus-runtime-smoke-plus-eval"; const DEFAULT_KEEP_PPM: &str = "750000"; const DEFAULT_FLOOR_PPM: &str = "0"; const SELECTION_METRIC: &str = "largest-compatible-magnitude-with-floor"; const SELECTION_SCOPE: &str = "compatible-base-tensor-values"; const TIE_BREAK: &str = "lower-tensor-index-then-lower-element-index"; const VALUE_SOURCE: &str = "base-parent-kept-values-else-zero"; const FLOOR_UNIT: &str = "parts-per-million-of-max-parent-magnitude"; /// Writes a pruned candidate `.slm` plus a recomputable operator receipt. pub(crate) fn write_candidate_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, reference_parent: &Path, output_slm: &Path, output_receipt: &Path, keep_ppm: Option<&str>, floor_ppm: Option<&str>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let reference_bytes = fs::read(reference_parent)?; let keep = parse_keep_ppm(keep_ppm.unwrap_or(DEFAULT_KEEP_PPM))?; let floor = parse_floor_ppm(floor_ppm.unwrap_or(DEFAULT_FLOOR_PPM))?; let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &reference_bytes, &reference_parent.display().to_string(), &output_slm.display().to_string(), keep, floor, )?; if let Some(parent) = output_slm.parent() { fs::create_dir_all(parent)?; } fs::write(output_slm, candidate)?; if let Some(parent) = output_receipt.parent() { fs::create_dir_all(parent)?; } fs::write(output_receipt, receipt)?; println!("SLM prune candidate written: {}", output_slm.display()); println!( "SLM prune operator receipt written: {}", output_receipt.display() ); Ok(()) } /// Validates a prune candidate and receipt by recomputing the operator output. pub(crate) fn validate_candidate_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, reference_parent: &Path, candidate_slm: &Path, receipt: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let reference_bytes = fs::read(reference_parent)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; validate_candidate_text( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &reference_bytes, &reference_parent.display().to_string(), &candidate_bytes, &candidate_slm.display().to_string(), &receipt_text, )?; println!("SLM prune candidate validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("receipt: {}", receipt.display()); Ok(()) } /// Recomputes prune output from receipt fields and compares both artifacts. fn validate_candidate_text( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, reference_bytes: &[u8], reference_path: &str, candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, ) -> io::Result<()> { let receipt = parse_manifest(receipt_text, "prune operator receipt")?; require_equal( &receipt, "tinyrustlm_prune_operator_version", PRUNE_OPERATOR_VERSION, )?; require_equal(&receipt, "operator_kind", OPERATOR_KIND)?; require_equal(&receipt, "base_parent_index", "0")?; require_equal(&receipt, "reference_parent_index", "1")?; require_equal(&receipt, "prune_keep_unit", "parts-per-million")?; require_equal(&receipt, "prune_floor_unit", FLOOR_UNIT)?; require_equal(&receipt, "prune_selection_metric", SELECTION_METRIC)?; require_equal(&receipt, "prune_selection_scope", SELECTION_SCOPE)?; require_equal(&receipt, "prune_tie_break", TIE_BREAK)?; require_equal(&receipt, "prune_value_source", VALUE_SOURCE)?; let keep = parse_keep_ppm(require_key(&receipt, "prune_keep_ppm")?)?; let floor = parse_floor_ppm(require_key(&receipt, "prune_floor_ppm")?)?; let (expected_candidate, expected_receipt) = build_candidate_bytes_and_receipt( compatibility_text, lineage_text, base_bytes, base_path, reference_bytes, reference_path, candidate_path, keep, floor, )?; if candidate_bytes != expected_candidate { return Err(invalid( "prune candidate bytes do not match the operator receipt", )); } if receipt_text != expected_receipt { return Err(invalid( "prune operator receipt fields do not match recomputed output", )); } Ok(()) } /// Builds the pruned `.slm` bytes and receipt that can reproduce them. fn build_candidate_bytes_and_receipt( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, reference_bytes: &[u8], reference_path: &str, candidate_path: &str, keep_ppm: u32, floor_ppm: u32, ) -> io::Result<(Vec, String)> { lineage::validate_text(compatibility_text, lineage_text)?; let compatibility = parse_passing_compatibility(compatibility_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let base_report = slm_validate::validate_bytes(base_bytes, base_path)?; let reference_report = slm_validate::validate_bytes(reference_bytes, reference_path)?; require_parent_report(&compatibility, 0, &base_report)?; require_parent_report(&compatibility, 1, &reference_report)?; let base = parse_model_values(base_bytes)?; let reference = parse_model_values(reference_bytes)?; let (output_values, prune_stats) = prune_values(&base, &reference, keep_ppm, floor_ppm)?; let output_tensors = output_specs(&base); let candidate = build_model_file_from_values_with_flags( &base.shape, &output_tensors, &base.tokenizer, &output_values, base.flags, )?; let candidate_report = slm_validate::validate_bytes(&candidate, candidate_path)?; require_report_equal( &compatibility, "parent.0.model_shape", &candidate_report.shape_summary(), )?; require_report_equal( &compatibility, "parent.0.quantization", candidate_report.quantization_label(), )?; require_report_equal( &compatibility, "parent.0.output_contract", candidate_report.output_contract_label(), )?; require_report_equal( &compatibility, "parent.0.tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), )?; require_report_equal( &compatibility, "parent.0.tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), )?; let receipt = build_receipt_text( &compatibility, &lineage_fields, lineage_text, base_path, reference_path, &base_report, &reference_report, &candidate_report, keep_ppm, floor_ppm, prune_stats, )?; Ok((candidate, receipt)) } /// Formats the manifest-style receipt for a deterministic prune candidate. #[allow(clippy::too_many_arguments)] fn build_receipt_text( compatibility: &HashMap, lineage_fields: &HashMap, lineage_text: &str, base_path: &str, reference_path: &str, base_report: &ValidationReport, reference_report: &ValidationReport, candidate_report: &ValidationReport, keep_ppm: u32, floor_ppm: u32, prune_stats: PruneStats, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_prune_operator_version", PRUNE_OPERATOR_VERSION, ); push_line(&mut text, "operator_kind", OPERATOR_KIND); push_line(&mut text, "operator_status", OPERATOR_STATUS); push_line( &mut text, "candidate_id", require_key(lineage_fields, "candidate_id")?, ); push_line( &mut text, "operator_id", require_key(lineage_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(lineage_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(lineage_fields, "resource_budget")?, ); push_line( &mut text, "compatibility_report_checksum", require_key(lineage_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(compatibility, "compatibility_scope")?, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, compatibility, 0, base_path, base_report)?; push_parent_lines( &mut text, compatibility, 1, reference_path, reference_report, )?; push_line(&mut text, "base_parent_index", "0"); push_line(&mut text, "reference_parent_index", "1"); push_line(&mut text, "prune_keep_unit", "parts-per-million"); push_line(&mut text, "prune_keep_ppm", &keep_ppm.to_string()); push_line(&mut text, "prune_floor_unit", FLOOR_UNIT); push_line(&mut text, "prune_floor_ppm", &floor_ppm.to_string()); push_line(&mut text, "prune_selection_metric", SELECTION_METRIC); push_line(&mut text, "prune_selection_scope", SELECTION_SCOPE); push_line(&mut text, "prune_tie_break", TIE_BREAK); push_line(&mut text, "prune_value_source", VALUE_SOURCE); push_line( &mut text, "prune_total_parameter_count", &prune_stats.total_parameter_count.to_string(), ); push_line( &mut text, "prune_requested_keep_count", &prune_stats.requested_keep_count.to_string(), ); push_line( &mut text, "prune_kept_parameter_count", &prune_stats.kept_parameter_count.to_string(), ); push_line( &mut text, "prune_pruned_parameter_count", &prune_stats.pruned_parameter_count.to_string(), ); push_line( &mut text, "prune_changed_parameter_count", &prune_stats.changed_parameter_count.to_string(), ); push_line( &mut text, "prune_keep_density_ppm", &prune_stats.keep_density_ppm.to_string(), ); push_line( &mut text, "prune_max_magnitude_bits", &format!("0x{:08x}", prune_stats.max_magnitude_bits), ); push_line( &mut text, "prune_floor_threshold_bits", &format!("0x{:08x}", prune_stats.floor_threshold_bits), ); push_line( &mut text, "prune_mask_checksum", &hex64(prune_stats.mask_checksum), ); push_line( &mut text, "prune_output_value_checksum", &hex64(prune_stats.output_value_checksum), ); push_line( &mut text, "candidate_artifact_path", candidate_report.path(), ); push_line( &mut text, "candidate_artifact_bytes", &candidate_report.file_bytes().to_string(), ); push_line( &mut text, "candidate_slm_version", &candidate_report.slm_version().to_string(), ); push_line( &mut text, "candidate_slm_checksum", &hex64(candidate_report.checksum()), ); push_line( &mut text, "candidate_model_shape", &candidate_report.shape_summary(), ); push_line( &mut text, "candidate_tensor_count", &candidate_report.tensor_count().to_string(), ); push_line( &mut text, "candidate_parameter_count", &candidate_report.parameter_count().to_string(), ); push_line( &mut text, "candidate_quantization", candidate_report.quantization_label(), ); push_line( &mut text, "candidate_output_contract", candidate_report.output_contract_label(), ); push_line( &mut text, "candidate_tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), ); push_line( &mut text, "candidate_tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), ); push_line(&mut text, "candidate_parent_contract", PARENT_CONTRACT); push_line(&mut text, "operator_output_status", OPERATOR_OUTPUT_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } /// Applies deterministic magnitude pruning and returns output values plus receipt stats. fn prune_values( base: &ParsedModel, reference: &ParsedModel, keep_ppm: u32, floor_ppm: u32, ) -> io::Result<(Vec>, PruneStats)> { if !same_shape(&base.shape, &reference.shape) { return Err(invalid("prune parents have different model shapes")); } if base.flags != reference.flags { return Err(invalid("prune parents have different output flags")); } if base.tokenizer.bytes != reference.tokenizer.bytes { return Err(invalid("prune parents have different tokenizer bytes")); } let reference_by_hash = reference .tensors .iter() .enumerate() .map(|(index, tensor)| (tensor.spec.name_hash, index)) .collect::>(); let mut ranked = Vec::new(); let mut total_parameter_count = 0u64; let mut max_magnitude = 0.0f32; for (tensor_index, base_tensor) in base.tensors.iter().enumerate() { let Some(reference_index) = reference_by_hash.get(&base_tensor.spec.name_hash) else { return Err(invalid( "reference parent is missing a tensor from the base parent", )); }; let reference_tensor = &reference.tensors[*reference_index]; require_same_tensor_spec(&base_tensor.spec, &reference_tensor.spec)?; total_parameter_count += base_tensor.values.len() as u64; for (value_index, (base_value, reference_value)) in base_tensor .values .iter() .zip(reference_tensor.values.iter()) .enumerate() { let score = base_value.abs().max(reference_value.abs()); if !score.is_finite() { return Err(invalid("prune score is not finite")); } max_magnitude = max_magnitude.max(score); ranked.push(RankedMagnitude { score, tensor_index, value_index, }); } } ranked.sort_by(compare_ranked_magnitude); let requested_keep_count = keep_count(total_parameter_count, keep_ppm)?; let floor_threshold = max_magnitude * (floor_ppm as f32 / PPM_DENOMINATOR as f32); let mut keep_masks = base .tensors .iter() .map(|tensor| vec![false; tensor.values.len()]) .collect::>(); for (rank, entry) in ranked.iter().enumerate() { if rank as u64 >= requested_keep_count { break; } if entry.score >= floor_threshold { keep_masks[entry.tensor_index][entry.value_index] = true; } } let mut output = Vec::with_capacity(base.tensors.len()); let mut stats = PruneStats { total_parameter_count, requested_keep_count, kept_parameter_count: 0, pruned_parameter_count: 0, changed_parameter_count: 0, keep_density_ppm: 0, max_magnitude_bits: max_magnitude.to_bits(), floor_threshold_bits: floor_threshold.to_bits(), mask_checksum: prune_mask_seed(keep_ppm, floor_ppm, floor_threshold), output_value_checksum: prune_value_seed(keep_ppm, floor_ppm), }; for (tensor_index, base_tensor) in base.tensors.iter().enumerate() { let mut values = Vec::with_capacity(base_tensor.values.len()); for (value_index, base_value) in base_tensor.values.iter().enumerate() { let keep = keep_masks[tensor_index][value_index]; let output_value = if keep { *base_value } else { 0.0 }; if keep { stats.kept_parameter_count += 1; } else { stats.pruned_parameter_count += 1; } if output_value != *base_value { stats.changed_parameter_count += 1; } mix_mask_value(&mut stats.mask_checksum, tensor_index as u64); mix_mask_value(&mut stats.mask_checksum, value_index as u64); mix_mask_value(&mut stats.mask_checksum, if keep { 1 } else { 0 }); mix_value_checksum(&mut stats.output_value_checksum, tensor_index as u64); mix_value_checksum(&mut stats.output_value_checksum, value_index as u64); mix_value_checksum( &mut stats.output_value_checksum, u64::from(output_value.to_bits()), ); values.push(output_value); } output.push(values); } stats.keep_density_ppm = ratio_ppm(stats.kept_parameter_count, stats.total_parameter_count)?; mix_mask_value(&mut stats.mask_checksum, stats.total_parameter_count); mix_mask_value(&mut stats.mask_checksum, stats.kept_parameter_count); mix_mask_value(&mut stats.mask_checksum, stats.pruned_parameter_count); mix_value_checksum( &mut stats.output_value_checksum, stats.changed_parameter_count, ); Ok((output, stats)) } /// Orders pruning candidates by descending magnitude with stable coordinate ties. fn compare_ranked_magnitude(left: &RankedMagnitude, right: &RankedMagnitude) -> Ordering { right .score .total_cmp(&left.score) .then_with(|| left.tensor_index.cmp(&right.tensor_index)) .then_with(|| left.value_index.cmp(&right.value_index)) } /// Converts a keep rate into a deterministic ceil-count for selected parameters. fn keep_count(total_parameter_count: u64, keep_ppm: u32) -> io::Result { if total_parameter_count == 0 || keep_ppm == 0 { return Ok(0); } let numerator = u128::from(total_parameter_count) * u128::from(keep_ppm) + u128::from(PPM_DENOMINATOR - 1); let count = numerator / u128::from(PPM_DENOMINATOR); u64::try_from(count).map_err(|_| invalid("prune keep count overflowed u64")) } /// Converts a count ratio into integer parts-per-million. fn ratio_ppm(numerator: u64, denominator: u64) -> io::Result { if denominator == 0 { return Ok(0); } let ppm = u128::from(numerator) * u128::from(PPM_DENOMINATOR) / u128::from(denominator); u64::try_from(ppm).map_err(|_| invalid("prune ratio overflowed u64")) } /// Starts the pruning mask checksum from operator parameters and floor threshold. fn prune_mask_seed(keep_ppm: u32, floor_ppm: u32, floor_threshold: f32) -> u64 { let mut acc = 0x7072_756e_656d_7631u64; mix_mask_value(&mut acc, u64::from(keep_ppm)); mix_mask_value(&mut acc, u64::from(floor_ppm)); mix_mask_value(&mut acc, u64::from(floor_threshold.to_bits())); acc } /// Starts the output-value checksum from operator parameters. fn prune_value_seed(keep_ppm: u32, floor_ppm: u32) -> u64 { let mut acc = 0x7072_756e_6576_7631u64; mix_value_checksum(&mut acc, u64::from(keep_ppm)); mix_value_checksum(&mut acc, u64::from(floor_ppm)); acc } /// Folds one mask decision ingredient into a compact deterministic checksum. fn mix_mask_value(acc: &mut u64, value: u64) { *acc ^= value.wrapping_add(0x9e37_79b9_7f4a_7c15); *acc = acc.rotate_left(11).wrapping_mul(0x1000_0000_01b3); } /// Folds one output-value ingredient into a compact deterministic checksum. fn mix_value_checksum(acc: &mut u64, value: u64) { *acc ^= value.wrapping_add(0xbf58_476d_1ce4_e5b9); *acc = acc.rotate_left(13).wrapping_mul(0x1000_0000_01b3); } /// Parses pruning retention as an integer parts-per-million value. fn parse_keep_ppm(value: &str) -> io::Result { let keep = value .parse::() .map_err(|_| invalid("prune keep must be an integer parts-per-million value"))?; if keep > PPM_DENOMINATOR { return Err(invalid("prune keep must be between 0 and 1000000")); } Ok(keep) } /// Parses pruning floor as an integer parts-per-million value. fn parse_floor_ppm(value: &str) -> io::Result { let floor = value .parse::() .map_err(|_| invalid("prune floor must be an integer parts-per-million value"))?; if floor > PPM_DENOMINATOR { return Err(invalid("prune floor must be between 0 and 1000000")); } Ok(floor) } /// Holds one magnitude-ranked parameter coordinate. struct RankedMagnitude { score: f32, tensor_index: usize, value_index: usize, } /// Holds deterministic pruning counts and checksum metadata. #[derive(Clone, Copy)] struct PruneStats { total_parameter_count: u64, requested_keep_count: u64, kept_parameter_count: u64, pruned_parameter_count: u64, changed_parameter_count: u64, keep_density_ppm: u64, max_magnitude_bits: u32, floor_threshold_bits: u32, mask_checksum: u64, output_value_checksum: u64, } #[cfg(test)] mod tests { use super::*; use crate::compatibility; use crate::tensor_writer::{tiny_fixture_tensors, tiny_fixture_tensors_with_dtype, DTYPE_Q8_0}; use crate::tokenizer_writer::ByteTokenizerSection; use crate::{build_model_file_from_values_with_flags, fixture_value}; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; // Exercises keep and floor parameters through candidate writing and receipt validation. #[test] fn writes_and_validates_prune_candidate() { let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "prune-f32", "prune-v1", "tiny").unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "candidate.slm", 500_000, 0, ) .unwrap(); validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); assert!(any_value_differs(&candidate, &base)); assert!(receipt.contains("operator_kind=deterministic-magnitude-parameter-pruning")); assert!(receipt.contains("prune_keep_ppm=500000")); assert!(receipt.contains("prune_floor_ppm=0")); assert!(receipt.contains("prune_mask_checksum=")); assert!(receipt.contains("prune_output_value_checksum=")); } // Exercises all path-level inputs plus default keep and floor parameters. #[test] fn path_writer_uses_default_parameters_then_validates() { let dir = unique_dir("path-defaults"); fs::create_dir_all(&dir).unwrap(); let base_path = dir.join("base.slm"); let reference_path = dir.join("reference.slm"); let compatibility_path = dir.join("parents.compat"); let lineage_path = dir.join("candidate.lineage"); let candidate_path = dir.join("candidate.slm"); let receipt_path = dir.join("candidate.operator"); let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); fs::write(&base_path, &base).unwrap(); fs::write(&reference_path, &reference).unwrap(); let compatibility = compatibility::compatibility_text_for_bytes( &base, &base_path.display().to_string(), &reference, &reference_path.display().to_string(), ) .unwrap(); fs::write(&compatibility_path, &compatibility).unwrap(); let lineage = lineage::build_template_text(&compatibility, "prune-path", "prune-v1", "tiny").unwrap(); fs::write(&lineage_path, &lineage).unwrap(); write_candidate_path( &compatibility_path, &lineage_path, &base_path, &reference_path, &candidate_path, &receipt_path, None, None, ) .unwrap(); validate_candidate_path( &compatibility_path, &lineage_path, &base_path, &reference_path, &candidate_path, &receipt_path, ) .unwrap(); let receipt = fs::read_to_string(receipt_path).unwrap(); assert!(receipt.contains("prune_keep_ppm=750000")); assert!(receipt.contains("prune_floor_ppm=0")); } // Covers the keep_ppm lower boundary where every base value is pruned. #[test] fn keep_zero_prunes_all_values() { let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "prune-zero", "prune-v1", "tiny").unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "candidate.slm", 0, 0, ) .unwrap(); let candidate_values = parse_model_values(&candidate).unwrap(); for tensor in candidate_values.tensors { assert!(tensor.values.iter().all(|value| *value == 0.0)); } assert!(receipt.contains("prune_kept_parameter_count=0")); assert!(receipt.contains("prune_keep_density_ppm=0")); } // Covers the keep_ppm upper boundary where floor zero preserves the base. #[test] fn keep_all_preserves_base_values() { let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "prune-all", "prune-v1", "tiny").unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "candidate.slm", 1_000_000, 0, ) .unwrap(); assert_same_values(&candidate, &base); assert!(receipt.contains("prune_pruned_parameter_count=0")); assert!(receipt.contains("prune_keep_density_ppm=1000000")); } // Confirms floor_ppm can prune lower-magnitude values inside the keep set. #[test] fn floor_ppm_changes_candidate_values() { let base = tiny_f32_descending_bytes(); let reference = tiny_f32_descending_bytes(); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "prune-floor", "prune-v1", "tiny") .unwrap(); let (no_floor, no_floor_receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "no-floor.slm", 1_000_000, 0, ) .unwrap(); let (high_floor, high_floor_receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "high-floor.slm", 1_000_000, 900_000, ) .unwrap(); assert_ne!(no_floor, high_floor); assert_same_values(&no_floor, &base); assert_ne!( parse_manifest(&no_floor_receipt, "no floor").unwrap()["prune_mask_checksum"], parse_manifest(&high_floor_receipt, "high floor").unwrap()["prune_mask_checksum"] ); assert!(high_floor_receipt.contains("prune_floor_ppm=900000")); } // Confirms the compatible reference parent participates in magnitude ranking. #[test] fn reference_parent_magnitude_changes_mask() { let base = tiny_f32_uniform_bytes(); let reference_a = tiny_f32_with_spike(0, 0, 1000.0); let reference_b = tiny_f32_with_spike(0, 1, 1000.0); let compatibility_a = compatibility::compatibility_text_for_bytes( &base, "base.slm", &reference_a, "ref-a.slm", ) .unwrap(); let compatibility_b = compatibility::compatibility_text_for_bytes( &base, "base.slm", &reference_b, "ref-b.slm", ) .unwrap(); let lineage_a = lineage::build_template_text(&compatibility_a, "prune-ref-a", "prune-v1", "tiny") .unwrap(); let lineage_b = lineage::build_template_text(&compatibility_b, "prune-ref-b", "prune-v1", "tiny") .unwrap(); let (candidate_a, receipt_a) = build_candidate_bytes_and_receipt( &compatibility_a, &lineage_a, &base, "base.slm", &reference_a, "ref-a.slm", "candidate-a.slm", 1, 0, ) .unwrap(); let (candidate_b, receipt_b) = build_candidate_bytes_and_receipt( &compatibility_b, &lineage_b, &base, "base.slm", &reference_b, "ref-b.slm", "candidate-b.slm", 1, 0, ) .unwrap(); assert_ne!(candidate_a, candidate_b); assert_ne!( parse_manifest(&receipt_a, "receipt a").unwrap()["prune_mask_checksum"], parse_manifest(&receipt_b, "receipt b").unwrap()["prune_mask_checksum"] ); } // Validates q8 parents keep their quantization route through pruning output. #[test] fn writes_and_validates_q8_prune_candidate() { let base = tiny_q8_scaled_bytes(1.0); let reference = tiny_q8_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "prune-q8", "prune-v1", "tiny").unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "candidate.slm", 500_000, 0, ) .unwrap(); slm_validate::validate_bytes(&candidate, "candidate.slm").unwrap(); validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); assert!(receipt.contains("candidate_quantization=q8_0")); } // Confirms base parameters are tied to compatibility receipts by checksum. #[test] fn rejects_parent_checksum_drift() { let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "prune-drift", "prune-v1", "tiny") .unwrap(); let changed_base = tiny_f32_scaled_bytes(3.0); let error = build_candidate_bytes_and_receipt( &compatibility, &lineage, &changed_base, "base.slm", &reference, "ref.slm", "candidate.slm", 500_000, 0, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("parent.0.slm_checksum")); } // Confirms validation catches candidate bytes that no longer match the receipt. #[test] fn validation_rejects_candidate_drift() { let base = tiny_f32_scaled_bytes(1.0); let reference = tiny_f32_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &reference, "ref.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "prune-drift", "prune-v1", "tiny") .unwrap(); let (mut candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", "candidate.slm", 500_000, 0, ) .unwrap(); let last = candidate.len() - 1; candidate[last] ^= 0x01; let error = validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &reference, "ref.slm", &candidate, "candidate.slm", &receipt, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate bytes")); } // Covers parser behavior for keep and floor inputs. #[test] fn rejects_invalid_prune_parameters() { assert_eq!( parse_keep_ppm("1000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_keep_ppm("-1").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_keep_ppm("many").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_floor_ppm("1000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_floor_ppm("-1").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_floor_ppm("high").unwrap_err().kind(), io::ErrorKind::InvalidData ); } // Compares decoded tensor values between two `.slm` byte buffers. fn assert_same_values(candidate: &[u8], expected: &[u8]) { let candidate_values = parse_model_values(candidate).unwrap(); let expected_values = parse_model_values(expected).unwrap(); for (candidate_tensor, expected_tensor) in candidate_values .tensors .iter() .zip(expected_values.tensors.iter()) { assert_eq!(candidate_tensor.values, expected_tensor.values); } } // Detects whether any decoded tensor value differs between two `.slm` buffers. fn any_value_differs(candidate: &[u8], expected: &[u8]) -> bool { let candidate_values = parse_model_values(candidate).unwrap(); let expected_values = parse_model_values(expected).unwrap(); candidate_values .tensors .iter() .zip(expected_values.tensors.iter()) .any(|(candidate_tensor, expected_tensor)| { candidate_tensor.values != expected_tensor.values }) } // Builds a tiny f32 model with all fixture values multiplied by scale. fn tiny_f32_scaled_bytes(scale: f32) -> Vec { build_tiny_bytes(tiny_fixture_tensors(), |tensor, index, _tensor_index| { fixture_value(tensor, index) * scale }) } // Builds a tiny f32 model with descending positive values for floor tests. fn tiny_f32_descending_bytes() -> Vec { build_tiny_bytes(tiny_fixture_tensors(), |_tensor, index, tensor_index| { let coordinate = tensor_index * 1000 + index; (10_000usize.saturating_sub(coordinate)) as f32 }) } // Builds a tiny f32 model with stable nonzero unique values. fn tiny_f32_uniform_bytes() -> Vec { build_tiny_bytes(tiny_fixture_tensors(), |_tensor, index, tensor_index| { 1.0 + (tensor_index as f32 * 0.01) + (index as f32 * 0.001) }) } // Builds a tiny f32 reference with one large magnitude coordinate. fn tiny_f32_with_spike(spike_tensor: usize, spike_index: usize, spike: f32) -> Vec { build_tiny_bytes(tiny_fixture_tensors(), |_tensor, index, tensor_index| { if tensor_index == spike_tensor && index == spike_index { spike } else { 1.0 } }) } // Builds a tiny q8 model with all fixture values multiplied by scale. fn tiny_q8_scaled_bytes(scale: f32) -> Vec { build_tiny_bytes( tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), |tensor, index, _tensor_index| fixture_value(tensor, index) * scale, ) } // Packs a tiny fixture model from caller-supplied tensor values. fn build_tiny_bytes(tensors: Vec, mut value: F) -> Vec where F: FnMut(&crate::tensor_writer::TensorSpec, usize, usize) -> f32, { let values = tensors .iter() .enumerate() .map(|(tensor_index, tensor)| { (0..tensor.element_count()) .map(|index| value(tensor, index, tensor_index)) .collect::>() }) .collect::>(); build_model_file_from_values_with_flags( &crate::tensor_writer::ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } // Creates an isolated temp directory for path-level operator tests. fn unique_dir(label: &str) -> PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-prune-{label}-{nanos}")) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/prune.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/quant_writer.rs BYTES: 1697 SHA256: BAE177AE9B3D8525DE0B2360EDB29882E034F551CEC87202B198470290D8686E ================================================================================ //! Quantization writer helpers. #![allow(dead_code)] /// Quantizes one f32 row into signed q8 values and a row scale. pub fn quantize_q8_row(row: &[f32], out: &mut [i8]) -> f32 { let mut max_abs = 0.0f32; for value in row { max_abs = max_abs.max(value.abs()); } let scale = if max_abs == 0.0 { 1.0 } else { max_abs / 127.0 }; for (index, value) in row.iter().enumerate() { out[index] = (*value / scale).round().clamp(-127.0, 127.0) as i8; } scale } /// Packs signed q4 nibbles into bytes using low nibble first. pub fn pack_q4_pair(a: i8, b: i8) -> u8 { ((b as u8) & 0x0f) << 4 | ((a as u8) & 0x0f) } /// Quantizes one f32 block into signed q4 values and a block scale. pub fn quantize_q4_block(block: &[f32], out: &mut [i8]) -> f32 { let mut max_abs = 0.0f32; for value in block { max_abs = max_abs.max(value.abs()); } let scale = if max_abs == 0.0 { 1.0 } else { max_abs / 7.0 }; for (index, value) in block.iter().enumerate() { out[index] = (*value / scale).round().clamp(-8.0, 7.0) as i8; } scale } #[cfg(test)] mod tests { use super::*; #[test] fn quantize_q8_row_produces_scale() { let mut out = [0i8; 2]; let scale = quantize_q8_row(&[1.0, -1.0], &mut out); assert!(scale > 0.0); assert_eq!(out, [127, -127]); } #[test] fn pack_q4_pair_low_nibble_first() { assert_eq!(pack_q4_pair(-1, 1), 0x1f); } #[test] fn quantize_q4_block_produces_scale() { let mut out = [0i8; 2]; let scale = quantize_q4_block(&[1.0, -1.0], &mut out); assert!(scale > 0.0); assert_eq!(out, [7, -7]); } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/quant_writer.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/selector.rs BYTES: 290730 SHA256: 0A7776F75175BDE827C68A609D2DA050C18B9DCFB614231A61672FF9E557DB9F ================================================================================ //! Browser selector registries built from admitted model-breeding records. use std::collections::{HashMap, HashSet}; use std::fs; use std::io; use std::path::Path; use crate::admission; use crate::multi_admission; use crate::provenance; const REGISTRY_VERSION: &str = "1"; const REGISTRY_SCOPE: &str = "browser-local-model-selector"; const REGISTRY_STATUS: &str = "admitted-records-only"; const ENTRY_STATUS: &str = "admitted"; const PUBLIC_CLAIM_STATUS: &str = "bound-to-eval-scope"; const REQUIRED_NEXT_GATE: &str = "browser-loads-selector-registry-entry-models"; const SELECTOR_DEFAULT_STRATEGY: &str = "browser-frugal-quantized"; const SELECTOR_MODEL_BYTE_BUDGET: u64 = 32 * 1024 * 1024; const SELECTOR_REGISTRY_TEXT_BYTE_BUDGET: u64 = 256 * 1024; const MANIFEST_TEXT_BYTE_BUDGET: u64 = 64 * 1024; const RECEIPT_TEXT_BYTE_BUDGET: u64 = 128 * 1024; const EVIDENCE_TEXT_BYTE_BUDGET: u64 = 128 * 1024; const ADAPTER_APPLY_STATUS_F32: &str = "runtime-f32-compatible-or-fuse-to-slm"; const ADAPTER_APPLY_STATUS_QUANTIZED: &str = "runtime-q8-q4-compatible-or-fuse-to-slm"; const LOW_RANK_APPLY_STATUS_F32: &str = "runtime-f32-compatible-low-rank"; const LOW_RANK_APPLY_STATUS_QUANTIZED: &str = "runtime-q8-q4-compatible-low-rank"; const ADAPTER_FAMILY_STATUS: &str = "receipt-validated"; const ADAPTER_FAMILY_STRATEGY: &str = "single-adapter-selection"; const ADAPTER_AUTO_APPLY_STATUS: &str = "enabled"; const ADAPTER_AUTO_APPLY_STRATEGY: &str = "receipt-preferred-compatible"; const ADAPTER_AUTO_APPLY_STACK_STATUS: &str = "enabled"; const ADAPTER_AUTO_APPLY_STACK_STRATEGY: &str = "receipt-declared-compatible-stack"; const ADAPTER_AUTO_APPLY_BYTE_BUDGET: u64 = 1024 * 1024; const ASSEMBLY_RECEIPT_STATUS: &str = "receipt-validated"; const ASSEMBLY_RECEIPT_KIND: &str = "browser-local-assembly-evidence"; const MODULE_PLAN_STATUS: &str = "receipt-validated"; const MODULE_PLAN_KIND: &str = "browser-local-module-plan"; const MODULE_PLAN_STRATEGY: &str = "selector-entry-self-assembly"; const MODULE_PLAN_RESOURCE_CLASS: &str = "browser-constrained-local-assembly"; const MODULE_PLAN_PROFILE: &str = "browser-constrained-v1"; const MODULE_PLAN_EXECUTION_PROFILE: &str = "single-threaded-wasm-local-v1"; const MODULE_PLAN_FETCH_POLICY: &str = "local-no-store-v1"; const MODULE_PLAN_ORIGIN_POLICY: &str = "same-origin-loopback-local-v1"; const MODULE_PLAN_FETCH_COUNT_LIMIT: u64 = 32; const MODULE_PLAN_ROUTE_SET_VERSION: &str = "1"; const MODULE_PLAN_ROUTE_SET_CHECKSUM_ALGORITHM: &str = "tinyrustlm-text-checksum-v1"; const MODULE_PLAN_ASSEMBLY_EVIDENCE_FILE_COUNT: u64 = 9; const MODULE_PLAN_WASM_MEMORY_INITIAL_PAGES: u64 = 17; const MODULE_PLAN_WASM_EXPORT_SET: &str = "tinyrustlm-generate-v1"; const MODULE_PLAN_WASM_TRANSFER_STRATEGY: &str = "copy-then-release-v1"; const MODULE_PLAN_MODEL_RELEASE_STRATEGY: &str = "free-before-reassembly-v1"; const MODULE_PLAN_RUNTIME_RESET_STRATEGY: &str = "reset-context-before-assembly-v1"; const MODULE_PLAN_ADAPTER_VALIDATION_STRATEGY: &str = "rust-validate-before-apply-v1"; const MODULE_PLAN_WASM_HEAP_MIN_BYTES: u64 = 64 * 1024; const MODULE_PLAN_CONTEXT_TOKEN_LIMIT_LIMIT: u64 = 4096; const MODULE_PLAN_SAMPLER_CANDIDATE_CAP: u64 = 1024; const MODULE_PLAN_PROMPT_BYTE_LIMIT: u64 = 4 * 1024; const MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET: u64 = 64 * 1024; const MODULE_PLAN_OUTPUT_BYTE_LIMIT: u64 = 64 * 1024; const MODULE_PLAN_KV_CACHE_BYTE_BUDGET_LIMIT: u64 = 8 * 1024 * 1024; const MODULE_PLAN_TOTAL_BYTE_BUDGET_LIMIT: u64 = SELECTOR_MODEL_BYTE_BUDGET + ADAPTER_AUTO_APPLY_BYTE_BUDGET + MODULE_PLAN_KV_CACHE_BYTE_BUDGET_LIMIT + MANIFEST_TEXT_BYTE_BUDGET + RECEIPT_TEXT_BYTE_BUDGET + RECEIPT_TEXT_BYTE_BUDGET + MODULE_PLAN_PROMPT_BYTE_LIMIT + MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET + MODULE_PLAN_OUTPUT_BYTE_LIMIT; const GENOME_STRATEGY: &str = "selector-admission-genome-v1"; const GENOME_LINEAGE_STATUS: &str = "admission-bound"; const SPECIES_STRATEGY: &str = "selector-speciation-fit-v1"; const SPECIES_FIT_STATUS: &str = "browser-fit-bound"; const NOVELTY_STRATEGY: &str = "selector-novelty-sketch-v1"; const NOVELTY_STATUS: &str = "behavior-sketch-bound"; const POPULATION_STRATEGY: &str = "selector-population-review-route-v1"; const POPULATION_STATUS: &str = "population-review-bound"; const MATE_SELECTION_STRATEGY: &str = "selector-mate-selection-route-v1"; const MATE_SELECTION_PARENT_POOL_STATUS: &str = "parent-pool-bound"; const MATE_SELECTION_ADMISSION_STATUS: &str = "admission-only"; const EVOLUTION_RECIPE_VERSION: &str = "1"; const EVOLUTION_RECIPE_STRATEGY: &str = "population-based-parent-pool-replay-v1"; const EVOLUTION_RECIPE_STATUS: &str = "planned"; const EVOLUTION_SELECTION_SOURCE: &str = "population-review-frontier-v1"; const EVOLUTION_SCHEDULE_CHECKSUM_ALGORITHM: &str = "tinyrustlm-text-checksum-v1"; const PHENOTYPE_EVIDENCE_STRATEGY: &str = "selector-phenotype-evidence-v1"; const PHENOTYPE_EVIDENCE_STATUS: &str = "runtime-eval-bound"; const HERITABLE_ARTIFACT_STRATEGY: &str = "selector-heritable-artifact-v1"; const HERITABLE_ARTIFACT_STATUS: &str = "served-artifact-bound"; const FITNESS_VECTOR_STATUS: &str = "eval-bound"; const EVOLUTION_SCHEDULE_KEYS: &[&str] = &[ "evolution_recipe_version", "evolution_recipe_strategy", "evolution_recipe_status", "evolution_selection_source", "evolution_relatedness_contract_checksum", "evolution_schedule_checksum_algorithm", "evolution_schedule_checksum", "scheduled_operator_family_index", "scheduled_operator_family_kind", "scheduled_operator_family_command", "scheduled_operator_family_selection_rule", "scheduled_operator_family_output_gate", ]; const ADAPTER_KEY_SUFFIXES: &[&str] = &[ "adapter_path", "adapter_manifest_path", "adapter_label", "adapter_apply_status", "adapter_artifact_checksum", "adapter_manifest_checksum", "adapter_count", ]; const ADAPTER_FAMILY_KEY_SUFFIXES: &[&str] = &[ "adapter_family_receipt_path", "adapter_family_receipt_checksum", "adapter_family_label", "adapter_family_status", "adapter_family_strategy", "adapter_family_adapter_count", "adapter_auto_apply_status", "adapter_auto_apply_strategy", "adapter_auto_apply_stack_status", "adapter_auto_apply_stack_strategy", "adapter_auto_apply_stack_count", "adapter_auto_apply_byte_budget", ]; const ASSEMBLY_RECEIPT_KEY_SUFFIXES: &[&str] = &[ "assembly_receipt_path", "assembly_receipt_checksum", "assembly_label", "assembly_status", "assembly_kind", ]; const MODULE_PLAN_KEY_SUFFIXES: &[&str] = &[ "module_plan_path", "module_plan_checksum", "module_plan_label", "module_plan_status", "module_plan_kind", "module_plan_strategy", "module_plan_resource_class", "module_plan_profile", "module_plan_execution_profile", "module_plan_fetch_policy", "module_plan_origin_policy", "module_plan_fetch_count_limit", "module_plan_planned_fetch_count", "module_plan_route_set_version", "module_plan_route_set_checksum_algorithm", "module_plan_route_set_checksum", "module_plan_operator_receipt_path", "module_plan_operator_receipt_checksum", "module_plan_wasm_memory_initial_pages", "module_plan_wasm_export_set", "module_plan_wasm_transfer_strategy", "module_plan_model_release_strategy", "module_plan_runtime_reset_strategy", "module_plan_adapter_validation_strategy", "module_plan_adapter_validation_count", "module_plan_adapter_apply_count", "module_plan_wasm_heap_min_bytes", "module_plan_context_token_limit", "module_plan_sampler_candidate_cap", "module_plan_tokenizer_checksum", "module_plan_prompt_byte_limit", "module_plan_model_byte_budget", "module_plan_adapter_byte_budget", "module_plan_adapter_stack_byte_budget", "module_plan_runtime_scratch_byte_budget", "module_plan_output_byte_limit", "module_plan_kv_cache_byte_budget", "module_plan_kv_cache_page_count", "module_plan_total_byte_budget", "module_plan_total_byte_budget_limit", "module_plan_module_count", ]; struct RegistryEntry { candidate_id: String, display_name: String, artifact_path: String, model_path: String, manifest_path: String, max_tokens: String, model_bytes: String, slm_checksum: String, tokenizer_checksum: String, model_shape: String, quantization: String, output_contract: String, admission_checksum: String, promotion_manifest_checksum: String, provenance_manifest_checksum: String, runtime_smoke_manifest_checksum: String, eval_manifest_checksum: String, eval_case_evidence_checksum: String, quality_scope: String, quality_boundary: String, eval_dataset: String, cases_passed: String, admission_kind: String, operator_receipt: Option, operator_receipt_checksum: Option, parent_pool_recipe_checksum: Option, population_review_checksum: Option, promotion_ledger_checksum: Option, admission_set_checksum: Option, parent_count: usize, evolution_schedule: Option, adapters: Vec, adapter_family: Option, assembly: Option, module_plan: Option, } #[derive(Clone, Debug, Eq, PartialEq)] struct RegistryOperatorReceipt { status: String, path: String, checksum: String, operator_id: String, operator_kind: String, candidate_slm_checksum: String, candidate_artifact_bytes: String, } #[derive(Clone, Debug, Eq, PartialEq)] struct RegistryEvolutionSchedule { recipe_version: String, recipe_strategy: String, recipe_status: String, selection_source: String, relatedness_contract_checksum: String, schedule_checksum_algorithm: String, schedule_checksum: String, family_index: String, family_kind: String, family_command: String, family_selection_rule: String, family_output_gate: String, } /// Optional browser-local adapter sidecar metadata for a selector registry entry. #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) struct RegistryAdapterRoute { pub(crate) candidate_id: String, pub(crate) adapter_path: String, pub(crate) manifest_path: String, pub(crate) label: String, pub(crate) apply_status: String, pub(crate) artifact_checksum: String, pub(crate) manifest_checksum: String, } /// Optional browser-local adapter family receipt metadata for a selector entry. #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) struct RegistryAdapterFamilyRoute { pub(crate) candidate_id: String, pub(crate) receipt_path: String, pub(crate) label: String, pub(crate) status: String, pub(crate) strategy: String, pub(crate) receipt_checksum: String, pub(crate) adapter_count: usize, pub(crate) auto_apply_status: String, pub(crate) auto_apply_strategy: String, pub(crate) auto_apply_stack_status: String, pub(crate) auto_apply_stack_strategy: String, pub(crate) auto_apply_stack_count: usize, pub(crate) auto_apply_byte_budget: u64, } /// Optional browser-local assembly evidence receipt metadata for a selector entry. #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) struct RegistryAssemblyRoute { pub(crate) candidate_id: String, pub(crate) receipt_path: String, pub(crate) label: String, pub(crate) status: String, pub(crate) kind: String, pub(crate) receipt_checksum: String, } /// Optional browser-local self-assembly module-plan receipt metadata for a selector entry. #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) struct RegistryModulePlanRoute { pub(crate) candidate_id: String, pub(crate) receipt_path: String, pub(crate) label: String, pub(crate) status: String, pub(crate) kind: String, pub(crate) strategy: String, pub(crate) resource_class: String, pub(crate) profile: String, pub(crate) execution_profile: String, pub(crate) fetch_policy: String, pub(crate) origin_policy: String, pub(crate) fetch_count_limit: u64, pub(crate) planned_fetch_count: u64, pub(crate) route_set_version: String, pub(crate) route_set_checksum_algorithm: String, pub(crate) route_set_checksum: String, pub(crate) operator_receipt_path: String, pub(crate) operator_receipt_checksum: String, pub(crate) wasm_memory_initial_pages: u64, pub(crate) wasm_export_set: String, pub(crate) wasm_transfer_strategy: String, pub(crate) model_release_strategy: String, pub(crate) runtime_reset_strategy: String, pub(crate) adapter_validation_strategy: String, pub(crate) adapter_validation_count: u64, pub(crate) adapter_apply_count: u64, pub(crate) wasm_heap_min_bytes: u64, pub(crate) context_token_limit: u64, pub(crate) sampler_candidate_cap: u64, pub(crate) tokenizer_checksum: String, pub(crate) prompt_byte_limit: u64, pub(crate) model_byte_budget: u64, pub(crate) adapter_byte_budget: u64, pub(crate) adapter_stack_byte_budget: u64, pub(crate) runtime_scratch_byte_budget: u64, pub(crate) output_byte_limit: u64, pub(crate) kv_cache_byte_budget: u64, pub(crate) kv_cache_page_count: u64, pub(crate) total_byte_budget: u64, pub(crate) total_byte_budget_limit: u64, pub(crate) receipt_checksum: String, pub(crate) module_count: usize, } /// Writes a browser selector registry from one or more selector admission records. pub(crate) fn write_registry_path(output: &Path, admission_paths: &[String]) -> io::Result<()> { let admission_texts = read_admissions(admission_paths)?; let registry = build_registry_text(&admission_texts)?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, registry)?; println!("SLM selector registry written: {}", output.display()); Ok(()) } /// Writes a browser selector registry with adapter, assembly, and module-plan receipts. pub(crate) fn write_registry_with_module_plan_routes_path( output: &Path, admission_paths: &[String], adapter_routes: &[RegistryAdapterRoute], family_routes: &[RegistryAdapterFamilyRoute], assembly_routes: &[RegistryAssemblyRoute], module_plan_routes: &[RegistryModulePlanRoute], ) -> io::Result<()> { let admission_texts = read_admissions(admission_paths)?; let registry = build_registry_text_with_module_plan_routes( &admission_texts, adapter_routes, family_routes, assembly_routes, module_plan_routes, )?; if let Some(parent) = output.parent() { fs::create_dir_all(parent)?; } fs::write(output, registry)?; println!("SLM selector registry written: {}", output.display()); println!("adapter_routes: {}", adapter_routes.len()); println!("adapter_family_routes: {}", family_routes.len()); println!("assembly_routes: {}", assembly_routes.len()); println!("module_plan_routes: {}", module_plan_routes.len()); Ok(()) } /// Validates a browser selector registry against its selector admission records. pub(crate) fn validate_registry_path( registry: &Path, admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_admissions(admission_paths)?; let registry_text = fs::read_to_string(registry)?; validate_registry_text(®istry_text, &admission_texts)?; println!("SLM selector registry validation: PASS"); println!("registry: {}", registry.display()); println!("admissions: {}", admission_paths.len()); Ok(()) } fn read_admissions(admission_paths: &[String]) -> io::Result> { if admission_paths.is_empty() { return Err(invalid( "selector-registry requires at least one admission record", )); } admission_paths .iter() .map(|path| fs::read_to_string(Path::new(path))) .collect() } pub(crate) fn build_registry_text(admission_texts: &[String]) -> io::Result { build_registry_text_with_adapters(admission_texts, &[]) } pub(crate) fn build_registry_text_with_adapters( admission_texts: &[String], adapter_routes: &[RegistryAdapterRoute], ) -> io::Result { build_registry_text_with_adapter_families(admission_texts, adapter_routes, &[]) } pub(crate) fn build_registry_text_with_adapter_families( admission_texts: &[String], adapter_routes: &[RegistryAdapterRoute], family_routes: &[RegistryAdapterFamilyRoute], ) -> io::Result { build_registry_text_with_adapter_family_and_assembly_routes( admission_texts, adapter_routes, family_routes, &[], ) } pub(crate) fn build_registry_text_with_adapter_family_and_assembly_routes( admission_texts: &[String], adapter_routes: &[RegistryAdapterRoute], family_routes: &[RegistryAdapterFamilyRoute], assembly_routes: &[RegistryAssemblyRoute], ) -> io::Result { build_registry_text_with_module_plan_routes( admission_texts, adapter_routes, family_routes, assembly_routes, &[], ) } pub(crate) fn build_registry_text_with_module_plan_routes( admission_texts: &[String], adapter_routes: &[RegistryAdapterRoute], family_routes: &[RegistryAdapterFamilyRoute], assembly_routes: &[RegistryAssemblyRoute], module_plan_routes: &[RegistryModulePlanRoute], ) -> io::Result { let mut entries = entries_from_admissions(admission_texts)?; attach_adapter_routes(&mut entries, adapter_routes)?; attach_adapter_family_routes(&mut entries, family_routes)?; attach_assembly_routes(&mut entries, assembly_routes)?; attach_module_plan_routes(&mut entries, module_plan_routes)?; let selector_id = selector_id(admission_texts)?; let default_entry = default_selector_entry(&entries)?; let mut text = String::new(); push_line( &mut text, "tinyrustlm_selector_registry_version", REGISTRY_VERSION, ); push_line(&mut text, "selector_id", &selector_id); push_line(&mut text, "registry_scope", REGISTRY_SCOPE); push_line(&mut text, "registry_status", REGISTRY_STATUS); push_line( &mut text, "selector_model_byte_budget", &SELECTOR_MODEL_BYTE_BUDGET.to_string(), ); push_line( &mut text, "selector_registry_text_byte_budget", &SELECTOR_REGISTRY_TEXT_BYTE_BUDGET.to_string(), ); push_line( &mut text, "manifest_text_byte_budget", &MANIFEST_TEXT_BYTE_BUDGET.to_string(), ); push_line( &mut text, "receipt_text_byte_budget", &RECEIPT_TEXT_BYTE_BUDGET.to_string(), ); push_line( &mut text, "evidence_text_byte_budget", &EVIDENCE_TEXT_BYTE_BUDGET.to_string(), ); push_line(&mut text, "entry_count", &entries.len().to_string()); push_line( &mut text, "selector_default_strategy", SELECTOR_DEFAULT_STRATEGY, ); push_line( &mut text, "selector_default_candidate_id", &default_entry.candidate_id, ); push_line( &mut text, "selector_default_quantization", &default_entry.quantization, ); push_line( &mut text, "admission_set_checksum", &admission_set_checksum(admission_texts), ); for (index, entry) in entries.iter().enumerate() { let prefix = format!("entry.{index}"); push_line( &mut text, &format!("{prefix}.candidate_id"), &entry.candidate_id, ); push_line( &mut text, &format!("{prefix}.display_name"), &entry.display_name, ); push_line( &mut text, &format!("{prefix}.model_path"), &entry.model_path, ); push_line( &mut text, &format!("{prefix}.manifest_path"), &entry.manifest_path, ); push_line( &mut text, &format!("{prefix}.artifact_path"), &entry.artifact_path, ); push_line( &mut text, &format!("{prefix}.max_tokens"), &entry.max_tokens, ); push_line( &mut text, &format!("{prefix}.model_bytes"), &entry.model_bytes, ); push_line( &mut text, &format!("{prefix}.slm_checksum"), &entry.slm_checksum, ); push_line( &mut text, &format!("{prefix}.tokenizer_checksum"), &entry.tokenizer_checksum, ); push_line( &mut text, &format!("{prefix}.model_shape"), &entry.model_shape, ); push_line( &mut text, &format!("{prefix}.quantization"), &entry.quantization, ); push_line( &mut text, &format!("{prefix}.output_contract"), &entry.output_contract, ); push_line( &mut text, &format!("{prefix}.genome_id"), ®istry_entry_genome_id(entry), ); push_line( &mut text, &format!("{prefix}.genome_strategy"), GENOME_STRATEGY, ); push_line( &mut text, &format!("{prefix}.genome_lineage_status"), GENOME_LINEAGE_STATUS, ); push_line( &mut text, &format!("{prefix}.genome_lineage_checksum"), ®istry_entry_genome_lineage_checksum(entry), ); push_line( &mut text, &format!("{prefix}.species_id"), ®istry_entry_species_id(entry), ); push_line( &mut text, &format!("{prefix}.species_strategy"), SPECIES_STRATEGY, ); push_line( &mut text, &format!("{prefix}.species_fit_status"), SPECIES_FIT_STATUS, ); push_line( &mut text, &format!("{prefix}.species_fit_checksum"), ®istry_entry_species_fit_checksum(entry), ); push_line( &mut text, &format!("{prefix}.novelty_id"), ®istry_entry_novelty_id(entry), ); push_line( &mut text, &format!("{prefix}.novelty_strategy"), NOVELTY_STRATEGY, ); push_line( &mut text, &format!("{prefix}.novelty_status"), NOVELTY_STATUS, ); push_line( &mut text, &format!("{prefix}.novelty_checksum"), ®istry_entry_novelty_checksum(entry), ); push_line( &mut text, &format!("{prefix}.population_id"), ®istry_entry_population_id(entry), ); push_line( &mut text, &format!("{prefix}.population_strategy"), POPULATION_STRATEGY, ); push_line( &mut text, &format!("{prefix}.population_status"), POPULATION_STATUS, ); push_line( &mut text, &format!("{prefix}.population_checksum"), ®istry_entry_population_checksum(entry), ); push_line( &mut text, &format!("{prefix}.mate_selection_id"), ®istry_entry_mate_selection_id(entry), ); push_line( &mut text, &format!("{prefix}.mate_selection_strategy"), MATE_SELECTION_STRATEGY, ); push_line( &mut text, &format!("{prefix}.mate_selection_status"), registry_entry_mate_selection_status(entry), ); push_line( &mut text, &format!("{prefix}.mate_selection_parent_count"), &entry.parent_count.to_string(), ); push_line( &mut text, &format!("{prefix}.mate_selection_checksum"), ®istry_entry_mate_selection_checksum(entry), ); push_registry_operator_receipt_lines(&mut text, &prefix, entry); push_registry_evolution_schedule_lines(&mut text, &prefix, entry); push_line( &mut text, &format!("{prefix}.phenotype_evidence_id"), ®istry_entry_phenotype_evidence_id(entry), ); push_line( &mut text, &format!("{prefix}.phenotype_evidence_strategy"), PHENOTYPE_EVIDENCE_STRATEGY, ); push_line( &mut text, &format!("{prefix}.phenotype_evidence_status"), PHENOTYPE_EVIDENCE_STATUS, ); push_line( &mut text, &format!("{prefix}.phenotype_evidence_checksum"), ®istry_entry_phenotype_evidence_checksum(entry), ); push_line( &mut text, &format!("{prefix}.heritable_artifact_id"), ®istry_entry_heritable_artifact_id(entry), ); push_line( &mut text, &format!("{prefix}.heritable_artifact_strategy"), HERITABLE_ARTIFACT_STRATEGY, ); push_line( &mut text, &format!("{prefix}.heritable_artifact_status"), HERITABLE_ARTIFACT_STATUS, ); push_line( &mut text, &format!("{prefix}.heritable_artifact_checksum"), ®istry_entry_heritable_artifact_checksum(entry), ); push_line( &mut text, &format!("{prefix}.admission_checksum"), &entry.admission_checksum, ); push_line( &mut text, &format!("{prefix}.promotion_manifest_checksum"), &entry.promotion_manifest_checksum, ); push_line( &mut text, &format!("{prefix}.provenance_manifest_checksum"), &entry.provenance_manifest_checksum, ); push_line( &mut text, &format!("{prefix}.runtime_smoke_manifest_checksum"), &entry.runtime_smoke_manifest_checksum, ); push_line( &mut text, &format!("{prefix}.eval_manifest_checksum"), &entry.eval_manifest_checksum, ); push_line( &mut text, &format!("{prefix}.eval_case_evidence_checksum"), &entry.eval_case_evidence_checksum, ); push_line( &mut text, &format!("{prefix}.quality_scope"), &entry.quality_scope, ); push_line( &mut text, &format!("{prefix}.quality_boundary"), &entry.quality_boundary, ); push_line( &mut text, &format!("{prefix}.eval_dataset"), &entry.eval_dataset, ); push_line( &mut text, &format!("{prefix}.cases_passed"), &entry.cases_passed, ); push_line( &mut text, &format!("{prefix}.fitness_vector_status"), FITNESS_VECTOR_STATUS, ); push_line( &mut text, &format!("{prefix}.fitness_vector_checksum"), ®istry_entry_fitness_vector_checksum(entry), ); if let Some(adapter) = entry.adapters.first() { push_line( &mut text, &format!("{prefix}.adapter_path"), &adapter.adapter_path, ); push_line( &mut text, &format!("{prefix}.adapter_manifest_path"), &adapter.manifest_path, ); push_line( &mut text, &format!("{prefix}.adapter_label"), &adapter.label, ); push_line( &mut text, &format!("{prefix}.adapter_apply_status"), &adapter.apply_status, ); push_line( &mut text, &format!("{prefix}.adapter_artifact_checksum"), &adapter.artifact_checksum, ); push_line( &mut text, &format!("{prefix}.adapter_manifest_checksum"), &adapter.manifest_checksum, ); } if entry.adapters.len() > 1 { push_line( &mut text, &format!("{prefix}.adapter_count"), &entry.adapters.len().to_string(), ); for (adapter_index, adapter) in entry.adapters.iter().enumerate() { let adapter_prefix = format!("{prefix}.adapter.{adapter_index}"); push_line( &mut text, &format!("{adapter_prefix}.path"), &adapter.adapter_path, ); push_line( &mut text, &format!("{adapter_prefix}.manifest_path"), &adapter.manifest_path, ); push_line( &mut text, &format!("{adapter_prefix}.label"), &adapter.label, ); push_line( &mut text, &format!("{adapter_prefix}.apply_status"), &adapter.apply_status, ); push_line( &mut text, &format!("{adapter_prefix}.artifact_checksum"), &adapter.artifact_checksum, ); push_line( &mut text, &format!("{adapter_prefix}.manifest_checksum"), &adapter.manifest_checksum, ); } } if let Some(family) = &entry.adapter_family { push_line( &mut text, &format!("{prefix}.adapter_family_receipt_path"), &family.receipt_path, ); push_line( &mut text, &format!("{prefix}.adapter_family_receipt_checksum"), &family.receipt_checksum, ); push_line( &mut text, &format!("{prefix}.adapter_family_label"), &family.label, ); push_line( &mut text, &format!("{prefix}.adapter_family_status"), &family.status, ); push_line( &mut text, &format!("{prefix}.adapter_family_strategy"), &family.strategy, ); push_line( &mut text, &format!("{prefix}.adapter_family_adapter_count"), &family.adapter_count.to_string(), ); push_line( &mut text, &format!("{prefix}.adapter_auto_apply_status"), &family.auto_apply_status, ); push_line( &mut text, &format!("{prefix}.adapter_auto_apply_strategy"), &family.auto_apply_strategy, ); push_line( &mut text, &format!("{prefix}.adapter_auto_apply_stack_status"), &family.auto_apply_stack_status, ); push_line( &mut text, &format!("{prefix}.adapter_auto_apply_stack_strategy"), &family.auto_apply_stack_strategy, ); push_line( &mut text, &format!("{prefix}.adapter_auto_apply_stack_count"), &family.auto_apply_stack_count.to_string(), ); push_line( &mut text, &format!("{prefix}.adapter_auto_apply_byte_budget"), &family.auto_apply_byte_budget.to_string(), ); } if let Some(assembly) = &entry.assembly { push_line( &mut text, &format!("{prefix}.assembly_receipt_path"), &assembly.receipt_path, ); push_line( &mut text, &format!("{prefix}.assembly_receipt_checksum"), &assembly.receipt_checksum, ); push_line( &mut text, &format!("{prefix}.assembly_label"), &assembly.label, ); push_line( &mut text, &format!("{prefix}.assembly_status"), &assembly.status, ); push_line( &mut text, &format!("{prefix}.assembly_kind"), &assembly.kind, ); } if let Some(module_plan) = &entry.module_plan { push_line( &mut text, &format!("{prefix}.module_plan_path"), &module_plan.receipt_path, ); push_line( &mut text, &format!("{prefix}.module_plan_checksum"), &module_plan.receipt_checksum, ); push_line( &mut text, &format!("{prefix}.module_plan_label"), &module_plan.label, ); push_line( &mut text, &format!("{prefix}.module_plan_status"), &module_plan.status, ); push_line( &mut text, &format!("{prefix}.module_plan_kind"), &module_plan.kind, ); push_line( &mut text, &format!("{prefix}.module_plan_strategy"), &module_plan.strategy, ); push_line( &mut text, &format!("{prefix}.module_plan_resource_class"), &module_plan.resource_class, ); push_line( &mut text, &format!("{prefix}.module_plan_profile"), &module_plan.profile, ); push_line( &mut text, &format!("{prefix}.module_plan_execution_profile"), &module_plan.execution_profile, ); push_line( &mut text, &format!("{prefix}.module_plan_fetch_policy"), &module_plan.fetch_policy, ); push_line( &mut text, &format!("{prefix}.module_plan_origin_policy"), &module_plan.origin_policy, ); push_line( &mut text, &format!("{prefix}.module_plan_fetch_count_limit"), &module_plan.fetch_count_limit.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_planned_fetch_count"), &module_plan.planned_fetch_count.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_route_set_version"), &module_plan.route_set_version, ); push_line( &mut text, &format!("{prefix}.module_plan_route_set_checksum_algorithm"), &module_plan.route_set_checksum_algorithm, ); push_line( &mut text, &format!("{prefix}.module_plan_route_set_checksum"), &module_plan.route_set_checksum, ); push_line( &mut text, &format!("{prefix}.module_plan_operator_receipt_path"), &module_plan.operator_receipt_path, ); push_line( &mut text, &format!("{prefix}.module_plan_operator_receipt_checksum"), &module_plan.operator_receipt_checksum, ); push_line( &mut text, &format!("{prefix}.module_plan_wasm_memory_initial_pages"), &module_plan.wasm_memory_initial_pages.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_wasm_export_set"), &module_plan.wasm_export_set, ); push_line( &mut text, &format!("{prefix}.module_plan_wasm_transfer_strategy"), &module_plan.wasm_transfer_strategy, ); push_line( &mut text, &format!("{prefix}.module_plan_model_release_strategy"), &module_plan.model_release_strategy, ); push_line( &mut text, &format!("{prefix}.module_plan_runtime_reset_strategy"), &module_plan.runtime_reset_strategy, ); push_line( &mut text, &format!("{prefix}.module_plan_adapter_validation_strategy"), &module_plan.adapter_validation_strategy, ); push_line( &mut text, &format!("{prefix}.module_plan_adapter_validation_count"), &module_plan.adapter_validation_count.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_adapter_apply_count"), &module_plan.adapter_apply_count.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_wasm_heap_min_bytes"), &module_plan.wasm_heap_min_bytes.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_context_token_limit"), &module_plan.context_token_limit.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_sampler_candidate_cap"), &module_plan.sampler_candidate_cap.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_tokenizer_checksum"), &module_plan.tokenizer_checksum, ); push_line( &mut text, &format!("{prefix}.module_plan_prompt_byte_limit"), &module_plan.prompt_byte_limit.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_model_byte_budget"), &module_plan.model_byte_budget.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_adapter_byte_budget"), &module_plan.adapter_byte_budget.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_adapter_stack_byte_budget"), &module_plan.adapter_stack_byte_budget.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_runtime_scratch_byte_budget"), &module_plan.runtime_scratch_byte_budget.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_output_byte_limit"), &module_plan.output_byte_limit.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_kv_cache_byte_budget"), &module_plan.kv_cache_byte_budget.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_kv_cache_page_count"), &module_plan.kv_cache_page_count.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_total_byte_budget"), &module_plan.total_byte_budget.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_total_byte_budget_limit"), &module_plan.total_byte_budget_limit.to_string(), ); push_line( &mut text, &format!("{prefix}.module_plan_module_count"), &module_plan.module_count.to_string(), ); } push_line( &mut text, &format!("{prefix}.selector_status"), ENTRY_STATUS, ); push_line( &mut text, &format!("{prefix}.public_claim_status"), PUBLIC_CLAIM_STATUS, ); } push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } fn validate_registry_text(registry_text: &str, admission_texts: &[String]) -> io::Result<()> { let actual = parse_manifest(registry_text, "selector registry")?; let adapter_routes = adapter_routes_from_registry(&actual)?; let family_routes = adapter_family_routes_from_registry(&actual)?; let assembly_routes = assembly_routes_from_registry(&actual)?; let module_plan_routes = module_plan_routes_from_registry(&actual)?; let expected_text = build_registry_text_with_module_plan_routes( admission_texts, &adapter_routes, &family_routes, &assembly_routes, &module_plan_routes, )?; let expected = parse_manifest(&expected_text, "expected selector registry")?; require_equal( &actual, "tinyrustlm_selector_registry_version", REGISTRY_VERSION, )?; require_equal(&actual, "registry_scope", REGISTRY_SCOPE)?; require_equal(&actual, "registry_status", REGISTRY_STATUS)?; require_equal( &actual, "selector_model_byte_budget", &SELECTOR_MODEL_BYTE_BUDGET.to_string(), )?; require_equal( &actual, "selector_registry_text_byte_budget", &SELECTOR_REGISTRY_TEXT_BYTE_BUDGET.to_string(), )?; require_equal( &actual, "manifest_text_byte_budget", &MANIFEST_TEXT_BYTE_BUDGET.to_string(), )?; require_equal( &actual, "receipt_text_byte_budget", &RECEIPT_TEXT_BYTE_BUDGET.to_string(), )?; require_equal( &actual, "evidence_text_byte_budget", &EVIDENCE_TEXT_BYTE_BUDGET.to_string(), )?; require_equal(&actual, "required_next_gate", REQUIRED_NEXT_GATE)?; for (key, expected_value) in &expected { require_equal(&actual, key, expected_value)?; } for key in actual.keys() { if !expected.contains_key(key) { return Err(invalid(&format!("unexpected selector registry key {key}"))); } } Ok(()) } fn default_selector_entry(entries: &[RegistryEntry]) -> io::Result<&RegistryEntry> { entries .iter() .min_by_key(|entry| { ( quantization_default_rank(&entry.quantization), &entry.candidate_id, ) }) .ok_or_else(|| invalid("selector registry requires at least one admission record")) } fn quantization_default_rank(quantization: &str) -> u8 { match quantization { "q4_0" => 0, "q8_0" => 1, "f32" => 2, _ => 3, } } // Pulls each reviewed admission into the browser selector entry shape. fn entries_from_admissions(admission_texts: &[String]) -> io::Result> { if admission_texts.is_empty() { return Err(invalid( "selector registry requires at least one admission record", )); } let selector_id = selector_id(admission_texts)?; let mut candidate_ids = HashSet::new(); let mut slm_checksums = HashSet::new(); let mut entries = Vec::with_capacity(admission_texts.len()); for admission_text in admission_texts { let fields = validate_admission_summary_text(admission_text)?; let actual_selector = require_key(&fields, "selector_id")?; if actual_selector != selector_id { return Err(invalid( "selector registry admissions must share one selector_id", )); } let candidate_id = require_key(&fields, "candidate_id")?.to_string(); if !candidate_ids.insert(candidate_id.clone()) { return Err(invalid(&format!( "duplicate selector registry candidate_id {candidate_id}" ))); } let slm_checksum = require_key(&fields, "candidate_slm_checksum")?.to_string(); if !slm_checksums.insert(slm_checksum.clone()) { return Err(invalid(&format!( "duplicate selector registry candidate checksum {slm_checksum}" ))); } let artifact_path = require_key(&fields, "candidate_artifact_path")?.to_string(); let model_path = browser_model_path(&artifact_path)?; let manifest_path = format!("{model_path}.manifest"); let model_shape = require_key(&fields, "candidate_model_shape")?.to_string(); let model_bytes = selector_model_bytes(require_key(&fields, "candidate_artifact_bytes")?)?; let tokenizer_checksum = require_key(&fields, "candidate_tokenizer_checksum")?.to_string(); let operator_receipt = registry_operator_receipt_from_fields(&fields)?; let evolution_schedule = registry_evolution_schedule_from_fields(&fields, operator_receipt.as_ref())?; entries.push(RegistryEntry { candidate_id: candidate_id.clone(), display_name: display_name( &candidate_id, require_key(&fields, "candidate_quantization")?, ), artifact_path, model_path, manifest_path, max_tokens: default_max_tokens(&model_shape).to_string(), model_bytes: model_bytes.to_string(), slm_checksum, tokenizer_checksum, model_shape, quantization: require_key(&fields, "candidate_quantization")?.to_string(), output_contract: require_key(&fields, "candidate_output_contract")?.to_string(), admission_checksum: hex64(provenance::text_checksum(admission_text.as_bytes())), promotion_manifest_checksum: require_key(&fields, "promotion_manifest_checksum")? .to_string(), provenance_manifest_checksum: require_key(&fields, "provenance_manifest_checksum")? .to_string(), runtime_smoke_manifest_checksum: require_key( &fields, "runtime_smoke_manifest_checksum", )? .to_string(), eval_manifest_checksum: require_key(&fields, "eval_manifest_checksum")?.to_string(), eval_case_evidence_checksum: require_key(&fields, "eval_case_evidence_checksum")? .to_string(), quality_scope: require_key(&fields, "quality_scope")?.to_string(), quality_boundary: require_key(&fields, "quality_boundary")?.to_string(), eval_dataset: require_key(&fields, "eval_dataset")?.to_string(), cases_passed: require_key(&fields, "cases_passed")?.to_string(), admission_kind: fields .get("admission_kind") .cloned() .unwrap_or_else(|| "selector-admission".to_string()), operator_receipt, operator_receipt_checksum: fields.get("operator_receipt_checksum").cloned(), parent_pool_recipe_checksum: fields.get("parent_pool_recipe_checksum").cloned(), population_review_checksum: fields.get("population_review_checksum").cloned(), promotion_ledger_checksum: fields.get("promotion_ledger_checksum").cloned(), admission_set_checksum: fields.get("admission_set_checksum").cloned(), parent_count: match fields.get("parent_count") { Some(value) => { let count = value.parse::().map_err(|_| { invalid("selector registry admission parent_count is invalid") })?; if count == 0 { return Err(invalid( "selector registry admission parent_count is invalid", )); } count } None => 1, }, evolution_schedule, adapters: Vec::new(), adapter_family: None, assembly: None, module_plan: None, }); } Ok(entries) } // Copies the full two-parent operator receipt family when an admission exposes it. fn registry_operator_receipt_from_fields( fields: &HashMap, ) -> io::Result> { if !fields.contains_key("operator_receipt_status") { return Ok(None); } require_equal(fields, "operator_receipt_status", "receipt-bound")?; let checksum = require_key(fields, "operator_receipt_checksum")?.to_string(); let candidate_slm_checksum = require_key(fields, "operator_receipt_candidate_slm_checksum")?.to_string(); validate_hex64(&checksum, "operator_receipt_checksum")?; validate_hex64( &candidate_slm_checksum, "operator_receipt_candidate_slm_checksum", )?; require_equal( fields, "operator_receipt_candidate_slm_checksum", require_key(fields, "candidate_slm_checksum")?, )?; require_equal( fields, "operator_receipt_candidate_artifact_bytes", require_key(fields, "candidate_artifact_bytes")?, )?; let candidate_artifact_bytes = require_key(fields, "operator_receipt_candidate_artifact_bytes")?.to_string(); if candidate_artifact_bytes.parse::().is_err() || candidate_artifact_bytes == "0" { return Err(invalid( "selector registry operator_receipt_candidate_artifact_bytes is invalid", )); } Ok(Some(RegistryOperatorReceipt { status: "receipt-bound".to_string(), path: require_key(fields, "operator_receipt_path")?.to_string(), checksum, operator_id: require_key(fields, "operator_receipt_operator_id")?.to_string(), operator_kind: require_key(fields, "operator_receipt_operator_kind")?.to_string(), candidate_slm_checksum, candidate_artifact_bytes, })) } // Copies parent-pool evolution schedule fields once an admission binds an operator receipt. fn registry_evolution_schedule_from_fields( fields: &HashMap, operator_receipt: Option<&RegistryOperatorReceipt>, ) -> io::Result> { if !EVOLUTION_SCHEDULE_KEYS .iter() .any(|key| fields.contains_key(*key)) { return Ok(None); } let Some(receipt) = operator_receipt else { return Err(invalid( "selector registry evolution schedule requires an operator receipt", )); }; require_equal(fields, "evolution_recipe_version", EVOLUTION_RECIPE_VERSION)?; require_equal( fields, "evolution_recipe_strategy", EVOLUTION_RECIPE_STRATEGY, )?; require_equal(fields, "evolution_recipe_status", EVOLUTION_RECIPE_STATUS)?; require_equal( fields, "evolution_selection_source", EVOLUTION_SELECTION_SOURCE, )?; require_equal( fields, "evolution_schedule_checksum_algorithm", EVOLUTION_SCHEDULE_CHECKSUM_ALGORITHM, )?; let relatedness_contract_checksum = require_key(fields, "evolution_relatedness_contract_checksum")?.to_string(); let schedule_checksum = require_key(fields, "evolution_schedule_checksum")?.to_string(); validate_hex64( &relatedness_contract_checksum, "evolution_relatedness_contract_checksum", )?; validate_hex64(&schedule_checksum, "evolution_schedule_checksum")?; let family_index = require_key(fields, "scheduled_operator_family_index")?.to_string(); if family_index.parse::().is_err() { return Err(invalid( "selector registry scheduled_operator_family_index is invalid", )); } for key in [ "scheduled_operator_family_kind", "scheduled_operator_family_command", "scheduled_operator_family_selection_rule", "scheduled_operator_family_output_gate", ] { validate_registry_slug(require_key(fields, key)?, key)?; } require_equal( fields, "scheduled_operator_family_kind", &receipt.operator_kind, )?; Ok(Some(RegistryEvolutionSchedule { recipe_version: EVOLUTION_RECIPE_VERSION.to_string(), recipe_strategy: EVOLUTION_RECIPE_STRATEGY.to_string(), recipe_status: EVOLUTION_RECIPE_STATUS.to_string(), selection_source: EVOLUTION_SELECTION_SOURCE.to_string(), relatedness_contract_checksum, schedule_checksum_algorithm: EVOLUTION_SCHEDULE_CHECKSUM_ALGORITHM.to_string(), schedule_checksum, family_index, family_kind: require_key(fields, "scheduled_operator_family_kind")?.to_string(), family_command: require_key(fields, "scheduled_operator_family_command")?.to_string(), family_selection_rule: require_key(fields, "scheduled_operator_family_selection_rule")? .to_string(), family_output_gate: require_key(fields, "scheduled_operator_family_output_gate")? .to_string(), })) } fn attach_adapter_routes( entries: &mut [RegistryEntry], adapter_routes: &[RegistryAdapterRoute], ) -> io::Result<()> { let mut entry_index = HashMap::new(); for (index, entry) in entries.iter().enumerate() { entry_index.insert(entry.candidate_id.clone(), index); } let mut seen = HashSet::new(); for route in adapter_routes { validate_registry_adapter_route(route)?; if !seen.insert(format!("{}\n{}", route.candidate_id, route.adapter_path)) { return Err(invalid(&format!( "duplicate selector registry adapter route for {}", route.candidate_id ))); } let Some(index) = entry_index.get(&route.candidate_id).copied() else { return Err(invalid(&format!( "adapter route candidate_id {} has no selector registry entry", route.candidate_id ))); }; validate_adapter_apply_status_for_quantization(route, &entries[index].quantization)?; entries[index].adapters.push(route.clone()); } Ok(()) } fn attach_adapter_family_routes( entries: &mut [RegistryEntry], family_routes: &[RegistryAdapterFamilyRoute], ) -> io::Result<()> { let mut entry_index = HashMap::new(); for (index, entry) in entries.iter().enumerate() { entry_index.insert(entry.candidate_id.clone(), index); } let mut seen = HashSet::new(); for route in family_routes { validate_registry_adapter_family_route(route)?; if !seen.insert(route.candidate_id.as_str()) { return Err(invalid(&format!( "duplicate selector registry adapter family route for {}", route.candidate_id ))); } let Some(index) = entry_index.get(&route.candidate_id).copied() else { return Err(invalid(&format!( "adapter family route candidate_id {} has no selector registry entry", route.candidate_id ))); }; if entries[index].adapters.len() != route.adapter_count { return Err(invalid( "selector registry adapter family count must match indexed adapter routes", )); } entries[index].adapter_family = Some(route.clone()); } Ok(()) } fn attach_assembly_routes( entries: &mut [RegistryEntry], assembly_routes: &[RegistryAssemblyRoute], ) -> io::Result<()> { let mut entry_index = HashMap::new(); for (index, entry) in entries.iter().enumerate() { entry_index.insert(entry.candidate_id.clone(), index); } let mut seen = HashSet::new(); for route in assembly_routes { validate_registry_assembly_route(route)?; if !seen.insert(route.candidate_id.as_str()) { return Err(invalid(&format!( "duplicate selector registry assembly route for {}", route.candidate_id ))); } let Some(index) = entry_index.get(&route.candidate_id).copied() else { return Err(invalid(&format!( "assembly route candidate_id {} has no selector registry entry", route.candidate_id ))); }; entries[index].assembly = Some(route.clone()); } Ok(()) } fn attach_module_plan_routes( entries: &mut [RegistryEntry], module_plan_routes: &[RegistryModulePlanRoute], ) -> io::Result<()> { let mut entry_index = HashMap::new(); for (index, entry) in entries.iter().enumerate() { entry_index.insert(entry.candidate_id.clone(), index); } let mut seen = HashSet::new(); for route in module_plan_routes { validate_registry_module_plan_route(route)?; if !seen.insert(route.candidate_id.as_str()) { return Err(invalid(&format!( "duplicate selector registry module plan route for {}", route.candidate_id ))); } let Some(index) = entry_index.get(&route.candidate_id).copied() else { return Err(invalid(&format!( "module plan route candidate_id {} has no selector registry entry", route.candidate_id ))); }; let entry = &entries[index]; let Some(family) = &entry.adapter_family else { return Err(invalid( "selector registry module plan requires an adapter family route", )); }; if entry.assembly.is_none() { return Err(invalid( "selector registry module plan requires an assembly route", )); } let assembly = entry.assembly.as_ref().expect("checked assembly route"); let expected_module_count = 4usize .checked_add(family.auto_apply_stack_count) .ok_or_else(|| invalid("selector registry module plan count overflow"))?; if route.module_count != expected_module_count { return Err(invalid( "selector registry module plan count must match model, manifest, receipts, and adapter stack", )); } let model_bytes = entry .model_bytes .parse::() .map_err(|_| invalid("selector registry module plan model budget is invalid"))?; if route.model_byte_budget != model_bytes { return Err(invalid( "selector registry module plan model byte budget must match the admitted model bytes", )); } if route.adapter_byte_budget != family.auto_apply_byte_budget { return Err(invalid( "selector registry module plan adapter byte budget must match the adapter family budget", )); } if route.adapter_stack_byte_budget > family.auto_apply_byte_budget { return Err(invalid( "selector registry module plan adapter stack byte budget must fit the adapter family budget", )); } let expected_context_token_limit = model_shape_context_token_limit(&entry.model_shape)?; if route.context_token_limit != expected_context_token_limit { return Err(invalid( "selector registry module plan context token limit must match admitted model shape", )); } if route.tokenizer_checksum != entry.tokenizer_checksum { return Err(invalid( "selector registry module plan tokenizer checksum must match admitted tokenizer", )); } if route.route_set_checksum != module_plan_route_set_checksum(entry, route, family, assembly)? { return Err(invalid( "selector registry module plan route set checksum must match generated assembly routes", )); } if let Some(operator_receipt_checksum) = &entry.operator_receipt_checksum { if route.operator_receipt_checksum != *operator_receipt_checksum { return Err(invalid( "selector registry module plan operator receipt checksum must match admitted operator receipt", )); } } entries[index].module_plan = Some(route.clone()); } Ok(()) } fn adapter_routes_from_registry( fields: &HashMap, ) -> io::Result> { let entry_count = require_key(fields, "entry_count")? .parse::() .map_err(|_| invalid("selector registry entry_count is invalid"))?; let mut routes = Vec::new(); for index in 0..entry_count { let prefix = format!("entry.{index}"); let has_adapter_key = ADAPTER_KEY_SUFFIXES.iter().any(|suffix| { let key = format!("{prefix}.{suffix}"); fields.contains_key(&key) }); if !has_adapter_key { continue; } let candidate_id_key = format!("{prefix}.candidate_id"); let candidate_id = require_key(fields, &candidate_id_key)?.to_string(); let adapter_count_key = format!("{prefix}.adapter_count"); if fields.contains_key(&adapter_count_key) { let adapter_count = require_key(fields, &adapter_count_key)? .parse::() .map_err(|_| invalid("selector registry adapter_count is invalid"))?; if adapter_count == 0 || adapter_count > 16 { return Err(invalid("selector registry adapter_count is invalid")); } let mut entry_routes = Vec::with_capacity(adapter_count); for adapter_index in 0..adapter_count { let adapter_prefix = format!("{prefix}.adapter.{adapter_index}"); let route = registry_adapter_route_from_fields( fields, &candidate_id, &format!("{adapter_prefix}.path"), &format!("{adapter_prefix}.manifest_path"), &format!("{adapter_prefix}.label"), &format!("{adapter_prefix}.apply_status"), &format!("{adapter_prefix}.artifact_checksum"), &format!("{adapter_prefix}.manifest_checksum"), )?; entry_routes.push(route); } if fields.contains_key(&format!("{prefix}.adapter_path")) { let legacy_route = legacy_adapter_route_from_fields(fields, &prefix, &candidate_id)?; if Some(&legacy_route) != entry_routes.first() { return Err(invalid( "selector registry legacy adapter fields must mirror the first indexed adapter route", )); } } routes.extend(entry_routes); continue; } let route = legacy_adapter_route_from_fields(fields, &prefix, &candidate_id)?; routes.push(route); } Ok(routes) } fn adapter_family_routes_from_registry( fields: &HashMap, ) -> io::Result> { let entry_count = require_key(fields, "entry_count")? .parse::() .map_err(|_| invalid("selector registry entry_count is invalid"))?; let mut routes = Vec::new(); for index in 0..entry_count { let prefix = format!("entry.{index}"); let has_family_key = ADAPTER_FAMILY_KEY_SUFFIXES.iter().any(|suffix| { let key = format!("{prefix}.{suffix}"); fields.contains_key(&key) }); if !has_family_key { continue; } let candidate_id_key = format!("{prefix}.candidate_id"); let route = RegistryAdapterFamilyRoute { candidate_id: require_key(fields, &candidate_id_key)?.to_string(), receipt_path: require_key(fields, &format!("{prefix}.adapter_family_receipt_path"))? .to_string(), receipt_checksum: require_key( fields, &format!("{prefix}.adapter_family_receipt_checksum"), )? .to_string(), label: require_key(fields, &format!("{prefix}.adapter_family_label"))?.to_string(), status: require_key(fields, &format!("{prefix}.adapter_family_status"))?.to_string(), strategy: require_key(fields, &format!("{prefix}.adapter_family_strategy"))? .to_string(), adapter_count: require_key(fields, &format!("{prefix}.adapter_family_adapter_count"))? .parse::() .map_err(|_| invalid("selector registry adapter family count is invalid"))?, auto_apply_status: require_key(fields, &format!("{prefix}.adapter_auto_apply_status"))? .to_string(), auto_apply_strategy: require_key( fields, &format!("{prefix}.adapter_auto_apply_strategy"), )? .to_string(), auto_apply_stack_status: require_key( fields, &format!("{prefix}.adapter_auto_apply_stack_status"), )? .to_string(), auto_apply_stack_strategy: require_key( fields, &format!("{prefix}.adapter_auto_apply_stack_strategy"), )? .to_string(), auto_apply_stack_count: require_key( fields, &format!("{prefix}.adapter_auto_apply_stack_count"), )? .parse::() .map_err(|_| invalid("selector registry adapter auto apply stack count is invalid"))?, auto_apply_byte_budget: require_key( fields, &format!("{prefix}.adapter_auto_apply_byte_budget"), )? .parse::() .map_err(|_| invalid("selector registry adapter auto apply byte budget is invalid"))?, }; validate_registry_adapter_family_route(&route)?; routes.push(route); } Ok(routes) } fn assembly_routes_from_registry( fields: &HashMap, ) -> io::Result> { let entry_count = require_key(fields, "entry_count")? .parse::() .map_err(|_| invalid("selector registry entry_count is invalid"))?; let mut routes = Vec::new(); for index in 0..entry_count { let prefix = format!("entry.{index}"); let has_assembly_key = ASSEMBLY_RECEIPT_KEY_SUFFIXES.iter().any(|suffix| { let key = format!("{prefix}.{suffix}"); fields.contains_key(&key) }); if !has_assembly_key { continue; } let candidate_id_key = format!("{prefix}.candidate_id"); let route = RegistryAssemblyRoute { candidate_id: require_key(fields, &candidate_id_key)?.to_string(), receipt_path: require_key(fields, &format!("{prefix}.assembly_receipt_path"))? .to_string(), receipt_checksum: require_key(fields, &format!("{prefix}.assembly_receipt_checksum"))? .to_string(), label: require_key(fields, &format!("{prefix}.assembly_label"))?.to_string(), status: require_key(fields, &format!("{prefix}.assembly_status"))?.to_string(), kind: require_key(fields, &format!("{prefix}.assembly_kind"))?.to_string(), }; validate_registry_assembly_route(&route)?; routes.push(route); } Ok(routes) } fn module_plan_routes_from_registry( fields: &HashMap, ) -> io::Result> { let entry_count = require_key(fields, "entry_count")? .parse::() .map_err(|_| invalid("selector registry entry_count is invalid"))?; let mut routes = Vec::new(); for index in 0..entry_count { let prefix = format!("entry.{index}"); let has_module_plan_key = MODULE_PLAN_KEY_SUFFIXES.iter().any(|suffix| { let key = format!("{prefix}.{suffix}"); fields.contains_key(&key) }); if !has_module_plan_key { continue; } let candidate_id_key = format!("{prefix}.candidate_id"); let route = RegistryModulePlanRoute { candidate_id: require_key(fields, &candidate_id_key)?.to_string(), receipt_path: require_key(fields, &format!("{prefix}.module_plan_path"))?.to_string(), receipt_checksum: require_key(fields, &format!("{prefix}.module_plan_checksum"))? .to_string(), label: require_key(fields, &format!("{prefix}.module_plan_label"))?.to_string(), status: require_key(fields, &format!("{prefix}.module_plan_status"))?.to_string(), kind: require_key(fields, &format!("{prefix}.module_plan_kind"))?.to_string(), strategy: require_key(fields, &format!("{prefix}.module_plan_strategy"))?.to_string(), resource_class: require_key(fields, &format!("{prefix}.module_plan_resource_class"))? .to_string(), profile: require_key(fields, &format!("{prefix}.module_plan_profile"))?.to_string(), execution_profile: require_key( fields, &format!("{prefix}.module_plan_execution_profile"), )? .to_string(), fetch_policy: require_key(fields, &format!("{prefix}.module_plan_fetch_policy"))? .to_string(), origin_policy: require_key(fields, &format!("{prefix}.module_plan_origin_policy"))? .to_string(), fetch_count_limit: parse_module_plan_count( fields, &format!("{prefix}.module_plan_fetch_count_limit"), "fetch count limit", )?, planned_fetch_count: parse_module_plan_count( fields, &format!("{prefix}.module_plan_planned_fetch_count"), "planned fetch count", )?, route_set_version: require_key( fields, &format!("{prefix}.module_plan_route_set_version"), )? .to_string(), route_set_checksum_algorithm: require_key( fields, &format!("{prefix}.module_plan_route_set_checksum_algorithm"), )? .to_string(), route_set_checksum: require_key( fields, &format!("{prefix}.module_plan_route_set_checksum"), )? .to_string(), operator_receipt_path: require_key( fields, &format!("{prefix}.module_plan_operator_receipt_path"), )? .to_string(), operator_receipt_checksum: require_key( fields, &format!("{prefix}.module_plan_operator_receipt_checksum"), )? .to_string(), wasm_memory_initial_pages: { let value = require_key( fields, &format!("{prefix}.module_plan_wasm_memory_initial_pages"), )?; let pages = value.parse::().map_err(|_| { invalid("selector registry module plan wasm memory initial pages is invalid") })?; if pages == 0 || pages.to_string() != value { return Err(invalid( "selector registry module plan wasm memory initial pages is invalid", )); } pages }, wasm_export_set: require_key(fields, &format!("{prefix}.module_plan_wasm_export_set"))? .to_string(), wasm_transfer_strategy: require_key( fields, &format!("{prefix}.module_plan_wasm_transfer_strategy"), )? .to_string(), model_release_strategy: require_key( fields, &format!("{prefix}.module_plan_model_release_strategy"), )? .to_string(), runtime_reset_strategy: require_key( fields, &format!("{prefix}.module_plan_runtime_reset_strategy"), )? .to_string(), adapter_validation_strategy: require_key( fields, &format!("{prefix}.module_plan_adapter_validation_strategy"), )? .to_string(), adapter_validation_count: parse_module_plan_count( fields, &format!("{prefix}.module_plan_adapter_validation_count"), "adapter validation count", )?, adapter_apply_count: parse_module_plan_count( fields, &format!("{prefix}.module_plan_adapter_apply_count"), "adapter apply count", )?, wasm_heap_min_bytes: parse_module_plan_byte_budget( fields, &format!("{prefix}.module_plan_wasm_heap_min_bytes"), "wasm heap", )?, context_token_limit: parse_module_plan_count( fields, &format!("{prefix}.module_plan_context_token_limit"), "context token limit", )?, sampler_candidate_cap: parse_module_plan_count( fields, &format!("{prefix}.module_plan_sampler_candidate_cap"), "sampler candidate cap", )?, tokenizer_checksum: require_key( fields, &format!("{prefix}.module_plan_tokenizer_checksum"), )? .to_string(), prompt_byte_limit: parse_module_plan_byte_budget( fields, &format!("{prefix}.module_plan_prompt_byte_limit"), "prompt", )?, model_byte_budget: parse_module_plan_byte_budget( fields, &format!("{prefix}.module_plan_model_byte_budget"), "model", )?, adapter_byte_budget: parse_module_plan_byte_budget( fields, &format!("{prefix}.module_plan_adapter_byte_budget"), "adapter", )?, adapter_stack_byte_budget: parse_module_plan_byte_budget( fields, &format!("{prefix}.module_plan_adapter_stack_byte_budget"), "adapter stack", )?, runtime_scratch_byte_budget: parse_module_plan_byte_budget( fields, &format!("{prefix}.module_plan_runtime_scratch_byte_budget"), "runtime scratch", )?, output_byte_limit: parse_module_plan_byte_budget( fields, &format!("{prefix}.module_plan_output_byte_limit"), "output", )?, kv_cache_byte_budget: parse_module_plan_byte_budget( fields, &format!("{prefix}.module_plan_kv_cache_byte_budget"), "kv cache", )?, kv_cache_page_count: parse_module_plan_page_count( fields, &format!("{prefix}.module_plan_kv_cache_page_count"), )?, total_byte_budget: parse_module_plan_byte_budget( fields, &format!("{prefix}.module_plan_total_byte_budget"), "total", )?, total_byte_budget_limit: parse_module_plan_byte_budget( fields, &format!("{prefix}.module_plan_total_byte_budget_limit"), "total limit", )?, module_count: require_key(fields, &format!("{prefix}.module_plan_module_count"))? .parse::() .map_err(|_| invalid("selector registry module plan count is invalid"))?, }; validate_registry_module_plan_route(&route)?; routes.push(route); } Ok(routes) } fn legacy_adapter_route_from_fields( fields: &HashMap, prefix: &str, candidate_id: &str, ) -> io::Result { registry_adapter_route_from_fields( fields, candidate_id, &format!("{prefix}.adapter_path"), &format!("{prefix}.adapter_manifest_path"), &format!("{prefix}.adapter_label"), &format!("{prefix}.adapter_apply_status"), &format!("{prefix}.adapter_artifact_checksum"), &format!("{prefix}.adapter_manifest_checksum"), ) } fn registry_adapter_route_from_fields( fields: &HashMap, candidate_id: &str, adapter_path_key: &str, manifest_path_key: &str, label_key: &str, apply_status_key: &str, artifact_checksum_key: &str, manifest_checksum_key: &str, ) -> io::Result { let route = RegistryAdapterRoute { candidate_id: candidate_id.to_string(), adapter_path: require_key(fields, adapter_path_key)?.to_string(), manifest_path: require_key(fields, manifest_path_key)?.to_string(), label: require_key(fields, label_key)?.to_string(), apply_status: require_key(fields, apply_status_key)?.to_string(), artifact_checksum: require_key(fields, artifact_checksum_key)?.to_string(), manifest_checksum: require_key(fields, manifest_checksum_key)?.to_string(), }; validate_registry_adapter_route(&route)?; Ok(route) } pub(crate) fn validate_registry_adapter_route(route: &RegistryAdapterRoute) -> io::Result<()> { if route.candidate_id.trim().is_empty() { return Err(invalid("selector registry adapter candidate_id is empty")); } validate_adapter_route_path(&route.adapter_path)?; let expected_manifest_path = format!("{}.manifest", route.adapter_path); if route.manifest_path != expected_manifest_path { return Err(invalid( "selector registry adapter manifest path must match adapter path sidecar", )); } if route.label.trim().is_empty() || route.label.contains('\r') || route.label.contains('\n') || route.label.len() > 160 { return Err(invalid("selector registry adapter label is invalid")); } if !is_supported_adapter_apply_status(&route.apply_status) { return Err(invalid( "selector registry adapter apply status is not runtime compatible", )); } validate_hex64(&route.artifact_checksum, "adapter artifact checksum")?; validate_hex64(&route.manifest_checksum, "adapter manifest checksum")?; Ok(()) } fn is_supported_adapter_apply_status(status: &str) -> bool { status == ADAPTER_APPLY_STATUS_F32 || status == ADAPTER_APPLY_STATUS_QUANTIZED || status == LOW_RANK_APPLY_STATUS_F32 || status == LOW_RANK_APPLY_STATUS_QUANTIZED } fn validate_adapter_apply_status_for_quantization( route: &RegistryAdapterRoute, quantization: &str, ) -> io::Result<()> { let (expected_f32, expected_quantized) = adapter_apply_status_pair_for_path(&route.adapter_path)?; let expected = match quantization { "f32" => expected_f32, "q8_0" | "q4_0" => expected_quantized, _ => { return Err(invalid( "selector registry adapter routes require f32, q8_0, or q4_0 entries", )); } }; if route.apply_status != expected { return Err(invalid( "selector registry adapter apply status does not match entry quantization", )); } Ok(()) } fn adapter_apply_status_pair_for_path(path: &str) -> io::Result<(&'static str, &'static str)> { if path.ends_with(".alr1") { return Ok((LOW_RANK_APPLY_STATUS_F32, LOW_RANK_APPLY_STATUS_QUANTIZED)); } if path.ends_with(".adp1") || path.ends_with(".asp1") { return Ok((ADAPTER_APPLY_STATUS_F32, ADAPTER_APPLY_STATUS_QUANTIZED)); } Err(invalid("selector registry adapter route is invalid")) } pub(crate) fn validate_registry_adapter_family_route( route: &RegistryAdapterFamilyRoute, ) -> io::Result<()> { if route.candidate_id.trim().is_empty() { return Err(invalid( "selector registry adapter family candidate_id is empty", )); } validate_adapter_family_receipt_path(&route.receipt_path)?; if route.label.trim().is_empty() || route.label.contains('\r') || route.label.contains('\n') || route.label.len() > 160 { return Err(invalid("selector registry adapter family label is invalid")); } if route.status != ADAPTER_FAMILY_STATUS { return Err(invalid( "selector registry adapter family status is invalid", )); } if route.strategy != ADAPTER_FAMILY_STRATEGY { return Err(invalid( "selector registry adapter family strategy is invalid", )); } if route.adapter_count < 2 || route.adapter_count > 16 { return Err(invalid("selector registry adapter family count is invalid")); } if route.auto_apply_status != ADAPTER_AUTO_APPLY_STATUS { return Err(invalid( "selector registry adapter auto apply status is invalid", )); } if route.auto_apply_strategy != ADAPTER_AUTO_APPLY_STRATEGY { return Err(invalid( "selector registry adapter auto apply strategy is invalid", )); } if route.auto_apply_stack_status != ADAPTER_AUTO_APPLY_STACK_STATUS { return Err(invalid( "selector registry adapter auto apply stack status is invalid", )); } if route.auto_apply_stack_strategy != ADAPTER_AUTO_APPLY_STACK_STRATEGY { return Err(invalid( "selector registry adapter auto apply stack strategy is invalid", )); } if route.auto_apply_stack_count == 0 || route.auto_apply_stack_count > route.adapter_count { return Err(invalid( "selector registry adapter auto apply stack count is invalid", )); } if route.auto_apply_byte_budget == 0 || route.auto_apply_byte_budget > ADAPTER_AUTO_APPLY_BYTE_BUDGET { return Err(invalid( "selector registry adapter auto apply byte budget is invalid", )); } validate_hex64(&route.receipt_checksum, "adapter family receipt checksum")?; Ok(()) } pub(crate) fn validate_registry_assembly_route(route: &RegistryAssemblyRoute) -> io::Result<()> { if route.candidate_id.trim().is_empty() { return Err(invalid("selector registry assembly candidate_id is empty")); } validate_assembly_receipt_path(&route.receipt_path)?; if route.label.trim().is_empty() || route.label.contains('\r') || route.label.contains('\n') || route.label.len() > 160 { return Err(invalid("selector registry assembly label is invalid")); } if route.status != ASSEMBLY_RECEIPT_STATUS { return Err(invalid("selector registry assembly status is invalid")); } if route.kind != ASSEMBLY_RECEIPT_KIND { return Err(invalid("selector registry assembly kind is invalid")); } validate_hex64(&route.receipt_checksum, "assembly receipt checksum")?; Ok(()) } /// Validates the selector-side module-plan envelope before it is mirrored into browser intake. pub(crate) fn validate_registry_module_plan_route( route: &RegistryModulePlanRoute, ) -> io::Result<()> { if route.candidate_id.trim().is_empty() { return Err(invalid( "selector registry module plan candidate_id is empty", )); } validate_module_plan_receipt_path(&route.receipt_path)?; if route.label.trim().is_empty() || route.label.contains('\r') || route.label.contains('\n') || route.label.len() > 160 { return Err(invalid("selector registry module plan label is invalid")); } if route.status != MODULE_PLAN_STATUS { return Err(invalid("selector registry module plan status is invalid")); } if route.kind != MODULE_PLAN_KIND { return Err(invalid("selector registry module plan kind is invalid")); } if route.strategy != MODULE_PLAN_STRATEGY { return Err(invalid("selector registry module plan strategy is invalid")); } if route.resource_class != MODULE_PLAN_RESOURCE_CLASS { return Err(invalid( "selector registry module plan resource class is invalid", )); } if route.profile != MODULE_PLAN_PROFILE { return Err(invalid("selector registry module plan profile is invalid")); } if route.execution_profile != MODULE_PLAN_EXECUTION_PROFILE { return Err(invalid( "selector registry module plan execution profile is invalid", )); } if route.fetch_policy != MODULE_PLAN_FETCH_POLICY { return Err(invalid( "selector registry module plan fetch policy is invalid", )); } if route.origin_policy != MODULE_PLAN_ORIGIN_POLICY { return Err(invalid( "selector registry module plan origin policy is invalid", )); } let module_count = u64::try_from(route.module_count) .map_err(|_| invalid("selector registry module plan count is invalid"))?; if route.fetch_count_limit != MODULE_PLAN_FETCH_COUNT_LIMIT || module_count + 1 > route.fetch_count_limit { return Err(invalid( "selector registry module plan fetch count limit is invalid", )); } if route.planned_fetch_count != module_plan_planned_fetch_count(route.module_count, route.adapter_apply_count)? || route.planned_fetch_count > route.fetch_count_limit { return Err(invalid( "selector registry module plan planned fetch count is invalid", )); } if route.route_set_version != MODULE_PLAN_ROUTE_SET_VERSION { return Err(invalid( "selector registry module plan route set version is invalid", )); } if route.route_set_checksum_algorithm != MODULE_PLAN_ROUTE_SET_CHECKSUM_ALGORITHM { return Err(invalid( "selector registry module plan route set checksum algorithm is invalid", )); } validate_hex64(&route.route_set_checksum, "module plan route set checksum")?; module_plan_operator_evidence_prefix(&route.candidate_id, &route.operator_receipt_path)?; validate_hex64( &route.operator_receipt_checksum, "module plan operator receipt checksum", )?; if route.wasm_memory_initial_pages != MODULE_PLAN_WASM_MEMORY_INITIAL_PAGES { return Err(invalid( "selector registry module plan wasm memory initial pages is invalid", )); } if route.wasm_export_set != MODULE_PLAN_WASM_EXPORT_SET { return Err(invalid( "selector registry module plan wasm export set is invalid", )); } if route.wasm_transfer_strategy != MODULE_PLAN_WASM_TRANSFER_STRATEGY { return Err(invalid( "selector registry module plan wasm transfer strategy is invalid", )); } if route.model_release_strategy != MODULE_PLAN_MODEL_RELEASE_STRATEGY { return Err(invalid( "selector registry module plan model release strategy is invalid", )); } if route.runtime_reset_strategy != MODULE_PLAN_RUNTIME_RESET_STRATEGY { return Err(invalid( "selector registry module plan runtime reset strategy is invalid", )); } if route.adapter_validation_strategy != MODULE_PLAN_ADAPTER_VALIDATION_STRATEGY { return Err(invalid( "selector registry module plan adapter validation strategy is invalid", )); } if route.adapter_apply_count == 0 || route.adapter_apply_count > module_count { return Err(invalid( "selector registry module plan adapter apply count is invalid", )); } if route.adapter_validation_count == 0 || route.adapter_validation_count > module_count || route.adapter_validation_count != route.adapter_apply_count { return Err(invalid( "selector registry module plan adapter validation count is invalid", )); } if route.wasm_heap_min_bytes != module_plan_wasm_heap_min_bytes( route.model_byte_budget, route.adapter_stack_byte_budget, route.prompt_byte_limit, )? { return Err(invalid( "selector registry module plan wasm heap min bytes is invalid", )); } if route.context_token_limit == 0 || route.context_token_limit > MODULE_PLAN_CONTEXT_TOKEN_LIMIT_LIMIT { return Err(invalid( "selector registry module plan context token limit is invalid", )); } if route.sampler_candidate_cap != MODULE_PLAN_SAMPLER_CANDIDATE_CAP { return Err(invalid( "selector registry module plan sampler candidate cap is invalid", )); } validate_hex64(&route.tokenizer_checksum, "module plan tokenizer checksum")?; if route.prompt_byte_limit != MODULE_PLAN_PROMPT_BYTE_LIMIT { return Err(invalid( "selector registry module plan prompt byte limit is invalid", )); } if route.model_byte_budget == 0 || route.model_byte_budget > SELECTOR_MODEL_BYTE_BUDGET { return Err(invalid( "selector registry module plan model byte budget is invalid", )); } if route.adapter_byte_budget == 0 || route.adapter_byte_budget > ADAPTER_AUTO_APPLY_BYTE_BUDGET { return Err(invalid( "selector registry module plan adapter byte budget is invalid", )); } if route.adapter_stack_byte_budget == 0 || route.adapter_stack_byte_budget > route.adapter_byte_budget { return Err(invalid( "selector registry module plan adapter stack byte budget is invalid", )); } if route.runtime_scratch_byte_budget != MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET { return Err(invalid( "selector registry module plan runtime scratch byte budget is invalid", )); } if route.output_byte_limit != MODULE_PLAN_OUTPUT_BYTE_LIMIT { return Err(invalid( "selector registry module plan output byte limit is invalid", )); } if route.kv_cache_byte_budget == 0 || route.kv_cache_byte_budget > MODULE_PLAN_KV_CACHE_BYTE_BUDGET_LIMIT { return Err(invalid( "selector registry module plan kv cache byte budget is invalid", )); } if route.kv_cache_page_count != module_plan_page_count_for_bytes(route.kv_cache_byte_budget)? { return Err(invalid( "selector registry module plan kv cache page count is invalid", )); } let minimum_total_budget = route .model_byte_budget .checked_add(route.prompt_byte_limit) .and_then(|value| value.checked_add(route.runtime_scratch_byte_budget)) .and_then(|value| value.checked_add(route.output_byte_limit)) .and_then(|value| value.checked_add(route.adapter_stack_byte_budget)) .and_then(|value| value.checked_add(route.kv_cache_byte_budget)) .ok_or_else(|| invalid("selector registry module plan total byte budget is invalid"))?; if route.total_byte_budget_limit != MODULE_PLAN_TOTAL_BYTE_BUDGET_LIMIT { return Err(invalid( "selector registry module plan total byte budget limit is invalid", )); } if route.total_byte_budget == 0 || route.total_byte_budget < minimum_total_budget || route.total_byte_budget > route.total_byte_budget_limit { return Err(invalid( "selector registry module plan total byte budget is invalid", )); } if !(5..=32).contains(&route.module_count) { return Err(invalid("selector registry module plan count is invalid")); } validate_hex64(&route.receipt_checksum, "module plan checksum")?; Ok(()) } fn parse_module_plan_byte_budget( fields: &HashMap, key: &str, label: &str, ) -> io::Result { // Parses exact decimal byte budgets so selector receipts cannot hide rounded values. let value = require_key(fields, key)?; let bytes = value.parse::().map_err(|_| { invalid(&format!( "selector registry module plan {label} byte budget is invalid" )) })?; if bytes == 0 || bytes.to_string() != value { return Err(invalid(&format!( "selector registry module plan {label} byte budget is invalid" ))); } Ok(bytes) } fn module_plan_wasm_heap_min_bytes( model_byte_budget: u64, adapter_stack_byte_budget: u64, prompt_byte_limit: u64, ) -> io::Result { // Keeps the browser allocation probe large enough for each generated transfer path. Ok(MODULE_PLAN_WASM_HEAP_MIN_BYTES .max(model_byte_budget) .max(adapter_stack_byte_budget) .max(prompt_byte_limit)) } fn module_plan_planned_fetch_count( module_count: usize, adapter_apply_count: u64, ) -> io::Result { // Counts model-owned generated assembly fetches across the receipt, modules, // evidence files, adapter manifests, and self-adapter manifest. let module_count = u64::try_from(module_count) .map_err(|_| invalid("selector registry module plan planned fetch count is invalid"))?; module_count .checked_add(1) .and_then(|value| value.checked_add(MODULE_PLAN_ASSEMBLY_EVIDENCE_FILE_COUNT)) .and_then(|value| value.checked_add(adapter_apply_count)) .and_then(|value| value.checked_add(1)) .ok_or_else(|| invalid("selector registry module plan planned fetch count is invalid")) } fn module_plan_route_set_checksum( entry: &RegistryEntry, route: &RegistryModulePlanRoute, family: &RegistryAdapterFamilyRoute, assembly: &RegistryAssemblyRoute, ) -> io::Result { // Recomputes the generated browser route envelope before selector metadata is accepted. module_plan_route_set_checksum_from_parts( &entry.candidate_id, &route.receipt_path, &entry.model_path, &entry.manifest_path, &assembly.receipt_path, &family.receipt_path, &entry.adapters, family.auto_apply_stack_count, &route.operator_receipt_path, ) } fn module_plan_route_set_checksum_from_parts( candidate_id: &str, module_plan_path: &str, model_path: &str, manifest_path: &str, assembly_path: &str, adapter_family_path: &str, adapters: &[RegistryAdapterRoute], stack_count: usize, operator_receipt_path: &str, ) -> io::Result { // Builds the same route classes the browser fetches during generated self-assembly. let evidence_files = module_plan_assembly_evidence_files( &module_plan_operator_evidence_prefix(candidate_id, operator_receipt_path)?, ); let evidence_count = u64::try_from(evidence_files.len()) .map_err(|_| invalid("selector registry module plan route set is invalid"))?; if evidence_count != MODULE_PLAN_ASSEMBLY_EVIDENCE_FILE_COUNT { return Err(invalid( "selector registry module plan route set evidence count is invalid", )); } let stack_indexes = module_plan_route_set_stack_indexes(adapters.len(), stack_count)?; let mut routes = Vec::new(); module_plan_push_route(&mut routes, "module-plan-receipt", module_plan_path); module_plan_push_route(&mut routes, "model", model_path); module_plan_push_route(&mut routes, "model-manifest", manifest_path); module_plan_push_route(&mut routes, "assembly-receipt", assembly_path); for file_name in evidence_files { module_plan_push_route( &mut routes, "assembly-evidence", &module_plan_evidence_route(candidate_id, &file_name), ); } module_plan_push_route(&mut routes, "adapter-family-receipt", adapter_family_path); for adapter in adapters { module_plan_push_route(&mut routes, "adapter-manifest", &adapter.manifest_path); } for adapter_index in stack_indexes { module_plan_push_route( &mut routes, "adapter-stack-artifact", &adapters[adapter_index].adapter_path, ); } Ok(module_plan_checksum_for_routes(&routes)) } fn module_plan_route_set_stack_indexes( adapter_count: usize, stack_count: usize, ) -> io::Result> { // Mirrors the generated adapter-family policy: self first, then the remaining stack members. if adapter_count == 0 || stack_count == 0 || stack_count > adapter_count { return Err(invalid( "selector registry module plan route set adapter stack is invalid", )); } let expected_stack_count = if adapter_count >= 3 { adapter_count - 1 } else { adapter_count }; if stack_count != expected_stack_count { return Err(invalid( "selector registry module plan route set adapter stack is invalid", )); } Ok((adapter_count - stack_count..adapter_count).collect()) } fn module_plan_push_route(routes: &mut Vec<(String, String)>, kind: &str, path: &str) { // Stores route metadata without borrowing temporary evidence path strings. routes.push((kind.to_string(), path.to_string())); } fn module_plan_evidence_route(candidate_id: &str, file_name: &str) -> String { // Canonicalizes generated evidence routes from the admitted selector candidate id. format!("../evidence/{candidate_id}/{file_name}") } fn module_plan_operator_evidence_prefix( candidate_id: &str, operator_receipt_path: &str, ) -> io::Result { // Extracts the operator-specific evidence lane from the bound operator receipt path. let route_prefix = format!("../evidence/{candidate_id}/"); let Some(file_name) = operator_receipt_path.strip_prefix(&route_prefix) else { return Err(invalid( "selector registry module plan operator receipt path is invalid", )); }; let Some(operator_prefix) = file_name.strip_suffix(".operator") else { return Err(invalid( "selector registry module plan operator receipt path is invalid", )); }; if operator_prefix.is_empty() || operator_prefix.len() > 64 || !operator_prefix .bytes() .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') || operator_prefix.starts_with('-') || operator_prefix.ends_with('-') || !matches!(operator_prefix, "sign-merge" | "soup") { return Err(invalid( "selector registry module plan operator receipt path is invalid", )); } Ok(operator_prefix.to_string()) } fn module_plan_assembly_evidence_files(operator_prefix: &str) -> Vec { // Builds the fixed evidence route family for whichever parent-pool operator made the candidate. vec![ "population.ledger".to_string(), "population.review".to_string(), "parent-pool.recipe".to_string(), format!("{operator_prefix}.operator"), format!("{operator_prefix}.candidate"), format!("{operator_prefix}.promotion"), format!("{operator_prefix}.runtime"), format!("{operator_prefix}.eval"), format!("{operator_prefix}.multi.admission"), ] } fn module_plan_checksum_for_routes(routes: &[(String, String)]) -> String { // Hashes the ordered route-kind and route-path list with the project text checksum. let mut text = String::new(); push_line( &mut text, "route_set_version", MODULE_PLAN_ROUTE_SET_VERSION, ); push_line( &mut text, "route_set_checksum_algorithm", MODULE_PLAN_ROUTE_SET_CHECKSUM_ALGORITHM, ); push_line(&mut text, "route_count", &routes.len().to_string()); for (index, (kind, path)) in routes.iter().enumerate() { push_line(&mut text, &format!("route.{index}.kind"), kind); push_line(&mut text, &format!("route.{index}.path"), path); } hex64(provenance::text_checksum(text.as_bytes())) } fn parse_module_plan_page_count(fields: &HashMap, key: &str) -> io::Result { // Parses the KV-cache page count as an exact selector-owned decimal field. let value = require_key(fields, key)?; let pages = value .parse::() .map_err(|_| invalid("selector registry module plan kv cache page count is invalid"))?; if pages == 0 || pages.to_string() != value { return Err(invalid( "selector registry module plan kv cache page count is invalid", )); } Ok(pages) } fn parse_module_plan_count( fields: &HashMap, key: &str, label: &str, ) -> io::Result { // Parses exact decimal count fields so resource limits stay selector-owned. let value = require_key(fields, key)?; let count = value .parse::() .map_err(|_| invalid(&format!("selector registry module plan {label} is invalid")))?; if count == 0 || count.to_string() != value { return Err(invalid(&format!( "selector registry module plan {label} is invalid" ))); } Ok(count) } fn model_shape_context_token_limit(model_shape: &str) -> io::Result { // Reads either compact fixture `ctx=` or validated manifest `context=` shape fields. for part in model_shape.split(',') { let part = part.trim(); let Some(value) = part .strip_prefix("context=") .or_else(|| part.strip_prefix("ctx=")) else { continue; }; let tokens = value .parse::() .map_err(|_| invalid("selector registry model shape context token limit is invalid"))?; if tokens == 0 || tokens.to_string() != value || tokens > MODULE_PLAN_CONTEXT_TOKEN_LIMIT_LIMIT { return Err(invalid( "selector registry model shape context token limit is invalid", )); } return Ok(tokens); } Err(invalid( "selector registry model shape context token limit is missing", )) } fn module_plan_page_count_for_bytes(bytes: u64) -> io::Result { // Recomputes the expected WebAssembly page count from the selector byte budget. let page_bytes = 64 * 1024u64; bytes .checked_add(page_bytes - 1) .map(|value| value / page_bytes) .ok_or_else(|| invalid("selector registry module plan kv cache page count is invalid")) } fn selector_id(admission_texts: &[String]) -> io::Result { let Some(first) = admission_texts.first() else { return Err(invalid( "selector registry requires at least one admission record", )); }; let fields = validate_admission_summary_text(first)?; Ok(require_key(&fields, "selector_id")?.to_string()) } fn validate_admission_summary_text(admission_text: &str) -> io::Result> { let fields = parse_manifest(admission_text, "selector registry admission")?; if fields.contains_key("tinyrustlm_selector_admission_version") { return admission::validate_record_summary_text(admission_text); } if fields.contains_key("tinyrustlm_multi_parent_selector_admission_version") { return multi_admission::validate_record_summary_text(admission_text); } Err(invalid( "selector registry admission record must use a supported admission version", )) } fn browser_model_path(artifact_path: &str) -> io::Result { let normalized = artifact_path.replace('\\', "/"); if let Some(rest) = normalized.strip_prefix("../models/") { validate_model_route_rest(rest)?; return Ok(format!("../models/{rest}")); } if let Some(index) = normalized.find("tinyrustlm/models/") { let rest = &normalized[index + "tinyrustlm/models/".len()..]; validate_model_route_rest(rest)?; return Ok(format!("../models/{rest}")); } Err(invalid( "selector registry entries must point at served tinyrustlm/models .slm artifacts", )) } fn validate_model_route_rest(rest: &str) -> io::Result<()> { if rest.is_empty() || !rest.ends_with(".slm") || rest.contains(':') || rest.contains('\\') || rest.contains("//") { return Err(invalid("selector registry model route is invalid")); } for part in rest.split('/') { if part.is_empty() || part == "." || part == ".." { return Err(invalid("selector registry model route is invalid")); } } Ok(()) } fn selector_model_bytes(value: &str) -> io::Result { let bytes = value .parse::() .map_err(|_| invalid("selector registry model bytes are invalid"))?; if bytes == 0 || bytes > SELECTOR_MODEL_BYTE_BUDGET || bytes.to_string() != value { return Err(invalid( "selector registry model bytes exceed the browser selector budget", )); } Ok(bytes) } fn validate_adapter_route_path(path: &str) -> io::Result<()> { let normalized = path.replace('\\', "/"); let Some(rest) = normalized.strip_prefix("../models/") else { return Err(invalid( "selector registry adapter route must point at served ../models adapter artifacts", )); }; if rest.is_empty() || !is_supported_adapter_artifact_name(rest) || rest.contains(':') || rest.contains('\\') || rest.contains("//") { return Err(invalid("selector registry adapter route is invalid")); } for part in rest.split('/') { if part.is_empty() || part == "." || part == ".." { return Err(invalid("selector registry adapter route is invalid")); } } Ok(()) } fn is_supported_adapter_artifact_name(path: &str) -> bool { path.ends_with(".adp1") || path.ends_with(".asp1") || path.ends_with(".alr1") } fn validate_adapter_family_receipt_path(path: &str) -> io::Result<()> { let normalized = path.replace('\\', "/"); let Some(rest) = normalized.strip_prefix("../models/") else { return Err(invalid( "selector registry adapter family receipt route must point at served ../models receipt artifacts", )); }; if rest.is_empty() || !rest.ends_with(".adapter-family.receipt") || rest.contains(':') || rest.contains('\\') || rest.contains("//") { return Err(invalid( "selector registry adapter family receipt route is invalid", )); } for part in rest.split('/') { if part.is_empty() || part == "." || part == ".." { return Err(invalid( "selector registry adapter family receipt route is invalid", )); } } Ok(()) } fn validate_assembly_receipt_path(path: &str) -> io::Result<()> { let normalized = path.replace('\\', "/"); let Some(rest) = normalized.strip_prefix("../models/") else { return Err(invalid( "selector registry assembly receipt route must point at served ../models receipt artifacts", )); }; if rest.is_empty() || !rest.ends_with(".assembly.receipt") || rest.contains(':') || rest.contains('\\') || rest.contains("//") { return Err(invalid( "selector registry assembly receipt route is invalid", )); } for part in rest.split('/') { if part.is_empty() || part == "." || part == ".." { return Err(invalid( "selector registry assembly receipt route is invalid", )); } } Ok(()) } fn validate_module_plan_receipt_path(path: &str) -> io::Result<()> { let normalized = path.replace('\\', "/"); let Some(rest) = normalized.strip_prefix("../models/") else { return Err(invalid( "selector registry module plan route must point at served ../models receipt artifacts", )); }; if rest.is_empty() || !rest.ends_with(".module-plan.receipt") || rest.contains(':') || rest.contains('\\') || rest.contains("//") { return Err(invalid("selector registry module plan route is invalid")); } for part in rest.split('/') { if part.is_empty() || part == "." || part == ".." { return Err(invalid("selector registry module plan route is invalid")); } } Ok(()) } fn validate_hex64(value: &str, label: &str) -> io::Result<()> { let Some(rest) = value.strip_prefix("0x") else { return Err(invalid(&format!("selector registry {label} is invalid"))); }; if rest.len() != 16 || !rest.bytes().all(|byte| byte.is_ascii_hexdigit()) { return Err(invalid(&format!("selector registry {label} is invalid"))); } Ok(()) } fn validate_registry_slug(value: &str, label: &str) -> io::Result<()> { // Keeps copied schedule commands and family names browser-safe without path semantics. if value.is_empty() || value.len() > 96 || !value .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) { return Err(invalid(&format!("selector registry {label} is invalid"))); } Ok(()) } fn default_max_tokens(model_shape: &str) -> usize { if model_shape.contains("hidden=16") { 16 } else { 8 } } fn display_name(candidate_id: &str, quantization: &str) -> String { // Gives converted source artifacts a stable browser label while leaving operator ids literal. if candidate_id.starts_with("converted-trained-") { return format!("Converted trained-source {quantization}"); } format!("{candidate_id} {quantization}") } // Builds a stable browser-local genome id from the candidate's runtime-visible shape. fn registry_entry_genome_id(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line(&mut text, "candidate_id", &entry.candidate_id); push_line(&mut text, "model_shape", &entry.model_shape); push_line(&mut text, "quantization", &entry.quantization); push_line(&mut text, "output_contract", &entry.output_contract); push_line(&mut text, "tokenizer_checksum", &entry.tokenizer_checksum); push_line(&mut text, "slm_checksum", &entry.slm_checksum); hex64(provenance::text_checksum(text.as_bytes())) } // Summarizes the admission/eval chain used as the selector entry's lineage route. fn registry_entry_genome_lineage_checksum(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line(&mut text, "admission_checksum", &entry.admission_checksum); push_line( &mut text, "promotion_manifest_checksum", &entry.promotion_manifest_checksum, ); push_line( &mut text, "runtime_smoke_manifest_checksum", &entry.runtime_smoke_manifest_checksum, ); push_line( &mut text, "eval_manifest_checksum", &entry.eval_manifest_checksum, ); hex64(provenance::text_checksum(text.as_bytes())) } // Groups candidates by the model family traits that matter to browser-local selection. fn registry_entry_species_id(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line(&mut text, "model_shape", &entry.model_shape); push_line(&mut text, "quantization", &entry.quantization); push_line(&mut text, "output_contract", &entry.output_contract); push_line(&mut text, "tokenizer_checksum", &entry.tokenizer_checksum); push_line(&mut text, "max_tokens", &entry.max_tokens); hex64(provenance::text_checksum(text.as_bytes())) } // Binds a candidate species to the browser resource envelope it is expected to fit. fn registry_entry_species_fit_checksum(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line( &mut text, "selector_model_byte_budget", &SELECTOR_MODEL_BYTE_BUDGET.to_string(), ); push_line( &mut text, "selector_registry_text_byte_budget", &SELECTOR_REGISTRY_TEXT_BYTE_BUDGET.to_string(), ); push_line( &mut text, "manifest_text_byte_budget", &MANIFEST_TEXT_BYTE_BUDGET.to_string(), ); push_line( &mut text, "receipt_text_byte_budget", &RECEIPT_TEXT_BYTE_BUDGET.to_string(), ); push_line( &mut text, "evidence_text_byte_budget", &EVIDENCE_TEXT_BYTE_BUDGET.to_string(), ); push_line(&mut text, "model_bytes", &entry.model_bytes); push_line(&mut text, "max_tokens", &entry.max_tokens); push_line(&mut text, "quantization", &entry.quantization); match &entry.module_plan { Some(module_plan) => { push_line(&mut text, "module_plan_status", "present"); push_line( &mut text, "module_plan_resource_class", &module_plan.resource_class, ); push_line(&mut text, "module_plan_profile", &module_plan.profile); push_line( &mut text, "module_plan_execution_profile", &module_plan.execution_profile, ); push_line( &mut text, "module_plan_fetch_policy", &module_plan.fetch_policy, ); push_line( &mut text, "module_plan_origin_policy", &module_plan.origin_policy, ); push_line( &mut text, "module_plan_fetch_count_limit", &module_plan.fetch_count_limit.to_string(), ); push_line( &mut text, "module_plan_planned_fetch_count", &module_plan.planned_fetch_count.to_string(), ); push_line( &mut text, "module_plan_route_set_version", &module_plan.route_set_version, ); push_line( &mut text, "module_plan_route_set_checksum_algorithm", &module_plan.route_set_checksum_algorithm, ); push_line( &mut text, "module_plan_route_set_checksum", &module_plan.route_set_checksum, ); push_line( &mut text, "module_plan_wasm_memory_initial_pages", &module_plan.wasm_memory_initial_pages.to_string(), ); push_line( &mut text, "module_plan_wasm_export_set", &module_plan.wasm_export_set, ); push_line( &mut text, "module_plan_wasm_transfer_strategy", &module_plan.wasm_transfer_strategy, ); push_line( &mut text, "module_plan_model_release_strategy", &module_plan.model_release_strategy, ); push_line( &mut text, "module_plan_runtime_reset_strategy", &module_plan.runtime_reset_strategy, ); push_line( &mut text, "module_plan_adapter_validation_strategy", &module_plan.adapter_validation_strategy, ); push_line( &mut text, "module_plan_adapter_validation_count", &module_plan.adapter_validation_count.to_string(), ); push_line( &mut text, "module_plan_adapter_apply_count", &module_plan.adapter_apply_count.to_string(), ); push_line( &mut text, "module_plan_wasm_heap_min_bytes", &module_plan.wasm_heap_min_bytes.to_string(), ); push_line( &mut text, "module_plan_context_token_limit", &module_plan.context_token_limit.to_string(), ); push_line( &mut text, "module_plan_sampler_candidate_cap", &module_plan.sampler_candidate_cap.to_string(), ); push_line( &mut text, "module_plan_tokenizer_checksum", &module_plan.tokenizer_checksum, ); push_line( &mut text, "module_plan_prompt_byte_limit", &module_plan.prompt_byte_limit.to_string(), ); push_line( &mut text, "module_plan_model_byte_budget", &module_plan.model_byte_budget.to_string(), ); push_line( &mut text, "module_plan_adapter_byte_budget", &module_plan.adapter_byte_budget.to_string(), ); push_line( &mut text, "module_plan_adapter_stack_byte_budget", &module_plan.adapter_stack_byte_budget.to_string(), ); push_line( &mut text, "module_plan_runtime_scratch_byte_budget", &module_plan.runtime_scratch_byte_budget.to_string(), ); push_line( &mut text, "module_plan_output_byte_limit", &module_plan.output_byte_limit.to_string(), ); push_line( &mut text, "module_plan_kv_cache_byte_budget", &module_plan.kv_cache_byte_budget.to_string(), ); push_line( &mut text, "module_plan_kv_cache_page_count", &module_plan.kv_cache_page_count.to_string(), ); push_line( &mut text, "module_plan_total_byte_budget", &module_plan.total_byte_budget.to_string(), ); push_line( &mut text, "module_plan_total_byte_budget_limit", &module_plan.total_byte_budget_limit.to_string(), ); push_line( &mut text, "module_plan_module_count", &module_plan.module_count.to_string(), ); } None => push_line(&mut text, "module_plan_status", "absent"), } hex64(provenance::text_checksum(text.as_bytes())) } // Sketches behavior-relevant traits so selector populations can keep useful variety. fn registry_entry_novelty_id(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line(&mut text, "species_id", ®istry_entry_species_id(entry)); push_line(&mut text, "quality_scope", &entry.quality_scope); push_line(&mut text, "eval_dataset", &entry.eval_dataset); push_line(&mut text, "output_contract", &entry.output_contract); push_line(&mut text, "quantization", &entry.quantization); push_line(&mut text, "max_tokens", &entry.max_tokens); hex64(provenance::text_checksum(text.as_bytes())) } // Binds the novelty sketch to the concrete eval and assembly evidence behind it. fn registry_entry_novelty_checksum(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line(&mut text, "genome_id", ®istry_entry_genome_id(entry)); push_line(&mut text, "species_id", ®istry_entry_species_id(entry)); push_line( &mut text, "fitness_vector_checksum", ®istry_entry_fitness_vector_checksum(entry), ); push_line( &mut text, "eval_case_evidence_checksum", &entry.eval_case_evidence_checksum, ); match &entry.assembly { Some(assembly) => { push_line(&mut text, "assembly_status", "present"); push_line( &mut text, "assembly_receipt_checksum", &assembly.receipt_checksum, ); } None => push_line(&mut text, "assembly_status", "absent"), } match &entry.adapter_family { Some(adapter_family) => { push_line(&mut text, "adapter_family_status", "present"); push_line( &mut text, "adapter_family_receipt_checksum", &adapter_family.receipt_checksum, ); push_line( &mut text, "adapter_family_stack_count", &adapter_family.auto_apply_stack_count.to_string(), ); } None => push_line(&mut text, "adapter_family_status", "absent"), } match &entry.module_plan { Some(module_plan) => { push_line(&mut text, "module_plan_status", "present"); push_line( &mut text, "module_plan_checksum", &module_plan.receipt_checksum, ); push_line( &mut text, "module_plan_resource_class", &module_plan.resource_class, ); push_line( &mut text, "module_plan_wasm_export_set", &module_plan.wasm_export_set, ); push_line( &mut text, "module_plan_wasm_transfer_strategy", &module_plan.wasm_transfer_strategy, ); push_line( &mut text, "module_plan_model_release_strategy", &module_plan.model_release_strategy, ); push_line( &mut text, "module_plan_runtime_reset_strategy", &module_plan.runtime_reset_strategy, ); push_line( &mut text, "module_plan_adapter_validation_strategy", &module_plan.adapter_validation_strategy, ); push_line( &mut text, "module_plan_adapter_validation_count", &module_plan.adapter_validation_count.to_string(), ); push_line( &mut text, "module_plan_adapter_apply_count", &module_plan.adapter_apply_count.to_string(), ); push_line( &mut text, "module_plan_module_count", &module_plan.module_count.to_string(), ); } None => push_line(&mut text, "module_plan_status", "absent"), } hex64(provenance::text_checksum(text.as_bytes())) } // Names the selector population lane from species, novelty, and scoped fitness traits. fn registry_entry_population_id(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line(&mut text, "species_id", ®istry_entry_species_id(entry)); push_line(&mut text, "novelty_id", ®istry_entry_novelty_id(entry)); push_line( &mut text, "fitness_vector_checksum", ®istry_entry_fitness_vector_checksum(entry), ); push_line(&mut text, "quality_scope", &entry.quality_scope); push_line(&mut text, "eval_dataset", &entry.eval_dataset); push_line(&mut text, "quantization", &entry.quantization); hex64(provenance::text_checksum(text.as_bytes())) } // Binds population provenance to the reviewed assembly and browser route context. fn registry_entry_population_checksum(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line( &mut text, "population_id", ®istry_entry_population_id(entry), ); push_line(&mut text, "genome_id", ®istry_entry_genome_id(entry)); push_line( &mut text, "genome_lineage_checksum", ®istry_entry_genome_lineage_checksum(entry), ); push_line( &mut text, "species_fit_checksum", ®istry_entry_species_fit_checksum(entry), ); push_line( &mut text, "novelty_checksum", ®istry_entry_novelty_checksum(entry), ); push_line( &mut text, "fitness_vector_checksum", ®istry_entry_fitness_vector_checksum(entry), ); match &entry.assembly { Some(assembly) => { push_line(&mut text, "population_review_route", "assembly-bound"); push_line( &mut text, "assembly_receipt_checksum", &assembly.receipt_checksum, ); } None => push_line(&mut text, "population_review_route", "admission-only"), } match &entry.module_plan { Some(module_plan) => { push_line(&mut text, "module_plan_status", "present"); push_line( &mut text, "module_plan_checksum", &module_plan.receipt_checksum, ); push_line( &mut text, "module_plan_module_count", &module_plan.module_count.to_string(), ); } None => push_line(&mut text, "module_plan_status", "absent"), } hex64(provenance::text_checksum(text.as_bytes())) } // Names the mate-selection lane from the parent-pool route when the admission has one. fn registry_entry_mate_selection_id(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line(&mut text, "candidate_id", &entry.candidate_id); push_line(&mut text, "admission_kind", &entry.admission_kind); push_line( &mut text, "population_id", ®istry_entry_population_id(entry), ); push_line( &mut text, "parent_pool_recipe_checksum", option_or_marker(&entry.parent_pool_recipe_checksum, "admission-only"), ); push_line(&mut text, "parent_count", &entry.parent_count.to_string()); hex64(provenance::text_checksum(text.as_bytes())) } // Marks whether a selector entry is backed by reviewed parent-pool mate selection. fn registry_entry_mate_selection_status(entry: &RegistryEntry) -> &'static str { if entry.parent_pool_recipe_checksum.is_some() { MATE_SELECTION_PARENT_POOL_STATUS } else { MATE_SELECTION_ADMISSION_STATUS } } // Binds the parent-pool recipe and sign-merge route into browser-visible provenance. fn registry_entry_mate_selection_checksum(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line( &mut text, "mate_selection_id", ®istry_entry_mate_selection_id(entry), ); push_line( &mut text, "mate_selection_status", registry_entry_mate_selection_status(entry), ); push_line( &mut text, "population_checksum", ®istry_entry_population_checksum(entry), ); push_line(&mut text, "parent_count", &entry.parent_count.to_string()); push_line( &mut text, "parent_pool_recipe_checksum", option_or_marker(&entry.parent_pool_recipe_checksum, "admission-only"), ); push_line( &mut text, "operator_receipt_checksum", option_or_marker(&entry.operator_receipt_checksum, "admission-only"), ); push_operator_receipt_checksum_inputs(&mut text, entry); push_line( &mut text, "population_review_checksum", option_or_marker(&entry.population_review_checksum, "admission-only"), ); push_line( &mut text, "promotion_ledger_checksum", option_or_marker(&entry.promotion_ledger_checksum, "admission-only"), ); push_line( &mut text, "admission_set_checksum", option_or_marker(&entry.admission_set_checksum, "admission-only"), ); push_line(&mut text, "admission_checksum", &entry.admission_checksum); hex64(provenance::text_checksum(text.as_bytes())) } // Emits selector entry fields for the optional two-parent operator receipt route. fn push_registry_operator_receipt_lines(text: &mut String, prefix: &str, entry: &RegistryEntry) { if let Some(receipt) = &entry.operator_receipt { push_line( text, &format!("{prefix}.operator_receipt_status"), &receipt.status, ); push_line( text, &format!("{prefix}.operator_receipt_path"), &receipt.path, ); push_line( text, &format!("{prefix}.operator_receipt_checksum"), &receipt.checksum, ); push_line( text, &format!("{prefix}.operator_receipt_operator_id"), &receipt.operator_id, ); push_line( text, &format!("{prefix}.operator_receipt_operator_kind"), &receipt.operator_kind, ); push_line( text, &format!("{prefix}.operator_receipt_candidate_slm_checksum"), &receipt.candidate_slm_checksum, ); push_line( text, &format!("{prefix}.operator_receipt_candidate_artifact_bytes"), &receipt.candidate_artifact_bytes, ); } } // Emits parent-pool evolution schedule fields for browser provenance and validation. fn push_registry_evolution_schedule_lines(text: &mut String, prefix: &str, entry: &RegistryEntry) { if let Some(schedule) = &entry.evolution_schedule { push_line( text, &format!("{prefix}.evolution_recipe_version"), &schedule.recipe_version, ); push_line( text, &format!("{prefix}.evolution_recipe_strategy"), &schedule.recipe_strategy, ); push_line( text, &format!("{prefix}.evolution_recipe_status"), &schedule.recipe_status, ); push_line( text, &format!("{prefix}.evolution_selection_source"), &schedule.selection_source, ); push_line( text, &format!("{prefix}.evolution_relatedness_contract_checksum"), &schedule.relatedness_contract_checksum, ); push_line( text, &format!("{prefix}.evolution_schedule_checksum_algorithm"), &schedule.schedule_checksum_algorithm, ); push_line( text, &format!("{prefix}.evolution_schedule_checksum"), &schedule.schedule_checksum, ); push_line( text, &format!("{prefix}.scheduled_operator_family_index"), &schedule.family_index, ); push_line( text, &format!("{prefix}.scheduled_operator_family_kind"), &schedule.family_kind, ); push_line( text, &format!("{prefix}.scheduled_operator_family_command"), &schedule.family_command, ); push_line( text, &format!("{prefix}.scheduled_operator_family_selection_rule"), &schedule.family_selection_rule, ); push_line( text, &format!("{prefix}.scheduled_operator_family_output_gate"), &schedule.family_output_gate, ); } } // Includes copied operator and schedule fields in the mate-selection proof digest. fn push_operator_receipt_checksum_inputs(text: &mut String, entry: &RegistryEntry) { if let Some(receipt) = &entry.operator_receipt { push_line(text, "operator_receipt_status", &receipt.status); push_line(text, "operator_receipt_path", &receipt.path); push_line(text, "operator_receipt_operator_id", &receipt.operator_id); push_line( text, "operator_receipt_operator_kind", &receipt.operator_kind, ); push_line( text, "operator_receipt_candidate_slm_checksum", &receipt.candidate_slm_checksum, ); push_line( text, "operator_receipt_candidate_artifact_bytes", &receipt.candidate_artifact_bytes, ); } else { push_line(text, "operator_receipt_status", "admission-only"); push_line(text, "operator_receipt_path", "admission-only"); push_line(text, "operator_receipt_operator_id", "admission-only"); push_line(text, "operator_receipt_operator_kind", "admission-only"); push_line( text, "operator_receipt_candidate_slm_checksum", "admission-only", ); push_line( text, "operator_receipt_candidate_artifact_bytes", "admission-only", ); } push_evolution_schedule_checksum_inputs(text, entry); } // Includes copied schedule metadata in the selector proof digest when a parent pool is scheduled. fn push_evolution_schedule_checksum_inputs(text: &mut String, entry: &RegistryEntry) { if let Some(schedule) = &entry.evolution_schedule { push_line(text, "evolution_recipe_version", &schedule.recipe_version); push_line(text, "evolution_recipe_strategy", &schedule.recipe_strategy); push_line(text, "evolution_recipe_status", &schedule.recipe_status); push_line( text, "evolution_selection_source", &schedule.selection_source, ); push_line( text, "evolution_relatedness_contract_checksum", &schedule.relatedness_contract_checksum, ); push_line( text, "evolution_schedule_checksum_algorithm", &schedule.schedule_checksum_algorithm, ); push_line( text, "evolution_schedule_checksum", &schedule.schedule_checksum, ); push_line( text, "scheduled_operator_family_index", &schedule.family_index, ); push_line( text, "scheduled_operator_family_kind", &schedule.family_kind, ); push_line( text, "scheduled_operator_family_command", &schedule.family_command, ); push_line( text, "scheduled_operator_family_selection_rule", &schedule.family_selection_rule, ); push_line( text, "scheduled_operator_family_output_gate", &schedule.family_output_gate, ); } else { for key in EVOLUTION_SCHEDULE_KEYS { push_line(text, key, "admission-only"); } } } // Names the observed behavior lane from runtime, eval, and selected-parent context. fn registry_entry_phenotype_evidence_id(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line(&mut text, "candidate_id", &entry.candidate_id); push_line( &mut text, "mate_selection_id", ®istry_entry_mate_selection_id(entry), ); push_line(&mut text, "quality_scope", &entry.quality_scope); push_line(&mut text, "eval_dataset", &entry.eval_dataset); push_line(&mut text, "cases_passed", &entry.cases_passed); push_line( &mut text, "eval_case_evidence_checksum", &entry.eval_case_evidence_checksum, ); hex64(provenance::text_checksum(text.as_bytes())) } // Binds phenotype evidence to the manifests and assembly receipt that produced it. fn registry_entry_phenotype_evidence_checksum(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line( &mut text, "phenotype_evidence_id", ®istry_entry_phenotype_evidence_id(entry), ); push_line( &mut text, "phenotype_evidence_status", PHENOTYPE_EVIDENCE_STATUS, ); push_line( &mut text, "provenance_manifest_checksum", &entry.provenance_manifest_checksum, ); push_line( &mut text, "runtime_smoke_manifest_checksum", &entry.runtime_smoke_manifest_checksum, ); push_line( &mut text, "eval_manifest_checksum", &entry.eval_manifest_checksum, ); push_line( &mut text, "eval_case_evidence_checksum", &entry.eval_case_evidence_checksum, ); push_line(&mut text, "quality_boundary", &entry.quality_boundary); push_line( &mut text, "fitness_vector_checksum", ®istry_entry_fitness_vector_checksum(entry), ); push_line( &mut text, "mate_selection_checksum", ®istry_entry_mate_selection_checksum(entry), ); match &entry.assembly { Some(assembly) => { push_line(&mut text, "assembly_status", "present"); push_line( &mut text, "assembly_receipt_checksum", &assembly.receipt_checksum, ); } None => push_line(&mut text, "assembly_status", "admission-only"), } hex64(provenance::text_checksum(text.as_bytes())) } // Names the served artifact identity that later selector work can inherit or compare. fn registry_entry_heritable_artifact_id(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line(&mut text, "candidate_id", &entry.candidate_id); push_line(&mut text, "artifact_path", &entry.artifact_path); push_line(&mut text, "model_path", &entry.model_path); push_line(&mut text, "manifest_path", &entry.manifest_path); push_line(&mut text, "model_bytes", &entry.model_bytes); push_line(&mut text, "slm_checksum", &entry.slm_checksum); push_line(&mut text, "model_shape", &entry.model_shape); push_line(&mut text, "quantization", &entry.quantization); push_line(&mut text, "output_contract", &entry.output_contract); push_line(&mut text, "genome_id", ®istry_entry_genome_id(entry)); hex64(provenance::text_checksum(text.as_bytes())) } // Binds the heritable artifact id to lineage, eval evidence, and browser route receipts. fn registry_entry_heritable_artifact_checksum(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line( &mut text, "heritable_artifact_id", ®istry_entry_heritable_artifact_id(entry), ); push_line( &mut text, "heritable_artifact_status", HERITABLE_ARTIFACT_STATUS, ); push_line(&mut text, "genome_id", ®istry_entry_genome_id(entry)); push_line( &mut text, "genome_lineage_checksum", ®istry_entry_genome_lineage_checksum(entry), ); push_line( &mut text, "phenotype_evidence_checksum", ®istry_entry_phenotype_evidence_checksum(entry), ); push_line( &mut text, "fitness_vector_checksum", ®istry_entry_fitness_vector_checksum(entry), ); push_line( &mut text, "provenance_manifest_checksum", &entry.provenance_manifest_checksum, ); push_line( &mut text, "runtime_smoke_manifest_checksum", &entry.runtime_smoke_manifest_checksum, ); match &entry.adapter_family { Some(adapter_family) => { push_line(&mut text, "adapter_family_status", "present"); push_line( &mut text, "adapter_family_receipt_checksum", &adapter_family.receipt_checksum, ); push_line( &mut text, "adapter_family_stack_count", &adapter_family.auto_apply_stack_count.to_string(), ); } None => push_line(&mut text, "adapter_family_status", "absent"), } match &entry.assembly { Some(assembly) => { push_line(&mut text, "assembly_status", "present"); push_line( &mut text, "assembly_receipt_checksum", &assembly.receipt_checksum, ); } None => push_line(&mut text, "assembly_status", "admission-only"), } match &entry.module_plan { Some(module_plan) => { push_line(&mut text, "module_plan_status", "present"); push_line( &mut text, "module_plan_checksum", &module_plan.receipt_checksum, ); push_line( &mut text, "module_plan_total_byte_budget", &module_plan.total_byte_budget.to_string(), ); push_line( &mut text, "module_plan_total_byte_budget_limit", &module_plan.total_byte_budget_limit.to_string(), ); push_line( &mut text, "module_plan_output_byte_limit", &module_plan.output_byte_limit.to_string(), ); } None => push_line(&mut text, "module_plan_status", "absent"), } hex64(provenance::text_checksum(text.as_bytes())) } // Keeps checksum text deterministic for admission-only entries without parent-pool fields. fn option_or_marker<'a>(value: &'a Option, marker: &'a str) -> &'a str { value.as_deref().unwrap_or(marker) } // Condenses the scoped eval facts into a selector fitness vector checksum. fn registry_entry_fitness_vector_checksum(entry: &RegistryEntry) -> String { let mut text = String::new(); push_line(&mut text, "quality_scope", &entry.quality_scope); push_line(&mut text, "quality_boundary", &entry.quality_boundary); push_line(&mut text, "eval_dataset", &entry.eval_dataset); push_line(&mut text, "cases_passed", &entry.cases_passed); push_line( &mut text, "eval_case_evidence_checksum", &entry.eval_case_evidence_checksum, ); hex64(provenance::text_checksum(text.as_bytes())) } fn admission_set_checksum(admission_texts: &[String]) -> String { let mut source = String::new(); for admission_text in admission_texts { push_line( &mut source, "admission_checksum", &hex64(provenance::text_checksum(admission_text.as_bytes())), ); } hex64(provenance::text_checksum(source.as_bytes())) } fn parse_manifest(text: &str, label: &str) -> io::Result> { let mut fields = HashMap::new(); for (line_index, raw_line) in text.lines().enumerate() { let line = raw_line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let Some((key, value)) = line.split_once('=') else { return Err(invalid(&format!( "{label} line {} is missing '='", line_index + 1 ))); }; let key = key.trim(); let value = value.trim(); validate_key(key, label, line_index + 1)?; if value.is_empty() || value.contains('\r') || value.contains('\n') { return Err(invalid(&format!("{label} key {key} has an invalid value"))); } if fields.insert(key.to_string(), value.to_string()).is_some() { return Err(invalid(&format!("duplicate {label} key {key}"))); } } Ok(fields) } fn validate_key(key: &str, label: &str, line_number: usize) -> io::Result<()> { if key.is_empty() || !key .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_')) { return Err(invalid(&format!( "{label} line {line_number} has an invalid key" ))); } Ok(()) } fn require_key<'a>(fields: &'a HashMap, key: &str) -> io::Result<&'a str> { fields .get(key) .map(String::as_str) .ok_or_else(|| invalid(&format!("manifest missing required key {key}"))) } fn require_equal(fields: &HashMap, key: &str, expected: &str) -> io::Result<()> { let actual = require_key(fields, key)?; if actual != expected { return Err(invalid(&format!( "selector registry key {key} was {actual}, expected {expected}" ))); } Ok(()) } fn push_line(text: &mut String, key: &str, value: &str) { text.push_str(key); text.push('='); text.push_str(value); text.push('\n'); } fn hex64(value: u64) -> String { format!("0x{value:016x}") } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } #[cfg(test)] mod tests { use super::*; use crate::build_model_file; use crate::candidate; use crate::compatibility; use crate::lineage; use crate::promotion; use crate::slm_validate; use crate::tensor_writer::{ tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_F32, DTYPE_Q4_0, DTYPE_Q8_0, }; use crate::tokenizer_writer::ByteTokenizerSection; #[test] fn writes_and_validates_selector_registry_from_admission_record() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap(); validate_registry_text(®istry, &[admission]).unwrap(); assert!(registry.contains("registry_status=admitted-records-only")); assert!(registry.contains("selector_model_byte_budget=33554432")); assert!(registry.contains("selector_registry_text_byte_budget=262144")); assert!(registry.contains("manifest_text_byte_budget=65536")); assert!(registry.contains("receipt_text_byte_budget=131072")); assert!(registry.contains("evidence_text_byte_budget=131072")); assert!(registry.contains("selector_default_strategy=browser-frugal-quantized")); assert!(registry.contains("selector_default_candidate_id=tiny-q8-candidate")); assert!(registry.contains("selector_default_quantization=q8_0")); assert!(registry.contains("entry.0.model_path=../models/tiny-q8.slm")); assert!(registry.contains("entry.0.selector_status=admitted")); } #[test] fn display_name_labels_converted_trained_source_entries() { assert_eq!( display_name("converted-trained-q8", "q8_0"), "Converted trained-source q8_0" ); assert_eq!( display_name("tiny-q8-candidate", "q8_0"), "tiny-q8-candidate q8_0" ); } #[test] fn writes_and_validates_selector_registry_from_operator_receipt_bound_admission() { let admission = fixture_operator_receipt_bound_admission( "tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm", ); let registry = build_registry_text(&[admission.clone()]).unwrap(); let admission_fields = parse_manifest(&admission, "admission").unwrap(); let registry_fields = parse_manifest(®istry, "selector registry").unwrap(); validate_registry_text(®istry, &[admission]).unwrap(); assert_eq!( registry_fields["entry.0.operator_receipt_status"], "receipt-bound" ); assert_eq!( registry_fields["entry.0.operator_receipt_checksum"], admission_fields["operator_receipt_checksum"] ); assert_eq!( registry_fields["entry.0.operator_receipt_operator_kind"], "deterministic-bounded-parameter-mutation" ); assert_eq!( registry_fields["entry.0.operator_receipt_candidate_slm_checksum"], registry_fields["entry.0.slm_checksum"] ); assert_eq!( registry_fields["entry.0.operator_receipt_candidate_artifact_bytes"], registry_fields["entry.0.model_bytes"] ); } #[test] fn writes_and_validates_selector_registry_from_federated_receipt_bound_admission() { let admission = fixture_operator_receipt_bound_admission_with_kind( "tiny-q8-federated", "tinyrustlm/models/tiny-q8-federated.slm", "federated-local-update-average", ); let registry = build_registry_text(&[admission.clone()]).unwrap(); let admission_fields = parse_manifest(&admission, "admission").unwrap(); let registry_fields = parse_manifest(®istry, "selector registry").unwrap(); validate_registry_text(®istry, &[admission]).unwrap(); assert_eq!( registry_fields["entry.0.operator_receipt_status"], "receipt-bound" ); assert_eq!( registry_fields["entry.0.operator_receipt_operator_kind"], "federated-local-update-average" ); assert_eq!( registry_fields["entry.0.operator_receipt_checksum"], admission_fields["operator_receipt_checksum"] ); assert_eq!( registry_fields["entry.0.operator_receipt_candidate_slm_checksum"], registry_fields["entry.0.slm_checksum"] ); assert_eq!( registry_fields["entry.0.operator_receipt_candidate_artifact_bytes"], registry_fields["entry.0.model_bytes"] ); } #[test] fn writes_and_validates_selector_registry_from_prune_receipt_bound_admission() { let admission = fixture_operator_receipt_bound_admission_with_kind( "tiny-q8-prune", "tinyrustlm/models/tiny-q8-prune.slm", "deterministic-magnitude-parameter-pruning", ); let registry = build_registry_text(&[admission.clone()]).unwrap(); let admission_fields = parse_manifest(&admission, "admission").unwrap(); let registry_fields = parse_manifest(®istry, "selector registry").unwrap(); validate_registry_text(®istry, &[admission]).unwrap(); assert_eq!( registry_fields["entry.0.operator_receipt_status"], "receipt-bound" ); assert_eq!( registry_fields["entry.0.operator_receipt_operator_kind"], "deterministic-magnitude-parameter-pruning" ); assert_eq!( registry_fields["entry.0.operator_receipt_checksum"], admission_fields["operator_receipt_checksum"] ); assert_eq!( registry_fields["entry.0.operator_receipt_candidate_slm_checksum"], registry_fields["entry.0.slm_checksum"] ); assert_eq!( registry_fields["entry.0.operator_receipt_candidate_artifact_bytes"], registry_fields["entry.0.model_bytes"] ); } #[test] fn writes_and_validates_selector_registry_from_dare_receipt_bound_admission() { // Confirms DARE operator receipts keep their kind and byte echo through selector routing. let admission = fixture_operator_receipt_bound_admission_with_kind( "tiny-q8-dare", "tinyrustlm/models/tiny-q8-dare.slm", "dropout-rescaled-task-delta", ); let registry = build_registry_text(&[admission.clone()]).unwrap(); let admission_fields = parse_manifest(&admission, "admission").unwrap(); let registry_fields = parse_manifest(®istry, "selector registry").unwrap(); validate_registry_text(®istry, &[admission]).unwrap(); assert_eq!( registry_fields["entry.0.operator_receipt_status"], "receipt-bound" ); assert_eq!( registry_fields["entry.0.operator_receipt_operator_kind"], "dropout-rescaled-task-delta" ); assert_eq!( registry_fields["entry.0.operator_receipt_checksum"], admission_fields["operator_receipt_checksum"] ); assert_eq!( registry_fields["entry.0.operator_receipt_candidate_slm_checksum"], registry_fields["entry.0.slm_checksum"] ); assert_eq!( registry_fields["entry.0.operator_receipt_candidate_artifact_bytes"], registry_fields["entry.0.model_bytes"] ); } #[test] fn rejects_selector_registry_federated_operator_receipt_kind_drift() { let admission = fixture_operator_receipt_bound_admission_with_kind( "tiny-q8-federated", "tinyrustlm/models/tiny-q8-federated.slm", "federated-local-update-average", ); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.operator_receipt_operator_kind=federated-local-update-average", "entry.0.operator_receipt_operator_kind=deterministic-bounded-parameter-mutation", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator_receipt_operator_kind")); } #[test] fn rejects_selector_registry_prune_operator_receipt_kind_drift() { let admission = fixture_operator_receipt_bound_admission_with_kind( "tiny-q8-prune", "tinyrustlm/models/tiny-q8-prune.slm", "deterministic-magnitude-parameter-pruning", ); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.operator_receipt_operator_kind=deterministic-magnitude-parameter-pruning", "entry.0.operator_receipt_operator_kind=deterministic-bounded-parameter-mutation", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator_receipt_operator_kind")); } #[test] fn rejects_selector_registry_dare_operator_receipt_kind_drift() { // Keeps DARE selector entries bound to the exact operator kind copied from admission. let admission = fixture_operator_receipt_bound_admission_with_kind( "tiny-q8-dare", "tinyrustlm/models/tiny-q8-dare.slm", "dropout-rescaled-task-delta", ); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.operator_receipt_operator_kind=dropout-rescaled-task-delta", "entry.0.operator_receipt_operator_kind=direct-parameter-task-delta", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator_receipt_operator_kind")); } #[test] fn writes_and_validates_selector_registry_from_multi_parent_admission_record() { let admission = fixture_multi_parent_admission("tiny-sign-merge", "tinyrustlm/models/sign-merge.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap(); let fields = parse_manifest(®istry, "selector registry").unwrap(); let entries = entries_from_admissions(&[admission.clone()]).unwrap(); let entry = &entries[0]; validate_registry_text(®istry, &[admission]).unwrap(); assert!(registry.contains("entry.0.candidate_id=tiny-sign-merge")); assert!(registry.contains("entry.0.model_path=../models/sign-merge.slm")); assert!(registry.contains("entry.0.operator_receipt_status=receipt-bound")); assert!(registry .contains("entry.0.operator_receipt_operator_kind=sign-aware-parent-pool-merge")); assert!( registry.contains("entry.0.operator_receipt_candidate_slm_checksum=0x000000000000000c") ); assert!(registry.contains("entry.0.operator_receipt_candidate_artifact_bytes=1024")); assert!(registry.contains("entry.0.evolution_recipe_version=1")); assert!(registry .contains("entry.0.evolution_recipe_strategy=population-based-parent-pool-replay-v1")); assert!(registry.contains("entry.0.evolution_recipe_status=planned")); assert!( registry.contains("entry.0.evolution_selection_source=population-review-frontier-v1") ); assert!( registry.contains("entry.0.evolution_relatedness_contract_checksum=0x0000000000000016") ); assert!(registry .contains("entry.0.evolution_schedule_checksum_algorithm=tinyrustlm-text-checksum-v1")); assert!(registry.contains("entry.0.evolution_schedule_checksum=0x0000000000000017")); assert!(registry.contains("entry.0.scheduled_operator_family_index=0")); assert!(registry .contains("entry.0.scheduled_operator_family_kind=sign-aware-parent-pool-merge")); assert!(registry.contains("entry.0.scheduled_operator_family_command=sign-merge-candidate")); assert!(registry.contains( "entry.0.scheduled_operator_family_selection_rule=seed-weighted-delta-sign-consensus" )); assert!(registry.contains( "entry.0.scheduled_operator_family_output_gate=multi-parent-candidate-manifest-plus-runtime-smoke-plus-eval" )); assert!(registry.contains("entry.0.selector_status=admitted")); assert_eq!( fields["entry.0.mate_selection_id"], registry_entry_mate_selection_id(entry) ); assert_eq!( fields["entry.0.mate_selection_status"], MATE_SELECTION_PARENT_POOL_STATUS ); assert_eq!(fields["entry.0.mate_selection_parent_count"], "3"); assert_eq!( fields["entry.0.mate_selection_checksum"], registry_entry_mate_selection_checksum(entry) ); } #[test] fn rejects_selector_registry_scheduled_operator_family_kind_drift() { let admission = fixture_multi_parent_admission("tiny-sign-merge", "tinyrustlm/models/sign-merge.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.scheduled_operator_family_kind=sign-aware-parent-pool-merge", "entry.0.scheduled_operator_family_kind=seed-weighted-parent-pool-soup", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("scheduled_operator_family_kind")); } #[test] fn writes_and_validates_mixed_selector_registry_admission_versions() { let first = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let second = fixture_multi_parent_admission("tiny-sign-merge", "tinyrustlm/models/sign-merge.slm"); let registry = build_registry_text(&[first.clone(), second.clone()]).unwrap(); validate_registry_text(®istry, &[first, second]).unwrap(); assert!(registry.contains("entry_count=2")); assert!(registry.contains("entry.1.candidate_id=tiny-sign-merge")); } #[test] fn writes_frugal_selector_default_for_mixed_quantizations() { let f32_admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let q8_admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let q4_admission = fixture_q4_admission("tiny-q4-candidate", "tinyrustlm/models/tiny-q4.slm"); let registry = build_registry_text(&[ f32_admission.clone(), q8_admission.clone(), q4_admission.clone(), ]) .unwrap(); validate_registry_text(®istry, &[f32_admission, q8_admission, q4_admission]).unwrap(); assert!(registry.contains("entry_count=3")); assert!(registry.contains("selector_model_byte_budget=33554432")); assert!(registry.contains("selector_default_candidate_id=tiny-q4-candidate")); assert!(registry.contains("selector_default_quantization=q4_0")); } #[test] fn writes_and_validates_selector_registry_with_adapter_route() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let route = fixture_adapter_route("tiny-f32-candidate"); let registry = build_registry_text_with_adapters(&[admission.clone()], &[route.clone()]).unwrap(); validate_registry_text(®istry, &[admission]).unwrap(); assert!(registry.contains("entry.0.adapter_path=../models/tiny-f32-self.adp1")); assert!(registry.contains("entry.0.adapter_label=Tiny f32 self ADP1")); assert!( registry.contains("entry.0.adapter_apply_status=runtime-f32-compatible-or-fuse-to-slm") ); } #[test] fn writes_and_validates_selector_registry_with_sparse_adapter_route() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let route = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-sparse.asp1".to_string(), manifest_path: "../models/tiny-f32-sparse.asp1.manifest".to_string(), label: "Tiny f32 sparse ASP1".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let registry = build_registry_text_with_adapters(&[admission.clone()], &[route.clone()]).unwrap(); validate_registry_text(®istry, &[admission]).unwrap(); assert!(registry.contains("entry.0.adapter_path=../models/tiny-f32-sparse.asp1")); assert!(registry.contains("entry.0.adapter_label=Tiny f32 sparse ASP1")); } #[test] fn writes_and_validates_selector_registry_with_low_rank_adapter_route() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let route = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-low-rank.alr1".to_string(), manifest_path: "../models/tiny-f32-low-rank.alr1.manifest".to_string(), label: "Tiny f32 low-rank ALR1".to_string(), apply_status: LOW_RANK_APPLY_STATUS_F32.to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let registry = build_registry_text_with_adapters(&[admission.clone()], &[route.clone()]).unwrap(); validate_registry_text(®istry, &[admission]).unwrap(); assert!(registry.contains("entry.0.adapter_path=../models/tiny-f32-low-rank.alr1")); assert!(registry.contains("entry.0.adapter_label=Tiny f32 low-rank ALR1")); assert!(registry.contains("entry.0.adapter_apply_status=runtime-f32-compatible-low-rank")); } #[test] fn writes_and_validates_selector_registry_with_adapter_family_routes() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let registry = build_registry_text_with_adapters( &[admission.clone()], &[first.clone(), second.clone()], ) .unwrap(); validate_registry_text(®istry, &[admission]).unwrap(); assert!(registry.contains("entry.0.adapter_path=../models/tiny-f32-self.adp1")); assert!(registry.contains("entry.0.adapter_count=2")); assert!(registry.contains("entry.0.adapter.0.path=../models/tiny-f32-self.adp1")); assert!(registry.contains("entry.0.adapter.1.path=../models/tiny-f32-family.adp1")); assert!(registry.contains("entry.0.adapter.1.label=Tiny f32 family ADP1")); } #[test] fn writes_and_validates_selector_registry_with_adapter_family_receipt() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let registry = build_registry_text_with_adapter_families( &[admission.clone()], &[first, second], &[family], ) .unwrap(); validate_registry_text(®istry, &[admission]).unwrap(); assert!(registry.contains( "entry.0.adapter_family_receipt_path=../models/tiny-f32.adapter-family.receipt" )); assert!(registry.contains("entry.0.adapter_family_status=receipt-validated")); assert!(registry.contains("entry.0.adapter_family_adapter_count=2")); assert!(registry.contains("entry.0.adapter_auto_apply_status=enabled")); assert!( registry.contains("entry.0.adapter_auto_apply_strategy=receipt-preferred-compatible") ); assert!(registry.contains("entry.0.adapter_auto_apply_stack_status=enabled")); assert!(registry.contains( "entry.0.adapter_auto_apply_stack_strategy=receipt-declared-compatible-stack" )); assert!(registry.contains("entry.0.adapter_auto_apply_stack_count=2")); assert!(registry.contains("entry.0.adapter_auto_apply_byte_budget=1048576")); } #[test] fn rejects_adapter_auto_apply_strategy_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let registry = build_registry_text_with_adapter_families( &[admission.clone()], &[first, second], &[family], ) .unwrap() .replace( "entry.0.adapter_auto_apply_strategy=receipt-preferred-compatible", "entry.0.adapter_auto_apply_strategy=manual-only", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("adapter auto apply strategy")); } #[test] fn rejects_adapter_auto_apply_byte_budget_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let registry = build_registry_text_with_adapter_families( &[admission.clone()], &[first, second], &[family], ) .unwrap() .replace( "entry.0.adapter_auto_apply_byte_budget=1048576", "entry.0.adapter_auto_apply_byte_budget=1048577", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("adapter auto apply byte budget")); } #[test] fn rejects_adapter_auto_apply_stack_count_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let registry = build_registry_text_with_adapter_families( &[admission.clone()], &[first, second], &[family], ) .unwrap() .replace( "entry.0.adapter_auto_apply_stack_count=2", "entry.0.adapter_auto_apply_stack_count=3", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("adapter auto apply stack count")); } #[test] fn writes_and_validates_selector_registry_with_assembly_receipt() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let assembly = fixture_assembly_route("tiny-f32-candidate"); let registry = build_registry_text_with_adapter_family_and_assembly_routes( &[admission.clone()], &[], &[], &[assembly], ) .unwrap(); validate_registry_text(®istry, &[admission]).unwrap(); assert!( registry.contains("entry.0.assembly_receipt_path=../models/tiny-f32.assembly.receipt") ); assert!(registry.contains("entry.0.assembly_status=receipt-validated")); assert!(registry.contains("entry.0.assembly_kind=browser-local-assembly-evidence")); } #[test] fn writes_and_validates_selector_registry_with_module_plan_receipt() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let tokenizer_checksum = module_plan.tokenizer_checksum.clone(); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap(); validate_registry_text(®istry, &[admission]).unwrap(); assert!( registry.contains("entry.0.module_plan_path=../models/tiny-f32.module-plan.receipt") ); assert!(registry.contains("entry.0.module_plan_status=receipt-validated")); assert!(registry.contains("entry.0.module_plan_kind=browser-local-module-plan")); assert!(registry.contains("entry.0.module_plan_strategy=selector-entry-self-assembly")); assert!(registry .contains("entry.0.module_plan_resource_class=browser-constrained-local-assembly")); assert!(registry.contains("entry.0.module_plan_profile=browser-constrained-v1")); assert!(registry .contains("entry.0.module_plan_execution_profile=single-threaded-wasm-local-v1")); assert!(registry.contains("entry.0.module_plan_fetch_policy=local-no-store-v1")); assert!( registry.contains("entry.0.module_plan_origin_policy=same-origin-loopback-local-v1") ); assert!(registry.contains("entry.0.module_plan_fetch_count_limit=32")); assert!(registry.contains("entry.0.module_plan_planned_fetch_count=19")); assert!(registry.contains("entry.0.module_plan_route_set_version=1")); assert!(registry.contains( "entry.0.module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1" )); assert!(registry.contains("entry.0.module_plan_route_set_checksum=0x")); assert!(registry.contains("entry.0.module_plan_wasm_memory_initial_pages=17")); assert!(registry.contains("entry.0.module_plan_wasm_export_set=tinyrustlm-generate-v1")); assert!( registry.contains("entry.0.module_plan_wasm_transfer_strategy=copy-then-release-v1") ); assert!(registry .contains("entry.0.module_plan_model_release_strategy=free-before-reassembly-v1")); assert!(registry.contains( "entry.0.module_plan_runtime_reset_strategy=reset-context-before-assembly-v1" )); assert!(registry.contains( "entry.0.module_plan_adapter_validation_strategy=rust-validate-before-apply-v1" )); assert!(registry.contains("entry.0.module_plan_adapter_validation_count=2")); assert!(registry.contains("entry.0.module_plan_adapter_apply_count=2")); assert!(registry.contains("entry.0.module_plan_wasm_heap_min_bytes=65536")); assert!(registry.contains("entry.0.module_plan_context_token_limit=16")); assert!(registry.contains("entry.0.module_plan_sampler_candidate_cap=1024")); assert!(registry.contains(&format!( "entry.0.module_plan_tokenizer_checksum={tokenizer_checksum}" ))); assert!(registry.contains("entry.0.module_plan_prompt_byte_limit=4096")); assert!(registry.contains(&format!( "entry.0.module_plan_model_byte_budget={}", tiny_fixture_f32_bytes().len() ))); assert!(registry.contains("entry.0.module_plan_adapter_byte_budget=1048576")); assert!(registry.contains("entry.0.module_plan_adapter_stack_byte_budget=2048")); assert!(registry.contains("entry.0.module_plan_runtime_scratch_byte_budget=65536")); assert!(registry.contains("entry.0.module_plan_output_byte_limit=65536")); assert!(registry.contains("entry.0.module_plan_kv_cache_byte_budget=1024")); assert!(registry.contains("entry.0.module_plan_kv_cache_page_count=1")); assert!(registry.contains(&format!( "entry.0.module_plan_total_byte_budget={}", tiny_fixture_f32_bytes().len() as u64 + 2048 + 1024 + MODULE_PLAN_PROMPT_BYTE_LIMIT + MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET + MODULE_PLAN_OUTPUT_BYTE_LIMIT ))); assert!(registry.contains(&format!( "entry.0.module_plan_total_byte_budget_limit={MODULE_PLAN_TOTAL_BYTE_BUDGET_LIMIT}" ))); assert!(registry.contains("entry.0.module_plan_module_count=6")); } #[test] fn rejects_module_plan_count_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_module_count=6", "entry.0.module_plan_module_count=5", ) .replace( "entry.0.module_plan_planned_fetch_count=19", "entry.0.module_plan_planned_fetch_count=18", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("module plan count")); } #[test] fn rejects_module_plan_resource_envelope_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_adapter_byte_budget=1048576", "entry.0.module_plan_adapter_byte_budget=1048577", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("adapter byte budget")); } #[test] fn rejects_module_plan_adapter_stack_byte_budget_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_adapter_stack_byte_budget=2048", "entry.0.module_plan_adapter_stack_byte_budget=0", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("adapter stack byte budget")); } #[test] fn rejects_module_plan_context_token_limit_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_context_token_limit=16", "entry.0.module_plan_context_token_limit=15", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("context token limit")); } #[test] fn rejects_module_plan_sampler_candidate_cap_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_sampler_candidate_cap=1024", "entry.0.module_plan_sampler_candidate_cap=1025", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("sampler candidate cap")); } #[test] fn rejects_module_plan_tokenizer_checksum_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let tokenizer_checksum = module_plan.tokenizer_checksum.clone(); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( &format!("entry.0.module_plan_tokenizer_checksum={tokenizer_checksum}"), "entry.0.module_plan_tokenizer_checksum=0x000000000000001d", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("tokenizer checksum")); } #[test] fn rejects_module_plan_profile_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_profile=browser-constrained-v1", "entry.0.module_plan_profile=desktop-expanded-v1", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("profile")); } #[test] fn rejects_module_plan_execution_profile_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_execution_profile=single-threaded-wasm-local-v1", "entry.0.module_plan_execution_profile=worker-pooled-wasm-v1", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("execution profile")); } #[test] fn rejects_module_plan_fetch_policy_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_fetch_policy=local-no-store-v1", "entry.0.module_plan_fetch_policy=cache-default-v1", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("fetch policy")); } #[test] fn rejects_module_plan_origin_policy_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_origin_policy=same-origin-loopback-local-v1", "entry.0.module_plan_origin_policy=cross-origin-network-v1", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("origin policy")); } #[test] fn rejects_module_plan_runtime_scratch_budget_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_runtime_scratch_byte_budget=65536", "entry.0.module_plan_runtime_scratch_byte_budget=65535", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("runtime scratch byte budget")); } #[test] fn rejects_module_plan_kv_cache_byte_budget_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_kv_cache_byte_budget=1024", "entry.0.module_plan_kv_cache_byte_budget=0", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("kv cache byte budget")); } #[test] fn rejects_module_plan_output_byte_limit_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_output_byte_limit=65536", "entry.0.module_plan_output_byte_limit=65535", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("output byte limit")); } #[test] fn rejects_module_plan_prompt_byte_limit_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_prompt_byte_limit=4096", "entry.0.module_plan_prompt_byte_limit=4095", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("prompt byte limit")); } #[test] fn rejects_module_plan_fetch_count_limit_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_fetch_count_limit=32", "entry.0.module_plan_fetch_count_limit=31", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("fetch count limit")); } #[test] fn rejects_module_plan_planned_fetch_count_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_planned_fetch_count=19", "entry.0.module_plan_planned_fetch_count=18", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("planned fetch count")); } #[test] fn rejects_module_plan_route_set_checksum_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let route_set_checksum = module_plan.route_set_checksum.clone(); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( &format!("entry.0.module_plan_route_set_checksum={route_set_checksum}"), "entry.0.module_plan_route_set_checksum=0x000000000000001d", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("route set checksum")); } #[test] fn rejects_module_plan_operator_receipt_path_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_operator_receipt_path=../evidence/tiny-f32-candidate/sign-merge.operator", "entry.0.module_plan_operator_receipt_path=../evidence/tiny-f32-candidate/other.operator", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator receipt path")); } #[test] fn rejects_module_plan_operator_receipt_checksum_drift() { let admission = fixture_operator_receipt_bound_f32_admission( "tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm", ); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let admission_fields = parse_manifest(&admission, "admission").unwrap(); let mut module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); module_plan.operator_receipt_checksum = admission_fields["operator_receipt_checksum"].clone(); let operator_receipt_checksum = module_plan.operator_receipt_checksum.clone(); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( &format!("entry.0.module_plan_operator_receipt_checksum={operator_receipt_checksum}"), "entry.0.module_plan_operator_receipt_checksum=0x0000000000000002", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator receipt checksum")); } #[test] fn rejects_module_plan_route_set_version_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_route_set_version=1", "entry.0.module_plan_route_set_version=2", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("route set version")); } #[test] fn rejects_module_plan_route_set_checksum_algorithm_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1", "entry.0.module_plan_route_set_checksum_algorithm=legacy-text-checksum-v0", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("route set checksum algorithm")); } #[test] fn rejects_module_plan_missing_prompt_byte_limit() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace("entry.0.module_plan_prompt_byte_limit=4096\n", ""); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("module_plan_prompt_byte_limit")); } #[test] fn rejects_module_plan_missing_fetch_count_limit() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace("entry.0.module_plan_fetch_count_limit=32\n", ""); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("module_plan_fetch_count_limit")); } #[test] fn rejects_module_plan_missing_planned_fetch_count() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace("entry.0.module_plan_planned_fetch_count=19\n", ""); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error .to_string() .contains("module_plan_planned_fetch_count")); } #[test] fn rejects_module_plan_missing_route_set_checksum() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let route_set_checksum = module_plan.route_set_checksum.clone(); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( &format!("entry.0.module_plan_route_set_checksum={route_set_checksum}\n"), "", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("module_plan_route_set_checksum")); } #[test] fn rejects_module_plan_missing_route_set_version() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace("entry.0.module_plan_route_set_version=1\n", ""); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("module_plan_route_set_version")); } #[test] fn rejects_module_plan_missing_route_set_checksum_algorithm() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1\n", "", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error .to_string() .contains("module_plan_route_set_checksum_algorithm")); } #[test] fn rejects_module_plan_missing_output_byte_limit() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace("entry.0.module_plan_output_byte_limit=65536\n", ""); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("module_plan_output_byte_limit")); } #[test] fn rejects_module_plan_kv_cache_page_count_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_kv_cache_page_count=1", "entry.0.module_plan_kv_cache_page_count=2", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("kv cache page count")); } #[test] fn rejects_module_plan_wasm_memory_initial_pages_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_wasm_memory_initial_pages=17", "entry.0.module_plan_wasm_memory_initial_pages=18", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert!(error .to_string() .contains("module plan wasm memory initial pages")); } #[test] fn rejects_module_plan_wasm_export_set_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_wasm_export_set=tinyrustlm-generate-v1", "entry.0.module_plan_wasm_export_set=tinyrustlm-extra-v1", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert!(error.to_string().contains("module plan wasm export set")); } #[test] fn rejects_module_plan_wasm_transfer_strategy_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_wasm_transfer_strategy=copy-then-release-v1", "entry.0.module_plan_wasm_transfer_strategy=copy-keep-v1", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert!(error.to_string().contains("wasm transfer strategy")); } #[test] fn rejects_module_plan_model_release_strategy_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_model_release_strategy=free-before-reassembly-v1", "entry.0.module_plan_model_release_strategy=keep-resident-v1", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert!(error.to_string().contains("model release strategy")); } #[test] fn rejects_module_plan_runtime_reset_strategy_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_runtime_reset_strategy=reset-context-before-assembly-v1", "entry.0.module_plan_runtime_reset_strategy=skip-reset-v1", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert!(error.to_string().contains("runtime reset strategy")); } #[test] fn rejects_module_plan_adapter_validation_strategy_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_adapter_validation_strategy=rust-validate-before-apply-v1", "entry.0.module_plan_adapter_validation_strategy=apply-without-rust-validate-v1", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert!(error.to_string().contains("adapter validation strategy")); } #[test] fn rejects_module_plan_adapter_validation_count_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_adapter_validation_count=2", "entry.0.module_plan_adapter_validation_count=1", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert!(error.to_string().contains("adapter validation count")); } #[test] fn rejects_module_plan_adapter_apply_count_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_adapter_apply_count=2", "entry.0.module_plan_adapter_apply_count=0", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert!(error.to_string().contains("adapter apply count")); } #[test] fn rejects_module_plan_wasm_heap_min_bytes_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_wasm_heap_min_bytes=65536", "entry.0.module_plan_wasm_heap_min_bytes=65535", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("wasm heap min bytes")); } #[test] fn rejects_module_plan_total_budget_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( &format!( "entry.0.module_plan_total_byte_budget={}", tiny_fixture_f32_bytes().len() as u64 + 2048 + 1024 + MODULE_PLAN_PROMPT_BYTE_LIMIT + MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET + MODULE_PLAN_OUTPUT_BYTE_LIMIT ), "entry.0.module_plan_total_byte_budget=1", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("total byte budget")); } #[test] fn rejects_module_plan_total_budget_limit_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( &format!( "entry.0.module_plan_total_byte_budget_limit={MODULE_PLAN_TOTAL_BYTE_BUDGET_LIMIT}" ), "entry.0.module_plan_total_byte_budget_limit=1", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("total byte budget limit")); } #[test] fn rejects_module_plan_missing_runtime_scratch_budget() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_runtime_scratch_byte_budget=65536\n", "", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error .to_string() .contains("module_plan_runtime_scratch_byte_budget")); } #[test] fn rejects_module_plan_missing_wasm_heap_min_bytes() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace("entry.0.module_plan_wasm_heap_min_bytes=65536\n", ""); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error .to_string() .contains("module_plan_wasm_heap_min_bytes")); } #[test] fn rejects_module_plan_malformed_runtime_scratch_budget() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_runtime_scratch_byte_budget=65536", "entry.0.module_plan_runtime_scratch_byte_budget=065536", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("runtime scratch byte budget")); } #[test] fn rejects_module_plan_malformed_wasm_heap_min_bytes() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap() .replace( "entry.0.module_plan_wasm_heap_min_bytes=65536", "entry.0.module_plan_wasm_heap_min_bytes=065536", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("wasm heap byte budget")); } #[test] fn writes_selector_registry_genome_species_novelty_population_phenotype_and_fitness_metadata() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap(); let fields = parse_manifest(®istry, "selector registry").unwrap(); let entries = entries_from_admissions(&[admission.clone()]).unwrap(); let entry = &entries[0]; validate_registry_text(®istry, &[admission]).unwrap(); assert_eq!(fields["entry.0.genome_id"], registry_entry_genome_id(entry)); assert_eq!(fields["entry.0.genome_strategy"], GENOME_STRATEGY); assert_eq!( fields["entry.0.genome_lineage_status"], GENOME_LINEAGE_STATUS ); assert_eq!( fields["entry.0.genome_lineage_checksum"], registry_entry_genome_lineage_checksum(entry) ); assert_eq!( fields["entry.0.species_id"], registry_entry_species_id(entry) ); assert_eq!(fields["entry.0.species_strategy"], SPECIES_STRATEGY); assert_eq!(fields["entry.0.species_fit_status"], SPECIES_FIT_STATUS); assert_eq!( fields["entry.0.species_fit_checksum"], registry_entry_species_fit_checksum(entry) ); assert_eq!( fields["entry.0.novelty_id"], registry_entry_novelty_id(entry) ); assert_eq!(fields["entry.0.novelty_strategy"], NOVELTY_STRATEGY); assert_eq!(fields["entry.0.novelty_status"], NOVELTY_STATUS); assert_eq!( fields["entry.0.novelty_checksum"], registry_entry_novelty_checksum(entry) ); assert_eq!( fields["entry.0.population_id"], registry_entry_population_id(entry) ); assert_eq!(fields["entry.0.population_strategy"], POPULATION_STRATEGY); assert_eq!(fields["entry.0.population_status"], POPULATION_STATUS); assert_eq!( fields["entry.0.population_checksum"], registry_entry_population_checksum(entry) ); assert_eq!( fields["entry.0.mate_selection_id"], registry_entry_mate_selection_id(entry) ); assert_eq!( fields["entry.0.mate_selection_strategy"], MATE_SELECTION_STRATEGY ); assert_eq!( fields["entry.0.mate_selection_status"], MATE_SELECTION_ADMISSION_STATUS ); assert_eq!(fields["entry.0.mate_selection_parent_count"], "1"); assert_eq!( fields["entry.0.mate_selection_checksum"], registry_entry_mate_selection_checksum(entry) ); assert_eq!( fields["entry.0.phenotype_evidence_id"], registry_entry_phenotype_evidence_id(entry) ); assert_eq!( fields["entry.0.phenotype_evidence_strategy"], PHENOTYPE_EVIDENCE_STRATEGY ); assert_eq!( fields["entry.0.phenotype_evidence_status"], PHENOTYPE_EVIDENCE_STATUS ); assert_eq!( fields["entry.0.phenotype_evidence_checksum"], registry_entry_phenotype_evidence_checksum(entry) ); assert_eq!( fields["entry.0.heritable_artifact_id"], registry_entry_heritable_artifact_id(entry) ); assert_eq!( fields["entry.0.heritable_artifact_strategy"], HERITABLE_ARTIFACT_STRATEGY ); assert_eq!( fields["entry.0.heritable_artifact_status"], HERITABLE_ARTIFACT_STATUS ); assert_eq!( fields["entry.0.heritable_artifact_checksum"], registry_entry_heritable_artifact_checksum(entry) ); assert_eq!( fields["entry.0.provenance_manifest_checksum"], entry.provenance_manifest_checksum ); assert_eq!( fields["entry.0.fitness_vector_status"], FITNESS_VECTOR_STATUS ); assert_eq!( fields["entry.0.fitness_vector_checksum"], registry_entry_fitness_vector_checksum(entry) ); } #[test] fn writes_selector_registry_module_plan_species_fit_novelty_and_population_metadata() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let first = fixture_adapter_route("tiny-f32-candidate"); let second = RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let assembly = fixture_assembly_route("tiny-f32-candidate"); let module_plan = fixture_module_plan_route("tiny-f32-candidate", 6); let registry = build_registry_text_with_module_plan_routes( &[admission.clone()], &[first, second], &[family], &[assembly], &[module_plan], ) .unwrap(); let fields = parse_manifest(®istry, "selector registry").unwrap(); let actual_adapter_routes = adapter_routes_from_registry(&fields).unwrap(); let actual_family_routes = adapter_family_routes_from_registry(&fields).unwrap(); let actual_assembly_routes = assembly_routes_from_registry(&fields).unwrap(); let actual_module_plan_routes = module_plan_routes_from_registry(&fields).unwrap(); let mut entries = entries_from_admissions(&[admission.clone()]).unwrap(); attach_adapter_routes(&mut entries, &actual_adapter_routes).unwrap(); attach_adapter_family_routes(&mut entries, &actual_family_routes).unwrap(); attach_assembly_routes(&mut entries, &actual_assembly_routes).unwrap(); attach_module_plan_routes(&mut entries, &actual_module_plan_routes).unwrap(); let entry = &entries[0]; validate_registry_text(®istry, &[admission]).unwrap(); assert_eq!( fields["entry.0.species_id"], registry_entry_species_id(entry) ); assert_eq!( fields["entry.0.species_fit_checksum"], registry_entry_species_fit_checksum(entry) ); assert_eq!( fields["entry.0.novelty_id"], registry_entry_novelty_id(entry) ); assert_eq!( fields["entry.0.novelty_checksum"], registry_entry_novelty_checksum(entry) ); assert_eq!( fields["entry.0.population_id"], registry_entry_population_id(entry) ); assert_eq!( fields["entry.0.population_checksum"], registry_entry_population_checksum(entry) ); assert_eq!( fields["entry.0.mate_selection_id"], registry_entry_mate_selection_id(entry) ); assert_eq!( fields["entry.0.mate_selection_checksum"], registry_entry_mate_selection_checksum(entry) ); assert_eq!( fields["entry.0.phenotype_evidence_id"], registry_entry_phenotype_evidence_id(entry) ); assert_eq!( fields["entry.0.phenotype_evidence_checksum"], registry_entry_phenotype_evidence_checksum(entry) ); assert_eq!( fields["entry.0.heritable_artifact_id"], registry_entry_heritable_artifact_id(entry) ); assert_eq!( fields["entry.0.heritable_artifact_checksum"], registry_entry_heritable_artifact_checksum(entry) ); } #[test] fn rejects_selector_registry_genome_drift() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.genome_strategy=selector-admission-genome-v1", "entry.0.genome_strategy=selector-admission-genome-v2", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("genome_strategy")); } #[test] fn rejects_selector_registry_species_drift() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.species_fit_status=browser-fit-bound", "entry.0.species_fit_status=desktop-fit-bound", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("species_fit_status")); } #[test] fn rejects_selector_registry_novelty_drift() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.novelty_status=behavior-sketch-bound", "entry.0.novelty_status=unreviewed", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("novelty_status")); } #[test] fn rejects_selector_registry_population_drift() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.population_status=population-review-bound", "entry.0.population_status=unreviewed", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("population_status")); } #[test] fn rejects_selector_registry_mate_selection_drift() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.mate_selection_status=admission-only", "entry.0.mate_selection_status=unbound", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("mate_selection_status")); } #[test] fn rejects_selector_registry_mate_selection_parent_count_drift() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.mate_selection_parent_count=1", "entry.0.mate_selection_parent_count=2", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("mate_selection_parent_count")); } #[test] fn rejects_selector_registry_operator_receipt_field_drift() { let admission = fixture_operator_receipt_bound_admission( "tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm", ); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.operator_receipt_operator_kind=deterministic-bounded-parameter-mutation", "entry.0.operator_receipt_operator_kind=unbound", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator_receipt_operator_kind")); } #[test] fn rejects_selector_registry_phenotype_evidence_drift() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.phenotype_evidence_status=runtime-eval-bound", "entry.0.phenotype_evidence_status=unbound", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("phenotype_evidence_status")); } #[test] fn rejects_selector_registry_heritable_artifact_drift() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.heritable_artifact_status=served-artifact-bound", "entry.0.heritable_artifact_status=detached", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("heritable_artifact_status")); } #[test] fn rejects_selector_registry_fitness_drift() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.fitness_vector_status=eval-bound", "entry.0.fitness_vector_status=unreviewed", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("fitness_vector_status")); } #[test] fn writes_and_validates_selector_registry_with_q8_adapter_route() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let route = RegistryAdapterRoute { candidate_id: "tiny-q8-candidate".to_string(), adapter_path: "../models/tiny-q8-self.adp1".to_string(), manifest_path: "../models/tiny-q8-self.adp1.manifest".to_string(), label: "Tiny q8_0 self ADP1".to_string(), apply_status: ADAPTER_APPLY_STATUS_QUANTIZED.to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let registry = build_registry_text_with_adapters(&[admission.clone()], &[route.clone()]).unwrap(); validate_registry_text(®istry, &[admission]).unwrap(); assert!(registry.contains("entry.0.quantization=q8_0")); assert!(registry.contains("entry.0.adapter_path=../models/tiny-q8-self.adp1")); assert!(registry .contains("entry.0.adapter_apply_status=runtime-q8-q4-compatible-or-fuse-to-slm")); } #[test] fn rejects_adapter_route_apply_status_quantization_mismatch() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let route = RegistryAdapterRoute { candidate_id: "tiny-q8-candidate".to_string(), ..fixture_adapter_route("tiny-f32-candidate") }; let error = build_registry_text_with_adapters(&[admission], &[route]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("entry quantization")); } #[test] fn rejects_duplicate_adapter_route_for_same_candidate() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let route = fixture_adapter_route("tiny-f32-candidate"); let error = build_registry_text_with_adapters(&[admission], &[route.clone(), route]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error .to_string() .contains("duplicate selector registry adapter route")); } #[test] fn rejects_adapter_family_receipt_count_drift() { let admission = fixture_f32_admission("tiny-f32-candidate", "tinyrustlm/models/tiny-f32.slm"); let route = fixture_adapter_route("tiny-f32-candidate"); let family = fixture_adapter_family_route("tiny-f32-candidate", 2); let error = build_registry_text_with_adapter_families(&[admission], &[route], &[family]) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("family count")); } #[test] fn rejects_empty_registry_input() { let error = build_registry_text(&[]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("at least one admission")); } #[test] fn rejects_selector_id_mismatch() { let left = fixture_admission("candidate-a", "tinyrustlm/models/a.slm"); let right = fixture_admission("candidate-b", "tinyrustlm/models/b.slm").replace( "selector_id=browser-local-selector", "selector_id=other-selector", ); let error = build_registry_text(&[left, right]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("selector_id")); } #[test] fn rejects_duplicate_candidate_id() { let left = fixture_admission("candidate-a", "tinyrustlm/models/a.slm"); let right = fixture_admission("candidate-a", "tinyrustlm/models/b.slm"); let error = build_registry_text(&[left, right]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error .to_string() .contains("duplicate selector registry candidate_id")); } #[test] fn rejects_unserved_candidate_path() { let admission = fixture_admission("candidate-a", "target/admission-smoke/a.slm"); let error = build_registry_text(&[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("served tinyrustlm/models")); } #[test] fn rejects_selector_registry_model_bytes_over_budget() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm") .replace( "candidate_artifact_bytes=8832", "candidate_artifact_bytes=33554433", ); let error = build_registry_text(&[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("browser selector budget")); } #[test] fn rejects_registry_entry_drift() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "entry.0.selector_status=admitted", "entry.0.selector_status=pending", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("selector_status")); } #[test] fn rejects_selector_registry_budget_drift() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "selector_model_byte_budget=33554432", "selector_model_byte_budget=33554431", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("selector_model_byte_budget")); } #[test] fn rejects_selector_registry_text_budget_drift() { let admission = fixture_admission("tiny-q8-candidate", "tinyrustlm/models/tiny-q8.slm"); let registry = build_registry_text(&[admission.clone()]).unwrap().replace( "manifest_text_byte_budget=65536", "manifest_text_byte_budget=65537", ); let error = validate_registry_text(®istry, &[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("manifest_text_byte_budget")); } #[test] fn rejects_unsupported_admission_version() { let admission = "selector_id=browser-local-selector\ncandidate_id=oops\n".to_string(); let error = build_registry_text(&[admission]).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("supported admission version")); } fn fixture_admission(candidate_id: &str, candidate_path: &str) -> String { fixture_admission_for_bytes(candidate_id, candidate_path, tiny_fixture_q8_bytes()) } fn fixture_f32_admission(candidate_id: &str, candidate_path: &str) -> String { fixture_admission_for_bytes(candidate_id, candidate_path, tiny_fixture_f32_bytes()) } fn fixture_q4_admission(candidate_id: &str, candidate_path: &str) -> String { fixture_admission_for_bytes(candidate_id, candidate_path, tiny_fixture_q4_bytes()) } fn fixture_operator_receipt_bound_admission( candidate_id: &str, candidate_path: &str, ) -> String { fixture_operator_receipt_bound_admission_for_bytes( candidate_id, candidate_path, tiny_fixture_q8_bytes(), ) } fn fixture_operator_receipt_bound_f32_admission( candidate_id: &str, candidate_path: &str, ) -> String { fixture_operator_receipt_bound_admission_for_bytes( candidate_id, candidate_path, tiny_fixture_f32_bytes(), ) } fn fixture_operator_receipt_bound_admission_for_bytes( candidate_id: &str, candidate_path: &str, candidate: Vec, ) -> String { fixture_operator_receipt_bound_admission_for_bytes_with_kind( candidate_id, candidate_path, candidate, "deterministic-bounded-parameter-mutation", ) } fn fixture_operator_receipt_bound_admission_with_kind( candidate_id: &str, candidate_path: &str, operator_kind: &str, ) -> String { fixture_operator_receipt_bound_admission_for_bytes_with_kind( candidate_id, candidate_path, tiny_fixture_q8_bytes(), operator_kind, ) } // Builds a full two-parent admission chain with the requested operator kind in the bound receipt. fn fixture_operator_receipt_bound_admission_for_bytes_with_kind( candidate_id: &str, candidate_path: &str, candidate: Vec, operator_kind: &str, ) -> String { let compatibility = compatibility::compatibility_text_for_bytes( &candidate, "left.slm", &candidate, "right.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, candidate_id, "operator-a", "fit") .unwrap(); let receipt = operator_receipt_text_with_kind(&lineage, &candidate, candidate_path, operator_kind); let candidate_manifest = candidate::build_manifest_text_with_operator_receipt_text( &compatibility, &lineage, &candidate, candidate_path, Some(("candidate.operator", &receipt)), ) .unwrap(); let promotion = promotion::build_template_text_with_operator_receipt_text( &compatibility, &lineage, &candidate, candidate_path, &candidate_manifest, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, Some(("candidate.operator", &receipt)), ) .unwrap(); let report = slm_validate::validate_bytes(&candidate, candidate_path).unwrap(); let provenance_manifest = provenance::build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = provenance::parse_manifest(&provenance_manifest).unwrap(); let runtime_smoke = provenance::build_runtime_smoke_text(&report, &provenance_manifest, &manifest_fields) .unwrap(); let eval = passing_eval_text(&report, &provenance_manifest); admission::build_record_text_with_operator_receipt_text( &compatibility, &lineage, &candidate, candidate_path, &candidate_manifest, &promotion, &provenance_manifest, &runtime_smoke, &eval, admission::DEFAULT_ADMISSION_SELECTOR_ID, Some(("candidate.operator", &receipt)), ) .unwrap() } fn fixture_admission_for_bytes( candidate_id: &str, candidate_path: &str, candidate: Vec, ) -> String { let compatibility = compatibility::compatibility_text_for_bytes( &candidate, "left.slm", &candidate, "right.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, candidate_id, "operator-a", "fit") .unwrap(); let candidate_manifest = candidate::build_manifest_text(&compatibility, &lineage, &candidate, candidate_path) .unwrap(); let promotion = promotion::build_template_text( &compatibility, &lineage, &candidate, candidate_path, &candidate_manifest, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, ) .unwrap(); let report = slm_validate::validate_bytes(&candidate, candidate_path).unwrap(); let provenance_manifest = provenance::build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = provenance::parse_manifest(&provenance_manifest).unwrap(); let runtime_smoke = provenance::build_runtime_smoke_text(&report, &provenance_manifest, &manifest_fields) .unwrap(); let eval = passing_eval_text(&report, &provenance_manifest); admission::build_record_text( &compatibility, &lineage, &candidate, candidate_path, &candidate_manifest, &promotion, &provenance_manifest, &runtime_smoke, &eval, admission::DEFAULT_ADMISSION_SELECTOR_ID, ) .unwrap() } // Keeps the synthetic receipt minimal while letting tests prove non-mutation operator routing. fn operator_receipt_text_with_kind( lineage_text: &str, candidate: &[u8], candidate_path: &str, operator_kind: &str, ) -> String { let lineage_fields = parse_manifest(lineage_text, "lineage").unwrap(); let report = slm_validate::validate_bytes(candidate, candidate_path).unwrap(); let mut text = String::new(); push_line(&mut text, "operator_kind", operator_kind); push_line( &mut text, "candidate_id", require_key(&lineage_fields, "candidate_id").unwrap(), ); push_line( &mut text, "operator_id", require_key(&lineage_fields, "operator_id").unwrap(), ); push_line(&mut text, "candidate_artifact_path", report.path()); push_line( &mut text, "candidate_artifact_bytes", &report.file_bytes().to_string(), ); push_line( &mut text, "candidate_slm_checksum", &hex64(report.checksum()), ); push_line( &mut text, "required_next_gate", "candidate-manifest-plus-runtime-smoke-plus-eval", ); text } fn fixture_adapter_route(candidate_id: &str) -> RegistryAdapterRoute { RegistryAdapterRoute { candidate_id: candidate_id.to_string(), adapter_path: "../models/tiny-f32-self.adp1".to_string(), manifest_path: "../models/tiny-f32-self.adp1.manifest".to_string(), label: "Tiny f32 self ADP1".to_string(), apply_status: ADAPTER_APPLY_STATUS_F32.to_string(), artifact_checksum: "0x00000000000000aa".to_string(), manifest_checksum: "0x00000000000000bb".to_string(), } } fn fixture_adapter_family_route( candidate_id: &str, adapter_count: usize, ) -> RegistryAdapterFamilyRoute { RegistryAdapterFamilyRoute { candidate_id: candidate_id.to_string(), receipt_path: "../models/tiny-f32.adapter-family.receipt".to_string(), label: "Tiny f32 adapter family".to_string(), status: ADAPTER_FAMILY_STATUS.to_string(), strategy: ADAPTER_FAMILY_STRATEGY.to_string(), receipt_checksum: "0x00000000000000ee".to_string(), adapter_count, auto_apply_status: ADAPTER_AUTO_APPLY_STATUS.to_string(), auto_apply_strategy: ADAPTER_AUTO_APPLY_STRATEGY.to_string(), auto_apply_stack_status: ADAPTER_AUTO_APPLY_STACK_STATUS.to_string(), auto_apply_stack_strategy: ADAPTER_AUTO_APPLY_STACK_STRATEGY.to_string(), auto_apply_stack_count: adapter_count, auto_apply_byte_budget: ADAPTER_AUTO_APPLY_BYTE_BUDGET, } } fn fixture_assembly_route(candidate_id: &str) -> RegistryAssemblyRoute { RegistryAssemblyRoute { candidate_id: candidate_id.to_string(), receipt_path: "../models/tiny-f32.assembly.receipt".to_string(), label: "Tiny f32 assembly evidence".to_string(), status: ASSEMBLY_RECEIPT_STATUS.to_string(), kind: ASSEMBLY_RECEIPT_KIND.to_string(), receipt_checksum: "0x00000000000000ef".to_string(), } } fn fixture_module_plan_route( candidate_id: &str, module_count: usize, ) -> RegistryModulePlanRoute { let tokenizer_report = slm_validate::validate_bytes(&tiny_fixture_f32_bytes(), "tiny-f32.slm").unwrap(); let adapters = vec![ fixture_adapter_route(candidate_id), RegistryAdapterRoute { adapter_path: "../models/tiny-f32-family.adp1".to_string(), manifest_path: "../models/tiny-f32-family.adp1.manifest".to_string(), label: "Tiny f32 family ADP1".to_string(), artifact_checksum: "0x00000000000000cc".to_string(), manifest_checksum: "0x00000000000000dd".to_string(), ..fixture_adapter_route(candidate_id) }, ]; let route_set_checksum = module_plan_route_set_checksum_from_parts( candidate_id, "../models/tiny-f32.module-plan.receipt", "../models/tiny-f32.slm", "../models/tiny-f32.slm.manifest", "../models/tiny-f32.assembly.receipt", "../models/tiny-f32.adapter-family.receipt", &adapters, 2, &format!("../evidence/{candidate_id}/sign-merge.operator"), ) .unwrap(); RegistryModulePlanRoute { candidate_id: candidate_id.to_string(), receipt_path: "../models/tiny-f32.module-plan.receipt".to_string(), label: "Tiny f32 module plan".to_string(), status: MODULE_PLAN_STATUS.to_string(), kind: MODULE_PLAN_KIND.to_string(), strategy: MODULE_PLAN_STRATEGY.to_string(), resource_class: MODULE_PLAN_RESOURCE_CLASS.to_string(), profile: MODULE_PLAN_PROFILE.to_string(), execution_profile: MODULE_PLAN_EXECUTION_PROFILE.to_string(), fetch_policy: MODULE_PLAN_FETCH_POLICY.to_string(), origin_policy: MODULE_PLAN_ORIGIN_POLICY.to_string(), fetch_count_limit: MODULE_PLAN_FETCH_COUNT_LIMIT, planned_fetch_count: module_plan_planned_fetch_count(module_count, 2).unwrap(), route_set_version: MODULE_PLAN_ROUTE_SET_VERSION.to_string(), route_set_checksum_algorithm: MODULE_PLAN_ROUTE_SET_CHECKSUM_ALGORITHM.to_string(), route_set_checksum, operator_receipt_path: format!("../evidence/{candidate_id}/sign-merge.operator"), operator_receipt_checksum: "0x0000000000000001".to_string(), wasm_memory_initial_pages: MODULE_PLAN_WASM_MEMORY_INITIAL_PAGES, wasm_export_set: MODULE_PLAN_WASM_EXPORT_SET.to_string(), wasm_transfer_strategy: MODULE_PLAN_WASM_TRANSFER_STRATEGY.to_string(), model_release_strategy: MODULE_PLAN_MODEL_RELEASE_STRATEGY.to_string(), runtime_reset_strategy: MODULE_PLAN_RUNTIME_RESET_STRATEGY.to_string(), adapter_validation_strategy: MODULE_PLAN_ADAPTER_VALIDATION_STRATEGY.to_string(), adapter_validation_count: 2, adapter_apply_count: 2, wasm_heap_min_bytes: MODULE_PLAN_WASM_HEAP_MIN_BYTES, context_token_limit: 16, sampler_candidate_cap: MODULE_PLAN_SAMPLER_CANDIDATE_CAP, tokenizer_checksum: hex64(tokenizer_report.tokenizer_checksum()), prompt_byte_limit: MODULE_PLAN_PROMPT_BYTE_LIMIT, model_byte_budget: tiny_fixture_f32_bytes().len() as u64, adapter_byte_budget: ADAPTER_AUTO_APPLY_BYTE_BUDGET, adapter_stack_byte_budget: 2048, runtime_scratch_byte_budget: MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET, output_byte_limit: MODULE_PLAN_OUTPUT_BYTE_LIMIT, kv_cache_byte_budget: 1024, kv_cache_page_count: 1, total_byte_budget: tiny_fixture_f32_bytes().len() as u64 + 2048 + 1024 + MODULE_PLAN_PROMPT_BYTE_LIMIT + MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET + MODULE_PLAN_OUTPUT_BYTE_LIMIT, total_byte_budget_limit: MODULE_PLAN_TOTAL_BYTE_BUDGET_LIMIT, receipt_checksum: "0x00000000000000f0".to_string(), module_count, } } fn fixture_multi_parent_admission(candidate_id: &str, candidate_path: &str) -> String { let mut text = String::new(); push_line( &mut text, "tinyrustlm_multi_parent_selector_admission_version", "1", ); push_line(&mut text, "admission_kind", "multi-parent-sign-merge"); push_line(&mut text, "selector_id", "browser-local-selector"); push_line( &mut text, "admission_status", "admitted-for-browser-selector", ); push_line( &mut text, "promotion_status", "runtime-smoke-and-eval-passed", ); push_line(&mut text, "promotion_kind", "multi-parent-sign-merge"); push_line(&mut text, "promoter_id", "local-smoke-runner"); push_line( &mut text, "promotion_scope", promotion::DEFAULT_PROMOTION_SCOPE, ); push_line(&mut text, "operator_receipt_checksum", "0x0000000000000001"); push_line(&mut text, "operator_receipt_status", "receipt-bound"); push_line( &mut text, "operator_receipt_path", "tinyrustlm/models/sign-merge.operator", ); push_line(&mut text, "operator_receipt_operator_id", candidate_id); push_line( &mut text, "operator_receipt_operator_kind", "sign-aware-parent-pool-merge", ); push_line( &mut text, "operator_receipt_candidate_slm_checksum", "0x000000000000000c", ); push_line( &mut text, "operator_receipt_candidate_artifact_bytes", "1024", ); push_line( &mut text, "parent_pool_recipe_checksum", "0x0000000000000002", ); push_line( &mut text, "population_review_checksum", "0x0000000000000003", ); push_line(&mut text, "promotion_ledger_checksum", "0x0000000000000004"); push_line(&mut text, "admission_set_checksum", "0x0000000000000005"); push_line(&mut text, "frontier_candidate_id", candidate_id); push_line( &mut text, "frontier_candidate_slm_checksum", "0x0000000000000006", ); push_line(&mut text, "parent_count", "3"); push_line(&mut text, "evolution_recipe_version", "1"); push_line( &mut text, "evolution_recipe_strategy", "population-based-parent-pool-replay-v1", ); push_line(&mut text, "evolution_recipe_status", "planned"); push_line( &mut text, "evolution_selection_source", "population-review-frontier-v1", ); push_line( &mut text, "evolution_relatedness_contract_checksum", "0x0000000000000016", ); push_line( &mut text, "evolution_schedule_checksum_algorithm", "tinyrustlm-text-checksum-v1", ); push_line( &mut text, "evolution_schedule_checksum", "0x0000000000000017", ); push_line(&mut text, "scheduled_operator_family_index", "0"); push_line( &mut text, "scheduled_operator_family_kind", "sign-aware-parent-pool-merge", ); push_line( &mut text, "scheduled_operator_family_command", "sign-merge-candidate", ); push_line( &mut text, "scheduled_operator_family_selection_rule", "seed-weighted-delta-sign-consensus", ); push_line( &mut text, "scheduled_operator_family_output_gate", "multi-parent-candidate-manifest-plus-runtime-smoke-plus-eval", ); push_line(&mut text, "candidate_id", candidate_id); push_line( &mut text, "candidate_manifest_checksum", "0x0000000000000007", ); push_line( &mut text, "promotion_manifest_checksum", "0x0000000000000008", ); push_line( &mut text, "provenance_manifest_checksum", "0x0000000000000009", ); push_line( &mut text, "runtime_smoke_manifest_checksum", "0x000000000000000a", ); push_line(&mut text, "eval_manifest_checksum", "0x000000000000000b"); push_line( &mut text, "eval_case_evidence_checksum", "0x0000000000000015", ); push_line(&mut text, "candidate_artifact_path", candidate_path); push_line(&mut text, "candidate_artifact_bytes", "1024"); push_line(&mut text, "candidate_slm_version", "1"); push_line(&mut text, "candidate_slm_checksum", "0x000000000000000c"); push_line( &mut text, "candidate_model_shape", "vocab=260,hidden=16,layers=1,heads=2,kv_heads=2,ctx=16,ffn=32", ); push_line(&mut text, "candidate_tensor_count", "12"); push_line(&mut text, "candidate_parameter_count", "4096"); push_line(&mut text, "candidate_quantization", "q8_0"); push_line( &mut text, "candidate_output_contract", "separate-output-weight", ); push_line( &mut text, "candidate_tokenizer_checksum", "0x000000000000000d", ); push_line( &mut text, "candidate_tensor_layout_checksum", "0x000000000000000e", ); push_line( &mut text, "candidate_parent_contract", "matches-parent-direct-parameter-contract", ); push_line(&mut text, "candidate_admission_status", "slm-validated"); push_line(&mut text, "runtime_smoke_status", "pass"); push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "quality_gate", "assistant-quality"); push_line(&mut text, "quality_scope", "tiny-fixture-runtime-eval-only"); push_line( &mut text, "quality_boundary", "fixture-runtime-and-eval-plumbing-not-product-assistant-quality", ); push_line( &mut text, "eval_dataset", "tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", ); push_line(&mut text, "case_count", "1"); push_line(&mut text, "cases_passed", "1"); push_line(&mut text, "cases_failed", "0"); push_line( &mut text, "promotion_decision", "accepted-for-browser-selector", ); push_line(&mut text, "browser_selector_status", "admitted"); push_line(&mut text, "public_claim_status", "bound-to-eval-scope"); push_line( &mut text, "required_next_gate", "multi-parent-selector-registry-route-binding", ); text } fn passing_eval_text(report: &slm_validate::ValidationReport, manifest: &str) -> String { let mut text = String::new(); push_line(&mut text, "tinyrustlm_eval_manifest_version", "1"); push_line(&mut text, "gate", "assistant-quality"); push_line(&mut text, "source_kind", "converted-trained"); push_line( &mut text, "manifest_checksum", &hex64(provenance::text_checksum(manifest.as_bytes())), ); push_line(&mut text, "slm_checksum", &hex64(report.checksum())); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "task_eval_status", "pass"); push_line(&mut text, "safety_review_status", "pass"); push_line( &mut text, "quality_decision", "accepted-for-assistant-quality", ); push_line(&mut text, "quality_scope", "tiny-fixture-runtime-eval-only"); push_line(&mut text, "evaluator", "local-reviewed-eval"); push_line( &mut text, "eval_dataset", "tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", ); push_line( &mut text, "eval_summary", "Reviewed task and safety evidence passed for declared scope", ); push_line( &mut text, "quality_boundary", "fixture-runtime-and-eval-plumbing-not-product-assistant-quality", ); push_line(&mut text, "case_count", "1"); push_line(&mut text, "cases_passed", "1"); push_line(&mut text, "cases_failed", "0"); push_line(&mut text, "case.0.status", "pass"); push_line(&mut text, "case.0.expected", "e"); push_line(&mut text, "case.0.actual", "e"); push_line(&mut text, "case.0.error", "ok"); text } fn tiny_fixture_q8_bytes() -> Vec { build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), &ByteTokenizerSection::phase_one(), ) .unwrap() } fn tiny_fixture_f32_bytes() -> Vec { build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(DTYPE_F32), &ByteTokenizerSection::phase_one(), ) .unwrap() } fn tiny_fixture_q4_bytes() -> Vec { build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors_with_dtype(DTYPE_Q4_0), &ByteTokenizerSection::phase_one(), ) .unwrap() } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/selector.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/sign_merge.rs BYTES: 47624 SHA256: E2C07EC2ADEB25F1C0CEBFBF807486CA68B0C548B57512EF24BC447FA29EF948 ================================================================================ //! Sign-aware multi-parent candidates built from parent-pool recipes. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::blend::{ hex64, invalid, output_specs, parse_manifest, parse_model_values, push_line, require_equal, require_key, require_report_equal, require_same_tensor_spec, same_shape, ParsedModel, }; use crate::build_model_file_from_values_with_flags; use crate::parent_pool; use crate::provenance; use crate::slm_validate::{self, ValidationReport}; const OPERATOR_VERSION: &str = "1"; const OPERATOR_KIND: &str = "sign-aware-parent-pool-merge"; const OPERATOR_STATUS: &str = "candidate-written"; const SIGN_SELECTION_RULE: &str = "seed-weighted-delta-sign-consensus"; const DELTA_MERGE_RULE: &str = "frontier-base-plus-selected-sign-weighted-average-delta"; const PARENT_CONTRACT: &str = "matches-parent-pool-direct-parameter-contract"; const OPERATOR_OUTPUT_STATUS: &str = "slm-validated"; const REQUIRED_NEXT_GATE: &str = "multi-parent-candidate-manifest-plus-runtime-smoke-plus-eval"; const PPM_DENOMINATOR: u64 = 1_000_000; const RELATEDNESS_KEYS: [&str; 5] = [ "relatedness_metric", "relatedness_scope", "relatedness_pair_count", "relatedness_all_pairs_status", "relatedness_contract_checksum", ]; const EVOLUTION_RECIPE_KEYS: [&str; 7] = [ "evolution_recipe_version", "evolution_recipe_strategy", "evolution_recipe_status", "evolution_selection_source", "evolution_relatedness_contract_checksum", "evolution_schedule_checksum_algorithm", "evolution_schedule_checksum", ]; #[derive(Clone)] struct RecipeParent { rank: String, role: String, selection_status: String, source_review_entry: String, source_ledger_entry: String, candidate_id: String, selector_id: String, operator_id: String, resource_budget: String, candidate_artifact_path: String, candidate_artifact_bytes: String, candidate_slm_checksum: String, candidate_model_shape: String, candidate_quantization: String, candidate_output_contract: String, candidate_tokenizer_checksum: String, candidate_tensor_layout_checksum: String, relatedness_group: String, relatedness_contract_checksum: String, population_fitness_ppm: String, seed_weight_ppm: u64, next_route: String, } struct ParentArtifact { path: String, seed_weight_ppm: u64, report: ValidationReport, model: ParsedModel, } #[derive(Default)] struct SignMergeStats { total_parameter_count: u64, participating_parent_count: u64, delta_observation_count: u64, nonzero_delta_observation_count: u64, zero_delta_observation_count: u64, positive_parameter_count: u64, negative_parameter_count: u64, neutral_parameter_count: u64, selected_delta_observation_count: u64, rejected_delta_observation_count: u64, } /// Writes a sign-aware multi-parent `.slm` candidate plus a recomputable receipt. pub(crate) fn write_candidate_path( ledger: &Path, review: &Path, recipe: &Path, output_slm: &Path, output_receipt: &Path, parent_paths: &[String], admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_texts(admission_paths, "sign-merge-candidate admissions")?; let parent_bytes = read_bytes(parent_paths, "sign-merge-candidate parents")?; let ledger_text = fs::read_to_string(ledger)?; let review_text = fs::read_to_string(review)?; let recipe_text = fs::read_to_string(recipe)?; let (candidate, receipt) = build_candidate_bytes_and_receipt( &ledger_text, &review_text, &recipe_text, &parent_bytes, output_slm.display().to_string().as_str(), &admission_texts, )?; if let Some(parent) = output_slm.parent() { fs::create_dir_all(parent)?; } if let Some(parent) = output_receipt.parent() { fs::create_dir_all(parent)?; } fs::write(output_slm, candidate)?; fs::write(output_receipt, receipt)?; println!( "SLM sign-aware parent-pool candidate written: {}", output_slm.display() ); println!( "SLM sign-aware parent-pool receipt written: {}", output_receipt.display() ); Ok(()) } /// Validates a sign-aware multi-parent candidate by recomputing bytes and receipt text. pub(crate) fn validate_candidate_path( ledger: &Path, review: &Path, recipe: &Path, candidate_slm: &Path, receipt: &Path, parent_paths: &[String], admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_texts(admission_paths, "validate-sign-merge-candidate admissions")?; let parent_bytes = read_bytes(parent_paths, "validate-sign-merge-candidate parents")?; let ledger_text = fs::read_to_string(ledger)?; let review_text = fs::read_to_string(review)?; let recipe_text = fs::read_to_string(recipe)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; validate_candidate_text( &ledger_text, &review_text, &recipe_text, &parent_bytes, &candidate_bytes, candidate_slm.display().to_string().as_str(), &receipt_text, &admission_texts, )?; println!("SLM sign-aware parent-pool candidate validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("receipt: {}", receipt.display()); Ok(()) } fn read_texts(paths: &[String], label: &str) -> io::Result> { if paths.is_empty() { return Err(invalid(&format!("{label} require at least one input"))); } paths .iter() .map(|path| fs::read_to_string(Path::new(path))) .collect() } fn read_bytes(paths: &[String], label: &str) -> io::Result)>> { if paths.len() < 2 { return Err(invalid(&format!( "{label} require at least two parent models" ))); } paths .iter() .map(|path| Ok((path.clone(), fs::read(Path::new(path))?))) .collect() } pub(crate) fn validate_candidate_text( ledger_text: &str, review_text: &str, recipe_text: &str, parent_bytes: &[(String, Vec)], candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, admission_texts: &[String], ) -> io::Result<()> { let (expected_candidate, expected_receipt) = build_candidate_bytes_and_receipt( ledger_text, review_text, recipe_text, parent_bytes, candidate_path, admission_texts, )?; if candidate_bytes != expected_candidate { return Err(invalid( "sign-aware parent-pool candidate bytes do not match recomputed output", )); } if receipt_text != expected_receipt { return Err(invalid( "sign-aware parent-pool receipt fields do not match recomputed output", )); } Ok(()) } pub(crate) fn build_candidate_bytes_and_receipt( ledger_text: &str, review_text: &str, recipe_text: &str, parent_bytes: &[(String, Vec)], candidate_path: &str, admission_texts: &[String], ) -> io::Result<(Vec, String)> { parent_pool::validate_recipe_text(ledger_text, review_text, recipe_text, admission_texts)?; let recipe_fields = parse_manifest(recipe_text, "parent-pool recipe")?; let recipe_parents = parse_recipe_parents(&recipe_fields)?; if recipe_parents.len() < 2 { return Err(invalid( "sign-aware parent-pool merge requires at least two parents", )); } if recipe_parents.len() != parent_bytes.len() { return Err(invalid( "sign-aware parent-pool merge parent count does not match recipe", )); } let artifacts = parent_artifacts(parent_bytes, &recipe_parents)?; let (output_values, stats) = sign_merge_values(&artifacts)?; let output_tensors = output_specs(&artifacts[0].model); let candidate = build_model_file_from_values_with_flags( &artifacts[0].model.shape, &output_tensors, &artifacts[0].model.tokenizer, &output_values, artifacts[0].model.flags, )?; let candidate_report = slm_validate::validate_bytes(&candidate, candidate_path)?; validate_candidate_contract(&recipe_fields, &candidate_report)?; let receipt = build_receipt_text( &recipe_fields, &recipe_parents, recipe_text, &artifacts, &candidate_report, stats, )?; Ok((candidate, receipt)) } fn parse_recipe_parents(fields: &HashMap) -> io::Result> { require_equal(fields, "tinyrustlm_parent_pool_recipe_version", "1")?; require_equal(fields, "recipe_kind", "sign-aware-parent-pool-v1")?; require_equal( fields, "parent_contract_status", "shared-direct-parameter-contract", )?; let count = parse_usize(require_key(fields, "parent_count")?, "parent_count")?; if count == 0 { return Err(invalid("parent-pool recipe has no parents")); } let mut parents = Vec::with_capacity(count); let mut seed_total = 0u64; for index in 0..count { let prefix = format!("parent.{index}"); let rank = required_prefixed(fields, &prefix, "rank")?; let expected_rank = (index + 1).to_string(); if rank != expected_rank { return Err(invalid(&format!( "parent-pool recipe parent {index} rank was {rank}, expected {expected_rank}" ))); } let role = required_prefixed(fields, &prefix, "role")?; if index == 0 && role != "frontier" { return Err(invalid("parent-pool recipe parent 0 must be frontier")); } if index > 0 && role != "parent-pool" { return Err(invalid( "parent-pool recipe non-frontier parents must use parent-pool role", )); } let seed_weight_ppm = parse_seed_weight(&required_prefixed(fields, &prefix, "seed_weight_ppm")?)?; seed_total = seed_total .checked_add(seed_weight_ppm) .ok_or_else(|| invalid("parent-pool recipe seed weight total overflow"))?; parents.push(RecipeParent { rank, role, selection_status: required_prefixed(fields, &prefix, "selection_status")?, source_review_entry: required_prefixed(fields, &prefix, "source_review_entry")?, source_ledger_entry: required_prefixed(fields, &prefix, "source_ledger_entry")?, candidate_id: required_prefixed(fields, &prefix, "candidate_id")?, selector_id: required_prefixed(fields, &prefix, "selector_id")?, operator_id: required_prefixed(fields, &prefix, "operator_id")?, resource_budget: required_prefixed(fields, &prefix, "resource_budget")?, candidate_artifact_path: required_prefixed(fields, &prefix, "candidate_artifact_path")?, candidate_artifact_bytes: required_prefixed( fields, &prefix, "candidate_artifact_bytes", )?, candidate_slm_checksum: required_prefixed(fields, &prefix, "candidate_slm_checksum")?, candidate_model_shape: required_prefixed(fields, &prefix, "candidate_model_shape")?, candidate_quantization: required_prefixed(fields, &prefix, "candidate_quantization")?, candidate_output_contract: required_prefixed( fields, &prefix, "candidate_output_contract", )?, candidate_tokenizer_checksum: required_prefixed( fields, &prefix, "candidate_tokenizer_checksum", )?, candidate_tensor_layout_checksum: required_prefixed( fields, &prefix, "candidate_tensor_layout_checksum", )?, relatedness_group: required_prefixed(fields, &prefix, "relatedness_group")?, relatedness_contract_checksum: required_prefixed( fields, &prefix, "relatedness_contract_checksum", )?, population_fitness_ppm: required_prefixed(fields, &prefix, "population_fitness_ppm")?, seed_weight_ppm, next_route: required_prefixed(fields, &prefix, "next_route")?, }); } if seed_total != PPM_DENOMINATOR { return Err(invalid( "parent-pool recipe seed weights must sum to 1000000", )); } Ok(parents) } fn parent_artifacts( parent_bytes: &[(String, Vec)], recipe_parents: &[RecipeParent], ) -> io::Result> { let mut artifacts = Vec::with_capacity(parent_bytes.len()); for ((path, bytes), recipe_parent) in parent_bytes.iter().zip(recipe_parents.iter()) { let report = slm_validate::validate_bytes(bytes, path)?; require_recipe_parent_report(recipe_parent, &report)?; let model = parse_model_values(bytes)?; artifacts.push(ParentArtifact { path: path.clone(), seed_weight_ppm: recipe_parent.seed_weight_ppm, report, model, }); } Ok(artifacts) } fn require_recipe_parent_report( recipe_parent: &RecipeParent, report: &ValidationReport, ) -> io::Result<()> { require_text_equal( "candidate_artifact_bytes", &recipe_parent.candidate_artifact_bytes, &report.file_bytes().to_string(), )?; require_text_equal( "candidate_slm_checksum", &recipe_parent.candidate_slm_checksum, &hex64(report.checksum()), )?; require_text_equal( "candidate_model_shape", &recipe_parent.candidate_model_shape, &report.shape_summary(), )?; require_text_equal( "candidate_quantization", &recipe_parent.candidate_quantization, report.quantization_label(), )?; require_text_equal( "candidate_output_contract", &recipe_parent.candidate_output_contract, report.output_contract_label(), )?; require_text_equal( "candidate_tokenizer_checksum", &recipe_parent.candidate_tokenizer_checksum, &hex64(report.tokenizer_checksum()), )?; require_text_equal( "candidate_tensor_layout_checksum", &recipe_parent.candidate_tensor_layout_checksum, &hex64(report.tensor_layout_checksum()), )?; Ok(()) } fn validate_candidate_contract( recipe_fields: &HashMap, report: &ValidationReport, ) -> io::Result<()> { require_report_equal( recipe_fields, "contract_model_shape", &report.shape_summary(), )?; require_report_equal( recipe_fields, "contract_quantization", report.quantization_label(), )?; require_report_equal( recipe_fields, "contract_output_contract", report.output_contract_label(), )?; require_report_equal( recipe_fields, "contract_tokenizer_checksum", &hex64(report.tokenizer_checksum()), )?; require_report_equal( recipe_fields, "contract_tensor_layout_checksum", &hex64(report.tensor_layout_checksum()), )?; Ok(()) } fn sign_merge_values(artifacts: &[ParentArtifact]) -> io::Result<(Vec>, SignMergeStats)> { let base = &artifacts .first() .ok_or_else(|| invalid("sign-aware parent-pool merge requires a frontier parent"))? .model; let mut parent_tensor_maps = Vec::with_capacity(artifacts.len().saturating_sub(1)); for artifact in artifacts.iter().skip(1) { require_compatible_parent(base, &artifact.model)?; parent_tensor_maps.push( artifact .model .tensors .iter() .enumerate() .map(|(index, tensor)| (tensor.spec.name_hash, index)) .collect::>(), ); } let mut output = Vec::with_capacity(base.tensors.len()); let mut stats = SignMergeStats { participating_parent_count: artifacts.len().saturating_sub(1) as u64, ..SignMergeStats::default() }; for base_tensor in &base.tensors { let mut tensor_values = Vec::with_capacity(base_tensor.values.len()); for (value_index, base_value) in base_tensor.values.iter().enumerate() { let mut positive_vote = 0u64; let mut negative_vote = 0u64; let mut positive_weighted_delta = 0.0f64; let mut negative_weighted_delta = 0.0f64; let mut positive_delta_count = 0u64; let mut negative_delta_count = 0u64; let mut zero_delta_count = 0u64; for (parent_index, artifact) in artifacts.iter().enumerate().skip(1) { let tensor_map = &parent_tensor_maps[parent_index - 1]; let Some(tensor_index) = tensor_map.get(&base_tensor.spec.name_hash) else { return Err(invalid( "parent-pool merge parent is missing a tensor from the frontier", )); }; let parent_tensor = &artifact.model.tensors[*tensor_index]; require_same_tensor_spec(&base_tensor.spec, &parent_tensor.spec)?; let delta = parent_tensor.values[value_index] - base_value; let weight = recipe_weight_for_parent(artifacts, parent_index)?; if delta > 0.0 { positive_vote = positive_vote .checked_add(weight) .ok_or_else(|| invalid("positive sign vote overflow"))?; positive_weighted_delta += f64::from(delta) * weight as f64; positive_delta_count += 1; } else if delta < 0.0 { negative_vote = negative_vote .checked_add(weight) .ok_or_else(|| invalid("negative sign vote overflow"))?; negative_weighted_delta += f64::from(delta) * weight as f64; negative_delta_count += 1; } else { zero_delta_count += 1; } } stats.total_parameter_count += 1; stats.delta_observation_count += stats.participating_parent_count; stats.nonzero_delta_observation_count += positive_delta_count + negative_delta_count; stats.zero_delta_observation_count += zero_delta_count; if positive_vote > negative_vote && positive_vote > 0 { stats.positive_parameter_count += 1; stats.selected_delta_observation_count += positive_delta_count; stats.rejected_delta_observation_count += negative_delta_count; tensor_values .push(*base_value + (positive_weighted_delta / positive_vote as f64) as f32); } else if negative_vote > positive_vote && negative_vote > 0 { stats.negative_parameter_count += 1; stats.selected_delta_observation_count += negative_delta_count; stats.rejected_delta_observation_count += positive_delta_count; tensor_values .push(*base_value + (negative_weighted_delta / negative_vote as f64) as f32); } else { stats.neutral_parameter_count += 1; stats.rejected_delta_observation_count += positive_delta_count + negative_delta_count; tensor_values.push(*base_value); } } output.push(tensor_values); } Ok((output, stats)) } fn require_compatible_parent(base: &ParsedModel, parent: &ParsedModel) -> io::Result<()> { if !same_shape(&base.shape, &parent.shape) { return Err(invalid( "sign-aware parent-pool merge parents have different model shapes", )); } if base.flags != parent.flags { return Err(invalid( "sign-aware parent-pool merge parents have different output flags", )); } if base.tokenizer.bytes != parent.tokenizer.bytes { return Err(invalid( "sign-aware parent-pool merge parents have different tokenizer bytes", )); } Ok(()) } fn recipe_weight_for_parent(artifacts: &[ParentArtifact], parent_index: usize) -> io::Result { Ok(artifacts .get(parent_index) .ok_or_else(|| invalid("parent-pool merge parent index escaped artifacts"))? .seed_weight_ppm) } // Builds the replay receipt that connects this sign-merge output to its scheduled family. fn build_receipt_text( recipe_fields: &HashMap, recipe_parents: &[RecipeParent], recipe_text: &str, artifacts: &[ParentArtifact], candidate_report: &ValidationReport, stats: SignMergeStats, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_sign_merge_operator_version", OPERATOR_VERSION, ); push_line(&mut text, "operator_kind", OPERATOR_KIND); push_line(&mut text, "operator_status", OPERATOR_STATUS); push_line( &mut text, "recipe_kind", require_key(recipe_fields, "recipe_kind")?, ); push_line( &mut text, "parent_pool_recipe_checksum", &hex64(provenance::text_checksum(recipe_text.as_bytes())), ); push_evolution_schedule_lines( &mut text, recipe_fields, OPERATOR_KIND, "sign-merge-candidate", SIGN_SELECTION_RULE, )?; push_line( &mut text, "population_review_checksum", require_key(recipe_fields, "population_review_checksum")?, ); push_line( &mut text, "promotion_ledger_checksum", require_key(recipe_fields, "promotion_ledger_checksum")?, ); push_line( &mut text, "admission_set_checksum", require_key(recipe_fields, "admission_set_checksum")?, ); push_line( &mut text, "frontier_candidate_id", require_key(recipe_fields, "frontier_candidate_id")?, ); push_line( &mut text, "frontier_candidate_slm_checksum", require_key(recipe_fields, "frontier_candidate_slm_checksum")?, ); push_line( &mut text, "parent_contract_status", require_key(recipe_fields, "parent_contract_status")?, ); push_line( &mut text, "contract_model_shape", require_key(recipe_fields, "contract_model_shape")?, ); push_line( &mut text, "contract_quantization", require_key(recipe_fields, "contract_quantization")?, ); push_line( &mut text, "contract_output_contract", require_key(recipe_fields, "contract_output_contract")?, ); push_line( &mut text, "contract_tokenizer_checksum", require_key(recipe_fields, "contract_tokenizer_checksum")?, ); push_line( &mut text, "contract_tensor_layout_checksum", require_key(recipe_fields, "contract_tensor_layout_checksum")?, ); for key in RELATEDNESS_KEYS { push_line(&mut text, key, require_key(recipe_fields, key)?); } push_line(&mut text, "parent_count", &recipe_parents.len().to_string()); for (index, (recipe_parent, artifact)) in recipe_parents.iter().zip(artifacts).enumerate() { push_parent_receipt_lines(&mut text, index, recipe_parent, artifact); } push_line(&mut text, "base_parent_index", "0"); push_line(&mut text, "sign_selection_rule", SIGN_SELECTION_RULE); push_line(&mut text, "delta_merge_rule", DELTA_MERGE_RULE); push_line( &mut text, "sign_total_parameter_count", &stats.total_parameter_count.to_string(), ); push_line( &mut text, "sign_participating_parent_count", &stats.participating_parent_count.to_string(), ); push_line( &mut text, "sign_delta_observation_count", &stats.delta_observation_count.to_string(), ); push_line( &mut text, "sign_nonzero_delta_observation_count", &stats.nonzero_delta_observation_count.to_string(), ); push_line( &mut text, "sign_zero_delta_observation_count", &stats.zero_delta_observation_count.to_string(), ); push_line( &mut text, "sign_positive_parameter_count", &stats.positive_parameter_count.to_string(), ); push_line( &mut text, "sign_negative_parameter_count", &stats.negative_parameter_count.to_string(), ); push_line( &mut text, "sign_neutral_parameter_count", &stats.neutral_parameter_count.to_string(), ); push_line( &mut text, "sign_selected_delta_observation_count", &stats.selected_delta_observation_count.to_string(), ); push_line( &mut text, "sign_rejected_delta_observation_count", &stats.rejected_delta_observation_count.to_string(), ); push_candidate_lines(&mut text, candidate_report); push_line(&mut text, "candidate_parent_contract", PARENT_CONTRACT); push_line(&mut text, "operator_output_status", OPERATOR_OUTPUT_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } // Copies the matching recipe schedule family into the operator receipt. fn push_evolution_schedule_lines( text: &mut String, recipe_fields: &HashMap, operator_kind: &str, command: &str, selection_rule: &str, ) -> io::Result<()> { for key in EVOLUTION_RECIPE_KEYS { push_line(text, key, require_key(recipe_fields, key)?); } let family_count = parse_usize( require_key(recipe_fields, "evolution_operator_family_count")?, "evolution_operator_family_count", )?; for index in 0..family_count { let prefix = format!("evolution_operator_family.{index}"); if required_prefixed(recipe_fields, &prefix, "operator_kind")? != operator_kind { continue; } require_equal(recipe_fields, &format!("{prefix}.command"), command)?; require_equal( recipe_fields, &format!("{prefix}.selection_rule"), selection_rule, )?; require_equal( recipe_fields, &format!("{prefix}.output_gate"), REQUIRED_NEXT_GATE, )?; push_line(text, "scheduled_operator_family_index", &index.to_string()); push_line(text, "scheduled_operator_family_kind", operator_kind); push_line(text, "scheduled_operator_family_command", command); push_line( text, "scheduled_operator_family_selection_rule", selection_rule, ); push_line( text, "scheduled_operator_family_output_gate", REQUIRED_NEXT_GATE, ); return Ok(()); } Err(invalid( "parent-pool evolution schedule does not include sign-merge operator family", )) } fn push_parent_receipt_lines( text: &mut String, index: usize, recipe_parent: &RecipeParent, artifact: &ParentArtifact, ) { let prefix = format!("parent.{index}"); push_line(text, &format!("{prefix}.rank"), &recipe_parent.rank); push_line(text, &format!("{prefix}.role"), &recipe_parent.role); push_line( text, &format!("{prefix}.selection_status"), &recipe_parent.selection_status, ); push_line( text, &format!("{prefix}.source_review_entry"), &recipe_parent.source_review_entry, ); push_line( text, &format!("{prefix}.source_ledger_entry"), &recipe_parent.source_ledger_entry, ); push_line( text, &format!("{prefix}.candidate_id"), &recipe_parent.candidate_id, ); push_line( text, &format!("{prefix}.selector_id"), &recipe_parent.selector_id, ); push_line( text, &format!("{prefix}.operator_id"), &recipe_parent.operator_id, ); push_line( text, &format!("{prefix}.resource_budget"), &recipe_parent.resource_budget, ); push_line( text, &format!("{prefix}.recipe_candidate_artifact_path"), &recipe_parent.candidate_artifact_path, ); push_line(text, &format!("{prefix}.actual_path"), &artifact.path); push_line( text, &format!("{prefix}.model_bytes"), &artifact.report.file_bytes().to_string(), ); push_line( text, &format!("{prefix}.slm_version"), &artifact.report.slm_version().to_string(), ); push_line( text, &format!("{prefix}.slm_checksum"), &hex64(artifact.report.checksum()), ); push_line( text, &format!("{prefix}.model_shape"), &artifact.report.shape_summary(), ); push_line( text, &format!("{prefix}.tensor_count"), &artifact.report.tensor_count().to_string(), ); push_line( text, &format!("{prefix}.parameter_count"), &artifact.report.parameter_count().to_string(), ); push_line( text, &format!("{prefix}.quantization"), artifact.report.quantization_label(), ); push_line( text, &format!("{prefix}.output_contract"), artifact.report.output_contract_label(), ); push_line( text, &format!("{prefix}.tokenizer_checksum"), &hex64(artifact.report.tokenizer_checksum()), ); push_line( text, &format!("{prefix}.tensor_layout_checksum"), &hex64(artifact.report.tensor_layout_checksum()), ); push_line( text, &format!("{prefix}.relatedness_group"), &recipe_parent.relatedness_group, ); push_line( text, &format!("{prefix}.relatedness_contract_checksum"), &recipe_parent.relatedness_contract_checksum, ); push_line( text, &format!("{prefix}.population_fitness_ppm"), &recipe_parent.population_fitness_ppm, ); push_line( text, &format!("{prefix}.seed_weight_ppm"), &recipe_parent.seed_weight_ppm.to_string(), ); push_line( text, &format!("{prefix}.next_route"), &recipe_parent.next_route, ); } fn push_candidate_lines(text: &mut String, report: &ValidationReport) { push_line(text, "candidate_artifact_path", report.path()); push_line( text, "candidate_artifact_bytes", &report.file_bytes().to_string(), ); push_line( text, "candidate_slm_version", &report.slm_version().to_string(), ); push_line(text, "candidate_slm_checksum", &hex64(report.checksum())); push_line(text, "candidate_model_shape", &report.shape_summary()); push_line( text, "candidate_tensor_count", &report.tensor_count().to_string(), ); push_line( text, "candidate_parameter_count", &report.parameter_count().to_string(), ); push_line(text, "candidate_quantization", report.quantization_label()); push_line( text, "candidate_output_contract", report.output_contract_label(), ); push_line( text, "candidate_tokenizer_checksum", &hex64(report.tokenizer_checksum()), ); push_line( text, "candidate_tensor_layout_checksum", &hex64(report.tensor_layout_checksum()), ); } fn required_prefixed( fields: &HashMap, prefix: &str, key: &str, ) -> io::Result { Ok(require_key(fields, &format!("{prefix}.{key}"))?.to_string()) } fn parse_usize(value: &str, label: &str) -> io::Result { value .parse::() .map_err(|_| invalid(&format!("{label} must be an integer"))) } fn parse_seed_weight(value: &str) -> io::Result { let parsed = value .parse::() .map_err(|_| invalid("parent-pool seed weight must be an integer"))?; if parsed > PPM_DENOMINATOR { return Err(invalid("parent-pool seed weight exceeded 1000000")); } Ok(parsed) } fn require_text_equal(key: &str, actual: &str, expected: &str) -> io::Result<()> { if actual != expected { return Err(invalid(&format!( "parent-pool recipe key {key} was {actual}, current artifact has {expected}" ))); } Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::admission; use crate::build_model_file_from_values_with_flags; use crate::candidate; use crate::compatibility; use crate::fixture_value; use crate::ledger; use crate::lineage; use crate::population; use crate::promotion; use crate::tensor_writer::{tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_F32}; use crate::tokenizer_writer::ByteTokenizerSection; use std::time::{SystemTime, UNIX_EPOCH}; #[test] fn writes_and_validates_sign_merge_candidate_text() { let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.003); let gamma_bytes = tiny_fixture_f32_bytes_with_offset(0.006); let alpha = fixture_admission( "tiny-alpha-candidate", "target/sign-merge/alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/sign-merge/beta.slm", &beta_bytes, ); let gamma = fixture_admission( "tiny-gamma-candidate", "target/sign-merge/gamma.slm", &gamma_bytes, ); let admissions = vec![alpha.clone(), beta.clone(), gamma.clone()]; let ledger = ledger::build_ledger_text(&admissions).unwrap(); let review = population::build_review_text(&ledger, &admissions).unwrap(); let recipe = parent_pool::build_recipe_text(&ledger, &review, &admissions).unwrap(); let parents = vec![ ("alpha.slm".to_string(), alpha_bytes.clone()), ("beta.slm".to_string(), beta_bytes), ("gamma.slm".to_string(), gamma_bytes), ]; let (candidate, receipt) = build_candidate_bytes_and_receipt( &ledger, &review, &recipe, &parents, "candidate.slm", &admissions, ) .unwrap(); validate_candidate_text( &ledger, &review, &recipe, &parents, &candidate, "candidate.slm", &receipt, &admissions, ) .unwrap(); let base = parse_model_values(&alpha_bytes).unwrap(); let merged = parse_model_values(&candidate).unwrap(); assert!(merged.tensors[0].values[0] > base.tensors[0].values[0]); assert!(receipt.contains("operator_kind=sign-aware-parent-pool-merge")); assert!(receipt.contains("evolution_schedule_checksum=0x")); assert!(receipt.contains("scheduled_operator_family_index=0")); assert!(receipt.contains("scheduled_operator_family_command=sign-merge-candidate")); assert!(receipt.contains("sign_positive_parameter_count=")); assert!(receipt.contains("sign_selected_delta_observation_count=")); } #[test] fn rejects_parent_order_checksum_drift() { let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.004); let alpha = fixture_admission( "tiny-alpha-candidate", "target/sign-merge/order-alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/sign-merge/order-beta.slm", &beta_bytes, ); let admissions = vec![alpha.clone(), beta.clone()]; let ledger = ledger::build_ledger_text(&admissions).unwrap(); let review = population::build_review_text(&ledger, &admissions).unwrap(); let recipe = parent_pool::build_recipe_text(&ledger, &review, &admissions).unwrap(); let parents = vec![ ("beta.slm".to_string(), beta_bytes), ("alpha.slm".to_string(), alpha_bytes), ]; let error = build_candidate_bytes_and_receipt( &ledger, &review, &recipe, &parents, "candidate.slm", &admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate_slm_checksum")); } #[test] fn rejects_single_parent_recipe() { let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let alpha = fixture_admission( "tiny-alpha-candidate", "target/sign-merge/single-alpha.slm", &alpha_bytes, ); let admissions = vec![alpha.clone()]; let ledger = ledger::build_ledger_text(&admissions).unwrap(); let review = population::build_review_text(&ledger, &admissions).unwrap(); let recipe = parent_pool::build_recipe_text(&ledger, &review, &admissions).unwrap(); let parents = vec![("alpha.slm".to_string(), alpha_bytes)]; let error = build_candidate_bytes_and_receipt( &ledger, &review, &recipe, &parents, "candidate.slm", &admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("at least two parents")); } #[test] fn validation_rejects_candidate_drift() { let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.004); let alpha = fixture_admission( "tiny-alpha-candidate", "target/sign-merge/drift-alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/sign-merge/drift-beta.slm", &beta_bytes, ); let admissions = vec![alpha.clone(), beta.clone()]; let ledger = ledger::build_ledger_text(&admissions).unwrap(); let review = population::build_review_text(&ledger, &admissions).unwrap(); let recipe = parent_pool::build_recipe_text(&ledger, &review, &admissions).unwrap(); let parents = vec![ ("alpha.slm".to_string(), alpha_bytes), ("beta.slm".to_string(), beta_bytes), ]; let (mut candidate, receipt) = build_candidate_bytes_and_receipt( &ledger, &review, &recipe, &parents, "candidate.slm", &admissions, ) .unwrap(); let last = candidate.len() - 1; candidate[last] ^= 0x01; let error = validate_candidate_text( &ledger, &review, &recipe, &parents, &candidate, "candidate.slm", &receipt, &admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate bytes")); } #[test] fn writes_and_validates_sign_merge_candidate_paths() { let dir = unique_dir("paths"); std::fs::create_dir_all(&dir).unwrap(); let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.005); let gamma_bytes = tiny_fixture_f32_bytes_with_offset(0.002); let alpha = fixture_admission( "tiny-alpha-candidate", "target/sign-merge/path-alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/sign-merge/path-beta.slm", &beta_bytes, ); let gamma = fixture_admission( "tiny-gamma-candidate", "target/sign-merge/path-gamma.slm", &gamma_bytes, ); let alpha_slm = dir.join("alpha.slm"); let beta_slm = dir.join("beta.slm"); let gamma_slm = dir.join("gamma.slm"); let alpha_admission = dir.join("alpha.admission"); let beta_admission = dir.join("beta.admission"); let gamma_admission = dir.join("gamma.admission"); let ledger_path = dir.join("pool.ledger"); let review_path = dir.join("pool.review"); let recipe_path = dir.join("pool.recipe"); let candidate_path = dir.join("candidate.slm"); let receipt_path = dir.join("candidate.operator"); std::fs::write(&alpha_slm, alpha_bytes).unwrap(); std::fs::write(&beta_slm, beta_bytes).unwrap(); std::fs::write(&gamma_slm, gamma_bytes).unwrap(); std::fs::write(&alpha_admission, alpha).unwrap(); std::fs::write(&beta_admission, beta).unwrap(); std::fs::write(&gamma_admission, gamma).unwrap(); let admissions = vec![ alpha_admission.to_string_lossy().to_string(), beta_admission.to_string_lossy().to_string(), gamma_admission.to_string_lossy().to_string(), ]; let parents = vec![ alpha_slm.to_string_lossy().to_string(), beta_slm.to_string_lossy().to_string(), gamma_slm.to_string_lossy().to_string(), ]; ledger::write_ledger_path(&ledger_path, &admissions).unwrap(); population::write_review_path(&ledger_path, &review_path, &admissions).unwrap(); parent_pool::write_recipe_path(&ledger_path, &review_path, &recipe_path, &admissions) .unwrap(); write_candidate_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &parents, &admissions, ) .unwrap(); validate_candidate_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &parents, &admissions, ) .unwrap(); let receipt = std::fs::read_to_string(receipt_path).unwrap(); assert!(receipt.contains("operator_output_status=slm-validated")); assert!(receipt.contains("scheduled_operator_family_command=sign-merge-candidate")); slm_validate::validate_path(&candidate_path).unwrap(); } fn fixture_admission(candidate_id: &str, candidate_path: &str, candidate: &[u8]) -> String { let compatibility = compatibility::compatibility_text_for_bytes( candidate, "left.slm", candidate, "right.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, candidate_id, "operator-a", "fit") .unwrap(); let candidate_manifest = candidate::build_manifest_text(&compatibility, &lineage, candidate, candidate_path) .unwrap(); let promotion = promotion::build_template_text( &compatibility, &lineage, candidate, candidate_path, &candidate_manifest, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, ) .unwrap(); let report = slm_validate::validate_bytes(candidate, candidate_path).unwrap(); let provenance_manifest = provenance::build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = provenance::parse_manifest(&provenance_manifest).unwrap(); let runtime_smoke = provenance::build_runtime_smoke_text(&report, &provenance_manifest, &manifest_fields) .unwrap(); let eval = passing_eval_text(&report, &provenance_manifest); admission::build_record_text( &compatibility, &lineage, candidate, candidate_path, &candidate_manifest, &promotion, &provenance_manifest, &runtime_smoke, &eval, admission::DEFAULT_ADMISSION_SELECTOR_ID, ) .unwrap() } fn passing_eval_text(report: &slm_validate::ValidationReport, manifest: &str) -> String { let mut text = String::new(); push_line(&mut text, "tinyrustlm_eval_manifest_version", "1"); push_line(&mut text, "gate", "assistant-quality"); push_line(&mut text, "source_kind", "converted-trained"); push_line( &mut text, "manifest_checksum", &hex64(provenance::text_checksum(manifest.as_bytes())), ); push_line(&mut text, "slm_checksum", &hex64(report.checksum())); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "task_eval_status", "pass"); push_line(&mut text, "safety_review_status", "pass"); push_line( &mut text, "quality_decision", "accepted-for-assistant-quality", ); push_line(&mut text, "quality_scope", "tiny-fixture-runtime-eval-only"); push_line(&mut text, "evaluator", "local-reviewed-eval"); push_line( &mut text, "eval_dataset", "tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", ); push_line( &mut text, "eval_summary", "Reviewed task and safety evidence passed for declared scope", ); push_line( &mut text, "quality_boundary", "fixture-runtime-and-eval-plumbing-not-product-assistant-quality", ); push_line(&mut text, "case_count", "1"); push_line(&mut text, "cases_passed", "1"); push_line(&mut text, "cases_failed", "0"); push_line(&mut text, "case.0.status", "pass"); push_line(&mut text, "case.0.expected", "e"); push_line(&mut text, "case.0.actual", "e"); push_line(&mut text, "case.0.error", "ok"); text } fn tiny_fixture_f32_bytes_with_offset(offset: f32) -> Vec { let tensors = tiny_fixture_tensors_with_dtype(DTYPE_F32); let values: Vec> = tensors .iter() .map(|tensor| { (0..tensor.element_count()) .map(|elem| fixture_value(tensor, elem) + offset) .collect() }) .collect(); build_model_file_from_values_with_flags( &ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } fn unique_dir(label: &str) -> std::path::PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-sign-merge-{label}-{nanos}")) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/sign_merge.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/slm_validate.rs BYTES: 33527 SHA256: 7366E6C2151E3BA6129E8E6B1F1D09AB942252A62280D4951297989478FBCAB5 ================================================================================ //! Native `.slm` admission validator for generated or converted model files. use std::collections::HashSet; use std::fs; use std::io; use std::path::Path; const HEADER_LEN: usize = 108; const TENSOR_ENTRY_LEN: usize = 64; const SLM_VERSION: u32 = 1; const DTYPE_F32: u32 = 1; const DTYPE_Q8_0: u32 = 2; const DTYPE_Q4_0: u32 = 3; #[derive(Clone, Copy, Debug)] struct SlmHeader { version: u32, header_length: u32, model_type: u32, flags: u32, vocab_size: u32, special_token_count: u32, hidden_size: u32, layer_count: u32, head_count: u32, kv_head_count: u32, head_dim: u32, ffn_size: u32, max_context: u32, rope_theta: f32, rms_norm_epsilon: f32, tokenizer_offset: u64, tokenizer_length: u64, tensor_directory_offset: u64, tensor_count: u32, tensor_data_offset: u64, checksum: u64, } #[derive(Clone, Copy, Debug)] struct TensorEntry { name_hash: u64, dtype: u32, rank: u32, dims: [u32; 4], byte_offset: u64, byte_length: u64, scale_offset: u64, block_size: u32, } /// Compact report returned by the native `.slm` admission validator. #[derive(Debug)] pub(crate) struct ValidationReport { path: String, file_bytes: usize, header: SlmHeader, tensors: Vec, parameter_count: u64, quantization_label: &'static str, tokenizer_checksum: u64, tensor_layout_checksum: u64, } impl ValidationReport { /// Returns the path label supplied to the validator. pub(crate) fn path(&self) -> &str { &self.path } /// Returns the model file length in bytes. pub(crate) fn file_bytes(&self) -> usize { self.file_bytes } /// Returns the runtime KV-cache allocation implied by the model header. pub(crate) fn kv_cache_byte_budget(&self) -> io::Result { kv_cache_byte_budget_from_shape( self.header.layer_count, self.header.max_context, self.header.kv_head_count, self.header.head_dim, ) } /// Returns the maximum context token count declared by the validated header. pub(crate) fn context_token_limit(&self) -> u32 { self.header.max_context } /// Returns the KV-cache byte budget as a 64 KiB WebAssembly page count. pub(crate) fn kv_cache_page_count(&self) -> io::Result { kv_cache_page_count_for_bytes(self.kv_cache_byte_budget()?) } /// Returns the parsed `.slm` version. pub(crate) fn slm_version(&self) -> u32 { self.header.version } /// Returns the v1 format flags field. pub(crate) fn flags(&self) -> u32 { self.header.flags } /// Returns a compact deterministic model shape string for manifests. pub(crate) fn shape_summary(&self) -> String { format!( "vocab={},hidden={},layers={},heads={},kv_heads={},head_dim={},ffn={},context={}", self.header.vocab_size, self.header.hidden_size, self.header.layer_count, self.header.head_count, self.header.kv_head_count, self.header.head_dim, self.header.ffn_size, self.header.max_context ) } /// Returns the number of tensor directory entries. pub(crate) fn tensor_count(&self) -> usize { self.tensors.len() } /// Returns the total logical parameter count. pub(crate) fn parameter_count(&self) -> u64 { self.parameter_count } /// Returns the detected quantization label. pub(crate) fn quantization_label(&self) -> &'static str { self.quantization_label } /// Returns the output-head contract label implied by the v1 flags. pub(crate) fn output_contract_label(&self) -> &'static str { if self.header.flags & 1 != 0 { "tied-output" } else { "explicit-output" } } /// Returns a stable checksum over the tokenizer section bytes. pub(crate) fn tokenizer_checksum(&self) -> u64 { self.tokenizer_checksum } /// Returns a stable checksum over logical tensor names, dtypes, ranks, shapes, and blocks. pub(crate) fn tensor_layout_checksum(&self) -> u64 { self.tensor_layout_checksum } /// Returns the `.slm` header checksum. pub(crate) fn checksum(&self) -> u64 { self.header.checksum } } /// Validates an `.slm` file from disk and prints a compact admission report. pub fn validate_path(path: &Path) -> io::Result<()> { let bytes = fs::read(path)?; let report = validate_bytes(&bytes, &path.display().to_string())?; print_report(&report); Ok(()) } /// Validates an `.slm` byte slice and returns a compact report. pub(crate) fn validate_bytes(bytes: &[u8], path: &str) -> io::Result { let header = parse_header(bytes)?; validate_header(bytes, &header)?; validate_checksum(bytes, &header)?; validate_tokenizer(bytes, &header)?; let tensors = parse_tensors(bytes, &header)?; validate_unique_tensors(&tensors)?; validate_required_tensors(&header, &tensors)?; validate_tensor_payloads(bytes, &tensors)?; let tokenizer_checksum = tokenizer_checksum(bytes, &header)?; let tensor_layout_checksum = tensor_layout_checksum(&tensors); let parameter_count = tensors.iter().try_fold(0u64, |acc, tensor| { acc.checked_add(element_count(tensor)) .ok_or_else(|| invalid("parameter count overflow")) })?; Ok(ValidationReport { path: path.to_string(), file_bytes: bytes.len(), header, quantization_label: quantization_label(&tensors), tensors, parameter_count, tokenizer_checksum, tensor_layout_checksum, }) } fn print_report(report: &ValidationReport) { println!("SLM validation: PASS"); println!("path: {}", report.path); println!("bytes: {}", report.file_bytes); println!("version: {}", report.header.version); println!( "shape: vocab={} hidden={} layers={} heads={} kv_heads={} head_dim={} ffn={} context={}", report.header.vocab_size, report.header.hidden_size, report.header.layer_count, report.header.head_count, report.header.kv_head_count, report.header.head_dim, report.header.ffn_size, report.header.max_context ); println!("tensor_count: {}", report.tensors.len()); println!("parameter_count: {}", report.parameter_count); println!("quantization: {}", report.quantization_label); println!("checksum: 0x{:016x}", report.header.checksum); } fn parse_header(bytes: &[u8]) -> io::Result { if bytes.len() < HEADER_LEN { return Err(invalid("file is shorter than the v1 header")); } if bytes.get(0..4) != Some(b"SLM1") { return Err(invalid("invalid SLM magic")); } Ok(SlmHeader { version: read_u32(bytes, 4)?, header_length: read_u32(bytes, 8)?, model_type: read_u32(bytes, 12)?, flags: read_u32(bytes, 16)?, vocab_size: read_u32(bytes, 20)?, special_token_count: read_u32(bytes, 24)?, hidden_size: read_u32(bytes, 28)?, layer_count: read_u32(bytes, 32)?, head_count: read_u32(bytes, 36)?, kv_head_count: read_u32(bytes, 40)?, head_dim: read_u32(bytes, 44)?, ffn_size: read_u32(bytes, 48)?, max_context: read_u32(bytes, 52)?, rope_theta: f32::from_bits(read_u32(bytes, 56)?), rms_norm_epsilon: f32::from_bits(read_u32(bytes, 60)?), tokenizer_offset: read_u64(bytes, 64)?, tokenizer_length: read_u64(bytes, 72)?, tensor_directory_offset: read_u64(bytes, 80)?, tensor_count: read_u32(bytes, 88)?, tensor_data_offset: read_u64(bytes, 92)?, checksum: read_u64(bytes, 100)?, }) } fn validate_header(bytes: &[u8], header: &SlmHeader) -> io::Result<()> { if header.version != SLM_VERSION { return Err(invalid("unsupported SLM version")); } if header.header_length < HEADER_LEN as u32 || header.header_length as usize > bytes.len() { return Err(invalid("invalid header length")); } if header.model_type != 1 { return Err(invalid("unsupported model type")); } if header.vocab_size < 260 || header.special_token_count < 4 { return Err(invalid( "byte tokenizer requires vocab >= 260 and four specials", )); } if header.hidden_size == 0 || header.layer_count == 0 || header.head_count == 0 || header.kv_head_count == 0 || header.head_dim == 0 || header.ffn_size == 0 || header.max_context == 0 { return Err(invalid("model dimensions must be nonzero")); } if header.head_count.checked_mul(header.head_dim) != Some(header.hidden_size) { return Err(invalid("hidden_size must equal head_count * head_dim")); } if header.kv_head_count > header.head_count || header.head_count % header.kv_head_count != 0 { return Err(invalid("kv_head_count must divide head_count")); } if !header.rope_theta.is_finite() || header.rope_theta <= 0.0 { return Err(invalid("rope_theta must be finite and positive")); } if !header.rms_norm_epsilon.is_finite() || header.rms_norm_epsilon <= 0.0 { return Err(invalid("rms_norm_epsilon must be finite and positive")); } if header.checksum == 0 { return Err(invalid("checksum must be nonzero")); } if header.tokenizer_offset < u64::from(header.header_length) { return Err(invalid("tokenizer overlaps the header")); } if !range_within( bytes.len(), header.tokenizer_offset, header.tokenizer_length, ) { return Err(invalid("tokenizer range escapes the file")); } if header.tensor_directory_offset % 64 != 0 || header.tensor_data_offset % 64 != 0 { return Err(invalid( "tensor directory and data offsets must be 64-byte aligned", )); } let directory_len = u64::from(header.tensor_count) .checked_mul(TENSOR_ENTRY_LEN as u64) .ok_or_else(|| invalid("tensor directory length overflow"))?; if !range_within(bytes.len(), header.tensor_directory_offset, directory_len) { return Err(invalid("tensor directory range escapes the file")); } if header.tensor_data_offset < header.tensor_directory_offset + directory_len { return Err(invalid( "tensor data begins before the tensor directory ends", )); } Ok(()) } fn validate_checksum(bytes: &[u8], header: &SlmHeader) -> io::Result<()> { let actual = simple_checksum(bytes); if header.checksum != actual { return Err(invalid("checksum mismatch")); } Ok(()) } fn kv_cache_byte_budget_from_shape( layer_count: u32, max_context: u32, kv_head_count: u32, head_dim: u32, ) -> io::Result { // Mirrors runtime KV allocation math so module-plan receipts use validated model shape. let key_value_copies = 2u64; let f32_bytes = 4u64; u64::from(layer_count) .checked_mul(u64::from(max_context)) .and_then(|value| value.checked_mul(u64::from(kv_head_count))) .and_then(|value| value.checked_mul(u64::from(head_dim))) .and_then(|value| value.checked_mul(key_value_copies)) .and_then(|value| value.checked_mul(f32_bytes)) .ok_or_else(|| invalid("kv cache byte budget overflow")) } fn kv_cache_page_count_for_bytes(bytes: u64) -> io::Result { // Converts the byte envelope to WebAssembly page units for browser display and checks. let page_bytes = 64 * 1024u64; bytes .checked_add(page_bytes - 1) .map(|value| value / page_bytes) .ok_or_else(|| invalid("kv cache page count overflow")) } fn validate_tokenizer(bytes: &[u8], header: &SlmHeader) -> io::Result<()> { let start = as_usize(header.tokenizer_offset)?; let len = as_usize(header.tokenizer_length)?; let end = start .checked_add(len) .ok_or_else(|| invalid("tokenizer section length overflow"))?; let section = bytes .get(start..end) .ok_or_else(|| invalid("tokenizer section escapes the file"))?; match section.get(0..4) { Some(b"BTOK") => validate_byte_tokenizer(section), Some(b"BPE1") => validate_bpe_tokenizer(section, header.vocab_size), _ => Err(invalid("unsupported tokenizer section magic")), } } fn validate_byte_tokenizer(section: &[u8]) -> io::Result<()> { if section.len() < 28 { return Err(invalid("byte tokenizer section is too short")); } if read_u32(section, 4)? != 1 { return Err(invalid("unsupported byte tokenizer section version")); } if read_u32(section, 8)? != 260 { return Err(invalid("phase-one byte tokenizer must declare 260 tokens")); } if read_u32(section, 12)? != 256 || read_u32(section, 16)? != 257 || read_u32(section, 20)? != 258 || read_u32(section, 24)? != 259 { return Err(invalid("phase-one byte tokenizer special ids are invalid")); } Ok(()) } fn validate_bpe_tokenizer(section: &[u8], header_vocab_size: u32) -> io::Result<()> { if section.len() < 36 { return Err(invalid("BPE tokenizer section is too short")); } if read_u32(section, 4)? != 1 { return Err(invalid("unsupported BPE tokenizer section version")); } let vocab_size = read_u32(section, 8)?; if vocab_size != header_vocab_size || vocab_size < 260 { return Err(invalid("BPE tokenizer vocab must match the model header")); } for offset in [12usize, 16, 20, 24] { if read_u32(section, offset)? >= vocab_size { return Err(invalid("BPE tokenizer special id escapes vocabulary")); } } let token_count = read_u32(section, 28)? as usize; let merge_count = read_u32(section, 32)? as usize; let mut offset = 36usize; let mut token_ids = HashSet::new(); for _ in 0..token_count { let id = read_u32(section, offset)?; let len = read_u32(section, offset + 4)? as usize; offset = offset .checked_add(8) .ok_or_else(|| invalid("BPE token table offset overflow"))?; let end = offset .checked_add(len) .ok_or_else(|| invalid("BPE token byte length overflow"))?; let token_bytes = section .get(offset..end) .ok_or_else(|| invalid("BPE token bytes escape tokenizer section"))?; if id < 260 || id >= vocab_size || token_bytes.is_empty() { return Err(invalid("BPE token table entry is invalid")); } if !token_ids.insert(id) { return Err(invalid("BPE token ids must be unique")); } offset = end; } for _ in 0..merge_count { let end = offset .checked_add(16) .ok_or_else(|| invalid("BPE merge table offset overflow"))?; if end > section.len() { return Err(invalid("BPE merge table escapes tokenizer section")); } let left = read_u32(section, offset)?; let right = read_u32(section, offset + 4)?; let output = read_u32(section, offset + 8)?; if left >= vocab_size || right >= vocab_size || output >= vocab_size || output < 260 { return Err(invalid("BPE merge ids must stay inside vocabulary")); } if !token_ids.contains(&output) { return Err(invalid("BPE merge output must exist in token table")); } offset = end; } if offset != section.len() { return Err(invalid("BPE tokenizer section has trailing bytes")); } Ok(()) } fn parse_tensors(bytes: &[u8], header: &SlmHeader) -> io::Result> { let start = as_usize(header.tensor_directory_offset)?; let mut tensors = Vec::with_capacity(header.tensor_count as usize); for index in 0..header.tensor_count as usize { let base = start + index * TENSOR_ENTRY_LEN; let entry = TensorEntry { name_hash: read_u64(bytes, base)?, dtype: read_u32(bytes, base + 8)?, rank: read_u32(bytes, base + 12)?, dims: [ read_u32(bytes, base + 16)?, read_u32(bytes, base + 20)?, read_u32(bytes, base + 24)?, read_u32(bytes, base + 28)?, ], byte_offset: read_u64(bytes, base + 32)?, byte_length: read_u64(bytes, base + 40)?, scale_offset: read_u64(bytes, base + 48)?, block_size: read_u32(bytes, base + 56)?, }; validate_tensor_directory_entry(bytes.len(), &entry)?; tensors.push(entry); } Ok(tensors) } fn validate_tensor_directory_entry(file_len: usize, tensor: &TensorEntry) -> io::Result<()> { if tensor.rank == 0 || tensor.rank > 4 { return Err(invalid("tensor rank must be between one and four")); } if !matches!(tensor.dtype, DTYPE_F32 | DTYPE_Q8_0 | DTYPE_Q4_0) { return Err(invalid("unsupported tensor dtype")); } for dim in tensor.dims.iter().take(tensor.rank as usize) { if *dim == 0 { return Err(invalid("tensor dimensions must be nonzero")); } } if tensor.byte_offset % 64 != 0 { return Err(invalid("tensor payload offset must be 64-byte aligned")); } if !range_within(file_len, tensor.byte_offset, tensor.byte_length) { return Err(invalid("tensor payload escapes the file")); } let expected = expected_payload_len(tensor)?; if tensor.byte_length != expected { return Err(invalid("tensor byte length does not match dtype and shape")); } match tensor.dtype { DTYPE_F32 => { if tensor.scale_offset != 0 || tensor.block_size != 0 { return Err(invalid( "f32 tensors must not declare quantization metadata", )); } } DTYPE_Q8_0 => { if tensor.scale_offset == 0 { return Err(invalid("q8_0 tensors require scale metadata")); } if tensor.block_size != cols_per_row(tensor)? as u32 { return Err(invalid("q8_0 block_size must equal columns per row")); } let scale_len = rows(tensor)? .checked_mul(4) .ok_or_else(|| invalid("q8_0 scale length overflow"))?; if !range_within(file_len, tensor.scale_offset, scale_len as u64) { return Err(invalid("q8_0 scale range escapes the file")); } } DTYPE_Q4_0 => { if tensor.scale_offset == 0 || tensor.block_size == 0 { return Err(invalid( "q4_0 tensors require scale metadata and block size", )); } let cols = cols_per_row(tensor)?; let block = tensor.block_size as usize; if block % 2 != 0 || cols % block != 0 { return Err(invalid( "q4_0 block size must be even and divide columns per row", )); } let scale_count = rows(tensor)? .checked_mul(cols / block) .ok_or_else(|| invalid("q4_0 scale count overflow"))?; let scale_len = scale_count .checked_mul(4) .ok_or_else(|| invalid("q4_0 scale length overflow"))?; if !range_within(file_len, tensor.scale_offset, scale_len as u64) { return Err(invalid("q4_0 scale range escapes the file")); } } _ => {} } Ok(()) } fn validate_unique_tensors(tensors: &[TensorEntry]) -> io::Result<()> { let mut seen = HashSet::new(); for tensor in tensors { if !seen.insert(tensor.name_hash) { return Err(invalid("duplicate tensor name hash")); } } Ok(()) } fn validate_required_tensors(header: &SlmHeader, tensors: &[TensorEntry]) -> io::Result<()> { require_tensor( tensors, "tok_embeddings.weight", &[header.vocab_size, header.hidden_size], )?; require_tensor(tensors, "norm.weight", &[header.hidden_size])?; if header.flags & 1 == 0 { require_tensor( tensors, "output.weight", &[header.vocab_size, header.hidden_size], )?; } for layer in 0..header.layer_count { let prefix = format!("layers.{layer}"); require_tensor( tensors, &format!("{prefix}.attention_norm.weight"), &[header.hidden_size], )?; require_tensor( tensors, &format!("{prefix}.ffn_norm.weight"), &[header.hidden_size], )?; for suffix in ["wq.weight", "wk.weight", "wv.weight", "wo.weight"] { require_tensor( tensors, &format!("{prefix}.{suffix}"), &[header.hidden_size, header.hidden_size], )?; } require_tensor( tensors, &format!("{prefix}.w1.weight"), &[header.ffn_size, header.hidden_size], )?; require_tensor( tensors, &format!("{prefix}.w2.weight"), &[header.hidden_size, header.ffn_size], )?; require_tensor( tensors, &format!("{prefix}.w3.weight"), &[header.ffn_size, header.hidden_size], )?; } Ok(()) } fn require_tensor(tensors: &[TensorEntry], name: &str, expected_dims: &[u32]) -> io::Result<()> { let hash = name_hash(name); let tensor = tensors .iter() .find(|entry| entry.name_hash == hash) .ok_or_else(|| invalid(&format!("missing required tensor {name}")))?; if dims(tensor) != expected_dims { return Err(invalid(&format!("shape mismatch for tensor {name}"))); } Ok(()) } fn validate_tensor_payloads(bytes: &[u8], tensors: &[TensorEntry]) -> io::Result<()> { for tensor in tensors { match tensor.dtype { DTYPE_F32 => validate_f32_payload(bytes, tensor)?, DTYPE_Q8_0 => validate_scales(bytes, tensor.scale_offset, rows(tensor)?)?, DTYPE_Q4_0 => { let block = tensor.block_size as usize; let scale_count = rows(tensor)? .checked_mul(cols_per_row(tensor)? / block) .ok_or_else(|| invalid("q4_0 scale count overflow"))?; validate_scales(bytes, tensor.scale_offset, scale_count)?; } _ => return Err(invalid("unsupported tensor dtype")), } } Ok(()) } fn validate_f32_payload(bytes: &[u8], tensor: &TensorEntry) -> io::Result<()> { let start = as_usize(tensor.byte_offset)?; let len = as_usize(tensor.byte_length)?; let payload = bytes .get(start..start + len) .ok_or_else(|| invalid("f32 tensor payload escapes the file"))?; for chunk in payload.chunks_exact(4) { let value = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); if !value.is_finite() { return Err(invalid("f32 tensor payload contains non-finite values")); } } Ok(()) } fn validate_scales(bytes: &[u8], scale_offset: u64, count: usize) -> io::Result<()> { let start = as_usize(scale_offset)?; let len = count .checked_mul(4) .ok_or_else(|| invalid("scale payload length overflow"))?; let payload = bytes .get(start..start + len) .ok_or_else(|| invalid("scale payload escapes the file"))?; for chunk in payload.chunks_exact(4) { let value = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); if !value.is_finite() || value <= 0.0 { return Err(invalid( "quantization scale payload contains non-positive values", )); } } Ok(()) } fn expected_payload_len(tensor: &TensorEntry) -> io::Result { let elements = element_count(tensor); match tensor.dtype { DTYPE_F32 => elements .checked_mul(4) .ok_or_else(|| invalid("f32 payload length overflow")), DTYPE_Q8_0 => Ok(elements), DTYPE_Q4_0 => { if elements % 2 != 0 { return Err(invalid("q4_0 tensor element count must be even")); } Ok(elements / 2) } _ => Err(invalid("unsupported tensor dtype")), } } fn element_count(tensor: &TensorEntry) -> u64 { let mut total = 1u64; for dim in tensor.dims.iter().take(tensor.rank as usize) { total = total.saturating_mul(u64::from(*dim)); } total } fn rows(tensor: &TensorEntry) -> io::Result { if tensor.rank <= 1 { Ok(1) } else { as_usize(u64::from(tensor.dims[0])) } } fn cols_per_row(tensor: &TensorEntry) -> io::Result { if tensor.rank <= 1 { return as_usize(element_count(tensor)); } let mut cols = 1u64; for dim in tensor.dims.iter().skip(1).take(tensor.rank as usize - 1) { cols = cols .checked_mul(u64::from(*dim)) .ok_or_else(|| invalid("columns per row overflow"))?; } as_usize(cols) } fn dims(tensor: &TensorEntry) -> Vec { tensor .dims .iter() .take(tensor.rank as usize) .copied() .collect() } fn quantization_label(tensors: &[TensorEntry]) -> &'static str { let mut has_f32 = false; let mut has_q8 = false; let mut has_q4 = false; for tensor in tensors { match tensor.dtype { DTYPE_F32 => has_f32 = true, DTYPE_Q8_0 => has_q8 = true, DTYPE_Q4_0 => has_q4 = true, _ => {} } } match (has_f32, has_q8, has_q4) { (true, false, false) => "f32", (false, true, false) => "q8_0", (false, false, true) => "q4_0", _ => "mixed", } } fn tokenizer_checksum(bytes: &[u8], header: &SlmHeader) -> io::Result { let start = as_usize(header.tokenizer_offset)?; let len = as_usize(header.tokenizer_length)?; let end = start .checked_add(len) .ok_or_else(|| invalid("tokenizer checksum range overflow"))?; let section = bytes .get(start..end) .ok_or_else(|| invalid("tokenizer checksum range escapes the file"))?; Ok(section_checksum(section, 0x746f6b656e697a65)) } fn tensor_layout_checksum(tensors: &[TensorEntry]) -> u64 { let mut sorted = tensors.iter().collect::>(); sorted.sort_by_key(|tensor| tensor.name_hash); let mut acc = 0x74656e736f722d6cu64; for tensor in sorted { mix_u64(&mut acc, tensor.name_hash); mix_u64(&mut acc, u64::from(tensor.dtype)); mix_u64(&mut acc, u64::from(tensor.rank)); for dim in tensor.dims { mix_u64(&mut acc, u64::from(dim)); } mix_u64(&mut acc, u64::from(tensor.block_size)); mix_u64(&mut acc, tensor.byte_length); } acc } fn section_checksum(bytes: &[u8], seed: u64) -> u64 { let mut acc = seed; for (index, byte) in bytes.iter().enumerate() { acc ^= u64::from(*byte).wrapping_add((index as u64) << 2); acc = acc.rotate_left(9).wrapping_mul(0x100000001b3); } acc } fn mix_u64(acc: &mut u64, value: u64) { for byte in value.to_le_bytes() { *acc ^= u64::from(byte); *acc = acc.rotate_left(11).wrapping_mul(0x100000001b3); } } fn read_u32(bytes: &[u8], offset: usize) -> io::Result { let end = offset .checked_add(4) .ok_or_else(|| invalid("u32 offset overflow"))?; let slice = bytes .get(offset..end) .ok_or_else(|| invalid("unexpected end while reading u32"))?; Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) } fn read_u64(bytes: &[u8], offset: usize) -> io::Result { let end = offset .checked_add(8) .ok_or_else(|| invalid("u64 offset overflow"))?; let slice = bytes .get(offset..end) .ok_or_else(|| invalid("unexpected end while reading u64"))?; Ok(u64::from_le_bytes([ slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7], ])) } fn range_within(file_len: usize, offset: u64, len: u64) -> bool { let Some(end) = offset.checked_add(len) else { return false; }; end <= file_len as u64 } fn simple_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x9e3779b97f4a7c15u64; for (index, byte) in bytes.iter().enumerate() { let value = if (100..108).contains(&index) { 0 } else { *byte }; acc ^= u64::from(value).wrapping_add((index as u64) << 1); acc = acc.rotate_left(7).wrapping_mul(0x100000001b3); } acc } fn name_hash(name: &str) -> u64 { let mut hash = 0xcbf29ce484222325u64; for byte in name.as_bytes() { hash ^= u64::from(*byte); hash = hash.wrapping_mul(0x100000001b3); } hash } fn as_usize(value: u64) -> io::Result { usize::try_from(value).map_err(|_| invalid("value does not fit in usize")) } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } #[cfg(test)] mod tests { use super::*; use crate::tensor_writer::{ tensors_for_shape, tiny_fixture_tensors, tiny_fixture_tied_tensors, ModelShape, DTYPE_F32, }; use crate::tokenizer_writer::{ByteTokenizerSection, TokenizerSection}; use crate::{build_model_file, build_model_file_with_flags}; const FLAG_TIED_OUTPUT: u32 = 1; #[test] fn validates_generated_tiny_fixture() { let bytes = build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors(), &ByteTokenizerSection::phase_one(), ) .unwrap(); let report = validate_bytes(&bytes, "memory.slm").unwrap(); assert_eq!(report.header.hidden_size, 8); assert_eq!(report.tensors.len(), 12); assert_eq!(report.quantization_label, "f32"); assert_ne!(report.tokenizer_checksum(), 0); assert_ne!(report.tensor_layout_checksum(), 0); assert_eq!(report.context_token_limit(), 16); assert_eq!(report.kv_cache_byte_budget().unwrap(), 1024); assert_eq!(report.kv_cache_page_count().unwrap(), 1); } #[test] fn validates_tied_output_fixture_without_output_weight() { let bytes = build_model_file_with_flags( &ModelShape::tiny_fixture(), &tiny_fixture_tied_tensors(), &ByteTokenizerSection::phase_one(), FLAG_TIED_OUTPUT, ) .unwrap(); let report = validate_bytes(&bytes, "tied.slm").unwrap(); assert_eq!(report.header.flags & FLAG_TIED_OUTPUT, FLAG_TIED_OUTPUT); assert_eq!(report.tensors.len(), 11); assert!(!report .tensors .iter() .any(|tensor| tensor.name_hash == name_hash("output.weight"))); } #[test] fn rejects_missing_output_without_tied_flag() { let bytes = build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tied_tensors(), &ByteTokenizerSection::phase_one(), ) .unwrap(); let error = validate_bytes(&bytes, "missing-output.slm").unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!( error .to_string() .contains("missing required tensor output.weight"), "{error}" ); } #[test] fn rejects_non_finite_f32_payload() { let mut bytes = build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors(), &ByteTokenizerSection::phase_one(), ) .unwrap(); let header = parse_header(&bytes).unwrap(); let tensors = parse_tensors(&bytes, &header).unwrap(); let start = tensors[0].byte_offset as usize; bytes[start..start + 4].copy_from_slice(&f32::NAN.to_le_bytes()); bytes[100..108].copy_from_slice(&0u64.to_le_bytes()); let checksum = simple_checksum(&bytes); bytes[100..108].copy_from_slice(&checksum.to_le_bytes()); let error = validate_bytes(&bytes, "nan.slm").unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } #[test] fn validates_bpe_tokenizer_section_when_vocab_matches_header() { let shape = ModelShape { vocab_size: 262, ..ModelShape::tiny_fixture() }; let bytes = build_model_file( &shape, &tensors_for_shape(&shape, DTYPE_F32), &TokenizerSection::tiny_bpe_demo(), ) .unwrap(); let report = validate_bytes(&bytes, "bpe.slm").unwrap(); assert_eq!(report.header.vocab_size, 262); assert_eq!(report.tensors.len(), 12); } #[test] fn rejects_bpe_tokenizer_vocab_drift() { let bytes = build_model_file( &ModelShape::tiny_fixture(), &tiny_fixture_tensors(), &TokenizerSection::tiny_bpe_demo(), ) .unwrap(); let error = validate_bytes(&bytes, "bpe-drift.slm").unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/slm_validate.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/soup.rs BYTES: 49370 SHA256: 2CEB401210DF55C49685BBA24B6DF94F9F34FE075CFCF08592F8CCA2B36DDF5E ================================================================================ //! Seed-weighted multi-parent soup candidates built from parent-pool recipes. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::blend::{ hex64, invalid, output_specs, parse_manifest, parse_model_values, push_line, require_equal, require_key, require_report_equal, require_same_tensor_spec, same_shape, ParsedModel, }; use crate::build_model_file_from_values_with_flags; use crate::parent_pool; use crate::provenance; use crate::slm_validate::{self, ValidationReport}; const OPERATOR_VERSION: &str = "1"; const OPERATOR_KIND: &str = "seed-weighted-parent-pool-soup"; const OPERATOR_STATUS: &str = "candidate-written"; const SOUP_MERGE_RULE: &str = "seed-weighted-direct-parameter-average"; const SOUP_WEIGHT_SOURCE: &str = "parent-pool-seed-weight-ppm"; const SOUP_WEIGHT_UNIT: &str = "parts-per-million"; const PARENT_CONTRACT: &str = "matches-parent-pool-direct-parameter-contract"; const OPERATOR_OUTPUT_STATUS: &str = "slm-validated"; const REQUIRED_NEXT_GATE: &str = "multi-parent-candidate-manifest-plus-runtime-smoke-plus-eval"; const PPM_DENOMINATOR: u64 = 1_000_000; const RELATEDNESS_KEYS: [&str; 5] = [ "relatedness_metric", "relatedness_scope", "relatedness_pair_count", "relatedness_all_pairs_status", "relatedness_contract_checksum", ]; const EVOLUTION_RECIPE_KEYS: [&str; 7] = [ "evolution_recipe_version", "evolution_recipe_strategy", "evolution_recipe_status", "evolution_selection_source", "evolution_relatedness_contract_checksum", "evolution_schedule_checksum_algorithm", "evolution_schedule_checksum", ]; #[derive(Clone)] struct RecipeParent { rank: String, role: String, selection_status: String, source_review_entry: String, source_ledger_entry: String, candidate_id: String, selector_id: String, operator_id: String, resource_budget: String, candidate_artifact_path: String, candidate_artifact_bytes: String, candidate_slm_checksum: String, candidate_model_shape: String, candidate_quantization: String, candidate_output_contract: String, candidate_tokenizer_checksum: String, candidate_tensor_layout_checksum: String, relatedness_group: String, relatedness_contract_checksum: String, population_fitness_ppm: String, seed_weight_ppm: u64, next_route: String, } struct ParentArtifact { path: String, seed_weight_ppm: u64, report: ValidationReport, model: ParsedModel, } #[derive(Default)] struct SoupStats { total_parameter_count: u64, parent_weight_checksum: u64, weighted_value_checksum: u64, changed_from_frontier_count: u64, changed_from_frontier_density_ppm: u64, } /// Writes a seed-weighted parent-pool soup `.slm` candidate plus a receipt. pub(crate) fn write_candidate_path( ledger: &Path, review: &Path, recipe: &Path, output_slm: &Path, output_receipt: &Path, parent_paths: &[String], admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_texts(admission_paths, "soup-candidate admissions")?; let parent_bytes = read_bytes(parent_paths, "soup-candidate parents")?; let ledger_text = fs::read_to_string(ledger)?; let review_text = fs::read_to_string(review)?; let recipe_text = fs::read_to_string(recipe)?; let (candidate, receipt) = build_candidate_bytes_and_receipt( &ledger_text, &review_text, &recipe_text, &parent_bytes, output_slm.display().to_string().as_str(), &admission_texts, )?; if let Some(parent) = output_slm.parent() { fs::create_dir_all(parent)?; } if let Some(parent) = output_receipt.parent() { fs::create_dir_all(parent)?; } fs::write(output_slm, candidate)?; fs::write(output_receipt, receipt)?; println!( "SLM parent-pool soup candidate written: {}", output_slm.display() ); println!( "SLM parent-pool soup receipt written: {}", output_receipt.display() ); Ok(()) } /// Validates a seed-weighted parent-pool soup candidate by exact recomputation. pub(crate) fn validate_candidate_path( ledger: &Path, review: &Path, recipe: &Path, candidate_slm: &Path, receipt: &Path, parent_paths: &[String], admission_paths: &[String], ) -> io::Result<()> { let admission_texts = read_texts(admission_paths, "validate-soup-candidate admissions")?; let parent_bytes = read_bytes(parent_paths, "validate-soup-candidate parents")?; let ledger_text = fs::read_to_string(ledger)?; let review_text = fs::read_to_string(review)?; let recipe_text = fs::read_to_string(recipe)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; validate_candidate_text( &ledger_text, &review_text, &recipe_text, &parent_bytes, &candidate_bytes, candidate_slm.display().to_string().as_str(), &receipt_text, &admission_texts, )?; println!("SLM parent-pool soup candidate validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("receipt: {}", receipt.display()); Ok(()) } // Reads the admission sidecar texts that bind the recipe inputs. fn read_texts(paths: &[String], label: &str) -> io::Result> { if paths.is_empty() { return Err(invalid(&format!("{label} require at least one input"))); } paths .iter() .map(|path| fs::read_to_string(Path::new(path))) .collect() } // Reads parent model bytes while requiring the multi-parent lane shape. fn read_bytes(paths: &[String], label: &str) -> io::Result)>> { if paths.len() < 2 { return Err(invalid(&format!( "{label} require at least two parent models" ))); } paths .iter() .map(|path| Ok((path.clone(), fs::read(Path::new(path))?))) .collect() } /// Validates candidate bytes and receipt text by rebuilding both artifacts. pub(crate) fn validate_candidate_text( ledger_text: &str, review_text: &str, recipe_text: &str, parent_bytes: &[(String, Vec)], candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, admission_texts: &[String], ) -> io::Result<()> { let receipt_fields = parse_manifest(receipt_text, "soup operator receipt")?; require_equal( &receipt_fields, "tinyrustlm_soup_operator_version", OPERATOR_VERSION, )?; require_equal(&receipt_fields, "operator_kind", OPERATOR_KIND)?; require_equal(&receipt_fields, "soup_merge_rule", SOUP_MERGE_RULE)?; require_equal(&receipt_fields, "soup_weight_source", SOUP_WEIGHT_SOURCE)?; require_equal(&receipt_fields, "soup_weight_unit", SOUP_WEIGHT_UNIT)?; let (expected_candidate, expected_receipt) = build_candidate_bytes_and_receipt( ledger_text, review_text, recipe_text, parent_bytes, candidate_path, admission_texts, )?; if candidate_bytes != expected_candidate { return Err(invalid( "parent-pool soup candidate bytes do not match recomputed output", )); } if receipt_text != expected_receipt { return Err(invalid( "parent-pool soup receipt fields do not match recomputed output", )); } Ok(()) } /// Builds a soup `.slm` candidate and the exact operator receipt for it. pub(crate) fn build_candidate_bytes_and_receipt( ledger_text: &str, review_text: &str, recipe_text: &str, parent_bytes: &[(String, Vec)], candidate_path: &str, admission_texts: &[String], ) -> io::Result<(Vec, String)> { parent_pool::validate_recipe_text(ledger_text, review_text, recipe_text, admission_texts)?; let recipe_fields = parse_manifest(recipe_text, "parent-pool recipe")?; let recipe_parents = parse_recipe_parents(&recipe_fields)?; if recipe_parents.len() < 2 { return Err(invalid("parent-pool soup requires at least two parents")); } if recipe_parents.len() != parent_bytes.len() { return Err(invalid( "parent-pool soup parent count does not match recipe", )); } let artifacts = parent_artifacts(parent_bytes, &recipe_parents)?; let (output_values, stats) = soup_values(&artifacts)?; let output_tensors = output_specs(&artifacts[0].model); let candidate = build_model_file_from_values_with_flags( &artifacts[0].model.shape, &output_tensors, &artifacts[0].model.tokenizer, &output_values, artifacts[0].model.flags, )?; let candidate_report = slm_validate::validate_bytes(&candidate, candidate_path)?; validate_candidate_contract(&recipe_fields, &candidate_report)?; let receipt = build_receipt_text( &recipe_fields, &recipe_parents, recipe_text, &artifacts, &candidate_report, stats, )?; Ok((candidate, receipt)) } // Extracts ordered parent records and validates their seed weights. fn parse_recipe_parents(fields: &HashMap) -> io::Result> { require_equal(fields, "tinyrustlm_parent_pool_recipe_version", "1")?; require_equal(fields, "recipe_kind", "sign-aware-parent-pool-v1")?; require_equal( fields, "parent_contract_status", "shared-direct-parameter-contract", )?; let count = parse_usize(require_key(fields, "parent_count")?, "parent_count")?; if count == 0 { return Err(invalid("parent-pool recipe has no parents")); } let mut parents = Vec::with_capacity(count); let mut seed_total = 0u64; for index in 0..count { let prefix = format!("parent.{index}"); let rank = required_prefixed(fields, &prefix, "rank")?; let expected_rank = (index + 1).to_string(); if rank != expected_rank { return Err(invalid(&format!( "parent-pool recipe parent {index} rank was {rank}, expected {expected_rank}" ))); } let role = required_prefixed(fields, &prefix, "role")?; if index == 0 && role != "frontier" { return Err(invalid("parent-pool recipe parent 0 must be frontier")); } if index > 0 && role != "parent-pool" { return Err(invalid( "parent-pool recipe non-frontier parents must use parent-pool role", )); } let seed_weight_ppm = parse_seed_weight(&required_prefixed(fields, &prefix, "seed_weight_ppm")?)?; seed_total = seed_total .checked_add(seed_weight_ppm) .ok_or_else(|| invalid("parent-pool recipe seed weight total overflow"))?; parents.push(RecipeParent { rank, role, selection_status: required_prefixed(fields, &prefix, "selection_status")?, source_review_entry: required_prefixed(fields, &prefix, "source_review_entry")?, source_ledger_entry: required_prefixed(fields, &prefix, "source_ledger_entry")?, candidate_id: required_prefixed(fields, &prefix, "candidate_id")?, selector_id: required_prefixed(fields, &prefix, "selector_id")?, operator_id: required_prefixed(fields, &prefix, "operator_id")?, resource_budget: required_prefixed(fields, &prefix, "resource_budget")?, candidate_artifact_path: required_prefixed(fields, &prefix, "candidate_artifact_path")?, candidate_artifact_bytes: required_prefixed( fields, &prefix, "candidate_artifact_bytes", )?, candidate_slm_checksum: required_prefixed(fields, &prefix, "candidate_slm_checksum")?, candidate_model_shape: required_prefixed(fields, &prefix, "candidate_model_shape")?, candidate_quantization: required_prefixed(fields, &prefix, "candidate_quantization")?, candidate_output_contract: required_prefixed( fields, &prefix, "candidate_output_contract", )?, candidate_tokenizer_checksum: required_prefixed( fields, &prefix, "candidate_tokenizer_checksum", )?, candidate_tensor_layout_checksum: required_prefixed( fields, &prefix, "candidate_tensor_layout_checksum", )?, relatedness_group: required_prefixed(fields, &prefix, "relatedness_group")?, relatedness_contract_checksum: required_prefixed( fields, &prefix, "relatedness_contract_checksum", )?, population_fitness_ppm: required_prefixed(fields, &prefix, "population_fitness_ppm")?, seed_weight_ppm, next_route: required_prefixed(fields, &prefix, "next_route")?, }); } if seed_total != PPM_DENOMINATOR { return Err(invalid( "parent-pool recipe seed weights must sum to 1000000", )); } Ok(parents) } // Validates each supplied parent against the recipe before tensor access. fn parent_artifacts( parent_bytes: &[(String, Vec)], recipe_parents: &[RecipeParent], ) -> io::Result> { let mut artifacts = Vec::with_capacity(parent_bytes.len()); for ((path, bytes), recipe_parent) in parent_bytes.iter().zip(recipe_parents.iter()) { let report = slm_validate::validate_bytes(bytes, path)?; require_recipe_parent_report(recipe_parent, &report)?; let model = parse_model_values(bytes)?; artifacts.push(ParentArtifact { path: path.clone(), seed_weight_ppm: recipe_parent.seed_weight_ppm, report, model, }); } Ok(artifacts) } // Confirms that one recipe parent line still matches its current `.slm` report. fn require_recipe_parent_report( recipe_parent: &RecipeParent, report: &ValidationReport, ) -> io::Result<()> { require_text_equal( "candidate_artifact_bytes", &recipe_parent.candidate_artifact_bytes, &report.file_bytes().to_string(), )?; require_text_equal( "candidate_slm_checksum", &recipe_parent.candidate_slm_checksum, &hex64(report.checksum()), )?; require_text_equal( "candidate_model_shape", &recipe_parent.candidate_model_shape, &report.shape_summary(), )?; require_text_equal( "candidate_quantization", &recipe_parent.candidate_quantization, report.quantization_label(), )?; require_text_equal( "candidate_output_contract", &recipe_parent.candidate_output_contract, report.output_contract_label(), )?; require_text_equal( "candidate_tokenizer_checksum", &recipe_parent.candidate_tokenizer_checksum, &hex64(report.tokenizer_checksum()), )?; require_text_equal( "candidate_tensor_layout_checksum", &recipe_parent.candidate_tensor_layout_checksum, &hex64(report.tensor_layout_checksum()), )?; Ok(()) } // Confirms that the emitted candidate preserves the recipe shared contract. fn validate_candidate_contract( recipe_fields: &HashMap, report: &ValidationReport, ) -> io::Result<()> { require_report_equal( recipe_fields, "contract_model_shape", &report.shape_summary(), )?; require_report_equal( recipe_fields, "contract_quantization", report.quantization_label(), )?; require_report_equal( recipe_fields, "contract_output_contract", report.output_contract_label(), )?; require_report_equal( recipe_fields, "contract_tokenizer_checksum", &hex64(report.tokenizer_checksum()), )?; require_report_equal( recipe_fields, "contract_tensor_layout_checksum", &hex64(report.tensor_layout_checksum()), )?; Ok(()) } // Applies the seed-weighted direct average for every tensor value. fn soup_values(artifacts: &[ParentArtifact]) -> io::Result<(Vec>, SoupStats)> { let base = &artifacts .first() .ok_or_else(|| invalid("parent-pool soup requires a frontier parent"))? .model; for artifact in artifacts.iter().skip(1) { require_compatible_parent(base, &artifact.model)?; } let parent_tensor_maps = artifacts .iter() .map(|artifact| { artifact .model .tensors .iter() .enumerate() .map(|(index, tensor)| (tensor.spec.name_hash, index)) .collect::>() }) .collect::>(); let mut output = Vec::with_capacity(base.tensors.len()); let mut stats = SoupStats { parent_weight_checksum: checksum_seed(0x736f_7570_5f77_7631), weighted_value_checksum: checksum_seed(0x736f_7570_5f76_7631), ..SoupStats::default() }; for (parent_index, artifact) in artifacts.iter().enumerate() { mix_checksum(&mut stats.parent_weight_checksum, parent_index as u64); mix_checksum(&mut stats.parent_weight_checksum, artifact.seed_weight_ppm); mix_checksum( &mut stats.parent_weight_checksum, artifact.report.checksum(), ); } for (tensor_index, base_tensor) in base.tensors.iter().enumerate() { let mut tensor_values = Vec::with_capacity(base_tensor.values.len()); for (value_index, base_value) in base_tensor.values.iter().enumerate() { let mut weighted = 0.0f64; for (parent_index, artifact) in artifacts.iter().enumerate() { let tensor_map = &parent_tensor_maps[parent_index]; let Some(parent_tensor_index) = tensor_map.get(&base_tensor.spec.name_hash) else { return Err(invalid( "parent-pool soup parent is missing a tensor from the frontier", )); }; let parent_tensor = &artifact.model.tensors[*parent_tensor_index]; require_same_tensor_spec(&base_tensor.spec, &parent_tensor.spec)?; weighted += parent_tensor.values[value_index] as f64 * artifact.seed_weight_ppm as f64 / PPM_DENOMINATOR as f64; } let value = weighted as f32; if !value.is_finite() { return Err(invalid("parent-pool soup produced a non-finite value")); } stats.total_parameter_count += 1; if value != *base_value { stats.changed_from_frontier_count += 1; } mix_checksum(&mut stats.weighted_value_checksum, tensor_index as u64); mix_checksum(&mut stats.weighted_value_checksum, value_index as u64); mix_checksum( &mut stats.weighted_value_checksum, u64::from(value.to_bits()), ); tensor_values.push(value); } output.push(tensor_values); } stats.changed_from_frontier_density_ppm = ratio_ppm( stats.changed_from_frontier_count, stats.total_parameter_count, )?; Ok((output, stats)) } // Keeps mixing inside identical shape, flag, and tokenizer lanes. fn require_compatible_parent(base: &ParsedModel, parent: &ParsedModel) -> io::Result<()> { if !same_shape(&base.shape, &parent.shape) { return Err(invalid( "parent-pool soup parents have different model shapes", )); } if base.flags != parent.flags { return Err(invalid( "parent-pool soup parents have different output flags", )); } if base.tokenizer.bytes != parent.tokenizer.bytes { return Err(invalid( "parent-pool soup parents have different tokenizer bytes", )); } Ok(()) } // Records recipe, parent, merge, statistic, and candidate fields for replay. fn build_receipt_text( recipe_fields: &HashMap, recipe_parents: &[RecipeParent], recipe_text: &str, artifacts: &[ParentArtifact], candidate_report: &ValidationReport, stats: SoupStats, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_soup_operator_version", OPERATOR_VERSION, ); push_line(&mut text, "operator_kind", OPERATOR_KIND); push_line(&mut text, "operator_status", OPERATOR_STATUS); push_line( &mut text, "recipe_kind", require_key(recipe_fields, "recipe_kind")?, ); push_line( &mut text, "parent_pool_recipe_checksum", &hex64(provenance::text_checksum(recipe_text.as_bytes())), ); push_evolution_schedule_lines( &mut text, recipe_fields, OPERATOR_KIND, "soup-candidate", SOUP_MERGE_RULE, )?; push_line( &mut text, "population_review_checksum", require_key(recipe_fields, "population_review_checksum")?, ); push_line( &mut text, "promotion_ledger_checksum", require_key(recipe_fields, "promotion_ledger_checksum")?, ); push_line( &mut text, "admission_set_checksum", require_key(recipe_fields, "admission_set_checksum")?, ); push_line( &mut text, "frontier_candidate_id", require_key(recipe_fields, "frontier_candidate_id")?, ); push_line( &mut text, "frontier_candidate_slm_checksum", require_key(recipe_fields, "frontier_candidate_slm_checksum")?, ); push_line( &mut text, "parent_contract_status", require_key(recipe_fields, "parent_contract_status")?, ); push_line( &mut text, "contract_model_shape", require_key(recipe_fields, "contract_model_shape")?, ); push_line( &mut text, "contract_quantization", require_key(recipe_fields, "contract_quantization")?, ); push_line( &mut text, "contract_output_contract", require_key(recipe_fields, "contract_output_contract")?, ); push_line( &mut text, "contract_tokenizer_checksum", require_key(recipe_fields, "contract_tokenizer_checksum")?, ); push_line( &mut text, "contract_tensor_layout_checksum", require_key(recipe_fields, "contract_tensor_layout_checksum")?, ); for key in RELATEDNESS_KEYS { push_line(&mut text, key, require_key(recipe_fields, key)?); } push_line(&mut text, "parent_count", &recipe_parents.len().to_string()); for (index, (recipe_parent, artifact)) in recipe_parents.iter().zip(artifacts).enumerate() { push_parent_receipt_lines(&mut text, index, recipe_parent, artifact); } push_line(&mut text, "base_parent_index", "0"); push_line(&mut text, "soup_merge_rule", SOUP_MERGE_RULE); push_line(&mut text, "soup_weight_source", SOUP_WEIGHT_SOURCE); push_line(&mut text, "soup_weight_unit", SOUP_WEIGHT_UNIT); push_line( &mut text, "soup_total_parameter_count", &stats.total_parameter_count.to_string(), ); push_line( &mut text, "soup_parent_weight_checksum", &hex64(stats.parent_weight_checksum), ); push_line( &mut text, "soup_weighted_value_checksum", &hex64(stats.weighted_value_checksum), ); push_line( &mut text, "soup_changed_from_frontier_count", &stats.changed_from_frontier_count.to_string(), ); push_line( &mut text, "soup_changed_from_frontier_density_ppm", &stats.changed_from_frontier_density_ppm.to_string(), ); push_candidate_lines(&mut text, candidate_report); push_line(&mut text, "candidate_parent_contract", PARENT_CONTRACT); push_line(&mut text, "operator_output_status", OPERATOR_OUTPUT_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } // Copies the matching recipe schedule family into the soup receipt. fn push_evolution_schedule_lines( text: &mut String, recipe_fields: &HashMap, operator_kind: &str, command: &str, selection_rule: &str, ) -> io::Result<()> { for key in EVOLUTION_RECIPE_KEYS { push_line(text, key, require_key(recipe_fields, key)?); } let family_count = parse_usize( require_key(recipe_fields, "evolution_operator_family_count")?, "evolution_operator_family_count", )?; for index in 0..family_count { let prefix = format!("evolution_operator_family.{index}"); if required_prefixed(recipe_fields, &prefix, "operator_kind")? != operator_kind { continue; } require_equal(recipe_fields, &format!("{prefix}.command"), command)?; require_equal( recipe_fields, &format!("{prefix}.selection_rule"), selection_rule, )?; require_equal( recipe_fields, &format!("{prefix}.output_gate"), REQUIRED_NEXT_GATE, )?; push_line(text, "scheduled_operator_family_index", &index.to_string()); push_line(text, "scheduled_operator_family_kind", operator_kind); push_line(text, "scheduled_operator_family_command", command); push_line( text, "scheduled_operator_family_selection_rule", selection_rule, ); push_line( text, "scheduled_operator_family_output_gate", REQUIRED_NEXT_GATE, ); return Ok(()); } Err(invalid( "parent-pool evolution schedule does not include soup operator family", )) } // Copies one parent's recipe and validation details into the receipt. fn push_parent_receipt_lines( text: &mut String, index: usize, recipe_parent: &RecipeParent, artifact: &ParentArtifact, ) { let prefix = format!("parent.{index}"); push_line(text, &format!("{prefix}.rank"), &recipe_parent.rank); push_line(text, &format!("{prefix}.role"), &recipe_parent.role); push_line( text, &format!("{prefix}.selection_status"), &recipe_parent.selection_status, ); push_line( text, &format!("{prefix}.source_review_entry"), &recipe_parent.source_review_entry, ); push_line( text, &format!("{prefix}.source_ledger_entry"), &recipe_parent.source_ledger_entry, ); push_line( text, &format!("{prefix}.candidate_id"), &recipe_parent.candidate_id, ); push_line( text, &format!("{prefix}.selector_id"), &recipe_parent.selector_id, ); push_line( text, &format!("{prefix}.operator_id"), &recipe_parent.operator_id, ); push_line( text, &format!("{prefix}.resource_budget"), &recipe_parent.resource_budget, ); push_line( text, &format!("{prefix}.recipe_candidate_artifact_path"), &recipe_parent.candidate_artifact_path, ); push_line(text, &format!("{prefix}.actual_path"), &artifact.path); push_line( text, &format!("{prefix}.model_bytes"), &artifact.report.file_bytes().to_string(), ); push_line( text, &format!("{prefix}.slm_version"), &artifact.report.slm_version().to_string(), ); push_line( text, &format!("{prefix}.slm_checksum"), &hex64(artifact.report.checksum()), ); push_line( text, &format!("{prefix}.model_shape"), &artifact.report.shape_summary(), ); push_line( text, &format!("{prefix}.tensor_count"), &artifact.report.tensor_count().to_string(), ); push_line( text, &format!("{prefix}.parameter_count"), &artifact.report.parameter_count().to_string(), ); push_line( text, &format!("{prefix}.quantization"), artifact.report.quantization_label(), ); push_line( text, &format!("{prefix}.output_contract"), artifact.report.output_contract_label(), ); push_line( text, &format!("{prefix}.tokenizer_checksum"), &hex64(artifact.report.tokenizer_checksum()), ); push_line( text, &format!("{prefix}.tensor_layout_checksum"), &hex64(artifact.report.tensor_layout_checksum()), ); push_line( text, &format!("{prefix}.relatedness_group"), &recipe_parent.relatedness_group, ); push_line( text, &format!("{prefix}.relatedness_contract_checksum"), &recipe_parent.relatedness_contract_checksum, ); push_line( text, &format!("{prefix}.population_fitness_ppm"), &recipe_parent.population_fitness_ppm, ); push_line( text, &format!("{prefix}.seed_weight_ppm"), &recipe_parent.seed_weight_ppm.to_string(), ); push_line( text, &format!("{prefix}.next_route"), &recipe_parent.next_route, ); } // Copies the emitted candidate validation report into the receipt. fn push_candidate_lines(text: &mut String, report: &ValidationReport) { push_line(text, "candidate_artifact_path", report.path()); push_line( text, "candidate_artifact_bytes", &report.file_bytes().to_string(), ); push_line( text, "candidate_slm_version", &report.slm_version().to_string(), ); push_line(text, "candidate_slm_checksum", &hex64(report.checksum())); push_line(text, "candidate_model_shape", &report.shape_summary()); push_line( text, "candidate_tensor_count", &report.tensor_count().to_string(), ); push_line( text, "candidate_parameter_count", &report.parameter_count().to_string(), ); push_line(text, "candidate_quantization", report.quantization_label()); push_line( text, "candidate_output_contract", report.output_contract_label(), ); push_line( text, "candidate_tokenizer_checksum", &hex64(report.tokenizer_checksum()), ); push_line( text, "candidate_tensor_layout_checksum", &hex64(report.tensor_layout_checksum()), ); } // Fetches a required `parent.N.key` field from the recipe manifest. fn required_prefixed( fields: &HashMap, prefix: &str, key: &str, ) -> io::Result { Ok(require_key(fields, &format!("{prefix}.{key}"))?.to_string()) } // Parses a count field used by recipe cardinality checks. fn parse_usize(value: &str, label: &str) -> io::Result { value .parse::() .map_err(|_| invalid(&format!("{label} must be an integer"))) } // Parses one parent's parts-per-million recipe weight. fn parse_seed_weight(value: &str) -> io::Result { let parsed = value .parse::() .map_err(|_| invalid("parent-pool seed weight must be an integer"))?; if parsed > PPM_DENOMINATOR { return Err(invalid("parent-pool seed weight exceeded 1000000")); } Ok(parsed) } // Reports recipe-to-artifact drift with the manifest key that changed. fn require_text_equal(key: &str, actual: &str, expected: &str) -> io::Result<()> { if actual != expected { return Err(invalid(&format!( "parent-pool recipe key {key} was {actual}, current artifact has {expected}" ))); } Ok(()) } // Starts receipt checksums from a stable operator-local seed. fn checksum_seed(seed: u64) -> u64 { let mut acc = seed; mix_checksum(&mut acc, PPM_DENOMINATOR); acc } // Mixes a small integer into the receipt checksum accumulator. fn mix_checksum(acc: &mut u64, value: u64) { *acc ^= value.wrapping_add(0x9e37_79b9_7f4a_7c15); *acc = acc.rotate_left(9).wrapping_mul(0x1000_0000_01b3); } // Converts a count ratio into parts-per-million for stable receipts. fn ratio_ppm(numerator: u64, denominator: u64) -> io::Result { if denominator == 0 { return Ok(0); } numerator .checked_mul(PPM_DENOMINATOR) .map(|value| value / denominator) .ok_or_else(|| invalid("soup density overflow")) } #[cfg(test)] mod tests { use super::*; use crate::admission; use crate::build_model_file_from_values_with_flags; use crate::candidate; use crate::compatibility; use crate::fixture_value; use crate::ledger; use crate::lineage; use crate::population; use crate::promotion; use crate::tensor_writer::{tiny_fixture_tensors_with_dtype, ModelShape, DTYPE_F32}; use crate::tokenizer_writer::ByteTokenizerSection; use std::time::{SystemTime, UNIX_EPOCH}; #[test] fn writes_and_validates_weighted_soup_candidate_text() { let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.003); let gamma_bytes = tiny_fixture_f32_bytes_with_offset(0.006); let alpha = fixture_admission( "tiny-alpha-candidate", "target/soup/alpha.slm", &alpha_bytes, ); let beta = fixture_admission("tiny-beta-candidate", "target/soup/beta.slm", &beta_bytes); let gamma = fixture_admission( "tiny-gamma-candidate", "target/soup/gamma.slm", &gamma_bytes, ); let admissions = vec![alpha.clone(), beta.clone(), gamma.clone()]; let ledger = ledger::build_ledger_text(&admissions).unwrap(); let review = population::build_review_text(&ledger, &admissions).unwrap(); let recipe = parent_pool::build_recipe_text(&ledger, &review, &admissions).unwrap(); let parents = vec![ ("alpha.slm".to_string(), alpha_bytes.clone()), ("beta.slm".to_string(), beta_bytes), ("gamma.slm".to_string(), gamma_bytes.clone()), ]; let (candidate, receipt) = build_candidate_bytes_and_receipt( &ledger, &review, &recipe, &parents, "candidate.slm", &admissions, ) .unwrap(); validate_candidate_text( &ledger, &review, &recipe, &parents, &candidate, "candidate.slm", &receipt, &admissions, ) .unwrap(); let base = parse_model_values(&alpha_bytes).unwrap(); let gamma = parse_model_values(&gamma_bytes).unwrap(); let merged = parse_model_values(&candidate).unwrap(); assert!(merged.tensors[0].values[0] > base.tensors[0].values[0]); assert!(merged.tensors[0].values[0] < gamma.tensors[0].values[0]); assert!(receipt.contains("operator_kind=seed-weighted-parent-pool-soup")); assert!(receipt.contains("evolution_schedule_checksum=0x")); assert!(receipt.contains("scheduled_operator_family_index=1")); assert!(receipt.contains("scheduled_operator_family_command=soup-candidate")); assert!(receipt.contains("soup_merge_rule=seed-weighted-direct-parameter-average")); assert!(receipt.contains("soup_parent_weight_checksum=")); assert!(receipt.contains("soup_weighted_value_checksum=")); } #[test] fn rejects_parent_order_checksum_drift() { let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.004); let alpha = fixture_admission( "tiny-alpha-candidate", "target/soup/order-alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/soup/order-beta.slm", &beta_bytes, ); let admissions = vec![alpha.clone(), beta.clone()]; let ledger = ledger::build_ledger_text(&admissions).unwrap(); let review = population::build_review_text(&ledger, &admissions).unwrap(); let recipe = parent_pool::build_recipe_text(&ledger, &review, &admissions).unwrap(); let parents = vec![ ("beta.slm".to_string(), beta_bytes), ("alpha.slm".to_string(), alpha_bytes), ]; let error = build_candidate_bytes_and_receipt( &ledger, &review, &recipe, &parents, "candidate.slm", &admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate_slm_checksum")); } #[test] fn rejects_single_parent_recipe() { let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let alpha = fixture_admission( "tiny-alpha-candidate", "target/soup/single-alpha.slm", &alpha_bytes, ); let admissions = vec![alpha.clone()]; let ledger = ledger::build_ledger_text(&admissions).unwrap(); let review = population::build_review_text(&ledger, &admissions).unwrap(); let recipe = parent_pool::build_recipe_text(&ledger, &review, &admissions).unwrap(); let parents = vec![("alpha.slm".to_string(), alpha_bytes)]; let error = build_candidate_bytes_and_receipt( &ledger, &review, &recipe, &parents, "candidate.slm", &admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("at least two parents")); } #[test] fn validation_rejects_candidate_drift() { let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.004); let alpha = fixture_admission( "tiny-alpha-candidate", "target/soup/drift-alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/soup/drift-beta.slm", &beta_bytes, ); let admissions = vec![alpha.clone(), beta.clone()]; let ledger = ledger::build_ledger_text(&admissions).unwrap(); let review = population::build_review_text(&ledger, &admissions).unwrap(); let recipe = parent_pool::build_recipe_text(&ledger, &review, &admissions).unwrap(); let parents = vec![ ("alpha.slm".to_string(), alpha_bytes), ("beta.slm".to_string(), beta_bytes), ]; let (mut candidate, receipt) = build_candidate_bytes_and_receipt( &ledger, &review, &recipe, &parents, "candidate.slm", &admissions, ) .unwrap(); let last = candidate.len() - 1; candidate[last] ^= 0x01; let error = validate_candidate_text( &ledger, &review, &recipe, &parents, &candidate, "candidate.slm", &receipt, &admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate bytes")); } #[test] fn validation_rejects_receipt_operator_kind_drift() { let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.004); let alpha = fixture_admission( "tiny-alpha-candidate", "target/soup/receipt-alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/soup/receipt-beta.slm", &beta_bytes, ); let admissions = vec![alpha.clone(), beta.clone()]; let ledger = ledger::build_ledger_text(&admissions).unwrap(); let review = population::build_review_text(&ledger, &admissions).unwrap(); let recipe = parent_pool::build_recipe_text(&ledger, &review, &admissions).unwrap(); let parents = vec![ ("alpha.slm".to_string(), alpha_bytes), ("beta.slm".to_string(), beta_bytes), ]; let (candidate, receipt) = build_candidate_bytes_and_receipt( &ledger, &review, &recipe, &parents, "candidate.slm", &admissions, ) .unwrap(); let drifted = receipt.replace( "operator_kind=seed-weighted-parent-pool-soup", "operator_kind=other-parent-pool-soup", ); let error = validate_candidate_text( &ledger, &review, &recipe, &parents, &candidate, "candidate.slm", &drifted, &admissions, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("operator_kind")); } #[test] fn writes_and_validates_soup_candidate_paths() { let dir = unique_dir("paths"); std::fs::create_dir_all(&dir).unwrap(); let alpha_bytes = tiny_fixture_f32_bytes_with_offset(0.0); let beta_bytes = tiny_fixture_f32_bytes_with_offset(0.005); let gamma_bytes = tiny_fixture_f32_bytes_with_offset(0.002); let alpha = fixture_admission( "tiny-alpha-candidate", "target/soup/path-alpha.slm", &alpha_bytes, ); let beta = fixture_admission( "tiny-beta-candidate", "target/soup/path-beta.slm", &beta_bytes, ); let gamma = fixture_admission( "tiny-gamma-candidate", "target/soup/path-gamma.slm", &gamma_bytes, ); let alpha_slm = dir.join("alpha.slm"); let beta_slm = dir.join("beta.slm"); let gamma_slm = dir.join("gamma.slm"); let alpha_admission = dir.join("alpha.admission"); let beta_admission = dir.join("beta.admission"); let gamma_admission = dir.join("gamma.admission"); let ledger_path = dir.join("pool.ledger"); let review_path = dir.join("pool.review"); let recipe_path = dir.join("pool.recipe"); let candidate_path = dir.join("candidate.slm"); let receipt_path = dir.join("candidate.operator"); std::fs::write(&alpha_slm, alpha_bytes).unwrap(); std::fs::write(&beta_slm, beta_bytes).unwrap(); std::fs::write(&gamma_slm, gamma_bytes).unwrap(); std::fs::write(&alpha_admission, alpha).unwrap(); std::fs::write(&beta_admission, beta).unwrap(); std::fs::write(&gamma_admission, gamma).unwrap(); let admissions = vec![ alpha_admission.to_string_lossy().to_string(), beta_admission.to_string_lossy().to_string(), gamma_admission.to_string_lossy().to_string(), ]; let parents = vec![ alpha_slm.to_string_lossy().to_string(), beta_slm.to_string_lossy().to_string(), gamma_slm.to_string_lossy().to_string(), ]; ledger::write_ledger_path(&ledger_path, &admissions).unwrap(); population::write_review_path(&ledger_path, &review_path, &admissions).unwrap(); parent_pool::write_recipe_path(&ledger_path, &review_path, &recipe_path, &admissions) .unwrap(); write_candidate_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &parents, &admissions, ) .unwrap(); validate_candidate_path( &ledger_path, &review_path, &recipe_path, &candidate_path, &receipt_path, &parents, &admissions, ) .unwrap(); let receipt = std::fs::read_to_string(receipt_path).unwrap(); assert!(receipt.contains("operator_output_status=slm-validated")); assert!(receipt.contains("scheduled_operator_family_command=soup-candidate")); slm_validate::validate_path(&candidate_path).unwrap(); } fn fixture_admission(candidate_id: &str, candidate_path: &str, candidate: &[u8]) -> String { let compatibility = compatibility::compatibility_text_for_bytes( candidate, "left.slm", candidate, "right.slm", ) .unwrap(); let lineage = lineage::build_template_text(&compatibility, candidate_id, "operator-a", "fit") .unwrap(); let candidate_manifest = candidate::build_manifest_text(&compatibility, &lineage, candidate, candidate_path) .unwrap(); let promotion = promotion::build_template_text( &compatibility, &lineage, candidate, candidate_path, &candidate_manifest, "local-smoke-runner", promotion::DEFAULT_PROMOTION_SCOPE, ) .unwrap(); let report = slm_validate::validate_bytes(candidate, candidate_path).unwrap(); let provenance_manifest = provenance::build_manifest_text(&report, "converted-trained").unwrap(); let manifest_fields = provenance::parse_manifest(&provenance_manifest).unwrap(); let runtime_smoke = provenance::build_runtime_smoke_text(&report, &provenance_manifest, &manifest_fields) .unwrap(); let eval = passing_eval_text(&report, &provenance_manifest); admission::build_record_text( &compatibility, &lineage, candidate, candidate_path, &candidate_manifest, &promotion, &provenance_manifest, &runtime_smoke, &eval, admission::DEFAULT_ADMISSION_SELECTOR_ID, ) .unwrap() } fn passing_eval_text(report: &slm_validate::ValidationReport, manifest: &str) -> String { let mut text = String::new(); push_line(&mut text, "tinyrustlm_eval_manifest_version", "1"); push_line(&mut text, "gate", "assistant-quality"); push_line(&mut text, "source_kind", "converted-trained"); push_line( &mut text, "manifest_checksum", &hex64(provenance::text_checksum(manifest.as_bytes())), ); push_line(&mut text, "slm_checksum", &hex64(report.checksum())); push_line(&mut text, "model_shape", &report.shape_summary()); push_line(&mut text, "eval_status", "pass"); push_line(&mut text, "task_eval_status", "pass"); push_line(&mut text, "safety_review_status", "pass"); push_line( &mut text, "quality_decision", "accepted-for-assistant-quality", ); push_line(&mut text, "quality_scope", "tiny-fixture-runtime-eval-only"); push_line(&mut text, "evaluator", "local-reviewed-eval"); push_line( &mut text, "eval_dataset", "tinyrustlm/tests/fixtures/assistant-quality-eval-cases.txt", ); push_line( &mut text, "eval_summary", "Reviewed task and safety evidence passed for declared scope", ); push_line( &mut text, "quality_boundary", "fixture-runtime-and-eval-plumbing-not-product-assistant-quality", ); push_line(&mut text, "case_count", "1"); push_line(&mut text, "cases_passed", "1"); push_line(&mut text, "cases_failed", "0"); push_line(&mut text, "case.0.status", "pass"); push_line(&mut text, "case.0.expected", "e"); push_line(&mut text, "case.0.actual", "e"); push_line(&mut text, "case.0.error", "ok"); text } fn tiny_fixture_f32_bytes_with_offset(offset: f32) -> Vec { let tensors = tiny_fixture_tensors_with_dtype(DTYPE_F32); let values: Vec> = tensors .iter() .map(|tensor| { (0..tensor.element_count()) .map(|elem| fixture_value(tensor, elem) + offset) .collect() }) .collect(); build_model_file_from_values_with_flags( &ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } fn unique_dir(label: &str) -> std::path::PathBuf { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-soup-{label}-{nanos}")) } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/soup.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/sparse_delta.rs BYTES: 33152 SHA256: F56C9FCB3E11C04F1EF42329FEFEF8C34FD002E67B1A66AAEF5451C346A7A72A ================================================================================ //! Offline sparse task-delta operator for model-breeding candidates. use std::cmp::Ordering; use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; use crate::blend::{ hex64, invalid, output_specs, parse_manifest, parse_model_values, parse_passing_compatibility, push_line, push_parent_lines, require_equal, require_key, require_parent_report, require_report_equal, require_same_tensor_spec, same_shape, ParsedModel, PPM_DENOMINATOR, }; use crate::build_model_file_from_values_with_flags; use crate::lineage; use crate::slm_validate::{self, ValidationReport}; const SPARSE_DELTA_OPERATOR_VERSION: &str = "1"; const OPERATOR_KIND: &str = "sparse-direct-parameter-task-delta"; const OPERATOR_STATUS: &str = "candidate-written"; const OPERATOR_OUTPUT_STATUS: &str = "slm-validated"; const PARENT_CONTRACT: &str = "matches-parent-direct-parameter-contract"; const REQUIRED_NEXT_GATE: &str = "candidate-manifest-plus-runtime-smoke-plus-eval"; const DEFAULT_DELTA_WEIGHT_PPM: &str = "1000000"; const DEFAULT_KEEP_PPM: &str = "250000"; const MASK_METADATA_VERSION: &str = "1"; const MASK_METADATA_KIND: &str = "implicit-top-k-absolute-delta-mask"; const MASK_RETENTION_SCOPE: &str = "nonzero-target-minus-base-deltas"; const MIN_DELTA_WEIGHT_PPM: i64 = -1_000_000; const MAX_DELTA_WEIGHT_PPM: i64 = 2_000_000; /// Writes a sparse task-delta candidate `.slm` plus a recomputable receipt. pub(crate) fn write_candidate_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, output_slm: &Path, output_receipt: &Path, delta_weight_ppm: Option<&str>, keep_ppm: Option<&str>, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let weight = parse_delta_weight_ppm(delta_weight_ppm.unwrap_or(DEFAULT_DELTA_WEIGHT_PPM))?; let keep = parse_keep_ppm(keep_ppm.unwrap_or(DEFAULT_KEEP_PPM))?; let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &output_slm.display().to_string(), weight, keep, )?; if let Some(parent) = output_slm.parent() { fs::create_dir_all(parent)?; } fs::write(output_slm, candidate)?; if let Some(parent) = output_receipt.parent() { fs::create_dir_all(parent)?; } fs::write(output_receipt, receipt)?; println!( "SLM sparse task-delta candidate written: {}", output_slm.display() ); println!( "SLM sparse task-delta operator receipt written: {}", output_receipt.display() ); Ok(()) } /// Validates a sparse task-delta candidate and receipt by recomputing output. pub(crate) fn validate_candidate_path( compatibility: &Path, lineage_manifest: &Path, base_parent: &Path, target_parent: &Path, candidate_slm: &Path, receipt: &Path, ) -> io::Result<()> { let compatibility_text = fs::read_to_string(compatibility)?; let lineage_text = fs::read_to_string(lineage_manifest)?; let base_bytes = fs::read(base_parent)?; let target_bytes = fs::read(target_parent)?; let candidate_bytes = fs::read(candidate_slm)?; let receipt_text = fs::read_to_string(receipt)?; validate_candidate_text( &compatibility_text, &lineage_text, &base_bytes, &base_parent.display().to_string(), &target_bytes, &target_parent.display().to_string(), &candidate_bytes, &candidate_slm.display().to_string(), &receipt_text, )?; println!("SLM sparse task-delta candidate validation: PASS"); println!("candidate: {}", candidate_slm.display()); println!("receipt: {}", receipt.display()); Ok(()) } fn validate_candidate_text( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, candidate_bytes: &[u8], candidate_path: &str, receipt_text: &str, ) -> io::Result<()> { let receipt = parse_manifest(receipt_text, "sparse task-delta operator receipt")?; require_equal( &receipt, "tinyrustlm_sparse_delta_operator_version", SPARSE_DELTA_OPERATOR_VERSION, )?; require_equal(&receipt, "delta_weight_unit", "parts-per-million")?; require_equal(&receipt, "base_parent_index", "0")?; require_equal(&receipt, "target_parent_index", "1")?; let weight = parse_delta_weight_ppm(require_key(&receipt, "delta_weight_ppm")?)?; let keep = parse_keep_ppm(require_key(&receipt, "sparse_keep_ppm")?)?; require_equal( &receipt, "base_coefficient_ppm", &(i64::from(PPM_DENOMINATOR) - weight).to_string(), )?; require_equal( &receipt, "target_delta_coefficient_ppm", &weight.to_string(), )?; require_equal(&receipt, "sparse_keep_unit", "parts-per-million")?; require_equal( &receipt, "sparse_selection_metric", "absolute-target-minus-base-delta", )?; require_equal( &receipt, "sparse_selection_scope", "compatible-parent-tensor-values", )?; require_equal( &receipt, "sparse_tie_break", "tensor-order-then-element-index", )?; require_equal( &receipt, "sparse_mask_metadata_version", MASK_METADATA_VERSION, )?; require_equal(&receipt, "sparse_mask_kind", MASK_METADATA_KIND)?; require_equal(&receipt, "sparse_retention_scope", MASK_RETENTION_SCOPE)?; let (expected_candidate, expected_receipt) = build_candidate_bytes_and_receipt( compatibility_text, lineage_text, base_bytes, base_path, target_bytes, target_path, candidate_path, weight, keep, )?; if candidate_bytes != expected_candidate { return Err(invalid( "sparse task-delta candidate bytes do not match the operator receipt", )); } if receipt_text != expected_receipt { return Err(invalid( "sparse task-delta operator receipt fields do not match recomputed output", )); } Ok(()) } fn build_candidate_bytes_and_receipt( compatibility_text: &str, lineage_text: &str, base_bytes: &[u8], base_path: &str, target_bytes: &[u8], target_path: &str, candidate_path: &str, delta_weight_ppm: i64, keep_ppm: u32, ) -> io::Result<(Vec, String)> { lineage::validate_text(compatibility_text, lineage_text)?; let compatibility = parse_passing_compatibility(compatibility_text)?; let lineage_fields = parse_manifest(lineage_text, "lineage")?; let base_report = slm_validate::validate_bytes(base_bytes, base_path)?; let target_report = slm_validate::validate_bytes(target_bytes, target_path)?; require_parent_report(&compatibility, 0, &base_report)?; require_parent_report(&compatibility, 1, &target_report)?; let base = parse_model_values(base_bytes)?; let target = parse_model_values(target_bytes)?; let (output_values, sparse_stats) = sparse_delta_values(&base, &target, delta_weight_ppm, keep_ppm)?; let output_tensors = output_specs(&base); let candidate = build_model_file_from_values_with_flags( &base.shape, &output_tensors, &base.tokenizer, &output_values, base.flags, )?; let candidate_report = slm_validate::validate_bytes(&candidate, candidate_path)?; require_report_equal( &compatibility, "parent.0.model_shape", &candidate_report.shape_summary(), )?; require_report_equal( &compatibility, "parent.0.quantization", candidate_report.quantization_label(), )?; require_report_equal( &compatibility, "parent.0.output_contract", candidate_report.output_contract_label(), )?; require_report_equal( &compatibility, "parent.0.tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), )?; require_report_equal( &compatibility, "parent.0.tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), )?; let receipt = build_receipt_text( &compatibility, &lineage_fields, lineage_text, base_path, target_path, &base_report, &target_report, &candidate_report, delta_weight_ppm, keep_ppm, sparse_stats, )?; Ok((candidate, receipt)) } #[allow(clippy::too_many_arguments)] fn build_receipt_text( compatibility: &HashMap, lineage_fields: &HashMap, lineage_text: &str, base_path: &str, target_path: &str, base_report: &ValidationReport, target_report: &ValidationReport, candidate_report: &ValidationReport, delta_weight_ppm: i64, keep_ppm: u32, sparse_stats: SparseStats, ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_sparse_delta_operator_version", SPARSE_DELTA_OPERATOR_VERSION, ); push_line(&mut text, "operator_kind", OPERATOR_KIND); push_line(&mut text, "operator_status", OPERATOR_STATUS); push_line( &mut text, "candidate_id", require_key(lineage_fields, "candidate_id")?, ); push_line( &mut text, "operator_id", require_key(lineage_fields, "operator_id")?, ); push_line( &mut text, "operator_lane", require_key(lineage_fields, "operator_lane")?, ); push_line( &mut text, "resource_budget", require_key(lineage_fields, "resource_budget")?, ); push_line( &mut text, "compatibility_report_checksum", require_key(lineage_fields, "compatibility_report_checksum")?, ); push_line( &mut text, "lineage_manifest_checksum", &hex64(lineage::text_checksum(lineage_text.as_bytes())), ); push_line( &mut text, "compatibility_scope", require_key(compatibility, "compatibility_scope")?, ); push_line(&mut text, "parent_count", "2"); push_parent_lines(&mut text, compatibility, 0, base_path, base_report)?; push_parent_lines(&mut text, compatibility, 1, target_path, target_report)?; push_line(&mut text, "delta_weight_unit", "parts-per-million"); push_line(&mut text, "base_parent_index", "0"); push_line(&mut text, "target_parent_index", "1"); push_line(&mut text, "delta_weight_ppm", &delta_weight_ppm.to_string()); push_line( &mut text, "base_coefficient_ppm", &(i64::from(PPM_DENOMINATOR) - delta_weight_ppm).to_string(), ); push_line( &mut text, "target_delta_coefficient_ppm", &delta_weight_ppm.to_string(), ); push_line(&mut text, "sparse_keep_unit", "parts-per-million"); push_line(&mut text, "sparse_keep_ppm", &keep_ppm.to_string()); push_line( &mut text, "sparse_selection_metric", "absolute-target-minus-base-delta", ); push_line( &mut text, "sparse_selection_scope", "compatible-parent-tensor-values", ); push_line( &mut text, "sparse_tie_break", "tensor-order-then-element-index", ); push_line( &mut text, "sparse_total_parameter_count", &sparse_stats.total_parameter_count.to_string(), ); push_line( &mut text, "sparse_nonzero_delta_count", &sparse_stats.nonzero_delta_count.to_string(), ); push_line( &mut text, "sparse_kept_parameter_count", &sparse_stats.kept_parameter_count.to_string(), ); push_line( &mut text, "sparse_pruned_parameter_count", &sparse_stats.pruned_parameter_count.to_string(), ); push_line( &mut text, "sparse_unchanged_parameter_count", &sparse_stats.unchanged_parameter_count.to_string(), ); push_line( &mut text, "sparse_pruned_nonzero_delta_count", &sparse_stats.pruned_nonzero_delta_count.to_string(), ); push_line( &mut text, "sparse_density_ppm", &sparse_stats.density_ppm.to_string(), ); push_line( &mut text, "sparse_nonzero_delta_retention_ppm", &sparse_stats.nonzero_delta_retention_ppm.to_string(), ); push_line( &mut text, "sparse_mask_metadata_version", MASK_METADATA_VERSION, ); push_line(&mut text, "sparse_mask_kind", MASK_METADATA_KIND); push_line(&mut text, "sparse_retention_scope", MASK_RETENTION_SCOPE); push_line( &mut text, "sparse_mask_checksum", &hex64(sparse_stats.mask_checksum), ); push_line( &mut text, "candidate_artifact_path", candidate_report.path(), ); push_line( &mut text, "candidate_artifact_bytes", &candidate_report.file_bytes().to_string(), ); push_line( &mut text, "candidate_slm_version", &candidate_report.slm_version().to_string(), ); push_line( &mut text, "candidate_slm_checksum", &hex64(candidate_report.checksum()), ); push_line( &mut text, "candidate_model_shape", &candidate_report.shape_summary(), ); push_line( &mut text, "candidate_tensor_count", &candidate_report.tensor_count().to_string(), ); push_line( &mut text, "candidate_parameter_count", &candidate_report.parameter_count().to_string(), ); push_line( &mut text, "candidate_quantization", candidate_report.quantization_label(), ); push_line( &mut text, "candidate_output_contract", candidate_report.output_contract_label(), ); push_line( &mut text, "candidate_tokenizer_checksum", &hex64(candidate_report.tokenizer_checksum()), ); push_line( &mut text, "candidate_tensor_layout_checksum", &hex64(candidate_report.tensor_layout_checksum()), ); push_line(&mut text, "candidate_parent_contract", PARENT_CONTRACT); push_line(&mut text, "operator_output_status", OPERATOR_OUTPUT_STATUS); push_line(&mut text, "required_next_gate", REQUIRED_NEXT_GATE); Ok(text) } fn sparse_delta_values( base: &ParsedModel, target: &ParsedModel, delta_weight_ppm: i64, keep_ppm: u32, ) -> io::Result<(Vec>, SparseStats)> { if !same_shape(&base.shape, &target.shape) { return Err(invalid( "sparse task-delta parents have different model shapes", )); } if base.flags != target.flags { return Err(invalid( "sparse task-delta parents have different output flags", )); } if base.tokenizer.bytes != target.tokenizer.bytes { return Err(invalid( "sparse task-delta parents have different tokenizer bytes", )); } let target_by_hash = target .tensors .iter() .enumerate() .map(|(index, tensor)| (tensor.spec.name_hash, index)) .collect::>(); let mut output = base .tensors .iter() .map(|tensor| tensor.values.clone()) .collect::>(); let mut ranked = Vec::new(); let mut total_parameter_count = 0u64; for (tensor_index, base_tensor) in base.tensors.iter().enumerate() { let Some(target_index) = target_by_hash.get(&base_tensor.spec.name_hash) else { return Err(invalid( "target parent is missing a tensor from the base parent", )); }; let target_tensor = &target.tensors[*target_index]; require_same_tensor_spec(&base_tensor.spec, &target_tensor.spec)?; total_parameter_count += base_tensor.values.len() as u64; for (value_index, (base_value, target_value)) in base_tensor .values .iter() .zip(target_tensor.values.iter()) .enumerate() { let delta = target_value - base_value; let magnitude = delta.abs(); if magnitude > 0.0 { ranked.push(RankedDelta { magnitude, tensor_index, value_index, delta, }); } } } ranked.sort_by(compare_ranked_delta); let requested_keep = keep_count(total_parameter_count, keep_ppm)?; let kept_parameter_count = requested_keep.min(ranked.len() as u64); let delta_weight = delta_weight_ppm as f32 / PPM_DENOMINATOR as f32; let selected = ranked .iter() .take(kept_parameter_count as usize) .collect::>(); for entry in &selected { output[entry.tensor_index][entry.value_index] += entry.delta * delta_weight; } let nonzero_delta_count = ranked.len() as u64; let stats = SparseStats { total_parameter_count, nonzero_delta_count, kept_parameter_count, pruned_parameter_count: total_parameter_count - kept_parameter_count, unchanged_parameter_count: total_parameter_count - nonzero_delta_count, pruned_nonzero_delta_count: nonzero_delta_count - kept_parameter_count, density_ppm: ratio_ppm(kept_parameter_count, total_parameter_count)?, nonzero_delta_retention_ppm: ratio_ppm(kept_parameter_count, nonzero_delta_count)?, mask_checksum: sparse_mask_checksum(&selected, total_parameter_count), }; Ok((output, stats)) } fn compare_ranked_delta(left: &RankedDelta, right: &RankedDelta) -> Ordering { right .magnitude .partial_cmp(&left.magnitude) .unwrap_or(Ordering::Equal) .then_with(|| left.tensor_index.cmp(&right.tensor_index)) .then_with(|| left.value_index.cmp(&right.value_index)) } fn keep_count(total_parameter_count: u64, keep_ppm: u32) -> io::Result { if total_parameter_count == 0 || keep_ppm == 0 { return Ok(0); } let numerator = u128::from(total_parameter_count) * u128::from(keep_ppm) + u128::from(PPM_DENOMINATOR - 1); let count = numerator / u128::from(PPM_DENOMINATOR); u64::try_from(count).map_err(|_| invalid("sparse keep count overflowed u64")) } fn ratio_ppm(numerator: u64, denominator: u64) -> io::Result { if denominator == 0 { return Ok(0); } let ppm = u128::from(numerator) * u128::from(PPM_DENOMINATOR) / u128::from(denominator); u64::try_from(ppm).map_err(|_| invalid("sparse ratio overflowed u64")) } fn sparse_mask_checksum(selected: &[&RankedDelta], total_parameter_count: u64) -> u64 { let mut acc = 0x7265_7461_696e_6d31u64; mix_mask_value(&mut acc, total_parameter_count); mix_mask_value(&mut acc, selected.len() as u64); for entry in selected { mix_mask_value(&mut acc, entry.tensor_index as u64); mix_mask_value(&mut acc, entry.value_index as u64); } acc } fn mix_mask_value(acc: &mut u64, value: u64) { *acc ^= value.wrapping_add(0x9e37_79b9_7f4a_7c15); *acc = acc.rotate_left(11).wrapping_mul(0x1000_0000_01b3); } fn parse_delta_weight_ppm(value: &str) -> io::Result { let weight = value.parse::().map_err(|_| { invalid("sparse task-delta weight must be an integer parts-per-million value") })?; if !(MIN_DELTA_WEIGHT_PPM..=MAX_DELTA_WEIGHT_PPM).contains(&weight) { return Err(invalid( "sparse task-delta weight must be between -1000000 and 2000000", )); } Ok(weight) } fn parse_keep_ppm(value: &str) -> io::Result { let keep = value .parse::() .map_err(|_| invalid("sparse keep must be an integer parts-per-million value"))?; if keep > PPM_DENOMINATOR { return Err(invalid("sparse keep must be between 0 and 1000000")); } Ok(keep) } struct RankedDelta { magnitude: f32, tensor_index: usize, value_index: usize, delta: f32, } #[derive(Clone, Copy)] struct SparseStats { total_parameter_count: u64, nonzero_delta_count: u64, kept_parameter_count: u64, pruned_parameter_count: u64, unchanged_parameter_count: u64, pruned_nonzero_delta_count: u64, density_ppm: u64, nonzero_delta_retention_ppm: u64, mask_checksum: u64, } #[cfg(test)] mod tests { use super::*; use crate::compatibility; use crate::tensor_writer::{tiny_fixture_tensors, tiny_fixture_tensors_with_dtype, DTYPE_Q8_0}; use crate::tokenizer_writer::ByteTokenizerSection; use crate::{build_model_file_from_values_with_flags, fixture_value}; #[test] fn writes_and_validates_sparse_f32_task_delta_candidate() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_index_delta_bytes(); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text( &compatibility, "sparse-f32", "sparse-task-vector", "tiny", ) .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", 1_000_000, 250_000, ) .unwrap(); validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); let base_values = parse_model_values(&base).unwrap(); let candidate_values = parse_model_values(&candidate).unwrap(); let target_values = parse_model_values(&target).unwrap(); let mut base_preserved = 0usize; let mut target_selected = 0usize; for ((candidate_tensor, base_tensor), target_tensor) in candidate_values .tensors .iter() .zip(base_values.tensors.iter()) .zip(target_values.tensors.iter()) { for ((candidate_value, base_value), target_value) in candidate_tensor .values .iter() .zip(base_tensor.values.iter()) .zip(target_tensor.values.iter()) { if candidate_value == base_value { base_preserved += 1; } if candidate_value == target_value { target_selected += 1; } } } assert!(base_preserved > 0); assert!(target_selected > 0); assert!(receipt.contains("operator_kind=sparse-direct-parameter-task-delta")); assert!(receipt.contains("sparse_keep_ppm=250000")); assert!(receipt.contains("sparse_kept_parameter_count=")); assert!(receipt.contains("sparse_mask_metadata_version=1")); assert!(receipt.contains("sparse_mask_kind=implicit-top-k-absolute-delta-mask")); assert!(receipt.contains("sparse_mask_checksum=")); assert!(receipt.contains("sparse_nonzero_delta_retention_ppm=")); } #[test] fn keep_all_matches_target_values_for_f32_task_delta() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text( &compatibility, "sparse-all", "sparse-task-vector", "tiny", ) .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", 1_000_000, 1_000_000, ) .unwrap(); let candidate_values = parse_model_values(&candidate).unwrap(); let target_values = parse_model_values(&target).unwrap(); for (candidate_tensor, target_tensor) in candidate_values .tensors .iter() .zip(target_values.tensors.iter()) { assert_eq!(candidate_tensor.values, target_tensor.values); } assert!(receipt.contains("sparse_keep_ppm=1000000")); assert!(receipt.contains("sparse_pruned_nonzero_delta_count=0")); assert!(receipt.contains("sparse_nonzero_delta_retention_ppm=1000000")); } #[test] fn keep_zero_preserves_base_values_for_f32_task_delta() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text( &compatibility, "sparse-zero", "sparse-task-vector", "tiny", ) .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", 1_000_000, 0, ) .unwrap(); let candidate_values = parse_model_values(&candidate).unwrap(); let base_values = parse_model_values(&base).unwrap(); for (candidate_tensor, base_tensor) in candidate_values .tensors .iter() .zip(base_values.tensors.iter()) { assert_eq!(candidate_tensor.values, base_tensor.values); } assert!(receipt.contains("sparse_kept_parameter_count=0")); assert!(receipt.contains("sparse_density_ppm=0")); assert!(receipt.contains("sparse_nonzero_delta_retention_ppm=0")); assert!(receipt.contains("sparse_retention_scope=nonzero-target-minus-base-deltas")); } #[test] fn sparse_mask_checksum_changes_with_selected_positions() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_index_delta_bytes(); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text( &compatibility, "sparse-mask", "sparse-task-vector", "tiny", ) .unwrap(); let (_, sparse_receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "sparse.slm", 1_000_000, 250_000, ) .unwrap(); let (_, denser_receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "dense.slm", 1_000_000, 500_000, ) .unwrap(); let sparse_fields = parse_manifest(&sparse_receipt, "sparse receipt").unwrap(); let denser_fields = parse_manifest(&denser_receipt, "denser receipt").unwrap(); assert_ne!( sparse_fields.get("sparse_mask_checksum"), denser_fields.get("sparse_mask_checksum") ); assert_ne!( sparse_fields.get("sparse_density_ppm"), denser_fields.get("sparse_density_ppm") ); } #[test] fn writes_and_validates_sparse_q8_task_delta_candidate() { let base = tiny_q8_scaled_bytes(1.0); let target = tiny_q8_scaled_bytes(2.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text(&compatibility, "sparse-q8", "sparse-task-vector", "tiny") .unwrap(); let (candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", 500_000, 500_000, ) .unwrap(); slm_validate::validate_bytes(&candidate, "candidate.slm").unwrap(); validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &candidate, "candidate.slm", &receipt, ) .unwrap(); assert!(receipt.contains("candidate_quantization=q8_0")); } #[test] fn validation_rejects_candidate_drift() { let base = tiny_f32_scaled_bytes(1.0); let target = tiny_f32_scaled_bytes(3.0); let compatibility = compatibility::compatibility_text_for_bytes(&base, "base.slm", &target, "target.slm") .unwrap(); let lineage = lineage::build_template_text( &compatibility, "sparse-drift", "sparse-task-vector", "tiny", ) .unwrap(); let (mut candidate, receipt) = build_candidate_bytes_and_receipt( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", "candidate.slm", 1_000_000, 250_000, ) .unwrap(); let last = candidate.len() - 1; candidate[last] ^= 0x01; let error = validate_candidate_text( &compatibility, &lineage, &base, "base.slm", &target, "target.slm", &candidate, "candidate.slm", &receipt, ) .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("candidate bytes")); } #[test] fn rejects_invalid_sparse_parameters() { assert_eq!( parse_delta_weight_ppm("-1000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_delta_weight_ppm("2000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_delta_weight_ppm("1.5").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_keep_ppm("1000001").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_keep_ppm("-1").unwrap_err().kind(), io::ErrorKind::InvalidData ); assert_eq!( parse_keep_ppm("half").unwrap_err().kind(), io::ErrorKind::InvalidData ); } fn tiny_f32_scaled_bytes(scale: f32) -> Vec { build_tiny_bytes(tiny_fixture_tensors(), |tensor, index, _tensor_index| { fixture_value(tensor, index) * scale }) } fn tiny_f32_index_delta_bytes() -> Vec { build_tiny_bytes(tiny_fixture_tensors(), |tensor, index, tensor_index| { fixture_value(tensor, index) + ((tensor_index + index) as f32 * 0.001) }) } fn tiny_q8_scaled_bytes(scale: f32) -> Vec { build_tiny_bytes( tiny_fixture_tensors_with_dtype(DTYPE_Q8_0), |tensor, index, _tensor_index| fixture_value(tensor, index) * scale, ) } fn build_tiny_bytes(tensors: Vec, mut value: F) -> Vec where F: FnMut(&crate::tensor_writer::TensorSpec, usize, usize) -> f32, { let values = tensors .iter() .enumerate() .map(|(tensor_index, tensor)| { (0..tensor.element_count()) .map(|index| value(tensor, index, tensor_index)) .collect::>() }) .collect::>(); build_model_file_from_values_with_flags( &crate::tensor_writer::ModelShape::tiny_fixture(), &tensors, &ByteTokenizerSection::phase_one(), &values, 0, ) .unwrap() } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/sparse_delta.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/tensor_writer.rs BYTES: 8874 SHA256: 0C2FFD4B3585128D44C36F91A7A9FF1CBF708D17A5EE14EC9BCF64B5E5F7A5EB ================================================================================ //! Tensor directory writer inputs. /// Float32 tensor dtype. pub const DTYPE_F32: u32 = 1; /// Q8_0 tensor dtype. pub const DTYPE_Q8_0: u32 = 2; /// Q4_0 tensor dtype. pub const DTYPE_Q4_0: u32 = 3; /// Model dimensions used to write deterministic `.slm` files. pub struct ModelShape { /// Token vocabulary size. pub vocab_size: u32, /// Number of special tokens. pub special_token_count: u32, /// Transformer hidden size. pub hidden_size: u32, /// Transformer layer count. pub layer_count: u32, /// Attention head count. pub head_count: u32, /// Key/value head count. pub kv_head_count: u32, /// Dimension per attention head. pub head_dim: u32, /// Feed-forward intermediate size. pub ffn_size: u32, /// Maximum context length. pub max_context: u32, } impl ModelShape { /// Returns the deterministic tiny fixture shape used by unit tests. pub fn tiny_fixture() -> Self { Self { vocab_size: 260, special_token_count: 4, hidden_size: 8, layer_count: 1, head_count: 2, kv_head_count: 2, head_dim: 4, ffn_size: 16, max_context: 16, } } /// Returns the first realistic TinyLM-16M target shape. pub fn tinylm16() -> Self { Self { vocab_size: 260, special_token_count: 4, hidden_size: 512, layer_count: 4, head_count: 8, kv_head_count: 8, head_dim: 64, ffn_size: 2048, max_context: 512, } } } /// Static tensor specification for fixture packing. pub struct TensorSpec { /// Stable tensor name hash. pub name_hash: u64, /// Tensor dtype. pub dtype: u32, /// Tensor rank. pub rank: u32, /// Tensor dimensions. pub dims: [u32; 4], /// Deterministic fill seed. pub seed: u32, /// Quantization block size, or zero for f32. pub block_size: u32, } impl TensorSpec { /// Creates a f32 tensor specification. pub fn f32(name: &str, dims: &[u32], seed: u32) -> Self { let mut padded = [1u32; 4]; for (index, dim) in dims.iter().enumerate() { padded[index] = *dim; } Self { name_hash: name_hash(name), dtype: DTYPE_F32, rank: dims.len() as u32, dims: padded, seed, block_size: 0, } } /// Creates a q8_0 tensor specification. pub fn q8(name: &str, dims: &[u32], seed: u32) -> Self { let mut spec = Self::f32(name, dims, seed); spec.dtype = DTYPE_Q8_0; spec.block_size = spec.cols_per_row() as u32; spec } /// Creates a q4_0 tensor specification. pub fn q4(name: &str, dims: &[u32], seed: u32) -> Self { let mut spec = Self::f32(name, dims, seed); spec.dtype = DTYPE_Q4_0; let cols = spec.cols_per_row(); spec.block_size = if cols >= 32 && cols % 32 == 0 { 32 } else { cols as u32 }; spec } /// Returns the tensor element count. pub fn element_count(&self) -> usize { let mut total = 1usize; for dim in self.dims.iter().take(self.rank as usize) { total *= *dim as usize; } total } /// Returns the serialized tensor data byte length. pub fn byte_len(&self) -> usize { match self.dtype { DTYPE_F32 => self.element_count() * 4, DTYPE_Q8_0 => self.element_count(), DTYPE_Q4_0 => self.element_count() / 2, _ => 0, } } /// Returns the serialized quantization scale byte length. pub fn scale_byte_len(&self) -> usize { match self.dtype { DTYPE_Q8_0 => self.rows() * 4, DTYPE_Q4_0 => self.rows() * self.blocks_per_row() * 4, _ => 0, } } /// Returns row count for row-wise quantization. pub fn rows(&self) -> usize { if self.rank <= 1 { 1 } else { self.dims[0] as usize } } /// Returns columns per row for row-wise quantization. pub fn cols_per_row(&self) -> usize { if self.rank <= 1 { self.element_count() } else { self.dims .iter() .skip(1) .take(self.rank as usize - 1) .fold(1usize, |acc, dim| acc * *dim as usize) } } /// Returns q4 blocks per row. pub fn blocks_per_row(&self) -> usize { let block = self.block_size as usize; if block == 0 { 0 } else { self.cols_per_row() / block } } } /// Returns tensor specs for the tiny test model. pub fn tiny_fixture_tensors() -> Vec { tiny_fixture_tensors_with_dtype(DTYPE_F32) } /// Returns tensor specs for a quantization-specific tiny test model. pub fn tiny_fixture_tensors_with_dtype(dtype: u32) -> Vec { tensors_for_shape(&ModelShape::tiny_fixture(), dtype) } /// Returns f32 tensor specs for a tiny tied-output test model. pub fn tiny_fixture_tied_tensors() -> Vec { tensors_for_shape_with_tied_output(&ModelShape::tiny_fixture(), DTYPE_F32) } /// Returns tensor specs for the TinyLM-16M f32 target model. pub fn tinylm16_f32_tensors() -> Vec { tensors_for_shape(&ModelShape::tinylm16(), DTYPE_F32) } /// Returns tensor specs for the TinyLM-16M q8_0 target model. pub fn tinylm16_q8_tensors() -> Vec { tensors_for_shape(&ModelShape::tinylm16(), DTYPE_Q8_0) } /// Returns tensor specs for the TinyLM-16M q4_0 target model. pub fn tinylm16_q4_tensors() -> Vec { tensors_for_shape(&ModelShape::tinylm16(), DTYPE_Q4_0) } /// Returns tensor specs for a model shape and dtype. pub fn tensors_for_shape(shape: &ModelShape, dtype: u32) -> Vec { let hidden = shape.hidden_size; let ffn = shape.ffn_size; let vocab = shape.vocab_size; let mut tensors = vec![ tensor_spec(dtype, "tok_embeddings.weight", &[vocab, hidden], 1), tensor_spec(dtype, "norm.weight", &[hidden], 2), tensor_spec(dtype, "output.weight", &[vocab, hidden], 3), ]; for layer in 0..shape.layer_count { let prefix = format!("layers.{layer}"); tensors.push(tensor_spec( dtype, &format!("{prefix}.attention_norm.weight"), &[hidden], 4, )); tensors.push(tensor_spec( dtype, &format!("{prefix}.ffn_norm.weight"), &[hidden], 5, )); tensors.push(tensor_spec( dtype, &format!("{prefix}.wq.weight"), &[hidden, hidden], 6, )); tensors.push(tensor_spec( dtype, &format!("{prefix}.wk.weight"), &[hidden, hidden], 7, )); tensors.push(tensor_spec( dtype, &format!("{prefix}.wv.weight"), &[hidden, hidden], 8, )); tensors.push(tensor_spec( dtype, &format!("{prefix}.wo.weight"), &[hidden, hidden], 9, )); tensors.push(tensor_spec( dtype, &format!("{prefix}.w1.weight"), &[ffn, hidden], 10, )); tensors.push(tensor_spec( dtype, &format!("{prefix}.w2.weight"), &[hidden, ffn], 11, )); tensors.push(tensor_spec( dtype, &format!("{prefix}.w3.weight"), &[ffn, hidden], 12, )); } tensors } /// Returns tensor specs for a model shape using tied output projection. pub fn tensors_for_shape_with_tied_output(shape: &ModelShape, dtype: u32) -> Vec { let output_hash = name_hash("output.weight"); let mut tensors = tensors_for_shape(shape, dtype); for tensor in &mut tensors { if tensor.name_hash == name_hash("tok_embeddings.weight") { tensor.seed = 13; } } tensors.retain(|tensor| tensor.name_hash != output_hash); tensors } fn tensor_spec(dtype: u32, name: &str, dims: &[u32], seed: u32) -> TensorSpec { match dtype { DTYPE_Q8_0 => TensorSpec::q8(name, dims, seed), DTYPE_Q4_0 => TensorSpec::q4(name, dims, seed), _ => TensorSpec::f32(name, dims, seed), } } /// Computes the stable FNV-1a hash used for tensor names. pub fn name_hash(name: &str) -> u64 { let mut hash = 0xcbf29ce484222325u64; for byte in name.as_bytes() { hash ^= u64::from(*byte); hash = hash.wrapping_mul(0x100000001b3); } hash } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/tensor_writer.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/tokenizer_writer.rs BYTES: 4339 SHA256: F201E5D93D65D447553C54691BBEA55B62B7D75522060854C2402BD316C3BFFD ================================================================================ //! Tokenizer section writer. /// Tokenizer section bytes. pub struct TokenizerSection { /// Serialized tokenizer metadata. pub bytes: Vec, } /// One custom BPE token table entry. pub struct BpeTokenSpec { /// Token id, which must be outside the byte fallback range. pub id: u32, /// UTF-8 bytes or raw byte sequence represented by the token. pub bytes: Vec, } /// One ranked custom BPE merge rule. pub struct BpeMergeSpec { /// Left token id. pub left: u32, /// Right token id. pub right: u32, /// Output token id. pub output: u32, /// Lower rank values merge first. pub rank: u32, } /// Compatibility alias for the phase-one byte-tokenizer section. pub type ByteTokenizerSection = TokenizerSection; impl TokenizerSection { /// Creates a phase-one byte tokenizer metadata section. pub fn phase_one() -> Self { let mut bytes = Vec::new(); bytes.extend_from_slice(b"BTOK"); bytes.extend_from_slice(&1u32.to_le_bytes()); bytes.extend_from_slice(&260u32.to_le_bytes()); bytes.extend_from_slice(&256u32.to_le_bytes()); bytes.extend_from_slice(&257u32.to_le_bytes()); bytes.extend_from_slice(&258u32.to_le_bytes()); bytes.extend_from_slice(&259u32.to_le_bytes()); Self { bytes } } /// Creates a small deterministic BPE tokenizer metadata section for tests. /// /// The section uses byte fallback plus two merges: `t` + `h` -> `th`, /// then `th` + `e` -> `the`. pub fn tiny_bpe_demo() -> Self { let tokens = vec![ BpeTokenSpec { id: 260, bytes: b"th".to_vec(), }, BpeTokenSpec { id: 261, bytes: b"the".to_vec(), }, ]; let merges = vec![ BpeMergeSpec { left: 116, right: 104, output: 260, rank: 0, }, BpeMergeSpec { left: 260, right: 101, output: 261, rank: 1, }, ]; Self::bpe_from_parts(262, &tokens, &merges) } /// Creates a custom BPE tokenizer metadata section from manifest parts. /// /// The caller owns semantic validation; this writer serializes the /// self-contained `BPE1` section used by both runtime and native /// validation. pub fn bpe_from_parts( vocab_size: u32, tokens: &[BpeTokenSpec], merges: &[BpeMergeSpec], ) -> Self { let mut bytes = Vec::new(); bytes.extend_from_slice(b"BPE1"); bytes.extend_from_slice(&1u32.to_le_bytes()); bytes.extend_from_slice(&vocab_size.to_le_bytes()); bytes.extend_from_slice(&256u32.to_le_bytes()); bytes.extend_from_slice(&257u32.to_le_bytes()); bytes.extend_from_slice(&258u32.to_le_bytes()); bytes.extend_from_slice(&259u32.to_le_bytes()); bytes.extend_from_slice(&(tokens.len() as u32).to_le_bytes()); bytes.extend_from_slice(&(merges.len() as u32).to_le_bytes()); for token in tokens { write_token(&mut bytes, token.id, &token.bytes); } for merge in merges { write_merge( &mut bytes, merge.left, merge.right, merge.output, merge.rank, ); } Self { bytes } } } fn write_token(bytes: &mut Vec, id: u32, text: &[u8]) { bytes.extend_from_slice(&id.to_le_bytes()); bytes.extend_from_slice(&(text.len() as u32).to_le_bytes()); bytes.extend_from_slice(text); } fn write_merge(bytes: &mut Vec, left: u32, right: u32, output: u32, rank: u32) { bytes.extend_from_slice(&left.to_le_bytes()); bytes.extend_from_slice(&right.to_le_bytes()); bytes.extend_from_slice(&output.to_le_bytes()); bytes.extend_from_slice(&rank.to_le_bytes()); } #[cfg(test)] mod tests { use super::*; #[test] fn tiny_bpe_demo_writes_self_describing_section() { let section = TokenizerSection::tiny_bpe_demo(); assert_eq!(section.bytes.get(0..4), Some(&b"BPE1"[..])); assert!(section.bytes.len() > ByteTokenizerSection::phase_one().bytes.len()); } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/tokenizer_writer.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/trained_adapter_source.rs BYTES: 52496 SHA256: 223350D68D5DC97D1343757FE2F0BA6C6734E619DE6E9771DDF1EE0D8D2C8E01 ================================================================================ //! Trained low-rank adapter source layout validation. use std::collections::{HashMap, HashSet}; use std::fs; use std::io; use std::path::{Component, Path, PathBuf}; use crate::adapter::{ build_low_rank_source_adapter_bytes, low_rank_adapter_apply_status, low_rank_adapter_checksum, validate_low_rank_adapter_bytes, LowRankSourceTensor, }; use crate::blend::{hex64, parse_model_values}; use crate::slm_validate::{self, ValidationReport}; use crate::tensor_writer::{ tensors_for_shape, tensors_for_shape_with_tied_output, ModelShape, TensorSpec, DTYPE_F32, }; use crate::tokenizer_writer::TokenizerSection; const ADAPTER_SOURCE_MANIFEST_NAME: &str = "adapter-source.manifest"; const ADAPTER_SOURCE_VERSION: &str = "1"; const ADAPTER_SOURCE_LAYOUT: &str = "low-rank-f32-factor-files-v1"; const ADAPTER_SOURCE_FORMAT: &str = "trained-low-rank-factors-v1"; const SOURCE_ALR1_ARTIFACT_VERSION: &str = "1"; const SOURCE_ALR1_ARTIFACT_KIND: &str = "trained-source-low-rank-f32-v1"; const SOURCE_ALR1_STATUS: &str = "artifact-written"; const SOURCE_ALR1_DTYPE: &str = "low-rank-f32-source-delta"; const SOURCE_ALR1_BASE_CONTRACT: &str = "matches-parent-direct-parameter-contract"; const SOURCE_ALR1_REVIEWED_SOURCE_CONTRACT: &str = "matches-reviewed-adapter-source-base-contract"; const SOURCE_ALR1_REQUIRED_NEXT_GATE: &str = "runtime-smoke-plus-eval-plus-selector-adapter-family-route"; const LOW_RANK_PAYLOAD_HEADER_BYTES: usize = 16; const DEFAULT_FACTOR_RANK: usize = 1; const MAX_FACTOR_RANK: usize = 8; const MAX_ABS_FACTOR: f32 = 64.0; const MAX_ABS_RECONSTRUCTED_DELTA: f32 = 128.0; struct NamedTensor { name: String, spec: TensorSpec, } struct AdapterSourceBundle { manifest_text: String, fields: HashMap, shape: ModelShape, tied_output: bool, stats: AdapterSourceStats, targets: Vec, } struct AdapterSourceTarget { name: String, name_hash: u64, rank: u32, dims: [u32; 4], rows: usize, cols: usize, factor_rank: usize, a_values: Vec, b_values: Vec, factor_parameter_count: u64, delta_l1_microunits: u64, } #[derive(Default)] struct AdapterSourceStats { target_tensor_count: usize, target_parameter_count: u64, factor_parameter_count: u64, delta_l1_microunits: u64, } /// Writes a reviewable trained low-rank adapter source fixture directory. pub fn write_adapter_source_template_path(output_dir: &Path, shape_name: &str) -> io::Result<()> { let (shape, tied_output) = shape_for_name(shape_name)?; let targets = default_adapter_targets(&shape, tied_output)?; let factor_dir = output_dir.join("factors"); fs::create_dir_all(&factor_dir)?; let mut manifest = String::new(); push_line( &mut manifest, "tinyrustlm_trained_adapter_source_version", ADAPTER_SOURCE_VERSION, ); push_line(&mut manifest, "model_family", "tinyrustlm"); push_line( &mut manifest, "adapter_source_layout", ADAPTER_SOURCE_LAYOUT, ); push_line(&mut manifest, "adapter_format", ADAPTER_SOURCE_FORMAT); push_line(&mut manifest, "model_shape", shape_name); push_line( &mut manifest, "base_tied_output", if tied_output { "true" } else { "false" }, ); push_line(&mut manifest, "base_tokenizer", "byte-v1"); push_line(&mut manifest, "source_dtype", "f32"); push_line( &mut manifest, "adapter_source_kind", "trained-adapter-fixture", ); push_line( &mut manifest, "adapter_source_id", "tinyrustlm-local-trained-adapter-fixture", ); push_line( &mut manifest, "adapter_source_license", "local-fixture-only", ); push_line( &mut manifest, "adapter_source_dataset", "tinyrustlm-local-adapter-source-fixture", ); push_line( &mut manifest, "adapter_training_summary", "Deterministic low-rank adapter source fixture for intake validation", ); push_shape_lines(&mut manifest, &shape); push_line( &mut manifest, "target_tensor_count", &targets.len().to_string(), ); for (index, target) in targets.iter().enumerate() { let (rows, cols) = matrix_shape(&target.spec)?; let rank = DEFAULT_FACTOR_RANK.min(rows.min(cols)); let a_values = fixture_a_values(index, rows, rank); let b_values = fixture_b_values(index, rank, cols); let a_bytes = f32_values_to_bytes(&a_values); let b_bytes = f32_values_to_bytes(&b_values); let safe_name = factor_file_stem(&target.name); let a_file = format!("factors/{safe_name}.A.f32"); let b_file = format!("factors/{safe_name}.B.f32"); fs::write(output_dir.join(&a_file), &a_bytes)?; fs::write(output_dir.join(&b_file), &b_bytes)?; let prefix = format!("target.{index}"); push_line(&mut manifest, &format!("{prefix}.name"), &target.name); push_line( &mut manifest, &format!("{prefix}.name_hash"), &format!("0x{:016x}", target.spec.name_hash), ); push_line( &mut manifest, &format!("{prefix}.rank"), &target.spec.rank.to_string(), ); push_line( &mut manifest, &format!("{prefix}.dims"), &dims_text(&target.spec), ); push_line( &mut manifest, &format!("{prefix}.factor_rank"), &rank.to_string(), ); push_line( &mut manifest, &format!("{prefix}.a_shape"), &format!("{rows},{rank}"), ); push_line( &mut manifest, &format!("{prefix}.b_shape"), &format!("{rank},{cols}"), ); push_line(&mut manifest, &format!("{prefix}.a_file"), &a_file); push_line(&mut manifest, &format!("{prefix}.b_file"), &b_file); push_line( &mut manifest, &format!("{prefix}.a_bytes"), &a_bytes.len().to_string(), ); push_line( &mut manifest, &format!("{prefix}.b_bytes"), &b_bytes.len().to_string(), ); push_line( &mut manifest, &format!("{prefix}.a_checksum"), &format!("0x{:016x}", source_checksum(&a_bytes)), ); push_line( &mut manifest, &format!("{prefix}.b_checksum"), &format!("0x{:016x}", source_checksum(&b_bytes)), ); push_line( &mut manifest, &format!("{prefix}.factor_parameter_count"), &factor_parameter_count(rows, cols, rank)?.to_string(), ); push_line( &mut manifest, &format!("{prefix}.delta_l1_microunits"), &delta_l1_microunits(&a_values, &b_values, rows, cols, rank)?.to_string(), ); } fs::write(output_dir.join(ADAPTER_SOURCE_MANIFEST_NAME), manifest)?; println!( "SLM trained adapter source template written: {}", output_dir.display() ); Ok(()) } /// Validates a trained low-rank adapter source directory. pub fn validate_adapter_source_path(source_dir: &Path) -> io::Result<()> { let stats = read_adapter_source(source_dir)?; println!("SLM trained adapter source validation: PASS"); println!("adapter_source_dir: {}", source_dir.display()); println!("target_tensor_count: {}", stats.target_tensor_count); println!("target_parameter_count: {}", stats.target_parameter_count); println!("factor_parameter_count: {}", stats.factor_parameter_count); println!("delta_l1_microunits: {}", stats.delta_l1_microunits); Ok(()) } /// Converts a reviewed trained low-rank adapter source directory into ALR1. pub fn convert_adapter_source_path( source_dir: &Path, base_parent: &Path, output_adapter: &Path, output_manifest: &Path, ) -> io::Result<()> { let bundle = read_adapter_source_bundle(source_dir)?; let base_bytes = fs::read(base_parent)?; let (adapter, manifest) = build_adapter_source_alr1_bytes_and_manifest( &bundle, &base_bytes, &base_parent.display().to_string(), &source_dir.display().to_string(), &output_adapter.display().to_string(), )?; if let Some(parent) = output_adapter.parent() { fs::create_dir_all(parent)?; } fs::write(output_adapter, adapter)?; if let Some(parent) = output_manifest.parent() { fs::create_dir_all(parent)?; } fs::write(output_manifest, manifest)?; println!( "SLM trained adapter source ALR1 artifact written: {}", output_adapter.display() ); println!( "SLM trained adapter source ALR1 manifest written: {}", output_manifest.display() ); Ok(()) } /// Validates a trained adapter source ALR1 artifact by recomputing it. pub fn validate_converted_adapter_source_path( source_dir: &Path, base_parent: &Path, adapter: &Path, manifest: &Path, ) -> io::Result<()> { let bundle = read_adapter_source_bundle(source_dir)?; let base_bytes = fs::read(base_parent)?; let adapter_bytes = fs::read(adapter)?; let manifest_text = fs::read_to_string(manifest)?; validate_adapter_source_alr1_text( &bundle, &base_bytes, &base_parent.display().to_string(), &source_dir.display().to_string(), &adapter.display().to_string(), &adapter_bytes, &manifest_text, )?; println!("SLM trained adapter source ALR1 validation: PASS"); println!("adapter_source_dir: {}", source_dir.display()); println!("base_parent: {}", base_parent.display()); println!("adapter: {}", adapter.display()); println!("manifest: {}", manifest.display()); Ok(()) } fn read_adapter_source(source_dir: &Path) -> io::Result { Ok(read_adapter_source_bundle(source_dir)?.stats) } fn read_adapter_source_bundle(source_dir: &Path) -> io::Result { let manifest_path = source_dir.join(ADAPTER_SOURCE_MANIFEST_NAME); let manifest = fs::read_to_string(&manifest_path)?; let fields = parse_key_value_manifest(&manifest)?; validate_adapter_source_header(&fields)?; let (shape, tied_output) = shape_from_fields(&fields)?; validate_shape_name_and_tied_output(&fields, &shape, tied_output)?; let expected_tensors = named_tensors_for_shape(&shape, tied_output); let target_count = parse_usize_key(&fields, "target_tensor_count")?; if target_count == 0 { return Err(invalid( "adapter source requires at least one target tensor", )); } let mut seen = HashSet::new(); let mut stats = AdapterSourceStats { target_tensor_count: target_count, ..AdapterSourceStats::default() }; let mut targets = Vec::with_capacity(target_count); for index in 0..target_count { let prefix = format!("target.{index}"); let name = require_key(&fields, &format!("{prefix}.name"))?; if !seen.insert(name.to_string()) { return Err(invalid("adapter source target tensor names must be unique")); } let expected = expected_tensors .iter() .find(|tensor| tensor.name == name) .ok_or_else(|| invalid("adapter source target tensor is not in the model shape"))?; let (rows, cols) = matrix_shape(&expected.spec)?; require_equal( &fields, &format!("{prefix}.name_hash"), &format!("0x{:016x}", expected.spec.name_hash), )?; require_equal( &fields, &format!("{prefix}.rank"), &expected.spec.rank.to_string(), )?; require_equal( &fields, &format!("{prefix}.dims"), &dims_text(&expected.spec), )?; let rank = parse_usize_key(&fields, &format!("{prefix}.factor_rank"))?; if rank == 0 || rank > MAX_FACTOR_RANK || rank > rows.min(cols) { return Err(invalid("adapter source factor_rank is out of range")); } require_equal( &fields, &format!("{prefix}.a_shape"), &format!("{rows},{rank}"), )?; require_equal( &fields, &format!("{prefix}.b_shape"), &format!("{rank},{cols}"), )?; let a_values = read_factor_file(source_dir, &fields, &prefix, "a", rows * rank)?; let b_values = read_factor_file(source_dir, &fields, &prefix, "b", rank * cols)?; let factor_count = factor_parameter_count(rows, cols, rank)?; let delta_l1 = delta_l1_microunits(&a_values, &b_values, rows, cols, rank)?; require_equal( &fields, &format!("{prefix}.factor_parameter_count"), &factor_count.to_string(), )?; require_equal( &fields, &format!("{prefix}.delta_l1_microunits"), &delta_l1.to_string(), )?; stats.target_parameter_count = stats .target_parameter_count .checked_add((rows * cols) as u64) .ok_or_else(|| invalid("adapter source target parameter count overflow"))?; stats.factor_parameter_count = stats .factor_parameter_count .checked_add(factor_count) .ok_or_else(|| invalid("adapter source factor parameter count overflow"))?; stats.delta_l1_microunits = stats .delta_l1_microunits .checked_add(delta_l1) .ok_or_else(|| invalid("adapter source delta L1 count overflow"))?; targets.push(AdapterSourceTarget { name: name.to_string(), name_hash: expected.spec.name_hash, rank: expected.spec.rank, dims: expected.spec.dims, rows, cols, factor_rank: rank, a_values, b_values, factor_parameter_count: factor_count, delta_l1_microunits: delta_l1, }); } reject_extra_target_keys(&fields, target_count)?; Ok(AdapterSourceBundle { manifest_text: manifest, fields, shape, tied_output, stats, targets, }) } fn build_adapter_source_alr1_bytes_and_manifest( bundle: &AdapterSourceBundle, base_bytes: &[u8], base_path: &str, source_dir_path: &str, adapter_path: &str, ) -> io::Result<(Vec, String)> { let base_report = slm_validate::validate_bytes(base_bytes, base_path)?; let base = parse_model_values(base_bytes)?; validate_base_model_for_source(bundle, &base, &base_report)?; let source_tensors = bundle .targets .iter() .map(|target| LowRankSourceTensor { name_hash: target.name_hash, rank: target.rank, dims: target.dims, rows: target.rows, cols: target.cols, factor_rank: target.factor_rank, a_values: &target.a_values, b_values: &target.b_values, }) .collect::>(); let adapter = build_low_rank_source_adapter_bytes(&base, &base_report, &source_tensors)?; validate_low_rank_adapter_bytes(&adapter)?; let manifest = build_adapter_source_alr1_manifest( bundle, source_dir_path, base_path, &base_report, adapter_path, &adapter, )?; Ok((adapter, manifest)) } fn validate_adapter_source_alr1_text( bundle: &AdapterSourceBundle, base_bytes: &[u8], base_path: &str, source_dir_path: &str, adapter_path: &str, adapter_bytes: &[u8], manifest_text: &str, ) -> io::Result<()> { validate_low_rank_adapter_bytes(adapter_bytes)?; let (expected_adapter, expected_manifest) = build_adapter_source_alr1_bytes_and_manifest( bundle, base_bytes, base_path, source_dir_path, adapter_path, )?; if adapter_bytes != expected_adapter { return Err(invalid( "trained adapter source ALR1 bytes do not match recomputed source factors", )); } if manifest_text != expected_manifest { return Err(invalid( "trained adapter source ALR1 manifest fields do not match recomputed output", )); } Ok(()) } fn validate_base_model_for_source( bundle: &AdapterSourceBundle, base: &crate::blend::ParsedModel, base_report: &ValidationReport, ) -> io::Result<()> { if !shape_matches(&bundle.shape, &base.shape) { return Err(invalid( "adapter source model shape does not match base parent", )); } let base_tied_output = base.flags & 1 != 0; if bundle.tied_output != base_tied_output { return Err(invalid( "adapter source tied-output contract does not match base parent", )); } if base_report.output_contract_label() != if bundle.tied_output { "tied-output" } else { "explicit-output" } { return Err(invalid( "adapter source output contract does not match base parent", )); } if base.tokenizer.bytes != TokenizerSection::phase_one().bytes { return Err(invalid( "adapter source base_tokenizer does not match base parent tokenizer", )); } let base_by_hash = base .tensors .iter() .map(|tensor| (tensor.spec.name_hash, tensor)) .collect::>(); for target in &bundle.targets { let Some(base_tensor) = base_by_hash.get(&target.name_hash) else { return Err(invalid( "adapter source target tensor is missing from base parent", )); }; if base_tensor.spec.rank != target.rank || base_tensor.spec.dims != target.dims { return Err(invalid( "adapter source target tensor shape does not match base parent", )); } } Ok(()) } fn build_adapter_source_alr1_manifest( bundle: &AdapterSourceBundle, source_dir_path: &str, base_path: &str, base_report: &ValidationReport, adapter_path: &str, adapter_bytes: &[u8], ) -> io::Result { let mut text = String::new(); push_line( &mut text, "tinyrustlm_adapter_artifact_version", SOURCE_ALR1_ARTIFACT_VERSION, ); push_line( &mut text, "adapter_artifact_kind", SOURCE_ALR1_ARTIFACT_KIND, ); push_line(&mut text, "adapter_status", SOURCE_ALR1_STATUS); push_line(&mut text, "adapter_source_dir", source_dir_path); push_line( &mut text, "adapter_source_manifest", ADAPTER_SOURCE_MANIFEST_NAME, ); push_line( &mut text, "adapter_source_manifest_checksum", &hex64(source_checksum(bundle.manifest_text.as_bytes())), ); push_line(&mut text, "adapter_source_layout", ADAPTER_SOURCE_LAYOUT); push_line(&mut text, "adapter_source_format", ADAPTER_SOURCE_FORMAT); push_line( &mut text, "adapter_source_kind", require_key(&bundle.fields, "adapter_source_kind")?, ); push_line( &mut text, "adapter_source_id", require_key(&bundle.fields, "adapter_source_id")?, ); push_line( &mut text, "adapter_source_license", require_key(&bundle.fields, "adapter_source_license")?, ); push_line( &mut text, "adapter_source_dataset", require_key(&bundle.fields, "adapter_source_dataset")?, ); push_line( &mut text, "adapter_training_summary", require_key(&bundle.fields, "adapter_training_summary")?, ); push_line(&mut text, "base_parent_path", base_path); push_line( &mut text, "base_model_bytes", &base_report.file_bytes().to_string(), ); push_line( &mut text, "base_slm_version", &base_report.slm_version().to_string(), ); push_line( &mut text, "base_slm_checksum", &hex64(base_report.checksum()), ); push_line(&mut text, "base_model_shape", &base_report.shape_summary()); push_line( &mut text, "base_tensor_count", &base_report.tensor_count().to_string(), ); push_line( &mut text, "base_parameter_count", &base_report.parameter_count().to_string(), ); push_line( &mut text, "base_quantization", base_report.quantization_label(), ); push_line( &mut text, "base_output_contract", base_report.output_contract_label(), ); push_line( &mut text, "base_tokenizer_checksum", &hex64(base_report.tokenizer_checksum()), ); push_line( &mut text, "base_tensor_layout_checksum", &hex64(base_report.tensor_layout_checksum()), ); push_line(&mut text, "adapter_artifact_path", adapter_path); push_line( &mut text, "adapter_artifact_bytes", &adapter_bytes.len().to_string(), ); push_line( &mut text, "adapter_artifact_checksum", &hex64(low_rank_adapter_checksum(adapter_bytes)?), ); push_line( &mut text, "adapter_tensor_count", &base_report.tensor_count().to_string(), ); push_line( &mut text, "adapter_parameter_count", &base_report.parameter_count().to_string(), ); push_line(&mut text, "adapter_dtype", SOURCE_ALR1_DTYPE); push_line( &mut text, "adapter_model_shape", &base_report.shape_summary(), ); push_line( &mut text, "adapter_base_quantization", base_report.quantization_label(), ); push_line( &mut text, "adapter_output_contract", base_report.output_contract_label(), ); push_line( &mut text, "adapter_tokenizer_checksum", &hex64(base_report.tokenizer_checksum()), ); push_line( &mut text, "adapter_tensor_layout_checksum", &hex64(base_report.tensor_layout_checksum()), ); push_line( &mut text, "adapter_base_contract", SOURCE_ALR1_BASE_CONTRACT, ); push_line( &mut text, "adapter_source_base_contract", SOURCE_ALR1_REVIEWED_SOURCE_CONTRACT, ); push_line(&mut text, "adapter_low_rank_format", "ALR1"); push_line( &mut text, "adapter_low_rank_component_cap", &MAX_FACTOR_RANK.to_string(), ); push_line( &mut text, "adapter_low_rank_payload_header_bytes", &LOW_RANK_PAYLOAD_HEADER_BYTES.to_string(), ); push_line(&mut text, "adapter_low_rank_factor_dtype", "f32"); push_line( &mut text, "adapter_low_rank_selection", "reviewed-trained-source-factors", ); push_line( &mut text, "adapter_low_rank_scope", "adapter-source-target-matrix-tensors", ); push_line( &mut text, "adapter_source_target_tensor_count", &bundle.stats.target_tensor_count.to_string(), ); push_line( &mut text, "adapter_source_target_parameter_count", &bundle.stats.target_parameter_count.to_string(), ); push_line( &mut text, "adapter_low_rank_active_tensor_count", &bundle.stats.target_tensor_count.to_string(), ); push_line( &mut text, "adapter_low_rank_component_count", &source_component_count(bundle)?.to_string(), ); push_line( &mut text, "adapter_low_rank_factor_parameter_count", &bundle.stats.factor_parameter_count.to_string(), ); push_line( &mut text, "adapter_low_rank_factor_density_ppm", &ratio_ppm( bundle.stats.factor_parameter_count, bundle.stats.target_parameter_count, )? .to_string(), ); push_line( &mut text, "adapter_source_delta_l1_microunits", &bundle.stats.delta_l1_microunits.to_string(), ); for (index, target) in bundle.targets.iter().enumerate() { let prefix = format!("source_target.{index}"); push_line(&mut text, &format!("{prefix}.name"), &target.name); push_line( &mut text, &format!("{prefix}.name_hash"), &hex64(target.name_hash), ); push_line( &mut text, &format!("{prefix}.factor_rank"), &target.factor_rank.to_string(), ); push_line( &mut text, &format!("{prefix}.factor_parameter_count"), &target.factor_parameter_count.to_string(), ); push_line( &mut text, &format!("{prefix}.delta_l1_microunits"), &target.delta_l1_microunits.to_string(), ); } push_line( &mut text, "adapter_apply_status", low_rank_adapter_apply_status(base_report), ); push_line( &mut text, "required_next_gate", SOURCE_ALR1_REQUIRED_NEXT_GATE, ); Ok(text) } fn source_component_count(bundle: &AdapterSourceBundle) -> io::Result { bundle.targets.iter().try_fold(0u64, |acc, target| { acc.checked_add(target.factor_rank as u64) .ok_or_else(|| invalid("adapter source component count overflow")) }) } fn ratio_ppm(numerator: u64, denominator: u64) -> io::Result { if denominator == 0 { return Ok(0); } let scaled = (u128::from(numerator) * 1_000_000u128) / u128::from(denominator); if scaled > u128::from(u32::MAX) { return Err(invalid("adapter source ratio ppm overflow")); } Ok(scaled as u32) } fn validate_adapter_source_header(fields: &HashMap) -> io::Result<()> { require_equal( fields, "tinyrustlm_trained_adapter_source_version", ADAPTER_SOURCE_VERSION, )?; require_equal(fields, "model_family", "tinyrustlm")?; require_equal(fields, "adapter_source_layout", ADAPTER_SOURCE_LAYOUT)?; require_equal(fields, "adapter_format", ADAPTER_SOURCE_FORMAT)?; require_equal(fields, "base_tokenizer", "byte-v1")?; require_equal(fields, "source_dtype", "f32")?; match require_key(fields, "adapter_source_kind")? { "trained-adapter-fixture" | "trained-adapter-export" => {} _ => { return Err(invalid( "adapter_source_kind must be trained-adapter-fixture or trained-adapter-export", )); } } require_evidence_field(fields, "adapter_source_id")?; require_evidence_field(fields, "adapter_source_license")?; require_evidence_field(fields, "adapter_source_dataset")?; require_evidence_field(fields, "adapter_training_summary")?; Ok(()) } fn shape_for_name(shape_name: &str) -> io::Result<(ModelShape, bool)> { match shape_name { "tiny-fixture" => Ok((ModelShape::tiny_fixture(), false)), "tiny-fixture-tied" => Ok((ModelShape::tiny_fixture(), true)), "tinylm16" => Ok((ModelShape::tinylm16(), false)), "tinylm16-tied" => Ok((ModelShape::tinylm16(), true)), _ => Err(invalid( "adapter-source-template shape must be tiny-fixture, tiny-fixture-tied, tinylm16, or tinylm16-tied", )), } } fn shape_from_fields(fields: &HashMap) -> io::Result<(ModelShape, bool)> { let shape = ModelShape { vocab_size: parse_u32_key(fields, "vocab_size")?, special_token_count: parse_u32_key(fields, "special_token_count")?, hidden_size: parse_u32_key(fields, "hidden_size")?, layer_count: parse_u32_key(fields, "layer_count")?, head_count: parse_u32_key(fields, "head_count")?, kv_head_count: parse_u32_key(fields, "kv_head_count")?, head_dim: parse_u32_key(fields, "head_dim")?, ffn_size: parse_u32_key(fields, "ffn_size")?, max_context: parse_u32_key(fields, "max_context")?, }; if shape.vocab_size < 260 || shape.special_token_count < 4 { return Err(invalid( "adapter source shape must support the phase-one byte tokenizer", )); } if shape.hidden_size == 0 || shape.layer_count == 0 || shape.head_count == 0 || shape.kv_head_count == 0 || shape.head_dim == 0 || shape.ffn_size == 0 || shape.max_context == 0 { return Err(invalid("adapter source shape dimensions must be nonzero")); } if shape.head_count.checked_mul(shape.head_dim) != Some(shape.hidden_size) { return Err(invalid( "adapter source hidden_size must equal heads * head_dim", )); } if shape.kv_head_count > shape.head_count || shape.head_count % shape.kv_head_count != 0 { return Err(invalid( "adapter source kv_head_count must divide head_count", )); } let tied_output = match fields.get("base_tied_output").map(String::as_str) { Some("true") => true, Some("false") => false, _ => { return Err(invalid( "adapter source base_tied_output must be true or false", )); } }; Ok((shape, tied_output)) } fn validate_shape_name_and_tied_output( fields: &HashMap, shape: &ModelShape, tied_output: bool, ) -> io::Result<()> { let shape_name = require_key(fields, "model_shape")?; let (expected_shape, expected_tied) = shape_for_name(shape_name)?; if !shape_matches(shape, &expected_shape) || tied_output != expected_tied { return Err(invalid( "adapter source model_shape and base_tied_output must match dimensions", )); } Ok(()) } fn default_adapter_targets(shape: &ModelShape, tied_output: bool) -> io::Result> { let mut selected = Vec::new(); for target_name in ["layers.0.wq.weight", "layers.0.w1.weight"] { let tensor = named_tensors_for_shape(shape, tied_output) .into_iter() .find(|entry| entry.name == target_name) .ok_or_else(|| invalid("adapter source template target tensor is missing"))?; selected.push(tensor); } Ok(selected) } fn named_tensors_for_shape(shape: &ModelShape, tied_output: bool) -> Vec { let tensors = if tied_output { tensors_for_shape_with_tied_output(shape, DTYPE_F32) } else { tensors_for_shape(shape, DTYPE_F32) }; tensor_names_for_shape(shape, tied_output) .into_iter() .zip(tensors) .map(|(name, spec)| NamedTensor { name, spec }) .collect() } fn tensor_names_for_shape(shape: &ModelShape, tied_output: bool) -> Vec { let mut names = vec![ "tok_embeddings.weight".to_string(), "norm.weight".to_string(), ]; if !tied_output { names.push("output.weight".to_string()); } for layer in 0..shape.layer_count { for suffix in [ "attention_norm.weight", "ffn_norm.weight", "wq.weight", "wk.weight", "wv.weight", "wo.weight", "w1.weight", "w2.weight", "w3.weight", ] { names.push(format!("layers.{layer}.{suffix}")); } } names } fn read_factor_file( source_dir: &Path, fields: &HashMap, prefix: &str, side: &str, expected_values: usize, ) -> io::Result> { let relative_file = require_key(fields, &format!("{prefix}.{side}_file"))?; let path = safe_factor_path(source_dir, relative_file)?; let bytes = fs::read(&path)?; require_equal( fields, &format!("{prefix}.{side}_bytes"), &bytes.len().to_string(), )?; require_equal( fields, &format!("{prefix}.{side}_checksum"), &format!("0x{:016x}", source_checksum(&bytes)), )?; read_f32_values(&bytes, expected_values) } fn read_f32_values(bytes: &[u8], expected_values: usize) -> io::Result> { let expected_bytes = expected_values .checked_mul(4) .ok_or_else(|| invalid("adapter source factor byte length overflow"))?; if bytes.len() != expected_bytes { return Err(invalid( "adapter source factor byte length does not match shape", )); } let mut values = Vec::with_capacity(expected_values); let mut any_nonzero = false; for chunk in bytes.chunks_exact(4) { let value = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); if !value.is_finite() { return Err(invalid( "adapter source factor contains a non-finite f32 value", )); } if value.abs() > MAX_ABS_FACTOR { return Err(invalid( "adapter source factor contains an out-of-range f32 value", )); } any_nonzero |= value != 0.0; values.push(value); } if !any_nonzero { return Err(invalid("adapter source factor must not be entirely zero")); } Ok(values) } fn delta_l1_microunits( a_values: &[f32], b_values: &[f32], rows: usize, cols: usize, rank: usize, ) -> io::Result { let mut total = 0.0f64; for row in 0..rows { for col in 0..cols { let mut value = 0.0f32; for component in 0..rank { value += a_values[row * rank + component] * b_values[component * cols + col]; } if !value.is_finite() { return Err(invalid("adapter source reconstructed delta is not finite")); } if value.abs() > MAX_ABS_RECONSTRUCTED_DELTA { return Err(invalid( "adapter source reconstructed delta is out of range", )); } total += f64::from(value.abs()); } } let scaled = (total * 1_000_000.0).round(); if !scaled.is_finite() || scaled < 0.0 || scaled > u64::MAX as f64 { return Err(invalid("adapter source delta L1 value overflow")); } Ok(scaled as u64) } fn factor_parameter_count(rows: usize, cols: usize, rank: usize) -> io::Result { let total = rows .checked_mul(rank) .and_then(|left| { rank.checked_mul(cols) .and_then(|right| left.checked_add(right)) }) .ok_or_else(|| invalid("adapter source factor parameter count overflow"))?; Ok(total as u64) } fn matrix_shape(spec: &TensorSpec) -> io::Result<(usize, usize)> { if spec.rank < 2 { return Err(invalid("adapter source target tensor must be a matrix")); } let rows = spec.dims[0] as usize; if rows == 0 { return Err(invalid("adapter source matrix row count is zero")); } let mut cols = 1usize; for dim in spec.dims.iter().take(spec.rank as usize).skip(1) { if *dim == 0 { return Err(invalid("adapter source matrix column dimension is zero")); } cols = cols .checked_mul(*dim as usize) .ok_or_else(|| invalid("adapter source matrix column count overflow"))?; } Ok((rows, cols)) } fn safe_factor_path(source_dir: &Path, relative_file: &str) -> io::Result { let path = Path::new(relative_file); if path.is_absolute() { return Err(invalid("adapter source factor file path must be relative")); } let mut components = path.components(); match components.next() { Some(Component::Normal(first)) if first == "factors" => {} _ => { return Err(invalid( "adapter source factor files must live under factors/", )) } } for component in components { match component { Component::Normal(_) => {} _ => return Err(invalid("adapter source factor file path is not safe")), } } Ok(source_dir.join(path)) } fn reject_extra_target_keys( fields: &HashMap, target_count: usize, ) -> io::Result<()> { for key in fields.keys() { if let Some(rest) = key.strip_prefix("target.") { let Some((index_text, field_name)) = rest.split_once('.') else { return Err(invalid(&format!("adapter source key {key} is malformed"))); }; let index = index_text .parse::() .map_err(|_| invalid(&format!("adapter source key {key} has invalid index")))?; if index >= target_count { return Err(invalid(&format!( "adapter source key {key} is outside declared target_tensor_count" ))); } match field_name { "name" | "name_hash" | "rank" | "dims" | "factor_rank" | "a_shape" | "b_shape" | "a_file" | "b_file" | "a_bytes" | "b_bytes" | "a_checksum" | "b_checksum" | "factor_parameter_count" | "delta_l1_microunits" => {} _ => { return Err(invalid(&format!( "adapter source key {key} has unknown field" ))); } } } } Ok(()) } fn fixture_a_values(target_index: usize, rows: usize, rank: usize) -> Vec { let mut values = Vec::with_capacity(rows * rank); for row in 0..rows { for component in 0..rank { let seed = (target_index + 1) as f32 * 0.00025; values.push(seed * (row as f32 + 1.0) * (component as f32 + 1.0)); } } values } fn fixture_b_values(target_index: usize, rank: usize, cols: usize) -> Vec { let mut values = Vec::with_capacity(rank * cols); for component in 0..rank { for col in 0..cols { let seed = (target_index + 1) as f32 * 0.0001; let sign = if col % 2 == 0 { 1.0 } else { -1.0 }; values.push(sign * seed * (component as f32 + 1.0) * (col as f32 + 1.0)); } } values } fn f32_values_to_bytes(values: &[f32]) -> Vec { let mut bytes = Vec::with_capacity(values.len() * 4); for value in values { bytes.extend_from_slice(&value.to_le_bytes()); } bytes } fn factor_file_stem(name: &str) -> String { let mut file = String::new(); for ch in name.chars() { if ch.is_ascii_alphanumeric() { file.push(ch); } else { file.push('_'); } } file } fn shape_matches(a: &ModelShape, b: &ModelShape) -> bool { a.vocab_size == b.vocab_size && a.special_token_count == b.special_token_count && a.hidden_size == b.hidden_size && a.layer_count == b.layer_count && a.head_count == b.head_count && a.kv_head_count == b.kv_head_count && a.head_dim == b.head_dim && a.ffn_size == b.ffn_size && a.max_context == b.max_context } fn dims_text(tensor: &TensorSpec) -> String { let mut text = String::new(); for (index, dim) in tensor.dims.iter().take(tensor.rank as usize).enumerate() { if index > 0 { text.push(','); } text.push_str(&dim.to_string()); } text } fn push_shape_lines(text: &mut String, shape: &ModelShape) { push_line(text, "vocab_size", &shape.vocab_size.to_string()); push_line( text, "special_token_count", &shape.special_token_count.to_string(), ); push_line(text, "hidden_size", &shape.hidden_size.to_string()); push_line(text, "layer_count", &shape.layer_count.to_string()); push_line(text, "head_count", &shape.head_count.to_string()); push_line(text, "kv_head_count", &shape.kv_head_count.to_string()); push_line(text, "head_dim", &shape.head_dim.to_string()); push_line(text, "ffn_size", &shape.ffn_size.to_string()); push_line(text, "max_context", &shape.max_context.to_string()); } fn parse_key_value_manifest(text: &str) -> io::Result> { let mut fields = HashMap::new(); for (line_index, raw_line) in text.lines().enumerate() { let line = raw_line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let Some((key, value)) = line.split_once('=') else { return Err(invalid(&format!( "adapter source manifest line {} is missing '='", line_index + 1 ))); }; let key = key.trim(); let value = value.trim(); if key.is_empty() || value.is_empty() { return Err(invalid(&format!( "adapter source manifest line {} has an empty key or value", line_index + 1 ))); } if fields.insert(key.to_string(), value.to_string()).is_some() { return Err(invalid(&format!( "duplicate adapter source manifest key {key}" ))); } } Ok(fields) } fn require_evidence_field(fields: &HashMap, key: &str) -> io::Result<()> { let value = require_key(fields, key)?; if value == "pending" || value == "not-reviewed" || value == "not-provided" || value.len() < 8 { return Err(invalid(&format!( "adapter source field {key} must contain reviewed routing evidence" ))); } Ok(()) } fn parse_u32_key(fields: &HashMap, key: &str) -> io::Result { require_key(fields, key)? .parse::() .map_err(|_| invalid(&format!("adapter source manifest key {key} must be a u32"))) } fn parse_usize_key(fields: &HashMap, key: &str) -> io::Result { require_key(fields, key)?.parse::().map_err(|_| { invalid(&format!( "adapter source manifest key {key} must be a usize" )) }) } fn require_key<'a>(fields: &'a HashMap, key: &str) -> io::Result<&'a str> { fields.get(key).map(String::as_str).ok_or_else(|| { invalid(&format!( "adapter source manifest missing required key {key}" )) }) } fn require_equal(fields: &HashMap, key: &str, expected: &str) -> io::Result<()> { let actual = require_key(fields, key)?; if actual != expected { return Err(invalid(&format!( "adapter source manifest key {key} was {actual}, expected {expected}" ))); } Ok(()) } fn push_line(text: &mut String, key: &str, value: &str) { text.push_str(key); text.push('='); text.push_str(value); text.push('\n'); } fn source_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x6eed0e9da4d94a4fu64; for (index, byte) in bytes.iter().enumerate() { acc ^= u64::from(*byte).wrapping_add((index as u64) << 3); acc = acc.rotate_left(11).wrapping_mul(0x100000001b3); } acc } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } #[cfg(test)] mod tests { use super::*; use crate::build_model_file_with_flags; use crate::tensor_writer::{ name_hash, tensors_for_shape, tensors_for_shape_with_tied_output, DTYPE_Q8_0, }; #[test] fn validates_generated_adapter_source_fixture() { let dir = temp_path("adapter-source-fixture"); write_adapter_source_template_path(&dir, "tiny-fixture").unwrap(); let manifest = fs::read_to_string(dir.join(ADAPTER_SOURCE_MANIFEST_NAME)).unwrap(); assert!(manifest.contains("adapter_source_layout=low-rank-f32-factor-files-v1")); assert!(manifest.contains("adapter_format=trained-low-rank-factors-v1")); assert!(manifest.contains("target.0.name=layers.0.wq.weight")); assert!(manifest.contains("target.1.name=layers.0.w1.weight")); validate_adapter_source_path(&dir).unwrap(); } #[test] fn validates_tied_adapter_source_fixture_without_output_tensor() { let dir = temp_path("adapter-source-tied-fixture"); write_adapter_source_template_path(&dir, "tiny-fixture-tied").unwrap(); let manifest = fs::read_to_string(dir.join(ADAPTER_SOURCE_MANIFEST_NAME)).unwrap(); assert!(manifest.contains("model_shape=tiny-fixture-tied")); assert!(manifest.contains("base_tied_output=true")); assert!(!manifest.contains("target.0.name=output.weight")); validate_adapter_source_path(&dir).unwrap(); } #[test] fn converts_adapter_source_to_alr1_fixture() { let dir = temp_path("adapter-source-alr1-fixture"); write_adapter_source_template_path(&dir, "tiny-fixture").unwrap(); let base_path = dir.join("base.slm"); write_tiny_base(&base_path, DTYPE_F32, false); let adapter_path = dir.join("source.alr1"); let manifest_path = dir.join("source.alr1.manifest"); convert_adapter_source_path(&dir, &base_path, &adapter_path, &manifest_path).unwrap(); let adapter = fs::read(&adapter_path).unwrap(); assert_eq!(adapter.get(0..4), Some(&b"ALR1"[..])); let manifest = fs::read_to_string(&manifest_path).unwrap(); assert!(manifest.contains("adapter_artifact_kind=trained-source-low-rank-f32-v1")); assert!(manifest.contains("adapter_dtype=low-rank-f32-source-delta")); assert!(manifest.contains("adapter_source_manifest_checksum=0x")); assert!(manifest.contains("source_target.0.name=layers.0.wq.weight")); validate_converted_adapter_source_path(&dir, &base_path, &adapter_path, &manifest_path) .unwrap(); } #[test] fn converts_adapter_source_to_quantized_base_alr1_fixture() { let dir = temp_path("adapter-source-q8-alr1-fixture"); write_adapter_source_template_path(&dir, "tiny-fixture").unwrap(); let base_path = dir.join("base-q8.slm"); write_tiny_base(&base_path, DTYPE_Q8_0, false); let adapter_path = dir.join("source-q8.alr1"); let manifest_path = dir.join("source-q8.alr1.manifest"); convert_adapter_source_path(&dir, &base_path, &adapter_path, &manifest_path).unwrap(); let manifest = fs::read_to_string(&manifest_path).unwrap(); assert!(manifest.contains("base_quantization=q8_0")); assert!(manifest.contains("adapter_apply_status=runtime-q8-q4-compatible-low-rank")); validate_converted_adapter_source_path(&dir, &base_path, &adapter_path, &manifest_path) .unwrap(); } #[test] fn rejects_adapter_source_alr1_base_contract_mismatch() { let dir = temp_path("adapter-source-alr1-base-mismatch"); write_adapter_source_template_path(&dir, "tiny-fixture").unwrap(); let base_path = dir.join("base-tied.slm"); write_tiny_base(&base_path, DTYPE_F32, true); let adapter_path = dir.join("source.alr1"); let manifest_path = dir.join("source.alr1.manifest"); let error = convert_adapter_source_path(&dir, &base_path, &adapter_path, &manifest_path) .unwrap_err(); assert!(error.to_string().contains("tied-output contract")); } #[test] fn rejects_adapter_source_alr1_artifact_drift() { let dir = temp_path("adapter-source-alr1-drift"); write_adapter_source_template_path(&dir, "tiny-fixture").unwrap(); let base_path = dir.join("base.slm"); write_tiny_base(&base_path, DTYPE_F32, false); let adapter_path = dir.join("source.alr1"); let manifest_path = dir.join("source.alr1.manifest"); convert_adapter_source_path(&dir, &base_path, &adapter_path, &manifest_path).unwrap(); let mut adapter = fs::read(&adapter_path).unwrap(); let last = adapter.len() - 1; adapter[last] ^= 0x01; fs::write(&adapter_path, adapter).unwrap(); let error = validate_converted_adapter_source_path(&dir, &base_path, &adapter_path, &manifest_path) .unwrap_err(); assert!(error.to_string().contains("checksum mismatch")); } #[test] fn rejects_adapter_source_checksum_drift() { let dir = temp_path("adapter-source-checksum-drift"); write_adapter_source_template_path(&dir, "tiny-fixture").unwrap(); let manifest = fs::read_to_string(dir.join(ADAPTER_SOURCE_MANIFEST_NAME)).unwrap(); let a_file = manifest .lines() .find_map(|line| line.strip_prefix("target.0.a_file=")) .unwrap(); let path = dir.join(a_file); let mut bytes = fs::read(&path).unwrap(); bytes[0] ^= 0x01; fs::write(path, bytes).unwrap(); let error = validate_adapter_source_path(&dir).unwrap_err(); assert!(error.to_string().contains("target.0.a_checksum")); } #[test] fn rejects_adapter_source_path_escape() { let dir = temp_path("adapter-source-path-escape"); write_adapter_source_template_path(&dir, "tiny-fixture").unwrap(); replace_manifest_value( &dir.join(ADAPTER_SOURCE_MANIFEST_NAME), "target.0.a_file", "factors/../outside.f32", ); let error = validate_adapter_source_path(&dir).unwrap_err(); assert!(error.to_string().contains("factor file path is not safe")); } #[test] fn rejects_non_finite_adapter_source_factor() { let dir = temp_path("adapter-source-non-finite"); write_adapter_source_template_path(&dir, "tiny-fixture").unwrap(); let manifest_path = dir.join(ADAPTER_SOURCE_MANIFEST_NAME); let manifest = fs::read_to_string(&manifest_path).unwrap(); let a_file = manifest .lines() .find_map(|line| line.strip_prefix("target.0.a_file=")) .unwrap(); let path = dir.join(a_file); let mut bytes = fs::read(&path).unwrap(); bytes[0..4].copy_from_slice(&f32::NAN.to_le_bytes()); fs::write(&path, &bytes).unwrap(); replace_manifest_value( &manifest_path, "target.0.a_checksum", &format!("0x{:016x}", source_checksum(&bytes)), ); let error = validate_adapter_source_path(&dir).unwrap_err(); assert!(error.to_string().contains("non-finite")); } fn replace_manifest_value(path: &Path, key: &str, value: &str) { let text = fs::read_to_string(path).unwrap(); let mut updated = String::new(); for line in text.lines() { if line.starts_with(&format!("{key}=")) { updated.push_str(key); updated.push('='); updated.push_str(value); updated.push('\n'); } else { updated.push_str(line); updated.push('\n'); } } fs::write(path, updated).unwrap(); } fn write_tiny_base(path: &Path, dtype: u32, tied_output: bool) { let shape = ModelShape::tiny_fixture(); let tensors = if tied_output { tensors_for_shape_with_tied_output(&shape, dtype) } else { tensors_for_shape(&shape, dtype) }; let tokenizer = TokenizerSection::phase_one(); let flags = if tied_output { 1 } else { 0 }; let bytes = build_model_file_with_flags(&shape, &tensors, &tokenizer, flags).unwrap(); fs::write(path, bytes).unwrap(); } fn temp_path(label: &str) -> PathBuf { let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-{label}-{nanos}")) } #[test] fn name_hash_matches_tensor_spec_for_targets() { let dir = temp_path("adapter-source-hash"); write_adapter_source_template_path(&dir, "tiny-fixture").unwrap(); let manifest = fs::read_to_string(dir.join(ADAPTER_SOURCE_MANIFEST_NAME)).unwrap(); assert!(manifest.contains(&format!( "target.0.name_hash=0x{:016x}", name_hash("layers.0.wq.weight") ))); } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/trained_adapter_source.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/trained_source.rs BYTES: 40482 SHA256: 54A054A391D60584BE042D8A02ECF9C5E4726388566C0AB3695C2CAFE5DA8E3A ================================================================================ //! Trained source-weight layout validation and conversion. use std::collections::HashMap; use std::fs; use std::io; use std::path::{Component, Path, PathBuf}; use crate::provenance; use crate::slm_validate; use crate::tensor_writer::{ tensors_for_shape, tensors_for_shape_with_tied_output, ModelShape, TensorSpec, DTYPE_F32, DTYPE_Q4_0, DTYPE_Q8_0, }; use crate::tokenizer_writer::{BpeMergeSpec, BpeTokenSpec, TokenizerSection}; use crate::{build_model_file_from_values_with_flags, fixture_value}; const SOURCE_MANIFEST_NAME: &str = "source.manifest"; const SOURCE_VERSION: &str = "1"; const SOURCE_LAYOUT: &str = "raw-f32-tensor-files-v1"; const MAX_ABS_SOURCE_WEIGHT: f32 = 64.0; const FLAG_TIED_OUTPUT: u32 = 1; struct SourceBundle { shape: ModelShape, tied_output: bool, tokenizer: TokenizerSection, tensors: Vec, values: Vec>, } #[derive(Clone, Copy)] enum SourceTokenizerTemplate { Byte, TinyBpeDemo, } struct SourceTemplate { shape: ModelShape, tied_output: bool, tokenizer: SourceTokenizerTemplate, } /// Writes a reviewable raw-f32 trained-source fixture directory. pub fn write_source_template_path(output_dir: &Path, shape_name: &str) -> io::Result<()> { let template = template_for_name(shape_name)?; let shape = template.shape; let tied_output = template.tied_output; let tensors = tensors_for_shape_and_output(&shape, DTYPE_F32, tied_output); let tensor_names = tensor_names_for_shape(&shape, tied_output); let tensor_dir = output_dir.join("tensors"); fs::create_dir_all(&tensor_dir)?; let mut manifest = String::new(); push_line( &mut manifest, "tinyrustlm_trained_source_version", SOURCE_VERSION, ); push_line(&mut manifest, "model_family", "tinyrustlm"); push_line(&mut manifest, "layout", SOURCE_LAYOUT); push_line(&mut manifest, "model_shape", shape_name); push_line( &mut manifest, "tied_output", if tied_output { "true" } else { "false" }, ); push_tokenizer_template_lines(&mut manifest, template.tokenizer); push_line(&mut manifest, "source_dtype", "f32"); push_line(&mut manifest, "source_kind", "trained-source-fixture"); push_line( &mut manifest, "source_id", "tinyrustlm-local-source-fixture", ); push_line(&mut manifest, "source_license", "local-fixture-only"); push_line( &mut manifest, "source_dataset", "tinyrustlm-local-conversion-fixture", ); push_line( &mut manifest, "source_training_summary", "Deterministic source-weight fixture for conversion path validation", ); push_shape_lines(&mut manifest, &shape); push_line(&mut manifest, "tensor_count", &tensors.len().to_string()); for (index, tensor) in tensors.iter().enumerate() { let tensor_name = &tensor_names[index]; let relative_file = format!("tensors/{}", tensor_file_name(&tensor_name)); let file_path = output_dir.join(&relative_file); let bytes = source_tensor_bytes(tensor)?; fs::write(&file_path, &bytes)?; let prefix = format!("tensor.{index}"); push_line(&mut manifest, &format!("{prefix}.name"), &tensor_name); push_line( &mut manifest, &format!("{prefix}.rank"), &tensor.rank.to_string(), ); push_line(&mut manifest, &format!("{prefix}.dims"), &dims_text(tensor)); push_line(&mut manifest, &format!("{prefix}.file"), &relative_file); push_line( &mut manifest, &format!("{prefix}.bytes"), &bytes.len().to_string(), ); push_line( &mut manifest, &format!("{prefix}.checksum"), &format!("0x{:016x}", source_checksum(&bytes)), ); } fs::write(output_dir.join(SOURCE_MANIFEST_NAME), manifest)?; println!("SLM source template written: {}", output_dir.display()); Ok(()) } /// Validates a raw-f32 trained-source directory and prints an admission report. pub fn validate_source_path(source_dir: &Path) -> io::Result<()> { let bundle = read_source_bundle(source_dir)?; println!("SLM source validation: PASS"); println!("source_dir: {}", source_dir.display()); println!( "shape: vocab={} hidden={} layers={} heads={} kv_heads={} head_dim={} ffn={} context={}", bundle.shape.vocab_size, bundle.shape.hidden_size, bundle.shape.layer_count, bundle.shape.head_count, bundle.shape.kv_head_count, bundle.shape.head_dim, bundle.shape.ffn_size, bundle.shape.max_context ); println!("tensor_count: {}", bundle.tensors.len()); println!("source_dtype: f32"); println!("tied_output: {}", bundle.tied_output); Ok(()) } /// Converts a validated raw-f32 trained-source directory into an `.slm` artifact. pub fn convert_trained_path( source_dir: &Path, output_slm: &Path, output_quantization: &str, ) -> io::Result<()> { let bundle = read_source_bundle(source_dir)?; let dtype = dtype_for_output(output_quantization)?; let output_tensors = tensors_for_shape_and_output(&bundle.shape, dtype, bundle.tied_output); let flags = if bundle.tied_output { FLAG_TIED_OUTPUT } else { 0 }; let bytes = build_model_file_from_values_with_flags( &bundle.shape, &output_tensors, &bundle.tokenizer, &bundle.values, flags, )?; if let Some(parent) = output_slm.parent() { fs::create_dir_all(parent)?; } fs::write(output_slm, &bytes)?; let report = slm_validate::validate_bytes(&bytes, &output_slm.display().to_string())?; println!( "SLM converted trained source written: {}", output_slm.display() ); println!("quantization: {}", report.quantization_label()); println!("checksum: 0x{:016x}", report.checksum()); let manifest = sidecar_manifest_path(output_slm); provenance::write_manifest_for_path(output_slm, &manifest, "converted-trained")?; Ok(()) } fn read_source_bundle(source_dir: &Path) -> io::Result { let manifest_path = source_dir.join(SOURCE_MANIFEST_NAME); let manifest = fs::read_to_string(&manifest_path)?; let fields = parse_key_value_manifest(&manifest)?; validate_source_header(&fields)?; let shape = shape_from_fields(&fields)?; let tied_output = tied_output_from_fields(&fields)?; validate_shape_name_and_tied_output(&fields, &shape, tied_output)?; validate_shape_name_and_tokenizer(&fields)?; let tokenizer = tokenizer_from_fields(&fields, &shape)?; let expected_tensors = tensors_for_shape_and_output(&shape, DTYPE_F32, tied_output); let expected_names = tensor_names_for_shape(&shape, tied_output); require_equal(&fields, "tensor_count", &expected_tensors.len().to_string())?; let mut values = Vec::with_capacity(expected_tensors.len()); for (index, expected) in expected_tensors.iter().enumerate() { let name = &expected_names[index]; let prefix = format!("tensor.{index}"); require_equal(&fields, &format!("{prefix}.name"), name)?; require_equal( &fields, &format!("{prefix}.rank"), &expected.rank.to_string(), )?; require_equal(&fields, &format!("{prefix}.dims"), &dims_text(expected))?; let relative_file = require_key(&fields, &format!("{prefix}.file"))?; let tensor_path = safe_tensor_path(source_dir, relative_file)?; let bytes = fs::read(&tensor_path)?; require_equal( &fields, &format!("{prefix}.bytes"), &bytes.len().to_string(), )?; require_equal( &fields, &format!("{prefix}.checksum"), &format!("0x{:016x}", source_checksum(&bytes)), )?; values.push(read_raw_f32_values(&bytes, expected)?); } Ok(SourceBundle { shape, tied_output, tokenizer, tensors: expected_tensors, values, }) } fn validate_source_header(fields: &HashMap) -> io::Result<()> { require_equal(fields, "tinyrustlm_trained_source_version", SOURCE_VERSION)?; require_equal(fields, "model_family", "tinyrustlm")?; require_equal(fields, "layout", SOURCE_LAYOUT)?; match require_key(fields, "tokenizer")? { "byte-v1" | "bpe-v1" => {} _ => return Err(invalid("source tokenizer must be byte-v1 or bpe-v1")), } require_equal(fields, "source_dtype", "f32")?; match require_key(fields, "source_kind")? { "trained-source-fixture" | "trained-export" => {} _ => { return Err(invalid( "source_kind must be trained-source-fixture or trained-export", )); } } require_evidence_field(fields, "source_id")?; require_evidence_field(fields, "source_license")?; require_evidence_field(fields, "source_dataset")?; require_evidence_field(fields, "source_training_summary")?; Ok(()) } fn template_for_name(shape_name: &str) -> io::Result { match shape_name { "tiny-fixture" => Ok(SourceTemplate { shape: ModelShape::tiny_fixture(), tied_output: false, tokenizer: SourceTokenizerTemplate::Byte, }), "tiny-fixture-tied" => Ok(SourceTemplate { shape: ModelShape::tiny_fixture(), tied_output: true, tokenizer: SourceTokenizerTemplate::Byte, }), "tiny-fixture-bpe" => Ok(SourceTemplate { shape: tiny_bpe_fixture_shape(), tied_output: false, tokenizer: SourceTokenizerTemplate::TinyBpeDemo, }), "tinylm16" => Ok(SourceTemplate { shape: ModelShape::tinylm16(), tied_output: false, tokenizer: SourceTokenizerTemplate::Byte, }), "tinylm16-tied" => Ok(SourceTemplate { shape: ModelShape::tinylm16(), tied_output: true, tokenizer: SourceTokenizerTemplate::Byte, }), _ => Err(invalid( "source-template shape must be tiny-fixture, tiny-fixture-tied, tiny-fixture-bpe, tinylm16, or tinylm16-tied", )), } } fn tiny_bpe_fixture_shape() -> ModelShape { ModelShape { vocab_size: 262, ..ModelShape::tiny_fixture() } } fn shape_from_fields(fields: &HashMap) -> io::Result { let shape = ModelShape { vocab_size: parse_u32_key(fields, "vocab_size")?, special_token_count: parse_u32_key(fields, "special_token_count")?, hidden_size: parse_u32_key(fields, "hidden_size")?, layer_count: parse_u32_key(fields, "layer_count")?, head_count: parse_u32_key(fields, "head_count")?, kv_head_count: parse_u32_key(fields, "kv_head_count")?, head_dim: parse_u32_key(fields, "head_dim")?, ffn_size: parse_u32_key(fields, "ffn_size")?, max_context: parse_u32_key(fields, "max_context")?, }; if shape.vocab_size < 260 || shape.special_token_count < 4 { return Err(invalid( "source shape must support the phase-one byte tokenizer", )); } if shape.hidden_size == 0 || shape.layer_count == 0 || shape.head_count == 0 || shape.kv_head_count == 0 || shape.head_dim == 0 || shape.ffn_size == 0 || shape.max_context == 0 { return Err(invalid("source shape dimensions must be nonzero")); } if shape.head_count.checked_mul(shape.head_dim) != Some(shape.hidden_size) { return Err(invalid("source hidden_size must equal heads * head_dim")); } if shape.kv_head_count > shape.head_count || shape.head_count % shape.kv_head_count != 0 { return Err(invalid("source kv_head_count must divide head_count")); } let shape_name = require_key(fields, "model_shape")?; if matches!(shape_name, "tiny-fixture" | "tiny-fixture-tied") && !shape_matches(&shape, &ModelShape::tiny_fixture()) { return Err(invalid( "model_shape=tiny-fixture does not match dimensions", )); } if shape_name == "tiny-fixture-bpe" && !shape_matches(&shape, &tiny_bpe_fixture_shape()) { return Err(invalid( "model_shape=tiny-fixture-bpe does not match dimensions", )); } if matches!(shape_name, "tinylm16" | "tinylm16-tied") && !shape_matches(&shape, &ModelShape::tinylm16()) { return Err(invalid("model_shape=tinylm16 does not match dimensions")); } if shape_name == "tinylm16-bpe" && !shape_matches_except_vocab(&shape, &ModelShape::tinylm16()) { return Err(invalid( "model_shape=tinylm16-bpe must match TinyLM-16M dimensions except vocab_size", )); } if !matches!( shape_name, "tiny-fixture" | "tiny-fixture-tied" | "tiny-fixture-bpe" | "tinylm16" | "tinylm16-tied" | "tinylm16-bpe" ) { return Err(invalid( "model_shape must be tiny-fixture, tiny-fixture-tied, tiny-fixture-bpe, tinylm16, tinylm16-tied, or tinylm16-bpe", )); } Ok(shape) } fn tied_output_from_fields(fields: &HashMap) -> io::Result { match fields.get("tied_output").map(String::as_str) { Some("true") => Ok(true), Some("false") | None => Ok(false), Some(_) => Err(invalid( "source manifest key tied_output must be true or false", )), } } fn validate_shape_name_and_tied_output( fields: &HashMap, _shape: &ModelShape, tied_output: bool, ) -> io::Result<()> { let shape_name = require_key(fields, "model_shape")?; let shape_name_is_tied = matches!(shape_name, "tiny-fixture-tied" | "tinylm16-tied"); if shape_name_is_tied != tied_output { return Err(invalid( "source manifest model_shape and tied_output must agree", )); } Ok(()) } fn validate_shape_name_and_tokenizer(fields: &HashMap) -> io::Result<()> { let shape_name = require_key(fields, "model_shape")?; let tokenizer = require_key(fields, "tokenizer")?; let shape_name_is_bpe = matches!(shape_name, "tiny-fixture-bpe" | "tinylm16-bpe"); if shape_name_is_bpe && tokenizer != "bpe-v1" { return Err(invalid("BPE source model_shape requires tokenizer=bpe-v1")); } if !shape_name_is_bpe && tokenizer == "bpe-v1" { return Err(invalid( "tokenizer=bpe-v1 requires a BPE source model_shape", )); } Ok(()) } fn tokenizer_from_fields( fields: &HashMap, shape: &ModelShape, ) -> io::Result { match require_key(fields, "tokenizer")? { "byte-v1" => Ok(TokenizerSection::phase_one()), "bpe-v1" => bpe_tokenizer_from_fields(fields, shape.vocab_size), _ => Err(invalid("source tokenizer must be byte-v1 or bpe-v1")), } } fn bpe_tokenizer_from_fields( fields: &HashMap, vocab_size: u32, ) -> io::Result { let token_count = parse_usize_key(fields, "bpe_token_count")?; let merge_count = parse_usize_key(fields, "bpe_merge_count")?; if token_count == 0 || merge_count == 0 { return Err(invalid( "BPE source tokenizer requires at least one token and one merge", )); } let mut tokens = Vec::with_capacity(token_count); for index in 0..token_count { let prefix = format!("bpe.token.{index}"); let id = parse_u32_key(fields, &format!("{prefix}.id"))?; let bytes = parse_hex_bytes(require_key(fields, &format!("{prefix}.bytes_hex"))?)?; if id < 260 || id >= vocab_size || bytes.is_empty() { return Err(invalid( "BPE token entry is outside the declared vocabulary", )); } if tokens.iter().any(|token: &BpeTokenSpec| token.id == id) { return Err(invalid("BPE token ids must be unique")); } tokens.push(BpeTokenSpec { id, bytes }); } let mut merges = Vec::with_capacity(merge_count); for index in 0..merge_count { let prefix = format!("bpe.merge.{index}"); let left = parse_u32_key(fields, &format!("{prefix}.left"))?; let right = parse_u32_key(fields, &format!("{prefix}.right"))?; let output = parse_u32_key(fields, &format!("{prefix}.output"))?; let rank = parse_u32_key(fields, &format!("{prefix}.rank"))?; if left >= vocab_size || right >= vocab_size || output >= vocab_size || output < 260 { return Err(invalid("BPE merge ids must stay inside vocabulary")); } if !tokens.iter().any(|token| token.id == output) { return Err(invalid("BPE merge output must reference a declared token")); } if merges.iter().any(|merge: &BpeMergeSpec| merge.rank == rank) { return Err(invalid("BPE merge ranks must be unique")); } merges.push(BpeMergeSpec { left, right, output, rank, }); } reject_extra_bpe_keys(fields, token_count, merge_count)?; Ok(TokenizerSection::bpe_from_parts( vocab_size, &tokens, &merges, )) } fn tensors_for_shape_and_output( shape: &ModelShape, dtype: u32, tied_output: bool, ) -> Vec { if tied_output { tensors_for_shape_with_tied_output(shape, dtype) } else { tensors_for_shape(shape, dtype) } } fn read_raw_f32_values(bytes: &[u8], tensor: &TensorSpec) -> io::Result> { let expected_bytes = tensor.element_count().checked_mul(4).ok_or_else(|| { invalid("source tensor byte length overflow while validating f32 payload") })?; if bytes.len() != expected_bytes { return Err(invalid("source tensor byte length does not match shape")); } let mut values = Vec::with_capacity(tensor.element_count()); let mut any_nonzero = false; for chunk in bytes.chunks_exact(4) { let value = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); if !value.is_finite() { return Err(invalid("source tensor contains a non-finite f32 value")); } if value.abs() > MAX_ABS_SOURCE_WEIGHT { return Err(invalid("source tensor contains an out-of-range f32 value")); } any_nonzero |= value != 0.0; values.push(value); } if !any_nonzero { return Err(invalid("source tensor must not be entirely zero")); } Ok(values) } fn source_tensor_bytes(tensor: &TensorSpec) -> io::Result> { let mut bytes = Vec::with_capacity(tensor.element_count() * 4); for elem in 0..tensor.element_count() { bytes.extend_from_slice(&fixture_value(tensor, elem).to_le_bytes()); } Ok(bytes) } fn safe_tensor_path(source_dir: &Path, relative_file: &str) -> io::Result { let path = Path::new(relative_file); if path.is_absolute() { return Err(invalid("source tensor file path must be relative")); } let mut components = path.components(); match components.next() { Some(Component::Normal(first)) if first == "tensors" => {} _ => return Err(invalid("source tensor files must live under tensors/")), } for component in components { match component { Component::Normal(_) => {} _ => return Err(invalid("source tensor file path is not safe")), } } Ok(source_dir.join(path)) } fn dtype_for_output(output_quantization: &str) -> io::Result { match output_quantization { "f32" => Ok(DTYPE_F32), "q8_0" => Ok(DTYPE_Q8_0), "q4_0" => Ok(DTYPE_Q4_0), _ => Err(invalid( "converted output quantization must be f32, q8_0, or q4_0", )), } } fn tensor_names_for_shape(shape: &ModelShape, tied_output: bool) -> Vec { let mut names = vec![ "tok_embeddings.weight".to_string(), "norm.weight".to_string(), ]; if !tied_output { names.push("output.weight".to_string()); } let per_layer = 9usize; names.reserve(shape.layer_count as usize * per_layer); for layer in 0..shape.layer_count { for suffix in [ "attention_norm.weight", "ffn_norm.weight", "wq.weight", "wk.weight", "wv.weight", "wo.weight", "w1.weight", "w2.weight", "w3.weight", ] { names.push(format!("layers.{layer}.{suffix}")); } } names } fn tensor_file_name(name: &str) -> String { let mut file = String::new(); for ch in name.chars() { if ch.is_ascii_alphanumeric() { file.push(ch); } else { file.push('_'); } } file.push_str(".f32"); file } fn dims_text(tensor: &TensorSpec) -> String { let mut text = String::new(); for (index, dim) in tensor.dims.iter().take(tensor.rank as usize).enumerate() { if index > 0 { text.push(','); } text.push_str(&dim.to_string()); } text } fn push_shape_lines(text: &mut String, shape: &ModelShape) { push_line(text, "vocab_size", &shape.vocab_size.to_string()); push_line( text, "special_token_count", &shape.special_token_count.to_string(), ); push_line(text, "hidden_size", &shape.hidden_size.to_string()); push_line(text, "layer_count", &shape.layer_count.to_string()); push_line(text, "head_count", &shape.head_count.to_string()); push_line(text, "kv_head_count", &shape.kv_head_count.to_string()); push_line(text, "head_dim", &shape.head_dim.to_string()); push_line(text, "ffn_size", &shape.ffn_size.to_string()); push_line(text, "max_context", &shape.max_context.to_string()); } fn push_tokenizer_template_lines(text: &mut String, tokenizer: SourceTokenizerTemplate) { match tokenizer { SourceTokenizerTemplate::Byte => { push_line(text, "tokenizer", "byte-v1"); } SourceTokenizerTemplate::TinyBpeDemo => { push_line(text, "tokenizer", "bpe-v1"); let tokens = tiny_bpe_token_specs(); let merges = tiny_bpe_merge_specs(); push_line(text, "bpe_token_count", &tokens.len().to_string()); push_line(text, "bpe_merge_count", &merges.len().to_string()); for (index, token) in tokens.iter().enumerate() { let prefix = format!("bpe.token.{index}"); push_line(text, &format!("{prefix}.id"), &token.id.to_string()); push_line( text, &format!("{prefix}.bytes_hex"), &hex_bytes(&token.bytes), ); } for (index, merge) in merges.iter().enumerate() { let prefix = format!("bpe.merge.{index}"); push_line(text, &format!("{prefix}.left"), &merge.left.to_string()); push_line(text, &format!("{prefix}.right"), &merge.right.to_string()); push_line(text, &format!("{prefix}.output"), &merge.output.to_string()); push_line(text, &format!("{prefix}.rank"), &merge.rank.to_string()); } } } } fn tiny_bpe_token_specs() -> Vec { vec![ BpeTokenSpec { id: 260, bytes: b"th".to_vec(), }, BpeTokenSpec { id: 261, bytes: b"the".to_vec(), }, ] } fn tiny_bpe_merge_specs() -> Vec { vec![ BpeMergeSpec { left: 116, right: 104, output: 260, rank: 0, }, BpeMergeSpec { left: 260, right: 101, output: 261, rank: 1, }, ] } fn shape_matches(a: &ModelShape, b: &ModelShape) -> bool { a.vocab_size == b.vocab_size && a.special_token_count == b.special_token_count && a.hidden_size == b.hidden_size && a.layer_count == b.layer_count && a.head_count == b.head_count && a.kv_head_count == b.kv_head_count && a.head_dim == b.head_dim && a.ffn_size == b.ffn_size && a.max_context == b.max_context } fn shape_matches_except_vocab(a: &ModelShape, b: &ModelShape) -> bool { a.special_token_count == b.special_token_count && a.hidden_size == b.hidden_size && a.layer_count == b.layer_count && a.head_count == b.head_count && a.kv_head_count == b.kv_head_count && a.head_dim == b.head_dim && a.ffn_size == b.ffn_size && a.max_context == b.max_context } fn sidecar_manifest_path(output_slm: &Path) -> PathBuf { let mut value = output_slm.as_os_str().to_os_string(); value.push(".manifest"); PathBuf::from(value) } fn parse_key_value_manifest(text: &str) -> io::Result> { let mut fields = HashMap::new(); for (line_index, raw_line) in text.lines().enumerate() { let line = raw_line.trim(); if line.is_empty() || line.starts_with('#') { continue; } let Some((key, value)) = line.split_once('=') else { return Err(invalid(&format!( "source manifest line {} is missing '='", line_index + 1 ))); }; let key = key.trim(); let value = value.trim(); if key.is_empty() || value.is_empty() { return Err(invalid(&format!( "source manifest line {} has an empty key or value", line_index + 1 ))); } if fields.insert(key.to_string(), value.to_string()).is_some() { return Err(invalid(&format!("duplicate source manifest key {key}"))); } } Ok(fields) } fn require_evidence_field(fields: &HashMap, key: &str) -> io::Result<()> { let value = require_key(fields, key)?; if value == "pending" || value == "not-reviewed" || value == "not-provided" || value.len() < 8 { return Err(invalid(&format!( "source field {key} must contain reviewed routing evidence" ))); } Ok(()) } fn parse_u32_key(fields: &HashMap, key: &str) -> io::Result { require_key(fields, key)? .parse::() .map_err(|_| invalid(&format!("source manifest key {key} must be a u32"))) } fn parse_usize_key(fields: &HashMap, key: &str) -> io::Result { require_key(fields, key)? .parse::() .map_err(|_| invalid(&format!("source manifest key {key} must be a usize"))) } fn reject_extra_bpe_keys( fields: &HashMap, token_count: usize, merge_count: usize, ) -> io::Result<()> { for key in fields.keys() { if let Some(rest) = key.strip_prefix("bpe.token.") { let Some((index_text, field_name)) = rest.split_once('.') else { return Err(invalid(&format!("BPE token key {key} is malformed"))); }; let index = index_text .parse::() .map_err(|_| invalid(&format!("BPE token key {key} has invalid index")))?; if index >= token_count { return Err(invalid(&format!( "BPE token key {key} is outside declared bpe_token_count" ))); } match field_name { "id" | "bytes_hex" => {} _ => return Err(invalid(&format!("BPE token key {key} has unknown field"))), } } if let Some(rest) = key.strip_prefix("bpe.merge.") { let Some((index_text, field_name)) = rest.split_once('.') else { return Err(invalid(&format!("BPE merge key {key} is malformed"))); }; let index = index_text .parse::() .map_err(|_| invalid(&format!("BPE merge key {key} has invalid index")))?; if index >= merge_count { return Err(invalid(&format!( "BPE merge key {key} is outside declared bpe_merge_count" ))); } match field_name { "left" | "right" | "output" | "rank" => {} _ => return Err(invalid(&format!("BPE merge key {key} has unknown field"))), } } } Ok(()) } fn parse_hex_bytes(value: &str) -> io::Result> { if value.len() % 2 != 0 { return Err(invalid("BPE token bytes_hex must have even length")); } let mut bytes = Vec::with_capacity(value.len() / 2); for pair in value.as_bytes().chunks_exact(2) { let high = hex_nibble(pair[0])?; let low = hex_nibble(pair[1])?; bytes.push((high << 4) | low); } Ok(bytes) } fn hex_nibble(byte: u8) -> io::Result { match byte { b'0'..=b'9' => Ok(byte - b'0'), b'a'..=b'f' => Ok(byte - b'a' + 10), b'A'..=b'F' => Ok(byte - b'A' + 10), _ => Err(invalid("BPE token bytes_hex contains a non-hex digit")), } } fn hex_bytes(bytes: &[u8]) -> String { const HEX: &[u8; 16] = b"0123456789abcdef"; let mut text = String::with_capacity(bytes.len() * 2); for byte in bytes { text.push(HEX[(byte >> 4) as usize] as char); text.push(HEX[(byte & 0x0f) as usize] as char); } text } fn require_key<'a>(fields: &'a HashMap, key: &str) -> io::Result<&'a str> { fields .get(key) .map(String::as_str) .ok_or_else(|| invalid(&format!("source manifest missing required key {key}"))) } fn require_equal(fields: &HashMap, key: &str, expected: &str) -> io::Result<()> { let actual = require_key(fields, key)?; if actual != expected { return Err(invalid(&format!( "source manifest key {key} was {actual}, expected {expected}" ))); } Ok(()) } fn push_line(text: &mut String, key: &str, value: &str) { text.push_str(key); text.push('='); text.push_str(value); text.push('\n'); } fn source_checksum(bytes: &[u8]) -> u64 { let mut acc = 0x6eed0e9da4d94a4fu64; for (index, byte) in bytes.iter().enumerate() { acc ^= u64::from(*byte).wrapping_add((index as u64) << 3); acc = acc.rotate_left(11).wrapping_mul(0x100000001b3); } acc } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } #[cfg(test)] mod tests { use super::*; use crate::tensor_writer::name_hash; #[test] fn validates_generated_source_fixture() { let dir = temp_path("source-fixture"); write_source_template_path(&dir, "tiny-fixture").unwrap(); validate_source_path(&dir).unwrap(); cleanup(&dir); } #[test] fn converts_source_fixture_to_all_supported_slm_quantizations() { let dir = temp_path("source-convert"); write_source_template_path(&dir, "tiny-fixture").unwrap(); for quantization in ["f32", "q8_0", "q4_0"] { let output = dir.join(format!("converted-{quantization}.slm")); convert_trained_path(&dir, &output, quantization).unwrap(); slm_validate::validate_path(&output).unwrap(); provenance::validate_manifest_path(&output, &sidecar_manifest_path(&output)).unwrap(); } cleanup(&dir); } #[test] fn validates_generated_tied_source_fixture_without_output_tensor() { let dir = temp_path("source-tied-fixture"); write_source_template_path(&dir, "tiny-fixture-tied").unwrap(); let manifest = fs::read_to_string(dir.join(SOURCE_MANIFEST_NAME)).unwrap(); assert!(manifest.contains("model_shape=tiny-fixture-tied")); assert!(manifest.contains("tied_output=true")); assert!(manifest.contains("tensor_count=11")); assert!(!manifest.contains("output.weight")); assert!(!dir.join("tensors").join("output_weight.f32").exists()); validate_source_path(&dir).unwrap(); cleanup(&dir); } #[test] fn rejects_tied_output_manifest_shape_disagreement() { let dir = temp_path("source-tied-disagreement"); write_source_template_path(&dir, "tiny-fixture").unwrap(); let manifest_path = dir.join(SOURCE_MANIFEST_NAME); let manifest = fs::read_to_string(&manifest_path) .unwrap() .replace("tied_output=false", "tied_output=true"); fs::write(&manifest_path, manifest).unwrap(); let error = validate_source_path(&dir).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("model_shape and tied_output")); cleanup(&dir); } #[test] fn converts_tied_source_fixture_to_all_supported_slm_quantizations() { let dir = temp_path("source-tied-convert"); write_source_template_path(&dir, "tiny-fixture-tied").unwrap(); for quantization in ["f32", "q8_0", "q4_0"] { let output = dir.join(format!("tied-converted-{quantization}.slm")); convert_trained_path(&dir, &output, quantization).unwrap(); let bytes = fs::read(&output).unwrap(); let report = slm_validate::validate_bytes(&bytes, &output.display().to_string()).unwrap(); assert_eq!(read_u32_le(&bytes, 16) & FLAG_TIED_OUTPUT, FLAG_TIED_OUTPUT); assert_eq!(report.tensor_count(), 11); assert!(!contains_tensor_hash(&bytes, name_hash("output.weight"))); assert!(contains_tensor_hash( &bytes, name_hash("tok_embeddings.weight") )); provenance::validate_manifest_path(&output, &sidecar_manifest_path(&output)).unwrap(); } cleanup(&dir); } #[test] fn validates_generated_bpe_source_fixture() { let dir = temp_path("source-bpe-fixture"); write_source_template_path(&dir, "tiny-fixture-bpe").unwrap(); let manifest = fs::read_to_string(dir.join(SOURCE_MANIFEST_NAME)).unwrap(); assert!(manifest.contains("model_shape=tiny-fixture-bpe")); assert!(manifest.contains("tokenizer=bpe-v1")); assert!(manifest.contains("vocab_size=262")); assert!(manifest.contains("bpe.token.1.bytes_hex=746865")); validate_source_path(&dir).unwrap(); cleanup(&dir); } #[test] fn converts_bpe_source_fixture_to_bpe_slm() { let dir = temp_path("source-bpe-convert"); write_source_template_path(&dir, "tiny-fixture-bpe").unwrap(); let output = dir.join("bpe-converted-q8.slm"); convert_trained_path(&dir, &output, "q8_0").unwrap(); let bytes = fs::read(&output).unwrap(); let report = slm_validate::validate_bytes(&bytes, &output.display().to_string()).unwrap(); assert!(report.shape_summary().starts_with("vocab=262,")); assert_eq!(bytes[108..112], *b"BPE1"); provenance::validate_manifest_path(&output, &sidecar_manifest_path(&output)).unwrap(); cleanup(&dir); } #[test] fn rejects_bpe_source_manifest_without_matching_shape() { let dir = temp_path("source-bpe-shape-mismatch"); write_source_template_path(&dir, "tiny-fixture").unwrap(); let manifest_path = dir.join(SOURCE_MANIFEST_NAME); let manifest = fs::read_to_string(&manifest_path) .unwrap() .replace("tokenizer=byte-v1", "tokenizer=bpe-v1"); fs::write(&manifest_path, manifest).unwrap(); let error = validate_source_path(&dir).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("BPE source model_shape")); cleanup(&dir); } #[test] fn rejects_bpe_source_merge_outside_vocab() { let dir = temp_path("source-bpe-merge-output"); write_source_template_path(&dir, "tiny-fixture-bpe").unwrap(); let manifest_path = dir.join(SOURCE_MANIFEST_NAME); let manifest = fs::read_to_string(&manifest_path) .unwrap() .replace("bpe.merge.1.output=261", "bpe.merge.1.output=300"); fs::write(&manifest_path, manifest).unwrap(); let error = validate_source_path(&dir).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); assert!(error.to_string().contains("inside vocabulary")); cleanup(&dir); } #[test] fn rejects_source_checksum_drift() { let dir = temp_path("source-drift"); write_source_template_path(&dir, "tiny-fixture").unwrap(); let first_tensor = dir.join("tensors").join("tok_embeddings_weight.f32"); let mut bytes = fs::read(&first_tensor).unwrap(); bytes[0] ^= 0x01; fs::write(first_tensor, bytes).unwrap(); let error = validate_source_path(&dir).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); cleanup(&dir); } #[test] fn rejects_non_finite_source_weight() { let dir = temp_path("source-nan"); write_source_template_path(&dir, "tiny-fixture").unwrap(); let tensor_file = dir.join("tensors").join("tok_embeddings_weight.f32"); let mut bytes = fs::read(&tensor_file).unwrap(); bytes[0..4].copy_from_slice(&f32::NAN.to_le_bytes()); fs::write(&tensor_file, &bytes).unwrap(); refresh_manifest_checksum( &dir.join(SOURCE_MANIFEST_NAME), "tensor.0.checksum", source_checksum(&bytes), ); let error = validate_source_path(&dir).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); cleanup(&dir); } #[test] fn rejects_source_path_traversal() { let dir = temp_path("source-path"); write_source_template_path(&dir, "tiny-fixture").unwrap(); let manifest_path = dir.join(SOURCE_MANIFEST_NAME); let manifest = fs::read_to_string(&manifest_path).unwrap().replace( "tensor.0.file=tensors/tok_embeddings_weight.f32", "tensor.0.file=../tok_embeddings_weight.f32", ); fs::write(&manifest_path, manifest).unwrap(); let error = validate_source_path(&dir).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::InvalidData); cleanup(&dir); } fn refresh_manifest_checksum(manifest_path: &Path, key: &str, checksum: u64) { let mut updated = String::new(); let prefix = format!("{key}="); for line in fs::read_to_string(manifest_path).unwrap().lines() { if line.starts_with(&prefix) { updated.push_str(&format!("{key}=0x{checksum:016x}\n")); } else { updated.push_str(line); updated.push('\n'); } } fs::write(manifest_path, updated).unwrap(); } fn read_u32_le(bytes: &[u8], offset: usize) -> u32 { u32::from_le_bytes([ bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3], ]) } fn read_u64_le(bytes: &[u8], offset: usize) -> u64 { u64::from_le_bytes([ bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3], bytes[offset + 4], bytes[offset + 5], bytes[offset + 6], bytes[offset + 7], ]) } fn contains_tensor_hash(bytes: &[u8], hash: u64) -> bool { let directory = read_u64_le(bytes, 80) as usize; let count = read_u32_le(bytes, 88) as usize; (0..count).any(|index| read_u64_le(bytes, directory + index * 64) == hash) } fn temp_path(name: &str) -> PathBuf { let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("tinyrustlm-{name}-{}-{nanos}", std::process::id())) } fn cleanup(path: &Path) { let _ = fs::remove_dir_all(path); } } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/trained_source.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/slm_pack/src/writer.rs BYTES: 1064 SHA256: A189F9B2C7911E1ED45AA2AF5266999BA0C4AE07B4E4BE33CC865D02CFF78F1A ================================================================================ //! Little-endian binary writing helpers. use std::io; /// Aligns a byte offset to the next 64-byte boundary. pub fn align_to_64(value: usize) -> usize { (value + 63) & !63 } /// Writes a little-endian u32 at `offset`. pub fn write_u32(bytes: &mut [u8], offset: usize, value: u32) -> io::Result<()> { write_bytes(bytes, offset, &value.to_le_bytes()) } /// Writes a little-endian u64 at `offset`. pub fn write_u64(bytes: &mut [u8], offset: usize, value: u64) -> io::Result<()> { write_bytes(bytes, offset, &value.to_le_bytes()) } /// Writes a little-endian f32 at `offset`. pub fn write_f32(bytes: &mut [u8], offset: usize, value: f32) -> io::Result<()> { write_bytes(bytes, offset, &value.to_le_bytes()) } fn write_bytes(bytes: &mut [u8], offset: usize, value: &[u8]) -> io::Result<()> { let end = offset + value.len(); if end > bytes.len() { return Err(io::Error::new( io::ErrorKind::UnexpectedEof, "write outside buffer", )); } bytes[offset..end].copy_from_slice(value); Ok(()) } ================================================================================ END FILE: tinyrustlm/tools/slm_pack/src/writer.rs ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/static-server.js BYTES: 2262 SHA256: 93A2E12153444E18D807D2F4C7E9FA9BAF5EBEAA81D93DC175778C97876FF61C ================================================================================ #!/usr/bin/env node "use strict"; const http = require("http"); const fs = require("fs"); const path = require("path"); const root = path.resolve(process.argv[2] || path.join(__dirname, "..")); const port = Number(process.argv[3] || 8080); const types = { ".html": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".wasm": "application/wasm", ".slm": "application/octet-stream", ".md": "text/plain; charset=utf-8" }; function send(request, response, code, body, type) { response.writeHead(code, { "content-type": type || "text/plain; charset=utf-8", "content-length": Buffer.byteLength(body) }); if (request.method === "HEAD") { response.end(); return; } response.end(body); } const server = http.createServer((request, response) => { if (request.method !== "GET" && request.method !== "HEAD") { send(request, response, 405, "method not allowed"); return; } const url = new URL(request.url, "http://127.0.0.1"); let relative = decodeURIComponent(url.pathname); if (relative.endsWith("/")) { relative += "index.html"; } const file = path.resolve(path.join(root, relative)); if (!file.startsWith(root)) { send(request, response, 403, "forbidden"); return; } fs.stat(file, (error, stats) => { if (error) { send(request, response, 404, "not found"); return; } if (!stats.isFile()) { send(request, response, 404, "not found"); return; } response.writeHead(200, { "content-type": types[path.extname(file).toLowerCase()] || "application/octet-stream", "content-length": stats.size }); if (request.method === "HEAD") { response.end(); return; } fs.createReadStream(file).pipe(response); }); }); server.on("error", (error) => { if (error && error.code === "EADDRINUSE") { process.stderr.write(`Port ${port} is already in use on 127.0.0.1.\n`); process.exit(2); } process.stderr.write(`TinyRustLM static server failed: ${error ? error.message : "unknown error"}\n`); process.exit(1); }); server.listen(port, "127.0.0.1", () => { process.stdout.write(`TinyRustLM static server listening at http://127.0.0.1:${port}/app/\n`); }); ================================================================================ END FILE: tinyrustlm/tools/static-server.js ================================================================================ ================================================================================ BEGIN FILE: tinyrustlm/tools/wasm-abi-smoke.js BYTES: 19863 SHA256: CCC8D69E0F0FFB739DED58452962829BB179136328820D7587EB05D457D3A0A0 ================================================================================ #!/usr/bin/env node "use strict"; const fs = require("fs"); const path = require("path"); const { TextDecoder, TextEncoder } = require("util"); const root = path.resolve(__dirname, ".."); const wasmPath = process.argv[2] || path.join(root, "runtime", "tinyrustlm.wasm"); const modelPath = process.argv[3] || path.join(root, "models", "tinylm16-q8.slm"); const adapterModelPath = process.argv[4] || path.join(root, "models", "tiny-test-model.slm"); const ErrorCode = { Ok: 0, NullPointer: 1, InvalidLength: 2, InvalidUtf8: 3, ModelNotLoaded: 12 }; const encoder = new TextEncoder(); const decoder = new TextDecoder("utf-8"); const U64_MASK = (1n << 64n) - 1n; const FNV_PRIME = 0x100000001b3n; const TOKENIZER_CHECKSUM_SEED = 0x746f6b656e697a65n; const ADAPTER_HEADER_LEN = 64; const ADAPTER_ENTRY_LEN = 64; const ADAPTER_CHECKSUM_OFFSET = 56; function fail(message) { throw new Error(message); } function memory(exports) { return new Uint8Array(exports.memory.buffer); } function readString(exports, ptr, len) { return decoder.decode(memory(exports).slice(ptr, ptr + len)); } function readLastResult(exports) { return readString(exports, exports.last_result_ptr(), exports.last_result_len()); } function readDiagnostics(exports) { return JSON.parse(readString(exports, exports.get_diagnostics_ptr(), exports.get_diagnostics_len())); } function allocCopy(exports, bytes) { const ptr = exports.alloc(bytes.length); if (!ptr) { fail(`alloc(${bytes.length}) returned null`); } memory(exports).set(bytes, ptr); return ptr; } function release(exports, ptr, len) { if (ptr) { exports.dealloc(ptr, len); } } function expectCode(label, actual, expected) { if (actual !== expected) { fail(`${label} returned ${actual}, expected ${expected}`); } } function expectLastError(exports, label, expectedCode, expectedMessage) { expectCode(label, expectedCode.actual, expectedCode.expected); const result = readLastResult(exports); if (result !== expectedMessage) { fail(`${label} result was ${JSON.stringify(result)}, expected ${JSON.stringify(expectedMessage)}`); } const diagnostics = readDiagnostics(exports); if (diagnostics.last_error !== expectedMessage) { fail(`${label} diagnostics last_error was ${JSON.stringify(diagnostics.last_error)}`); } if (diagnostics.model_loaded !== true) { fail(`${label} diagnostics lost the loaded model state`); } } function isHex64(value) { return /^0x[0-9a-fA-F]{16}$/.test(String(value || "")); } function expectAssemblyDiagnostics(label, diagnostics, expectedApplyCount, expectLoadedState) { if (diagnostics.adapter_apply_count !== expectedApplyCount) { fail(`${label} adapter_apply_count was ${diagnostics.adapter_apply_count}`); } if (!isHex64(diagnostics.last_adapter_checksum)) { fail(`${label} last_adapter_checksum was ${JSON.stringify(diagnostics.last_adapter_checksum)}`); } if (!isHex64(diagnostics.assembly_state_checksum)) { fail(`${label} assembly_state_checksum was ${JSON.stringify(diagnostics.assembly_state_checksum)}`); } const zeroChecksum = "0x0000000000000000"; if (expectedApplyCount === 0 && diagnostics.last_adapter_checksum !== zeroChecksum) { fail(`${label} last_adapter_checksum was ${diagnostics.last_adapter_checksum}`); } if (expectedApplyCount > 0 && diagnostics.last_adapter_checksum === zeroChecksum) { fail(`${label} last_adapter_checksum stayed zero`); } if (expectLoadedState && diagnostics.assembly_state_checksum === zeroChecksum) { fail(`${label} assembly_state_checksum stayed zero`); } if (!expectLoadedState && diagnostics.assembly_state_checksum !== zeroChecksum) { fail(`${label} assembly_state_checksum was ${diagnostics.assembly_state_checksum}`); } } function alignTo64(value) { return (value + 63) & ~63; } function readU32(bytes, offset) { return bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16) | (bytes[offset + 3] << 24); } function readU64(bytes, offset) { let value = 0n; for (let index = 7; index >= 0; index -= 1) { value = (value << 8n) | BigInt(bytes[offset + index]); } return value; } function writeU32(bytes, offset, value) { bytes[offset] = value & 0xff; bytes[offset + 1] = (value >>> 8) & 0xff; bytes[offset + 2] = (value >>> 16) & 0xff; bytes[offset + 3] = (value >>> 24) & 0xff; } function writeU64(bytes, offset, value) { let cursor = BigInt(value); for (let index = 0; index < 8; index += 1) { bytes[offset + index] = Number(cursor & 0xffn); cursor >>= 8n; } } function rotateLeft64(value, shift) { const bits = BigInt(shift); return (((value << bits) & U64_MASK) | (value >> (64n - bits))) & U64_MASK; } function mixU64(acc, value) { let cursor = BigInt(value); let mixed = acc; for (let index = 0; index < 8; index += 1) { mixed ^= cursor & 0xffn; mixed = (rotateLeft64(mixed, 11) * FNV_PRIME) & U64_MASK; cursor >>= 8n; } return mixed; } function sectionChecksum(bytes, seed) { let acc = seed; for (let index = 0; index < bytes.length; index += 1) { acc ^= BigInt(bytes[index]) + (BigInt(index) << 2n); acc = (rotateLeft64(acc, 9) * FNV_PRIME) & U64_MASK; } return acc; } function payloadChecksum(bytes) { let acc = 0x64656c7461663332n; for (let index = 0; index < bytes.length; index += 1) { acc ^= BigInt(bytes[index]) + (BigInt(index) << 1n); acc = (rotateLeft64(acc, 7) * FNV_PRIME) & U64_MASK; } return acc; } function adapterChecksum(bytes) { let acc = 0x6164617074657231n; for (let index = 0; index < bytes.length; index += 1) { const value = index >= ADAPTER_CHECKSUM_OFFSET && index < ADAPTER_CHECKSUM_OFFSET + 8 ? 0 : bytes[index]; acc ^= BigInt(value) + (BigInt(index) << 3n); acc = (rotateLeft64(acc, 11) * FNV_PRIME) & U64_MASK; } return acc; } function parseSlmForAdapter(modelBytes) { const tokenizerOffset = Number(readU64(modelBytes, 64)); const tokenizerLength = Number(readU64(modelBytes, 72)); const directoryOffset = Number(readU64(modelBytes, 80)); const tensorCount = readU32(modelBytes, 88); const tensors = []; for (let index = 0; index < tensorCount; index += 1) { const entry = directoryOffset + index * 64; const rank = readU32(modelBytes, entry + 12); const dims = [ readU32(modelBytes, entry + 16), readU32(modelBytes, entry + 20), readU32(modelBytes, entry + 24), readU32(modelBytes, entry + 28) ]; const elementCount = dims.slice(0, rank).reduce((acc, dim) => acc * dim, 1); tensors.push({ nameHash: readU64(modelBytes, entry), dtype: readU32(modelBytes, entry + 8), rank, dims, byteLength: readU64(modelBytes, entry + 40), blockSize: readU32(modelBytes, entry + 56), elementCount }); } return { flags: readU32(modelBytes, 16), tokenizer: modelBytes.slice(tokenizerOffset, tokenizerOffset + tokenizerLength), tensors }; } function parameterCount(tensors) { return tensors.reduce((acc, tensor) => acc + BigInt(tensor.elementCount), 0n); } function tensorLayoutChecksum(tensors) { const sorted = [...tensors].sort((left, right) => (left.nameHash < right.nameHash ? -1 : 1)); let acc = 0x74656e736f722d6cn; for (const tensor of sorted) { acc = mixU64(acc, tensor.nameHash); acc = mixU64(acc, BigInt(tensor.dtype)); acc = mixU64(acc, BigInt(tensor.rank)); for (const dim of tensor.dims) { acc = mixU64(acc, BigInt(dim)); } acc = mixU64(acc, BigInt(tensor.blockSize)); acc = mixU64(acc, tensor.byteLength); } return acc; } function buildZeroAdapter(modelBytes) { const parsed = parseSlmForAdapter(modelBytes); const dataOffset = alignTo64(ADAPTER_HEADER_LEN + parsed.tensors.length * ADAPTER_ENTRY_LEN); let cursor = dataOffset; const payloads = []; for (const tensor of parsed.tensors) { cursor = alignTo64(cursor); const byteLength = tensor.elementCount * 4; payloads.push({ offset: cursor, bytes: new Uint8Array(byteLength), tensor }); cursor += byteLength; } const bytes = new Uint8Array(cursor); bytes.set(Buffer.from("ADP1"), 0); writeU32(bytes, 4, 1); writeU32(bytes, 8, ADAPTER_HEADER_LEN); writeU32(bytes, 12, parsed.tensors.length); writeU32(bytes, 16, parsed.flags); writeU32(bytes, 20, ADAPTER_ENTRY_LEN); writeU64(bytes, 24, parameterCount(parsed.tensors)); writeU64(bytes, 32, tensorLayoutChecksum(parsed.tensors)); writeU64(bytes, 40, sectionChecksum(parsed.tokenizer, TOKENIZER_CHECKSUM_SEED)); writeU64(bytes, 48, BigInt(dataOffset)); writeU64(bytes, ADAPTER_CHECKSUM_OFFSET, 0n); payloads.forEach((payload, index) => { const entry = ADAPTER_HEADER_LEN + index * ADAPTER_ENTRY_LEN; const tensor = payload.tensor; writeU64(bytes, entry, tensor.nameHash); writeU32(bytes, entry + 8, tensor.rank); writeU32(bytes, entry + 12, tensor.dims[0]); writeU32(bytes, entry + 16, tensor.dims[1]); writeU32(bytes, entry + 20, tensor.dims[2]); writeU32(bytes, entry + 24, tensor.dims[3]); writeU32(bytes, entry + 28, 0); writeU64(bytes, entry + 32, BigInt(payload.offset)); writeU64(bytes, entry + 40, BigInt(payload.bytes.length)); writeU64(bytes, entry + 48, BigInt(tensor.elementCount)); writeU64(bytes, entry + 56, payloadChecksum(payload.bytes)); bytes.set(payload.bytes, payload.offset); }); writeU64(bytes, ADAPTER_CHECKSUM_OFFSET, adapterChecksum(bytes)); return bytes; } function generateBytes(exports, label, bytes, maxNewTokens, expectedCode, expectedMessage) { const ptr = allocCopy(exports, bytes); try { const actual = exports.generate(ptr, bytes.length, maxNewTokens); expectLastError(exports, label, { actual, expected: expectedCode }, expectedMessage); } finally { release(exports, ptr, bytes.length); } } async function main() { const wasmBytes = fs.readFileSync(wasmPath); const modelBytes = fs.readFileSync(modelPath); const adapterModelBytes = fs.readFileSync(adapterModelPath); const instance = await WebAssembly.instantiate(wasmBytes, {}); const exports = instance.instance.exports; expectCode("init_runtime", exports.init_runtime(), ErrorCode.Ok); const modelPtr = allocCopy(exports, modelBytes); try { expectCode("load_model", exports.load_model(modelPtr, modelBytes.length), ErrorCode.Ok); } finally { release(exports, modelPtr, modelBytes.length); } generateBytes( exports, "invalid utf-8 prompt", Uint8Array.from([0xc3, 0x28]), 1, ErrorCode.InvalidUtf8, "invalid utf-8" ); expectLastError( exports, "null prompt pointer", { actual: exports.generate(0, 1, 1), expected: ErrorCode.NullPointer }, "null pointer" ); const oneByte = allocCopy(exports, Uint8Array.from([0x68])); try { expectLastError( exports, "zero prompt length", { actual: exports.generate(oneByte, 0, 1), expected: ErrorCode.InvalidLength }, "invalid length" ); } finally { release(exports, oneByte, 1); } generateBytes( exports, "zero max_new_tokens", encoder.encode("hi"), 0, ErrorCode.InvalidLength, "invalid length" ); expectLastError( exports, "invalid sampling config", { actual: exports.set_sampling_config(1.0, 0, 1.0, 1), expected: ErrorCode.InvalidLength }, "invalid length" ); expectCode("restore greedy sampling", exports.set_sampling_config(0.0, 1, 1.0, 1), ErrorCode.Ok); const recoveryPtr = allocCopy(exports, encoder.encode("hi")); try { expectCode("recovery generate", exports.generate(recoveryPtr, 2, 1), ErrorCode.Ok); } finally { release(exports, recoveryPtr, 2); } const recoveryText = readLastResult(exports); if (recoveryText !== "e") { fail(`recovery result was ${JSON.stringify(recoveryText)}, expected "e"`); } const recoveryDiagnostics = readDiagnostics(exports); if (recoveryDiagnostics.last_error !== "ok") { fail(`recovery diagnostics last_error was ${JSON.stringify(recoveryDiagnostics.last_error)}`); } if (recoveryDiagnostics.selected_next_token !== 101) { fail(`recovery selected token was ${recoveryDiagnostics.selected_next_token}`); } if (recoveryDiagnostics.active_quantization_mode !== "q8_0") { fail(`recovery quantization was ${JSON.stringify(recoveryDiagnostics.active_quantization_mode)}`); } expectAssemblyDiagnostics("recovery", recoveryDiagnostics, 0, true); if (recoveryDiagnostics.sampling_temperature !== 0 || recoveryDiagnostics.sampling_top_k !== 1 || recoveryDiagnostics.sampling_top_p !== 1 || recoveryDiagnostics.sampling_seed !== 1) { fail(`recovery sampling config was ${JSON.stringify({ temperature: recoveryDiagnostics.sampling_temperature, topK: recoveryDiagnostics.sampling_top_k, topP: recoveryDiagnostics.sampling_top_p, seed: recoveryDiagnostics.sampling_seed })}`); } expectCode("generate_next_token", exports.generate_next_token(), ErrorCode.Ok); const stepText = readLastResult(exports); if (stepText !== "e") { fail(`generate_next_token result was ${JSON.stringify(stepText)}, expected "e"`); } const stepDiagnostics = readDiagnostics(exports); if (stepDiagnostics.last_error !== "ok") { fail(`generate_next_token diagnostics last_error was ${JSON.stringify(stepDiagnostics.last_error)}`); } if (stepDiagnostics.generated_token_count !== 2) { fail(`generate_next_token generated count was ${stepDiagnostics.generated_token_count}`); } if (stepDiagnostics.kv_cache_length !== 5) { fail(`generate_next_token kv cache length was ${stepDiagnostics.kv_cache_length}`); } if (stepDiagnostics.selected_next_token !== 101) { fail(`generate_next_token selected token was ${stepDiagnostics.selected_next_token}`); } if (stepDiagnostics.model_loaded !== true) { fail("generate_next_token diagnostics lost model_loaded state"); } const adapterModelPtr = allocCopy(exports, adapterModelBytes); try { expectCode("load adapter model", exports.load_model(adapterModelPtr, adapterModelBytes.length), ErrorCode.Ok); } finally { release(exports, adapterModelPtr, adapterModelBytes.length); } const adapterBytes = buildZeroAdapter(adapterModelBytes); if (typeof exports.validate_adapter_delta !== "function") { fail("validate_adapter_delta export was missing"); } const validateAdapterPtr = allocCopy(exports, adapterBytes); try { expectCode("validate_adapter_delta", exports.validate_adapter_delta(validateAdapterPtr, adapterBytes.length), ErrorCode.Ok); } finally { release(exports, validateAdapterPtr, adapterBytes.length); } const validateAdapterText = readLastResult(exports); if (validateAdapterText !== "adapter validated") { fail(`validate_adapter_delta result was ${JSON.stringify(validateAdapterText)}, expected "adapter validated"`); } const validateAdapterDiagnostics = readDiagnostics(exports); if (validateAdapterDiagnostics.last_error !== "ok") { fail(`validate_adapter_delta diagnostics last_error was ${JSON.stringify(validateAdapterDiagnostics.last_error)}`); } if (validateAdapterDiagnostics.model_loaded !== true || validateAdapterDiagnostics.active_quantization_mode !== "f32") { fail(`validate_adapter_delta model state was ${JSON.stringify({ modelLoaded: validateAdapterDiagnostics.model_loaded, activeQuantizationMode: validateAdapterDiagnostics.active_quantization_mode })}`); } expectAssemblyDiagnostics("validate_adapter_delta", validateAdapterDiagnostics, 0, true); const adapterPtr = allocCopy(exports, adapterBytes); try { expectCode("apply_adapter_delta", exports.apply_adapter_delta(adapterPtr, adapterBytes.length), ErrorCode.Ok); } finally { release(exports, adapterPtr, adapterBytes.length); } const adapterText = readLastResult(exports); if (adapterText !== "adapter applied") { fail(`apply_adapter_delta result was ${JSON.stringify(adapterText)}, expected "adapter applied"`); } const adapterDiagnostics = readDiagnostics(exports); if (adapterDiagnostics.last_error !== "ok") { fail(`apply_adapter_delta diagnostics last_error was ${JSON.stringify(adapterDiagnostics.last_error)}`); } if (adapterDiagnostics.model_loaded !== true || adapterDiagnostics.active_quantization_mode !== "f32") { fail(`apply_adapter_delta model state was ${JSON.stringify({ modelLoaded: adapterDiagnostics.model_loaded, activeQuantizationMode: adapterDiagnostics.active_quantization_mode })}`); } if (adapterDiagnostics.generated_token_count !== 0 || adapterDiagnostics.kv_cache_length !== 0 || adapterDiagnostics.selected_next_token !== 0) { fail(`apply_adapter_delta reset state was ${JSON.stringify({ generatedTokenCount: adapterDiagnostics.generated_token_count, kvCacheLength: adapterDiagnostics.kv_cache_length, selectedNextToken: adapterDiagnostics.selected_next_token })}`); } expectAssemblyDiagnostics("apply_adapter_delta", adapterDiagnostics, 1, true); expectCode("free_model", exports.free_model(), ErrorCode.Ok); const freeText = readLastResult(exports); if (freeText !== "model freed") { fail(`free_model result was ${JSON.stringify(freeText)}, expected "model freed"`); } const freeDiagnostics = readDiagnostics(exports); if (freeDiagnostics.last_error !== "ok") { fail(`free_model diagnostics last_error was ${JSON.stringify(freeDiagnostics.last_error)}`); } if (freeDiagnostics.model_loaded !== false) { fail(`free_model model_loaded was ${freeDiagnostics.model_loaded}`); } if (freeDiagnostics.active_quantization_mode !== "none") { fail(`free_model quantization was ${JSON.stringify(freeDiagnostics.active_quantization_mode)}`); } expectAssemblyDiagnostics("free_model", freeDiagnostics, 0, false); expectCode("post-free generate_next_token", exports.generate_next_token(), ErrorCode.ModelNotLoaded); const postFreeText = readLastResult(exports); if (postFreeText !== "model not loaded") { fail(`post-free generate_next_token result was ${JSON.stringify(postFreeText)}, expected "model not loaded"`); } const postFreeDiagnostics = readDiagnostics(exports); if (postFreeDiagnostics.last_error !== "model not loaded") { fail(`post-free diagnostics last_error was ${JSON.stringify(postFreeDiagnostics.last_error)}`); } if (postFreeDiagnostics.model_loaded !== false) { fail(`post-free model_loaded was ${postFreeDiagnostics.model_loaded}`); } console.log(JSON.stringify({ wasm: path.relative(process.cwd(), wasmPath), model: path.relative(process.cwd(), modelPath), invalidUtf8: "passed", nullPointer: "passed", invalidLength: "passed", invalidSamplingConfig: "passed", recovery: recoveryText, generateNextToken: stepText, adapterValidate: validateAdapterText, adapterApply: adapterText, freeModel: freeText, postFreeGenerateNextToken: postFreeText, diagnostics: { recovery_last_error: recoveryDiagnostics.last_error, recovery_selected_next_token: recoveryDiagnostics.selected_next_token, step_generated_token_count: stepDiagnostics.generated_token_count, step_kv_cache_length: stepDiagnostics.kv_cache_length, adapter_validate_active_quantization_mode: validateAdapterDiagnostics.active_quantization_mode, adapter_active_quantization_mode: adapterDiagnostics.active_quantization_mode, adapter_apply_count: adapterDiagnostics.adapter_apply_count, assembly_state_checksum: adapterDiagnostics.assembly_state_checksum, active_quantization_mode: postFreeDiagnostics.active_quantization_mode, post_free_last_error: postFreeDiagnostics.last_error } }, null, 2)); } main().catch((error) => { console.error(error); process.exit(1); }); ================================================================================ END FILE: tinyrustlm/tools/wasm-abi-smoke.js ================================================================================ ================================================================================ BEGIN FILE: tools/vs/Build-TinyRustLM.ps1 BYTES: 4483 SHA256: 5371F463A326D4635C6291E518CF958D705CB1326759699CB58524C9ECE74ECC ================================================================================ [CmdletBinding()] param( [ValidateSet("Debug", "Release")] [string]$Configuration = "Debug", [switch]$Clean, [switch]$CleanOnly, [switch]$RunTests, [switch]$RegenerateModels ) $ErrorActionPreference = "Stop" $Root = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path function Resolve-CommandPath { param( [Parameter(Mandatory = $true)] [string]$Name, [string[]]$PreferredPaths = @() ) foreach ($candidate in $PreferredPaths) { if ($candidate -and (Test-Path -LiteralPath $candidate)) { return (Resolve-Path -LiteralPath $candidate).Path } } $command = Get-Command $Name -ErrorAction SilentlyContinue if ($null -ne $command) { return $command.Source } throw "Required command '$Name' was not found. Install Rust and Node, then reopen Visual Studio." } $Cargo = Resolve-CommandPath "cargo.exe" @( (Join-Path $env:USERPROFILE ".cargo\bin\cargo.exe"), "C:\Users\AI\.cargo\bin\cargo.exe" ) $Rustup = Resolve-CommandPath "rustup.exe" @( (Join-Path $env:USERPROFILE ".cargo\bin\rustup.exe"), "C:\Users\AI\.cargo\bin\rustup.exe" ) Push-Location $Root try { if ($Clean -or $CleanOnly) { & $Cargo clean if ($LASTEXITCODE -ne 0) { throw "cargo clean failed with exit code $LASTEXITCODE" } if ($CleanOnly) { exit 0 } } $installedTargets = & $Rustup target list --installed if ($LASTEXITCODE -ne 0) { throw "rustup target list failed with exit code $LASTEXITCODE" } if ($installedTargets -notcontains "wasm32-unknown-unknown") { & $Rustup target add wasm32-unknown-unknown if ($LASTEXITCODE -ne 0) { throw "rustup target add wasm32-unknown-unknown failed with exit code $LASTEXITCODE" } } & $Cargo build --workspace if ($LASTEXITCODE -ne 0) { throw "cargo build --workspace failed with exit code $LASTEXITCODE" } if ($RunTests) { & $Cargo test --workspace if ($LASTEXITCODE -ne 0) { throw "cargo test --workspace failed with exit code $LASTEXITCODE" } } & $Cargo build -p tinyrustlm-runtime --release --target wasm32-unknown-unknown if ($LASTEXITCODE -ne 0) { throw "cargo wasm build failed with exit code $LASTEXITCODE" } Copy-Item -LiteralPath "target\wasm32-unknown-unknown\release\tinyrustlm_runtime.wasm" -Destination "tinyrustlm\runtime\tinyrustlm.wasm" -Force & $Cargo run -p tinyrustlm-slm-pack -- runtime-wasm-manifest "tinyrustlm\runtime\tinyrustlm.wasm" "tinyrustlm\runtime\tinyrustlm.wasm.manifest" if ($LASTEXITCODE -ne 0) { throw "runtime WASM manifest generation failed with exit code $LASTEXITCODE" } $models = @( @{ Path = "tinyrustlm\models\tiny-test-model.slm"; Mode = "tiny-fixture" }, @{ Path = "tinyrustlm\models\tiny-test-model-tied.slm"; Mode = "tiny-fixture-tied" }, @{ Path = "tinyrustlm\models\tiny-test-model-q8.slm"; Mode = "tiny-fixture-q8" }, @{ Path = "tinyrustlm\models\tiny-test-model-q4.slm"; Mode = "tiny-fixture-q4" }, @{ Path = "tinyrustlm\models\tiny-test-model-bpe.slm"; Mode = "tiny-fixture-bpe" }, @{ Path = "tinyrustlm\models\tinylm16-f32.slm"; Mode = "tinylm16-f32" }, @{ Path = "tinyrustlm\models\tinylm16-q8.slm"; Mode = "tinylm16-q8" }, @{ Path = "tinyrustlm\models\tinylm16-q4.slm"; Mode = "tinylm16-q4" } ) foreach ($model in $models) { if ($RegenerateModels -or -not (Test-Path -LiteralPath $model.Path)) { & $Cargo run -p tinyrustlm-slm-pack -- $model.Path $model.Mode if ($LASTEXITCODE -ne 0) { throw "model pack failed for $($model.Path) with exit code $LASTEXITCODE" } } $manifestPath = "$($model.Path).manifest" if ($RegenerateModels -or -not (Test-Path -LiteralPath $manifestPath)) { & $Cargo run -p tinyrustlm-slm-pack -- manifest $model.Path $manifestPath deterministic-smoke if ($LASTEXITCODE -ne 0) { throw "model manifest generation failed for $($model.Path) with exit code $LASTEXITCODE" } } } Write-Host "TinyRustLM $Configuration build complete." Write-Host "Run from Visual Studio with Debug > Start Debugging, or open http://127.0.0.1:8080/app/ after starting the server." } finally { Pop-Location } ================================================================================ END FILE: tools/vs/Build-TinyRustLM.ps1 ================================================================================ ================================================================================ BEGIN FILE: tools/vs/Run-TinyRustLM.ps1 BYTES: 4087 SHA256: B1C08AF0BFEB1C0C6EA1EC19004DFE1BFD21C6BDE219C56232B4532ED136D1E8 ================================================================================ [CmdletBinding()] param( [int]$Port = 8080, [int]$PortSearchLimit = 20, [switch]$NoBuild, [switch]$NoBrowser ) $ErrorActionPreference = "Stop" $Root = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path function Get-AppUrl { param([int]$CandidatePort) return "http://127.0.0.1:$CandidatePort/app/" } function Resolve-ServerExecutable { $server = Join-Path $Root "target\debug\tinyrustlm-local-server.exe" if (-not (Test-Path -LiteralPath $server)) { throw "TinyRustLM Rust local server was not found at $server. Run the build first or remove -NoBuild." } return (Resolve-Path -LiteralPath $server).Path } function Get-WasmUrl { param([int]$CandidatePort) return "http://127.0.0.1:$CandidatePort/runtime/tinyrustlm.wasm" } function Test-LocalPortOpen { param([int]$CandidatePort) $client = [System.Net.Sockets.TcpClient]::new() try { $connect = $client.ConnectAsync("127.0.0.1", $CandidatePort) if (-not $connect.Wait(300)) { return $false } return $client.Connected } catch { return $false } finally { $client.Dispose() } } function Test-TinyRustLMServer { param([int]$CandidatePort) $appUrl = Get-AppUrl $CandidatePort $wasmUrl = Get-WasmUrl $CandidatePort try { $page = Invoke-WebRequest -Uri $appUrl -Method Get -UseBasicParsing -TimeoutSec 2 if ($page.StatusCode -lt 200 -or $page.StatusCode -ge 300) { return $false } $content = [string]$page.Content if (-not $content.Contains("TinyRustLM")) { return $false } $wasm = Invoke-WebRequest -Uri $wasmUrl -Method Head -UseBasicParsing -TimeoutSec 2 if ($wasm.StatusCode -lt 200 -or $wasm.StatusCode -ge 300) { return $false } return $true } catch { return $false } } function Resolve-RunTarget { param( [int]$PreferredPort, [int]$SearchLimit ) if ($SearchLimit -lt 0) { throw "PortSearchLimit must be zero or greater." } for ($offset = 0; $offset -le $SearchLimit; $offset++) { $candidate = $PreferredPort + $offset if ($candidate -gt 65535) { break } if (Test-TinyRustLMServer $candidate) { return [pscustomobject]@{ Port = $candidate Url = Get-AppUrl $candidate Reuse = $true } } if (-not (Test-LocalPortOpen $candidate)) { return [pscustomobject]@{ Port = $candidate Url = Get-AppUrl $candidate Reuse = $false } } Write-Host "Port $candidate is in use by another local service; checking next port." } throw "No available local port found from $PreferredPort through $($PreferredPort + $SearchLimit)." } Push-Location $Root try { if (-not $NoBuild) { & (Join-Path $PSScriptRoot "Build-TinyRustLM.ps1") -Configuration Debug if ($LASTEXITCODE -ne 0) { throw "Visual Studio pre-run build failed with exit code $LASTEXITCODE" } } $target = Resolve-RunTarget -PreferredPort $Port -SearchLimit $PortSearchLimit if ($target.Reuse) { Write-Host "TinyRustLM is already running at $($target.Url)" if (-not $NoBrowser) { Start-Process $target.Url } exit 0 } $Server = Resolve-ServerExecutable if (-not $NoBrowser) { Start-Job -ScriptBlock { param($OpenUrl) Start-Sleep -Milliseconds 900 Start-Process $OpenUrl } -ArgumentList $target.Url | Out-Null } Write-Host "Starting TinyRustLM static server at $($target.Url)" Write-Host "Stop debugging in Visual Studio to stop this foreground server." & $Server "tinyrustlm" $target.Port if ($LASTEXITCODE -ne 0) { throw "static server exited with code $LASTEXITCODE" } } finally { Pop-Location } ================================================================================ END FILE: tools/vs/Run-TinyRustLM.ps1 ================================================================================ ================================================================================ BEGIN FILE: tools/vs/Test-TinyRustLM.ps1 BYTES: 21955 SHA256: 5CB97570E976185DA8ECFDA4819FEBAC0F8BD94097EFEB3C6E92F44464676E0A ================================================================================ [CmdletBinding()] param( [switch]$BrowserSmoke, [switch]$PerformanceSoak, [int]$BrowserSmokePort = 8080, [int]$PortSearchLimit = 20, [int]$PerformanceSoakCycles = 3, [int]$PerformanceSoakTokens = 4 ) $ErrorActionPreference = "Stop" $Root = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path function Resolve-CommandPath { param( [Parameter(Mandatory = $true)] [string]$Name, [string[]]$PreferredPaths = @() ) foreach ($candidate in $PreferredPaths) { if ($candidate -and (Test-Path -LiteralPath $candidate)) { return (Resolve-Path -LiteralPath $candidate).Path } } $command = Get-Command $Name -ErrorAction SilentlyContinue if ($null -ne $command) { return $command.Source } throw "Required command '$Name' was not found. Install Rust and Node, then reopen Visual Studio." } $Cargo = Resolve-CommandPath "cargo.exe" @( (Join-Path $env:USERPROFILE ".cargo\bin\cargo.exe"), "C:\Users\AI\.cargo\bin\cargo.exe" ) function Get-AppUrl { param([int]$CandidatePort) return "http://127.0.0.1:$CandidatePort/app/" } function Get-WasmUrl { param([int]$CandidatePort) return "http://127.0.0.1:$CandidatePort/runtime/tinyrustlm.wasm" } function Test-LocalPortOpen { param([int]$CandidatePort) $client = [System.Net.Sockets.TcpClient]::new() try { $connect = $client.ConnectAsync("127.0.0.1", $CandidatePort) if (-not $connect.Wait(300)) { return $false } return $client.Connected } catch { return $false } finally { $client.Dispose() } } function Test-TinyRustLMServer { param([int]$CandidatePort) try { $page = Invoke-WebRequest -Uri (Get-AppUrl $CandidatePort) -Method Get -UseBasicParsing -TimeoutSec 2 if ($page.StatusCode -lt 200 -or $page.StatusCode -ge 300) { return $false } if (-not ([string]$page.Content).Contains("TinyRustLM")) { return $false } $wasm = Invoke-WebRequest -Uri (Get-WasmUrl $CandidatePort) -Method Head -UseBasicParsing -TimeoutSec 2 if ($wasm.StatusCode -lt 200 -or $wasm.StatusCode -ge 300) { return $false } return $true } catch { return $false } } function Resolve-BrowserSmokeTarget { param( [int]$PreferredPort, [int]$SearchLimit ) if ($SearchLimit -lt 0) { throw "PortSearchLimit must be zero or greater." } for ($offset = 0; $offset -le $SearchLimit; $offset++) { $candidate = $PreferredPort + $offset if ($candidate -gt 65535) { break } if (Test-TinyRustLMServer $candidate) { return [pscustomobject]@{ Port = $candidate Url = Get-AppUrl $candidate Reuse = $true } } if (-not (Test-LocalPortOpen $candidate)) { return [pscustomobject]@{ Port = $candidate Url = Get-AppUrl $candidate Reuse = $false } } } throw "No available local browser-smoke port found from $PreferredPort through $($PreferredPort + $SearchLimit)." } function Resolve-FreeLocalPort { param( [int]$PreferredPort, [int]$SearchLimit ) if ($SearchLimit -lt 0) { throw "PortSearchLimit must be zero or greater." } for ($offset = 0; $offset -le $SearchLimit; $offset++) { $candidate = $PreferredPort + $offset if ($candidate -gt 65535) { break } if (-not (Test-LocalPortOpen $candidate)) { return $candidate } } throw "No available local port found from $PreferredPort through $($PreferredPort + $SearchLimit)." } function Resolve-ServerExecutable { $server = Join-Path $Root "target\debug\tinyrustlm-local-server.exe" if (-not (Test-Path -LiteralPath $server)) { throw "TinyRustLM Rust local server was not found at $server after build." } return (Resolve-Path -LiteralPath $server).Path } function New-MultiParentBrowserSmokeRoot { param( [string]$Quantization = "f32" ) $safeQuantization = $Quantization -replace "[^A-Za-z0-9_]", "_" $bundleBase = Join-Path $Root ("target\browser-served-multi-parent-{0}-{1}" -f $safeQuantization, ([guid]::NewGuid().ToString("N"))) $servedRoot = Join-Path $bundleBase "tinyrustlm" New-Item -ItemType Directory -Force -Path $servedRoot | Out-Null Copy-Item -LiteralPath (Join-Path $Root "tinyrustlm\app") -Destination $servedRoot -Recurse -Force Copy-Item -LiteralPath (Join-Path $Root "tinyrustlm\runtime") -Destination $servedRoot -Recurse -Force $bundleStdout = Join-Path $bundleBase "browser-bundle.stdout.txt" $bundleStderr = Join-Path $bundleBase "browser-bundle.stderr.txt" $bundleArgs = @("run", "-p", "tinyrustlm-slm-pack", "--", "browser-multi-parent-bundle", $servedRoot) if ($Quantization -ne "f32") { $bundleArgs += $Quantization } $bundleProcess = Start-Process -FilePath $Cargo ` -ArgumentList $bundleArgs ` -RedirectStandardOutput $bundleStdout ` -RedirectStandardError $bundleStderr ` -Wait ` -PassThru ` -WindowStyle Hidden $bundleExitCode = $bundleProcess.ExitCode if ($bundleExitCode -ne 0) { throw "SLM browser multi-parent bundle generation failed with exit code $bundleExitCode" } return (Resolve-Path -LiteralPath $servedRoot).Path } Push-Location $Root try { & (Join-Path $PSScriptRoot "Build-TinyRustLM.ps1") -Configuration Debug -RunTests if ($LASTEXITCODE -ne 0) { throw "build and unit tests failed with exit code $LASTEXITCODE" } $docTargets = @( @("rustdoc", "-p", "tinyrustlm-runtime", "--lib", "--", "-D", "missing_docs"), @("rustdoc", "-p", "tinyrustlm-slm-pack", "--bin", "tinyrustlm-slm-pack", "--", "-D", "missing_docs"), @("rustdoc", "-p", "tinyrustlm-local-server", "--bin", "tinyrustlm-local-server", "--", "-D", "missing_docs"), @("rustdoc", "-p", "tinyrustlm-browser-harness", "--bin", "tinyrustlm-browser-harness", "--", "-D", "missing_docs") ) foreach ($docTarget in $docTargets) { & $Cargo @docTarget if ($LASTEXITCODE -ne 0) { throw "Rust public API documentation check failed for '$($docTarget -join ' ')' with exit code $LASTEXITCODE" } } node --check "tinyrustlm\app\app.js" if ($LASTEXITCODE -ne 0) { throw "app.js syntax check failed with exit code $LASTEXITCODE" } node --check "tinyrustlm\tools\static-server.js" if ($LASTEXITCODE -ne 0) { throw "static-server.js syntax check failed with exit code $LASTEXITCODE" } node --check "tinyrustlm\tools\browser-smoke.js" if ($LASTEXITCODE -ne 0) { throw "browser-smoke.js syntax check failed with exit code $LASTEXITCODE" } node --check "tinyrustlm\tools\wasm-abi-smoke.js" if ($LASTEXITCODE -ne 0) { throw "wasm-abi-smoke.js syntax check failed with exit code $LASTEXITCODE" } & $Cargo run -p tinyrustlm-browser-harness -- tinyrustlm if ($LASTEXITCODE -ne 0) { throw "TinyRustLM Rust browser harness static contract check failed with exit code $LASTEXITCODE" } $modelPaths = @( "tinyrustlm\models\tiny-test-model.slm", "tinyrustlm\models\tiny-test-model-tied.slm", "tinyrustlm\models\tiny-test-model-q8.slm", "tinyrustlm\models\tiny-test-model-q4.slm", "tinyrustlm\models\tiny-test-model-bpe.slm", "tinyrustlm\models\tinylm16-f32.slm", "tinyrustlm\models\tinylm16-q8.slm", "tinyrustlm\models\tinylm16-q4.slm" ) foreach ($modelPath in $modelPaths) { & $Cargo run -p tinyrustlm-slm-pack -- validate $modelPath if ($LASTEXITCODE -ne 0) { throw "SLM validation failed for $modelPath with exit code $LASTEXITCODE" } $manifestPath = "$modelPath.manifest" if (-not (Test-Path -LiteralPath $manifestPath)) { throw "SLM provenance manifest is missing for $modelPath" } & $Cargo run -p tinyrustlm-slm-pack -- validate-manifest $modelPath $manifestPath if ($LASTEXITCODE -ne 0) { throw "SLM manifest validation failed for $modelPath with exit code $LASTEXITCODE" } } $sourceFixture = "tinyrustlm\tests\fixtures\trained-source-tiny" & $Cargo run -p tinyrustlm-slm-pack -- validate-source $sourceFixture if ($LASTEXITCODE -ne 0) { throw "SLM trained-source validation failed for $sourceFixture with exit code $LASTEXITCODE" } $convertedDir = "target\trained-source-smoke" New-Item -ItemType Directory -Force -Path $convertedDir | Out-Null $conversionModes = @( [pscustomobject]@{ Quantization = "f32"; Suffix = "f32" }, [pscustomobject]@{ Quantization = "q8_0"; Suffix = "q8" }, [pscustomobject]@{ Quantization = "q4_0"; Suffix = "q4" } ) foreach ($conversionMode in $conversionModes) { $convertedModel = Join-Path $convertedDir "tiny-converted-$($conversionMode.Suffix).slm" $convertedManifest = "$convertedModel.manifest" & $Cargo run -p tinyrustlm-slm-pack -- convert-trained $sourceFixture $convertedModel $conversionMode.Quantization if ($LASTEXITCODE -ne 0) { throw "SLM trained-source $($conversionMode.Quantization) conversion failed with exit code $LASTEXITCODE" } & $Cargo run -p tinyrustlm-slm-pack -- validate $convertedModel if ($LASTEXITCODE -ne 0) { throw "Converted $($conversionMode.Quantization) SLM validation failed with exit code $LASTEXITCODE" } & $Cargo run -p tinyrustlm-slm-pack -- validate-manifest $convertedModel $convertedManifest if ($LASTEXITCODE -ne 0) { throw "Converted $($conversionMode.Quantization) SLM manifest validation failed with exit code $LASTEXITCODE" } & $Cargo run -p tinyrustlm-slm-pack -- quality-gate $convertedModel $convertedManifest runtime-smoke if ($LASTEXITCODE -ne 0) { throw "Converted $($conversionMode.Quantization) SLM runtime-smoke gate failed with exit code $LASTEXITCODE" } $convertedEval = Join-Path $convertedDir "tiny-converted-$($conversionMode.Suffix).eval" & $Cargo run -p tinyrustlm-runtime --bin tinyrustlm-eval -- $convertedModel $convertedManifest "tinyrustlm\tests\fixtures\assistant-quality-eval-cases.txt" $convertedEval if ($LASTEXITCODE -ne 0) { throw "TinyRustLM $($conversionMode.Quantization) eval runner failed with exit code $LASTEXITCODE" } & $Cargo run -p tinyrustlm-slm-pack -- quality-gate $convertedModel $convertedManifest assistant-quality $convertedEval if ($LASTEXITCODE -ne 0) { throw "Converted $($conversionMode.Quantization) SLM assistant-quality gate failed with exit code $LASTEXITCODE" } } $tiedSourceFixture = Join-Path $convertedDir "source-tiny-tied" & $Cargo run -p tinyrustlm-slm-pack -- source-template $tiedSourceFixture tiny-fixture-tied if ($LASTEXITCODE -ne 0) { throw "SLM tied trained-source template generation failed with exit code $LASTEXITCODE" } & $Cargo run -p tinyrustlm-slm-pack -- validate-source $tiedSourceFixture if ($LASTEXITCODE -ne 0) { throw "SLM tied trained-source validation failed with exit code $LASTEXITCODE" } foreach ($conversionMode in $conversionModes) { $convertedModel = Join-Path $convertedDir "tiny-tied-converted-$($conversionMode.Suffix).slm" $convertedManifest = "$convertedModel.manifest" & $Cargo run -p tinyrustlm-slm-pack -- convert-trained $tiedSourceFixture $convertedModel $conversionMode.Quantization if ($LASTEXITCODE -ne 0) { throw "SLM tied trained-source $($conversionMode.Quantization) conversion failed with exit code $LASTEXITCODE" } & $Cargo run -p tinyrustlm-slm-pack -- validate $convertedModel if ($LASTEXITCODE -ne 0) { throw "Converted tied $($conversionMode.Quantization) SLM validation failed with exit code $LASTEXITCODE" } & $Cargo run -p tinyrustlm-slm-pack -- validate-manifest $convertedModel $convertedManifest if ($LASTEXITCODE -ne 0) { throw "Converted tied $($conversionMode.Quantization) SLM manifest validation failed with exit code $LASTEXITCODE" } & $Cargo run -p tinyrustlm-slm-pack -- quality-gate $convertedModel $convertedManifest runtime-smoke if ($LASTEXITCODE -ne 0) { throw "Converted tied $($conversionMode.Quantization) SLM runtime-smoke gate failed with exit code $LASTEXITCODE" } } $bpeSourceFixture = Join-Path $convertedDir "source-tiny-bpe" & $Cargo run -p tinyrustlm-slm-pack -- source-template $bpeSourceFixture tiny-fixture-bpe if ($LASTEXITCODE -ne 0) { throw "SLM BPE trained-source template generation failed with exit code $LASTEXITCODE" } & $Cargo run -p tinyrustlm-slm-pack -- validate-source $bpeSourceFixture if ($LASTEXITCODE -ne 0) { throw "SLM BPE trained-source validation failed with exit code $LASTEXITCODE" } $bpeConvertedModel = Join-Path $convertedDir "tiny-bpe-converted-q8.slm" $bpeConvertedManifest = "$bpeConvertedModel.manifest" & $Cargo run -p tinyrustlm-slm-pack -- convert-trained $bpeSourceFixture $bpeConvertedModel q8_0 if ($LASTEXITCODE -ne 0) { throw "SLM BPE trained-source q8_0 conversion failed with exit code $LASTEXITCODE" } & $Cargo run -p tinyrustlm-slm-pack -- validate $bpeConvertedModel if ($LASTEXITCODE -ne 0) { throw "Converted BPE q8_0 SLM validation failed with exit code $LASTEXITCODE" } & $Cargo run -p tinyrustlm-slm-pack -- validate-manifest $bpeConvertedModel $bpeConvertedManifest if ($LASTEXITCODE -ne 0) { throw "Converted BPE q8_0 SLM manifest validation failed with exit code $LASTEXITCODE" } & $Cargo run -p tinyrustlm-slm-pack -- quality-gate $bpeConvertedModel $bpeConvertedManifest runtime-smoke if ($LASTEXITCODE -ne 0) { throw "Converted BPE q8_0 SLM runtime-smoke gate failed with exit code $LASTEXITCODE" } node "tinyrustlm\tools\wasm-abi-smoke.js" if ($LASTEXITCODE -ne 0) { throw "WASM ABI smoke failed with exit code $LASTEXITCODE" } if ($BrowserSmoke -or $PerformanceSoak) { $target = Resolve-BrowserSmokeTarget -PreferredPort $BrowserSmokePort -SearchLimit $PortSearchLimit $server = $null if ($target.Reuse) { Write-Host "Using existing TinyRustLM server at $($target.Url) for browser checks." } else { $serverExe = Resolve-ServerExecutable $server = Start-Process -FilePath $serverExe -ArgumentList @("tinyrustlm", "$($target.Port)") -PassThru -WindowStyle Hidden } try { for ($i = 0; $i -lt 40; $i++) { if (Test-TinyRustLMServer $target.Port) { break } Start-Sleep -Milliseconds 250 } if (-not (Test-TinyRustLMServer $target.Port)) { throw "TinyRustLM browser-smoke server did not become ready at $($target.Url)" } & $Cargo run -p tinyrustlm-browser-harness -- tinyrustlm --http $target.Url if ($LASTEXITCODE -ne 0) { throw "TinyRustLM Rust browser harness HTTP contract check failed with exit code $LASTEXITCODE" } if ($BrowserSmoke) { node "tinyrustlm\tools\browser-smoke.js" $target.Url 9225 tinylm16q8 if ($LASTEXITCODE -ne 0) { throw "q8 browser smoke failed with exit code $LASTEXITCODE" } node "tinyrustlm\tools\browser-smoke.js" $target.Url 9226 tinylm16q4 if ($LASTEXITCODE -ne 0) { throw "q4 browser smoke failed with exit code $LASTEXITCODE" } node "tinyrustlm\tools\browser-smoke.js" $target.Url 9227 tinylm16q8 loop if ($LASTEXITCODE -ne 0) { throw "browser loop smoke failed with exit code $LASTEXITCODE" } node "tinyrustlm\tools\browser-smoke.js" $target.Url 9228 tinylm16q8 model-error if ($LASTEXITCODE -ne 0) { throw "malformed model browser smoke failed with exit code $LASTEXITCODE" } node "tinyrustlm\tools\browser-smoke.js" $target.Url 9229 tinylm16q8 context-error if ($LASTEXITCODE -ne 0) { throw "context overflow browser smoke failed with exit code $LASTEXITCODE" } node "tinyrustlm\tools\browser-smoke.js" $target.Url 9230 tinylm16q8 missing-model if ($LASTEXITCODE -ne 0) { throw "missing model browser smoke failed with exit code $LASTEXITCODE" } node "tinyrustlm\tools\browser-smoke.js" $target.Url 9231 tinylm16q8 endurance 3 if ($LASTEXITCODE -ne 0) { throw "browser endurance smoke failed with exit code $LASTEXITCODE" } node "tinyrustlm\tools\browser-smoke.js" $target.Url 9232 tinylm16q8 performance 4 if ($LASTEXITCODE -ne 0) { throw "browser performance smoke failed with exit code $LASTEXITCODE" } node "tinyrustlm\tools\browser-smoke.js" $target.Url 9235 tinylm16q8 step-token if ($LASTEXITCODE -ne 0) { throw "browser step-token smoke failed with exit code $LASTEXITCODE" } node "tinyrustlm\tools\browser-smoke.js" $target.Url 9238 tinyf32 adapter-sidecar if ($LASTEXITCODE -ne 0) { throw "browser adapter sidecar smoke failed with exit code $LASTEXITCODE" } node "tinyrustlm\tools\browser-smoke.js" $target.Url 9236 multi-parent-sign-merge-q8 multi-parent-registry if ($LASTEXITCODE -ne 0) { throw "multi-parent registry browser smoke failed with exit code $LASTEXITCODE" } $bundleSpecs = @( @{ Quantization = "f32"; Model = "multi-parent-sign-merge-f32"; PortOffset = 100; Smokes = @(@{ Port = 9237; Mode = "multi-parent-registry-file" }, @{ Port = 9239; Mode = "adapter-sidecar-registry-file" }) }, @{ Quantization = "q8_0"; Model = "multi-parent-sign-merge-q8"; PortOffset = 101; Smokes = @(@{ Port = 9243; Mode = "adapter-sidecar-registry-file" }) }, @{ Quantization = "q4_0"; Model = "multi-parent-sign-merge-q4"; PortOffset = 102; Smokes = @(@{ Port = 9244; Mode = "adapter-sidecar-registry-file" }) } ) foreach ($bundleSpec in $bundleSpecs) { $bundleRoot = New-MultiParentBrowserSmokeRoot -Quantization $bundleSpec.Quantization $bundlePort = Resolve-FreeLocalPort -PreferredPort ($target.Port + $bundleSpec.PortOffset) -SearchLimit $PortSearchLimit $bundleUrl = Get-AppUrl $bundlePort $bundleServer = $null try { $serverExe = Resolve-ServerExecutable $bundleServer = Start-Process -FilePath $serverExe -ArgumentList @($bundleRoot, "$bundlePort") -PassThru -WindowStyle Hidden for ($i = 0; $i -lt 40; $i++) { if (Test-TinyRustLMServer $bundlePort) { break } Start-Sleep -Milliseconds 250 } if (-not (Test-TinyRustLMServer $bundlePort)) { throw "TinyRustLM generated-bundle browser-smoke server did not become ready at $bundleUrl" } foreach ($smoke in $bundleSpec.Smokes) { node "tinyrustlm\tools\browser-smoke.js" $bundleUrl $smoke.Port $bundleSpec.Model $smoke.Mode if ($LASTEXITCODE -ne 0) { throw "$($bundleSpec.Quantization) generated-bundle browser smoke failed with exit code $LASTEXITCODE" } } } finally { if ($null -ne $bundleServer -and -not $bundleServer.HasExited) { Stop-Process -Id $bundleServer.Id -Force -ErrorAction SilentlyContinue } } } node "tinyrustlm\tools\browser-smoke.js" $target.Url 9234 tinylm16q8 ui-audit if ($LASTEXITCODE -ne 0) { throw "browser UI audit failed with exit code $LASTEXITCODE" } } if ($PerformanceSoak) { node "tinyrustlm\tools\browser-smoke.js" $target.Url 9233 tinylm16q8 performance-soak $PerformanceSoakCycles $PerformanceSoakTokens if ($LASTEXITCODE -ne 0) { throw "browser performance soak failed with exit code $LASTEXITCODE" } } } finally { if ($null -ne $server -and -not $server.HasExited) { Stop-Process -Id $server.Id -Force -ErrorAction SilentlyContinue } } } Write-Host "TinyRustLM tests complete." } finally { Pop-Location } ================================================================================ END FILE: tools/vs/Test-TinyRustLM.ps1 ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/index.md BYTES: 15523 SHA256: 57FAEB895813A09929CC23C62C3483F9E2A9302401A22C50A566038417C7666C ================================================================================ --- title: GGUF.MiRust.com LLM Wiki Index source_site: GGUF.MiRust.com public_route: /gguf-mirust/ status: planned_pending_publication reviewed_utc: 2026-06-29T20:08:59Z --- # GGUF.MiRust.com This local LLM Wiki namespace routes durable memory for the GGUF.MiRust.com Rust mini-browser and browser-based AI harness project. ## Required Records - [Source Memory Guide](source-memory-guide.md) - [Knowledge Map](knowledge-map.md) - [Log](log.md) - [Report Intake Index 2026-06-25](reports/report-intake-index-2026-06-25.md) - [Report Intake Index 2026-06-26](reports/report-intake-index-2026-06-26.md) - [Report Intake Index 2026-06-28](reports/report-intake-index-2026-06-28.md) ## Report Memory - [Enterprise Rust Governance Memory](reports/enterprise-rust-governance-memory-2026-06-25.md) - [Browser Local Runtime Memory](reports/browser-local-runtime-memory-2026-06-25.md) - [TinyLM Modular Architecture Memory](reports/tinylm-modular-architecture-memory-2026-06-25.md) - [Teleodynamic Resource Bounded Memory](reports/teleodynamic-resource-bounded-memory-2026-06-25.md) - [Brand Product Positioning Memory](reports/brand-product-positioning-memory-2026-06-25.md) - [Model Breeding Ecology Memory](reports/model-breeding-ecology-memory-2026-06-26.md) - [Two Parent Operator Browser Provenance Memory](reports/two-parent-operator-browser-provenance-memory-2026-06-29.md) - [Crossover Operator Memory](reports/crossover-operator-memory-2026-06-29.md) - [Mutation Operator Memory](reports/mutation-operator-memory-2026-06-29.md) - [Prune Operator Memory](reports/prune-operator-memory-2026-06-29.md) - [DARE Operator Memory](reports/dare-operator-memory-2026-06-29.md) - [DARE Browser Operator Provenance Memory](reports/dare-browser-operator-provenance-memory-2026-06-29.md) - [Browser Converted Trained Provenance Memory](reports/browser-converted-trained-provenance-memory-2026-06-29.md) - [Browser Converted Trained File Route Memory](reports/browser-converted-trained-file-route-memory-2026-06-29.md) - [Browser Converted Trained All Route Memory](reports/browser-converted-trained-all-route-memory-2026-06-29.md) - [Federated Operator Memory](reports/federated-operator-memory-2026-06-29.md) - [Weighted Soup Operator Memory](reports/weighted-soup-operator-memory-2026-06-29.md) - [Multi-Parent Soup Manifest Memory](reports/multi-parent-soup-manifest-memory-2026-06-29.md) - [Browser Parent-Pool Soup Bundle Memory](reports/browser-parent-pool-soup-bundle-memory-2026-06-29.md) - [Browser Multi-Parent Operator Provenance Memory](reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md) - [Parent-Pool Evolution Schedule Memory](reports/parent-pool-evolution-schedule-memory-2026-06-29.md) - [Operator Schedule Carry-Forward Memory](reports/operator-schedule-carry-forward-memory-2026-06-29.md) - [Federated Selector Receipt Route Memory](reports/federated-selector-receipt-route-memory-2026-06-29.md) - [Candidate Operator Receipt Binding Memory](reports/candidate-operator-receipt-binding-memory-2026-06-29.md) - [Promotion Operator Receipt Binding Memory](reports/promotion-operator-receipt-binding-memory-2026-06-29.md) - [Admission Operator Receipt Binding Memory](reports/admission-operator-receipt-binding-memory-2026-06-29.md) - [Selector Operator Receipt Binding Memory](reports/selector-operator-receipt-binding-memory-2026-06-29.md) - [Runtime Adapter Apply Memory](reports/runtime-adapter-apply-memory-2026-06-27.md) - [Sparse Adapter Package Memory](reports/sparse-adapter-package-memory-2026-06-27.md) - [Low-Rank Adapter Package Memory](reports/low-rank-adapter-package-memory-2026-06-28.md) - [Trained Adapter Source Memory](reports/trained-adapter-source-memory-2026-06-28.md) - [Trained Adapter Source ALR1 Memory](reports/trained-adapter-source-alr1-memory-2026-06-28.md) - [Browser Low-Rank Adapter Route Memory](reports/browser-low-rank-adapter-route-memory-2026-06-28.md) - [Browser Source-Backed ALR1 Route Memory](reports/browser-source-backed-alr1-route-memory-2026-06-28.md) - [Browser Source-Backed ALR1 Contract Memory](reports/browser-source-backed-alr1-contract-memory-2026-06-28.md) - [Browser Adapter Sidecar Memory](reports/browser-adapter-sidecar-memory-2026-06-27.md) - [Registry Adapter Sidecar Memory](reports/registry-adapter-sidecar-memory-2026-06-27.md) - [Registry Adapter Family Memory](reports/registry-adapter-family-memory-2026-06-27.md) - [Adapter Family Receipt Memory](reports/adapter-family-receipt-memory-2026-06-27.md) - [Assembly Receipt Memory](reports/assembly-receipt-memory-2026-06-27.md) - [Browser Sparse Adapter Route Memory](reports/browser-sparse-adapter-route-memory-2026-06-27.md) - [Browser Preferred Adapter Route Memory](reports/browser-preferred-adapter-route-memory-2026-06-27.md) - [Browser Multi Quant Selector Root Memory](reports/browser-multi-quant-selector-root-memory-2026-06-27.md) - [Browser Frugal Selector Default Memory](reports/browser-frugal-selector-default-memory-2026-06-27.md) - [Browser Selector Budget Memory](reports/browser-selector-budget-memory-2026-06-27.md) - [Browser Selector Budget Contract Memory](reports/browser-selector-budget-contract-memory-2026-06-27.md) - [Browser Auto Assembly Memory](reports/browser-auto-assembly-memory-2026-06-27.md) - [Browser Auto Assembly Budget Memory](reports/browser-auto-assembly-budget-memory-2026-06-27.md) - [Browser Text Sidecar Budget Memory](reports/browser-text-sidecar-budget-memory-2026-06-27.md) - [Browser Text Sidecar Contract Memory](reports/browser-text-sidecar-contract-memory-2026-06-27.md) - [Browser Runtime Manifest Memory](reports/browser-runtime-manifest-memory-2026-06-27.md) - [Browser Adapter Stack Memory](reports/browser-adapter-stack-memory-2026-06-27.md) - [Browser Module Plan Memory](reports/browser-module-plan-memory-2026-06-27.md) - [Browser Module Plan Resource Memory](reports/browser-module-plan-resource-memory-2026-06-27.md) - [Browser Module Plan Resource Drift Memory](reports/browser-module-plan-resource-drift-memory-2026-06-27.md) - [Browser Module Plan Graph Drift Memory](reports/browser-module-plan-graph-drift-memory-2026-06-27.md) - [Browser Module Plan Stack Drift Memory](reports/browser-module-plan-stack-drift-memory-2026-06-27.md) - [Browser Module Plan Role Drift Memory](reports/browser-module-plan-role-drift-memory-2026-06-27.md) - [Browser Module Plan Display Memory](reports/browser-module-plan-display-memory-2026-06-27.md) - [Browser Module Plan Budget Display Memory](reports/browser-module-plan-budget-display-memory-2026-06-27.md) - [Browser Module Plan Role Display Memory](reports/browser-module-plan-role-display-memory-2026-06-27.md) - [Browser Module Plan Slots Memory](reports/browser-module-plan-slots-memory-2026-06-27.md) - [Browser Module Plan Dependencies Memory](reports/browser-module-plan-dependencies-memory-2026-06-27.md) - [Browser Module Plan Phases Memory](reports/browser-module-plan-phases-memory-2026-06-27.md) - [Browser Module Plan Byte Counts Memory](reports/browser-module-plan-byte-counts-memory-2026-06-27.md) - [Browser Module Plan Checksums Memory](reports/browser-module-plan-checksums-memory-2026-06-27.md) - [Browser Module Plan Profile Memory](reports/browser-module-plan-profile-memory-2026-06-28.md) - [Browser Module Plan Execution Profile Memory](reports/browser-module-plan-execution-profile-memory-2026-06-28.md) - [Browser Module Plan Fetch Policy Memory](reports/browser-module-plan-fetch-policy-memory-2026-06-28.md) - [Browser Module Plan Origin Policy Memory](reports/browser-module-plan-origin-policy-memory-2026-06-28.md) - [Browser Module Plan Fetch Count Memory](reports/browser-module-plan-fetch-count-memory-2026-06-28.md) - [Browser Module Plan Runtime Scratch Memory](reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md) - [Browser Module Plan Output Limit Memory](reports/browser-module-plan-output-limit-memory-2026-06-28.md) - [Browser Module Plan Total Budget Memory](reports/browser-module-plan-total-budget-memory-2026-06-28.md) - [Browser Module Plan Total Limit Memory](reports/browser-module-plan-total-limit-memory-2026-06-28.md) - [Browser Module Plan WASM Memory Memory](reports/browser-module-plan-wasm-memory-memory-2026-06-28.md) - [Browser Module Plan WASM Export Set Memory](reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md) - [Browser Module Plan WASM Heap Memory](reports/browser-module-plan-wasm-heap-memory-2026-06-28.md) - [Browser Module Plan WASM Transfer Memory](reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md) - [Browser Module Plan Model Release Memory](reports/browser-module-plan-model-release-memory-2026-06-29.md) - [Browser Module Plan Runtime Reset Memory](reports/browser-module-plan-runtime-reset-memory-2026-06-29.md) - [Browser Module Plan Adapter Validation Memory](reports/browser-module-plan-adapter-validation-memory-2026-06-29.md) - [Browser Module Plan Adapter Validation Count Memory](reports/browser-module-plan-adapter-validation-count-memory-2026-06-29.md) - [Browser Module Plan Adapter Apply Count Memory](reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md) - [Browser Module Plan Planned Fetch Count Memory](reports/browser-module-plan-planned-fetch-count-memory-2026-06-29.md) - [Browser Module Plan Actual Fetch Count Memory](reports/browser-module-plan-actual-fetch-count-memory-2026-06-29.md) - [Browser Module Plan Observed Route Set Memory](reports/browser-module-plan-observed-route-set-memory-2026-06-29.md) - [Browser Module Plan Actual Module Bytes Memory](reports/browser-module-plan-actual-module-bytes-memory-2026-06-29.md) - [Browser Module Plan Actual Module Checksums Memory](reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md) - [Browser Module Plan Route Set Memory](reports/browser-module-plan-route-set-memory-2026-06-29.md) - [Browser Module Plan Route Set Version Memory](reports/browser-module-plan-route-set-version-memory-2026-06-29.md) - [Browser Module Plan Route Set Algorithm Memory](reports/browser-module-plan-route-set-algorithm-memory-2026-06-29.md) - [Browser Module Plan Operator Receipt Memory](reports/browser-module-plan-operator-receipt-memory-2026-06-29.md) - [Browser Module Plan KV Cache Memory](reports/browser-module-plan-kv-cache-memory-2026-06-28.md) - [Browser Module Plan Adapter Stack Budget Memory](reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28.md) - [Browser Module Plan Context Token Memory](reports/browser-module-plan-context-token-memory-2026-06-28.md) - [Browser Module Plan Tokenizer Memory](reports/browser-module-plan-tokenizer-memory-2026-06-28.md) - [Browser Module Plan Sampler Cap Memory](reports/browser-module-plan-sampler-cap-memory-2026-06-28.md) - [Browser Module Plan Prompt Limit Memory](reports/browser-module-plan-prompt-limit-memory-2026-06-28.md) - [Browser Module Plan Count Drift Memory](reports/browser-module-plan-count-drift-memory-2026-06-28.md) - [Browser Combined Selector Assembly Memory](reports/browser-combined-selector-assembly-memory-2026-06-28.md) - [Browser Combined Selector Cycle Memory](reports/browser-combined-selector-cycle-memory-2026-06-28.md) - [Browser Combined Selector Route Soak Memory](reports/browser-combined-selector-route-soak-memory-2026-06-28.md) - [Browser Combined Selector Extended Route Soak Memory](reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md) - [Browser Combined Selector Stress Route Soak Memory](reports/browser-combined-selector-stress-route-soak-memory-2026-06-28.md) - [Browser Combined Selector Reload Soak Memory](reports/browser-combined-selector-reload-soak-memory-2026-06-28.md) - [Browser Assembly Trace Memory](reports/browser-assembly-trace-memory-2026-06-28.md) - [Browser Eval Case Evidence Checksum Memory](reports/browser-eval-case-evidence-checksum-memory-2026-06-28.md) - [Browser Assembly Eval Case Drift Memory](reports/browser-assembly-eval-case-drift-memory-2026-06-28.md) - [Browser Assembly Evidence File Drift Memory](reports/browser-assembly-evidence-file-drift-memory-2026-06-28.md) - [Browser Adapter Family Receipt Drift Memory](reports/browser-adapter-family-receipt-drift-memory-2026-06-28.md) - [Browser Adapter Manifest Drift Memory](reports/browser-adapter-manifest-drift-memory-2026-06-28.md) - [Browser Adapter Artifact Drift Memory](reports/browser-adapter-artifact-drift-memory-2026-06-28.md) - [Browser Adapter Stack Prefetch Drift Memory](reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md) - [Browser Adapter Stack Rust Validate Memory](reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md) - [Browser Adapter Stack Rust Validate Drift Memory](reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28.md) - [Browser Runtime Assembly Diagnostics Memory](reports/browser-runtime-assembly-diagnostics-memory-2026-06-28.md) - [Browser Selector Genome Fitness Memory](reports/browser-selector-genome-fitness-memory-2026-06-28.md) - [Browser Selector Species Fit Memory](reports/browser-selector-species-fit-memory-2026-06-28.md) - [Browser Selector Novelty Memory](reports/browser-selector-novelty-memory-2026-06-28.md) - [Browser Selector Population Memory](reports/browser-selector-population-memory-2026-06-28.md) - [Browser Selector Mate Selection Memory](reports/browser-selector-mate-selection-memory-2026-06-28.md) - [Browser Selector Phenotype Evidence Memory](reports/browser-selector-phenotype-evidence-memory-2026-06-28.md) - [Browser Selector Heritable Artifact Memory](reports/browser-selector-heritable-artifact-memory-2026-06-28.md) - [Model Breeding Reference Ideas](research/model-breeding-reference-ideas-2026-06-26.md) - [ModelBreeder and Zero-Dependency Reference Ideas](research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md) - [UAIX File Handoff Memory Strategy Dogfood](../../docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md) ## Boundary This namespace is a source memory plan for TinyRustLM. Current implementation claims must still be verified through `workspace.uai`, `.uai/test-plan.uai`, source files, and local test output before being repeated publicly. Latest route: Browser Converted Trained Provenance Memory records the `converted-trained-registry` proof for selector-served converted-trained manifests, Browser Converted Trained File Route Memory records `browser-converted-trained-bundle` plus `converted-trained-registry-file` proof for real selector/model/manifest files, and Browser Converted Trained All Route Memory records the q4-defaulted f32/q8/q4 converted-trained selector root; Crossover, Mutation, Prune, and DARE Operator Memory record deterministic operator paths for `crossover-candidate`, `mutation-candidate`, `prune-candidate`, and `dare-candidate`, with q8 validation and receipt-bound recomputation; Parent-Pool Evolution Schedule Memory records checksum-bound sign-merge plus soup replay planning inside `parent-pool-recipe`; load `.uai/short-term-memory.uai`, `.uai/long-term-memory.uai`, all Browser Converted Trained reports, the Crossover/Mutation/Prune/DARE Operator reports, the Federated/Weighted Soup reports, the Parent-Pool Evolution Schedule report, the Browser Multi-Parent Operator Provenance report, the Selector/Admission/Promotion/Candidate Operator Receipt Binding reports, the Model Breeding reference pages, the Browser Selector reports, the Browser Combined Selector reports, the Browser Module Plan reports, and the UAIX dogfood note for the current memory map. ================================================================================ END FILE: wiki/gguf-mirust/index.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/knowledge-map.md BYTES: 31725 SHA256: 7971DDF6B1CF5870BE5EF0FB11C665BD53A77913B279666C1600D847056641A7 ================================================================================ --- title: GGUF.MiRust.com Knowledge Map source_site: GGUF.MiRust.com public_route: /gguf-mirust/knowledge-map/ status: planned_pending_publication reviewed_utc: 2026-06-29T20:08:59Z --- # Knowledge Map ## Nodes - Project profile: `.uai/system-profile.uai` - Browser harness architecture: `docs/architecture/browser-harness.md` - AIWikis route plan: `docs/aiwikis-routing.md` - File Handoff rules: `.uai/file-handoff.uai` - Pointer ledger: `.uai/long-term-memory.uai` - UAIX File Handoff strategy dogfood: `docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md` - Report intake index: `wiki/gguf-mirust/reports/report-intake-index-2026-06-25.md` - Report intake index 2026-06-26: `wiki/gguf-mirust/reports/report-intake-index-2026-06-26.md` - Report intake index 2026-06-28: `wiki/gguf-mirust/reports/report-intake-index-2026-06-28.md` - Enterprise Rust governance memory: `wiki/gguf-mirust/reports/enterprise-rust-governance-memory-2026-06-25.md` - Browser local runtime memory: `wiki/gguf-mirust/reports/browser-local-runtime-memory-2026-06-25.md` - TinyLM modular architecture memory: `wiki/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25.md` - Teleodynamic resource-bounded memory: `wiki/gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25.md` - Brand product positioning memory: `wiki/gguf-mirust/reports/brand-product-positioning-memory-2026-06-25.md` - Model breeding ecology memory: `wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md` - Two-parent operator browser provenance memory: `wiki/gguf-mirust/reports/two-parent-operator-browser-provenance-memory-2026-06-29.md` - Crossover operator memory: `wiki/gguf-mirust/reports/crossover-operator-memory-2026-06-29.md` - Mutation operator memory: `wiki/gguf-mirust/reports/mutation-operator-memory-2026-06-29.md` - Prune operator memory: `wiki/gguf-mirust/reports/prune-operator-memory-2026-06-29.md` - DARE operator memory: `wiki/gguf-mirust/reports/dare-operator-memory-2026-06-29.md` - DARE browser operator provenance memory: `wiki/gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29.md` - Browser converted trained provenance memory: `wiki/gguf-mirust/reports/browser-converted-trained-provenance-memory-2026-06-29.md` - Browser converted trained file route memory: `wiki/gguf-mirust/reports/browser-converted-trained-file-route-memory-2026-06-29.md` - Browser converted trained all route memory: `wiki/gguf-mirust/reports/browser-converted-trained-all-route-memory-2026-06-29.md` - Federated operator memory: `wiki/gguf-mirust/reports/federated-operator-memory-2026-06-29.md` - Weighted soup operator memory: `wiki/gguf-mirust/reports/weighted-soup-operator-memory-2026-06-29.md` - Multi-parent soup manifest memory: `wiki/gguf-mirust/reports/multi-parent-soup-manifest-memory-2026-06-29.md` - Browser parent-pool soup bundle memory: `wiki/gguf-mirust/reports/browser-parent-pool-soup-bundle-memory-2026-06-29.md` - Browser multi-parent operator provenance memory: `wiki/gguf-mirust/reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md` covers generated Operator rows plus generated selector operator receipt byte and kind drift fallback before generated routes. - Browser mixed operator selector memory: `wiki/gguf-mirust/reports/browser-mixed-operator-selector-memory-2026-06-29.md` covers one selector root carrying sign-merge and soup q4/q8/f32 routes with same-page cross-family assembly, cycle proof, route-soak proof, and reload-soak proof. - Parent-pool evolution schedule memory: `wiki/gguf-mirust/reports/parent-pool-evolution-schedule-memory-2026-06-29.md` covers checksum-bound sign-merge plus soup operator-family planning in parent-pool recipes. - Operator schedule carry-forward memory: `wiki/gguf-mirust/reports/operator-schedule-carry-forward-memory-2026-06-29.md` covers parent-pool schedule identity in sign-merge and soup receipts plus multi-parent candidate manifest validation. - Federated selector receipt route memory: `wiki/gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29.md` - Candidate operator receipt binding memory: `wiki/gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29.md` - Promotion operator receipt binding memory: `wiki/gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29.md` - Admission operator receipt binding memory: `wiki/gguf-mirust/reports/admission-operator-receipt-binding-memory-2026-06-29.md` - Selector operator receipt binding memory: `wiki/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29.md` - Runtime adapter apply memory: `wiki/gguf-mirust/reports/runtime-adapter-apply-memory-2026-06-27.md` - Sparse adapter package memory: `wiki/gguf-mirust/reports/sparse-adapter-package-memory-2026-06-27.md` - Low-rank adapter package memory: `wiki/gguf-mirust/reports/low-rank-adapter-package-memory-2026-06-28.md` - Trained adapter source memory: `wiki/gguf-mirust/reports/trained-adapter-source-memory-2026-06-28.md` - Trained adapter source ALR1 memory: `wiki/gguf-mirust/reports/trained-adapter-source-alr1-memory-2026-06-28.md` - Browser low-rank adapter route memory: `wiki/gguf-mirust/reports/browser-low-rank-adapter-route-memory-2026-06-28.md` - Browser source-backed ALR1 route memory: `wiki/gguf-mirust/reports/browser-source-backed-alr1-route-memory-2026-06-28.md` - Browser source-backed ALR1 contract memory: `wiki/gguf-mirust/reports/browser-source-backed-alr1-contract-memory-2026-06-28.md` - Browser adapter sidecar memory: `wiki/gguf-mirust/reports/browser-adapter-sidecar-memory-2026-06-27.md` - Registry adapter sidecar memory: `wiki/gguf-mirust/reports/registry-adapter-sidecar-memory-2026-06-27.md` - Registry adapter family memory: `wiki/gguf-mirust/reports/registry-adapter-family-memory-2026-06-27.md` - Adapter family receipt memory: `wiki/gguf-mirust/reports/adapter-family-receipt-memory-2026-06-27.md` - Assembly receipt memory: `wiki/gguf-mirust/reports/assembly-receipt-memory-2026-06-27.md` - Browser sparse adapter route memory: `wiki/gguf-mirust/reports/browser-sparse-adapter-route-memory-2026-06-27.md` - Browser preferred adapter route memory: `wiki/gguf-mirust/reports/browser-preferred-adapter-route-memory-2026-06-27.md` - Browser multi quant selector root memory: `wiki/gguf-mirust/reports/browser-multi-quant-selector-root-memory-2026-06-27.md` - Browser frugal selector default memory: `wiki/gguf-mirust/reports/browser-frugal-selector-default-memory-2026-06-27.md` - Browser selector budget memory: `wiki/gguf-mirust/reports/browser-selector-budget-memory-2026-06-27.md` - Browser selector budget contract memory: `wiki/gguf-mirust/reports/browser-selector-budget-contract-memory-2026-06-27.md` - Browser auto assembly memory: `wiki/gguf-mirust/reports/browser-auto-assembly-memory-2026-06-27.md` - Browser auto assembly budget memory: `wiki/gguf-mirust/reports/browser-auto-assembly-budget-memory-2026-06-27.md` - Browser text sidecar budget memory: `wiki/gguf-mirust/reports/browser-text-sidecar-budget-memory-2026-06-27.md` - Browser text sidecar contract memory: `wiki/gguf-mirust/reports/browser-text-sidecar-contract-memory-2026-06-27.md` - Browser runtime manifest memory: `wiki/gguf-mirust/reports/browser-runtime-manifest-memory-2026-06-27.md` - Browser adapter stack memory: `wiki/gguf-mirust/reports/browser-adapter-stack-memory-2026-06-27.md` - Browser module plan memory: `wiki/gguf-mirust/reports/browser-module-plan-memory-2026-06-27.md` - Browser module plan resource memory: `wiki/gguf-mirust/reports/browser-module-plan-resource-memory-2026-06-27.md` - Browser module plan resource drift memory: `wiki/gguf-mirust/reports/browser-module-plan-resource-drift-memory-2026-06-27.md` - Browser module plan graph drift memory: `wiki/gguf-mirust/reports/browser-module-plan-graph-drift-memory-2026-06-27.md` - Browser module plan stack drift memory: `wiki/gguf-mirust/reports/browser-module-plan-stack-drift-memory-2026-06-27.md` - Browser module plan role drift memory: `wiki/gguf-mirust/reports/browser-module-plan-role-drift-memory-2026-06-27.md` - Browser module plan display memory: `wiki/gguf-mirust/reports/browser-module-plan-display-memory-2026-06-27.md` - Browser module plan budget display memory: `wiki/gguf-mirust/reports/browser-module-plan-budget-display-memory-2026-06-27.md` - Browser module plan role display memory: `wiki/gguf-mirust/reports/browser-module-plan-role-display-memory-2026-06-27.md` - Browser module plan slots memory: `wiki/gguf-mirust/reports/browser-module-plan-slots-memory-2026-06-27.md` - Browser module plan dependencies memory: `wiki/gguf-mirust/reports/browser-module-plan-dependencies-memory-2026-06-27.md` - Browser module plan phases memory: `wiki/gguf-mirust/reports/browser-module-plan-phases-memory-2026-06-27.md` - Browser module plan byte counts memory: `wiki/gguf-mirust/reports/browser-module-plan-byte-counts-memory-2026-06-27.md` - Browser module plan checksums memory: `wiki/gguf-mirust/reports/browser-module-plan-checksums-memory-2026-06-27.md` - Browser combined selector assembly memory: `wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md` - Browser combined selector cycle memory: `wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md` covers repeated all-root q4_0/q8_0/f32 switching plus release-before-reassembly proof. - Browser combined selector route soak memory: `wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md` covers three generated q4_0/q8_0/f32 cycles with per-pass route counts for every self-assembly file. - Browser combined selector extended route soak memory: `wiki/gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md` covers five generated q4_0/q8_0/f32 cycles, fifteen assemblies, path-flexible total-budget assertions, and per-pass route counts. - Browser combined selector stress route soak memory: `wiki/gguf-mirust/reports/browser-combined-selector-stress-route-soak-memory-2026-06-28.md` covers eight generated q4_0/q8_0/f32 cycles, twenty-four assemblies, and per-pass local route counts. - Browser combined selector reload soak memory: `wiki/gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28.md` covers fresh page-lifetime q4_0 defaults and repeated generated self-assembly route counts across reload passes. - Browser assembly trace memory: `wiki/gguf-mirust/reports/browser-assembly-trace-memory-2026-06-28.md` - Browser eval case evidence checksum memory: `wiki/gguf-mirust/reports/browser-eval-case-evidence-checksum-memory-2026-06-28.md` - Browser assembly eval case drift memory: `wiki/gguf-mirust/reports/browser-assembly-eval-case-drift-memory-2026-06-28.md` - Browser assembly evidence file drift memory: `wiki/gguf-mirust/reports/browser-assembly-evidence-file-drift-memory-2026-06-28.md` - Browser adapter family receipt drift memory: `wiki/gguf-mirust/reports/browser-adapter-family-receipt-drift-memory-2026-06-28.md` - Browser adapter manifest drift memory: `wiki/gguf-mirust/reports/browser-adapter-manifest-drift-memory-2026-06-28.md` - Browser adapter artifact drift memory: `wiki/gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28.md` - Browser adapter stack prefetch drift memory: `wiki/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md` - Browser adapter stack Rust validate memory: `wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md` - Browser adapter stack Rust validate drift memory: `wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28.md` - Browser runtime assembly diagnostics memory: `wiki/gguf-mirust/reports/browser-runtime-assembly-diagnostics-memory-2026-06-28.md` - Browser selector genome fitness memory: `wiki/gguf-mirust/reports/browser-selector-genome-fitness-memory-2026-06-28.md` - Browser selector species fit memory: `wiki/gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28.md` - Browser selector novelty memory: `wiki/gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28.md` - Browser selector population memory: `wiki/gguf-mirust/reports/browser-selector-population-memory-2026-06-28.md` - Browser selector mate selection memory: `wiki/gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28.md` - Browser selector phenotype evidence memory: `wiki/gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28.md` - Browser selector heritable artifact memory: `wiki/gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28.md` - Browser module plan profile memory: `wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md` - Browser module plan execution profile memory: `wiki/gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28.md` - Browser module plan fetch policy memory: `wiki/gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28.md` - Browser module plan origin policy memory: `wiki/gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28.md` - Browser module plan fetch count memory: `wiki/gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28.md` - Browser module plan runtime scratch memory: `wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md` - Browser module plan total budget memory: `wiki/gguf-mirust/reports/browser-module-plan-total-budget-memory-2026-06-28.md` - Browser module plan total limit memory: `wiki/gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28.md` - Browser module plan WASM memory: `wiki/gguf-mirust/reports/browser-module-plan-wasm-memory-memory-2026-06-28.md` - Browser module plan WASM export set memory: `wiki/gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md` - Browser module plan WASM heap memory: `wiki/gguf-mirust/reports/browser-module-plan-wasm-heap-memory-2026-06-28.md` - Browser module plan WASM transfer memory: `wiki/gguf-mirust/reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md` - Browser module plan model release memory: `wiki/gguf-mirust/reports/browser-module-plan-model-release-memory-2026-06-29.md` - Browser module plan runtime reset memory: `wiki/gguf-mirust/reports/browser-module-plan-runtime-reset-memory-2026-06-29.md` - Browser module plan adapter validation memory: `wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29.md` - Browser module plan adapter validation count memory: `wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-count-memory-2026-06-29.md` - Browser module plan adapter apply count memory: `wiki/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md` - Browser module plan planned fetch count memory: `wiki/gguf-mirust/reports/browser-module-plan-planned-fetch-count-memory-2026-06-29.md` - Browser module plan actual fetch count memory: `wiki/gguf-mirust/reports/browser-module-plan-actual-fetch-count-memory-2026-06-29.md` - Browser module plan observed route set memory: `wiki/gguf-mirust/reports/browser-module-plan-observed-route-set-memory-2026-06-29.md` - Browser module plan actual module bytes memory: `wiki/gguf-mirust/reports/browser-module-plan-actual-module-bytes-memory-2026-06-29.md` - Browser module plan actual module checksums memory: `wiki/gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md` - Browser module plan route set memory: `wiki/gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29.md` - Browser module plan route set version memory: `wiki/gguf-mirust/reports/browser-module-plan-route-set-version-memory-2026-06-29.md` - Browser module plan route set algorithm memory: `wiki/gguf-mirust/reports/browser-module-plan-route-set-algorithm-memory-2026-06-29.md` - Browser module plan operator receipt memory: `wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md` - Browser module plan KV cache memory: `wiki/gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28.md` - Browser module plan adapter stack budget memory: `wiki/gguf-mirust/reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28.md` - Browser module plan context token memory: `wiki/gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28.md` - Browser module plan tokenizer memory: `wiki/gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28.md` - Browser module plan sampler cap memory: `wiki/gguf-mirust/reports/browser-module-plan-sampler-cap-memory-2026-06-28.md` - Browser module plan prompt limit memory: `wiki/gguf-mirust/reports/browser-module-plan-prompt-limit-memory-2026-06-28.md` - Browser module plan count drift memory: `wiki/gguf-mirust/reports/browser-module-plan-count-drift-memory-2026-06-28.md` - Model breeding reference ideas: `wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md` - ModelBreeder and zero-dependency reference ideas: `wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md` - Raw report evidence: `raw/gguf-mirust/report-intake-2026-06-25/` - Raw model-breeding evidence: `raw/gguf-mirust/report-intake-2026-06-26/` - Raw ModelBreeder and zero-dependency evidence: `raw/gguf-mirust/report-intake-2026-06-28/` ## Relationships - `.uai/long-term-memory.uai` points to durable files and public routes. - `docs/architecture/browser-harness.md` defines implementation boundaries. - `wiki/gguf-mirust/source-memory-guide.md` is the public routing record for future agents. - Report synthesis records distribute active handoff reports by theme so agents can load governance, browser runtime, modular model, teleodynamic, or brand context without bulk-loading every original report. - Model breeding records route compatible merge, sparse lineage, adapter ecology, population search, federated/local-update ideas, seed-weighted parent-pool soup ideas, browser-constrained assembly, UAIX memory strategy, sparse-mask receipt metadata, sparse ASP1 adapter packages, low-rank ALR1 adapter packages, source-backed browser ALR1 routes, source-backed ALR1 receipt source echoes and manifest-vs-receipt provenance checks, population objective-vector fields, parent relatedness recipe/receipt/manifest fields, genome/fitness/novelty/speciation/population guidance, zero-dependency browser-runtime guidance, selector `genome_id`, `genome_lineage_checksum`, `species_id`, `species_fit_checksum`, `novelty_id`, `novelty_checksum`, `population_id`, `population_checksum`, `mate_selection_id`, `mate_selection_parent_count`, `mate_selection_checksum`, `phenotype_evidence_id`, `phenotype_evidence_checksum`, and `fitness_vector_checksum` fields rendered in Model Provenance, runtime f32/q8_0/q4_0 ADP1/ASP1/ALR1 adapter validation and apply, runtime assembly diagnostics with adapter apply count plus model/adapter assembly checksums, runtime KV-cache byte/page diagnostics, checked browser f32/q8_0/q4_0 ADP1 sidecars, registry-carried f32/q8_0/q4_0 ADP1/ASP1/ALR1 sidecars, registry-carried adapter families, adapter-family receipts with preferred member and stack fields, registry-controlled auto assembly with `adapter_auto_apply_byte_budget=1048576`, generated f32/q8_0/q4_0 bundle roots, one q4-defaulted combined f32/q8_0/q4_0 selector root with all-three-entry `combined-selector-assembly` proof, repeated selector cycle proof, route-soak proof for every generated self-assembly file including an eight-cycle stress route-soak, reload-soak proof for fresh page-lifetime q4_0 default assembly and repeated local route requests, browser selector byte-budget intake, browser text-sidecar byte envelopes and registry-declared contract fields, runtime WASM manifests before instantiation, selector-declared module-plan receipts with `browser-constrained-v1` profile, `single-threaded-wasm-local-v1` execution profile, `local-no-store-v1` fetch policy, resource envelopes, runtime scratch envelope, generated-output cap, KV-cache byte/page envelope, total self-assembly byte budget, module-count matching, planned fetch-count matching, actual fetch-count matching, observed route-set matching, actual module-byte matching, actual module-checksum matching, route-set checksum algorithm matching, route-set version matching, route-set checksum matching, operator receipt route/checksum matching across selector registry, module plan, assembly receipt, and fetched evidence, role fields, assembly slots, phase fields, dependency edges, per-module byte-count fields, per-module checksum fields, browser-owned Module Plan Trace from plan verification through ready state, registry-backed `eval_case_evidence_checksum` routing through admissions, ledgers, selector registries, assembly receipts, and Model Provenance, assembly eval-case drift proof before evidence or adapter routes, assembly evidence-file drift proof before later evidence or adapter routes, adapter-family receipt drift proof before adapter manifests or stack artifacts, adapter-manifest drift proof before later manifests or stack artifacts, source-backed ALR1 manifest drift proof before stack artifact fetch, adapter-artifact drift proof before later stack artifacts or `apply_adapter_delta`, adapter-stack prefetch drift proof that all fetched auto-stack bytes verify before any Rust adapter apply, adapter-stack Rust validation proof that all fetched auto-stack bytes pass `validate_adapter_delta` before first apply, adapter-stack Rust validation drift proof that checksum-consistent ADP1 identity drift reaches Rust validation and stops before apply, profile/execution-profile/fetch-policy/runtime-scratch/output-limit/KV-cache/total-budget/count/planned-fetch-count/route-set-algorithm/route-set-version/route-set/operator-receipt/resource/graph/stack/role/slot/phase/byte/checksum/dependency drift smokes before generated model or stack artifact fetch, Module Plan display fields, visible execution/fetch/model/adapter/scratch/output/KV/total budget rows, Plan Fetches rows, Actual Fetches rows, Actual Route Set rows, Actual Module Bytes rows, Actual Module Checksums rows, Route Hash rows, Route Version rows, Route Set rows, byte summaries, checksum summaries, slot summaries, role summaries, phase summaries, dependency summaries, and trace summaries from verified receipts and browser checkpoints, the `selector_model_byte_budget=33554432` registry contract, assembly receipts with evidence-file fetches, and candidate-evaluation research into future TinyRustLM work without changing current quality authority. - Module-plan adapter stack budget records route exact `module_plan_adapter_stack_byte_budget` generation, registry validation, receipt matching, UI rendering, and drift smoke coverage for generated q4_0/q8_0/f32 auto-stack bytes. - Module-plan tokenizer records route tokenizer checksum identity through generated selector entries, served receipts, UI rendering, genome/species checksum ingredients, and drift smoke coverage for generated q4_0/q8_0/f32 roots. - Module-plan WASM export-set records route `tinyrustlm-generate-v1` selector and receipt fields, instantiated export checks, Module Plan WASM ABI rendering, and drift smoke coverage for generated q4_0/q8_0/f32 roots. - Module-plan WASM transfer records route `copy-then-release-v1` selector and receipt fields, Module Plan Transfer rendering, source fallback behavior, and drift smoke coverage for generated q4_0/q8_0/f32 roots. - Module-plan model release records route `free-before-reassembly-v1` selector and receipt fields, Module Plan Release rendering, source fallback behavior, and drift smoke coverage for generated q4_0/q8_0/f32 roots. - Module-plan adapter validation records route `rust-validate-before-apply-v1` selector and receipt fields, Module Plan Validate rendering, source fallback behavior, and drift smoke coverage for generated q4_0/q8_0/f32 roots. - Module-plan adapter apply count records route `module_plan_adapter_apply_count=3`, Module Plan Apply Count rendering, adapter-family stack count agreement, runtime `adapter_apply_count` diagnostics checks, and drift smoke coverage before generated model fetch. - Module-plan planned fetch count records route `module_plan_planned_fetch_count=21`, Module Plan Plan Fetches rendering, selector/receipt/generated-route agreement, and drift smoke coverage before generated model fetch. - Module-plan actual fetch count records browser-owned generated route accounting, Module Plan Actual Fetches rendering, planned-versus-actual Ready gating, and generated q4_0/q8_0/f32 combined-selector proof. - Module-plan observed route set records browser-owned `{kind,path}` route observations, Module Plan Actual Route Set rendering, observed-versus-declared Ready gating, and generated q4_0/q8_0/f32 combined-selector proof. - Module-plan actual module bytes records browser-owned module byte observations, Module Plan Actual Module Bytes rendering, observed-versus-receipt Ready gating, and generated q4_0/q8_0/f32 combined-selector proof. - Module-plan actual module checksums records browser-owned module checksum observations, Module Plan Actual Module Checksums rendering, observed-versus-receipt Ready gating, module-plan-payload-checksum-drift, and generated q4_0/q8_0/f32 combined-selector proof. - Module-plan route-set records route `module_plan_route_set_checksum`, Module Plan Route Set rendering, selector/receipt/ordered-route agreement, and drift smoke coverage before generated model fetch. - Federated operator memory records base/local-update parent roles, `local_update_weight_ppm`, local-update counts, raw and weighted delta checksums, q8 validation, parameter tests, and CLI proof before downstream candidate manifests. - Weighted soup operator memory records parent-pool seed weights, direct weighted tensor averaging, parent order checksums, weighted-value checksums, changed-from-frontier density, focused drift tests, and CLI validation before downstream candidate manifests. - Multi-parent soup manifest memory records parent-pool operator-kind dispatch, sign-merge or soup receipt recomputation, `candidate_manifest_status=validated-parent-pool-operator-output`, soup metric preservation, and downstream multi-parent promotion/admission/selector/browser-bundle test coverage. - Browser parent-pool soup bundle memory records `browser-multi-parent-bundle` operator selection, `multi-parent-soup-*` generated ids, `soup.*` evidence routes, `multi-parent-weighted-soup` assembly receipts, selector route-set prefix derivation, and browser validation for soup evidence families. - Browser multi-parent operator provenance memory records multi-parent admission `operator_receipt_*` carry-forward into generated selector entries, q4/q8/f32 browser Model Provenance Operator rows for parent-pool soup/sign-merge, and generated operator byte/kind drift fallback before generated routes. - Operator schedule carry-forward memory records `evolution_schedule_checksum`, scheduled family index, command, selection rule, and output gate flowing from parent-pool recipes into sign-merge/soup receipts and multi-parent candidate manifests. - Federated selector receipt route records `federated-local-update-average` receipt handoff through candidate, promotion, admission, selector registry fields, browser Model Provenance Operator rendering, operator-kind drift rejection, and browser operator-receipt byte-count drift fallback. - Module-plan route-set version records route `module_plan_route_set_version=1`, Module Plan Route Version rendering, route-set checksum preimage versioning, and drift smoke coverage before generated model fetch. - Module-plan route-set algorithm records route `module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1`, Module Plan Route Hash rendering, route-set checksum preimage algorithm labels, and drift smoke coverage before generated model fetch. - Module-plan operator receipt records route `entry.N.module_plan_operator_receipt_*` plus `.module-plan.receipt` `operator_receipt_*` fields through assembly receipt agreement and evidence checksum verification before generated model fetch. - Crossover operator records route `crossover-candidate` and `validate-crossover-candidate`, deterministic seed-plus-keep selection, per-parent density fields, mask checksum, q8 validation, browser Operator rendering, crossover byte-echo fallback, parameter tests, drift tests, and CLI proof before downstream candidate manifests. - Mutation operator records route `mutation-candidate` and `validate-mutation-candidate`, deterministic seed/rate/magnitude perturbation, reference-parent scaling, selection checksum, delta checksum, q8 validation, browser Operator rendering, mutation byte-echo fallback, parameter tests, drift tests, and CLI proof before downstream candidate manifests. - Prune operator records route `prune-candidate` and `validate-prune-candidate`, deterministic magnitude ranking, keep/floor ppm fields, mask checksum, output-value checksum, q8 validation, selector receipt carry-forward, browser Operator rendering, prune byte-echo fallback, parameter tests, drift tests, and CLI proof before downstream candidate manifests. - DARE operator records route `dare-candidate` and `validate-dare-candidate`, seeded dropout/rescaled task deltas, signed delta weights, keep/drop ppm fields, mask/raw/rescaled delta checksums, q8 validation, parameter tests, drift tests, and CLI proof before downstream candidate manifests. - DARE browser operator provenance records DARE receipt-bound selector fields, Model Provenance Operator rendering, selector operator-kind drift rejection, and DARE byte fallback through `dare-operator-registry` and `dare-operator-receipt-drift`. - Browser converted trained provenance records route `converted-trained-registry`, converted-trained q8 selector fixture proof, converted-trained manifest request proof, and browser Model Provenance source/admission/quality field assertions. - Browser converted trained file route records `browser-converted-trained-bundle`, generated q8 file-backed root proof, and `converted-trained-registry-file` selector/model/manifest fetch assertions. - Browser converted trained all route records `browser-converted-trained-bundle all`, generated q4-defaulted f32/q8/q4 file-backed root proof, and q4/q8/f32 `converted-trained-registry-file` selector/model/manifest fetch assertions. - Candidate operator receipt binding records route optional operator receipt fields through candidate manifests, tying receipt checksum, operator identity, candidate bytes, and candidate checksum to downstream eval and promotion gates. - Selector operator receipt binding records route receipt-bound admission fields into selector registry entries and browser Model Provenance Operator metadata. - Module-plan prompt-limit records route `module_plan_prompt_byte_limit=4096` selector and receipt fields, Module Plan Prompt Limit rendering, source prompt-copy boundary proof, total-budget inclusion, and drift smoke coverage for generated q4_0/q8_0/f32 roots. - Module-plan fetch-count records route `module_plan_fetch_count_limit=32` selector and receipt fields, Module Plan Fetch Limit rendering, generated route-count computation, and drift smoke coverage for generated q4_0/q8_0/f32 roots. - Short-term memory routes current report indexes, Model Breeding synthesis/reference pages, UAIX dogfood, active bucket scan, and long-term pointer ledger; long-term memory keeps checksum pointers for durable reports and research. - Raw evidence preserves exact report bytes with checksums; synthesis records carry reviewed interpretation, not source replacement authority. ================================================================================ END FILE: wiki/gguf-mirust/knowledge-map.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/log.md BYTES: 38024 SHA256: E29FC184355011CD3684083B080BF66A9FF8ED734D86E776756C9C10A381B7B7 ================================================================================ --- title: GGUF.MiRust.com LLM Wiki Log source_site: GGUF.MiRust.com public_route: /gguf-mirust/log/ status: planned_pending_publication reviewed_utc: 2026-06-29T20:08:59Z --- # LLM Wiki Log ## 2026-06-24 - Created the GGUF.MiRust.com Rust workspace skeleton. - Configured UAIX Project Handoff with File Handoff plus LLM Wiki memory. - Routed durable memory to AIWikis.org under `/gguf-mirust/`. - Recorded dogfood feedback for UAIX and LLMWikis setup guidance. ## 2026-06-26 - Processed 26 active Improvement reports into raw evidence under `raw/gguf-mirust/report-intake-2026-06-26/`. - Added model-breeding durable memory, reference ideas, and report intake routing. - Added `.uai/taboo.uai` to route GGUF.MiRust.com public copy toward constructive local-model craft and lineage. ## 2026-06-27 - Added browser Module Plan checksums so generated `.module-plan.receipt` files carry uniform `module.N.checksum` fields, the UI renders the checksum summary, and `module-plan-checksum-drift` proves checksum mismatches stop before generated `.slm`, ADP1, ASP1, or adapter-manifest routes. - Refreshed UAIX File Handoff memory strategy so reports stay in durable raw/wiki memory, short-term memory routes current report/research/dogfood paths, long-term memory keeps checksum pointers, and the Model Breeding reference page names diverse research lanes. - Added browser Module Plan byte counts so generated `.module-plan.receipt` files carry `module.N.byte_count` fields, the UI renders the byte summary, and `module-plan-byte-drift` proves byte-count mismatches stop before generated `.slm`, ADP1, ASP1, or adapter-manifest routes. - Added browser Module Plan phases so generated `.module-plan.receipt` files carry `module.N.phase` fields, the UI renders the phase summary, and `module-plan-phase-drift` proves phase mismatches stop before generated `.slm`, ADP1, ASP1, or adapter-manifest routes. - Added browser Module Plan dependencies so generated `.module-plan.receipt` files carry `module.N.depends_on` fields, the UI renders the dependency summary, and `module-plan-dependency-drift` proves dependency mismatches stop before generated `.slm`, ADP1, ASP1, or adapter-manifest routes. - Added browser Module Plan assembly slots so generated `.module-plan.receipt` files carry typed `module.N.assembly_slot` fields, the UI renders the slot summary, and `module-plan-slot-drift` proves slot mismatches stop before generated `.slm`, ADP1, ASP1, or adapter-manifest routes. - Added browser-smoke `module-plan-role-drift` so a checksum-consistent generated q4 module-plan receipt role mismatch stops before generated `.slm`, ADP1, ASP1, or adapter-manifest routes. - Added browser Module Plan role display so generated `.module-plan.receipt` files carry planner-readable `module.N.role` fields, source fallback reads unavailable, and generated q4 smoke asserts the rendered runtime/model-manifest/assembly/adapter-family/stack role summary. - Added browser Module Plan budget display so verified `.module-plan.receipt` model and adapter byte envelopes render in the UI, source fallback reads unavailable, and generated q4 smoke asserts `6592 bytes` plus `1048576 bytes`. - Added browser Module Plan display so verified `.module-plan.receipt` status, kind, resource class, module count, model route, and stack routes render in the UI and smoke assertions cover source fallback plus generated q4 receipt state. - Added browser-smoke `module-plan-stack-drift` so a checksum-consistent generated q4 module-plan receipt stack member path mismatch stops before generated `.slm`, ADP1, ASP1, or adapter-manifest routes. - Added browser-smoke `module-plan-graph-drift` so a checksum-consistent generated q4 module-plan receipt model path mismatch stops before the generated `.slm` route. - Added browser-smoke `module-plan-resource-drift` so a checksum-consistent generated q4 module-plan receipt budget mismatch stops before the generated `.slm` route. - Added browser module-plan resource envelopes so generated selector entries and served `.module-plan.receipt` files declare a resource class, admitted model byte budget, and adapter-family byte budget before browser model fetch. - Added browser module-plan receipts so generated selector entries declare checksum-bound `.module-plan.receipt` routes, app.js verifies the plan graph before generated `.slm` fetch, and generated-root smoke proves the plan route is requested before stack assembly and generation. ## 2026-06-29 - Added parent-pool evolution schedule fields so `parent-pool-recipe` records `population-based-parent-pool-replay-v1`, sign-merge and soup operator families, selected parent seed weights, population fitness echoes, and a checksum that `validate-parent-pool-recipe` recomputes. - Added operator schedule carry-forward so sign-merge and soup receipts echo parent-pool schedule identity plus scheduled family fields, and multi-parent candidate manifests validate those fields against the recipe. - Added browser converted-trained all-route proof so `browser-converted-trained-bundle ... all` stages converted-trained f32/q8/q4 under one q4-defaulted selector root and `converted-trained-registry-file` fetches real selector, model, and manifest files for all three entries. - Added browser converted-trained file-route proof so `browser-converted-trained-bundle` stages `converted-trained-q8` under a runnable root and `converted-trained-registry-file` fetches real selector, model, and manifest files before rendering converted-trained provenance fields. - Added browser converted-trained provenance proof so `converted-trained-registry` serves `converted-trained-q8`, fetches a converted-trained manifest, renders converted-trained source/admission/quality/pending-eval fields, and keeps compact multi-parent registry behavior green. - Added compact browser provenance proof for blend, task-delta, and sparse task-delta so their registry smokes render receipt-bound Operator rows and their receipt-drift smokes fall back to static q8 with Operator unavailable. - Added crossover and mutation operator browser provenance proof so `crossover-operator-registry` renders `receipt-bound / deterministic-direct-parameter-crossover / 0x00000000000000b2`, `mutation-operator-registry` renders `receipt-bound / deterministic-bounded-parameter-mutation / 0x00000000000000b3`, and both byte-echo drift smokes fall back to static q8 with Operator unavailable. - Added prune operator browser provenance proof so `prune-operator-registry` renders `receipt-bound / deterministic-magnitude-parameter-pruning / 0x00000000000000b1`, and `prune-operator-receipt-drift` falls back to static q8 with Operator unavailable. - Added DARE operator browser provenance proof so `dare-operator-registry` renders `receipt-bound / dropout-rescaled-task-delta / 0x00000000000000b7`, and `dare-operator-receipt-drift` falls back to static q8 with Operator unavailable. - Added mixed browser parent-pool operator selector proof so `browser-multi-parent-bundle all mixed` serves sign-merge and soup q4/q8/f32 entries in one selector, preserves `multi-parent-sign-merge-q4` as default, and `combined-selector-operator-family` assembles all six routes in one page. - Added `combined-selector-operator-family-cycle` so the mixed sign-merge plus soup root repeats all six q4/q8/f32 assemblies in one page while proving release-before-reassembly, Rust validation/apply counts, stack completions, governed route counts, and local-origin requests. - Added `combined-selector-operator-family-route-soak` so the mixed sign-merge plus soup root repeats all six q4/q8/f32 assemblies and proves every expected self-assembly route for each generated model is requested once per pass. - Added `combined-selector-operator-family-reload-soak` so two fresh page lifetimes each start on the sign-merge q4 default and rebuild sign-merge plus soup q4/q8/f32 assemblies with every expected route requested at least twice. - Added browser-smoke `generated-selector-operator-kind-drift` and app.js generated assembly operator-kind agreement so soup/sign-merge selector entries fall back to `tinylm16q8` before generated `.slm`, module-plan, assembly, adapter-family, or stack routes when `operator_receipt_operator_kind` drifts. - Added browser parent-pool soup bundle routing so `browser-multi-parent-bundle [quantization] soup` stages `multi-parent-soup-*` models with `soup.*` evidence files, `assembly_strategy=multi-parent-weighted-soup`, selector module-plan operator-prefix validation, and browser route-set checksum derivation for soup evidence families. - Added browser-smoke `generated-selector-operator-receipt-drift` so served generated soup and sign-merge selector registries with drifted `operator_receipt_candidate_artifact_bytes` fall back to `tinylm16q8` before generated `.slm`, module-plan, assembly, adapter-family, or stack routes are requested. - Extended multi-parent candidate manifests so validated sign-merge and soup parent-pool operator receipts share one manifest gate, dispatch by `operator_kind`, preserve sign or soup metrics, and keep downstream multi-parent promotion/admission/selector/browser-bundle validation green. - Added seed-weighted parent-pool soup receipts so `soup-candidate` writes direct averaged `.slm` candidates from parent-pool seed weights and `validate-soup-candidate` recomputes candidate bytes, parent order checksums, weighted-value checksums, changed-from-frontier density, and receipt text before downstream manifests. - Added browser-smoke `selector-operator-receipt-drift` so a selector registry entry with mismatched `operator_receipt_candidate_artifact_bytes` falls back to static `tinylm16q8`, keeps the generated route out of model options, and renders Operator as unavailable. - Extended the federated selector receipt route into browser smoke so the intercepted registry carries federated `entry.0.operator_receipt_*` fields and Model Provenance renders `receipt-bound / federated-local-update-average / 0x00000000000000b0`. - Added browser Module Plan Actual Module Checksums proof so generated q4_0/q8_0/f32 self-assembly records accepted module checksums, renders Actual Module Checksums, and gates Ready on observed checksums matching receipt module checksum rows. - Added offline federated/local-update operator receipts so `federated-candidate` writes compatibility-bound base/local-update `.slm` candidates with `local_update_weight_ppm`, local-update counts, raw and weighted delta checksums, while `validate-federated-candidate` recomputes candidate bytes and receipt text before downstream manifests. - Added federated selector receipt route proof so a `federated-local-update-average` receipt-bound candidate flows through candidate, promotion, admission, and selector registry records with operator kind, receipt checksum, candidate checksum, and byte-count equality preserved, then rejects operator-kind drift. - Added `module-plan-payload-checksum-drift` so a coherent family ADP1 payload checksum rewrite stops at the stale module-plan checksum row before generated model or adapter routes. - Added browser Module Plan Actual Module Bytes proof so generated q4_0/q8_0/f32 self-assembly records accepted module byte lengths, renders Actual Module Bytes, and gates Ready on observed totals matching receipt module byte rows. - Added browser Module Plan operator receipt binding so generated selector entries, `.module-plan.receipt` files, assembly receipts, and fetched `sign-merge.operator` evidence agree before generated model bytes or adapter routes proceed. - Added selector operator receipt binding so receipt-bound selector admissions emit `entry.N.operator_receipt_*` fields in `selector-registry`, validation rejects copied-field drift, and browser Model Provenance renders an Operator row. - Added browser multi-parent operator provenance proof so generated soup/sign-merge selector entries carry `entry.N.operator_receipt_*` fields from multi-parent admissions, and q4/q8/f32 soup browser smokes render receipt-bound Operator rows. - Added admission operator receipt carry-forward so two-parent `admission-record` and `validate-admission` can preserve and recompute promotion receipt fields before selector registry intake. - Added promotion operator receipt carry-forward so two-parent `promotion-template` and `validate-promotion` can preserve and recompute receipt-bound candidate fields before runtime smoke and eval gates. - Added offline deterministic direct-parameter crossover so `crossover-candidate` writes seed-plus-keep `.slm` candidates with receipt-bound selection counts, densities, and mask checksum, while `validate-crossover-candidate` recomputes candidate bytes and receipt text before downstream manifests. - Added offline deterministic bounded mutation so `mutation-candidate` writes seed/rate/magnitude `.slm` candidates with receipt-bound reference scaling, selection checksum, and delta checksum, while `validate-mutation-candidate` recomputes candidate bytes and receipt text before downstream manifests. - Added offline deterministic magnitude pruning so `prune-candidate` writes keep/floor `.slm` candidates with receipt-bound selected/pruned counts, mask checksum, and output-value checksum, while `validate-prune-candidate` recomputes candidate bytes and receipt text before downstream manifests. - Added offline DARE-style dropout/rescaled task-delta candidates so `dare-candidate` writes seeded keep/drop `.slm` candidates with receipt-bound mask, raw-delta, and rescaled-delta checksums, while `validate-dare-candidate` recomputes candidate bytes and receipt text before downstream manifests. - Added browser Module Plan route-set checksum algorithm proof so generated selector registries and `.module-plan.receipt` files carry `module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1`, the UI renders Route Hash, and generated smokes prove algorithm drift stops before generated model bytes. - Added browser Module Plan adapter validation-count proof so generated selector registries and `.module-plan.receipt` files carry `module_plan_adapter_validation_count=3`, the UI renders Validate Count, and generated smokes prove exactly three Rust validation calls before the three adapter applies. - Added browser adapter-stack self assembly so generated adapter-family receipts declare ordered stack members, selector registries carry stack fields, and browser smoke proves family ADP1 plus sparse ASP1 apply before generation. - Added browser text-sidecar budget contract fields to selector registries so generated registries declare selector, manifest, receipt, and evidence text envelopes, Rust validates them, and browser intake requires exact local matches before accepting entries. - Added a browser runtime WASM manifest so checked and generated roots verify runtime bytes before `WebAssembly.instantiate`, and added a drift smoke proving model routes are not requested after runtime manifest checksum mismatch. - Added browser text-sidecar byte envelopes for selector registries, manifests, receipts, and assembly evidence files, with durable report routing. - Added browser selector byte-budget intake so registry entries must declare bounded `entry.N.model_bytes`, fetched registry models must match declared bytes before WASM transfer, and oversized registry routes fall back before model fetch. - Added a selector registry budget contract so generated registries carry `selector_model_byte_budget=33554432`, Rust validates the line, and the browser requires it before accepting registry entries. - Added registry-controlled browser auto assembly so generated selector entries require adapter auto-apply fields, the browser applies the receipt-preferred sparse ASP1 module after receipt/evidence/manifest verification, and generated-root smokes prove q4_0, q8_0, and f32 assembly before generation. - Added an adapter auto-assembly byte-budget contract so generated adapter-family entries carry `adapter_auto_apply_byte_budget=1048576`, browser manifest checks parse `adapter_artifact_bytes`, and fetched auto-assembled module bytes must match the manifest before WASM transfer. - Added TinyRustLM runtime f32 `ADP1` adapter apply support through Rust model validation, runtime state reset, WASM ABI export, and Node ABI smoke coverage. - Added the TinyRustLM browser Adapter Sidecar route for the checked tiny f32 self-ADP1 package with static harness, headless browser smoke, and workspace test evidence. - Extended runtime `ADP1` adapter apply and checked browser Adapter Sidecar routing to tiny q8_0 and q4_0 self-sidecars, preserving compact quantized storage after apply. - Added generated selector-registry f32 adapter sidecar routing so `browser-multi-parent-bundle` stages a self-ADP1 package and `adapter-sidecar-registry-file` verifies the browser path. - Added generated selector-registry adapter-family routing so the bundle stages self and family ADP1 packages and browser smoke applies the second registry option. - Added adapter-family receipt routing so generated selector registries carry a served receipt path, checksum, family strategy, and adapter count for compatible f32 ADP1 sidecar sets. - Added assembly receipt routing so generated multi-parent bundles carry a browser-verified receipt and fetch/checksum the referenced ledger, review, recipe, operator, candidate, promotion, runtime, eval, admission, and adapter-family evidence files. - Extended selector-registry adapter routing to f32/q8_0/q4_0 entries when apply status matches quantization, with a focused q8_0 registry-adapter browser smoke. - Extended generated browser bundle routing to file-backed f32/q8_0/q4_0 roots, including selector registry, model, manifest, assembly receipt, evidence files, adapter-family receipt, adapter manifests, and family ADP1 apply smoke for q8_0 and q4_0. - Added sparse task-delta receipt metadata for density, nonzero-delta retention, unchanged/pruned counts, and an implicit top-k mask checksum. - Added sparse `ASP1` adapter packages with write/validate commands, manifest density and mask metadata, and runtime f32/q8_0/q4_0 sparse apply. - Added browser-routed sparse `ASP1` adapter-family members for generated bundles, including served manifest verification, ASP1 artifact checksum transfer, refreshed WASM, and headless `adapter-sidecar-registry-file` apply proof. - Added receipt-bound preferred adapter selection so generated adapter-family receipts name the sparse `ASP1` member and the browser defaults to that verified route before Apply. - Added combined multi-quant generated selector roots so one `browser-multi-parent-bundle all` output serves f32, q8_0, and q4_0 multi-parent modules with receipt-preferred sparse `ASP1` apply proof for each entry. - Added browser-frugal selector defaults so combined generated roots start on q4_0 before any model bytes load while still allowing q8_0 and f32 entry switching. - Added parent-pool relatedness metadata: recipes write relatedness metric, scope, pair count, shared-family checksum, and per-parent group fields; sign-merge receipts echo them; multi-parent candidate manifests carry the summary. - Added population-review objective-vector metadata: reviews write quality/frugality/quantization fit weights plus per-entry objective-vector checksums before parent-pool routing. ## 2026-06-28 - Added browser module-plan fetch-count proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_fetch_count_limit=32`, the Module Plan panel renders `Fetch Limit`, the browser computes planned generated-root route count before model fetch, and `module-plan-fetch-count-drift` proves mismatch stops before `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan prompt-limit proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_prompt_byte_limit=4096`, the Module Plan panel renders `Prompt Limit`, source prompt bytes stop before WASM transfer when they exceed the envelope, and `module-plan-prompt-limit-drift` proves prompt-limit mismatch stops before generated `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan output-limit proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_output_byte_limit=65536`, the Module Plan panel renders `Output Limit`, and `module-plan-output-limit-drift` proves output cap mismatch stops at module-plan validation. - Added browser module-plan WASM export-set proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_wasm_export_set=tinyrustlm-generate-v1`, the Module Plan panel renders `WASM ABI`, instantiated runtime exports are checked before generated model bytes, and `module-plan-wasm-export-set-drift` proves export-set mismatch stops before generated `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan WASM transfer proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_wasm_transfer_strategy=copy-then-release-v1`, the Module Plan panel renders `Transfer`, and `module-plan-wasm-transfer-drift` proves transfer-strategy mismatch stops before generated `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan model-release proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_model_release_strategy=free-before-reassembly-v1`, the Module Plan panel renders `Release`, `module-plan-model-release-drift` stops before generated model bytes, and `combined-selector-cycle` proves `free_model` before post-initial q4_0/q8_0/f32 reassembly. - Added browser module-plan runtime-reset proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_runtime_reset_strategy=reset-context-before-assembly-v1`, the Module Plan panel renders `Reset`, `module-plan-runtime-reset-drift` stops before generated model bytes, and `combined-selector-cycle` proves `reset_context` before q4_0/q8_0/f32 adapter validation/application. - Added browser module-plan sampler-cap proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_sampler_candidate_cap=1024`, the Module Plan panel renders `Sampler Cap`, browser Top K clamps to the fixed-buffer envelope, and `module-plan-sampler-cap-drift` proves sampler-cap mismatch stops before generated `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan tokenizer proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_tokenizer_checksum`, the Module Plan panel renders `Tokenizer`, and `module-plan-tokenizer-drift` proves tokenizer mismatch stops before generated `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan context-token proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_context_token_limit=16`, the Module Plan panel renders `Context`, and `module-plan-context-token-drift` proves context mismatch stops before generated `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser selector heritable-artifact metadata so generated selector registries bind served artifact identity into deterministic heritable artifact ids and checksums; Model Provenance now renders Artifact, and `combined-selector-assembly` proves q4_0/q8_0/f32 generated entries show genome/species/novelty/population/mate-selection/phenotype/artifact/fitness fields while assembling locally. - Added browser selector phenotype-evidence metadata so generated selector registries bind runtime/eval/provenance observations into deterministic phenotype-evidence ids and checksums; Model Provenance now renders Phenotype, and `combined-selector-assembly` proves q4_0/q8_0/f32 generated entries show genome/species/novelty/population/mate-selection/phenotype/fitness fields while assembling locally. - Added browser selector mate-selection metadata so generated selector registries bind parent-pool route evidence into deterministic mate-selection ids, status, parent count, and checksums; Model Provenance now renders Mate Selection, and `combined-selector-assembly` proves q4_0/q8_0/f32 generated entries show genome/species/novelty/population/mate-selection/fitness fields while assembling locally. - Added browser selector population metadata so generated selector registries carry deterministic population ids and population-review checksums; Model Provenance now renders a Population row, and `combined-selector-assembly` proves q4_0/q8_0/f32 generated entries show genome/species/novelty/population/fitness fields while assembling locally. - Added browser selector novelty metadata so generated selector registries carry deterministic novelty ids and behavior-sketch checksums; Model Provenance now renders a Novelty row, and `combined-selector-assembly` proves q4_0/q8_0/f32 generated entries show genome/species/novelty/fitness fields while assembling locally. - Added browser selector species-fit metadata so generated selector registries carry deterministic species ids and browser-fit checksums; Model Provenance now renders a Species row, and `combined-selector-assembly` proves q4_0/q8_0/f32 generated entries show genome/species/fitness fields while assembling locally. - Added browser selector genome/fitness metadata so generated selector registries carry deterministic genome ids, genome lineage checksums, and scoped fitness-vector checksums; Model Provenance now renders Genome and Fitness rows, and `combined-selector-assembly` proves q4_0/q8_0/f32 generated entries show the fields while assembling locally. - Processed 4 active Improvement research files into raw evidence under `raw/gguf-mirust/report-intake-2026-06-28/`, added `report-intake-index-2026-06-28.md`, and routed ModelBreeder plus zero-dependency Rust browser-runtime guidance through `modelbreeder-zero-dependency-reference-ideas-2026-06-28.md`. - Added browser-smoke `combined-selector-route-stress-soak` so one generated `browser-multi-parent-bundle all` root runs eight q4_0/q8_0/f32 cycles, proves twenty-four assemblies, and requires every generated self-assembly route once per pass. - Added browser module-plan count drift proof so checksum-consistent receipt `module_count` drift rejects against selector `module_plan_module_count` before generated `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan WASM memory pages so generated selector entries and `.module-plan.receipt` files carry `module_plan_wasm_memory_initial_pages=17`, the Module Plan panel renders `WASM Pages`, and `module-plan-wasm-memory-drift` proves page-count mismatch stops before `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan KV-cache budget proof so Rust runtime diagnostics, selector registries, served `.module-plan.receipt` files, and the Module Plan panel carry exact KV byte/page envelopes; `module-plan-kv-cache-drift` proves page-count mismatch stops before generated `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan adapter-stack budget proof so generated selector entries and `.module-plan.receipt` files carry exact `module_plan_adapter_stack_byte_budget=22144`, the Module Plan panel renders `Stack Budget`, and `module-plan-adapter-stack-budget-drift` proves mismatch stops before generated `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan total limit so generated selector entries and `.module-plan.receipt` files carry a selector-owned total cap, the Module Plan panel renders `Total Limit`, and `module-plan-total-limit-drift` proves cap mismatch stops before `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan total budget so generated selector entries and `.module-plan.receipt` files carry `module_plan_total_byte_budget`, the Module Plan panel renders `Total Budget`, and `module-plan-total-budget-drift` proves total mismatch stops before `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser-smoke `combined-selector-reload-soak` so a generated `browser-multi-parent-bundle all` root proves q4_0 default boot selection and q4_0/q8_0/f32 self-assembly across separate page lifetimes with repeated local route requests. - Added browser source-backed ALR1 contract proof so source-backed `.alr1` manifests must match exact kind/dtype pairs and adapter-family receipt source echoes; `source-backed-alr1-manifest-drift` proves source contract drift stops before ADP1/ASP1/ALR1 stack artifact fetch. - Added browser source-backed ALR1 routing so generated bundles convert reviewed adapter source templates into served `.alr1` stack members, browser `.alr1` manifest checks accept the source-backed kind/dtype, and `combined-selector-assembly` proves q4_0/q8_0/f32 apply ADP1 plus ASP1 plus source-backed ALR1 before generation. - Added trained adapter source ALR1 conversion so `convert-adapter-source` packs reviewed low-rank f32 factor bundles into runtime `ALR1` packages and `validate-converted-adapter-source` recomputes the artifact and manifest from source plus base `.slm`. - Added trained low-rank adapter source intake so `adapter-source-template` writes `adapter-source.manifest` plus raw f32 factor files and `validate-adapter-source` recomputes target tensor, factor rank, checksum, finite-factor, parameter-count, and delta-L1 fields before future ALR1 packaging. - Added runtime assembly diagnostics so Rust reports `adapter_apply_count`, `last_adapter_checksum`, and `assembly_state_checksum`; WASM ABI smoke, checked manual sidecar smoke, and generated q4_0/q8_0/f32 combined selector smokes now assert those fields. - Added browser module-plan origin policy so generated selector entries and `.module-plan.receipt` files carry `module_plan_origin_policy=same-origin-loopback-local-v1`, the Module Plan panel renders `Origin`, and `module-plan-origin-policy-drift` proves origin-policy mismatch stops before `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan fetch policy so generated selector entries and `.module-plan.receipt` files carry `module_plan_fetch_policy=local-no-store-v1`, the Module Plan panel renders `Fetch`, and `module-plan-fetch-policy-drift` proves fetch-policy mismatch stops before `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan execution profile so generated selector entries and `.module-plan.receipt` files carry `module_plan_execution_profile=single-threaded-wasm-local-v1`, the Module Plan panel renders `Execution`, and `module-plan-execution-profile-drift` proves execution-profile mismatch stops before `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan runtime scratch budget so generated selector entries and `.module-plan.receipt` files carry `module_plan_runtime_scratch_byte_budget=65536`, the Module Plan panel renders `Scratch Budget`, and `module-plan-runtime-scratch-drift` proves scratch-budget mismatch stops before `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser module-plan profile contract so generated selector entries and `.module-plan.receipt` files carry `browser-constrained-v1`, Rust and browser validation require it before generated model fetch, and `module-plan-profile-drift` proves profile mismatch stops before `.slm`, adapter-family, adapter-manifest, or stack artifact routes. - Added browser-smoke `combined-selector-route-soak` so one generated `browser-multi-parent-bundle all` root runs three q4_0/q8_0/f32 cycles and proves every module-plan, model, manifest, assembly, evidence, adapter-family, adapter-manifest, and ADP1/ASP1/ALR1 stack route is requested once per pass. - Added browser-smoke `combined-selector-route-extended-soak` so one generated `browser-multi-parent-bundle all` root runs five q4_0/q8_0/f32 cycles, proves fifteen assemblies, keeps path-flexible total-budget assertions, and requires every generated self-assembly route once per pass. - Added browser-smoke `combined-selector-cycle` so one generated `browser-multi-parent-bundle all` root cycles q4_0, q8_0, and f32 twice in one page while post-initial passes release the prior WASM model before fresh Rust stack validation, stack apply, stack completion, reset diagnostics, and one-token generation. - Added browser adapter stack Rust validation so generated auto assembly fetches/checks the ADP1/ASP1/ALR1 stack, calls `validate_adapter_delta` for every fetched member, then applies the stack only after semantic preflight passes. - Added browser-smoke `adapter-stack-rust-validate-drift` so checksum-consistent family ADP1 identity drift passes browser byte gates, reaches Rust `validate_adapter_delta`, returns `shape mismatch`, and stops before any `apply_adapter_delta`. - Added low-rank `ALR1` adapter packages with write/validate commands, deterministic factor manifests, and runtime f32/q8_0/q4_0 low-rank apply. - Added browser Module Plan Trace so generated roots render a browser-owned checkpoint chain from plan verification through model acceptance, manifest, assembly evidence, adapter-family verification, adapter-stack apply, and ready state. - Added browser-smoke `combined-selector-assembly` so one generated `browser-multi-parent-bundle all` root starts on q4_0, switches through q4_0, q8_0, and f32 entries, verifies each module plan before model bytes, auto-applies each ADP1 plus ASP1 stack before generation, and keeps requests local. - Added browser-routed low-rank `ALR1` adapter-family members so generated f32/q8_0/q4_0 bundles stage `{id}-low-rank.alr1`, module plans declare a third stack member, and browser smokes prove ADP1 plus ASP1 plus ALR1 auto assembly before generation. - Added browser eval-case evidence checksums so passed eval sidecars now flow through admissions, promotion ledgers, selector registries, generated assembly receipts, and Model Provenance; `combined-selector-assembly` proves q4_0/q8_0/f32 entries display the same eval digest. - Added browser-smoke `assembly-eval-case-drift` so a checksum-consistent generated assembly receipt with a mismatched eval digest stops before evidence files, adapter-family receipts, adapter manifests, or adapter stack routes. - Added browser-smoke `assembly-evidence-file-drift` so a generated root with valid selector, module-plan, model, manifest, and assembly receipt bytes rejects one drifted fetched evidence file before later evidence, adapter-family, adapter manifest, or stack routes. - Added browser-smoke `adapter-family-receipt-drift` so a generated root with valid assembly evidence rejects drifted adapter-family receipt bytes before adapter manifests or ADP1/ASP1/ALR1 stack artifacts. - Added browser-smoke `adapter-manifest-drift` so a generated root with valid assembly evidence and adapter-family receipt rejects a drifted family ADP1 manifest before sparse/low-rank manifests or ADP1/ASP1/ALR1 stack artifacts. - Added browser-smoke `adapter-artifact-drift` so a generated root with valid adapter manifests rejects drifted family ADP1 artifact bytes before sparse/low-rank artifacts or any `apply_adapter_delta` call. - Added browser-smoke `adapter-stack-prefetch-drift` so generated auto assembly verifies the fetched family ADP1 and sparse ASP1 stack bytes before any Rust adapter apply, then stops before low-rank ALR1 on sparse artifact drift. ## 2026-06-29 - Added candidate operator receipt binding so `candidate-manifest` and `validate-candidate` can optionally bind a supplied operator receipt by path, checksum, operator id/kind, candidate bytes, and candidate checksum; focused tests, CLI proof, full slm_pack tests, and workspace tests passed. - Added browser module-plan route-set version proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_route_set_version=1`, the Module Plan panel renders `Route Version`, and `module-plan-route-set-version-drift` stops before generated model bytes. - Added browser module-plan adapter-validation proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1`, the Module Plan panel renders `Validate`, `module-plan-adapter-validation-drift` stops before generated model bytes, and `combined-selector-assembly` proves `validate_adapter_delta` before q4_0/q8_0/f32 adapter apply. - Added browser module-plan adapter apply-count proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_adapter_apply_count=3`, the Module Plan panel renders `Apply Count`, app.js checks runtime `adapter_apply_count`, and `module-plan-adapter-apply-count-drift` stops before generated model bytes. - Added browser module-plan planned-fetch-count proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_planned_fetch_count=21`, the Module Plan panel renders `Plan Fetches`, and `module-plan-planned-fetch-count-drift` stops before generated model bytes. - Added browser-owned module-plan actual fetch-count proof so the app counts accepted generated self-assembly route fetches, the Module Plan panel renders `Actual Fetches`, and generated Ready requires the observed count to match the planned count. - Added browser-observed module-plan route-set proof so the app records accepted generated route `{kind,path}` entries, the Module Plan panel renders `Actual Route Set`, and generated Ready requires the observed checksum to match the declared Route Set. - Added browser module-plan route-set proof so generated selector entries and `.module-plan.receipt` files carry `module_plan_route_set_checksum`, the Module Plan panel renders `Route Set`, and `module-plan-route-set-drift` stops before generated model bytes. ================================================================================ END FILE: wiki/gguf-mirust/log.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/adapter-family-receipt-memory-2026-06-27.md BYTES: 5961 SHA256: B1CA668DF85A1AA491AA9C09722BE673EE8CDA1ACC3D34094261DF3E9D004DAE ================================================================================ --- title: Adapter Family Receipt Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/adapter-family-receipt-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T16:25:00Z --- # Adapter Family Receipt Memory ## Summary TinyRustLM now gives compatible browser-local adapter families a recomputable receipt and served manifest checks that the browser completes before family options are enabled. `browser-multi-parent-bundle` writes runnable f32/q8_0/q4_0 TinyRustLM roots with app shell, WASM runtime, matching `.adapter-family.receipt` files, generated self ADP1, family ADP1, and sparse ASP1 adapter manifests, and selector metadata; the packer validates that all sidecars share the same adapter identity, including base quantization, and records a receipt path plus checksum in `selector.registry`. `app.js` fetches the served receipt, recomputes its text checksum, fetches each served adapter manifest, matches each member route, manifest route, route-derived format, label, apply status, artifact checksum, manifest checksum, manifest byte count, and shared identity field before showing the family sidecars, then recomputes the selected ADP1/ASP1 artifact checksum before WASM transfer. ## Implementation Memory - `tinyrustlm/tools/slm_pack/src/adapter_family.rs` builds and validates format-neutral `browser-local-adapter-family` receipts from registry adapter routes plus adapter manifest files, while accepting the earlier ADP1-specific receipt kind for existing fixtures. - The receipt requires two to sixteen members, local `../models/*.adp1` or `../models/*.asp1` routes, matching manifest checksums, f32/q8_0/q4_0 runtime apply status, and shared tensor count, parameter count, model shape, output contract, tokenizer checksum, tensor layout checksum, and adapter base contract. - `tinyrustlm/tools/slm_pack/src/selector.rs` now accepts optional `entry.N.adapter_family_*` fields for f32/q8_0/q4_0 selector entries and validates receipt route, receipt checksum shape, family status, strategy, and adapter count against indexed ADP1/ASP1 routes. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes a runnable browser root by copying the app shell and WASM runtime, writes the served `.adapter-family.receipt`, validates it, then emits one selector-family route alongside generated self ADP1, family ADP1, and sparse ASP1 sidecars. - `tinyrustlm/app/app.js` route-checks the receipt metadata from `selector.registry`, fetches and checksum-verifies the served receipt, fetches and verifies each served adapter manifest by route extension, matches family members against the registry routes, recomputes the selected artifact checksum before transfer, and still leaves byte parsing and mutation authority inside Rust. - `tinyrustlm/tools/browser-smoke.js` requires the generated browser smoke network trace to include the matching `.adapter-family.receipt`, both generated `.adp1.manifest` routes, and the generated `.asp1.manifest` route before the registry-supplied family sidecar can pass, and the applied sidecar must match the artifact checksum embedded in the verified metadata. ## Validation Memory - `cargo fmt --all -- --check` passed. - `node --check tinyrustlm/app/app.js` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `cargo test -p tinyrustlm-slm-pack adapter_family` passed with 5 filtered tests. - `cargo test -p tinyrustlm-slm-pack selector` passed with 19 tests. - `cargo test -p tinyrustlm-slm-pack browser_bundle` passed. - `cargo test -p tinyrustlm-slm-pack` passed with 141 tests. - `cargo test --workspace` passed with 219 tests. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18640/app/ 9241 tinyf32 adapter-sidecar` passed, applying the checked tiny f32 sidecar after artifact checksum verification. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8091/app/ 9240 tinyq8 adapter-sidecar` passed after static q8_0 sidecar routing was added. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8091/app/ 9241 tinyq4 adapter-sidecar` passed after static q4_0 sidecar routing was added. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18640/app/ 9242 tinyf32 adapter-sidecar-checksum-mismatch` passed, proving a corrupted sidecar is rejected before `apply_adapter_delta` and prior generation diagnostics remain intact. - A self-contained generated-root `adapter-sidecar-registry-file` browser smoke passed against `http://127.0.0.1:18642/app/`, loading the real generated selector registry from a packer-written app root, fetching `multi-parent-sign-merge-f32.adapter-family.receipt`, fetching both generated `.adp1.manifest` files, and applying `multi-parent-sign-merge-f32-family.adp1`. - A focused `adapter-sidecar-registry-q8` browser smoke passed against `http://127.0.0.1:8092/app/`, proving the browser accepts registry metadata for a q8_0 ADP1 route whose apply status matches the selected entry quantization. - Generated q8_0 and q4_0 roots passed `adapter-sidecar-registry-file`, fetching the matching adapter-family receipt, both adapter manifests, and applying the matching family ADP1 route while preserving the selected quantization mode. - A later generated-root `adapter-sidecar-registry-file` browser smoke passed after the bundle added sparse ASP1 family members, fetching all three adapter manifests and applying `multi-parent-sign-merge-f32-sparse.asp1`. ## Routing Notes Use this report before changing `adapter_family.rs`, selector registry `entry.N.adapter_family_*` fields, generated browser bundle ADP1/ASP1 staging, browser registry receipt parsing, browser adapter manifest parsing, or browser adapter artifact checksum verification. The receipt and served manifests are selector assembly proof for compatible f32/q8_0/q4_0 sidecar choices, the selected artifact checksum must match before WASM transfer, and Rust runtime validation still owns package identity and tensor mutation. ================================================================================ END FILE: wiki/gguf-mirust/reports/adapter-family-receipt-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/admission-operator-receipt-binding-memory-2026-06-29.md BYTES: 4814 SHA256: 59CD900D6868CAEE98D79DEF2241665164C4F00AE933D6F20DD096B9750AEA8D ================================================================================ --- title: Admission Operator Receipt Binding Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/admission-operator-receipt-binding-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T09:05:00Z --- # Admission Operator Receipt Binding Memory TinyRustLM two-parent selector admission records can now carry the candidate's producer receipt binding through the final selector-admission gate. ## What Changed - `tinyrustlm/tools/slm_pack/src/admission.rs` keeps existing unbound admission behavior while adding receipt-aware record and validation paths. - `admission-record [selector-id] [input.operator]` reads the optional operator receipt and requires it when candidate/promotion evidence is receipt-bound. - `validate-admission [input.operator]` recomputes candidate, promotion, runtime, eval, and admission evidence before accepting the selector-facing record. - Receipt-bound admissions copy the promotion's `operator_receipt_*` fields, and admission summary validation now recognizes those fields for selector-facing intake. ## Admission Fields - `operator_receipt_status=receipt-bound` - `operator_receipt_path=` - `operator_receipt_checksum=` - `operator_receipt_operator_id=` - `operator_receipt_operator_kind=` - `operator_receipt_candidate_slm_checksum=` - `operator_receipt_candidate_artifact_bytes=` ## Validation Boundaries - Admission validation recomputes the receipt-bound candidate manifest and promotion before runtime-smoke, eval, and selector-admission fields are accepted. - Bound admission fields must exactly match the validated promotion's receipt fields. - Bound evidence without the receipt input does not produce or validate an admission. - Admission summary validation checks the receipt status, receipt checksum, candidate checksum, byte count, operator id, and operator kind when receipt fields are present. ## Verification - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml admission -- --nocapture` passed with 21 focused admission and neighboring selector/ledger tests. - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml` passed with 265 tests. - `C:\Users\AI\.cargo\bin\cargo.exe build --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml` rebuilt the CLI. - CLI smoke wrote and validated compatibility, lineage, mutation candidate, operator receipt, receipt-bound candidate manifest, receipt-bound promotion, provenance manifest, runtime-smoke sidecar, passing eval sidecar, receipt-bound admission record, and receipt-bound admission validation under `C:\Users\AI\AppData\Local\Temp\tinyrustlm-admission-cli-ce1a4e394bb948f5b0be53862c1d9dfc\`. - CLI smoke inspected `candidate.admission` and found `operator_receipt_status=receipt-bound`, `operator_receipt_checksum=0x4c8ea6e30f7cf736`, and `operator_receipt_operator_kind=deterministic-bounded-parameter-mutation`. - `C:\Users\AI\.cargo\bin\cargo.exe test --workspace` passed with browser harness, local server, runtime, slm_pack, and doc-test checks. - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` passed. No coverage tool is active in this no-third-party workspace; evidence for the 75% target is focused happy-path coverage, path-parameter coverage, missing receipt rejection, admission receipt drift rejection, summary validation coverage, full packer suite, workspace suite, build, formatting, and CLI write/validate smoke. ## Test Coverage Notes - `operator_receipt: Option<&Path>` is covered by a path-level admission record write and validation test. - `operator_receipt` text binding is covered by receipt-bound record and validation text tests. - `operator_receipt_checksum` is covered by admission checksum drift rejection. - Missing receipt input for bound evidence is covered by explicit rejection. - Admission summary validation covers receipt-bound fields so selector-facing summary parsing has a local field-shape gate. - Existing unbound admission tests continue to cover runtime-smoke drift, eval drift, selector id validation, overclaim rejection, and case-total validation. ## Routing Open this report before changing `admission.rs`, `admission-record`, `validate-admission`, two-parent receipt-bound selector admission fields, or selector intake assumptions about admission provenance. ================================================================================ END FILE: wiki/gguf-mirust/reports/admission-operator-receipt-binding-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/assembly-receipt-memory-2026-06-27.md BYTES: 4640 SHA256: AB1F2A4E32F0DECE417FDD1F6EACF30F1DC92666C67AAB3DB7477626DE957871 ================================================================================ --- title: Assembly Receipt Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/assembly-receipt-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T16:25:00Z --- # Assembly Receipt Memory ## Summary TinyRustLM now gives generated browser-served multi-parent bundles a compact assembly receipt that the browser can verify and display. `browser-multi-parent-bundle` writes the matching `multi-parent-sign-merge-f32`, `multi-parent-sign-merge-q8`, or `multi-parent-sign-merge-q4` `.assembly.receipt` next to the generated `.slm`, records the receipt path, checksum, label, status, and kind in `selector.registry`, and validates that registry before the bundle is complete. The receipt binds the generated model to its model manifest, population ledger, population review, parent-pool recipe, sign-merge operator receipt, multi-parent candidate manifest, promotion template, runtime-smoke sidecar, eval manifest, selector admission record, and adapter-family receipt by local routes and text checksums. The browser fetches the receipt only after the selected model is accepted and its local `.slm.manifest` is loaded, recomputes the receipt checksum, matches the selected model path and manifest path, matches the model checksum, fetches the nine local evidence files named by the receipt, recomputes each evidence text checksum, and renders the assembly kind, parent count, operator checksum, ledger checksum, and next gate. ## Implementation Notes - `tinyrustlm/tools/slm_pack/src/selector.rs` now supports optional `entry.N.assembly_receipt_path`, `entry.N.assembly_receipt_checksum`, `entry.N.assembly_label`, `entry.N.assembly_status`, and `entry.N.assembly_kind` fields. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes the assembly receipt into generated f32/q8_0/q4_0 bundle roots and adds one selector assembly route for the selected `multi-parent-sign-merge-*` model. - `tinyrustlm/app/index.html` adds an Assembly Evidence panel. - `tinyrustlm/app/app.js` route-checks assembly receipt metadata, fetches the served receipt, recomputes its text checksum, validates the selected model and manifest linkage, fetches each local evidence file named by the receipt, verifies each evidence checksum, and renders receipt fields without parsing model or adapter bytes. - `tinyrustlm/tools/browser-smoke.js` requires the generated-root `adapter-sidecar-registry-file` trace to include the matching `.assembly.receipt` plus the nine matching `/evidence/multi-parent-sign-merge-*/*` evidence routes, and checks rendered receipt fields before the sidecar smoke can pass. - `tinyrustlm/tools/browser_harness/src/main.rs` includes the Assembly Evidence panel in the static browser contract. ## Verification - `node --check tinyrustlm/app/app.js` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `cargo fmt --all -- --check` passed. - `cargo test -p tinyrustlm-slm-pack selector` passed with 20 tests. - `cargo test -p tinyrustlm-slm-pack browser_bundle` passed. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` passed with 8 checks. - `cargo test -p tinyrustlm-slm-pack` passed with 142 tests. - `cargo test --workspace` passed with 220 tests. - A generated-root `adapter-sidecar-registry-file` browser smoke passed against `http://127.0.0.1:18644/app/`, loading the real generated selector registry, fetching the assembly receipt, fetching all nine referenced evidence files, rendering parent count 3 plus operator and ledger checksums, fetching the adapter-family receipt and both adapter manifests, and applying `multi-parent-sign-merge-f32-family.adp1`. - Generated q8_0 and q4_0 roots passed `adapter-sidecar-registry-file`, fetching the matching assembly receipt, all nine matching evidence files, adapter-family receipt, both adapter manifests, and family ADP1 route while preserving the selected quantization mode. - A later f32 generated root passed `adapter-sidecar-registry-file` with the sparse ASP1 family member, fetching all three adapter manifests and applying `multi-parent-sign-merge-f32-sparse.asp1`. ## Routing Use this report before changing selector registry assembly fields, generated browser bundle evidence staging, browser assembly receipt parsing, Assembly Evidence UI, or generated-root adapter-sidecar smoke expectations. The assembly receipt is a browser-visible proof route for the multi-parent evidence chain; Rust tooling still owns artifact generation and validation, while the browser verifies served receipt integrity, fetches the referenced evidence files, verifies their checksums, and displays the route result. ================================================================================ END FILE: wiki/gguf-mirust/reports/assembly-receipt-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/brand-product-positioning-memory-2026-06-25.md BYTES: 2709 SHA256: 60D0BE8BD0D98231CAAE71AFBD8978EAE1F776F995F4A5E43E2BC337EEE7A94B ================================================================================ --- title: Brand Product Positioning Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/brand-product-positioning-memory-2026-06-25/ status: planned_pending_publication reviewed_utc: 2026-06-25T00:00:00Z --- # Brand Product Positioning Memory ## Source Reports - `Branding MiRust.com.md` - `Machine Inteligence framwork for rust.md` These two files have identical SHA256 hashes and are treated as duplicate content with different filenames. ## Durable Reading The brand reports frame MiRust as a Rust-centered AI/runtime identity. For GGUF.MiRust.com, the strongest product story is not "yet another AI wrapper." It is a transparent local runtime that users and developers can inspect: a small Rust/WASM model runner, static browser UI, custom `.slm` files, explicit diagnostics, and no remote inference. The current product name TinyRustLM should carry that story: - Tiny: local, small, inspectable, resource-aware. - Rust: memory safety, typed boundaries, no hidden framework stack. - LM: language model runtime, not a general agent platform yet. ## Positioning Notes - Lead with local proof, not grand intelligence claims. - Use "browser-local" and "custom Rust/WASM runtime" before "AI assistant." - Be clear that current model artifacts are deterministic smoke models, not trained-quality assistants. - Keep GGUF.MiRust.com aligned with AIWikis.org memory routing and UAIX handoff discipline. - Treat the Visual Studio solution as developer accessibility, not a separate product. ## Copy Direction Durable copy should emphasize: - "All inference runs locally in this browser." - "Prompts are not sent to a server." - "The runtime, model format, tokenizer, quantized matvec, and diagnostics are implemented in custom Rust." - "The current milestone proves the execution path; quality-oriented trained model conversion remains future work." Avoid: - Claims that imply GGUF compatibility before it exists. - Cloud AI positioning. - Vague "autonomous intelligence" language without runtime evidence. - Naming that conflicts with existing MiRust or Rust project identities. ## Thought Questions - How can the product make smallness feel like trust rather than limitation? - What should the UI say when a deterministic smoke model responds correctly but not intelligently? - Is the brand promise "runs anywhere" or "can be understood locally"? The second is more defensible today. - How should the site distinguish TinyRustLM from future GGUF or Mini Browser work? ## Current Boundary Use this record for naming, copy, positioning, and public explanation. Do not let brand ambition outrun the source-verified support boundary in `workspace.uai` and `.uai/test-plan.uai`. ================================================================================ END FILE: wiki/gguf-mirust/reports/brand-product-positioning-memory-2026-06-25.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28.md BYTES: 3416 SHA256: E6CF6A987B39832F924E9EFE764AB57B770E838A154D0F9B132E6395B4F8E482 ================================================================================ --- title: Browser Adapter Artifact Drift Memory 2026-06-28 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T07:20:00Z --- # Browser Adapter Artifact Drift Memory TinyRustLM now has a browser smoke proof for generated adapter stack artifact drift after selector, module plan, model bytes, model manifest, assembly receipt, assembly evidence files, adapter-family receipt, and all adapter manifests have passed. The smoke flips one byte in the first generated family ADP1 stack artifact while serving the same route and byte count. Browser state records `adapter artifact checksum mismatch`, keeps the q4_0 model loaded, leaves generation and adapter controls available, keeps Step Token disabled before generation context, and stops before sparse ASP1, low-rank ALR1, or any `apply_adapter_delta` call. ## Implementation Shape - `tinyrustlm/tools/browser-smoke.js` adds `adapter-artifact-drift` as a generated q4 default smoke mode. - The Fetch interceptor targets the exact stack artifact pathname, not manifest paths, then fulfills the request with a same-length binary body whose final byte is changed. - The assertion requires Module Plan Trace to reach `adapter family verified` and not reach `adapter stack applied` or `ready`. - The assertion requires selector, module-plan, model, model manifest, assembly receipt, all assembly evidence, adapter-family receipt, and all adapter manifest routes before the drifted artifact request. - The assertion requires only the first stack artifact route after manifests, with no later sparse or low-rank artifact route and no non-local request. ## Verification - `node --check tinyrustlm/tools/browser-smoke.js` - `node --check tinyrustlm/app/app.js` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18749/app/ 19606 multi-parent-sign-merge-q4 adapter-artifact-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18749/app/ 19607 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` - `cargo test -p tinyrustlm-browser-harness` - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` The paired normal smoke proved the same generated q4 root still reaches `Ready`, auto-applies ADP1 plus ASP1 plus ALR1 before generation, renders the full Module Plan Trace through `ready`, and generates the deterministic local `e` response. ## Routing Load this report before changing generated adapter stack artifact fetches, adapter artifact checksum matching, `applyAdapterByIndex`, `verifyAdapterArtifactBytes`, adapter auto-assembly ordering, or browser smoke assertions for `adapter-artifact-drift`. Use it with: - `browser-adapter-manifest-drift-memory-2026-06-28.md` - `browser-adapter-family-receipt-drift-memory-2026-06-28.md` - `browser-assembly-evidence-file-drift-memory-2026-06-28.md` - `browser-assembly-trace-memory-2026-06-28.md` - `adapter-family-receipt-memory-2026-06-27.md` - `browser-adapter-stack-memory-2026-06-27.md` ## Next Route The verified chain now covers generated-root drift gates from module plan, assembly eval digest, fetched evidence files, adapter-family receipt, adapter manifest, and adapter artifact bytes. The next useful assembly bead is trained adapter or real trained-weight routing that still feeds the same receipts, manifests, eval sidecars, and browser proof graph. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-adapter-family-receipt-drift-memory-2026-06-28.md BYTES: 3260 SHA256: D330405FC5F2A27B4E0F817AC679FA9CBC53F6A76E242582700D5792D98F48A5 ================================================================================ --- title: Browser Adapter Family Receipt Drift Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-adapter-family-receipt-drift-memory-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T06:35:00Z --- # Browser Adapter Family Receipt Drift Memory ## Summary TinyRustLM now has a browser smoke proof for generated adapter-family receipt drift after assembly evidence has already passed. The generated selector registry, module-plan receipt, model bytes, model manifest, assembly receipt, and every assembly evidence file remain valid; the smoke mutates only the served adapter-family receipt text while preserving its byte count. The browser keeps the generated q4_0 model loaded, records `adapter family receipt checksum mismatch`, leaves generation available, disables adapter controls, and stops before adapter manifests or ADP1/ASP1/ALR1 stack artifacts are requested. ## Implementation - `tinyrustlm/tools/browser-smoke.js` adds `adapter-family-receipt-drift`. - The Fetch interceptor mutates the served `/models/multi-parent-sign-merge-q4.adapter-family.receipt` candidate id in flight without changing the receipt byte count. - The assertion requires selector, module-plan, model, manifest, assembly receipt, and all assembly evidence-file routes to be requested first. - The assertion requires the adapter-family receipt route to be requested and rejects adapter manifest, family ADP1, sparse ASP1, and low-rank ALR1 artifact requests afterward. - The smoke distinguishes this boundary from assembly rejection: diagnostics keep `model_loaded=true`, Module Plan Trace reaches `assembly evidence verified`, and it does not reach `adapter family verified` or `ready`. ## Verification - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `node --check tinyrustlm/app/app.js` passed. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/adapter-family-receipt-drift/tinyrustlm all` regenerated a validated all-root with 3 admissions, 3 module-plan routes, 3 assembly routes, 3 adapter-family routes, and 12 adapter routes. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18747/app/ 19599 multi-parent-sign-merge-q4 adapter-family-receipt-drift` passed with `runtimeStatus=Ready`, `modelState=loaded`, `assemblyState=loaded`, `adapterState=adapter family receipt checksum mismatch`, `model_loaded=true`, Module Plan Trace through `assembly evidence verified`, and network requests ending at the adapter-family receipt route. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18747/app/ 19600 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` passed on the paired normal generated root, proving the valid path still reaches `ready` and applies family ADP1 plus sparse ASP1 plus low-rank ALR1 before generation. ## Routing Notes Use this page before changing `loadAdapterFamilyReceipt`, adapter-family receipt checksum handling, adapter-family receipt route assertions, generated adapter-family manifests, or browser auto-assembly sequencing after assembly evidence has passed. Pair it with Browser Assembly Evidence File Drift Memory for the previous evidence-file gate and Browser Adapter Stack Memory for the valid ADP1/ASP1/ALR1 stack path. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-adapter-family-receipt-drift-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-adapter-manifest-drift-memory-2026-06-28.md BYTES: 3133 SHA256: 996199A693C531DE1AEE849A69DFAFB258DE1EB83D670294D01D3F288B93F2DB ================================================================================ --- title: Browser Adapter Manifest Drift Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-adapter-manifest-drift-memory-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T06:55:00Z --- # Browser Adapter Manifest Drift Memory ## Summary TinyRustLM now has a browser smoke proof for generated adapter manifest drift after the selector registry, module-plan receipt, model bytes, model manifest, assembly receipt, all assembly evidence files, adapter-family receipt, and the first self-adapter manifest have already passed. The smoke mutates only the served family ADP1 manifest text at the same byte count. The browser keeps the generated q4_0 model loaded, records `adapter 1 manifest checksum mismatch`, leaves generation available, disables adapter controls, and stops before sparse or low-rank adapter manifests or ADP1/ASP1/ALR1 stack artifacts are requested. ## Implementation - `tinyrustlm/tools/browser-smoke.js` adds `adapter-manifest-drift`. - The Fetch interceptor mutates `/models/multi-parent-sign-merge-q4-family.adp1.manifest` in flight by changing `adapter_status=artifact-written` to an equal-length drifted status string. - The assertion requires selector, module-plan, model, manifest, assembly receipt, all assembly evidence files, adapter-family receipt, self adapter manifest, and the drifted family adapter manifest routes to be requested first. - The assertion rejects later sparse and low-rank manifest requests plus all ADP1, ASP1, and ALR1 stack artifact requests afterward. - The smoke distinguishes this boundary from receipt drift: diagnostics keep `model_loaded=true`, Module Plan Trace reaches `assembly evidence verified`, and it does not reach `adapter family verified` or `ready`. ## Verification - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `node --check tinyrustlm/app/app.js` passed. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18748/app/ 19601 multi-parent-sign-merge-q4 adapter-manifest-drift` passed with `runtimeStatus=Ready`, `modelState=loaded`, `assemblyState=loaded`, `adapterState=adapter 1 manifest checksum mismatch`, `model_loaded=true`, Module Plan Trace through `assembly evidence verified`, and network requests ending at the family ADP1 manifest. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18748/app/ 19602 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` passed on the same generated root, proving the valid path still reaches `ready` and applies family ADP1 plus sparse ASP1 plus low-rank ALR1 before generation. - `cargo test -p tinyrustlm-browser-harness` passed with 6 tests. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` passed with 9 static checks. ## Routing Notes Use this page before changing `validateAdapterManifest`, adapter manifest checksum handling, generated adapter-family manifest routes, or browser auto-assembly sequencing after the adapter-family receipt has passed. Pair it with Browser Adapter Family Receipt Drift Memory for the previous receipt gate and Browser Adapter Stack Memory for the valid ADP1/ASP1/ALR1 stack path. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-adapter-manifest-drift-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-adapter-sidecar-memory-2026-06-27.md BYTES: 4382 SHA256: 0FC03072EA8A509832838A3D71BAAA087A3BCD1F5960E69C5624A2E80E07041F ================================================================================ --- title: Browser Adapter Sidecar Memory 2026-06-27 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-adapter-sidecar-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T13:52:09Z --- # Browser Adapter Sidecar Memory This durable note records the TinyRustLM browser UI path for applying local f32, q8_0, and q4_0 `ADP1` sidecars. ## Boundary The browser app now exposes an Adapter Sidecar panel for the checked tiny f32, q8_0, and q4_0 fixtures. The routes are `../models/tiny-test-model-self.adp1`, `../models/tiny-test-model-q8-self.adp1`, and `../models/tiny-test-model-q4-self.adp1`, each generated from its matching tiny `.slm` against itself as a zero-delta package. JavaScript selects the route, fetches local bytes, copies them into WASM memory, calls `apply_adapter_delta`, and then renders Rust's result text and diagnostics. JavaScript does not parse adapter bytes. Rust remains the authority for `ADP1` package identity, checksums, tensor directory, tokenizer checksum, tensor layout checksum, finite delta values, fused values, compact q8_0/q4_0 re-quantization, and generation-state reset. ## Implementation Shape - `tinyrustlm/app/index.html` adds the Adapter Sidecar panel, selector, apply button, and status field. - `tinyrustlm/app/app.js` declares the tiny f32, q8_0, and q4_0 self-sidecar routes, filters adapter routes to local `../models/*.adp1`, fetches bytes, calls `apply_adapter_delta`, resets host-side generation context, and keeps adapter controls tied to a loaded model. - `tinyrustlm/tools/browser_harness/src/main.rs` checks the static IDs, visible panel text, JS WASM call marker, Rust export definition, and checked sidecar route. - `tinyrustlm/tools/browser-smoke.js` adds `adapter-sidecar` mode: select tiny f32, q8_0, or q4_0, generate one token, apply the matching sidecar, then verify `adapter applied`, matching quantization diagnostics, cleared token/KV state, and local-only requests. - `tools/vs/Test-TinyRustLM.ps1` wires the sidecar smoke into `-BrowserSmoke`. - `tinyrustlm/models/tiny-test-model-self.adp1`, `tiny-test-model-q8-self.adp1`, `tiny-test-model-q4-self.adp1`, and their manifests are the checked local packages and proof sidecars for this browser route. ## Artifact Hashes - `tinyrustlm/models/tiny-test-model-self.adp1`: `DBEEB5875D00958179600C1CB353CA1FAB7604F3D755A5DA905BFFF7F45B8BA8` - `tinyrustlm/models/tiny-test-model-self.adp1.manifest`: `78D72C47C6423F4E16E194DBB7F56F055071962FF611CC8C12E971C4C0FB75D0` - `tinyrustlm/models/tiny-test-model-q8-self.adp1`: `7B4E998EFEAC9B9D7BB6F909FC99BC17CA81A905D5C19FA0970A8229BF67E5E8` - `tinyrustlm/models/tiny-test-model-q8-self.adp1.manifest`: `5680FD9A8676B818BCE3B90175AE75B574ACFE380B0B374A27ED46EA2C714AEB` - `tinyrustlm/models/tiny-test-model-q4-self.adp1`: `9BD044B950E0CED7B8C9785D0ECEB0E175B91861D1C845267BC0D690A0CC9C56` - `tinyrustlm/models/tiny-test-model-q4-self.adp1.manifest`: `2060583F1243B373C8E3AEFECA5EFD763F09979E679249B9C087C1EC3DFF1880` - `tinyrustlm/runtime/tinyrustlm.wasm`: `2948DAF23FECD6560A732A4F08A92A3885D89BD52FF1F3A3E6C54A3E699CAA12` ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - PowerShell parse check for `tools/vs/Test-TinyRustLM.ps1` - `cargo fmt --all` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-slm-pack adapter` - `cargo test -p tinyrustlm-runtime adapter` - `cargo test -p tinyrustlm-browser-harness` - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` - `node tinyrustlm/tools/wasm-abi-smoke.js` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18510/app/ 9250 tinyf32 adapter-sidecar` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8091/app/ 9240 tinyq8 adapter-sidecar` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8091/app/ 9241 tinyq4 adapter-sidecar` - `cargo test --workspace` ## Next Routes - Keep `adapter-sidecar` browser smoke in the default browser helper when adapter UI or runtime state changes. - Keep registry-provided adapter sidecars tied to explicit local adapter routes, matching manifest fields, and smoke evidence. - Use `browser-sparse-adapter-route-memory-2026-06-27.md` for the generated browser ASP1 route proof, then extend the same manifest and receipt shape toward LoRA-style modules and longer selector-route exercises. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-adapter-sidecar-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-adapter-stack-memory-2026-06-27.md BYTES: 2484 SHA256: 98D332795CB298FEA383E772BF7DD87CFBE12DAFF80062D158EC00344503A8FE ================================================================================ --- title: Browser Adapter Stack Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-adapter-stack-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T18:30:04Z --- # Browser Adapter Stack Memory ## Routing Summary Use this report when work touches generated adapter-family receipts, selector registry adapter auto-apply fields, browser self-assembly, or `adapter-sidecar-registry-file` smoke coverage. It records the first browser-verified ordered adapter stack for TinyRustLM generated bundles. ## Implementation - `tinyrustlm/tools/slm_pack/src/adapter_family.rs` now writes receipt fields for `adapter_family_auto_apply_stack_status`, `adapter_family_auto_apply_stack_strategy`, `adapter_family_auto_apply_stack_count`, and ordered stack members with adapter index, path, and manifest path. - `tinyrustlm/tools/slm_pack/src/selector.rs` now carries `entry.N.adapter_auto_apply_stack_*` fields through registry generation and validation, and rejects stack-count drift. - `tinyrustlm/app/app.js` verifies the stack against the fetched adapter-family receipt and adapter manifests, sums manifest-declared artifact bytes against the auto-apply byte budget, then sequentially fetches, checksum-checks, and transfers each stack member to Rust. - `tinyrustlm/tools/browser-smoke.js` now requires generated roots to request the family ADP1 and sparse ASP1 stack routes and to record two pre-generation `apply_adapter_delta` calls plus `adapter_stack_applied(2)`. - `tinyrustlm/tools/browser_harness/src/main.rs` checks the static browser host for the adapter stack strategy marker. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all` - `cargo test -p tinyrustlm-slm-pack adapter_family::` - `cargo test -p tinyrustlm-slm-pack selector::` - `cargo test -p tinyrustlm-slm-pack browser_bundle::` - `cargo test -p tinyrustlm-browser-harness` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-adapter-stack/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18694/app/ 19524 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` ## Next Routing The next useful modular bead is richer stack planning: stack receipts can later add resource-class labels, per-module purpose labels, or eval-derived stack candidates, while this bead keeps the browser path local, manifest-bound, and Rust-validated. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-adapter-stack-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md BYTES: 3063 SHA256: BFB328FDF1E70202411B4C5E27CFA76BF3BC5087350B66F535231B50028B03A5 ================================================================================ --- title: Browser Adapter Stack Prefetch Drift Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T08:10:00Z --- # Browser Adapter Stack Prefetch Drift Memory ## Summary TinyRustLM browser auto assembly now prefetches and verifies the full receipt-declared adapter stack before any stack member is transferred into WASM. The browser still treats ADP1/ASP1/ALR1 payloads as opaque bytes: it verifies routes, manifest-declared byte counts, the auto-assembly byte budget, and artifact checksums, then Rust remains the adapter package parser and tensor mutation authority. ## Implementation - `tinyrustlm/app/app.js` now fetches the auto-apply stack into verified byte buffers first, using the existing adapter manifest byte-count and checksum rules. - `applyAutoAssemblyStack` no longer applies the first family ADP1 artifact before later sparse ASP1 or low-rank ALR1 bytes have been fetched and checked. - `applyAdapterByIndex` can consume already verified bytes for auto assembly while preserving the manual adapter path that fetches a selected adapter on demand. - `tinyrustlm/tools/browser-smoke.js` adds `adapter-stack-prefetch-drift`, which flips the second stack artifact (`sparse.asp1`) after all manifests pass. - The smoke asserts the family ADP1 and sparse ASP1 artifact routes are requested, the low-rank ALR1 artifact route is not requested after sparse drift, the model stays loaded, the trace reaches `adapter family verified`, and no `apply_adapter_delta` call appears. - The smoke harness module-plan checksum expectations were refreshed to the current generated f32/q8_0/q4_0 bundle receipts. ## Verification Passed on 2026-06-28: - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/adapter-stack-prefetch-drift/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18750/app/ 19608 multi-parent-sign-merge-q4 adapter-stack-prefetch-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18750/app/ 19609 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18750/app/ 19610 multi-parent-sign-merge-q4 adapter-artifact-drift` - `cargo test -p tinyrustlm-browser-harness` - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` ## Routing Load this report when work touches generated adapter stack prefetch, receipt-declared auto assembly, fetched stack artifact byte verification, `adapter-stack-prefetch-drift`, or the point where browser bytes cross into `apply_adapter_delta`. Related routes: - `wiki/gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-adapter-stack-memory-2026-06-27.md` - `wiki/gguf-mirust/reports/browser-module-plan-checksums-memory-2026-06-27.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28.md BYTES: 4020 SHA256: 2599385320092B530DDFB59859133F233EED0707A413475FE19205E38D4595C1 ================================================================================ --- title: Browser Adapter Stack Rust Validate Drift Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T08:45:00Z --- # Browser Adapter Stack Rust Validate Drift Memory ## Summary TinyRustLM now has a browser smoke proof for a checksum-consistent generated adapter stack member that still fails Rust semantic validation before any stack mutation. The smoke mutates a family ADP1 header identity field, recomputes the adapter package checksum, updates every browser-visible checksum echo, fetches the complete ADP1/ASP1/ALR1 stack, and confirms `validate_adapter_delta` returns `shape mismatch` before any `apply_adapter_delta` call. ## Implementation - `tinyrustlm/tools/browser-smoke.js` adds `adapter-stack-rust-validate-drift`. - The interceptor changes the family ADP1 identity byte at header offset 16 and recomputes the adapter package checksum at bytes 56-63. - The smoke updates the selector registry, module-plan receipt, assembly receipt, adapter-family receipt, adapter manifest, and served adapter artifact so browser route, byte, and checksum gates all stay aligned. - The assertion requires all adapter manifests and all three stack artifacts to be requested, then requires the console to contain `validate_adapter_delta(...) -> 9` and `shape mismatch`. - The assertion rejects any `apply_adapter_delta` console entry and requires the Module Plan Trace to stop after `adapter family verified`. - `runPageAdapterLoadStateSmoke` now exits promptly when startup reaches `Adapter load failed`, which keeps drift smokes focused on the adapter state transition. ## Verification Passed on 2026-06-28: - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/adapter-stack-rust-validate-drift/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18753/app/ 19617 multi-parent-sign-merge-q4 adapter-stack-rust-validate-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18754/app/ 19621 multi-parent-sign-merge-q4 adapter-stack-rust-validate-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18754/app/ 19622 multi-parent-sign-merge-q4 adapter-stack-prefetch-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18754/app/ 19623 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18754/app/ 19624 multi-parent-sign-merge-q4 combined-selector-assembly` The semantic drift proof showed all three stack artifact routes requested, `validate_adapter_delta(Multi-parent sign-merge q4_0 family ADP1) -> 9`, `shape mismatch`, loaded model diagnostics, a trace through `adapter family verified`, and no `apply_adapter_delta` entry. The existing prefetch drift proof still stopped before low-rank ALR1 fetch, the normal generated q4 route validated and applied all three stack members before generation, and the combined selector smoke preserved q4/q8/f32 validation-before-apply ordering. The generated path `target/adapter-stack-rust-validate-drift/tinyrustlm` was used for the new semantic-drift smoke. The established `target/adapter-stack-validate/tinyrustlm` route remains the harness baseline for rendered Module Plan byte/checksum constants. ## Routing Load this report when work touches generated auto-stack validation failure paths, `adapter-stack-rust-validate-drift`, checksum-consistent adapter artifact mutation, or proof that Rust semantic validation stops mutation after browser byte gates pass. Related routes: - `wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-adapter-artifact-drift-memory-2026-06-28.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md BYTES: 3879 SHA256: 6A3413A669A05142C6C733A06B4BA172213B766C2E92602EF4AD10DF4F9B5468 ================================================================================ --- title: Browser Adapter Stack Rust Validate Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T08:30:00Z --- # Browser Adapter Stack Rust Validate Memory ## Summary TinyRustLM generated browser auto assembly now asks Rust to validate every fetched ADP1/ASP1/ALR1 stack member before the first stack member is applied. The browser still owns local route, byte-count, budget, and checksum verification; Rust owns package parsing, model identity matching, tensor payload validation, and the eventual tensor mutation boundary. ## Implementation - `tinyrustlm/runtime/src/model.rs` now exposes `Model::validate_adapter_delta`, sharing the same adapter parser and tensor payload checks used by `apply_adapter_delta`. - `tinyrustlm/runtime/src/generate.rs` adds `Runtime::validate_adapter_delta`, which records `adapter validated` and preserves generation/KV diagnostics. - `tinyrustlm/runtime/src/wasm_exports.rs` exports `validate_adapter_delta(ptr, len)` for bytes already copied into WASM memory. - `tinyrustlm/app/app.js` validates every receipt-declared auto-stack byte buffer through `validate_adapter_delta` after browser byte verification and before the first `apply_adapter_delta` call. - Manual adapter apply still uses the existing selected-adapter path; the new semantic preflight is scoped to generated auto assembly. - `tinyrustlm/tools/browser-smoke.js` now asserts generated auto assembly logs `validate_adapter_delta` for the stack before the latest `apply_adapter_delta`. - `tinyrustlm/tools/wasm-abi-smoke.js` and `tinyrustlm/tools/browser_harness/src/main.rs` now include the validation export in ABI and static contract coverage. ## Verification Passed on 2026-06-28: - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `node --check tinyrustlm/tools/wasm-abi-smoke.js` - `cargo fmt --check` - `cargo test -p tinyrustlm-runtime adapter` - `cargo test -p tinyrustlm-runtime` - `cargo test -p tinyrustlm-browser-harness` - `cargo build -p tinyrustlm-runtime --release --target wasm32-unknown-unknown` - `cargo run -p tinyrustlm-slm-pack -- runtime-wasm-manifest .\tinyrustlm\runtime\tinyrustlm.wasm .\tinyrustlm\runtime\tinyrustlm.wasm.manifest` - `node tinyrustlm/tools/wasm-abi-smoke.js` - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/adapter-stack-validate/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18752/app/ 19614 multi-parent-sign-merge-q4 adapter-stack-prefetch-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18752/app/ 19615 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18752/app/ 19616 multi-parent-sign-merge-q4 combined-selector-assembly` The normal generated-root smoke rendered three validation calls, then three apply calls, then `adapter_stack_applied(3)`. The combined q4/q8/f32 smoke proved the same validation-before-apply order across every generated selector entry. The sparse stack drift smoke still stopped at `adapter artifact checksum mismatch` after adapter-family verification, before low-rank fetch or Rust apply. ## Routing Load this report when work touches generated adapter auto assembly, the `validate_adapter_delta` WASM ABI, Rust semantic adapter preflight, or browser proof that validation completes before apply. Related routes: - `wiki/gguf-mirust/reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/runtime-adapter-apply-memory-2026-06-27.md` - `wiki/gguf-mirust/reports/browser-low-rank-adapter-route-memory-2026-06-28.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-assembly-eval-case-drift-memory-2026-06-28.md BYTES: 3032 SHA256: FC06567D7366205205B1986A7E724961090583E9D978CB68256C5CE5C3186758 ================================================================================ --- title: Browser Assembly Eval Case Drift Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-assembly-eval-case-drift-memory-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T04:30:00Z --- # Browser Assembly Eval Case Drift Memory ## Summary TinyRustLM now treats `eval_case_evidence_checksum` as an assembly gate for generated browser roots. A checksum-consistent generated assembly receipt whose eval-case digest differs from the selector registry value stops the load before evidence files, adapter-family receipts, adapter manifests, or adapter stack artifacts are requested. The browser frees the already accepted model, marks Model State as `assembly evidence rejected`, leaves model selection available, disables generation controls, records Module Plan Trace through `assembly evidence rejected`, and keeps diagnostics at `model_loaded=false`. ## Implementation - `tinyrustlm/app/app.js` now turns generated assembly receipt failure into a load failure state before adapter-family verification or generation. - The browser calls `free_model` when available, clears loaded-context state, renders Assembly Evidence and Adapter Sidecar failure states, and leaves selector recovery available. - `tinyrustlm/tools/browser-smoke.js` adds `assembly-eval-case-drift`. - The smoke mutates only the generated assembly receipt `eval_case_evidence_checksum`, recomputes that assembly receipt checksum, updates the selector assembly checksum, updates the module-plan assembly checksum, and updates the selector module-plan checksum so the proof reaches the eval digest gate itself. - The smoke asserts no assembly evidence routes, adapter-family receipt, adapter manifests, or adapter stack artifacts are requested after the digest mismatch. ## Verification - `node --check tinyrustlm/app/app.js` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/assembly-eval-case-drift/tinyrustlm all` regenerated a validated all-root. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8099/app/ 9238 multi-parent-sign-merge-q4 assembly-eval-case-drift` passed with `runtimeStatus=Model load failed`, `modelState=assembly evidence rejected`, `assemblyState=assembly eval case evidence checksum mismatch`, `adapterState=assembly evidence rejected`, and `model_loaded=false`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8099/app/ 9237 multi-parent-sign-merge-q4 combined-selector-assembly` passed after refreshing generated all-root module-plan byte and checksum expectations. ## Routing Notes Use this page before changing generated assembly receipt eval fields, selector registry eval digest matching, `loadAssemblyReceipt`, Module Plan Trace failure checkpoints, or browser smoke assertions around generated assembly proof. Pair it with Browser Eval Case Evidence Checksum Memory for the positive digest route and Browser Assembly Trace Memory for ready-state sequencing. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-assembly-eval-case-drift-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-assembly-evidence-file-drift-memory-2026-06-28.md BYTES: 3464 SHA256: 0C55453352A660616EEA6212B379BEFE62D6CC3C11BED08D20F0B0903517124C ================================================================================ --- title: Browser Assembly Evidence File Drift Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-assembly-evidence-file-drift-memory-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T05:30:00Z --- # Browser Assembly Evidence File Drift Memory ## Summary TinyRustLM now has a browser smoke proof for fetched assembly evidence-file drift. The generated selector registry, module-plan receipt, model bytes, model manifest, and assembly receipt remain checksum-valid; the smoke mutates only the first served evidence file body and proves the browser rejects assembly before adapter-family receipts, adapter manifests, or adapter stack artifacts are requested. The browser frees the already accepted generated model, marks Model State as `assembly evidence rejected`, leaves the model selector available, disables generation controls, records Module Plan Trace through `assembly evidence rejected`, and keeps diagnostics at `model_loaded=false`. ## Implementation - `tinyrustlm/tools/browser-smoke.js` adds `assembly-evidence-file-drift`. - The smoke selects generated `multi-parent-sign-merge-q4` by default. - The Fetch interceptor mutates only `/evidence/multi-parent-sign-merge-q4/population.ledger` in flight, leaving selector, module-plan, assembly receipt, model, and manifest routes untouched. - The assertion requires the first evidence route to be requested, rejects later evidence routes, and rejects adapter-family receipt, adapter manifest, and adapter stack route requests. - The smoke also refreshes generated-root module-plan byte and checksum expectations for current ADP1 plus ASP1 plus ALR1 all-root receipts. ## Verification - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `node --check tinyrustlm/app/app.js` passed. - `cargo test -p tinyrustlm-browser-harness` passed with 6 tests. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` passed with 9 checks. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/assembly-evidence-file-drift/tinyrustlm all` regenerated a validated all-root with 3 admissions, 3 module-plan routes, 3 assembly routes, 3 adapter-family routes, and 12 adapter routes. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18732/app/ 19570 multi-parent-sign-merge-q4 assembly-evidence-file-drift` passed with `runtimeStatus=Model load failed`, `modelState=assembly evidence rejected`, `assemblyState=assembly evidence promotion_ledger_path checksum mismatch`, `adapterState=assembly evidence rejected`, `model_loaded=false`, and network requests ending at `/evidence/multi-parent-sign-merge-q4/population.ledger`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18732/app/ 19574 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` passed after refreshing generated q4 module-plan byte/checksum expectations and proved the normal path still fetches all evidence files, verifies the adapter-family receipt, and applies the family ADP1 plus sparse ASP1 plus low-rank ALR1 stack before generation. ## Routing Notes Use this page before changing assembly evidence-file fetching, `verifyAssemblyEvidenceFiles`, receipt evidence path/checksum fields, generated evidence routes, or browser smoke assertions around evidence-file integrity. Pair it with Browser Assembly Eval Case Drift Memory for the pre-evidence digest gate and Browser Assembly Trace Memory for failure and ready checkpoint sequencing. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-assembly-evidence-file-drift-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-assembly-trace-memory-2026-06-28.md BYTES: 3672 SHA256: 69EDC1FF684DD221A05F882668944115EFB526D1BC779AA27AD743FDB4AB9F54 ================================================================================ --- title: Browser Assembly Trace Memory public_route: /gguf-mirust/reports/browser-assembly-trace-memory-2026-06-28/ reviewed_utc: 2026-06-28T01:07:16Z source_authority: local verified TinyRustLM implementation status: reviewed_current --- # Browser Assembly Trace Memory TinyRustLM now renders a live Module Plan Trace row for generated browser roots. The row is written by browser-side assembly checkpoints, not by parsing model or adapter bytes, and records the actual verified sequence from module-plan receipt acceptance through model load, manifest verification, assembly evidence verification, adapter-family verification, auto-applied adapter stack, and ready state. The generated-root trace asserted by browser smoke is: `0: plan verified, 1: model accepted, 2: manifest verified, 3: assembly evidence verified, 4: adapter family verified, 5: adapter stack applied, 6: ready` This makes self-assembly more inspectable in the constrained browser surface. A future change that skips a stage, leaves stale state after a selector switch, or reaches Ready before the generated adapter stack has applied will break the generated-root smoke assertion. ## Implementation Route - `tinyrustlm/app/index.html` adds `modulePlanTrace` inside the Module Plan panel. - `tinyrustlm/app/app.js` resets trace state on each model-load sequence and records checkpoints only after the corresponding verified step completes. - `tinyrustlm/tools/browser_harness/src/main.rs` treats `modulePlanTrace` as a required static UI id. - `tinyrustlm/tools/browser-smoke.js` captures and asserts the generated trace in `adapter-sidecar-registry-file` and `combined-selector-assembly`; source-root UI audit expects `unavailable`. - `tinyrustlm/docs/browser-runtime.md` and `tinyrustlm/docs/testing.md` document the trace as a live browser assembly proof field. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-browser-harness` passed with 6 tests. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` passed with 9 checks. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-assembly-trace/tinyrustlm all` staged a generated all root. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18744/app/ 19596 multi-parent-sign-merge-q4 combined-selector-assembly` passed and proved q4_0, q8_0, and f32 each render the trace before one-token local generation. The regenerated all-root receipts produced current module-plan summaries: - q4_0 bytes: `0: 6592 bytes, 1: 585 bytes, 2: 1849 bytes, 3: 4316 bytes, 4: 20224 bytes, 5: 832 bytes` - q8_0 bytes: `0: 8832 bytes, 1: 585 bytes, 2: 1849 bytes, 3: 4316 bytes, 4: 20224 bytes, 5: 832 bytes` - f32 bytes: `0: 20352 bytes, 1: 586 bytes, 2: 1862 bytes, 3: 4316 bytes, 4: 20224 bytes, 5: 832 bytes` - q4_0 checksums: `0: 0x1a6808e3098d1ce0, 1: 0xb3f89bf19fb0895a, 2: 0x10c2f412e7751fbd, 3: 0x0571c8fd7c145691, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6` - q8_0 checksums: `0: 0x0132bc82d5a0d7d6, 1: 0x8f297c2ea011d241, 2: 0x3b94db808395e594, 3: 0x125729a41dd119bd, 4: 0x8194a8a671285019, 5: 0x6fa5d29bee9b7cfb` - f32 checksums: `0: 0x8a0e6c4c01998199, 1: 0xd944f90f17c6d61c, 2: 0xcf7cb192a48b5ed3, 3: 0x8ccb2722ee499c66, 4: 0xe9669ade4571fd42, 5: 0x34008cedc028ed5c` ## Next Route Use this report before changing the browser model-load sequence, generated module-plan display, generated auto-assembly stack, or combined-selector assembly smoke. Keep the trace as browser-owned proof of completed checkpoints, while Rust remains the authority for `.slm`, ADP1, and ASP1 validation. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-assembly-trace-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-auto-assembly-budget-memory-2026-06-27.md BYTES: 3775 SHA256: 16D0202CDB003028E3712C0E5832EED72D8617D9E20C24E21CBDA017B827ABD5 ================================================================================ --- title: Browser Auto Assembly Budget Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-auto-assembly-budget-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T17:00:03Z --- # Browser Auto Assembly Budget Memory ## Summary TinyRustLM generated adapter-family routes now carry an explicit browser-local byte envelope for auto-assembled modules. Rust emits and validates `entry.N.adapter_auto_apply_byte_budget=1048576`; the browser requires that registry field, checks each generated adapter manifest's `adapter_artifact_bytes`, and confirms fetched adapter bytes match the manifest before copying any auto-assembled module into WASM. ## Implementation Memory - `tinyrustlm/tools/slm_pack/src/selector.rs` adds `ADAPTER_AUTO_APPLY_BYTE_BUDGET`, writes `entry.N.adapter_auto_apply_byte_budget`, parses it back from selector registries, and rejects budget values above the local envelope. - `tinyrustlm/tools/slm_pack/src/adapter_family.rs` returns generated adapter-family registry routes with the 1 MiB auto-apply byte budget. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` asserts f32, q8_0, q4_0, and combined `all` generated selector roots carry the budget line. - `tinyrustlm/app/app.js` requires `adapter_auto_apply_byte_budget` when parsing adapter-family registry entries and caps it against the browser constant. - Browser adapter-family verification now parses `adapter_artifact_bytes` from served `.adp1.manifest` and `.asp1.manifest` files; the receipt-preferred auto-applied artifact must fit the registry budget before auto assembly is enabled. - `applySelectedAdapter("auto")` checks the fetched artifact byte length against the verified manifest and the family budget before WASM transfer; manual checked Adapter Sidecar routes remain available without adapter-family manifests. ## Validation Memory - `node --check tinyrustlm/app/app.js` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `cargo fmt --all` passed. - `cargo fmt --all -- --check` passed through `C:\Users\AI\.cargo\bin\cargo.exe`. - `cargo test -p tinyrustlm-slm-pack selector::` passed with 23 filtered tests, including adapter auto-apply byte-budget drift rejection. - `cargo test -p tinyrustlm-slm-pack adapter_family::` passed with 3 filtered tests. - `cargo test -p tinyrustlm-slm-pack browser_bundle::` passed with 3 filtered tests asserting generated registry budget fields. - `browser-multi-parent-bundle target/browser-auto-assembly-budget/tinyrustlm all` generated a combined selector root whose f32, q8_0, and q4_0 entries each carried `entry.N.adapter_auto_apply_byte_budget=1048576`. - Generated adapter manifests declared `adapter_artifact_bytes=832` for the receipt-preferred sparse ASP1 artifacts and `adapter_artifact_bytes=20224` for ADP1 artifacts, all below the 1 MiB auto-apply envelope. - Served-root `adapter-sidecar-registry-file` smokes passed on `http://127.0.0.1:18684/app/` for `multi-parent-sign-merge-q4`, `multi-parent-sign-merge-q8`, and `multi-parent-sign-merge-f32`; each auto-applied the receipt-preferred sparse ASP1 before generation and then generated `e`. - Normal-root `adapter-sidecar` smoke passed on `http://127.0.0.1:18685/app/` for `tinyq4`, preserving manual checked sidecar behavior. - `cargo test --workspace` passed with 243 checks across crates and doc-tests. - `git diff --check` exited cleanly with line-ending normalization notices only. ## Routing Notes Use this report before changing `adapter_auto_apply_byte_budget`, browser adapter manifest byte-count checks, auto-assembly pre-WASM transfer checks, generated bundle adapter-family registry fields, or the boundary between constrained auto assembly and manual checked Adapter Sidecar controls. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-auto-assembly-budget-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-auto-assembly-memory-2026-06-27.md BYTES: 3891 SHA256: FB00139461018797F281DDE5A95750F7123820CC52AD50558941536E5728FB75 ================================================================================ --- title: Browser Auto Assembly Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-auto-assembly-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T16:36:46Z --- # Browser Auto Assembly Memory ## Summary TinyRustLM generated selector registries now explicitly opt compatible adapter families into browser-local auto-assembly. Rust emits and validates `entry.N.adapter_auto_apply_status=enabled` and `entry.N.adapter_auto_apply_strategy=receipt-preferred-compatible`, and the browser auto-applies the receipt-preferred adapter only after model, manifest, assembly receipt, evidence files, adapter-family receipt, and adapter manifests verify. ## Implementation Memory - `tinyrustlm/tools/slm_pack/src/selector.rs` adds checksum-bound registry fields for adapter auto-apply status and strategy whenever an adapter-family receipt route is present. - `validate-selector-registry` rejects missing or drifted adapter auto-apply fields, including strategy drift away from `receipt-preferred-compatible`. - `tinyrustlm/tools/slm_pack/src/adapter_family.rs` returns registry adapter-family routes with the auto-apply status and strategy used by generated bundles. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` asserts generated f32, q8_0, q4_0, and combined `all` selector roots carry the auto-apply fields. - `tinyrustlm/app/app.js` requires those fields while parsing `selector.registry`; generated adapter-family entries become auto-apply candidates only after all browser receipt, evidence, and manifest checks pass. - Auto assembly calls `apply_adapter_delta` with runtime status `Assembling modules`, records `model.autoAssemblyApplied`, resets generation diagnostics through the existing Rust adapter-apply path, and leaves manual Adapter Sidecar behavior unchanged for checked tiny fixtures. - `tinyrustlm/tools/browser-smoke.js` treats `adapter-sidecar-registry-file` as auto-assembly proof: it waits for adapter state `applied` before generation, checks the pre-generation apply console entry and reset diagnostics, then generates one token from the assembled module. ## Validation Memory - `node --check tinyrustlm/app/app.js` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `cargo fmt --all` passed. - `cargo fmt --all -- --check` passed through `C:\Users\AI\.cargo\bin\cargo.exe`. - `cargo test -p tinyrustlm-slm-pack selector::` passed with 22 filtered tests, including adapter auto-apply strategy drift rejection. - `cargo test -p tinyrustlm-slm-pack adapter_family::` passed with 3 filtered tests. - `cargo test -p tinyrustlm-slm-pack browser_bundle::` passed with 3 filtered tests asserting auto-apply fields in generated registries. - `browser-multi-parent-bundle .\target\browser-auto-assembly-contract\tinyrustlm all` generated a combined selector root whose f32, q8_0, and q4_0 entries all carried the auto-apply status and strategy. - Served-root `adapter-sidecar-registry-file` smokes passed on `http://127.0.0.1:18682/app/` for `multi-parent-sign-merge-q4`, `multi-parent-sign-merge-q8`, and `multi-parent-sign-merge-f32`; each auto-applied the receipt-preferred sparse ASP1 before generation and then generated `e`. - Normal-root `adapter-sidecar` smoke passed on `http://127.0.0.1:18683/app/` for `tinyq4`, preserving manual apply behavior. - Normal-root intercepted `adapter-sidecar-registry-q8` smoke passed on `http://127.0.0.1:18683/app/` for `tinyq8`, preserving manual registry q8 ADP1 behavior. - `cargo test --workspace` passed with 242 checks across crates and doc-tests. ## Routing Notes Use this report before changing selector registry adapter auto-apply fields, browser generated adapter-family startup behavior, `adapter-sidecar-registry-file` smoke assertions, or the boundary between receipt-verified generated modules and manual checked Adapter Sidecar controls. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-auto-assembly-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md BYTES: 3133 SHA256: 8052D26545B1DE28756D956C4DE5EB4EAF60C4ADFDEF355E26AB4033AA8DBC6F ================================================================================ --- title: Browser Combined Selector Assembly Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T01:07:16Z --- # Browser Combined Selector Assembly Memory ## Summary TinyRustLM now has a headless browser smoke mode named `combined-selector-assembly` that proves one generated `browser-multi-parent-bundle all` root can start on the frugal q4_0 entry, switch through q8_0 and f32 generated entries, fetch each served `.module-plan.receipt` before that entry's `.slm`, verify the rendered Module Plan fields, and auto-apply the family ADP1 plus sparse ASP1 stack before generation. ## Implemented Shape - `tinyrustlm/tools/browser-smoke.js` adds `runPageCombinedSelectorAssemblySmoke` and `assertCombinedSelectorAssemblySmoke`. - The smoke walks `multi-parent-sign-merge-q4`, `multi-parent-sign-merge-q8`, and `multi-parent-sign-merge-f32` in one browser page. - The assertion reuses the generated adapter-family checks for each quantization and adds plan-before-model and plan-before-stack request ordering checks. - The combined selector default remains `multi-parent-sign-merge-q4`. - Each step renders `modulePlanState=loaded`, `modulePlanResource=browser-constrained-local-assembly`, six modules, ordered byte summaries, ordered checksum summaries, slots, roles, phases, dependencies, browser-owned trace checkpoints, model route, and stack route. ## Current Generated Summaries - q4_0 bytes: `0: 6592 bytes, 1: 585 bytes, 2: 1849 bytes, 3: 4316 bytes, 4: 20224 bytes, 5: 832 bytes` - q8_0 bytes: `0: 8832 bytes, 1: 585 bytes, 2: 1849 bytes, 3: 4316 bytes, 4: 20224 bytes, 5: 832 bytes` - f32 bytes: `0: 20352 bytes, 1: 586 bytes, 2: 1862 bytes, 3: 4316 bytes, 4: 20224 bytes, 5: 832 bytes` - q4_0 checksums: `0: 0x1a6808e3098d1ce0, 1: 0xb3f89bf19fb0895a, 2: 0x10c2f412e7751fbd, 3: 0x0571c8fd7c145691, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6` - q8_0 checksums: `0: 0x0132bc82d5a0d7d6, 1: 0x8f297c2ea011d241, 2: 0x3b94db808395e594, 3: 0x125729a41dd119bd, 4: 0x8194a8a671285019, 5: 0x6fa5d29bee9b7cfb` - f32 checksums: `0: 0x8a0e6c4c01998199, 1: 0xd944f90f17c6d61c, 2: 0xcf7cb192a48b5ed3, 3: 0x8ccb2722ee499c66, 4: 0xe9669ade4571fd42, 5: 0x34008cedc028ed5c` - Trace: `0: plan verified, 1: model accepted, 2: manifest verified, 3: assembly evidence verified, 4: adapter family verified, 5: adapter stack applied, 6: ready` ## Verification - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/combined-selector-assembly/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18742/app/ 19594 multi-parent-sign-merge-q4 combined-selector-assembly` The smoke observed only loopback requests. For each quantization, the network request order showed `.module-plan.receipt` before `.slm`, then manifest, assembly receipt, evidence files, adapter-family receipt, adapter manifests, family ADP1, and sparse ASP1. Each quantization generated `e` with `selected_next_token=101` after `adapter_stack_applied(2)`. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md BYTES: 4157 SHA256: 7D42391A51C39CF31F3203E349DA5771E75CD84C8DE6EB26B5E2952728E801A3 ================================================================================ --- title: Browser Combined Selector Cycle Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T09:10:00Z --- # Browser Combined Selector Cycle Memory ## Summary TinyRustLM now has a same-page generated-root browser smoke that cycles a combined q4_0/q8_0/f32 selector route twice. The proof keeps one served `browser-multi-parent-bundle all` root active, starts from the q4_0 default, walks q4_0, q8_0, f32, q4_0, q8_0, f32, and requires each pass to re-enter the generated module-plan, assembly, adapter-family, ADP1/ASP1/ALR1 validation, stack apply, reset-diagnostics, and one-token generation path. The browser also releases the previously loaded WASM model with `free_model` before each post-initial selector switch starts the next generated assembly. ## Implementation - `tinyrustlm/tools/browser-smoke.js` adds `combined-selector-cycle`. - `tinyrustlm/app/app.js` calls `free_model` when a loaded model is replaced by a selector switch, records the release in the local console, and then fetches the next generated module plan and model. - The existing combined selector runner now accepts a cycle count while preserving the original one-pass `combined-selector-assembly` behavior. - Each step records cycle index, pass index, console text before selection, console text before generation, and per-step console deltas. - The cycle assertion requires every step to report at least three new `validate_adapter_delta` calls, three new `apply_adapter_delta` calls, and one new `adapter_stack_applied(3)` before generation. - The cycle assertion now requires zero `free_model` calls for the initial q4_0 pass, exactly one `free_model` call before each later q8_0/f32/q4_0/q8_0/f32 assembly, and that release must appear before the next stack validation in the per-step console delta. - Cycle mode keeps module-plan route, model route, role, slot, phase, dependency, trace, assembly, evidence, adapter-family, manifest, and stack route checks strict while allowing fresh generated target paths to produce different manifest/evidence byte and checksum summaries. ## Verification Passed on 2026-06-28: - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/combined-selector-release/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18757/app/ 19628 multi-parent-sign-merge-q4 combined-selector-cycle 2` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18759/app/ 19630 multi-parent-sign-merge-q4 combined-selector-assembly` The cycle smoke produced six steps in one browser page. Every step had reset diagnostics before generation, `active_quantization_mode` matching the selected q4_0/q8_0/f32 entry, three Rust validation calls, three Rust apply calls, one stack completion, a ready Module Plan Trace, and a deterministic `e` generation. The initial q4_0 pass had no release call because it used the page's initial loaded model; every later pass had one `free_model(previous -> next) -> 0` plus `model freed` before the next validation call. The original one-pass combined selector smoke still passed on the established exact-summary baseline root. ## Routing Load this report when work touches `combined-selector-cycle`, longer same-page generated selector exercises, repeated q4_0/q8_0/f32 model switching, release-before-reassembly behavior, repeated generated stack validation/apply proof, or fresh generated-root path-flexible Module Plan summary assertions. Related routes: - `wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-assembly-trace-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md BYTES: 2879 SHA256: DA24658D962A61AAF9EC3F1577818981FAAD3EEC8BC5E71970D5C37C52D5AE03 ================================================================================ --- title: Browser Combined Selector Extended Route Soak Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T19:35:00Z --- # Browser Combined Selector Extended Route Soak Memory ## Summary TinyRustLM now has a named extended route-soak proof for one generated `all` root. The `combined-selector-route-extended-soak` smoke defaults to five q4_0/q8_0/f32 cycles, so one page completes fifteen generated assemblies while requiring fresh local route requests on every pass. ## Implementation - `tinyrustlm/tools/browser-smoke.js` adds `combined-selector-route-extended-soak` as a route-soak mode. - The extended mode defaults to five cycles and requires at least five cycles even if a lower argument is supplied. - Route-soak assertions reuse the combined selector cycle proof, then count every generated self-assembly route for module-plan receipts, models, manifests, assembly evidence, adapter-family receipts, adapter manifests, and ADP1/ASP1/ALR1 stack artifacts. - Path-flexible route-soak assertions now accept positive Total Budget values while canonical baseline smokes keep exact total-budget fixtures. - `tinyrustlm/README.md` and `tinyrustlm/docs/testing.md` document the extended mode. ## Verification Passed on 2026-06-28: - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/combined-selector-route-extended-soak/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8192/app/ 9297 multi-parent-sign-merge-q4 combined-selector-route-extended-soak` The smoke proved the q4_0 default, five q4_0/q8_0/f32 cycles, fifteen generated assemblies, release-before-reassembly on every post-initial pass, three adapter validations and applies before each generation, verified Module Plan WASM Pages `17`, and repeated local requests for every self-assembly route. Coverage note: no coverage tool is active in this no-third-party workspace; the evidence is focused harness syntax, Rust browser harness unit tests, generated bundle staging, and a served-root browser smoke. ## Routing Load this report when work touches longer generated selector-route reuse, `combined-selector-route-extended-soak`, path-flexible Module Plan total-budget assertions, or generated self-assembly route-count proof. Related routes: - `wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28.md BYTES: 3641 SHA256: A7D1A7EFDD0A345BC9DBA3098E6CF78C2344908B75C7644DE343E30795B99BF7 ================================================================================ --- title: Browser Combined Selector Reload Soak Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T14:40:00Z --- # Browser Combined Selector Reload Soak Memory ## Summary TinyRustLM now proves a generated `browser-multi-parent-bundle all` root can rebuild its q4_0/q8_0/f32 self-assembly graph across separate browser page lifetimes. The browser boot path honors the selector registry's q4_0 frugal default on each fresh page load, and `combined-selector-reload-soak` verifies the runtime manifest, selector registry, module plans, models, manifests, assembly evidence, adapter-family receipts, adapter manifests, and ADP1/ASP1/source-backed ALR1 stack artifacts are requested again for every reload pass. ## Implementation - `tinyrustlm/app/app.js` now lets selector-registry boot prefer the declared default model instead of preserving browser-restored form state. - `tinyrustlm/tools/browser-smoke.js` adds `combined-selector-reload-soak`. - The reload-soak runner navigates to a fresh app URL for each page lifetime, then runs the normal q4_0/q8_0/f32 combined selector assembly pass. - The reload-soak assertion requires each page lifetime to start on q4_0, expose exactly the generated q4_0/q8_0/f32 options, validate and apply the three-member ADP1/ASP1/source-backed ALR1 stack for each entry, and request every generated self-assembly route at least once per page lifetime. - The strict `combined-selector-assembly` exact module-plan byte and checksum baselines were refreshed for the current generated manifest bytes. ## Verification Passed on 2026-06-28: - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/combined-selector-reload-soak/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8186/app/ 9287 multi-parent-sign-merge-q4 combined-selector-reload-soak 2` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8186/app/ 9289 multi-parent-sign-merge-q4 combined-selector-assembly` The reload-soak produced two independent page lifetimes. Each lifetime started from the q4_0 registry default, then walked q4_0, q8_0, and f32. Every generated entry verified its module plan before model bytes, fetched assembly evidence and adapter-family receipts, verified adapter manifests, validated all three stack members through Rust, applied the stack before generation, and generated one local token. ## Routing Load this report when work touches generated selector reload behavior, registry default boot selection, fresh page lifetime self-assembly, route-count proof across reloads, or `combined-selector-reload-soak`. Related routes: - `wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-frugal-selector-default-memory-2026-06-27.md` - `wiki/gguf-mirust/reports/browser-source-backed-alr1-contract-memory-2026-06-28.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md BYTES: 2751 SHA256: 90B263C8DE3153653351B78B62F5D60A11A9FFC608EFEA9815AD9C57B69500E4 ================================================================================ --- title: Browser Combined Selector Route Soak Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T09:40:00Z --- # Browser Combined Selector Route Soak Memory ## Summary TinyRustLM now has a longer generated-root route-soak proof for the combined q4_0/q8_0/f32 selector. The browser fetches local assembly resources with `cache: "no-store"`, then `combined-selector-route-soak` runs three full q4_0/q8_0/f32 cycles in one page and requires every generated self-assembly route to be requested once per pass. ## Implementation - `tinyrustlm/app/app.js` uses a shared no-store local fetch option for text sidecars, WASM bytes, model bytes, and adapter bytes. - `tinyrustlm/tools/browser-smoke.js` adds `combined-selector-route-soak`. - The route-soak assertion reuses `combined-selector-cycle` checks, then counts requests for each generated model's module-plan receipt, `.slm`, `.slm.manifest`, assembly receipt, evidence files, adapter-family receipt, adapter manifests, and ADP1/ASP1/ALR1 stack artifacts. - Default route-soak length is three cycles, capped by the existing combined selector cycle limit. ## Verification Passed on 2026-06-28: - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/combined-selector-route-soak/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18760/app/ 19640 multi-parent-sign-merge-q4 combined-selector-route-soak 3` The smoke produced nine generated passes in one browser page. The selector started on q4_0, then walked q4_0/q8_0/f32 three times. Every post-initial pass released the previous WASM model before the next validation call, every pass validated and applied the ADP1/ASP1/ALR1 stack, every pass reached the ready trace, and every generated self-assembly file route was observed at least three times. ## Routing Load this report when work touches repeated generated selector reuse, route-count proof for self-assembly resources, cache behavior for local generated files, or `combined-selector-route-soak`. Related routes: - `wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-combined-selector-stress-route-soak-memory-2026-06-28.md BYTES: 2718 SHA256: 263D098DE974A43F1F507CBFADB6BC0877ED5CCDF12274BED55C5D0B6CA846AC ================================================================================ --- title: Browser Combined Selector Stress Route Soak Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-combined-selector-stress-route-soak-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T21:05:00Z --- # Browser Combined Selector Stress Route Soak Memory ## Summary TinyRustLM now has a named stress route-soak proof for one generated `all` root. The `combined-selector-route-stress-soak` browser smoke defaults to eight q4_0/q8_0/f32 cycles, so one page completes twenty-four generated assemblies while requiring fresh local route requests on every pass. ## Source Changes - `tinyrustlm/tools/browser-smoke.js` adds `combined-selector-route-stress-soak` as a route-soak mode. - The route-soak cycle cap increases to ten cycles, while the stress mode defaults to eight and requires at least eight. - `runPageCombinedSelectorAssemblySmoke(client, cycles)` now documents its bounded `cycles` contract and can drive the deeper pass count. - `tinyrustlm/README.md` and `tinyrustlm/docs/testing.md` route the new mode next to the three-cycle and five-cycle proofs. ## Verified Behavior - The generated root starts on q4_0 through the browser-frugal selector default. - The smoke walks q4_0, q8_0, and f32 entries for eight cycles. - Each pass verifies module-plan-before-model ordering, assembly evidence, adapter-family receipt and manifest checks, ADP1 plus ASP1 plus source-backed ALR1 route requests, Rust `validate_adapter_delta` before `apply_adapter_delta`, `adapter_stack_applied(3)`, runtime assembly diagnostics, and one-token generation. - The route-count assertion requires every generated self-assembly route to be requested at least eight times for its model entry. ## Verification - `node --check tinyrustlm\tools\browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/combined-selector-route-stress-soak/tinyrustlm all` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8194/app/ 9299 multi-parent-sign-merge-q4 combined-selector-route-stress-soak` ## Routing Load this report when work touches longer generated selector-route reuse, `combined-selector-route-stress-soak`, eight-cycle local route-count pressure, bounded combined-selector cycle handling, or generated self-assembly route freshness. ## Related Routes - `wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-combined-selector-reload-soak-memory-2026-06-28.md` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-combined-selector-stress-route-soak-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-converted-trained-all-route-memory-2026-06-29.md BYTES: 3453 SHA256: 42A6F370271EC6797FC0D0524F1D801241D8AB47307603B801E2DBB4D8F3FBF8 ================================================================================ # Browser Converted-Trained All Route Memory - 2026-06-29 ## Route - Source route: `tinyrustlm-slm-pack browser-converted-trained-bundle` - Browser route: `browser-smoke converted-trained-registry-file` - Generated root: `target/browser-converted-trained-all-20260629/tinyrustlm` - Primary files: `models/selector.registry`, `models/converted-trained-f32.slm`, `models/converted-trained-q8.slm`, `models/converted-trained-q4.slm`, matching `.slm.manifest` files, and `evidence/converted-trained-*/*` ## What Changed `browser-converted-trained-bundle [f32|q8_0|q4_0|all]` can now stage all converted trained-source quantizations into one runnable TinyRustLM root. The `all` path converts the reviewed trained-source directory to f32, q8_0, and q4_0 `.slm` artifacts, writes each provenance manifest, writes compatibility, lineage, candidate, promotion, runtime, eval, and admission sidecars per candidate, then writes and validates one `models/selector.registry` across all three admissions. The selector registry keeps `selector_default_strategy=browser-frugal-quantized`, `selector_default_candidate_id=converted-trained-q4`, and `selector_default_quantization=q4_0`. The browser smoke harness now knows the converted-trained f32/q8/q4 model keys and validates the selected entry without requiring the registry to contain only one option. ## Verification - `cargo fmt --all` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo test -p tinyrustlm-slm-pack writes_all_browser_converted_trained_bundle_from_source` - `cargo test -p tinyrustlm-slm-pack writes_browser_converted_trained_bundle_from_source` - `cargo test -p tinyrustlm-slm-pack rejects_browser_converted_trained_bundle_unknown_quantization` - `cargo run -p tinyrustlm-slm-pack -- browser-converted-trained-bundle .\target\browser-converted-trained-all-20260629\tinyrustlm .\tinyrustlm\tests\fixtures\trained-source-tiny all` - `cargo run -p tinyrustlm-local-server -- .\target\browser-converted-trained-all-20260629\tinyrustlm 8099` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8099/app/ 9291 converted-trained-q4 converted-trained-registry-file` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8099/app/ 9292 converted-trained-q8 converted-trained-registry-file` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8099/app/ 9293 converted-trained-f32 converted-trained-registry-file` - `cargo test -p tinyrustlm-slm-pack` ## Result The generated selector has three entries and defaults to `converted-trained-q4`. The q4, q8, and f32 browser smokes each generated `e`, reported the matching active quantization mode, fetched `/models/selector.registry`, fetched the selected converted-trained `.slm`, fetched the selected `.slm.manifest`, and rendered converted-trained provenance source, admission, quality, trained-claim, and next-gate fields. This proves reviewed trained-source weights can now be served as a local q4/q8/f32 selector set through the same browser-local route used by generated selector roots. Product assistant-quality claims remain tied to future task evidence beyond this route proof. ## Open Next - Add real trained source weights after a reviewed source manifest exists. - Keep converted-trained all roots q4-defaulted when selector frugality is desired. - Extend converted-trained browser proof toward richer module-plan or adapter-family routes only after those sidecars have typed evidence. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-converted-trained-all-route-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-converted-trained-file-route-memory-2026-06-29.md BYTES: 3282 SHA256: 149461852AA3AF42A72CF9ACF2676B278C4564170E6D85194033691A8A5C16C3 ================================================================================ # Browser Converted-Trained File Route Memory - 2026-06-29 ## Route - Source route: `tinyrustlm-slm-pack browser-converted-trained-bundle` - Browser route: `browser-smoke converted-trained-registry-file` - Generated root: `target/browser-converted-trained-file-20260629/tinyrustlm` - Primary files: `models/selector.registry`, `models/converted-trained-q8.slm`, `models/converted-trained-q8.slm.manifest`, and `evidence/converted-trained-q8/*` ## What Changed The converted-trained browser path now has a file-backed route. `browser-converted-trained-bundle [f32|q8_0|q4_0]` copies the app shell and WASM runtime, converts a reviewed trained-source directory into a served `.slm`, validates its provenance manifest, writes compatibility, lineage, candidate, promotion, runtime, eval, and admission sidecars, then writes and validates `models/selector.registry`. The browser smoke tool now accepts `converted-trained-registry-file`. That mode selects `converted-trained-q8` from a real served registry and verifies the browser fetches the registry, converted `.slm`, and converted `.slm.manifest` routes while rendering converted-trained source, admission, quality boundary, and pending trained-claim fields. ## Verification - `cargo fmt --all` - `cargo fmt --all -- --check` - `node --check tinyrustlm/tools/browser-smoke.js` - `node --check tinyrustlm/app/app.js` - `cargo test -p tinyrustlm-slm-pack browser_bundle::tests::writes_browser_converted_trained_bundle_from_source` - `cargo test -p tinyrustlm-slm-pack browser_bundle::tests::rejects_browser_converted_trained_bundle_unknown_quantization` - `cargo test -p tinyrustlm-slm-pack selector::tests::display_name_labels_converted_trained_source_entries` - `cargo run -p tinyrustlm-slm-pack -- browser-converted-trained-bundle .\target\browser-converted-trained-file-20260629\tinyrustlm .\tinyrustlm\tests\fixtures\trained-source-tiny q8_0` - `cargo run -p tinyrustlm-local-server -- .\target\browser-converted-trained-file-20260629\tinyrustlm 8096` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8096/app/ 9290 converted-trained-q8 converted-trained-registry-file` - `cargo test -p tinyrustlm-slm-pack` - `git diff --check` ## Result The file-backed smoke selected `converted-trained-q8`, generated `e`, and fetched `/models/selector.registry`, `/models/converted-trained-q8.slm`, and `/models/converted-trained-q8.slm.manifest` from the served root. The Model Provenance panel showed source `converted-trained`, selector admission `structure-accepted-quality-pending`, quality `runtime-compatible-not-quality-verified`, trained claim `pending-evaluation`, and model option label `Converted trained-source q8_0`. This proves the converted trained-source artifact can move through the same local selector, model, manifest, and browser provenance path as other served candidates. Broader assistant-quality claims remain bound to later task evidence beyond this file-route proof. ## Open Next - Add real trained source weights after a reviewed source manifest exists. - Repeat this file-backed route for f32 and q4_0 when those served converted roots are ready. - Keep converted-trained selector entries on local `../models/*.slm` routes with matching manifests and admission sidecars. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-converted-trained-file-route-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-converted-trained-provenance-memory-2026-06-29.md BYTES: 2397 SHA256: 4BE9C47DA03D06C181630E1A6E1B2340CC6F8FA70AEB794450668213307D99DF ================================================================================ --- title: Browser Converted Trained Provenance Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-converted-trained-provenance-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T18:52:33Z --- # Browser Converted Trained Provenance Memory TinyRustLM now has a focused browser smoke route proving a selector-served converted-trained `.slm` manifest keeps its source and quality boundary visible in the browser. ## What Changed - `tinyrustlm/tools/browser-smoke.js` adds `converted-trained-registry` mode. - The mode serves a compact `models/selector.registry` entry named `converted-trained-q8`. - The mode intercepts `/models/converted-trained-q8.slm` by reusing the checked tiny q8 bytes under a converted-trained route. - The mode serves `/models/converted-trained-q8.slm.manifest` with `source_kind=converted-trained`. - The browser smoke now captures Model Provenance source, admission, quality, trained-quality, and next-gate fields from `runPageSmoke`. - The assertion requires the browser to render `converted-trained`, `structure-accepted-quality-pending`, `runtime-compatible-not-quality-verified`, and `pending-evaluation`. ## Verification - `node --check tinyrustlm/tools/browser-smoke.js` - `node --check tinyrustlm/app/app.js` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8080/app/ 9281 converted-trained-q8 converted-trained-registry` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8080/app/ 9282 multi-parent-sign-merge-q8 multi-parent-registry` - `git diff --check` The converted-trained browser smoke selected `converted-trained-q8`, generated `e`, fetched `/models/converted-trained-q8.slm.manifest`, and rendered the converted-trained provenance fields. The compact multi-parent registry regression still selected `multi-parent-sign-merge-q8`, generated `e`, and rendered the federated Operator row. No coverage tool is active in the no-third-party workspace, so the changed harness is covered by syntax checks plus the positive converted-trained browser smoke and a shared registry regression smoke. ## Routing Open this report before changing `converted-trained-registry`, browser provenance assertions for converted-trained manifests, compact selector registry fixtures that route converted trained-source artifacts, or the browser-visible trained-source claim boundary. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-converted-trained-provenance-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-eval-case-evidence-checksum-memory-2026-06-28.md BYTES: 3167 SHA256: 7918E1422B06980A1A3A6143125A923A24403EEAEB7A19948DC044F39E822520 ================================================================================ --- title: Browser Eval Case Evidence Checksum Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-eval-case-evidence-checksum-memory-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T03:42:00Z --- # Browser Eval Case Evidence Checksum Memory ## Summary TinyRustLM now carries a compact `eval_case_evidence_checksum` from passed evaluation sidecars into selector admission records, promotion ledgers, selector registries, generated assembly receipts, and the browser Model Provenance panel. The checksum is derived from normalized `case_count`, `cases_passed`, `cases_failed`, and ordered `case.N.status/expected/actual/error` fields after the converted-trained evaluation gate has passed. For the generated `browser-multi-parent-bundle all` proof root, q4_0, q8_0, and f32 entries all displayed: `eval_case_evidence_checksum=0xabdeb569ab3eea3e` This gives the constrained browser route a stable digest for the evaluated case body without loading all eval case text into hot memory or selector UI. ## Implementation - `provenance.rs` exposes `eval_case_evidence_checksum` and tests that case-body changes alter the digest. - `admission.rs` and `multi_admission.rs` write and validate `eval_case_evidence_checksum` alongside `eval_manifest_checksum`. - `ledger.rs` carries the checksum into promotion-ledger entries for population and parent-pool routing. - `selector.rs` writes the checksum into `entry.N.eval_case_evidence_checksum`. - `browser_bundle.rs` writes the same checksum into generated `.assembly.receipt` files. - `app.js` requires the selector checksum for registry-backed models, renders eval cases and checksum in Model Provenance, and verifies assembly receipts match the registry value. - `browser-smoke.js` asserts registry-backed models show `1 passed` and a hex eval checksum, including `combined-selector-assembly`. ## Verification - `cargo test -p tinyrustlm-slm-pack` passed 168 tests. - `cargo test -p tinyrustlm-runtime` passed 77 tests. - `cargo test -p tinyrustlm-browser-harness` passed 6 tests. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` passed 9 checks. - `node --check tinyrustlm/app/app.js` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `node tinyrustlm/tools/wasm-abi-smoke.js tinyrustlm/runtime/tinyrustlm.wasm` passed. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-assembly-trace/tinyrustlm all` regenerated a validated all-root. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8098/app/ 9233 multi-parent-sign-merge-q4 combined-selector-assembly` passed and proved q4_0, q8_0, and f32 all display `1 passed`, the same eval-case checksum, verified module-plan fields, and ADP1 plus ASP1 plus ALR1 stack apply before generation. ## Routing Notes Use this page before changing selector admission evidence fields, promotion-ledger admission copies, generated assembly receipts, the Model Provenance panel, or browser-smoke registry-backed provenance assertions. Use Browser Assembly Trace Memory for checkpoint sequencing and Browser Low-Rank Adapter Route Memory for ALR1 stack routing. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-eval-case-evidence-checksum-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-frugal-selector-default-memory-2026-06-27.md BYTES: 3103 SHA256: AC0D6CC2539BC26940718E2F90FAA24EB82D8964A8E5D1D4BCAEE95FEEE25702 ================================================================================ --- title: Browser Frugal Selector Default Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-frugal-selector-default-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T15:37:28Z --- # Browser Frugal Selector Default Memory ## Summary TinyRustLM selector registries now carry a typed default-model signal for constrained browser roots. The generated registry marks `browser-frugal-quantized` as the selector default strategy and chooses the lowest ranked supported quantization, so a combined f32/q8_0/q4_0 generated root starts on q4_0 before any model bytes are loaded. ## Implementation Memory - `tinyrustlm/tools/slm_pack/src/selector.rs` writes `selector_default_strategy`, `selector_default_candidate_id`, and `selector_default_quantization` into every generated selector registry, ranking `q4_0` before `q8_0` before `f32`. - `tinyrustlm/app/app.js` parses and validates those registry-level default fields, rejects inconsistent default metadata, and uses the default key when there is no already-valid selected model. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` verifies that `browser-multi-parent-bundle all` writes `multi-parent-sign-merge-q4` as the combined-root default. - `tinyrustlm/tools/browser-smoke.js` records the initial selected model for generated combined roots and requires it to be `multi-parent-sign-merge-q4` before scripted switching. ## Validation Memory - `cargo fmt --all -- --check` passed through `C:\Users\AI\.cargo\bin\cargo.exe`. - `node --check tinyrustlm/app/app.js` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `cargo test -p tinyrustlm-slm-pack selector` passed with 23 filtered tests, including the mixed f32/q8_0/q4_0 default test. - `cargo test -p tinyrustlm-slm-pack browser_bundle` passed with 3 filtered tests, including the combined-root default assertion. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-frugal-selector-default\tinyrustlm all` staged one root whose selector registry had `entry_count=3`, `selector_default_strategy=browser-frugal-quantized`, `selector_default_candidate_id=multi-parent-sign-merge-q4`, and `selector_default_quantization=q4_0`. - Served-root `adapter-sidecar-registry-file` smokes on `http://127.0.0.1:18678/app/` passed for `multi-parent-sign-merge-q4`, `multi-parent-sign-merge-q8`, and `multi-parent-sign-merge-f32`; each observed initial selected model `multi-parent-sign-merge-q4`, selected sparse `ASP1` adapter index `2`, and preserved the active quantization after apply. - `cargo test --workspace` passed with 239 checks across crates and doc-tests. - `git diff --check` completed with line-ending normalization notices only. - Port `18678` had no listener after the smoke run, and matching temporary browser smoke profiles under `%TEMP%` were removed. ## Routing Notes Use this report before changing selector registry default fields, combined generated selector roots, browser model-select defaulting, or browser smoke assertions that prove a constrained root starts on q4_0. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-frugal-selector-default-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-local-runtime-memory-2026-06-25.md BYTES: 4111 SHA256: ADD5B499A5CC5D4A1A6B0455809460BAD05832B1EB7814D7F2A041CDA01CDBE6 ================================================================================ --- title: Browser Local Runtime Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-local-runtime-memory-2026-06-25/ status: planned_pending_publication reviewed_utc: 2026-06-25T00:00:00Z --- # Browser Local Runtime Memory ## Source Reports - `Building a lightweight AI runtime in the browser with Rust.md` - `Building Rust AI Runtime for Web.md` - `Rust Browser Tiny LLM Architecture.md` - `To run a TinyLM-16M transformer in-browser.md` - `Building Custom Rust SML Runtime.md` ## Durable Reading The browser runtime reports converge on one useful truth: client-side AI succeeds or fails at the boundary between strict local resource control and a friendly enough interface that users trust it. For TinyRustLM, that boundary is intentionally narrow: - Static HTML, CSS, and handwritten JavaScript. - Local WASM loaded by the browser. - Local `.slm` model files. - Raw bytes copied into Rust-controlled memory. - Explicit Rust error codes and diagnostics returned across the WASM ABI. - No remote inference, package manager, CDN, telemetry, framework, or hidden model fetch. The reports often recommend tools that the prompt forbids for the current version. That is still useful as contrast. WebGPU, OPFS, IndexedDB, workers, framework runtimes, and external model formats may become future comparison points, but the current proof must stay inside the pure Rust/WASM/static-file slice. ## Runtime Lessons The reports point to several hardening principles that fit the active implementation: - Fetch is not load. The UI must distinguish missing local file, malformed bytes, unsupported model, and rejected tensor directory. - Load is not readiness. The runtime is ready only after WASM initialization, model byte transfer, model validation, and diagnostics render. - Local-only is an observable property. Browser smoke should fail on non-local origins, not merely promise privacy in copy. - Memory pressure should be visible. Model load time, prompt tokens, generated tokens, tokens per second, scratch arena use, KV length, and quantization mode all help future agents understand runtime behavior. - The JS host should stay humble. It fetches, copies, calls, and renders. It should not parse model formats or own inference logic. ## Current Implementation Fit TinyRustLM already follows the key path from these reports: - Browser loads `tinyrustlm.wasm`. - Browser loads local TinyLM-16M-shaped `.slm` files. - Rust parses and validates `.slm`. - Prompt bytes cross the JS/WASM boundary. - Rust tokenizes and generates deterministic local output. - Diagnostics render in the UI. - Browser smoke covers q8, q4, reload/reset/model switching, malformed model rejection, missing-model fetch failure, context overflow, endurance loops, and local-only requests. ## Future Design Pressure The reports suggest a ladder of future work, but the order matters: 1. Finish correctness and hardening in the current local file model. 2. Improve sampling and tokenizer quality without adding external tokenizer formats. 3. Add measured performance improvements only after tests prove the current kernels. 4. Consider persistence or streaming only after the `.slm` format and browser error surface are stable. 5. Consider WebGPU or workers only as a later acceleration layer, not as a replacement for the audited Rust core. ## Thought Questions - What diagnostics would let a non-expert user know that the model is local, small, deterministic, and not a cloud assistant? - How should the UI recover when one local model fails but another valid local model is available? - When model files get larger, should the first optimization be faster math, streaming load, persistent cache, or smaller quantized formats? - What should the browser refuse to do even if the user asks, because it would break the local-only trust story? ## Current Boundary Use this record to reason about browser runtime design. Do not import framework, WebGPU, OPFS, or wasm-bindgen recommendations into the active code until the zero-dependency milestone is complete and the human approves a new boundary. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-local-runtime-memory-2026-06-25.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-low-rank-adapter-route-memory-2026-06-28.md BYTES: 2614 SHA256: E9C584550367F02809DB6C44648AF1903CEFF1FD9C17C61F8E2011C49A90DD68 ================================================================================ --- title: Browser Low-Rank Adapter Route Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-low-rank-adapter-route-memory-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T02:37:25Z --- # Browser Low-Rank Adapter Route Memory ## Summary Generated browser bundles now include `ALR1` low-rank adapter-family members for f32, q8_0, and q4_0 selector entries. The browser verifies route metadata, adapter-family receipt fields, `ALR1` manifests, module-plan stack module 6, and fetched artifact checksums before transferring low-rank bytes to WASM. ## Implementation - `adapter_family.rs` accepts `.alr1` routes with `low-rank-f32-task-delta-v1`, `low-rank-f32-delta`, and low-rank runtime apply statuses. - `selector.rs` validates `.alr1` served artifact paths and quantization-matched low-rank apply statuses. - `browser_bundle.rs` stages `{id}-low-rank.alr1` plus manifest for every generated f32/q8_0/q4_0 bundle entry and declares it as the third auto-apply stack member. - `app.js` recognizes `.alr1` manifests, keeps adapter bytes opaque to JavaScript, verifies module-plan role `adapter-stack-low-rank-delta`, and passes the bytes to Rust `apply_adapter_delta`. - `browser-smoke.js` asserts four adapter options, three stack routes, `ALR1` manifest/artifact network requests, `module_count` 7, and `adapter_stack_applied(3)`. ## Verification - `cargo test -p tinyrustlm-slm-pack` passed 167 tests. - `cargo build -p tinyrustlm-runtime --release --target wasm32-unknown-unknown`, copied rebuilt WASM to `tinyrustlm/runtime/tinyrustlm.wasm`, and refreshed `tinyrustlm.wasm.manifest`. - `cargo test -p tinyrustlm-runtime` passed 77 tests. - `cargo test -p tinyrustlm-browser-harness` passed 6 tests. - `node --check tinyrustlm/app/app.js` and `node --check tinyrustlm/tools/browser-smoke.js` passed. - `node tinyrustlm/tools/wasm-abi-smoke.js tinyrustlm/runtime/tinyrustlm.wasm` passed. - Generated `target/browser-alr1-route/tinyrustlm` with `browser-multi-parent-bundle ... all`. - Browser smoke passed for `multi-parent-sign-merge-f32` and `multi-parent-sign-merge-q8` in `adapter-sidecar-registry-file` mode on `http://127.0.0.1:8097/app/`; both auto-applied family `ADP1`, sparse `ASP1`, and low-rank `ALR1` before generation and kept requests local. ## Routing Notes - Use this page for browser `ALR1` route, receipt, manifest, and module-plan stack work. - Use `low-rank-adapter-package-memory-2026-06-28.md` for Rust packer/runtime `ALR1` package internals. - Use `browser-assembly-trace-memory-2026-06-28.md` for Module Plan Trace sequencing. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-low-rank-adapter-route-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-mixed-operator-selector-memory-2026-06-29.md BYTES: 9887 SHA256: 7AB166C77EFFBC733EBC708717D87765A7AB0D2F411E5E1D5893ABB32F0AB466 ================================================================================ # Browser Mixed Operator Selector Memory - 2026-06-29 ## Purpose Route future agents to the first browser-served selector root that carries both parent-pool operator families at once. This proof covers one generated `selector.registry` that serves sign-merge and weighted-soup q4/q8/f32 entries, then makes the browser assemble across both families in one page. ## Implementation - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` now accepts `browser-multi-parent-bundle [f32|q8_0|q4_0|all] mixed`. - The mixed mode expands the operator selector into `sign-merge` plus `soup`, while the existing `sign-merge` default and explicit `soup` mode remain unchanged. - Mixed `all` roots stage six generated models: `multi-parent-sign-merge-f32`, `multi-parent-sign-merge-q8`, `multi-parent-sign-merge-q4`, `multi-parent-soup-f32`, `multi-parent-soup-q8`, and `multi-parent-soup-q4`. - Each entry keeps its own module-plan receipt, assembly receipt, adapter-family receipt, ADP1/ASP1/ALR1 stack, and operator-scoped evidence files. - The selector default remains `multi-parent-sign-merge-q4`, preserving the browser-frugal q4 route when multiple q4 entries are present. - `tinyrustlm/tools/browser-smoke.js` now has `combined-selector-operator-family`, which switches one browser page through sign-merge q4, soup q4, sign-merge q8, soup q8, sign-merge f32, and soup f32. - `tinyrustlm/tools/browser-smoke.js` also has `combined-selector-operator-family-cycle`, which repeats that six-entry sequence and applies the existing release-before-reassembly, validation-count, apply-count, stack-completion, route-count, and local-origin checks across both operator families. - `tinyrustlm/tools/browser-smoke.js` also has `combined-selector-operator-family-route-soak`, which reuses the route-soak assertion layer for the mixed six-entry sequence and proves every expected self-assembly route is requested once per generated assembly pass. - `tinyrustlm/tools/browser-smoke.js` also has `combined-selector-operator-family-reload-soak`, which repeats the mixed six-entry assembly sequence across fresh browser page lifetimes and checks each reload contains three sign-merge steps plus three soup steps. ## Browser Proof The mixed root was generated with: ```powershell C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-multi-parent-mixed-operator-family\tinyrustlm all mixed ``` Observed generator proof: - `SLM selector registry validation: PASS` - `admissions: 6` - `adapter_routes: 24` - `adapter_family_routes: 6` - `assembly_routes: 6` - `module_plan_routes: 6` - `SLM browser multi-parent model count: 6` The browser proof passed with: ```powershell C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-local-server -- target\browser-served-multi-parent-mixed-operator-family\tinyrustlm 8116 node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8116/app/ 9387 multi-parent-sign-merge-q4 combined-selector-operator-family ``` The smoke observed initial selection `multi-parent-sign-merge-q4` and these model options in one selector: - `multi-parent-sign-merge-f32` - `multi-parent-sign-merge-q8` - `multi-parent-sign-merge-q4` - `multi-parent-soup-f32` - `multi-parent-soup-q8` - `multi-parent-soup-q4` The browser walked this assembly sequence: - `multi-parent-sign-merge-q4` - `multi-parent-soup-q4` - `multi-parent-sign-merge-q8` - `multi-parent-soup-q8` - `multi-parent-sign-merge-f32` - `multi-parent-soup-f32` Each entry reached Ready after module-plan verification, generated model and manifest acceptance, operator-scoped assembly evidence verification, adapter-family receipt and manifest verification, Rust `validate_adapter_delta` for three stack members, three adapter applies, 21 generated self-assembly fetches, matching actual route-set checksum, matching module bytes, and matching module checksums. Observed browser Operator rows included both families: - Sign-merge entries rendered `receipt-bound / sign-aware-parent-pool-merge / `. - Soup entries rendered `receipt-bound / seed-weighted-parent-pool-soup / `. The repeated mixed-family cycle proof passed with: ```powershell C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-mixed-operator-cycle\tinyrustlm all mixed C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-local-server -- target\browser-served-mixed-operator-cycle\tinyrustlm 8117 node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8117/app/ 9388 multi-parent-sign-merge-q4 combined-selector-operator-family-cycle 2 ``` The cycle smoke walked 12 generated assemblies in one page: - Cycle 0: sign-merge q4, soup q4, sign-merge q8, soup q8, sign-merge f32, soup f32. - Cycle 1: sign-merge q4, soup q4, sign-merge q8, soup q8, sign-merge f32, soup f32. The assertion layer required six sign-merge steps and six soup steps, one `free_model` before every post-initial assembly, three Rust validation calls, at least three Rust apply calls, one stack completion per step, 21 governed generated-route fetches per step, and same-origin loopback-only requests. Port 8117 was clear after the smoke. The mixed-family route-soak proof passed with: ```powershell C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-local-server -- target\browser-served-mixed-operator-cycle\tinyrustlm 8118 node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8118/app/ 9389 multi-parent-sign-merge-q4 combined-selector-operator-family-route-soak 2 ``` The route-soak smoke repeated the 12 generated assemblies from the mixed cycle proof and asserted that every expected module-plan, model, manifest, assembly receipt, evidence-file, adapter-family receipt, adapter manifest, and ADP1/ASP1/ALR1 stack artifact route for all six generated models was requested at least twice. The smoke finished on `multi-parent-soup-f32`, and port 8118 was clear after shutdown. The mixed-family reload-soak proof passed with: ```powershell C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-local-server -- target\browser-served-mixed-operator-cycle\tinyrustlm 8119 node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8119/app/ 9390 multi-parent-sign-merge-q4 combined-selector-operator-family-reload-soak 2 ``` The reload-soak smoke ran two fresh browser page lifetimes. Each lifetime started from `multi-parent-sign-merge-q4`, then assembled: - `multi-parent-sign-merge-q4` - `multi-parent-soup-q4` - `multi-parent-sign-merge-q8` - `multi-parent-soup-q8` - `multi-parent-sign-merge-f32` - `multi-parent-soup-f32` The assertion layer required three sign-merge steps and three soup steps per reload, runtime WASM manifest and selector registry requests at least once per reload, and every expected self-assembly route for all six generated models requested at least twice. Each reload finished on `multi-parent-soup-f32`, and port 8119 was clear after shutdown. ## Verification - `node --check tinyrustlm\tools\browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::tests::writes_combined_browser_multi_parent_mixed_operator_bundle --quiet` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::tests --quiet` with 7 tests passed. - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-multi-parent-mixed-operator-family\tinyrustlm all mixed` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8116/app/ 9387 multi-parent-sign-merge-q4 combined-selector-operator-family` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-mixed-operator-cycle\tinyrustlm all mixed` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8117/app/ 9388 multi-parent-sign-merge-q4 combined-selector-operator-family-cycle 2` - `node --check tinyrustlm\tools\browser-smoke.js` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8118/app/ 9389 multi-parent-sign-merge-q4 combined-selector-operator-family-route-soak 2` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8119/app/ 9390 multi-parent-sign-merge-q4 combined-selector-operator-family-reload-soak 2` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack --quiet` with 293 tests passed. - `git diff --check` returned only line-ending normalization notices. - Ports 8116, 8117, 8118, and 8119 had no listening server after the smokes. No coverage tool is active in this zero-dependency workspace. The closest automated evidence is the new mixed-operator Rust bundle test, the full browser-bundle test module, the full packer suite, the six-entry browser smoke that exercises the new `operator` parameter value through real file-backed selector routing, the mixed route-soak smoke that exercises every generated self-assembly route twice, and the mixed reload-soak smoke that repeats the six-entry proof across fresh page lifetimes. ## Routing Open this report before changing: - `browser-multi-parent-bundle` operator selection. - Mixed sign-merge plus soup selector roots. - `combined-selector-operator-family`, `combined-selector-operator-family-cycle`, `combined-selector-operator-family-route-soak`, and `combined-selector-operator-family-reload-soak` browser smoke behavior. - Browser selector defaults when multiple generated q4 entries exist. - Cross-family generated self-assembly route accounting. Related memory: - `wiki/gguf-mirust/reports/browser-parent-pool-soup-bundle-memory-2026-06-29.md` - `wiki/gguf-mirust/reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md` - `wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-combined-selector-cycle-memory-2026-06-28.md` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-mixed-operator-selector-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-actual-fetch-count-memory-2026-06-29.md BYTES: 2749 SHA256: 53AA6AFE088CBC57488D767A56B8E3AD1FE120D26C4294B03A731516CF34AF69 ================================================================================ --- title: Browser Module Plan Actual Fetch Count Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-actual-fetch-count-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T10:55:00Z --- # Browser Module Plan Actual Fetch Count Memory TinyRustLM generated self-assembly now has browser-owned fetch accounting. The browser counts each accepted generated module-plan route as it is fetched and only marks the generated model ready when the observed count matches `module_plan_planned_fetch_count`. ## What Changed - `tinyrustlm/app/index.html` adds the Module Plan `Actual Fetches` row. - `tinyrustlm/app/app.js` resets the generated-route counter on model load, records accepted module-plan route fetches through counted text and binary fetch wrappers, renders `Actual Fetches`, and rejects generated readiness when `actual_fetch_count != planned_fetch_count`. - `tinyrustlm/tools/browser-smoke.js` captures `modulePlanActualFetchCount` in generated and source snapshots, asserts q4_0/q8_0/f32 generated assemblies display `21 fetches`, and keeps source-root fallback at `unavailable`. ## Browser Contract Generated q4_0, q8_0, and f32 self-assembly currently requires 21 accepted module-plan routes: - 1 module-plan receipt - 1 generated `.slm` model - 1 generated `.slm.manifest` - 1 assembly receipt - 9 assembly evidence files - 1 adapter-family receipt - 4 adapter manifests - 3 auto-applied stack artifacts The browser-owned counter tracks the same route family as `module_plan_planned_fetch_count=21`. Manual adapter applies after load do not increment the generated self-assembly counter. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `git diff --check` - `cargo run --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml -- tinyrustlm` - Existing generated root `target/module-plan-actual-fetch-count-20260629/tinyrustlm all` served on `http://127.0.0.1:18752/app/`. - Generated `combined-selector-assembly` proved q4_0, q8_0, and f32 all reached `Ready`, generated response `e`, applied the three-adapter stack, and displayed `Plan Fetches 21 fetches` plus `Actual Fetches 21 fetches`. - Source `ui-audit` on `http://127.0.0.1:18753/app/` proved desktop and mobile fallback snapshots keep `Actual Fetches`, `Plan Fetches`, and route-set rows at `unavailable`. - No local server or browser debug listener remained open after the smoke runs. ## Routing Open this report before changing generated self-assembly route wrappers, Module Plan `Actual Fetches` display, planned-versus-actual readiness gates, or browser-smoke generated route-count assertions. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-actual-fetch-count-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-actual-module-bytes-memory-2026-06-29.md BYTES: 3029 SHA256: A94D45A8EE9112BA407CEC4A28271636D5B1CE30DEF94BF01D4F07B38DC406A6 ================================================================================ --- title: Browser Module Plan Actual Module Bytes Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-actual-module-bytes-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T11:40:00Z --- # Browser Module Plan Actual Module Bytes Memory TinyRustLM generated self-assembly now has browser-observed module-byte accounting. The browser records the accepted byte length for each module-plan module as that module is fetched, renders `Actual Module Bytes`, and only marks generated entries ready when the observed total equals the receipt-declared module byte total. ## What Changed - `tinyrustlm/app/index.html` adds the Module Plan `Actual Module Bytes` row. - `tinyrustlm/app/app.js` resets module-byte accounting on generated model load, records actual model, manifest, receipt, and auto-stack artifact bytes by module index, rejects duplicate or missing module indexes, and requires observed module bytes to match the verified receipt before generated Ready. - `tinyrustlm/tools/browser-smoke.js` captures `modulePlanActualModuleBytes` in generated and source snapshots, derives the expected total from the rendered Module Plan byte summary, and keeps source-root fallback at `unavailable`. ## Browser Contract The observed module-byte total covers the seven module-plan modules: - generated `.slm` model bytes - generated `.slm.manifest` text bytes - generated `.assembly.receipt` text bytes - generated `.adapter-family.receipt` text bytes - family ADP1 stack artifact bytes - sparse ASP1 stack artifact bytes - source-backed ALR1 stack artifact bytes The module byte total is intentionally narrower than `module_plan_total_byte_budget`; prompt, scratch, output, KV, and total-envelope budgets remain separate Module Plan rows. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `cargo run --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml -- tinyrustlm` - Existing generated root `target/module-plan-actual-module-bytes-20260629/tinyrustlm all` served on `http://127.0.0.1:18764/app/`. - Generated `combined-selector-assembly` proved q4_0, q8_0, and f32 all reached `Ready`, generated response `e`, applied the three-adapter stack, displayed `Actual Fetches 21 fetches`, matched Actual Route Set to Route Set, and displayed actual module-byte totals equal to the rendered module byte summaries: - q4_0 `37234 bytes` - q8_0 `39474 bytes` - f32 `51008 bytes` - Source `ui-audit` on `http://127.0.0.1:18765/app/` proved desktop and mobile fallback snapshots keep `Actual Module Bytes`, `Actual Fetches`, and `Actual Route Set` at `unavailable`. ## Routing Open this report before changing generated module byte accounting, `recordModulePlanActualModuleBytes`, Module Plan `Actual Module Bytes` display, stack artifact byte recording, or browser-smoke assertions that compare fetched module bytes to receipt-declared module byte rows. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-actual-module-bytes-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md BYTES: 5239 SHA256: CD6774044CEE88D349C633A4D8747C5054C11E11AAF9AF32DCDA4323792EAFBD ================================================================================ --- title: Browser Module Plan Actual Module Checksums Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T13:30:00Z --- # Browser Module Plan Actual Module Checksums Memory TinyRustLM generated self-assembly now has browser-observed module-checksum accounting. The browser records the checksum identity of each accepted module-plan module as the module is accepted, renders `Actual Module Checksums`, and only marks generated entries ready when the observed checksum list equals the verified receipt-declared module checksum list. ## What Changed - `tinyrustlm/app/index.html` adds the Module Plan `Actual Module Checksums` row. - `tinyrustlm/app/app.js` resets observed module checksums on generated model load, records generated text module checksums from fetched text, records generated adapter-stack checksums from fetched artifact bytes, records the accepted model checksum from the verified `.slm.manifest` after Rust accepts the model, rejects duplicate or missing module checksum indexes, and requires observed checksums to match the verified receipt before generated Ready. - `tinyrustlm/tools/browser-smoke.js` captures `modulePlanActualModuleChecksums` in generated and source snapshots, asserts generated actual checksums equal the rendered declared checksum summary, keeps source-root fallback at `unavailable`, and refreshes exact generated module summary constants for the current q4_0/q8_0/f32 bundle output. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-payload-checksum-drift`, which rewrites a generated family ADP1 payload checksum through its manifest, adapter-family receipt, assembly receipt, selector registry, and module-plan receipt while leaving the module checksum row stale. - `tinyrustlm/docs/testing.md` routes actual-checksum changes through source `ui-audit`, generated `combined-selector-assembly`, generated `adapter-sidecar-registry-file`, and `module-plan-payload-checksum-drift`. ## Browser Contract The observed checksum list covers the seven module-plan modules: - generated `.slm` model identity after Rust load and manifest verification - generated `.slm.manifest` text checksum - generated `.assembly.receipt` text checksum - generated `.adapter-family.receipt` text checksum - family ADP1 stack artifact checksum - sparse ASP1 stack artifact checksum - source-backed ALR1 stack artifact checksum The model checksum remains the `.slm` checksum identity carried by the model manifest after Rust accepts the model; JavaScript still does not parse `.slm` tensor payloads. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - Generated `module-plan-payload-checksum-drift` on `http://127.0.0.1:18768/app/` proved the coherent payload checksum rewrite stops at `module plan adapter module checksum mismatch` after only selector registry plus module-plan receipt requests; generated model, manifest, assembly, evidence, adapter-family, adapter-manifest, and stack artifact routes were not requested. - Generated q4_0 `adapter-sidecar-registry-file` on `http://127.0.0.1:18768/app/` still reached `Ready`, rendered `Actual Module Checksums` equal to `Checksums`, and applied the ADP1/ASP1/ALR1 stack before generation after the new smoke mode was added. - `cargo fmt --all -- --check` - `cargo run --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml -- tinyrustlm` - Fresh generated `all` root staged at `target/module-plan-actual-module-checksums-20260629/tinyrustlm`. - Generated `combined-selector-assembly` on `http://127.0.0.1:18766/app/` proved q4_0, q8_0, and f32 all reached `Ready`, generated response `e`, applied the three-adapter stack, displayed `Actual Fetches 21 fetches`, matched Actual Route Set to Route Set, and displayed `Actual Module Checksums` equal to the declared checksum summary for every entry: - q4_0 `0: 0x1a6808e3098d1ce0, 1: 0xfa5ea1108910598f, 2: 0xec65527ba6a0a24d, 3: 0x6c3f07949496907d, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6, 6: 0xcaf46ccfc262fad2` - q8_0 `0: 0x0132bc82d5a0d7d6, 1: 0x855c8c30e39227c5, 2: 0x88f5f52063d8d332, 3: 0x0988468dc4daf944, 4: 0x8194a8a671285019, 5: 0x6fa5d29bee9b7cfb, 6: 0x1ed9d08142edfda9` - f32 `0: 0x8a0e6c4c01998199, 1: 0xc2b257b1f036bfcb, 2: 0xd6d39c383538e5c3, 3: 0xe958c9dabb3565f0, 4: 0xe9669ade4571fd42, 5: 0x34008cedc028ed5c, 6: 0x1c64143141c223b5` - Generated `adapter-sidecar-registry-file` on the same root proved the q4_0 exact-summary path reaches `Ready` with `Actual Module Checksums` matching `Checksums`. - Source `ui-audit` on `http://127.0.0.1:18767/app/` proved desktop and mobile fallback snapshots keep `Actual Module Checksums`, `Actual Module Bytes`, `Actual Fetches`, and `Actual Route Set` at `unavailable`. ## Routing Open this report before changing generated module checksum accounting, `recordModulePlanActualModuleChecksum`, Module Plan `Actual Module Checksums` display, actual text module checksum recording, stack artifact checksum recording, or browser-smoke assertions that compare fetched module checksums to receipt-declared module checksum rows. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md BYTES: 3704 SHA256: 2CAA25EF243E7441A46E3FF42FB40FF78C42AAA99DEF30713845D7155A93A016 ================================================================================ # Browser Module Plan Adapter Apply Count Memory - 2026-06-29 status: reviewed_current authority: generated from current implementation and verification evidence ## Summary Generated module-plan selector entries and served `.module-plan.receipt` files now bind `module_plan_adapter_apply_count=3` for the ADP1/ASP1/ALR1 auto-assembly stack. The browser verifies selector, receipt, adapter-family stack count, and runtime diagnostics agreement, renders the Module Plan `Apply Count` row, and rejects count drift before generated model bytes or stack artifacts are fetched. ## Implementation Route - `tinyrustlm/tools/slm_pack/src/selector.rs` writes, parses, checksums, and validates `entry.N.module_plan_adapter_apply_count`. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` derives `module_plan_adapter_apply_count` from the generated auto-apply stack and writes it into generated `.module-plan.receipt` files and selector route records. - `tinyrustlm/app/index.html` adds the Module Plan `Apply Count` row. - `tinyrustlm/app/app.js` validates selector and receipt agreement, requires the count to match the adapter-family auto-apply stack, and compares runtime `adapter_apply_count` diagnostics after generated stack assembly. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-adapter-apply-count-drift`, asserts generated roots render `3`, asserts source roots render `unavailable`, and refreshes q4_0/q8_0/f32 module-plan byte/checksum summaries after the new receipt field. - `tinyrustlm/tools/browser_harness/src/main.rs` includes the new row id in the static UI contract. ## Verified Behavior - `cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml module_plan_adapter -- --nocapture` passed, including `rejects_module_plan_adapter_apply_count_drift`. - `cargo test --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml` passed with 6 tests. - `cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture` passed with 4 tests. - `node --check tinyrustlm/app/app.js` and `node --check tinyrustlm/tools/browser-smoke.js` passed. - Generated q4_0, q8_0, and f32 roots refreshed module-plan expected totals and module checksums after adding the receipt line. - Generated-root `module-plan-adapter-apply-count-drift` passed on `http://127.0.0.1:8242/app/`, returning `Module plan adapter apply count mismatch` after selector plus module-plan receipt requests and before generated model routes. - Fresh generated all-root `combined-selector-assembly` passed on `http://127.0.0.1:8252/app/` with q4_0 default, q8_0 switch, and f32 switch; each entry rendered Apply Count `3`, reported runtime `adapter_apply_count=3`, carried nonzero adapter and assembly checksums, and generated after ADP1 plus ASP1 plus ALR1 stack apply. - `cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml` passed with 223 tests. ## Current Positive Proof The positive generated browser assembly proof is current as of `2026-06-29T02:30:52Z`: `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8252/app/ 9353 multi-parent-sign-merge-q4 combined-selector-assembly` exited 0 against `target/goal-combined-assembly-proof/tinyrustlm`. ## Routing Notes Open this report before changing generated adapter-stack cardinality, selector registry module-plan count metadata, Module Plan `Apply Count` display, runtime `adapter_apply_count` diagnostics checks, or `module-plan-adapter-apply-count-drift` smoke assertions. Keep this field separate from `adapter_auto_apply_stack_count`: the family receipt says what stack is preferred, while the module plan says how many adapter mutations the generated assembly must complete before generation. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28.md BYTES: 2460 SHA256: 647A223259C1E98F5020C5249C16A8E8194915986EA0159605FBA8CEEB5DBCC7 ================================================================================ # Browser Module Plan Adapter Stack Budget Memory - 2026-06-28 status: current public_route: /gguf-mirust/reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28/ source_authority: local source, generated bundle, focused Rust tests, and browser smoke ## Route Summary Generated selector entries and served `.module-plan.receipt` files now bind the exact auto-applied adapter stack payload budget before generated model bytes load. ## Implemented Shape - `module_plan_adapter_stack_byte_budget` is emitted in selector registries and module-plan receipts. - The generated browser bundle computes the value from the staged ADP1 plus ASP1 plus ALR1 artifact byte counts. - Browser registry intake requires the stack byte budget to be positive, inside the adapter-family cap, and included in the total self-assembly budget. - Browser module-plan receipt validation checks the field against selector metadata and sums the ordered stack module byte counts. - Adapter-family manifest loading verifies fetched stack artifact byte counts against the receipt-declared stack modules before auto-apply. - The Module Plan panel renders `Stack Budget` beside model, adapter, scratch, KV, total, and limit rows. ## Verified Evidence - `cargo test -p tinyrustlm-slm-pack selector::tests::` - `cargo test -p tinyrustlm-slm-pack browser_bundle::tests::` - `cargo test -p tinyrustlm-browser-harness` - `cargo fmt --all -- --check` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-stack-budget\tinyrustlm all` - `cargo run -p tinyrustlm-browser-harness -- .\tinyrustlm` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8102/app/ 19580 multi-parent-sign-merge-q4 combined-selector-assembly` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8102/app/ 19581 multi-parent-sign-merge-q4 module-plan-adapter-stack-budget-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8102/app/ 19582 multi-parent-sign-merge-q4 module-plan-total-budget-drift` ## Current Generated Values - Stack Budget: `22144 bytes` - q4_0 Total Budget: `103783 bytes` - q8_0 Total Budget: `106023 bytes` - f32 Total Budget: `117557 bytes` ## Next Route Use this report before changing adapter-stack module byte accounting, adapter-family manifest byte checks, module-plan total budget math, or Module Plan panel budget rows. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-count-memory-2026-06-29.md BYTES: 3607 SHA256: 8B28A780E19D412F2D1AF5E33747E8F2D068B262FD8A8FCBCACA0FE28751065F ================================================================================ --- title: Browser Module Plan Adapter Validation Count Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-adapter-validation-count-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T02:53:13Z --- # Browser Module Plan Adapter Validation Count Memory TinyRustLM generated module plans now bind adapter validation cardinality with `module_plan_adapter_validation_count=3` beside `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1` and `module_plan_adapter_apply_count=3`. ## What Changed - `tinyrustlm/tools/slm_pack/src/selector.rs` writes, parses, validates, and checksums `module_plan_adapter_validation_count`; selector validation requires the count to be positive, within module count, and equal to the planned apply count. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` emits the count into generated selector registry entries and `.module-plan.receipt` files for q4_0, q8_0, and f32 generated roots. - `tinyrustlm/app/app.js` requires selector, receipt, adapter-family, and expected constant agreement before generated model bytes are accepted, renders `Validate Count`, and checks the actual Rust validation loop count before adapter application. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-adapter-validation-count-drift`, positive generated-root assertions for `Validate Count 3`, source-root fallback assertions, and exact per-step validation-delta checks for combined generated assemblies. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml module_plan_adapter -- --nocapture` - `cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture` - `cargo test --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml` - `cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml` - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` - Generated `target/module-plan-adapter-validation-count/tinyrustlm all`. - Served generated root on `http://127.0.0.1:8254/app/`. - `module-plan-adapter-validation-count-drift` stopped at `Module plan adapter validation count mismatch` after selector registry plus module-plan receipt fetch. - `combined-selector-assembly` proved q4_0, q8_0, and f32 render `Validate Count 3`, run exactly three `validate_adapter_delta` calls per generated assembly step, apply three adapters, and generate one local token. - Source `ui-audit` on `http://127.0.0.1:8255/app/` proved source roots render the validation-count row as `unavailable`. ## Current Generated Module-Plan Values - Total budgets: q4_0 `173422 bytes`, q8_0 `175662 bytes`, f32 `187196 bytes`. - q4_0 checksums: `0: 0x1a6808e3098d1ce0, 1: 0xbda29682e8a42104, 2: 0xe6a285ad92365df6, 3: 0x3c400205a8a0afa6, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6, 6: 0xcaf46ccfc262fad2`. - q8_0 checksums: `0: 0x0132bc82d5a0d7d6, 1: 0xf52fd0b0ec77c9fa, 2: 0x64d2170d074b3bae, 3: 0x3548cb7b1f378d9f, 4: 0x8194a8a671285019, 5: 0x6fa5d29bee9b7cfb, 6: 0x1ed9d08142edfda9`. - f32 checksums: `0: 0x8a0e6c4c01998199, 1: 0x49ce8042500c7d7c, 2: 0x85f5554a9995f494, 3: 0x492df944fbed530f, 4: 0xe9669ade4571fd42, 5: 0x34008cedc028ed5c, 6: 0x1c64143141c223b5`. ## Routing Open this report before changing generated adapter validation cardinality, Module Plan `Validate Count` display, selector/receipt adapter validation-count fields, or `module-plan-adapter-validation-count-drift` smoke assertions. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-count-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29.md BYTES: 3195 SHA256: 4559CFCA94879CE971CDD15824619068364A6BDF577FD85AED7F79D46FEC7B7D ================================================================================ # Browser Module Plan Adapter Validation Memory - 2026-06-29 status: reviewed_current authority: generated from current implementation and verification evidence ## Summary Generated module-plan selector entries and served `.module-plan.receipt` files now bind `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1`. The browser verifies selector and receipt agreement, renders the verified Module Plan `Validate` row, and requires the generated auto-assembly path to use Rust `validate_adapter_delta` before any `apply_adapter_delta` call. ## Implementation Route - `tinyrustlm/tools/slm_pack/src/selector.rs` writes, parses, checksums, and validates `entry.N.module_plan_adapter_validation_strategy`. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `module_plan_adapter_validation_strategy=rust-validate-before-apply-v1` into generated `.module-plan.receipt` files and selector route records. - `tinyrustlm/app/index.html` adds the Module Plan `Validate` row. - `tinyrustlm/app/app.js` validates selector and receipt agreement, requires the same strategy before generated auto-assembly, and renders the verified field only after receipt acceptance. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-adapter-validation-drift`, asserts generated roots render `rust-validate-before-apply-v1`, and asserts source roots render `unavailable`. - `tinyrustlm/tools/browser_harness/src/main.rs` includes the new row id in the static contract. ## Verified Behavior - Node syntax checks passed for `tinyrustlm/app/app.js` and `tinyrustlm/tools/browser-smoke.js`. - `cargo fmt --all -- --check` passed with `C:\Users\AI\.cargo\bin\cargo.exe`. - `cargo test -p tinyrustlm-slm-pack selector` passed with 74 tests, including `rejects_module_plan_adapter_validation_strategy_drift`. - `cargo test -p tinyrustlm-slm-pack browser_bundle` passed with 4 tests. - `cargo test -p tinyrustlm-browser-harness` passed with 6 tests. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` passed with 9 static checks. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\module-plan-adapter-validation\tinyrustlm all` passed and validated 3 module-plan routes. - Generated-root `module-plan-adapter-validation-drift` passed on `http://127.0.0.1:8240/app/`, returning `Module plan adapter validation strategy mismatch` after selector plus module-plan receipt requests and before generated model routes. - Generated-root `combined-selector-assembly` passed on `http://127.0.0.1:8240/app/`, proving q4_0/q8_0/f32 generated assemblies render `Validate` as `rust-validate-before-apply-v1` and log all `validate_adapter_delta` calls before `apply_adapter_delta`. - Source-root `ui-audit` passed on `http://127.0.0.1:8241/app/`, proving the fallback row remains `unavailable`. ## Routing Notes Open this report before changing generated adapter-stack validation sequencing, selector registry module-plan validation metadata, Module Plan `Validate` display, or `module-plan-adapter-validation-drift` smoke assertions. Keep this field separate from stack byte budgets: it records Rust validation authority before mutation, not how many adapter bytes are allowed. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-budget-display-memory-2026-06-27.md BYTES: 2673 SHA256: 3F49857269DEE429CA3C5E3DCB54D3CA3BE14363B4E823A644AD8B7F0636DC33 ================================================================================ --- title: Browser Module Plan Budget Display Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-budget-display-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T21:02:20Z --- # Browser Module Plan Budget Display Memory ## Routing Summary Use this report when work touches the browser Module Plan panel's visible resource budget rows, verified `.module-plan.receipt` budget fields, source fallback UI audit assertions, or generated-root adapter-sidecar smoke assertions for model and adapter byte envelopes. ## Implementation - `tinyrustlm/app/index.html` adds `Model Budget` and `Adapter Budget` rows to the Module Plan panel. - `tinyrustlm/app/app.js` renders `module_plan_model_byte_budget` and `module_plan_adapter_byte_budget` only from the already verified receipt field map. Missing fallback fields render `unavailable`. - `tinyrustlm/tools/browser_harness/src/main.rs` treats the new budget row ids as part of the static app contract. - `tinyrustlm/tools/browser-smoke.js` captures the budget rows in source-root `ui-audit` and generated-root `adapter-sidecar-registry-file` snapshots. Generated roots assert the q4/q8/f32 model budget text from known admitted artifact bytes and assert the adapter envelope as `1048576 bytes`. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-browser-harness` - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18710/app/ 19542 tinylm16q8 ui-audit` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-budget-display/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18712/app/ 19544 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` - `cargo test --workspace` ## Outcome The source-root desktop/mobile UI audit showed Module Plan fallback state `none` with `modulePlanModelBudget=unavailable` and `modulePlanAdapterBudget=unavailable`. The generated q4 registry-file smoke showed `modulePlanState=loaded`, `modulePlanModelBudget=6592 bytes`, `modulePlanAdapterBudget=1048576 bytes`, and the existing verified model route plus family ADP1 and sparse ASP1 stack display. Workspace tests passed with 249 checks. ## Next Routing The next useful constrained-browser bead is planner-readable module purpose or stack role labels in the `.module-plan.receipt`, still rendered only after checksum/resource/graph/stack verification and still keeping JavaScript out of model and adapter payload parsing. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-budget-display-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-byte-counts-memory-2026-06-27.md BYTES: 3688 SHA256: 92F73FF2BE95A36B54C22ACE0A9B5087D76846C83E51B54084340AF03159CB1C ================================================================================ --- title: Browser Module Plan Byte Counts Memory 2026-06-27 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-byte-counts-memory-2026-06-27/ status: reviewed_current reviewed_utc: 2026-06-28T01:07:16Z --- # Browser Module Plan Byte Counts Memory ## Summary TinyRustLM generated `.module-plan.receipt` files now carry explicit `module.N.byte_count` fields for every browser-local assembly module. The browser verifies those byte counts against fetched model bytes, fetched text sidecars, and adapter manifest artifact sizes before generated model or adapter stack work can continue. ## Implemented Shape - `module.0.byte_count`: generated `.slm` byte length, checked before WASM model transfer. - `module.1.byte_count`: `.slm.manifest` text byte length, checked after manifest fetch. - `module.2.byte_count`: `.assembly.receipt` text byte length, checked after assembly receipt fetch. - `module.3.byte_count`: `.adapter-family.receipt` text byte length, checked after adapter-family receipt fetch. - `module.4+ .byte_count`: receipt-declared adapter stack artifact byte lengths, checked against fetched adapter manifests before artifact fetch and auto apply. ## Source Routes - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes per-module byte counts into generated module-plan receipts and asserts them in browser-bundle tests. - `tinyrustlm/app/app.js` verifies receipt byte counts before model transfer, text-sidecar use, adapter-stack artifact fetch, and auto apply. - `tinyrustlm/app/index.html` adds the Module Plan `Bytes` row. - `tinyrustlm/tools/browser_harness/src/main.rs` requires the `modulePlanBytes` UI id. - `tinyrustlm/tools/browser-smoke.js` checks generated-root byte display, source-root fallback, and `module-plan-byte-drift`. ## Verification - `node --check tinyrustlm\app\app.js` - `node --check tinyrustlm\tools\browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-module-plan-byte-counts\tinyrustlm all` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:18732/app/ 19576 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:18732/app/ 19572 multi-parent-sign-merge-q4 module-plan-byte-drift` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:18734/app/ 19574 tinylm16q8 ui-audit` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe test --workspace` ## Evidence Notes The current regenerated q4 summary after the browser assembly trace pass is `0: 6592 bytes, 1: 585 bytes, 2: 1849 bytes, 3: 4316 bytes, 4: 20224 bytes, 5: 832 bytes`. The byte-drift smoke mutated only `module.0.byte_count` while keeping the receipt checksum aligned through `selector.registry`. The browser requested `/models/selector.registry` and `/models/multi-parent-sign-merge-q4.module-plan.receipt`, reported `Module plan field module.0.byte_count was 6591`, and stopped before generated `.slm`, ADP1, ASP1, and adapter-manifest routes. The source-root UI audit proved checked fallback models render the Module Plan byte row as `unavailable` on desktop and mobile. ## Routing Use this report when changing `.module-plan.receipt` byte-count fields, Module Plan byte rendering, browser pre-model-fetch byte validation, adapter-stack artifact byte matching, or `module-plan-byte-drift` assertions. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-byte-counts-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-checksums-memory-2026-06-27.md BYTES: 3659 SHA256: 16CB53908E60814591ACCA0231C3BC12B01CE73F471115CC27BBFD739BD52097 ================================================================================ --- title: Browser Module Plan Checksums Memory 2026-06-27 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-checksums-memory-2026-06-27/ status: reviewed_current reviewed_utc: 2026-06-28T01:07:16Z --- # Browser Module Plan Checksums Memory ## Summary TinyRustLM generated `.module-plan.receipt` files now carry uniform `module.N.checksum` fields for every browser-local assembly module. The browser verifies those checksums from the module-plan receipt before generated model bytes or adapter stack artifacts can be fetched. ## Implemented Shape - `module.0.checksum`: generated `.slm` checksum, matched before model byte transfer. - `module.1.checksum`: `.slm.manifest` checksum, matched before manifest trust. - `module.2.checksum`: `.assembly.receipt` checksum, matched before evidence-file fetches. - `module.3.checksum`: `.adapter-family.receipt` checksum, matched before family manifest loading. - `module.4+ .checksum`: receipt-declared adapter stack artifact checksums, matched to route manifest metadata before artifact fetch and auto apply. ## Source Routes - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes per-module checksums into generated module-plan receipts and asserts stack checksum fields in browser-bundle tests. - `tinyrustlm/app/app.js` renders the ordered checksum summary and verifies stack module checksums before generated stack work. - `tinyrustlm/app/index.html` adds the Module Plan `Checksums` row. - `tinyrustlm/tools/browser_harness/src/main.rs` requires the `modulePlanChecksums` UI id. - `tinyrustlm/tools/browser-smoke.js` checks generated-root checksum display, source-root fallback, and `module-plan-checksum-drift`. ## Verification - `node --check tinyrustlm\app\app.js` - `node --check tinyrustlm\tools\browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-checksums/tinyrustlm all` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:18736/app/ 19586 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:18736/app/ 19588 multi-parent-sign-merge-q4 module-plan-checksum-drift` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:18738/app/ 19590 tinylm16q8 ui-audit` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe test --workspace` ## Evidence Notes The current regenerated q4 summary after the browser assembly trace pass is `0: 0x1a6808e3098d1ce0, 1: 0xb3f89bf19fb0895a, 2: 0x10c2f412e7751fbd, 3: 0x0571c8fd7c145691, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6`. The checksum-drift smoke mutated only `module.4.checksum` while keeping the receipt checksum aligned through `selector.registry`. The browser requested `/models/selector.registry` and `/models/multi-parent-sign-merge-q4.module-plan.receipt`, reported `module plan adapter module checksum mismatch`, and stopped before generated `.slm`, ADP1, ASP1, and adapter-manifest routes. The source-root UI audit proved checked fallback models render the Module Plan checksum row as `unavailable` on desktop and mobile. ## Routing Use this report when changing `.module-plan.receipt` checksum fields, Module Plan checksum rendering, browser pre-model-fetch checksum validation, stack artifact checksum matching, or `module-plan-checksum-drift` assertions. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-checksums-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28.md BYTES: 2901 SHA256: 73EECC40D7FB6F561B3AEB9BA11F3EE8D631C1662600E0A75F96FFEA6FB51242 ================================================================================ # Browser Module Plan Context Token Memory - 2026-06-28 status: current public_route: /gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28/ source_authority: local source, generated bundle, focused Rust tests, and browser smoke ## Route Summary Generated selector entries and served `.module-plan.receipt` files now bind each model's validated context token limit before generated model bytes load. ## Implemented Shape - `ValidationReport::context_token_limit()` exposes the validated `.slm` header `max_context`. - `module_plan_context_token_limit` is emitted in generated selector registries and `.module-plan.receipt` files. - Selector validation requires the context token limit to be positive, no more than `4096`, and equal to the admitted model shape's `context=` or `ctx=` field. - Browser registry intake parses the model shape context, carries it on the selected model entry, and requires the selector module plan to match it. - Browser receipt validation rechecks the served receipt against selector metadata, the model entry, and `max_tokens`. - The Module Plan panel renders `Context` as `16 tokens`. - `module-plan-context-token-drift` mutates only the receipt context field while refreshing the selector checksum, then proves browser validation stops before generated `.slm`, manifest, assembly, adapter-family, or stack routes. ## Verified Evidence - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-slm-pack selector::tests::rejects_module_plan_context_token_limit_drift` - `cargo test -p tinyrustlm-slm-pack browser_bundle::tests::` - `cargo test -p tinyrustlm-browser-harness` - `cargo run -p tinyrustlm-browser-harness -- .\tinyrustlm` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-context-token\tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8103/app/ 19590 multi-parent-sign-merge-q4 combined-selector-assembly` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8103/app/ 19591 multi-parent-sign-merge-q4 module-plan-context-token-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8103/app/ 19592 multi-parent-sign-merge-q4 module-plan-kv-cache-drift` ## Current Generated Values - Context: `16 tokens` for generated q4_0, q8_0, and f32 entries. - q4_0 Total Budget: `103784 bytes` - q8_0 Total Budget: `106024 bytes` - f32 Total Budget: `117558 bytes` - q4_0 Module Checksums: `0: 0x1a6808e3098d1ce0, 1: 0x054f22afda830bf2, 2: 0xe7f7464613e7d1fb, 3: 0x6aa2cfa5d379a3ff, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6, 6: 0xcaf46ccfc262fad2` ## Next Route Use this report before changing context-window sizing, tokenizer context limits, selector shape parsing, Module Plan panel resource rows, or browser receipt validation for generated self-assembly. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-count-drift-memory-2026-06-28.md BYTES: 2367 SHA256: B1FD636C15E3EE71C679B012CD00CF7C81FAB355823A91FA8239EEBF167D629F ================================================================================ --- title: Browser Module Plan Count Drift Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-module-plan-count-drift-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T20:20:00Z --- # Browser Module Plan Count Drift Memory ## Summary `module-plan-count-drift` is now a served-browser proof for selector-to-receipt module cardinality. The smoke mutates only the served `.module-plan.receipt` `module_count` field, refreshes the selector registry module-plan checksum to keep the route internally consistent, and requires the browser to reject with `Module plan module count mismatch` before any generated `.slm`, adapter-family receipt, adapter manifest, or stack artifact route is fetched. ## Implementation Route - `tinyrustlm/tools/browser-smoke.js` adds `driftModulePlanCount(receiptText)` to lower `module_count` by one while preserving checksum-consistent selector routing. - `installModulePlanCountDriftInterceptor(client, modelKey)` reuses the shared module-plan drift interceptor so `selector.registry` points at the drifted receipt checksum. - `assertModulePlanCountDriftSmoke(result, modelKey, networkRequests)` verifies the error state and confirms only the selector registry plus module-plan receipt routes are requested. - `tinyrustlm/README.md`, `tinyrustlm/docs/testing.md`, and `.uai/test-plan.uai` route the new smoke mode for future work. ## Verification - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo test -p tinyrustlm-browser-harness` with 6 tests passed. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/module-plan-count-drift/tinyrustlm all` - `cargo run -p tinyrustlm-local-server -- target/module-plan-count-drift/tinyrustlm 8193` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8193/app/ 9298 multi-parent-sign-merge-q4 module-plan-count-drift` The browser smoke returned `Model load failed`, `fetch error`, and `Module plan module count mismatch`. The network trace stopped at `/models/selector.registry` and `/models/multi-parent-sign-merge-q4.module-plan.receipt`. ## Disk Cleanup Note Before verification, project-safe cleanup removed the active repo `target/` tree and recoverable Visual Studio `.vs` cache content where files were not open. `E:\` finished this bead with about 67.8 GiB free after the focused rebuild. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-count-drift-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-dependencies-memory-2026-06-27.md BYTES: 2563 SHA256: 3110A860EDE9CFA733FA59E1FBC280BE4B3856135FDC7A8B5E3031041E29CDC5 ================================================================================ # Browser Module Plan Dependencies Memory - 2026-06-27 ## Summary Browser module-plan receipts now carry `module.N.depends_on` fields. The generated browser bundle writes a small dependency chain from runtime WASM through the model, manifest, assembly receipt, adapter-family receipt, and ordered adapter stack; the browser verifies those edges before fetching generated `.slm` bytes or stack artifacts. ## Implementation Notes - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `module.N.depends_on` beside each module kind, role, assembly slot, route, and checksum. - `tinyrustlm/app/app.js` validates exact dependency edges during module-plan verification: module 0 depends on `runtime-wasm`, then each later module depends on the previous `module.N`. - `tinyrustlm/app/index.html` adds a Module Plan `Depends` row, and `app.js` renders the ordered dependency summary only from verified receipt fields. - `tinyrustlm/tools/browser-smoke.js` asserts generated q4 dependency display, source-root fallback `unavailable`, and `module-plan-dependency-drift` behavior. - `tinyrustlm/tools/browser_harness/src/main.rs` treats `modulePlanDepends` as part of the static app contract. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-slm-pack browser_bundle::` - `cargo test -p tinyrustlm-browser-harness` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-dependencies/tinyrustlm all` - Generated-root browser smoke on `http://127.0.0.1:18724/app/` for `multi-parent-sign-merge-q4 adapter-sidecar-registry-file` showed `0: runtime-wasm, 1: module.0, 2: module.1, 3: module.2, 4: module.3, 5: module.4`. - Generated-root browser smoke on `http://127.0.0.1:18724/app/` for `multi-parent-sign-merge-q4 module-plan-dependency-drift` stopped at the receipt with `Module plan field module.4.depends_on was module.2` and requested no generated q4 `.slm`, ADP1, ASP1, or adapter-manifest route. - Source-root `ui-audit` on `http://127.0.0.1:18726/app/` proved Module Plan dependency fallback is `unavailable` on desktop and mobile. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` - `cargo test --workspace` ## Routing Open this report before changing module-plan `depends_on` field names, dependency display, `module-plan-dependency-drift`, or pre-model-fetch generated plan verification. Pair it with the role, slot, graph, and stack reports when changing planner-readable module semantics. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-dependencies-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-display-memory-2026-06-27.md BYTES: 3094 SHA256: A108B5BF2942B9B5BA3906FE2877FA97729E0AD8BD031D20D301156221123D24 ================================================================================ --- title: Browser Module Plan Display Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-display-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T20:48:35Z --- # Browser Module Plan Display Memory ## Routing Summary Use this report when work touches the browser Module Plan panel, verified `.module-plan.receipt` display fields, generated adapter stack route display, or smoke assertions that receipt metadata is visible without parsing model or adapter bytes. ## Implementation - `tinyrustlm/app/index.html` adds a Module Plan evidence panel with status, kind, resource class, module count, model route, and stack summary fields. - `tinyrustlm/app/app.js` stores the verified module-plan receipt fields after checksum/resource/graph/stack validation and renders only those line-based receipt fields. Checked fallback models render `none` and `unavailable` values. - The rendered stack summary reads the receipt-declared `adapter_auto_apply_stack_count` plus the stack member `module.K.adapter_path` fields, matching the same generated family ADP1 plus sparse ASP1 routes already verified before model load. - `tinyrustlm/tools/browser-smoke.js` now captures and asserts Module Plan panel fields in source-root UI audit and generated-root `adapter-sidecar-registry-file` smoke. - `tinyrustlm/tools/browser_harness/src/main.rs` treats the Module Plan ids and heading as part of the static app contract. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18706/app/ 19538 tinylm16q8 ui-audit` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-display/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18708/app/ 19540 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-browser-harness` - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` - `cargo test --workspace` - `git diff --check` The source-root desktop/mobile UI audit showed the new panel and verified fallback state `modulePlanState=none` with unavailable fields for the checked q8_0 model. The generated q4 registry-file smoke showed `modulePlanState=loaded`, `modulePlanKind=browser-local-module-plan`, `modulePlanResource=browser-constrained-local-assembly`, `modulePlanModules=6`, `modulePlanModel=../models/multi-parent-sign-merge-q4.slm`, and stack display `2: ../models/multi-parent-sign-merge-q4-family.adp1, ../models/multi-parent-sign-merge-q4-sparse.asp1`. Workspace tests passed with 249 checks, the diff check emitted line-ending notes only, temporary browser profiles were removed, and the source/generated local-server ports were clear. ## Next Routing The next constrained-browser bead can use the displayed receipt graph as a stable user-facing route for richer module assembly state, while keeping JavaScript on line-based metadata and Rust on model and adapter payload validation. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-display-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28.md BYTES: 3717 SHA256: A3F8F48E00AE929E231D0007434C72949AE1BC0FA228F27628FD8392CF5726C6 ================================================================================ --- title: Browser Module Plan Execution Profile Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T11:45:00Z --- # Browser Module Plan Execution Profile Memory ## Summary TinyRustLM generated module plans now bind the browser execution topology before generated model fetch. Selector registry entries and served `.module-plan.receipt` files carry `module_plan_execution_profile=single-threaded-wasm-local-v1`; Rust selector validation, browser registry intake, and browser receipt validation all require that exact value. ## Implementation - `tinyrustlm/tools/slm_pack/src/selector.rs` adds `MODULE_PLAN_EXECUTION_PROFILE`, writes `entry.N.module_plan_execution_profile`, parses it back, and rejects execution-profile drift. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `module_plan_execution_profile=single-threaded-wasm-local-v1` into every generated `.module-plan.receipt` and returns the same value to selector registry generation. - `tinyrustlm/app/app.js` requires the registry execution profile and receipt execution profile to match before any generated `.slm` fetch. - `tinyrustlm/app/index.html` and `tinyrustlm/tools/browser-smoke.js` render and assert a verified `Execution` row in the Module Plan panel. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-execution-profile-drift`, which mutates only the served receipt execution profile while updating the selector registry checksum. ## Verification Passed on 2026-06-28: - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack module_plan` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/module-plan-execution-profile-drift/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18764/app/ 19647 multi-parent-sign-merge-q4 module-plan-execution-profile-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18764/app/ 19649 multi-parent-sign-merge-q4 combined-selector-assembly` The drift smoke requested only the app shell, runtime files, selector registry, and q4 module-plan receipt, then stopped with `Module plan field module_plan_execution_profile was worker-pooled-wasm-v1`. It did not request the generated `.slm` route or any adapter-family, adapter-manifest, ADP1, ASP1, or ALR1 stack artifact route. The positive smoke walked q4_0, q8_0, and f32 entries from one generated root and rendered `single-threaded-wasm-local-v1` in the Module Plan `Execution` row for every entry while reaching the ready trace after ADP1 plus ASP1 plus ALR1 stack validation and apply. ## Routing Load this report when work touches browser execution topology, module-plan profile fields, generated selector/receipt execution metadata, Module Plan execution display, or `module-plan-execution-profile-drift`. Related routes: - `wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-module-plan-resource-memory-2026-06-27.md` - `wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28.md BYTES: 3818 SHA256: A41A205E9F2AE73D45A702FDFC3FF2BAA2B589D0056D4157F07D593B5BA4F1B9 ================================================================================ --- title: Browser Module Plan Fetch Count Memory 2026-06-28 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T23:59:00Z --- # Browser Module Plan Fetch Count Memory This record routes the browser module-plan fetch-count envelope added on 2026-06-28. ## Implementation Summary - Generated selector registry entries now carry `entry.N.module_plan_fetch_count_limit=32`. - Served `.module-plan.receipt` files now carry `module_plan_fetch_count_limit=32`. - Rust selector validation requires selector and receipt agreement, rejects missing fetch-count limit fields, and requires `module_count + 1` to fit the declared route-count envelope. - Browser registry intake computes the planned generated-root route count from module-plan modules, assembly evidence routes, and adapter manifests before generated model bytes are fetched. - Browser smoke now counts the actual generated self-assembly requests owned by each q4_0, q8_0, and f32 module-plan model key. - The actual-count assertion treats `/models/{model}...` and `/evidence/{model}/...` as governed requests, expects 21 requests per generated assembly pass, and keeps each pass under the 32-fetch envelope. - Browser receipt validation requires the same value and renders `Fetch Limit` as `32 fetches` in the Module Plan panel. - `module-plan-fetch-count-drift` mutates the served receipt limit while refreshing selector checksum routing, proving the browser stops at module-plan validation. ## Current Budget Values - Fetch count limit: `32 fetches`. - q4_0 total budget: `173415 bytes`. - q8_0 total budget: `175655 bytes`. - f32 total budget: `187189 bytes`. - Total byte budget limit: `43454464 bytes`. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack fetch_count_limit` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack writes_and_validates_selector_registry_with_module_plan_receipt` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack writes_combined_browser_multi_parent_bundle` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack writes_quantized_browser_multi_parent_bundles` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\module-plan-fetch-count-drift\tinyrustlm all` - Generated-root `combined-selector-assembly` proved q4_0, q8_0, and f32 render `Fetch Limit` as `32 fetches`. - Generated-root `module-plan-fetch-count-drift` proved drift stops after selector plus module-plan receipt fetch, before generated model, assembly evidence, adapter-family, manifest, or stack artifact routes. - Source-root `ui-audit` proved non-generated roots keep Module Plan fetch limit fallback as `unavailable`. - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\module-plan-actual-fetch-count\tinyrustlm all` - Generated-root `combined-selector-cycle` on `target\module-plan-actual-fetch-count\tinyrustlm` proved two q4_0/q8_0/f32 passes with 21 governed requests per model pass. - Generated-root `combined-selector-reload-soak` on `target\module-plan-actual-fetch-count\tinyrustlm` proved two fresh page lifetimes with 21 governed requests per model pass. ## Routing Rule Open this page before changing generated self-assembly route counts, actual generated request accounting, selector `module_plan_fetch_count_limit`, served `.module-plan.receipt` fetch-count fields, Module Plan `Fetch Limit` display, or fetch-count smoke assertions. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28.md BYTES: 3762 SHA256: D372F255D5365898585F8908903B67996A7D962529995926B7D27783F754C25D ================================================================================ --- title: Browser Module Plan Fetch Policy Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T12:25:00Z --- # Browser Module Plan Fetch Policy Memory ## Summary TinyRustLM generated module plans now bind browser-local fetch behavior before generated model fetch. Selector registry entries and served `.module-plan.receipt` files carry `module_plan_fetch_policy=local-no-store-v1`; Rust selector validation, browser registry intake, and browser receipt validation all require that exact value. ## Implementation - `tinyrustlm/tools/slm_pack/src/selector.rs` adds `MODULE_PLAN_FETCH_POLICY`, writes `entry.N.module_plan_fetch_policy`, parses it back, and rejects fetch-policy drift. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `module_plan_fetch_policy=local-no-store-v1` into every generated `.module-plan.receipt` and returns the same value to selector registry generation. - `tinyrustlm/app/app.js` requires the registry fetch policy and receipt fetch policy to match before any generated `.slm` fetch. - `tinyrustlm/app/index.html` and `tinyrustlm/tools/browser-smoke.js` render and assert a verified `Fetch` row in the Module Plan panel. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-fetch-policy-drift`, which mutates only the served receipt fetch policy while updating the selector registry checksum. ## Verification Passed on 2026-06-28: - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack module_plan` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/module-plan-fetch-policy-drift/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18766/app/ 19651 multi-parent-sign-merge-q4 module-plan-fetch-policy-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18766/app/ 19652 multi-parent-sign-merge-q4 combined-selector-assembly` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18766/app/ 19653 multi-parent-sign-merge-q4 module-plan-execution-profile-drift` The fetch-policy drift smoke requested only the app shell, runtime files, selector registry, and q4 module-plan receipt, then stopped with `Module plan field module_plan_fetch_policy was cache-default-v1`. It did not request the generated `.slm` route or any adapter-family, adapter-manifest, ADP1, ASP1, or ALR1 stack artifact route. The positive smoke walked q4_0, q8_0, and f32 entries from one generated root and rendered `local-no-store-v1` in the Module Plan `Fetch` row for every entry while reaching the ready trace after ADP1 plus ASP1 plus ALR1 stack validation and apply. ## Routing Load this report when work touches browser-local fetch policy, generated selector/receipt fetch metadata, Module Plan fetch display, request-log scoping for module-plan drift smokes, or `module-plan-fetch-policy-drift`. Related routes: - `wiki/gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-graph-drift-memory-2026-06-27.md BYTES: 2479 SHA256: 9672865125017B6B68D563A126831042B7C3D63E856FDA7474AA1352ABEC975C ================================================================================ --- title: Browser Module Plan Graph Drift Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-graph-drift-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T20:20:05Z --- # Browser Module Plan Graph Drift Memory ## Routing Summary Use this report when work touches browser-smoke `module-plan-graph-drift`, generated `.module-plan.receipt` graph metadata, checksum-consistent route drift, or proof that generated `.slm` bytes are not fetched after module-plan graph mismatch. ## Implementation - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-graph-drift` mode for generated multi-parent selector roots. - The smoke intercepts the served selector registry and selected `.module-plan.receipt`, changes only the receipt `module.0.path` model graph line, recomputes the receipt checksum with the browser checksum algorithm, and patches only the matching `entry.N.module_plan_checksum`. - The resource envelope and selector metadata remain aligned, so the browser proves the graph gate itself: checksum verification and budget checks pass, then `app.js` rejects the route mismatch before generated `.slm` fetch. - The smoke asserts the browser stays local-origin, reports `Model load failed` with `Module plan field module.0.path was ...`, keeps model selection recoverable, and never requests `/models/multi-parent-sign-merge-q4.slm`. ## Verification - `node --check tinyrustlm/tools/browser-smoke.js` - `node --check tinyrustlm/app/app.js` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-graph-drift/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18702/app/ 19534 multi-parent-sign-merge-q4 module-plan-graph-drift` - `cargo fmt --all -- --check` - `cargo test --workspace` The live generated-root q4 graph drift smoke requested `/models/selector.registry` and `/models/multi-parent-sign-merge-q4.module-plan.receipt`, surfaced `Module plan field module.0.path was ../models/multi-parent-sign-merge-q4-graph-drift.slm`, left generation controls stopped with model selection still available, and did not request `/models/multi-parent-sign-merge-q4.slm`. Workspace tests passed with 249 checks. ## Next Routing The sibling stack-member proof now lives in `browser-module-plan-stack-drift-memory-2026-06-27.md`. The next useful route is positive module-plan stack display without JavaScript model or adapter payload parsing. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-graph-drift-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28.md BYTES: 3848 SHA256: C6057779C984870809BFEE50032CFC095466971544A7AE78EF8863957AFAA8F2 ================================================================================ --- title: Browser Module Plan KV Cache Memory 2026-06-28 public_route: /gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28/ status: current authority: implementation-report --- # Browser Module Plan KV Cache Memory ## Routing Summary Generated browser module plans now bind the KV-cache memory envelope before generated model bytes are fetched. Open `tinyrustlm/tools/slm_pack/src/selector.rs`, `tinyrustlm/tools/slm_pack/src/browser_bundle.rs`, `tinyrustlm/tools/slm_pack/src/slm_validate.rs`, `tinyrustlm/runtime/src/kv_cache.rs`, `tinyrustlm/runtime/src/diagnostics.rs`, `tinyrustlm/runtime/src/generate.rs`, `tinyrustlm/app/app.js`, and `tinyrustlm/tools/browser-smoke.js` when KV-cache byte budget, page count, or browser module-plan total budget changes are in scope. ## Implemented Shape - `KvCache` reports its exact byte budget and 64 KiB page count from layer count, max context, KV head count, and head dimension. - Runtime diagnostics expose `kv_cache_byte_budget` and `kv_cache_page_count`, record them after model load, and clear them on load failure or `free_model`. - `ValidationReport` computes the same KV-cache byte budget and page count from validated `.slm` shape metadata. - Generated `selector.registry` entries and served `.module-plan.receipt` files emit `module_plan_kv_cache_byte_budget` and `module_plan_kv_cache_page_count`. - Browser receipt validation checks selector and receipt KV-cache fields before generated `.slm` or stack artifact routes are fetched. - The Module Plan panel renders verified `KV Budget` and `KV Pages` rows. - The total self-assembly cap is now `43384832` bytes because it includes the 8 MiB KV-cache cap beside model, adapter, text-sidecar, runtime scratch, and WASM memory caps. ## Browser Proof - Normal generated-root smoke verifies `KV Budget` as `1024 bytes` and `KV Pages` as `1` for q4_0, q8_0, and f32 tiny generated entries. - Exact generated Module Plan total budgets are `103780 bytes` for q4_0, `106020 bytes` for q8_0, and `117554 bytes` for f32. - `module-plan-kv-cache-drift` mutates the served KV page count while refreshing receipt and selector checksums, then proves browser validation stops at the module-plan receipt. - `module-plan-total-budget-drift` and `module-plan-total-limit-drift` were rerun after the KV-cache envelope became part of the total budget math. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-runtime -- --nocapture` with 82 tests - `cargo test -p tinyrustlm-slm-pack selector -- --nocapture` with 56 selector-filtered tests - `cargo test -p tinyrustlm-slm-pack slm_validate -- --nocapture` with 6 tests - `cargo test -p tinyrustlm-slm-pack browser_bundle -- --nocapture` with 4 tests - `cargo test -p tinyrustlm-browser-harness` with 6 tests - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` with 9 static checks - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle ..\target\browser-served-kv-cache\tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8101/app/ 19604 multi-parent-sign-merge-q4 combined-selector-assembly` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8101/app/ 19601 multi-parent-sign-merge-q4 module-plan-kv-cache-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8101/app/ 19602 multi-parent-sign-merge-q4 module-plan-total-budget-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8101/app/ 19603 multi-parent-sign-merge-q4 module-plan-total-limit-drift` ## Next Routing Use this report before claiming paged KV-cache, prefix-cache, radix-cache, or longer-context memory behavior. Those lanes should first become typed receipts, diagnostics, and browser-smoke assertions instead of public copy. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-memory-2026-06-27.md BYTES: 2756 SHA256: 3D7E2CA642E29DCBFC51F6C2FD95626BDABD298CD627C5885E032EEA03657CC9 ================================================================================ --- title: Browser Module Plan Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T19:03:56Z --- # Browser Module Plan Memory ## Routing Summary Use this report when work touches generated selector registry module-plan fields, browser self-assembly order, generated bundle staging, or `adapter-sidecar-registry-file` smoke coverage. It records the first browser-verified module graph receipt for TinyRustLM generated bundles. ## Implementation - `tinyrustlm/tools/slm_pack/src/selector.rs` now carries `entry.N.module_plan_*` fields through registry generation and validation, and rejects module-count drift against model, manifest, receipts, and adapter stack members. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` now writes served `.module-plan.receipt` files for generated f32/q8_0/q4_0 roots and the combined `all` root. - `tinyrustlm/app/app.js` fetches and checksum-verifies a declared module plan before fetching generated `.slm` bytes, then matches model, manifest, assembly receipt, adapter-family receipt, and stack members against selector metadata. - `tinyrustlm/tools/browser-smoke.js` requires generated roots to request the module-plan route during `adapter-sidecar-registry-file` smoke. - `tinyrustlm/tools/browser_harness/src/main.rs` checks the static browser host for the module-plan strategy marker. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-slm-pack selector::` - `cargo test -p tinyrustlm-slm-pack browser_bundle::` - `cargo test -p tinyrustlm-browser-harness` - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18696/app/ 19526 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` - `cargo test --workspace` - `git diff --check` The live generated-root q4 smoke network trace requested `/models/multi-parent-sign-merge-q4.module-plan.receipt` before `/models/multi-parent-sign-merge-q4.slm`, then fetched the assembly receipt, evidence files, adapter-family receipt, generated adapter manifests, family ADP1, and sparse ASP1. The pre-generation console recorded two `apply_adapter_delta` calls followed by `adapter_stack_applied(2)`. ## Next Routing The next useful modular bead is plan variation: module plans can later carry resource classes, purpose labels, planner-selected candidates, or alternative stack recipes while keeping this browser path local, receipt-bound, and Rust-validated. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-model-release-memory-2026-06-29.md BYTES: 2971 SHA256: 0B5FE7AF325DD0C42DB9142C218A7385E0FF42C51ECCD37D4A3DCD3E18F5D13E ================================================================================ # Browser Module Plan Model Release Memory - 2026-06-29 status: reviewed_current authority: generated from current implementation and verification evidence ## Summary Generated module-plan selector entries and served `.module-plan.receipt` files now bind `module_plan_model_release_strategy=free-before-reassembly-v1`. The browser verifies selector and receipt agreement, renders the verified Module Plan `Release` row, and keeps same-page generated q4_0/q8_0/f32 switching tied to the existing `free_model` release-before-reassembly behavior. ## Implementation Route - `tinyrustlm/tools/slm_pack/src/selector.rs` writes, parses, checksums, and validates `entry.N.module_plan_model_release_strategy`. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `module_plan_model_release_strategy=free-before-reassembly-v1` into generated `.module-plan.receipt` files and selector route records. - `tinyrustlm/app/index.html` adds the Module Plan `Release` row. - `tinyrustlm/app/app.js` validates selector and receipt agreement, requires `free-before-reassembly-v1`, and renders the verified field only after receipt acceptance. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-model-release-drift`, asserts generated roots render `free-before-reassembly-v1`, and asserts source roots render `unavailable`. - `tinyrustlm/tools/browser_harness/src/main.rs` includes the new row id in the static contract. ## Verified Behavior - Node syntax checks passed for `tinyrustlm/app/app.js` and `tinyrustlm/tools/browser-smoke.js`. - `cargo fmt --all -- --check` passed. - `cargo test -p tinyrustlm-slm-pack selector` passed with 72 tests. - `cargo test -p tinyrustlm-slm-pack browser_bundle` passed with 4 tests. - `cargo test -p tinyrustlm-browser-harness` passed with 6 tests. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` passed with 9 static checks. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\module-plan-model-release\tinyrustlm all` passed and validated 3 module-plan routes. - Generated-root `module-plan-model-release-drift` passed on `http://127.0.0.1:8233/app/`, returning `Module plan model release strategy mismatch` after selector plus module-plan receipt requests and before generated model routes. - Generated-root `combined-selector-cycle` passed on `http://127.0.0.1:8233/app/`, proving q4_0/q8_0/f32 generated assemblies render `Release` as `free-before-reassembly-v1` while `free_model` runs before post-initial assemblies. - Source-root `ui-audit` passed on `http://127.0.0.1:8234/app/`, proving the fallback row remains `unavailable`. ## Routing Notes Open this report before changing generated model-switch release sequencing, selector registry module-plan release metadata, Module Plan `Release` display, or `module-plan-model-release-drift` smoke assertions. Keep this field separate from WASM byte transfer: it records loaded-model lifetime discipline during reassembly, not byte copy mechanics. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-model-release-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-observed-route-set-memory-2026-06-29.md BYTES: 2925 SHA256: 6B2E9249BE13582A0DF8AD1C59AAF83DA73B77913A5D1429D1BCE59B1428AB11 ================================================================================ --- title: Browser Module Plan Observed Route Set Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-observed-route-set-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T11:10:00Z --- # Browser Module Plan Observed Route Set Memory TinyRustLM generated self-assembly now records the browser-observed route set. Each accepted generated fetch appends its route kind and path to the in-page route list, and generated Ready requires the observed route-set checksum to match the declared `module_plan_route_set_checksum`. ## What Changed - `tinyrustlm/app/index.html` adds the Module Plan `Actual Route Set` row. - `tinyrustlm/app/app.js` records `{ kind, path }` for every accepted generated module-plan fetch, computes the observed route-set checksum with the same route-set checksum preimage as the selector and receipt, renders the row, and rejects Ready when the observed route set differs from the declared route set. - `tinyrustlm/tools/browser-smoke.js` captures `modulePlanActualRouteSetChecksum`, requires it to equal `modulePlanRouteSetChecksum` for generated q4_0/q8_0/f32 assemblies, and keeps source-root fallback at `unavailable`. ## Browser Contract The observed route set uses the same ordered route classes declared by the module plan: - `module-plan-receipt` - `model` - `model-manifest` - `assembly-receipt` - `assembly-evidence` - `adapter-family-receipt` - `adapter-manifest` - `adapter-stack-artifact` The row shows an in-flight `N/21 routes` summary until all planned routes are observed. At readiness, it shows the checksum and that checksum must equal `module_plan_route_set_checksum`. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `git diff --check` - `cargo run --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml -- tinyrustlm` - Generated `target/module-plan-observed-route-set-20260629/tinyrustlm all`. - Generated `combined-selector-assembly` on `http://127.0.0.1:18762/app/` proved q4_0, q8_0, and f32 all reached `Ready`, generated response `e`, applied the three-adapter stack, displayed `Plan Fetches 21 fetches`, displayed `Actual Fetches 21 fetches`, and displayed observed route-set checksums equal to the declared route-set checksums: - q4_0 `0xe7d8c862dec256cb` - q8_0 `0xc6215c5348cef337` - f32 `0x5317f0a7a894574c` - Source `ui-audit` on `http://127.0.0.1:18763/app/` proved desktop and mobile fallback snapshots keep `Actual Route Set`, `Actual Fetches`, and `Plan Fetches` at `unavailable`. - No local server or browser debug listener remained open after the smoke runs. ## Routing Open this report before changing generated fetch route kinds, counted fetch wrappers, Module Plan `Actual Route Set` display, route-set checksum preimages, or generated Ready gating for observed routes. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-observed-route-set-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md BYTES: 5602 SHA256: E470B5CFC80EBEDE1B14CD9981C59CBC3F6EC09CD0ED6E571B8E7881E1FDA4EC ================================================================================ --- title: Browser Module Plan Operator Receipt Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T10:45:00Z --- # Browser Module Plan Operator Receipt Memory TinyRustLM generated module plans now carry the sign-merge operator receipt route and checksum beside the assembly route set, so the browser can bind selector registry, module-plan receipt, assembly receipt, and evidence-file identity before generated model bytes are trusted. ## What Changed - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `operator_receipt_path` and `operator_receipt_checksum` into each generated `.module-plan.receipt`, mirrors them as `entry.N.module_plan_operator_receipt_*` selector fields, and tests the values against the generated `sign-merge.operator` checksum. - `tinyrustlm/tools/slm_pack/src/selector.rs` parses and validates the module-plan operator receipt fields, requires the canonical `../evidence/{candidate_id}/sign-merge.operator` route, requires a hex64 checksum, and rejects selector/module-plan checksum drift against admitted operator receipt identity. - `tinyrustlm/app/app.js` validates registry module-plan operator fields, verifies served `.module-plan.receipt` agreement, and checks generated assembly receipts agree with the same operator receipt route/checksum before evidence files or adapter-family routes proceed. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-operator-receipt-drift`, refreshes generated module-plan byte/checksum constants, proves checksum-consistent receipt drift stops after selector registry plus module-plan receipt, and lets fresh combined generated roots prove module-plan summary shape without pinning regenerated receipt checksums. ## Browser Contract The generated q4_0, q8_0, and f32 bundle roots now require this identity chain: 1. selector registry `entry.N.module_plan_operator_receipt_path` 2. selector registry `entry.N.module_plan_operator_receipt_checksum` 3. served `.module-plan.receipt` `operator_receipt_path` 4. served `.module-plan.receipt` `operator_receipt_checksum` 5. generated `.assembly.receipt` `operator_receipt_path` 6. generated `.assembly.receipt` `operator_receipt_checksum` 7. fetched `../evidence/{candidate_id}/sign-merge.operator` body checksum The fields bind the module-plan envelope to the already receipt-bound sign-merge operator lane without adding any network or third-party dependency. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml module_plan_operator -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml selector::tests:: -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml` - `C:\Users\AI\.cargo\bin\cargo.exe test --workspace` - `C:\Users\AI\.cargo\bin\cargo.exe run --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml -- tinyrustlm` - Generated `target/module-plan-operator-receipt-drift-20260629/tinyrustlm all`. - Served generated root on `http://127.0.0.1:18731/app/`. - `module-plan-operator-receipt-drift` for `multi-parent-sign-merge-q4` stopped at `module plan operator receipt checksum mismatch` after requesting only app shell, runtime manifest/WASM, selector registry, and the q4 module-plan receipt. - Served generated root on `http://127.0.0.1:18734/app/`. - `adapter-sidecar-registry-file` for `multi-parent-sign-merge-q4` loaded the module plan, verified assembly evidence including `sign-merge.operator`, fetched adapter-family and stack manifests, validated three stack artifacts in Rust, applied all three, and generated `e`. - Generated fresh root `target/combined-selector-assembly-refresh-20260629/tinyrustlm all`. - Served fresh generated root on `http://127.0.0.1:18751/app/`. - `combined-selector-assembly` proved q4_0 default selection, q4_0/q8_0/f32 same-page switching, module-plan-before-model fetch ordering, operator receipt agreement, ADP1 plus ASP1 plus ALR1 stack validation/application, `adapter_apply_count=3`, and generated response `e` for every entry. - `git diff --check` ## Current Generated Module-Plan Values - Operator receipt checksums: q4_0 `0x1b388cfa4d204a83`, q8_0 `0xbc40437e9d767cf0`, f32 `0x921cb1168ec2821e`. - Total budgets after operator receipt binding: q4_0 `173429 bytes`, q8_0 `175669 bytes`, f32 `187203 bytes`. - q4_0 checksums: `0: 0x1a6808e3098d1ce0, 1: 0x329cad8f407f1193, 2: 0x61c5be47683f6978, 3: 0xc09d91cb22b9e098, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6, 6: 0xcaf46ccfc262fad2`. - q8_0 checksums: `0: 0x0132bc82d5a0d7d6, 1: 0x236fd027242c32af, 2: 0x5a2e2f77c75e1b1a, 3: 0xb3f1a7cdbb4fb1a9, 4: 0x8194a8a671285019, 5: 0x6fa5d29bee9b7cfb, 6: 0x1ed9d08142edfda9`. - f32 checksums: `0: 0x8a0e6c4c01998199, 1: 0xf4f55c7e082a43a0, 2: 0x9f72fd36ac75d0b5, 3: 0xb7e3756e8c25004e, 4: 0xe9669ade4571fd42, 5: 0x34008cedc028ed5c, 6: 0x1c64143141c223b5`. ## Routing Open this report before changing generated module-plan operator receipt fields, selector `module_plan_operator_receipt_*` validation, assembly receipt/operator receipt agreement, or `module-plan-operator-receipt-drift` browser smoke assertions. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28.md BYTES: 4876 SHA256: 34F5A9125DEF78DAB20F0E22413C4D1B8577AB02324FF9A455B9FE04B10C1215 ================================================================================ --- title: Browser Module Plan Origin Policy Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T09:33:21Z --- # Browser Module Plan Origin Policy Memory ## Summary TinyRustLM generated module plans now bind the browser origin boundary before generated model fetch. Selector registry entries and served `.module-plan.receipt` files carry `module_plan_origin_policy=same-origin-loopback-local-v1`; Rust selector validation, browser registry intake, and browser receipt validation all require that exact value. ## Implementation - `tinyrustlm/tools/slm_pack/src/selector.rs` adds `MODULE_PLAN_ORIGIN_POLICY`, writes `entry.N.module_plan_origin_policy`, parses it back, and rejects origin-policy drift. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `module_plan_origin_policy=same-origin-loopback-local-v1` into every generated `.module-plan.receipt` and returns the same value to selector registry generation. - `tinyrustlm/app/app.js` requires the registry origin policy and receipt origin policy to match before any generated `.slm` fetch. - `tinyrustlm/app/index.html`, `tinyrustlm/tools/browser_harness/src/main.rs`, and `tinyrustlm/tools/browser-smoke.js` render and assert a verified `Origin` row in the Module Plan panel. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-origin-policy-drift`, which mutates only the served receipt origin policy while updating the selector registry checksum. ## Verification Passed on 2026-06-28: - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack module_plan` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/module-plan-origin-policy-drift/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18768/app/ 19602 multi-parent-sign-merge-q4 module-plan-origin-policy-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18768/app/ 19600 multi-parent-sign-merge-q4 module-plan-fetch-policy-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18768/app/ 19596 multi-parent-sign-merge-q4 combined-selector-assembly` The origin-policy drift smoke requested only the app shell, runtime files, selector registry, and q4 module-plan receipt, then stopped with `Module plan field module_plan_origin_policy was cross-origin-network-v1`. It did not request the generated `.slm` route or any adapter-family, adapter-manifest, ADP1, ASP1, or ALR1 stack artifact route. The positive smoke walked q4_0, q8_0, and f32 entries from one generated root and rendered `same-origin-loopback-local-v1` in the Module Plan `Origin` row for every entry while reaching the ready trace after ADP1 plus ASP1 plus ALR1 stack validation and apply. Current generated module summaries: - q4_0 bytes: `0: 6592 bytes, 1: 594 bytes, 2: 1896 bytes, 3: 5421 bytes, 4: 20224 bytes, 5: 832 bytes, 6: 832 bytes` - q4_0 checksums: `0: 0x1a6808e3098d1ce0, 1: 0x1d6776f86916e40f, 2: 0x456db16712644b6a, 3: 0x643a529184698ac0, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6, 6: 0x199a2b73d817476a` - q8_0 bytes: `0: 8832 bytes, 1: 594 bytes, 2: 1896 bytes, 3: 5421 bytes, 4: 20224 bytes, 5: 832 bytes, 6: 832 bytes` - q8_0 checksums: `0: 0x0132bc82d5a0d7d6, 1: 0x618fd5697e2738ff, 2: 0xbd079b6e8af29ecf, 3: 0x0ffad515fff41062, 4: 0x8194a8a671285019, 5: 0x6fa5d29bee9b7cfb, 6: 0x3f8c127d335dcd96` - f32 bytes: `0: 20352 bytes, 1: 595 bytes, 2: 1909 bytes, 3: 5421 bytes, 4: 20224 bytes, 5: 832 bytes, 6: 832 bytes` - f32 checksums: `0: 0x8a0e6c4c01998199, 1: 0xe9f713cf1da24e64, 2: 0x7bbb3881da0d0f75, 3: 0x7d2ecba475101b8a, 4: 0xe9669ade4571fd42, 5: 0x34008cedc028ed5c, 6: 0xbddf0c5c088bce18` ## Routing Load this report when work touches browser-local origin policy, generated selector/receipt origin metadata, Module Plan origin display, same-origin module-plan drift assertions, or `module-plan-origin-policy-drift`. Related routes: - `wiki/gguf-mirust/reports/browser-module-plan-fetch-policy-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-module-plan-execution-profile-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-output-limit-memory-2026-06-28.md BYTES: 4292 SHA256: 1FCF532A72DDE97F67D7324452E35B8F2A077B4D89E202D7887F241AE2E667C7 ================================================================================ --- title: Browser Module Plan Output Limit Memory 2026-06-28 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-output-limit-memory-2026-06-28/ status: reviewed reviewed_utc: 2026-06-28T22:11:44Z --- # Browser Module Plan Output Limit Memory ## Routing Summary Generated browser module plans now carry `module_plan_output_byte_limit=65536` beside the runtime scratch and KV-cache envelopes. Open `tinyrustlm/tools/slm_pack/src/selector.rs`, `tinyrustlm/tools/slm_pack/src/browser_bundle.rs`, `tinyrustlm/app/app.js`, `tinyrustlm/app/index.html`, `tinyrustlm/tools/browser_harness/src/main.rs`, and `tinyrustlm/tools/browser-smoke.js` before changing generated-output byte caps, total self-assembly budgets, or Module Plan panel rows. ## Implementation Memory - Rust selector registries emit and validate `entry.N.module_plan_output_byte_limit=65536`; missing or drifted values stop registry acceptance. - Generated `.module-plan.receipt` files emit `module_plan_output_byte_limit=65536`. - The browser registry intake requires the selector-owned output cap before accepting a generated entry. - Browser receipt validation requires the served cap to match the selector-owned value and the local `64 * 1024` runtime result cap before generated bytes are used. - Module-plan total budget math now includes model bytes, adapter stack bytes, runtime scratch, output cap, KV-cache budget, and declared module byte counts. - The Module Plan panel renders an `Output Limit` row for generated roots and `unavailable` for source-root fixtures without module-plan receipts. - `module-plan-output-limit-drift` mutates the served receipt cap while refreshing the selector module-plan checksum, proving the browser stops at module-plan validation. ## Verification Memory Passed on 2026-06-28: - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack module_plan_output` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack missing_output_byte_limit` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack writes_and_validates_selector_registry_with_module_plan_receipt` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack writes_browser_multi_parent_bundle` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack writes_quantized_browser_multi_parent_bundles` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack writes_combined_browser_multi_parent_bundle` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack` with 211 tests. - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\module-plan-output-limit-drift\tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8197/app/ 19731 multi-parent-sign-merge-q4 combined-selector-assembly` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8197/app/ 19732 multi-parent-sign-merge-q4 module-plan-output-limit-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8197/app/ 19733 multi-parent-sign-merge-q4 module-plan-runtime-scratch-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8198/app/ 19734 tinylm16q8 ui-audit` Normal generated-root smoke verified `Output Limit` as `65536 bytes` for q4_0, q8_0, and f32. Exact Total Budget values are now `169320 bytes` for q4_0, `171560 bytes` for q8_0, and `183094 bytes` for f32. The total cap is now `43450368 bytes`. No coverage tool is active in the no-third-party workspace, so focused syntax checks, Rust unit tests, full `tinyrustlm-slm-pack` tests, generated-root validation, static harness checks, and browser-smoke evidence are the recorded coverage evidence for this bead. ## Research Route This implements the zero-dependency browser-runtime and fit-boundary guidance from `wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md`: resource envelopes should become typed, checksum-routed receipts and browser proofs before generated artifacts are consumed. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-output-limit-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-phases-memory-2026-06-27.md BYTES: 3251 SHA256: 7110F3B1C8550EB338A471E51D3D676DE464FFA04A089F692D53C0F8A8FBCB9B ================================================================================ --- title: Browser Module Plan Phases Memory 2026-06-27 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-phases-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T23:00:19Z --- # Browser Module Plan Phases Memory ## Summary TinyRustLM generated `.module-plan.receipt` files now carry explicit `module.N.phase` fields for the local assembly lifecycle. The browser verifies those phases after receipt checksum validation and before generated `.slm`, ADP1, ASP1, or adapter-manifest fetches. ## Implemented Shape - `module.0.phase=load-model-bytes` - `module.1.phase=verify-model-manifest` - `module.2.phase=verify-assembly-evidence` - `module.3.phase=verify-adapter-family` - `module.4.phase=apply-adapter-stack-0` - `module.5.phase=apply-adapter-stack-1` ## Source Routes - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes phase fields into generated module-plan receipts and asserts them in browser-bundle tests. - `tinyrustlm/app/app.js` verifies base and adapter-stack phases before generated model or adapter bytes and renders the ordered phase summary. - `tinyrustlm/app/index.html` adds the Module Plan `Phases` row. - `tinyrustlm/tools/browser_harness/src/main.rs` requires the `modulePlanPhases` UI id. - `tinyrustlm/tools/browser-smoke.js` checks generated-root phase display, source-root fallback, and `module-plan-phase-drift`. ## Verification - `node --check tinyrustlm\app\app.js` - `node --check tinyrustlm\tools\browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-module-plan-phases\tinyrustlm all` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:18728/app/ 19564 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:18728/app/ 19566 multi-parent-sign-merge-q4 module-plan-phase-drift` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:18730/app/ 19568 tinylm16q8 ui-audit` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe test --workspace` ## Evidence Notes The generated-root q4 smoke rendered the phase summary as `0: load-model-bytes, 1: verify-model-manifest, 2: verify-assembly-evidence, 3: verify-adapter-family, 4: apply-adapter-stack-0, 5: apply-adapter-stack-1`. The phase-drift smoke mutated only `module.4.phase` while keeping the receipt checksum aligned through `selector.registry`. The browser requested `/models/selector.registry` and `/models/multi-parent-sign-merge-q4.module-plan.receipt`, then stopped before generated `.slm`, ADP1, ASP1, and adapter-manifest routes. The source-root UI audit proved checked fallback models render the Module Plan phase row as `unavailable` on desktop and mobile. ## Routing Use this report when changing `.module-plan.receipt` phase fields, Module Plan phase rendering, browser pre-model-fetch phase validation, or `module-plan-phase-drift` assertions. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-phases-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-planned-fetch-count-memory-2026-06-29.md BYTES: 3511 SHA256: 1EC42CAD8E48113418B19C5B3DE8C2713BA989C4A886B9D7CC54C1FFEE1BFC09 ================================================================================ --- title: Browser Module Plan Planned Fetch Count Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-planned-fetch-count-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T03:34:05Z --- # Browser Module Plan Planned Fetch Count Memory TinyRustLM generated module plans now bind the exact self-assembly route count with `module_plan_planned_fetch_count=21`, separate from the 32-fetch envelope. ## What Changed - `tinyrustlm/tools/slm_pack/src/selector.rs` writes, parses, checksums, and validates `module_plan_planned_fetch_count`; selector validation recomputes the count from module count, evidence files, adapter apply count, and the self-adapter manifest. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` emits the planned count into generated selector registry entries and `.module-plan.receipt` files for q4_0, q8_0, and f32 roots. - `tinyrustlm/app/app.js` verifies selector, receipt, generated-route formula, and the `21` constant agree before generated bytes are accepted, and renders `Plan Fetches`. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-planned-fetch-count-drift`, positive generated-root assertions for `Plan Fetches 21`, source-root fallback assertions, and exact generated route-budget checks. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml planned_fetch -- --nocapture` - `cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture` - `cargo test --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml` - `cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml rejects_module_plan_count_drift -- --nocapture` - `cargo test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml` - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` - Generated `target/module-plan-planned-fetch-count/tinyrustlm all`. - Served generated root on `http://127.0.0.1:8256/app/`. - `module-plan-planned-fetch-count-drift` stopped at `Module plan module plan planned fetch count mismatch` after selector registry plus module-plan receipt fetch. - `combined-selector-assembly` proved q4_0, q8_0, and f32 render `Plan Fetches 21`, use 21 governed self-assembly requests per generated assembly, apply three adapters, and generate one local token. - Source `ui-audit` on `http://127.0.0.1:8257/app/` proved source roots render the planned-fetch row as `unavailable`. - Static browser harness passed with 9 checks. ## Current Generated Module-Plan Values - Total budgets: q4_0 `173417 bytes`, q8_0 `175657 bytes`, f32 `187191 bytes`. - q4_0 checksums: `0: 0x1a6808e3098d1ce0, 1: 0x6d74e9f101d2b990, 2: 0x90860d865bb402e5, 3: 0xc5c8992662a5788e, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6, 6: 0xcaf46ccfc262fad2`. - q8_0 checksums: `0: 0x0132bc82d5a0d7d6, 1: 0x3d14ef7fa1b3ae05, 2: 0xad66de0b203ffca1, 3: 0x59268023ad4e3c0f, 4: 0x8194a8a671285019, 5: 0x6fa5d29bee9b7cfb, 6: 0x1ed9d08142edfda9`. - f32 checksums: `0: 0x8a0e6c4c01998199, 1: 0x1fe27dc9a8b25956, 2: 0x10214fcc0189495e, 3: 0x3822d9dae682fcd3, 4: 0xe9669ade4571fd42, 5: 0x34008cedc028ed5c, 6: 0x1c64143141c223b5`. ## Routing Open this report before changing generated self-assembly route counts, Module Plan `Plan Fetches` display, selector/receipt planned-fetch fields, or `module-plan-planned-fetch-count-drift` smoke assertions. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-planned-fetch-count-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md BYTES: 3457 SHA256: 59C30FC8709C4A92D9F9B3EA374C53B18126EABD5A8A08D9B8AEDA70D00C071E ================================================================================ --- title: Browser Module Plan Profile Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T10:20:00Z --- # Browser Module Plan Profile Memory ## Summary TinyRustLM generated module plans now carry an explicit constrained self-assembly profile: `browser-constrained-v1`. The profile is emitted in both selector registry module-plan routes and served `.module-plan.receipt` files, validated by Rust selector checks, and rechecked by the browser before any generated `.slm` bytes are fetched. ## Implementation - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `module_plan_profile=browser-constrained-v1` into each generated module-plan receipt and returns that profile to selector registry generation. - `tinyrustlm/tools/slm_pack/src/selector.rs` requires `entry.N.module_plan_profile=browser-constrained-v1`, writes it to selector registries, parses it back, and rejects profile drift. - `tinyrustlm/app/app.js` requires the registry profile before admitting a generated module plan and requires the receipt profile to match before model fetch. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-profile-drift`, which mutates only the served receipt profile while updating the selector checksum. - `tinyrustlm/tools/browser_harness/src/main.rs` adds a static app marker for `browser-constrained-v1`. ## Verification Passed on 2026-06-28: - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack module_plan` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/module-plan-profile-drift/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18761/app/ 19641 multi-parent-sign-merge-q4 module-plan-profile-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18761/app/ 19642 multi-parent-sign-merge-q4 combined-selector-assembly` The drift smoke requested only the app shell, runtime files, selector registry, and q4 module-plan receipt, then stopped with `Module plan field module_plan_profile was desktop-expanded-v1`. It did not request the generated `.slm`, adapter-family receipt, adapter manifests, or ADP1/ASP1/ALR1 stack artifacts. The positive smoke then walked q4_0, q8_0, and f32 entries from the same generated root and reached the ready trace with each stack validated and applied. ## Routing Load this report when work touches module-plan contract identity, selector-to-receipt self-assembly envelopes, `browser-constrained-v1`, generated bundle module-plan receipts, or `module-plan-profile-drift`. Related routes: - `wiki/gguf-mirust/reports/browser-module-plan-resource-memory-2026-06-27.md` - `wiki/gguf-mirust/reports/browser-module-plan-resource-drift-memory-2026-06-27.md` - `wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-combined-selector-route-soak-memory-2026-06-28.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-prompt-limit-memory-2026-06-28.md BYTES: 2189 SHA256: 2093B791B5898E269C218421764FC3B4F2EB12450D16A8FA6F2C65A83CF3FA60 ================================================================================ --- title: Browser Module Plan Prompt Limit Memory 2026-06-28 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-prompt-limit-memory-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T23:59:00Z --- # Browser Module Plan Prompt Limit Memory This record routes the browser module-plan prompt byte envelope added on 2026-06-28. ## Implementation Summary - Generated selector registry entries now carry `entry.N.module_plan_prompt_byte_limit=4096`. - Served `.module-plan.receipt` files now carry `module_plan_prompt_byte_limit=4096`. - Rust selector validation requires selector and receipt agreement before generated `.slm` bytes are fetched. - Browser receipt validation requires the same value, renders `Prompt Limit` in the Module Plan panel, and includes the limit in total budget math. - The source app rejects prompt payloads above 4096 UTF-8 bytes before copying prompt bytes into WASM, leaving the loaded model recoverable. ## Current Budget Values - Prompt byte limit: `4096 bytes`. - Total byte budget limit: `43454464 bytes`. - Generated q4_0 total budget: `173416 bytes`. - Generated q8_0 total budget: `175656 bytes`. - Generated f32 total budget: `187190 bytes`. ## Verification - `combined-selector-assembly` on the generated all-root proved q4_0, q8_0, and f32 render `Prompt Limit` as `4096 bytes` and carry the updated totals before generation. - `module-plan-prompt-limit-drift` proved checksum-consistent prompt-limit drift stops after selector plus module-plan receipt fetch, before generated model, assembly evidence, adapter-family, manifest, or stack artifact routes. - Source-root `ui-audit` proved non-generated roots keep Module Plan prompt limit fallback as `unavailable`. - Source-root `prompt-limit` submitted a 4097-byte prompt and proved the browser reports `prompt byte limit exceeded`, keeps prompt/generated diagnostics at zero, and leaves Generate, Reset, and model selection usable. ## Routing Rule Open this page before changing prompt transfer limits, generated module-plan total-budget math, selector registry prompt fields, Module Plan prompt display, or browser prompt-copy behavior. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-prompt-limit-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-resource-drift-memory-2026-06-27.md BYTES: 2686 SHA256: B84383557F1A76E1DD1D15004D6D7BBF7C3C2AE2136DCCE25C5C8A2F13B15571 ================================================================================ --- title: Browser Module Plan Resource Drift Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-resource-drift-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T20:05:12Z --- # Browser Module Plan Resource Drift Memory ## Routing Summary Use this report when work touches browser-smoke `module-plan-resource-drift`, generated `.module-plan.receipt` resource envelopes, checksum-consistent receipt drift, or proof that generated `.slm` bytes are not fetched after module-plan budget mismatch. ## Implementation - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-resource-drift` mode for generated multi-parent selector roots. - The smoke intercepts the served selector registry and selected `.module-plan.receipt`, changes only `module_plan_adapter_byte_budget=1048576` to `1048575` in the receipt, recomputes the receipt checksum with the browser checksum algorithm, and patches only the matching `entry.N.module_plan_checksum`. - The selector metadata budget remains unchanged, so the browser proves the receipt envelope gate itself: checksum verification passes, then `app.js` rejects the adapter byte-budget mismatch before generated `.slm` fetch. - The smoke asserts the browser stays local-origin, reports `Model load failed` with `Module plan module plan adapter byte budget mismatch`, keeps model selection recoverable, and never requests `/models/multi-parent-sign-merge-q4.slm`. ## Verification - `node --check tinyrustlm/tools/browser-smoke.js` - `node --check tinyrustlm/app/app.js` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-resource-drift/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18700/app/ 19530 multi-parent-sign-merge-q4 module-plan-resource-drift` - `cargo fmt --all -- --check` - `cargo test --workspace` - `git diff --check` The live generated-root q4 drift smoke requested `/models/selector.registry` and `/models/multi-parent-sign-merge-q4.module-plan.receipt`, surfaced `Module plan module plan adapter byte budget mismatch`, left generation controls stopped with model selection still available, and did not request `/models/multi-parent-sign-merge-q4.slm`. Workspace tests passed with 249 checks. `git diff --check` returned clean status with line-ending notices only. ## Next Routing The graph mismatch sibling is now covered by `browser-module-plan-graph-drift-memory-2026-06-27.md`. The next useful drift bead is a module-plan stack-member mismatch smoke: keep receipt checksum consistent but change one adapter stack field, then prove the browser stops before adapter artifact transfer. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-resource-drift-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-resource-memory-2026-06-27.md BYTES: 3092 SHA256: 7695A6C9455075D2E984F6A7AD9B24427B07880E269EDD486479897647167D2E ================================================================================ --- title: Browser Module Plan Resource Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-resource-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T19:26:45Z --- # Browser Module Plan Resource Memory ## Routing Summary Use this report when work touches generated selector `module_plan_*` resource fields, constrained browser self-assembly, served `.module-plan.receipt` byte envelopes, or generated-root `adapter-sidecar-registry-file` smoke coverage. It extends the first browser module-plan receipt with resource-class and byte-budget verification before generated `.slm` fetch. ## Implementation - `tinyrustlm/tools/slm_pack/src/selector.rs` now carries `entry.N.module_plan_resource_class`, `entry.N.module_plan_model_byte_budget`, and `entry.N.module_plan_adapter_byte_budget` through selector registry generation, parsing, validation, and rebuild-drift checks. - Selector validation rejects module-plan resource-class drift, non-canonical byte budgets, model byte budget drift against the admitted artifact bytes, and adapter byte budget drift against the adapter-family auto-apply budget. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes the same resource envelope into served `.module-plan.receipt` files and returns it to selector registry route generation. - `tinyrustlm/app/app.js` requires the resource envelope before accepting generated module-plan registry routes, then rechecks the receipt's resource class, model byte budget, and adapter byte budget before generated model bytes are requested. - `tinyrustlm/tools/browser_harness/src/main.rs` now treats `browser-constrained-local-assembly` as part of the static browser contract. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all` - `cargo test -p tinyrustlm-slm-pack selector::` - `cargo test -p tinyrustlm-slm-pack browser_bundle::` - `cargo test -p tinyrustlm-browser-harness` - `cargo fmt --all -- --check` - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-resource/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18698/app/ 19528 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` - `cargo test --workspace` - `git diff --check` The live generated-root q4 smoke requested `/models/multi-parent-sign-merge-q4.module-plan.receipt` before `/models/multi-parent-sign-merge-q4.slm`, auto-applied the family ADP1 plus sparse ASP1 stack before generation, preserved `q4_0` diagnostics, cleaned the temporary browser profile, and left only `TIME_WAIT` loopback entries on ports 18698 and 19528. `git diff --check` reported only existing line-ending conversion notices. ## Next Routing The next useful module-plan bead is planner-visible variation: selector entries could declare purpose labels, planner-selected stack recipes, or alternative local module plans while preserving this resource-class and byte-budget envelope. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-resource-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-role-display-memory-2026-06-27.md BYTES: 3215 SHA256: D2E7F9732CF6B19CBBAA1010281CB18C4AD52394B04F3E20ACFFE9FD435C4B32 ================================================================================ --- title: Browser Module Plan Role Display Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-role-display-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T21:19:44Z --- # Browser Module Plan Role Display Memory ## Routing Summary Use this report when work touches `.module-plan.receipt` module role fields, planner-readable local assembly graph metadata, Module Plan role rendering, or browser smoke assertions for generated role summaries. ## Implementation - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `module.N.role` beside each receipt module kind and path. - Generated non-stack roles are `runtime-model`, `model-provenance-manifest`, `assembly-evidence`, and `adapter-family`. - Generated stack member roles classify adapter modules as `adapter-stack-family-delta`, `adapter-stack-sparse-delta`, `adapter-stack-self-delta`, or `adapter-stack-delta` from their served artifact paths. - `tinyrustlm/app/index.html` adds a `Roles` row to the Module Plan panel. - `tinyrustlm/app/app.js` verifies each expected role while validating the receipt graph and renders an ordered role summary only from the verified receipt field map. - `tinyrustlm/tools/browser_harness/src/main.rs` treats `modulePlanRoles` as part of the static app contract. - `tinyrustlm/tools/browser-smoke.js` captures `modulePlanRoles` in source-root UI audit snapshots and generated-root adapter-sidecar-registry-file results. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-slm-pack browser_bundle::` - `cargo test -p tinyrustlm-browser-harness` - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-role-display/tinyrustlm all` - Receipt inspection confirmed generated q4 roles for runtime model, provenance manifest, assembly evidence, adapter family, family stack delta, and sparse stack delta. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18714/app/ 19546 tinylm16q8 ui-audit` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18716/app/ 19548 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` - `cargo test --workspace` - `git diff --check` passed with line-ending notes only. ## Outcome The source-root desktop/mobile UI audit showed Module Plan fallback state `none` with `modulePlanRoles=unavailable`. The generated q4 registry-file smoke showed `modulePlanState=loaded` and rendered `0: runtime-model, 1: model-provenance-manifest, 2: assembly-evidence, 3: adapter-family, 4: adapter-stack-family-delta, 5: adapter-stack-sparse-delta` while preserving the verified model budget, adapter budget, model route, stack routes, and pre-generation family ADP1 plus sparse ASP1 apply. Workspace tests passed with 249 checks. ## Next Routing The next useful constrained-browser bead is to make the role-bearing Module Plan consumable by a small planner state machine or to add compact role-drift proof before generated model fetch, while keeping JavaScript out of model and adapter payload parsing. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-role-display-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-role-drift-memory-2026-06-27.md BYTES: 2747 SHA256: 8154A6BEAE9CD081E702FD3FE99A5E15E2F3A636C70CEC3E1CD28C0D9A5B63BE ================================================================================ --- title: Browser Module Plan Role Drift Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-role-drift-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T21:46:45Z --- # Browser Module Plan Role Drift Memory ## Routing Summary Use this report when work touches browser-smoke `module-plan-role-drift`, `.module-plan.receipt` role fields, checksum-consistent role mutation, or proof that generated model and adapter-stack bytes are not fetched after module-plan role mismatch. ## Implementation - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-role-drift` mode for generated multi-parent selector roots. - The smoke intercepts the served selector registry and selected `.module-plan.receipt`, changes only the receipt `module.4.role` line, recomputes the receipt checksum with the browser checksum algorithm, and patches only the matching `entry.N.module_plan_checksum`. - The resource envelope, model graph, stack routes, and selector metadata remain aligned, so the browser proves the role gate itself: checksum verification, resource checks, graph checks, and stack route checks pass before `app.js` rejects the role mismatch. - The smoke asserts the browser stays local-origin, reports `Model load failed` with `Module plan field module.4.role was adapter-stack-role-drift`, keeps model selection recoverable, never requests `/models/multi-parent-sign-merge-q4.slm`, and never requests the generated q4 stack adapter artifacts or their manifests. ## Verification - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-role-drift/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18718/app/ 19550 multi-parent-sign-merge-q4 module-plan-role-drift` - `cargo test --workspace` - `git diff --check` passed with line-ending notes only. The live generated-root q4 role drift smoke requested `/models/selector.registry` and `/models/multi-parent-sign-merge-q4.module-plan.receipt`, surfaced `Module plan field module.4.role was adapter-stack-role-drift`, left generation controls stopped with model selection still available, and did not request `/models/multi-parent-sign-merge-q4.slm`, `/models/multi-parent-sign-merge-q4-family.adp1`, `/models/multi-parent-sign-merge-q4-sparse.asp1`, or their adapter manifests. Workspace tests passed with 249 checks. ## Next Routing The next useful constrained-browser bead is to let a small local planner consume verified Module Plan roles as typed assembly slots while preserving the pre-model-fetch receipt gate and keeping JavaScript out of model and adapter payload parsing. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-role-drift-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-route-set-algorithm-memory-2026-06-29.md BYTES: 5139 SHA256: 7ED26846B8327B7707FC54A9B26C141914A0B8E3CE9011A978B498465CA389C7 ================================================================================ --- title: Browser Module Plan Route Set Algorithm Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-route-set-algorithm-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T05:02:39Z --- # Browser Module Plan Route Set Algorithm Memory TinyRustLM generated module plans now bind the route-list checksum recipe with `module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1` before accepting generated model bytes. ## What Changed - `tinyrustlm/tools/slm_pack/src/selector.rs` writes, parses, and validates `module_plan_route_set_checksum_algorithm`; selector validation rejects missing or drifted algorithm labels before trusting `module_plan_route_set_checksum`. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` emits `module_plan_route_set_checksum_algorithm=tinyrustlm-text-checksum-v1` into generated selector registry entries and served `.module-plan.receipt` files, and includes `route_set_checksum_algorithm=tinyrustlm-text-checksum-v1` in the route-set checksum preimage. - `tinyrustlm/app/app.js` requires selector, receipt, and constant agreement, uses the shared algorithm constant in browser checksum recomputation, and renders `Route Hash` from verified module-plan receipt fields. - `tinyrustlm/app/index.html`, `tinyrustlm/tools/browser_harness/src/main.rs`, and `tinyrustlm/tools/browser-smoke.js` cover the new row, source fallback, generated q4_0/q8_0/f32 positive display, and `module-plan-route-set-algorithm-drift`. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml route_set -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml writes_and_validates_selector_registry_with_module_plan_receipt -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\module-plan-route-set-algorithm\tinyrustlm all` - Generated `module-plan-route-set-algorithm-drift` on `http://127.0.0.1:8262/app/`, stopping at `Module plan route set checksum algorithm mismatch` after selector registry plus module-plan receipt fetch. - Generated `combined-selector-assembly` on `http://127.0.0.1:8262/app/`, proving q4_0, q8_0, and f32 render Route Hash `tinyrustlm-text-checksum-v1`, Route Version `1`, Route Set checksums, verified receipts, declared route fetches, ADP1/ASP1/ALR1 apply, and one local token. - Source `ui-audit` on `http://127.0.0.1:8263/app/` proved source roots render Route Hash, Route Version, and Route Set as `unavailable`. - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml` passed with 232 tests. - Temporary generated root and local loopback servers were cleaned up. No coverage tool is active in this no-third-party workspace; evidence for the 75% target is focused Rust parameter and drift tests, the full slm_pack suite, static harness checks, generated browser drift smoke, normal combined assembly smoke, and source UI audit. ## Current Generated Module-Plan Values - Route Hash: q4_0, q8_0, and f32 `tinyrustlm-text-checksum-v1`; source roots `unavailable`. - Route Version: q4_0, q8_0, and f32 `1`; source roots `unavailable`. - Route Set checksums: q4_0 `0xe7d8c862dec256cb`, q8_0 `0xc6215c5348cef337`, f32 `0x5317f0a7a894574c`. - Total budgets: q4_0 `173417 bytes`, q8_0 `175657 bytes`, f32 `187191 bytes`. - q4_0 byte counts: `0: 6592 bytes, 1: 594 bytes, 2: 1896 bytes, 3: 5999 bytes, 4: 20224 bytes, 5: 832 bytes, 6: 1088 bytes`. - q8_0 byte counts: `0: 8832 bytes, 1: 594 bytes, 2: 1896 bytes, 3: 5999 bytes, 4: 20224 bytes, 5: 832 bytes, 6: 1088 bytes`. - f32 byte counts: `0: 20352 bytes, 1: 595 bytes, 2: 1909 bytes, 3: 5999 bytes, 4: 20224 bytes, 5: 832 bytes, 6: 1088 bytes`. - q4_0 checksums: `0: 0x1a6808e3098d1ce0, 1: 0xe0c893f895647ac4, 2: 0xd439438523a9d9d0, 3: 0xffdc3d42fbaadcd3, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6, 6: 0xcaf46ccfc262fad2`. - q8_0 checksums: `0: 0x0132bc82d5a0d7d6, 1: 0x6e8937606e8b4302, 2: 0x694e3792b24c50d6, 3: 0x52e3d3293940234c, 4: 0x8194a8a671285019, 5: 0x6fa5d29bee9b7cfb, 6: 0x1ed9d08142edfda9`. - f32 checksums: `0: 0x8a0e6c4c01998199, 1: 0xc1b16a606f675f73, 2: 0x718ef606fc242734, 3: 0x71620ee975d2fc43, 4: 0xe9669ade4571fd42, 5: 0x34008cedc028ed5c, 6: 0x1c64143141c223b5`. ## Routing Open this report before changing `module_plan_route_set_checksum_algorithm`, route-set checksum algorithm labels, route-set checksum preimage fields, Route Hash display, generated module-plan receipt algorithm fields, or `module-plan-route-set-algorithm-drift` smoke assertions. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-route-set-algorithm-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29.md BYTES: 4217 SHA256: DF04091F0D759F281992FA33BE6B7AECA1DDEADFF44EEBCDE60300AECF8F7728 ================================================================================ --- title: Browser Module Plan Route Set Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T04:08:27Z --- # Browser Module Plan Route Set Memory TinyRustLM generated module plans now bind the ordered browser self-assembly route set with `module_plan_route_set_checksum`, separate from the route count and the 32-fetch envelope. ## What Changed - `tinyrustlm/tools/slm_pack/src/selector.rs` writes, parses, validates, and species-fit-checksums `module_plan_route_set_checksum`; selector validation recomputes the checksum from candidate id, module-plan receipt, model, manifest, assembly receipt, nine evidence files, adapter-family receipt, adapter manifests, and auto-apply stack artifacts. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` emits the checksum into generated selector registry entries and `.module-plan.receipt` files for q4_0, q8_0, and f32 roots. - `tinyrustlm/app/app.js` recomputes the same ordered route list before generated bytes are accepted, verifies selector and receipt agreement, and renders `Route Set`. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-route-set-drift`, positive generated-root assertions for a nonzero Route Set checksum, source-root fallback assertions, and refreshed generated module-plan byte/checksum constants. ## Route Set Shape The generated route-set checksum covers these route classes in order: 1. module-plan receipt 2. model 3. model manifest 4. assembly receipt 5. nine assembly evidence files 6. adapter-family receipt 7. all adapter manifests 8. auto-apply stack artifacts The generated q4_0, q8_0, and f32 bundles keep `module_plan_planned_fetch_count=21`; the route-set checksum binds which 21 planned fetch routes are expected. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml route_set -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - Generated `target/module-plan-route-set-checksum/tinyrustlm all`. - Served generated root on `http://127.0.0.1:8258/app/`. - `module-plan-route-set-drift` stopped at `Module plan route set checksum mismatch` after selector registry plus module-plan receipt fetch. - `combined-selector-assembly` proved q4_0, q8_0, and f32 render nonzero Route Set checksums, verify module-plan receipts, fetch the declared local route set, apply three adapters, and generate one local token. - Source `ui-audit` on `http://127.0.0.1:8259/app/` proved source roots render the Route Set row as `unavailable`. - Temporary generated root and local servers were cleaned up. ## Current Generated Module-Plan Values - Route Set checksums: q4_0 `0x8a907a6db005b5c9`, q8_0 `0x424e40e4dd3d7f13`, f32 `0xd809fc21c74f8251`. - Total budgets: q4_0 `173416 bytes`, q8_0 `175656 bytes`, f32 `187190 bytes`. - q4_0 checksums: `0: 0x1a6808e3098d1ce0, 1: 0xbf4653f4b1159852, 2: 0x55a4522b720d6a93, 3: 0x95184559c603dd8c, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6, 6: 0xcaf46ccfc262fad2`. - q8_0 checksums: `0: 0x0132bc82d5a0d7d6, 1: 0xf59b4b60be91c4c9, 2: 0x8c51bcb700821b78, 3: 0xae6fce334e201781, 4: 0x8194a8a671285019, 5: 0x6fa5d29bee9b7cfb, 6: 0x1ed9d08142edfda9`. - f32 checksums: `0: 0x8a0e6c4c01998199, 1: 0x3856420edf6883a6, 2: 0x9112bb3d933d1121, 3: 0x2791ad2eeb8471f5, 4: 0xe9669ade4571fd42, 5: 0x34008cedc028ed5c, 6: 0x1c64143141c223b5`. ## Routing Open this report before changing generated self-assembly route ordering, `module_plan_route_set_checksum`, Module Plan `Route Set` display, selector/receipt route-set validation, or `module-plan-route-set-drift` smoke assertions. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-route-set-version-memory-2026-06-29.md BYTES: 4801 SHA256: 059AEC1201D4E11C5764DF2393471380FD93968270630B1C0C138FA2F501133C ================================================================================ --- title: Browser Module Plan Route Set Version Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-route-set-version-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T04:38:15Z --- # Browser Module Plan Route Set Version Memory TinyRustLM generated module plans now bind the route-list recipe with `module_plan_route_set_version=1` before the route-set checksum is accepted. ## What Changed - `tinyrustlm/tools/slm_pack/src/selector.rs` writes, parses, and validates `module_plan_route_set_version`; selector validation rejects missing or drifted route-set versions before trusting `module_plan_route_set_checksum`. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` emits `module_plan_route_set_version=1` into generated selector registry entries and served `.module-plan.receipt` files, and uses the shared version constant in the route-list checksum preimage. - `tinyrustlm/app/app.js` requires selector, receipt, and constant agreement, uses the shared version constant in browser checksum recomputation, and renders `Route Version` from verified module-plan receipt fields. - `tinyrustlm/app/index.html`, `tinyrustlm/tools/browser_harness/src/main.rs`, and `tinyrustlm/tools/browser-smoke.js` cover the new row, source fallback, generated q4_0/q8_0/f32 positive display, and `module-plan-route-set-version-drift`. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml route_set -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml browser_bundle::tests:: -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/browser_harness/Cargo.toml` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml writes_and_validates_selector_registry_with_module_plan_receipt -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\module-plan-route-set-version\tinyrustlm all` - Generated `module-plan-route-set-version-drift` on `http://127.0.0.1:8260/app/`, stopping at `Module plan route set version mismatch` after selector registry plus module-plan receipt fetch. - Generated `combined-selector-assembly` on `http://127.0.0.1:8260/app/`, proving q4_0, q8_0, and f32 render Route Version `1`, Route Set checksums, verified receipts, declared route fetches, ADP1/ASP1/ALR1 apply, and one local token. - Source `ui-audit` on `http://127.0.0.1:8261/app/` proved source roots render Route Version and Route Set as `unavailable`. - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml` passed with 230 tests. - Temporary generated root and local loopback servers were cleaned up. No coverage tool is active in this no-third-party workspace; evidence for the 75% target is focused Rust parameter and drift tests, the full slm_pack suite, static harness checks, generated browser drift smoke, normal combined assembly smoke, and source UI audit. ## Current Generated Module-Plan Values - Route Version: q4_0, q8_0, and f32 `1`; source roots `unavailable`. - Route Set checksums: q4_0 `0x8a907a6db005b5c9`, q8_0 `0x424e40e4dd3d7f13`, f32 `0xd809fc21c74f8251`. - Total budgets: q4_0 `173415 bytes`, q8_0 `175655 bytes`, f32 `187189 bytes`. - q4_0 byte counts: `0: 6592 bytes, 1: 592 bytes, 2: 1896 bytes, 3: 5999 bytes, 4: 20224 bytes, 5: 832 bytes, 6: 1088 bytes`. - q8_0 byte counts: `0: 8832 bytes, 1: 592 bytes, 2: 1896 bytes, 3: 5999 bytes, 4: 20224 bytes, 5: 832 bytes, 6: 1088 bytes`. - f32 byte counts: `0: 20352 bytes, 1: 593 bytes, 2: 1909 bytes, 3: 5999 bytes, 4: 20224 bytes, 5: 832 bytes, 6: 1088 bytes`. - q4_0 checksums: `0: 0x1a6808e3098d1ce0, 1: 0x9f35c3048cb29e35, 2: 0xc75023a04ebf9452, 3: 0x748f22ff0a3d77c8, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6, 6: 0xcaf46ccfc262fad2`. - q8_0 checksums: `0: 0x0132bc82d5a0d7d6, 1: 0x37bf7e42d4022b0d, 2: 0x94d589d542466103, 3: 0x3046e8d87d288ec7, 4: 0x8194a8a671285019, 5: 0x6fa5d29bee9b7cfb, 6: 0x1ed9d08142edfda9`. - f32 checksums: `0: 0x8a0e6c4c01998199, 1: 0x9d91a60e269e660e, 2: 0x09c6bd3c09db46e6, 3: 0xbadf8b67e26343d7, 4: 0xe9669ade4571fd42, 5: 0x34008cedc028ed5c, 6: 0x1c64143141c223b5`. ## Routing Open this report before changing `module_plan_route_set_version`, route-set checksum preimage versioning, Route Version display, generated module-plan receipt version fields, or `module-plan-route-set-version-drift` smoke assertions. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-route-set-version-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-runtime-reset-memory-2026-06-29.md BYTES: 3178 SHA256: 99318A970ABAA9324A5C141CF78697ECC603E2B60B5B80EEE07D5F820F537301 ================================================================================ # Browser Module Plan Runtime Reset Memory - 2026-06-29 status: reviewed_current authority: generated from current implementation and verification evidence ## Summary Generated module-plan selector entries and served `.module-plan.receipt` files now bind `module_plan_runtime_reset_strategy=reset-context-before-assembly-v1`. The browser verifies selector and receipt agreement, renders the verified Module Plan `Reset` row, calls WASM `reset_context` after generated model bytes load, and proves the reset happens before assembly evidence and adapter-stack work. ## Implementation Route - `tinyrustlm/tools/slm_pack/src/selector.rs` writes, parses, checksums, and validates `entry.N.module_plan_runtime_reset_strategy`. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `module_plan_runtime_reset_strategy=reset-context-before-assembly-v1` into generated `.module-plan.receipt` files and selector route records. - `tinyrustlm/app/index.html` adds the Module Plan `Reset` row. - `tinyrustlm/app/app.js` validates selector and receipt agreement, requires `reset-context-before-assembly-v1`, and calls `reset_context` before recording generated assembly progress. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-runtime-reset-drift`, asserts generated roots render `reset-context-before-assembly-v1`, checks `reset_context` precedes adapter validation/application, and asserts source roots render `unavailable`. - `tinyrustlm/tools/browser_harness/src/main.rs` includes the new row id in the static contract. ## Verified Behavior - Node syntax checks passed for `tinyrustlm/app/app.js` and `tinyrustlm/tools/browser-smoke.js`. - `cargo fmt --all -- --check` passed with `C:\Users\AI\.cargo\bin\cargo.exe`. - `cargo test -p tinyrustlm-slm-pack selector` passed with 73 tests. - `cargo test -p tinyrustlm-slm-pack browser_bundle` passed with 4 tests. - `cargo test -p tinyrustlm-browser-harness` passed with 6 tests. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` passed with 9 static checks. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\module-plan-runtime-reset\tinyrustlm all` passed and validated 3 module-plan routes. - Generated-root `module-plan-runtime-reset-drift` passed on `http://127.0.0.1:8235/app/`, returning `Module plan runtime reset strategy mismatch` after selector plus module-plan receipt requests and before generated model routes. - Generated-root `combined-selector-cycle` passed on `http://127.0.0.1:8235/app/`, proving q4_0/q8_0/f32 generated assemblies render `Reset` as `reset-context-before-assembly-v1` and log `reset_context(...)` before adapter validation/application on every generated pass. - Source-root `ui-audit` passed on `http://127.0.0.1:8236/app/`, proving the fallback row remains `unavailable`. ## Routing Notes Open this report before changing generated model-load context reset sequencing, selector registry module-plan reset metadata, Module Plan `Reset` display, or `module-plan-runtime-reset-drift` smoke assertions. Keep this field separate from model release: release records prior-model lifetime, while reset records fresh runtime context before verified assembly. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-runtime-reset-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md BYTES: 3723 SHA256: 19E68CF4969FF3F34E5C54AE0C698E02035C1D4C0F42E66A73EED49068AA27F8 ================================================================================ --- title: Browser Module Plan Runtime Scratch Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T11:05:00Z --- # Browser Module Plan Runtime Scratch Memory ## Summary TinyRustLM generated module plans now bind a browser runtime scratch envelope before generated model fetch. Selector registry entries and served `.module-plan.receipt` files carry `module_plan_runtime_scratch_byte_budget=65536`; Rust selector validation, browser registry intake, and browser receipt validation all require that exact value. ## Implementation - `tinyrustlm/tools/slm_pack/src/selector.rs` adds `MODULE_PLAN_RUNTIME_SCRATCH_BYTE_BUDGET`, writes `entry.N.module_plan_runtime_scratch_byte_budget`, parses it back, and rejects drift, missing fields, or malformed decimal values. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `module_plan_runtime_scratch_byte_budget=65536` into every generated `.module-plan.receipt` and returns the same budget to selector registry generation. - `tinyrustlm/app/app.js` requires the registry scratch budget and receipt scratch budget to match the browser envelope before any generated `.slm` fetch. - `tinyrustlm/app/index.html` and `tinyrustlm/tools/browser-smoke.js` render and assert a verified `Scratch Budget` row in the Module Plan panel. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-runtime-scratch-drift`, which mutates only the served receipt scratch budget while updating the selector registry checksum. ## Verification Passed on 2026-06-28: - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack module_plan` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/module-plan-runtime-scratch-drift/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18762/app/ 19645 multi-parent-sign-merge-q4 module-plan-runtime-scratch-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18762/app/ 19646 multi-parent-sign-merge-q4 combined-selector-assembly` The drift smoke requested only the app shell, runtime files, selector registry, and q4 module-plan receipt, then stopped with `Module plan module plan runtime scratch byte budget mismatch`. It did not request the generated `.slm` route or any adapter-family, adapter-manifest, ADP1, ASP1, or ALR1 stack artifact route. The positive smoke walked q4_0, q8_0, and f32 entries from one generated root and rendered `65536 bytes` in the Module Plan `Scratch Budget` row for every entry while reaching the ready trace after ADP1 plus ASP1 plus ALR1 stack validation and apply. ## Routing Load this report when work touches browser-constrained runtime envelopes, module-plan scratch budgets, generated selector/receipt resource fields, Module Plan budget display, or `module-plan-runtime-scratch-drift`. Related routes: - `wiki/gguf-mirust/reports/browser-module-plan-profile-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-module-plan-resource-memory-2026-06-27.md` - `wiki/gguf-mirust/reports/browser-module-plan-resource-drift-memory-2026-06-27.md` - `wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-sampler-cap-memory-2026-06-28.md BYTES: 3464 SHA256: B47BDDC936EE16EB489B7F28D5D208DFF630F5C914E1A76DE93B4F3F2B968612 ================================================================================ --- title: Browser Module Plan Sampler Cap Memory 2026-06-28 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-sampler-cap-memory-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T23:59:00Z --- # Browser Module Plan Sampler Cap Memory This report routes the browser module-plan sampler candidate cap proof so future agents can preserve the fixed-buffer decoding envelope while changing generated selector, receipt, or browser assembly code. ## Implementation - Generated selector registries now carry `entry.N.module_plan_sampler_candidate_cap=1024`. - Served `.module-plan.receipt` files now carry `module_plan_sampler_candidate_cap=1024`. - Rust selector validation rejects sampler-cap drift before a generated route becomes admissible. - Browser registry intake and receipt validation require the selector cap, receipt cap, and local fixed-buffer sampler cap to match before generated `.slm` bytes or adapter stack artifacts are fetched. - The Module Plan panel renders `Sampler Cap` as `1024 candidates` for generated q4_0/q8_0/f32 entries and `unavailable` for checked source routes. - `module-plan-sampler-cap-drift` mutates the served receipt cap while refreshing the selector checksum, then proves startup stops at the module-plan receipt before model bytes, adapter-family receipt, adapter manifests, or stack artifacts are requested. ## Browser Evidence - Generated all-root staging: `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-sampler-cap\tinyrustlm all`. - Normal generated assembly: `node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8105/app/ 19596 multi-parent-sign-merge-q4 combined-selector-assembly`. - Sampler-cap drift: `node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8105/app/ 19598 multi-parent-sign-merge-q4 module-plan-sampler-cap-drift`. - Source UI fallback: `node .\tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8106/app/ 19602 tinylm16q8 ui-audit`. ## Rust And Script Evidence - `node --check tinyrustlm\app\app.js` - `node --check tinyrustlm\tools\browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector::tests::rejects_module_plan_sampler_candidate_cap_drift` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector::tests::writes_and_validates_selector_registry_with_module_plan_receipt` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::tests::writes_combined_browser_multi_parent_bundle` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector::tests::` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::tests::` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- .\tinyrustlm` ## Generated Values - Sampler cap: `1024 candidates`. - q4 total budget: `103782 bytes`. - q8 total budget: `106022 bytes`. - f32 total budget: `117556 bytes`. - Drift failure text: `Module plan sampler candidate cap mismatch`. ## Routing Rule Open this report before changing fixed-buffer sampling limits, selector `module_plan_sampler_candidate_cap`, served `.module-plan.receipt` sampler fields, browser `Top K` clamping, Module Plan sampler display, or `module-plan-sampler-cap-drift` smoke assertions. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-sampler-cap-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-slots-memory-2026-06-27.md BYTES: 2563 SHA256: F96F60042441F838CA058F85AB628DBA4A48FF2AC211293A86A51C65BAD62EBB ================================================================================ # Browser Module Plan Assembly Slots Memory - 2026-06-27 ## Summary Browser module-plan receipts now carry typed `module.N.assembly_slot` fields. The generated browser bundle writes stable slots for runtime model, model manifest, assembly receipt, adapter-family receipt, and each adapter-stack position; the browser verifies those slots before fetching generated `.slm` bytes or stack artifacts. ## Implementation Notes - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `module.N.assembly_slot` beside each module kind, role, route, and checksum. - `tinyrustlm/app/app.js` validates exact assembly slots during module-plan verification: `runtime-model`, `model-manifest`, `assembly-receipt`, `adapter-family-receipt`, then `adapter-stack-N`. - `tinyrustlm/app/index.html` adds a Module Plan `Slots` row, and `app.js` renders the ordered slot summary only from verified receipt fields. - `tinyrustlm/tools/browser-smoke.js` asserts generated q4 slot display, source-root fallback `unavailable`, and `module-plan-slot-drift` behavior. - `tinyrustlm/tools/browser_harness/src/main.rs` treats `modulePlanSlots` as part of the static app contract. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-slm-pack browser_bundle::` - `cargo test -p tinyrustlm-browser-harness` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-slots/tinyrustlm all` - Generated-root browser smoke on `http://127.0.0.1:18720/app/` for `multi-parent-sign-merge-q4 adapter-sidecar-registry-file` showed `0: runtime-model, 1: model-manifest, 2: assembly-receipt, 3: adapter-family-receipt, 4: adapter-stack-0, 5: adapter-stack-1`. - Generated-root browser smoke on `http://127.0.0.1:18720/app/` for `multi-parent-sign-merge-q4 module-plan-slot-drift` stopped at the receipt with `Module plan field module.4.assembly_slot was adapter-stack-slot-drift` and requested no generated q4 `.slm`, ADP1, ASP1, or adapter-manifest route. - Source-root `ui-audit` on `http://127.0.0.1:18722/app/` proved Module Plan slot fallback is `unavailable` on desktop and mobile. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` - `cargo test --workspace` ## Routing Open this report before changing module-plan `assembly_slot` field names, slot display, `module-plan-slot-drift`, or pre-model-fetch generated plan verification. Pair it with the role-display and role-drift reports when changing planner-readable module semantics. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-slots-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-stack-drift-memory-2026-06-27.md BYTES: 2814 SHA256: 32A30EC59AAD3BE790A8B12570825E4076C29F79E44DA26D73DEA4D2D611B8C8 ================================================================================ --- title: Browser Module Plan Stack Drift Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-stack-drift-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T20:20:05Z --- # Browser Module Plan Stack Drift Memory ## Routing Summary Use this report when work touches browser-smoke `module-plan-stack-drift`, generated `.module-plan.receipt` adapter-stack metadata, checksum-consistent stack route drift, or proof that generated model and adapter bytes are not fetched after module-plan stack mismatch. ## Implementation - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-stack-drift` mode for generated multi-parent selector roots. - The smoke intercepts the served selector registry and selected `.module-plan.receipt`, changes only the receipt `module.4.adapter_path` stack-member graph line, recomputes the receipt checksum with the browser checksum algorithm, and patches only the matching `entry.N.module_plan_checksum`. - The resource envelope, model graph, and selector metadata remain aligned, so the browser proves the adapter-stack graph gate itself: checksum verification and budget checks pass, then `app.js` rejects the stack route mismatch before generated `.slm` fetch. - The smoke asserts the browser stays local-origin, reports `Model load failed` with `Module plan field module.4.adapter_path was ...`, keeps model selection recoverable, never requests `/models/multi-parent-sign-merge-q4.slm`, and never requests the generated q4 stack adapter artifacts or their manifests. ## Verification - `node --check tinyrustlm/tools/browser-smoke.js` - `node --check tinyrustlm/app/app.js` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-module-plan-stack-drift/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18704/app/ 19536 multi-parent-sign-merge-q4 module-plan-stack-drift` - `cargo fmt --all -- --check` - `cargo test --workspace` The live generated-root q4 stack drift smoke requested `/models/selector.registry` and `/models/multi-parent-sign-merge-q4.module-plan.receipt`, surfaced `Module plan field module.4.adapter_path was ../models/multi-parent-sign-merge-q4-family-stack-drift.adp1`, left generation controls stopped with model selection still available, and did not request `/models/multi-parent-sign-merge-q4.slm`, `/models/multi-parent-sign-merge-q4-family.adp1`, `/models/multi-parent-sign-merge-q4-sparse.asp1`, or their adapter manifests. Workspace tests passed with 249 checks. ## Next Routing The next useful constrained-browser bead is to move from drift proofs toward a positive module-plan stack receipt display: show the verified module graph and stack routes in the browser without expanding JavaScript into model or adapter parsing. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-stack-drift-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28.md BYTES: 3201 SHA256: DD620500D7E2AC962B0242AA8DD321186776300B0F328DC7C9113536B7FEFA92 ================================================================================ # Browser Module Plan Tokenizer Memory - 2026-06-28 status: current public_route: /gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28/ source_authority: local source, generated bundle, focused Rust tests, and browser smoke ## Route Summary Generated selector entries and served `.module-plan.receipt` files now bind tokenizer checksum identity before generated model bytes load. ## Implemented Shape - `module_plan_tokenizer_checksum` is emitted in generated selector registries and `.module-plan.receipt` files. - Selector validation requires the module-plan tokenizer checksum to match the admitted model tokenizer checksum. - Browser registry intake carries the selector tokenizer checksum on each generated entry. - Browser receipt validation rechecks the served receipt tokenizer checksum against selector metadata before generated `.slm` fetch. - Genome, species-fit, and species checksum generation include tokenizer identity where the candidate route needs it. - The Module Plan panel renders `Tokenizer` as the verified checksum value for generated roots and keeps source-root fallback as `unavailable`. - `module-plan-tokenizer-drift` mutates only the receipt tokenizer checksum while refreshing the selector checksum, then proves browser validation stops before generated `.slm`, manifest, assembly, adapter-family, or stack routes. ## Verified Evidence - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-slm-pack selector::tests::rejects_module_plan_tokenizer_checksum_drift` - `cargo test -p tinyrustlm-slm-pack selector::tests::writes_and_validates_selector_registry_with_module_plan_receipt` - `cargo test -p tinyrustlm-slm-pack selector::tests::` - `cargo test -p tinyrustlm-slm-pack browser_bundle::tests::` - `cargo test -p tinyrustlm-browser-harness` - `cargo run -p tinyrustlm-browser-harness -- .\tinyrustlm` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-served-tokenizer\tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8104/app/ 19584 multi-parent-sign-merge-q4 combined-selector-assembly` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8104/app/ 19586 multi-parent-sign-merge-q4 module-plan-tokenizer-drift` ## Current Generated Values - Tokenizer checksum: `0x288f65d94c26743e` for generated q4_0, q8_0, and f32 entries. - q4_0 Total Budget: `103780 bytes` - q8_0 Total Budget: `106020 bytes` - f32 Total Budget: `117554 bytes` - q4_0 Module Checksums: `0: 0x1a6808e3098d1ce0, 1: 0xd1b3d62daec1c2a3, 2: 0x3431b665f2a7ba7e, 3: 0x51845f58d5fa3279, 4: 0x0bd71e0020bc6ebf, 5: 0x69638218a1dd1eb6, 6: 0xcaf46ccfc262fad2` ## Coverage Note No coverage tool is active in the no-third-party workspace; focused parameter tests, Rust tests, static harness checks, generated-root proof, and browser-smoke evidence were recorded against the 75% target. ## Next Route Use this report before changing tokenizer identity, selector tokenizer fields, generated genome/species checksum ingredients, Module Plan panel tokenizer rows, or browser receipt validation for generated self-assembly. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-total-budget-memory-2026-06-28.md BYTES: 3554 SHA256: 3DAB4D7483A72A60017D94A76FAC99282DDA337535752BA0AC74BB09172CBDF8 ================================================================================ --- title: Browser Module Plan Total Budget Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-module-plan-total-budget-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T15:30:00Z --- # Browser Module Plan Total Budget Memory ## Summary TinyRustLM generated module plans now carry `module_plan_total_byte_budget`, an exact browser-local self-assembly envelope for the model bytes, model manifest text, assembly receipt text, adapter-family receipt text, ordered ADP1/ASP1/source-backed ALR1 stack artifact bytes, and runtime scratch budget. The selector registry and served `.module-plan.receipt` must agree on that total before the browser fetches generated model bytes. The UI renders the verified Total Budget row, and `module-plan-total-budget-drift` proves checksum-consistent total drift stops at the module-plan receipt. ## Implementation - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` computes the total from exact staged files plus the module-plan runtime scratch envelope while writing generated module-plan receipts. - `tinyrustlm/tools/slm_pack/src/selector.rs` emits and validates `entry.N.module_plan_total_byte_budget` with a bounded registry contract. - `tinyrustlm/app/app.js` accepts registry entries only when the total is present, bounded, and matches the receipt-declared module bytes plus runtime scratch. - `tinyrustlm/app/index.html` renders the Module Plan `Total Budget` row. - `tinyrustlm/tools/browser-smoke.js` checks exact q4_0/q8_0/f32 total-budget UI values in `combined-selector-assembly` and adds `module-plan-total-budget-drift`. ## Verification Passed on 2026-06-28: - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack module_plan` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/module-plan-total-budget-drift/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8190/app/ 9293 multi-parent-sign-merge-q4 combined-selector-assembly` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8190/app/ 9294 multi-parent-sign-merge-q4 module-plan-total-budget-drift` - `C:\Users\AI\.cargo\bin\cargo.exe test --workspace` The normal generated-root smoke verified Total Budget values of `102760 bytes` for q4_0, `105000 bytes` for q8_0, and `116534 bytes` for f32. The drift smoke stopped after `/models/multi-parent-sign-merge-q4.module-plan.receipt`; no generated `.slm`, adapter-family, adapter-manifest, or stack artifact route was fetched. ## Routing Load this report when work touches `module_plan_total_byte_budget`, module-plan total envelope generation, Total Budget display, receipt-declared module byte summation, or `module-plan-total-budget-drift`. Related routes: - `wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-module-plan-byte-counts-memory-2026-06-27.md` - `wiki/gguf-mirust/reports/browser-module-plan-checksums-memory-2026-06-27.md` - `wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-total-budget-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28.md BYTES: 3761 SHA256: BAE2630090806ECF120218CE59141FABA7D764D3AD53F58C8BF951070A9CCF41 ================================================================================ --- title: Browser Module Plan Total Limit Memory 2026-06-28 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28/ status: reviewed reviewed_utc: 2026-06-28T18:20:00Z --- # Browser Module Plan Total Limit Memory ## Routing Summary Generated browser module plans now carry `module_plan_total_byte_budget_limit` beside the exact `module_plan_total_byte_budget`. This turns the browser-constrained self-assembly cap into selector and receipt evidence rather than an implicit source constant. Open `tinyrustlm/tools/slm_pack/src/selector.rs`, `tinyrustlm/tools/slm_pack/src/browser_bundle.rs`, `tinyrustlm/app/app.js`, `tinyrustlm/app/index.html`, and `tinyrustlm/tools/browser-smoke.js` before changing this field. ## Implementation Memory - `selector.registry` entries emit `entry.N.module_plan_total_byte_budget_limit=43384832` for generated module-plan routes. - Served `.module-plan.receipt` files emit `module_plan_total_byte_budget_limit=43384832`. - Rust selector validation rejects cap drift before registry acceptance and keeps the exact total bounded by the declared cap. - Browser registry intake requires the cap, requires it to match the local browser limit constant, and rejects entries where the exact total exceeds the cap. - Browser receipt validation requires the served cap to match the selector-owned value before generated `.slm`, adapter-family, adapter-manifest, or stack artifact routes are fetched. - The Module Plan panel renders `Total Limit` from verified receipt fields. - `module-plan-total-limit-drift` mutates the served receipt cap while refreshing the receipt checksum and selector module-plan checksum, then proves the browser stops at the module-plan receipt. ## Verification Memory Passed on 2026-06-28: - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector` with 54 selector-filtered tests. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle` with 4 tests. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` with 6 tests. - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` with 9 checks. - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-total-limit\tinyrustlm all`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8100/app/ 19582 multi-parent-sign-merge-q4 combined-selector-assembly`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8100/app/ 19584 multi-parent-sign-merge-q4 module-plan-total-limit-drift`. - `git diff --check` returned line-ending notices only, with no whitespace errors. The normal generated-root smoke verified `Total Limit` as `43384832 bytes` for q4_0, q8_0, and f32. Exact Total Budget values after the cap field are `103780 bytes` for q4_0, `106020 bytes` for q8_0, and `117554 bytes` for f32. The drift smoke stopped after `/models/multi-parent-sign-merge-q4.module-plan.receipt`; no generated `.slm`, adapter-family, adapter-manifest, or stack artifact route was fetched. No coverage tool is active in the no-third-party workspace, so focused syntax checks, Rust unit tests, generated-root validation, static harness checks, and browser-smoke evidence are the recorded coverage evidence for this bead. ## Research Route This implements the resource-envelope and speciation-fit guidance from `wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md`: browser fit boundaries should be local, typed, checksum-routed evidence before model bytes are consumed. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md BYTES: 3924 SHA256: A9A5E5FC1C1CBAE5AE6D8EFEC71D556DDB0BD70F1E1A059B2DBD96C06E85D98E ================================================================================ --- title: Browser Module Plan WASM Export Set Memory 2026-06-28 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T23:59:00Z --- # Browser Module Plan WASM Export Set Memory This report routes the browser module-plan WASM export-set proof so future agents can preserve the Rust-owned browser runtime ABI while changing generated selector, receipt, or browser assembly code. ## Implementation - Generated selector registries now carry `entry.N.module_plan_wasm_export_set=tinyrustlm-generate-v1`. - Served `.module-plan.receipt` files now carry `module_plan_wasm_export_set=tinyrustlm-generate-v1`. - Rust selector validation rejects export-set drift before a generated route becomes admissible. - Browser registry intake requires the selector export set to match the local `tinyrustlm-generate-v1` ABI name. - Browser receipt validation compares the receipt field with the selector field and verifies the instantiated WASM exports before generated `.slm` bytes or adapter stack artifacts are fetched. - The Module Plan panel renders `WASM ABI` as `tinyrustlm-generate-v1` for generated q4_0/q8_0/f32 entries and `unavailable` for checked source routes. - `module-plan-wasm-export-set-drift` mutates the served receipt export set while refreshing the selector checksum, then proves startup stops at the module-plan receipt before model bytes, adapter-family receipt, adapter manifests, or stack artifacts are requested. ## Browser Evidence - Generated all-root staging: `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\module-plan-wasm-export-set-drift\tinyrustlm all`. - Normal generated assembly: `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8106/app/ 9264 multi-parent-sign-merge-q4 combined-selector-assembly`. - WASM export-set drift: `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8106/app/ 9263 multi-parent-sign-merge-q4 module-plan-wasm-export-set-drift`. - Source UI fallback: `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8107/app/ 9265 tinylm16q8 ui-audit`. ## Rust And Script Evidence - `node --check tinyrustlm\app\app.js` - `node --check tinyrustlm\tools\browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector::tests::rejects_module_plan_wasm_export_set_drift` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector::tests` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::tests::writes_browser_multi_parent_bundle` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::tests::writes_quantized_browser_multi_parent_bundles` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle::tests::writes_combined_browser_multi_parent_bundle` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` ## Generated Values - WASM ABI: `tinyrustlm-generate-v1`. - Required export names: `memory`, `alloc`, `dealloc`, `init_runtime`, `load_model`, `generate`, `set_sampling_config`, `generate_next_token`, `validate_adapter_delta`, `apply_adapter_delta`, `last_result_ptr`, `last_result_len`, `get_diagnostics_ptr`, `get_diagnostics_len`, `reset_context`, and `free_model`. - q4 total budget: `103789 bytes`. - q8 total budget: `106029 bytes`. - f32 total budget: `117563 bytes`. - Drift failure text: `Module plan WASM export set mismatch`. ## Routing Rule Open this report before changing Rust WASM exports, browser WASM boundary calls, selector `module_plan_wasm_export_set`, served `.module-plan.receipt` export-set fields, Module Plan `WASM ABI` display, or `module-plan-wasm-export-set-drift` smoke assertions. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-wasm-heap-memory-2026-06-28.md BYTES: 2998 SHA256: D674ACA30BE14EDDD171E1E98CB6E045F6082D44C4398C2D80AB620A935BCDB3 ================================================================================ # Browser Module Plan WASM Heap Memory - 2026-06-28 status: reviewed_current authority: generated from current implementation and verification evidence ## Summary Generated module-plan selector entries and served `.module-plan.receipt` files now bind `module_plan_wasm_heap_min_bytes`. The browser verifies selector and receipt agreement, recomputes the heap floor as `max(64 KiB, model byte budget, adapter stack byte budget, prompt byte limit)`, renders the verified Module Plan `Heap Floor` row, and probes WASM `alloc`/`dealloc` for that floor before generated model bytes or stack artifacts are fetched. ## Implementation Route - `tinyrustlm/tools/slm_pack/src/selector.rs` writes, parses, checksums, and validates `entry.N.module_plan_wasm_heap_min_bytes`. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes the same field into generated `.module-plan.receipt` files and selector route records. - `tinyrustlm/app/index.html` adds the Module Plan `Heap Floor` row. - `tinyrustlm/app/app.js` validates the selector/receipt value, recomputes the heap-floor formula, probes WASM allocation with the verified byte count, releases that probe allocation, and keeps source roots at `unavailable`. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-wasm-heap-drift` and asserts generated roots render `65536 bytes` while source roots render `unavailable`. - `tinyrustlm/tools/browser_harness/src/main.rs` includes the new row id in the static contract. ## Verified Behavior - Node syntax checks passed for `tinyrustlm/app/app.js` and `tinyrustlm/tools/browser-smoke.js`. - `cargo fmt --all -- --check` passed. - `cargo test -p tinyrustlm-browser-harness` passed with 6 tests. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` passed with 9 static checks. - `cargo test -p tinyrustlm-slm-pack browser_bundle` passed with 4 tests. - `cargo test -p tinyrustlm-slm-pack selector` passed with 70 tests. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\module-plan-wasm-heap\tinyrustlm all` passed and validated 3 module-plan routes. - Generated-root `module-plan-wasm-heap-drift` passed on `http://127.0.0.1:8221/app/`, returning `Module plan WASM heap min bytes mismatch` after selector plus module-plan receipt requests and before generated model routes. - Generated-root `combined-selector-cycle` passed on `http://127.0.0.1:8221/app/`, proving q4_0/q8_0/f32 generated assemblies render `Heap Floor` as `65536 bytes` and still reach ready with ADP1 plus ASP1 plus ALR1 stack apply. - Source-root `ui-audit` passed on `http://127.0.0.1:8222/app/`, proving the fallback row remains `unavailable`. ## Routing Notes Open this report before changing browser WASM allocation probes, module-plan heap or transfer envelopes, generated bundle module-plan receipts, or selector registry heap-floor validation. Keep heap floor separate from `module_plan_total_byte_budget`; it proves available transfer capacity rather than counting another fetched resource. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-wasm-heap-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-wasm-memory-memory-2026-06-28.md BYTES: 4342 SHA256: 321EAE98E9A6FE2D7855AF06E3B49EB456193BF1757EE7310235574C559AABA1 ================================================================================ --- title: Browser Module Plan WASM Memory Memory 2026-06-28 source_site: GGUF.MiRust.com local_route: /gguf-mirust/reports/browser-module-plan-wasm-memory-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T18:40:00Z --- # Browser Module Plan WASM Memory Memory ## Summary TinyRustLM generated module plans now carry `module_plan_wasm_memory_initial_pages=17`, binding selector registry routes and served `.module-plan.receipt` files to the runtime WASM module's exported linear-memory footprint before `init_runtime()` can grow memory. The browser records the initial page count immediately after `WebAssembly.instantiate`, requires selector and receipt agreement before generated model bytes are fetched, and renders a Module Plan `WASM Pages` row. The `module-plan-wasm-memory-drift` smoke proves checksum-consistent page-count drift stops at the module-plan receipt. ## Implementation - `tinyrustlm/tools/slm_pack/src/selector.rs` emits, parses, and validates `entry.N.module_plan_wasm_memory_initial_pages`, rejecting non-canonical or drifted values. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `module_plan_wasm_memory_initial_pages=17` into generated receipts and selector route metadata. - `tinyrustlm/app/app.js` captures the exported WASM memory page count before runtime initialization, validates the receipt against that captured value, and leaves generated `.slm` bytes unfetched on mismatch. - `tinyrustlm/app/index.html` renders the Module Plan `WASM Pages` field. - `tinyrustlm/tools/browser-smoke.js` checks the visible `17` page contract for q4_0, q8_0, and f32 generated entries and adds `module-plan-wasm-memory-drift`. ## Verification Passed on 2026-06-28: - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack module_plan` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-browser-harness -- tinyrustlm` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/module-plan-wasm-memory-drift/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8191/app/ 9295 multi-parent-sign-merge-q4 combined-selector-assembly` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8191/app/ 9296 multi-parent-sign-merge-q4 module-plan-wasm-memory-drift` - `C:\Users\AI\.cargo\bin\cargo.exe test --workspace` The normal generated-root smoke verified `modulePlanWasmPages` as `17` for q4_0, q8_0, and f32 entries. The drift smoke stopped after `/models/multi-parent-sign-merge-q4.module-plan.receipt`; no generated `.slm`, adapter-family, adapter-manifest, or stack artifact route was fetched. No coverage tool is currently active in this workspace. The closest coverage evidence for this change is the focused Rust tests, browser harness checks, two generated-root browser smokes, and full workspace test sweep. ## Operational Note Before verification, `E:\` free space had fallen to about 1.5 GiB. Generated publish/smoke artifacts were removed from `E:\Source\Python\LocalEndpoint-Smoke-Publish`, `E:\Source\Python\LocalEndpoint.com-Publish`, `E:\Source\Python\LocalEndpointConnectScaffold-CSharp\artifacts`, and `E:\Source\Python\LocalEndpointConnectScaffold-CSharp\TestResults`, restoring about 66.5 GiB free while leaving this Rust workspace source, `.uai`, wiki, and handoff files intact. ## Routing Load this report when work touches `module_plan_wasm_memory_initial_pages`, browser WASM memory-page constraints, Module Plan `WASM Pages` display, generated selector module-plan route metadata, or `module-plan-wasm-memory-drift`. Related routes: - `wiki/gguf-mirust/reports/browser-module-plan-total-budget-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-module-plan-origin-policy-memory-2026-06-28.md` - `wiki/gguf-mirust/reports/browser-combined-selector-assembly-memory-2026-06-28.md` - `.uai/short-term-memory.uai` - `.uai/long-term-memory.uai` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-wasm-memory-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md BYTES: 3079 SHA256: 071E1C816B8F5A5715EF183D40832E81ADBFF036038A62928A8F268E28DBA92D ================================================================================ # Browser Module Plan WASM Transfer Memory - 2026-06-28 status: reviewed_current authority: generated from current implementation and verification evidence ## Summary Generated module-plan selector entries and served `.module-plan.receipt` files now bind `module_plan_wasm_transfer_strategy=copy-then-release-v1`. The browser verifies selector and receipt agreement, renders the verified Module Plan `Transfer` row, and keeps the WASM byte-transfer contract aligned with the existing JavaScript copy-to-WASM and `dealloc` release discipline before generated model bytes or stack artifacts are fetched. ## Implementation Route - `tinyrustlm/tools/slm_pack/src/selector.rs` writes, parses, checksums, and validates `entry.N.module_plan_wasm_transfer_strategy`. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` writes `module_plan_wasm_transfer_strategy=copy-then-release-v1` into generated `.module-plan.receipt` files and selector route records. - `tinyrustlm/app/index.html` adds the Module Plan `Transfer` row. - `tinyrustlm/app/app.js` validates selector and receipt agreement, requires the `copy-then-release-v1` strategy, and renders the verified field only after the receipt is accepted. - `tinyrustlm/tools/browser-smoke.js` adds `module-plan-wasm-transfer-drift` and asserts generated roots render `copy-then-release-v1` while source roots render `unavailable`. - `tinyrustlm/tools/browser_harness/src/main.rs` includes the new row id in the static contract. ## Verified Behavior - Node syntax checks passed for `tinyrustlm/app/app.js` and `tinyrustlm/tools/browser-smoke.js`. - `cargo fmt --all -- --check` passed. - `cargo test -p tinyrustlm-slm-pack selector` passed with 71 tests. - `cargo test -p tinyrustlm-slm-pack browser_bundle` passed with 4 tests. - `cargo test -p tinyrustlm-browser-harness` passed with 6 tests. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` passed with 9 static checks. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\module-plan-wasm-transfer\tinyrustlm all` passed and validated 3 module-plan routes. - Generated-root `module-plan-wasm-transfer-drift` passed on `http://127.0.0.1:8231/app/`, returning `Module plan WASM transfer strategy mismatch` after selector plus module-plan receipt requests and before generated model routes. - Generated-root `combined-selector-cycle` passed on `http://127.0.0.1:8231/app/`, proving q4_0/q8_0/f32 generated assemblies render `Transfer` as `copy-then-release-v1` and still reach ready with ADP1 plus ASP1 plus ALR1 stack apply. - Source-root `ui-audit` passed on `http://127.0.0.1:8232/app/`, proving the fallback row remains `unavailable`. ## Routing Notes Open this report before changing browser WASM byte-copy helpers, generated bundle module-plan receipts, selector registry transfer-strategy validation, Module Plan `Transfer` display, or `module-plan-wasm-transfer-drift` smoke assertions. Keep this field separate from heap floor and export-set checks: it records how accepted bytes cross into WASM memory after route and envelope validation. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md BYTES: 14235 SHA256: 0D4C33B0BFF8BF0828C8F73CA3DC717CDEFF005AE9835BA7AF5FA1C4AF2F5843 ================================================================================ # Browser Multi-Parent Operator Provenance Memory - 2026-06-29 ## Purpose Route future agents to the proof that generated multi-parent selector entries carry receipt-bound operator metadata all the way into browser Model Provenance. This report covers the soup and sign-merge parent-pool paths where the browser now renders `receipt-bound / / ` from selector `entry.N.operator_receipt_*` fields. ## Implementation - `tinyrustlm/tools/slm_pack/src/multi_admission.rs` now emits receipt-bound operator metadata from the parent-pool operator receipt into multi-parent admission records. - Multi-parent admission records copy the receipt path, receipt checksum, operator id, operator kind, candidate `.slm` checksum, and candidate byte count. - Multi-parent admission summary validation now checks receipt status, operator identity, candidate checksum equality, and candidate byte-count equality. - `tinyrustlm/tools/slm_pack/src/selector.rs` already copies receipt-bound admission metadata into selector registry entries as `entry.N.operator_receipt_*`; generated multi-parent records now use that same route. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` tests prove generated soup selector registries contain operator receipt fields for q8 and all-quant roots. - `tinyrustlm/tools/browser-smoke.js` now expects generated multi-parent models to render the operator receipt row, with `seed-weighted-parent-pool-soup` for `multi-parent-soup-*` and `sign-aware-parent-pool-merge` for `multi-parent-sign-merge-*`. - `tinyrustlm/tools/browser-smoke.js` also has `generated-selector-operator-receipt-drift`, which mutates served generated selector `operator_receipt_candidate_artifact_bytes` fields before browser registry intake and proves no generated model, module-plan, assembly, adapter-family, or adapter-stack route is requested. - `tinyrustlm/app/app.js` now maps generated assembly-backed `multi-parent-soup-*` and `multi-parent-sign-merge-*` selector entries to their expected operator kinds before accepting `entry.N.operator_receipt_*`. - `tinyrustlm/tools/browser-smoke.js` now also has `generated-selector-operator-kind-drift`, which rewrites generated selector operator-kind fields while preserving byte echoes and proves the same fallback-before-generated-route boundary. ## Soup Browser Proof The fresh all-quant soup root was generated with: ```powershell C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-multi-parent-soup-operator-provenance\tinyrustlm all soup ``` The generated `models/selector.registry` contains `entry.N.operator_receipt_*` fields for all three soup entries: - `multi-parent-soup-f32`: `operator_receipt_operator_kind=seed-weighted-parent-pool-soup`, checksum `0x2efb938150b29ce3`. - `multi-parent-soup-q8`: `operator_receipt_operator_kind=seed-weighted-parent-pool-soup`, checksum `0x22cf99b6d8fcaf3b`. - `multi-parent-soup-q4`: `operator_receipt_operator_kind=seed-weighted-parent-pool-soup`, checksum `0x1eccc0af80f7e84e`. The browser proof passed with: ```powershell C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-local-server -- target\browser-served-multi-parent-soup-operator-provenance\tinyrustlm 8099 node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8099/app/ 9360 multi-parent-soup-q4 combined-selector-assembly ``` Observed Model Provenance Operator rows: - q4: `receipt-bound / seed-weighted-parent-pool-soup / 0x1eccc0af80f7e84e` - q8: `receipt-bound / seed-weighted-parent-pool-soup / 0x22cf99b6d8fcaf3b` - f32: `receipt-bound / seed-weighted-parent-pool-soup / 0x2efb938150b29ce3` The same smoke also proved q4-first selection, q4/q8/f32 switching in one browser session, module-plan verification before model bytes, `soup.*` evidence fetches, adapter-family receipt and manifest verification, ADP1/ASP1/ALR1 Rust validation, three adapter applies, 21 generated self-assembly fetches per entry, and matching actual route-set, module-byte, and module-checksum accounting. ## Sign-Merge Browser Proof The fresh all-quant sign-merge root was generated with: ```powershell C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-multi-parent-sign-merge-operator-provenance\tinyrustlm all sign-merge ``` The generated `models/selector.registry` contains `entry.N.operator_receipt_*` fields for all three sign-merge entries: - `multi-parent-sign-merge-f32`: `operator_receipt_operator_kind=sign-aware-parent-pool-merge`, checksum `0x37052cadf8caf762`. - `multi-parent-sign-merge-q8`: `operator_receipt_operator_kind=sign-aware-parent-pool-merge`, checksum `0xf1eb189593029e5d`. - `multi-parent-sign-merge-q4`: `operator_receipt_operator_kind=sign-aware-parent-pool-merge`, checksum `0xeb8d651eb9fccc62`. The browser proof passed with: ```powershell C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-local-server -- target\browser-served-multi-parent-sign-merge-operator-provenance\tinyrustlm 8109 node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8109/app/ 9361 multi-parent-sign-merge-q4 combined-selector-assembly ``` Observed Model Provenance Operator rows: - q4: `receipt-bound / sign-aware-parent-pool-merge / 0xeb8d651eb9fccc62` - q8: `receipt-bound / sign-aware-parent-pool-merge / 0xf1eb189593029e5d` - f32: `receipt-bound / sign-aware-parent-pool-merge / 0x37052cadf8caf762` The sign-merge smoke also proved q4-first selection, q4/q8/f32 switching in one browser session, module-plan verification before model bytes, `sign-merge.*` evidence fetches, adapter-family receipt and manifest verification, ADP1/ASP1/ALR1 Rust validation, three adapter applies, 21 generated self-assembly fetches per entry, and matching actual route-set, module-byte, and module-checksum accounting. ## Generated Drift Proof The generated selector drift proof passed for both parent-pool families: ```powershell C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-local-server -- target\browser-served-multi-parent-soup-operator-provenance\tinyrustlm 8112 node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8112/app/ 9370 multi-parent-soup-q4 generated-selector-operator-receipt-drift C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-local-server -- target\browser-served-multi-parent-sign-merge-operator-provenance\tinyrustlm 8112 node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8112/app/ 9371 multi-parent-sign-merge-q4 generated-selector-operator-receipt-drift ``` Both smokes mutated generated `models/selector.registry` operator receipt byte echoes before app.js accepted selector entries. The browser rejected the generated q4/q8/f32 entries, selected fallback `tinylm16q8`, rendered Operator as `unavailable`, and completed one-token generation from the checked local q8 fallback served by the harness. Observed request shape for both families: - `/runtime/tinyrustlm.wasm.manifest` - `/runtime/tinyrustlm.wasm` - `/models/selector.registry` - `/models/tinylm16-q8.slm` - `/models/tinylm16-q8.slm.manifest` No generated `.slm`, `.module-plan.receipt`, `.assembly.receipt`, `.adapter-family.receipt`, ADP1, ASP1, or ALR1 route was requested after the selector operator receipt drift. ## Generated Operator-Kind Drift Proof Fresh generated roots were staged with the current source app shell: ```powershell C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-multi-parent-soup-operator-kind-drift\tinyrustlm all soup C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-multi-parent-sign-merge-operator-kind-drift\tinyrustlm all ``` The new generated selector operator-kind drift proof passed for both parent-pool families: ```powershell C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-local-server -- target\browser-served-multi-parent-soup-operator-kind-drift\tinyrustlm 8114 node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8114/app/ 9381 multi-parent-soup-q4 generated-selector-operator-kind-drift C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-local-server -- target\browser-served-multi-parent-sign-merge-operator-kind-drift\tinyrustlm 8114 node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8114/app/ 9382 multi-parent-sign-merge-q4 generated-selector-operator-kind-drift ``` Both smokes rewrote generated selector `operator_receipt_operator_kind` values before app.js accepted selector entries. The browser rejected the generated q4/q8/f32 entries, selected fallback `tinylm16q8`, rendered Operator as `unavailable`, and completed one-token generation from the checked local q8 fallback served by the harness. Observed request shape for both families matched the byte-drift proof: - `/runtime/tinyrustlm.wasm.manifest` - `/runtime/tinyrustlm.wasm` - `/models/selector.registry` - `/models/tinylm16-q8.slm` - `/models/tinylm16-q8.slm.manifest` No generated `.slm`, `.module-plan.receipt`, `.assembly.receipt`, `.adapter-family.receipt`, ADP1, ASP1, or ALR1 route was requested after the selector operator kind drift. The positive sign-merge generated root still passed: ```powershell node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8114/app/ 9383 multi-parent-sign-merge-q4 combined-selector-assembly ``` That pass proved q4/q8/f32 generated entries still reach Ready, render `receipt-bound / sign-aware-parent-pool-merge / ` Operator rows, verify module plans, fetch sign-merge evidence, validate ADP1/ASP1/ALR1 stacks, and apply three adapters before generation. The compact federated selector fixture still passed: ```powershell node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8115/app/ 9384 multi-parent-sign-merge-q8 multi-parent-registry ``` That pass rendered `receipt-bound / federated-local-update-average / 0x00000000000000b0`, proving the browser operator-kind check is scoped to generated assembly-backed entries rather than every candidate id that starts with `multi-parent-*`. ## Verification - `node --check tinyrustlm\tools\browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack multi_admission -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack writes_and_validates_selector_registry_from_multi_parent_admission_record -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack writes_browser_multi_parent_soup_bundle -- --nocapture` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8099/app/ 9360 multi-parent-soup-q4 combined-selector-assembly` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-multi-parent-sign-merge-operator-provenance\tinyrustlm all sign-merge` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8109/app/ 9361 multi-parent-sign-merge-q4 combined-selector-assembly` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8112/app/ 9370 multi-parent-soup-q4 generated-selector-operator-receipt-drift` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8112/app/ 9371 multi-parent-sign-merge-q4 generated-selector-operator-receipt-drift` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8113/app/ 9372 tinylm16q8 selector-operator-receipt-drift` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-multi-parent-soup-operator-kind-drift\tinyrustlm all soup` - `C:\Users\AI\.cargo\bin\cargo.exe run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-multi-parent-sign-merge-operator-kind-drift\tinyrustlm all` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8114/app/ 9381 multi-parent-soup-q4 generated-selector-operator-kind-drift` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8114/app/ 9382 multi-parent-sign-merge-q4 generated-selector-operator-kind-drift` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8114/app/ 9383 multi-parent-sign-merge-q4 combined-selector-assembly` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8115/app/ 9384 multi-parent-sign-merge-q8 multi-parent-registry` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8115/app/ 9385 tinylm16q8 selector-operator-receipt-drift` - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8114/app/ 9386 multi-parent-sign-merge-q4 generated-selector-operator-receipt-drift` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack --quiet` with 292 tests passed. - `git diff --check` returned only line-ending normalization notices. - Ports 8114 and 8115 had no listening server after the browser-smoke runs; remaining TCP rows were `TimeWait` only. ## Test Coverage Notes No coverage tool is active in this zero-dependency workspace. Focused coverage now exercises the changed multi-parent admission receipt-path parameter, receipt text parameter, selector copied fields, browser-bundle generated soup registry fields, browser-visible operator row assertion, generated selector operator receipt byte-drift fallback behavior, generated selector operator-kind fallback behavior, and the app.js generated assembly parameter that scopes operator-kind agreement. ## Routing Open this report before changing: - `multi-parent-admission-record` receipt carry-forward. - Selector `entry.N.operator_receipt_*` fields. - Browser Model Provenance Operator rendering for generated parent-pool models. - `generated-selector-operator-receipt-drift`, `generated-selector-operator-kind-drift`, or selector operator receipt byte/kind equality checks. - Browser-generated assembly scoping in `expectedGeneratedOperatorReceiptKind`. - `browser-multi-parent-bundle ... soup` registry output. - Generated multi-parent browser smoke provenance assertions. Related memory: - `wiki/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29.md` - `wiki/gguf-mirust/reports/browser-parent-pool-soup-bundle-memory-2026-06-29.md` - `wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md` - `wiki/gguf-mirust/reports/multi-parent-soup-manifest-memory-2026-06-29.md` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-multi-quant-selector-root-memory-2026-06-27.md BYTES: 3531 SHA256: 4509B88D0202052A43EE3B0E4F8BF5D88EEDB4AA4809EDA8F6D667AB003D5F6C ================================================================================ --- title: Browser Multi Quant Selector Root Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-multi-quant-selector-root-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T15:17:51Z --- # Browser Multi Quant Selector Root Memory ## Summary TinyRustLM generated browser bundles can now stage one runnable selector root containing the f32, q8_0, and q4_0 multi-parent sign-merge modules together. The shared `selector.registry` carries three admitted model entries, nine adapter routes, three adapter-family receipts, three assembly receipts, and the browser can switch between entries in the same served root before applying each receipt-preferred sparse `ASP1` sidecar. ## Implementation Memory - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` now stages each quantized generated module through a shared helper, then writes one combined selector registry from all staged admission paths and route records. - `browser-multi-parent-bundle all` expands to f32, q8_0, and q4_0 while the existing single-quantization modes still produce one-entry roots. - Each staged module keeps its own evidence directory, model file, manifest, assembly receipt, adapter-family receipt, self `ADP1`, family `ADP1`, sparse `ASP1`, and adapter manifests under the shared generated root. - `tinyrustlm/tools/slm_pack/src/main.rs` CLI usage now documents the `all` mode. - The browser app schema did not need a new field: existing selector entries, assembly receipt routes, adapter-family receipt routes, preferred adapter fields, and adapter manifest verification are reused by candidate id. ## Validation Memory - `cargo fmt --all -- --check` passed through `C:\Users\AI\.cargo\bin\cargo.exe`. - `cargo test -p tinyrustlm-slm-pack browser_bundle` passed with 3 filtered tests, including `writes_combined_browser_multi_parent_bundle`. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-multi-quant-selector\tinyrustlm all` staged one root with `admissions: 3`, `adapter_routes: 9`, `adapter_family_routes: 3`, and `assembly_routes: 3`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18677/app/ 9267 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` passed from the combined root, selected adapter index `2`, applied `Multi-parent sign-merge q4_0 sparse ASP1`, and preserved `active_quantization_mode=q4_0`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18677/app/ 9268 multi-parent-sign-merge-q8 adapter-sidecar-registry-file` passed from the combined root, selected adapter index `2`, applied `Multi-parent sign-merge q8_0 sparse ASP1`, and preserved `active_quantization_mode=q8_0`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18677/app/ 9269 multi-parent-sign-merge-f32 adapter-sidecar-registry-file` passed from the combined root, selected adapter index `2`, applied `Multi-parent sign-merge f32 sparse ASP1`, and preserved `active_quantization_mode=f32`. - `cargo test --workspace` passed with 238 checks across crates and doc-tests. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - Port `18677` had no listener after the smoke run, and the late-released temporary browser profile directories were removed from `%TEMP%`. ## Routing Notes Use this report before changing generated multi-parent bundle staging, selector registry fan-in, browser selector entry switching, generated f32/q8_0/q4_0 adapter-family routing, or longer browser route exercises for modular self-assembly. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-multi-quant-selector-root-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-parent-pool-soup-bundle-memory-2026-06-29.md BYTES: 6549 SHA256: A1DCD6DCB1CD938542360F3068FA2D6A30F11DF1F1AE58DE18F56A7EF74CE74F ================================================================================ # Browser Parent-Pool Soup Bundle Memory - 2026-06-29 ## Purpose Route future agents to the first generated browser bundle path for a non-sign-merge parent-pool operator. This report covers the `soup` bundle lane that writes `multi-parent-soup-*` models, serves `soup.*` evidence files, and keeps selector, module-plan, assembly, and browser validators bound to the selected operator prefix. ## Implementation - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` now has a `BundleOperator` descriptor for `sign-merge` and `soup`. - `browser-multi-parent-bundle [f32|q8_0|q4_0|all] [sign-merge|soup]` defaults to sign-merge and can generate soup bundles with ids such as `multi-parent-soup-q8`. - Soup bundles call `soup::write_candidate_path`, then reuse the same multi-parent candidate manifest, promotion, runtime, eval, admission, adapter-family, assembly, and module-plan pipeline. - Soup evidence files are named `soup.operator`, `soup.candidate`, `soup.promotion`, `soup.runtime`, `soup.eval`, and `soup.multi.admission`. - Assembly receipts emit `assembly_strategy=multi-parent-weighted-soup` for soup and keep sign-merge receipts at `assembly_strategy=multi-parent-sign-merge`. - `selector.rs` derives the module-plan evidence family from `module_plan_operator_receipt_path`, currently accepting `sign-merge` and `soup` operator prefixes. - `tinyrustlm/app/app.js` derives browser assembly evidence route checks from the module-plan/assembly operator receipt path, then recomputes the route-set checksum using that prefix. - `tinyrustlm/tools/browser-smoke.js` derives multi-parent evidence routes from `multi-parent-soup-*` ids when a soup model is explicitly supplied. - `tinyrustlm/tools/browser-smoke.js` has a generated multi-parent helper so both `multi-parent-sign-merge-*` and `multi-parent-soup-*` file-backed bundles share eval-proof, parent-pool, selector-registry, module-plan route-set, and adapter-stack checks. - `tinyrustlm/tools/browser-smoke.js` derives the combined selector family from the requested model key, so `multi-parent-soup-q4 combined-selector-assembly` expects the soup q4/q8/f32 sequence while the default remains sign-merge. ## Browser Smoke Continuation The q8 soup generated-root smoke path was proven with: ```powershell cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-multi-parent-soup-q8-check\tinyrustlm q8_0 soup cargo run -p tinyrustlm-local-server -- target\browser-served-multi-parent-soup-q8-check\tinyrustlm 8097 node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8097/app/ 9347 multi-parent-soup-q8 adapter-sidecar-registry-file node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8097/app/ 9349 multi-parent-soup-q8 multi-parent-registry-file ``` The adapter-sidecar smoke proved `multi-parent-soup-q8` model selection, `q8_0` diagnostics, `soup.*` assembly evidence routes, a matching module-plan route-set checksum, 21 generated self-assembly fetches, adapter-family receipt/manifests, and ADP1/ASP1/ALR1 validation before generation. The multi-parent-registry smoke proved the generated selector route requests the expected local q8 soup model, manifest, assembly, evidence, module-plan, and adapter-family files. The all-quantization soup generated-root smoke path was proven with: ```powershell cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target\browser-served-multi-parent-soup-all-check\tinyrustlm all soup cargo run -p tinyrustlm-local-server -- target\browser-served-multi-parent-soup-all-check\tinyrustlm 8098 node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8098/app/ 9358 multi-parent-soup-q4 combined-selector-assembly node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8098/app/ 9359 multi-parent-soup-q4 combined-selector-cycle 2 ``` The combined-selector smoke proved q4-first frugal default selection with options `multi-parent-soup-f32`, `multi-parent-soup-q8`, and `multi-parent-soup-q4`, then walked q4, q8, and f32 soup entries in one browser session. Each entry reached Ready only after module-plan receipt verification, model/manifest acceptance, `soup.*` evidence verification, adapter-family receipt and manifest verification, ADP1/ASP1/ALR1 validation, three adapter applies, 21 generated self-assembly fetches, matching actual route-set checksum, matching actual module bytes, and matching actual module checksums. The cycle smoke repeated the soup family twice in one page: q4, q8, f32, q4, q8, and f32. It proved the q4 default, release-before-reassembly after the initial pass, fresh module-plan/model/manifest/evidence/adapter-family/stack route fetches, three Rust validations and three applies per pass, 21 generated self-assembly fetches per pass, and matching actual route-set, module-byte, and module-checksum accounting per pass. ## Verification - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-slm-pack writes_browser_multi_parent_soup_bundle -- --nocapture` - `cargo test -p tinyrustlm-slm-pack browser_bundle -- --nocapture` - `cargo test -p tinyrustlm-slm-pack module_plan -- --nocapture` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo test -p tinyrustlm-slm-pack` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8097/app/ 9347 multi-parent-soup-q8 adapter-sidecar-registry-file` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8097/app/ 9349 multi-parent-soup-q8 multi-parent-registry-file` - `cargo test -p tinyrustlm-slm-pack writes_combined_browser_multi_parent_soup_bundle -- --nocapture` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8098/app/ 9358 multi-parent-soup-q4 combined-selector-assembly` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8098/app/ 9359 multi-parent-soup-q4 combined-selector-cycle 2` Observed full packer suite result: 291 passed, 0 failed. ## Routing Open this report before changing: - `browser-multi-parent-bundle` operator selection. - Generated evidence filenames for parent-pool operators. - `module_plan_operator_receipt_path` validation. - Browser route-set checksum preimages for generated self-assembly. - Browser assembly receipt validation for sign-merge or soup. Related memory: - `wiki/gguf-mirust/reports/weighted-soup-operator-memory-2026-06-29.md` - `wiki/gguf-mirust/reports/multi-parent-soup-manifest-memory-2026-06-29.md` - `wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md` - `wiki/gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29.md` ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-parent-pool-soup-bundle-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-preferred-adapter-route-memory-2026-06-27.md BYTES: 3666 SHA256: D37DA3659296328E7B072A721E697FD42FD128DDA60B8C0EF9E7D9D4B5CA1BA3 ================================================================================ --- title: Browser Preferred Adapter Route Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-preferred-adapter-route-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T15:01:33Z --- # Browser Preferred Adapter Route Memory ## Summary TinyRustLM generated adapter-family receipts now declare a preferred local adapter member. The packer derives the preferred member from the generated family, favoring the sparse `ASP1` route when present, records the preferred adapter index, adapter path, and manifest path in the checksum-bound receipt, and validates the recomputed receipt. The browser verifies those receipt fields after fetching the adapter-family receipt and all member manifests, then defaults the Adapter Sidecar selector to the verified preferred member before apply. ## Implementation Memory - `tinyrustlm/tools/slm_pack/src/adapter_family.rs` writes `adapter_family_preferred_adapter_index`, `adapter_family_preferred_adapter_path`, and `adapter_family_preferred_manifest_path` into the deterministic adapter-family receipt. The preferred member is the first `.asp1` route when present; otherwise it is the first compatible member. - `tinyrustlm/app/app.js` validates the preferred adapter index, route, and manifest path against the already parsed registry adapter list before enabling family options, then selects that member in the Adapter Sidecar dropdown after receipt and manifest verification. - `tinyrustlm/tools/browser-smoke.js` no longer hand-selects the generated sparse member. It observes the app-selected value before clicking Apply, so `selectedAdapterBeforeApply=2` proves the browser consumed the verified receipt preference. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` tests now assert that f32/q8_0/q4_0 generated bundle receipts prefer the sparse `ASP1` member. ## Validation Memory - `node --check tinyrustlm/app/app.js`, `node --check tinyrustlm/tools/browser-smoke.js`, and `node --check tinyrustlm/tools/wasm-abi-smoke.js` passed. - `cargo fmt --all -- --check` passed through `C:\Users\AI\.cargo\bin\cargo.exe`. - `cargo test -p tinyrustlm-slm-pack adapter_family` passed with 6 filtered tests. - `cargo test -p tinyrustlm-slm-pack browser_bundle` passed with 2 filtered tests. - `cargo test --workspace` passed with 237 checks across crates and doc-tests. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-preferred-adapter-route\tinyrustlm f32` staged a generated f32 root whose receipt prefers `../models/multi-parent-sign-merge-f32-sparse.asp1`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18675/app/ 9265 multi-parent-sign-merge-f32 adapter-sidecar-registry-file` passed with `selectedAdapterBeforeApply` equal to `2`, applying `Multi-parent sign-merge f32 sparse ASP1`. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-preferred-adapter-route-q8\tinyrustlm q8_0` staged a generated q8_0 root whose receipt prefers `../models/multi-parent-sign-merge-q8-sparse.asp1`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18676/app/ 9266 multi-parent-sign-merge-q8 adapter-sidecar-registry-file` passed with `selectedAdapterBeforeApply` equal to `2`, applying `Multi-parent sign-merge q8_0 sparse ASP1` and preserving `active_quantization_mode=q8_0`. ## Routing Notes Use this report before changing adapter-family receipt fields, generated bundle adapter ordering, browser Adapter Sidecar default selection, or `adapter-sidecar-registry-file` selection assertions. This is the first browser-consumed preferred-module signal for the modular self-assembly lane. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-preferred-adapter-route-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-runtime-assembly-diagnostics-memory-2026-06-28.md BYTES: 2982 SHA256: C2CF05E8739F35C9050453610BDA3591DD349D82F05338810F03C59B6853C8B0 ================================================================================ --- title: Browser Runtime Assembly Diagnostics Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-runtime-assembly-diagnostics-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T13:40:00Z --- # Browser Runtime Assembly Diagnostics Memory TinyRustLM now carries Rust-owned assembly-state evidence in runtime diagnostics. Model load records a nonzero `assembly_state_checksum` with `adapter_apply_count=0`; successful `apply_adapter_delta` increments `adapter_apply_count`, records `last_adapter_checksum`, and folds the adapter into the assembly checksum. Freeing or failed model load clears the fields. ## Implementation - `tinyrustlm/runtime/src/diagnostics.rs` renders `adapter_apply_count`, `last_adapter_checksum`, and `assembly_state_checksum` in diagnostics JSON without serde. - `tinyrustlm/runtime/src/generate.rs` seeds the assembly digest from the loaded model checksum and quantization, records each Rust-accepted adapter package after successful apply, and clears assembly state on free or load failure. - `tinyrustlm/tools/wasm-abi-smoke.js` verifies the fields through the WASM ABI. - `tinyrustlm/tools/browser-smoke.js` requires generated q4_0/q8_0/f32 auto assembly to show `adapter_apply_count=3` plus nonzero adapter and assembly checksums before generation; checked manual sidecar apply requires count 1. ## Verification - `cargo fmt --all -- --check` - `node --check tinyrustlm/tools/wasm-abi-smoke.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo test -p tinyrustlm-runtime` - `cargo build -p tinyrustlm-runtime --release --target wasm32-unknown-unknown` - `cargo run -p tinyrustlm-slm-pack -- runtime-wasm-manifest tinyrustlm/runtime/tinyrustlm.wasm tinyrustlm/runtime/tinyrustlm.wasm.manifest` - `node tinyrustlm/tools/wasm-abi-smoke.js` - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` - `cargo test -p tinyrustlm-browser-harness` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/runtime-assembly-diagnostics/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18770/app/ 19621 multi-parent-sign-merge-q4 combined-selector-assembly` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18770/app/ 19624 multi-parent-sign-merge-q4 combined-selector-cycle 2` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18771/app/ 19623 tinyf32 adapter-sidecar` ## Evidence Notes The generated combined-selector assembly smoke rendered q4_0, q8_0, and f32 entries with `adapter_apply_count=3` before generation. The checked manual adapter smoke rendered count 0 before apply and count 1 after apply. The WASM ABI smoke rendered count 1 after direct adapter apply and zero state after `free_model`. ## Routing Use this report when changing Rust diagnostics, adapter apply accounting, generated auto-assembly browser assertions, manual adapter sidecar assertions, or claims that browser self-assembly reached Rust runtime state. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-runtime-assembly-diagnostics-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-runtime-manifest-memory-2026-06-27.md BYTES: 3870 SHA256: 228588130FDC5FB879C269F913DCF4B1C43B1A37ADC3E3443A3E0D2F0F633A56 ================================================================================ --- title: Browser Runtime Manifest Memory 2026-06-27 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-runtime-manifest-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T18:07:37Z --- # Browser Runtime Manifest Memory TinyRustLM now verifies the browser runtime WASM bytes before instantiating them. The checked app fetches `runtime/tinyrustlm.wasm.manifest`, validates the runtime kind, status, local path, byte count, checksum, and next gate, then fetches `runtime/tinyrustlm.wasm` and recomputes the same 64-bit local checksum before `WebAssembly.instantiate`. This extends the self-assembly path from verified model, adapter, receipt, and evidence files to the runtime module itself. The browser now proves the Rust engine bytes first, then continues into selector-registry model choice, assembly receipts, adapter-family receipts, manifest checks, and receipt-preferred sparse ASP1 auto assembly. ## Implementation - `tinyrustlm/app/app.js` adds `../runtime/tinyrustlm.wasm.manifest`, byte-level checksum recomputation, runtime manifest field validation, byte-count validation, and pre-instantiation checksum validation. - `tinyrustlm/runtime/tinyrustlm.wasm.manifest` binds the checked runtime to byte count `135624` and checksum `0x63d480b279aaa3be`; SHA256 for the manifest file is `7C7697DD8504CD45BA016602BE23D257ED8B8DFB1A28EBDC2DFDDBABE021EFC6`. - `tinyrustlm/tools/slm_pack` writes runtime manifests for generated `browser-multi-parent-bundle` roots and exposes `runtime-wasm-manifest ` for checked runtime refresh after a rebuild. - `tools/vs/Build-TinyRustLM.ps1` calls `runtime-wasm-manifest` immediately after copying the release WASM into `tinyrustlm/runtime/`. - `tinyrustlm/tools/browser_harness` now treats the runtime manifest path, fields, byte count, and loopback route as part of the static browser contract. - `tinyrustlm/tools/browser-smoke.js` asserts normal smokes request the runtime manifest and adds `runtime-manifest-drift`, which intercepts the manifest with a valid shape and mismatched checksum. ## Verification - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - PowerShell parse check for `tools/vs/Build-TinyRustLM.ps1` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-slm-pack browser_bundle::` with 4 focused tests - `cargo test -p tinyrustlm-browser-harness` with 6 focused tests - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` with 9 static checks - `cargo run -p tinyrustlm-slm-pack -- runtime-wasm-manifest tinyrustlm/runtime/tinyrustlm.wasm tinyrustlm/runtime/tinyrustlm.wasm.manifest` - `tools/vs/Build-TinyRustLM.ps1 -Configuration Debug` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/browser-runtime-manifest/tinyrustlm all` - Browser smoke `single` against the checked source root requested `/runtime/tinyrustlm.wasm.manifest`, verified the runtime, loaded TinyLM-16M q8_0, and generated `e`. - Browser smoke `runtime-manifest-drift` stopped at boot with `WASM runtime checksum mismatch` and made no `.slm` model request. - Browser smoke `adapter-sidecar-registry-file` against the generated q4 root requested the runtime manifest, loaded the generated selector route, verified assembly evidence and adapter-family sidecars, auto-applied sparse ASP1, and generated `e`. - `cargo test --workspace` passed with 245 checks. ## Routing Load this report before changing runtime WASM rebuild/copy flows, generated browser bundle runtime staging, browser boot sequencing, runtime manifest fields, or smoke assertions around WASM instantiation. This report complements the browser text-sidecar, selector budget, auto-assembly, adapter-family receipt, and assembly receipt reports; together they define the browser-local module assembly chain. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-runtime-manifest-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-selector-budget-contract-memory-2026-06-27.md BYTES: 3465 SHA256: 2EEEC2EE7B665B4CC614E44B3190AE020ECCB73CE834C05E0FB3327EE90A59EA ================================================================================ --- title: Browser Selector Budget Contract Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-selector-budget-contract-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T16:08:47Z --- # Browser Selector Budget Contract Memory ## Summary TinyRustLM selector registries now carry a registry-level browser model-byte budget. Rust emits and validates `selector_model_byte_budget=33554432`, rejects admitted model entries above that budget, and the browser requires the registry budget before accepting selector entries. ## Implementation Memory - `tinyrustlm/tools/slm_pack/src/selector.rs` now writes `selector_model_byte_budget=33554432` into every selector registry. - `validate-selector-registry` recomputes the budget line and rejects drift. - Selector registry construction rejects `candidate_artifact_bytes` values that are zero, non-decimal, or above the 32 MiB browser budget before writing an entry. - `tinyrustlm/app/app.js` now requires `selector_model_byte_budget`, rejects registries whose declared budget exceeds the browser constant, and checks each `entry.N.model_bytes` against the registry budget before model fetch. - `tinyrustlm/tools/browser-smoke.js` adds the budget line to intercepted selector registry fixtures, including `selector-budget`, `multi-parent-registry`, and q8 adapter-sidecar registry smoke. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` now asserts generated single-quant and combined roots carry the budget line. ## Validation Memory - `node --check tinyrustlm/app/app.js` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `cargo fmt --all -- --check` passed through `C:\Users\AI\.cargo\bin\cargo.exe`. - `cargo test -p tinyrustlm-slm-pack selector::` passed with 21 filtered tests, including over-budget model-byte rejection and registry budget drift rejection. - `cargo test -p tinyrustlm-slm-pack browser_bundle::` passed with 3 filtered tests asserting budget metadata in generated registries. - `browser-smoke multi-parent-registry` passed against `http://127.0.0.1:18680/app/` with the intercepted budget-bearing registry. - `browser-smoke selector-budget` passed against `http://127.0.0.1:18680/app/`, proving an oversized entry remained unaccepted and unfetched while fallback `tinylm16q8` loaded. - `browser-multi-parent-bundle .\target\browser-selector-budget-contract\tinyrustlm all` generated a three-entry selector root whose registry declared `selector_model_byte_budget=33554432` and model byte counts `20352`, `8832`, and `6592`. - Served-root `adapter-sidecar-registry-file` smoke passed on `http://127.0.0.1:18681/app/` for `multi-parent-sign-merge-q4`, proving the generated budget-bearing registry still defaulted to q4_0, loaded assembly evidence, selected sparse ASP1, and applied the adapter. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` passed with 8 checks. - `cargo test --workspace` passed with 241 checks across crates and doc-tests. - `git diff --check` completed with line-ending normalization notices only. - Ports `18680` and `18681` had no listeners after the smoke run, and matching temporary browser smoke profiles under `%TEMP%` were removed. ## Routing Notes Use this report before changing `selector_model_byte_budget`, selector registry model-byte validation, generated browser bundle registry fields, browser selector intake, or browser smokes that intercept selector registry text. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-selector-budget-contract-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-selector-budget-memory-2026-06-27.md BYTES: 2374 SHA256: 44C0A755E57BF105708065EB05B795D710F003EADE2D0D6B985ED428CEC90DE0 ================================================================================ --- title: Browser Selector Budget Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-selector-budget-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T15:54:11Z --- # Browser Selector Budget Memory ## Summary TinyRustLM browser selector intake now treats `entry.N.model_bytes` as a browser-local resource budget before selecting registry models. Registry entries must declare a positive decimal byte count no larger than 32 MiB, and fetched model bytes must match the declared count before the buffer is copied into WASM. ## Implementation Memory - `tinyrustlm/app/app.js` rejects selector registry entries that omit `entry.N.model_bytes`, use a non-decimal or unsafe integer byte value, declare zero bytes, or exceed the 32 MiB browser selector budget. - `tinyrustlm/app/app.js` keeps static fallback models available when a selector registry is rejected, so local TinyLM fixtures still load without registry metadata. - `tinyrustlm/app/app.js` checks a registry-selected model's fetched byte length against the declared `model_bytes` value before transferring bytes to the Rust runtime. - `tinyrustlm/tools/browser-smoke.js` adds `selector-budget` mode with an intercepted registry entry declaring `33554433` bytes for an oversized q4_0 parent. ## Validation Memory - `node --check tinyrustlm/app/app.js` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `cargo fmt --all -- --check` passed through `C:\Users\AI\.cargo\bin\cargo.exe`. - `browser-smoke selector-budget` passed against `http://127.0.0.1:18679/app/`, proving the oversized registry option was not accepted, `/models/oversized-browser-parent.slm` was not requested, and fallback `tinylm16q8` loaded with q8_0 diagnostics. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` passed with 8 checks. - `cargo test --workspace` passed with 239 checks across crates and doc-tests. - `git diff --check` completed with line-ending normalization notices only. - Port `18679` had no listener after the smoke run, and no matching temporary browser smoke profiles remained under `%TEMP%`. ## Routing Notes Use this report before changing selector registry entry budget fields, registry model-byte validation, selector fallback behavior, or browser smoke assertions that prove oversized registry models are ignored before fetch. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-selector-budget-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-selector-genome-fitness-memory-2026-06-28.md BYTES: 2460 SHA256: 89755A73E94A90AC86CCFABD3DA39721E1212D71B0A14863ECF7CCC9B674EFA5 ================================================================================ --- title: Browser Selector Genome Fitness Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-selector-genome-fitness-memory-2026-06-28/ status: reviewed reviewed_utc: 2026-06-28T22:40:00Z --- # Browser Selector Genome Fitness Memory ## Routing Summary Generated selector registries now carry ModelBreeder-inspired genome and fitness routing fields without changing the quality authority of the tiny fixtures. Open `tinyrustlm/tools/slm_pack/src/selector.rs` for generation and validation, `tinyrustlm/app/app.js` plus `tinyrustlm/app/index.html` for browser rendering, and `tinyrustlm/tools/browser-smoke.js` for served-root proof. ## Implementation Memory - `selector.registry` entries emit `entry.N.genome_id`, `entry.N.genome_strategy=selector-admission-genome-v1`, `entry.N.genome_lineage_status=admission-bound`, `entry.N.genome_lineage_checksum`, `entry.N.fitness_vector_status=eval-bound`, and `entry.N.fitness_vector_checksum`. - Genome ids are deterministic checksums over the candidate id, model shape, quantization, output contract, and `.slm` checksum. - Genome lineage checksums summarize admission, promotion, runtime-smoke, and eval manifest checksums. - Fitness vector checksums summarize scoped eval facts: quality scope, quality boundary, eval dataset, cases passed, and eval-case evidence checksum. - The browser rejects generated selector entries missing the genome/fitness fields, then renders compact `Genome` and `Fitness` rows in Model Provenance for registry-backed entries. ## Verification Memory - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack` - Fresh generated `browser-multi-parent-bundle .\target\browser-served-modelbreeder\tinyrustlm all` - Served-root smoke: `combined-selector-assembly` on `http://127.0.0.1:8096/app/`, proving q4_0/q8_0/f32 generated entries show hex genome ids and `eval-bound / ` fitness vectors while still loading module plans, assembly receipts, evidence files, adapter-family receipts, adapter manifests, and ADP1/ASP1/ALR1 stacks locally. ## Next Route Future genome/fitness extensions should stay receipt-driven: add novelty, population, or speciation fields first to typed selector/admission/review sidecars, then render only the bounded summary needed for browser provenance. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-selector-genome-fitness-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28.md BYTES: 3749 SHA256: 479F96F62FA73B2B39D588BB2C5A2E7CB30EE7A8A9698270F9072041B8F47E78 ================================================================================ --- title: Browser Selector Heritable Artifact Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28/ status: reviewed reviewed_utc: 2026-06-28T17:44:00Z --- # Browser Selector Heritable Artifact Memory ## Routing Summary Generated selector registries now carry the ModelBreeder heritable-artifact lane beside genome, species, novelty, population, mate-selection, phenotype evidence, and fitness evidence. Open `tinyrustlm/tools/slm_pack/src/selector.rs` for registry generation and validation, `tinyrustlm/app/app.js` plus `tinyrustlm/app/index.html` for browser intake and rendering, and `tinyrustlm/tools/browser-smoke.js` for served-root proof. ## Implementation Memory - `selector.registry` entries emit `entry.N.heritable_artifact_id`, `entry.N.heritable_artifact_strategy=selector-heritable-artifact-v1`, `entry.N.heritable_artifact_status=served-artifact-bound`, and `entry.N.heritable_artifact_checksum`. - Heritable artifact ids hash candidate id, source artifact path, served model path, manifest path, model bytes, SLM checksum, model shape, quantization, output contract, and genome id. - Heritable artifact checksums bind that id to genome lineage, phenotype evidence, fitness vector, provenance manifest, runtime-smoke manifest, adapter-family receipt state, assembly receipt state, and module-plan receipt state. - The browser rejects registry entries missing heritable-artifact metadata, then renders a compact `Artifact` row in Model Provenance as ` / / `. - Browser smoke asserts generated registry-backed q4_0, q8_0, and f32 entries display `served-artifact-bound / / ` while keeping source-root fallback rows unavailable. - Exact generated module-plan checksum baselines were refreshed because the selector-linked provenance and receipt text changed while byte totals stayed `103780 bytes` for q4_0, `106020 bytes` for q8_0, and `117554 bytes` for f32. ## Verification Memory - `C:\Users\AI\.cargo\bin\cargo.exe fmt --check` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector` with 53 selector-filtered tests passed. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle` with 4 tests passed. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` with 6 tests passed. - Fresh generated `browser-multi-parent-bundle target\browser-served-heritable-artifact\tinyrustlm all`, with selector registry validation passing for 3 admissions, 12 adapter routes, 3 adapter-family routes, 3 assembly routes, and 3 module-plan routes. - Served-root smoke: `combined-selector-assembly` on `http://127.0.0.1:8100/app/` with debugger port `19572`, proving q4_0, q8_0, and f32 generated entries show `served-artifact-bound / / ` while still loading module plans, assembly receipts, evidence files, adapter-family receipts, adapter manifests, and ADP1/ASP1/ALR1 stacks locally. No coverage tool is active in the no-third-party workspace, so focused syntax, Rust tests, generated-root, and browser-smoke evidence is the recorded coverage evidence for this bead. ## Research Route This implements the heritable-artifact lane from `wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md` by turning served artifact identity into selector-visible provenance metadata. Future work can deepen this into richer artifact inheritance records only after Rust validators and browser smokes cover every added selector field. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28.md BYTES: 3638 SHA256: AEA83101E25E26E81495C42CA8E88A8067D5189315D9FDA12FBA8C2E5F6716C3 ================================================================================ --- title: Browser Selector Mate Selection Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28/ status: reviewed reviewed_utc: 2026-06-28T23:59:00Z --- # Browser Selector Mate Selection Memory ## Routing Summary Generated selector registries now carry the ModelBreeder mate-selection lane beside genome, species, novelty, population, and fitness evidence. Open `tinyrustlm/tools/slm_pack/src/selector.rs` for registry generation and validation, `tinyrustlm/app/app.js` plus `tinyrustlm/app/index.html` for browser intake and rendering, and `tinyrustlm/tools/browser-smoke.js` for served-root proof. ## Implementation Memory - `selector.registry` entries emit `entry.N.mate_selection_id`, `entry.N.mate_selection_strategy=selector-mate-selection-route-v1`, `entry.N.mate_selection_status`, `entry.N.mate_selection_parent_count`, and `entry.N.mate_selection_checksum`. - Multi-parent sign-merge admissions render mate selection as `parent-pool-bound` with the reviewed `parent_count`; ordinary selector admissions render `admission-only` with parent count `1`. - Mate-selection ids hash candidate id, admission kind, population id, parent-pool recipe checksum when present, and parent count. - Mate-selection checksums bind that id to population checksum, parent-pool recipe checksum, sign-merge operator receipt checksum, population-review checksum, promotion-ledger checksum, admission-set checksum, and admission checksum. - The browser rejects registry entries missing mate-selection metadata, then renders a compact `Mate Selection` row in Model Provenance as ` / parents / / `. - Browser smoke asserts generated registry-backed q4_0, q8_0, and f32 entries display `parent-pool-bound / 3 parents / / ` while keeping source-root fallback rows unavailable. ## Verification Memory - `C:\Users\AI\.cargo\bin\cargo.exe fmt` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector` with 51 selector-filtered tests passed. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle` with 4 tests passed. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` with 6 tests passed. - Fresh generated `browser-multi-parent-bundle target\browser-served-mate-selection\tinyrustlm all`, with selector registry validation passing for 3 admissions, 12 adapter routes, 3 adapter-family routes, 3 assembly routes, and 3 module-plan routes. - Served-root smoke: `combined-selector-assembly` on `http://127.0.0.1:8098/app/` with debugger port `19568`, proving q4_0, q8_0, and f32 generated entries show `parent-pool-bound / 3 parents / / ` while still loading module plans, assembly receipts, evidence files, adapter-family receipts, adapter manifests, and ADP1/ASP1/ALR1 stacks locally. No coverage tool is active in the no-third-party workspace, so focused syntax, Rust tests, generated-root, and browser-smoke evidence is the recorded coverage evidence for this bead. ## Research Route This implements the mate-selection lane from `wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md` and the parent-pool route from `wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md`. Future work can deepen this into richer parent relatedness display only after Rust validators and browser smokes cover every added selector field. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28.md BYTES: 2834 SHA256: 704BA1F22C6482A6E5BBB1B9A3DEFE0D67D2204FB23FBD57BA2E355D51D1FB19 ================================================================================ --- title: Browser Selector Novelty Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28/ status: reviewed reviewed_utc: 2026-06-28T23:35:00Z --- # Browser Selector Novelty Memory ## Routing Summary Generated selector registries now carry the ModelBreeder novelty lane beside genome, species, and fitness evidence. Open `tinyrustlm/tools/slm_pack/src/selector.rs` for registry generation and validation, `tinyrustlm/app/app.js` plus `tinyrustlm/app/index.html` for browser intake and rendering, and `tinyrustlm/tools/browser-smoke.js` for served-root proof. ## Implementation Memory - `selector.registry` entries emit `entry.N.novelty_id`, `entry.N.novelty_strategy=selector-novelty-sketch-v1`, `entry.N.novelty_status=behavior-sketch-bound`, and `entry.N.novelty_checksum`. - Novelty ids hash browser-visible behavior descriptors: species id, quality scope, eval dataset, output contract, quantization, and max-token envelope. - Novelty checksums bind the descriptor to concrete eval evidence plus assembly, adapter-family, and module-plan routes when those routes are present. - The browser rejects registry entries missing novelty metadata, then renders a compact `Novelty` row in Model Provenance as `behavior-sketch-bound / / `. - Browser smoke now asserts generated registry-backed q4_0, q8_0, and f32 entries display valid Genome, Species, Novelty, Fitness, eval case, and eval checksum rows. ## Verification Memory - `cargo fmt` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack` - Fresh generated `browser-multi-parent-bundle .\target\browser-served-multi-parent-all\tinyrustlm all` - Served-root smoke: `combined-selector-assembly` on `http://127.0.0.1:8096/app/` with debugger port `19564`, proving q4_0, q8_0, and f32 generated entries show `behavior-sketch-bound / / ` while still loading module plans, assembly receipts, evidence files, adapter-family receipts, adapter manifests, and ADP1/ASP1/ALR1 stacks locally. No coverage tool is active in the no-third-party workspace, so focused syntax, Rust tests, generated-root, and browser-smoke evidence is the recorded coverage evidence for this bead. ## Research Route This implements the novelty lane from `wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md`. Future population fields should follow the same pattern: add deterministic selector/admission/review fields first, add drift tests, then render only compact provenance summaries in the browser. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28.md BYTES: 3600 SHA256: 5DF064A8F2F5492F02A2DAFCD7D0586A71D9E0EB847477C33B9FAAC0655AB581 ================================================================================ --- title: Browser Selector Phenotype Evidence Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28/ status: reviewed reviewed_utc: 2026-06-28T17:21:00Z --- # Browser Selector Phenotype Evidence Memory ## Routing Summary Generated selector registries now carry the ModelBreeder phenotype-evidence lane beside genome, species, novelty, population, mate-selection, and fitness evidence. Open `tinyrustlm/tools/slm_pack/src/selector.rs` for registry generation and validation, `tinyrustlm/app/app.js` plus `tinyrustlm/app/index.html` for browser intake and rendering, and `tinyrustlm/tools/browser-smoke.js` for served-root proof. ## Implementation Memory - `selector.registry` entries emit `entry.N.phenotype_evidence_id`, `entry.N.phenotype_evidence_strategy=selector-phenotype-evidence-v1`, `entry.N.phenotype_evidence_status=runtime-eval-bound`, and `entry.N.phenotype_evidence_checksum`. - The selector also emits `entry.N.provenance_manifest_checksum`, so phenotype evidence can bind the model manifest route with runtime-smoke, eval-manifest, eval-case, assembly receipt, mate-selection, and fitness-vector evidence. - Phenotype evidence ids hash candidate id, mate-selection id, quality scope, eval dataset, passed case count, and eval-case evidence checksum. - Phenotype evidence checksums bind that id to provenance, runtime, eval, eval-case, quality-boundary, fitness, mate-selection, and assembly receipt state. - The browser rejects registry entries missing phenotype-evidence metadata, then renders a compact `Phenotype` row in Model Provenance as ` / / `. - Browser smoke asserts generated registry-backed q4_0, q8_0, and f32 entries display `runtime-eval-bound / / ` while keeping source-root fallback rows unavailable. ## Verification Memory - `C:\Users\AI\.cargo\bin\cargo.exe fmt` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector` with 52 selector-filtered tests passed. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle` with 4 tests passed. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` with 6 tests passed. - Fresh generated `browser-multi-parent-bundle target\browser-served-phenotype-evidence\tinyrustlm all`, with selector registry validation passing for 3 admissions, 12 adapter routes, 3 adapter-family routes, 3 assembly routes, and 3 module-plan routes. - Served-root smoke: `combined-selector-assembly` on `http://127.0.0.1:8099/app/` with debugger port `19570`, proving q4_0, q8_0, and f32 generated entries show `runtime-eval-bound / / ` while still loading module plans, assembly receipts, evidence files, adapter-family receipts, adapter manifests, and ADP1/ASP1/ALR1 stacks locally. No coverage tool is active in the no-third-party workspace, so focused syntax, Rust tests, generated-root, and browser-smoke evidence is the recorded coverage evidence for this bead. ## Research Route This implements the phenotype-evidence lane from `wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md` by turning runtime-smoke and eval observations into selector-visible provenance metadata. Future work can deepen this into richer phenotype summaries only after Rust validators and browser smokes cover every added selector field. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-selector-population-memory-2026-06-28.md BYTES: 3280 SHA256: 834635F5E977FD48FAA481ACA814D37088D0238330CC28E823612C0F4541C377 ================================================================================ --- title: Browser Selector Population Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-selector-population-memory-2026-06-28/ status: reviewed reviewed_utc: 2026-06-28T23:58:00Z --- # Browser Selector Population Memory ## Routing Summary Generated selector registries now carry the ModelBreeder population lane beside genome, species, novelty, and fitness evidence. Open `tinyrustlm/tools/slm_pack/src/selector.rs` for registry generation and validation, `tinyrustlm/app/app.js` plus `tinyrustlm/app/index.html` for browser intake and rendering, and `tinyrustlm/tools/browser-smoke.js` for served-root proof. ## Implementation Memory - `selector.registry` entries emit `entry.N.population_id`, `entry.N.population_strategy=selector-population-review-route-v1`, `entry.N.population_status=population-review-bound`, and `entry.N.population_checksum`. - Population ids hash the selector-visible population lane from species id, novelty id, scoped fitness checksum, quality scope, eval dataset, and quantization. - Population checksums bind that lane to genome lineage, species fit, novelty, fitness, and the assembly/module-plan route context when those routes are present. - The browser rejects registry entries missing population metadata, then renders a compact `Population` row in Model Provenance as `population-review-bound / / `. - Browser smoke now asserts generated registry-backed q4_0, q8_0, and f32 entries display valid Genome, Species, Novelty, Population, Fitness, eval case, and eval checksum rows. ## Verification Memory - `C:\Users\AI\.cargo\bin\cargo.exe fmt` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --check` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector` with 49 selector-filtered tests passed. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack browser_bundle` with 4 tests passed. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` with 6 tests passed. - Fresh generated `browser-multi-parent-bundle target\browser-served-multi-parent-all\tinyrustlm all`, with selector registry validation passing for 3 admissions, 12 adapter routes, 3 adapter-family routes, 3 assembly routes, and 3 module-plan routes. - Served-root smoke: `combined-selector-assembly` on `http://127.0.0.1:8097/app/` with debugger port `19566`, proving q4_0, q8_0, and f32 generated entries show `population-review-bound / / ` while still loading module plans, assembly receipts, evidence files, adapter-family receipts, adapter manifests, and ADP1/ASP1/ALR1 stacks locally. No coverage tool is active in the no-third-party workspace, so focused syntax, Rust tests, generated-root, and browser-smoke evidence is the recorded coverage evidence for this bead. ## Research Route This implements the population lane from `wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md`. Future population work can deepen this from compact selector-route identity toward explicit population-review route fields only after the browser and Rust validators have deterministic drift tests for every added field. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-selector-population-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28.md BYTES: 2600 SHA256: 79D69E393291415095F7C8E1FA73D8060C109E0F54FE4E9E4BAB7BBE44404F7F ================================================================================ --- title: Browser Selector Species Fit Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28/ status: reviewed reviewed_utc: 2026-06-28T22:55:00Z --- # Browser Selector Species Fit Memory ## Routing Summary Generated selector registries now carry the ModelBreeder speciation-fit lane beside genome and fitness evidence. Open `tinyrustlm/tools/slm_pack/src/selector.rs` for generation and validation, `tinyrustlm/app/app.js` plus `tinyrustlm/app/index.html` for browser rendering, and `tinyrustlm/tools/browser-smoke.js` for served-root proof. ## Implementation Memory - `selector.registry` entries emit `entry.N.species_id`, `entry.N.species_strategy=selector-speciation-fit-v1`, `entry.N.species_fit_status=browser-fit-bound`, and `entry.N.species_fit_checksum`. - Species ids group candidates by browser-relevant family traits: model shape, quantization, output contract, and max-token envelope. - Species-fit checksums bind the candidate to selector text budgets, model bytes, quantization, max tokens, and the module-plan resource envelope when a module plan is present. - The browser rejects registry entries missing species-fit metadata, then renders a compact `Species` row in Model Provenance as `browser-fit-bound / / `. - Browser smoke now asserts generated registry-backed q4_0, q8_0, and f32 entries display valid Genome, Species, Fitness, eval case, and eval checksum rows. ## Verification Memory - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack` - Fresh generated `browser-multi-parent-bundle .\target\browser-served-multi-parent-all\tinyrustlm all` - Served-root smoke: `combined-selector-assembly` on `http://127.0.0.1:8096/app/`, proving q4_0/q8_0/f32 generated entries show `browser-fit-bound / / ` while still loading module plans, assembly receipts, evidence files, adapter-family receipts, adapter manifests, and ADP1/ASP1/ALR1 stacks locally. ## Research Route This implements the speciation-fit lane from `wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md`. Future novelty or population fields should follow the same pattern: add deterministic selector/admission/review fields first, add drift tests, then render only compact provenance summaries in the browser. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-source-backed-alr1-contract-memory-2026-06-28.md BYTES: 2738 SHA256: 943C3617E1F1090B1CCB455E22694D56E87076E5EE3CD2EC4C6BD909165C0690 ================================================================================ --- title: Browser Source-Backed ALR1 Contract Memory status: current reviewed_utc: 2026-06-28T13:30:00Z --- # Browser Source-Backed ALR1 Contract Memory TinyRustLM now treats source-backed ALR1 provenance fields as first-class route contracts before browser auto assembly can fetch or apply stack artifacts. ## Implementation - `tinyrustlm/tools/slm_pack/src/adapter_family.rs` now couples adapter kind and dtype as exact route pairs, accepts source-backed ALR1 only with `low-rank-f32-source-delta`, validates source manifest, source checksum, layout, format, and source-base contract fields, and echoes those fields into adapter-family receipts. - `tinyrustlm/app/app.js` now validates source-backed ALR1 receipt echoes, checks fetched source-backed ALR1 manifests against the receipt, and rejects a manifest whose source contract differs from the already verified adapter-family receipt. - `tinyrustlm/tools/browser-smoke.js` adds `source-backed-alr1-manifest-drift`, mutating only the low-rank ALR1 manifest source-base contract while recomputing selector, module-plan, assembly, and adapter-family checksum carriers so the browser reaches the intended manifest-vs-receipt comparison. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` tests now assert generated adapter-family receipts carry source-backed ALR1 provenance echoes for the `adapter.3` stack member. ## Evidence - `cargo fmt --all` - `cargo fmt --all -- --check` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo test -p tinyrustlm-slm-pack adapter_family` - `cargo test -p tinyrustlm-slm-pack browser_bundle` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/source-backed-alr1-contract/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8176/app/ 9276 multi-parent-sign-merge-q4 source-backed-alr1-manifest-drift` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8176/app/ 9277 multi-parent-sign-merge-q4 combined-selector-assembly` - `cargo test --workspace` ## Result The drift smoke kept the generated q4 selector, module plan, model, manifest, assembly receipt, evidence files, adapter-family receipt, and all adapter manifests fetchable through the low-rank ALR1 manifest. The browser then rejected `adapter_source_base_contract` before fetching any ADP1, ASP1, or ALR1 stack artifacts, while the valid combined selector path still applied the source-backed ALR1 stack member for q4_0, q8_0, and f32. ## Routing Use this report before changing source-backed ALR1 manifest fields, adapter-family receipt source echoes, `.alr1` kind/dtype routing, `validateSourceBackedAdapterManifest`, or `source-backed-alr1-manifest-drift` smoke expectations. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-source-backed-alr1-contract-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-source-backed-alr1-route-memory-2026-06-28.md BYTES: 2292 SHA256: E68D782AA14A7142234F5F83FEA061BD6AF8D7CFB10F39A9E2C46A91FC7D0031 ================================================================================ --- title: Browser Source-Backed ALR1 Route Memory status: current reviewed_utc: 2026-06-28T11:25:34Z --- # Browser Source-Backed ALR1 Route Memory TinyRustLM generated browser bundles now serve ALR1 stack members that come from reviewed trained adapter source bundles instead of only synthetic low-rank task-delta receipts. ## Implementation - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` stages `low-rank-adapter.source` evidence for each generated f32/q8_0/q4_0 entry, converts it with `convert_adapter_source_path`, and validates it with `validate_converted_adapter_source_path`. - `tinyrustlm/tools/slm_pack/src/adapter_family.rs` accepts source-backed ALR1 manifest kind and dtype for `.alr1` family members while preserving checksum, apply-status, quantization, and shared identity checks. - `tinyrustlm/app/app.js` accepts source-backed ALR1 manifest kind and dtype for local `.alr1` routes without parsing adapter payload bytes. - `tinyrustlm/tools/browser-smoke.js` expects source-backed ALR1 labels and exact Module Plan byte/checksum summaries for generated roots. ## Evidence - `cargo fmt --all` - `cargo fmt --all -- --check` - `node --check tinyrustlm/app/app.js` - `node --check tinyrustlm/tools/browser-smoke.js` - `cargo test -p tinyrustlm-slm-pack adapter_family` - `cargo test -p tinyrustlm-slm-pack browser_bundle` - `cargo test -p tinyrustlm-slm-pack trained_adapter_source` - `cargo test -p tinyrustlm-slm-pack` - `cargo test -p tinyrustlm-browser-harness` - `cargo test --workspace` - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle target/source-backed-alr1-route/tinyrustlm all` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18770/app/ 9229 multi-parent-sign-merge-q4 combined-selector-assembly` ## Result The generated q4/q8/f32 selector root now fetches source-backed `.alr1` manifests and artifacts, validates each source-backed ALR1 package through Rust before apply, applies ADP1 plus ASP1 plus source-backed ALR1 before generation, and reaches ready through the verified Module Plan trace. ## Routing Use this report before changing generated browser bundle ALR1 staging, source-backed adapter-family receipt members, browser `.alr1` manifest validation, or combined selector source-backed ALR1 smoke expectations. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-source-backed-alr1-route-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-sparse-adapter-route-memory-2026-06-27.md BYTES: 5612 SHA256: ABA176E597769E7776FD92B812B426E04F986422C94E111896FA6D9235FEDDD3 ================================================================================ --- title: Browser Sparse Adapter Route Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-sparse-adapter-route-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T14:48:27Z --- # Browser Sparse Adapter Route Memory ## Summary TinyRustLM now routes generated sparse `ASP1` adapter packages through the browser selector path. Generated f32/q8_0/q4_0 browser bundles stage a three-member adapter family: self `ADP1`, family `ADP1`, and sparse `ASP1`. The browser fetches the served adapter-family receipt, verifies all served adapter manifests by route-derived format, selects the sparse `ASP1` member during generated-root smoke, checks the artifact checksum, transfers bytes into WASM, and Rust applies the package through `apply_adapter_delta`. ## Implementation Memory - `tinyrustlm/tools/slm_pack/src/selector.rs` accepts local `../models/*.adp1` and `../models/*.asp1` adapter routes while preserving paired `.manifest` sidecars, checksum fields, apply-status matching, and duplicate-route rejection. - `tinyrustlm/tools/slm_pack/src/adapter_family.rs` writes format-neutral `browser-local-adapter-family` receipts and validates each member manifest against the member route: raw `ADP1` requires `raw-f32-task-delta-v1` and `f32-delta`; sparse `ASP1` requires `sparse-f32-task-delta-v1` and `sparse-f32-delta`. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` now emits `multi-parent-sign-merge-*-sparse.asp1` plus its manifest after the existing generated self and family `ADP1` sidecars, then records all three members in the selector registry and receipt. - `tinyrustlm/app/app.js` infers adapter manifest kind and dtype from the selected route extension, accepts both current format-neutral and earlier ADP1-specific family receipt kinds, and keeps adapter bytes opaque to JavaScript before WASM transfer. - `tinyrustlm/tools/browser-smoke.js` expects three generated adapter options and applies the sparse `ASP1` option in `adapter-sidecar-registry-file`, with network assertions for the `ASP1` manifest and artifact route. - `tinyrustlm/runtime/tinyrustlm.wasm` was rebuilt from current runtime source so the browser-served WASM artifact includes the same `ASP1` runtime apply support as native Rust tests. ## Validation Memory - `node --check tinyrustlm/app/app.js` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `cargo fmt --all` passed through `C:\Users\AI\.cargo\bin\cargo.exe`. - `cargo test -p tinyrustlm-slm-pack selector` passed with 22 filtered tests. - `cargo test -p tinyrustlm-slm-pack adapter_family` passed with 6 filtered tests. - `cargo test -p tinyrustlm-slm-pack browser_bundle` passed with 2 filtered tests. - `cargo test -p tinyrustlm-slm-pack` passed with 151 tests. - `cargo build -p tinyrustlm-runtime --release --target wasm32-unknown-unknown` passed and the resulting WASM was copied to `tinyrustlm/runtime/tinyrustlm.wasm`. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-asp1-route\tinyrustlm f32` staged a generated root with three adapter routes and `adapter_routes: 3`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18671/app/ 9261 multi-parent-sign-merge-f32 adapter-sidecar-registry-file` passed, selecting `Multi-parent sign-merge f32 sparse ASP1`, fetching `/models/multi-parent-sign-merge-f32-sparse.asp1.manifest`, fetching `/models/multi-parent-sign-merge-f32-sparse.asp1`, and receiving `adapter applied`. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-asp1-route-q8\tinyrustlm q8_0` staged a generated q8_0 root with three adapter routes and `adapter_routes: 3`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18673/app/ 9263 multi-parent-sign-merge-q8 adapter-sidecar-registry-file` passed, selecting `Multi-parent sign-merge q8_0 sparse ASP1`, fetching `/models/multi-parent-sign-merge-q8-sparse.asp1.manifest`, fetching `/models/multi-parent-sign-merge-q8-sparse.asp1`, receiving `adapter applied`, and preserving `active_quantization_mode` as `q8_0`. - `cargo run -p tinyrustlm-slm-pack -- browser-multi-parent-bundle .\target\browser-asp1-route-q4\tinyrustlm q4_0` staged a generated q4_0 root with three adapter routes and `adapter_routes: 3`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18674/app/ 9264 multi-parent-sign-merge-q4 adapter-sidecar-registry-file` passed, selecting `Multi-parent sign-merge q4_0 sparse ASP1`, fetching `/models/multi-parent-sign-merge-q4-sparse.asp1.manifest`, fetching `/models/multi-parent-sign-merge-q4-sparse.asp1`, receiving `adapter applied`, and preserving `active_quantization_mode` as `q4_0`. - Final verification also passed: `node --check tinyrustlm/tools/wasm-abi-smoke.js`, `cargo fmt --all -- --check`, `cargo test --workspace`, `node tinyrustlm/tools/wasm-abi-smoke.js`, `cargo run -p tinyrustlm-browser-harness -- tinyrustlm`, fresh f32 `browser-multi-parent-bundle` staging under `target\browser-asp1-route-final\tinyrustlm`, served-root `adapter-sidecar-registry-file` browser smoke at `http://127.0.0.1:18672/app/`, q8_0 and q4_0 served-root sparse ASP1 smokes, and `git diff --check`. ## Routing Notes Use this report before changing browser selector adapter route formats, generated adapter-family bundle staging, adapter-family receipt format checks, `app.js` adapter manifest validation, checked-in WASM rebuild expectations, or `adapter-sidecar-registry-file` network assertions. This report is the browser-route companion to the sparse adapter package report and the adapter-family receipt report. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-sparse-adapter-route-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-text-sidecar-budget-memory-2026-06-27.md BYTES: 3287 SHA256: EC2C8F3A6A0A5FA58B6508905ECEF5F1229401FBB6D1928EEDAEBCF90B2101C8 ================================================================================ --- title: Browser Text Sidecar Budget Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-text-sidecar-budget-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T17:18:16Z --- # Browser Text Sidecar Budget Memory ## Summary TinyRustLM now applies explicit browser-local byte envelopes to text sidecars before parsing them in JavaScript. Selector registries are capped at 256 KiB, `.slm` and adapter manifests at 64 KiB, assembly and adapter-family receipts at 128 KiB, and assembly evidence files at 128 KiB. The browser fetches each text sidecar as bytes, checks the length, and decodes only after the sidecar fits its local envelope. ## Implementation Memory - `tinyrustlm/app/app.js` adds sidecar text budgets for selector registries, manifests, receipts, and evidence files. - `fetchTextWithinBudget` centralizes the browser fetch/decode path so text files are checked as bytes before `parseManifest` or checksum validation. - Selector registry loading, `.slm` manifest loading, assembly receipt loading, assembly evidence verification, adapter-family receipt loading, and generated adapter manifest loading now use the bounded text path. - Binary `.slm`, ADP1, and ASP1 artifacts keep their existing byte checks and WASM transfer path; this bead only bounds text sidecars. - Oversized generated adapter manifests stop generated adapter-family options before any adapter artifact request or `apply_adapter_delta` call. - `tinyrustlm/tools/browser-smoke.js` adds `adapter-manifest-budget`, which intercepts a generated sparse ASP1 manifest with 64 KiB plus one byte and verifies the browser keeps the model ready while leaving generated adapter controls disabled. - The smoke harness now checks adapter artifact requests by exact URL path so a `.manifest` route cannot satisfy an artifact-route assertion by prefix overlap. ## Validation Memory - `node --check tinyrustlm/app/app.js` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `cargo fmt --all -- --check` passed through `C:\Users\AI\.cargo\bin\cargo.exe`. - `browser-multi-parent-bundle target/browser-text-sidecar-budget/tinyrustlm all` generated a combined f32/q8_0/q4_0 selector root for browser proof. - Served-root `adapter-sidecar-registry-file` smoke passed on `http://127.0.0.1:18686/app/` for `multi-parent-sign-merge-q4`; it loaded the q4 generated model, verified assembly evidence, auto-applied the receipt-preferred sparse ASP1, and generated `e`. - Served-root `adapter-manifest-budget` smoke passed on `http://127.0.0.1:18686/app/` for `multi-parent-sign-merge-q4`; it loaded the model and assembly evidence, reported `Adapter manifest byte budget exceeded`, kept Generate enabled, left generated adapter controls disabled, and did not request the exact sparse ASP1 artifact route. - `cargo test --workspace` passed with 243 checks across runtime, packer, browser harness, local server, and doc-tests. ## Routing Notes Use this report before changing browser text-sidecar fetches, selector.registry intake, `.slm` or adapter manifest parsing, assembly receipt or evidence-file verification, adapter-family receipt verification, generated adapter-family option enablement, or the smoke assertions around oversized sidecar text. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-text-sidecar-budget-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/browser-text-sidecar-contract-memory-2026-06-27.md BYTES: 3261 SHA256: 7A3E2D5D6B223AD5312D1CC17D7129713C45CCC8ED6A16C69814DB8E553A5018 ================================================================================ --- title: Browser Text Sidecar Contract Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/browser-text-sidecar-contract-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T17:35:40Z --- # Browser Text Sidecar Contract Memory ## Summary TinyRustLM selector registries now declare the browser text-sidecar byte contract that the static app enforces before registry entries are accepted. Generated registries carry exact limits for selector registry text at 256 KiB, manifest text at 64 KiB, receipt text at 128 KiB, and evidence text at 128 KiB. Rust emits and validates those fields; `app.js` accepts selector registries only when every declared text budget matches the local browser envelope. ## Implementation Memory - `tinyrustlm/tools/slm_pack/src/selector.rs` writes `selector_registry_text_byte_budget=262144`, `manifest_text_byte_budget=65536`, `receipt_text_byte_budget=131072`, and `evidence_text_byte_budget=131072` next to `selector_model_byte_budget=33554432`. - Selector registry validation now recomputes those text-budget contract fields and reports drift by field name. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` checks generated f32, q8_0, q4_0, and combined roots for the text-budget contract fields. - `tinyrustlm/app/app.js` requires exact text-budget matches before accepting a registry option list, so drift leaves the static fallback models available and blocks the drifted route before model fetch. - `tinyrustlm/tools/browser-smoke.js` adds `sidecar-budget-contract`, which serves a registry with a mismatched manifest text budget and verifies the browser falls back to `tinylm16q8` without requesting the drifted parent model. ## Validation Memory - `node --check tinyrustlm/app/app.js` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` passed. - `cargo test -p tinyrustlm-slm-pack selector::` passed with 24 tests, including text-budget drift coverage. - `cargo test -p tinyrustlm-slm-pack browser_bundle::` passed with 3 tests. - `browser-multi-parent-bundle target/browser-sidecar-contract-budget/tinyrustlm all` generated a combined f32/q8_0/q4_0 selector root with the contract fields. - Served-root `adapter-sidecar-registry-file` smoke passed on `http://127.0.0.1:18690/app/` for `multi-parent-sign-merge-q4`; it loaded the q4 generated model, verified assembly evidence, auto-applied the receipt-preferred sparse ASP1, and generated `e`. - Static-root `sidecar-budget-contract` smoke passed on `http://127.0.0.1:18691/app/`; the drifted registry was not accepted, `/models/sidecar-budget-contract-parent.slm` was not requested, and fallback `tinylm16q8` generated `e`. - Regression smokes passed for `selector-budget`, `multi-parent-registry`, and `adapter-sidecar-registry-q8`. - `cargo test --workspace` passed with 244 checks across runtime, packer, browser harness, local server, and doc-tests. ## Routing Notes Use this report before changing selector registry headers, text-sidecar budget constants, browser registry intake, generated browser bundle registry output, or smoke fixtures that prove budget drift leaves static fallback routing intact before model bytes are fetched. ================================================================================ END FILE: wiki/gguf-mirust/reports/browser-text-sidecar-contract-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29.md BYTES: 4100 SHA256: C5EFAA0227F89F843E96FDA76DEED5780A70992CDBAA896C2BA2C4432F25EC40 ================================================================================ --- title: Candidate Operator Receipt Binding Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T07:40:00Z --- # Candidate Operator Receipt Binding Memory TinyRustLM two-parent candidate manifests can now optionally bind the exact operator receipt that produced the candidate `.slm`. ## What Changed - `tinyrustlm/tools/slm_pack/src/candidate.rs` keeps existing unbound `candidate-manifest` behavior while adding optional producer receipt binding. - `candidate-manifest [input.operator]` reads the receipt, validates its identity fields against lineage and candidate bytes, and writes recomputable receipt fields into the candidate manifest. - `validate-candidate [input.operator]` recomputes the receipt binding when the optional receipt is supplied. - Bound manifests do not validate without the referenced receipt input; unbound manifests remain valid on the existing path. ## Manifest Fields - `operator_receipt_status=receipt-bound` - `operator_receipt_path=` - `operator_receipt_checksum=` - `operator_receipt_operator_id=` - `operator_receipt_operator_kind=` - `operator_receipt_candidate_slm_checksum=` - `operator_receipt_candidate_artifact_bytes=` ## Validation Boundaries - The receipt `candidate_id` must match lineage `candidate_id`. - The receipt `operator_id` must match lineage `operator_id`. - The receipt `candidate_slm_checksum` must match the validated candidate `.slm`. - The receipt `candidate_artifact_bytes` must match the validated candidate byte count. - The manifest receipt checksum must match the supplied receipt text, including comment-preserving drift. ## Verification - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml candidate -- --nocapture` passed with 50 focused candidate and neighboring operator tests. - CLI smoke wrote `target/candidate-operator-binding/parents.compat`. - CLI smoke wrote `target/candidate-operator-binding/candidate.lineage`. - CLI smoke wrote `target/candidate-operator-binding/candidate.slm` and `target/candidate-operator-binding/candidate.operator` through `mutation-candidate`. - CLI smoke validated the mutation receipt with `validate-mutation-candidate`. - CLI smoke wrote `target/candidate-operator-binding/candidate.candidate` through receipt-bound `candidate-manifest`. - CLI smoke validated the receipt-bound candidate manifest with `validate-candidate`. - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml -- --nocapture` passed with 257 tests. - `C:\Users\AI\.cargo\bin\cargo.exe test --workspace` passed with browser harness, local server, runtime, and slm_pack tests. - `git diff --check` exited 0 with line-ending notices only. No coverage tool is active in this no-third-party workspace; evidence for the 75% target is the focused receipt-binding happy path, path-parameter coverage, drift rejection tests, full packer suite, workspace suite, formatting, and CLI write/validate smoke. ## Test Coverage Notes - `operator_receipt: Option<&Path>` is covered by path-level unbound and bound write/validate tests. - `operator_receipt.path` is covered by manifest field assertions and CLI emitted path inspection. - `operator_receipt.text` is covered by checksum drift rejection. - Candidate checksum and byte-count receipt fields are covered by build-time rejection tests. - Bound-manifest validation without the receipt input is covered by an explicit rejection test. ## Routing Open this report before changing `candidate.rs`, `candidate-manifest`, `validate-candidate`, two-parent operator receipt fields, or downstream promotion assumptions about two-parent candidate provenance. ================================================================================ END FILE: wiki/gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/crossover-operator-memory-2026-06-29.md BYTES: 4818 SHA256: 45C75982DF21B915FAFC4E0CAF041D2A761BD144352F9B4CF1C2592C75411FEB ================================================================================ --- title: Crossover Operator Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/crossover-operator-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T17:25:00Z --- # Crossover Operator Memory TinyRustLM now has an offline deterministic direct-parameter crossover operator for model-breeding candidates. ## What Changed - `tinyrustlm/tools/slm_pack/src/crossover.rs` adds `crossover-candidate` and `validate-crossover-candidate` support for compatible two-parent `.slm` files. - The operator selects each tensor element from parent 0 or parent 1 using `crossover_seed` plus `crossover_parent0_keep_ppm`; the receipt records total parameter count, per-parent selection counts, density in parts-per-million, and `crossover_mask_checksum`. - Validation recomputes lineage, parent compatibility checks, candidate bytes, and the entire operator receipt before accepting the artifact. - `tinyrustlm/tools/slm_pack/src/main.rs` exposes the new CLI commands and help text. - `tinyrustlm/tools/browser-smoke.js` now has a `crossover-operator-registry` fixture that proves browser Model Provenance renders a receipt-bound crossover operator row, plus `crossover-operator-receipt-drift` for browser byte-echo fallback. - `tinyrustlm/README.md` routes the crossover browser smoke commands beside the other compact operator provenance examples. ## Receipt Fields - `tinyrustlm_crossover_operator_version=1` - `operator_kind=deterministic-direct-parameter-crossover` - `crossover_seed=` - `crossover_parent0_keep_unit=parts-per-million` - `crossover_parent0_keep_ppm=<0..1000000>` - `crossover_parent1_keep_ppm=<1000000-parent0>` - `crossover_selection_metric=splitmix64-tensor-element-threshold` - `crossover_selection_scope=compatible-parent-tensor-values` - `crossover_tie_break=parent0-when-threshold-equal` - `crossover_total_parameter_count`, `crossover_parent0_parameter_count`, `crossover_parent1_parameter_count` - `crossover_parent0_density_ppm`, `crossover_parent1_density_ppm` - `crossover_mask_checksum` ## Verification - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml crossover -- --nocapture` passed with 9 crossover tests. - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml -- --nocapture` passed with 241 tests. - CLI smoke wrote `target/crossover-cli/same-parent.compat`. - CLI smoke wrote `target/crossover-cli/same-parent.lineage`. - CLI smoke wrote `target/crossover-cli/same-parent-crossover.slm` and `target/crossover-cli/same-parent-crossover.operator` with explicit seed `77` and keep `500000`. - CLI smoke validated the crossover candidate and receipt with `validate-crossover-candidate`. - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8128/app/ 9420 tinylm16-crossover-q8 crossover-operator-registry` passed, rendering `receipt-bound / deterministic-direct-parameter-crossover / 0x00000000000000b2`. - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8128/app/ 9421 tinylm16q8 crossover-operator-receipt-drift` passed, dropping the drifted crossover registry entry and returning to static q8 with operator provenance unavailable. - Regression smokes for the shared compact fixture passed on `http://127.0.0.1:8128/app/`: federated `multi-parent-registry`, prune `prune-operator-registry`, and prune `prune-operator-receipt-drift`. - `node --check tinyrustlm\tools\browser-smoke.js` passed after the crossover browser fixture update. No coverage tool is active in this no-third-party workspace; evidence for the 75% target is the focused parameter and drift test slice, the full `slm_pack` suite, formatting, the CLI write/validate smoke, and the browser provenance/drift smokes. ## Test Coverage Notes - `crossover_seed` is covered by seed-different candidate and mask checksum tests. - `crossover_parent0_keep_ppm` is covered by zero, full, partial, default, and invalid parse tests. - Parent path inputs are covered by path-level write/validate and compatibility-bound checksum drift rejection. - Candidate and receipt paths are covered by path-level write/validate, recompute validation, and candidate drift rejection. - Browser operator receipt routing is covered by crossover positive provenance rendering and crossover byte-echo fallback smokes, plus federated and prune fixture regression smokes through the same compact registry fixture. - Quantization route behavior is covered by q8 candidate validation. ## Routing Open this report before changing `crossover.rs`, `crossover-candidate`, `validate-crossover-candidate`, deterministic selection masks, crossover receipt fields, crossover browser operator provenance, or crossover parameter validation. ================================================================================ END FILE: wiki/gguf-mirust/reports/crossover-operator-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29.md BYTES: 2272 SHA256: B4E4621B1F3725A20E2ABDE1B54B2F5A51B65F4F8DEB560B7C3ADA95E2C5D87B ================================================================================ --- title: DARE Browser Operator Provenance Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T18:46:12Z --- # DARE Browser Operator Provenance Memory TinyRustLM now routes DARE operator receipt metadata into the compact browser selector provenance path. ## What Changed - `tinyrustlm/tools/browser-smoke.js` adds `dare-operator-registry` and `dare-operator-receipt-drift` modes. - The DARE fixture registers `tinylm16-dare-q8` as a q8_0 selector entry backed by the local `tinylm16-q8.slm` route. - The selector entry carries `entry.0.operator_receipt_*` fields with `operator_receipt_operator_kind=dropout-rescaled-task-delta`. - The browser Model Provenance Operator row renders `receipt-bound / dropout-rescaled-task-delta / 0x00000000000000b7` for the positive DARE fixture. - The DARE receipt drift mode changes the receipt-declared candidate byte count, rejects the selector entry, falls back to static q8, and renders Operator as `unavailable`. - `tinyrustlm/tools/slm_pack/src/selector.rs` now has DARE-specific selector registry tests for receipt kind carry-forward and operator-kind drift rejection. ## Verification - `node --check tinyrustlm/tools/browser-smoke.js` - `node --check tinyrustlm/app/app.js` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector_registry_from_dare -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector_registry_dare -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack --quiet` - `C:\Users\AI\.cargo\bin\cargo.exe test --workspace --quiet` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8080/app/ 9272 tinylm16-dare-q8 dare-operator-registry` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8080/app/ 9273 tinylm16q8 dare-operator-receipt-drift` - Long-term checksum audit, report/research pointer audit, and summary-length audit all passed after routing updates. ## Routing Open this report before changing DARE compact selector fixtures, browser Model Provenance Operator rendering for DARE, DARE selector receipt byte echo, or DARE operator receipt drift smoke behavior. ================================================================================ END FILE: wiki/gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/dare-operator-memory-2026-06-29.md BYTES: 4348 SHA256: 59BC2841527354FAE01412FF708F41236EE5FFA740688D05833BE0C59CD2C179 ================================================================================ --- title: DARE Operator Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/dare-operator-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T18:04:57Z --- # DARE Operator Memory TinyRustLM now has an offline DARE-style dropout/rescaled task-delta operator for model-breeding candidates. ## What Changed - `tinyrustlm/tools/slm_pack/src/dare.rs` adds `dare-candidate` and `validate-dare-candidate` support for compatible two-parent `.slm` files. - Parent 0 is the base artifact and parent 1 is the compatible target artifact. - The operator computes target-minus-base task deltas, deterministically drops nonzero deltas with a SplitMix64 coordinate mask, rescales kept deltas by the inverse keep rate, applies signed `delta_weight_ppm`, and writes a normal `.slm` candidate in the base parent's dtype/layout. - The receipt records delta weight, keep/drop rates, dropout seed, selection and rescale strategy labels, total/nonzero/selected/dropped/unchanged counts, density, nonzero retention, mask checksum, raw delta checksum, rescaled delta checksum, and candidate artifact checksum. - Validation recomputes lineage, parent compatibility checks, candidate bytes, and the entire operator receipt before accepting the artifact. - `tinyrustlm/tools/slm_pack/src/main.rs` exposes the new CLI commands and usage line. - `tinyrustlm/README.md` routes the DARE commands beside the existing direct-parameter model-breeding operator examples. ## Receipt Fields - `tinyrustlm_dare_operator_version=1` - `operator_kind=dropout-rescaled-task-delta` - `base_parent_index=0` - `target_parent_index=1` - `delta_weight_unit=parts-per-million` - `delta_weight_ppm=<-1000000..2000000>` - `dare_keep_unit=parts-per-million` - `dare_keep_ppm=<0..1000000>` - `dare_drop_unit=parts-per-million` - `dare_drop_ppm=<1000000-dare_keep_ppm>` - `dare_dropout_seed=` - `dare_selection_metric=splitmix64-nonzero-delta-threshold` - `dare_selection_scope=nonzero-target-minus-base-deltas` - `dare_tie_break=select-when-threshold-equal` - `dare_rescale_strategy=inverse-keep-rate` - `dare_rescale_multiplier_ppm` - `dare_total_parameter_count`, `dare_nonzero_delta_count`, `dare_selected_delta_count`, `dare_dropped_delta_count`, `dare_unchanged_parameter_count` - `dare_selection_density_ppm` - `dare_nonzero_delta_retention_ppm` - `dare_mask_checksum` - `dare_raw_delta_checksum` - `dare_rescaled_delta_checksum` ## Verification - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack dare -- --nocapture` passed with 11 DARE tests. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack --quiet` passed with 316 tests. - CLI smoke wrote `target/dare-cli/dare-candidate.slm` and `target/dare-cli/dare-candidate.operator` from a TinyLM-16M q8_0 base plus a bounded-mutation target, with `delta_weight_ppm=1000000`, `dare_keep_ppm=500000`, and `dare_dropout_seed=29`. - CLI smoke validated the DARE candidate and receipt with `validate-dare-candidate`; the candidate stayed q8_0 and 17,160,000 bytes. No coverage tool is active in this no-third-party workspace; evidence for the 75% target is the focused parameter and drift test slice, the full `slm_pack` suite, formatting, and the q8 write/validate CLI smoke. ## Test Coverage Notes - `delta_weight_ppm` is covered by default, positive scaling, accepted negative scaling, full-weight target matching, and invalid parse tests. - `keep_ppm` is covered by default, zero, full, partial, receipt rescale, and invalid parse tests. - `dropout_seed` is covered by default, explicit seeded writing, selection-mask changes, and invalid parse tests. - Parent path inputs are covered by path-level write/validate and compatibility-bound checksum drift rejection. - Candidate and receipt paths are covered by path-level write/validate, recompute validation, and candidate drift rejection. - Base and target parent semantics are covered by keep-zero preserving base values, keep-full/full-weight matching target values, negative-weight extrapolation, and q8 candidate validation. ## Routing Open this report before changing `dare.rs`, `dare-candidate`, `validate-dare-candidate`, DARE dropout masks, rescaled task-delta receipt fields, signed DARE weighting, or DARE parameter validation. ================================================================================ END FILE: wiki/gguf-mirust/reports/dare-operator-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/enterprise-rust-governance-memory-2026-06-25.md BYTES: 4534 SHA256: 150C24D20325B10BA57123EBC832B83FF08B40DA3DE6F986FEB344A203650524 ================================================================================ --- title: Enterprise Rust Governance Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/enterprise-rust-governance-memory-2026-06-25/ status: planned_pending_publication reviewed_utc: 2026-06-25T00:00:00Z --- # Enterprise Rust Governance Memory ## Source Reports - `best practices and governance guidelines for enterprise Rust adoption.md` - `Enterprise Rust Best Practices.md` - `Rust Design Patterns and SOLID Principles.md` - `Rust ownership model and type system naturally embody many SOLID concepts.md` ## Durable Reading The governance reports are strongest when treated as a discipline layer rather than a crate shopping list. For TinyRustLM, enterprise quality means fewer moving parts, clearer boundaries, and stronger proof. The active project intentionally rejects common enterprise defaults such as broad dependency adoption, framework abstraction, telemetry, cloud observability, and cargo plugin requirements at runtime. The reports still matter because they name the habits that make a no-dependency runtime maintainable: - Pin the trust boundary. In this project, the trust boundary is the browser fetching local static files and calling a narrow WASM ABI. All parsing and inference responsibility belongs to Rust. - Make quality visible. Tests, docs, checksums, smoke results, and `.uai` proof records are not paperwork; they are how a future agent knows which claims are safe. - Treat dependencies as a governance decision. The strongest supply-chain control here is not cargo-audit, but the absence of third-party crates in the runtime and packer. - Keep unsafe code rare, named, and audited. The reports support the local rule that unsafe belongs only at the WASM memory boundary when unavoidable. - Prefer typed boundaries over pattern cosplay. Rust does not need object-oriented design transplanted into it. Cohesion, newtypes, enums, typestate, explicit errors, and ownership usually carry the intent better. ## Design Pressure For TinyRustLM The reports push toward an enterprise posture where every feature earns its cost. A tempting browser AI project can accumulate frameworks, SDKs, adapters, caches, workers, telemetry, and model compatibility layers. TinyRustLM should resist that until the tiny local runtime is obviously correct. Good future additions should pass this test: 1. Does the change make local inference more correct, measurable, or recoverable? 2. Can it be tested without adding an opaque dependency? 3. Does it reduce ambiguity for the next maintainer? 4. Does it preserve the browser-local privacy story? 5. Does it avoid turning TinyRustLM into a general LLM framework? ## Patterns To Carry Forward - Use small modules with plain data ownership: parser, tensor views, quantization, ops, cache, generation, diagnostics, and app host. - Let enums and explicit error codes describe state transitions instead of stringly control flow. - Keep source memory factual: hot `.uai` for active state, durable Markdown/wiki records for long-term memory, raw evidence for original reports. - Prefer deterministic tests first. Randomized or property-style testing can be simulated with deterministic local loops before any external tooling is considered. - Make recovery paths a feature. Missing models, malformed models, context overflow, and browser reload loops are enterprise behavior, not merely edge cases. ## Anti-Patterns To Avoid - Adding a trait hierarchy because a report says "ports and adapters" when a simple module boundary is enough. - Adding a crate to enforce a policy that this project can enforce by having no crate. - Hiding model or prompt data behind generic abstractions before the SLM path is proven. - Treating brand, philosophy, or future architecture as implementation fact. - Letting `.uai/long-term-memory.uai` become a second report store. ## Thought Questions - What is the smallest runtime surface that can still be honestly called an AI runtime? - Which invariants should be enforced in `.slm` validation rather than left to later matrix operations to discover? - How can the browser UI show operator confidence without pretending deterministic smoke models are trained-quality assistants? - What would make a future dependency worth breaking the zero-dependency posture, and who would be allowed to decide? ## Current Boundary Use this record for governance pressure. Do not treat its third-party tool suggestions as implementation authority while the active prompt requires zero third-party runtime and packer dependencies. ================================================================================ END FILE: wiki/gguf-mirust/reports/enterprise-rust-governance-memory-2026-06-25.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/federated-operator-memory-2026-06-29.md BYTES: 3635 SHA256: C00FFA080E7971E2E05736080D03478A22429095EDD1B608E9D79960F42A0FF7 ================================================================================ --- title: Federated Operator Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/federated-operator-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T13:45:00Z --- # Federated Operator Memory TinyRustLM now has an offline federated/local-update operator for model-breeding candidates. ## What Changed - `tinyrustlm/tools/slm_pack/src/federated.rs` adds `federated-candidate` and `validate-federated-candidate` support for compatible two-parent `.slm` files. - Parent 0 is the global/base artifact and parent 1 is the compatible local-update artifact. - The operator writes `base + local_update_weight_ppm * (local_update - base)` in parts-per-million form, preserving the base parent's dtype/layout and writing a normal `.slm` candidate. - The receipt records total parameter count, changed parameter count, changed density, raw local-update delta checksum, and weighted delta checksum. - Validation recomputes lineage, parent compatibility checks, candidate bytes, and the entire operator receipt before accepting the artifact. - `tinyrustlm/tools/slm_pack/src/main.rs` exposes the new CLI commands and usage line. ## Receipt Fields - `tinyrustlm_federated_operator_version=1` - `operator_kind=federated-local-update-average` - `base_parent_index=0` - `local_update_parent_index=1` - `local_update_strategy=single-client-fedavg-v1` - `local_update_scope=compatible-direct-parameter-delta` - `local_update_weight_unit=parts-per-million` - `local_update_weight_ppm=<0..1000000>` - `base_coefficient_ppm=<1000000-local_update_weight_ppm>` - `local_update_coefficient_ppm=` - `local_update_total_parameter_count` - `local_update_changed_parameter_count` - `local_update_changed_density_ppm` - `local_update_delta_checksum` - `local_update_weighted_delta_checksum` ## Verification - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all` - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack federated` passed with 9 federated tests. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack` passed with 278 tests. - `C:\Users\AI\.cargo\bin\cargo.exe build -p tinyrustlm-slm-pack` - CLI smoke wrote `target/federated-cli/tiny-q8.compat`. - CLI smoke wrote `target/federated-cli/tiny-q8.lineage`. - CLI smoke wrote `target/federated-cli/tiny-q8-federated.slm` and `target/federated-cli/tiny-q8-federated.operator` with local-update weight `500000`. - CLI smoke validated the federated candidate and receipt with `validate-federated-candidate`. No coverage tool is active in this no-third-party workspace; evidence for the 75% target is the focused parameter and drift test slice, the full `slm_pack` suite, formatting, and the CLI write/validate smoke. ## Test Coverage Notes - `local_update_weight_ppm` is covered by zero, full, partial, default, and invalid parse tests. - Parent path inputs are covered by path-level write/validate and compatibility-bound checksum drift rejection. - Candidate and receipt paths are covered by path-level write/validate, recompute validation, and candidate drift rejection. - Base and local-update parent semantics are covered by weight-zero preserving base values, full-weight matching local-update values, and partial-weight candidate/checksum changes. - Quantization route behavior is covered by q8 candidate validation. ## Routing Open this report before changing `federated.rs`, `federated-candidate`, `validate-federated-candidate`, local-update receipt fields, local-update weighting, or federated/local-update parameter validation. ================================================================================ END FILE: wiki/gguf-mirust/reports/federated-operator-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29.md BYTES: 4845 SHA256: 2FAE2A02CCDBEC887074A417B24EA0B2EAF6A518908F1A317B366AD4BF5571AC ================================================================================ --- title: Federated Selector Receipt Route Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T14:55:00Z --- # Federated Selector Receipt Route Memory TinyRustLM now has downstream selector-registry and browser provenance proof for the federated/local-update operator receipt. ## What Changed - `tinyrustlm/tools/slm_pack/src/selector.rs` now has a selector test that builds a federated receipt-bound admission chain through candidate, promotion, admission, and selector registry text. - The test uses `operator_kind=federated-local-update-average` rather than the older mutation-style synthetic operator kind. - The registry writer preserves the admission receipt fields as `entry.0.operator_receipt_*`. - Registry validation preserves the federated operator kind, receipt checksum, candidate checksum equality, and candidate byte-count equality. - Registry validation now rejects federated operator-kind drift if `entry.0.operator_receipt_operator_kind` no longer matches the receipt-bound admission. - Shared selector fixtures now accept an operator kind argument, so future non-mutation operators can prove the same downstream route without cloning the whole helper chain. - `tinyrustlm/tools/browser-smoke.js` now adds federated `entry.0.operator_receipt_*` fields to the intercepted `multi-parent-registry` fixture. - Browser smoke captures the Model Provenance Operator row and asserts the rendered value includes `federated-local-update-average`. - Browser smoke now includes `selector-operator-receipt-drift`, which mutates the selector entry's operator receipt candidate byte count and proves the browser falls back to static local models before the drifted candidate becomes selectable. ## Verification - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector::tests::rejects_selector_registry_federated_operator_receipt_kind_drift` passed. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector::tests::` passed with 86 selector tests. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack` passed with 280 tests. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18881/app/ 9312 tinylm16q8 selector-operator-receipt-drift` passed and kept `selectedModel=tinylm16q8`, fallback static model options, and Model Provenance Operator `unavailable`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18880/app/ 9311 multi-parent-sign-merge-q8 multi-parent-registry` passed and rendered `receipt-bound / federated-local-update-average / 0x00000000000000b0`. - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:18881/app/ 9313 multi-parent-sign-merge-q8 multi-parent-registry` passed as the positive regression for the receipt-bound route. No coverage tool is active in this no-third-party workspace; this proof is recorded against the 75% target through the focused selector route test, the full selector suite, the full packer suite, and the targeted browser registry smoke. ## Test Coverage Notes - The federated operator-kind parameter is covered by the selector route test asserting `entry.0.operator_receipt_operator_kind=federated-local-update-average`. - The federated operator-kind drift path is covered by replacing that registry field with the mutation operator kind and asserting selector validation rejects `operator_receipt_operator_kind`. - Receipt checksum propagation is covered by asserting the registry entry checksum equals the admission receipt checksum. - Candidate checksum and byte-count propagation are covered by asserting the registry operator receipt fields match `entry.0.slm_checksum` and `entry.0.model_bytes`. - The helper operator-kind parameter is covered by preserving the existing default mutation-style route while exercising the federated route through the new test. - Browser provenance rendering is covered by the `multi-parent-registry` smoke, which captures `provenanceOperator` and asserts the federated operator kind survives browser registry intake. - Browser candidate byte-count drift is covered by `selector-operator-receipt-drift`, which changes `entry.0.operator_receipt_candidate_artifact_bytes`, asserts the generated registry entry is absent from `modelOptions`, and proves fallback q8 generation keeps the Operator row unavailable. ## Routing Open this report before changing selector registry operator receipt fields, browser Model Provenance Operator assertions, browser selector operator-receipt drift fallback, federated downstream handoff, receipt-bound admission-to-registry validation, or helper fixtures for non-mutation operator routes. ================================================================================ END FILE: wiki/gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/low-rank-adapter-package-memory-2026-06-28.md BYTES: 2527 SHA256: 570B199DD88B8BC53FC27C40834EE2C9E6F04D3D930DB81EF5814013F9E40BA3 ================================================================================ --- title: Low-Rank Adapter Package Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/low-rank-adapter-package-memory-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T00:00:00Z --- # Low-Rank Adapter Package Memory ## Summary TinyRustLM now has an `ALR1` low-rank adapter package lane for matrix-shaped f32 task deltas. `tinyrustlm-slm-pack low-rank-adapter-delta` writes deterministic `A` and `B` factor payloads plus a recomputable manifest, and `validate-low-rank-adapter-delta` rebuilds the artifact from the same compatibility-bound parents and lineage. Runtime adapter apply can consume compatible `ALR1` packages for already loaded f32, q8_0, or q4_0 models. ## Implementation Memory - `tinyrustlm/tools/slm_pack/src/adapter.rs` writes `ALR1` payloads under the same adapter header and tensor directory family as `ADP1` and `ASP1`. - Low-rank generation uses deterministic cross-residual components for matrix tensors, records component limit/cap, active matrix counts, factor density, initial L1, and residual L1 in the manifest, and leaves non-matrix tensors as no-op payloads. - `tinyrustlm/runtime/src/adapter.rs` validates the `ALR1` payload header, rank, matrix shape, factor byte count, payload checksum, and finite factors before exposing reconstructed delta values. - `tinyrustlm/runtime/src/model.rs` applies reconstructed low-rank deltas to f32 tensors and re-quantizes compact q8_0 rows or q4_0 blocks when a compatible quantized model is loaded. - The current browser adapter-family route still serves `ADP1` and `ASP1` packages. Selector-routed `ALR1` families are the next browser assembly bead. ## Validation Memory Current verification for this slice: - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-runtime adapter` with 12 adapter tests - `cargo test -p tinyrustlm-slm-pack adapter` with 27 adapter tests - CLI `compatibility`, `lineage-template`, `low-rank-adapter-delta`, and `validate-low-rank-adapter-delta` chain under `target/low-rank-adapter/` - `cargo test -p tinyrustlm-runtime` with 77 tests - `cargo test -p tinyrustlm-slm-pack` with 165 tests - `cargo test -p tinyrustlm-browser-harness` with 6 tests ## Routing Notes Use this report before changing `ALR1` parsing, `low-rank-adapter-delta`, `validate-low-rank-adapter-delta`, low-rank manifest fields, deterministic factor selection, or runtime low-rank apply. Pair it with the browser adapter-family and module-plan reports before adding selector-routed `ALR1` packages. ================================================================================ END FILE: wiki/gguf-mirust/reports/low-rank-adapter-package-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md BYTES: 9114 SHA256: 49CF8E4B99CDFF079F484D78F5644576C5B55B92106FBC98215004E3F28E8D5D ================================================================================ --- title: Model Breeding Ecology Memory 2026-06-26 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26/ status: planned_pending_publication reviewed_utc: 2026-06-27T13:45:00Z --- # Model Breeding Ecology Memory This durable synthesis turns the 2026-06-26 Improvement batch into routing memory for future TinyRustLM work. Model breeding in this project means a traceable candidate lifecycle: compatible parent artifacts, explicit lineage metadata, a bounded operator, deterministic conversion or merge output, evaluation sidecars, and a promotion record. It does not mean self-editing runtime behavior inside the browser app. ## Core Translation - Breeding unit: a local `.slm` candidate or future adapter/delta package with checksums, tokenizer identity, tensor schema, quantization layout, parent hashes, operator metadata, and evaluation evidence. - Compatibility gate: parameter-level merging requires the same base family, tensor names, shapes, tokenizer route, dtype or quantization semantics, and output-head contract. - Heterogeneous path: when architecture or tokenizer compatibility breaks, use distillation or retraining into the `.slm` ABI instead of direct weight mixing. - Operator lanes: model soups, task-vector addition, LoRA/adapters, TIES-style sign agreement, DARE-style sparse deltas, Model Breadcrumbs-style sparse masks, kinship-aware parent selection, evolutionary merge recipes, pruning, quantization, and post-merge fine-tuning route future work; current implemented slices include `sparse-delta-candidate` receipts with density, retention, and mask checksum fields, `adapter-delta`, `fuse-adapter-delta`, promotion ledgers, population reviews with objective-vector fields, parent-pool recipes with relatedness fields, sign-merge receipts that echo relatedness, multi-parent manifests that carry the relatedness summary, selector routing, and browser-verified adapter-family receipts plus manifests. - Code beading: split model work into small durable beads such as source manifest, candidate manifest, compatibility result, operator run, eval sidecar, promotion record, and rollback record. - 4Fs lens: Fast, Flexible, Frugal, and Federated are useful design adjectives for future model ecology choices, not canonical project law. ## Project Architecture Pressure TinyRustLM should first make model lineage cheap to record before making model breeding powerful. The current `.slm` manifest and quality-gate system already has most of the right shape: checksums, source kind, admission status, quality boundary, and eval sidecars. The next durable increment is a candidate lineage schema that records parent artifact hashes and an operator contract without changing the browser inference path. Potential future modules: - `compatibility`: validates base family, tokenizer hash, tensor directory, shape agreement, quantization mode, tied-output flag, and vocab size before any merge operator runs. - `lineage`: records parent ids, source hashes, operator version, parameter recipe, build tool hash, and evaluator route. - `candidate_eval`: runs bounded task cases, latency, scratch, context, and size gates before any candidate becomes selectable. - `adapter_delta`: stores future LoRA or adapter deltas as separate artifacts until the runtime has an explicit typed boundary for applying or fusing them. - `breeding_operator`: offline tool only; it produces `.slm` or candidate artifacts that still pass the normal admission and manifest gates. - `population_review`: validates a promotion ledger against admissions, scores candidates by quality, frugality, and quantization fit, records the weighted objective-vector contract plus per-entry objective checksums, then records the frontier route and parent-pool route. - `parent_pool_recipe`: validates the population review, requires selected parents to share one direct-parameter contract, and records ranked roles, seed weights, relatedness metric/scope/pair count/status, shared relatedness checksum, and per-parent relatedness groups for recipe consumers. ## Report Cluster Synthesis ### Model Merging Math `AI Model Merging Architectures Explained.md`, `Model merging refers to combining multiple trained neural.md`, and `Rust Tiny LLM Model Breeding Pipeline.md` route agents to weight-space fusion ideas: interpolation, soups, task arithmetic, TIES, DARE, alignment, and out-of-core merge execution. The project use is compatibility-first offline tooling. ### Adapters And LoRA `Tiny-LLM Adapters and LoRA.md`, `lightweight multi-model LLM system in Rust.md`, and the on-device tiny-language-model reports route agents to parameter-efficient adaptation. The useful pattern is a frozen base artifact plus small signed deltas, not a dependency-heavy runtime jump. ### Tiny Model Ecology `AI Evolution_ Small Models, Big Ecology.md`, the on-device reports, and 4Fs reports route agents to a population of small models where each candidate has bounded memory, latency, and evaluation evidence. This supports future model selector and cascade ideas only after single-model correctness stays strong. ### Teleodynamic Resource Loops `Teleodynamic Evolution of AI Ecosystems.md` and related reports route agents to measurable resource behavior: context budget, scratch bytes, KV length, load time, and candidate fitness. Translate theory into counters, gates, and smoke tests. ### Mutualist Product Voice `Mutualist Persistence.md`, `Aggressive Mutualism.md`, and the human motivation reports route agents to a constructive public voice: TinyRustLM grows by helping users inspect, swap, and improve local models. Public copy should follow `.uai/taboo.uai` and stay centered on proof, craft, lineage, and local agency. ## 2026-06-27 Implementation Notes - Compatibility, lineage, blend, task-delta, sparse task-delta, adapter-delta, adapter-fuse, candidate manifests, multi-parent candidate manifests, promotion templates, multi-parent promotion templates, multi-parent admission records, runtime-smoke sidecars, selector admission records, promotion ledgers, population reviews, parent-pool recipes, sign-merge receipts, and selector registries now exist as no-crate `tinyrustlm-slm-pack` gates. - Population review maps the population-based-training idea into a deterministic offline file: `promotion-ledger-plus-admission-records` becomes a ranked frontier candidate plus a parent pool for later recipes, with objective-vector metadata that names the weighted scoring dimensions. - Parent-pool recipe turns that ranked review into a shared-contract parent recipe with normalized seed weights and deterministic relatedness identity; sign-merge receipts echo that identity, and multi-parent candidate manifests carry it forward. - The browser runtime remains downstream of admitted registry routes only; population work stays offline until a candidate has passed the ordinary `.slm`, manifest, runtime-smoke, eval, admission, and ledger gates. ## 2026-06-27 Reference Routing Refresh - The companion research page now routes diverse model-breeding references beyond the first merge set: FedAvg, evolution strategies, sparse receipt retention metrics, pruning masks, lottery-ticket sparsity, adapter families, and quantized adapter training. - The 2026-06-27 research refresh adds Model Breadcrumbs, model kinship, evolutionary merge recipes, Mergenetic-style adaptive search, and multi-objective evolutionary merging as planning metadata; sparse masks, parent relatedness, and weighted population objective vectors now have first receipt-level forms, while resource budgets and recipe search remain future typed lanes. - Use those references as future metadata and eval lanes: distributed parent updates, search budgets, old-task retention, task masks, compact candidate artifacts, and adapter manifests. - Keep the current implementation boundary unchanged: offline tools produce evidence-bound `.slm` or adapter artifacts, while browser selection consumes only admitted registry routes. ## Implementation Sequence 1. Keep compatibility, lineage, operator receipts, manifests, promotion, admission, ledger, population review, parent-pool recipe, sign-merge, and multi-parent candidate files as the offline model-breeding path. 2. Extend planner/search work only when it can produce replayable recipe proposals, resource budgets, and eval sidecars that feed the same gates. 3. Require every produced candidate `.slm` to pass native validation, manifest validation, runtime-smoke, and fixture eval gates. 4. Add browser UI only after candidate provenance can be rendered as clean local model lineage. ## Hot Memory Hooks - `.uai/report-synthesis.uai` carries the compact research cluster. - `.uai/architecture.uai` routes future modules and compatibility boundaries. - `.uai/coding-standards.uai` keeps breeding offline and manifest-driven. - `.uai/operations.uai` records the report preservation and future checks. - `.uai/short-term-memory.uai` points to this durable synthesis. - `.uai/taboo.uai` controls site voice for the mutualist/model-breeding story. ================================================================================ END FILE: wiki/gguf-mirust/reports/model-breeding-ecology-memory-2026-06-26.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/multi-parent-soup-manifest-memory-2026-06-29.md BYTES: 2160 SHA256: 8FC66ED7289E9B2E33C477EC8F43AF0D851576F2BA7825BDC20BCA306DD5C568 ================================================================================ --- title: Multi-Parent Soup Manifest Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/multi-parent-soup-manifest-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T16:25:00Z --- # Multi-Parent Soup Manifest Memory `tinyrustlm-slm-pack multi-parent-candidate-manifest` now accepts validated parent-pool operator receipts from both `sign-merge-candidate` and `soup-candidate`. The manifest builder parses `operator_kind`, routes recomputation through the owning operator module, and preserves shared parent-pool fields plus the operator-specific metric block. Sign-merge manifests keep sign consensus fields. Soup manifests keep direct averaging fields: `soup_merge_rule`, `soup_weight_source`, `soup_weight_unit`, `soup_total_parameter_count`, `soup_parent_weight_checksum`, `soup_weighted_value_checksum`, `soup_changed_from_frontier_count`, and `soup_changed_from_frontier_density_ppm`. The candidate manifest status is now `validated-parent-pool-operator-output`, reflecting the shared gate. Existing downstream promotion, admission, selector, and browser-bundle paths still validate after the change, while the manifest route no longer assumes the only parent-pool operator is sign merge. ## Source Routes - `tinyrustlm/tools/slm_pack/src/multi_candidate.rs` - `tinyrustlm/tools/slm_pack/src/soup.rs` - `tinyrustlm/tools/slm_pack/src/sign_merge.rs` - `tinyrustlm/tools/slm_pack/src/multi_promotion.rs` - `tinyrustlm/tools/slm_pack/src/multi_admission.rs` ## Verification - `cargo fmt --all -- --check` passed. - `cargo test -p tinyrustlm-slm-pack multi_candidate -- --nocapture` passed with 8 tests. - `cargo test -p tinyrustlm-slm-pack multi_ -- --nocapture` passed with 23 tests, covering downstream multi-parent promotion, admission, selector, and browser-bundle paths. - `cargo test -p tinyrustlm-slm-pack` passed with 289 tests. ## Routing Open this report when changing `multi-parent-candidate-manifest`, `validate-multi-parent-candidate`, soup receipt handoff, parent-pool operator-kind dispatch, candidate manifest status, soup metric preservation, or sign-merge manifest compatibility. ================================================================================ END FILE: wiki/gguf-mirust/reports/multi-parent-soup-manifest-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/mutation-operator-memory-2026-06-29.md BYTES: 5356 SHA256: 5B9F1CF41251AC9A65C662952EB64893832CB276AEA0354CC41A6DE6B67BA9BB ================================================================================ --- title: Mutation Operator Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/mutation-operator-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T17:25:00Z --- # Mutation Operator Memory TinyRustLM now has an offline deterministic bounded mutation operator for model-breeding candidates. ## What Changed - `tinyrustlm/tools/slm_pack/src/mutation.rs` adds `mutation-candidate` and `validate-mutation-candidate` support for compatible two-parent `.slm` files. - Parent 0 is the base layout and output contract; parent 1 is the compatible reference parent used for bounded value-scale context. - The operator selects tensor elements by `mutation_seed` plus `mutation_rate_ppm`, applies signed deterministic perturbations bounded by `mutation_magnitude_ppm`, and writes a normal `.slm` candidate in the base parent's dtype/layout. - The receipt records selection counts, changed counts, selection density, `mutation_mask_checksum`, and `mutation_delta_checksum`. - Validation recomputes lineage, parent compatibility checks, candidate bytes, and the entire operator receipt before accepting the artifact. - `tinyrustlm/tools/slm_pack/src/main.rs` exposes the new CLI commands and usage line. - `tinyrustlm/tools/browser-smoke.js` now has a `mutation-operator-registry` fixture that proves browser Model Provenance renders a receipt-bound mutation operator row, plus `mutation-operator-receipt-drift` for browser byte-echo fallback. - `tinyrustlm/README.md` routes the mutation browser smoke commands beside the other compact operator provenance examples. ## Receipt Fields - `tinyrustlm_mutation_operator_version=1` - `operator_kind=deterministic-bounded-parameter-mutation` - `base_parent_index=0` - `reference_parent_index=1` - `mutation_seed=` - `mutation_rate_unit=parts-per-million` - `mutation_rate_ppm=<0..1000000>` - `mutation_magnitude_unit=parts-per-million-of-value-scale` - `mutation_magnitude_ppm=<0..1000000>` - `mutation_selection_metric=splitmix64-tensor-element-threshold` - `mutation_selection_scope=compatible-base-tensor-values` - `mutation_tie_break=mutate-when-threshold-equal` - `mutation_value_scale=max-abs-parent-value-or-one` - `mutation_total_parameter_count`, `mutation_selected_parameter_count`, `mutation_changed_parameter_count` - `mutation_selection_density_ppm` - `mutation_mask_checksum` - `mutation_delta_checksum` ## Verification - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml mutation -- --nocapture` passed with 11 mutation tests. - CLI smoke wrote `target/mutation-cli/parents.compat`. - CLI smoke wrote `target/mutation-cli/candidate.lineage`. - CLI smoke wrote `target/mutation-cli/candidate.slm` and `target/mutation-cli/candidate.operator` with seed `77`, rate `1000000`, and magnitude `100000`. - CLI smoke validated the mutation candidate and receipt with `validate-mutation-candidate`. - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml -- --nocapture` passed with 252 tests. - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8128/app/ 9422 tinylm16-mutation-q8 mutation-operator-registry` passed, rendering `receipt-bound / deterministic-bounded-parameter-mutation / 0x00000000000000b3`. - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8128/app/ 9423 tinylm16q8 mutation-operator-receipt-drift` passed, dropping the drifted mutation registry entry and returning to static q8 with operator provenance unavailable. - Regression smokes for the shared compact fixture passed on `http://127.0.0.1:8128/app/`: federated `multi-parent-registry`, prune `prune-operator-registry`, and prune `prune-operator-receipt-drift`. - `node --check tinyrustlm\tools\browser-smoke.js` passed after the mutation browser fixture update. No coverage tool is active in this no-third-party workspace; evidence for the 75% target is the focused parameter and drift test slice, the full `slm_pack` suite, formatting, the CLI write/validate smoke, and the browser provenance/drift smokes. ## Test Coverage Notes - `mutation_seed` is covered by seed-different candidate and mask checksum tests. - `mutation_rate_ppm` is covered by rate-zero, full-rate, partial-rate, default, and invalid parse tests. - `mutation_magnitude_ppm` is covered by magnitude-zero, magnitude-different, default, and invalid parse tests. - The reference parent parameter is covered by a scale-different candidate test and compatibility-bound checksum validation. - Parent path inputs are covered by path-level write/validate and parent checksum drift rejection. - Candidate and receipt paths are covered by path-level write/validate, recompute validation, and candidate drift rejection. - Browser operator receipt routing is covered by mutation positive provenance rendering and mutation byte-echo fallback smokes, plus federated and prune fixture regression smokes through the same compact registry fixture. - Quantization route behavior is covered by q8 candidate validation. ## Routing Open this report before changing `mutation.rs`, `mutation-candidate`, `validate-mutation-candidate`, deterministic mutation masks, mutation receipt fields, mutation browser operator provenance, or mutation parameter validation. ================================================================================ END FILE: wiki/gguf-mirust/reports/mutation-operator-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/operator-schedule-carry-forward-memory-2026-06-29.md BYTES: 3085 SHA256: 927274A319833D6A83BE79B20ACB44C2589F617AA76C6BABC76EBDBDC163F960 ================================================================================ --- title: Operator Schedule Carry-Forward Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/operator-schedule-carry-forward-memory-2026-06-29/ status: reviewed_current reviewed_utc: 2026-06-29T20:22:33Z --- # Operator Schedule Carry-Forward Memory ## Summary Parent-pool evolution schedules now flow beyond the recipe into sign-merge and soup operator receipts, multi-parent candidate manifests, multi-parent promotion templates, and multi-parent selector admission records. The handoff chain records the schedule checksum, schedule strategy/status/source, selected operator-family index, scheduled command, scheduled selection rule, and scheduled output gate. ## Source Change - `tinyrustlm/tools/slm_pack/src/sign_merge.rs` copies the sign-merge schedule family from the parent-pool recipe into each sign-merge receipt. - `tinyrustlm/tools/slm_pack/src/soup.rs` copies the soup schedule family from the parent-pool recipe into each soup receipt. - `tinyrustlm/tools/slm_pack/src/multi_candidate.rs` validates the scheduled family against the recipe and carries the schedule fields into the candidate manifest. - `tinyrustlm/tools/slm_pack/src/multi_promotion.rs` carries the schedule fields from the candidate manifest into the multi-parent promotion template. - `tinyrustlm/tools/slm_pack/src/multi_admission.rs` carries the schedule fields into the selector admission record and validates scheduled family kind against the bound operator receipt. - `tinyrustlm/tools/slm_pack/src/selector.rs` updates the multi-parent selector fixture schema so selector-registry validation consumes the new admission shape. ## Verification - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-slm-pack sign_merge -- --nocapture` - `cargo test -p tinyrustlm-slm-pack soup -- --nocapture` - `cargo test -p tinyrustlm-slm-pack multi_candidate -- --nocapture` - `cargo test -p tinyrustlm-slm-pack multi_promotion -- --nocapture` - `cargo test -p tinyrustlm-slm-pack multi_admission -- --nocapture` - `cargo test -p tinyrustlm-slm-pack writes_and_validates_selector_registry_from_multi_parent_admission_record -- --nocapture` - `cargo test -p tinyrustlm-slm-pack writes_and_validates_mixed_selector_registry_admission_versions -- --nocapture` - `cargo test -p tinyrustlm-slm-pack` The focused tests assert schedule checksum and scheduled-family command fields for sign-merge receipts, soup receipts, candidate manifests, promotion templates, admission records, and selector-registry admission fixtures. The full packer suite passed with 324 tests. No coverage tool is active in the zero-dependency workspace, so focused field assertions plus full packer coverage are recorded against the 75% target. ## Routing Load this report before changing parent-pool evolution schedules, sign-merge receipts, soup receipts, multi-parent candidate manifests, multi-parent promotion templates, multi-parent admission records, scheduled operator-family handoff, selector registry admission fixtures, or browser bundle evidence chains that consume parent-pool operator receipts. ================================================================================ END FILE: wiki/gguf-mirust/reports/operator-schedule-carry-forward-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/parent-pool-evolution-schedule-memory-2026-06-29.md BYTES: 1996 SHA256: 7252D69EA8006080C29A12961736F33C8045F5161E59E91F7787FCF7A722F9CE ================================================================================ --- title: Parent-Pool Evolution Schedule Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/parent-pool-evolution-schedule-memory-2026-06-29/ status: reviewed_current reviewed_utc: 2026-06-29T19:52:45Z --- # Parent-Pool Evolution Schedule Memory ## Summary `parent-pool-recipe` now writes an explicit evolution schedule alongside the reviewed parent seed weights. The schedule binds `population-based-parent-pool-replay-v1`, planned `sign-aware-parent-pool-merge` and `seed-weighted-parent-pool-soup` operator families, each family's command and selection rule, selected parent ids, seed weights, population fitness values, and a checksum over the schedule text. ## Source Change - `tinyrustlm/tools/slm_pack/src/parent_pool.rs` adds schedule constants, `EvolutionOperatorFamily`, `build_evolution_schedule_text`, and an `evolution_schedule_checksum` field. - The recipe still validates the promotion ledger, population review, admission records, shared direct-parameter contract, relatedness fields, and seed weights before writing schedule fields. - `validate-parent-pool-recipe` recomputes the full recipe, so changed schedule fields or checksum drift are rejected before sign-merge, soup, or multi-parent candidate-manifest work consumes the parent pool. ## Verification - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-slm-pack parent_pool -- --nocapture` - `cargo test -p tinyrustlm-slm-pack` The focused parent-pool tests assert the operator-family fields, parent seed-weight schedule fields, checksum algorithm, and checksum drift rejection. The full packer test suite passed with 323 tests. No coverage tool is active in the zero-dependency workspace, so focused field/drift tests plus full packer coverage are recorded against the 75% target. ## Routing Load this report before changing parent-pool recipes, PBT-style population replay, parent-pool operator scheduling, sign-merge/soup recipe handoff, or evolution schedule checksum validation. ================================================================================ END FILE: wiki/gguf-mirust/reports/parent-pool-evolution-schedule-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29.md BYTES: 4555 SHA256: 4AD7EC8BF5F93D3FC51332B6AF2ABE94C7AD23EC3D509554D86A706734E397C5 ================================================================================ --- title: Promotion Operator Receipt Binding Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T08:15:00Z --- # Promotion Operator Receipt Binding Memory TinyRustLM two-parent promotion templates can now carry the candidate manifest's producer receipt binding forward into the promotion record. ## What Changed - `tinyrustlm/tools/slm_pack/src/promotion.rs` keeps existing unbound promotion behavior while adding receipt-aware template and validation paths. - `promotion-template [promoter-id] [promotion-scope] [input.operator]` reads the optional receipt and requires it when the candidate manifest is receipt-bound. - `validate-promotion [input.operator]` recomputes candidate and receipt binding before accepting the promotion record. - Receipt-bound candidate manifests without the receipt input do not validate through promotion; unbound candidate manifests and unbound promotions keep the existing path. ## Promotion Fields - `operator_receipt_status=receipt-bound` - `operator_receipt_path=` - `operator_receipt_checksum=` - `operator_receipt_operator_id=` - `operator_receipt_operator_kind=` - `operator_receipt_candidate_slm_checksum=` - `operator_receipt_candidate_artifact_bytes=` ## Validation Boundaries - Promotion validation first recomputes the candidate manifest binding against compatibility, lineage, candidate bytes, and optional operator receipt text. - Bound promotion fields must exactly match the candidate manifest's receipt fields. - Unbound candidate manifests cannot be paired with stray `operator_receipt_*` promotion fields. - Receipt checksum drift, missing receipt input, and candidate artifact drift are rejected before promotion can advance to runtime smoke and eval sidecars. ## Verification - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml candidate -- --nocapture` passed with 50 focused candidate and neighboring operator tests. - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml promotion -- --nocapture` passed with 15 focused promotion and neighboring ledger tests. - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml` passed with 261 tests. - `C:\Users\AI\.cargo\bin\cargo.exe build --manifest-path tinyrustlm/tools/slm_pack/Cargo.toml` rebuilt the CLI binary. - CLI smoke wrote and validated compatibility, lineage, mutation candidate, operator receipt, receipt-bound candidate manifest, receipt-bound promotion template, and receipt-bound promotion validation under `C:\Users\AI\AppData\Local\Temp\tinyrustlm-promotion-cli-7b5f19ad0c7848139d9c7cbcfd0a5b69\`. - CLI smoke inspected `candidate.promotion` and found `operator_receipt_status=receipt-bound`, `operator_receipt_checksum=0x8164c5a20346a815`, and `operator_receipt_operator_kind=deterministic-bounded-parameter-mutation`. - `C:\Users\AI\.cargo\bin\cargo.exe test --workspace` passed with browser harness, local server, runtime, slm_pack, and doc-test checks. No coverage tool is active in this no-third-party workspace; evidence for the 75% target is the focused happy path, path-parameter coverage, receipt drift rejection, missing receipt rejection, full packer suite, workspace suite, build, formatting, and CLI write/validate smoke. ## Test Coverage Notes - `operator_receipt: Option<&Path>` is covered by a path-level promotion template write and validation test. - `operator_receipt` text binding is covered by receipt-bound template and validation text tests. - `operator_receipt_checksum` is covered by promotion checksum drift rejection. - Missing receipt input for a bound candidate and promotion is covered by explicit rejection. - Existing unbound promotion tests continue to cover default promoter id, promotion scope, candidate drift, manifest drift, and promotion overclaim behavior. ## Routing Open this report before changing `promotion.rs`, `promotion-template`, `validate-promotion`, candidate receipt carry-forward, promotion gate behavior, or downstream admission assumptions about two-parent candidate provenance. ================================================================================ END FILE: wiki/gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/prune-operator-memory-2026-06-29.md BYTES: 6211 SHA256: 2FB6185B39E63EEC21374FD777B2713C648B9A06E423D42EA37962BF9FBF238C ================================================================================ --- title: Prune Operator Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/prune-operator-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T23:10:00Z --- # Prune Operator Memory TinyRustLM now has an offline deterministic magnitude-pruning operator for model-breeding candidates. ## What Changed - `tinyrustlm/tools/slm_pack/src/prune.rs` adds `prune-candidate` and `validate-prune-candidate` support for compatible two-parent `.slm` files. - Parent 0 is the base layout and output contract; parent 1 is the compatible reference parent used for magnitude-ranking context. - The operator ranks compatible tensor values by `max(abs(base), abs(reference))`, keeps the strongest base values by `keep_ppm`, applies an optional `floor_ppm`, zeros unkept values, and writes a normal `.slm` candidate in the base parent's dtype/layout. - The receipt records requested keep count, kept/pruned/changed counts, keep density, max-magnitude bits, floor-threshold bits, `prune_mask_checksum`, and `prune_output_value_checksum`. - Validation recomputes lineage, parent compatibility checks, candidate bytes, and the entire operator receipt before accepting the artifact. - `tinyrustlm/tools/slm_pack/src/main.rs` exposes the new CLI commands and usage line. - `tinyrustlm/tools/slm_pack/src/selector.rs` now has explicit prune receipt carry-forward and receipt-kind drift tests for selector registry handoff. - `tinyrustlm/tools/browser-smoke.js` now has a `prune-operator-registry` fixture that proves browser Model Provenance renders a receipt-bound prune operator row, plus `prune-operator-receipt-drift` for browser byte-echo fallback. - `tinyrustlm/README.md` routes the prune browser smoke commands beside the existing selector-operator receipt smoke examples. ## Receipt Fields - `tinyrustlm_prune_operator_version=1` - `operator_kind=deterministic-magnitude-parameter-pruning` - `base_parent_index=0` - `reference_parent_index=1` - `prune_keep_unit=parts-per-million` - `prune_keep_ppm=<0..1000000>` - `prune_floor_unit=parts-per-million-of-max-parent-magnitude` - `prune_floor_ppm=<0..1000000>` - `prune_selection_metric=largest-compatible-magnitude-with-floor` - `prune_selection_scope=compatible-base-tensor-values` - `prune_tie_break=lower-tensor-index-then-lower-element-index` - `prune_value_source=base-parent-kept-values-else-zero` - `prune_total_parameter_count`, `prune_requested_keep_count`, `prune_kept_parameter_count`, `prune_pruned_parameter_count`, `prune_changed_parameter_count` - `prune_keep_density_ppm` - `prune_max_magnitude_bits` - `prune_floor_threshold_bits` - `prune_mask_checksum` - `prune_output_value_checksum` ## Verification - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack prune -- --nocapture` passed with 12 prune-filtered tests, including the selector handoff tests whose names include prune. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack selector::tests:: -- --nocapture` passed with 88 selector tests, including prune receipt-bound admission carry-forward and prune operator-kind drift rejection. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack --quiet` passed with 305 tests. - `C:\Users\AI\.cargo\bin\cargo.exe test --workspace --quiet` passed. - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8126/app/ 9410 tinylm16-prune-q8 prune-operator-registry` passed, rendering `receipt-bound / deterministic-magnitude-parameter-pruning / 0x00000000000000b1`. - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8126/app/ 9411 tinylm16q8 prune-operator-receipt-drift` passed, dropping the drifted prune registry entry and returning to static q8 with operator provenance unavailable. - Regression smokes for the existing federated compact fixture passed on `http://127.0.0.1:8127/app/`: `multi-parent-registry` rendered `federated-local-update-average`, and `selector-operator-receipt-drift` still fell back to static q8. - `node --check tinyrustlm\tools\browser-smoke.js`, `C:\Users\AI\.cargo\bin\cargo.exe fmt --all -- --check`, and `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-browser-harness --quiet` passed after the prune browser fixture update. - CLI smoke wrote `target/prune-cli/tinylm16-q8-self.compat`. - CLI smoke wrote `target/prune-cli/tinylm16-q8-prune.lineage`. - CLI smoke wrote `target/prune-cli/tinylm16-q8-prune.slm` and `target/prune-cli/tinylm16-q8-prune.operator` with keep `750000` and floor `0`. - CLI smoke validated the prune candidate and receipt with `validate-prune-candidate`. - CLI smoke validated the resulting `.slm` with `validate`; the candidate stayed q8_0 and 17,160,000 bytes. - `git diff --check` passed with line-ending normalization notices only. No coverage tool is active in this no-third-party workspace; evidence for the 75% target is the focused parameter and drift test slice, the full `slm_pack` suite, workspace tests, formatting, and the CLI write/validate smoke. ## Test Coverage Notes - `keep_ppm` is covered by default, zero, full, accepted-path, and invalid parse tests. - `floor_ppm` is covered by default, value-changing floor behavior, accepted-path, and invalid parse tests. - The reference parent parameter is covered by a magnitude-spike test that changes the selected mask and candidate. - Parent path inputs are covered by path-level write/validate and parent checksum drift rejection. - Candidate and receipt paths are covered by path-level write/validate, recompute validation, candidate drift rejection, selector receipt carry-forward, and selector operator-kind drift rejection. - Browser operator receipt routing is covered by prune positive provenance rendering and prune byte-echo fallback smokes, plus federated fixture regression smokes through the same compact registry fixture. - Quantization route behavior is covered by q8 candidate validation. ## Routing Open this report before changing `prune.rs`, `prune-candidate`, `validate-prune-candidate`, deterministic pruning masks, pruning receipt fields, selector operator receipt handoff, prune browser operator provenance, or pruning parameter validation. ================================================================================ END FILE: wiki/gguf-mirust/reports/prune-operator-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/registry-adapter-family-memory-2026-06-27.md BYTES: 3231 SHA256: D9403FB1EF61BC4A7FB79A1075573BECAE69F3FA9E741C9303FC10DBBED3ED97 ================================================================================ --- title: Registry Adapter Family Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/registry-adapter-family-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T16:25:00Z --- # Registry Adapter Family Memory ## Summary TinyRustLM now proves generated selector registries can expose small families of compatible local f32/q8_0/q4_0 `ADP1` and `ASP1` sidecars for matching admitted model entries. The registry keeps the earlier single-adapter fields for the first route, then adds indexed adapter-family fields when more than one route exists. The browser parses the indexed family, displays self ADP1, family ADP1, and sparse ASP1 options, selects the sparse route during `adapter-sidecar-registry-file`, fetches the matching `multi-parent-sign-merge-*-sparse.asp1` from the same local origin, transfers bytes into WASM, and leaves package validation to Rust. ## Implementation Memory - `tinyrustlm/tools/slm_pack/src/selector.rs` stores zero or more `RegistryAdapterRoute` values per entry, rejects duplicate adapter paths for the same candidate, and requires adapter apply status to match f32/q8_0/q4_0 registry entry quantization. - Single-adapter registries keep the existing `entry.N.adapter_path`, manifest, label, apply status, and checksum fields. - Multi-adapter registries add `entry.N.adapter_count` plus indexed fields such as `entry.N.adapter.1.path`, `manifest_path`, `label`, `apply_status`, `artifact_checksum`, and `manifest_checksum`. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` now stages matching self and family `.adp1` packages plus a sparse `.asp1` package for generated f32/q8_0/q4_0 roots through the same compatibility, lineage, adapter-delta, sparse-adapter-delta, and validation gates. - `tinyrustlm/app/app.js` parses either the legacy single-sidecar fields or indexed adapter-family fields, keeps routes local to `../models/*.adp1` or `../models/*.asp1`, and does not parse adapter bytes. - `tinyrustlm/tools/browser-smoke.js` now expects all three generated adapter options and applies the sparse route during `adapter-sidecar-registry-file`. ## Validation Memory - `cargo fmt --all` passed. - `node --check tinyrustlm/app/app.js` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - `cargo test -p tinyrustlm-slm-pack selector` passed with 17 tests. - `cargo test -p tinyrustlm-slm-pack browser_bundle` passed. - A generated browser bundle served over the Rust local server passed `adapter-sidecar-registry-file`, showing all three generated adapter options and applying `multi-parent-sign-merge-f32-sparse.asp1`. - Generated q8_0 and q4_0 browser bundles keep the same adapter-family route shape, with sparse ASP1 coverage owned by `browser-sparse-adapter-route-memory-2026-06-27.md`. ## Routing Notes Use this report before changing selector registry adapter-family fields, generated bundle adapter staging, browser registry adapter parsing, or `adapter-sidecar-registry-file` assertions. This report extends the registry adapter sidecar memory from one route to a small typed family; runtime ADP1/ASP1 package validation and browser byte-transfer boundaries remain owned by the runtime and browser adapter reports. ================================================================================ END FILE: wiki/gguf-mirust/reports/registry-adapter-family-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/registry-adapter-sidecar-memory-2026-06-27.md BYTES: 4106 SHA256: 96335F13A53262F4486265C96D01FF6F3274700EBB008400A8A0930B2AE748BB ================================================================================ --- title: Registry Adapter Sidecar Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/registry-adapter-sidecar-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T16:25:00Z --- # Registry Adapter Sidecar Memory ## Summary TinyRustLM now proves selector registries can carry admitted local `.slm` model routes plus compatible local f32, q8_0, or q4_0 `ADP1` adapter sidecar routes when the adapter apply status matches the entry quantization. `browser-multi-parent-bundle` stages generated f32, q8_0, and q4_0 sign-merge families, while the browser smoke harness also serves an intercepted tiny q8_0 registry entry with a matching ADP1 route. In each path, the browser loads the model from the registry, shows the registry-supplied adapter option, checks the selected `.adp1` artifact checksum, transfers the local bytes into WASM, and Rust validates the package before applying it. ## Implementation Memory - `tinyrustlm/tools/slm_pack/src/selector.rs` now has optional `RegistryAdapterRoute` fields for f32/q8_0/q4_0 registry entries: adapter path, adapter manifest path, label, apply status, adapter checksum, and manifest checksum. - Selector validation still recomputes the admitted model route fields from admission records, then validates optional adapter route fields structurally and requires apply status to match entry quantization. - `tinyrustlm/tools/slm_pack/src/browser_bundle.rs` now builds self and family adapters for generated f32/q8_0/q4_0 sign-merge candidates through the existing compatibility, lineage, adapter-delta, and validate-adapter-delta gates. - `tools/browser-smoke.js` now has `adapter-sidecar-registry-file` mode, which reuses the adapter-sidecar click path against a generated file-backed registry, plus `adapter-sidecar-registry-q8` for a quantized registry-supplied adapter route. - `tools/vs/Test-TinyRustLM.ps1 -BrowserSmoke` now runs the generated registry model smoke for f32 and generated registry adapter smokes for f32/q8_0/q4_0 staged bundle roots. ## Validation Memory - `cargo fmt --all -- --check` passed. - `node --check tinyrustlm/tools/browser-smoke.js` passed. - PowerShell parsing of `tools/vs/Test-TinyRustLM.ps1` passed. - `cargo test -p tinyrustlm-slm-pack selector::` passed with 17 tests. - `cargo test -p tinyrustlm-slm-pack adapter_family::` passed with 3 tests. - `cargo test -p tinyrustlm-slm-pack` passed with 147 tests. - `cargo run -p tinyrustlm-browser-harness -- tinyrustlm` passed with 8 checks. - `node tinyrustlm/tools/wasm-abi-smoke.js` passed. - A generated browser bundle served over the Rust local server passed `multi-parent-registry-file`. - The same generated bundle passed `adapter-sidecar-registry-file`, including the local `multi-parent-sign-merge-f32-self.adp1` request and post-apply f32 diagnostic reset. - The intercepted q8_0 registry route passed `adapter-sidecar-registry-q8`, including the `models/selector.registry` request, `tiny-test-model-q8-self.adp1` request, `adapter applied` response, and q8_0 diagnostic reset. - The checked tiny f32/q8_0/q4_0 fallback routes pass `adapter-sidecar`. - Generated q8_0 and q4_0 browser bundle roots passed `adapter-sidecar-registry-file`, including selector registry, model, manifest, assembly receipt, evidence files, adapter-family receipt, adapter manifests, family ADP1 request, `adapter applied` response, and selected quantization diagnostics after apply. ## Routing Notes Use this report before changing selector registry fields, generated browser bundle staging, registry-supplied adapter UI behavior, or file-backed browser smoke coverage. This report does not replace the runtime adapter apply report or the checked browser adapter sidecar report; it links those two beads into the selector registry route. Future adapter work can extend this bead toward LoRA-style packages, compact adapter variants, or compact adapter-family metadata. Those future formats still need explicit package manifests, runtime validation, browser route filtering, and smoke evidence before they become browser-visible options. ================================================================================ END FILE: wiki/gguf-mirust/reports/registry-adapter-sidecar-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/report-intake-index-2026-06-25.md BYTES: 6432 SHA256: 068DE841DDCC3D4CDEB8518274ACF1CE21004861FFDEDEE81824B408D856946D ================================================================================ --- title: Report Intake Index 2026-06-25 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/report-intake-index-2026-06-25/ status: planned_pending_publication reviewed_utc: 2026-06-25T00:00:00Z --- # Report Intake Index 2026-06-25 This record routes the 23 active Improvement reports that were processed into GGUF.MiRust.com memory on 2026-06-25. The reports are not a single instruction source. They form a field of pressure around TinyRustLM: enterprise discipline, browser-local execution, tiny model architecture, modular skill composition, teleodynamic/resource-bounded behavior, and product positioning. The active implementation prompt remains stricter than many reports because it requires a zero-dependency custom Rust/WASM runtime, no third-party crates, no npm, no wasm-bindgen, no ML framework, no remote inference, and local static model files only. ## Durable Synthesis Records - [Enterprise Rust Governance Memory](enterprise-rust-governance-memory-2026-06-25.md) - [Browser Local Runtime Memory](browser-local-runtime-memory-2026-06-25.md) - [TinyLM Modular Architecture Memory](tinylm-modular-architecture-memory-2026-06-25.md) - [Teleodynamic Resource Bounded Memory](teleodynamic-resource-bounded-memory-2026-06-25.md) - [Brand Product Positioning Memory](brand-product-positioning-memory-2026-06-25.md) ## Source Inventory | Source report | Theme | SHA256 | | --- | --- | --- | | best practices and governance guidelines for enterprise Rust adoption.md | Enterprise governance | E21E55B89EA8142374C0563B0E81F530584F1849B44B23836A6E3FA0E7E06F7B | | Branding MiRust.com.md | Brand and product position | 2AD930E5AD223D29CC1E5B0B1C3FA69B7F75AB6F11E1A2ED222ED7EA7C8925F9 | | Building a lightweight AI runtime in the browser with Rust.md | Browser local runtime | 29DB7C6AD77A18076C0B820C9AF17BC1A061BD63856AF42F3465952B407568CC | | Building Custom Rust SML Runtime.md | Runtime architecture, typed VM analogy | FEFE15940895E87634D805A680DF9FC8AED8246DEB152577D5683119F0A27167 | | Building Rust AI Runtime for Web.md | Browser runtime and WebAssembly limits | 9C65C6EEB53B9664E99B5BAD6DA3FF600FF2435FE62E55C323685C23D720AAFA | | Enterprise Rust Best Practices.md | Enterprise governance | 4AA20BDCB09E7304008F36DC5FAB668B982AC38736BFE96087AA5A823556F26E | | Machine Inteligence framwork for rust.md | Duplicate brand/product content | 2AD930E5AD223D29CC1E5B0B1C3FA69B7F75AB6F11E1A2ED222ED7EA7C8925F9 | | Modular AI in Browser.md | Modular browser AI and skill composition | AE3690ED7E2EB6EE2563BE58DA636907555AA2A4310E707311FF76E553AC3972 | | Modular Tiny Language Models Architecture.md | Modular tiny models | AE5B3DB9B02C19E8EB363C6BE44CC93D0001F9AE7E5CD9FADAE8970CC279A7A1 | | Multiple Tiny Language Models Architectures and Trends.md | Multiple tiny model systems | 0B9B9E861F95A80CAC26A1FBBCE904CD4E8A519AFFA2D9F7D18EDDC38E1927F9 | | Rust Browser Tiny LLM Architecture.md | Browser native modular tiny LLM | 3A8C41DCB8F108508BF0494B35FEE8AEE20F93098F1389D14D5D85026E5A2A5D | | Rust Design Patterns and SOLID Principles.md | Rust patterns and anti-patterns | 6E929C6C60C5FD2E4369EBBBA7368B0E3FF50D6267CED9EFE40EDD8A48335139 | | Rust In-Browser Teleodynamic AI Plan.md | Teleodynamic browser AI | DCCCEA520740823D585BADEAE500CBC381E816D120772F69F28CB63B783ABE78 | | Rust ownership model and type system naturally embody many SOLID concepts.md | Rust patterns and SOLID mapping | F1F48056D4517F95A9A344132B7C2B35AF94524124F81A49CCC5CEF7DBA543B0 | | Rust WebAssembly Teleodynamic AI Architecture.md | Teleodynamic WebAssembly architecture | 3A3F5F906858B934BB60C0C3C6F2F9015A020D31E2F269EE43486A768D463487 | | Teleodynamic AI in the Browser.md | Teleodynamic browser agent | 2F0A4D4E7F46FC401B7ED47354A21E4F1F40AE08C89F4C70512B8DF8994FC45B | | Teleodynamic AI is an approach where a system’s structure and parameters co-evolve.md | Modular teleodynamic skill systems | FC41A09C9A863B76ACBC7E694A80113E8A6A103F0C62CE18B0A3384A9C912DB3 | | Teleodynamic AI is an approach.md | Duplicate modular teleodynamic skill systems | FC41A09C9A863B76ACBC7E694A80113E8A6A103F0C62CE18B0A3384A9C912DB3 | | Teleodynamic AI refers to resource-bounded.md | Resource-bounded browser agents | BFFC87F10A7A66ED002DF6AB161B0A06A2791C6DE45BEC5CB7313D87851DAFE5 | | Teleodynamic Tiny Language Model Architecture.md | Teleodynamic multi-model architecture | 9F657BEEC6C1B43B907E1267E4273761D4F946D097CCE247DDACCFF92617180A | | Teleodynamics is a theoretical framework .md | Teleodynamic ensembles | AED5AC457EB29A648B960E4201068E5BC278A6BDB8ED8E82E18968AA808C50E6 | | Tiny Language Models Architecture.md | Multi-model SLM ecosystem | 2769072DA2BB333D953F801C73C126E716EA685ABBBE6290631D0368281FA5EE | | To run a TinyLM-16M transformer in-browser.md | TinyLM-16M implementation plan | BACB21BCF5F15DB102044311256A921014DE9E73B3C43EFFC4F17AEDA649B92C | ## Duplicate Content Notes - `Branding MiRust.com.md` and `Machine Inteligence framwork for rust.md` have identical SHA256 hashes. Treat them as one brand/product-positioning source with two filenames. - `Teleodynamic AI is an approach where a system’s structure and parameters co-evolve.md` and `Teleodynamic AI is an approach.md` have identical SHA256 hashes. Treat them as one modular teleodynamic skill-system source with two filenames. ## Processing Judgment The reports contain many useful ideas that conflict with the active TinyRustLM constraint set when read literally. Framework recommendations such as Candle, Burn, WebGPU-first stacks, wasm-bindgen-rayon, IndexedDB-heavy loaders, package managers, and external tokenization formats are preserved as future comparison context only. They are not current implementation instructions. The durable memory therefore separates inspiration from authority: - Current authority: the TinyRustLM prompt, local `.uai` files, source code, tests, and generated local `.slm` artifacts. - Durable report memory: design pressure, questions, trade-off maps, and future directions. - Raw evidence: copied source reports under `raw/gguf-mirust/report-intake-2026-06-25/`. ## Next Agent Routing - For build, test, or runtime facts, read `tinyrustlm/README.md`, `tinyrustlm/docs/`, and `.uai/test-plan.uai`. - For report-derived philosophy and design pressure, read the five synthesis records linked above. - For exact original report wording, read the raw evidence copies and compare checksums against this index. ================================================================================ END FILE: wiki/gguf-mirust/reports/report-intake-index-2026-06-25.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/report-intake-index-2026-06-26.md BYTES: 6439 SHA256: 92BD64EC61B290C2A4CBB1DAE14622043B5714E8C6EE922145E410930F240EEB ================================================================================ --- title: Report Intake Index 2026-06-26 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/report-intake-index-2026-06-26/ status: planned_pending_publication reviewed_utc: 2026-06-26T18:44:35Z --- # Report Intake Index 2026-06-26 This record routes the 26 active Improvement reports processed into GGUF.MiRust.com memory on 2026-06-26. The batch deepens the project around model breeding, code beading, the 4Fs lens, LoRA and adapter composition, model merging, on-device tiny LLMs, teleodynamic resource loops, mutualist product voice, and human motivation as a UX/product metaphor. It is research memory and future architecture pressure, not a direct implementation claim. ## Durable Synthesis Records - [Model Breeding Ecology Memory](model-breeding-ecology-memory-2026-06-26.md) - [Model Breeding Reference Ideas](../research/model-breeding-reference-ideas-2026-06-26.md) ## Source Inventory | Source report | Theme | SHA256 | | --- | --- | --- | | 4Fs and code beadingmodel breeding.md | 4Fs, code beading, model breeding definitions | C9B395CF265EA6D4BA17BD7087A72AC6B18C5FA7896E03E443ABE6D1E3A83545 | | Adaptable, Resource-Efficient AI Ecosystems.md | 4Fs and adaptable model ecologies | 41BCB67FEEB7018C987C47BE89E1BABFFF1D9274694385B70098EBA940091F93 | | Aggressive Mutualism.md | mutualist framing and propagation metaphors | 91DD6DA9CEC06068698AFA0107283467DF5AFF22DF2928DE445E7611478FCB0C | | AI Code Beading and Model Breeding.md | code beading, teleodynamic convergence, mutable small models | 4E3F836C01BF7B801BD32BF8AD560AB2DD481AB0C5587F5E168096B3127B6D68 | | AI Evolution_ Small Models, Big Ecology.md | small model ecology and evolution pipeline | FBBCC2EBBDB3986DF84D4499557F59FC7C76677EFA7616DF159BD199AF98DB0E | | AI Model Merging Architectures Explained.md | weight-space fusion and merge methods | 00AF4011D1AA1C092BDA79C92CB08FCEC5F2375A0573CFAB22964113AA26FD9A | | AI's Cosmic Legacy and Survival.md | long-horizon speculative source, routed as metaphor only | 1CA83C0A56258E2003C788188334760A2D60E708396AEDF02F181926BCFC0485 | | AI's Perfect Evolutionary Being.md | evolutionary evaluation and social dynamics | D513358C57DC051A37F4143F5BA6BFA4FFD0D211162BAE79D94A3C60B1BEC31A | | Designing the Perfect Evolutionary AI System.md | evolutionary system goals and metrics | 9E128AFFD9B4820DB3D00F6341C1009E213E1942A9246CC20F0F15A723101090 | | Designing the Perfect Evolutionary AI.md | evolutionary AI architecture and experiments | 99B36CD92B99D7B1E52A412200FA3E2BEA61BEC351AC4A548F92EA16F366DF04 | | Evolution, Legacy, and Societal Evaluation.md | legacy, status, and human evaluation metaphors | 3A89B96DE48D6BB349868BB80441544E60E5D3633B831D242ED0FE181D10759A | | Evolutionary and Psychological Motivations.md | motivation and persistence metaphors | F7ABC73E307042E68819A57C0C45A0DEC8A28998FC0685A203B82BF11D014F30 | | Human drive – the intrinsic motivation to survive.md | human drive and thriving as product-language input | 7DC69C173147A3AC77E9B0574B7E522D0E9474D6892CD176EA4803F1B0968D3E | | lightweight multi-model LLM system in Rust.md | Rust multi-model patterns and on-device packaging | 0A098D4C95ADC2778F65A2AD53245645C3761304B8C51366AF744AD774C1B60A | | Model merging refers to combining multiple trained neural.md | model merging taxonomy | 1E47985328FD767905C0B8A81BFAD812813FDD671843778DD3EC81FC5D590358 | | Mutualist Persistence.md | mutualist public positioning and user agency | 994958596FF14D98C3AB9EA7FEFB5B22653689E4F76AEB0E473E90D6EDC7E22B | | Perfect Evolutionary AI.md | evolutionary metrics and candidate evaluation | A5100FF2A285103814FCED49934FADADA842B9AFBB704FC45547BDE8A0364171 | | powerful AI systems will tend to develop instrumental drives.md | speculative agency source, routed away from product voice | 81277A7101F3716FD470C3569B4F0A6F3611F7210454F9F8E0C9DB5CC4D86EC4 | | Rust Tiny LLM Model Breeding Pipeline.md | Rust-native breeding pipeline and lineage | 71AE9B36F84EACC85545F1143C0576B1501A1CA98988645D5A3DCF6874E80A8F | | Survival_ Drive, Strive, and Thrive.md | thriving, meaning, and motivation metaphors | E45E0F1D08B11939AF4EAE8D1C07BABF15B692F33B2E83891360D27E4BD73107 | | Teleodynamic Evolution of AI Ecosystems.md | teleodynamic model ecology and interchangeability | FD28C1844C1F6B04FA6773EDF28F77E2C3B7D347C01524D0A15A3A6A2AC3CECB | | The 4Fs framework—Fast, Flexible, Frugal, Federated.md | 4Fs model-system lens | BAAACDFDDF387EEC003F7856018FD5FA5651FD62A6C416E30FB233E979DB5ADA | | The rise of on-device, tiny language models part 2.md | client-side multi-model strategies | 8C29B3464D077F898E57834E38E31F55ECD4B48002E76EB4B3487F81D24DE55A | | The rise of on-device, tiny language models.md | on-device tiny LLMs and breeding algorithms | BA9444DF20FD357747BF320B125613E657B3124A2436CA5E82ECC33F317E1CCC | | The terms 4Fs and code beading model breeding.md | duplicate 4Fs, code beading, model breeding definitions | C9B395CF265EA6D4BA17BD7087A72AC6B18C5FA7896E03E443ABE6D1E3A83545 | | Tiny-LLM Adapters and LoRA.md | adapters, LoRA, compatibility, promotion | 7ECA22D6E00B6BBF0AE5A5CF99C0CC2BECAE3AEC6461D4DCA028C36FFF23889A | ## Duplicate Content Notes - `4Fs and code beadingmodel breeding.md` and `The terms 4Fs and code beading model breeding.md` have identical SHA256 hashes. Treat them as one 4Fs/code-beading/model-breeding source with two filenames. ## Processing Judgment The reports contain direct implementation suggestions that exceed the current TinyRustLM scope, including third-party Rust ML frameworks, external model hubs, dynamic downloads, and broader orchestration. Preserve those as reference context only. Current authority remains the TinyRustLM source tree, local `.uai` hot memory, generated `.slm` artifacts, manifests, and test output. This batch adds a future model-breeding path around compatible base families, tensor-schema matching, tokenizer hashes, parent checksums, candidate manifests, offline merge operators, and evaluation sidecars. ## Next Agent Routing - For model breeding concepts, read `model-breeding-ecology-memory-2026-06-26.md`. - For research references, read `../research/model-breeding-reference-ideas-2026-06-26.md`. - For exact original report wording, read `raw/gguf-mirust/report-intake-2026-06-26/` and verify SHA256 hashes against this index. - For current implementation claims, read `workspace.uai`, `.uai/test-plan.uai`, `tinyrustlm/README.md`, and source tests. ================================================================================ END FILE: wiki/gguf-mirust/reports/report-intake-index-2026-06-26.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/report-intake-index-2026-06-28.md BYTES: 3071 SHA256: 032CEED373BEDF5D231CF731DB1D9A607DE4EB33E13681846A11D5AE4D9CE2CA ================================================================================ --- title: Report Intake Index 2026-06-28 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/report-intake-index-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T21:20:00Z --- # Report Intake Index 2026-06-28 This record routes the 4 active Improvement research files processed into GGUF.MiRust.com memory on 2026-06-28. The batch adds practical ModelBreeder guidance and zero-dependency Rust browser-runtime pressure. It is research memory and future architecture input; implementation authority remains the source tree, typed manifests, receipts, browser smokes, and local tests. ## Durable Synthesis Records - [ModelBreeder and Zero-Dependency Reference Ideas](../research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md) ## Source Inventory | Source report | Theme | SHA256 | | --- | --- | --- | | ModelBreeder site and theory emphasize controlled evolution.md | ModelBreeder copy, genome schema, fitness vectors, novelty, speciation, CLI loop ideas | 18FE9E16D435D53892C8963E14212B7A3BEDFEE84E9FCD0AC87CB7BA322DA1E9 | | ModelBreeder Theory vs. Source Files.md | Browser client-side model visualization, Rust inference contrast, broad breeder-paradigm context | 8A57EAE46580251F3AB45F4170E82E7D2AAE6209CD1CF1642A4011875FF6A157 | | theory emphasize controlled evolution of AI models.md | Duplicate ModelBreeder copy, genome schema, fitness vectors, novelty, speciation, CLI loop ideas | 18FE9E16D435D53892C8963E14212B7A3BEDFEE84E9FCD0AC87CB7BA322DA1E9 | | Zero-Dependency Rust LLM Improvements.md | Browser Wasm SIMD, K-quant pressure, adapters, tokenizer, deterministic sampler, KV cache, allocator, telemetry | AFB87761528AD1060130E7CAAC0D8CF3D1CA2CA84E893DBAF737BFED48181589 | ## Duplicate Content Notes - `ModelBreeder site and theory emphasize controlled evolution.md` and `theory emphasize controlled evolution of AI models.md` have identical SHA256 hashes. Treat them as one ModelBreeder guidance source with two filenames. ## Processing Judgment Use the ModelBreeder guidance as a route toward typed genome, fitness vector, novelty, population, parent-selection, and speciation evidence. Use the zero-dependency Rust guidance as future pressure for browser-bound inference work: SIMD feature probes, hierarchical quantization contracts, deterministic sampling, compact tokenizer records, page/radix KV-cache planning, adapter delta application, native diagnostics, and Wasm memory-budget proof. Keep third-party libraries and off-repo systems as references only. Local work should first become a compatibility field, receipt or manifest field, eval/provenance field, browser-smoke assertion, or wiki/.uai route. ## Next Agent Routing - For exact original report wording, read `raw/gguf-mirust/report-intake-2026-06-28/` and verify SHA256 hashes against this index. - For implementation guidance, read `../research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md`. - For current implementation claims, read `workspace.uai`, `.uai/test-plan.uai`, `tinyrustlm/README.md`, and source tests. ================================================================================ END FILE: wiki/gguf-mirust/reports/report-intake-index-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/runtime-adapter-apply-memory-2026-06-27.md BYTES: 3202 SHA256: D9221DB8D0951B0A93277C799FF4DBB32DF5FC3A4ACA12B5CC622A9359FE4B34 ================================================================================ --- title: Runtime Adapter Apply Memory 2026-06-27 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/runtime-adapter-apply-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T14:30:00Z --- # Runtime Adapter Apply Memory This durable note records the TinyRustLM browser-runtime adapter application slice, now extended from the first f32 path to checked f32/q8_0/q4_0 runtime apply. ## Boundary The runtime now accepts a compatible `ADP1` f32 adapter-delta package for an already loaded f32, q8_0, or q4_0 `.slm` model. The package is validated against the loaded model's tensor count, flags, logical parameter count, tensor layout checksum, tokenizer checksum, per-tensor name hash, rank, dimensions, element count, payload checksum, package checksum, and finite f32 delta values before any tensor mutation or compact re-quantization. This is a runtime assembly bead, not a new public model-quality claim. Offline `adapter-delta` and `fuse-adapter-delta` remain the provenance path for producing durable candidate artifacts. Runtime apply is a browser-local assembly path for compatible base models plus small typed delta packages. ## Implementation Shape - `tinyrustlm/runtime/src/adapter.rs` parses `ADP1`, mirrors the packer checksum contracts, and returns validated f32 payload ranges. - `tinyrustlm/runtime/src/model.rs` stores tokenizer and tensor-layout identity checksums during model load, validates all fused values before mutation, applies f32 deltas in place, and re-quantizes q8_0 rows or q4_0 blocks when a compatible compact model is loaded. - `tinyrustlm/runtime/src/generate.rs` exposes `Runtime::apply_adapter_delta`, clears prompt/KV/generation diagnostics after a successful apply, and keeps the loaded model plus sampling configuration. - `tinyrustlm/runtime/src/wasm_exports.rs` exposes `apply_adapter_delta(ptr, len)` through the raw WASM ABI. - `tinyrustlm/tools/wasm-abi-smoke.js` builds a zero-delta `ADP1` package for the tiny f32 fixture and calls the new export after the existing q8 ABI recovery path. - `tinyrustlm/tools/browser-smoke.js` proves the static tiny q8_0 and q4_0 sidecars preserve compact quantization diagnostics after Rust apply. ## Verification - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-runtime adapter` - `node --check tinyrustlm/tools/wasm-abi-smoke.js` - `cargo build -p tinyrustlm-runtime --release --target wasm32-unknown-unknown` - Copied `target/wasm32-unknown-unknown/release/tinyrustlm_runtime.wasm` to `tinyrustlm/runtime/tinyrustlm.wasm` - `node tinyrustlm/tools/wasm-abi-smoke.js` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8091/app/ 9240 tinyq8 adapter-sidecar` - `node tinyrustlm/tools/browser-smoke.js http://127.0.0.1:8091/app/ 9241 tinyq4 adapter-sidecar` ## Next Routes - Keep the static f32/q8_0/q4_0 sidecar smokes tied to Adapter Sidecar changes. - Use registry-carried adapter-family routing for admitted f32 generated bundles until compact adapter-family metadata has its own typed path. - Keep broader model-breeding operators offline unless their outputs pass normal `.slm`, manifest, runtime-smoke, eval, admission, ledger, and selector gates. ================================================================================ END FILE: wiki/gguf-mirust/reports/runtime-adapter-apply-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29.md BYTES: 3566 SHA256: B420A9343C6C48AAD2C33C8D63A2E0F09D28FBE1734BC9DB31D7DBA3AC03191C ================================================================================ # Selector Operator Receipt Binding Memory 2026-06-29 ## Summary TinyRustLM selector registries now preserve the full two-parent operator receipt family when a selector admission record carries `operator_receipt_status=receipt-bound`. This keeps candidate and promotion receipt identity visible after the admission-to-registry handoff. ## Implemented Boundary - `tinyrustlm/tools/slm_pack/src/selector.rs` copies receipt-bound admission fields into selector entries as `entry.N.operator_receipt_*`. - The copied fields include status, path, checksum, operator id, operator kind, candidate `.slm` checksum, and candidate artifact byte count. - Registry validation recomputes the expected entry from the admission text and rejects drift in any copied receipt field. - Multi-parent admissions now also emit the full receipt-bound field family, so generated sign-merge and soup entries can render the same browser Operator row as two-parent receipt-bound admissions. - `entry.N.mate_selection_checksum` now includes the copied operator receipt family when present. - `tinyrustlm/app/app.js` parses optional selector receipt metadata, validates candidate checksum and byte equality, stores it on the selected model, and renders a compact Model Provenance Operator row. - `tinyrustlm/app/index.html` adds the Operator row, and the Rust browser harness checks the new DOM id. ## Verification - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm\tools\slm_pack\Cargo.toml selector::tests::writes_and_validates_selector_registry_from_operator_receipt_bound_admission -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm\tools\slm_pack\Cargo.toml selector::tests::rejects_selector_registry_operator_receipt_field_drift -- --nocapture` - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm\tools\slm_pack\Cargo.toml selector::tests:: -- --nocapture` passed with 82 selector tests. - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm\tools\slm_pack\Cargo.toml` passed with 267 tests. - `C:\Users\AI\.cargo\bin\cargo.exe build --manifest-path tinyrustlm\tools\slm_pack\Cargo.toml` passed. - `node --check tinyrustlm\app\app.js` passed. - `node --check tinyrustlm\tools\browser-smoke.js` passed. - `C:\Users\AI\.cargo\bin\cargo.exe test --manifest-path tinyrustlm\tools\browser_harness\Cargo.toml -- --nocapture` passed with 6 tests. - `C:\Users\AI\.cargo\bin\cargo.exe run --manifest-path tinyrustlm\tools\browser_harness\Cargo.toml -- tinyrustlm` passed with 9 checks. - Receipt-bound q8 CLI smoke passed through compatibility, lineage, mutation, candidate manifest, promotion, manifest, runtime smoke, assistant-quality eval, admission, selector-registry, and validate-selector-registry under `C:\Users\AI\AppData\Local\Temp\tinyrustlm-selector-receipt-4acd025a5de0418dbc54c0ffe6c91350`. ## Test Coverage Notes No coverage tool is active in this no-third-party workspace. Focused selector tests cover the receipt-bound admission input, copied selector fields, candidate checksum equality, candidate byte equality, registry validation, and copied-field drift rejection against the 75% coverage target. ## Routing Load this report before changing `selector-registry`, `validate-selector-registry`, selector provenance fields, Model Provenance Operator rendering, mate-selection checksum inputs, or assumptions about receipt-bound admissions reaching browser selector entries. For generated multi-parent browser proof, also load `browser-multi-parent-operator-provenance-memory-2026-06-29.md`. ================================================================================ END FILE: wiki/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/sparse-adapter-package-memory-2026-06-27.md BYTES: 2891 SHA256: 618BE504A83212ABEF705E7D6037ED604091B291EAD9C8C7B34ED1DD6C64402B ================================================================================ --- title: Sparse Adapter Package Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/sparse-adapter-package-memory-2026-06-27/ status: planned_pending_publication reviewed_utc: 2026-06-27T13:52:09Z --- # Sparse Adapter Package Memory ## Summary TinyRustLM now has a first compact adapter package format, `ASP1`, for sparse f32 task-delta payloads. The format keeps the same compatibility-bound identity fields as raw `ADP1` adapter packages, but stores only selected delta positions as `(u64 value_index, f32 delta)` pairs. `tinyrustlm-slm-pack sparse-adapter-delta` writes the package plus a recomputable manifest, and `validate-sparse-adapter-delta` rebuilds the bytes and manifest from the compatibility-bound parents. ## Implementation Memory - `tinyrustlm/tools/slm_pack/src/adapter.rs` ranks nonzero target-minus-base deltas by absolute value, tensor index, and value index, keeps the requested parts-per-million subset, sorts each tensor payload by value index, and writes `ASP1` tensor payloads. - Sparse adapter manifests record artifact kind, dtype, density, nonzero retention, unchanged and pruned counts, mask metadata, mask checksum, parent checksums, tokenizer checksum, tensor layout checksum, and adapter checksum. - `tinyrustlm/runtime/src/adapter.rs` parses both raw `ADP1` and sparse `ASP1`, validates identity fields, package checksum, payload checksums, sorted sparse indices, finite deltas, and tensor directory shape. - `tinyrustlm/runtime/src/model.rs` applies raw or sparse adapter payloads to loaded f32, q8_0, or q4_0 tensors. Compact q8_0 and q4_0 tensors are reconstructed per row or block, updated by selected sparse entries, then re-quantized back into compact storage. - Browser selector routes now include generated sparse `ASP1` members when `browser-multi-parent-bundle` stages adapter families, while checked tiny fallback routes remain `ADP1`. ## Validation Memory The implementation slice adds packer tests for sparse f32 and q8 adapter artifacts and runtime tests proving sparse adapter application for f32, q8_0, and q4_0 loaded tensors. Current verification: - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-runtime applies_sparse_adapter_delta` with 3 tests - `cargo test -p tinyrustlm-slm-pack adapter::tests::writes_and_validates_sparse` with 2 tests - `cargo test -p tinyrustlm-runtime` with 75 tests - `cargo test -p tinyrustlm-slm-pack adapter::` with 11 tests - `cargo test -p tinyrustlm-slm-pack` with 150 tests - `cargo test --workspace` with 236 tests ## Routing Notes Use this report before changing `ASP1` package parsing, sparse adapter manifest fields, `sparse-adapter-delta`, `validate-sparse-adapter-delta`, or runtime sparse adapter apply. Pair it with `browser-sparse-adapter-route-memory-2026-06-27.md` when generated browser adapter-family routing or served `.asp1` artifacts are in scope. ================================================================================ END FILE: wiki/gguf-mirust/reports/sparse-adapter-package-memory-2026-06-27.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25.md BYTES: 3561 SHA256: 2F5C442FF34005873F2E2515827CB336A6C11B5ECBCAFD99BDECBD001F278EF7 ================================================================================ --- title: Teleodynamic Resource Bounded Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25/ status: planned_pending_publication reviewed_utc: 2026-06-25T00:00:00Z --- # Teleodynamic Resource Bounded Memory ## Source Reports - `Rust In-Browser Teleodynamic AI Plan.md` - `Rust WebAssembly Teleodynamic AI Architecture.md` - `Teleodynamic AI in the Browser.md` - `Teleodynamic AI refers to resource-bounded.md` - `Teleodynamic Tiny Language Model Architecture.md` - `Teleodynamics is a theoretical framework .md` - `Modular AI in Browser.md` ## Durable Reading The teleodynamic reports are speculative and philosophical, but they carry one practical idea that fits TinyRustLM: intelligence in the browser should be resource-aware, self-limiting, and honest about its constraints. For this project, teleodynamic language should be translated into engineering terms: - Resource pressure means context length, model file size, scratch arena use, KV cache length, latency, and UI recoverability. - Self-organization means the runtime can expose enough state for a user or future controller to choose safer next steps. - Constraint maintenance means preserving local-only inference, zero-dependency runtime behavior, and explicit failure states even as features grow. - No-op can be valuable. A local model should sometimes stop, ask for a smaller prompt, or refuse a mode rather than blow past context or memory limits. ## Useful Translations | Teleodynamic phrase | TinyRustLM engineering meaning | | --- | --- | | Resource-bounded agency | Generation bounded by context, memory, max tokens, and local CPU latency | | Viability | Runtime remains recoverable after bad input, missing files, rejected models, and resets | | Inner/outer loops | Inner token generation now; future outer loop could choose model, quantization, or prompt strategy | | Constraint closure | The app keeps inference local and model files auditable | | Phase transition | State changes like Booting, Loading runtime, Loading model, Ready, Model rejected, Model load failed | ## Design Pressure The reports encourage a UI and runtime that make constraints legible: - Show model mode and quantization instead of hiding them. - Show context overflow as a meaningful state, not a crash. - Keep reset and model reload paths tested. - Let missing or malformed models fail in place and recover through model selection. - Treat benchmark data as user-facing truth, not internal decoration. ## Risks - The theory can become vague ornament. Keep it grounded in measurable runtime state. - Resource-bounded claims can excuse weak output. Keep quality limitations explicit. - Multi-agent and swarm ideas can distract from the required single-runtime proof. - Browser persistence and dynamic modules can become hidden trust expansions if added too early. ## Thought Questions - What would it mean for a browser SLM to conserve user attention, not just CPU cycles? - Should the runtime expose a "confidence to continue" signal based on context pressure and model type? - Could a tiny model become more useful by knowing when to route, pause, or ask than by generating more tokens? - How should local-only AI communicate its limits without feeling broken? ## Current Boundary Use this record as conceptual design pressure for diagnostics, resource budgets, and graceful degradation. Do not treat teleodynamic theory as permission to add frameworks, remote orchestration, dynamic downloads, or untested adaptive behavior. ================================================================================ END FILE: wiki/gguf-mirust/reports/teleodynamic-resource-bounded-memory-2026-06-25.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25.md BYTES: 4014 SHA256: 6DD5D2BD049DB4C2D7054FB24F6EC14ED6AF90B2484ACD522181E64C64F3C36E ================================================================================ --- title: TinyLM Modular Architecture Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25/ status: planned_pending_publication reviewed_utc: 2026-06-25T00:00:00Z --- # TinyLM Modular Architecture Memory ## Source Reports - `Modular AI in Browser.md` - `Modular Tiny Language Models Architecture.md` - `Multiple Tiny Language Models Architectures and Trends.md` - `Rust Browser Tiny LLM Architecture.md` - `Tiny Language Models Architecture.md` - `Teleodynamic AI is an approach where a system’s structure and parameters co-evolve.md` - `Teleodynamic AI is an approach.md` ## Durable Reading The modular tiny-model reports are useful because they widen the horizon beyond one small model. They describe skill modules, routing, adapters, tiny model ensembles, cascades, mixture-of-agents patterns, speculative decoding, prefix/cache reuse, and browser-local composition. For TinyRustLM, these are future architecture ideas, not current deliverables. The immediate product still needs one model path to be boringly correct: - Byte tokenizer now, custom BPE later. - TinyLM-16M-shaped f32/q8/q4 files now. - One local `.slm` loader and validator now. - Greedy deterministic generation now. - Sampling, trained-quality conversion, multi-model routing, and adapters later. ## Concepts Worth Keeping - Routing is a product primitive, not just an inference trick. A future TinyRustLM could route between q8, q4, tiny fixtures, task-specific SLMs, or adapters based on latency, memory, confidence, and user intent. - A model ABI matters before a model marketplace. The `.slm` header, tensor directory, tokenizer metadata, quantization fields, and checksum are the seed of that ABI. - Small models are operational units. Their usefulness depends on load cost, context fit, specialized competence, and recoverable failure behavior. - Composition should not hide provenance. If a response used base model plus adapter, or local small model plus fallback, the UI should be able to say so. - Multi-model systems need tests for routing mistakes, stale caches, incompatible tokenizers, and quality drift, not just speed. ## Design Tensions - Generality versus auditability: every generic routing mechanism makes it harder to prove the current local runtime. - Skill composition versus privacy: dynamic modules can preserve locality, but only if acquisition, signatures, permissions, and provenance are explicit. - Speed versus truthfulness: speculative decoding and cascades are attractive, but the UI must not make weak local models feel more capable than they are. - Rich tokenizers versus format simplicity: custom BPE is needed for quality, but byte-level fallback is still the most testable foundation. ## Future Architecture Sketch Future modular work should proceed in layers: 1. Stabilize `.slm` v1 for one TinyLM-16M path. 2. Add tokenizer section expansion for custom BPE while preserving byte fallback. 3. Add model capability metadata: context length, quantization, intended task, provenance, checksum, and compatibility. 4. Add a local router that can choose among installed local `.slm` files without remote calls. 5. Add adapter or skill package concepts only after the base ABI can reject incompatible files safely. ## Thought Questions - Should a tiny model ecosystem optimize first for many specialized weak models or one stronger local generalist? - What evidence should a router need before it switches models automatically? - How can model provenance be visible without making the UI feel like a debug console? - Can a tiny local runtime degrade gracefully by asking better questions instead of pretending to know more? ## Current Boundary Use this record for future modular and multi-model thinking. Do not implement adapters, LoRA, task arithmetic, speculative decoding, marketplace behavior, or multi-agent orchestration until the active TinyLM-16M runtime path is correct, tested, benchmarked, and explicitly expanded. ================================================================================ END FILE: wiki/gguf-mirust/reports/tinylm-modular-architecture-memory-2026-06-25.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/trained-adapter-source-alr1-memory-2026-06-28.md BYTES: 2793 SHA256: B4DAC0D2681665AAAD5E9B92839428C9D6064B05D2D43FB6D7DE80B98C1AEDDB ================================================================================ --- title: Trained Adapter Source ALR1 Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/trained-adapter-source-alr1-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T10:56:00Z --- # Trained Adapter Source ALR1 Memory TinyRustLM can now convert a reviewed trained low-rank adapter source bundle into a runtime `ALR1` package. This turns `adapter-source.manifest` plus checked raw f32 factor files into the same typed adapter format already consumed by the Rust runtime and browser adapter-family routes. ## Implementation - `tinyrustlm/tools/slm_pack/src/adapter.rs` now exposes a source-backed ALR1 pack helper that writes the existing ALR1 header, tensor directory, package checksum, payload checksums, and component-major A/B factor payloads. - `tinyrustlm/tools/slm_pack/src/trained_adapter_source.rs` now has `convert-adapter-source` and `validate-converted-adapter-source`. - Conversion validates the adapter source bundle, validates the base `.slm`, checks model shape, tied-output contract, byte tokenizer, target tensor hashes, target ranks, and target dimensions, then emits a sparse-by-directory ALR1 package with payloads only for source target tensors. - The ALR1 manifest binds source manifest checksum, source id/license/dataset/training summary, base model checksum, tensor layout checksum, tokenizer checksum, base quantization, ALR1 checksum, active target count, component count, factor parameter count, factor density, delta L1, per-target factor metadata, runtime apply status, and next route. - Validation recomputes the ALR1 bytes and manifest from the source directory plus base model and rejects artifact or manifest drift. ## Verification - `cargo fmt --all` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-slm-pack trained_adapter_source` with 10 tests - `cargo test -p tinyrustlm-slm-pack` with 185 tests - `cargo build -p tinyrustlm-slm-pack` - CLI round-trip: `adapter-source-template`, `convert-adapter-source`, and `validate-converted-adapter-source` against `models/tiny-test-model.slm` - `cargo test --workspace` with browser harness 6, local server 5, runtime 80, packer 185, and runtime doc-tests ## Evidence Notes The CLI round-trip produced a 1,088-byte `source.alr1` artifact and a 2,825-byte recomputable manifest from a tiny source bundle. Unit coverage converts f32 and q8_0 bases, rejects tied-output base contract mismatch, rejects ALR1 artifact checksum drift, and keeps the earlier source checksum/path/finiteness checks. ## Routing Use this report when changing `convert-adapter-source`, `validate-converted-adapter-source`, source-factor to ALR1 packaging, source-backed ALR1 manifests, or Model Breeding adapter-family work that starts from reviewed trained low-rank factor bundles. ================================================================================ END FILE: wiki/gguf-mirust/reports/trained-adapter-source-alr1-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/trained-adapter-source-memory-2026-06-28.md BYTES: 2492 SHA256: 6BFB7B990D93BADA6D32763802C3AA6129072FFED647E7678A1475EB739A74EF ================================================================================ --- title: Trained Adapter Source Memory source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/trained-adapter-source-memory-2026-06-28/ status: reviewed_current reviewed_utc: 2026-06-28T10:56:00Z --- # Trained Adapter Source Memory TinyRustLM has a reviewed source-intake lane for trained low-rank adapter modules. The packer can write a deterministic `adapter-source.manifest` plus raw f32 factor files under `factors/`, then validate the same bundle before source-backed runtime `ALR1` packaging. ## Implementation - `tinyrustlm/tools/slm_pack/src/trained_adapter_source.rs` adds `adapter-source-template` and `validate-adapter-source`. - The source manifest binds `model_shape`, `base_tied_output`, byte tokenizer scope, target tensor names and hashes, factor rank, factor file paths, byte counts, checksums, factor parameter counts, and reconstructed delta L1 fields. - Validation accepts tiny and TinyLM-16M shapes with tied-output variants, requires safe relative factor paths under `factors/`, checks finite bounded f32 factors, and recomputes factor counts plus delta L1. - `tinyrustlm/tools/slm_pack/src/main.rs` exposes the two commands through the no-crate packer CLI. - `tinyrustlm/README.md`, `tinyrustlm/docs/testing.md`, and the Model Breeding reference ideas page route this source lane as the first trained LoRA-style adapter intake step. - Source-backed ALR1 conversion now has its own bridge report at `wiki/gguf-mirust/reports/trained-adapter-source-alr1-memory-2026-06-28.md`. ## Verification - `cargo fmt --all` - `cargo fmt --all -- --check` - `cargo test -p tinyrustlm-slm-pack trained_adapter_source` - `cargo test -p tinyrustlm-slm-pack` with 181 tests - `cargo run -p tinyrustlm-slm-pack -- adapter-source-template tiny-fixture` - `cargo run -p tinyrustlm-slm-pack -- validate-adapter-source ` ## Evidence Notes The CLI round-trip wrote a tiny low-rank adapter source bundle and validated two target tensors, 192 target parameters, 40 factor parameters, and `delta_l1_microunits=522`. Unit coverage validates the standard and tied-output templates, then rejects factor checksum drift, factor path escape, and non-finite factor payloads after checksum refresh. ## Routing Use this report when changing trained low-rank adapter source manifests, factor-file validation, or trained LoRA-style source intake. Use the source ALR1 bridge report when changing conversion from reviewed factor bundles into runtime `ALR1` packages. ================================================================================ END FILE: wiki/gguf-mirust/reports/trained-adapter-source-memory-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/two-parent-operator-browser-provenance-memory-2026-06-29.md BYTES: 4229 SHA256: 53D1C965236A14267AD9AAAAB68DB2A77262BB4D4C085F0CFEF84A39CDEDC3CE ================================================================================ --- title: Two Parent Operator Browser Provenance Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/two-parent-operator-browser-provenance-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T17:41:02Z --- # Two Parent Operator Browser Provenance Memory TinyRustLM now has compact browser selector proof for the original two-parent direct-parameter operator lane: blend, task-delta, and sparse task-delta. ## What Changed - `tinyrustlm/tools/browser-smoke.js` adds `blend-operator-registry`, `delta-operator-registry`, and `sparse-delta-operator-registry` compact selector fixtures. - The fixtures render browser Model Provenance Operator rows for `direct-parameter-weighted-average`, `direct-parameter-task-delta`, and `sparse-direct-parameter-task-delta`. - `blend-operator-receipt-drift`, `delta-operator-receipt-drift`, and `sparse-delta-operator-receipt-drift` prove byte-echo drift returns to the static q8 route with operator provenance unavailable. - `tinyrustlm/README.md` routes the six browser smoke commands beside the other compact operator provenance examples. ## Browser Fixture Routes - `tinylm16-blend-q8` loads the q8 TinyLM artifact route and carries operator checksum `0x00000000000000b4`. - `tinylm16-delta-q8` loads the q8 TinyLM artifact route and carries operator checksum `0x00000000000000b5`. - `tinylm16-sparse-delta-q8` loads the q8 TinyLM artifact route and carries operator checksum `0x00000000000000b6`. - All three fixtures keep the model route under `../models/tinylm16-q8.slm`, preserve q8_0 quantization, and use the shared selector operator receipt validation path. ## Verification - `node --check tinyrustlm\tools\browser-smoke.js` passed. - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8129/app/ 9430 tinylm16-blend-q8 blend-operator-registry` passed, rendering `receipt-bound / direct-parameter-weighted-average / 0x00000000000000b4`. - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8129/app/ 9431 tinylm16-delta-q8 delta-operator-registry` passed, rendering `receipt-bound / direct-parameter-task-delta / 0x00000000000000b5`. - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8129/app/ 9432 tinylm16-sparse-delta-q8 sparse-delta-operator-registry` passed, rendering `receipt-bound / sparse-direct-parameter-task-delta / 0x00000000000000b6`. - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8129/app/ 9433 tinylm16q8 blend-operator-receipt-drift` passed and returned to static q8 with operator provenance unavailable. - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8129/app/ 9434 tinylm16q8 delta-operator-receipt-drift` passed and returned to static q8 with operator provenance unavailable. - `node tinyrustlm\tools\browser-smoke.js http://127.0.0.1:8129/app/ 9435 tinylm16q8 sparse-delta-operator-receipt-drift` passed and returned to static q8 with operator provenance unavailable. - Regression smokes for the shared compact fixture passed on `http://127.0.0.1:8129/app/`: federated `multi-parent-registry`, prune `prune-operator-registry`, crossover `crossover-operator-registry`, and mutation `mutation-operator-registry`. No coverage tool is active in this no-third-party workspace; evidence for the 75% target is the focused browser provenance and drift slice plus the existing Rust receipt tests for the operator implementations. ## Test Coverage Notes - Browser `modelKey` parameters are covered by positive registry smokes for all three compact candidates. - Browser `smokeMode` parameters are covered by the three positive modes and the three byte-echo drift modes. - Operator kind routing is covered by exact Model Provenance row assertions for all three operator strings. - Candidate artifact byte equality is covered by the drift smokes that mutate the receipt byte echo and require fallback. - Shared compact-registry behavior is covered by federated, prune, crossover, and mutation regression smokes after the new modes were added. ## Routing Open this report before changing browser selector operator provenance for `blend-candidate`, `delta-candidate`, `sparse-delta-candidate`, compact registry fixtures, or receipt byte-echo fallback behavior. ================================================================================ END FILE: wiki/gguf-mirust/reports/two-parent-operator-browser-provenance-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/reports/weighted-soup-operator-memory-2026-06-29.md BYTES: 4301 SHA256: 52465109140EE8FD6846104E09496604814CB2FD959BECB586CFA1A9BD4052F7 ================================================================================ --- title: Weighted Soup Operator Memory 2026-06-29 source_site: GGUF.MiRust.com public_route: /gguf-mirust/reports/weighted-soup-operator-memory-2026-06-29/ status: planned_pending_publication reviewed_utc: 2026-06-29T15:45:00Z --- # Weighted Soup Operator Memory TinyRustLM now has an offline parent-pool weighted soup operator for model-breeding candidates. ## What Changed - `tinyrustlm/tools/slm_pack/src/soup.rs` adds `soup-candidate` and `validate-soup-candidate` support for validated parent-pool recipes. - The operator starts from the existing ledger, population review, parent-pool recipe, admission records, and ordered parent `.slm` files. - It uses every parent recipe `seed_weight_ppm` to compute a direct weighted average for each compatible tensor value. - It preserves the frontier parent's shape, tokenizer, flags, dtype/layout lane, and writes a normal checksum-bearing `.slm` candidate. - The receipt records recipe, relatedness, parent, merge-rule, weight-source, parent-weight checksum, weighted-value checksum, changed-from-frontier count, changed density, candidate artifact fields, and next gate. - Validation parses the receipt identity fields, then recomputes recipe validation, parent artifact checks, candidate bytes, and the full receipt before accepting the artifact. - `tinyrustlm/tools/slm_pack/src/main.rs` exposes the new CLI commands and usage line. - `tinyrustlm/models/README.md` now documents the soup write/validate command pair next to sign-merge. ## Receipt Fields - `tinyrustlm_soup_operator_version=1` - `operator_kind=seed-weighted-parent-pool-soup` - `operator_status=candidate-written` - `recipe_kind=sign-aware-parent-pool-v1` - `parent_pool_recipe_checksum` - `population_review_checksum` - `promotion_ledger_checksum` - `admission_set_checksum` - `frontier_candidate_id` - `frontier_candidate_slm_checksum` - `parent_contract_status` - `contract_model_shape` - `contract_quantization` - `contract_output_contract` - `contract_tokenizer_checksum` - `contract_tensor_layout_checksum` - `relatedness_metric` - `relatedness_scope` - `relatedness_pair_count` - `relatedness_all_pairs_status` - `relatedness_contract_checksum` - `parent.N.seed_weight_ppm` - `base_parent_index=0` - `soup_merge_rule=seed-weighted-direct-parameter-average` - `soup_weight_source=parent-pool-seed-weight-ppm` - `soup_weight_unit=parts-per-million` - `soup_total_parameter_count` - `soup_parent_weight_checksum` - `soup_weighted_value_checksum` - `soup_changed_from_frontier_count` - `soup_changed_from_frontier_density_ppm` - `candidate_parent_contract=matches-parent-pool-direct-parameter-contract` - `operator_output_status=slm-validated` - `required_next_gate=multi-parent-candidate-manifest-plus-runtime-smoke-plus-eval` ## Verification - `C:\Users\AI\.cargo\bin\cargo.exe fmt --all` - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack soup -- --nocapture` passed with 6 soup tests. - `C:\Users\AI\.cargo\bin\cargo.exe test -p tinyrustlm-slm-pack` passed with 286 tests. No coverage tool is active in this no-third-party workspace; evidence for the 75% target is the focused parameter and drift test slice, full packer suite, and path-level write/validate coverage. ## Test Coverage Notes - `ledger_text`, `review_text`, `recipe_text`, and `admission_texts` are covered by parent-pool recipe validation in every soup build/validate test. - `parent_bytes` and parent ordering are covered by valid multi-parent builds plus checksum drift rejection when parent order changes. - `candidate_bytes` and `candidate_path` are covered by exact recompute validation, candidate byte drift rejection, and path-level write/validate tests. - `receipt_text` is covered by receipt operator-kind drift rejection plus full receipt recomputation. - `parent_paths` and `admission_paths` are covered by `writes_and_validates_soup_candidate_paths`. - Multi-parent cardinality is covered by the single-parent recipe rejection. - Merge semantics are covered by asserting the generated candidate moves between frontier and higher-offset parent values. ## Routing Open this report before changing `soup.rs`, `soup-candidate`, `validate-soup-candidate`, parent-pool seed-weight handling, soup receipt fields, direct weighted-average math, or multi-parent operator routing. ================================================================================ END FILE: wiki/gguf-mirust/reports/weighted-soup-operator-memory-2026-06-29.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md BYTES: 4634 SHA256: 90CF6F38DAE201B934497B50113757DBD439436A65B22B98F1860B0F9767D2BE ================================================================================ --- title: ModelBreeder and Zero-Dependency Reference Ideas 2026-06-28 source_site: GGUF.MiRust.com public_route: /gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28/ status: planned_pending_publication reviewed_utc: 2026-06-28T21:20:00Z --- # ModelBreeder and Zero-Dependency Reference Ideas This record routes the 2026-06-28 Improvement research into practical GGUF.MiRust.com guidance without requiring future agents to bulk-load the original reports. ## ModelBreeder Guidance Lanes - Product voice lane: use fitness, scope notes, breeding invariants, evaluation checkpoints, governance principles, local agency, and proof-of-use language for public copy. - Genome lane: represent a candidate with base model id, adapter stack, random seed, source provenance, model artifact path, and mutation or recombination log. - Fitness vector lane: route accuracy, loss, latency, memory, energy, novelty, cost, and composite score into typed eval sidecars before any promotion claim. - Novelty lane: record a hash sketch, behavior descriptor, or eval-output distance so candidate selection can preserve useful variety instead of only the top scalar score. - Population lane: keep parent selection, seed weights, objective vectors, generation id, champion status, and archive status as manifest or receipt data. - Speciation-fit lane: preserve f32/q8_0/q4_0 families, tokenizer families, tensor-layout fingerprints, adapter families, and browser resource envelopes as local fit boundaries. - Evolution-loop lane: implement breeding loops as bounded offline tooling first; browser runtime should consume generated, validated artifacts rather than mutate active model bytes. ## Zero-Dependency Browser Runtime Lanes - SIMD lane: future matvec work should route through explicit Wasm SIMD feature probes, scalar fallbacks, deterministic fixtures, and byte-counted benchmark records. - Hierarchical quantization lane: K-quant support, if added, needs typed super-block/sub-block metadata, direct fused dequant-matvec loops, and tests for irregular bit packing. - Adapter lane: keep ADP1, ASP1, and ALR1 as compact update formats with base-model checksum binding, factor/sparse/raw payload checksums, and f32/q8/q4 apply proofs. - Tokenizer lane: keep byte-tokenizer and future BPE tables embedded or checksum-routed so browser bundles remain self-contained and reproducible. - Sampler lane: keep stochastic decoding deterministic through seeded RNG state, bounded candidate arrays, and fixture outputs for top-k/top-p/temperature parameters. - KV-cache lane: treat paged cache, prefix sharing, and radix routing as future memory-budget features that need route receipts and page-count diagnostics before UI claims. - Speculative decoding lane: route draft/target or model-free speculative decoding as planner research until artifact format, rollback proof, and eval fixtures exist. - Multimodal lane: QOI image and Cooley-Tukey FFT ideas are future no-third-party intake routes; each needs a typed payload format, fixture corpus, and checksum-backed diagnostics. - Allocator lane: any custom Wasm allocator needs a bounded design note, page-growth counters, scratch-arena reset proof, and browser smoke evidence. - Telemetry lane: diagnostics should stay native and compact: counters, checksums, token timing, scratch usage, adapter apply counts, and assembly state hashes. ## Research-To-Implementation Map - ModelBreeder schemas become `Genome` and `FitnessVector` style manifest/eval fields. - Multi-parent guidance maps to the current parent-pool recipe, sign-merge, multi-parent candidate manifest, promotion template, admission record, and selector registry lanes. - Novelty, population, mate-selection, phenotype-evidence, heritable-artifact, and speciation guidance maps to selector registry fields, Model Provenance rows, objective-vector metadata, runtime/eval/artifact evidence checksums, and browser-smoke assertions. - Browser runtime guidance maps to future source work only when it can be proven through deterministic fixtures, browser smokes, or receipt validation. - Public wording guidance routes through `.uai/taboo.uai` before website copy changes. ## Raw Evidence Exact originals are preserved under `raw/gguf-mirust/report-intake-2026-06-28/`. The intake index is `wiki/gguf-mirust/reports/report-intake-index-2026-06-28.md`. ## Routing Rule Open this page before changing ModelBreeder-derived schema names, fitness/novelty/population metadata, zero-dependency browser runtime plans, Wasm SIMD/quantization/tokenizer/sampler/KV-cache guidance, or public copy related to model breeding. ================================================================================ END FILE: wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md BYTES: 11353 SHA256: 8786266ADB39C382B607A431E40F2876F9A8ABD860EE025F22FF37B2F6D5E8BE ================================================================================ --- title: Model Breeding Reference Ideas 2026-06-26 source_site: GGUF.MiRust.com public_route: /gguf-mirust/research/model-breeding-reference-ideas-2026-06-26/ status: planned_pending_publication reviewed_utc: 2026-06-28T11:25:34Z --- # Model Breeding Reference Ideas This record routes primary research, project concepts, and setup references that are useful for turning the 2026-06-26 report batch into future TinyRustLM work. The 2026-06-28 refresh treats Model Breeding as a memory strategy too: concepts live as route maps, typed receipt ideas, proof prompts, and future evidence lanes before they become code. ## Primary Research Routes | Reference | Project use | | --- | --- | | [Model soups: averaging weights of multiple fine-tuned models improves accuracy without increasing inference time](https://arxiv.org/abs/2203.05482) | Weight averaging can be a future offline operator when parent models share one low-loss basin and exact schema compatibility. | | [Git Re-Basin: Merging Models modulo Permutation Symmetries](https://arxiv.org/abs/2209.04836) | Alignment before merge matters; future compatibility checks should treat tensor schema and hidden-unit alignment as explicit metadata. | | [Editing Models with Task Arithmetic](https://arxiv.org/abs/2212.04089) | Task vectors suggest a candidate-delta format where base weights and deltas are tracked separately with parent hashes. | | [TIES-Merging: Resolving Interference When Merging Models](https://arxiv.org/abs/2306.01708) | Sign agreement maps to implemented sign-merge receipts fed by parent-pool recipes with ranked shared-contract parent sets and relatedness metadata. | | [Language Models are Super Mario: Absorbing Abilities from Homologous Models as a Free Lunch](https://arxiv.org/abs/2311.03099) | DARE-style sparse deltas map to the lineage-bound sparse task-delta candidate lane, with rescale variants left as future operator metadata. | | [Model Breadcrumbs: Scaling Multi-Task Model Merging with Sparse Masks](https://arxiv.org/abs/2312.06795) | Sparse masking now has a first receipt-level form through `sparse-delta-candidate` density, nonzero-delta retention, and implicit top-k mask checksum fields. | | [LoRA: Low-Rank Adaptation of Large Language Models](https://arxiv.org/abs/2106.09685) | LoRA remains the broader low-rank adapter reference lane; current implementation covers trained low-rank adapter source validation, source-backed factor-to-ALR1 packaging, ADP1 raw packages, ASP1 sparse packages, ALR1 low-rank factor packages, adapter-fuse for raw ADP1, and compatible f32/q8/q4 runtime apply. | | [Evolutionary Optimization of Model Merging Recipes](https://arxiv.org/abs/2403.13187) | Evolutionary merge recipes map to offline recipe search, parent-pool selection, operator receipts, eval sidecars, and promotion ledgers. | | [Exploring Model Kinship for Merging Large Language Models](https://arxiv.org/abs/2410.12613) | Parent relatedness now has a first TinyRustLM form: parent-pool recipes write shared-family checksums, sign-merge receipts echo them, and multi-parent candidate manifests carry them. | | [Mergenetic: a Simple Evolutionary Model Merging Library](https://arxiv.org/abs/2505.11427) | Adaptive search can remain a planner-layer idea: propose merge weights and masks, then let existing compatibility, receipt, and eval gates decide admission. | | [Multi-objective Evolutionary Merging Enables Efficient Reasoning Models](https://arxiv.org/abs/2604.06465) | Multi-objective scoring now has a first TinyRustLM form: population reviews write weighted quality/frugality/quantization objective-vector metadata and per-entry objective checksums. | | [Population Based Training of Neural Networks](https://arxiv.org/abs/1711.09846) | Population-style candidate evaluation now maps to `population-review` plus `parent-pool-recipe`: objective vectors, fitness scores, frontier selection, parent routing, seed weights, resource budgets, and staged promotion. | | [Communication-Efficient Learning of Deep Networks from Decentralized Data](https://arxiv.org/abs/1602.05629) | FedAvg is a reference lane for federated or on-device parent updates; in TinyRustLM it maps to offline recipe metadata and evidence records. | | [Evolution Strategies as a Scalable Alternative to Reinforcement Learning](https://arxiv.org/abs/1703.03864) | Evolution-style search maps to population-level candidate proposal, fitness fields, and resource-budget records before promotion. | | [Overcoming catastrophic forgetting in neural networks](https://arxiv.org/abs/1612.00796) | Retention metrics can inspire eval sidecar cases when a candidate absorbs a new task without dropping old fixture behavior. | | [PackNet: Adding Multiple Tasks to a Single Network by Iterative Pruning](https://arxiv.org/abs/1711.05769) | Task-specific pruning suggests future mask or slot metadata for keeping small skills separable inside compact artifacts. | | [The Lottery Ticket Hypothesis: Finding Sparse, Trainable Neural Networks](https://arxiv.org/abs/1803.03635) | Sparse subnetworks inform pruning, mask, and compact-candidate experiments that still pass ordinary `.slm` validation. | | [Parameter-Efficient Transfer Learning for NLP](https://arxiv.org/abs/1902.00751) | Adapter modules give a broader adapter-family lane beyond LoRA for future package manifests and fuse receipts. | | [QLoRA: Efficient Finetuning of Quantized LLMs](https://arxiv.org/abs/2305.14314) | Quantized adapter training remains a future comparison lane; current q8/q4 ADP1, ASP1, and ALR1 runtime apply uses f32 deltas/factors plus compact re-quantization. | ## Diverse Reference Lanes - Architecture-preserving merge lane: use model soups, task arithmetic, TIES, DARE, Re-Basin, and kinship as references for compatible parent sets, tensor-layout fingerprints, relatedness checksums, and operator receipts. - Sparse-lineage lane: use Model Breadcrumbs, PackNet, lottery tickets, and retention metrics as references for mask checksums, selected-parameter counts, density, nonzero-delta retention, and retention-aware eval sidecars. - Adapter-ecology lane: use LoRA, adapter modules, QLoRA, trained low-rank adapter source manifests, source-backed ALR1 manifests, source-backed browser ALR1 routes, ADP1, ASP1, ALR1, adapter-family receipts, fuse receipts, and runtime f32/q8/q4 apply as a compact update route separate from full `.slm` candidates. - Population-search lane: use population-based training, evolution strategies, Mergenetic-style adaptive search, and multi-objective evolutionary merging as planner inputs for population reviews, objective vectors, frontiers, seed weights, and promotion ledgers. - Federated/local-update lane: use FedAvg and on-device parent updates as references for future local evidence records, not browser runtime behavior. - Browser-constrained assembly lane: use runtime WASM manifests, selector budgets, text sidecar envelopes, module-plan receipts, assembly receipts, and adapter-family receipts as the local proof graph for served candidates. - UAIX memory-strategy lane: use File Handoff plus LLM Wiki as the memory route so reports and research bodies remain durable, short-term memory tells agents what to open now, and long-term memory stays pointer-shaped with checksums. - Heritable-artifact lane: treat `.slm` files, manifests, adapter packages, module-plan receipts, assembly receipts, eval sidecars, and selector entries as the local genome-like record for a candidate. - Mate-selection lane: use compatibility reports, population reviews, parent-pool recipes, relatedness checksums, seed weights, and objective vectors to choose parent sets before any operator writes a candidate. - Phenotype-evidence lane: treat runtime-smoke sidecars, eval-case evidence checksums, Model Provenance rows, browser smokes, and promotion ledgers as the observable behavior record for a candidate. - Speciation-and-fit lane: keep f32/q8_0/q4_0, tokenizer families, tensor layouts, adapter families, and resource envelopes as explicit fit boundaries for local browser assembly. ## UAIX Setup Route - [UAIX AI Memory Package Wizard](https://uaix.org/en-us/tools/ai-memory-package-wizard/#setup-file-handoff) routes this project toward File Handoff plus LLM Wiki: active intake buckets, raw evidence preservation, durable wiki synthesis, hot `.uai` routing, and pointer-only long-term memory. - The setup-file-handoff route is applied as a cycle: active buckets are intake, raw/wiki files hold durable bodies, `.uai` files hold short routing and synthesis, and long-term memory keeps checksum pointers for current reports and research pages. ## Research-To-Implementation Map - Soups and task arithmetic become offline operators, not browser runtime features. - TIES and DARE become compatibility and merge recipe metadata; implemented slices are `sparse-delta-candidate` for largest absolute task deltas with mask metadata, `parent-pool-recipe` for ranked shared-contract parent sets, and `sign-merge-candidate` for seed-weighted sign consensus. - Model Breadcrumbs and kinship metrics now split: sparse-mask retention has a first receipt-level form, parent relatedness has first recipe/receipt/manifest fields, and richer retention-aware eval metadata remains a future typed evidence lane. - Evolutionary merge work becomes planner evidence only: search may propose parent sets, weights, masks, or operator chains, but `tinyrustlm-slm-pack` compatibility, receipt validation, eval, and promotion records stay authoritative. - LoRA becomes adapter-family research around the current trained adapter source and ADP1/ASP1/ALR1 lanes: validated low-rank factor source bundles can hold reviewed trained deltas, source-backed ALR1 conversion can package them against a compatible base `.slm`, generated browser bundles can serve those source-backed ALR1 packages as stack members, validated raw packages can produce normal `.slm` candidates, and compatible ADP1, ASP1, or ALR1 packages can apply to loaded f32/q8/q4 runtime models. - PBT becomes population-review plus parent-pool recipe logic: objective-vector metadata, parent selection, fitness scores, seed weights, budget caps, frontier routing, parent-pool routing, and promotion evidence. - FedAvg and evolution strategies become population-recipe references: they can shape future metadata for distributed parent updates, search budgets, and promotion ledgers. - EWC, PackNet, lottery tickets, adapters, and QLoRA become retention, pruning, mask, and compact-update reference lanes for future eval sidecars and adapter manifests. - UAIX File Handoff keeps dropped reports transient while raw evidence and durable synthesis carry long-memory authority. - Model Breeding concepts should first become one of four local evidence shapes: compatibility field, receipt/manifest field, eval/provenance field, or browser-smoke assertion. - Short-term memory should point to current report, research, dogfood, and pointer-ledger routes; long-term memory should carry checksum-bearing pointers to the durable bodies, including every current report page. ## Routing Rule Use this page for reference selection and concept routing. Use `model-breeding-ecology-memory-2026-06-26.md` for project synthesis. Use `.uai/short-term-memory.uai` for the current handoff state, current report routes, and pointer-ledger route. ================================================================================ END FILE: wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md ================================================================================ ================================================================================ BEGIN FILE: wiki/gguf-mirust/source-memory-guide.md BYTES: 36767 SHA256: 85DC5C82ECBEEF18E482BFAEE8D1C34B3F8E1585B9BBB1C89E785DA8904EAD9F ================================================================================ --- title: GGUF.MiRust.com Source Memory Guide source_site: GGUF.MiRust.com public_route: /gguf-mirust/source-memory-guide/ status: planned_pending_publication reviewed_utc: 2026-06-29T20:08:59Z --- # GGUF.MiRust.com Source Memory Guide Use this guide to route future agents to the correct memory layer. ## Active Project Memory Hot Project Handoff memory lives in `.uai/`. Start with `.uai/startup-packet.uai`, `.uai/workspace-guidance.uai`, `.uai/file-handoff.uai`, `.uai/long-term-memory.uai`, and `.uai/taboo.uai` when public site voice or product copy is in scope. ## Durable Project Memory Reviewed durable memory lives in `wiki/gguf-mirust/` and publishes under `https://aiwikis.org/gguf-mirust/` when deployed. Raw evidence manifests live under `raw/gguf-mirust/`. Report-derived long-term memory lives under `wiki/gguf-mirust/reports/`. Start with `reports/report-intake-index-2026-06-25.md` for the first processed batch, `reports/report-intake-index-2026-06-26.md` for model-breeding research, and `reports/report-intake-index-2026-06-28.md` for ModelBreeder plus zero-dependency browser-runtime research, then load only the thematic synthesis record needed for the task. UAIX File Handoff strategy is recorded in `docs/dogfood/uaix-file-handoff-memory-strategy-2026-06-26.md`. Current report pages are represented in `.uai/long-term-memory.uai`; `.uai/short-term-memory.uai` tells agents which report, research, dogfood, and pointer-ledger routes to open now. For browser-served model-breeding evidence, load `reports/assembly-receipt-memory-2026-06-27.md` when selector assembly receipt fields, generated bundle evidence staging, evidence-file fetches, or browser Assembly Evidence rendering are in scope. For browser proof of the original two-parent operators, load `reports/two-parent-operator-browser-provenance-memory-2026-06-29.md` when blend, task-delta, sparse task-delta, compact selector operator fixtures, Model Provenance Operator rendering, or receipt byte-echo fallback is in scope. For offline direct-parameter crossover, load `reports/crossover-operator-memory-2026-06-29.md` when `crossover-candidate`, `validate-crossover-candidate`, seed/keep selection, mask checksums, q8 crossover proof, browser Operator rendering, crossover byte-echo fallback, or downstream candidate handoff is in scope. For offline bounded mutation, load `reports/mutation-operator-memory-2026-06-29.md` when `mutation-candidate`, `validate-mutation-candidate`, seed/rate/magnitude parameters, reference scaling, selection and delta checksums, q8 mutation proof, browser Operator rendering, mutation byte-echo fallback, or downstream candidate handoff is in scope. For offline magnitude pruning, load `reports/prune-operator-memory-2026-06-29.md` when `prune-candidate`, `validate-prune-candidate`, keep/floor parameters, magnitude ranking, mask checksums, output-value checksums, q8 prune proof, selector receipt carry-forward, browser Operator rendering, prune byte-echo fallback, operator-kind drift rejection, or downstream candidate handoff is in scope. For offline DARE task-delta candidates, load `reports/dare-operator-memory-2026-06-29.md` when `dare-candidate`, `validate-dare-candidate`, signed task-delta weights, keep/drop rates, dropout seeds, seeded mask checksums, raw/rescaled delta checksums, q8 proof, or downstream candidate handoff is in scope. For DARE browser operator provenance, load `reports/dare-browser-operator-provenance-memory-2026-06-29.md` when DARE selector receipt fields, `dare-operator-registry`, `dare-operator-receipt-drift`, compact Model Provenance Operator rendering, or DARE byte fallback behavior is in scope. For browser converted-trained provenance, load `reports/browser-converted-trained-provenance-memory-2026-06-29.md` when `converted-trained-registry`, converted-trained q8 selector fixtures, converted-trained manifest request proof, browser Model Provenance source/admission/quality fields, or pending-eval provenance assertions are in scope. For browser converted-trained file routing, load `reports/browser-converted-trained-file-route-memory-2026-06-29.md` when `browser-converted-trained-bundle`, `converted-trained-registry-file`, generated converted-trained roots, real selector/model/manifest fetch proof, or converted-trained file-backed browser smoke is in scope. For browser converted-trained all routing, load `reports/browser-converted-trained-all-route-memory-2026-06-29.md` when `browser-converted-trained-bundle all`, q4-defaulted converted-trained f32/q8/q4 roots, all-quant selector defaults, or q4/q8/f32 file-backed browser smokes are in scope. For offline federated/local-update candidates, load `reports/federated-operator-memory-2026-06-29.md` when `federated-candidate`, `validate-federated-candidate`, base/local-update parent roles, `local_update_weight_ppm`, local-update counts, delta checksums, q8 proof, or downstream candidate handoff is in scope. For offline weighted soup candidates, load `reports/weighted-soup-operator-memory-2026-06-29.md` when `soup-candidate`, `validate-soup-candidate`, parent-pool `seed_weight_ppm`, weighted tensor averaging, parent order checksums, weighted-value checksums, changed-from-frontier density, or soup receipt routing is in scope. For multi-parent soup manifest handoff, load `reports/multi-parent-soup-manifest-memory-2026-06-29.md` when `multi-parent-candidate-manifest`, `validate-multi-parent-candidate`, soup receipt handoff, parent-pool operator-kind dispatch, `candidate_manifest_status=validated-parent-pool-operator-output`, sign or soup metric preservation, or downstream multi-parent promotion/admission/selector routing is in scope. For federated selector receipt routing, load `reports/federated-selector-receipt-route-memory-2026-06-29.md` when a `federated-local-update-average` receipt must be traced from candidate/promotion/admission evidence into `entry.N.operator_receipt_*` selector registry fields, browser Model Provenance Operator rendering, operator-kind drift rejection, or browser operator-receipt byte-count drift fallback. For candidate operator receipt binding, load `reports/candidate-operator-receipt-binding-memory-2026-06-29.md` when `candidate-manifest`, `validate-candidate`, optional `[input.operator]`, receipt checksum fields, operator identity, candidate bytes, or candidate checksum equality are in scope. For promotion operator receipt binding, load `reports/promotion-operator-receipt-binding-memory-2026-06-29.md` when `promotion-template`, `validate-promotion`, optional `[input.operator]`, receipt carry-forward, promotion receipt fields, missing receipt input, or receipt checksum drift are in scope. For admission operator receipt binding, load `reports/admission-operator-receipt-binding-memory-2026-06-29.md` when `admission-record`, `validate-admission`, optional `[input.operator]`, receipt carry-forward, admission receipt fields, missing receipt input, summary validation, or receipt checksum drift are in scope. For selector operator receipt binding, load `reports/selector-operator-receipt-binding-memory-2026-06-29.md` when `selector-registry`, `validate-selector-registry`, `entry.N.operator_receipt_*`, mate-selection checksums, Model Provenance Operator rendering, or receipt-bound admission-to-registry handoff is in scope. For browser multi-parent operator provenance, load `reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md` when multi-parent admissions, generated selector `entry.N.operator_receipt_*` fields, parent-pool soup/sign-merge Operator rows, generated combined-selector provenance assertions, `generated-selector-operator-receipt-drift`, or `generated-selector-operator-kind-drift` fallback-before-generated-route proof is in scope. For browser mixed operator selectors, load `reports/browser-mixed-operator-selector-memory-2026-06-29.md` when `browser-multi-parent-bundle all mixed`, sign-merge plus soup q4/q8/f32 selector roots, q4 default preservation, `combined-selector-operator-family`, `combined-selector-operator-family-cycle`, `combined-selector-operator-family-route-soak`, `combined-selector-operator-family-reload-soak`, release-before-reassembly, fresh page lifetimes, or cross-family self-assembly route accounting is in scope. For parent-pool evolution schedules, load `reports/parent-pool-evolution-schedule-memory-2026-06-29.md` when `parent-pool-recipe`, `validate-parent-pool-recipe`, PBT-style parent-pool replay, sign-merge/soup operator-family planning, seed-weight schedule metadata, or `evolution_schedule_checksum` validation is in scope. For operator schedule carry-forward, load `reports/operator-schedule-carry-forward-memory-2026-06-29.md` when sign-merge receipts, soup receipts, multi-parent candidate manifests, scheduled family index/command/selection rule/output gate fields, or browser bundle evidence chains consume parent-pool operator receipts. For compact adapter package work, load `reports/sparse-adapter-package-memory-2026-06-27.md` when `ASP1`, `sparse-adapter-delta`, `validate-sparse-adapter-delta`, or runtime sparse adapter apply is in scope. For low-rank adapter package work, load `reports/low-rank-adapter-package-memory-2026-06-28.md` when `ALR1`, `low-rank-adapter-delta`, `validate-low-rank-adapter-delta`, deterministic factor payloads, or runtime low-rank adapter apply is in scope. For trained adapter source work, load `reports/trained-adapter-source-memory-2026-06-28.md` when `adapter-source-template`, `validate-adapter-source`, trained low-rank factor manifests, or factor-file validation is in scope. For trained adapter source ALR1 conversion, load `reports/trained-adapter-source-alr1-memory-2026-06-28.md` when `convert-adapter-source`, `validate-converted-adapter-source`, source-factor ALR1 packaging, source-backed ALR1 manifests, or reviewed factor-to-runtime adapter routing is in scope. For browser low-rank adapter routing, load `reports/browser-low-rank-adapter-route-memory-2026-06-28.md` when generated `.alr1` routes, low-rank adapter-family members, `ALR1` manifests, module-plan low-rank stack roles, or `adapter-sidecar-registry-file` ALR1 smoke evidence is in scope. For browser source-backed ALR1 routing, load `reports/browser-source-backed-alr1-route-memory-2026-06-28.md` when generated bundles should convert reviewed adapter source templates into served source-backed `.alr1` stack members, or when app `.alr1` manifest kind/dtype acceptance changes. For browser source-backed ALR1 contracts, load `reports/browser-source-backed-alr1-contract-memory-2026-06-28.md` when source-backed `.alr1` kind/dtype pairing, adapter-family receipt source echoes, manifest-vs-receipt provenance checks, or `source-backed-alr1-manifest-drift` smoke expectations are in scope. For browser sparse adapter routing, load `reports/browser-sparse-adapter-route-memory-2026-06-27.md` when selector adapter routes, generated adapter families, served `.asp1` artifacts, browser manifest checks, or `adapter-sidecar-registry-file` smoke are in scope. For browser preferred adapter routing, load `reports/browser-preferred-adapter-route-memory-2026-06-27.md` when adapter-family receipt preferred fields, browser default adapter selection, generated sparse ASP1 preference, or smoke assertions around `selectedAdapterBeforeApply` are in scope. For combined generated selector roots, load `reports/browser-multi-quant-selector-root-memory-2026-06-27.md` when `browser-multi-parent-bundle all`, one-root f32/q8_0/q4_0 selector fan-in, or same-served-root adapter-sidecar smokes are in scope. For combined selector assembly proof, load `reports/browser-combined-selector-assembly-memory-2026-06-28.md` when `combined-selector-assembly`, all-root q4_0 default, all-three-entry module-plan ordering, or same-page q4_0/q8_0/f32 auto assembly is in scope. For combined selector cycle proof, load `reports/browser-combined-selector-cycle-memory-2026-06-28.md` when `combined-selector-cycle`, repeated all-root q4_0/q8_0/f32 switching, release-before-reassembly behavior, per-pass Rust stack validation/apply deltas, or fresh generated-root path-flexible Module Plan summaries are in scope. For combined selector route-soak proof, load `reports/browser-combined-selector-route-soak-memory-2026-06-28.md` when `combined-selector-route-soak`, repeated generated self-assembly route counts, no-store local fetch behavior, or longer q4_0/q8_0/f32 selector pressure is in scope. For combined selector extended route-soak proof, load `reports/browser-combined-selector-extended-route-soak-memory-2026-06-28.md` when `combined-selector-route-extended-soak`, five-cycle q4_0/q8_0/f32 route pressure, fifteen generated assemblies, path-flexible total-budget checks, or extended route-count proof is in scope. For combined selector stress route-soak proof, load `reports/browser-combined-selector-stress-route-soak-memory-2026-06-28.md` when `combined-selector-route-stress-soak`, eight-cycle q4_0/q8_0/f32 route pressure, twenty-four generated assemblies, or deeper self-assembly route-count proof is in scope. For combined selector reload-soak proof, load `reports/browser-combined-selector-reload-soak-memory-2026-06-28.md` when `combined-selector-reload-soak`, registry default boot selection, fresh page-lifetime self-assembly, or reload route-count proof is in scope. For browser module-plan profile proof, load `reports/browser-module-plan-profile-memory-2026-06-28.md` when `browser-constrained-v1`, selector-to-receipt self-assembly profile matching, generated module-plan profile fields, or `module-plan-profile-drift` is in scope. For browser module-plan execution profile proof, load `reports/browser-module-plan-execution-profile-memory-2026-06-28.md` when `single-threaded-wasm-local-v1`, Module Plan `Execution`, generated module-plan execution fields, or `module-plan-execution-profile-drift` is in scope. For browser module-plan fetch-policy proof, load `reports/browser-module-plan-fetch-policy-memory-2026-06-28.md` when `local-no-store-v1`, Module Plan `Fetch`, generated module-plan fetch fields, no-store local fetch behavior, or `module-plan-fetch-policy-drift` is in scope. For browser module-plan origin-policy proof, load `reports/browser-module-plan-origin-policy-memory-2026-06-28.md` when `same-origin-loopback-local-v1`, Module Plan `Origin`, generated module-plan origin fields, same-origin local assembly behavior, or `module-plan-origin-policy-drift` is in scope. For browser module-plan fetch-count proof, load `reports/browser-module-plan-fetch-count-memory-2026-06-28.md` when `module_plan_fetch_count_limit`, Module Plan `Fetch Limit`, generated self-assembly route counts, or `module-plan-fetch-count-drift` is in scope. For browser module-plan runtime scratch proof, load `reports/browser-module-plan-runtime-scratch-memory-2026-06-28.md` when `module_plan_runtime_scratch_byte_budget`, Module Plan `Scratch Budget`, browser runtime scratch envelopes, or `module-plan-runtime-scratch-drift` is in scope. For browser module-plan total budget proof, load `reports/browser-module-plan-total-budget-memory-2026-06-28.md` when `module_plan_total_byte_budget`, Module Plan `Total Budget`, exact module-plan self-assembly totals, or `module-plan-total-budget-drift` is in scope. For browser module-plan total limit proof, load `reports/browser-module-plan-total-limit-memory-2026-06-28.md` when `module_plan_total_byte_budget_limit`, Module Plan `Total Limit`, explicit browser self-assembly caps, or `module-plan-total-limit-drift` is in scope. For browser module-plan WASM memory proof, load `reports/browser-module-plan-wasm-memory-memory-2026-06-28.md` when `module_plan_wasm_memory_initial_pages`, Module Plan `WASM Pages`, pre-init exported WASM memory page checks, or `module-plan-wasm-memory-drift` is in scope. For browser module-plan WASM export-set proof, load `reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md` when `module_plan_wasm_export_set`, `tinyrustlm-generate-v1`, instantiated WASM export checks, Module Plan `WASM ABI`, or `module-plan-wasm-export-set-drift` is in scope. For browser module-plan WASM heap proof, load `reports/browser-module-plan-wasm-heap-memory-2026-06-28.md` when `module_plan_wasm_heap_min_bytes`, Module Plan `Heap Floor`, browser allocation probes, or `module-plan-wasm-heap-drift` is in scope. For browser module-plan WASM transfer proof, load `reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md` when `module_plan_wasm_transfer_strategy`, `copy-then-release-v1`, Module Plan `Transfer`, browser byte-copy release discipline, or `module-plan-wasm-transfer-drift` is in scope. For browser module-plan model-release proof, load `reports/browser-module-plan-model-release-memory-2026-06-29.md` when `module_plan_model_release_strategy`, `free-before-reassembly-v1`, Module Plan `Release`, generated model lifetime discipline, or `module-plan-model-release-drift` is in scope. For browser module-plan runtime-reset proof, load `reports/browser-module-plan-runtime-reset-memory-2026-06-29.md` when `module_plan_runtime_reset_strategy`, `reset-context-before-assembly-v1`, Module Plan `Reset`, generated runtime context reset sequencing, or `module-plan-runtime-reset-drift` is in scope. For browser module-plan adapter-validation proof, load `reports/browser-module-plan-adapter-validation-memory-2026-06-29.md` when `module_plan_adapter_validation_strategy`, `rust-validate-before-apply-v1`, Module Plan `Validate`, generated adapter validation sequencing, or `module-plan-adapter-validation-drift` is in scope. For browser module-plan adapter validation-count proof, load `reports/browser-module-plan-adapter-validation-count-memory-2026-06-29.md` when `module_plan_adapter_validation_count`, Module Plan `Validate Count`, actual Rust validation-call cardinality, adapter-family stack count agreement, or `module-plan-adapter-validation-count-drift` is in scope. For browser module-plan adapter apply-count proof, load `reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md` when `module_plan_adapter_apply_count`, Module Plan `Apply Count`, runtime `adapter_apply_count`, generated adapter stack cardinality, or `module-plan-adapter-apply-count-drift` is in scope. For browser module-plan planned-fetch-count proof, load `reports/browser-module-plan-planned-fetch-count-memory-2026-06-29.md` when `module_plan_planned_fetch_count`, Module Plan `Plan Fetches`, generated self-assembly route cardinality, or `module-plan-planned-fetch-count-drift` is in scope. For browser module-plan actual-fetch-count proof, load `reports/browser-module-plan-actual-fetch-count-memory-2026-06-29.md` when browser-owned generated route accounting, Module Plan `Actual Fetches`, counted fetch wrappers, source fallback, or planned-versus-actual Ready gating is in scope. For browser module-plan observed-route-set proof, load `reports/browser-module-plan-observed-route-set-memory-2026-06-29.md` when browser-owned route-set observations, Module Plan `Actual Route Set`, route kind labels, source fallback, or observed-versus-declared Ready gating is in scope. For browser module-plan actual-module-bytes proof, load `reports/browser-module-plan-actual-module-bytes-memory-2026-06-29.md` when browser-owned generated module-byte accounting, Module Plan `Actual Module Bytes`, stack artifact byte recording, source fallback, or observed-versus-receipt Ready gating is in scope. For browser module-plan actual-module-checksums proof, load `reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md` when browser-owned generated module-checksum accounting, Module Plan `Actual Module Checksums`, text/module checksum recording, stack artifact checksum recording, source fallback, module-plan-payload-checksum-drift, or observed-versus-receipt Ready gating is in scope. For browser module-plan route-set proof, load `reports/browser-module-plan-route-set-memory-2026-06-29.md` when `module_plan_route_set_checksum`, Module Plan `Route Set`, generated self-assembly route ordering, or `module-plan-route-set-drift` is in scope. For browser module-plan route-set version proof, load `reports/browser-module-plan-route-set-version-memory-2026-06-29.md` when `module_plan_route_set_version`, Module Plan `Route Version`, route-set checksum preimage versioning, or `module-plan-route-set-version-drift` is in scope. For browser module-plan route-set algorithm proof, load `reports/browser-module-plan-route-set-algorithm-memory-2026-06-29.md` when `module_plan_route_set_checksum_algorithm`, Module Plan `Route Hash`, route-set checksum preimage algorithm labels, or `module-plan-route-set-algorithm-drift` is in scope. For browser module-plan operator receipt proof, load `reports/browser-module-plan-operator-receipt-memory-2026-06-29.md` when `module_plan_operator_receipt_path`, `module_plan_operator_receipt_checksum`, `.module-plan.receipt` `operator_receipt_*` fields, assembly receipt/operator receipt agreement, or `module-plan-operator-receipt-drift` is in scope. For browser parent-pool soup bundle proof, load `reports/browser-parent-pool-soup-bundle-memory-2026-06-29.md` when `browser-multi-parent-bundle` operator selection, `multi-parent-soup-*` generated ids, `soup.*` evidence files, module-plan operator-prefix route sets, `assembly_strategy=multi-parent-weighted-soup`, or browser assembly validation for soup routes is in scope. For browser module-plan KV-cache proof, load `reports/browser-module-plan-kv-cache-memory-2026-06-28.md` when `module_plan_kv_cache_byte_budget`, `module_plan_kv_cache_page_count`, Module Plan `KV Budget` or `KV Pages`, runtime KV diagnostics, or `module-plan-kv-cache-drift` is in scope. For browser module-plan output-limit proof, load `reports/browser-module-plan-output-limit-memory-2026-06-28.md` when `module_plan_output_byte_limit`, Module Plan `Output Limit`, generated-result caps, output-buffer boundaries, or `module-plan-output-limit-drift` is in scope. For browser module-plan adapter-stack budget proof, load `reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28.md` when `module_plan_adapter_stack_byte_budget`, Module Plan `Stack Budget`, generated auto-stack byte totals, or `module-plan-adapter-stack-budget-drift` is in scope. For browser module-plan context-token proof, load `reports/browser-module-plan-context-token-memory-2026-06-28.md` when `module_plan_context_token_limit`, Module Plan `Context`, selector model-shape context parsing, or `module-plan-context-token-drift` is in scope. For browser module-plan tokenizer proof, load `reports/browser-module-plan-tokenizer-memory-2026-06-28.md` when `module_plan_tokenizer_checksum`, Module Plan `Tokenizer`, tokenizer-aware genome/species checksums, selector tokenizer routing, or `module-plan-tokenizer-drift` is in scope. For browser module-plan sampler-cap proof, load `reports/browser-module-plan-sampler-cap-memory-2026-06-28.md` when `module_plan_sampler_candidate_cap`, Module Plan `Sampler Cap`, fixed-buffer Top K clamping, or `module-plan-sampler-cap-drift` is in scope. For browser module-plan prompt-limit proof, load `reports/browser-module-plan-prompt-limit-memory-2026-06-28.md` when `module_plan_prompt_byte_limit`, Module Plan `Prompt Limit`, source prompt byte transfer, total budget math, `module-plan-prompt-limit-drift`, or `prompt-limit` source smoke behavior is in scope. For browser module-plan count drift proof, load `reports/browser-module-plan-count-drift-memory-2026-06-28.md` when selector `module_plan_module_count`, receipt `module_count`, module-plan cardinality, or `module-plan-count-drift` is in scope. For browser assembly trace proof, load `reports/browser-assembly-trace-memory-2026-06-28.md` when the Module Plan Trace row, browser load checkpoints, generated all-root trace assertion, or ready-state sequencing is in scope. For browser eval-case evidence checksum proof, load `reports/browser-eval-case-evidence-checksum-memory-2026-06-28.md` when selector admission eval evidence fields, promotion-ledger admission copies, generated assembly receipt eval digests, Model Provenance eval fields, or browser-smoke registry-backed provenance assertions are in scope. For browser selector genome/fitness proof, load `reports/browser-selector-genome-fitness-memory-2026-06-28.md` when selector `genome_id`, genome lineage checksums, scoped fitness-vector checksums, Model Provenance genome/fitness rows, or ModelBreeder-inspired browser registry metadata are in scope. For browser selector species-fit proof, load `reports/browser-selector-species-fit-memory-2026-06-28.md` when selector `species_id`, `species_strategy=selector-speciation-fit-v1`, `species_fit_status=browser-fit-bound`, `species_fit_checksum`, Model Provenance Species rows, or ModelBreeder speciation-fit browser registry metadata are in scope. For browser selector novelty proof, load `reports/browser-selector-novelty-memory-2026-06-28.md` when selector `novelty_id`, `novelty_strategy=selector-novelty-sketch-v1`, `novelty_status=behavior-sketch-bound`, `novelty_checksum`, Model Provenance Novelty rows, or ModelBreeder behavior-sketch registry metadata are in scope. For browser selector population proof, load `reports/browser-selector-population-memory-2026-06-28.md` when selector `population_id`, `population_strategy=selector-population-review-route-v1`, `population_status=population-review-bound`, `population_checksum`, Model Provenance Population rows, or ModelBreeder population-review registry metadata are in scope. For browser selector mate-selection proof, load `reports/browser-selector-mate-selection-memory-2026-06-28.md` when selector `mate_selection_id`, `mate_selection_strategy=selector-mate-selection-route-v1`, `mate_selection_status`, `mate_selection_parent_count`, `mate_selection_checksum`, Model Provenance Mate Selection rows, or ModelBreeder parent-pool route metadata are in scope. For browser selector phenotype-evidence proof, load `reports/browser-selector-phenotype-evidence-memory-2026-06-28.md` when selector `phenotype_evidence_id`, `phenotype_evidence_strategy=selector-phenotype-evidence-v1`, `phenotype_evidence_status=runtime-eval-bound`, `phenotype_evidence_checksum`, `provenance_manifest_checksum`, Model Provenance Phenotype rows, or ModelBreeder phenotype-evidence registry metadata are in scope. For browser selector heritable-artifact proof, load `reports/browser-selector-heritable-artifact-memory-2026-06-28.md` when selector `heritable_artifact_id`, `heritable_artifact_strategy=selector-heritable-artifact-v1`, `heritable_artifact_status=served-artifact-bound`, `heritable_artifact_checksum`, Model Provenance Artifact rows, or ModelBreeder artifact-inheritance registry metadata are in scope. For browser assembly eval-case drift proof, load `reports/browser-assembly-eval-case-drift-memory-2026-06-28.md` when generated assembly receipt eval digests, selector-to-assembly digest matching, Assembly Evidence failure states, or `assembly-eval-case-drift` smoke assertions are in scope. For browser assembly evidence-file drift proof, load `reports/browser-assembly-evidence-file-drift-memory-2026-06-28.md` when `verifyAssemblyEvidenceFiles`, fetched evidence-file checksums, generated evidence routes, Assembly Evidence failure states, or `assembly-evidence-file-drift` smoke assertions are in scope. For browser adapter-family receipt drift proof, load `reports/browser-adapter-family-receipt-drift-memory-2026-06-28.md` when `loadAdapterFamilyReceipt`, served adapter-family receipt bytes, post-evidence adapter-family failure state, or `adapter-family-receipt-drift` smoke assertions are in scope. For browser adapter manifest drift proof, load `reports/browser-adapter-manifest-drift-memory-2026-06-28.md` when `validateAdapterManifest`, served adapter manifest bytes, post-receipt adapter failure state, or `adapter-manifest-drift` smoke assertions are in scope. For browser adapter artifact drift proof, load `reports/browser-adapter-artifact-drift-memory-2026-06-28.md` when generated adapter artifact checksum matching, exact stack artifact route interception, post-manifest adapter failure state, or `adapter-artifact-drift` smoke assertions are in scope. For browser adapter stack preflight proof, load `reports/browser-adapter-stack-prefetch-drift-memory-2026-06-28.md` when generated auto-apply stack bytes, full-stack artifact prefetch, pre-WASM stack verification, or `adapter-stack-prefetch-drift` smoke assertions are in scope. For browser adapter stack Rust validation proof, load `reports/browser-adapter-stack-rust-validate-memory-2026-06-28.md` when `validate_adapter_delta`, generated auto-stack semantic preflight, validation-before-apply ordering, or WASM adapter ABI coverage is in scope. For browser adapter stack Rust validation drift proof, load `reports/browser-adapter-stack-rust-validate-drift-memory-2026-06-28.md` when checksum-consistent ADP1 identity drift, `adapter-stack-rust-validate-drift`, validation failure state, or no-apply assertions are in scope. For browser runtime assembly diagnostics proof, load `reports/browser-runtime-assembly-diagnostics-memory-2026-06-28.md` when Rust diagnostics assembly fields, `adapter_apply_count`, `last_adapter_checksum`, `assembly_state_checksum`, manual adapter sidecar assertions, or generated auto-stack runtime state assertions are in scope. For browser frugal selector defaults, load `reports/browser-frugal-selector-default-memory-2026-06-27.md` when selector default metadata, q4_0 initial selection, combined-root first load behavior, or default-selection smoke assertions are in scope. For browser selector byte budgets, load `reports/browser-selector-budget-memory-2026-06-27.md` when `entry.N.model_bytes`, registry fallback behavior, pre-WASM model byte transfer checks, or `selector-budget` smoke assertions are in scope. For browser selector budget contracts, load `reports/browser-selector-budget-contract-memory-2026-06-27.md` when `selector_model_byte_budget`, registry-level budget validation, generated bundle registry fields, or selector-budget contract smoke evidence is in scope. For browser auto assembly, load `reports/browser-auto-assembly-memory-2026-06-27.md` when selector adapter auto-apply fields, generated adapter-family startup apply, receipt-preferred sparse ASP1 auto selection, or `adapter-sidecar-registry-file` pre-generation assembly proof is in scope. For browser auto-assembly byte budgets, load `reports/browser-auto-assembly-budget-memory-2026-06-27.md` when `adapter_auto_apply_byte_budget`, adapter manifest artifact bytes, pre-WASM adapter transfer checks, or constrained browser module assembly is in scope. For browser text-sidecar byte budgets, load `reports/browser-text-sidecar-budget-memory-2026-06-27.md` when selector.registry, `.slm` manifests, adapter manifests, receipts, assembly evidence text, or sidecar pre-parse fetch limits are in scope. For browser text-sidecar budget contracts, load `reports/browser-text-sidecar-contract-memory-2026-06-27.md` when selector registry header fields, generated registry contract validation, exact browser budget intake, or sidecar-budget-contract fallback smoke evidence is in scope. For browser runtime manifests, load `reports/browser-runtime-manifest-memory-2026-06-27.md` when runtime WASM rebuild/copy flows, generated bundle runtime staging, browser boot sequencing, or manifest-drift smoke evidence is in scope. For browser adapter stacks, load `reports/browser-adapter-stack-memory-2026-06-27.md` when generated adapter-family receipts, selector `adapter_auto_apply_stack_*` fields, ordered ADP1/ASP1/ALR1 startup apply, or adapter-stack smoke evidence is in scope. For browser module plans, load `reports/browser-module-plan-memory-2026-06-27.md` when generated selector `module_plan_*` fields, served `.module-plan.receipt` files, pre-model-fetch plan verification, or generated-root adapter-stack smoke routes are in scope. For browser module-plan resource envelopes, load `reports/browser-module-plan-resource-memory-2026-06-27.md` when `module_plan_resource_class`, `module_plan_model_byte_budget`, `module_plan_adapter_byte_budget`, constrained self-assembly routing, or pre-model-fetch plan budget checks are in scope. For browser module-plan resource drift proof, load `reports/browser-module-plan-resource-drift-memory-2026-06-27.md` when `module-plan-resource-drift`, checksum-consistent receipt mutation, or no-generated-`.slm`-fetch proof is in scope. For browser module-plan graph drift proof, load `reports/browser-module-plan-graph-drift-memory-2026-06-27.md` when `module-plan-graph-drift`, checksum-consistent graph-route mutation, or no-generated-`.slm`-fetch proof is in scope. For browser module-plan stack drift proof, load `reports/browser-module-plan-stack-drift-memory-2026-06-27.md` when `module-plan-stack-drift`, checksum-consistent stack-member mutation, or no-generated-model-or-stack-artifact-fetch proof is in scope. For browser module-plan role drift proof, load `reports/browser-module-plan-role-drift-memory-2026-06-27.md` when `module-plan-role-drift`, checksum-consistent role mutation, or no-generated-model-or-stack-artifact-fetch proof is in scope. For browser module-plan display proof, load `reports/browser-module-plan-display-memory-2026-06-27.md` when the Module Plan panel, rendered verified receipt fields, generated model route display, stack route display, or panel smoke assertions are in scope. For browser module-plan budget display proof, load `reports/browser-module-plan-budget-display-memory-2026-06-27.md` when the Module Plan panel's visible model/adapter byte-budget rows or budget smoke assertions are in scope. For browser module-plan role display proof, load `reports/browser-module-plan-role-display-memory-2026-06-27.md` when `.module-plan.receipt` module roles, rendered role summaries, or role smoke assertions are in scope. For browser module-plan assembly-slot proof, load `reports/browser-module-plan-slots-memory-2026-06-27.md` when `.module-plan.receipt` `module.N.assembly_slot` fields, rendered slot summaries, or `module-plan-slot-drift` assertions are in scope. For browser module-plan dependency proof, load `reports/browser-module-plan-dependencies-memory-2026-06-27.md` when `.module-plan.receipt` `module.N.depends_on` fields, rendered dependency summaries, or `module-plan-dependency-drift` assertions are in scope. For browser module-plan phase proof, load `reports/browser-module-plan-phases-memory-2026-06-27.md` when `.module-plan.receipt` `module.N.phase` fields, rendered phase summaries, or `module-plan-phase-drift` assertions are in scope. For browser module-plan byte-count proof, load `reports/browser-module-plan-byte-counts-memory-2026-06-27.md` when `.module-plan.receipt` `module.N.byte_count` fields, rendered byte summaries, fetched text/model byte matching, adapter-stack artifact byte matching, or `module-plan-byte-drift` assertions are in scope. For browser module-plan checksum proof, load `reports/browser-module-plan-checksums-memory-2026-06-27.md` when `.module-plan.receipt` `module.N.checksum` fields, rendered checksum summaries, stack artifact checksum matching, or `module-plan-checksum-drift` assertions are in scope. Model-breeding references live under `wiki/gguf-mirust/research/model-breeding-reference-ideas-2026-06-26.md`; open it for compatible merge, sparse-lineage, adapter-ecology, low-rank ALR1/LoRA reference routing, source-backed browser ALR1 routing, population-search, federated/local-update, browser-constrained-assembly, UAIX-memory-strategy, sparse-mask breadcrumb, objective-vector, parent-relatedness, evolutionary-recipe, adaptive-search, and multi-objective-fitness routing. ModelBreeder and zero-dependency references live under `wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md`; open it for genome/fitness/novelty/population/mate-selection/phenotype-evidence/speciation fields, public-copy voice routing, zero-dependency Wasm SIMD, hierarchical quantization, deterministic tokenizer/sampler, KV-cache, allocator, multimodal, and telemetry guidance. ## Active File Intake Dropped files live only in `agent-file-handoff/Content/` and `agent-file-handoff/Improvement/`. There is no source-site Archive bucket for default resting memory. ## Implementation Boundary The repository currently contains TinyRustLM, a zero-dependency Rust/WASM browser-local SLM runtime and UI. Future claims still require source inspection and current test evidence; report memory provides design pressure, not implementation proof. ================================================================================ END FILE: wiki/gguf-mirust/source-memory-guide.md ================================================================================ ================================================================================ BEGIN FILE: wiki/global/rust-browser-harness-standards.md BYTES: 521 SHA256: 4AFE8ECAEAD9013ADC704CA4F6FA5B4414F8DCEAFC17637AB075149C6E1A291C ================================================================================ # Rust Browser Harness Standards Reviewed: 2026-06-24 These standards are shared guidance for GGUF.MiRust.com until a broader organization-level Rust harness standard exists. - Keep browser actions typed and reviewable. - Keep model output as proposals until a policy gate accepts them. - Keep page content, prompts, memory files, and operator commands as separate authority layers. - Do not execute code from handoff intake, page content, or model output. - Require tests before changing runtime control boundaries. ================================================================================ END FILE: wiki/global/rust-browser-harness-standards.md ================================================================================ ================================================================================ BEGIN FILE: workspace.uai BYTES: 74032 SHA256: 2762B139D7B5EB92B3673C458D431A7B9FD252B8FF4E82BB52B9D5EB7C62B56C ================================================================================ profile: gguf-mirust.workspace.v77 project_name: GGUF.MiRust.com canonical_root: E:\Source\Rust\GGUF.MiRust.com updated_utc: 2026-06-29T20:22:33Z version_authority: current_version: 0.1.0 next_version: 0.1.0 policy: Increment intentionally after real implementation milestones; source scaffolding does not imply runtime support. active_product: name: TinyRustLM root: tinyrustlm/ purpose: Zero-dependency Rust/WASM browser-local SLM runtime and UI. memory_authority: hot_memory_root: .uai/ llm_wiki_namespace: wiki/gguf-mirust/ aiwikis_public_namespace: https://aiwikis.org/gguf-mirust/ file_handoff_root: agent-file-handoff/ site_voice_hot_memory: .uai/taboo.uai uaix_file_handoff_strategy_source: https://uaix.org/en-us/tools/ai-memory-package-wizard/#setup-file-handoff report_storage_strategy: hot_uai_routes_current_state_and_synthesis; durable_reports_live_in_wiki_raw_evidence_and_pointer_ledgers research_reference_strategy: diverse_model_breeding_reference_bodies_live_in_wiki_research_and_route_through_short_term_memory_report_synthesis_and_long_term_checksum_pointers; lanes include compatible_merge_dare_dropout_rescaled_task_delta_sparse_lineage_adapter_ecology_with_trained_source_alr1_and_adp1_asp1_alr1_population_search_federated_local_update_browser_constrained_assembly_uaix_memory_strategy_heritable_artifacts_mate_selection_phenotype_evidence_speciation_fit_genome_fitness_novelty_and_zero_dependency_browser_runtime_guidance two_parent_operator_browser_provenance_2026_06_29: wiki/gguf-mirust/reports/two-parent-operator-browser-provenance-memory-2026-06-29.md routes compact browser Model Provenance Operator rendering and receipt byte-echo fallback for blend, task-delta, and sparse task-delta selector fixtures. crossover_operator_2026_06_29: wiki/gguf-mirust/reports/crossover-operator-memory-2026-06-29.md routes deterministic direct-parameter crossover commands, seed and parent0 keep fields, selection density, mask checksum, q8 validation, focused parameter tests, drift tests, CLI write/validate proof, browser Operator rendering, and crossover byte-echo fallback. mutation_operator_2026_06_29: wiki/gguf-mirust/reports/mutation-operator-memory-2026-06-29.md routes deterministic bounded mutation commands, seed/rate/magnitude fields, reference scaling, selection checksum, delta checksum, q8 validation, focused parameter tests, drift tests, CLI write/validate proof, browser Operator rendering, and mutation byte-echo fallback. prune_operator_2026_06_29: wiki/gguf-mirust/reports/prune-operator-memory-2026-06-29.md routes deterministic magnitude pruning commands, keep/floor fields, selected/pruned counts, mask checksum, output-value checksum, q8 validation, focused parameter tests, selector receipt carry-forward, browser Operator rendering, prune byte-echo fallback, drift tests, and CLI write/validate proof. dare_operator_2026_06_29: wiki/gguf-mirust/reports/dare-operator-memory-2026-06-29.md routes DARE dropout/rescaled task-delta commands, signed delta weight ppm, keep/drop ppm, dropout seed, selected/dropped counts, mask/raw/rescaled delta checksums, q8 validation, focused parameter tests, drift tests, and CLI write/validate proof. dare_browser_operator_provenance_2026_06_29: wiki/gguf-mirust/reports/dare-browser-operator-provenance-memory-2026-06-29.md routes DARE compact browser Operator rendering, selector receipt byte echo, DARE operator-kind drift rejection, and browser byte fallback. browser_converted_trained_provenance_2026_06_29: wiki/gguf-mirust/reports/browser-converted-trained-provenance-memory-2026-06-29.md routes converted-trained q8 selector fixture proof, converted-trained manifest request proof, and browser Model Provenance source/admission/quality field assertions. browser_converted_trained_file_route_2026_06_29: wiki/gguf-mirust/reports/browser-converted-trained-file-route-memory-2026-06-29.md routes `browser-converted-trained-bundle`, generated file-backed root proof, and `converted-trained-registry-file` selector/model/manifest browser smoke. browser_converted_trained_all_route_2026_06_29: wiki/gguf-mirust/reports/browser-converted-trained-all-route-memory-2026-06-29.md routes `browser-converted-trained-bundle all`, q4-defaulted converted-trained f32/q8/q4 selector roots, and q4/q8/f32 selector/model/manifest browser smokes. federated_operator_2026_06_29: wiki/gguf-mirust/reports/federated-operator-memory-2026-06-29.md routes federated/local-update commands, base/local-update parent roles, local_update_weight_ppm, local-update delta checksums, q8 validation, focused parameter tests, drift tests, and CLI write/validate proof. weighted_soup_operator_2026_06_29: wiki/gguf-mirust/reports/weighted-soup-operator-memory-2026-06-29.md routes parent-pool soup commands, recipe seed weights, direct weighted averaging, parent-weight checksum, weighted-value checksum, drift tests, and focused verification proof. multi_parent_soup_manifest_2026_06_29: wiki/gguf-mirust/reports/multi-parent-soup-manifest-memory-2026-06-29.md routes multi-parent candidate manifests accepting soup receipts, parent-pool operator dispatch, soup metric preservation, manifest status, focused tests, and full packer proof. federated_selector_receipt_route_2026_06_29: wiki/gguf-mirust/reports/federated-selector-receipt-route-memory-2026-06-29.md routes federated operator receipt fields through candidate, promotion, admission, selector registry proof, browser Model Provenance Operator rendering, federated operator-kind drift rejection, and browser operator-receipt byte-count drift fallback. candidate_operator_receipt_binding_2026_06_29: wiki/gguf-mirust/reports/candidate-operator-receipt-binding-memory-2026-06-29.md routes optional operator receipt binding for candidate manifests, bound receipt fields, checksum drift tests, CLI proof, and validation behavior. promotion_operator_receipt_binding_2026_06_29: wiki/gguf-mirust/reports/promotion-operator-receipt-binding-memory-2026-06-29.md routes optional operator receipt carry-forward for promotion templates, bound receipt fields, receipt drift tests, CLI proof, and validation behavior. admission_operator_receipt_binding_2026_06_29: wiki/gguf-mirust/reports/admission-operator-receipt-binding-memory-2026-06-29.md routes optional operator receipt carry-forward for selector admissions, bound receipt fields, summary validation, CLI proof, and validation behavior. selector_operator_receipt_binding_2026_06_29: wiki/gguf-mirust/reports/selector-operator-receipt-binding-memory-2026-06-29.md routes receipt-bound admission fields into selector registry entries, mate-selection checksums, browser provenance Operator rendering, and CLI admission-to-registry proof. browser_multi_parent_operator_provenance_2026_06_29: wiki/gguf-mirust/reports/browser-multi-parent-operator-provenance-memory-2026-06-29.md routes multi-parent admission operator receipt carry-forward into generated selector entries, q4/q8/f32 soup and sign-merge browser Operator row proof, generated selector operator receipt byte drift fallback, and generated assembly operator-kind drift fallback before generated routes. browser_mixed_operator_selector_2026_06_29: wiki/gguf-mirust/reports/browser-mixed-operator-selector-memory-2026-06-29.md routes mixed sign-merge plus soup generated selector roots, q4/q8/f32 cross-family assembly cycles, q4 default preservation, release-before-reassembly proof, operator-family smoke proof, mixed route-soak proof, and mixed reload-soak proof. parent_pool_evolution_schedule_2026_06_29: wiki/gguf-mirust/reports/parent-pool-evolution-schedule-memory-2026-06-29.md routes parent-pool recipe evolution schedule fields, sign-merge/soup operator families, seed-weight replay metadata, schedule checksum drift tests, and full packer verification. operator_schedule_carry_forward_2026_06_29: wiki/gguf-mirust/reports/operator-schedule-carry-forward-memory-2026-06-29.md routes sign-merge/soup receipt schedule echoes, scheduled family index/command/rule/output gate, multi-parent candidate/promotion/admission carry-forward, selector admission schema proof, and focused/full packer proof. modelbreeder_zero_dependency_reference_2026_06_28: wiki/gguf-mirust/research/modelbreeder-zero-dependency-reference-ideas-2026-06-28.md routes latest Improvement research into genome_fitness_novelty_population_speciation_voice_wasm_simd_hierarchical_quantization_tokenizer_sampler_kv_cache_allocator_multimodal_and_telemetry_future_lanes browser_selector_species_fit_2026_06_28: wiki/gguf-mirust/reports/browser-selector-species-fit-memory-2026-06-28.md routes generated selector species ids, browser-fit checksums, Model Provenance Species rows, and combined-selector-assembly proof. browser_selector_novelty_2026_06_28: wiki/gguf-mirust/reports/browser-selector-novelty-memory-2026-06-28.md routes generated selector novelty ids, behavior-sketch checksums, Model Provenance Novelty rows, and combined-selector-assembly proof. browser_selector_population_2026_06_28: wiki/gguf-mirust/reports/browser-selector-population-memory-2026-06-28.md routes generated selector population ids, population-review checksums, Model Provenance Population rows, and combined-selector-assembly proof. browser_selector_mate_selection_2026_06_28: wiki/gguf-mirust/reports/browser-selector-mate-selection-memory-2026-06-28.md routes generated selector mate-selection ids, parent counts, parent-pool-bound checksums, Model Provenance Mate Selection rows, and combined-selector-assembly proof. browser_selector_phenotype_evidence_2026_06_28: wiki/gguf-mirust/reports/browser-selector-phenotype-evidence-memory-2026-06-28.md routes generated selector phenotype-evidence ids, runtime-eval-bound checksums, Model Provenance Phenotype rows, and combined-selector-assembly proof. browser_selector_heritable_artifact_2026_06_28: wiki/gguf-mirust/reports/browser-selector-heritable-artifact-memory-2026-06-28.md routes generated selector heritable artifact ids, served-artifact-bound checksums, Model Provenance Artifact rows, and combined-selector-assembly proof. browser_module_plan_total_limit_2026_06_28: wiki/gguf-mirust/reports/browser-module-plan-total-limit-memory-2026-06-28.md routes explicit module-plan total byte budget cap fields, Module Plan Total Limit rows, and module-plan-total-limit-drift proof. browser_module_plan_output_limit_2026_06_28: wiki/gguf-mirust/reports/browser-module-plan-output-limit-memory-2026-06-28.md routes output byte limit fields, Module Plan Output Limit rows, total budget inclusion, and module-plan-output-limit-drift proof. browser_module_plan_kv_cache_2026_06_28: wiki/gguf-mirust/reports/browser-module-plan-kv-cache-memory-2026-06-28.md routes KV-cache byte budget and page-count fields, runtime KV diagnostics, Module Plan KV rows, and module-plan-kv-cache-drift proof. browser_module_plan_adapter_stack_budget_2026_06_28: wiki/gguf-mirust/reports/browser-module-plan-adapter-stack-budget-memory-2026-06-28.md routes exact ADP1/ASP1/ALR1 stack byte budget fields, Module Plan Stack Budget rows, and module-plan-adapter-stack-budget-drift proof. browser_module_plan_context_token_2026_06_28: wiki/gguf-mirust/reports/browser-module-plan-context-token-memory-2026-06-28.md routes validated context token limit fields, Module Plan Context rows, and module-plan-context-token-drift proof. browser_module_plan_tokenizer_2026_06_28: wiki/gguf-mirust/reports/browser-module-plan-tokenizer-memory-2026-06-28.md routes tokenizer checksum fields, Module Plan Tokenizer rows, genome/species checksum ingredients, and module-plan-tokenizer-drift proof. browser_module_plan_sampler_cap_2026_06_28: wiki/gguf-mirust/reports/browser-module-plan-sampler-cap-memory-2026-06-28.md routes fixed-buffer sampler candidate cap fields, Module Plan Sampler Cap rows, Top K clamping, and module-plan-sampler-cap-drift proof. browser_module_plan_wasm_export_set_2026_06_28: wiki/gguf-mirust/reports/browser-module-plan-wasm-export-set-memory-2026-06-28.md routes tinyrustlm-generate-v1 WASM export-set fields, instantiated export checks, Module Plan WASM ABI rows, and module-plan-wasm-export-set-drift proof. browser_module_plan_wasm_heap_2026_06_28: wiki/gguf-mirust/reports/browser-module-plan-wasm-heap-memory-2026-06-28.md routes WASM heap-floor fields, browser alloc/dealloc probes, Module Plan Heap Floor rows, and module-plan-wasm-heap-drift proof. browser_module_plan_wasm_transfer_2026_06_28: wiki/gguf-mirust/reports/browser-module-plan-wasm-transfer-memory-2026-06-28.md routes copy-then-release transfer-strategy fields, Module Plan Transfer rows, source fallback, and module-plan-wasm-transfer-drift proof. browser_module_plan_model_release_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-model-release-memory-2026-06-29.md routes free-before-reassembly model-release fields, Module Plan Release rows, source fallback, model-release drift proof, and combined-selector-cycle release-before-reassembly proof. browser_module_plan_runtime_reset_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-runtime-reset-memory-2026-06-29.md routes reset-context-before-assembly fields, Module Plan Reset rows, source fallback, runtime-reset drift proof, and combined-selector-cycle reset-before-adapter proof. browser_module_plan_adapter_validation_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-memory-2026-06-29.md routes rust-validate-before-apply fields, Module Plan Validate rows, source fallback, adapter-validation drift proof, and combined-selector-assembly validation-before-apply proof. browser_module_plan_adapter_validation_count_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-adapter-validation-count-memory-2026-06-29.md routes validation-count fields, Module Plan Validate Count rows, selector/receipt/adapter-family agreement, source fallback, per-step Rust validation-call counting, and adapter-validation-count drift proof. browser_module_plan_adapter_apply_count_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-adapter-apply-count-memory-2026-06-29.md routes apply-count fields, Module Plan Apply Count rows, runtime adapter_apply_count diagnostics checks, source fallback, and adapter-apply-count drift proof. browser_module_plan_planned_fetch_count_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-planned-fetch-count-memory-2026-06-29.md routes planned-fetch-count fields, Module Plan Plan Fetches rows, selector/receipt/generated-route agreement, source fallback, and planned-fetch-count drift proof. browser_module_plan_actual_fetch_count_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-actual-fetch-count-memory-2026-06-29.md routes browser-owned generated self-assembly fetch accounting, Module Plan Actual Fetches rows, planned-vs-actual readiness gating, source fallback, and combined-selector proof. browser_module_plan_observed_route_set_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-observed-route-set-memory-2026-06-29.md routes browser-observed generated route-set checksums, Module Plan Actual Route Set rows, observed-vs-declared route gating, source fallback, and combined-selector proof. browser_module_plan_actual_module_bytes_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-actual-module-bytes-memory-2026-06-29.md routes browser-observed generated module byte totals, Module Plan Actual Module Bytes rows, observed-vs-declared module-byte readiness gating, source fallback, and combined-selector proof. browser_module_plan_actual_module_checksums_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-actual-module-checksums-memory-2026-06-29.md routes browser-observed generated module checksum totals, Module Plan Actual Module Checksums rows, observed-vs-declared module-checksum readiness gating, source fallback, combined-selector proof, and module-plan-payload-checksum-drift. browser_module_plan_route_set_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-route-set-memory-2026-06-29.md routes route-set checksum fields, Module Plan Route Set rows, selector/receipt/ordered-route agreement, source fallback, and route-set drift proof. browser_module_plan_route_set_version_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-route-set-version-memory-2026-06-29.md routes route-set version fields, Module Plan Route Version rows, checksum preimage versioning, source fallback, and route-set-version drift proof. browser_module_plan_route_set_algorithm_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-route-set-algorithm-memory-2026-06-29.md routes route-set checksum algorithm fields, Module Plan Route Hash rows, checksum preimage algorithm labels, source fallback, and route-set-algorithm drift proof. browser_module_plan_operator_receipt_2026_06_29: wiki/gguf-mirust/reports/browser-module-plan-operator-receipt-memory-2026-06-29.md routes module-plan operator receipt path/checksum fields, selector/receipt/assembly agreement, evidence checksum binding, and module-plan-operator-receipt-drift proof. browser_module_plan_prompt_limit_2026_06_28: wiki/gguf-mirust/reports/browser-module-plan-prompt-limit-memory-2026-06-28.md routes prompt byte limit fields, Module Plan Prompt Limit rows, source prompt-copy boundary proof, and module-plan-prompt-limit-drift proof. browser_module_plan_fetch_count_2026_06_28: wiki/gguf-mirust/reports/browser-module-plan-fetch-count-memory-2026-06-28.md routes fetch-count limit fields, Module Plan Fetch Limit rows, generated route-count computation, actual governed request counting, and fetch-count proof. short_term_report_route_strategy: .uai/short-term-memory.uai keeps the current report indexes, research route, active bucket disposition, UAIX strategy source, dogfood route, report pointer audit, and long-term pointer ledger route in one cold-start block. report_pointer_audit_strategy: every current wiki/gguf-mirust/reports/*.md and wiki/gguf-mirust/research/*.md page is represented in .uai/long-term-memory.uai; add future report and research pages to long-term pointers and short-term routes together. setup_file_handoff_strategy_2026_06_28: active buckets are intake, durable bodies live in raw/wiki Markdown, hot .uai files carry routing and synthesis, short-term memory names current report/research routes, and long-term memory keeps checksum pointers. site_voice_strategy: .uai/taboo.uai keeps GGUF.MiRust.com public copy centered on proof, craft, lineage, fit, local agency, routes, and implementation evidence. support_boundary: status: milestone_160_browser_module_plan_actual_module_checksums static_browser_shell: implemented_source wasm_exports: implemented_source_with_explicit_error_code_generate_next_token_free_model_validate_adapter_delta_and_apply_adapter_delta byte_tokenizer: implemented_source custom_bpe_tokenizer: implemented_for_tiny_bpe_slm_fixture_with_runtime_merge_diagnostics slm_parser: implemented_source math_ops: implemented_source_with_direct_dot_matvec_matmul_rmsnorm_softmax_silu_and_swiglu_tests tiny_transformer_forward: implemented_for_tiny_f32_fixture tinylm16_f32_forward: implemented_for_real_shaped_deterministic_smoke_model tinylm16_q8_forward: implemented_for_real_shaped_deterministic_smoke_model_with_native_quant_storage_and_reusable_scratch_row_dequantization tinylm16_q4_forward: implemented_for_real_shaped_deterministic_smoke_model_with_native_quant_storage_and_reusable_scratch_row_dequantization slm_checksum_validation: packer_writes_nonzero_zeroed_field_checksum_and_runtime_rejects_zero_or_mismatched_checksum slm_admission_validation: native_packer_validate_command_verifies_header_checksum_tokenizer_required_shapes_payload_lengths_finite_f32_and_quant_scales slm_provenance_manifest_validation: generated_and_validated_for_all_eight_local_models_with_deterministic_smoke_quality_boundary_and_trained_quality_nonclaim slm_quality_gate: runtime_smoke_gate_verified_for_existing_tinylm16_q8_manifest_and_for_f32_q8_q4_converted_fixture_outputs; assistant_quality_gate_rejects_pending_eval_templates_missing_case_evidence_zero_case_eval_files_stray_case_keys_and_per_case_expected_actual_mismatches slm_converted_trained_browser_provenance: browser_smoke_converted_trained_registry_proves_selector_served_converted_trained_q8_route_fetches_converted_trained_manifest_and_renders_source_admission_quality_and_pending_eval_fields_with_shared_multi_parent_registry_regression slm_converted_trained_file_route: browser_converted_trained_bundle_stages_reviewed_source_q8_as_served_slm_manifest_evidence_admission_and_selector_registry_with_converted_trained_registry_file_smoke_fetching_real_selector_model_and_manifest_routes slm_converted_trained_all_route: browser_converted_trained_bundle_all_stages_reviewed_source_f32_q8_q4_as_one_q4_defaulted_selector_root_with_converted_trained_registry_file_smokes_fetching_real_selector_model_and_manifest_routes_for_all_three_entries slm_parent_compatibility: no_crate_tinyrustlm_slm_pack_compatibility_command_validates_two_parent_slm_files_and_emits_line_based_parent_set_reports_with_shape_tokenizer_checksum_tensor_layout_checksum_quantization_output_contract_flags_parent_checksums_and_direct_parameter_pass_fail_decision slm_candidate_lineage: no_crate_tinyrustlm_slm_pack_lineage_template_and_validate_lineage_commands_bind_planned_candidate_records_to_passing_parent_compatibility_reports_with_checksum_copied_parent_fields_operator_id_resource_budget_pending_artifact_fields_and_next_gate slm_blend_operator: no_crate_tinyrustlm_slm_pack_blend_candidate_and_validate_blend_candidate_commands_bind_validated_lineage_compatibility_bound_parent_checksums_blend_weights_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest_with_browser_compact_operator_row_and_byte_echo_fallback_proof slm_task_delta_operator: no_crate_tinyrustlm_slm_pack_delta_candidate_and_validate_delta_candidate_commands_bind_validated_lineage_compatibility_bound_base_and_target_parent_checksums_signed_task_delta_weights_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest_with_browser_compact_operator_row_and_byte_echo_fallback_proof slm_sparse_delta_operator: no_crate_tinyrustlm_slm_pack_sparse_delta_candidate_and_validate_sparse_delta_candidate_commands_bind_validated_lineage_compatibility_bound_base_and_target_parent_checksums_signed_task_delta_weights_absolute_delta_keep_rate_selected_parameter_counts_density_nonzero_retention_ppm_implicit_top_k_mask_checksum_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest_with_browser_compact_operator_row_and_byte_echo_fallback_proof slm_crossover_operator: no_crate_tinyrustlm_slm_pack_crossover_candidate_and_validate_crossover_candidate_commands_bind_validated_lineage_compatibility_bound_parent_checksums_seed_parent0_keep_rate_selected_parameter_counts_density_ppm_mask_checksum_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest_with_browser_compact_operator_row_and_byte_echo_fallback_proof slm_mutation_operator: no_crate_tinyrustlm_slm_pack_mutation_candidate_and_validate_mutation_candidate_commands_bind_validated_lineage_compatibility_bound_base_and_reference_parent_checksums_seed_rate_magnitude_reference_scale_selection_checksum_delta_checksum_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest_with_browser_compact_operator_row_and_byte_echo_fallback_proof slm_prune_operator: no_crate_tinyrustlm_slm_pack_prune_candidate_and_validate_prune_candidate_commands_bind_validated_lineage_compatibility_bound_base_and_reference_parent_checksums_keep_ppm_floor_ppm_magnitude_ranking_selected_pruned_counts_mask_checksum_output_value_checksum_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest slm_dare_operator: no_crate_tinyrustlm_slm_pack_dare_candidate_and_validate_dare_candidate_commands_bind_validated_lineage_compatibility_bound_base_and_target_parent_checksums_signed_delta_weight_ppm_keep_drop_ppm_dropout_seed_nonzero_delta_mask_raw_delta_rescaled_delta_checksums_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest_with_browser_compact_operator_row_and_byte_echo_fallback_proof slm_dare_browser_operator: no_crate_tinyrustlm_slm_pack_selector_tests_and_browser_smoke_prove_DARE_dropout_rescaled_task_delta_receipts_survive_receipt_bound_admission_selector_registry_and_browser_model_provenance_handoff_with_operator_kind_receipt_checksum_candidate_checksum_byte_count_equality_operator_row_rendering_operator_kind_drift_rejection_and_browser_byte_count_drift_fallback slm_federated_operator: no_crate_tinyrustlm_slm_pack_federated_candidate_and_validate_federated_candidate_commands_bind_validated_lineage_compatibility_bound_base_and_local_update_parent_checksums_local_update_weight_ppm_local_update_counts_delta_checksum_weighted_delta_checksum_candidate_slm_bytes_and_recomputable_operator_receipts_before_candidate_manifest slm_weighted_soup_operator: no_crate_tinyrustlm_slm_pack_soup_candidate_and_validate_soup_candidate_commands_bind_parent_pool_recipe_ledger_review_admissions_and_ordered_parent_slm_files_then_write_recipe_seed_weighted_direct_average_slm_candidates_with_parent_weight_weighted_value_and_frontier_change_receipt_checksums slm_federated_selector_receipt_route: no_crate_tinyrustlm_slm_pack_selector_tests_and_browser_smoke_prove_federated_local_update_receipts_survive_candidate_promotion_admission_selector_registry_and_browser_model_provenance_handoff_with_operator_kind_receipt_checksum_candidate_checksum_byte_count_equality_operator_row_rendering_operator_kind_drift_rejection_and_browser_byte_count_drift_fallback slm_adapter_delta_artifact: no_crate_tinyrustlm_slm_pack_adapter_delta_and_validate_adapter_delta_commands_bind_validated_lineage_compatibility_bound_base_and_target_parent_checksums_raw_f32_task_delta_adp1_bytes_recomputable_manifest_and_runtime_f32_q8_q4_apply_or_fuse_status slm_sparse_adapter_delta_artifact: no_crate_tinyrustlm_slm_pack_sparse_adapter_delta_and_validate_sparse_adapter_delta_commands_bind_validated_lineage_compatibility_bound_base_and_target_parent_checksums_sparse_f32_task_delta_asp1_bytes_density_retention_mask_checksum_recomputable_manifest_and_runtime_f32_q8_q4_apply_status slm_low_rank_adapter_delta_artifact: no_crate_tinyrustlm_slm_pack_low_rank_adapter_delta_and_validate_low_rank_adapter_delta_commands_bind_validated_lineage_compatibility_bound_base_and_target_parent_checksums_low_rank_f32_task_delta_alr1_factor_bytes_component_limit_factor_density_residual_l1_recomputable_manifest_and_runtime_f32_q8_q4_apply_status slm_trained_adapter_source: no_crate_tinyrustlm_slm_pack_adapter_source_template_and_validate_adapter_source_commands_write_and_validate_reviewed_low_rank_f32_factor_source_bundles_with_shape_tied_output_target_tensor_factor_rank_checksum_finite_factor_parameter_count_and_delta_l1_fields_before_source_backed_alr1_packaging slm_trained_adapter_source_alr1: no_crate_tinyrustlm_slm_pack_convert_adapter_source_and_validate_converted_adapter_source_commands_validate_reviewed_low_rank_f32_factor_bundles_against_base_slm_shape_tied_output_tokenizer_tensor_layout_and_target_tensor_identity_then_write_and_recompute_runtime_alr1_artifacts_and_manifests browser_source_backed_alr1_route: browser_multi_parent_bundle_stages_reviewed_adapter_source_templates_for_generated_q4_q8_f32_entries_converts_them_into_source_backed_alr1_stack_members_adapter_family_receipts_accept_source_backed_kind_dtype_pairs_app_js_accepts_source_backed_alr1_manifests_without_payload_parsing_and_combined_selector_assembly_proves_apply_before_generation browser_source_backed_alr1_contract: source_backed_alr1_manifest_intake_requires_exact_kind_dtype_pair_adapter_family_source_echoes_manifest_source_field_match_and_source_backed_alr1_manifest_drift_proves_contract_drift_stops_before_stack_artifact_fetch slm_adapter_fuse_candidate: no_crate_tinyrustlm_slm_pack_fuse_adapter_delta_and_validate_fuse_adapter_delta_commands_validate_adapter_package_manifest_adp1_header_tensor_directory_then_write_normal_slm_candidate_and_recomputable_fuse_receipt_before_candidate_manifest slm_runtime_adapter_apply: no_crate_runtime_validate_adapter_delta_and_apply_adapter_delta_validate_compatible_adp1_raw_asp1_sparse_and_alr1_low_rank_packages_against_loaded_f32_q8_0_q4_0_model_identity_payload_checksums_tensor_directory_tokenizer_layout_and_fused_values_apply_requantizes_q8_q4_compact_tensors_when_needed_resets_generation_state_and_exports_wasm_validate_adapter_delta_plus_apply_adapter_delta browser_adapter_sidecar: checked_tiny_f32_q8_q4_self_adp1_sidecar_routes_in_static_app_fetch_local_models_tiny_test_model_self_adp1_tiny_test_model_q8_self_adp1_and_tiny_test_model_q4_self_adp1_recompute_selected_adp1_artifact_checksum_before_wasm_transfer_call_apply_adapter_delta_and_browser_smoke_verifies_adapter_applied_matching_quantization_state_reset_checksum_mismatch_rejection_and_local_only_requests browser_registry_adapter_family: browser_multi_parent_bundle_generates_multi_parent_sign_merge_f32_q8_and_q4_self_adp1_family_adp1_sparse_asp1_and_low_rank_alr1_sidecars_manifests_adapter_family_receipts_with_preferred_adapter_index_path_manifest_fields_and_assembly_receipts_records_legacy_first_route_indexed_adapter_family_fields_adapter_family_receipt_fields_explicit_adapter_auto_apply_fields_adapter_auto_apply_byte_budget_1048576_and_assembly_receipt_fields_in_selector_registry_app_js_fetches_and_checksum_verifies_the_served_assembly_receipt_and_receipt_referenced_evidence_files_after_model_manifest_load_fetches_and_checksum_verifies_the_adapter_family_receipt_plus_served_route_derived_adp1_asp1_alr1_adapter_manifests_with_artifact_byte_counts_before_enabling_family_options_defaults_to_the_receipt_preferred_sparse_asp1_member_prefetches_and_verifies_the_declared_adp1_asp1_alr1_auto_stack_then_calls_rust_validate_adapter_delta_for_each_member_before_rust_apply_when_the_registry_strategy_is_receipt_preferred_compatible_and_the_adapter_bytes_fit_the_family_budget_and_browser_smoke_adapter_sidecar_registry_file_requires_the_assembly_receipt_evidence_file_adapter_receipt_manifest_and_auto_stack_artifact_requests_before_pre_generation_validate_then_apply browser_text_sidecar_budgets: app_js_checks_selector_registry_text_256kib_manifest_text_64kib_receipt_text_128kib_and_evidence_text_128kib_before_decoding_or_parsing_generated_sidecars_browser_smoke_adapter_manifest_budget_proves_oversized_sparse_manifest_blocks_artifact_fetch_and_apply_while_model_and_assembly_remain_ready_and_selector_registries_now_declare_exact_selector_registry_manifest_receipt_and_evidence_text_budget_contract_fields_required_by_rust_validation_and_browser_registry_intake browser_runtime_wasm_manifest: app_js_fetches_runtime_tinyrustlm_wasm_manifest_validates_runtime_kind_status_path_byte_count_checksum_and_next_gate_recomputes_fetched_wasm_checksum_before_webassembly_instantiate_slm_pack_writes_manifests_for_generated_browser_roots_and_build_helper_refreshes_checked_runtime_manifest_after_wasm_copy browser_adapter_stack: generated_adapter_family_receipts_declare_ordered_auto_apply_stack_members_selector_registries_carry_adapter_auto_apply_stack_status_strategy_count_fields_app_js_verifies_receipt_stack_indexes_paths_manifest_paths_and_aggregate_manifest_declared_adapter_bytes_then_prefetches_checksum_checks_validates_with_rust_and_transfers_family_adp1_plus_sparse_asp1_plus_low_rank_alr1_before_generation_with_rust_validating_each_package_before_apply browser_module_plan: generated_selector_entries_declare_module_plan_route_checksum_status_kind_strategy_profile_execution_profile_fetch_policy_origin_policy_fetch_count_limit_planned_fetch_count_route_set_checksum_algorithm_route_set_version_route_set_checksum_tokenizer_checksum_sampler_candidate_cap_wasm_memory_initial_pages_resource_class_model_byte_budget_adapter_byte_budget_adapter_stack_byte_budget_runtime_scratch_byte_budget_output_byte_limit_kv_cache_byte_budget_kv_cache_page_count_total_byte_budget_module_count_module_byte_count_fields_module_checksum_fields_module_role_fields_module_phase_fields_module_dependency_fields_and_module_assembly_slot_fields_generated_bundles_write_served_module_plan_receipts_for_f32_q8_q4_and_all_roots_app_js_checksum_verifies_the_browser_constrained_v1_profile_single_threaded_wasm_local_v1_execution_profile_local_no_store_v1_fetch_policy_same_origin_loopback_local_v1_origin_policy_fetch_count_limit_32_planned_fetch_count_21_route_set_checksum_algorithm_tinyrustlm_text_checksum_v1_route_set_version_1_route_set_checksum_tokenizer_identity_sampler_candidate_cap_1024_pre_init_wasm_page_envelope_resource_envelope_runtime_scratch_envelope_output_cap_total_self_assembly_envelope_plan_graph_module_byte_counts_module_checksums_module_roles_module_phases_module_dependencies_module_assembly_slots_and_stack_members_against_model_manifest_assembly_receipt_adapter_family_receipt_adapter_manifest_artifact_bytes_and_artifact_checksums_before_fetching_generated_slm_or_stack_artifact_bytes_and_renders_verified_receipt_fields_in_the_module_plan_panel_including_visible_execution_fetch_origin_fetch_limit_plan_fetches_route_hash_route_version_route_set_tokenizer_sampler_cap_wasm_pages_model_adapter_stack_scratch_output_kv_total_byte_budgets_ordered_byte_summary_ordered_checksum_summary_ordered_slot_summary_ordered_role_summary_ordered_phase_summary_and_ordered_dependency_summary_browser_smoke_module_plan_profile_drift_module_plan_execution_profile_drift_module_plan_fetch_policy_drift_module_plan_origin_policy_drift_module_plan_fetch_count_drift_module_plan_planned_fetch_count_drift_module_plan_route_set_algorithm_drift_module_plan_route_set_version_drift_module_plan_route_set_drift_module_plan_tokenizer_drift_module_plan_sampler_cap_drift_module_plan_wasm_memory_drift_module_plan_runtime_scratch_drift_module_plan_output_limit_drift_module_plan_kv_cache_drift_module_plan_adapter_stack_budget_drift_module_plan_total_budget_drift_module_plan_resource_drift_module_plan_graph_drift_module_plan_stack_drift_module_plan_role_drift_module_plan_slot_drift_module_plan_phase_drift_module_plan_dependency_drift_module_plan_byte_drift_and_module_plan_checksum_drift_prove_checksum_consistent_receipt_drift_stops_before_generated_slm_or_stack_artifact_fetch browser_module_plan_total_budget: verified_for_generated_module_plan_total_byte_budget_fields_covering_model_bytes_manifest_text_assembly_receipt_text_adapter_family_receipt_text_ordered_stack_artifact_bytes_and_runtime_scratch_budget_with_browser_pre_model_fetch_total_validation_total_budget_display_combined_selector_assembly_exact_q4_q8_f32_totals_and_module_plan_total_budget_drift_no_slm_or_stack_artifact_fetch_smoke browser_module_plan_total_limit: verified_for_generated_module_plan_total_byte_budget_limit_43454464_fields_in_selector_registry_and_served_receipts_with_browser_pre_model_fetch_cap_validation_Total_Limit_display_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_total_limit_drift_no_slm_or_stack_artifact_fetch_smoke browser_module_plan_route_set_algorithm: verified_for_generated_module_plan_route_set_checksum_algorithm_tinyrustlm_text_checksum_v1_fields_with_Route_Hash_display_checksum_preimage_algorithm_binding_source_fallback_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_route_set_algorithm_drift browser_module_plan_operator_receipt: verified_for_generated_module_plan_operator_receipt_path_and_checksum_fields_with_selector_receipt_assembly_receipt_and_fetched_sign_merge_operator_agreement_q4_positive_generated_root_smoke_and_module_plan_operator_receipt_drift browser_module_plan_prompt_limit: verified_for_generated_module_plan_prompt_byte_limit_4096_fields_in_selector_registry_and_served_receipts_with_browser_pre_model_fetch_validation_Prompt_Limit_display_source_prompt_limit_smoke_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_prompt_limit_drift browser_module_plan_wasm_memory: verified_for_generated_module_plan_wasm_memory_initial_pages_17_fields_covering_the_runtime_wasm_exported_linear_memory_size_before_init_runtime_growth_with_browser_pre_model_fetch_validation_wasm_pages_display_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_wasm_memory_drift_no_slm_or_stack_artifact_fetch_smoke browser_module_plan_wasm_heap: verified_for_generated_module_plan_wasm_heap_min_bytes_65536_fields_covering_browser_alloc_dealloc_probe_before_generated_model_fetch_Heap_Floor_display_combined_selector_cycle_q4_q8_f32_assertions_source_ui_audit_fallback_and_module_plan_wasm_heap_drift browser_module_plan_wasm_transfer: verified_for_generated_module_plan_wasm_transfer_strategy_copy_then_release_v1_fields_covering_browser_copy_to_wasm_then_release_discipline_with_Transfer_display_combined_selector_cycle_q4_q8_f32_assertions_source_ui_audit_fallback_and_module_plan_wasm_transfer_drift browser_module_plan_model_release: verified_for_generated_module_plan_model_release_strategy_free_before_reassembly_v1_fields_covering_free_model_before_post_initial_generated_assembly_with_Release_display_combined_selector_cycle_q4_q8_f32_assertions_source_ui_audit_fallback_and_module_plan_model_release_drift browser_module_plan_runtime_reset: verified_for_generated_module_plan_runtime_reset_strategy_reset_context_before_assembly_v1_fields_covering_reset_context_after_generated_model_load_before_adapter_validation_apply_with_Reset_display_combined_selector_cycle_q4_q8_f32_assertions_source_ui_audit_fallback_and_module_plan_runtime_reset_drift browser_module_plan_adapter_validation: verified_for_generated_module_plan_adapter_validation_strategy_rust_validate_before_apply_v1_fields_covering_validate_adapter_delta_before_apply_adapter_delta_with_Validate_display_combined_selector_assembly_q4_q8_f32_assertions_source_ui_audit_fallback_and_module_plan_adapter_validation_drift browser_module_plan_adapter_validation_count: verified_for_generated_module_plan_adapter_validation_count_3_fields_covering_selector_receipt_adapter_family_stack_count_agreement_with_Validate_Count_display_exact_three_Rust_validate_adapter_delta_calls_per_generated_assembly_step_source_fallback_and_module_plan_adapter_validation_count_drift browser_module_plan_adapter_apply_count: verified_for_generated_module_plan_adapter_apply_count_3_fields_covering_ADP1_ASP1_ALR1_stack_cardinality_with_Apply_Count_display_adapter_family_stack_count_binding_runtime_adapter_apply_count_diagnostics_check_source_fallback_and_module_plan_adapter_apply_count_drift browser_module_plan_actual_fetch_count: verified_for_browser_owned_generated_self_assembly_route_accounting_with_Actual_Fetches_display_planned_21_vs_actual_21_readiness_gate_source_fallback_and_combined_selector_assembly_q4_q8_f32_assertions browser_module_plan_observed_route_set: verified_for_browser_observed_generated_self_assembly_route_set_checksums_with_Actual_Route_Set_display_observed_equals_declared_ready_gate_source_fallback_and_combined_selector_assembly_q4_q8_f32_assertions browser_module_plan_actual_module_bytes: verified_for_browser_observed_generated_self_assembly_module_bytes_with_Actual_Module_Bytes_display_q4_37238_q8_39478_f32_51012_ready_gate_source_fallback_and_combined_selector_assembly_assertions browser_module_plan_actual_module_checksums: verified_for_browser_observed_generated_self_assembly_module_checksums_with_Actual_Module_Checksums_display_declared_equals_actual_ready_gate_source_fallback_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_payload_checksum_drift_before_generated_routes browser_module_plan_kv_cache: verified_for_generated_module_plan_kv_cache_byte_budget_1024_and_page_count_1_fields_with_runtime_diagnostics_KV_Budget_KV_Pages_display_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_kv_cache_drift browser_module_plan_output_limit: verified_for_generated_module_plan_output_byte_limit_65536_fields_with_Output_Limit_display_total_budget_inclusion_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_output_limit_drift browser_module_plan_adapter_stack_budget: verified_for_generated_module_plan_adapter_stack_byte_budget_22144_fields_covering_exact_ADP1_ASP1_ALR1_stack_payload_bytes_with_Stack_Budget_display_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_adapter_stack_budget_drift browser_module_plan_tokenizer: verified_for_generated_module_plan_tokenizer_checksum_fields_covering_admitted_tokenizer_identity_with_Tokenizer_display_combined_selector_assembly_q4_q8_f32_assertions_genome_species_checksum_binding_and_module_plan_tokenizer_drift browser_module_plan_sampler_cap: verified_for_generated_module_plan_sampler_candidate_cap_1024_fields_covering_fixed_buffer_sampling_envelope_with_Sampler_Cap_display_Top_K_clamping_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_sampler_cap_drift browser_module_plan_fetch_count: verified_for_generated_module_plan_fetch_count_limit_32_fields_covering_browser_self_assembly_route_count_actual_governed_request_counting_with_Fetch_Limit_display_combined_selector_cycle_reload_soak_q4_q8_f32_assertions_and_module_plan_fetch_count_drift browser_module_plan_wasm_export_set: verified_for_generated_module_plan_wasm_export_set_tinyrustlm_generate_v1_fields_covering_instantiated_memory_alloc_dealloc_init_runtime_load_model_generate_sampling_step_diagnostics_reset_adapter_validate_apply_and_free_model_exports_with_WASM_ABI_display_combined_selector_assembly_q4_q8_f32_assertions_and_module_plan_wasm_export_set_drift browser_module_plan_count_drift: verified_for_checksum_consistent_receipt_module_count_drift_with_selector_module_plan_checksum_refresh_and_no_generated_slm_adapter_family_adapter_manifest_or_stack_artifact_fetch browser_module_plan_dependencies: generated_module_plan_receipts_declare_module_depends_on_fields_from_runtime_wasm_through_model_manifest_assembly_adapter_family_and_stack_members_app_js_verifies_the_dependency_chain_before_generated_slm_fetch_and_renders_ordered_dependency_summary_browser_smoke_module_plan_dependency_drift_proves_checksum_consistent_dependency_drift_stops_before_generated_slm_or_stack_artifact_fetch browser_module_plan_phases: generated_module_plan_receipts_declare_module_phase_fields_for_load_model_bytes_verify_model_manifest_verify_assembly_evidence_verify_adapter_family_and_ordered_apply_adapter_stack_members_app_js_verifies_phase_values_before_generated_slm_fetch_and_renders_ordered_phase_summary_browser_smoke_module_plan_phase_drift_proves_checksum_consistent_phase_drift_stops_before_generated_slm_or_stack_artifact_fetch browser_module_plan_byte_counts: generated_module_plan_receipts_declare_module_byte_count_fields_for_model_bytes_manifest_text_assembly_receipt_text_adapter_family_receipt_text_and_ordered_stack_artifacts_app_js_verifies_byte_counts_before_generated_model_or_stack_artifact_work_and_renders_ordered_byte_summary_browser_smoke_module_plan_byte_drift_proves_checksum_consistent_byte_drift_stops_before_generated_slm_or_stack_artifact_fetch browser_module_plan_checksums: generated_module_plan_receipts_declare_uniform_module_checksum_fields_for_model_manifest_assembly_receipt_adapter_family_receipt_and_ordered_stack_artifacts_app_js_verifies_checksums_before_generated_model_or_stack_artifact_work_and_renders_ordered_checksum_summary_browser_smoke_module_plan_checksum_drift_proves_checksum_consistent_checksum_drift_stops_before_generated_slm_or_stack_artifact_fetch browser_combined_selector_assembly: browser_smoke_combined_selector_assembly_verifies_one_generated_all_root_defaults_to_q4_then_switches_q4_q8_f32_entries_with_each_module_plan_requested_before_model_bytes_and_each_family_adp1_plus_sparse_asp1_plus_low_rank_alr1_stack_validated_and_auto_applied_before_generation browser_combined_selector_cycle: browser_smoke_combined_selector_cycle_verifies_one_generated_all_root_repeats_q4_q8_f32_entry_switching_twice_with_free_model_release_before_each_post_initial_assembly_plus_fresh_stack_validation_apply_completion_reset_diagnostics_and_generation_each_pass browser_combined_selector_route_soak: browser_smoke_combined_selector_route_soak_verifies_one_generated_all_root_runs_three_q4_q8_f32_cycles_with_no_store_local_fetches_and_requires_each_module_plan_model_manifest_assembly_evidence_adapter_family_adapter_manifest_and_stack_artifact_route_once_per_pass browser_combined_selector_extended_route_soak: browser_smoke_combined_selector_route_extended_soak_verifies_one_generated_all_root_runs_five_q4_q8_f32_cycles_with_fifteen_assemblies_fresh_route_requests_release_before_reassembly_rust_stack_validate_apply_wasm_pages_17_and_path_flexible_total_budgets browser_combined_selector_reload_soak: browser_smoke_combined_selector_reload_soak_verifies_one_generated_all_root_rebuilds_q4_q8_f32_self_assembly_across_two_fresh_page_lifetimes_with_q4_default_boot_selection_and_repeated_runtime_registry_module_plan_model_manifest_evidence_adapter_and_stack_routes browser_runtime_assembly_diagnostics: runtime_diagnostics_report_adapter_apply_count_last_adapter_checksum_and_assembly_state_checksum_with_model_load_nonzero_state_manual_sidecar_count_1_generated_stack_count_3_and_free_clearing_state browser_assembly_trace: app_js_records_browser_owned_module_plan_trace_checkpoints_for_generated_roots_from_plan_verified_through_model_accepted_manifest_verified_assembly_evidence_verified_adapter_family_verified_adapter_stack_applied_and_ready_and_browser_smoke_asserts_the_exact_trace_for_q4_q8_f32_combined_selector_assembly browser_eval_case_evidence_checksum: eval_case_evidence_checksum_is_written_from_passed_eval_sidecars_into_selector_and_multi_parent_admissions_promotion_ledgers_selector_registries_generated_assembly_receipts_and_model_provenance_then_checked_by_combined_selector_assembly_for_q4_q8_f32_generated_entries browser_selector_genome_fitness: generated_selector_registries_now_carry_deterministic_genome_id_genome_strategy_genome_lineage_checksum_and_eval_bound_fitness_vector_checksum_fields_app_js_requires_them_for_registry_entries_and_model_provenance_renders_genome_fitness_rows_checked_by_combined_selector_assembly_for_q4_q8_f32_generated_entries browser_selector_species_fit: generated_selector_registries_now_carry_deterministic_species_id_species_strategy_species_fit_status_and_browser_fit_checksum_fields_app_js_requires_them_for_registry_entries_and_model_provenance_renders_species_rows_checked_by_combined_selector_assembly_for_q4_q8_f32_generated_entries browser_selector_novelty: generated_selector_registries_now_carry_deterministic_novelty_id_novelty_strategy_novelty_status_and_behavior_sketch_checksum_fields_app_js_requires_them_for_registry_entries_and_model_provenance_renders_novelty_rows_checked_by_combined_selector_assembly_for_q4_q8_f32_generated_entries browser_selector_population: generated_selector_registries_now_carry_deterministic_population_id_population_strategy_population_status_and_population_review_checksum_fields_app_js_requires_them_for_registry_entries_and_model_provenance_renders_population_rows_checked_by_combined_selector_assembly_for_q4_q8_f32_generated_entries browser_selector_mate_selection: generated_selector_registries_now_carry_deterministic_mate_selection_id_strategy_status_parent_count_and_parent_pool_bound_checksum_fields_app_js_requires_them_for_registry_entries_and_model_provenance_renders_mate_selection_rows_checked_by_combined_selector_assembly_for_q4_q8_f32_generated_entries browser_selector_phenotype_evidence: generated_selector_registries_now_carry_deterministic_phenotype_evidence_id_strategy_status_provenance_manifest_checksum_and_runtime_eval_bound_checksum_fields_app_js_requires_them_for_registry_entries_and_model_provenance_renders_phenotype_rows_checked_by_combined_selector_assembly_for_q4_q8_f32_generated_entries browser_selector_heritable_artifact: generated_selector_registries_now_carry_deterministic_heritable_artifact_id_strategy_status_and_served_artifact_bound_checksum_fields_app_js_requires_them_for_registry_entries_and_model_provenance_renders_artifact_rows_checked_by_combined_selector_assembly_for_q4_q8_f32_generated_entries browser_assembly_eval_case_drift: app_js_releases_loaded_generated_model_state_and_stops_before_evidence_adapter_family_adapter_manifest_and_adapter_stack_routes_when_assembly_receipt_eval_case_checksum_differs_from_selector_eval_digest browser_assembly_evidence_file_drift: browser_smoke_mutates_one_fetched_assembly_evidence_file_body_while_selector_module_plan_model_manifest_and_assembly_receipt_bytes_remain_valid_then_app_js_releases_loaded_model_state_before_later_evidence_or_adapter_routes browser_adapter_manifest_drift: browser_smoke_mutates_the_generated_family_adp1_manifest_body_after_adapter_family_receipt_verification_then_stops_before_sparse_low_rank_manifest_routes_or_adp1_asp1_alr1_stack_artifacts_while_preserving_loaded_model_state browser_adapter_artifact_drift: browser_smoke_mutates_the_generated_family_adp1_artifact_body_after_all_adapter_manifests_verify_then_stops_before_sparse_low_rank_artifact_routes_or_apply_adapter_delta_while_preserving_loaded_model_state browser_adapter_stack_prefetch_drift: browser_smoke_mutates_the_generated_sparse_asp1_artifact_body_after_family_adp1_fetch_then_stops_before_low_rank_alr1_artifact_route_or_apply_adapter_delta_while_preserving_loaded_model_state browser_adapter_stack_rust_validate: browser_smoke_verifies_generated_q4_q8_f32_auto_stack_calls_validate_adapter_delta_for_family_adp1_sparse_asp1_and_low_rank_alr1_before_latest_apply_adapter_delta_call browser_adapter_stack_rust_validate_drift: browser_smoke_keeps_selector_module_plan_assembly_adapter_family_manifest_and_artifact_checksums_aligned_while_family_adp1_identity_drifts_then_requires_validate_adapter_delta_shape_mismatch_before_any_apply_adapter_delta slm_candidate_artifact: no_crate_tinyrustlm_slm_pack_candidate_manifest_and_validate_candidate_commands_bind_validated_lineage_to_validated_candidate_slm_artifacts_with_lineage_checksum_candidate_checksum_shape_tokenizer_checksum_tensor_layout_checksum_direct_parent_contract_optional_operator_receipt_checksum_operator_identity_candidate_bytes_candidate_checksum_binding_pending_eval_status_and_next_promotion_gate slm_candidate_promotion: no_crate_tinyrustlm_slm_pack_promotion_template_and_validate_promotion_commands_bind_candidate_manifest_checksums_to_pending_runtime_smoke_eval_selector_and_public_claim_statuses_before_browser_admission slm_runtime_smoke_sidecar: no_crate_tinyrustlm_slm_pack_runtime_smoke_and_validate_runtime_smoke_commands_bind_provenance_manifest_checksum_slm_checksum_source_kind_model_shape_and_runtime_smoke_decision slm_selector_admission: no_crate_tinyrustlm_slm_pack_admission_record_and_validate_admission_commands_bind_promotion_runtime_smoke_and_passed_converted_trained_eval_sidecars_before_selector_registry_routing slm_promotion_ledger: no_crate_tinyrustlm_slm_pack_promotion_ledger_and_validate_promotion_ledger_commands_bind_validated_admission_records_to_hash_chained_promotion_history_with_duplicate_candidate_and_duplicate_artifact_rejection_before_selector_or_population_review slm_population_review: no_crate_tinyrustlm_slm_pack_population_review_and_validate_population_review_commands_recompute_ledger_backed_admission_rankings_frontier_selection_parent_pool_routes_fitness_scores_weighted_quality_frugality_quantization_objective_vector_metadata_and_per_entry_objective_checksums slm_parent_pool_recipe: no_crate_tinyrustlm_slm_pack_parent_pool_recipe_and_validate_parent_pool_recipe_commands_validate_population_reviews_require_shared_direct_parameter_contracts_and_recompute_fitness_normalized_seed_weights_relatedness_metric_scope_pair_count_status_checksum_per_parent_relatedness_groups_and_checksum_bound_sign_merge_plus_soup_evolution_schedule_fields_before_multi_parent_consumers slm_sign_merge_operator: no_crate_tinyrustlm_slm_pack_sign_merge_candidate_and_validate_sign_merge_candidate_commands_validate_parent_pool_recipe_ledger_review_admissions_and_parent_slm_files_then_write_seed_weighted_sign_consensus_slm_candidates_with_recomputable_receipts_that_echo_parent_relatedness_before_multi_parent_candidate_manifest slm_multi_parent_candidate_manifest: no_crate_tinyrustlm_slm_pack_multi_parent_candidate_manifest_and_validate_multi_parent_candidate_commands_dispatch_parent_pool_operator_kind_validate_sign_merge_or_soup_receipts_preserve_operator_specific_metrics_then_bind_receipt_checksum_parent_pool_recipe_checksum_relatedness_summary_parent_summaries_candidate_slm_fields_pending_eval_status_and_next_promotion_route slm_multi_parent_promotion: no_crate_tinyrustlm_slm_pack_multi_parent_promotion_template_and_validate_multi_parent_promotion_commands_validate_multi_parent_candidate_manifests_then_bind_candidate_manifest_checksum_operator_receipt_checksum_recipe_checksum_parent_count_candidate_slm_fields_pending_runtime_smoke_eval_status_and_not_admitted_selector_state slm_multi_parent_admission: no_crate_tinyrustlm_slm_pack_multi_parent_admission_record_and_validate_multi_parent_admission_commands_validate_multi_parent_promotion_templates_runtime_smoke_provenance_and_passed_eval_sidecars_then_bind_parent_pool_candidate_and_evidence_checksums_for_selector_registry_routing slm_selector_registry: no_crate_tinyrustlm_slm_pack_selector_registry_and_validate_selector_registry_commands_bind_validated_selector_admission_records_and_multi_parent_admission_records_to_served_browser_safe_models_routes_with_browser_frugal_quantized_default_metadata_selector_model_byte_budget_33554432_contract_selector_registry_text_byte_budget_262144_manifest_text_byte_budget_65536_receipt_text_byte_budget_131072_evidence_text_byte_budget_131072_contract_selector_genome_species_novelty_population_mate_selection_optional_operator_receipt_and_fitness_metadata_optional_f32_q8_q4_adapter_sidecar_fields_indexed_adapter_family_fields_receipt_fields_explicit_adapter_auto_apply_fields_adapter_auto_apply_byte_budget_1048576_and_module_plan_resource_envelope_fields_for_generated_bundles_with_apply_status_matching_entry_quantization slm_browser_multi_parent_bundle: no_crate_tinyrustlm_slm_pack_browser_multi_parent_bundle_command_accepts_f32_q8_0_q4_0_or_all_and_stages_app_shell_wasm_runtime_runtime_wasm_manifest_matching_multi_parent_sign_merge_model_manifest_selector_registry_with_q4_default_metadata_selector_model_byte_budget_text_sidecar_budget_contract_fields_genome_species_novelty_population_fitness_metadata_auto_apply_fields_adapter_auto_apply_byte_budget_1048576_module_plan_receipt_with_resource_class_model_byte_budget_and_adapter_byte_budget_self_adp1_family_adp1_sparse_asp1_sidecars_adapter_manifests_adapter_family_receipt_with_preferred_sparse_member_assembly_receipt_and_evidence_chain_under_single_quant_roots_or_one_combined_f32_q8_q4_root_for_file_backed_browser_smoke slm_trained_source_conversion: raw_f32_source_manifest_layout_validates_safe_paths_checksums_exact_shapes_finite_bounded_nonzero_weights_tied_output_shape_agreement_output_weight_omission_for_tied_sources_and_converts_untied_and_tied_tiny_source_fixtures_to_f32_q8_q4_converted_trained_slm_artifacts_with_manifests slm_eval_runner: native_tinyrustlm_eval_executes_scoped_fixture_cases_against_converted_f32_q8_q4_slm_artifacts_rejects_zero_case_or_stray_case_eval_files_and_generates_case_ledger_sidecars_that_pass_assistant_quality_gate_only_for_tiny_converted_source_fixture_scope rust_local_server: no_crate_static_server_serves_app_wasm_slm_and_manifest_routes_over_loopback_with_get_head_content_length_percent_decode_and_traversal_rejection rust_mini_browser_harness: no_crate_contract_harness_verifies_static_app_ui_ids_local_only_markers_js_wasm_boundary_calls_rust_wasm_export_definitions_model_manifest_routes_and_loopback_content_types direct_q8_matvec: implemented_for_named_model_matrix_dispatch direct_q4_matvec: implemented_for_named_model_matrix_dispatch model_tensor_routing: model_load_pre_resolves_top_level_and_layer_tensor_indices_generation_uses_indices_without_per_token_layer_name_formatting tied_output_projection: artifact_backed_tiny_tied_slm_fixture_omits_output_weight_sets_v1_flag_routes_projection_to_tok_embeddings_and_has_positive_and_negative_validation_tests quantized_decoded_shadow_storage: removed_for_q8_q4_runtime_tensors; quantized_tensor_f32_borrow_rejected_and_copy_to_runtime_owned_reusable_f32_buffers_verified reusable_generation_buffers: runtime_allocates_forward_scratch_and_logits_on_model_load_reuses_them_across_generate_and_generate_next_token_and_top_k_diagnostics_scan_without_vocab_sized_candidate_vec fixed_buffer_stochastic_sampling: temperature_top_k_top_p_seed_sampling_scans_logits_into_fixed_1024_candidate_buffers_accepts_bpe_top_k_262_and_rejects_oversized_top_k_without_vocab_sized_candidate_vec context_boundary_state: generation_accepts_last_prompt_slot_rejects_full_context_prompt_clears_failed_request_state_and_extends_token_state_with_generated_tokens output_buffer_boundary: generated_result_decode_capped_at_64_kib_byte_and_bpe_decode_return_output_buffer_exceeded_before_replacing_last_result_full_generate_failures_clear_stale_generation_state quantized_fixture_decode: implemented_for_q8_0_and_q4_0_tiny_fixtures greedy_generation: implemented_for_tiny_f32_q8_0_q4_0_fixtures tinylm16_f32_generation: passed_node_wasm_and_headless_browser_smoke tinylm16_q8_generation: passed_node_wasm_and_headless_browser_smoke browser_model_selector: implemented_for_tinylm16_q8_tinylm16_q4_tinylm16_f32_tiny_f32_q8_0_q4_0_tiny_bpe_and_tiny_tied_output_fixtures_with_optional_models_selector_registry_intake_for_admitted_browser_safe_routes_validated_browser_frugal_quantized_defaults_selector_model_byte_budget_contract_browser_served_multi_parent_registry_fixture_smoke_generated_file_backed_multi_parent_sign_merge_f32_q8_q4_bundle_smoke_combined_f32_q8_q4_selector_root_smoke_and_registry_carried_f32_q8_q4_adapter_family_smoke browser_conversation_transcript: implemented_for_local_user_and_tinyrustlm_turns_with_dom_safe_text_rendering_step_token_assistant_turn_extension_reset_context_separate_from_clear_transcript_clear_click_removal_and_headless_browser_assertions browser_step_token_control: implemented_for_context_sensitive_generate_next_token_browser_button_response_append_transcript_append_console_logging_benchmark_update_reset_disable_error_disable_clear_preserve_and_headless_browser_assertions browser_smoke: passed_headless_chrome_tinylm16_q8_default_with_runtime_manifest_request_runtime_manifest_drift_before_model_fetch_module_plan_profile_drift_module_plan_execution_profile_drift_module_plan_fetch_policy_drift_module_plan_fetch_count_drift_module_plan_runtime_scratch_drift_module_plan_sampler_cap_drift_module_plan_resource_drift_module_plan_graph_drift_module_plan_stack_drift_module_plan_role_drift_module_plan_slot_drift_module_plan_phase_drift_module_plan_dependency_drift_module_plan_byte_drift_and_module_plan_checksum_drift_before_generated_slm_or_stack_artifact_fetch_assembly_eval_case_drift_assembly_evidence_file_drift_adapter_family_receipt_drift_adapter_manifest_drift_adapter_artifact_drift_adapter_stack_prefetch_drift_and_adapter_stack_rust_validate_drift_before_later_stack_artifacts_or_rust_adapter_apply_module_plan_panel_fallback_generated_receipt_display_visible_execution_fetch_fetch_limit_tokenizer_sampler_cap_model_adapter_scratch_budget_rows_byte_summary_checksum_summary_slot_summary_role_summary_phase_summary_dependency_summary_and_trace_tinylm16_q4_selected_step_token_tinyf32_tinyq8_tinyq4_adapter_sidecar_adapter_sidecar_checksum_mismatch_selector_budget_with_registry_budget_contract_sidecar_budget_contract_adapter_sidecar_registry_file_for_generated_f32_q8_q4_roots_and_one_combined_f32_q8_q4_selector_root_defaulting_to_q4_then_fetching_profile_execution_profile_fetch_policy_fetch_count_sampler_cap_and_runtime_scratch_verified_module_plan_receipt_before_generated_slm_validating_and_applying_family_adp1_plus_sparse_asp1_plus_low_rank_alr1_stack_before_generation_and_rendering_exact_trace_with_adapter_auto_apply_byte_budget_1048576_multi_parent_registry_generated_multi_parent_registry_file_reload_reset_model_switch_loop_malformed_model_context_overflow_missing_model_desktop_mobile_ui_audit_with_model_provenance_conversation_transcript_clear_button_state_endurance_performance_and_performance_soak wasm_abi_smoke: passed_invalid_utf8_null_pointer_invalid_length_zero_generation_length_invalid_sampling_recovery_generate_next_token_f32_adapter_validate_f32_adapter_apply_free_model_and_post_free_model_not_loaded_against_tinylm16_q8_plus_tiny_f32_adapter_base browser_adapter_sidecar_smoke: passed_headless_chrome_tinyf32_tinyq8_and_tinyq4_generate_one_token_then_apply_matching_self_adp1_plus_intercepted_registry_tinyq8_adp1_generated_file_backed_f32_q8_sparse_asp1_routes_and_combined_root_f32_q8_q4_sparse_asp1_routes_selected_by_verified_adapter_family_preference_with_browser_frugal_q4_initial_selection_auto_applied_before_generation_for_generated_registry_routes_with_adapter_auto_apply_byte_budget_1048576_adapter_applied_response_matching_quantization_diagnostics_cleared_token_kv_state_and_local_only_sidecar_request diagnostics_json_escape: runtime_escapes_quotes_backslashes_control_characters_line_separators_and_paragraph_separators_before_browser_json_parse performance_smoke: passed_four_token_q8_q4_browser_benchmark_panel_and_reset_recovery performance_soak: passed_three_cycle_four_token_q8_q4_browser_benchmark_panel_reset_recovery_and_local_only_requests visual_studio_solution: TinyRustLM.sln_build_test_run_wrapper_model_admission_manifest_validation_all_quantization_converted_source_gate_ui_audit_rust_local_server_reuse_browser_harness_and_busy_port_fallback_verified model_breeding_research_memory: report_intake_2026_06_26_preserved_and_synthesized_for_future_candidate_lineage_compatibility_offline_merge_sparse_delta_mask_metadata_population_review_objective_vector_metadata_parent_relatedness_metadata_adapter_delta_sparse_adapter_delta_low_rank_adapter_delta_adapter_fuse_runtime_f32_q8_q4_adapter_apply_population_eval_parent_pool_recipe_sign_merge_multi_parent_manifest_multi_parent_promotion_multi_parent_admission_selector_route_browser_served_multi_parent_registry_smoke_generated_browser_bundle_work_combined_multi_quant_selector_root_browser_frugal_selector_default_browser_selector_byte_budget_contract_browser_text_sidecar_budget_contract_registry_carried_adapter_family_routing_browser_sparse_asp1_route_browser_auto_assembly_browser_auto_assembly_byte_budget_browser_module_plan_receipts_browser_module_plan_role_drift_browser_module_plan_slot_drift_browser_module_plan_phase_drift_browser_module_plan_dependency_drift_browser_module_plan_byte_drift_browser_module_plan_checksum_drift_browser_verified_adapter_family_receipts_and_manifests_and_browser_verified_assembly_receipts_with_evidence_file_fetches; source_gates_now_implemented_as_slm_parent_compatibility_report_candidate_lineage_template_blend_operator_receipt_task_delta_operator_receipt_sparse_delta_operator_receipt_with_retention_and_mask_checksum_crossover_operator_receipt_mutation_operator_receipt_prune_operator_receipt_dare_operator_receipt_with_dropout_rescaled_delta_checksums_operator_receipt_bound_candidate_artifact_manifest_population_review_with_objective_vector_checksums_parent_pool_recipe_with_relatedness_checksum_sign_merge_receipt_with_relatedness_echo_multi_parent_candidate_manifest_with_relatedness_summary_adapter_delta_artifact_manifest_sparse_adapter_delta_artifact_manifest_low_rank_adapter_delta_artifact_manifest_adapter_fuse_receipt_runtime_f32_q8_q4_adp1_asp1_alr1_apply_candidate_artifact_manifest_multi_parent_candidate_manifest_promotion_template_multi_parent_promotion_template_multi_parent_admission_record_runtime_smoke_sidecar_selector_admission_promotion_ledger_population_review_parent_pool_recipe_sign_merge_receipt_selector_registry_browser_multi_parent_bundle_combined_multi_quant_selector_root_browser_frugal_selector_default_browser_selector_byte_budget_contract_browser_text_sidecar_budget_contract_registry_adapter_family_smoke_browser_sparse_asp1_smoke_browser_auto_assembly_browser_auto_assembly_byte_budget_browser_module_plan_receipts_browser_module_plan_role_drift_browser_module_plan_slot_drift_browser_module_plan_phase_drift_browser_module_plan_dependency_drift_browser_module_plan_byte_drift_browser_module_plan_checksum_drift_browser_verified_adapter_family_receipt_manifest_module_and_browser_verified_assembly_receipt_evidence_file_module modelbreeder_zero_dependency_research_memory: report_intake_2026_06_28_preserved_and_synthesized_for_genome_fitness_vector_novelty_population_speciation_public_voice_zero_dependency_wasm_simd_hierarchical_quantization_adapter_tokenizer_sampler_kv_cache_allocator_multimodal_and_telemetry_future_lanes; KV_cache_lane_now_implemented_as_runtime_byte_page_diagnostics_selector_receipt_fields_Module_Plan_rows_and_drift_smoke; sampler_lane_now_bound_as_module_plan_sampler_candidate_cap_1024_with_UI_and_drift_smoke public_rust_doc_gate: workspace_missing_docs_denied_and_runtime_slm_pack_local_server_browser_harness_strict_rustdoc_verified static_server: rust_local_server_streams_files_supports_head_requests_and_keeps_node_server_as_fallback_tooling cargo_tests: passed_277_checks wasm_artifact: tinyrustlm/runtime/tinyrustlm.wasm wasm_artifact_sha256: 9416CB0169CF8A9F61D7F12BD531D43FA887A29F95CC8E6871AF4C3E33BCD6C3 wasm_manifest_artifact: tinyrustlm/runtime/tinyrustlm.wasm.manifest wasm_manifest_bytes: 264 wasm_manifest_sha256: E9A1CD14425FCA92FCE26CBF3240BFF9F19D35BFE34E1D60F4FE667BF97E1BF3 wasm_manifest_runtime_checksum: 0xb91a94b0e82f73c0 slm_model_artifact: tinyrustlm/models/tiny-test-model.slm slm_model_artifact_sha256: 17D79EE766578729D2B69090547E819E011D76115519514E19AC3754DE610A1A slm_model_q8_artifact: tinyrustlm/models/tiny-test-model-q8.slm slm_model_q8_artifact_sha256: 6AF985853325EAA6D3EAAA8AADD3511DA9596EB542FB2D03A9BC9DC1F4377ADF slm_model_q4_artifact: tinyrustlm/models/tiny-test-model-q4.slm slm_model_q4_artifact_sha256: 4004E2152F0B6382C6043A15084DE6DC4AE6AE6B6C5BA43ABDE8812ED0174CF6 slm_model_bpe_artifact: tinyrustlm/models/tiny-test-model-bpe.slm slm_model_bpe_artifact_sha256: 31B27903C1588A1F246281DEF8027094C0D3862635FA7D3761AA1327471F3E82 slm_model_bpe_manifest_sha256: AE28DDD62E91834A1F7F6D29BE186CB9EA81A92FAEBC0A5AF3E5A4897DC15B52 slm_tiny_f32_self_adp1_artifact: tinyrustlm/models/tiny-test-model-self.adp1 slm_tiny_f32_self_adp1_artifact_bytes: 20224 slm_tiny_f32_self_adp1_artifact_sha256: DBEEB5875D00958179600C1CB353CA1FAB7604F3D755A5DA905BFFF7F45B8BA8 slm_tiny_f32_self_adp1_manifest: tinyrustlm/models/tiny-test-model-self.adp1.manifest slm_tiny_f32_self_adp1_manifest_bytes: 2004 slm_tiny_f32_self_adp1_manifest_sha256: 78D72C47C6423F4E16E194DBB7F56F055071962FF611CC8C12E971C4C0FB75D0 slm_tiny_q8_self_adp1_artifact: tinyrustlm/models/tiny-test-model-q8-self.adp1 slm_tiny_q8_self_adp1_artifact_bytes: 20224 slm_tiny_q8_self_adp1_artifact_sha256: 7B4E998EFEAC9B9D7BB6F909FC99BC17CA81A905D5C19FA0970A8229BF67E5E8 slm_tiny_q8_self_adp1_manifest: tinyrustlm/models/tiny-test-model-q8-self.adp1.manifest slm_tiny_q8_self_adp1_manifest_bytes: 2026 slm_tiny_q8_self_adp1_manifest_sha256: 5680FD9A8676B818BCE3B90175AE75B574ACFE380B0B374A27ED46EA2C714AEB slm_tiny_q4_self_adp1_artifact: tinyrustlm/models/tiny-test-model-q4-self.adp1 slm_tiny_q4_self_adp1_artifact_bytes: 20224 slm_tiny_q4_self_adp1_artifact_sha256: 9BD044B950E0CED7B8C9785D0ECEB0E175B91861D1C845267BC0D690A0CC9C56 slm_tiny_q4_self_adp1_manifest: tinyrustlm/models/tiny-test-model-q4-self.adp1.manifest slm_tiny_q4_self_adp1_manifest_bytes: 2026 slm_tiny_q4_self_adp1_manifest_sha256: 2060583F1243B373C8E3AEFECA5EFD763F09979E679249B9C087C1EC3DFF1880 slm_model_tied_artifact: tinyrustlm/models/tiny-test-model-tied.slm slm_model_tied_bytes: 11968 slm_model_tied_artifact_sha256: 9D68DC80CD2CCC2366344B92A497629AF1D693350F92B3B0EE383D4B30E08B7C slm_model_tied_manifest_sha256: 469A78D503B010323709EEAF6731DC8AFE05F0DE442BC16BC63F58C636A1490C slm_model_tinylm16_f32_artifact: tinyrustlm/models/tinylm16-f32.slm slm_model_tinylm16_f32_bytes: 68194944 slm_model_tinylm16_f32_artifact_sha256: 70E9765080247FE859506534E87330D73FF50B66B8A48DC627C307069BB0DC5B slm_model_tinylm16_q8_artifact: tinyrustlm/models/tinylm16-q8.slm slm_model_tinylm16_q8_bytes: 17160000 slm_model_tinylm16_q8_artifact_sha256: C3919E6D7244890E9B3C2B5E40C37F8D322467D859C15B8155700F20408DB950 slm_model_tinylm16_q4_artifact: tinyrustlm/models/tinylm16-q4.slm slm_model_tinylm16_q4_bytes: 10657728 slm_model_tinylm16_q4_artifact_sha256: 5AC2BD957113732BE9AB2AADFA2D2EFD54C3131E7E6C97BE424FAC6E72BB365B local_static_server: http://127.0.0.1:8080/app/ public_claim_model_breeding_delta: trained low-rank adapter source validation, source-backed ALR1 conversion, source-backed ALR1 browser routes and source-field contract checks for generated q4_0/q8_0/f32 stacks, f32/q8_0/q4_0 ADP1, ASP1, and ALR1 runtime adapter apply, sparse ASP1 adapter manifests with density/retention/mask fields, low-rank ALR1 manifests with factor/residual fields, checked browser f32/q8_0/q4_0 ADP1 sidecar routes, registry-carried f32/q8_0/q4_0 ADP1/ASP1/ALR1 adapter routes plus browser-fetched checksum-verified receipts and adapter manifests, registry-controlled auto assembly before generation for generated ADP1/ASP1/source-backed ALR1 stacks with `adapter_auto_apply_byte_budget=1048576` and full-stack byte preflight before Rust adapter apply, one combined f32/q8_0/q4_0 generated selector root with served browser smokes for all entries and one same-page combined-selector assembly smoke across q4_0/q8_0/f32, browser-verified module-plan receipts with resource-class, byte-budget, byte-count, checksum, role, phase, dependency, and assembly-slot envelopes before generated `.slm` fetch plus visible budget, byte, checksum, slot, role, phase, dependency, and trace display, browser-verified generated assembly receipts with evidence-file fetches, eval-case evidence checksum matching, and assembly eval-digest drift proof before evidence or adapter routes for file-backed f32/q8_0/q4_0 generated roots, selector registries declaring exact browser text-sidecar budget contract fields, population-review objective-vector metadata, parent-pool relatedness recipes, direct-parameter crossover, bounded mutation, and DARE dropout/rescaled task-delta receipts, sign-merge candidate receipts with relatedness echo fields, multi-parent candidate manifests with relatedness summaries, multi-parent promotion templates, multi-parent admission records, selector route binding, browser-served registry smoke, and generated browser-served multi-parent f32/q8_0/q4_0 bundle routing are verified for validated parent-pool recipes and local model routes. public_claim: TinyRustLM verifies browser-local f32/q8_0/q4_0 tiny and TinyLM-16M smoke generation, runtime WASM manifest verification before browser instantiation, custom BPE and tied-output fixtures, checksum-bearing .slm admission, provenance/runtime-smoke/eval gates, selector-registry intake for selector and multi-parent admission records, browser-served multi-parent registry smoke, self-contained generated browser-served multi-parent f32/q8_0/q4_0 bundle routing with runtime WASM manifests plus browser-verified module-plan resource envelopes, byte-count fields, checksum fields, phase fields, dependency fields, assembly-slot fields, assembly receipts, evidence-file chains, registry-backed eval-case evidence checksums in Model Provenance, and source-backed ALR1 stack members converted from reviewed adapter source templates, one combined generated selector root that defaults to q4_0 then switches among q4_0/q8_0/f32 entries and auto-applies receipt-declared family ADP1 plus sparse ASP1 plus source-backed low-rank ALR1 stacks before generation only after module-plan resource, byte, checksum, slot, role, phase, dependency, and trace checkpoints verify the sequence through ready, `adapter_auto_apply_byte_budget=1048576`, adapter artifact byte checks pass, and the auto stack preflights before Rust adapter apply, selector registries that declare exact browser text-sidecar budgets before generated entry intake, Step Token UI/ABI behavior, f32/q8_0/q4_0 ADP1/ASP1/ALR1 runtime adapter apply with checked browser f32/q8_0/q4_0 ADP1 sidecar checksum verification and registry-carried browser f32/q8_0/q4_0 ADP1/ASP1/ALR1 adapter routes whose served receipts and adapter manifests are fetched and checksum-verified before family options are enabled, served module-plan and adapter-stack smokes for f32/q8_0/q4_0 generated roots, and offline model-breeding beads through compatibility, lineage, blend, task-delta, sparse-delta, crossover, bounded mutation, DARE dropout/rescaled task-delta, trained low-rank adapter source validation, source-backed ALR1 conversion, raw/sparse/low-rank adapter artifacts, promotion, admission, ledger, population-review objective-vector metadata, parent-pool recipe with relatedness checksum, sign-merge receipts with relatedness echo fields, multi-parent candidate manifests with relatedness summaries, multi-parent promotion templates, and multi-parent admission records; trained-model quality remains unclaimed until converted-trained eval evidence passes. ================================================================================ END FILE: workspace.uai ================================================================================