vomebook commited on
Commit
7db25c2
·
1 Parent(s): 0b623b1

Apply a separate reviewed budget to JS program decisions

Browse files
package.json CHANGED
@@ -21,7 +21,7 @@
21
  "lint": "eslint static scripts tests --max-warnings 0",
22
  "markup": "node scripts/check_markup.mjs",
23
  "types": "tsc --project config/types/jsconfig.check.json && tsc --project config/types/jsconfig.service-worker.json && tsc --project config/types/jsconfig.service-worker-strict.json && tsc --project config/types/jsconfig.chapter-worker-strict.json && tsc --project config/types/jsconfig.strict.json && tsc --project config/types/jsconfig.search-exact.json && tsc --project config/types/jsconfig.reader-exact.json && tsc --project config/types/jsconfig.window-page-tests.json",
24
- "check:static": "npm run lint && npm run markup && npm run types && python3 -B scripts/check_strict_inventory.py && python3 -B scripts/check_complexity.py --scope site"
25
  },
26
  "_overrideNote": "Pin the patched minimatch version within ESLint's supported range; rerun checker regressions when updating ESLint.",
27
  "overrides": { "minimatch": "11.0.9" },
 
21
  "lint": "eslint static scripts tests --max-warnings 0",
22
  "markup": "node scripts/check_markup.mjs",
23
  "types": "tsc --project config/types/jsconfig.check.json && tsc --project config/types/jsconfig.service-worker.json && tsc --project config/types/jsconfig.service-worker-strict.json && tsc --project config/types/jsconfig.chapter-worker-strict.json && tsc --project config/types/jsconfig.strict.json && tsc --project config/types/jsconfig.search-exact.json && tsc --project config/types/jsconfig.reader-exact.json && tsc --project config/types/jsconfig.window-page-tests.json",
24
+ "check:static": "npm run lint && npm run markup && npm run types && python3 -B scripts/check_strict_inventory.py && python3 -B quality/check_complexity_v2.py --scope site"
25
  },
26
  "_overrideNote": "Pin the patched minimatch version within ESLint's supported range; rerun checker regressions when updating ESLint.",
27
  "overrides": { "minimatch": "11.0.9" },
quality/check_complexity_v2.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Keep v1 ceilings and audit the separately reviewed JS program budget."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ from collections import Counter
6
+ from dataclasses import astuple
7
+ from hashlib import sha256
8
+ import json
9
+ from pathlib import Path
10
+ import re
11
+ import subprocess
12
+ import sys
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+ sys.path.insert(0, str(ROOT / "scripts"))
16
+ import check_complexity as v1 # noqa: E402
17
+
18
+ SCOPES = ("frontend", "site")
19
+ WRAPPER = "quality/eslint.complexity.config.mjs"
20
+ PROGRAM_RULE = "book-complexity/program"
21
+ PROGRAM_MESSAGE = re.compile(r"Program complexity: ([1-9][0-9]*)\.")
22
+ METRIC = "js-program-classic"
23
+
24
+
25
+ def lint(root, files):
26
+ paths = [path.relative_to(root).as_posix() for path in files]
27
+ if not paths or len(paths) != len(set(paths)):
28
+ raise ValueError("Empty or duplicate JS input inventory")
29
+ command = ["node", "node_modules/eslint/bin/eslint.js", "--no-inline-config", "--no-ignore", "--format", "json",
30
+ "--rule", 'complexity:["error",1]', "--config", WRAPPER, "--", *paths]
31
+ run = subprocess.run(command, cwd=root, text=True, capture_output=True, check=False) # noqa: S603
32
+ if run.returncode not in {0, 1} or not run.stdout:
33
+ raise ValueError(f"ESLint could not measure JavaScript: {run.stderr.strip()}")
34
+ return read_results(root, set(paths), json.loads(run.stdout))
35
+
36
+
37
+ def read_results(root, expected, items):
38
+ regions, programs = [], {}
39
+ for item in items:
40
+ path = Path(item["filePath"]).relative_to(root).as_posix()
41
+ if path not in expected or path in programs:
42
+ raise ValueError(f"Unexpected or duplicate ESLint file result: {path}")
43
+ programs[path] = read_messages(path, item["messages"], regions)
44
+ if missing := expected - programs.keys():
45
+ raise ValueError(f"Missing ESLint file results: {sorted(missing)}")
46
+ return regions, programs
47
+
48
+
49
+ def read_messages(path, messages, regions):
50
+ program = None
51
+ for msg in messages:
52
+ rule, text = msg["ruleId"], msg["message"]
53
+ if msg.get("fatal") or rule is None:
54
+ raise ValueError(f"ESLint could not score {path}:{msg.get('line', '?')}: {text}")
55
+ if rule == PROGRAM_RULE:
56
+ if program is not None:
57
+ raise ValueError(f"Duplicate program score: {path}")
58
+ match = PROGRAM_MESSAGE.fullmatch(text)
59
+ if not match or (msg.get("messageId"), msg.get("line"), msg.get("column")) != ("score", 1, 1):
60
+ raise ValueError(f"Malformed program score: {path}: {text}")
61
+ program = int(match[1]) - 1
62
+ elif rule == "complexity":
63
+ match = v1.COMPLEXITY_MESSAGE.fullmatch(text)
64
+ if not match or int(match[2]) <= 1:
65
+ raise ValueError(f"Malformed v1 region score: {path}: {text}")
66
+ regions.append(v1.Score(path, match[1], msg["line"], int(match[2])))
67
+ if program is None:
68
+ raise ValueError(f"Missing program score: {path}")
69
+ return program
70
+
71
+
72
+ def digest(records):
73
+ payload = json.dumps(sorted(records), separators=(",", ":"), ensure_ascii=True)
74
+ return sha256(payload.encode("ascii")).hexdigest()
75
+
76
+
77
+ def verify_v1(root, py, js, python, regions):
78
+ # Compare v1's complete fact multiset, not just totals or hotspot maxima.
79
+ reference = Counter([*v1.python_scores(root, py), *v1.js_scores(root, js)])
80
+ wrapped = Counter([*python, *regions])
81
+ if reference != wrapped:
82
+ raise ValueError(f"v1 region mismatch: missing {list((reference - wrapped).items())[:5]}; "
83
+ f"added {list((wrapped - reference).items())[:5]}")
84
+ return digest(astuple(fact) for fact in reference.elements())
85
+
86
+
87
+ def program_snapshot(programs, scope):
88
+ return {"version": 2, "scope": scope, "metric": METRIC, "branches": sum(programs.values()),
89
+ "files": {path: n for path, n in sorted(programs.items()) if n > 0}}
90
+
91
+
92
+ def program_regressions(old, new):
93
+ if new["branches"] > old["branches"]:
94
+ yield f"Program decisions {new['branches']} > {old['branches']}"
95
+ for path, actual in new["files"].items():
96
+ cap = old["files"].get(path, 0)
97
+ if actual > cap:
98
+ yield f"{path}: program decisions {actual} > {cap}"
99
+
100
+
101
+ def unique_object(pairs):
102
+ result = {}
103
+ for key, value in pairs:
104
+ if key in result:
105
+ raise ValueError(f"Duplicate budget key: {key}")
106
+ result[key] = value
107
+ return result
108
+
109
+
110
+ def integer(value, minimum=0):
111
+ return type(value) is int and value >= minimum
112
+
113
+
114
+ def read_budget(path, scope, version):
115
+ data = json.loads(path.read_bytes(), object_pairs_hook=unique_object)
116
+ identity = {"version": version, "scope": scope}
117
+ identity.update({"limit": v1.LIMIT} if version == 1 else {"metric": METRIC})
118
+ if (not isinstance(data, dict) or data.keys() != identity.keys() | {"branches", "files"}
119
+ or any(type(data[k]) is not type(v) or data[k] != v for k, v in identity.items())
120
+ or not integer(data["branches"]) or not isinstance(data["files"], dict)):
121
+ raise ValueError(f"Invalid v{version} budget schema, scope or metric: {path}")
122
+ if version == 1:
123
+ for counts in data["files"].values():
124
+ if not (isinstance(counts, dict) and counts.keys() == {"peak", "excess"}
125
+ and integer(counts["peak"], v1.LIMIT + 1) and integer(counts["excess"], counts["peak"] - v1.LIMIT)):
126
+ raise ValueError(f"Invalid v1 file caps: {path}")
127
+ else:
128
+ caps = data["files"].values()
129
+ if not all(integer(n, 1) for n in caps) or data["branches"] > sum(caps):
130
+ raise ValueError(f"Invalid program file or total caps: {path}")
131
+ return data
132
+
133
+
134
+ def budget_pair(candidate, trusted, scope, version):
135
+ old = read_budget(candidate, scope, version)
136
+ base = read_budget(trusted, scope, version)
137
+ if candidate.samefile(trusted):
138
+ raise ValueError(f"Use an independent trusted v{version} budget, not the checked-in file itself")
139
+ return old, base
140
+
141
+
142
+ def read_caps(root, args):
143
+ old_v1 = read_budget(root / args.budget, args.scope, 1)
144
+ old_program = read_budget(root / args.program_budget, args.scope, 2)
145
+ if args.base_budget:
146
+ _, base_v1 = budget_pair(root / args.budget, args.base_budget, args.scope, 1)
147
+ reject("Checked-in v1 budget raises trusted caps", v1.regressions(base_v1, old_v1))
148
+ if args.base_program_budget:
149
+ _, base_program = budget_pair(root / args.program_budget, args.base_program_budget, args.scope, 2)
150
+ reject("Checked-in program budget raises trusted caps", program_regressions(base_program, old_program))
151
+ return old_v1, old_program
152
+
153
+
154
+ def reject(label, problems):
155
+ if messages := list(problems):
156
+ raise ValueError(label + ":\n" + "\n".join(messages))
157
+
158
+
159
+ def report(root, py, js, python, regions, legacy, programs, program, reference_digest):
160
+ ranked = sorted(programs.items(), key=lambda item: (-item[1], item[0]))
161
+ overs = [{"path": path, "score": n + 1, "excess": n + 1 - v1.LIMIT}
162
+ for path, n in ranked if n + 1 > v1.LIMIT]
163
+ return {
164
+ "scope": legacy["scope"],
165
+ "inventory": {"python": len(py), "javascript": len(js)},
166
+ "owned_source_bytes_sha256": digest((p.relative_to(root).as_posix(), sha256(p.read_bytes()).hexdigest())
167
+ for p in [*py, *js]),
168
+ "v1_parity_verified": reference_digest is not None,
169
+ "v1_reference_facts_sha256": reference_digest,
170
+ "v1_facts_sha256": digest(astuple(fact) for fact in [*python, *regions]),
171
+ "v1_python_facts": len(python),
172
+ "v1_js_reported_facts": len(regions),
173
+ "v1_python_decisions": sum(fact.complexity - 1 for fact in python),
174
+ "v1_js_region_decisions": sum(fact.complexity - 1 for fact in regions),
175
+ "v1_snapshot": legacy,
176
+ "program_facts_sha256": digest(programs.items()),
177
+ "program_decisions_by_path": dict(sorted(programs.items())),
178
+ "program_debt": {"nonzero_files": len(program["files"]), "peak_score": ranked[0][1] + 1,
179
+ "over_limit_files": overs, "total_excess": sum(item["excess"] for item in overs)},
180
+ "combined_decisions_informational": legacy["branches"] + program["branches"],
181
+ "program_budget_proposal": program,
182
+ }
183
+
184
+
185
+ def arguments(argv):
186
+ parser = argparse.ArgumentParser(description=__doc__)
187
+ parser.add_argument("--scope", choices=SCOPES, required=True)
188
+ parser.add_argument("--mode", choices=("report", "check"), default="check")
189
+ parser.add_argument("--verify-v1", action="store_true", help="Compare every v1 fact with a separate original run")
190
+ parser.add_argument("--budget", type=Path, default=v1.BUDGET, help="Existing v1 budget")
191
+ parser.add_argument("--base-budget", type=Path, help="Independent trusted v1 budget")
192
+ parser.add_argument("--program-budget", type=Path, default=Path("quality/js-program-budget.json"),
193
+ help="Reviewed JS program budget")
194
+ parser.add_argument("--base-program-budget", type=Path, help="Independent trusted JS program budget")
195
+ return parser.parse_args(argv)
196
+
197
+
198
+ def main(argv=None):
199
+ args = arguments(argv)
200
+ try:
201
+ caps = read_caps(ROOT, args) if args.mode == "check" else None
202
+ py, js = v1.inventory(ROOT, args.scope)
203
+ python = list(v1.python_scores(ROOT, py))
204
+ regions, programs = lint(ROOT, js)
205
+ reference_digest = verify_v1(ROOT, py, js, python, regions) if args.verify_v1 else None
206
+ legacy = v1.snapshot([*python, *regions], args.scope)
207
+ program = program_snapshot(programs, args.scope)
208
+ if caps is not None:
209
+ reject("v1 complexity regressions", v1.regressions(caps[0], legacy))
210
+ reject("JS program complexity regressions", program_regressions(caps[1], program))
211
+ print(f"v1: {legacy['branches']} decisions; JS program: {program['branches']} decisions in {len(programs)} files")
212
+ else:
213
+ print(json.dumps(report(ROOT, py, js, python, regions, legacy, programs, program, reference_digest), indent=2))
214
+ except (OSError, ValueError, SyntaxError, KeyError, TypeError) as error:
215
+ print(error, file=sys.stderr)
216
+ return 1
217
+ return 0
218
+
219
+
220
+ if __name__ == "__main__":
221
+ raise SystemExit(main())
quality/eslint.complexity.config.mjs ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { createRequire } from "node:module";
2
+ import lintConfig from "../eslint.config.mjs";
3
+ import { programComplexityRule } from "./program-complexity.mjs";
4
+
5
+ const localRequire = createRequire(import.meta.url);
6
+ const eslintPackage = localRequire.resolve("eslint/package.json");
7
+ const eslintRequire = createRequire(eslintPackage);
8
+ for (const [name, actual, expected] of [
9
+ ["ESLint", localRequire(eslintPackage).version, "10.15.0"],
10
+ ["Espree (from ESLint)", eslintRequire("espree/package.json").version, "11.2.0"],
11
+ ]) {
12
+ if (actual !== expected) throw new Error(`${name}: expected ${expected}, got ${actual}; review rule parity before updating`);
13
+ }
14
+
15
+ // Keep the repository's complete flat config. The checker passes the same
16
+ // CLI flags and built-in complexity rule as v1, and adds only this rule.
17
+ export default [
18
+ ...lintConfig,
19
+ {
20
+ plugins: { "book-complexity": { rules: { program: programComplexityRule } } },
21
+ rules: { "book-complexity/program": "error" },
22
+ },
23
+ ];
quality/js-program-budget.json ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": 2,
3
+ "scope": "site",
4
+ "metric": "js-program-classic",
5
+ "branches": 701,
6
+ "files": {
7
+ "scripts/build/build_static_assets.mjs": 13,
8
+ "scripts/build/check_reader_release.mjs": 11,
9
+ "scripts/build/compile_static_assets.mjs": 9,
10
+ "scripts/build/compose_app.mjs": 2,
11
+ "scripts/build/copy_reader_vendor.mjs": 7,
12
+ "scripts/check_markup.mjs": 3,
13
+ "scripts/data/fetch_search_generation.mjs": 5,
14
+ "scripts/data/prepare_test_data.mjs": 3,
15
+ "scripts/reader/check_adapter_coverage.mjs": 15,
16
+ "scripts/reader/check_chapter_search_core_coverage.mjs": 10,
17
+ "scripts/reader/check_chapter_search_index_coverage.mjs": 10,
18
+ "scripts/reader/check_chapter_search_proxy_coverage.mjs": 10,
19
+ "scripts/reader/check_chapter_search_worker_coverage.mjs": 10,
20
+ "scripts/reader/check_document_loader_coverage.mjs": 9,
21
+ "scripts/reader/check_pdf_book_client_coverage.mjs": 11,
22
+ "scripts/reader/check_pdf_book_compact_coverage.mjs": 11,
23
+ "scripts/reader/check_pdf_book_url_coverage.mjs": 11,
24
+ "scripts/reader/check_pdf_book_validate_coverage.mjs": 11,
25
+ "scripts/reader/check_pdf_network_coverage.mjs": 21,
26
+ "scripts/reader/check_pdf_network_mutations.mjs": 21,
27
+ "scripts/reader/check_pdf_partition_config_coverage.mjs": 11,
28
+ "scripts/reader/check_pdf_partition_page_coverage.mjs": 11,
29
+ "scripts/reader/check_pdf_partition_policy_coverage.mjs": 11,
30
+ "scripts/reader/check_pdf_partition_requests_coverage.mjs": 11,
31
+ "scripts/reader/check_pdf_partition_shape_coverage.mjs": 11,
32
+ "scripts/reader/check_pdf_prefetch_contracts.mjs": 8,
33
+ "scripts/reader/check_pdf_search_decode_coverage.mjs": 11,
34
+ "scripts/reader/check_pdf_search_stream_coverage.mjs": 11,
35
+ "scripts/reader/check_pdf_text_store_coverage.mjs": 10,
36
+ "scripts/reader/check_pdf_text_store_mutations.mjs": 21,
37
+ "scripts/reader/check_reader_core_coverage.mjs": 21,
38
+ "scripts/reader/check_reader_djvu_contracts.mjs": 89,
39
+ "scripts/reader/check_reader_image_loader_coverage.mjs": 8,
40
+ "scripts/reader/check_reader_lifecycle_coverage.mjs": 10,
41
+ "scripts/reader/check_reader_media_coverage.mjs": 13,
42
+ "scripts/reader/check_reader_text_coverage.mjs": 10,
43
+ "scripts/reader/check_reader_v3_coverage.mjs": 11,
44
+ "scripts/reader/check_reader_v3_mutations.mjs": 22,
45
+ "scripts/reader/check_request_manager_coverage.mjs": 9,
46
+ "scripts/search/check_download_controller_coverage.mjs": 8,
47
+ "scripts/search/check_reader_navigation_baseline.mjs": 8,
48
+ "scripts/search/check_search_file_types_coverage.mjs": 8,
49
+ "scripts/search/check_search_filter_equality_baseline.mjs": 6,
50
+ "scripts/search/check_search_folder_merge_baseline.mjs": 6,
51
+ "scripts/search/check_search_folder_selection_coverage.mjs": 7,
52
+ "scripts/search/check_search_height_index_coverage.mjs": 7,
53
+ "scripts/search/check_search_highlight_coverage.mjs": 9,
54
+ "scripts/search/check_search_readability_baseline.mjs": 6,
55
+ "scripts/search/check_search_record_path_coverage.mjs": 7,
56
+ "scripts/search/check_search_recovery_coverage.mjs": 7,
57
+ "scripts/search/check_search_response_cache_coverage.mjs": 10,
58
+ "scripts/search/check_search_response_validation_coverage.mjs": 7,
59
+ "scripts/search/check_search_result_identity_coverage.mjs": 7,
60
+ "scripts/search/check_search_size_coverage.mjs": 7,
61
+ "scripts/search/check_search_stable_stringify_coverage.mjs": 7,
62
+ "scripts/search/check_search_view_key_coverage.mjs": 7,
63
+ "scripts/search/check_search_window_page_coverage.mjs": 7,
64
+ "scripts/search/check_sidebar_markup_coverage.mjs": 7,
65
+ "static/reader-resources.js": 1,
66
+ "static/reader.js": 24,
67
+ "static/reader/core/reader-contract.js": 1,
68
+ "static/reader/core/reader-request-manager.js": 1,
69
+ "static/reader/core/reader-runtime.js": 1,
70
+ "static/reader/core/reader-security.js": 1,
71
+ "static/reader/core/reader-store.js": 1,
72
+ "static/reader/formats/reader-chapter-repository.js": 1,
73
+ "static/reader/formats/reader-format-adapters.js": 1,
74
+ "static/reader/formats/reader-section-virtualizer.js": 1,
75
+ "static/reader/pdf/pdf-worker-wrapper.mjs": 4,
76
+ "static/reader/search/workers/reader-chapter-search-worker.mjs": 2,
77
+ "static/reader/ui/reader-scroll-anchor.js": 1,
78
+ "static/search/downloads/application/controller.js": 1,
79
+ "static/search/execution/application/session.js": 1,
80
+ "static/search/reader-host/application/navigation.js": 1,
81
+ "static/sw.js": 7,
82
+ "static/tts-client.js": 1
83
+ }
84
+ }
quality/program-complexity.mjs ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const LOGICAL_ASSIGNMENTS = new Set(["&&=", "||=", "??="]);
2
+
3
+ // Match the classic listeners in ESLint 10.15.0. Follow ESLint's actual code
4
+ // paths rather than treating whole classes (including keys/heritage) as scopes.
5
+ export const programComplexityRule = {
6
+ meta: { schema: [], messages: { score: "Program complexity: {{score}}." } },
7
+ create(context) {
8
+ const origins = [];
9
+ let score = 1;
10
+ const decision = () => {
11
+ if (origins.at(-1) === "program") score++;
12
+ };
13
+ const optional = node => {
14
+ if (node.optional === true) decision();
15
+ };
16
+ return {
17
+ onCodePathStart(codePath) {
18
+ origins.push(codePath.origin);
19
+ },
20
+ onCodePathEnd(codePath, node) {
21
+ origins.pop();
22
+ if (codePath.origin === "program") {
23
+ context.report({ node, loc: { line: 1, column: 0 }, messageId: "score", data: { score } });
24
+ }
25
+ },
26
+ CatchClause: decision,
27
+ ConditionalExpression: decision,
28
+ LogicalExpression: decision,
29
+ ForStatement: decision,
30
+ ForInStatement: decision,
31
+ ForOfStatement: decision,
32
+ IfStatement: decision,
33
+ WhileStatement: decision,
34
+ DoWhileStatement: decision,
35
+ AssignmentPattern: decision,
36
+ "SwitchCase[test]": decision,
37
+ AssignmentExpression(node) {
38
+ if (LOGICAL_ASSIGNMENTS.has(node.operator)) decision();
39
+ },
40
+ MemberExpression: optional,
41
+ CallExpression: optional,
42
+ };
43
+ },
44
+ };
scripts/complexity-policy.md CHANGED
@@ -3,7 +3,7 @@
3
  The goal is fewer decisions and less dead code, not smaller functions at any cost.
4
 
5
  - Measure owned source under `static/` and `scripts/`; Space additionally measures `backend/` and `app.py`. Pipeline v1 measures Python in `scripts/`. Tests, vendored code, types, assets, generated output, Pipeline's standalone JS tool, and Space's native C extension are not measured by v1. They retain their separate checks. Do not move source outside this inventory to avoid the budget.
6
- - JavaScript uses the project's lockfile-pinned ESLint `complexity` rule, with inline directives disabled. It measures function and class execution regions, not outer script/module statements. Python uses an AST decision count: branches, loop headers, `except`, assertions, Boolean short circuits, comprehensions, and non-default `match` arms. Module, class, function and lambda bodies are separate regions. These are static counts, not coverage or runtime cost; the two language scores are not directly comparable.
7
  - Each file has a default peak of **12**. Existing files over 12 have grandfathered caps on both the peak and the sum of points above 12. The repository also caps the total number of decisions (scores minus each region's base point). Moving branches into helpers does not earn a reduction in that total.
8
- - Read hotspots with `python3 -B scripts/check_complexity.py --scope frontend --mode report` (use `site` in Space and `pipeline` in Pipeline). Use `--mode tighten` to lower checked-in caps after a reduction; it refuses a regression. Review baseline changes as policy changes: do not regenerate upward with `sample` to make a check green. An independent reviewer or CI can pass `--base-budget` from a trusted revision to reject edits that raise existing caps.
9
  - Tests still decide whether a change is correct. Keep site contracts, readbacks, sanitization, and rollback boundaries intact. Prove a compatibility branch has no current consumer before removing it.
 
3
  The goal is fewer decisions and less dead code, not smaller functions at any cost.
4
 
5
  - Measure owned source under `static/` and `scripts/`; Space additionally measures `backend/` and `app.py`. Pipeline v1 measures Python in `scripts/`. Tests, vendored code, types, assets, generated output, Pipeline's standalone JS tool, and Space's native C extension are not measured by v1. They retain their separate checks. Do not move source outside this inventory to avoid the budget.
6
+ - JavaScript uses the lockfile-pinned ESLint `complexity` rule with inline directives disabled. Its function and class execution regions retain the v1 budget. The same run counts outer script/module decisions separately against `quality/js-program-budget.json`; nothing is added to or removed from the v1 account. The top-level default is zero new decisions per file. Python uses an AST decision count: branches, loop headers, `except`, assertions, Boolean short circuits, comprehensions, and non-default `match` arms. Module, class, function and lambda bodies are separate regions. These are static counts, not coverage or runtime cost; the two language scores are not directly comparable.
7
  - Each file has a default peak of **12**. Existing files over 12 have grandfathered caps on both the peak and the sum of points above 12. The repository also caps the total number of decisions (scores minus each region's base point). Moving branches into helpers does not earn a reduction in that total.
8
+ - Read hotspots with `python3 -B scripts/check_complexity.py --scope frontend --mode report` (use `site` in Space and `pipeline` in Pipeline). Use `--mode tighten` to lower checked-in caps after a reduction; it refuses a regression. Review baseline changes as policy changes: do not regenerate upward with `sample` to make a check green. The static gate runs `quality/check_complexity_v2.py`. An independent reviewer or CI can pass `--base-budget` and `--base-program-budget` to it from a trusted revision to reject edits that raise existing caps. Tighten a program cap only after reviewing report mode's exact proposal. Do not transfer room between the two budgets.
9
  - Tests still decide whether a change is correct. Keep site contracts, readbacks, sanitization, and rollback boundaries intact. Prove a compatibility branch has no current consumer before removing it.