@mizchi/vlmkit-core 0.9.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/apng.d.mts +42 -0
  2. package/dist/apng.mjs +199 -0
  3. package/dist/auth-state.d.mts +14 -3
  4. package/dist/auth-state.mjs +30 -6
  5. package/dist/bitmap-font.d.mts +48 -0
  6. package/dist/bitmap-font.mjs +945 -0
  7. package/dist/browser-launch.d.mts +65 -0
  8. package/dist/browser-launch.mjs +194 -0
  9. package/dist/cli-error.d.mts +73 -1
  10. package/dist/cli-error.mjs +164 -32
  11. package/dist/element-compare.mjs +8 -11
  12. package/dist/filmstrip.d.mts +121 -0
  13. package/dist/filmstrip.mjs +181 -0
  14. package/dist/gate-config.d.mts +107 -22
  15. package/dist/gate-config.mjs +138 -9
  16. package/dist/heatmap.d.mts +48 -4
  17. package/dist/heatmap.mjs +157 -12
  18. package/dist/index.d.mts +6 -4
  19. package/dist/index.mjs +4 -2
  20. package/dist/mask.d.mts +66 -2
  21. package/dist/mask.mjs +91 -4
  22. package/dist/page-load.d.mts +83 -0
  23. package/dist/page-load.mjs +116 -0
  24. package/dist/page-open.d.mts +123 -2
  25. package/dist/page-open.mjs +176 -6
  26. package/dist/plugin/args.d.mts +86 -0
  27. package/dist/plugin/args.mjs +162 -0
  28. package/dist/plugin/browser.d.mts +6 -0
  29. package/dist/plugin/browser.mjs +6 -0
  30. package/dist/plugin/cli-entry.d.mts +11 -0
  31. package/dist/plugin/cli-entry.mjs +69 -0
  32. package/dist/plugin/contract.d.mts +270 -0
  33. package/dist/plugin/contract.mjs +51 -0
  34. package/dist/plugin/index.d.mts +82 -0
  35. package/dist/plugin/index.mjs +81 -0
  36. package/dist/plugin/load.d.mts +36 -0
  37. package/dist/plugin/load.mjs +98 -0
  38. package/dist/plugin/registry.d.mts +60 -0
  39. package/dist/plugin/registry.mjs +160 -0
  40. package/dist/plugin/rule-tier.d.mts +65 -0
  41. package/dist/plugin/rule-tier.mjs +77 -0
  42. package/dist/plugin/rules.d.mts +112 -0
  43. package/dist/plugin/rules.mjs +188 -0
  44. package/dist/plugin/runner.d.mts +198 -0
  45. package/dist/plugin/runner.mjs +440 -0
  46. package/dist/png-utils.d.mts +31 -1
  47. package/dist/png-utils.mjs +24 -1
  48. package/dist/rect-overlap.d.mts +41 -0
  49. package/dist/rect-overlap.mjs +28 -0
  50. package/dist/run-ledger.d.mts +56 -2
  51. package/dist/run-ledger.mjs +102 -11
  52. package/dist/types.d.mts +60 -1
  53. package/dist/version.d.mts +20 -0
  54. package/dist/version.mjs +20 -0
  55. package/dist/webp.d.mts +31 -0
  56. package/dist/webp.mjs +105 -0
  57. package/package.json +17 -3
@@ -0,0 +1,198 @@
1
+ import { LedgerWrite } from "../run-ledger.mjs";
2
+ import { AnyGateDefinition, Finding, GateDefinition } from "./contract.mjs";
3
+ import { AppliedRules, FindingCounts, RuleSettings } from "./rules.mjs";
4
+
5
+ //#region src/plugin/runner.d.ts
6
+ /** Flags the runner owns. A gate's `parse` never sees these as its own. */
7
+ declare const SHARED_GATE_FLAGS: readonly ["--json", "--advisory", "--fail-on-suspect", "--rule", "--rules", "--timing", "--ledger", "--no-ledger", "--help", "-h"];
8
+ interface SharedFlags {
9
+ json: boolean;
10
+ advisory: boolean;
11
+ help: boolean;
12
+ /** `--rules`: print the gate's rule table and exit without measuring. */
13
+ listRules: boolean;
14
+ /** `--rule <ref>=<setting>`, repeatable — a one-off override for this run. */
15
+ ruleOverrides: RuleSettings;
16
+ /**
17
+ * `--timing`: include the per-phase breakdown in the output.
18
+ *
19
+ * Opt-in rather than always-on because the numbers differ every run, and
20
+ * `--json` is a contract other tools diff and cache against.
21
+ */
22
+ timing: boolean;
23
+ /**
24
+ * `--ledger <path>`: where the append-only run record goes. It defaulted to
25
+ * `.vlmkit/run-ledger.jsonl` with no flag at all and nothing announcing it,
26
+ * so the only ways to find it were `ls` and reading the source — which is how
27
+ * v6's adopting agent found it.
28
+ */
29
+ ledgerPath?: string;
30
+ /** `--no-ledger`: the flag form of VLMKIT_NO_LEDGER=1. */
31
+ noLedger: boolean;
32
+ }
33
+ /**
34
+ * Read the shared flags. `--fail-on-suspect` is still accepted and still
35
+ * does nothing: it was the documented way to opt *into* failing before
36
+ * failing became the default, and scripts in the wild still pass it.
37
+ */
38
+ declare function parseSharedFlags(argv: readonly string[]): SharedFlags;
39
+ /** Drop the runner-owned flags so a gate's parser never has to know them. */
40
+ declare function stripSharedFlags(argv: readonly string[]): string[];
41
+ /**
42
+ * Wall-clock ms per contract phase.
43
+ *
44
+ * The split exists to answer "where does a gate's time actually go", and the
45
+ * answer shapes how a ruleset should be tuned. `run` is one measurement shared
46
+ * by every rule the gate declares; `findings` is the only phase where per-rule
47
+ * work happens, and it is a projection over an in-memory report. So the cost
48
+ * unit is the **gate**, not the rule — which is exactly why `--rule x=off`
49
+ * cannot make a run faster, and why `vlmkit bench gates` reports *attributed*
50
+ * per-rule cost rather than pretending each rule was timed on its own.
51
+ *
52
+ * Always collected: five `performance.now()` reads are far below the noise
53
+ * floor of a browser launch. Reported only when asked, because a timing field
54
+ * is nondeterministic and `--json` has to stay byte-stable for equal inputs.
55
+ */
56
+ interface GateTiming {
57
+ parseMs: number;
58
+ runMs: number;
59
+ /** `gate.findings` — the projection. Per-rule work lives here. */
60
+ findingsMs: number;
61
+ /** `applyRuleSettings` — suppression and re-tuning. */
62
+ rulesMs: number;
63
+ /** `gate.format`, or the JSON serialization when `--json` is set. */
64
+ formatMs: number;
65
+ ledgerMs: number;
66
+ /** Everything above plus the runner's own overhead. */
67
+ totalMs: number;
68
+ }
69
+ interface GateOutcome<Report = unknown> {
70
+ gateId: string;
71
+ command: string;
72
+ /** `fail` when a suspect survived rule settings; `--advisory` does not change it. */
73
+ verdict: "pass" | "fail";
74
+ report: Report;
75
+ findings: readonly Finding[];
76
+ counts: FindingCounts;
77
+ rules: AppliedRules;
78
+ /** Exit code the caller should adopt — `--advisory` is applied here. */
79
+ exitCode: 0 | 1;
80
+ /** Rendered output (prose or JSON), ready to write. */
81
+ text: string;
82
+ timing: GateTiming;
83
+ /**
84
+ * The run-ledger append, or `null` when the ledger is off or the gate declares
85
+ * none. Surfaced so the CLI can announce a file it just brought into existence
86
+ * instead of leaving it to be found with `ls`.
87
+ */
88
+ ledgerWrite: LedgerWrite | null;
89
+ }
90
+ interface RunGateOptions {
91
+ cwd?: string;
92
+ /** Project-level rule settings; `--rule` overrides win over these. */
93
+ rules?: RuleSettings;
94
+ /** Set false to skip the ledger append (batch runs, tests). */
95
+ ledger?: boolean;
96
+ }
97
+ /**
98
+ * Run one gate end to end and return what happened. Deliberately does not
99
+ * print or set `process.exitCode` — `runGateCli` does that, and tests get to
100
+ * assert on an object instead of scraping stdout.
101
+ */
102
+ declare function runGate<Report, Options>(gate: GateDefinition<Report, Options>, argv: readonly string[], options?: RunGateOptions): Promise<GateOutcome<Report>>;
103
+ /**
104
+ * Suppression and re-tuning are reported, never silent — the same reason
105
+ * `check integrity` prints its exemptions and `gates suppressions` exists.
106
+ * A gate that passes because three rules were turned off must say so on the
107
+ * same screen as the verdict.
108
+ *
109
+ * It also has to say when the prose above it disagrees. `format(report, rules)` lets a gate
110
+ * render suppression into its own output. All 27 built-ins now do; when only `check integrity`
111
+ * did, the other 26 rendered from the raw report and `--rule x=off` produced a screen that
112
+ * contradicted itself. Measured on `scan handlers` at the time:
113
+ *
114
+ * status: 5 suspect issue(s), 7 warn <- red, and rendered pre-suppression
115
+ * ... five suspect lines ...
116
+ * 5 finding(s) suppressed by rule settings
117
+ * $ echo $? -> 0
118
+ *
119
+ * A reader has to know which half to believe. `gate.format.length < 2` says the formatter never
120
+ * received the rule view — its declared arity, so no gate has to be listed here — and that is
121
+ * when the disclaimer is printed. It is not dead code with the built-ins migrated: a project's
122
+ * own gate, or one from a third-party plugin, is written against the one-parameter form in
123
+ * `docs/authoring-gates.md` and reaches this branch on its first `--rule x=off`.
124
+ *
125
+ * The count line stays even for a rule-aware gate, which does mean a gate's own
126
+ * "N finding(s) not shown" and this line can appear on one screen with the same number. That is
127
+ * deliberate: this one is the runner's accounting, tied to the exit code, and a formatter that
128
+ * forgets to render its own note must not be able to make the suppression invisible.
129
+ */
130
+ declare function formatRuleNotes(gate: AnyGateDefinition, applied: AppliedRules): string;
131
+ /** `vlmkit <gate> --rules` — the tunable surface, without measuring anything. */
132
+ declare function formatRuleTable(gate: AnyGateDefinition): string;
133
+ /**
134
+ * Help text, composed from the definition. The shared-flag block is appended
135
+ * here rather than copied into every gate's usage string, which is how the
136
+ * `--advisory` contract drifted out of `check integrity` in the first place.
137
+ */
138
+ declare function formatGateHelp(gate: AnyGateDefinition): string;
139
+ interface GateCliIo {
140
+ out?: (text: string) => void;
141
+ err?: (text: string) => void;
142
+ }
143
+ /**
144
+ * Put `line` directly under the gate's verdict line.
145
+ *
146
+ * Falls back to appending when a gate has no such line, so a gate that does not follow
147
+ * the convention keeps the previous behaviour instead of losing the annotation. This is
148
+ * the one place the runner touches gate-owned prose, which is why it is a single
149
+ * insertion at a documented anchor rather than a rewrite.
150
+ */
151
+ declare function withExitIntent(text: string, line: string): string;
152
+ /**
153
+ * Is this run measuring a live URL that nothing has pinned?
154
+ *
155
+ * v5's CI agent was asked whether a run was reproducible and had to answer it by
156
+ * writing a jitter server and diffing outputs itself: "No gate says its input was
157
+ * unpinned. Four gates hit a live URL and returned verdicts with nothing indicating a
158
+ * re-run could differ."
159
+ *
160
+ * The runner can tell, from what it already has: the gate declares `--har` (so pinning
161
+ * is available for it), argv names an http(s) source, and no `--har` was passed. Said
162
+ * once per run rather than measured — the agent asked for `--repeat 2 --require-stable`,
163
+ * but the question it was actually answering is "could this differ", and that is
164
+ * decidable without running anything twice.
165
+ */
166
+ declare function unpinnedLiveInput(gate: AnyGateDefinition, argv: readonly string[]): string | null;
167
+ /**
168
+ * Announce a file this run brought into existence in an un-ignored spot.
169
+ *
170
+ * The run ledger has always been written to `.vlmkit/run-ledger.jsonl` with no
171
+ * flag, no mention in any output, and an env-var opt-out. v6's adopting agent:
172
+ * "adopting the tool dirtied the repo silently. `--output` covers stdout logs;
173
+ * `test-results/` and `.vlmkit/run-ledger.jsonl` have no flag and nothing
174
+ * announces them. The agent found them with `ls` and wrote the `.gitignore`
175
+ * itself." The gates that write reports already print `report: <path>`; the
176
+ * ledger was the one genuinely silent write.
177
+ *
178
+ * Only on CREATION, and only when the path is not already ignored. A line on
179
+ * every run would be noise on a file that gets one appended line per gate, and
180
+ * the moment worth reporting is the moment the repo changed shape.
181
+ */
182
+ declare function newOutputNotice(write: LedgerWrite | null, cwd: string): string | null;
183
+ /**
184
+ * CLI adapter: handle `--help` / `--rules`, run the gate, write the output,
185
+ * return the exit code. A migrated gate's whole `main()` becomes one call.
186
+ */
187
+ declare function runGateCli<Report, Options>(gate: GateDefinition<Report, Options>, argv: readonly string[], options?: RunGateOptions & GateCliIo): Promise<0 | 1>;
188
+ /**
189
+ * The phase breakdown as one block.
190
+ *
191
+ * Shows `run` as a share of the total because that share is the actionable
192
+ * number: it says whether a slow gate is slow at measuring (nothing to tune
193
+ * but the page) or slow at everything else (a formatter doing real work — the
194
+ * defect `formatA11yTouchReport` had, where a "formatter" ran a policy).
195
+ */
196
+ declare function formatGateTiming(outcome: GateOutcome): string;
197
+ //#endregion
198
+ export { GateCliIo, GateOutcome, GateTiming, RunGateOptions, SHARED_GATE_FLAGS, SharedFlags, formatGateHelp, formatGateTiming, formatRuleNotes, formatRuleTable, newOutputNotice, parseSharedFlags, runGate, runGateCli, stripSharedFlags, unpinnedLiveInput, withExitIntent };
@@ -0,0 +1,440 @@
1
+ import { UsageError } from "../cli-error.mjs";
2
+ import { authStateNotice, resetAuthStateNotice } from "../auth-state.mjs";
3
+ import { BOLD, CYAN, DIM, RED, RESET, YELLOW } from "../terminal-colors.mjs";
4
+ import { gateCommandString } from "./contract.mjs";
5
+ import { RULE_SETTINGS, applyRuleSettings, countFindings, resolveRules } from "./rules.mjs";
6
+ import { GATE_EXIT_HELP } from "../gate-exit.mjs";
7
+ import { LEDGER_RELATIVE_PATH, VLMKIT_IGNORE_ENTRIES, appendRunLedger, configureRunLedger, firstLedgerWrite, isGitIgnored, isGitRepo } from "../run-ledger.mjs";
8
+ import { relative } from "node:path";
9
+ //#region src/plugin/runner.ts
10
+ /**
11
+ * The core gate runner — the part every gate stopped having to write.
12
+ *
13
+ * Measured on this repo before the plugin contract existed: 20 gate modules
14
+ * had their own `parseArgs`, 22 their own `printUsage`, 22 called
15
+ * `appendRunLedger` by hand, and only 6 used `applyGateExit`. The
16
+ * consequences were not cosmetic. `check breakpoints` called
17
+ * `process.exit(1)` directly, which truncates buffered stdout — the reason
18
+ * `applyGateExit` exists. `check integrity` had no `--advisory` at all,
19
+ * so the one gate most likely to be piloted before it gates CI was the one
20
+ * gate that could not be. Two commands in the same group disagreed about
21
+ * whether a finding should fail the command.
22
+ *
23
+ * So the runner owns the whole envelope: help, `--json`, `--advisory`, rule
24
+ * settings, the ledger write, the verdict, the exit code. A gate contributes
25
+ * measurement (`run`), projection (`findings`), and prose (`format`) — and
26
+ * nothing else. What a gate cannot do is disagree with the contract.
27
+ */
28
+ /** Flags the runner owns. A gate's `parse` never sees these as its own. */
29
+ const SHARED_GATE_FLAGS = [
30
+ "--json",
31
+ "--advisory",
32
+ "--fail-on-suspect",
33
+ "--rule",
34
+ "--rules",
35
+ "--timing",
36
+ "--ledger",
37
+ "--no-ledger",
38
+ "--help",
39
+ "-h"
40
+ ];
41
+ /**
42
+ * Read the shared flags. `--fail-on-suspect` is still accepted and still
43
+ * does nothing: it was the documented way to opt *into* failing before
44
+ * failing became the default, and scripts in the wild still pass it.
45
+ */
46
+ function parseSharedFlags(argv) {
47
+ const ruleOverrides = {};
48
+ for (let i = 0; i < argv.length; i++) {
49
+ if (argv[i] !== "--rule") continue;
50
+ const spec = argv[i + 1];
51
+ if (spec === void 0 || spec.startsWith("--")) throw new UsageError("--rule needs <ruleRef>=<off|suspect|warn|info>");
52
+ const eq = spec.lastIndexOf("=");
53
+ if (eq <= 0) throw new UsageError(`--rule expects <ruleRef>=<setting>, got ${JSON.stringify(spec)}`);
54
+ const ref = spec.slice(0, eq).trim();
55
+ const setting = spec.slice(eq + 1).trim();
56
+ if (!RULE_SETTINGS.includes(setting)) throw new UsageError(`--rule ${ref}: setting must be one of ${RULE_SETTINGS.join(", ")}, got ${JSON.stringify(setting)}`);
57
+ ruleOverrides[ref] = setting;
58
+ }
59
+ const ledgerAt = argv.indexOf("--ledger");
60
+ if (ledgerAt >= 0) {
61
+ const value = argv[ledgerAt + 1];
62
+ if (value === void 0 || value.startsWith("--")) throw new UsageError("--ledger needs a path");
63
+ }
64
+ return {
65
+ json: argv.includes("--json"),
66
+ advisory: argv.includes("--advisory"),
67
+ help: argv.includes("--help") || argv.includes("-h"),
68
+ listRules: argv.includes("--rules"),
69
+ timing: argv.includes("--timing"),
70
+ ...ledgerAt >= 0 ? { ledgerPath: argv[ledgerAt + 1] } : {},
71
+ noLedger: argv.includes("--no-ledger"),
72
+ ruleOverrides
73
+ };
74
+ }
75
+ /** Drop the runner-owned flags so a gate's parser never has to know them. */
76
+ function stripSharedFlags(argv) {
77
+ const out = [];
78
+ for (let i = 0; i < argv.length; i++) {
79
+ const arg = argv[i];
80
+ if (arg === "--rule" || arg === "--ledger") {
81
+ i++;
82
+ continue;
83
+ }
84
+ if (SHARED_GATE_FLAGS.includes(arg)) continue;
85
+ out.push(arg);
86
+ }
87
+ return out;
88
+ }
89
+ /**
90
+ * A `--rule` that names THIS gate and a rule it does not have is a typo, and a
91
+ * typo that silences nothing is precisely the failure rule settings exist to
92
+ * remove — so it fails the run instead of being ignored.
93
+ *
94
+ * Only that exact shape is checked. A key naming another gate, or a bare rule
95
+ * id, must pass silently: `vlmkit gates` appends every `--rule` flag from
96
+ * `defaults.rules` to every job, so a gate legitimately receives references
97
+ * meant for its neighbours. Registry-wide validation of the config is
98
+ * `validateRuleSettings`'s job, where the whole catalog is in view.
99
+ */
100
+ function assertKnownRuleOverrides(gate, overrides) {
101
+ const prefix = `${gate.id}/`;
102
+ for (const key of Object.keys(overrides)) {
103
+ if (!key.startsWith(prefix)) continue;
104
+ const ruleId = key.slice(prefix.length);
105
+ if (ruleId === "*" || gate.rules.some((rule) => rule.id === ruleId)) continue;
106
+ throw new UsageError(`--rule ${key}: ${gate.id} has no rule "${ruleId}". Known: ${gate.rules.map((rule) => rule.id).join(", ")}`);
107
+ }
108
+ }
109
+ /**
110
+ * Run one gate end to end and return what happened. Deliberately does not
111
+ * print or set `process.exitCode` — `runGateCli` does that, and tests get to
112
+ * assert on an object instead of scraping stdout.
113
+ */
114
+ async function runGate(gate, argv, options = {}) {
115
+ const cwd = options.cwd ?? process.cwd();
116
+ const t0 = performance.now();
117
+ const shared = parseSharedFlags(argv);
118
+ const gateArgv = stripSharedFlags(argv);
119
+ const ctx = {
120
+ cwd,
121
+ argv: gateArgv,
122
+ json: shared.json
123
+ };
124
+ configureRunLedger({
125
+ cwd,
126
+ ...shared.ledgerPath ? { path: shared.ledgerPath } : {},
127
+ ...shared.noLedger ? { disabled: true } : {}
128
+ });
129
+ resetAuthStateNotice();
130
+ const tParse = performance.now();
131
+ const parsed = gate.parse(gateArgv, ctx);
132
+ const tRun = performance.now();
133
+ const report = await gate.run(parsed, ctx);
134
+ const tFindings = performance.now();
135
+ const settings = {
136
+ ...options.rules,
137
+ ...shared.ruleOverrides
138
+ };
139
+ assertKnownRuleOverrides(gate, shared.ruleOverrides);
140
+ const projected = gate.findings(report, parsed);
141
+ const tRules = performance.now();
142
+ const rules = applyRuleSettings(gate, projected, settings);
143
+ const counts = countFindings(rules.findings);
144
+ const verdict = counts.suspect > 0 ? "fail" : "pass";
145
+ const tLedger = performance.now();
146
+ if (options.ledger !== false && gate.ledger) {
147
+ const entry = gate.ledger(report, parsed);
148
+ if (entry) appendRunLedger(entry);
149
+ }
150
+ const ledgerWrite = firstLedgerWrite();
151
+ const tFormat = performance.now();
152
+ const timing = {
153
+ parseMs: round(tRun - tParse),
154
+ runMs: round(tFindings - tRun),
155
+ findingsMs: round(tRules - tFindings),
156
+ rulesMs: round(tLedger - tRules),
157
+ ledgerMs: round(tFormat - tLedger),
158
+ formatMs: 0,
159
+ totalMs: 0
160
+ };
161
+ const resolved = resolveRules(gate, settings);
162
+ const prose = shared.json ? "" : [gate.format(report, {
163
+ effective: (ruleId) => resolved.decisions.get(ruleId)?.effective ?? gate.rules.find((r) => r.id === ruleId)?.severity ?? "warn",
164
+ setting: (ruleId) => {
165
+ const decision = resolved.decisions.get(ruleId);
166
+ return decision?.via ? decision.effective : void 0;
167
+ }
168
+ }), formatRuleNotes(gate, rules)].filter(Boolean).join("\n");
169
+ timing.formatMs = round(performance.now() - tFormat);
170
+ timing.totalMs = round(performance.now() - t0);
171
+ const text = shared.json ? JSON.stringify({
172
+ gate: gate.id,
173
+ command: gateCommandString(gate),
174
+ verdict,
175
+ counts,
176
+ findings: rules.findings,
177
+ suppressed: rules.suppressed,
178
+ retuned: rules.retuned,
179
+ report,
180
+ ...shared.timing ? { timing } : {}
181
+ }, null, 2) : prose;
182
+ return {
183
+ gateId: gate.id,
184
+ command: gateCommandString(gate),
185
+ verdict,
186
+ report,
187
+ findings: rules.findings,
188
+ counts,
189
+ rules,
190
+ exitCode: verdict === "fail" && !shared.advisory ? 1 : 0,
191
+ text,
192
+ timing,
193
+ ledgerWrite
194
+ };
195
+ }
196
+ /** Sub-microsecond precision is noise at this scale and makes tables unreadable. */
197
+ function round(ms) {
198
+ return Math.round(ms * 1e3) / 1e3;
199
+ }
200
+ /**
201
+ * Suppression and re-tuning are reported, never silent — the same reason
202
+ * `check integrity` prints its exemptions and `gates suppressions` exists.
203
+ * A gate that passes because three rules were turned off must say so on the
204
+ * same screen as the verdict.
205
+ *
206
+ * It also has to say when the prose above it disagrees. `format(report, rules)` lets a gate
207
+ * render suppression into its own output. All 27 built-ins now do; when only `check integrity`
208
+ * did, the other 26 rendered from the raw report and `--rule x=off` produced a screen that
209
+ * contradicted itself. Measured on `scan handlers` at the time:
210
+ *
211
+ * status: 5 suspect issue(s), 7 warn <- red, and rendered pre-suppression
212
+ * ... five suspect lines ...
213
+ * 5 finding(s) suppressed by rule settings
214
+ * $ echo $? -> 0
215
+ *
216
+ * A reader has to know which half to believe. `gate.format.length < 2` says the formatter never
217
+ * received the rule view — its declared arity, so no gate has to be listed here — and that is
218
+ * when the disclaimer is printed. It is not dead code with the built-ins migrated: a project's
219
+ * own gate, or one from a third-party plugin, is written against the one-parameter form in
220
+ * `docs/authoring-gates.md` and reaches this branch on its first `--rule x=off`.
221
+ *
222
+ * The count line stays even for a rule-aware gate, which does mean a gate's own
223
+ * "N finding(s) not shown" and this line can appear on one screen with the same number. That is
224
+ * deliberate: this one is the runner's accounting, tied to the exit code, and a formatter that
225
+ * forgets to render its own note must not be able to make the suppression invisible.
226
+ */
227
+ function formatRuleNotes(gate, applied) {
228
+ const lines = [];
229
+ if (applied.suppressed.length > 0) {
230
+ const byRule = /* @__PURE__ */ new Map();
231
+ for (const s of applied.suppressed) byRule.set(s.finding.rule, (byRule.get(s.finding.rule) ?? 0) + 1);
232
+ lines.push("");
233
+ lines.push(`${YELLOW}${applied.suppressed.length} finding(s) suppressed by rule settings${RESET} ${DIM}(${[...byRule].map(([rule, n]) => `${rule} x${n}`).join(", ")})${RESET}`);
234
+ if (gate.format.length < 2) lines.push(`${DIM} The report above was rendered before those settings were applied, so it still lists them and its own status line still counts them. The verdict and exit code do not.${RESET}`);
235
+ }
236
+ if (applied.retuned.length > 0) {
237
+ const byRule = /* @__PURE__ */ new Map();
238
+ for (const r of applied.retuned) byRule.set(r.finding.rule, {
239
+ from: r.from,
240
+ to: r.to
241
+ });
242
+ lines.push(`${DIM}re-tuned: ${[...byRule].map(([rule, n]) => `${rule} ${n.from}->${n.to}`).join(", ")}${RESET}`);
243
+ }
244
+ if (applied.undeclared.length > 0) {
245
+ lines.push("");
246
+ lines.push(`${RED}${gate.id} emitted undeclared rule id(s): ${applied.undeclared.join(", ")}${RESET} ${DIM}— add them to the gate's rules table.${RESET}`);
247
+ }
248
+ return lines.join("\n");
249
+ }
250
+ /** `vlmkit <gate> --rules` — the tunable surface, without measuring anything. */
251
+ function formatRuleTable(gate) {
252
+ const lines = [];
253
+ lines.push("");
254
+ lines.push(`${BOLD}${CYAN}${gateCommandString(gate)}${RESET} ${DIM}${gate.id}${RESET}`);
255
+ lines.push("");
256
+ lines.push(`${gate.rules.length} rule(s). Tune with ${DIM}--rule ${gate.id}/<id>=<off|suspect|warn|info>${RESET}`);
257
+ lines.push(`or in ${DIM}vlmkit.gates.json${RESET} under ${DIM}"rules"${RESET}.`);
258
+ lines.push("");
259
+ const width = Math.max(...gate.rules.map((r) => r.id.length));
260
+ for (const rule of gate.rules) {
261
+ const severity = rule.severity === "suspect" ? `${RED}suspect${RESET}` : rule.severity === "warn" ? `${YELLOW}warn${RESET}` : `${DIM}info${RESET}`;
262
+ lines.push(` ${rule.id.padEnd(width)} ${severity.padEnd(16)} ${rule.title}`);
263
+ if (rule.docs) lines.push(` ${" ".repeat(width)} ${DIM}${rule.docs}${RESET}`);
264
+ }
265
+ return lines.join("\n");
266
+ }
267
+ /**
268
+ * Help text, composed from the definition. The shared-flag block is appended
269
+ * here rather than copied into every gate's usage string, which is how the
270
+ * `--advisory` contract drifted out of `check integrity` in the first place.
271
+ */
272
+ function formatGateHelp(gate) {
273
+ const lines = [];
274
+ const positionals = (gate.inputs ?? []).filter((i) => i.positional !== void 0).sort((a, b) => a.positional - b.positional).map((i) => i.required === false ? `[${i.placeholder ?? i.name}]` : `<${i.placeholder ?? i.name}>`).join(" ");
275
+ lines.push(`Usage: vlmkit ${gateCommandString(gate)}${positionals ? ` ${positionals}` : ""} [options]`);
276
+ lines.push("");
277
+ lines.push(gate.usage?.trim() || gate.summary);
278
+ const flags = (gate.inputs ?? []).filter((i) => i.positional === void 0);
279
+ if (flags.length > 0) {
280
+ lines.push("");
281
+ lines.push("Options:");
282
+ const width = Math.max(...flags.map((f) => flagLabel(f).length), 22);
283
+ for (const flag of flags) {
284
+ const suffix = flag.defaultDescription ? ` (default: ${flag.defaultDescription})` : "";
285
+ lines.push(` ${flagLabel(flag).padEnd(width)} ${flag.description}${suffix}`);
286
+ }
287
+ }
288
+ lines.push("");
289
+ lines.push("Shared options (every gate):");
290
+ lines.push(" --json Print the JSON report");
291
+ lines.push(GATE_EXIT_HELP);
292
+ lines.push(" --rule <ref>=<setting> Re-tune or disable one rule (off|suspect|warn|info), repeatable");
293
+ lines.push(" --rules List this gate's rules and exit");
294
+ lines.push(" --timing Add the per-phase ms breakdown to the output");
295
+ lines.push(` --ledger <path> Where to append the run record (default: ${LEDGER_RELATIVE_PATH})`);
296
+ lines.push(" --no-ledger Do not write the run record at all");
297
+ lines.push(" --fail-on-suspect Accepted no-op (a suspect already exits 1)");
298
+ lines.push(" -h, --help Show this help");
299
+ lines.push("");
300
+ lines.push("Persisting: a `\"gates\"` entry in vlmkit.gates.json is the whole command, so any");
301
+ lines.push("flag above belongs there and is committed with the page. Quoted values survive:");
302
+ lines.push(` "gates": ["${gateCommandString(gate)} --some-flag \\"a value with spaces\\""]`);
303
+ lines.push("Rule settings also have their own `\"rules\"` block.");
304
+ return lines.join("\n");
305
+ }
306
+ function flagLabel(input) {
307
+ const value = input.kind === "boolean" ? "" : input.placeholder ? ` <${input.placeholder}>` : input.kind === "number" ? " <n>" : input.kind === "number-list" || input.kind === "string-list" ? " <list>" : input.kind === "path" || input.kind === "path-or-url" ? " <path>" : input.choices ? ` <${input.choices.join("|")}>` : " <value>";
308
+ return `--${input.name}${value}${input.repeatable ? " (repeatable)" : ""}`;
309
+ }
310
+ /**
311
+ * A gate's own headline line, which the runner may annotate.
312
+ *
313
+ * Every gate opens its prose with `verdict:` or `status:`. That convention is already
314
+ * load-bearing elsewhere — `batch-cli`'s `gateReported()` uses exactly this pattern to
315
+ * tell "the gate measured the page" from "the gate never ran" — so formalizing it here
316
+ * is recognising a contract rather than inventing one.
317
+ */
318
+ const VERDICT_LINE = /^\s*(?:\u001B\[[0-9;]*m)*(verdict|status):/;
319
+ /**
320
+ * Put `line` directly under the gate's verdict line.
321
+ *
322
+ * Falls back to appending when a gate has no such line, so a gate that does not follow
323
+ * the convention keeps the previous behaviour instead of losing the annotation. This is
324
+ * the one place the runner touches gate-owned prose, which is why it is a single
325
+ * insertion at a documented anchor rather than a rewrite.
326
+ */
327
+ function withExitIntent(text, line) {
328
+ const lines = text.split("\n");
329
+ const at = lines.findIndex((l) => VERDICT_LINE.test(l));
330
+ if (at < 0) return `${text}\n${line}`;
331
+ return [
332
+ ...lines.slice(0, at + 1),
333
+ line,
334
+ ...lines.slice(at + 1)
335
+ ].join("\n");
336
+ }
337
+ /**
338
+ * Is this run measuring a live URL that nothing has pinned?
339
+ *
340
+ * v5's CI agent was asked whether a run was reproducible and had to answer it by
341
+ * writing a jitter server and diffing outputs itself: "No gate says its input was
342
+ * unpinned. Four gates hit a live URL and returned verdicts with nothing indicating a
343
+ * re-run could differ."
344
+ *
345
+ * The runner can tell, from what it already has: the gate declares `--har` (so pinning
346
+ * is available for it), argv names an http(s) source, and no `--har` was passed. Said
347
+ * once per run rather than measured — the agent asked for `--repeat 2 --require-stable`,
348
+ * but the question it was actually answering is "could this differ", and that is
349
+ * decidable without running anything twice.
350
+ */
351
+ function unpinnedLiveInput(gate, argv) {
352
+ if (!(gate.inputs ?? []).some((input) => input.name === "har") || argv.includes("--har")) return null;
353
+ const url = argv.find((arg) => /^https?:\/\//.test(arg));
354
+ if (!url) return null;
355
+ return `${DIM} ${url} is live and not pinned — a re-run may measure different data. Pin it: vlmkit snapshot record-har ${url} --out app.har, then --har app.har${RESET}`;
356
+ }
357
+ /**
358
+ * Announce a file this run brought into existence in an un-ignored spot.
359
+ *
360
+ * The run ledger has always been written to `.vlmkit/run-ledger.jsonl` with no
361
+ * flag, no mention in any output, and an env-var opt-out. v6's adopting agent:
362
+ * "adopting the tool dirtied the repo silently. `--output` covers stdout logs;
363
+ * `test-results/` and `.vlmkit/run-ledger.jsonl` have no flag and nothing
364
+ * announces them. The agent found them with `ls` and wrote the `.gitignore`
365
+ * itself." The gates that write reports already print `report: <path>`; the
366
+ * ledger was the one genuinely silent write.
367
+ *
368
+ * Only on CREATION, and only when the path is not already ignored. A line on
369
+ * every run would be noise on a file that gets one appended line per gate, and
370
+ * the moment worth reporting is the moment the repo changed shape.
371
+ */
372
+ function newOutputNotice(write, cwd) {
373
+ if (!write?.created) return null;
374
+ if (!isGitRepo(cwd) || isGitIgnored(cwd, write.path)) return null;
375
+ const rel = relative(cwd, write.path).split("\\").join("/") || write.path;
376
+ const entries = rel === LEDGER_RELATIVE_PATH.split("\\").join("/") ? [...VLMKIT_IGNORE_ENTRIES] : [rel];
377
+ return [
378
+ `${DIM} created ${rel} — an append-only record of every gate run, one line each.${RESET}`,
379
+ `${DIM} It is not in .gitignore. Ignore it${entries.length > 1 ? " (`vlmkit gates init` writes these)" : ""}:${RESET}`,
380
+ ...entries.map((entry) => `${DIM} ${entry}${RESET}`),
381
+ `${DIM} Or move it with --ledger <path>, or turn it off with --no-ledger.${RESET}`
382
+ ].join("\n");
383
+ }
384
+ /**
385
+ * CLI adapter: handle `--help` / `--rules`, run the gate, write the output,
386
+ * return the exit code. A migrated gate's whole `main()` becomes one call.
387
+ */
388
+ async function runGateCli(gate, argv, options = {}) {
389
+ const out = options.out ?? ((text) => console.log(text));
390
+ const shared = parseSharedFlags(argv);
391
+ if (shared.help) {
392
+ out(formatGateHelp(gate));
393
+ return 0;
394
+ }
395
+ if (shared.listRules) {
396
+ out(formatRuleTable(gate));
397
+ return 0;
398
+ }
399
+ const outcome = await runGate(gate, argv, options);
400
+ if (outcome.exitCode === 0 && outcome.counts.warn > 0 && !shared.json) {
401
+ const ids = [...new Set(outcome.findings.filter((f) => f.severity === "warn").map((f) => f.rule))];
402
+ out(withExitIntent(outcome.text, `${DIM} exits 0 — ${outcome.counts.warn} warn(s) did not fail this command. To gate on one: --rule ${ids[0]}=suspect${ids.length > 1 ? ` (also: ${ids.slice(1).join(", ")})` : ""}${RESET}`));
403
+ } else out(outcome.text);
404
+ if (!shared.json) {
405
+ const unpinned = unpinnedLiveInput(gate, argv);
406
+ if (unpinned) out(unpinned);
407
+ const created = newOutputNotice(outcome.ledgerWrite, options.cwd ?? process.cwd());
408
+ if (created) out(created);
409
+ const auth = authStateNotice();
410
+ if (auth) out(` ${DIM}${auth}${RESET}`);
411
+ }
412
+ if (shared.timing && !shared.json) out(formatGateTiming(outcome));
413
+ return outcome.exitCode;
414
+ }
415
+ /**
416
+ * The phase breakdown as one block.
417
+ *
418
+ * Shows `run` as a share of the total because that share is the actionable
419
+ * number: it says whether a slow gate is slow at measuring (nothing to tune
420
+ * but the page) or slow at everything else (a formatter doing real work — the
421
+ * defect `formatA11yTouchReport` had, where a "formatter" ran a policy).
422
+ */
423
+ function formatGateTiming(outcome) {
424
+ const t = outcome.timing;
425
+ const share = t.totalMs > 0 ? t.runMs / t.totalMs * 100 : 0;
426
+ const row = (label, ms) => ` ${label.padEnd(10)} ${`${ms.toFixed(1)}ms`.padStart(9)}`;
427
+ return [
428
+ "",
429
+ `${BOLD}${CYAN}timing${RESET} ${DIM}${outcome.command}${RESET}`,
430
+ row("parse", t.parseMs),
431
+ `${row("run", t.runMs)} ${DIM}${share.toFixed(1)}% of total — the measurement, shared by every rule${RESET}`,
432
+ `${row("findings", t.findingsMs)} ${DIM}the projection; the only per-rule phase${RESET}`,
433
+ row("rules", t.rulesMs),
434
+ row("format", t.formatMs),
435
+ row("ledger", t.ledgerMs),
436
+ ` ${BOLD}${"total".padEnd(10)}${`${t.totalMs.toFixed(1)}ms`.padStart(9)}${RESET}`
437
+ ].join("\n");
438
+ }
439
+ //#endregion
440
+ export { SHARED_GATE_FLAGS, formatGateHelp, formatGateTiming, formatRuleNotes, formatRuleTable, newOutputNotice, parseSharedFlags, runGate, runGateCli, stripSharedFlags, unpinnedLiveInput, withExitIntent };
@@ -4,6 +4,36 @@ interface PngData {
4
4
  height: number;
5
5
  data: Uint8Array;
6
6
  }
7
+ /**
8
+ * How far two images differ in *magnitude*, independent of any perceptual
9
+ * threshold.
10
+ *
11
+ * A pixel-diff ratio answers "how many pixels changed enough to count", and a
12
+ * comparator with a perceptual threshold can legitimately answer *none* while
13
+ * every pixel in the image has moved. Measured on a 1258x203 hero whose
14
+ * background gradient went from a blue tint to a purple one: 246,914 of 256,632
15
+ * pixels differed, by at most 8/255 per channel, and pixelmatch scored the diff
16
+ * at 0.0%. A gate that reports only the ratio cannot distinguish that from an
17
+ * identical render, which is the difference between a caught regression and a
18
+ * silent one.
19
+ *
20
+ * Alpha is deliberately excluded. A screenshot of an opaque element is fully
21
+ * opaque, so an alpha delta here would mean the two images were cropped
22
+ * differently — a size mismatch, not a colour change, and one the caller should
23
+ * see as such rather than folded into a colour statistic.
24
+ */
25
+ interface ChangeMagnitude {
26
+ /** Pixels with any non-zero channel delta, however small. */
27
+ changedPixels: number;
28
+ totalPixels: number;
29
+ /** Fraction of pixels that moved at all. 1.0 means the whole box shifted. */
30
+ changedFraction: number;
31
+ /** Largest single-channel delta anywhere, 0-255. */
32
+ maxChannelDelta: number;
33
+ /** Mean per-pixel max-channel delta over the whole image, 0-255. */
34
+ meanChannelDelta: number;
35
+ }
36
+ declare function measureChangeMagnitude(a: PngData, b: PngData): ChangeMagnitude;
7
37
  /**
8
38
  * Crop or pad an image to the target dimensions.
9
39
  * Only handles the common region; overflow is zero-filled.
@@ -27,4 +57,4 @@ declare function decodePng(path: string): Promise<PngData>;
27
57
  */
28
58
  declare function encodePng(path: string, data: PngData): Promise<void>;
29
59
  //#endregion
30
- export { PngData, cropImage, cropRegion, decodePng, encodePng };
60
+ export { ChangeMagnitude, PngData, cropImage, cropRegion, decodePng, encodePng, measureChangeMagnitude };