The core from JavaScript
Gantry’s core is the Go package github.com/c65llc/gantry/core: lint,
format, generate, the read model, queries and edits, over files held in
memory. It never touches the operating system, so it compiles to
WebAssembly as gantry.wasm. @c65llc/gantry-core, in web/core/, runs
that module in a module Worker behind a typed, promise-based client. A host
(a web app, an editor extension) gives it files and gets back the same
findings, tally and outputs gantry lint --json, gantry fmt and
gantry generate give for the same files.
The package is private to this repository and not published to npm.
Using the client
Section titled “Using the client”import { createCore } from "@c65llc/gantry-core";import wasmUrl from "@c65llc/gantry-core/gantry.wasm?url";
const core = createCore({ wasmUrl: new URL(wasmUrl, location.href) });const result = await core.lint(files, { strict: true });core.close();createCore(opts) takes:
| Option | Value |
|---|---|
wasmUrl |
Where gantry.wasm is served. Go’s wasm_exec.js is loaded from beside it, so serve the two together (web/core/dist/ holds both after make wasm). |
workerUrl |
The worker script. Optional; the default is the package’s worker.js. |
timeoutMs |
How long a worker with calls in flight may stay silent before it is taken for hung. Optional; the default, DEFAULT_TIMEOUT_MS, is ten minutes, and 0 turns the watchdog off. The wait starts only after the worker’s first reply, so loading the module never trips it. |
The worker starts on the first call and loads the module once. Each call returns a Promise:
- It resolves with the result.
- It rejects with
GantryErrorwhen core refuses the call, such as for an invalid path. The message is the bridge’s error,"<fn>: <message>", and the worker carries on. - It rejects with
GantryCrashErrorwhen the worker dies, fails to load the module, the module exits, or the watchdog fires. Every call in flight is rejected, and the next call starts a fresh worker.
close() stops the worker and rejects what is in flight; a later call starts
a new one. createClient(spawn) builds the same client over any transport,
such as Node’s worker_threads, which the package’s tests and the VS Code
extension use. The worker side of such a transport is serve(port, instantiate), exported as @c65llc/gantry-core/serve.
The Files contract
Section titled “The Files contract”Every function takes the project as Files: an object from
project-relative path to file contents (UTF-8 text).
- A key is a slash path relative to the project root:
gantry.yaml,docs/design/rulings/safe-area.md. A key that is absolute, has a.or..element, a leading or trailing slash, a backslash, a colon anywhere (C:x,a/b:stream) or a NUL byte is refused: the call fails withfile name must be a project-relative path written with /, naming the key.scopeis the exception: it takes the whole folder listing, so it ignores such a key (a name likecaptures/2026-11-27T10:00:00.pngis legal on POSIX). The key is never inreadand causes no error. Every other function refuses it, since a host passes them only the scoped files. Filesmust holdgantry.yaml, or the call fails withno gantry.yaml found.- A file outside the project’s scope (a blob no manifest frame names,
node_modules/) is ignored. The result is the same as with only the scoped files.
Reading a project: list, scope, read, call
Section titled “Reading a project: list, scope, read, call”A host does not read a whole folder. It reads only what the project uses:
- List the folder: every file path, each with
""as its contents, exceptgantry.yamland, when present,starboard.yamlandairframe.yaml, which it reads: scope needs the content directory each names. - Scope: call
scopeon that listing. Itscontentis the content directory and itsreadevery file the project uses. - Scope again for evidence: if
<content>/evidence/manifest.yamlis in the listing, read its contents into the listing and callscopeagain. Only then doesheads, the evidence blobs the manifest names, list them: a host learns<content>from the first call, so it cannot read the manifest before it. - Read those files, and only those: each of
readin full, and the first 1024 bytes of each ofheads. - Call
lint,modelor any other function with the files read.
const listing = Object.fromEntries(paths.map((p) => [p, ""]));listing["gantry.yaml"] = await readText("gantry.yaml");let scope = await core.scope(listing);const manifest = `${scope.content}/evidence/manifest.yaml`;if (manifest in listing) { listing[manifest] = await readText(manifest); scope = await core.scope(listing);}const files = Object.fromEntries([ ...(await Promise.all(scope.read.map(async (p) => [p, await readText(p)]))), ...(await Promise.all(scope.heads.map(async (p) => [p, await readHead(p, 1024)]))),]);const result = await core.lint(files);The package exports these steps as selectFiles(tree, scope), which the
web app’s hosts and the VS Code extension both read through. tree lists
the folder (as project-relative slash paths), reads a file and reads a
file’s first bytes; selectFiles skips anything under .git or
node_modules and returns the files, the content directory and the heads.
A blob may be passed truncated to its first 1024 bytes; core reads only LFS
pointers from it. That is enough to tell a Git LFS pointer from the real
file, which is all the evidence rules and a frame’s state need. A host
that leaves a blob out gets that frame reported as missing. Without the
manifest’s contents in the listing, heads is empty: skipping step 3 on a
project with frames reports every frame evidence-blob-missing.
History needs base files
Section titled “History needs base files”The history rules compare the project with an earlier version of it, as
gantry lint --base <ref> does from git. Core has no git, so the host passes
that version as files:
base: the project at the base ref. Without it the history rules do not run, exactly as without--base. Files with nogantry.yamlthat loads are an empty base, reported asbase-empty.ancestor: the project at the merge-base of the base and HEAD. Without it the base is taken as the fork point: a defect retitled since the base is an edit, never adefect-id-collision.
Of each, only gantry.yaml, the lint baseline and the content directory are
read.
Functions
Section titled “Functions”Each function’s arguments are the named fields of one JSON object. Every
result marshals with lowerCamelCase field names, and its lists and maps are
never null: an empty one is [] or {}. web/core/src/types.ts declares
every type below, field for field.
scope(files) → ScopeResult
Section titled “scope(files) → ScopeResult”Which of a folder’s files the project uses.
- Arguments:
{"files": Files}, the listing (see above). - Result:
{"content": string, "read": string[], "heads": string[]}.contentis the content directory (docs/designwhengantry.yamldoes not parse).readis sorted:gantry.yaml, the lint baseline,.gitattributes, every file under the content directory but its evidence blobs, every file a test glob matches,starboard.yamland its screens registry, andairframe.yamlwith the<content>/**/*.tokens.jsonand<content>/components/*.yamlfiles under its content directory (design-systemunless it names one), each when present. It never holds a blob.headsis the blob path of every manifest frame whose blob is in the listing, sorted, each once. A blob may be passed truncated to its first 1024 bytes; core reads only LFS pointers from it.
lint(files, opts?) → LintResult
Section titled “lint(files, opts?) → LintResult”gantry lint, and with base, gantry lint --base.
-
Arguments:
{"files": Files, "strict": boolean, "base"?: Files, "ancestor"?: Files}. The client sendsbaseandancestoronly when given. -
Result:
{"diagnostics": [Diagnostic],"tally": [TallyRow],"errors": 0,"warnings": 0,"infos": 0,"passed": true}passedis the CLI’s exit status: no errors and, when strict, no warnings. -
A
Diagnosticis{"rule", "severity", "file", "path", "line"?, "message", "fix"?, "docs"}:severityiserror,warnorinfo,lineis 1-based and absent when unknown, andfixis{"description", "replace"?: {"file", "path", "value"}}. The diagnostics are sorted, andgantry lint --json’serrors,warningsandinfoslists are these, by severity. -
A
TallyRowis{"rung", "rule", "examined", "findings", "baselined"?, "skipped"}. -
A
gantry.yamlthat does not parse is a finding (yaml-syntaxorconfig-invalid), not an error.
format(files) → Record<string, string>
Section titled “format(files) → Record<string, string>”The files gantry fmt would rewrite, in canonical form: gantry.yaml and
the record files. Files already canonical are left out.
- Arguments:
{"files": Files}. - Result: an object from path to new contents;
{}when everything is formatted.
generate(files) → GenerateResult
Section titled “generate(files) → GenerateResult”What gantry generate would change.
- Arguments:
{"files": Files}. - Result:
{"write": {path: contents}, "remove": [path]}: the generated files that are missing or differ, and the orphans under the generated directory. A current project gives{"write": {}, "remove": []}. - A project with load errors is refused, as the CLI refuses it.
model(files) → Model
Section titled “model(files) → Model”The read view of the project, as far as it loaded.
-
Arguments:
{"files": Files}. -
Result:
{"config": ModelConfig,"rulings": [Ruling],"defects": [Defect],"passes": [Pass],"primers": [Primer],"frames": [Frame],"citedBy": {"ruling:safe-area": ["defect:D-0001", "primer:ios"]},"loadErrors": 0}citedByis keyed by the rulings, defects and passes that are cited, asruling:<id>,defect:<id>orpass:<id>. Each value lists the records citing it, as<kind>:<id>, where the kind may also beprimerorframe.loadErrorscounts the load findings of error severity, so a UI can say “fix lint first”. A record that does not parse is absent. Each frame has astate:pulled(the blob is the real file),pointer(a Git LFS pointer not yet pulled, which a UI draws as a “not pulled” tile, never a broken image) ormissing(no file), read from the blob’s first 1024 bytes.config.classeslists the defect classes ingantry.yaml’s order, andconfig.classOwesmaps each to what closing a defect of that class must carry, asdefect-closed-owingchecks it:{"anyOf": [], "allOf": [], "assertionKinds": []}, each list never null.config.testGlobsmaps each platform, andcorewhen the project has a core platform, to its test-file globs asgantry.yamlwrites them (project-relative, doublestar syntax); a platform with no globs maps to[], never null.
query(files, expr) → object[]
Section titled “query(files, expr) → object[]”gantry query --json.
- Arguments:
{"files": Files, "expr": string}.expris a kind (rulings,defects,passesorframes) and anyfield=valueterms. - Result: the records selected, as their front-matter objects, sorted by ID.
edit(files, ops) → EditResult
Section titled “edit(files, ops) → EditResult”Applies ops in order, through the same scaffolding as gantry new,
amend and close. Each op sees the results of the ones before it. If any
op fails, the whole batch fails with op <i> (<op>): <message> and nothing
comes back.
-
Arguments:
{"files": Files, "ops": [EditOp]}. AnEditOpisopplus that op’s fields, each a string or a list of strings in the CLI’s grammar:opFields new-rulingid,nounnew-defecttitle,class,severity,rulings,platforms,apps,framesnew-passslug,title,dateamendruling,summary,replaces,change,by,pass,date,assertionsclosedefect,owesCore reads no clock, so the host always passes
date, asYYYY-MM-DD:new-passandamendfail withdate is requiredwithout one anddate must be YYYY-MM-DDfor any other form. An op whose file would land outside the project (acontentdirectory of../outor/abs) fails with the invalid-path error, naming the file. -
Result:
{"files": {path: contents}, "created": [id], "diagnostics": [Diagnostic]}: the full new contents of every changed or new file, the IDs the ops created in op order, and the lint findings in the changed files. The host writesfiles.
rules() → RuleInfo[]
Section titled “rules() → RuleInfo[]”Every lint rule, by rung then ID, as gantry rules --json lists them. The
listing includes the two findings the CLI reports while reading --base,
base-empty and base-unavailable, so every finding a run can print is listed.
- Arguments:
{}. - Result:
[{"id", "rung", "kind", "default", "summary", "docs", "cli"?}].cliistrueonbase-emptyandbase-unavailable, which no lint rule runs, and absent otherwise.
refs(text, defectPrefix, markdown) → Ref[]
Section titled “refs(text, defectPrefix, markdown) → Ref[]”The references in any text, in the order they appear, found as lint finds
them in a record: @ruling, @defect, @pass, @evidence, @screen,
@component and @token references, and bare defect IDs. An editor uses
it to find the references in a record or in a source file’s comments.
- Arguments:
{"text": string, "defectPrefix": string, "markdown": boolean}.defectPrefixis the project’s (config.defectPrefixin the model): a bare defect ID is that prefix, digits and an optional letterbtoz. An empty prefix finds no bare IDs.markdownsays the text is a record file: its code spans and fenced code blocks are skipped, as lint skips them. Passfalsefor a source file, whose backticks are not Markdown, so a reference in a comment counts wherever it sits. - Result:
[{"kind", "id", "fragment", "offset", "length"}].kindis the record kind (defectfor a bare ID),fragmentwhat follows a#or"".offsetandlengthare UTF-16 code units, as a JavaScript string and an editor count them, so the reference istext.slice(offset, offset + length). Nothing found is[].
symbols(path, text, platform) → Symbol[]
Section titled “symbols(path, text, platform) → Symbol[]”The tests a test file declares, each with its line, so an editor can place what a ruling’s assertion or a defect’s owe names.
- Arguments:
{"path": string, "text": string, "platform": string}.pathis the file’s project-relative path: its extension picks the language (.swift,.kt,.ts,.tsx,.js,.csor.rs), andtextis its contents.platformis the platform whose test globs matchedpath;"", a file no platform’s globs claim, gives[]. - Result:
[{"name", "bare", "line"}](TestSymbolintypes.ts, asSymbolis JavaScript’s own), in the order the language’s patterns find them.nameis the symbol fully scoped, as an assertion names it:TabsUITests.testSelectedfor a test in a Swift class,tabs › shows the selected tabfor a test in adescribeblock.bareis the test’s own name without its scope (testSelected,shows the selected tab), exact wherenamecannot be split, such as a Kotlin name with a dot in backticks.lineis 0-based. The declarations are the ones lint’s symbol index holds for the same file, found with the same patterns, so a name here resolves for an assertion on that platform. An unknown extension, a text over 2 MiB, or one that is not valid UTF-8 gives[], as lint skips such a file.
capture(files, inputs, options, head) → CaptureResult
Section titled “capture(files, inputs, options, head) → CaptureResult”gantry evidence add as a pure call: each input is recorded as a frame. Its
blob is stored once per hash under the content directory, and the evidence
manifest is rewritten in its canonical form with the new frames added, its
comments kept. For the same inputs and head the manifest text and the blob
bytes are the CLI’s, and a Go test runs both and compares them. Everything is
checked before anything is returned.
- Arguments:
{"files": Files, "inputs": [CaptureInput], "options": CaptureOptions, "head": Head}. ACaptureInputis{"name", "data"}:nameis the file’s name (only its base name and extension are used, to label the frame and to guess a type its bytes do not give away) anddataits bytes, base64 (standard alphabet).CaptureOptionsare the CLI’s flags, all strings:platformandappearance(required), andpass,device,app,labelandnote(""leaves each out). Alabelnames one frame, so it takes one input; without it each frame is labelled<pass>-<platform>-<appearance>-<file stem>.headis{"commit", "dirty"}, what the host read from git; an emptycommitsays it has none, so the frames carry none and the result warnsnot a git work tree; frames carry no commit, as the CLI does outside a work tree. - Result:
{"files", "blobs", "frames", "warnings"}(CaptureResultintypes.ts).filesmaps the evidence manifest’s path to its full new text;blobsmaps each new blob’s path to its bytes, base64 (a blob the project already stores is not sent again, so the same screenshot twice is one blob).framesare the new frames in input order, shaped as the model’s, each withstatepulled.warningsare the CLI’s (a project whose.gitattributesdoes not store the blobs through Git LFS). The host writesfilesandblobs; blobs first, so a manifest never names a blob that was not written. - Errors: a refusal is the CLI’s finding text, every problem found joined with
;(*CaptureErrorin Go, whoseProblemslists them): no inputs, a missing platform or appearance, a label given with several files, data that is not base64, an unknown platform, appearance, pass or app, a label that is not kebab-case, repeated or already a frame, or an evidence manifest that does not load. Agantry.yamlthat does not load isgantry.yaml does not load; run gantry lint(ErrCaptureNotLoaded); a project without one isErrNoProject. - The media type is sniffed from the first 512 bytes, as the CLI does, from a
table of the types a capture is (images, PDF, video, archives, fonts) rather than
by
net/http, which would add about 2 MB togantry.wasm; an HTML or XML document is thereforetext/plainand audioapplication/octet-stream(its extension then decides). A file over 64 MiB, or an empty one, is refused.
The bridge
Section titled “The bridge”gantry.wasm (cmd/gantry-wasm) sets globalThis.__gantry to an object
holding one function per name: scope, lint, format, generate, model,
query, edit, rules, refs, symbols and capture. Each takes one JSON string, the arguments
object, and returns one JSON string, the envelope:
{"ok": true, "value": …}{"ok": false, "error": "<fn>: <message>"}Unknown argument fields and trailing data are refused, so a misspelt argument
fails loudly. A panic inside core comes back as
{"ok": false, "error": "<fn>: internal error: …"}, never a crash. The
client encodes the arguments on the main thread and unwraps the envelope:
ok: true resolves with value, ok: false rejects with GantryError.
Building and testing
Section titled “Building and testing”make build wasm # bin/gantry, web/core/dist/gantry.wasm and wasm_exec.jsmake web-test # lint, build and test web/ (needs Node 24 and corepack)The tests run the real gantry.wasm in a worker thread and compare it with
bin/gantry on the example projects. They also hold the size budget:
gantry.wasm is at most 10 MB raw and 2 MB with brotli.