t1k:cocos:base:source-scan-guard
| Field | Value |
|---|---|
| Module | base |
| Version | 4.51.9 |
| Effort | medium |
| 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
How to invoke
Section titled “How to invoke”/t1k:cocos:base:source-scan-guardWhen to use
Section titled “When to use”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.
What it does
Section titled “What it does”scripts/source-scan-guard.cjs — cross-platform Node; its one runtime dependency is the pinned
typescript compiler API (see “Target detection”).
| Check id | Severity | Flags |
|---|---|---|
map-set-iterator-spread | ERROR | [...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-spread | WARN | for … 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-spread | WARN | for … 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-import | ERROR | a 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-import | WARN | a 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-ccclass | ERROR | more than one Component subclass per file (editor errorID 3615) |
engine-import-in-domain | ERROR | cc or db:// imported under **/domain/** |
engine-import-in-domain | WARN | the same import under **/application/** — the corpus carries legitimate pure-data db:// imports there |
es2020-syntax | WARN | ?., ??, ??= under a <= es2017 target |
es2020-syntax | ERROR | BigInt literal under a <= es2017 target — not downlevelled, tsc rejects it (TS2737) |
test-under-assets | ERROR | a test file under assets/ outside a dot-prefixed directory |
es2019-api | ERROR | .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-api | WARN | .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-true | WARN | a 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.
bun .claude/skills/t1k-cocos-base-source-scan-guard/scripts/source-scan-guard.cjs --changedbun .claude/skills/t1k-cocos-base-source-scan-guard/scripts/source-scan-guard.cjs --all --json build/source-scan.jsonFlags: --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:
| Surface | Own code | Vendored (assets/packages/**) |
|---|---|---|
counts | error / warn / total | counts.vendored.{error,warn,total} |
findings[] | every finding | every finding, each vendored: true |
| text output | full list, ERRORs uncapped | printed under a vendored (…) heading |
| verdict | decides green/red | detail.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 for…of check is a WARN
Section titled “The for…of check is a WARN”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.
Executed by
Section titled “Executed by”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”.
| Step | Agent |
|---|---|
Run source-scan-guard.cjs --all (or --changed) and label each hit by trap id | t1k-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 |
Hard rules
Section titled “Hard rules”-
--allwalksassets/,tests/andsrc/, skipping every dot-prefixed segment,node_modules,library,tempandbuild. A dot-prefixed directory underassets/(.tests/) is invisible to the Cocos asset-db and is therefore the sanctioned in-module test location — but--allskips it too, so it is never scanned at all, not merely unreported (measured: FlopHousePLA--allread 1,077 of 1,358.tsfiles; 281 were never looked at). The same dot filter is the reason a--changedscan after a kit update does not read.claude/as project source. -
A bare
this._byIdis only flagged when the same file declared it aSet/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()) andnew Set()/new Map()are unambiguous and always flagged.Object.keys/.values/.entriesare 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 inrules/code-conventions-cocos.mdis 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. -
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 individuallytypeare erased, soYstill closes a cycle or tripsengine-import-in-domainon its own. -
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. -
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; thetypescript@5.9.3pin inscripts/package.jsonis 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). -
A check that should be silent is still worth an antipode test.
iterators-es2017is the same source asiterators-redwith a moved target; without it, a broken detector looks identical to a correct one on the green fixture. -
multiple-ccclassunder-reports a base class imported from another file.class Hud extends BaseViewwhereBaseViewlives 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. -
Cocos
tsconfig.jsonis JSONC, and a bareJSON.parsefails on it silently. The stock file ships/* Base configuration. Do not edit this field. */, soJSON.parsewould throw and a reader that swallowed it would fall back toes5— reporting es5-modees2020-syntaxfindings 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 roottsconfig.json’s owntargetis the only declaration on disk. -
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.
-
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 sharedcircular-value-importid alone; the reported chain follows real import edges. Detail:references/hard-rules-10-14.md§ 10. -
--assume-native-iterationopts out of the iterator check (silences the spread ERROR and thefor...ofWARN for the whole scan) — use it only on evidence the emitted bundle keeps real iterators. -
Exit 2 is the “I could not tell you” code — never read it as a pass (compiler API unresolvable,
--changedoutside a git tree/no commits, unknown or valueless flag,--filesnone readable, any uncaught error).--changedwith nothing to scan deliberately exits 0 — do not “fix” it into an exit 2. Detail:references/hard-rules-10-14.md§ 12. -
--changedscans untracked files too (git ls-files --others -z --exclude-standard,-zon BOTH listings, split on\0); any git call failing inside--changedis exit 2, never a truthful-looking empty pass. Detail:references/hard-rules-10-14.md§ 13. -
Known gap, not implemented: statically detecting a
.scene/.prefabthat 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 inreferences/hard-rules-10-14.md§ 14.
See also
Section titled “See also”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.