gpu-engine 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +96 -2
  3. package/SPEC.md +988 -0
  4. package/THIRD_PARTY_NOTICES.md +29 -0
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.mjs +4 -0
  7. package/dist/harness.d.mts +132 -0
  8. package/dist/harness.mjs +1 -0
  9. package/dist/index.d.mts +98 -0
  10. package/dist/index.mjs +1 -0
  11. package/dist/load-o_thEAKC.mjs +258 -0
  12. package/dist/scaffold-CY5xhy-V.mjs +106 -0
  13. package/dist/types-BwigqFwr.d.mts +868 -0
  14. package/docs/apps.md +108 -0
  15. package/docs/cli.md +126 -0
  16. package/docs/data.md +101 -0
  17. package/docs/diagnostics.md +509 -0
  18. package/docs/harness.md +191 -0
  19. package/docs/layers.md +249 -0
  20. package/docs/measurements/auto-threshold.json +335 -0
  21. package/docs/measurements/auto-threshold.md +56 -0
  22. package/docs/measurements/real-gpu-2026-11-22.json +4718 -0
  23. package/docs/measurements/real-gpu-2026-11-22.md +75 -0
  24. package/docs/runtime.md +112 -0
  25. package/docs/sealed-test-set.md +107 -0
  26. package/docs/weights-format.md +138 -0
  27. package/llms.txt +24 -0
  28. package/package.json +73 -3
  29. package/skills/gpu-engine/SKILL.md +117 -0
  30. package/templates/common/AGENTS.md +27 -0
  31. package/templates/common/github/workflows/ci.yml +35 -0
  32. package/templates/common/gitignore +3 -0
  33. package/templates/common/package.template.json +27 -0
  34. package/templates/common/tsconfig.template.json +17 -0
  35. package/templates/pooled/NEW_MODEL_NAME.eval.ts +93 -0
  36. package/templates/pooled/NEW_MODEL_NAME.model.ts +11 -0
  37. package/templates/pooled/SPEC.md +31 -0
  38. package/templates/pooled/src/decode.ts +10 -0
  39. package/templates/pooled/src/index.ts +44 -0
  40. package/templates/pooled/src/weights.ts +4 -0
  41. package/templates/retrieve/NEW_MODEL_NAME.eval.ts +149 -0
  42. package/templates/retrieve/NEW_MODEL_NAME.model.ts +12 -0
  43. package/templates/retrieve/SPEC.md +33 -0
  44. package/templates/retrieve/data/table.jsonl +16 -0
  45. package/templates/retrieve/src/decode.ts +9 -0
  46. package/templates/retrieve/src/index.ts +45 -0
  47. package/templates/retrieve/src/table.ts +21 -0
  48. package/templates/retrieve/src/weights.ts +4 -0
  49. package/templates/tag/NEW_MODEL_NAME.eval.ts +114 -0
  50. package/templates/tag/NEW_MODEL_NAME.model.ts +11 -0
  51. package/templates/tag/SPEC.md +31 -0
  52. package/templates/tag/src/decode.ts +25 -0
  53. package/templates/tag/src/index.ts +44 -0
  54. package/templates/tag/src/weights.ts +4 -0
@@ -0,0 +1,106 @@
1
+ import{B as e,C as t,F as n,H as r,I as i,L as a,O as o,P as s,R as c,S as l,T as u,U as d,V as f,_ as p,a as m,b as h,c as g,d as _,f as v,g as y,h as b,i as x,l as S,m as C,n as w,o as T,p as E,r as ee,s as te,u as ne,v as re,w as ie,x as ae,y as oe,z as se}from"./load-o_thEAKC.mjs";import{builtinModules as ce,createRequire as le,stripTypeScriptTypes as ue,syncBuiltinESMExports as de}from"node:module";import{execFile as fe,spawnSync as pe}from"node:child_process";import me,{existsSync as he,readFileSync as ge,realpathSync as _e}from"node:fs";import{appendFile as ve,glob as ye,mkdir as be,readFile as D,readdir as xe,realpath as Se,rename as Ce,rm as we,stat as Te,writeFile as O}from"node:fs/promises";import{basename as k,dirname as A,extname as Ee,isAbsolute as De,join as j,relative as M,resolve as N,sep as P}from"node:path";import{createCipheriv as Oe,createDecipheriv as ke,createHash as Ae,randomBytes as je}from"node:crypto";import*as F from"valibot";import{promisify as Me}from"node:util";import{brotliCompressSync as Ne,constants as Pe}from"node:zlib";import{pathToFileURL as Fe}from"node:url";import{setImmediate as Ie,setTimeout as Le}from"node:timers/promises";import{homedir as Re}from"node:os";const ze={PROJECT_FILE_MISSING:{why:"The folder has no `*.model.ts` or no `*.eval.ts` file.",fix:"Run the command in the model package folder, pass `--dir <path>`, or create the file with `gpu-engine new`."},PROJECT_FILE_AMBIGUOUS:{why:"The folder has more than one `*.model.ts` or more than one `*.eval.ts` file.",fix:"Keep one model file and one eval file per package, or pass `--dir` to the package you mean."},PROJECT_EXPORT_INVALID:{why:"The model or eval file does not default-export the result of `defineModel` or `defineEval`.",fix:"Write `export default defineModel({ ... })` in the model file and `export default defineEval(model, { ... })` in the eval file."},PROJECT_IMPORT_FAILED:{why:`The model or eval file threw while it was imported: a syntax error, a missing import, or code at the top level that fails.`,fix:"Run `node <file>` to see the full error, fix the file, then run the command again."},PROJECT_STATE_INVALID:{why:"A file the harness keeps for itself, `tries.jsonl` or `.gpu-engine/candidate.json`, does not parse or has another shape: a line a killed `loop` left half-written, a hand edit, or a file written by an older version.",fix:"For `tries.jsonl`, restore it from git or delete the broken line; the harness only appends to it. For `.gpu-engine/candidate.json`, run `gpu-engine loop` to write a fresh candidate."},DATA_SET_MISSING:{why:`One of the train, dev or test sets has no files.`,fix:"Add JSONL files to the set folder, or declare a generator in `defineDataset` and run `gpu-engine loop` to write them."},DATA_SET_TOO_SMALL:{why:"A set has fewer examples than `minSize` asks for.",fix:"Add examples or raise the generator count. Lower `minSize` only when the smaller set still measures the model."},DATA_SPLIT_OVERLAP:{why:`The same example, after normalising case and whitespace, appears in two sets, so a score there measures memory.`,fix:`Remove the shared examples from one of the sets. Change the test set only by hand, then delete its lock entry and rerun.`},DATA_GROUP_SHARED:{why:`A declared group appears in more than one set, so the split does not test anything new.`,fix:`Move every example of the group into one set.`},DATA_VOCAB_SHARED:{why:`A declared vocabulary word appears in more than one set, so the model can pass by memorising words.`,fix:"Split the vocabulary so each word belongs to one set, or drop the word from the `vocab` field of those rows when sharing it is intended."},DATA_HASH_CHANGED:{why:"A data file no longer matches the hash recorded in `data.lock.json`.",fix:"Restore the file. If the change is intended, delete that set from `data.lock.json` by hand and rerun to record the new hash."},DATA_GENERATOR_CHANGED:{why:"A train or dev generator no longer writes the file it wrote before. Generators only run into an empty folder, so without this check `loop` would keep training on the old rows and ignore the edit.",fix:"Run `gpu-engine loop --regenerate train` (or `dev`, or `train,dev`) to rewrite the file and its lock entry, or undo the generator change. The test set is never regenerated."},DATA_TEST_READ:{why:"Something other than `promote` read or referenced the sealed test set.",fix:"Remove the reference. Only the `sealed('data/test/...')` call in the eval file may name the test folder, and only `gpu-engine promote` reads it."},DATA_TEST_PRINTED:{why:`A test example or a test-only field was about to be printed or written to a file, or the package code wrote one into a file the promote workflow commits.`,fix:"Report test results as per-set aggregates only. Tries rows hold dev scores only. Never print or write from `metric`, `decode` or a baseline."},BUDGET_BYTES_EXCEEDED:{why:"The Brotli-compressed weights are larger than `budgets.brotliBytes`.",fix:`Shrink the model (hash buckets, layer sizes) or raise the budget.`},GATE_FLOOR_FAILED:{why:`A set scored below the last promoted score minus the gate noise.`,fix:"Keep tuning on dev with `gpu-engine loop` until every set is back above its floor."},GATE_FILE_INVALID:{why:"`gate.json` is not `{ level, promoted }` with `promoted` null or a promoted entry with dev and test scores.",fix:"Restore `gate.json` from history. Only `gpu-engine promote` and `promote --seal` write it."},TRAIN_DIVERGED:{why:`Every checkpoint of a seed holds a weight that is not finite, or scores a dev loss that is not finite: the loss stopped being finite and training never recovered, so there are no weights to keep.`,fix:"Lower `train.learningRate` or raise `train.warmup`, then run `gpu-engine loop` again."},PROMOTE_CANDIDATE_MISSING:{why:`There is no candidate to promote.`,fix:"Run `gpu-engine loop` first. It writes the candidate that `promote` scores."},PROMOTE_CANDIDATE_STALE:{why:`The model definition or the data changed after the candidate was trained.`,fix:"Run `gpu-engine loop` to train a fresh candidate, then promote."},PROMOTE_SCORE_FAILED:{why:"`metric`, `decode` or a baseline threw while `promote` scored a test set, or the package code raised an unhandled promise rejection or an uncaught exception after the read. Its message is not shown, since it can quote a test example.",fix:"Make `metric`, `decode` and the baselines return a value for every input and gold the head can produce and start no promise they leave unhandled, check them on dev with `gpu-engine loop --fail`, then promote again."},PROMOTE_OUTSIDE_CI:{why:"The test set is sealed at level 3, so `promote` only runs in CI.",fix:"Run the `promote` workflow in CI. It holds the key in the `GPU_ENGINE_TEST_KEY` secret."},SEAL_KEY_MISSING:{why:`The test set is encrypted and no key was given.`,fix:"Set `GPU_ENGINE_TEST_KEY` in the CI secret store. The key never goes into the repository."},SEAL_KEY_INVALID:{why:`The key is not 64 hex characters, or it does not decrypt the sealed test set.`,fix:"Set `GPU_ENGINE_TEST_KEY` to the key written by `gpu-engine promote --seal`."},SEAL_REFUSED:{why:"`promote --seal` cannot seal this package: it is already at level 3, a sealed file or `.github/workflows/promote.yml` already exists, or the key path is inside the working tree or names a file that exists.",fix:"Seal once per package. Pass `--key-out` with a new file outside the repository, and move an existing promote workflow aside first."},SEAL_PLAINTEXT_FOUND:{why:`The package is sealed at level 3, but a plaintext test file is in the test folder, where any agent can read it.`,fix:"Delete the plaintext file. The sealed `.enc` file beside it holds the test set, and only the promote workflow in CI decrypts it."},SEAL_LOCK_INVALID:{why:"The test entry of `data.lock.json` does not describe the sealed files: it is missing, names a file that is not sealed, or lacks a `plaintext` hash. A sealed set cannot be fingerprinted again without the key.",fix:"Restore `data.lock.json` and the `.enc` files from the commit that sealed them."},SEAL_GENERATOR_FOUND:{why:"The eval file declares `generate.test`. With that generator and `seed`, anyone who can read the eval file rebuilds the sealed test rows without the key, so level 3 guarantees nothing.",fix:"Remove `test` from `defineDataset({ generate })`, or move the generator to a script outside the package, then seal or run `doctor` again. The test set it already wrote stays."},SEAL_WORKFLOW_MISSING:{why:"The package is sealed at level 3, but `.github/workflows/promote.yml` is missing or does not run `gpu-engine promote` and `gpu-engine promote --scan` with `GPU_ENGINE_TEST_KEY`, so nothing can promote it safely.",fix:"Restore `.github/workflows/promote.yml` from the commit that sealed the test set. A workflow written before `promote --scan` existed: move it aside and run `promote --seal` on a fresh copy, or add the scan step before the commit step by hand."},SEAL_HISTORY_PLAINTEXT:{why:`The test set is sealed now, but git history still holds the plaintext test files, so anyone with a clone can read the rows from an old commit.`,fix:"Purge the plaintext files from every branch (`git filter-repo --invert-paths --path <file>`), force-push and replace every clone, or write a new test set that was never committed in plaintext and seal that. `docs/sealed-test-set.md` shows both."},PROMOTE_SCAN_FAILED:{why:"`data.lock.json` at git `HEAD` (or in the working tree outside git) names no test file, so `promote --scan` has nothing to scan the committed files with. It changed nothing.",fix:"Run `gpu-engine loop` so the data step records the test set in `data.lock.json`, commit the lock, then scan again."},VERIFY_SCORE_CHANGED:{why:"Re-scoring the committed weights on dev does not give the scores in `report.json`.",fix:"Run `gpu-engine promote` again to write a report for these weights. Never edit `report.json` by hand."},VERIFY_WEIGHTS_CHANGED:{why:"The committed weights do not match the hash in `report.json`.",fix:"Restore the promoted weights, or run `gpu-engine promote` again."},VERIFY_FILE_STALE:{why:"A generated file (`MODEL_CARD.md`, `RESULTS.md`, `src/weights.ts`) does not match what the report regenerates.",fix:"Run `gpu-engine promote` again. Never edit generated files by hand."},VERIFY_READS_MISSING:{why:"`reads.jsonl` has fewer test reads than the report counts.",fix:"Restore `reads.jsonl` from history. The read log is append-only."},VERIFY_REPORT_INVALID:{why:"`report.json` is missing or is not the report `gpu-engine promote` writes.",fix:"Run `gpu-engine promote` to write it, or restore it from history. Never edit `report.json` by hand."},PARITY_ADAPTER_MISSING:{why:`No WebGPU adapter was found, so the WGSL output cannot be compared.`,fix:"Install the `webgpu` package in the model package (`npm install --save-dev webgpu@^0.6.2`) and a Vulkan driver (on Linux, `apt-get install mesa-vulkan-drivers` for lavapipe)."},PARITY_DECODE_DIFFERS:{why:`The WGSL and CPU outputs decode to different results on a fixture.`,fix:"Find the layer that diverges with the layer tests in `test/gpu`, and fix its WGSL template."},PARITY_TOLERANCE_EXCEEDED:{why:"The largest logit difference between WGSL and CPU is above `parity.tolerance`.",fix:"Fix the diverging WGSL template. Raise `parity.tolerance` only with a measured reason."},SHIP_SIZE_EXCEEDED:{why:"The built model package, with its weights, is larger than `ship.brotliBytes` after Brotli.",fix:"Shrink the model or the decode code, or raise `ship.brotliBytes`."},SHIP_PACKAGE_INVALID:{why:"The ship checks read what the package ships from `package.json` and `npm pack --dry-run --json`, and one of them is missing, does not parse or failed.",fix:"Run doctor in the model package folder, fix `package.json` until `npm pack --dry-run` lists its files, and check that `npm` is on the PATH."},SHIP_DEPENDENCY_FOUND:{why:"The model package declares a runtime dependency (`dependencies`, `peerDependencies`, `optionalDependencies` or `bundleDependencies`), or a shipped script imports another module. The shipped model must have zero runtime dependencies.",fix:"Move the package to `devDependencies` and bundle what the model needs into the build with `npm run build`."},SHIP_BUILD_STALE:{why:`The package has promoted weights, or a report that records a retrieve table, but no packed file holds those weights or that table, so the build predates the promotion and would ship another model than the one measured.`,fix:"Run `npm run build` (`gpu-engine build`) after `gpu-engine promote` or a table change, then run doctor again."},SHIP_FILE_NOT_ALLOWED:{why:"The packed model package contains a file outside `ship.files`.",fix:"Add the file to `files` in package.json only if it must ship, and list it in `ship.files`; otherwise exclude it."},BUILD_SOURCE_UNSUPPORTED:{why:"`gpu-engine build` bundles static ES module syntax into one module that runs in browsers, and a bundled file uses something it cannot bundle: a dynamic `import()`, an import with attributes, a JSON file, a Node built-in, an absolute path, an import cycle, TypeScript syntax that has no erasable form, an export a `let` or `var` holds (the bundle reads it once), or a top-level `await` (each module runs inside a function); or the declarations it wrote for an exported type would not typecheck.",fix:"Import with a static `import` from a relative path or an installed package, export data from a `.ts` file instead of JSON, export a `const` (or a function that returns the current value), move an `await` into an async function, keep Node-only code out of `src/index.ts` and what it imports, and export the types and symbols an exported type names."},BUILD_IMPORT_UNRESOLVED:{why:"A module that `src/index.ts` reaches imports a file that does not exist or a package that is not installed, or the package exports no ES module entry for that path.",fix:"Check the path, with its `.ts` extension, or run `npm install`."},BUILD_TYPES_FAILED:{why:"`gpu-engine build` writes `dist/index.d.mts` with the TypeScript checker, and TypeScript is not installed, the package has a type error, or an export is a kind the declarations cannot hold (a class, an enum or a namespace).",fix:"Install TypeScript (`npm install --save-dev typescript`), fix what `npx tsc -p .` reports, and export functions, constants, interfaces and type aliases from `src/index.ts`."},NEW_NAME_INVALID:{why:`The model name becomes the package name, the file names and the weights file name, so it must be a lowercase npm package name without a scope.`,fix:"Use lowercase letters, digits and `-`, starting with a letter, at most 64 characters, such as `unit-phrases`."},NEW_TARGET_EXISTS:{why:"`gpu-engine new` writes a fresh package and never overwrites a file, and the target folder already holds files.",fix:"Pick another name, pass `--dir` to create the package somewhere else, or remove the folder first."},CLI_COMMAND_UNKNOWN:{why:"The command is not one of `new`, `loop`, `promote`, `parity`, `inspect`, `doctor` or `build`.",fix:"Run `gpu-engine --help` to see the commands."},CLI_FLAG_INVALID:{why:`A flag is unknown for this command, is missing its value, is given twice, would be ignored, or cannot be combined with another flag given, or a required argument is missing.`,fix:"Run `gpu-engine <command> --help` to see its arguments and flags."}},Be={...d,...ze};function Ve(e){return Object.hasOwn(ze,e)}function He(e){return ze[e]}function I(e,t,n={}){let{why:r,fix:i}=Ve(e)?He(e):d[e];return{code:e,message:t,why:r,fix:i,...n}}function L(e,t,n){return new r(I(e,t,n))}function R(e){let t=e.file===void 0?``:` (${e.file}${e.line===void 0?``:`:${e.line}`})`;return`${e.code}${t}: ${e.message}\n why: ${e.why}\n fix: ${e.fix}`}function Ue(e,t){let n=e.get(t);if(!n)throw Error(`the pool backward pass needs '${t}' in the cache; run forward with a cache first`);return n}function We(e,t,n,r){let i=new Float32Array(n*r);for(let a=0;a<r;a++){let o=(e[a]??0)/n;for(let e=0;e<n;e++)i[e*r+a]=o;let s=t[a]??-1;s>=0&&s<n&&(i[s*r+a]=o+(e[r+a]??0))}return i}function Ge(e,n,r){let{inWidth:i,outWidth:a}=e,o=2*i,{weight:s,bias:c}=t(e),l=Math.sqrt(6/(o+a));for(let e=0;e<a*o;e++)n[s+e]=(r()*2-1)*l;n.fill(0,c,c+a)}function Ke(e,n,r,i,a,o){let{inWidth:s,outWidth:c}=e,l=2*s,{weight:u,bias:d}=t(e),f=Ue(i,`pooled`),p=Ue(i,`argmax`),m=new Float64Array(l);for(let e=0;e<c;e++){let t=a[e]??0;r[d+e]=(r[d+e]??0)+t;let i=u+e*l;for(let e=0;e<l;e++)r[i+e]=(r[i+e]??0)+t*(f[e]??0),m[e]=(m[e]??0)+(n[i+e]??0)*t}return We(m,p,o,s)}const qe={init:Ge,backward:Ke,encodeGold(e,t){if(`outputs`in e){if(typeof t==`string`||t.length!==e.outputs)throw L(`DATA_ROW_INVALID`,`a pooled values head needs \`gold\` as ${e.outputs} numbers`);let n=t,r=new Float32Array(e.outputs);for(let[e,t]of n.entries()){if(typeof t!=`number`||!Number.isFinite(t))throw L(`DATA_ROW_INVALID`,`gold[${e}] is not a finite number`);r[e]=t}return r}if(typeof t!=`string`)throw L(`DATA_ROW_INVALID`,"a pooled class head needs `gold` as one label");let n=e.labels.indexOf(t);if(n<0)throw L(`DATA_LABEL_UNKNOWN`,`gold is not one of the ${e.labels.length} head labels`);return Int32Array.of(n)},loss(e,t,n){if(`outputs`in e){let r=e.outputs;if(t.length<r)throw RangeError(`expected ${r} logits, got ${t.length}`);if(n.length<r)throw RangeError(`expected ${r} gold values, got ${n.length}`);let i=new Float32Array(r),a=0;for(let e=0;e<r;e++){let o=(t[e]??0)-(n[e]??0);a+=o*o,i[e]=2*o/r}return{loss:a/r,dLogits:i}}let r=e.labels.length;if(t.length<r)throw RangeError(`expected ${r} logits, got ${t.length}`);if(n.length<1)throw RangeError(`expected one gold label`);let i=n[0]??0,a=-1/0;for(let e=0;e<r;e++)a=Math.max(a,t[e]??0);let o=0;for(let e=0;e<r;e++)o+=Math.exp((t[e]??0)-a);let s=new Float32Array(r);for(let e=0;e<r;e++)s[e]=Math.exp((t[e]??0)-a)/o-+(e===i);return{loss:a+Math.log(o)-(t[i]??0),dLogits:s}}};function Je(e,t,n,r,i){let a=new Float32Array(r),o=new Float32Array(n*r);for(let e=0;e<r;e++){let o=0;for(let a=0;a<n;a++)o+=(i[a]??0)*(t[a*r+e]??0);a[e]=o}for(let t=0;t<n;t++){let n=i[t]??0;for(let i=0;i<r;i++)o[t*r+i]=n*(e[i]??0)}return{dQuery:a,dTable:o}}function Ye(e,t,n,r){let i=Array.from(e),a=[];for(let e=0;e<t;e++)i.includes(e)||a.push(e);let o=Math.min(n,a.length);for(let e=0;e<o;e++){let t=e+Math.floor(r()*(a.length-e)),n=a[t]??0;a[t]=a[e]??0,a[e]=n}return[...i,...a.slice(0,o)]}function Xe(e,t){let n=-1/0;for(let r=0;r<e.length;r++)t(r)&&(n=Math.max(n,e[r]??0));let r=0;for(let i=0;i<e.length;i++)t(i)&&(r+=Math.exp((e[i]??0)-n));return n+Math.log(r)}const Ze={init:Ge,backward:Ke,encodeGold(e,t,n,r){return Int32Array.from(h(t,l(r)))},loss(e,t,n){if(n.length<1)throw RangeError(`expected at least one gold candidate`);let r=new Set(Array.from(n)),i=Xe(t,()=>!0),a=Xe(t,e=>r.has(e)),o=new Float32Array(t.length);for(let e=0;e<t.length;e++){let n=t[e]??0;o[e]=Math.exp(n-i)-(r.has(e)?Math.exp(n-a):0)}return{loss:i-a,dLogits:o}}};function Qe(e,t){let n=e.get(t);if(!n)throw Error(`tag backward needs '${t}' in the cache; run forward with a cache first`);return n}const $e={tag:{init(e,t,n){let{inWidth:r,outWidth:i}=e,{weight:a,bias:o}=re(e),s=Math.sqrt(6/(r+i));for(let e=0;e<i*r;e++)t[a+e]=(n()*2-1)*s;t.fill(0,o,o+i)},backward(e,t,n,r,i,a){let{inWidth:o,outWidth:s}=e,{weight:c,bias:l}=re(e),u=Qe(r,`x`);for(let e=0;e<s;e++){let t=0;for(let n=0;n<a;n++)t+=i[n*s+e]??0;n[l+e]=(n[l+e]??0)+t;let r=c+e*o;for(let t=0;t<o;t++){let c=0;for(let n=0;n<a;n++)c+=(i[n*s+e]??0)*(u[n*o+t]??0);n[r+t]=(n[r+t]??0)+c}}let d=new Float32Array(a*o);for(let e=0;e<a;e++)for(let n=0;n<o;n++){let r=0;for(let a=0;a<s;a++)r+=(t[c+a*o+n]??0)*(i[e*s+a]??0);d[e*o+n]=r}return d},encodeGold(e,t,{count:n,tokens:r}){if(!Array.isArray(t))throw L(`DATA_ROW_INVALID`,"a tag head needs `gold` as an array of labels");if(t.length!==r)throw L(`DATA_ROW_INVALID`,`\`gold\` has ${t.length} labels for ${r} tokens`);let i=new Map(e.labels.map((e,t)=>[e,t])),a=t,o=new Int32Array(n);for(let[t,r]of a.entries()){let a=typeof r==`string`?i.get(r):void 0;if(a===void 0)throw L(`DATA_LABEL_UNKNOWN`,`gold[${t}] is not one of the ${e.labels.length} head labels`);t<n&&(o[t]=a)}return o},loss(e,t,n,r){let i=e.labels.length,a=new Float32Array(r*i);if(r===0)return{loss:0,dLogits:a};if(t.length<r*i)throw RangeError(`expected ${r*i} logits, got ${t.length}`);if(n.length<r)throw RangeError(`expected ${r} gold labels, got ${n.length}`);let o=0;for(let e=0;e<r;e++){let s=e*i,c=-1/0;for(let e=0;e<i;e++)c=Math.max(c,t[s+e]??0);let l=0;for(let e=0;e<i;e++)l+=Math.exp((t[s+e]??0)-c);let u=n[e]??0;o+=c+Math.log(l)-(t[s+u]??0);for(let e=0;e<i;e++){let n=Math.exp((t[s+e]??0)-c)/l;a[s+e]=(n-+(e===u))/r}}return{loss:o/r,dLogits:a}}},pooled:qe,retrieve:Ze};function et(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let e=Math.imul(t^t>>>15,t|1);return e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function tt(e,t){let n=e.get(t);if(!n)throw Error(`biScan backward needs '${t}' in the cache; run forward with a cache first`);return n}const nt={init(e,t,n){let{inWidth:r}=e,i=e.spec.size,a=Math.sqrt(6/(r+i));for(let o of ne(e)){for(let e=0;e<i*r;e++)t[o.gateWeight+e]=(n()*2-1)*a;for(let e=0;e<i*r;e++)t[o.candidateWeight+e]=(n()*2-1)*a;for(let e=0;e<i;e++)t[o.gateBias+e]=3*e/Math.max(1,i-1);t.fill(0,o.candidateBias,o.candidateBias+i)}},backward(e,t,n,r,i,a){let{inWidth:o,outWidth:s}=e,c=e.spec.size,l=tt(r,`x`),u=tt(r,`gate`),d=tt(r,`tanh`),f=tt(r,`y`),p=new Float64Array(a*o);for(let[r,m]of ne(e).entries()){let e=r*c,h=new Float64Array(a*c),g=new Float64Array(a*c);for(let t=0;t<c;t++){let n=0;for(let o=a-1;o>=0;o--){let l=_(r,o,a),p=l*s+e+t,m=o===0?0:f[_(r,o-1,a)*s+e+t]??0,v=u[p]??0,y=d[p]??0,b=(i[p]??0)+n;h[l*c+t]=b*(m-y)*v*(1-v),g[l*c+t]=b*(1-v)*(1-y*y),n=b*v}}let v=[[m.gateWeight,m.gateBias,h],[m.candidateWeight,m.candidateBias,g]];for(let[e,r,i]of v){for(let t=0;t<c;t++){let s=0;for(let e=0;e<a;e++)s+=i[e*c+t]??0;n[r+t]=(n[r+t]??0)+s;let u=e+t*o;for(let e=0;e<o;e++){let r=0;for(let n=0;n<a;n++)r+=(i[n*c+t]??0)*(l[n*o+e]??0);n[u+e]=(n[u+e]??0)+r}}for(let n=0;n<a;n++)for(let r=0;r<o;r++){let a=p[n*o+r]??0;for(let s=0;s<c;s++)a+=(t[e+s*o+r]??0)*(i[n*c+s]??0);p[n*o+r]=a}}}return Float32Array.from(p)}};function rt(e,t){let n=e.get(t);if(!n)throw Error(`conv backward needs '${t}' in the cache; run forward with a cache first`);return n}const it={init(e,t,n){let r=e.inWidth,{taps:i}=e.spec,{kernel:a,bias:o}=S(e),s=(i-1)/2;for(let e=0;e<i;e++)for(let i=0;i<r;i++){let o=(n()*2-1)*.1;t[a+e*r+i]=e===s?1:o}t.fill(0,o,o+r)},backward(e,t,n,r,i,a){let o=e.inWidth,{taps:s}=e.spec,c=(s-1)/2,{kernel:l,bias:u}=S(e),d=rt(r,`x`),f=rt(r,`y`),p=new Float64Array(a*o);for(let e=0;e<a*o;e++){let t=f[e]??0;p[e]=(i[e]??0)*(1-t*t)}for(let e=0;e<o;e++){let t=0;for(let n=0;n<a;n++)t+=p[n*o+e]??0;n[u+e]=(n[u+e]??0)+t;for(let t=0;t<s;t++){let r=0;for(let n=Math.max(0,c-t);n<Math.min(a,a+c-t);n++)r+=(p[n*o+e]??0)*(d[(n+t-c)*o+e]??0);let i=l+t*o+e;n[i]=(n[i]??0)+r}}let m=new Float32Array(a*o);for(let e=0;e<a;e++)for(let n=0;n<o;n++){let r=0;for(let i=0;i<s;i++){let s=e-i+c;s>=0&&s<a&&(r+=(t[l+i*o+n]??0)*(p[s*o+n]??0))}m[e*o+n]=r}return m}};function at(e,t){let n=e.get(t);if(!n)throw Error(`dense backward needs '${t}' in the cache; run forward with a cache first`);return n}const ot={embed:{init(e,t,n){let{table:r,bias:i,rows:a}=te(e);t.fill(0,r,r+a*e.outWidth);for(let r=0;r<e.outWidth;r++)t[i+r]=(n()*2-1)*.1},backward(e,t,n,r,i,a){let{inWidth:o,outWidth:s}=e,{table:c,bias:l,rows:u}=te(e),d=r.get(`rows`);if(!d)throw Error(`embed backward needs 'rows' in the cache; run forward with a cache first`);for(let e=0;e<s;e++){let t=0;for(let n=0;n<a;n++)t+=i[n*s+e]??0;n[l+e]=(n[l+e]??0)+t}for(let e=0;e<a;e++)for(let t=0;t<o;t++){let r=d[e*o+t]??-1;if(r<0||r>=u)continue;let a=c+r*s;for(let t=0;t<s;t++)n[a+t]=(n[a+t]??0)+(i[e*s+t]??0)}}},conv:it,biScan:nt,dense:{init(e,t,n){let{inWidth:r,outWidth:i}=e,{weight:a,bias:o}=g(e),s=Math.sqrt(e.spec.activation===`relu`?6/r:6/(r+i));for(let e=0;e<i*r;e++)t[a+e]=(n()*2-1)*s;t.fill(0,o,o+i)},backward(e,t,n,r,i,a){let{inWidth:o,outWidth:s}=e,{activation:c}=e.spec,{weight:l,bias:u}=g(e),d=at(r,`x`),f=at(r,`y`),p=new Float64Array(a*s);for(let e=0;e<a*s;e++){let t=f[e]??0,n=c===`relu`?+(t>0):c===`tanh`?1-t*t:1;p[e]=(i[e]??0)*n}for(let e=0;e<s;e++){let t=0;for(let n=0;n<a;n++)t+=p[n*s+e]??0;n[u+e]=(n[u+e]??0)+t;let r=l+e*o;for(let t=0;t<o;t++){let i=0;for(let n=0;n<a;n++)i+=(p[n*s+e]??0)*(d[n*o+t]??0);n[r+t]=(n[r+t]??0)+i}}let m=new Float32Array(a*o);for(let e=0;e<a;e++)for(let n=0;n<o;n++){let r=0;for(let i=0;i<s;i++)r+=(t[l+i*o+n]??0)*(p[e*s+i]??0);m[e*o+n]=r}return m}}},st=.9,ct=.999;function lt(e){return{m:new Float32Array(e),v:new Float32Array(e)}}function ut(e,t,n,r){if(r<=1)return e;let i=Math.min(Math.round(t*r),r);return n<=i?e*n/i:e*.5*(1+Math.cos(Math.PI*(n-i)/(r-i)))}function dt(e,t,n,r,i){let{m:a,v:o}=e,s=1-st**r,c=1-ct**r;for(let e=0;e<t.length;e++){let r=n[e]??0,l=st*(a[e]??0)+.09999999999999998*r,u=ct*(o[e]??0)+.0010000000000000009*r*r;a[e]=l,o[e]=u,t[e]=(t[e]??0)-l/s*i/(Math.sqrt(u/c)+1e-8)}}function ft(e){switch(e.kind){case`embed`:return ot.embed;case`conv`:return ot.conv;case`biScan`:return ot.biScan;case`dense`:return ot.dense;case`tag`:return $e.tag;case`pooled`:return $e.pooled;case`retrieve`:return $e.retrieve;default:throw Error(`no train op for kind '${i(e)}'`)}}function pt(e){switch(e.kind){case`tag`:return $e.tag;case`pooled`:return $e.pooled;case`retrieve`:return $e.retrieve;default:throw Error(`no train op for head kind '${i(e)}'`)}}function mt(t,n,r){let{head:i,input:a}=t.definition,o=pt(i);return n.map(t=>{let{rows:n,count:s}=c(a,t.input),l={count:s,tokens:e(t.input)};return{rows:n,n:s,gold:o.encodeGold(i,t.gold,l,r?.ids)}})}function ht(e,t){if(t===void 0||t.length===0)throw L(`RUN_TABLE_MISSING`,"training a retrieve head needs `table`, its { id, text } rows");let{input:n}=e.definition;return{ids:t.map(e=>e.id),rows:t.map(e=>{let{rows:t,count:r}=c(n,e.text);return{rows:t,n:r}})}}function gt(e,t){let n=new Float32Array(e.size);for(let r of e.ops)ft(r.spec).init(r,n,t);return n}function _t(e,t,n,r,i=1,a){if(a!==void 0)return bt(e,t,n,a,{grads:r,scale:i});let{head:o}=e.definition,s=[],c=T(e,t,n.rows,n.n,s),{loss:l,dLogits:u}=pt(o).loss(o,c,n.gold,n.n);return yt(e,t,s,vt(u,i),n.n,r),l}function vt(e,t){return t===1?e:e.map(e=>e*t)}function yt(e,t,n,r,i,a){let o=r;for(let r=e.ops.length-1;r>=0;r--){let s=e.ops[r],c=n[r];if(s===void 0||c===void 0)throw Error(`op ${r} has no forward cache`);if(o===void 0)throw Error(`op ${r+1} returned no input gradient for op ${r}`);o=ft(s.spec).backward(s,t,a,c,o,i)}}function bt(e,t,n,{table:r,candidates:i},a){let{head:o}=e.definition,s=e.outWidth,c=a===void 0?void 0:[],l=T(e,t,n.rows,n.n,c),u=[],d=new Float32Array(i.length*s);for(let[n,a]of i.entries()){let i=r.rows[a];if(i===void 0)throw RangeError(`candidate ${a} is not a table row`);let o=c===void 0?void 0:[];d.set(T(e,t,i.rows,i.n,o),n*s),o!==void 0&&u.push(o)}let f=ae(l,d,i.length,s),p=Int32Array.from({length:n.gold.length},(e,t)=>t),{loss:m,dLogits:h}=pt(o).loss(o,f,p,n.n);if(a===void 0||c===void 0)return m;let{grads:g,scale:_}=a,{dQuery:v,dTable:y}=Je(l,d,i.length,s,vt(h,_));yt(e,t,c,v,n.n,g);for(let[n,a]of i.entries()){let i=r.rows[a],o=u[n];if(i===void 0||o===void 0)throw Error(`candidate ${n} has no forward cache`);yt(e,t,o,y.slice(n*s,(n+1)*s),i.n,g)}return m}function xt(e,t,n,r){let{head:i}=e.definition,a=pt(i),o;if(r!==void 0){o=new Float32Array(r.rows.length*e.outWidth);for(let[n,i]of r.rows.entries())o.set(T(e,t,i.rows,i.n),n*e.outWidth)}let s=0;for(let c of n){let n=T(e,t,c.rows,c.n);r!==void 0&&o!==void 0&&(n=ae(n,o,r.rows.length,e.outWidth)),s+=a.loss(i,n,c.gold,c.n).loss}return s/n.length}function St(e,t,n){return({weights:r})=>{let i=xt(e,r,t,n);return Number.isFinite(i)?-i:-1/0}}function Ct(e,t){for(let n=e.length-1;n>0;n--){let r=Math.floor(t()*(n+1)),i=e[n]??0;e[n]=e[r]??0,e[r]=i}}function wt(e,t,n){u(e,n);for(let e of[`train`,`dev`])if(t[e].length===0)throw L(`DATA_SET_TOO_SMALL`,`cannot train: the ${e} set has no examples`)}function Tt(e){return e.every(e=>Number.isFinite(e))}async function Et(e,t,n){let{plan:r,train:i,options:a}=e,o=performance.now(),s=et(t),c=gt(r,s),l=new Float32Array(r.size),u=new Float32Array(r.size),d=lt(r.size),f=a.epochs*Math.ceil(i.length/a.batch),p=r.definition.quant,m=p===void 0?1/0:Math.round(p.qatFrom*f),h=i.map((e,t)=>t),g=0,_=0,v,b,x,S=`epochs`,C=async()=>{if(!Tt(c)){v??=g;return}let t=new Float32Array(r.size);p===void 0?t.set(c):y(r,c,t);let n=await e.score({plan:r,weights:t.slice()});if(n===-1/0&&(v??=g),typeof n!=`number`||Number.isNaN(n))throw TypeError(`the dev scorer returned ${String(n)} at step ${g}, expected a number`);x={weights:t,dev:n,step:g,epoch:_},(b===void 0||n>b.dev)&&(b=x)};training:for(;_<a.epochs;){Ct(h,s);for(let t=0;t<h.length;t+=a.batch){let o=h.slice(t,t+a.batch),p=g>=m?l:c;p===l&&y(r,c,l),u.fill(0);let b=0;for(let t of o){let n=i[t];if(n===void 0)continue;let{table:c}=e,l=c===void 0?void 0:{table:c,candidates:Ye(n.gold,c.rows.length,a.negatives??0,s)};b+=_t(r,p,n,u,1/o.length,l)}if(Number.isFinite(b)||(v??=g),g++,dt(d,c,u,g,ut(a.learningRate,a.warmup,g,f)),!Tt(c)){v??=g-1,t+a.batch>=h.length&&_++;break training}if(g<f&&performance.now()>=n){S=`budget`,t+a.batch>=h.length&&_++;break training}}_++,await C()}if(x?.step!==g&&await C(),b===void 0||x===void 0||b.dev===-1/0)throw L(`TRAIN_DIVERGED`,`seed ${t}: the loss stopped being finite at step ${v??g}, and no checkpoint of the seed has finite weights and a finite dev score`);let w={seed:t,best:b,last:x,steps:g,seconds:(performance.now()-o)/1e3,stoppedBy:S};return v===void 0?w:{...w,divergedAt:v}}async function Dt(e,t,n,r,i){let o=performance.now(),s=a(e),c=s.definition.head.kind===`retrieve`;wt(n,t,c);let l=c?ht(s,t.table):void 0,u={plan:s,train:mt(s,t.train,l),options:n,score:r??St(s,mt(s,t.dev,l),l),...l===void 0?{}:{table:l}},d=o+n.budgetSeconds*1e3,f=[];for(let[e,t]of n.seeds.entries()){let r=performance.now(),a=await Et(u,t,r+(d-r)/(n.seeds.length-e));f.push(a),i?.(a,e,n.seeds.length)}let p=f[0];for(let e of f)(p===void 0||e.best.dev>p.best.dev)&&(p=e);if(p===void 0)throw Error(`train ran no seed`);return{plan:s,weights:p.best.weights.slice(),seed:p.seed,checkpoint:p.best===p.last?`last`:`best`,steps:p.steps,seconds:(performance.now()-o)/1e3,stoppedBy:f.some(e=>e.stoppedBy===`budget`)?`budget`:`epochs`,devBySeed:Object.fromEntries(f.map(e=>[String(e.seed),e.best.dev])),runs:f}}function Ot(e,t){let n;try{n=JSON.parse(t)}catch{return{ok:!1}}let r=F.safeParse(e,n,{abortEarly:!0});return r.success?{ok:!0,value:r.output}:{ok:!1,field:kt(r.issues[0].path)}}function kt(e){let t=``;for(let n of e??[]){let e=n.key;t+=typeof e==`number`?`[${e}]`:t===``?String(e):`.${String(e)}`}return t}const At=F.check(e=>!Array.isArray(e));function z(e){return F.pipe(F.unknown(),At,F.object(e))}function jt(e){return F.pipe(F.unknown(),At,F.strictObject(e))}function Mt(e){return F.pipe(F.custom(e=>typeof e==`object`&&!!e&&!Array.isArray(e)),F.rawTransform(({dataset:t,addIssue:n,NEVER:r})=>{let i=[];for(let[a,o]of Object.entries(t.value)){let s=F.safeParse(e,o,{abortEarly:!0});if(!s.success)return n({path:[{type:`object`,origin:`value`,input:t.value,key:a,value:o},...s.issues[0].path??[]]}),r;i.push([a,s.output])}return Object.fromEntries(i)}))}const Nt=F.pipe(F.string(),F.regex(/^[0-9a-f]{64}$/u)),B=F.pipe(F.number(),F.finite()),Pt=F.pipe(F.number(),F.safeInteger()),V=F.pipe(F.number(),F.integer(),F.minValue(0)),Ft=`data/test`;async function It(e){let t=e,n=[];for(;;)try{return j(await Se(t),...n)}catch{let r=A(t);if(r===t)return e;n.unshift(k(t)),t=r}}function Lt(e,t){let n=M(t,e);return n===``||n!==`..`&&!n.startsWith(`..${P}`)&&!De(n)}async function Rt(e,t){return Lt(await It(N(e.dir,t)),await It(N(e.dir,Ft)))}async function zt(e,t){if(await Rt(e,t))throw L(`DATA_TEST_READ`,`refused to open ${t}: it is inside ${Ft}/, which only the guard opens`)}async function Bt(e,t){return await zt(e,t),D(N(e.dir,t),`utf8`)}async function Vt(e,t){return await zt(e,t),D(N(e.dir,t))}async function Ht(e,t,n,r){r===`replace`&&await zt(e,t);let i=N(e.dir,t);await be(A(i),{recursive:!0}),await O(i,n,{flag:r===`create`?`wx`:`w`})}async function Ut(e,t){let n=A(t);if(/[*?]/u.test(n))throw L(`DEFINE_SET_FOLDER`,`set pattern '${t}' has a wildcard in its folder; use one folder per set`);let r=N(e.dir,n),i=k(t),a=i.replaceAll(/[.+^${}()|[\]\\]/gu,`\\$&`).replaceAll(`*`,`[^/]*`).replaceAll(`?`,`[^/]`),o=RegExp(`^${a}$`,`u`),s=[];for await(let e of ye(i.startsWith(`.`)?`.*`:`*`,{cwd:r,withFileTypes:!0}))e.isFile()&&o.test(e.name)&&s.push(`${n}/${e.name}`);return s.toSorted()}async function Wt(e,t){try{return(await xe(N(e.dir,t),{withFileTypes:!0})).some(e=>e.isFile())}catch{return!1}}const Gt=z({input:F.union([F.string(),z({text:F.string(),flags:F.optional(Mt(F.array(F.boolean())))})]),gold:F.union([F.string(),F.array(F.string()),F.array(F.number())]),expect:F.optional(F.unknown()),group:F.optional(F.string()),vocab:F.optional(F.array(F.string()))});function Kt(e){let t=Ot(Gt,e);return t.ok?t.value:void 0}function qt(e){return e.split(`
2
+ `).map((e,t)=>({line:t+1,text:e.trim()})).filter(e=>e.text!==``)}function Jt(e,t){return qt(t).map(({line:t,text:n})=>{let r=Kt(n);if(r===void 0)throw L(`DATA_ROW_INVALID`,`${e}:${t} is not a JSON { input, gold } row`,{file:e,line:t});return r})}async function Yt(e,t){return Jt(t,await Bt(e,t))}let Xt=!1;function Zt(){if(Xt)throw L(`DATA_TEST_READ`,`the test folder handle is already held by the guard in src/harness/sealed.ts`);return Xt=!0,{read:(e,t)=>D(N(e.dir,t)),remove:(e,t)=>we(N(e.dir,t))}}const Qt=Zt(),$t=new TextDecoder;function en(e){return e.toLowerCase().replaceAll(/\s+/gu,` `).trim()}function tn(e){return Ae(`sha256`).update(en(e)).digest(`hex`).slice(0,16)}function nn(e){return typeof e==`string`?e:e.text}const rn=/"(?:[^"\\\n]|\\.)*"/uy;function an(e){let t=[e];for(let n=e.indexOf(`"`);n!==-1;n=e.indexOf(`"`,n+1)){rn.lastIndex=n;let r=rn.exec(e)?.[0];if(r===void 0||!r.includes(`\\`))continue;let i;try{i=JSON.parse(r)}catch{continue}typeof i==`string`&&t.push(...an(i))}return t}function on(e){let t=/* @__PURE__ */ new Set;for(let n of Object.values(e))for(let e of n){let n=en(nn(e.input));n.length>=8&&t.add(n)}return e=>{let n=e.flatMap(an).map(en),r=0;for(let e of t)n.some(t=>t.includes(e))&&r++;return r}}function sn(e){return Ae(`sha256`).update(e).digest(`hex`)}const cn=Me(fe);async function ln(e){try{let{stdout:t}=await cn(`git`,[`rev-parse`,`HEAD`],{cwd:e});return t.trim()}catch{return`none`}}async function un(e,t,n){let r={at:(/* @__PURE__ */ new Date()).toISOString(),kind:n.kind,command:e.command,commit:await ln(t.dir),files:n.files,examples:n.examples,outcome:n.outcome};await ve(j(t.dir,`reads.jsonl`),`${JSON.stringify(r)}\n`)}function dn(e){return[...e].toSorted()}const fn=`.enc`,pn=new TextEncoder().encode(`GPUESEAL`);async function mn(e,t){return{plain:(await Ut(e,t)).filter(e=>!e.endsWith(fn)),sealed:await Ut(e,`${t}${fn}`)}}function hn(e,t,n){let r=je(12),i=Oe(`aes-256-gcm`,e,r,{authTagLength:16});i.setAAD(new TextEncoder().encode(t));let a=Buffer.concat([i.update(n),i.final()]);return Buffer.concat([pn,r,a,i.getAuthTag()])}function gn(e,t,n){let r=pn.length;if(!(e.length!==32||n.length<r+12+16)&&pn.every((e,t)=>n[t]===e))try{let i=ke(`aes-256-gcm`,e,n.subarray(r,r+12),{authTagLength:16});return i.setAAD(new TextEncoder().encode(t)),i.setAuthTag(n.subarray(n.length-16)),Buffer.concat([i.update(n.subarray(r+12,n.length-16)),i.final()])}catch{return}}async function _n(e,t,n,r){let i=Object.keys(r).toSorted(),a={},o=0,s=`failed`;try{for(let e of i){let i=await Qt.read(t,e),s=sn(i),c=r[e];if(c===void 0||s!==c.sha256)throw L(`DATA_HASH_CHANGED`,`${e} does not match the SHA-256 in data.lock.json; nothing was sealed`,{file:e});o+=qt($t.decode(i)).length;let l=`${e}${fn}`,u=hn(n,e,i);await Ht(t,l,u,`create`),a[l]={sha256:sn(u),examples:c.examples,plaintext:s}}s=`ok`}finally{await un(e,t,{kind:`digest`,files:i,examples:o,outcome:s})}return a}async function vn(e,t){for(let n of t)await Qt.remove(e,n)}async function yn(e,t){let{plain:n,sealed:r}=await mn(t,t.evaluation.sets.test.path),i=[...n,...r].toSorted(),a={},o={},s={},c=/* @__PURE__ */ new Set,l=/* @__PURE__ */ new Set,u=/* @__PURE__ */ new Set,d=0,f=`failed`;try{for(let e of i){let n=await Qt.read(t,e);if(a[e]=sn(n),r.includes(e))continue;let i=qt($t.decode(n));o[e]=i.length;let f=0;for(let{text:e}of i){d++;let t=Kt(e);if(t===void 0)f++;else{c.add(tn(nn(t.input))),t.group!==void 0&&l.add(tn(t.group));for(let e of t.vocab??[])u.add(tn(e))}}s[e]=f}f=`ok`}finally{await un(e,t,{kind:`digest`,files:i,examples:d,outcome:f})}return{files:a,sealed:r,examples:o,invalid:s,fingerprints:{inputs:dn(c),groups:dn(l),vocabulary:dn(u)}}}async function bn(e,t,n){return xn(t,await Qt.read(e,t),n)}function xn(e,t,n){if(!e.endsWith(`.enc`))return $t.decode(t);if(n===void 0)throw L(`SEAL_KEY_MISSING`,`${e} is sealed and no key was given`,{file:e});let r=gn(n,e.slice(0,-4),t);if(r===void 0)throw L(`SEAL_KEY_INVALID`,`the key does not decrypt ${e}`,{file:e});return $t.decode(r)}async function Sn(e,t,n){let r=[`verify`,`seal`,`scan`].find(t=>e.flags[t]===!0);if(e.command!==`promote`||r!==void 0)throw L(`DATA_TEST_READ`,`\`${e.command===`promote`?`promote --${r}`:e.command}\` asked to read the test set; only \`promote\` reads it`);let{plain:i,sealed:a}=await mn(t,t.evaluation.sets.test.path),o=a.length>0?a:i,s={},c=0,l=`failed`;try{for(let e of o){let r=e.endsWith(`.enc`)?e.slice(0,-4):e,i=Jt(r,await bn(t,e,n));s[k(r,Ee(r))]=i,c+=i.length}l=`ok`}finally{await un(e,t,{kind:`examples`,files:o,examples:c,outcome:l})}return s}async function Cn(e,t,n,r){if(e.command!==`promote`||e.flags.scan!==!0)throw L(`DATA_TEST_READ`,`\`${e.command}\` asked to scan for test inputs; only \`promote --scan\` does`);let i=Object.keys(n).toSorted(),a={},o=0,s=`failed`;try{for(let e of i){let i;try{i=await Qt.read(t,e)}catch{throw L(`DATA_HASH_CHANGED`,`${e} is in data.lock.json but cannot be read`,{file:e})}if(sn(i)!==n[e]?.sha256)throw L(`DATA_HASH_CHANGED`,`${e} does not match the SHA-256 in data.lock.json`,{file:e});let s=xn(e,i,r),c=e.endsWith(`.enc`)?e.slice(0,-4):e,l=Jt(c,s);a[c]=l,o+=l.length}s=`ok`}finally{await un(e,t,{kind:`digest`,files:i,examples:o,outcome:s})}return on(a)}const wn=/* @__PURE__ */ new Set([`.ts`,`.mts`,`.cts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.jsx`,`.vue`,`.svelte`]),Tn=/* @__PURE__ */ new Set([`node_modules`,`dist`,`.git`,`.gpu-engine`]),En=/(?<![\p{L}\p{N}_-])data[\\/]+test(?![\p{L}\p{N}_-])/iu,Dn=/(['"`])data\1\s*,\s*(['"`])test\2/iu,On=/\bsealed\(\s*(['"`])data\/test\/[^'"`\n]*\1\s*\)/gu;async function kn(e,t,n){let r=await xe(t,{withFileTypes:!0});for(let i of r.toSorted((e,t)=>e.name<t.name?-1:+(e.name>t.name))){let r=j(t,i.name);i.isDirectory()?Tn.has(i.name)||await kn(e,r,n):i.isFile()&&wn.has(Ee(i.name))&&n.push(M(e,r).split(P).join(`/`))}return n}async function An(e){let t=[];for(let n of await kn(e,e,[])){let r=n.endsWith(`.eval.ts`),i=(await D(j(e,n),`utf8`)).split(`
3
+ `);for(let[e,a]of i.entries()){let i=r?a.replaceAll(On,``):a;if(!En.test(i)&&!Dn.test(i))continue;let o=e+1;t.push(I(`DATA_TEST_READ`,`${n}:${o} names the test folder`,{file:n,line:o}))}}return t}const H=`data.lock.json`,U=[`train`,`dev`,`test`];function W(e,t){let{sets:n}=e.evaluation;return t===`test`?n.test.path:n[t]}function jn(e,t){return e+U.indexOf(t)*2654435769>>>0}function Mn(e){return`${A(e)}/${k(e).replaceAll(`*`,`main`).replaceAll(`?`,`0`)}`}async function Nn(e){let{generate:t}=e.evaluation.data;if(t===void 0)return[];let n=[];for(let r of U){let i=t[r],a=W(e,r);if(i===void 0||await Wt(e,A(a)))continue;let o=Mn(a);await Ht(e,o,Pn(e,r,i),`create`),n.push(o)}return n}function Pn(e,t,n){return n(et(jn(e.evaluation.data.seed,t))).map(e=>`${JSON.stringify(e)}\n`).join(``)}const Fn=[`train`,`dev`];async function In(e){let{generate:t}=e.evaluation.data,n=[];for(let r of Fn){let i=t?.[r];if(i===void 0)continue;let a=Mn(W(e,r)),o;try{o=await Vt(e,a)}catch(e){if(dr(e))continue;throw e}let s=Pn(e,r,i),c=new TextDecoder().decode(o);if(s===c)continue;let l=`${a} is not what the ${r} generator writes now (${`${qt(s).length} rows now, ${qt(c).length} in the file`})`;n.push(I(`DATA_GENERATOR_CHANGED`,l,{file:a}))}return n}async function Ln(e,t){let n=[];for(let r of t){let t=e.evaluation.data.generate?.[r];if(t===void 0)continue;let i=Mn(W(e,r));await Ht(e,i,Pn(e,r,t),`replace`),n.push(i)}let{lock:r,problem:i}=await fr(e);if(i===void 0&&t.some(e=>r[e]!==void 0)){let n=Object.fromEntries(Object.entries(r).filter(([e])=>!t.some(t=>t===e)));await Ht(e,H,ur(n),`replace`)}return n}function Rn(e){return Ae(`sha256`).update(e).digest(`hex`)}function zn(e,t,n){let r=`${e} ${e===1?t:`${t}s`}`;return n===void 0?r:`${r} ${e===1?n[0]:n[1]}`}function Bn(e,t){if(typeof e==`string`||e.length===0)return`invalid`;let n=e;return!n.every(e=>typeof e==`string`)||new Set(n).size!==n.length?`invalid`:t===void 0||n.every(e=>typeof e==`string`&&t.has(e))?void 0:`unknown`}function Vn(e,t,n){let{head:r}=e,{gold:i}=t;if(typeof t.input!=`string`)try{c(e.input,t.input)}catch{return`invalid`}if(r.kind===`retrieve`)return Bn(i,n);if(`outputs`in r){if(typeof i==`string`)return`invalid`;let e=i;return e.length===r.outputs&&e.every(e=>Number.isFinite(e))?void 0:`invalid`}let a=new Set(r.labels);if(r.kind===`pooled`)return typeof i==`string`?a.has(i)?void 0:`unknown`:`invalid`;if(typeof i==`string`)return`invalid`;let o=i;return o.length!==f(nn(t.input)).length||!o.every(e=>typeof e==`string`)?`invalid`:o.every(e=>typeof e==`string`&&a.has(e))?void 0:`unknown`}function Hn(e,t,n){let r=tn(t),i=e.get(r);i===void 0?e.set(r,[n]):i.includes(n)||i.push(n)}const Un={DATA_ROW_INVALID:{verb:[`is`,`are`],what:`not a JSON { input, gold } row with gold in the shape of the head`},DATA_LABEL_UNKNOWN:{verb:[`has`,`have`],what:`a gold label outside the head labels`},TABLE_ROW_INVALID:{verb:[`is`,`are`],what:`not a JSON { id, text } row with a non-empty string id no earlier row uses`},TABLE_ID_UNKNOWN:{verb:[`has`,`have`],what:`a gold id that names no row of the table`}},Wn={DATA_ROW_INVALID:`DATA_ROW_INVALID`,DATA_LABEL_UNKNOWN:`DATA_LABEL_UNKNOWN`,TABLE_ROW_INVALID:`DATA_ROW_INVALID`,TABLE_ID_UNKNOWN:`DATA_LABEL_UNKNOWN`};function Gn(e,t,n){let[r]=n,i=Wn[e],{verb:a,what:o}=Un[e];return I(i,`${t}: ${zn(n.length,`row`,a)} ${o} (first at line ${r})`,{file:t,line:r})}function Kn(e){let t=[],n=[],r=/* @__PURE__ */ new Set;for(let{line:i,text:a}of qt(e)){let e;try{e=JSON.parse(a)}catch{n.push(i);continue}let o=typeof e==`object`&&e&&`id`in e?e.id:void 0,s=typeof e==`object`&&e&&`text`in e?e.text:void 0;typeof o!=`string`||o===``||typeof s!=`string`||r.has(o)?n.push(i):(r.add(o),t.push({id:o,text:s}))}return{rows:t,invalid:n}}async function qn(e,t,n){if(e.head.kind===`retrieve`&&t.table!==void 0)try{return Kn(await Bt({dir:n},t.table)).rows}catch(e){if(dr(e))return;throw e}}async function Jn(e){if(e.model.head.kind!==`retrieve`)return;let t=e.evaluation.table;if(t===void 0)return{files:{},rows:[],diagnostics:[I(`DATA_SET_MISSING`,`a retrieve head needs eval.table, a JSONL file of { id, text } rows, and the eval has none`)]};let n;try{n=await Vt(e,t)}catch(e){if(!dr(e))throw e;return{files:{},rows:[],diagnostics:[I(`DATA_SET_MISSING`,`0 files match ${t}, so the retrieve head has no table`,{file:t})]}}let{rows:r,invalid:i}=Kn(new TextDecoder().decode(n)),a=[];return i.length>0&&a.push(Gn(`TABLE_ROW_INVALID`,t,i)),r.length===0&&i.length===0&&a.push(I(`DATA_SET_MISSING`,`${t} has 0 rows, so the retrieve head has no table`,{file:t})),{files:{[t]:{sha256:Rn(n),examples:r.length+i.length}},ids:new Set(r.map(e=>e.id)),rows:r,diagnostics:a}}async function Yn(e){let t=await Jn(e),[n]=t?.diagnostics??[];if(n!==void 0)throw new r(n);return t?.rows}async function Xn(e,t,n){let r=W(e,t),i={inputs:/* @__PURE__ */ new Map,groups:/* @__PURE__ */ new Map,vocabulary:/* @__PURE__ */ new Map},a={},o={},s=[];for(let t of await Ut(e,r)){let r=await Vt(e,t),c=qt(new TextDecoder().decode(r));a[t]={sha256:Rn(r),examples:c.length};let l=[],u=[],d=[];for(let{line:r,text:a}of c){let o=Kt(a),s=o===void 0?`invalid`:Vn(e.model,o,n);if(s===`invalid`||o===void 0)u.push(r);else{s===`unknown`?d.push(r):l.push(o),Hn(i.inputs,nn(o.input),t),o.group!==void 0&&Hn(i.groups,o.group,t);for(let e of o.vocab??[])Hn(i.vocabulary,e,t)}}if(u.length>0&&s.push(Gn(`DATA_ROW_INVALID`,t,u)),d.length>0){let n=e.model.head.kind===`retrieve`?`TABLE_ID_UNKNOWN`:`DATA_LABEL_UNKNOWN`;s.push(Gn(n,t,d))}o[k(t,Ee(t))]=l}return{facts:{kind:t,pattern:r,files:a,fingerprints:i},examples:o,diagnostics:s}}function Zn(e,t){let n=Object.keys(e.files);return n.length===Object.keys(t).length&&n.every(n=>t[n]?.sha256===e.files[n]?.sha256)}function Qn(e,t,n){let r={};for(let[e,i]of Object.entries(t.files))r[e]={sha256:i,examples:(t.sealed.includes(e)?n?.files[e]?.examples:t.examples[e])??0};let i=n?.fingerprints!==void 0&&Zn(n,r)?n.fingerprints:void 0,a=i??t.fingerprints,o=Object.keys(r).toSorted(),s=e=>new Map(e.map(e=>[e,o])),c=[];if(n===void 0&&t.sealed.length>0){let e=`${t.sealed.join(`, `)} ${t.sealed.length===1?`is`:`are`} sealed, and ${H} has no test entry with their fingerprints`;c.push(I(`SEAL_LOCK_INVALID`,e,{file:H}))}if(i===void 0)for(let e of o){let n=t.invalid[e]??0;if(n===0)continue;let r=`${e}: ${zn(n,`row`,[`is`,`are`])} not a JSON { input, gold } row (counted by the guard's digest)`;c.push(I(`DATA_ROW_INVALID`,r,{file:e}))}return{facts:{kind:`test`,pattern:e,files:r,fingerprints:{inputs:s(a.inputs),groups:s(a.groups),vocabulary:s(a.vocabulary)}},diagnostics:c,fingerprints:t.fingerprints}}function $n(e){let t=[];for(let n of U)Object.keys(e[n].files).length>0||t.push(I(`DATA_SET_MISSING`,`0 files match ${e[n].pattern}, so the ${n} set is missing`));return t}function er(e,t){let n=[];for(let r of U)for(let[i,{examples:a}]of Object.entries(e[r].files)){if(a>=t[r])continue;let e=`${i} has ${zn(a,`example`)}; minSize.${r} is ${t[r]}`;n.push(I(`DATA_SET_TOO_SMALL`,e,{file:i}))}return n}function tr(e){return e===`inputs`?{code:`DATA_SPLIT_OVERLAP`,noun:`example`}:e===`groups`?{code:`DATA_GROUP_SHARED`,noun:`group`}:{code:`DATA_VOCAB_SHARED`,noun:`vocabulary word`}}const nr=[[`train`,`dev`],[`train`,`test`],[`dev`,`test`]];function rr(e,t){let{code:n,noun:r}=tr(t),i=[];for(let[a,o]of nr){let s=e[a].fingerprints[t],c=e[o].fingerprints[t],l=[...s.keys()].filter(e=>c.has(e));if(l.length===0)continue;let u=e=>[...new Set(l.flatMap(t=>e.get(t)??[]))].toSorted().join(`, `),d=zn(l.length,r,[`appears`,`appear`]);i.push(I(n,`${d} in both ${a} (${u(s)}) and ${o} (${u(c)})`))}return i}function ir(e,t,n){let r=[],i=[...U.map(t=>[t,e[t].files]),...n===void 0?[]:[[`table`,n]]];for(let[e,n]of i){let i=t[e];if(i!==void 0)for(let t of[.../* @__PURE__ */ new Set([...Object.keys(i.files),...Object.keys(n)])].toSorted()){let a=i.files[t],o=n[t];if(a!==void 0&&o!==void 0&&a.sha256===o.sha256)continue;let s;if(a===void 0)s=`${t} is not in the ${e} entry of ${H}`;else if(o===void 0)s=`${t} is in the ${e} entry of ${H} but no longer exists`;else{let e=`${zn(o.examples,`example`)} now, ${a.examples} recorded`;s=`${t} does not match the SHA-256 in ${H} (${e})`}r.push(I(`DATA_HASH_CHANGED`,s,{file:t}))}}return r}const ar=[...U,`table`],or=Mt(z({sha256:Nt,examples:V,plaintext:F.optional(Nt)})),sr=z({files:or}),cr=jt({train:F.optional(sr),dev:F.optional(sr),test:F.optional(z({files:or,fingerprints:z({inputs:F.array(F.string()),groups:F.array(F.string()),vocabulary:F.array(F.string())})})),table:F.optional(sr)});function lr(e){let t=Ot(cr,e);return t.ok?t.value:void 0}function ur(e){let t={};for(let n of ar){let r=e[n];if(r===void 0)continue;let i={};for(let e of Object.keys(r.files).toSorted()){let t=r.files[e];if(t===void 0)continue;let{sha256:n,examples:a,plaintext:o}=t;i[e]=o===void 0?{sha256:n,examples:a}:{sha256:n,examples:a,plaintext:o}}let a=r.fingerprints;t[n]=a===void 0?{files:i}:{files:i,fingerprints:{inputs:a.inputs,groups:a.groups,vocabulary:a.vocabulary}}}return`${JSON.stringify(t,null,2)}\n`}function dr(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}async function fr(e){let t;try{t=await Bt(e,H)}catch(e){if(dr(e))return{lock:{}};throw e}let n=lr(t);return n===void 0?{lock:{},problem:I(`DATA_HASH_CHANGED`,`${H} is not a lock file, so no recorded hash can be compared`,{file:H})}:{lock:n}}async function pr(e,t){let{lock:n,problem:r}=await fr(t),i=await Jn(t),a=await Xn(t,`train`,i?.ids),o=await Xn(t,`dev`,i?.ids),s=Qn(W(t,`test`),await yn(e,t),n.test),c={train:a.facts,dev:o.facts,test:s.facts};return{diagnostics:[...$n(c),...er(c,t.evaluation.data.minSize),...i?.diagnostics??[],...a.diagnostics,...o.diagnostics,...s.diagnostics,...rr(c,`inputs`),...rr(c,`groups`),...rr(c,`vocabulary`),...r===void 0?ir(c,n,i?.files):[r]],facts:c,...i===void 0?{}:{table:i},lock:n,testFingerprints:s.fingerprints,examples:{train:a.examples,dev:o.examples}}}function mr(e,t,n,r){let i=e.table??(r===void 0?void 0:{files:r});return{train:e.train??{files:t.train.files},dev:e.dev??{files:t.dev.files},test:e.test??{files:t.test.files,fingerprints:n},...i===void 0?{}:{table:i}}}async function hr(e,t){return[...(await pr(e,t)).diagnostics]}async function gr(e,t){let n=await Nn(t),r=await In(t),i=await pr(e,t),a=[...r,...i.diagnostics],{lock:o}=i,s=i.table?.files,c=U.some(e=>o[e]===void 0)||s!==void 0&&!o.table;return a.length===0&&c&&(o=mr(o,i.facts,i.testFingerprints,s),await Ht(t,H,ur(o),`replace`)),{diagnostics:a,lock:o,written:n,examples:i.examples}}const G=`gate.json`;function _r(e){return`${JSON.stringify(e,null,2)}\n`}const vr={level:2,promoted:null};function K(e){return Ne(e,{params:{[Pe.BROTLI_PARAM_QUALITY]:11}}).length}const yr=e=>e.toFixed(3);function br(e,t,n,r){let i=[],a=`noise ${yr(r.noise)}, seed spread ${yr(r.spread)}`;for(let[o,s]of Object.entries(t)){let t=`floor ${e} ${o}`,c=n!==void 0&&Object.hasOwn(n,o)?n[o]:void 0;if(c===void 0){i.push({name:t,pass:!0,detail:`model ${yr(s.model)}, nothing promoted yet (${a})`});continue}let l=s.model>=c-r.noise-1e-9,u=`model ${yr(s.model)} >= promoted ${yr(c)} - noise = ${yr(c-r.noise)} (${a})`;i.push(l?{name:t,pass:l,detail:u}:{name:t,pass:l,detail:u,code:`GATE_FLOOR_FAILED`})}for(let[r,a]of Object.entries(n??{})){if(Object.hasOwn(t,r))continue;let n=`promoted ${yr(a)}, but the set has no score now`;i.push({name:`floor ${e} ${r}`,pass:!1,detail:n,code:`GATE_FLOOR_FAILED`})}return i}function xr(e){let{budgets:t,promoted:n,scores:r}=e,i=br(`dev`,r.dev,n?.dev,e);r.test!==void 0&&i.push(...br(`test`,r.test,n?.test,e));let a=e.brotliBytes<=t.brotliBytes,o=`weights ${e.brotliBytes} Brotli bytes <= budgets.brotliBytes ${t.brotliBytes}`;i.push(a?{name:`budget bytes`,pass:!0,detail:o}:{name:`budget bytes`,pass:!1,detail:o,code:`BUDGET_BYTES_EXCEEDED`});let s=e.macsPerToken<=t.macsPerToken,c=`${e.macsPerToken} multiply-adds per token <= budgets.macsPerToken ${t.macsPerToken}`;i.push(s?{name:`budget macs`,pass:!0,detail:c}:{name:`budget macs`,pass:!1,detail:c,code:`DEFINE_BUDGET_EXCEEDED`});let{files:l,changed:u}=e.data;return i.push(u.length===0?{name:`data`,pass:!0,detail:`${l} files match data.lock.json`}:{name:`data`,pass:!1,detail:`${u.length} of ${l} files differ from data.lock.json: ${u.join(`, `)}`,code:`DATA_HASH_CHANGED`}),i}function Sr(e){return e.every(e=>e.pass)}function Cr(e){let t=e.code===void 0?``:` [${e.code}]`;return`${e.pass?`pass`:`FAIL`} ${e.name}: ${e.detail}${t}`}function wr(e){throw L(`GATE_FILE_INVALID`,`${G}: ${e}`,{file:G})}const Tr=Mt(B),Er=z({level:F.picklist([1,2,3]),promoted:F.nullable(z({at:F.string(),commit:F.string(),weights:F.string(),definition:F.string(),dev:Tr,test:Tr}))});function Dr(e){if(e===void 0)return`not JSON`;if(e===``)return`not an object`;if(e===`level`)return`level must be 1, 2 or 3`;if(e===`promoted`)return`promoted must be null or an object`;let t=e.split(`.`)[1]??``;return t===`dev`||t===`test`?`promoted.${t} must map each set to a score`:`promoted.${t} must be a string`}function Or(e){let t=Ot(Er,e);return t.ok?t.value:wr(Dr(t.field))}function kr(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}async function Ar(e){let t;try{t=await D(j(e.dir,G),`utf8`)}catch(e){if(kr(e))return vr;throw e}return Or(t)}const jr=/[\p{ID_Start}$_\\][\p{ID_Continue}$\\]*/uy,Mr=/(?:\d|\.\d)[\p{ID_Continue}.]*/uy,Nr=/\s+/uy,Pr=/* @__PURE__ */ new Set([`await`,`case`,`delete`,`do`,`else`,`in`,`instanceof`,`new`,`of`,`return`,`throw`,`typeof`,`void`,`yield`]);function Fr(e,t,n){return e.lastIndex=n,e.exec(t)?.[0]}function Ir(e,t,n){let r=t;for(;r<e.length;){let t=e[r];if(t===`\\`)r+=2;else if(t===n)return{end:r+1,closed:!0};else if(n==="`"&&t===`$`&&e[r+1]===`{`)return{end:r+2,closed:!1};else if(n!=="`"&&t===`
4
+ `)return{end:r,closed:!0};else r++}return{end:e.length,closed:!0}}function Lr(e,t){let n=t+1,r=!1;for(;n<e.length&&e[n]!==`
5
+ `;){let t=e[n];if(t===`/`&&!r)return n+1+(Fr(jr,e,n+1)??``).length;t===`[`?r=!0:t===`]`&&(r=!1),n+=t===`\\`?2:1}return n}function Rr(e,t,n,r){let i=e.indexOf(t,n);return i===-1?e.length:i+r}function zr(e){return e===void 0?!0:e.kind===`string`?!1:e.kind===`name`?Pr.has(e.text):/^\.?\d/u.test(e.text)||e.text===`template`||e.text===`regexp`?!1:e.text!==`)`&&e.text!==`]`}function Br(e){let t=[],n=[],r=e.startsWith(`#!`)?e.indexOf(`
6
+ `)+1||e.length:0;for(;r<e.length;){let i=e[r]??``,a=e[r+1],o=Fr(Nr,e,r);if(o!==void 0)r+=o.length;else if(i===`/`&&a===`/`)r=Rr(e,`
7
+ `,r+2,0);else if(i===`/`&&a===`*`)r=Rr(e,`*/`,r+2,2);else if(i===`/`&&zr(t.at(-1))){let n=Lr(e,r);t.push({kind:`punct`,text:`regexp`,at:r,end:n}),r=n}else if(i===`"`||i===`'`){let{end:n}=Ir(e,r+1,i);t.push({kind:`string`,text:e.slice(r+1,n-1),at:r,end:n}),r=n}else if(i==="`"){let{end:i,closed:a}=Ir(e,r+1,"`");a?t.push({kind:`string`,text:e.slice(r+1,i-1),at:r,end:i}):n.push(0),r=i}else if(i===`}`&&n.at(-1)===0){n.pop();let{end:i,closed:a}=Ir(e,r+1,"`");a||n.push(0),t.push({kind:`punct`,text:`template`,at:r,end:i}),r=i}else{let a=Fr(jr,e,r)??Fr(Mr,e,r);if(a!==void 0){t.push({kind:/^[\d.]/u.test(a)?`punct`:`name`,text:a,at:r,end:r+a.length}),r+=a.length;continue}let o=e.startsWith(`...`,r)?`...`:i;n.length>0&&o===`{`&&(n[n.length-1]=(n.at(-1)??0)+1),n.length>0&&o===`}`&&(n[n.length-1]=(n.at(-1)??0)-1),t.push({kind:`punct`,text:o,at:r,end:r+o.length}),r+=o.length}}return t}function Vr(e,t){let n=0;for(let r=t;r<e.length;r++){let t=e[r]?.text;if(t===`{`)n++;else if(t===`}`&&--n===0)return r+1}return-1}function Hr(e,t){let n=t;for(;n<e.length;){let t=e[n];if(t===void 0)return;if(t.text===`{`){if(n=Vr(e,n),n===-1)return}else if(t.kind===`name`&&t.text===`from`){let t=e[n+1];return t?.kind===`string`?t:void 0}else if(t.text===`*`||t.text===`,`||t.kind===`name`)n++;else return}}function Ur(e,t){let n=e[t+1];return e[t]?.text===`(`&&n?.kind===`string`?n:void 0}function Wr(e){let t=Br(e),n=[];for(let[r,i]of t.entries()){if(i.kind!==`name`||i.text!==`import`&&i.text!==`export`&&i.text!==`require`||t[r-1]?.text===`.`)continue;let a=t[r+1],o;i.text===`require`||i.text===`import`&&a?.text===`(`?o=Ur(t,r+1):i.text===`import`&&a?.kind===`string`?o=a:a!==void 0&&(a.text===`{`||a.text===`*`||a.text===`type`||i.text===`import`)&&(o=Hr(t,r+1)),o!==void 0&&n.push({specifier:o.text,line:e.slice(0,i.at).split(`
8
+ `).length})}return n}async function Gr(e,t){let n;try{n=await xe(e,{withFileTypes:!0})}catch{throw L(`PROJECT_FILE_MISSING`,`${e} is not a folder that can be listed`)}let r=n.filter(e=>!e.isDirectory()&&e.name.endsWith(t)).map(e=>e.name).toSorted(),[i]=r;if(i===void 0)throw L(`PROJECT_FILE_MISSING`,`no *${t} file in ${e}`);if(r.length>1)throw L(`PROJECT_FILE_AMBIGUOUS`,`${r.length} *${t} files in ${e}: ${r.join(`, `)}`);return j(e,i)}function q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Kr(e){return q(e)&&typeof e.name==`string`&&q(e.input)&&Array.isArray(e.net)&&q(e.head)&&q(e.budgets)}function qr(e){return q(e)&&q(e.sets)&&q(e.sets.test)&&e.sets.test.kind===`sealed`&&q(e.data)&&q(e.train)&&typeof e.metric==`function`}async function Jr(e){let t;try{t=await import(Fe(e).href)}catch(t){throw t instanceof r?t:L(`PROJECT_IMPORT_FAILED`,`${e} threw while it was imported: ${t instanceof Error?t.message:String(t)}`)}return q(t)?t.default:void 0}async function Yr(e){let t=N(e),n=await Gr(t,`.model.ts`),r=await Gr(t,`.eval.ts`),i=await Jr(n);if(!Kr(i))throw L(`PROJECT_EXPORT_INVALID`,`${n} does not default-export a model definition`);let a=await Jr(r);if(!qr(a))throw L(`PROJECT_EXPORT_INVALID`,`${r} does not default-export an eval definition`);ie(i,a);let s={dir:t,modelFile:n,evalFile:r,model:o(i),evaluation:a},c=await qn(s.model,s.evaluation,t);return c===void 0?s:{...s,table:c}}function Xr(e){return typeof e==`object`&&!!e&&`createProgram`in e&&`createPrinter`in e}function Zr(e){return typeof e==`object`&&!!e&&`flags`in e&&`getSymbol`in e}function Qr(e){return typeof e==`object`&&!!e&&`kind`in e&&`pos`in e&&`end`in e}function $r(e){let t=Reflect.get(e,`objectFlags`);return typeof t==`number`?t:0}function ei(e){for(let t of[j(e,`package.json`),import.meta.filename]){let e=le(t),n;try{n=e.resolve(`typescript`)}catch{continue}let r=e(n);if(Xr(r))return r}}function J(e){throw L(`BUILD_TYPES_FAILED`,e)}const ti={target:`es2023`,lib:[`es2023`,`dom`],module:`nodenext`,moduleResolution:`nodenext`,strict:!0,allowImportingTsExtensions:!0,skipLibCheck:!0};function ni(e,t){let n=j(t,`tsconfig.json`),r=e.sys.fileExists(n)?e.readConfigFile(n,t=>e.sys.readFile(t)):{config:{compilerOptions:ti}};r.error!==void 0&&J(`tsconfig.json: ${e.flattenDiagnosticMessageText(r.error.messageText,`
9
+ `)}`);let i=e.parseJsonConfigFileContent(r.config,e.sys,t),[a]=i.errors.filter(e=>e.code!==18003);return a!==void 0&&J(`tsconfig.json: ${e.flattenDiagnosticMessageText(a.messageText,`
10
+ `)}`),{...i.options,noEmit:!0,declaration:!1,composite:!1,incremental:!1}}function ri(e,t,n){let r=e.flattenDiagnosticMessageText(n.messageText,` `),{file:i,start:a}=n;if(i===void 0)return`TS${n.code} ${r}`;let o=a===void 0?1:i.getLineAndCharacterOfPosition(a).line+1;return`${M(t,i.fileName).split(P).join(`/`)}:${o}: TS${n.code} ${r}`}function ii(e,t){let n=M(e,t);return!n.startsWith(`..`)&&!n.split(P).includes(`node_modules`)}var ai=class{ts;program;checker;printer;file;flags;aliasFlags;named=/* @__PURE__ */ new Map;queue=[];seen=/* @__PURE__ */ new Set;constructor(e,t,n){this.ts=e,this.program=t,this.checker=t.getTypeChecker(),this.printer=e.createPrinter({removeComments:!0}),this.file=n,this.flags=e.NodeBuilderFlags.NoTruncation|e.NodeBuilderFlags.MultilineObjectLiterals|e.NodeBuilderFlags.UseSingleQuotesForStringLiteralType|e.NodeBuilderFlags.IgnoreErrors,this.aliasFlags=this.flags|e.NodeBuilderFlags.InTypeAlias}isReference(e){return($r(e)&this.ts.ObjectFlags.Reference)!==0}print(e,t){return e===void 0&&J(`cannot print the type of ${t}`),this.printer.printNode(this.ts.EmitHint.Unspecified,e,this.file)}isGlobal(e){return(e.declarations??[]).every(e=>{let t=e.getSourceFile();if(this.program.isSourceFileDefaultLibrary(t)||!this.ts.isExternalModule(t))return!0;for(let t=e;t.parent!==void 0;t=t.parent)if(this.ts.isModuleDeclaration(t)&&t.name.text===`global`)return!0;return!1})}want(e,t=e.name){if(this.isGlobal(e))return;let n=this.named.get(t);n!==e&&(n!==void 0&&J(`two different types are named \`${t}\`; rename one`),this.named.set(t,e),this.queue.push([e,t]))}visitNodes(e){let{ts:t,checker:n}=this,r=Reflect.get(e,`root`),i=typeof r==`object`&&r?Reflect.get(r,`node`):Reflect.get(e,`declaration`);if(!Qr(i)||!(t.isConditionalTypeNode(i)||t.isMappedTypeNode(i)))return;let a=t.isConditionalTypeNode(i)?[i.checkType,i.extendsType,i.trueType,i.falseType]:[i.typeParameter.constraint,i.nameType,i.type];for(let e of a)e!==void 0&&this.visitType(n.getTypeFromTypeNode(e))}visitSignature(e){for(let t of e.getTypeParameters()??[])this.visitType(t);for(let t of e.getParameters())this.visitType(this.checker.getTypeOfSymbol(t));this.visitType(this.checker.getReturnTypeOfSignature(e))}visitType(e,t){let{ts:n,checker:r}=this;if(!(this.seen.has(e)&&t===void 0)){if(this.seen.add(e),e.aliasSymbol!==void 0&&e.aliasSymbol!==t){this.want(e.aliasSymbol);for(let t of e.aliasTypeArguments??[])this.visitType(t)}else if(e.isUnionOrIntersection())for(let t of e.types)this.visitType(t);else if(e.flags&n.TypeFlags.TypeParameter){let t=r.getBaseConstraintOfType(e);t!==void 0&&t!==e&&this.visitType(t)}else if(e.flags&n.TypeFlags.Conditional)this.visitNodes(e);else if(e.flags&(n.TypeFlags.Index|n.TypeFlags.IndexedAccess))for(let t of[`type`,`objectType`,`indexType`]){let n=Reflect.get(e,t);Zr(n)&&this.visitType(n)}else if(e.flags&n.TypeFlags.Object){if($r(e)&n.ObjectFlags.Mapped&&this.visitNodes(e),this.isReference(e)){let t=e.target;!(t.objectFlags&n.ObjectFlags.Tuple)&&t.symbol!==void 0&&t!==e&&this.want(t.symbol);for(let t of r.getTypeArguments(e))this.visitType(t);if(t!==e)return}if($r(e)&(n.ObjectFlags.Interface|n.ObjectFlags.Class)&&e.symbol!==void 0&&(t===void 0||e.symbol!==t))this.want(e.symbol);else{for(let t of r.getPropertiesOfType(e))this.visitType(r.getTypeOfSymbol(t));for(let t of[...e.getCallSignatures(),...e.getConstructSignatures()])this.visitSignature(t);for(let t of r.getIndexInfosOfType(e))this.visitType(t.keyType),this.visitType(t.type)}}}}docs(e,t){let n=this.ts.displayPartsToString(e.getDocumentationComment(this.checker)).trim(),r=e.getJsDocTags(this.checker).map(e=>`@${e.name}${e.text===void 0?``:` ${this.ts.displayPartsToString(e.text)}`}`),i=[...n===``?[]:n.split(`
11
+ `),...r].map(e=>e.replaceAll(`*/`,`* /`));return i.length===0?[]:i.length===1?[`${t}/** ${i[0]} */`]:[`${t}/**`,...i.map(e=>`${t} * ${e}`.trimEnd()),`${t} */`]}typeText(e,t,n=!1){let r=n?this.aliasFlags:this.flags;return this.print(this.checker.typeToTypeNode(e,void 0,r),t)}signatureText(e,t){this.visitSignature(e);let n=this.checker.signatureToSignatureDeclaration(e,this.ts.SyntaxKind.CallSignature,void 0,this.flags);return this.print(n,t).replace(/;$/u,``)}typeParameters(e,t){return e===void 0||e.length===0?``:`<${e.map(e=>(this.visitType(e),this.print(this.checker.typeParameterToDeclaration(e,void 0,this.flags),t))).join(`, `)}>`}propertyName(e){return/^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(e)?e:JSON.stringify(e)}members(e,t){let{ts:n,checker:r}=this,i=[];for(let n of e.getCallSignatures())i.push(` ${this.signatureText(n,t)};`);for(let n of e.getConstructSignatures())i.push(` new ${this.signatureText(n,t)};`);for(let n of r.getIndexInfosOfType(e))this.visitType(n.keyType),this.visitType(n.type),i.push(` ${this.print(r.indexInfoToIndexSignatureDeclaration(n,void 0,this.flags),t)}`);for(let a of r.getPropertiesOfType(e)){let e=this.propertyName(a.name),o=a.valueDeclaration??a.declarations?.[0],s=a.flags&n.SymbolFlags.Optional?`?`:``,c=r.getTypeOfSymbol(a);if(i.push(...this.docs(a,` `)),o!==void 0&&(n.isMethodSignature(o)||n.isMethodDeclaration(o))){for(let n of c.getCallSignatures())i.push(` ${e}${s}${this.signatureText(n,`${t}.${a.name}`)};`);continue}let l=o!==void 0&&n.getCombinedModifierFlags(o)&n.ModifierFlags.Readonly?`readonly `:``;this.visitType(c),i.push(` ${l}${e}${s}: ${this.typeText(c,`${t}.${a.name}`)};`)}return i}declarationOf(e,t){let{ts:n,checker:r}=this,i=[...this.docs(e,``)];if(e.flags&(n.SymbolFlags.Class|n.SymbolFlags.Enum|n.SymbolFlags.Module)&&J(`\`${t}\` is a class, an enum or a namespace, which the declarations cannot hold`),e.flags&n.SymbolFlags.Interface){let n=r.getDeclaredTypeOfSymbol(e),a=this.typeParameters(n.isClassOrInterface()?n.typeParameters:void 0,t);i.push(`interface ${t}${a} {`,...this.members(n,t),`}`)}if(e.flags&n.SymbolFlags.TypeAlias){let a=r.getDeclaredTypeOfSymbol(e),o=(e.declarations?.find(n.isTypeAliasDeclaration)?.typeParameters??[]).map(e=>r.getTypeAtLocation(e));this.visitType(a,e),i.push(`type ${t}${this.typeParameters(o,t)} = ${this.typeText(a,t,!0)};`)}if(e.flags&n.SymbolFlags.Function)for(let n of r.getTypeOfSymbol(e).getCallSignatures())i.push(`declare function ${t}${this.signatureText(n,t)};`);else if(e.flags&n.SymbolFlags.Variable){let n=r.getTypeOfSymbol(e);this.visitType(n),i.push(`declare const ${t}: ${this.typeText(n,t)};`)}else{let a=e.declarations?.find(n.isExportAssignment);if(a!==void 0){let e=r.getTypeAtLocation(a.expression);this.visitType(e),i.push(`declare const ${t}: ${this.typeText(e,t)};`)}}return i}render(e){let{ts:t,checker:n}=this,r=n.getSymbolAtLocation(this.file);r===void 0&&J(`src/index.ts is not a module`);let i=[],a;for(let o of n.getExportsOfModule(r)){let r=o.flags&t.SymbolFlags.Alias?n.getAliasedSymbol(o):o;if(this.isGlobal(r)&&J(`\`${o.name}\` re-exports a global, which the declarations cannot hold`),r.name==="default"&&o.name!=="default")throw L(`BUILD_SOURCE_UNSUPPORTED`,`${e} exports \`${o.name}\`, an anonymous default export under another name, which the declarations cannot name; give the default a name where it is declared`);r.name==="default"?a=r:(this.want(r,r.name),i.push([r.name,o.name]))}let o=[],s=()=>{for(let e=this.queue.shift();e!==void 0;e=this.queue.shift())o.push(this.declarationOf(...e).join(`
12
+ `))};if(s(),a!==void 0){let e=`_default`;for(let t=1;this.named.has(e);t++)e=`_default${t}`;this.want(a,e),i.push([e,`default`]),s()}let c=i.map(([e,t])=>e===t?e:`${e} as ${t}`);return["// The declarations of dist/index.mjs, written by `gpu-engine build` from src/index.ts.",``,o.join(`
13
+
14
+ `),``,`export { ${c.join(`, `)} };`,``].join(`
15
+ `)}};function oi(e,t){let n=ei(t);n===void 0&&J("no `typescript` is installed in the package or next to gpu-engine");let r=n.createProgram([e],ni(n,t)),i=n.getPreEmitDiagnostics(r).filter(e=>e.file===void 0||ii(t,e.file.fileName)),[a]=i;a!==void 0&&J(`${i.length} type error(s) in the package; the first: ${ri(n,t,a)}`);let o=r.getSourceFile(e);o===void 0&&J(`TypeScript did not load ${e}`);let s=new ai(n,r,o).render(M(t,e).split(P).join(`/`));return ci(n,t,s),s}const si={target:`es2023`,lib:[`es2023`,`dom`],module:`nodenext`,moduleResolution:`nodenext`,strict:!0,exactOptionalPropertyTypes:!0,skipLibCheck:!1,noEmit:!0,types:[]};function ci(e,t,n){let r=j(t,`dist`,`index.d.mts`),{options:i}=e.convertCompilerOptionsFromJson(si,t),a=e.createCompilerHost(i),o={...a,getSourceFile:(t,i,...o)=>t===r?e.createSourceFile(t,n,i):a.getSourceFile(t,i,...o),fileExists:e=>e===r||a.fileExists(e),readFile:e=>e===r?n:a.readFile(e)},s=e.createProgram([r],i,o),[c,...l]=e.getPreEmitDiagnostics(s);if(c!==void 0)throw L(`BUILD_SOURCE_UNSUPPORTED`,`src/index.ts exports a type that dist/index.d.mts cannot declare, so the file would not typecheck (${l.length+1} error(s); the first: ${ri(e,t,c)})`)}const li=`src/table.ts`,ui=/^[\p{L}_$][\p{L}\p{N}_$]*$/u,di=`__gpuEngineDefault`,fi=/* @__PURE__ */ new Set([`const`,`let`,`var`]),pi=/* @__PURE__ */ new Set([`async`,`break`,`class`,`const`,`continue`,`debugger`,`do`,`export`,`for`,`function`,`if`,`import`,`let`,`return`,`switch`,`throw`,`try`,`var`,`while`]),mi=/* @__PURE__ */ new Set([`(`,`[`,`{`]),hi=/* @__PURE__ */ new Set([`)`,`]`,`}`]);function Y(e,t){return M(e,t).split(P).join(`/`)||t}function gi(e,t,n=A(e)){let r=Br(t),i=[],a=/* @__PURE__ */ new Map,o=[],s=0,c=(r,i)=>{let a=t.slice(0,r?.at??0).split(`
16
+ `).length;throw L(`BUILD_SOURCE_UNSUPPORTED`,`${Y(n,e)}:${a}: ${i}`,{file:Y(n,e),line:a})},l=()=>`__gpuEngineReexport${s++}`,u=e=>r[e],d=e=>r[e]?.text,f=e=>{let t=u(e);return(t===void 0||t.kind!==`name`&&t.kind!==`string`)&&c(t,`expected a name`),t?.text??``},p=e=>{let t=[],n=e+1;for(;d(n)!==`}`;){u(n)===void 0&&c(u(e),`an import or export list does not close`),d(n)===`type`&&u(n+1)?.kind===`name`&&d(n+1)!==`as`&&c(u(n),"a `type` specifier is left after stripping types");let r=f(n);n++;let i=r;d(n)===`as`&&u(n)?.kind===`name`&&(i=f(n+1),n+=2),t.push([r,i]),d(n)===`,`?n++:d(n)!==`}`&&c(u(n),`cannot read this import or export list`)}return{pairs:t,next:n+1}},m=e=>((d(e)!==`from`||u(e+1)?.kind!==`string`)&&c(u(e),"expected `from` and a string"),h(e+1)),h=e=>{let t=u(e),n=u(e+1);n?.kind===`name`&&(n.text===`with`||n.text===`assert`)&&d(e+2)===`{`&&c(n,`an import with attributes cannot be bundled`);let r=n?.text===`;`?n.end:t?.end??0;return{specifier:t?.text??``,end:r}},g=(e,t)=>(ui.test(e)||c(t,`\`${e}\` is not a name the bundle can bind`),e),_=(e,n)=>{let i=0,a=e;for(;a<r.length;a++){let o=r[a];if(o===void 0)break;if(mi.has(o.text)&&o.kind===`punct`)i++;else if(hi.has(o.text)&&o.kind===`punct`){if(i===0)return a;i--}else if(i===0&&o.kind===`punct`&&(o.text===`,`||o.text===`;`))return a;else if(n&&i===0&&o.kind===`name`&&pi.has(o.text)&&a>e){let e=r[a-1];if(e!==void 0&&t.slice(e.end,o.at).includes(`
17
+ `))return a}}return a},v=e=>{let t=u(e);if(t?.kind===`name`)return{names:[g(t.text,t)],next:e+1};let n=t?.text===`[`?`]`:t?.text===`{`?`}`:void 0;if(n===void 0)return c(t,`cannot read this exported declaration`);let r=[],i=e+1;for(;d(i)!==n;)if(u(i)===void 0&&c(t,`a destructuring pattern does not close`),n===`]`&&d(i)===`,`)i++;else{if(d(i)===`...`){let e=v(i+1);r.push(...e.names),i=e.next}else if(n===`]`){let e=v(i);r.push(...e.names),i=e.next}else{let e=u(i);if(e?.text===`[`?i=_(i+1,!1)+1:i++,d(i)===`:`){let e=v(i+1);r.push(...e.names),i=e.next}else e?.kind===`name`?r.push(g(e.text,e)):c(e,`cannot read this destructuring pattern`)}d(i)===`=`&&(i=_(i+1,!1)),d(i)===`,`?i++:d(i)!==n&&c(u(i),`cannot read this destructuring pattern`)}return{names:r,next:i+1}},y=/* @__PURE__ */ new Map,b=0;for(let e=0;e<r.length;e++){let t=r[e];if(t===void 0)break;if(t.kind===`punct`){mi.has(t.text)?b++:hi.has(t.text)&&b--;continue}let n=u(e+1);if(t.kind===`name`&&(t.text===`var`||t.text===`let`&&b===0)&&d(e-1)!==`.`&&(n?.kind===`name`||n?.text===`[`||n?.text===`{`)){for(let n=e+1;;n++){let e=v(n);for(let n of e.names)y.set(n,t);if(n=e.next,d(n)===`=`&&(n=_(n+1,!0)),d(n)!==`,`)break}continue}if(t.kind!==`name`||t.text!==`import`&&t.text!==`export`||d(e-1)===`.`)continue;let s=u(e+1);if(t.text===`import`&&s?.text===`(`&&c(t,"a dynamic `import()` cannot be bundled"),t.text===`import`&&s?.text===`.`||b!==0||s===void 0)continue;if(t.text===`import`){if(s.kind===`string`){let{specifier:n,end:r}=h(e+1);i.push({specifier:n,bindings:[],star:!1}),o.push({from:t.at,to:r,text:``});continue}let n=[],r=e+1;if(u(r)?.kind===`name`&&d(r)!==`from`?(n.push({imported:`default`,local:g(d(r)??``,u(r))}),r++,d(r)===`,`&&r++):d(r)===`from`&&d(r+1)===`from`&&(n.push({imported:`default`,local:`from`}),r++),d(r)===`*`)d(r+1)!==`as`&&c(u(r),"expected `* as name`"),n.push({imported:`*`,local:g(d(r+2)??``,u(r+2))}),r+=3;else if(d(r)===`{`){let e=p(r);for(let[t,i]of e.pairs)n.push({imported:t,local:g(i,u(r))});r=e.next}let{specifier:a,end:l}=m(r);i.push({specifier:a,bindings:n,star:!1}),o.push({from:t.at,to:l,text:``});continue}if(s.text===`{`){let n=p(e+1);if(d(n.next)===`from`){let{specifier:e,end:r}=m(n.next),s=n.pairs.map(([e,t])=>{let n=l();return a.set(t,n),{imported:e,local:n}});i.push({specifier:e,bindings:s,star:!1}),o.push({from:t.at,to:r,text:``})}else{for(let[e,t]of n.pairs)a.set(t,g(e,s));let e=d(n.next)===`;`?u(n.next)?.end??0:u(n.next-1)?.end??0;o.push({from:t.at,to:e,text:``})}continue}if(s.text===`*`){if(d(e+2)===`as`){let n=l();a.set(f(e+3),n);let{specifier:r,end:s}=m(e+4);i.push({specifier:r,bindings:[{imported:`*`,local:n}],star:!1}),o.push({from:t.at,to:s,text:``})}else{let{specifier:n,end:r}=m(e+2);i.push({specifier:n,bindings:[],star:!0}),o.push({from:t.at,to:r,text:``})}continue}if(s.text==="default"){let n=e+2;d(n)===`async`&&d(n+1)===`function`&&n++;let r=d(n);if(r===`function`||r===`class`){d(n+1)===`*`&&n++;let e=u(n+1);if(e?.kind===`name`&&e.text!==`extends`){a.set(`default`,g(e.text,e)),o.push({from:t.at,to:s.end,text:``});continue}}a.set(`default`,di),o.push({from:t.at,to:s.end,text:`const ${di} =`});continue}if(s.kind===`name`&&fi.has(s.text)){let n=e+2;for(;;){let e=v(n);for(let t of e.names)a.set(t,t);if(n=e.next,d(n)===`=`&&(n=_(n+1,!0)),d(n)!==`,`)break;n++}o.push({from:t.at,to:s.at,text:``});continue}let x=e+1;if(d(x)===`async`&&x++,d(x)===`function`||d(x)===`class`){d(x+1)===`*`&&x++;let e=u(x+1);e?.kind!==`name`&&c(e,`an exported function or class needs a name`),a.set(e?.text??``,g(e?.text??``,e)),o.push({from:t.at,to:s.at,text:``})}else c(t,`this export form cannot be bundled`)}let x=``,S=0;for(let e of o.toSorted((e,t)=>e.from-t.from))x+=t.slice(S,e.from)+e.text,S=e.to;x+=t.slice(S),x=x.replace(/^#!.*$/mu,``).replace(/^\/\/# sourceMappingURL=.*$/gmu,``);let C=/* @__PURE__ */ new Map;for(let[e,n]of a){let r=y.get(n);r!==void 0&&C.set(e,t.slice(0,r.at).split(`
18
+ `).length)}return{file:e,body:x,imports:i,exports:a,mutable:C}}function _i(e,t){return typeof e==`object`&&e?Object.entries(e).find(([e])=>e===t)?.[1]:void 0}function vi(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e)for(let t of[`browser`,`import`,`default`]){let n=vi(_i(e,t));if(n!==void 0)return n}}function yi(e,t){let n=_i(e,`exports`);if(n===void 0){if(t!==`.`)return t;let n=_i(e,`module`)??_i(e,`main`);return typeof n==`string`?n:`index.js`}return vi(typeof n==`string`||typeof n==`object`&&!(`.`in(n??{}))?t===`.`?n:void 0:_i(n,t))}var bi=class{root;packages=/* @__PURE__ */ new Set;constructor(e){this.root=e}unresolved(e,t){throw L(`BUILD_IMPORT_UNRESOLVED`,`${Y(this.root,e)}: ${t}`,{file:Y(this.root,e)})}unsupported(e,t){throw L(`BUILD_SOURCE_UNSUPPORTED`,`${Y(this.root,e)}: ${t}`,{file:Y(this.root,e)})}resolvePackage(e,t){let n=e.split(`/`),r=e.startsWith(`@`)?n.slice(0,2).join(`/`):n[0]??``,i=`.${e.slice(r.length)}`;for(let n=A(t);;n=A(n)){let a=j(n,`node_modules`,r),o=j(a,`package.json`);if(he(o)){let n=yi(JSON.parse(ge(o,`utf8`)),i);n===void 0&&this.unresolved(t,`${r} exports no \`${i}\` for import`);let s=N(a,n);return he(s)||this.unresolved(t,`${e} resolves to ${n}, which does not exist`),this.packages.add(_e(a)),_e(s)}A(n)===n&&this.unresolved(t,`cannot find the package \`${r}\``)}}resolveImport(e,t){if((e.startsWith(`node:`)||ce.includes(e))&&this.unsupported(t,`imports \`${e}\`, a Node built-in; the shipped module runs in browsers`),(e.startsWith(`/`)||e.startsWith(`file:`))&&this.unsupported(t,`imports the absolute path \`${e}\``),e.startsWith(`./`)||e.startsWith(`../`)){let n=N(A(t),e);return he(n)||this.unresolved(t,`imports \`${e}\`, which does not exist`),n}return this.resolvePackage(e,t)}readModule(e){e.endsWith(`.json`)&&this.unsupported(e,`a JSON import cannot be bundled; export the data from a .ts file`);let t=ge(e,`utf8`),n=t;if(/\.[cm]?ts$/u.test(e))try{n=xi(t)}catch(t){this.unsupported(e,t instanceof Error?t.message.split(`
19
+ `)[0]??``:String(t))}let r=gi(e,n,this.root),i=M(this.root,e),a=!i.startsWith(`..`)&&!i.split(P).includes(`node_modules`),[o]=r.mutable;if(a&&o!==void 0){let[t,n]=o;throw L(`BUILD_SOURCE_UNSUPPORTED`,`${Y(this.root,e)}:${n}: exports \`${t}\` from a \`let\` or \`var\`; the bundle reads each export once, so a later assignment would not reach the importers. Export a \`const\`, or a function that returns the current value`,{file:Y(this.root,e),line:n})}return r}};function xi(e){let t=Reflect.get(process,`emitWarning`),n=process.emitWarning.bind(process);Reflect.set(process,`emitWarning`,(e,...t)=>{String(e).includes(`stripTypeScriptTypes`)||Reflect.apply(n,process,[e,...t])});try{return ue(e,{mode:`strip`})}finally{Reflect.set(process,`emitWarning`,t)}}function Si(e){return`__gpuEngineModule${e}`}function Ci(e){return ui.test(e)?e:JSON.stringify(e)}function wi(e){return[...e].map(([e,t])=>e===t?t:`${Ci(e)}: ${t}`).join(`, `)}function Ti(e,t){return ui.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Ei(e,t){let n=new bi(t),r=[],i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set,s=e=>{let c=a.get(e);if(c!==void 0)return c;if(o.has(e))throw L(`BUILD_SOURCE_UNSUPPORTED`,`${Y(t,e)} is part of an import cycle`,{file:Y(t,e)});o.add(e);let l=n.readModule(e),u=l.imports.map(({specifier:t})=>n.resolveImport(t,e));i.set(l,u);for(let e of u)s(e);return o.delete(e),r.push(l),a.set(e,r.length-1),r.length-1},c=s(N(e)),l=/* @__PURE__ */ new Map,u=e=>{let t=l.get(e);if(t!==void 0)return t;let n=r[e],o=/* @__PURE__ */ new Map;if(n===void 0)return o;let s=i.get(n)??[];for(let[e,t]of n.imports.entries()){if(!t.star)continue;let n=a.get(s[e]??``)??-1;for(let e of u(n).keys())e!=="default"&&o.set(e,Ti(Si(n),e))}for(let[e,t]of n.exports)o.set(e,t);return l.set(e,o),o},d=r.map((e,n)=>{let r=i.get(e)??[],o=e.imports.flatMap((e,t)=>{let n=Si(a.get(r[t]??``)??-1),i=e.bindings.filter(e=>e.imported===`*`),o=e.bindings.filter(e=>e.imported!==`*`),s=i.map(e=>`const ${e.local} = ${n};`);return o.length>0&&s.push(`const { ${wi(o.map(e=>[e.imported,e.local]))} } = ${n};`),s});return[`// ${Y(t,e.file)}`,`const ${Si(n)} = (() => {`,...o,e.body.trim(),`return { ${wi(u(n))} };`,`})();`].join(`
20
+ `)}),f=[...u(c).keys()],p=f.filter(e=>e!=="default"),m=[];if(p.some(e=>!ui.test(e)))throw L(`BUILD_SOURCE_UNSUPPORTED`,`${Y(t,e)} exports a name that is not an identifier`);p.length>0&&m.push(`export const { ${p.join(`, `)} } = ${Si(c)};`),f.includes(`default`)&&m.push(`export default ${Si(c)}.default;`);let h=[...d,...m,``].join(`
21
+ `);Di(h);let g=Wr(h)[0];if(g!==void 0)throw L(`BUILD_SOURCE_UNSUPPORTED`,`the bundle still loads \`${g.specifier}\` (a \`require\` call or an import the build cannot read)`);return{text:h,packages:[...n.packages]}}function Di(e){let t=pe(process.execPath,[`--input-type=module`,`--check`],{input:e,encoding:`utf8`});if(t.status===0)return;let n=(t.stderr||String(t.error)).split(`
22
+ `),r=n.findIndex(e=>/^\[stdin\]:\d+$/u.test(e)),i=Number(n[r]?.slice(8)??0),a=n[r+2]?.indexOf(`^`)??-1,o=a===-1?void 0:/^[\w$]+/u.exec(n[r+1]?.slice(a)??``)?.[0],s=e.split(`
23
+ `).slice(0,i),c=s[s.findLastIndex(e=>/^const __gpuEngineModule\d+ = \(\(\) => \{$/u.test(e))-1]?.replace(/^\/\/ /u,``)??`the bundle`,l=n.find(e=>/^\w*Error: /u.test(e))??`it does not parse`;throw L(`BUILD_SOURCE_UNSUPPORTED`,`${c} ${o===`await`?"uses top-level `await`, which the bundle cannot keep: each module runs inside a function. Move the `await` into an async function, such as the `load` the package exports":`does not parse once bundled (${l})`}`,{file:c})}function Oi(e){return he(e)?ge(e,`utf8`):void 0}const ki=[`LICENSE`,`LICENSE.md`,`LICENSE.txt`,`LICENCE`,`LICENCE.md`];function Ai(e){let t=[];for(let n of e.split(/^## /mu).slice(1)){let[e=``]=n.split(`
24
+ `),r=/^- Project: (.+)$/mu.exec(n)?.[1],i=/^- Licen[cs]e: (.+)$/mu.exec(n)?.[1];i!==void 0&&t.push(`- ${e.trim()}${r===void 0?``:` (${r})`}: ${i}`)}return t}function ji(e){let t=["Built by `gpu-engine build`. Licences of the bundled packages:"];for(let n of e.toSorted()){let e=JSON.parse(ge(j(n,`package.json`),`utf8`)),r=_i(e,`name`),i=typeof r==`string`?r:n,a=ki.map(e=>j(n,e)).find(e=>he(e)),o=a===void 0?void 0:ge(a,`utf8`).trim(),s=_i(e,`license`),c=typeof s==`string`?s:`no licence file`;t.push(``,`${i}: ${o===void 0?c:``}`),o!==void 0&&t.push(...o.split(`
25
+ `));let l=Oi(j(n,`THIRD_PARTY_NOTICES.md`)),u=l===void 0?[]:Ai(l);u.length>0&&(t.push(``,`Third-party code in ${i}, under the same MIT permission notice (THIRD_PARTY_NOTICES.md):`),t.push(...u))}return[`/*!`,...t.map(e=>e===``?` *`:` * ${e.replaceAll(`*/`,`* /`)}`.trimEnd()),` */`,``].join(`
26
+ `)}function Mi(e){return/['\\\n\r\u2028\u2029]/u.test(e)?JSON.stringify(e):`'${e}'`}function Ni(e){return`{ id: ${Mi(e.id)}, text: ${Mi(e.text)} }`}function Pi(e,t){return[`// Written by \`gpu-engine build\` from ${e}, the table the eval names. Change that file, not this one.`,`import type { TableRow } from 'gpu-engine'`,``,`export const table: readonly TableRow[] = [`,...t.map(e=>` ${Ni(e)},`),`]`,``].join(`
27
+ `)}async function Fi(e){if(e.model.head.kind!==`retrieve`)return;let t=e.evaluation.table;if(t===void 0)throw L(`DATA_SET_MISSING`,`a retrieve head needs eval.table, and the eval has none`);let n;try{n=await Vt(e,t)}catch(e){throw e instanceof r?e:L(`DATA_SET_MISSING`,`${t} cannot be read, so the retrieve head has no table`,{file:t})}let{rows:i,invalid:a}=Kn(new TextDecoder().decode(n)),[o]=a;if(o!==void 0)throw L(`DATA_ROW_INVALID`,`${t}: ${a.length} line(s) are not { id, text } rows`,{file:t,line:o});if(i.length===0)throw L(`DATA_SET_MISSING`,`${t} has 0 rows`,{file:t});return{file:t,rows:i}}async function Ii(e,t){let n;try{n=await D(e,`utf8`)}catch{n=void 0}n!==t&&await O(e,t)}async function Li(e){let t=[],n=await Fi(e);if(n!==void 0){let r=Pi(n.file,n.rows);await Ii(j(e.dir,li),r),t.push({path:li,bytes:Buffer.byteLength(r),brotliBytes:K(Buffer.from(r))})}let r=j(e.dir,`src/index.ts`),i=Ei(r,e.dir),a=ji(i.packages)+i.text,o=oi(r,e.dir);await be(j(e.dir,`dist`),{recursive:!0});for(let[n,r]of[[`dist/index.mjs`,a],[`dist/index.d.mts`,o]])await O(j(e.dir,n),r),t.push({path:n,bytes:Buffer.byteLength(r),brotliBytes:K(Buffer.from(r))});return t}async function Ri(e){let t=await Yr(e.dir);for(let n of await Li(t))e.print(`wrote ${n.path} (${n.bytes} bytes, ${n.brotliBytes} Brotli bytes)`);return 0}function zi(e){return e.input.rows.some(e=>e.kind===`flag`)?e=>e:e=>typeof e==`string`?e:e.text}function Bi(e){let{evaluation:t}=e;if(typeof t.metric!=`function`)throw TypeError(`the eval definition has no metric function`);return t}function Vi(e,t,n,r){switch(e.kind){case`tag`:return p.tag.decode(e,t,n);case`pooled`:return p.pooled.decode(e,t,n);case`retrieve`:return p.retrieve.decode(e,t,n,r?.ids);default:throw Error(`no decode for head kind '${i(e)}'`)}}function Hi(e,t,n){if(t.definition.head.kind!==`retrieve`)return;let{table:r}=e;if(r===void 0||r.length===0)throw L(`RUN_TABLE_MISSING`,`a retrieve head is scored against eval.table, and it has no rows`);return m(t,n,r)}function Ui(e,t,n,r){let i=c(e.definition.input,n),a=T(e,t,i.rows,i.count);if(e.definition.head.kind===`retrieve`){if(r===void 0)throw L(`RUN_TABLE_MISSING`,`a retrieve head needs the encoded table`);a=ae(a,r.vectors,r.rows,r.size)}return Vi(e.definition.head,a,i.count,r)}function Wi(e,t,n,r){if(typeof e==`number`&&Number.isFinite(e))return e;throw TypeError(`metric returned ${String(e)} for ${t} on ${n} row ${r+1}, expected a number`)}function Gi(e,t,n){let r=Bi(e),{decode:i}=r,a=zi(t.definition),o=i===void 0?e=>e:(e,t)=>i(e,a(t)),s=Hi(e,t,n);return{evaluation:r,decode:o,input:a,table:s,gold:e=>s===void 0?e:oe(e,s.ids),predict:e=>o(Ui(t,n,e,s),e)}}function Ki(e,t){return t.expect===void 0?e.decode(e.gold(t.gold),t.input):t.expect}function qi(e,t,n,r,i){let a=Gi(e,t,n),{metric:o,baselines:s}=a.evaluation;return i.map((e,t)=>{let n=Ki(a,e),i=a.predict(e.input),c={};for(let[i,l]of Object.entries(s))c[i]=Wi(o(l(a.input(e.input)),n),i,r,t);let l=Wi(o(a.decode(a.gold(e.gold),e.input),n),`oracle`,r,t);return{model:Wi(o(i,n),`model`,r,t),baselines:c,oracle:l,predicted:i,reference:n}})}function Ji(e){return e.length===0?0:e.reduce((e,t)=>e+t,0)/e.length}function Yi(e,t,n,r){let i=Gi(e,t,n),{metric:a}=i.evaluation,o={};for(let[e,t]of Object.entries(r))o[e]=Ji(t.map((t,n)=>{let r=i.predict(t.input);return Wi(a(r,Ki(i,t)),`model`,e,n)}));return o}function Xi(e){return Ji(Object.values(e))}function Zi(e,t,n){let r=a(e.model),i={};for(let[a,o]of Object.entries(n)){let n=qi(e,r,t,a,o),s={};for(let t of Object.keys(e.evaluation.baselines))s[t]=Ji(n.map(e=>e.baselines[t]??0));i[a]={examples:o.length,model:Ji(n.map(e=>e.model)),baselines:s,oracle:Ji(n.map(e=>e.oracle))}}return i}const X=`report.json`,Qi=`MODEL_CARD.md`,$i=`RESULTS.md`,ea=`src/weights.ts`,ta=`parity.json`;function Z(e){return`weights/${e}.bin`}function na(e){return`${JSON.stringify(e,null,2)}\n`}function ra(e,t,n){return[`// Generated by \`gpu-engine promote\` from ${Z(e)}. Do not edit: \`gpu-engine promote --verify\` regenerates it.`,``,`/** The promoted weights file, lowercase hex. SHA-256 ${t}. */`,`export const weightsHex =`,` '${Buffer.from(n).toString(`hex`)}'`,``].join(`
28
+ `)}const ia=e=>e.toFixed(3),Q=e=>`\`${e}\``;function aa(e,t){let n=[e,...t].map(e=>e.map(e=>e.replaceAll(`|`,`\\|`))),r=e.map((e,t)=>Math.max(3,...n.map(e=>(e[t]??``).length))),i=e=>`| ${r.map((t,n)=>(e[n]??``).padEnd(t)).join(` | `)} |`,[a=[],...o]=n;return[i(a),`| ${r.map(e=>`-`.repeat(e)).join(` | `)} |`,...o.map(i)]}function oa(e){let t=/* @__PURE__ */ new Set;for(let n of[e.dev,e.test])for(let e of Object.values(n))for(let n of Object.keys(e.baselines))t.add(n);return[...t]}function sa(e,t,n){let r=Object.entries(t),i=[e,...r.map(([e,t])=>`${e} (${t.examples})`)],a=(e,t)=>[e,...r.map(([,e])=>{let n=t(e);return n===void 0?``:ia(n)})];return aa(i,[a(`model`,e=>e.model),...n.map(e=>a(`baseline ${e}`,t=>t.baselines[e])),a(`oracle`,e=>e.oracle)])}function ca(e){return e.map(e=>{let t=e.code===void 0?``:` (${Q(e.code)})`;return`- ${e.pass?`pass`:`FAIL`} ${e.name}: ${e.detail}${t}`})}const la={1:`convention and lint`,2:`counted reads`,3:`out of reach`},ua=/llvmpipe|lavapipe|swiftshader|softpipe|\bwarp\b|software/iu,da=[`llvmpipe`,`lavapipe`,`swiftshader`,`softpipe`,`warp`];function fa(e){if(!ua.test(e))return;let t=da.find(t=>RegExp(`\\b${t}\\b`,`iu`).test(e));return t===void 0?`software adapter`:`software adapter (${t})`}function pa(e,t){if(t===null)return["Parity has not run for these weights. Run `gpu-engine parity` to compare the trainer, the CPU runtime and the WGSL runtime."];let n=fa(t.adapter),r=`the WebGPU adapter ${Q(t.adapter)}${n===void 0?``:`, a ${n}`}`;return[`Measured on ${t.date} for weights SHA-256 ${Q(e.weights.sha256)}.`,``,`- Trainer and CPU: ${t.trainerCpu} (one forward pass).`,`- CPU and WGSL on ${r}: largest logit difference ${t.maxDifference.toExponential(2)} (tolerance ${t.tolerance.toExponential(2)}), decoded results differ on ${t.decodeDiffers} of ${t.fixtures} fixtures.`,...n===void 0?[]:[`- Parity and speed figures here are from a ${n}, not a GPU.`],`- Real GPU: ${t.realGpu}.`,`- Real browser: not run.`]}function ma(e){let t=[];for(let n of[`train`,`dev`,`test`])for(let[r,i]of Object.entries(e.data[n]))t.push([n,Q(r),String(i.examples),Q(i.sha256)]);for(let[n,r]of Object.entries(e.data.table??{}))t.push([`table`,Q(n),String(r.examples),Q(r.sha256)]);return aa([`Set`,`File`,`Examples`,`SHA-256`],t)}function ha(e){let{train:t}=e;return aa([`Seed`,`Best dev score`],Object.entries(t.devBySeed).map(([e,n])=>[e===String(t.chosenSeed)?`${e} (chosen)`:e,ia(n)]))}function ga(e,t,n){let r=oa(e),i=`${e.testReads} ${e.testReads===1?`time`:`times`}`,{train:a}=e;return[`# ${e.name}`,``,"Generated by `gpu-engine promote` from `report.json`. Do not edit it: `gpu-engine promote --verify` regenerates it and fails on any difference.",``,...aa([`Field`,`Value`],[[`Promoted`,e.date],[`Commit`,Q(e.commit)],[`Definition hash`,Q(e.definition)],[`Weights`,`${Q(Z(e.name))}, ${e.weights.bytes} bytes, ${e.weights.brotliBytes} Brotli bytes`],[`Weights SHA-256`,Q(e.weights.sha256)],[`Parameters`,String(e.params)],[`Multiply-adds per token`,String(e.macsPerToken)]]),``,`## Test set`,``,`Sealed at level ${e.level} (${la[e.level]}). The test set has been read ${i}, counted in \`reads.jsonl\`; the test scores below come from the last read. Test results are per-set aggregates only.`,``,`## Scores`,``,`The model on its ${n.quant===void 0?`float32`:n.quant.kind} weights, each baseline, and the oracle: the gold through \`decode\`, the ceiling the decode step allows.`,``,...sa(`dev`,e.dev,r),``,...sa(`test`,e.test,r),``,`## Training`,``,`Seeds ${a.seeds.join(`, `)}; the ${a.checkpoint} checkpoint of seed ${a.chosenSeed} after ${a.steps} steps; ${a.seconds.toFixed(1)} s for all seeds.`,``,...ha(e),``,`## Gate`,``,...ca(e.gate),``,`## Data`,``,...ma(e),``,`## Parity`,``,...pa(e,t),``].join(`
29
+ `)}function _a(e){let t=oa(e);return[`# ${e.name} results`,``,`Generated by \`gpu-engine promote\` from \`report.json\` (promoted ${e.date}, weights SHA-256 ${Q(e.weights.sha256)}). Do not edit it.`,``,`## dev`,``,...sa(`dev`,e.dev,t),``,`## test`,``,...sa(`test`,e.test,t),``,`## Gate`,``,...ca(e.gate),``].join(`
30
+ `)}function va(e){throw L(`VERIFY_REPORT_INVALID`,`${X}: ${e} is missing or has the wrong type`,{file:X})}const ya=Mt(B),ba=Mt(z({examples:V,model:B,baselines:ya,oracle:B})),xa=F.custom(e=>typeof e==`string`&&Object.hasOwn(Be,e)),Sa=Mt(z({sha256:Nt,examples:V})),Ca=z({name:F.string(),date:F.string(),commit:F.string(),definition:F.string(),weights:z({sha256:F.string(),bytes:V,brotliBytes:V}),params:V,macsPerToken:V,train:z({seeds:F.array(Pt),chosenSeed:Pt,checkpoint:F.picklist([`best`,`last`]),steps:V,seconds:B,devBySeed:ya}),data:z({train:Sa,dev:Sa,test:Sa,table:F.optional(Sa)}),dev:ba,test:ba,gate:F.array(z({name:F.string(),pass:F.boolean(),detail:F.string(),code:F.optional(xa)})),testReads:V,level:F.picklist([1,2,3])});function wa(e){let t=Ot(Ca,e);return t.ok?t.value:va(t.field===void 0?`the file (not JSON)`:t.field||`the report`)}const Ta=z({date:F.string(),weights:F.string(),adapter:F.string(),tolerance:F.number(),fixtures:F.number(),trainerCpu:F.literal(`identical`),maxDifference:F.number(),decodeDiffers:F.number(),realGpu:F.string()});function Ea(e){let t=Ot(Ta,e);return t.ok?t.value:null}const Da=`tries.jsonl`,Oa=[`at`,`commit`,`dirty`,`idea`,`status`,`definition`,`seeds`,`dev`,`devScore`,`devSpread`,`brotliBytes`,`macsPerToken`,`trainSeconds`,`gate`],ka=`diverged`;function Aa(e){let t=e.diverged===void 0?Oa:[...Oa,ka];return Object.fromEntries(t.map(t=>[t,e[t]]))}function ja(e,t,n){if(Array.isArray(e))for(let[r,i]of e.entries())ja(i,`${t}[${r}]`,n);else if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e)){let e=t===``?r:`${t}.${r}`;n.push(e),ja(i,e,n)}return n}function Ma(e){let t=ja(e,``,[]).filter(e=>/test/iu.test(e.split(`.`).at(-1)??``));if(t.length>0)throw L(`DATA_TEST_PRINTED`,`a tries row may not hold test fields; refused keys: ${t.join(`, `)}`);let n=typeof e==`object`&&e?Object.keys(e):[],r=/* @__PURE__ */ new Set([...Oa,ka]),i=n.filter(e=>!r.has(e)),a=Oa.filter(e=>!n.includes(e));if(i.length>0||a.length>0){let e=[...i.length>0?[`unknown keys: ${i.join(`, `)}`]:[],...a.length>0?[`missing keys: ${a.join(`, `)}`]:[]];throw TypeError(`a tries row has the closed key list ${Oa.join(`, `)}; ${e.join(`; `)}`)}}async function Na(e,t){Ma(t),await ve(j(e.dir,Da),`${JSON.stringify(Aa(t))}\n`)}function Pa(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function Fa(e){let t;try{t=JSON.parse(e)}catch{return`it is not JSON`}try{Ma(t)}catch(e){return e instanceof Error?e.message:String(e)}return t.status===null||t.status===`kept`||t.status===`dropped`?t:`its status is not kept, dropped or null`}function Ia(e){let t=[];for(let[n,r]of e.split(`
31
+ `).entries()){if(r.trim()===``)continue;let e=Fa(r);if(typeof e==`string`)throw L(`PROJECT_STATE_INVALID`,`line ${n+1} of ${Da} is not a tries row: ${e}`,{file:Da,line:n+1});t.push({line:n+1,row:e})}return t}async function La(e){try{return Ia(await D(j(e.dir,Da),`utf8`)).map(({row:e})=>e)}catch(e){if(Pa(e))return[];throw e}}async function Ra(e,t){let n=j(e.dir,Da),r=()=>L(`CLI_FLAG_INVALID`,`--mark needs a try to mark, and ${Da} has none; run a try first`),i;try{i=await D(n,`utf8`)}catch(e){throw Pa(e)?r():e}let a=Ia(i).at(-1);if(a===void 0)throw r();let{row:o}=a;if(o.status!==null)throw L(`CLI_FLAG_INVALID`,`the last try is already marked ${o.status}; --mark sets a status once`);let s={...o,status:t},c=i.split(`
32
+ `);return c[a.line-1]=JSON.stringify(Aa(s)),await O(n,c.join(`
33
+ `)),s}const za=`.gpu-engine`,Ba=`${za}/candidate.bin`,Va=`${za}/candidate.json`,Ha=`${za}/checkpoints`,Ua=Me(fe);async function Wa(e){try{let t=await Ua(`git`,[`rev-parse`,`HEAD`],{cwd:e}),n=await Ua(`git`,[`status`,`--porcelain`,`--`,`:(top)`,`:(exclude)${Da}`,`:(exclude)reads.jsonl`],{cwd:e});return{commit:t.stdout.trim(),dirty:n.stdout.trim()!==``}}catch{return{commit:`none`,dirty:!1}}}function Ga(e){let t=t=>Object.fromEntries(Object.entries(e[t]?.files??{}).map(([e,{sha256:t}])=>[e,t])),n={train:t(`train`),dev:t(`dev`),test:t(`test`)};return e.table===void 0?n:{...n,table:t(`table`)}}function Ka(e,t){let n=Object.entries(e??{}),r=t??{};return n.length===Object.keys(r).length&&n.every(([e,t])=>r[e]===t)}function qa(e,t,n){if(e.definition!==t)return`the candidate was trained from definition ${e.definition}, the model file now hashes to ${t}`;let r=ar.filter(t=>!Ka(e.data[t],n[t]));return r.length===0?void 0:`the ${r.join(`, `)} data changed after the candidate was trained`}const Ja=Mt(Nt),Ya=z({at:F.string(),commit:F.string(),dirty:F.boolean(),definition:F.string(),data:z({train:Ja,dev:Ja,test:Ja,table:F.optional(Ja)}),seeds:F.array(Pt),seed:Pt,checkpoint:F.picklist([`best`,`last`]),steps:V,trainSeconds:B,stoppedBy:F.picklist([`epochs`,`budget`]),devBySeed:Mt(B),dev:ba,devScore:B,devSpread:B,brotliBytes:V,macsPerToken:V});function Xa(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}async function Za(e){try{let t=await D(j(e.dir,Va),`utf8`),n=await D(j(e.dir,Ba)),r=Ot(Ya,t);if(!r.ok){let e=r.field===void 0?`it is not JSON`:`${r.field||`the file`} is missing or has the wrong type`;throw L(`PROJECT_STATE_INVALID`,`${Va} is not a candidate: ${e}`,{file:Va})}return{candidate:r.value,bytes:n}}catch(e){throw Xa(e)?L(`PROMOTE_CANDIDATE_MISSING`,`${Va} or ${Ba} does not exist`):e}}async function Qa(e,t,n,r){await we(j(e.dir,Ha),{recursive:!0,force:!0}),await be(j(e.dir,Ha),{recursive:!0});for(let n of t.runs)for(let r of[`best`,`last`]){let i=C(b(t.plan,n[r].weights));await O(j(e.dir,Ha,`seed-${n.seed}-${r}.bin`),i)}await O(j(e.dir,Ba),r),await O(j(e.dir,Va),`${JSON.stringify(n,null,2)}\n`)}const $a=e=>e.toFixed(3);function eo(e,t,n){let{seed:r,best:i,steps:a,seconds:o,stoppedBy:s}=e;return`train: seed ${r} done (${t+1}/${n}), best dev ${$a(i.dev)} at epoch ${i.epoch}, ${a} steps, ${o.toFixed(1)} s, stopped by ${s}`}function to(e,t,n){let r=Object.keys(t),i=[[`model`,e=>e.model],...n.map(e=>[`baseline ${e}`,t=>t.baselines[e]??NaN]),[`oracle`,e=>e.oracle]],a=r.map(e=>`${e} (${t[e]?.examples??0})`),o=Math.max(e.length,...i.map(([e])=>e.length)),s=a.map(e=>Math.max(e.length,5)),c=(e,t)=>[e.padEnd(o),...t.map((e,t)=>e.padStart(s[t]??5))].join(` `);return[c(e,a),...i.map(([e,n])=>c(e,r.map(e=>$a(n(t[e]??no)))))]}const no={examples:0,model:NaN,baselines:{},oracle:NaN};function ro(e){return Object.values(e).flat()}function io(e,t){for(let n of t)e.printError(R(n));return t.length>0}function ao(e){let t=Object.values(e);return t.length===0?0:Math.max(...t)-Math.min(...t)}async function oo(e,t,n){let{candidate:r,bytes:i}=await Za(t),a=await gr(e,t);if(io(e,a.diagnostics))return 1;let o=qa(r,n.hash,Ga(a.lock));if(o!==void 0)throw L(`PROMOTE_CANDIDATE_STALE`,o);let s=a.examples.dev,c=typeof e.flags.set==`string`?e.flags.set:void 0;if(c!==void 0&&!Object.hasOwn(s,c))throw L(`CLI_FLAG_INVALID`,`--set ${c} is not a dev set; the dev sets are ${Object.keys(s).join(`, `)}`);let l=E(v(i),n),u=0;for(let[r,i]of Object.entries(s))if(c===void 0||r===c)for(let[a,o]of qi(t,n,l,r,i).entries()){if(o.model>=o.oracle)continue;u++;let t=JSON.stringify(i[a]?.input),n=JSON.stringify(o.reference);e.print(`dev ${r} row ${a+1}: input ${t} expected ${n} got ${JSON.stringify(o.predicted)}`)}return e.print(`${u} dev ${u===1?`miss`:`misses`}`),0}function so(e,t){let n=[];for(let r of e.split(`,`)){let e=Fn.find(e=>e===r);if(e===void 0||n.includes(e))throw L(`CLI_FLAG_INVALID`,`--regenerate takes train, dev or train,dev; ${r===`test`?`the test set is written once and never regenerated`:`'${r}' is not one of them or repeats`}`);if(t.evaluation.data.generate?.[e]===void 0)throw L(`CLI_FLAG_INVALID`,`--regenerate ${e}: the eval file declares no ${e} generator`);n.push(e)}return n}async function co(e){let t=e.flags.mark;if(t===`kept`||t===`dropped`){let n=Object.keys(e.flags).filter(e=>e!==`mark`&&e!==`dir`);if(n.length>0)throw L(`CLI_FLAG_INVALID`,`--mark takes no other loop flag but --dir; got --${n.join(`, --`)}`);let r=await Ra({dir:e.dir},t);return e.print(`try: marked the last try (${r.at}, dev ${$a(r.devScore)}) ${t}`),0}let n=await Yr(e.dir),r=a(n.model);if(io(e,await An(n.dir)))return 1;if(e.flags.fail===!0)return oo(e,n,r);if(await La(n),typeof e.flags.regenerate==`string`){let t=so(e.flags.regenerate,n),r=await Ln(n,t);for(let[n,i]of r.entries())e.print(`data: regenerated ${i} and removed the ${t[n]??``} entry of data.lock.json`)}let i=await gr(e,n);if(io(e,i.diagnostics))return 1;for(let t of i.written)e.print(`data: wrote ${t}`);let o=n.evaluation.train,s=i.examples.dev,c=await Dt(n.model,{train:ro(i.examples.train),dev:ro(s),...n.table?{table:n.table}:{}},o,e=>Xi(Yi(n,e.plan,e.weights,s)),(t,n,r)=>e.print(eo(t,n,r))),l=C(b(c.plan,c.weights)),u=Zi(n,c.weights,s),d=Object.fromEntries(Object.entries(u).map(([e,t])=>[e,t.model])),f=ao(c.devBySeed),p=K(l),m=Ga(i.lock),h=await Ar(n),g=xr({noise:n.evaluation.gate.noise,budgets:n.model.budgets,promoted:h.promoted,scores:{dev:u},spread:f,brotliBytes:p,macsPerToken:r.macsPerToken,data:{files:U.reduce((e,t)=>e+Object.keys(m[t]).length,0),changed:[]}}),_=Sr(g),{commit:v,dirty:y}=await Wa(n.dir),x=(/* @__PURE__ */ new Date()).toISOString(),S={at:x,commit:v,dirty:y,definition:r.hash,data:m,seeds:o.seeds,seed:c.seed,checkpoint:c.checkpoint,steps:c.steps,trainSeconds:c.seconds,stoppedBy:c.stoppedBy,devBySeed:c.devBySeed,dev:u,devScore:Xi(d),devSpread:f,brotliBytes:p,macsPerToken:r.macsPerToken};await Qa(n,c,S,l);let w=c.seconds.toFixed(1);e.print(`train: seeds ${o.seeds.join(`, `)}; chose seed ${c.seed} (${c.checkpoint} checkpoint, ${c.steps} steps); ${w} s, stopped by ${c.stoppedBy}`);let T=Object.fromEntries(c.runs.flatMap(e=>e.divergedAt===void 0?[]:[[String(e.seed),e.divergedAt]])),E=Object.entries(T).map(([e,t])=>`seed ${e} at step ${t}`);E.length>0&&e.print(`note: training diverged on ${E.join(`, `)} (the loss stopped being finite; checkpoints with non-finite weights were not scored); lower train.learningRate or raise train.warmup`),e.print(``);for(let t of to(`dev`,u,Object.keys(n.evaluation.baselines)))e.print(t);e.print(``);for(let t of g)e.print(Cr(t));return e.print(``),e.print(`candidate: ${Ba} (dev ${$a(S.devScore)}, ${p} Brotli bytes)`),await Na(n,{at:x,commit:v,dirty:y,idea:typeof e.flags.log==`string`?e.flags.log:``,status:e.flags.status===`kept`||e.flags.status===`dropped`?e.flags.status:null,definition:r.hash,seeds:o.seeds,dev:d,devScore:S.devScore,devSpread:f,brotliBytes:p,macsPerToken:r.macsPerToken,trainSeconds:c.seconds,gate:_?`pass`:`fail`,...E.length>0?{diverged:T}:{}}),e.print(`try: appended to tries.jsonl (gate ${_?`pass`:`fail`})`),+!_}const lo=[`log`,`info`,`warn`,`error`,`debug`,`trace`,`dir`,`dirxml`,`table`,`group`,`groupCollapsed`,`assert`,`count`,`timeLog`,`timeEnd`],uo=[`write`,`writeSync`,`writev`,`writevSync`,`writeFile`,`writeFileSync`,`appendFile`,`appendFileSync`],fo=/* @__PURE__ */ new Set([1,2]),po=[`unhandledRejection`,`uncaughtException`];function mo(e){return typeof e==`function`}function ho(e){return typeof e[0]==`number`&&fo.has(e[0])}function go(e){let[t]=e;return t!=null&&typeof t!=`function`}function _o(){let e=!1,t=0,n=0,r=0,i,a=[],o=(r,o,s=()=>!0)=>{let c=Object.getOwnPropertyDescriptor(r,o),l=Reflect.get(r,o);typeof l==`function`&&(Object.defineProperty(r,o,{value:function(...a){if(!e||t>0||!s(a))return Reflect.apply(l,this??r,a);n++,i?.(`print`);let o=a.at(-1);return typeof o==`function`&&queueMicrotask(()=>Reflect.apply(o,void 0,[null])),!0},writable:!0,configurable:!0,enumerable:c?.enumerable??!1}),a.push(()=>{c===void 0?Reflect.deleteProperty(r,o):Object.defineProperty(r,o,c)}))};for(let e of lo)o(console,e);for(let e of[process.stdout,process.stderr])o(e,`write`),o(e,`end`,go);o(process,`_rawDebug`);for(let e of uo)o(me,e,ho);de(),a.push(()=>de());let s=()=>{r++,i?.(`error`)},c=/* @__PURE__ */ new Map,l=()=>{for(let e of po)c.set(e,process.rawListeners(e)),process.removeAllListeners(e),process.on(e,s)},u=()=>{for(let e of po){let t=c.get(e);if(t!==void 0){process.removeListener(e,s);for(let n of t)mo(n)&&process.on(e,n)}}c.clear()};return{attempts:()=>n,errors:()=>r,start:()=>{e=!0,l()},own:e=>{t++;try{e()}finally{t--}},settle:async()=>{await Le(0),await Ie()},hold:e=>{i=e},restore:()=>{u();for(let e of a.splice(0).toReversed())e()}}}const vo=`reads.jsonl`,yo=`weights`,bo=`.gpu-engine`,xo=[yo,ea,G,X,Qi,$i,vo,Da],So=Me(fe);let Co=0;async function wo(e,t){await be(j(e,bo),{recursive:!0});let n=[];try{for(let[r,i]of t){Co++;let t=j(e,bo,`write-${process.pid}-${Co}.tmp`);n.push([t,j(e,r)]),await O(t,i)}for(let[e,t]of n)await be(A(t),{recursive:!0}),await Ce(e,t)}finally{await Promise.all(n.map(([e])=>we(e,{force:!0})))}}function To(e){return e.split(P).join(`/`)}async function Eo(e,t){try{return(await xe(j(e,t),{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(t=>To(M(e,j(t.parentPath,t.name)))).toSorted()}catch{return[]}}async function Do(e){try{return await D(e)}catch{return}}async function Oo(e){let t=await Eo(e,yo);for(let n of xo.slice(1))await Do(j(e,n))!==void 0&&t.push(n);return t}async function ko(e,t){try{let{stdout:n}=await So(`git`,[`show`,`HEAD:./${t}`],{cwd:e,encoding:`buffer`,maxBuffer:268435456});return n}catch{return}}async function Ao(e,t){let n=await ko(e,t);n===void 0?await we(j(e,t),{force:!0}):await wo(e,[[t,n]])}function jo(e,t){let n=e;for(let e of t)n=n.replaceAll(e,``);return n}function Mo(e){let t=/* @__PURE__ */ new Set;for(let n of e)t.add(n),n.endsWith(`.enc`)&&t.add(n.slice(0,-4));return[...t].toSorted((e,t)=>t.length-e.length)}async function No(e,t,n){let r=await Oo(e),i=/* @__PURE__ */ new Map;for(let t of r)i.set(t,jo((await D(j(e,t))).toString(`utf8`),n));let a=t([...r.map(e=>jo(e,n)),...i.values()]);if(a===0)return{inputs:0,files:0};let o=0;for(let a of r){let r=i.get(a)??``;if(t([jo(a,n)])>0)await we(j(e,a),{force:!0}),o++;else if(t([r])===0)continue;else a.endsWith(`.jsonl`)?(await wo(e,[[a,(await D(j(e,a),`utf8`)).split(`
34
+ `).filter(e=>t([jo(e,n)])===0).join(`
35
+ `)]]),o++):(await Ao(e,a),o++)}return{inputs:a,files:o}}const Po=[`new`,`loop`,`promote`,`parity`,`inspect`,`doctor`],Fo=[`at`,`kind`,`command`,`commit`,`files`,`examples`,`outcome`],Io=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/u,Lo=/^(?:[0-9a-f]{40}|[0-9a-f]{64}|none)$/u;function Ro(e,t){let n;try{n=JSON.parse(e)}catch{return!1}if(typeof n!=`object`||!n||Array.isArray(n))return!1;let r=Object.keys(n);if(r.length!==Fo.length||!Fo.every(e=>r.includes(e)))return!1;let i=e=>Object.entries(n).find(([t])=>t===e)?.[1],a=i(`at`),o=i(`commit`),s=i(`files`),c=i(`examples`);return typeof a==`string`&&Io.test(a)&&(i(`kind`)===`digest`||i(`kind`)===`examples`)&&Po.some(e=>e===i(`command`))&&typeof o==`string`&&Lo.test(o)&&Array.isArray(s)&&s.every(e=>typeof e==`string`&&t.includes(e))&&typeof c==`number`&&Number.isSafeInteger(c)&&c>=0&&(i(`outcome`)===`ok`||i(`outcome`)===`failed`)}function zo(e){return e.split(`
36
+ `).filter(e=>e.trim()!==``)}async function Bo(e,t){for(let t of await Oo(e))t!==`reads.jsonl`&&await Ao(e,t);let n=await Do(j(e,vo));if(n===void 0)return;let r=zo((await ko(e,`reads.jsonl`))?.toString(`utf8`)??``),i=new Set(r),a=zo(n.toString(`utf8`)).filter(e=>!i.has(e)&&Ro(e,t)),o=[...r,...a];await wo(e,[[vo,o.length===0?``:`${o.join(`
37
+ `)}\n`]])}const Vo=`.github/workflows/promote.yml`,$=`GPU_ENGINE_TEST_KEY`,Ho=Me(fe);function Uo(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}async function Wo(e){try{return await D(e),!0}catch(e){if(Uo(e))return!1;throw e}}async function Go(e){let t=e,n=[];for(;;)try{return j(await Se(t),...n)}catch{let r=A(t);if(r===t)return e;n.unshift(k(t)),t=r}}function Ko(e,t){let n=M(t,e);return n===``||n!==`..`&&!n.startsWith(`..${P}`)&&!De(n)}async function qo(e){try{let{stdout:t}=await Ho(`git`,[`rev-parse`,`--show-toplevel`],{cwd:e});return t.trim()}catch{return}}function Jo(e){let t=e.trim();if(!(/* @__PURE__ */ RegExp(`^[0-9a-fA-F]{64}$`,`u`)).test(t))throw L(`SEAL_KEY_INVALID`,`${$} is not 64 hex characters`);return Buffer.from(t,`hex`)}function Yo(e){if(e.CI!==`true`)throw L(`PROMOTE_OUTSIDE_CI`,"the test set is sealed at level 3 and CI is not `true`; nothing was read");let t=e[$];if(t===void 0||t.trim()===``)throw L(`SEAL_KEY_MISSING`,`the test set is sealed at level 3 and ${$} is not set`);return Jo(t)}async function Xo(e,t){return t===3||(await mn(e,W(e,`test`))).sealed.length>0}function Zo(e,t){return e===t||e===3&&t<3}function Qo(e){let t=e.test;if(t===void 0)return e;let n={};for(let[e,r]of Object.entries(t.files))e.endsWith(`.enc`)&&r.plaintext!==void 0?n[e.slice(0,-4)]={sha256:r.plaintext,examples:r.examples}:n[e]=r;return{...e,test:{...t,files:n}}}function $o(){return`# Written by \`gpu-engine promote --seal\`. The test set is sealed (level 3): only this workflow reads it, with the
38
+ # key in the repository secret ${$}. CI has no candidate (.gpu-engine/ is not committed), so it trains one
39
+ # with \`loop\` first, promotes it, and commits the promotion and the read log back to the branch.
40
+ name: promote
41
+
42
+ on:
43
+ workflow_dispatch:
44
+
45
+ permissions:
46
+ contents: write
47
+
48
+ concurrency:
49
+ group: promote-\${{ github.ref }}
50
+ cancel-in-progress: false
51
+
52
+ jobs:
53
+ promote:
54
+ runs-on: ubuntu-latest
55
+ timeout-minutes: 60
56
+ steps:
57
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
58
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
59
+ with:
60
+ node-version: 24
61
+ - name: Install
62
+ run: |
63
+ set -euo pipefail
64
+ corepack enable
65
+ if [ -f pnpm-lock.yaml ]; then pnpm install --frozen-lockfile
66
+ elif [ -f package-lock.json ]; then npm ci
67
+ else npm install
68
+ fi
69
+ - name: Train a candidate
70
+ run: |
71
+ set -euo pipefail
72
+ ./node_modules/.bin/gpu-engine loop --log "promote workflow"
73
+ - name: Promote
74
+ id: promote
75
+ env:
76
+ ${$}: \${{ secrets.${$} }}
77
+ run: |
78
+ set -euo pipefail
79
+ ./node_modules/.bin/gpu-engine promote
80
+ # Runs after a failed promote too, so every read of the test set stays counted in reads.jsonl. The scan first
81
+ # removes any test input the package's code wrote into these files, or puts them back when it cannot scan.
82
+ # Only exit 0 (clean) and 3 (repaired) confirm they are safe to commit: any other code, a refusal
83
+ # or a crash, commits nothing. The job then fails with the scan's exit code.
84
+ - name: Scan and commit the promotion and the read log
85
+ if: \${{ !cancelled() && steps.promote.outcome != 'skipped' }}
86
+ env:
87
+ ${$}: \${{ secrets.${$} }}
88
+ run: |
89
+ set -euo pipefail
90
+ scan=0
91
+ ./node_modules/.bin/gpu-engine promote --scan || scan=$?
92
+ if [ "$scan" -ne 0 ] && [ "$scan" -ne 3 ]; then exit "$scan"; fi
93
+ git config user.name "github-actions[bot]"
94
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
95
+ for path in ${xo.join(` `)}; do
96
+ if [ -e "$path" ]; then git add -- "$path"; fi
97
+ done
98
+ if git diff --cached --quiet; then exit "$scan"; fi
99
+ git commit -m "chore: promote in CI (\${{ steps.promote.outcome }})"
100
+ git push
101
+ exit "$scan"
102
+ `}async function es(e,t){let n;try{n=(await Ho(`git`,[`-c`,`core.quotePath=false`,`log`,`--all`,`--full-history`,`--no-renames`,`--relative`,`--name-only`,`--format=%x00%H`,`--`,t],{cwd:e,maxBuffer:67108864})).stdout}catch{return{paths:[],commits:0}}let r=/* @__PURE__ */ new Set,i=0;for(let e of n.split(`\0`).slice(1)){let t=e.split(`
103
+ `).slice(1).filter(e=>e.trim()!==``&&!e.endsWith(`.enc`));if(t.length!==0){i++;for(let e of t)r.add(e)}}return{paths:[...r].toSorted(),commits:i}}function ts(e,t){let n=e.flags[`key-out`];return typeof n==`string`?N(t.dir,n):j(Re(),`.gpu-engine`,`keys`,`${t.model.name}.key`)}function ns(e){let{generate:t,seed:n}=e.evaluation.data;if(t?.test!==void 0)return`${k(e.evalFile)} declares generate.test; with it and seed ${n} anyone can rebuild the sealed rows without the key`}async function rs(e,t){if((await Ar(e)).level===3)return`${G} is already at level 3; the test set is sealed`;let{sealed:n}=await mn(e,W(e,`test`));if(n.length>0)return`${n.join(`, `)} already ${n.length===1?`exists`:`exist`}`;if(await Wo(j(e.dir,`.github/workflows/promote.yml`)))return`${Vo} already exists`;let r=await Go(t),i=[e.dir,await qo(e.dir)].filter(e=>e!==void 0);for(let e of i)if(Ko(r,await Go(e)))return`the key path ${t} is inside ${e}; keep the key outside`;if(await Wo(t))return`the key path ${t} already exists; pass --key-out with a new file`}async function is(e,t){let n=ns(t);if(n!==void 0)throw L(`SEAL_GENERATOR_FOUND`,`${n}; nothing was sealed`);let r=ts(e,t),i=await rs(t,r);if(i!==void 0)throw L(`SEAL_REFUSED`,`${i}; nothing was sealed`);let a=await gr(e,t);for(let t of a.diagnostics)e.printError(R(t));if(a.diagnostics.length>0)return 1;let o=a.lock.test;if(o===void 0||Object.keys(o.files).length===0)throw L(`SEAL_REFUSED`,`${H} records no test file to seal; nothing was sealed`);let s=je(32);await be(A(r),{recursive:!0,mode:448}),await O(r,`${s.toString(`hex`)}\n`,{flag:`wx`,mode:384});let c=await _n(e,t,s,o.files),l={...a.lock,test:{...o,files:c}};await Ht(t,H,ur(l),`replace`);let u=await Ar(t);await O(j(t.dir,G),_r({level:3,promoted:u.promoted})),await be(A(j(t.dir,Vo)),{recursive:!0}),await O(j(t.dir,Vo),$o(),{flag:`wx`});let d=Object.keys(o.files).toSorted();await vn(t,d);let f=await es(t.dir,A(W(t,`test`)));if(f.commits>0){let t=f.paths.length,n=`git history holds ${`${t} plaintext test ${t===1?`file`:`files`}`} in ${`${f.commits} ${f.commits===1?`commit`:`commits`}`}; the seal stands, but a clone still reads those rows`;e.printError(R(I(`SEAL_HISTORY_PLAINTEXT`,n,{file:f.paths[0]})))}for(let t of d){let n=o.files[t]?.examples??0;e.print(`sealed: ${t} -> ${t}${fn} (${n} ${n===1?`row`:`rows`}); the plaintext is deleted`)}return e.print(`${H}: records the sealed files and keeps the fingerprints`),e.print(`${G}: level 3; promote now runs only in CI with ${$}`),e.print(`workflow: ${Vo}`),e.print(`key: written to ${r} (mode 0600); it is not printed`),e.print(`next: gh secret set ${$} < ${r}, then delete ${r} from every machine an agent works on and keep a copy where no agent can read it`),0}async function as(e){let t=[],{plain:n,sealed:r}=await mn(e,W(e,`test`));for(let e of n){let n=`${e} is a plaintext test file in a package sealed at level 3`;t.push(I(`SEAL_PLAINTEXT_FOUND`,n,{file:e}))}let i;try{i=lr(await Bt(e,H))}catch(e){if(!Uo(e))throw e}let a=i?.test;if(r.length===0){let e=`${G} is at level 3, but no file matches the sealed test pattern`;t.push(I(`SEAL_LOCK_INVALID`,e,{file:H}))}else if(a===void 0){let e=`${H} has no test entry; the sealed files are ${r.join(`, `)}`;t.push(I(`SEAL_LOCK_INVALID`,e,{file:H}))}else{let e=Object.keys(a.files).toSorted(),n=e.filter(e=>!e.endsWith(`.enc`)||a.files[e]?.plaintext===void 0),i=e.length===r.length&&e.every((e,t)=>e===r[t]);if(n.length>0||!i){let n=`the test entry of ${H} names ${e.join(`, `)||`no file`}; the sealed files are ${r.join(`, `)}, each with a plaintext hash`;t.push(I(`SEAL_LOCK_INVALID`,n,{file:H}))}}let o;try{o=await D(j(e.dir,Vo),`utf8`)}catch(e){if(!Uo(e))throw e}if(o===void 0)t.push(I(`SEAL_WORKFLOW_MISSING`,`${Vo} does not exist`,{file:Vo}));else if(!o.includes(`GPU_ENGINE_TEST_KEY`)||!o.includes(`gpu-engine promote
104
+ `)||!o.includes(`gpu-engine promote --scan`)){let e=`${Vo} does not run \`gpu-engine promote\` and \`gpu-engine promote --scan\` with ${$}`;t.push(I(`SEAL_WORKFLOW_MISSING`,e,{file:Vo}))}let s=ns(e);return s!==void 0&&t.push(I(`SEAL_GENERATOR_FOUND`,s,{file:k(e.evalFile)})),t}const os=Me(fe);async function ss(e){try{let{stdout:t}=await os(`git`,[`rev-parse`,`HEAD`],{cwd:e});return t.trim()}catch{return`none`}}function cs(e){return Ae(`sha256`).update(e).digest(`hex`)}function ls(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}async function us(e){try{return await D(e,`utf8`)}catch(e){if(ls(e))return;throw e}}async function ds(e){let t=await us(j(e.dir,`reads.jsonl`))??``,n=0;for(let e of t.split(`
105
+ `))if(e.trim()!==``)try{let t=JSON.parse(e);typeof t==`object`&&t&&`kind`in t&&t.kind===`examples`&&n++}catch{}return n}function fs(e,t){return L(`DATA_TEST_PRINTED`,`${`${e} test ${e===1?`input`:`inputs`}`} appeared in ${t}; nothing was printed or written`)}function ps(e,t){let n=[String(e)];e instanceof r&&n.push(R(e.diagnostic)),typeof e==`object`&&e&&`message`in e&&n.push(String(e.message));let i=t(n);return i===0?e:fs(i,`an error message`)}const ms=e=>`${e} ${e===1?`row`:`rows`}`;function hs(e,t){let n=e.table===void 0?void 0:new Set(e.table.map(e=>e.id)),r=e.model.head.kind===`retrieve`?`a gold id that names no row of the table`:`a gold label outside the head`,i=[];for(let[a,o]of Object.entries(t)){let t=o.map(t=>Vn(e.model,t,n)),s=t.filter(e=>e===`invalid`).length,c=t.filter(e=>e===`unknown`).length;s>0&&i.push(I(`DATA_ROW_INVALID`,`test set ${a}: ${ms(s)} with gold not in the shape of the head`)),c>0&&i.push(I(`DATA_LABEL_UNKNOWN`,`test set ${a}: ${ms(c)} with ${r}`))}return i}const gs=e=>`${e} ${e===1?`time`:`times`}`,_s=e=>`${e} unhandled ${e===1?`error`:`errors`}`;async function vs(e,t,n,r){let i={};for(let[a,o]of Object.entries(n)){let n=r.attempts(),s=r.errors(),c;try{c=Zi(e,t,{[a]:o})}catch{c=void 0}await r.settle();let l=r.attempts()-n;if(l>0)throw L(`DATA_TEST_PRINTED`,`metric, decode or a baseline tried to print ${gs(l)} while test set ${a} was scored; nothing was printed`);let u=r.errors()-s;if(u>0)throw L(`PROMOTE_SCORE_FAILED`,`the package code raised ${_s(u)} while scoring test set ${a} (${o.length} rows); nothing was printed`);if(c===void 0)throw L(`PROMOTE_SCORE_FAILED`,`metric, decode or a baseline threw while scoring test set ${a} (${o.length} rows)`);Object.assign(i,c)}return i}function ys(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.model]))}function bs(e){let t=Object.values(e);return t.length===0?0:Math.max(...t)-Math.min(...t)}async function xs(e,t){let n=await us(j(e.dir,ta)),r=n===void 0?null:Ea(n);return r!==null&&r.weights===t?r:null}function Ss(e){let t=t=>Object.fromEntries(Object.entries(e[t]?.files??{}).map(([e,{sha256:t,examples:n}])=>[e,{sha256:t,examples:n}])),n={train:t(`train`),dev:t(`dev`),test:t(`test`)};return e.table===void 0?n:{...n,table:t(`table`)}}function Cs(e,t){for(let n of t)e.printError(R(n));return t.length>0}async function ws(e,t,n,r){let i=await Xo(t,(await Ar(t)).level)?Yo(process.env):void 0,o=a(t.model);if(Cs(e,await An(t.dir)))return 1;let{candidate:s,bytes:c}=await Za(t),l=await gr(e,t);if(Cs(e,l.diagnostics))return 1;let u=qa(s,o.hash,Ga(l.lock));if(u!==void 0)throw L(`PROMOTE_CANDIDATE_STALE`,u);let d=E(v(c),o),f=Zi(t,d,l.examples.dev),p=await Ar(t),m=await mn(t,W(t,`test`)),h=m.sealed.length>0?3:p.level,g=K(c),_=Ss(l.lock),y={noise:t.evaluation.gate.noise,budgets:t.model.budgets,promoted:p.promoted,spread:s.devSpread,brotliBytes:g,macsPerToken:o.macsPerToken,data:{files:U.reduce((e,t)=>e+Object.keys(_[t]).length,0),changed:[]}},b=Object.keys(t.evaluation.baselines),x=xr({...y,scores:{dev:f}});if(!Sr(x)){for(let t of to(`dev`,f,b))e.print(t);e.print(``);for(let t of x)e.print(Cr(t));return e.print(``),e.print(`not promoted: a gate line failed before the test set was read; nothing was read or written`),1}n.start();let S=await Sn(e,t,i),C=on(S);r({scan:C,paths:Mo([...m.plain,...m.sealed])});try{let r=hs(t,S),i=C(r.map(R));if(i>0)throw fs(i,`what promote was about to print or write`);if(Cs(e,r))return 1;let a=await vs(t,d,S,n),l=xr({...y,scores:{dev:f,test:a}}),u=Sr(l),p=Ts({project:t,modelPlan:o,bytes:c,brotliBytes:g,candidate:s,data:_,dev:f,test:a,lines:l,level:h,commit:await ss(t.dir),testReads:await ds(t)}),m=await xs(t,p.weights.sha256),v=[...to(`dev`,f,b),``,...to(`test`,a,b),``,...l.map(Cr),``,u?`promoted: ${Z(p.name)} (${c.byteLength} bytes, ${g} Brotli bytes); test reads ${p.testReads}`:`not promoted: a gate line failed; nothing was written`],x=u?Ds(p,c,h,m,t.model):[],w=C([...v,...x.map(([,e])=>e)]);if(w>0)throw fs(w,`what promote was about to print or write`);if(await n.settle(),n.attempts()>0)throw L(`DATA_TEST_PRINTED`,`metric, decode or a baseline tried to print ${gs(n.attempts())} after the test sets were scored; nothing was printed or written`);if(n.errors()>0)throw L(`PROMOTE_SCORE_FAILED`,`the package code raised ${_s(n.errors())} after the test sets were scored; nothing was printed or written`);u&&await wo(t.dir,[[Z(p.name),c],...x]);for(let t of v)e.print(t);return+!u}catch(e){throw ps(e,C)}}function Ts(e){let{candidate:t,modelPlan:n}=e;return{name:e.project.model.name,date:(/* @__PURE__ */ new Date()).toISOString(),commit:e.commit,definition:n.hash,weights:{sha256:cs(e.bytes),bytes:e.bytes.byteLength,brotliBytes:e.brotliBytes},params:n.size,macsPerToken:n.macsPerToken,train:{seeds:t.seeds,chosenSeed:t.seed,checkpoint:t.checkpoint,steps:t.steps,seconds:t.trainSeconds,devBySeed:t.devBySeed},data:e.data,dev:e.dev,test:e.test,gate:e.lines,testReads:e.testReads,level:e.level}}function Es(e){return{at:e.date,commit:e.commit,weights:e.weights.sha256,definition:e.definition,dev:ys(e.dev),test:ys(e.test)}}function Ds(e,t,n,r,i){return[[ea,ra(e.name,e.weights.sha256,t)],[G,_r({level:n,promoted:Es(e)})],[Qi,ga(e,r,i)],[$i,_a(e)],[X,na(e)]]}async function Os(e){let t=await us(j(e.dir,X));if(t===void 0)throw L(`VERIFY_REPORT_INVALID`,`${X} does not exist; nothing was promoted`,{file:X});return wa(t)}async function ks(e){let t={};for(let n of await Ut(e,W(e,`dev`)))t[k(n,Ee(n))]=await Yt(e,n);return t}function As(e,t){let n=e.level===3?t:Qo(t),r=[];for(let t of ar){let i=e.data[t];if(i===void 0)continue;let a=n[t]?.files??{};for(let e of[.../* @__PURE__ */ new Set([...Object.keys(i),...Object.keys(a)])].toSorted()){let t=i[e]?.sha256,n=a[e]?.sha256;if(t!==void 0&&t===n)continue;let o;o=t===void 0?`${e} is in ${H} but not in ${X}`:n===void 0?`${e} is in ${X} but not in ${H}`:`${e} has another SHA-256 in ${H} than the one ${X} recorded`,r.push(I(`DATA_HASH_CHANGED`,o,{file:e}))}}return r}async function js(e){try{return lr(await Bt(e,`data.lock.json`))??{}}catch(e){if(ls(e))return{};throw e}}function Ms(e,t){let n=[.../* @__PURE__ */ new Set([...Object.keys(e),...Object.keys(t)])];for(let r of n){let n=e[r],i=t[r];if(n===void 0)return`dev ${r} is in ${X} but has no examples now`;if(i===void 0)return`dev ${r} has no row in ${X}`;if(n.examples!==i.examples)return`dev ${r}: ${n.examples} examples now, ${i.examples} recorded`;let a=[[`model`,n.model,i.model],[`oracle`,n.oracle,i.oracle],...Object.entries(n.baselines).map(([e,t])=>[`baseline ${e}`,t,i.baselines[e]])];if(Object.keys(i.baselines).length!==Object.keys(n.baselines).length)return`dev ${r}: the baselines are not the ones ${X} recorded`;for(let[e,t,n]of a)if(n!==t)return`dev ${r} ${e}: re-scored ${t}, ${X} says ${String(n)}`}}function Ns(e,t){let n=Object.entries(e),r=new Map(Object.entries(t));return n.length===r.size&&n.every(([e,t])=>r.get(e)===t)}function Ps(e,t){if(!Zo(e.level,t.level))return`level ${e.level}, ${X} says ${t.level}`;if(e.promoted===null)return`promoted is null`;let n=Es(t);for(let t of[`at`,`commit`,`weights`,`definition`])if(e.promoted[t]!==n[t])return`promoted.${t} is not the one ${X} records`;for(let t of[`dev`,`test`])if(!Ns(e.promoted[t],n[t]))return`promoted.${t} is not the model score per set in ${X}`}async function Fs(e,t,n,r){let i=Z(n.name),a;try{a=await D(j(e.dir,i))}catch(e){if(!ls(e))throw e;r.failures.push(I(`VERIFY_WEIGHTS_CHANGED`,`${i} does not exist`,{file:i}));return}if(t.hash!==n.definition){let e=`the model file hashes to ${t.hash}; ${X} was promoted from ${n.definition}`;r.failures.push(I(`WEIGHTS_DEFINITION_MISMATCH`,e,{file:X}));return}let o=cs(a),s=K(a),{weights:c}=n;if(o!==c.sha256||a.byteLength!==c.bytes||s!==c.brotliBytes){let e=`${i} has SHA-256 ${o}, ${a.byteLength} bytes and ${s} Brotli bytes; ${X} records ${c.sha256}, ${c.bytes} and ${c.brotliBytes}`;r.failures.push(I(`VERIFY_WEIGHTS_CHANGED`,e,{file:i}))}else return r.passes.push(`weights: ${i} matches ${X} (SHA-256 ${o})`),a}async function Is(e,t){let n=a(t.model),i={failures:[],passes:[]},{failures:o,passes:s}=i,c=await An(t.dir);o.push(...c),c.length===0&&s.push(`level 1 scan: no code names the test folder`);let l=await Os(t),u=[...await hr(e,t),...As(l,await js(t))];if(o.push(...u),u.length===0){let e=U.reduce((e,t)=>e+Object.keys(l.data[t]).length,0);s.push(`data: ${e} files pass the data checks and match ${H} and ${X}`)}let d=await Fs(t,n,l,i),f=l.dev;if(d!==void 0&&u.length===0){f=Zi(t,E(v(d),n),await ks(t));let e=Ms(f,l.dev);e===void 0?s.push(`dev: re-scored, equal to ${X}`):o.push(I(`VERIFY_SCORE_CHANGED`,e,{file:X}))}let p;try{p=await Ar(t)}catch(e){if(!(e instanceof r))throw e;o.push(e.diagnostic)}if(p!==void 0){let e=Ps(p,l);e===void 0?s.push(`${G}: level and promoted entry match ${X}`):o.push(I(`VERIFY_SCORE_CHANGED`,`${G}: ${e}`,{file:G}));let r=xr({noise:t.evaluation.gate.noise,budgets:t.model.budgets,promoted:p.promoted,scores:{dev:f},spread:bs(l.train.devBySeed),brotliBytes:d===void 0?l.weights.brotliBytes:K(d),macsPerToken:n.macsPerToken,data:{files:0,changed:[]}}).filter(e=>e.name!==`data`);for(let e of r)e.pass||e.code===void 0?s.push(`${e.name}: ${e.detail}`):o.push(I(e.code,`${e.name}: ${e.detail}`))}let m=await ds(t);if(m>=l.testReads)s.push(`${vo}: ${m} test reads, ${X} counts ${l.testReads}`);else{let e=`${vo} has ${m} test reads; ${X} counts ${l.testReads}`;o.push(I(`VERIFY_READS_MISSING`,e,{file:vo}))}let h=[[Qi,ga(l,await xs(t,l.weights.sha256),t.model)],[$i,_a(l)]];d!==void 0&&h.push([ea,ra(l.name,l.weights.sha256,d)]);let g=[];for(let[e,n]of h)await us(j(t.dir,e))!==n&&(g.push(e),o.push(I(`VERIFY_FILE_STALE`,`${e} is not what ${X} regenerates`,{file:e})));g.length===0&&s.push(`generated files: ${h.map(([e])=>e).join(`, `)} regenerate byte-identical`);for(let t of s)e.print(`pass ${t}`);return Cs(e,o),e.print(o.length===0?`verify: pass`:`verify: ${o.length} ${o.length===1?`failure`:`failures`}`),o.length===0?0:1}function Ls(e){return`${`${e.inputs} test ${e.inputs===1?`input`:`inputs`}`} appeared in ${`${e.files} ${e.files===1?`file`:`files`}`} the promote workflow commits; the lines holding them were removed and the other files put back to git HEAD`}async function Rs(e){try{let{stdout:t}=await os(`git`,[`show`,`HEAD:./${H}`],{cwd:e}),n=lr(t);if(n!==void 0)return n}catch{}let t=await us(j(e,H));return t===void 0?void 0:lr(t)}async function zs(e){let t=(await Rs(e.dir))?.test?.files??{},n=Object.keys(t),i=Mo(n);if(n.length===0)throw L(`PROMOTE_SCAN_FAILED`,`${H} names no test file, so there is nothing to scan with`,{file:H});let a=n.some(e=>e.endsWith(`.enc`))?Yo(process.env):void 0,o;try{o=await Cn(e,{dir:e.dir},t,a)}catch(t){return t instanceof r?e.printError(R(t.diagnostic)):e.printError(`the scan stopped on an error that is not shown, since it can quote a test row`),await Bo(e.dir,i),e.print(`scan: could not open the test set; the files the promote workflow commits were put back to git HEAD`),3}let s=await No(e.dir,o,i);return s.inputs===0?(e.print(`scan: no test input in the files the promote workflow commits`),0):(e.printError(R(I(`DATA_TEST_PRINTED`,Ls(s)))),3)}async function Bs(e){if(e.flags.seal===!0)return is(e,await Yr(e.dir));if(e.flags.verify===!0)return Is(e,await Yr(e.dir));if(e.flags.scan===!0)return zs(e);let t=_o(),n={...e,print:n=>t.own(()=>e.print(n)),printError:n=>t.own(()=>e.printError(n))},i,a=e=>{i=e},o,s;try{if(o=await ws(n,await Yr(e.dir),t,a),await t.settle(),o===0&&t.attempts()>0){let e=`the package code tried to print ${gs(t.attempts())} after the promotion was written; nothing was printed`;n.printError(R(I(`DATA_TEST_PRINTED`,e))),o=1}if(o===0&&t.errors()>0){let e=`the package code raised ${_s(t.errors())} after the promotion was written`;n.printError(R(I(`PROMOTE_SCORE_FAILED`,e))),o=1}}catch(e){await t.settle(),s=e,o=1}if(i!==void 0){let t=await No(e.dir,i.scan,i.paths);t.inputs>0&&(n.printError(R(I(`DATA_TEST_PRINTED`,Ls(t)))),o=1)}if(s!==void 0){if(e.ownsProcess!==!0)throw t.restore(),s;s instanceof r?n.printError(R(s.diagnostic)):n.printError(s instanceof Error?s.message:`promote failed`)}if(e.ownsProcess!==!0)return t.restore(),o;let c=/* @__PURE__ */ new Set;return t.hold(e=>{if(process.exitCode=1,c.has(e))return;c.add(e);let t=e===`print`?I(`DATA_TEST_PRINTED`,`the package code tried to print after promote returned; nothing was printed`):I(`PROMOTE_SCORE_FAILED`,`the package code raised an unhandled error after promote returned`);n.printError(R(t))}),o}const Vs=Me(fe),Hs=`package.json`,Us=[`dependencies`,`peerDependencies`,`optionalDependencies`,`bundleDependencies`,`bundledDependencies`],Ws=/\.[cm]?js$/u;function Gs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ks(e){return Gs(e)&&typeof e.stderr==`string`&&e.stderr.trim()!==``?e.stderr.trim().split(`
106
+ `)[0]??``:e instanceof Error?e.message:String(e)}async function qs(e){let t;try{({stdout:t}=await Vs(`npm`,[`pack`,`--dry-run`,`--json`,`--ignore-scripts`],{cwd:e,maxBuffer:16777216,shell:process.platform===`win32`}))}catch(e){return`\`npm pack --dry-run\` failed: ${Ks(e)}`}let n;try{n=JSON.parse(t)}catch{return"`npm pack --dry-run --json` did not print JSON"}let r=Array.isArray(n)?n[0]:void 0;return!Gs(r)||!Array.isArray(r.files)?"`npm pack --dry-run --json` printed no file list":r.files.flatMap(e=>Gs(e)&&typeof e.path==`string`?[e.path]:[])}function Js(e){return Us.filter(t=>t in e).map(t=>{let n=e[t];return I(`SHIP_DEPENDENCY_FOUND`,`package.json has a \`${t}\` field (${Gs(n)?Object.keys(n).length:Array.isArray(n)?n.length:0} entries)`,{file:Hs})})}function Ys(e,t){return Wr(t).map(({specifier:t,line:n})=>I(`SHIP_DEPENDENCY_FOUND`,`${e} imports \`${t}\`; the shipped module must import nothing`,{file:e,line:n}))}function Xs(e){return[I(`SHIP_PACKAGE_INVALID`,e,{file:Hs})]}async function Zs(e){let t;try{t=await D(j(e,X),`utf8`)}catch{return}let n;try{n=Object.entries(wa(t).data.table??{})}catch{return}let[r]=n;return r===void 0?void 0:[r[0],r[1].sha256]}async function Qs(e,t){if(e.model.head.kind!==`retrieve`)return[];let n=await Zs(e.dir),r=n?.[0]??e.evaluation.table;if(r===void 0)return[];let i;try{i=await Vt(e,r)}catch{return[]}let a=[];n!==void 0&&Ae(`sha256`).update(i).digest(`hex`)!==n[1]&&a.push(I(`SHIP_BUILD_STALE`,`${r} no longer has the SHA-256 that report.json records for the table`,{file:r}));let{rows:o}=Kn(new TextDecoder().decode(i)),s=o.filter(e=>!t.some(t=>t.includes(Ni(e))));return s.length>0&&a.push(I(`SHIP_BUILD_STALE`,`no packed file holds ${$s(s.length,`row`)} of ${r}, so the build ships another table than the one evaluated`,{file:r})),a}function $s(e,t){return`${e} ${t}${e===1?``:`s`}`}async function ec(e){let t;try{t=JSON.parse(await D(j(e.dir,Hs),`utf8`))}catch(e){return Xs(Gs(e)&&e.code===`ENOENT`?`package.json is missing`:`package.json does not parse as JSON`)}if(!Gs(t))return Xs(`package.json is not a JSON object`);let n=Js(t),r=await qs(e.dir);if(typeof r==`string`)return[...n,...Xs(r)];let i=r.filter(e=>e!==Hs),a=/* @__PURE__ */ new Map;for(let t of i)a.set(t,await D(j(e.dir,t)));for(let[e,t]of a)Ws.test(e)&&n.push(...Ys(e,new TextDecoder().decode(t)));let o=Z(e.model.name),s;try{s=await D(j(e.dir,o))}catch(e){if(!(Gs(e)&&e.code===`ENOENT`))throw e}if(s!==void 0){let e=Buffer.from(s).toString(`hex`);[...a.values()].some(t=>Buffer.from(t).includes(e))||n.push(I(`SHIP_BUILD_STALE`,`no packed file holds ${o} as lowercase hex, so the size check would measure a build without the promoted weights`))}let c=[...a].flatMap(([e,t])=>Ws.test(e)?[new TextDecoder().decode(t)]:[]);n.push(...await Qs(e,c));let l=e.evaluation.ship;if(l===void 0)return n;let u=new Set(l.files);for(let e of i)u.has(e)||n.push(I(`SHIP_FILE_NOT_ALLOWED`,`npm pack ships ${e}, which ship.files does not list`,{file:e}));let d=0;for(let e of a.values())d+=K(e);return d>l.brotliBytes&&n.push(I(`SHIP_SIZE_EXCEEDED`,`${$s(a.size,`packed file`)}: ${d} Brotli bytes, over ship.brotliBytes ${l.brotliBytes}`)),n}const tc=`reads.jsonl`;function nc(e){return Ae(`sha256`).update(e).digest(`hex`)}function rc(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}async function ic(e){try{return await D(e)}catch(e){if(rc(e))return;throw e}}async function ac(e){let t=await ic(e);return t===void 0?void 0:new TextDecoder().decode(t)}async function oc(e){try{return(await Te(e)).isDirectory()}catch(e){if(rc(e))return!1;throw e}}const sc=(e,t)=>`${e} ${e===1?t:`${t}s`}`;async function cc(e){let{generate:t}=e.evaluation.data;if(t===void 0)return[];let n=[];for(let r of U)t[r]!==void 0&&(await Wt(e,A(W(e,r)))||n.push(r));return n}function lc(e,t){return e.code===`DATA_SET_MISSING`&&e.message.endsWith(`so the ${t} set is missing`)}async function uc(e){try{return lr(await Bt(e,`data.lock.json`))??{}}catch(e){if(rc(e))return{};throw e}}async function dc(e,t,n){let r=await cc(t),i=(await hr(e,t)).filter(e=>!r.some(t=>lc(e,t)));n.findings.push(...i),r.length>0&&n.lines.push(`note data: ${r.join(`, `)} ${r.length===1?`has`:`have`} no files yet; \`gpu-engine loop\` will generate ${r.length===1?`it`:`them`} with defineDataset.generate (doctor writes no data)`);let a=await uc(t),o=U.filter(e=>a[e]===void 0&&!r.includes(e));return o.length>0&&n.lines.push(`note ${H}: no entry for ${o.join(`, `)} yet; \`gpu-engine loop\` records it once every data check passes (doctor writes no lock)`),i.length===0&&n.lines.push(`pass data: the section 7 data checks found nothing`),a}async function fc(e,t){try{let n=await Ar(e),r=`level ${n.level}, ${n.promoted===null?`nothing promoted`:`promoted`}`;return await ic(j(e.dir,`gate.json`))===void 0?t.lines.push(`note ${G}: no file yet, so ${r}`):t.lines.push(`pass ${G}: ${r}`),n}catch(e){if(!(e instanceof r))throw e;t.findings.push(e.diagnostic);return}}async function pc(e,t){let n=Z(e.model.name),r=await ic(j(e.dir,n));if(r===void 0)return;let i=K(r),a=e.model.budgets.brotliBytes,o=`${n} is ${i} Brotli bytes; budgets.brotliBytes is ${a}`;return i>a?t.findings.push(I(`BUDGET_BYTES_EXCEEDED`,o,{file:n})):t.lines.push(`pass budget: ${o}`),r}function mc(e,t){let n=Object.entries(e),r=new Map(Object.entries(t));return n.length===r.size&&n.every(([e,t])=>r.get(e)===t)}function hc(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.model]))}function gc(e,t){if(!Zo(e.level,t.level))return`level ${e.level}, ${X} says ${t.level}`;let{promoted:n}=e;if(n===null)return`promoted is null, ${X} records a promotion`;let r={at:t.date,commit:t.commit,weights:t.weights.sha256};for(let e of[`at`,`commit`,`weights`])if(n[e]!==r[e])return`promoted.${e} is not the one ${X} records`;if(n.definition!==t.definition)return`promoted.definition is not the one ${X} records`;if(!mc(n.dev,hc(t.dev)))return`promoted.dev is not the model score per set`;if(!mc(n.test,hc(t.test)))return`promoted.test is not the model score per set`}async function _c(e,t,n){let{findings:i,lines:o}=n,s=await ac(j(e.dir,X));if(s===void 0){if(t.gate?.promoted===void 0||t.gate.promoted===null){o.push(`note ${X}: nothing promoted yet, so there is no report to check`);return}let e=`${G} records a promotion, but ${X} does not exist`;i.push(I(`VERIFY_REPORT_INVALID`,e,{file:X}));return}let c;try{c=wa(s)}catch(e){if(!(e instanceof r))throw e;i.push(e.diagnostic);return}let l=i.length,u=a(e.model).hash,d=u!==c.definition;d&&o.push(`note ${X}: the model file hashes to ${u}, the promotion was from ${c.definition}; expected while tuning. \`promote --verify\` (CI) fails with WEIGHTS_DEFINITION_MISMATCH until you promote once when the tuning is done`);let f=Z(c.name),p=c.name===e.model.name?t.weights:await ic(j(e.dir,f));if(p===void 0)i.push(I(`VERIFY_WEIGHTS_CHANGED`,`${f} does not exist`,{file:f}));else{let e=nc(p),t=K(p),{weights:n}=c;if(e!==n.sha256||p.byteLength!==n.bytes||t!==n.brotliBytes){let r=`${f} has SHA-256 ${e}, ${p.byteLength} bytes and ${t} Brotli bytes; ${X} records ${n.sha256}, ${n.bytes} and ${n.brotliBytes}`;i.push(I(`VERIFY_WEIGHTS_CHANGED`,r,{file:f}))}}if(i.push(...As(c,t.lock)),t.gate!==void 0){let e=gc(t.gate,c);e!==void 0&&i.push(I(`VERIFY_SCORE_CHANGED`,`${G}: ${e}`,{file:G}))}let m=await ds(e);if(m<c.testReads){let e=`${tc} has ${sc(m,`test read`)}; ${X} counts ${c.testReads}`;i.push(I(`VERIFY_READS_MISSING`,e,{file:tc}))}let h=await ac(j(e.dir,ta)),g=h===void 0?null:Ea(h),_=g!==null&&g.weights===c.weights.sha256?g:null,v=[[$i,_a(c)]];d||v.unshift([Qi,ga(c,_,e.model)]),p!==void 0&&v.push([ea,ra(c.name,c.weights.sha256,p)]);for(let[t,n]of v)await ac(j(e.dir,t))!==n&&i.push(I(`VERIFY_FILE_STALE`,`${t} is not what ${X} regenerates`,{file:t}));i.length===l&&o.push(`pass ${X}: agrees with ${d?``:`the model file, `}${f}, ${H}, ${G}, ${tc} and ${v.map(([e])=>e).join(`, `)}`)}async function vc(e,t,n){let r=await t();n.findings.push(...r),r.length===0&&n.lines.push(`pass ${e}: nothing found`)}async function yc(e){let t={findings:[],lines:[]},n;try{n=await Yr(e.dir)}catch(e){if(!(e instanceof r))throw e;return t.findings.push(e.diagnostic),t}t.lines.push(`pass project: ${k(n.modelFile)} and ${k(n.evalFile)} load and pass the definition checks`);let i=await An(n.dir);t.findings.push(...i),i.length===0&&t.lines.push(`pass level 1 scan: no code names the test folder`);let a=await dc(e,n,t),o=await fc(n,t),s=await pc(n,t);return await _c(n,{lock:a,gate:o,weights:s},t),await oc(j(n.dir,`dist`))?(await vc(`ship checks`,()=>ec(n),t),n.evaluation.ship===void 0&&t.lines.push("note ship checks: the eval file has no `ship`, so the file and size checks did not run")):t.lines.push(`note ship checks: no dist/ folder, nothing built to check`),o?.level===3&&await vc(`level 3 checks`,()=>as(n),t),t}async function bc(e){let{findings:t,lines:n}=await yc(e);for(let t of n)e.print(t);for(let n of t)e.printError(R(n));return e.print(t.length===0?`doctor: pass`:`doctor: ${sc(t.length,`finding`)}`),t.length===0?0:1}function xc(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}async function Sc(e){try{return await D(e)}catch(e){if(xc(e))return;throw e}}function Cc(e){try{return v(e).hash}catch{return}}function wc(e,t){return e.byteLength===t.byteLength&&e.every((e,n)=>e===t[n])}async function Tc(e){let t=n(e.model),r=Z(e.model.name),i=await Sc(j(e.dir,r)),a=await Sc(j(e.dir,Ba)),o="running the candidate of the last `gpu-engine loop`";if(a!==void 0&&Cc(a)===t){if(i!==void 0&&wc(a,i))return{path:r,bytes:i,promoted:!0};let e=`nothing is promoted (${r} does not exist); ${o}`;return i!==void 0&&(e=Cc(i)===t?`${o}, not the promoted ${r}`:`${r} was promoted from another model definition; ${o}, trained from the model file`),{path:Ba,bytes:a,promoted:!1,note:e}}if(i!==void 0&&(Cc(i)===t||a===void 0))return{path:r,bytes:i,promoted:!0};if(a!==void 0){let e=i===void 0?`nothing is promoted (${r} does not exist); ${o}`:o;return{path:Ba,bytes:a,promoted:!1,note:e}}throw L(`PROMOTE_CANDIDATE_MISSING`,`nothing is promoted (${r} does not exist) and there is no candidate (${Ba})`)}const Ec=e=>JSON.stringify(e);function Dc(e){let{feature:t}=e;return t.kind===`hash`?`hash(${t.buckets}, k ${t.k})`:t.kind===`flag`?`flag ${t.name}`:`shape`}function Oc(e,t){let n=e.slice(0,t),r=Math.max(0,...n.map(e=>Ec(e.text).length)),i=[`tokens: ${e.length} (input.max ${t})`];for(let[e,t]of n.entries())i.push(` ${String(e).padStart(String(n.length-1).length)} ${Ec(t.text).padEnd(r)} ${t.start}-${t.end}`);let a=e.length-n.length;return a>0&&i.push(` ${a} more after input.max: no feature rows and no output`),i}function kc(e,t,n){let{blocks:r}=se(e.input),i=r.map(e=>`${Dc(e)} ${e.slots}`).join(`, `),a=[`feature rows: ${n.slots} slots per token (${i}), embedding row per slot, - when empty`],o=Math.max(0,...t.slice(0,n.count).map(e=>Ec(e.text).length));for(let e=0;e<n.count;e++){let i=r.map(t=>{let r=[];for(let i=t.slot;i<t.slot+t.slots;i++){let t=n.rows[e*n.slots+i]??-1;r.push(t<0?`-`:String(t))}return`${Dc(t)} [${r.join(`, `)}]`});a.push(` ${String(e).padStart(String(n.count-1).length)} ${Ec(t[e]?.text??``).padEnd(o)} ${i.join(` `)}`)}return a}function Ac(e,t,n){return`labels`in e?[...e.labels]:e.kind===`retrieve`&&n!==void 0&&n.length===t?n.map(e=>e.id):Array.from({length:t},(e,t)=>`output ${t}`)}const jc=e=>e.toFixed(4);function Mc(e,t,n,r,i){if(e.kind===`tag`){let a=Ac(e,e.labels.length,i),o=[`raw output: ${t.length} logits, one per label (${a.join(`, `)}) for each of ${n} tokens`],s=Math.max(0,...r.slice(0,n).map(e=>Ec(e.text).length));for(let e=0;e<n;e++){let i=a.map((n,r)=>`${n} ${jc(t[e*a.length+r]??NaN)}`);o.push(` ${String(e).padStart(String(n-1).length)} ${Ec(r[e]?.text??``).padEnd(s)} ${i.join(` `)}`)}return o}let a=Ac(e,t.length,i);return[`raw output: ${t.length} logits for the whole input`,...a.map((e,n)=>` ${e} ${jc(t[n]??NaN)}`)]}function Nc(e,t){let r=Cc(e);if(r===void 0)return;let i=n(t);return r===i?`definition: ${r}`:`definition: ${r}; the model file hashes to ${i}`}function Pc(e){return JSON.stringify(e)??String(e)}async function Fc(e){let[t=``]=e.positionals,n=await Yr(e.dir),r=n.model,i=f(t),a=c(r.input,t);e.print(`input: ${Ec(t)} (every flag off)`);for(let t of Oc(i,r.input.max))e.print(t);for(let t of kc(r,i,a))e.print(t);let o=await Tc(n),s=o.promoted?`promoted, `:``;e.print(`weights: ${o.path} (${s}${o.bytes.byteLength} bytes)`),o.note!==void 0&&e.print(`note: ${o.note}`);let l=Nc(o.bytes,r);l!==void 0&&e.print(l);let u=await Yn(n),d=await w(o.bytes,{backend:`auto`,definition:r,...u===void 0?{}:{table:u}}),[p,m]=await ee(d,t),[h,g]=p===void 0?await d.run(t):[p,void 0];if(m!==void 0)for(let t of Mc(r.head,m.logits,m.count,i,u))e.print(t);if(h===void 0){e.print(`head output: ${Pc(g)}`);let{decode:r}=n.evaluation;e.print(r===void 0?`decoded result: ${Pc(g)} (the eval has no decode)`:`decoded result: ${Pc(r(g,t))}`)}let{backend:_,reason:v}=d.inspect();return e.print(`backend: ${_}`),e.print(`reason: ${v}`),h===void 0?0:(e.printError(R(h)),1)}const Ic=[`parity`,`check`,`with`,`many`,`small`,`tokens`,`and`,`42`,`Words`];function Lc(e){return Array.from({length:e},(e,t)=>Ic[t%Ic.length]).join(` `)}function Rc(e){return[{label:`edge: empty text`,input:``},{label:`edge: one token`,input:`parity`},{label:`edge: exactly ${e} tokens`,input:Lc(e)},{label:`edge: ${e+3} tokens, more than input.max`,input:Lc(e+3)}]}async function zc(e){let t=[];for(let n of await Ut(e,W(e,`dev`)))for(let[r,i]of(await Yt(e,n)).entries())t.push({label:`dev ${n} row ${r+1}`,input:i.input});return[...t,...Rc(e.model.input.max)]}const Bc="add the `webgpu` package as a devDependency of the model package (`npm install --save-dev webgpu@^0.6.2`) and install a Vulkan driver (on Linux, `apt-get install mesa-vulkan-drivers` for lavapipe)";function Vc(e){return e instanceof Error?e.message:String(e)}async function Hc(e){let t;try{t=le(j(e,`package.json`)).resolve(`webgpu`)}catch{throw L(`PARITY_ADAPTER_MISSING`,`the \`webgpu\` package does not resolve from ${e}: ${Bc}`)}let n;try{n=await import(Fe(t).href)}catch(e){throw L(`PARITY_ADAPTER_MISSING`,`the \`webgpu\` package failed to load (${Vc(e)}): ${Bc}`)}if(typeof n!=`object`||!n||!(`create`in n)||typeof n.create!=`function`)throw L(`PARITY_ADAPTER_MISSING`,`the \`webgpu\` package in ${t} has no \`create\` export`);let{create:r}=n;return{path:t,create:e=>r(e)}}const Uc=/* @__PURE__ */ new Map;async function Wc(e){let t=await Hc(e),n,r;try{n=Uc.get(t.path)??t.create([]),Uc.set(t.path,n),r=await n.requestAdapter()}catch(e){throw L(`PARITY_ADAPTER_MISSING`,`WebGPU failed to start (${Vc(e)}): ${Bc}`)}if(r===null)throw L(`PARITY_ADAPTER_MISSING`,`WebGPU found no adapter: ${Bc}`);return{gpu:n,adapter:x(r)}}function Gc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Kc(e,t,n){if(typeof e==`number`&&typeof t==`number`)return Number.isFinite(e)&&Number.isFinite(t)&&Math.abs(e-t)<=n;if(Array.isArray(e)&&Array.isArray(t)){let r=e,i=t;return r.length===i.length&&r.every((e,t)=>Kc(e,i[t],n))}if(Gc(e)&&Gc(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(r=>Object.hasOwn(t,r)&&Kc(e[r],t[r],n))}return Object.is(e,t)}function qc(e,t){if(e.length!==t.length)return!1;let n=new Uint32Array(e.buffer,e.byteOffset,e.length),r=new Uint32Array(t.buffer,t.byteOffset,t.length);return n.every((e,t)=>e===r[t])}function Jc(e){return e.every(e=>Number.isFinite(e))}function Yc(e,t,n){throw L(n.code,`${e} on ${t.label}: ${n.message}`)}function Xc(e,t,n,r){return`${n} on ${e} of ${t} fixtures, first on ${r??`none`}`}async function Zc(e,t,n,r,i=t){let o=a(e.model),s=E(v(t),o),c=Hi(e,o,s),l=e.table===void 0?{}:{table:e.table},u=e.model,d=await w(t,{backend:`cpu`,definition:u,...l}),f=await w(i,{backend:`webgpu`,definition:u,gpu:r.gpu,...l});try{return await Qc(e,{cpu:d,gpu:f},o,s,c,n)}finally{await Promise.all([d.destroy(),f.destroy()])}}async function Qc(e,t,n,r,i,a){let{cpu:o,gpu:s}=t,{tolerance:l}=e.evaluation.parity,u=e.evaluation.decode,d=zi(e.model),f=0,p,m=0,h,g=0,_,v=0,y;for(let e of a){let t=c(n.definition.input,e.input),a=T(n,r,t.rows,t.count),b=i===void 0?a:ae(a,i.vectors,i.rows,i.size),[x,S]=await ee(o,e.input);x&&Yc(`the CPU runtime`,e,x);let[C,w]=await ee(s,e.input);if(C&&Yc(`the WebGPU runtime`,e,C),qc(b,S.logits)||(f++,p??=e.label),!Jc(S.logits)||!Jc(w.logits)||S.logits.length!==w.logits.length){m++,h??=e.label;continue}for(let[t,n]of S.logits.entries()){let r=Math.abs(n-(w.logits[t]??NaN));r>v&&(v=r,y=e.label)}let[E,te]=await o.run(e.input);E&&Yc(`the CPU runtime`,e,E);let[ne,re]=await s.run(e.input);ne&&Yc(`the WebGPU runtime`,e,ne);let ie=t=>u===void 0?t:u(t,d(e.input));Kc(ie(te),ie(re),l)||(g++,_??=e.label)}let b=a.length,x=[];return f>0&&x.push(I(`PARITY_TOLERANCE_EXCEEDED`,Xc(f,b,`the trainer and CPU logits are not bitwise identical (tolerance 0, they share the forward pass)`,p))),m>0&&x.push(I(`PARITY_TOLERANCE_EXCEEDED`,Xc(m,b,`a CPU or WGSL logit is not finite, or the two have different lengths`,h))),v>l&&x.push(I(`PARITY_TOLERANCE_EXCEEDED`,`the largest CPU and WGSL logit difference is ${v.toExponential(2)}, above parity.tolerance ${l.toExponential(2)}, on ${y??`none`}`)),g>0&&x.push(I(`PARITY_DECODE_DIFFERS`,Xc(g,b,`the CPU and WGSL results decode differently`,_))),{fixtures:b,trainerCpuDiffers:f,maxDifference:v,decodeDiffers:g,diagnostics:x}}function $c(e){return Ae(`sha256`).update(e).digest(`hex`)}function el(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}async function tl(e){try{return await D(e)}catch(e){if(el(e))return;throw e}}async function nl(e){let t=await tl(j(e,X));if(t===void 0)throw L(`VERIFY_REPORT_INVALID`,`${X} does not exist; nothing was promoted`,{file:X});return wa(new TextDecoder().decode(t))}async function rl(e,t){let n=Z(t.name),r=await tl(j(e,n));if(r===void 0)throw L(`VERIFY_WEIGHTS_CHANGED`,`${n} does not exist, and ${X} names it`,{file:n});if($c(r)!==t.weights.sha256)throw L(`VERIFY_WEIGHTS_CHANGED`,`${n} does not have the SHA-256 that ${X} records`,{file:n});return r}function il(e){return`${JSON.stringify(e,null,2)}\n`}function al(e,t){return il({...e,date:``})===il({...t,date:``})}async function ol(e,t){let n=await tl(e);(n===void 0||new TextDecoder().decode(n)!==t)&&await O(e,t)}async function sl(e,t=Wc){let n=await Yr(e.dir),r=await nl(n.dir),i=await rl(n.dir,r),a=await zc(n),o=await t(n.dir),s=await Zc(n,i,a,o),{tolerance:c}=n.evaluation.parity,l=Rc(n.model.input.max).length;e.print(`weights: ${Z(r.name)} (SHA-256 ${r.weights.sha256})`),e.print(`fixtures: ${s.fixtures} (${s.fixtures-l} dev inputs and ${l} edge inputs; the test set is never read)`),e.print(`trainer and CPU: ${s.trainerCpuDiffers===0?`identical`:`differ on ${s.trainerCpuDiffers}`} on ${s.fixtures} fixtures`);let u=`largest logit difference ${s.maxDifference.toExponential(2)} (tolerance ${c.toExponential(2)}), decoded results differ on ${s.decodeDiffers} of ${s.fixtures} fixtures`;e.print(`CPU and WGSL on ${o.adapter}: ${u}`);let d=fa(o.adapter),f=d===void 0?`${o.adapter}: ${u}`:`not run`;if(e.print(d===void 0?`real GPU: ${f}, real browser: not run`:`real GPU: not run (${o.adapter} is a ${d}), real browser: not run`),s.diagnostics.length>0){for(let t of s.diagnostics)e.printError(R(t));return 1}let p={date:(/* @__PURE__ */ new Date()).toISOString(),weights:r.weights.sha256,adapter:o.adapter,tolerance:c,fixtures:s.fixtures,trainerCpu:`identical`,maxDifference:s.maxDifference,decodeDiffers:s.decodeDiffers,realGpu:f},m=await tl(j(n.dir,ta)),h=m===void 0?null:Ea(new TextDecoder().decode(m)),g=h!==null&&al(h,p)?h:p;return g===p&&await ol(j(n.dir,ta),il(g)),await ol(j(n.dir,Qi),ga(r,g,n.model)),e.print(g===p?`wrote ${ta} and ${Qi}`:`${ta} unchanged`),0}const cl=[`tag`,`pooled`,`retrieve`],ll=`NEW_MODEL_NAME`,ul=`skills/gpu-engine/SKILL.md`,dl=/* @__PURE__ */ new Map([[`gitignore`,`.gitignore`],[`github`,`.github`],[`package.template.json`,`package.json`],[`tsconfig.template.json`,`tsconfig.json`]]);function fl(){for(let e=import.meta.dirname;;e=A(e)){if(he(j(e,`templates`,`common`)))return e;if(A(e)===e)throw Error(`gpu-engine: no templates folder above ${import.meta.dirname}`)}}async function pl(e){return(await xe(e,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(t=>M(e,j(t.parentPath,t.name)).split(P).join(`/`)).toSorted()}function ml(e,t){let[n=``,...r]=e.split(`/`);return[dl.get(n)??n,...r].join(`/`).replaceAll(ll,t)}async function hl(e=fl()){let t=JSON.parse(await D(j(e,`package.json`),`utf8`));return typeof t!=`object`||!t||!(`version`in t)?`0.0.0`:String(t.version)}async function gl(e){return`^${await hl(e)}`}async function _l(e,t){if(!s.test(e))throw L(`NEW_NAME_INVALID`,`\`${e}\` is not a lowercase name of letters, digits and \`-\``);let n=fl(),r=await gl(n),i=/* @__PURE__ */ new Map;for(let a of[`common`,t]){let t=j(n,`templates`,a);for(let n of await pl(t)){let a=await D(j(t,n),`utf8`);i.set(ml(n,e),a.replaceAll(ll,e).replaceAll(`GPU_ENGINE_VERSION`,r))}}return i.set(ul,await D(j(n,ul),`utf8`)),[...i].toSorted(([e],[t])=>e.localeCompare(t))}async function vl(e,t,n){let r=await _l(t,n);if(he(e)&&(await xe(e)).length>0)throw L(`NEW_TARGET_EXISTS`,`${e} already holds files`);for(let[t,n]of r){let r=j(e,t);await be(A(r),{recursive:!0}),await O(r,n,{flag:`wx`})}return r.map(([e])=>e)}function yl(e){return cl.some(t=>t===e)}async function bl(e){let[t=``]=e.positionals,n=e.flags.head;if(!yl(n))throw L(`CLI_FLAG_INVALID`,`--head must be one of ${cl.join(`, `)}`);let r=N(e.dir,t),i=await vl(r,t,n);return e.print(`created ${r} with a ${n} head (${i.length} files)`),e.print(`next:`),e.print(` cd ${r}`),e.print(` npm install`),e.print(` npx gpu-engine doctor`),e.print(` npx gpu-engine loop --log "starter" (the first loop writes data/train, data/dev and data/test)`),0}export{bc as a,ga as c,Yr as d,Dt as f,R as g,L as h,Fc as i,_a as l,Be as m,bl as n,Bs as o,I as p,sl as r,co as s,hl as t,Ri as u};