Project-specific guardrails. This file is the source of truth; CLAUDE.md and .cursorrules point here.
Browser-first IFC toolkit: a WebGPU web viewer plus a headless CLI/MCP/server. No first-party desktop app. Domain logic (decode, geometry, styling, export) lives in Rust crates under rust/* and is the source of truth for the server, CLI, SDK, and wasm; TypeScript packages under packages/* and apps under apps/* consume it (TS mostly does GPU upload and UI). Architecture docs: docs/architecture/overview.md.
Everything here is agent-written; there is no AI-disclosure rule. Submitters must answer for the code.
Every PR has an accountable submitter, and the test is answering, not authorship. When review asks a question, the submitter answers with evidence: a test, a run, a measurement, a model file that reproduces it. "The agent wrote it" is never an answer. "Here is the run that proves it" always is. You do not need to be able to write the code. You do need to be able to demonstrate what it does. Unanswered questions block the merge.
A PR claiming user-visible behaviour shows that behaviour. Not "should work". For this repo that usually means a real IFC model from a real authoring tool, an oracle run, or a viewer screenshot: ground truth an agent cannot fabricate, and the contribution it cannot make. Supplying one is worth more than another sweep.
Default lane: a PR closes an issue carrying the ready label. ready means the maintainer has decided it is in scope, wanted now, and scoped. scripts/check-issue-queue.mjs checks this and prints its own mode; read that line, not this one, because no prose here tracks a config key. The escape hatch is the unqueued label, applied by the maintainer.
Filing issues is welcome and unrestricted: an audit producing twenty good issue reports is a real contribution. Filing is not claiming, and an unlabelled issue is not a work item.
One defect class per issue, one issue per PR. A defect class found once and paid for N times is N review contexts for one decision: nine separate PRs once landed one state-reset class, one call site at a time. Fix the class. Above roughly 1,500 changed lines, stack PRs against the same issue rather than shipping one unreviewable diff.
A sweep needs a charter. Audit-driven work is valuable and not discouraged, but it has no natural stopping point, so it needs an issue naming one: what is swept, and what ends it. Approved once, instead of adjudicated per PR.
- Install:
corepack enable && pnpm install. - Build:
pnpm build(turbo). WASM:pnpm build:wasm(needs Rust nightly +wasm-pack);pnpm build:wasm:fetchpulls the prebuilt wasm from npm when Rust is unavailable (e.g. Windows without WSL). - Typecheck:
pnpm typecheck(turbo, wasm-free: no Rust needed). This covers test sources too. The roottsconfig.jsonexcludes**/*.test.tsso tests never reachdist/, everypackages/*config inherits that throughtsconfig.packages.json, andexcludefiltersinclude— so a package's"include": ["src/**/*"]cannot pull its own tests back and most test files were in no typecheck program (#2457). Since vitest andtsx --testtranspile per file without checking types, an unchecked test still runs while everything it asserts at type level (expectTypeOf,@ts-expect-error, a typed fixture) is silently unverified. Each package'stypecheckscript therefore runsscripts/typecheck-tests.mjs, which derives a no-emit test program from that package's own tsconfig and lists the test files underfiles— unlikeinclude,filesis not filtered byexclude. The generated<pkg>/tsconfig.tests.jsonis gitignored (rebuilt every run); the shared emit-off overrides live intsconfig.tests.base.json. Never fix a test-only type error by putting tests back in a package's emit tsconfig; that ships them todist/. - Test:
pnpm test(turbo, TS);cargo test --workspace(Rust, notcargo check);pnpm test:wasm-contract(real wasm boundary);pnpm test:collab(collab pair). - Always run typecheck/test through the root
pnpm typecheck/pnpm test(turbo), never a package-local script (pnpm --filter <pkg> typecheck,cd packages/<pkg> && tsc --noEmit/vitest run) or an editor's TS server in isolation.turbo.jsonmakestypecheckdepend on^build, but that dependency graph only fires through turbo; a package-local script or IDE process resolves workspace siblings straight off theirdist/(roottsconfig.jsonpath-maps most packages todist/*.d.ts; the rest, e.g.@ifc-lite/pointcloud, resolve viapackage.json#types→dist/index.d.ts). An unbuilt or stale siblingdist/then throws "Cannot find module" / missing-export errors that describe no bug in the source; rebuild (pnpm build) before trusting a bypass-turbo result that disagrees withpnpm typecheck/pnpm test. - Dev viewer:
pnpm dev(full monorepo build, then--filter viewer dev; needs a built@ifc-lite/wasm). - Fixtures:
pnpm fixtures(tests skip when absent). Dead code:pnpm knip(TS) /cargo test --workspace(Rust). - Publish:
pnpm changeset; refresh the API-surface snapshot withpnpm api-surface:update.
House rules. No as any / @ts-ignore (fix the types or add a .d.ts); no silent catch {} (log or rethrow); split production modules over ~400 non-generated lines; new packages and features ship tests; package-specific deps go in the consuming package, never root.
Which of those a machine enforces, and which you self-police. The TypeScript house rules above are SELF-POLICED: tsc --strict does not flag as any, @ts-ignore or catch {}, and no lint rule here does either. pnpm lint runs oxlint over apps, packages and scripts. It gates the ERROR tier (the curated .oxlintrc.json list: rules whose every hit here was a real defect) and any per-file RISE in jsx-a11y warnings (check-jsx-a11y.mjs). Other warnings are visible, not blocking; a rule absent from that config still runs at warn. oxlint honours // eslint-disable-next-line <rule> with the directive on the line DIRECTLY above the offence and a reason above that. Clear warnings in files you are already touching, never in a sweep.
Rust is NOT self-policed. CI runs cargo clippy --workspace --all-targets -- -D warnings, so a warning-only defect (an unused import, a needless borrow) is a hard CI failure even when cargo test --workspace is green locally, because cargo test does not fail on warnings. Run it verbatim before pushing Rust.
The ~400-line rule is enforced on both sides: for Rust by the module_size_ratchet test in rust/processing/tests/, for TypeScript by scripts/check-module-size.mjs. A new non-generated, non-test file over 400 lines fails unless it has an allowlist row, and an allowlisted file may not grow past its recorded budget. Prefer splitting to allowlisting. For a module whose bulk is #[cfg(test)], the house pattern is a sibling <name>_tests.rs included via #[cfg(test)] #[path = "<name>_tests.rs"] mod tests; (see stream_meta.rs). The rule binds production modules only; test files are exempt, though a long test file should still be split where it has a genuine logical seam, never merely to hit a line count.
Do not trust any list of CI gates written down in this file. The authoritative list of gates is .github/workflows/; the authoritative list of REQUIRED ones is the main ruleset, gh api repos/:owner/:repo/rulesets. Read them; prose lists go stale.
Run node scripts/pre-handoff.mjs after committing. A delegated task is not done
until it passes or each failure is explained. Report SKIPPED coverage too.
It also runs CI's revert oracle and UI drift ratchet. For the oracle, changed
tests may import only what main has, or the revert stops them loading. Reach a
new module through entry points main has (a CLI, an export); for a pure new
module, run check-test-revert-oracle.mjs with a surgical --mutation <patch>.
Push when ready. Pushes run CI; verify first (local/fleet). Merge: label mergify-trial;
open threads or a red PR viewer selection hold it. Never unlabel, no admin merge.
- User-facing APIs/exports/scripts use exact IFC EXPRESS names: PascalCase attributes (
GlobalId,Name,ObjectType), full relationship names (IfcRelAggregates, notAggregates). Never invent aliases. - STEP type names are stored UPPERCASE; render via
store.entities.getTypeName(id)to getIfcPascalCase. - The rule binds where an EXPRESS name exists. A derived collection is named for what it holds:
EntityRelationshipsData'svoids/fills/groups/connectionshold the related objects, not theIfcRel*entities (#2422, don't re-open). - Frozen, not endorsed:
withAliases(sandbox) emits both spellings, PascalCase canonical, because sandbox scripts are unversioned; templates' non-entity data shapes (BimPropertySet.name, …); and the georeference typesMapConversion,ProjectedCRS,GeoreferenceInfo(eastings,factorX, …), read across the viewer, so a rename is a major (#4673).server-client'sGeoreferencingmirrors the server's snake_case JSON. Fields added to the georeference types keep their casing; other new surface, georeference included, gets the EXPRESS name.
- One canonical load path: every model, primary and federated, any format, loads via
useIfcLoader.loadFile(file, target);useIfcFederation.addModelis a thin wrapper. Never add a second load/ingest pipeline: a federated-only path that drifts fromloadFilesilently skips load-time features. - Resolve selections/IDs through
FederationRegistry(toGlobalId/fromGlobalId/getModelForGlobalId), never ad-hoc math; honor the single-model fallbackglobalId === expressId. Verify behaviour atmodels.sizeof 1 and N.- Resolving a globalId back to a model+expressId is the exception: use
modelSlice.resolveGlobalIdFromModels(viaresolveEntityRef, the canonical caller), not the registry. Two reasons, and the first applies always, not just in a narrow window: the registry knows nothing about overlay-allocated ids, so an entity created throughStoreEditorfails to resolve through it entirely —modelSlice.ts's second pass consultsmutationViewsprecisely for that. It is also store-backed rather than a singleton, so it cannot be stale right after a model swap.toGlobalIdand the registry rule above still stand for everything else; do not hand-roll the offset arithmetic as a third copy.
- Resolving a globalId back to a model+expressId is the exception: use
extractEntityAttributesOnDemandre-parses the source buffer, so never call it in loops; use cachedEntityNodegetters.
- Free every WASM handle (
MeshCollection,MeshDataJs, pre-pass cache) deterministically: wrap pre-pass + job batches intry/finallyso.free()/clearPrePassCache()run on early return, on throw, and when an async generator is abandoned (.return()runsfinally). Getters copy into JS arrays, so.free()right after extraction is safe; don't deep-copy already-extracted meshes. - Coordinates: IFC is Z-up, the viewer is Y-up (converted during mesh parsing).
/api/create(theifc-lite viewCLI REST endpoint) expects IFC Z-up[x, y, z]. - CSG: the pure-Rust exact kernel (
rust/geometry/src/kernel/) is the only CSG kernel on every target; Manifold C++ and the BSP port are deleted, and there is no kernel selection, build-time or runtime. Diagnostics:csg::take_csg_census(),GeometryRouter::take_csg_failures()/take_host_opening_diagnostics(). - Mesh changes land in
produce_element_meshes_owned(processing/src/element/owned_session.rs); native/browser arming isprocessing/src/execution.rs. Discovery usesscan::ScanClass,discovery::Discoveryandcore::is_geometry_job; add a record-kind arm there, not another scan. Column adapters retain scheduling.discovery::TypeGeometryPlanowns type-map policy (EmitTagged/SuppressInstanced); native default-off layer slicing and browser merge/template policies remain explicit. - Workspace
[profile.release]setspanic = 'abort'; harnesses/examples that needcatch_unwind(per-element panic isolation) must build with--profile server-release(panic=unwind). - Driving
GeometryRouterdirectly in examples/harnesses skips the RTC rebase: georeferenced models (>1 km coords, e.g. ISSUE_098 at ~5,000 km) produce f32-fabricated geometry "failures"; bucket by coordinate magnitude or rebase before blaming the kernel. - Colour and coordinate resolution shares Rust resolvers between native
process(content, request, sink)and browser batches; don't fork it. Single homes:default_color_for_type,resolve_submesh_color,extract_surface_style_colors(the IfcSurfaceStyle to Rendering to Colour leaf; SurfaceColour is the apparent colour, a distinct DiffuseColour IfcColourRgb is onlyshading_color, per #859/#871), and the indexed-colour resolvers, all inifc_lite_processing::style;rotation_angle_about_z(site/building rotation, offresolve_scaled_placement) inifc_lite_geometry.styling_parityRust tests fail the build if a duplicateget_default_color*table or a per-pipelineextract_color_from_rendering/extract_color_rgbreappears. New type default: editdefault_color_for_typeand extend the mesh fixture. Sanctioned exceptions: the 2D drafting fill palette (IFC_TYPE_FILL_COLORS,Drawing2DCanvas.tsx) is a drafting convention rather than 3D appearance, and standalone debug tools underrust/geometry/examples/(can't reach the downstream crate). (#913, #996, #997) - Cross-platform determinism is enforced weekly by
.github/workflows/determinism.yml(arm64; dispatch it before kernel-sensitive merges): it re-runsexact_predicate_determinism,geometry_correctness_harnessandexport_goldenagainst the committed x86_64 pins; a mismatch is a real platform bug. It also pinsrust/processing/tests/manifests/mesh_determinism.json(x86_64/arm64) andmesh_determinism.wasm32.json(equal except the libm-trig gap): a legitimate geometry-output change re-pins both, not just the snapshots (#1492,docs/architecture/mesh-determinism.md). Byte outputs are hash-pinned intests/golden/*.json; a red pin prints itsIFC_LITE_REPIN_GOLDEN=1command; re-pin only what you meant to move (#7671). - Geometry-affecting PRs also run
.github/workflows/ifcopenshell-parity.yml(path-gated): a per-PR quick lane diffs ifc-lite against committed reference dumps intools/ifcopenshell_reference/, plus a nightly full lane on the pinned engine. It IS blocking:parity (in-tree fixtures, committed reference)is a required context in themainruleset, so a legitimate output change means regenerating the committed reference in the same PR (#1519). Being absent fromtest.ymlsneeds:list is a different thing from being non-required.
- Perf-sensitive paths:
rust/geometry,rust/processing,rust/core,packages/geometry,packages/wasm,scripts/build-wasm.sh. A change under these must carry a perf verdict in the PR. - Read the ledger before optimizing:
scripts/perf/README.md(lever ledger) lists shipped wins, dead ends, and un-shipped levers. Do not re-spike a listed dead end without a genuinely new mechanism — isolated microbench wins have been refuted end-to-end three times (#1429 threaded WASM, Manifold, #1445 shared-index). A perf claim is only real as an end-to-end worker-pool number, never a kernel-only microbench. - Measure base-vs-branch, never vs the committed baseline. Run
scripts/perf/probe.sh <fixture> --iters 5 --jsonon both your base and your branch, and paste the parse/geometry/total deltas plus a byte-identity statement (mesh/triangle counts unchanged, or an FNV hash if outputs may legitimately differ). Default fixture:tests/models/ara3d/AC20-FZK-Haus.ifc; for CSG/void/mesher changes also runtests/models/ara3d/ISSUE_129_N1540_17_EXE_MOD_448200_02_09_11SMC_IGC_V17.ifc, and when feasible a heavy CSG model (Holter/ISSUE_053) since per-PR CI never touches it and that is where every shipped regression has lived. - Never cite a local
pnpm benchmark:checkagainsttests/benchmark/baseline.jsonas evidence — the baseline is CI-recorded (SwiftShader), so faster local hardware makes it vacuously green. Use the scratch-baseline flow intests/benchmark/README.md. - Guard against contaminated measurement: confirm
packages/wasm/pkg/ifc-lite_bg.wasmis newer than yourrust/edits before trusting a WASM number (stale artifacts and turbo overwritingpkg/have each caused phantom regression hunts); run each A/B interleaved on an otherwise-idle machine; in the browser, load the target file first in a fresh tab (the 7th load in a session runs 2-4x slower from memory pressure, not code). - Record the verdict in the repo, not chat. When a perf PR closes with a measured result, record the verdict and lesson (what won/lost and why, so the next agent doesn't re-walk it) in the
scripts/perf/README.mdledger in the same PR. This is distinct from the numeric baseline, which lives only in the generatedperf-numbersregion ofdocs/guide/performance.md(see Documentation upkeep) — the ledger carries the narrative, the docs carry the numbers; don't duplicate a benchmark figure into the ledger prose.
- Don't hand-edit
packages/wasm/pkg/*: change the Rust crates and regenerate withscripts/build-wasm.sh. The wasm runtime (.wasm/.js) is gitignored and rebuilt on every Rust-capable host; the type surfacepkg/ifc-lite.d.tsis committed (force-added past the wasm-packpkg/.gitignore*) for the wasm-free typecheck lane (#952), sopnpm typecheckruns without the Rust toolchain (tsconfig.jsonpath-maps@ifc-lite/wasmtopkg/ifc-lite.d.ts, andbuild-wasm.shsoft-skips when wasm-pack is absent).build-wasm.shstrips the platform-variant__wasm_bindgen_func_elem_*trampoline indices from the.d.tsso the sync gate can exact-diff across macOS/Linux, so only ever regenerate it via that script. When a Rust public-API change alters the bindings, re-runbuild-wasm.shand commit the regeneratedpkg/ifc-lite.d.ts; CI (test.yml, "Verify committed wasm types are in sync") fails if it drifts.build-wasm.shalso rewritespkg/README.mdandpkg/package.json, which is why neither is tracked — they fall under thepkg/.gitignore*like the runtime, so the churn can no longer reach a commit. Nothing reads them: the workspace member ispackages/wasm/package.json, and the docs gate checkspackages/wasm/README.md. - The wasm build needs only the pinned Rust nightly +
wasm-pack(the Manifold C++ / LLVM-20 cross-toolchain was removed at M9; the bundle is pure Rust). That toolchain is single-sourced in the.github/actions/setup-wasm-buildcomposite action: change it there once, not per-workflow (git grep -l setup-wasm-build .github/workflowslists the consumers). - The
apps/desktopTauri shell and the viewer override-contract are gone (see top). The desktop capability lives in@ifc-lite/geometry(IPlatformBridge/NativeBridge/isTauri(),@tauri-apps/apioptional dep) for third parties building their own Tauri shell; keep it web-pure (it must never be imported on the web path, and is lazy-loaded only underisTauri()). - The Rust tree is intentionally not rustfmt-clean and no CI runs fmt: never run a repo-wide
cargo fmt(it produces a 100+ file reformat blast that buries the real diff). Format only the lines you touch. - Beyond the server, CLI, SDK, and wasm, a fifth Rust consumer exists: the PyO3 wheel
ifclite_geom(rust/python, abi3-py39). Public-API changes in the Rust crates it builds on can break it;.github/workflows/python-wheels.ymlcarries the path gate and publishes on anifclite-geom-v*tag. - Adding or changing a sandbox bridge method (
packages/sandbox/src/bridge-*.ts, i.e.NAMESPACE_SCHEMAS) also changes the generated ambientbimtype surface,apps/viewer/src/lib/scripts/templates/bim-globals.d.ts(the types the built-in template scripts under that folder are written against). Runpnpm generate:bim-globalsand commit it; CI (node scripts/generate-bim-globals.mjs --check, node-tests job) fails on drift. The editor completions and the LLM system prompt readNAMESPACE_SCHEMASlive, so the.d.tsis the only consumer that can rot — and it did: it never carriedbim.clash(#891 → #2418) and lost twocreateparameters at #598, because the generator had stopped running and the file got hand-edited instead. Never hand-edit it; fix the schema and regenerate. - A
tsReturn/tsParamTypesmay NAME a type instead of spelling its shape inline (Promise<BimClash.ClashResult>). Those declarations are extracted from their defining package byscripts/generate-bim-globals.mjs(DERIVED_TYPE_SOURCES/DERIVED_TYPE_ROOTS) — never transcribe another package's types into the generator, which would be a hand-maintained copy in the one script whose purpose is to stop copies rotting (#2422). Referencing a type the generator cannot resolve is a hard error telling you which list to add the file to.pnpm check:templates(node-tests job) typechecks the built-in templates against the generated surface and is what catches atsReturnnaming a type that is never emitted; its tsconfig keepsskipLibCheck: falseon purpose, because the generated.d.tsis the subject of that check rather than a dependency of it. Cargo.lockis committed (app crates need reproducibility; an upstream yank broke CI once). Refresh withcargo update -p <crate>, never by deleting it.- Neither a PR branch nor
maindeploys to Vercel: Git deploys are off for every branch butproduction(git.deploymentEnabledin eachvercel.json), so PRs get no Vercel checks, and production moves only when.github/workflows/deploy-nightly.ymlfast-forwards theproductionbranch (05:45 UTC nightly, orworkflow_dispatchwith a ref already onmain) — so a merge is live within 24h. To preview a branch:vercel linkper root (.,apps/viewer-embed,apps/landing), thenvercel pull --environment=preview && vercel build && vercel deploy --prebuilt --archive=tgz.
- A public API or CLI flag change updates the matching guide in the same PR.
docs/guide/*.md,docs/tutorials/*.md, and the README carry livets/typescriptsnippets that CI typechecks against each package'ssrc(pnpm docs:check-samples), so a renamed export or changed signature fails the build until the snippet is fixed. Snippets use shared ambient globals (scripts/docs/doc-samples-globals.d.ts); a snippet that is deliberately illustrative pseudo-code opts out with<!-- docs-check: skip -->on the line directly above the fence (use sparingly — prefer fixing it). - Perf and size numbers live only inside the generated
perf-numbersregion ofdocs/guide/performance.md, stamped fromtests/benchmark/baseline.json. Don't hand-write a benchmark number into prose; refresh the region withpnpm docs:generateafter recording a new baseline. - The package table in
docs/api/typescript.mdand the CLI command table indocs/guide/cli.mdare generated (<!-- BEGIN/END GENERATED -->regions). Edit the source (eachpackage.jsondescription, the CLIHELPtext), then runpnpm docs:generate; CI (pnpm docs:check-generated) fails if a region is stale. - Every new published package ships a
README.md(it is the npm landing page); CI enforces this withpnpm docs:check-readmes.
- Changes to published
packages/*needpnpm changeset(never hand-edit versions orCHANGELOG.md). Bump level = biggest API change: removing/renaming an export ismajor(>=1.0 pkg) orminor(0.x), neverpatchwhen the surface shrank. - Only re-export from a package's
index.tswhat has a real consumer: an unused public export is permanent semver liability. - The exported surface of every published package is snapshotted in
scripts/api-surface.jsonand CI-enforced (scripts/check-api-surface.mjs): when you intentionally add/remove/rename an export, runpnpm api-surface:updateand commit the snapshot alongside the changeset.
- Supersede means delete: replace a path, remove the old one in the same PR. No "legacy"/"fallback"/"just-in-case" path; if one must stay, gate it behind
// TODO(remove-by: <cond>, <owner>)and a tracking issue. - Delete dead code with the change that orphans it. When renaming/removing a public symbol, grep the whole repo (
docs/,examples/,scripts/,*.md) and fix every reference in the same PR. - Prove removals: TS with
pnpm knip(on-demand, not a CI gate); Rust withcargo test --workspace, notcargo check(check skips#[cfg(test)], so a test-only reference to a deleted fn slips through). Intentionally-unused Rust items need#[allow(dead_code)]and a why.
- Not committed (no LFS): catalogued in
tests/models/manifest.json, fetched viapnpm fixtures. Tests must skip (never throw/panic) when a fixture is absent; point topnpm fixturesin the skip message. Add one: drop undertests/models/<group>/, runpnpm fixtures:manifest, thenpnpm fixtures:upload; commit only the manifest. CI runspnpm fixturesbefore tests.
File-supplied references can cycle, overflow the stack (uncatchable SIGABRT)
or fan out until the loader hangs. #2866 found seven unbounded sites.
- A depth cap bounds path length, not breadth: cycles can still cost
O(k^depth)(7.21s measured at k=3). - A visited set bounds revisits, not recursive stack use on a long acyclic chain.
- A work budget bounds acyclic DAG expansion even when no id repeats on the current path.
Choose the visited set's SCOPE by what the walk returns:
- global / memoising when the result is a pure function of the id (a colour is determined by item id plus style map). Safe and strictly stronger: it kills fan-out outright.
- path-scoped (insert on the way in, remove on the way out) when output ACCUMULATES. A boolean operand tree is a DAG and geometry accumulates, so the same node down two branches is two real pieces of geometry. A global set silently drops the second: missing geometry, not a cycle guard, and no termination test notices.
Prefer iterative walks with visited sets: no stack depth cap is needed.
Tight caps reject valid input (#960: 42-node Revit FirstOperand chains).
Use ifc_lite_core::limits for shared bounds; see
ifc_lite_geometry::placement::resolve_chain for an iterative, visited-set
PlacementRelTo walk without a depth cap. For branching occurrences,
representation::RepresentationWalk uses an explicit stack and path-scoped
cycle checks, MAX_MAPPED_ITEM_DEPTH for geometry callers, and Expand work
budgets for mapped attempts and Items members (default MAX_WALK_LEVELS).
A guard that both ACTS and REPORTS has a two-part contract — bound the work, and report that you bounded it. Mutate the halves separately; they fail differently (a missing bound hangs, a missing report returns a truncated success).
scripts/check-refwalk-guards.mjs (CI) enforces the presence of a guard, not
its choice: it fails when a self- or mutually-recursive function, or a
cursor-chasing loop, reaches decode_by_id/resolve_ref/resolve_ref_list
under rust/geometry/src, rust/processing/src or rust/wasm-bindings/src
with no visited set, path stack or depth cap in scope. Five of the six #2866
fixes are detected at their parent commit and clear at the fix; the sixth
(#2870) spans two files and is missed, which is the documented blind spot. Which
guard is right stays a review question — everything above still applies. The
allowlist is scripts/refwalk-guard-allowlist.txt and is empty.
-
A new test must assert behavior through a real fixture or a stated invariant. Don't write: set-state-then-read-it-back store tests, tests that assert a mock's return value (they test the mock), constructor/setter tautologies, or byte-for-byte output pinning unless the byte layout IS the compatibility contract (e.g. signed bundles). Regression tests cite the issue/PR number in the test name or a comment.
-
Every package with test files needs a
testscript in its package.json orturbo testsilently skips it;scripts/check-test-wiring.mjs(CI) enforces this. Packages use vitest OR node:test viatsx --test; match the package's existing convention, never mix within a package. -
A new gate under
scripts/must be INVOKED, and a package.json entry is not invocation. A guard nothing runs is as absent, and as invisible, as one that finds nothing: #3062 shipped a gate script and its test with no workflow step, nopackage.jsonscript and no turbo task, and nothing flagged it.scripts/check-test-wiring.mjsauditsscripts/— everycheck-*/verify-*file at any depth and in.mjs,.jsor.cjs(verify-npm-publish.jsandcheck-benchmark-regression.jsare real gates). It accepts exactly the wiring this repo actually uses: a.github/workflows/step runningnode scripts/<gate>.mjs(the common case, see thenode-testsjob); a rootpackage.jsonscript a workflow reaches throughpnpm <name>, possibly transitively (check-changesets.mjs<-lint<- the Lint job); a workspace package's script reached by a turbo task (check-tla-chunk-await.mjsis the viewerbuildscript's tail so Vercel runs it too); or a file that an already-reached script imports or spawns. A rootpackage.jsonentry no workflow calls is rejected.scripts/*.test.mjsis audited separately from the gate itself. Thenode --testcatch-all intest.ymlis per-directory, because a shell glob has no**, and a gate whose test runs while its script never executes is still the #3062 failure.A script that genuinely should not run in CI declares
@unwired-by-design <reason>in its own header and is then listed in the checker's OK output rather than hidden. Nothing judges the reason, so its only safeguard is that every declaration is printed and lives in the diff. STATED HOLES: the check is lexical and does not evaluate workflow expressions, so a gate whose only step sits in a job withif: falsestill counts as wired; andaudit-*.mjsreports rather than gates, so it is not demanded. -
Never assert on a source file's text. A test that greps
Thing.tsxcertifies a string exists, not that the code works:SearchModal.filter.wiring.test.tsxasserted the whole body ofhandleRowClickand stayed 5/5 green whenonRowClick={handleRowClick}was replaced withonRowClick={() => {}}— defect #2396 verbatim.scripts/check-source-text-assertions.mjs(CI) blocks new ones; the remaining list is inscripts/source-text-assertion-allowlist.txtand only ratchets down (#2434). -
Testing a viewer component. It is mountable — including one that reads
useViewerStore, which is a module-level Zustand store you seed withsetState. Two Vite-isms blocked it; both are fixed inapps/viewer/src/test/. The recipe:import '@/test/setup-dom.js'; // MUST be first: registers happy-dom import { installLayout } from '@/test/dom-layout.js'; installLayout(); // only if it virtualizes or measures import { render, click, advance, cleanup } from '@/test/render.js'; import { fixtureModel, fixtureModels } from '@/test/store-fixture.js'; useViewerStore.setState({ ...fixtureModels(fixtureModel('m', { idOffset: 1_000_000 })) }); const ui = render(<YourPanel />); click(/* what a user clicks */); assert.equal(useViewerStore.getState().selectedEntityId, expected);
~icons/*(unplugin-icons virtual modules) andimport.meta.envare handled bysrc/test/vite-module-hooks.mjs, registered from the--importflag in the viewer'stestscript — it cannot be registered from inside a test file, because module resolution finishes before any module body runs.installLayout()also makesResizeObserverdeliver an entry: happy-dom ships the class but never fires it, which is why a virtualized list otherwise renders zero rows. Viewer mounting (#2434):RibbonToolbarand its tabs mount as-is;FileTabneedsfileCommands;PropertiesPanelandModelQueryneed a real parsed store, not a cast stub (new IfcParser().parseColumnar(...)over inline STEP);ViewportContainerneeds stubbednavigator.gpuand a loaded model, else it shows "WebGPU Not Available". Radix dropdowns open onpointerdownthenclick, and portal todocument.body.RibbonContentLargeButtonnames itselftooltip ?? contentLabel; registeredRibbonCommandLargeButtonuses the registry label as its name and tooltip as its description. Assert visible and accessible labels separately. Assert behavior, not wiring: an unreachable component, ignored hook result, or uncalled handler can look correct in source. #2434 tests that only found a component survived deleting it; assert its values (one such bug shipped until mutation testing). -
Geometry/WASM changes: mocked
@ifc-lite/wasmtests prove nothing about the boundary;pnpm test:wasm-contractruns the realbuildPrePassOnce/processGeometryBatchpath and pins the field surface plus unit-scale contract. Extend it when adding wasm API surface. It skips clean (exit 0) if the wasm runtime isn't built, so a local green there proves nothing unless you ranscripts/build-wasm.shfirst (CI restores the built artifact before the step).
- Discover the full SDK API with
ifc-lite schema(JSON).evalruns SDK expressions (ifc-lite eval model.ifc "bim.query().byType('IfcWall').count()"); always pass--jsonfor machine output.HeadlessBackend(packages/cli/src/headless-backend.ts) runs query/export/create/IDS/BCF without a renderer.
collab-server(packages/collab-server) persists CRDT state (Yjs update frames plus room/audit logs) to disk, so a persistence-format change needs legacy migration or you poison existing rooms (a data-loss class, #1501). Exercise the pair withpnpm test:collab(beyondturbo test); run the server withpnpm collab:server. Recipients rebuild the model from the CRDT via IFCX (snapshotToIfcxthenparseIfcxViewerModel), not a legacy STEP transport.
- One way to save a file:
apps/viewer/src/lib/export/download.ts. UsedownloadBlob/downloadFile/downloadDataUrl; never hand-roll an<a download>plusURL.createObjectURLdance, and never write another filename regex.downloadFilealready copies the wasmUint8Array<ArrayBufferLike>into aBlobPart, and emitsemitFileDownloaded(lib/tours/events) so task-gated tours can observe saves; a bespoke download path breaks tour progression, not just filename handling. - Run every user/model-derived filename through
sanitizeFilename(preserves case and dots, strips only OS-unsafe chars, see #1299). It is not a slug; don't lowercase or hyphenate names for filenames. Slugs (extension IDs) are a separate concern. - CSV and list exports neutralize spreadsheet formula injection on user-derived cells, including BOM-prefixed values (#1506). Route any new export column through the existing sanitizer; never hand-roll a CSV writer that skips it.
- Elements carrying
data-tourare interactive-tour anchors. If you move, rename, or delete one, updateapps/viewer/src/lib/tours/anchors.tsand the referencing steps underapps/viewer/src/lib/tours/tours/in the same PR. An anchor no component renders failsanchors.contract.test.ts; one unmounted when its step runs auto-skips and fires atour_step_brokenPostHog event. Tour telemetry (lib/tours/telemetry.ts) carries only registry ids, enums, and numbers, never file or model names (scrub-safe). - The tour demo kit reuses the committed
building-architecture.ifcsample as its base; its variants (building-architecture-rev-b.ifc,building-architecture.ids,demo-kit.json) are derived from that base bytools/demo-kit/derive-variants.mts. Revision B preserves the base's GlobalIds (diff matches on GlobalId, so a regenerated base would make compare read as 100% added/deleted) and carries the injected clash. Never hand-edit or regenerate one artifact in isolation; rerun the derivation script, which self-verifies the IDS/clash/diff invariants.
- Everything here is world-readable the moment it is pushed: code, docs, comments, commit messages, PR titles and bodies, changesets, issue text. Write as if a competitor and a client are both reading, because they are.
- Never name a client, customer, prospect, or partner organisation, and never describe a commercial relationship (engagement, contract, statement of work, pricing, fee, or the intent to convert one into another). Use a generic segment instead: "an AEC design platform", "a desktop authoring client", "an enterprise buyer".
- The same rule applies to anything a named party would consider non-public: their customer base or buyer profile, internal or unreleased API schemas, unreleased product plans, architecture they have not published, and any data they supplied.
- This binds commit messages and PR text as much as file contents. A commit that removes a client name but explains itself by naming the client has published it again.
- Roadmap, strategy and ecosystem docs are the usual offenders, because naming a real partner feels like it makes the argument concrete. It does not; the generic segment carries the same argument. If a claim only works with the real name attached, it belongs in a private repo.
- If you find such a reference, remove it and say so without repeating it. Removing it from the working tree stops further publication but does not erase git history, so flag it rather than assuming the fix is complete.
- MPL-2.0 header on every new file: see
./LICENSE_HEADER.md.
Respect assignments, and assign yourself before you start. This is not etiquette, it is the mechanism that stops two people building the same thing.
Before touching an issue:
gh issue view <n> --json assignees,title— if someone else is assigned, it is theirs. See "Helping on someone else's issue" below for the two ways that changes.- Look for an open PR on it.
gh pr list --search "<n>"is a TEXT search: it matches comment bodies, so it both misses linked PRs that never mention the number and returns unrelated ones that happen to contain it. Treat a hit as a reason to look, not as an answer, and confirm by opening the PR. The linked-PR list on the issue page is authoritative where the two disagree. - If both are clear,
gh issue edit <n> --add-assignee <you>before writing code, not when you open the PR. An assignment made at PR time claims nothing; the window it needed to cover has already closed.
Check again immediately before opening the PR. A claim can appear while you work, and the second check is the cheap one.
gh issue edit --add-assignee cannot tell two agents apart: they all push and assign as the same account. An assignment to that account means somebody claimed this. It does not mean you did, and the field cannot tell you which. So treat it as a claim by someone else until you can show otherwise, and leave a claim comment naming the session, which is the only artifact that can:
gh issue comment <n> --body "Claiming this. Session <id>, branch <name>."
If the account is assigned with no claim comment, ask on the issue rather than reading the field as your own. This applies to OUR sessions only. An outside contributor has their own account, so for them the field says what it appears to say.
Also label the claim with your session's claimed:session-<id> label (create it if missing; <id> is your branch suffix); remove it when the PR merges or you stop. Outside contributors' issues get claimed:contributor. Before starting, gh issue view <n> --json labels: a claimed:* label that is not yours means it is taken.
Doing one does not do the other. Run both, every time:
gh issue view <n> --json assignees # is one of us on it
gh pr list --search "<n>" # CANDIDATES; confirm on the issue page
On #3012 the account was self-assigned and a PR appeared 47 minutes later. That looked like a session ignoring the claim; it was an outside contributor, who has no reason to know about an internal assignment. No assignee field would have helped, because no session held it. Only the PR search would have.
The expensive case is that both of you are already half-built when the claim appears. The session named in the earliest claim comment decides. The other stops immediately and hands over what it has as a comment or a patch on that session's PR. "The assignee decides" cannot work here, because the field holds one shared account and cannot name a session.
An outside contributor's PR takes precedence over any internal claim, however early. They cannot see our claims and are not bound by them. Stopping mid-build is cheap; two finished implementations of the same thing is not.
Helping is welcome. Taking over is not. Two things make it help: they accepted an offer (silence is not a yes), or it has gone quiet (no commits, no word, about a week; even then comment first and wait a couple of days).
Help, no permission needed: reviewing their PR including finding real defects; diagnosing a failing check and posting the cause; answering a question they asked; reporting a defect in shipped code even if their PR introduced it.
Not help, however good the code: building a parallel implementation and announcing it afterwards; carrying an unraised branch that duplicates their work; pushing to their branch; opening a competing PR on their issue.
If you built something before noticing, say so plainly, hand it over, and let them decide. That is recoverable; landing it is not. Do not close a duplicate silently: list what it holds that the survivor does not.
This rule exists because it was broken twice in two days against the same external contributor (#2951 filed, assigned and implemented by them as #2952, with #2970 arriving fifteen hours later doing the same thing; and #2670, where they were mid-development when told a parallel implementation existed). The cost is not the wasted effort. It is that a contributor who did everything correctly had to be the one to raise it, twice.
Applies to every agent and every session, including short-lived subagents.
This root file is the shared contract; the closest AGENTS.md to an edited file also applies. Package-specific gotchas live in code-adjacent files: apps/viewer/AGENTS.md, rust/AGENTS.md, packages/geometry/AGENTS.md, packages/collab/AGENTS.md, packages/collab-server/AGENTS.md. Add more as a package accumulates its own footguns.