@autotelic/joggle 0.0.0-stage → 0.1.1

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 (101) hide show
  1. package/JOGGLE.md +634 -0
  2. package/LICENSE +21 -0
  3. package/README.md +88 -2
  4. package/bin/joggle.js +6 -0
  5. package/dist/answer-store.js +305 -0
  6. package/dist/architecture.js +190 -0
  7. package/dist/ask.js +184 -0
  8. package/dist/astro.js +75 -0
  9. package/dist/atoms.js +76 -0
  10. package/dist/bundles.js +156 -0
  11. package/dist/calibration.js +60 -0
  12. package/dist/candidates.js +561 -0
  13. package/dist/canonical.js +24 -0
  14. package/dist/cascade.js +98 -0
  15. package/dist/check.js +854 -0
  16. package/dist/cluster.js +69 -0
  17. package/dist/config.js +195 -0
  18. package/dist/content-mappers.js +83 -0
  19. package/dist/decision.js +203 -0
  20. package/dist/fingerprint.js +61 -0
  21. package/dist/git.js +127 -0
  22. package/dist/gitignore.js +65 -0
  23. package/dist/glob.js +51 -0
  24. package/dist/imports.js +153 -0
  25. package/dist/jsonc.js +95 -0
  26. package/dist/main.js +630 -0
  27. package/dist/manifest.js +42 -0
  28. package/dist/meta.js +170 -0
  29. package/dist/moves.js +47 -0
  30. package/dist/operation.js +133 -0
  31. package/dist/parsecache.js +264 -0
  32. package/dist/plans.js +425 -0
  33. package/dist/plugin.js +71 -0
  34. package/dist/plugins.js +136 -0
  35. package/dist/policy.js +676 -0
  36. package/dist/presets/composition.js +32 -0
  37. package/dist/report.js +474 -0
  38. package/dist/reporting.js +132 -0
  39. package/dist/result.js +28 -0
  40. package/dist/roles.js +303 -0
  41. package/dist/rule.js +194 -0
  42. package/dist/rules/append-only-honoured.js +190 -0
  43. package/dist/rules/bundle-conformance.js +245 -0
  44. package/dist/rules/call-pattern.js +209 -0
  45. package/dist/rules/cluster-verdict.js +700 -0
  46. package/dist/rules/compose-types.js +250 -0
  47. package/dist/rules/data-error-as-outage.js +482 -0
  48. package/dist/rules/declared-staleness.js +242 -0
  49. package/dist/rules/dependency-fit.js +297 -0
  50. package/dist/rules/deviation-has-a-shape.js +225 -0
  51. package/dist/rules/doc-matches-code.js +191 -0
  52. package/dist/rules/duplicate-call-run.js +240 -0
  53. package/dist/rules/duplicate-implementation.js +89 -0
  54. package/dist/rules/duplicate-meaning.js +130 -0
  55. package/dist/rules/fact-or-derivation.js +202 -0
  56. package/dist/rules/field-type-drift.js +373 -0
  57. package/dist/rules/generic-carries-a-caller.js +198 -0
  58. package/dist/rules/hoist-to-domain.js +288 -0
  59. package/dist/rules/import-architecture.js +393 -0
  60. package/dist/rules/index.js +105 -0
  61. package/dist/rules/inferred-over-recorded.js +214 -0
  62. package/dist/rules/intent-drift.js +286 -0
  63. package/dist/rules/invariant-has-a-reconciler.js +190 -0
  64. package/dist/rules/language-drift.js +234 -0
  65. package/dist/rules/meaning-switched-by-flag.js +189 -0
  66. package/dist/rules/module-direction.js +231 -0
  67. package/dist/rules/name-as-address.js +216 -0
  68. package/dist/rules/name-the-primitive.js +203 -0
  69. package/dist/rules/naming-drift.js +218 -0
  70. package/dist/rules/nullability-drift.js +220 -0
  71. package/dist/rules/object-shape.js +280 -0
  72. package/dist/rules/one-concept-one-type.js +243 -0
  73. package/dist/rules/page-needs-composition.js +227 -0
  74. package/dist/rules/reimplemented-primitive.js +283 -0
  75. package/dist/rules/reversal.js +264 -0
  76. package/dist/rules/rule-judgment.js +252 -0
  77. package/dist/rules/schema-excludes-domain-value.js +190 -0
  78. package/dist/rules/shallow-module.js +204 -0
  79. package/dist/rules/single-path.js +237 -0
  80. package/dist/rules/structural-collapse.js +198 -0
  81. package/dist/rules/temporal-coupling.js +205 -0
  82. package/dist/rules/types-over-logic.js +198 -0
  83. package/dist/rules/unaccounted-drop.js +190 -0
  84. package/dist/rules/unbounded-default-read.js +227 -0
  85. package/dist/run-cache.js +132 -0
  86. package/dist/schema.js +285 -0
  87. package/dist/similarity.js +119 -0
  88. package/dist/source.js +30 -0
  89. package/dist/sql.js +34 -0
  90. package/dist/stages.js +39 -0
  91. package/dist/state.js +65 -0
  92. package/dist/testing.js +131 -0
  93. package/dist/tsconfig-scope.js +32 -0
  94. package/dist/tsgo.js +127 -0
  95. package/dist/typefacts.js +455 -0
  96. package/dist/typetrace.js +283 -0
  97. package/dist/verdict.js +65 -0
  98. package/dist/vocabulary.js +365 -0
  99. package/dist/workspace.js +1963 -0
  100. package/extensions/joggle.ts +454 -0
  101. package/package.json +85 -3
@@ -0,0 +1,32 @@
1
+ import { pageNeedsComposition } from "../rules/page-needs-composition.js";
2
+ import { bundleRules } from "../rules/bundle-conformance.js";
3
+ /**
4
+ * The composition pattern, as an opinion rather than a default.
5
+ *
6
+ * These five rules came out of a starter repository's own documentation. They are
7
+ * somebody's architecture -- a provider owning `{ state, actions, meta }`, blocks
8
+ * exported by dot notation, one file per block -- and running them on a codebase
9
+ * that never agreed to that is the entropy machine with a command-line flag.
10
+ *
11
+ * So they ship as a preset. A repository opts in:
12
+ *
13
+ * { "presets": ["@autotelic/joggle/presets/composition"] }
14
+ *
15
+ * and gets the rules AND their severities. It can then override any of it per
16
+ * rule, because a preset sets defaults rather than taking over.
17
+ *
18
+ * Every rule is judged now: the bundle checks find the departure from the
19
+ * pattern, and Jev decides whether it is a defect. The page rule triggers on
20
+ * evidence -- local state and inline markup -- rather than on a file being under
21
+ * `routes/`.
22
+ */
23
+ export const rules = [...bundleRules, pageNeedsComposition];
24
+ export const config = {
25
+ rules: {
26
+ "joggle/bundle-dot-notation": "warn",
27
+ "joggle/bundle-tripartite-value": "warn",
28
+ "joggle/bundle-one-file-per-block": "warn",
29
+ "joggle/bundle-context-hook": "warn",
30
+ "joggle/page-needs-composition": "warn",
31
+ },
32
+ };
package/dist/report.js ADDED
@@ -0,0 +1,474 @@
1
+ import { Match } from "effect";
2
+ import { moveOrder, moveVocabulary } from "./moves.js";
3
+ /**
4
+ * The funnel, worded for the report.
5
+ *
6
+ * One line per rule that dropped anything, with the counts by stage and one
7
+ * example. The example matters more than the count: "gated 12" says a threshold
8
+ * may be wrong, while naming one candidate and the reason it failed says whether
9
+ * the threshold is wrong about the right thing.
10
+ */
11
+ export const funnelNotes = (drops) => {
12
+ const byRule = new Map();
13
+ for (const drop of drops) {
14
+ const stages = byRule.get(drop.ruleId) ?? new Map();
15
+ stages.set(drop.stage, (stages.get(drop.stage) ?? 0) + 1);
16
+ byRule.set(drop.ruleId, stages);
17
+ }
18
+ return [...byRule.entries()].map(([ruleId, stages]) => {
19
+ const parts = [...stages.entries()]
20
+ .sort((left, right) => left[0].localeCompare(right[0]))
21
+ .map(([stage, count]) => stage + " " + count);
22
+ const example = drops.find((drop) => drop.ruleId === ruleId);
23
+ return {
24
+ ruleId,
25
+ reason: "dropped " +
26
+ parts.join(", ") +
27
+ (example === undefined ? "" : "; e.g. " + example.subject + ": " + example.reason),
28
+ };
29
+ });
30
+ };
31
+ const rank = { error: 0, warn: 1, info: 2 };
32
+ /** Rank findings for reading: file, line, column, severity, then rule. */
33
+ export const sortDiagnostics = (diagnostics) => [...diagnostics].sort((a, b) => a.location.file.localeCompare(b.location.file) ||
34
+ a.location.line - b.location.line ||
35
+ a.location.column - b.location.column ||
36
+ rank[a.severity] - rank[b.severity] ||
37
+ a.ruleId.localeCompare(b.ruleId));
38
+ /**
39
+ * Fold findings that report the same site and the same move into one.
40
+ *
41
+ * `reversal` proves a copy and `duplicate-implementation` judges it, and both
42
+ * anchor at the same declaration; `compose-types` and `reversal` do the same for
43
+ * a containment. Two findings for one thing is not more evidence -- it is one
44
+ * thing counted twice, and it made the report say a site was a `contract` and a
45
+ * `combine` at once.
46
+ *
47
+ * The richer finding wins: a repair is a work order, a panel is an explanation,
48
+ * a judgement has looked. The fact-only duplicate is still counted in the note,
49
+ * so the report says what it folded rather than pretending it never existed.
50
+ *
51
+ * @param diagnostics - the configured findings, in rule order.
52
+ * @returns the survivors, in their original order, and how many were folded.
53
+ */
54
+ export const foldSiteDuplicates = (diagnostics) => {
55
+ const siteOf = (entry) => [
56
+ entry.move ?? "requirement",
57
+ entry.location.file,
58
+ String(entry.location.line),
59
+ String(entry.location.column),
60
+ ].join("\u0000");
61
+ const strength = (entry) => (entry.repair === undefined ? 0 : 4) +
62
+ (entry.panel === undefined ? 0 : 2) +
63
+ (entry.judged ? 1 : 0);
64
+ const loudness = (entry) => Match.value(entry.severity).pipe(Match.when("error", () => 2), Match.when("warn", () => 1), Match.orElse(() => 0));
65
+ const better = (left, right) => {
66
+ const richer = strength(right) - strength(left);
67
+ if (richer !== 0)
68
+ return richer > 0 ? right : left;
69
+ const louder = loudness(right) - loudness(left);
70
+ if (louder !== 0)
71
+ return louder > 0 ? right : left;
72
+ return right.ruleId.localeCompare(left.ruleId) < 0 ? right : left;
73
+ };
74
+ const order = new Map();
75
+ diagnostics.forEach((entry, index) => {
76
+ const site = siteOf(entry);
77
+ if (!order.has(site))
78
+ order.set(site, index);
79
+ });
80
+ const bySite = new Map();
81
+ let folded = 0;
82
+ for (const entry of diagnostics) {
83
+ const site = siteOf(entry);
84
+ const existing = bySite.get(site);
85
+ if (existing === undefined) {
86
+ bySite.set(site, entry);
87
+ continue;
88
+ }
89
+ folded += 1;
90
+ bySite.set(site, better(existing, entry));
91
+ }
92
+ // A site keeps the position of its FIRST appearance, even when a later,
93
+ // richer finding is the one that survives.
94
+ const survivors = [...bySite.entries()]
95
+ .sort((left, right) => (order.get(left[0]) ?? 0) - (order.get(right[0]) ?? 0))
96
+ .map(([, entry]) => entry);
97
+ return { diagnostics: survivors, folded };
98
+ };
99
+ /**
100
+ * The report is a ranked list, not a file listing. A probability decision per
101
+ * candidate gives every finding a comparable score -- see the re-ranking cookbook
102
+ * -- so the most likely real duplication is read first. File order is the
103
+ * tiebreak, which keeps runs deterministic.
104
+ *
105
+ * @param diagnostics - the findings to order.
106
+ * @returns the findings, most likely first.
107
+ */
108
+ export const rankDiagnostics = (diagnostics) => [...diagnostics].sort((a, b) => (b.score ?? -1) - (a.score ?? -1) ||
109
+ a.location.file.localeCompare(b.location.file) ||
110
+ a.location.line - b.location.line);
111
+ const plain = {
112
+ bold: (t) => t,
113
+ dim: (t) => t,
114
+ red: (t) => t,
115
+ yellow: (t) => t,
116
+ underline: (t) => t,
117
+ };
118
+ const ansi = (on) => on
119
+ ? {
120
+ bold: (t) => `\u001b[1m${t}\u001b[0m`,
121
+ dim: (t) => `\u001b[2m${t}\u001b[0m`,
122
+ red: (t) => `\u001b[31m${t}\u001b[0m`,
123
+ yellow: (t) => `\u001b[33m${t}\u001b[0m`,
124
+ underline: (t) => `\u001b[4m${t}\u001b[0m`,
125
+ }
126
+ : plain;
127
+ /** oxlint and ESLint say "warning"; the internal severity stays short. */
128
+ const label = (severity) => (severity === "warn" ? "warning" : severity);
129
+ const plural = (count, noun) => `${count} ${noun}${count === 1 ? "" : "s"}`;
130
+ const counts = (report) => ({
131
+ errors: report.diagnostics.filter((d) => d.severity === "error").length,
132
+ warnings: report.diagnostics.filter((d) => d.severity === "warn").length,
133
+ infos: report.diagnostics.filter((d) => d.severity === "info").length,
134
+ judged: report.diagnostics.filter((d) => d.judged).length,
135
+ });
136
+ /** Findings per entropy reversal, for a machine. */
137
+ const moveCounts = (report) => {
138
+ const of = (key) => report.diagnostics.filter((diagnostic) => (diagnostic.move ?? "correctness") === key).length;
139
+ return { contract: of("contract"), combine: of("combine"), expand: of("expand"), correctness: of("correctness") };
140
+ };
141
+ const problemSummary = (report) => {
142
+ const { errors, warnings, infos } = counts(report);
143
+ const total = report.diagnostics.length;
144
+ if (total === 0)
145
+ return "0 problems";
146
+ const parts = [];
147
+ if (errors > 0)
148
+ parts.push(plural(errors, "error"));
149
+ if (warnings > 0)
150
+ parts.push(plural(warnings, "warning"));
151
+ // `info` was missing from this list, so a run whose findings were all notices
152
+ // printed as "208 problems ()" -- a summary saying nothing at the moment it has
153
+ // the most to say.
154
+ if (infos > 0)
155
+ parts.push(plural(infos, "notice"));
156
+ return `${plural(total, "problem")} (${parts.join(", ")})`;
157
+ };
158
+ /** joggle-specific tail: how much of this was actually decided, and by what. */
159
+ const provenance = (report) => {
160
+ if (report.replayed) {
161
+ return `Replayed the previous run: nothing it depends on changed across ${plural(report.files, "file")}. No analysis, no decisions, no tokens.`;
162
+ }
163
+ const { judged } = counts(report);
164
+ if (report.diagnostics.length === 0 && report.decision.requests === 0)
165
+ return "";
166
+ const { requests, calls, replayed, unavailable, inputTokens } = report.decision;
167
+ const u = unavailable > 0 ? `, ${unavailable} unavailable` : "";
168
+ const phases = report.timings
169
+ .filter((timing) => timing.ms >= 50)
170
+ .sort((a, b) => b.ms - a.ms)
171
+ .map((timing) => `${timing.phase} ${Math.round(timing.ms / 100) / 10}s`)
172
+ .join(", ");
173
+ const where = phases === "" ? "" : ` (${phases})`;
174
+ const tokens = `${inputTokens.toLocaleString("en-US")} input tokens`;
175
+ return `Finished in ${Math.round(report.elapsedMs / 100) / 10}s on ${plural(report.files, "file")} using ${plural(report.rules, "rule")}${where}. ${judged} of ${report.diagnostics.length} findings verified by the model; ${requests} decisions in ${calls} API calls, ${replayed} replayed${u}, ${tokens}.`;
176
+ };
177
+ const notes = (report) => {
178
+ // A missing key changes what the tool IS, not just what it saw, and it was
179
+ // only visible as "0 API calls" in a footer and an "(unverified)" suffix. Say
180
+ // it in a sentence.
181
+ const noKey = report.decision.unavailable > 0 && report.decision.calls === 0
182
+ ? [
183
+ "note: no model key reached the provider, so judged rules were skipped. Set TYPESAFE_API_KEY (or run with --offline to say so on purpose).",
184
+ ]
185
+ : [];
186
+ return [
187
+ ...noKey,
188
+ ...report.skipped.map((skip) => `note: ${skip.ruleId} skipped — ${skip.reason}`),
189
+ ...report.notes.map((note) => `note: ${note.ruleId} — ${note.reason}`),
190
+ ];
191
+ };
192
+ /* -------------------------------------------------------------------------- */
193
+ /* text */
194
+ /* -------------------------------------------------------------------------- */
195
+ /**
196
+ * The report grouped by entropy reversal.
197
+ *
198
+ * joggle is the entropy reverser: you press the frontier out, then look at what
199
+ * you built and ask what it can be rebuilt from. Each finding says which move it
200
+ * is -- contract a copy back to the primitive that already exists, combine
201
+ * primitives into a composition, or expand the vocabulary with a new name, type
202
+ * or boundary -- and the report prints them in the ratchet order: the copies hide
203
+ * the primitives, so contract first; composing makes them explicit; a new
204
+ * primitive is built out of the ones you can now see. A finding with no move
205
+ * checks the code against a requirement and belongs in neither.
206
+ */
207
+ const moveCensus = (report) => {
208
+ const counted = new Map();
209
+ for (const diagnostic of report.diagnostics) {
210
+ const key = diagnostic.move ?? "correctness";
211
+ counted.set(key, (counted.get(key) ?? 0) + 1);
212
+ }
213
+ const keys = [...moveOrder, "correctness"];
214
+ const rows = keys.filter((key) => (counted.get(key) ?? 0) > 0);
215
+ // One bucket is not a grouping, and a run that is all correctness gains
216
+ // nothing from a heading that says so.
217
+ if (rows.length <= 1)
218
+ return [];
219
+ const width = Math.max(...rows.map((key) => (key === "correctness" ? "correctness" : moveVocabulary[key].label).length));
220
+ const lines = ["", "by move:"];
221
+ for (const key of rows) {
222
+ const name = key === "correctness" ? "correctness" : moveVocabulary[key].label;
223
+ const blurb = key === "correctness" ? "a requirement the code does not meet" : moveVocabulary[key].blurb;
224
+ lines.push(String(counted.get(key)).padStart(5) + " " + name.padEnd(width) + " " + blurb);
225
+ }
226
+ return lines;
227
+ };
228
+ /**
229
+ * How many findings each rule produced, largest first.
230
+ *
231
+ * The flat list is right for a machine and right for CI, and it is a wall at scale:
232
+ * nine hundred findings in score order tells a reader nothing about what KIND of
233
+ * work they are being handed. This is the shape of the report, printed above the
234
+ * summary, and it is omitted when there is only one rule because a census of one
235
+ * is a line that says nothing.
236
+ */
237
+ const census = (report) => {
238
+ const byRule = new Map();
239
+ for (const diagnostic of report.diagnostics) {
240
+ const entry = byRule.get(diagnostic.ruleId) ?? { total: 0, warnings: 0, notices: 0 };
241
+ entry.total += 1;
242
+ if (diagnostic.severity === "warn")
243
+ entry.warnings += 1;
244
+ if (diagnostic.severity === "info")
245
+ entry.notices += 1;
246
+ byRule.set(diagnostic.ruleId, entry);
247
+ }
248
+ if (byRule.size <= 1)
249
+ return [];
250
+ const rows = [...byRule.entries()].sort((left, right) => right[1].total - left[1].total || left[0].localeCompare(right[0]));
251
+ const width = Math.max(...rows.map(([id]) => id.length));
252
+ const lines = ["", "by rule:"];
253
+ for (const [id, counts] of rows) {
254
+ const detail = [
255
+ counts.warnings > 0 ? plural(counts.warnings, "warning") : "",
256
+ counts.notices > 0 ? plural(counts.notices, "notice") : "",
257
+ ]
258
+ .filter((part) => part !== "")
259
+ .join(", ");
260
+ const leading = String(counts.total).padStart(5) + " " + id.padEnd(width);
261
+ lines.push(detail === "" ? leading : leading + " " + detail);
262
+ }
263
+ return lines;
264
+ };
265
+ /**
266
+ * The operation a finding proposes, when it proposes one.
267
+ *
268
+ * It goes on the same line as the problem, because the operation IS the finding:
269
+ * "merge into a.ts:8, 4 edits" is a work order, and "declared twice" is a
270
+ * complaint. A host that ignores it still gets a linter.
271
+ */
272
+ const operationNote = (diagnostic) => {
273
+ const repair = diagnostic.repair;
274
+ if (repair === undefined)
275
+ return "";
276
+ const edits = repair.cascade.length;
277
+ return ` -> ${repair.operation}, ${edits} edit${edits === 1 ? "" : "s"}`;
278
+ };
279
+ /**
280
+ * The shape of the codebase, and what this run changed.
281
+ *
282
+ * The number to watch is the concept count against the declaration count: a
283
+ * change that adds declarations without adding concepts is the entropy this tool
284
+ * exists to remove.
285
+ */
286
+ const structureLine = (structure) => {
287
+ const { concepts, declarations, duplicated, overloaded } = structure;
288
+ // A replayed report has no measurement of its own, and a zero that looks
289
+ // measured is worse than silence.
290
+ if (declarations === 0)
291
+ return "";
292
+ return `${concepts} concept${concepts === 1 ? "" : "s"} · ${declarations} declaration${declarations === 1 ? "" : "s"} · ${duplicated} duplicated · ${overloaded} overloaded`;
293
+ };
294
+ const findingLine = (d) => {
295
+ const { file, line, column } = d.location;
296
+ const help = d.help === undefined ? "" : ` help: ${d.help}`;
297
+ const score = d.score === undefined ? "" : ` (${d.score.toFixed(2)})`;
298
+ return `${file}:${line}:${column}: ${label(d.severity)} ${d.ruleId}${score}: ${d.message}${operationNote(d)}${help}`;
299
+ };
300
+ /**
301
+ * The judgement behind a finding, indented under it.
302
+ *
303
+ * The one line per finding is the work order; this is why. A reader can see
304
+ * which question moved the outcome -- "redundant 0.90, verdict collapse 0.88" --
305
+ * instead of one confidence standing in for nine answers.
306
+ */
307
+ const panelLines = (diagnostic) => {
308
+ const panel = diagnostic.panel;
309
+ if (panel === undefined || panel.answers.length === 0)
310
+ return [];
311
+ const answers = panel.answers.map((answer) => {
312
+ const probability = answer.probability === undefined ? "" : " " + answer.probability.toFixed(2);
313
+ return answer.label === undefined
314
+ ? answer.question + probability
315
+ : answer.question + " " + answer.label + probability;
316
+ });
317
+ const table = panel.derived === undefined ? "" : "; table " + panel.derived;
318
+ const agreement = panel.agreement === undefined ? "" : " (" + panel.agreement + ")";
319
+ return [" judged: " + answers.join(", ") + table + agreement];
320
+ };
321
+ const text = (report) => {
322
+ const lines = [];
323
+ // Group the findings by the reversal they propose, in the ratchet order, when
324
+ // any of them propose one. A flat list is a wall; a grouping by move is the
325
+ // question the tool exists to ask.
326
+ if (report.diagnostics.some((diagnostic) => diagnostic.move !== undefined)) {
327
+ for (const move of moveOrder) {
328
+ const findings = report.diagnostics.filter((diagnostic) => diagnostic.move === move);
329
+ if (findings.length === 0)
330
+ continue;
331
+ lines.push("");
332
+ lines.push(moveVocabulary[move].label + " — " + moveVocabulary[move].blurb);
333
+ lines.push(...findings.flatMap((diagnostic) => [findingLine(diagnostic), ...panelLines(diagnostic)]));
334
+ }
335
+ const rest = report.diagnostics.filter((diagnostic) => diagnostic.move === undefined);
336
+ if (rest.length > 0) {
337
+ lines.push("");
338
+ lines.push("correctness — a requirement the code does not meet");
339
+ lines.push(...rest.flatMap((diagnostic) => [findingLine(diagnostic), ...panelLines(diagnostic)]));
340
+ }
341
+ }
342
+ else {
343
+ lines.push(...report.diagnostics.flatMap((diagnostic) => [findingLine(diagnostic), ...panelLines(diagnostic)]));
344
+ }
345
+ if (lines.length > 0)
346
+ lines.push("");
347
+ lines.push(...moveCensus(report));
348
+ lines.push(...census(report));
349
+ lines.push(problemSummary(report));
350
+ const measured = structureLine(report.structure);
351
+ if (measured !== "")
352
+ lines.push(measured);
353
+ const provenanceLine = provenance(report);
354
+ if (provenanceLine !== "")
355
+ lines.push(provenanceLine);
356
+ lines.push(...notes(report));
357
+ return lines.join("\n");
358
+ };
359
+ /* -------------------------------------------------------------------------- */
360
+ /* stylish */
361
+ /* -------------------------------------------------------------------------- */
362
+ const stylish = (report, c) => {
363
+ const lines = [];
364
+ const byFile = new Map();
365
+ for (const diagnostic of report.diagnostics) {
366
+ const existing = byFile.get(diagnostic.location.file);
367
+ if (existing === undefined)
368
+ byFile.set(diagnostic.location.file, [diagnostic]);
369
+ else
370
+ existing.push(diagnostic);
371
+ }
372
+ for (const [file, diagnostics] of byFile) {
373
+ lines.push("");
374
+ lines.push(c.underline(file));
375
+ const where = diagnostics.map((d) => `${d.location.line}:${d.location.column}`);
376
+ const severity = diagnostics.map((d) => label(d.severity));
377
+ const whereWidth = Math.max(...where.map((w) => w.length));
378
+ const severityWidth = Math.max(...severity.map((s) => s.length));
379
+ diagnostics.forEach((diagnostic, index) => {
380
+ // Pad before colouring: ANSI escapes count as characters to padEnd.
381
+ const padded = (severity[index] ?? "").padEnd(severityWidth);
382
+ const level = diagnostic.severity === "error" ? c.red(padded) : c.yellow(padded);
383
+ const verified = diagnostic.judged ? "" : c.dim(" (unverified)");
384
+ const score = diagnostic.score === undefined ? "" : diagnostic.score.toFixed(2);
385
+ lines.push(` ${c.dim((where[index] ?? "").padEnd(whereWidth))} ${level} ${c.dim(score.padEnd(4))} ${diagnostic.message}${verified} ${c.dim(diagnostic.ruleId)}`);
386
+ });
387
+ }
388
+ const { errors } = counts(report);
389
+ const summary = problemSummary(report);
390
+ if (lines.length > 0)
391
+ lines.push("");
392
+ lines.push(errors > 0 ? c.red(`✖ ${summary}`) : c.yellow(`✖ ${summary}`));
393
+ const provenanceLine = provenance(report);
394
+ if (provenanceLine !== "")
395
+ lines.push(c.dim(provenanceLine));
396
+ lines.push(...notes(report).map((n) => c.dim(n)));
397
+ return lines.join("\n");
398
+ };
399
+ /* -------------------------------------------------------------------------- */
400
+ /* unix */
401
+ /* -------------------------------------------------------------------------- */
402
+ const unix = (report) => {
403
+ const lines = report.diagnostics.map((d) => {
404
+ const { file, line, column } = d.location;
405
+ const severity = d.severity === "error" ? "Error" : "Warning";
406
+ return `${file}:${line}:${column}: ${d.message} [${severity}/${d.ruleId}]`;
407
+ });
408
+ lines.push("");
409
+ lines.push(problemSummary(report).replace(/ \(.*\)$/, ""));
410
+ return lines.join("\n");
411
+ };
412
+ /* -------------------------------------------------------------------------- */
413
+ /* machine formats */
414
+ /* -------------------------------------------------------------------------- */
415
+ const json = (report) => JSON.stringify({
416
+ diagnostics: report.diagnostics,
417
+ summary: {
418
+ files: report.files,
419
+ rules: report.rules,
420
+ structure: report.structure,
421
+ problems: report.diagnostics.length,
422
+ ...counts(report),
423
+ byMove: moveCounts(report),
424
+ skipped: report.skipped,
425
+ notes: report.notes,
426
+ decision: report.decision,
427
+ replayed: report.replayed,
428
+ timings: report.timings,
429
+ elapsedMs: report.elapsedMs,
430
+ // The funnel, in the machine-readable format too. It was in the report and
431
+ // not in the JSON, which made the one artifact a script can read the one
432
+ // artifact that hid where the candidates went -- and reading it is how the
433
+ // gated band below was found.
434
+ drops: report.drops,
435
+ },
436
+ }, null, 2);
437
+ /** GitHub Actions workflow commands, so CI annotations come for free. */
438
+ const github = (report) => {
439
+ const lines = [];
440
+ for (const diagnostic of report.diagnostics) {
441
+ const level = Match.value(diagnostic.severity).pipe(Match.when("error", () => "error"), Match.when("warn", () => "warning"), Match.orElse(() => "notice"));
442
+ const { file, line, column } = diagnostic.location;
443
+ const body = diagnostic.help === undefined ? diagnostic.message : `${diagnostic.message} ${diagnostic.help}`;
444
+ lines.push(`::${level} file=${file},line=${line},col=${column},title=${diagnostic.ruleId}::${body.replace(/\r?\n/g, " ")}`);
445
+ }
446
+ for (const skip of report.skipped) {
447
+ lines.push(`::notice title=${skip.ruleId}::rule skipped — ${skip.reason}`);
448
+ }
449
+ return lines.join("\n");
450
+ };
451
+ /** Render a report in one of the output formats. */
452
+ export const render = (report, format, options = {}) => {
453
+ switch (format) {
454
+ case "json":
455
+ return json(report);
456
+ case "github":
457
+ return github(report);
458
+ case "unix":
459
+ return unix(report);
460
+ case "stylish":
461
+ return stylish(report, ansi(options?.color === true));
462
+ case "text":
463
+ return text(report);
464
+ }
465
+ };
466
+ /** The process exit code a report and a warning ceiling imply. */
467
+ export const exitCodeFor = (report, maxWarnings) => {
468
+ const { errors, warnings } = counts(report);
469
+ if (errors > 0)
470
+ return 1;
471
+ if (maxWarnings >= 0 && warnings > maxWarnings)
472
+ return 1;
473
+ return 0;
474
+ };
@@ -0,0 +1,132 @@
1
+ import { policy } from "./policy.js";
2
+ import { RuleAuthoringError } from "./schema.js";
3
+ import { lineStarts } from "./workspace.js";
4
+ import { lineAt } from "./cascade.js";
5
+ import { finding } from "./rule.js";
6
+ /** Declare a rule's messages. Identity, so the keys keep their literal types. */
7
+ export const messages = (registry) => registry;
8
+ const isUnit = (subject) => "location" in subject;
9
+ const isFile = (subject) => "path" in subject;
10
+ const isLocation = (subject) => "line" in subject;
11
+ /**
12
+ * A locator for one workspace.
13
+ *
14
+ * It caches each file's line starts, so many findings in one file do not each
15
+ * re-scan it, and a span's column is derived from where its line begins.
16
+ *
17
+ * @param workspace - the analysed workspace, whose files carry the text.
18
+ * @returns a function from a subject to its location.
19
+ */
20
+ export const locator = (workspace) => {
21
+ let index;
22
+ const byPath = () => {
23
+ if (index === undefined) {
24
+ index = new Map();
25
+ // A rule is tested against a stub workspace that may not carry files, and a
26
+ // subject already carrying a location never needs them.
27
+ for (const file of workspace.files ?? [])
28
+ index.set(file.path, file);
29
+ }
30
+ return index;
31
+ };
32
+ const starts = new Map();
33
+ return (subject) => {
34
+ if (isUnit(subject))
35
+ return subject.location;
36
+ if (isFile(subject))
37
+ return { file: subject.path, line: 1, column: 1 };
38
+ if (isLocation(subject)) {
39
+ return { file: subject.file, line: subject.line, column: subject.column };
40
+ }
41
+ // Absence is a local fact, not an API: a subject whose file the workspace
42
+ // does not carry still reports, at the file's first line.
43
+ let startsOfFile = starts.get(subject.file);
44
+ if (startsOfFile === undefined) {
45
+ const source = byPath().get(subject.file);
46
+ if (source === undefined) {
47
+ return { file: subject.file, line: 1, column: subject.column ?? 1 };
48
+ }
49
+ startsOfFile = lineStarts(source.text);
50
+ starts.set(subject.file, startsOfFile);
51
+ }
52
+ const line = lineAt(startsOfFile, subject.start);
53
+ const column = subject.column ?? subject.start - (startsOfFile[line - 1] ?? 0) + 1;
54
+ return { file: subject.file, line, column };
55
+ };
56
+ };
57
+ const PLACEHOLDER = /\{\{(\w+)\}\}/g;
58
+ /**
59
+ * Fill a message template, and say so when it cannot be filled.
60
+ *
61
+ * A missing id or a missing datum is a bug in the rule, not a condition of the
62
+ * code under analysis, so it throws rather than reporting a partial sentence.
63
+ * Tests catch it where it belongs.
64
+ */
65
+ const fill = (input) => input.template.replace(PLACEHOLDER, (_whole, name) => {
66
+ const value = input.data?.[name];
67
+ if (value === undefined) {
68
+ throw RuleAuthoringError.make({
69
+ ruleId: input.ruleId,
70
+ messageId: input.messageId,
71
+ detail: "the template needs data." + name,
72
+ });
73
+ }
74
+ return String(value);
75
+ });
76
+ /** Resolve a registry entry, or throw the authoring error that names the rule. */
77
+ const templateFor = (input) => {
78
+ const template = input.rule.messages?.[input.messageId];
79
+ if (template === undefined) {
80
+ throw RuleAuthoringError.make({
81
+ ruleId: input.rule.id,
82
+ messageId: input.messageId,
83
+ detail: "no message is declared with this id",
84
+ });
85
+ }
86
+ return fill({
87
+ template,
88
+ data: input.data,
89
+ ruleId: input.rule.id,
90
+ messageId: input.messageId,
91
+ });
92
+ };
93
+ /**
94
+ * A printed type cut to the length a finding's help can carry.
95
+ *
96
+ * @param value - the type as the checker printed it.
97
+ * @returns the value, or its prefix and an ellipsis when it is too long.
98
+ */
99
+ export const shortType = (value) => {
100
+ const max = policy.oneConceptOneType.maxTypeChars;
101
+ return value.length <= max ? value : value.slice(0, max) + "...";
102
+ };
103
+ /**
104
+ * Bind a rule to its messages and a locator, giving the report function a rule
105
+ * calls.
106
+ *
107
+ * @param rule - the rule, whose `messages` registry is the only place a message
108
+ * string may live.
109
+ * @param locate - how a subject becomes a location, from {@link locator}.
110
+ * @returns the report function.
111
+ */
112
+ export const reporter = (rule, locate) => (input) => {
113
+ const message = templateFor({ rule, messageId: input.messageId, data: input.data });
114
+ const help = input.helpId === undefined
115
+ ? undefined
116
+ : templateFor({ rule, messageId: input.helpId, data: input.data });
117
+ return finding({
118
+ ruleId: rule.id,
119
+ severity: input.severity ?? rule.severity,
120
+ message,
121
+ help,
122
+ location: locate(input.about),
123
+ judged: input.judged ?? rule.judged,
124
+ confidence: input.confidence,
125
+ score: input.score,
126
+ identity: input.identity,
127
+ repair: input.repair,
128
+ move: input.move ?? rule.move,
129
+ stoppedAt: input.stoppedAt,
130
+ panel: input.panel,
131
+ });
132
+ };
package/dist/result.js ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The checker's type at each recorded `return` of a declaration.
3
+ *
4
+ * The declaration-level trace joins a NAME to its type. This joins a RETURN
5
+ * EXPRESSION to its type through the node-type layer, by byte offset, which is
6
+ * the one fact a candidate filter can read before a judgement is paid for: a
7
+ * helper that returns `number` cannot be the single path for a string, and a
8
+ * function that returns `boolean` does not shorten the data its caller reads.
9
+ *
10
+ * Empty when the type layer did not run, or when the declaration records no
11
+ * `return`. An empty answer is UNKNOWN, not "no".
12
+ */
13
+ export const returnTypesOf = (unit, file, nodeTypes) => {
14
+ if (nodeTypes === undefined || file === undefined)
15
+ return [];
16
+ return file.facts.returns
17
+ .filter((site) => site.start >= unit.start && site.end <= unit.end)
18
+ .map((site) => nodeTypes(unit.file, site.start));
19
+ };
20
+ /**
21
+ * Whether a declaration can produce a value outside `excluded`.
22
+ *
23
+ * True when the answer is unknown -- no type layer, no recorded return, or a
24
+ * return the checker could not type -- because a filter must never lose a real
25
+ * candidate to save a judgement. Only a declaration whose every recorded return
26
+ * is one of `excluded` is dropped.
27
+ */
28
+ export const mayYield = (types, excluded) => types.length === 0 || types.some((type) => type === undefined || !excluded.has(type));