Skip to content

t1k:cocos:base:source-scan-guard

FieldValue
Modulebase
Version4.51.9
Effortmedium
Tools—

Keywords: build-only trap, circular import, domain purity, es2017 target, es2020, iterator spread, lint guard, map set spread, multiple ccclass, preflight scan, scan source, source scan, test under assets

/t1k:cocos:base:source-scan-guard

After any merge, rebase or conflict resolution, run this and the type gate (t1k-cocos-base-tsc-validate) before anything else — before more edits, before a build. A hand-resolved conflict leaves unparsable or duplicated code (a merge-magnet file such as a shared GameConfig.ts/ViewTypes.ts is the usual site; a template merge can duplicate a method), and the guard exits 2 on a file it cannot parse, which is the fastest signal. Evidence: ForceMasterPort and two H5 clones fixed this after the fact.

Before a review, before a build, and after any change to code that touches Map/Set, module imports, @ccclass files, or the domain/ layer. Every check here is invisible to the editor preview and to tsc — they only surface in the shipped build, or in the bundle size, which is why they need a scanner rather than a reminder.

NOT for: style, naming, or formatting (that is t1k-cocos-base-code-conventions), and not a substitute for /t1k:doctor, which validates the kit rather than a project’s sources.

scripts/source-scan-guard.cjs — cross-platform Node; its one runtime dependency is the pinned typescript compiler API (see “Target detection”).

Check idSeverityFlags
map-set-iterator-spreadERROR[...map.values()], [...set], [...new Set(x)], and the same spread inside a call’s arguments (Math.max(...m.values())) — the build’s loose-mode down-level breaks all three shapes identically
map-set-iterator-spreadWARNfor … of over a Map/Set — lowered to a .length-indexed loop, iterates zero times. Warn because the corpus contradicts itself; see below
map-set-iterator-spreadWARNfor … of over an Iterable-typed subject — its own hint says to trace the call sites first, because an array is Iterable too and iterates fine
circular-value-importERRORa value-import cycle across @ccclass modules carrying an in-cycle @property(X) (including the array form, @property([X])) — the decorator evaluates mid-initialisation and the scene ref is silently dropped
circular-value-importWARNa value-import cycle with no in-cycle @property(X) — a layering smell, not a build break (no @property means this half cannot fire without a @ccclass in the cycle)
multiple-ccclassERRORmore than one Component subclass per file (editor errorID 3615)
engine-import-in-domainERRORcc or db:// imported under **/domain/**
engine-import-in-domainWARNthe same import under **/application/** — the corpus carries legitimate pure-data db:// imports there
es2020-syntaxWARN?., ??, ??= under a <= es2017 target
es2020-syntaxERRORBigInt literal under a <= es2017 target — not downlevelled, tsc rejects it (TS2737)
test-under-assetsERRORa test file under assets/ outside a dot-prefixed directory
es2019-apiERROR.flat(, .flatMap(, Object.fromEntries, .matchAll(, .replaceAll(, structuredClone(, and .at( on an obvious array/string (literal, or the result of split/slice/filter/…) when the effective lib is below the API’s edition. Effective lib = the highest ES entry of compilerOptions.lib (es2022, esnext, es2019.array …), else the target’s default; this.flat()/this.at() are the project’s own methods and skipped
es2019-apiWARN.at(x) on a receiver the scan cannot prove is an Array/String (could be a project accessor), and every hit when no tsconfig was found (target unknown — it cannot prove the API missing)
debug-flag-hardcoded-trueWARNa variable, object property or class field whose name contains the word debug/cheat/cheats (DEBUG_KEYS, debug, enableCheats, _cheatMode) initialised to literal true. @property-decorated fields are skipped (the scene overrides them)

Why es2019-api is an ERROR and debug-flag-hardcoded-true is a WARN. An ES2019+ call against an es2017 lib is never correct code for that project: tsc rejects it or the shipped runtime lacks it, and the id covers the whole ES2019-ES2022 surface (the name is the first edition). A hardcoded-true debug flag is only a defect when it ships, and the scan cannot tell a dev-only entry point from release code, so it advises. Gate it on import { DEBUG } from 'cc/env' (or default it false). Tighten per project with checks: { "debug-flag-hardcoded-true": "error" }. Evidence: JuiceKingIdle e8654092, 08e350e (ES2019 calls fixed three times after the guard passed them); VitaMahjongg docs/p6-release-gates.md (debug keys shipped).

multiple-ccclass counts classes that resolve to Component — directly, or through a base class declared in the same file. It does not count @ccclass decorators: Cocos permits any number of non-Component @ccclass data classes in one file, and errorID 3615 is a component-registration constraint. A base class imported from another file (class Hud extends BaseView) is not guessed at — see gotcha 7.

Target detection reads temp/tsconfig.cocos.json first, then tsconfig.json, then --target / --downlevel-iteration; with neither file it falls back to es5. The target drives the es2020-syntax check only, never the iterator check (§ “The for…of contradiction” below). Monorepos: pass --project <dir> naming the directory that holds the project’s own tsconfig.json and assets/, not the git root. The JSONC order, the nested-tsconfig search, the --no-nested-tsconfig pin and the TypeScript compiler-API install (exit 2 when missing) are in references/target-and-monorepos.md.

Terminal window
bun .claude/skills/t1k-cocos-base-source-scan-guard/scripts/source-scan-guard.cjs --changed
bun .claude/skills/t1k-cocos-base-source-scan-guard/scripts/source-scan-guard.cjs --all --json build/source-scan.json

Flags: --all · --changed (git diff against the merge-base) · --files a.ts,b.ts · --project <dir> · --target <es5|es2017|…> · --downlevel-iteration / --no-downlevel-iteration · --assume-native-iteration · --no-nested-tsconfig · --json [<path>] · --format json|text · --quiet · --config <path> · --verdict (checkpoints mode — see § “Unsummoned enforcement” below).

Exit: 0 no ERROR (warnings allowed) · 1 at least one ERROR · 2 usage/runtime error — the scanner could not run or read what it was asked to read (see gotcha 12). Never treat 2 as a pass.

Output. The JSON report is the complete, machine-readable surface — every finding, sorted ERROR first, then by file/line/check. Text output prints every ERROR but caps WARNs at 10 per check and ends with … N further warning(s) not shown (…), so a project with hundreds of advisory hits cannot scroll the one build-failing line off the screen. --json - or --format json writes JSON to stdout; --json <path> writes it to a file (creating parent directories).

Config at .claude/source-scan-guard.json (or source-scan-guard.json at the project root) overrides the defaults — domainGlobs (default **/domain/**), applicationGlobs (default **/application/**), testPatterns, ignore, assumeNativeIteration, and checks (per-id "off"/"warn"/"error"):

{ "domainGlobs": ["**/domain/**"], "checks": { "es2020-syntax": "error" } }

You should not need ignore for the CPM vendor mirror (#1040). assets/packages/** — the playableSync / t1k modules update mirror of published @playablelabs/* packages — is scanned, but its findings are tiered: still reported, still tallied, never counted toward the verdict or the exit code. It is in scope by construction on every CPM project and a project must not edit a file in it, so before this tier existed the checkpoint sat red on a pristine project and a package-sync commit read as this project’s regression. Three surfaces show the split:

SurfaceOwn codeVendored (assets/packages/**)
countserror / warn / totalcounts.vendored.{error,warn,total}
findings[]every findingevery finding, each vendored: true
text outputfull list, ERRORs uncappedprinted under a vendored (…) heading
verdictdecides green/reddetail.vendored, named in evidence

Use ignore for a different directory you own and want excluded outright — it drops a path from the scan entirely (no findings, no counts), which is the right answer for editor-generated or out-of-tree trees and the wrong one for the mirror, where you want the findings kept.

The predicate is assets/packages/ exactly — a project’s own code under, say, assets/scripts/packages/ keeps full weight. --changed tiers the mirror the same way, so a playableSync commit no longer reports vendored .ts churn as this project’s change.

Unsummoned enforcement — the source-scan-guard checkpoint

Section titled “Unsummoned enforcement — the source-scan-guard checkpoint”

--verdict emits the layered-checkpoints {status, evidence, detail} object on stdout (§10 of theonekit-core’s plans/260909-layered-project-checklists) instead of the default text/JSON report, and inverts the exit-code convention: 0 whenever the scan ran (red or green alike), 2 only when it could not run — the exit code separates ran-from-crashed, never green-from-red. It composes with the selection flags above (--all / --changed / --files); naming none of them defaults to --all, deliberately not --changed, so an unsummoned run cannot miss a change that was never committed.

.claude/t1k-checkpoints-cocos.json’s source-scan-guard entry calls --verdict at Stop, on ANY anchored Cocos project, whether or not anyone invoked this skill. That is the enforcement mechanism for a cc/db:// import landing in a Domain/Application file — including one written by a Bash sed/heredoc/script that no PostToolUse: Edit|Write|MultiEdit hook could ever see: the checkpoints Stop pipeline re-verifies from a git-working-tree diff, not a tool-call queue, so it is tool-agnostic by construction. This kit ships zero hooks by design (gate #22 — see .claude/HOOKS-STATUS.json), so the checkpoint is the whole story here; there is no separate .claude/hooks/ entry to look for.

Two kill switches: T1K_SKIP_CHECKPOINTS=1 disables the entire checkpoints pipeline (every checkpoint, every kit); T1K_SKIP_SOURCE_SCAN_GUARD_CHECKPOINT=1 disables only --verdict mode, reporting unknown (never a silent green) so a deliberate skip is never mistaken for a clean scan.

A WARN-only run is red, deliberately (#1040). --verdict keys off counts.total (own-code findings), not counts.error — so one advisory es2020-syntax in your own code still reds the checkpoint, and the reporter’s measured workaround (1 error / 107 warns → 0 errors / 90 warns) would have stayed red even after the vendored ERROR was gone. Two reasons that is the intended shape rather than a bug: the tier at severity is what makes the reporting advisory — this checkpoint’s own entry is severity: warn in .claude/t1k-checkpoints-cocos.json, so a red never blocks a write, it only lists the checkpoint in the Stop frame. And a verdict that turns green on “only warnings” cannot be told apart from one that scanned cleanly, which is exactly the false-green theonekit-core/.claude/modules/t1k-verification/rules/green-that-proves-nothing.md names. If a specific check is noise on your project and you have confirmed it against the emitted bundle, silence that check — not the severity: checks: { "es2020-syntax": "off" } — so the remaining checks keep their weight. Vendored findings never reach this decision at all; see the config section above.

The checkpoint’s verify.selfTest reuses the tests/fixtures/domain-red fixture above — it is already a proven RED case for check 4 (engine-import-in-domain), so no second fixture was needed.

The spread half ([...map.values()]) is an ERROR in every build mode; the for…of half is a WARN because two studio sources disagree and both are right for their own build mode, and the check never consults target. Confirm against your own emitted bundle before treating it as a defect. Iterable<T> subjects raise the WARN arm only. Reasoning and how the subject is resolved: references/for-of-warn.md.

The eight trap checks are one script with a verdict. Routing SSOT: theonekit-core/.claude/modules/t1k-orchestration/rules/orchestration-rules.md § “Task-Type → Agent Routing”.

StepAgent
Run source-scan-guard.cjs --all (or --changed) and label each hit by trap idt1k-list-classifier
Fix a hit (split a Component file, break a cycle, move a cc import out of domain)t1k-cocos-base-developer — reasoning tier
  1. --all walks assets/, tests/ and src/, skipping every dot-prefixed segment, node_modules, library, temp and build. A dot-prefixed directory under assets/ (.tests/) is invisible to the Cocos asset-db and is therefore the sanctioned in-module test location — but --all skips it too, so it is never scanned at all, not merely unreported (measured: FlopHousePLA --all read 1,077 of 1,358 .ts files; 281 were never looked at). The same dot filter is the reason a --changed scan after a kit update does not read .claude/ as project source.

  2. A bare this._byId is only flagged when the same file declared it a Set/Map. A field on a base class is not guessed at — a guard that guesses produces false positives and gets disabled. A call on the value itself (.values() / .keys() / .entries()) and new Set() / new Map() are unambiguous and always flagged. Object.keys / .values / .entries are not flagged: Object.values(o) is an array, and flagging the three siblings that do return iterators would need per-callee reasoning the AST walk does not do — the ESLint selector in rules/code-conventions-cocos.md is the check that covers them. Known gap, by the same no-guessing rule: [...arr.keys()] on a receiver whose declared type is a Map/Set alias this file cannot see (an imported type, a signature declared elsewhere) is also not flagged — there is no type checker here (see “Target detection”), so an unresolvable receiver always answers “not provably a collection” rather than being guessed at either way.

  3. import type / export type — including the per-specifier inline form (import { type X }, export { type X } from './x') — are excluded from the import graph, because they are erased at compile time and cannot close a runtime cycle. That is the documented fix for a real cycle, so flagging it would flag the remedy. A mixed clause (import { type X, Y }) still counts: only the names that are individually type are erased, so Y still closes a cycle or trips engine-import-in-domain on its own.

  4. Comments, string bodies, template literals and regex literals are never matched as code — and no masking pass is needed to achieve it, because matching walks the AST the parser already produced. A fix site that quotes the broken form in a comment (// was [...x.values()]) is a comment node, not an expression, so it cannot report itself.

  5. Parsing is the TypeScript compiler API, not a tokenising regex. The earlier regex/mask design produced a class of false positives (nested template literals, a regex after )) that a real parser removes structurally; the typescript@5.9.3 pin in scripts/package.json is what buys that, and it is a genuine runtime dependency, not an optional convenience (see “Target detection” above and gotcha 12 — a missing pin is exit 2).

  6. A check that should be silent is still worth an antipode test. iterators-es2017 is the same source as iterators-red with a moved target; without it, a broken detector looks identical to a correct one on the green fixture.

  7. multiple-ccclass under-reports a base class imported from another file. class Hud extends BaseView where BaseView lives elsewhere is not resolved, so two such components in one file are missed. Deliberate: the same no-guessing call as gotcha 2 — a wrong ERROR here disables the check.

  8. Cocos tsconfig.json is JSONC, and a bare JSON.parse fails on it silently. The stock file ships /* Base configuration. Do not edit this field. */, so JSON.parse would throw and a reader that swallowed it would fall back to es5 — reporting es5-mode es2020-syntax findings on every correctly-written es2017 project, and looking like it worked. Both files are parsed as JSONC (parseJsonc), so this is handled; assert the parsed target anyway, not merely that the scan produced findings. temp/ is gitignored, so on a fresh clone the root tsconfig.json’s own target is the only declaration on disk.

  9. Findings sort ERROR-first. On the real TilePopReady corpus, path-ordered findings put both blocking ERRORs at positions 97-98 of 126, behind 96 warnings of an advisory check — invisible in any log tail. If you add a check, do not assume insertion order survives to output.

  10. A cycle is an ERROR only when the cycle itself carries an in-cycle @property(X) (or @property([X])); otherwise a WARN (layering smell, not a build break). Count findings by severity, never by the shared circular-value-import id alone; the reported chain follows real import edges. Detail: references/hard-rules-10-14.md § 10.

  11. --assume-native-iteration opts out of the iterator check (silences the spread ERROR and the for...of WARN for the whole scan) — use it only on evidence the emitted bundle keeps real iterators.

  12. Exit 2 is the “I could not tell you” code — never read it as a pass (compiler API unresolvable, --changed outside a git tree/no commits, unknown or valueless flag, --files none readable, any uncaught error). --changed with nothing to scan deliberately exits 0 — do not “fix” it into an exit 2. Detail: references/hard-rules-10-14.md § 12.

  13. --changed scans untracked files too (git ls-files --others -z --exclude-standard, -z on BOTH listings, split on \0); any git call failing inside --changed is exit 2, never a truthful-looking empty pass. Detail: references/hard-rules-10-14.md § 13.

  14. Known gap, not implemented: statically detecting a .scene/.prefab that silently drops component fields on next save (unresolvable __type__ cid; serialized keys the class no longer declares as @property). Recorded as this scanner’s natural home; mechanisms in references/hard-rules-10-14.md § 14.

  • rules/code-conventions-cocos.md § “Release build ≠ editor preview” — the rule this guard enforces.
  • t1k-cocos-base-clean-architecture — the layer rules check 4 enforces.
  • t1k-cocos-base-tsc-validate — the type-level gate; it cannot see any of these eight.