@autotelic/joggle 0.0.0-stage → 0.1.2

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,198 @@
1
+ import { Effect } from "effect";
2
+ import { Decision } from "effect/ai";
3
+ import { Atoms } from "../atoms.js";
4
+ import { policy } from "../policy.js";
5
+ import { verdictsOf } from "../plans.js";
6
+ import { locator, messages, reporter, shortType } from "../reporting.js";
7
+ import { verdictOf } from "../verdict.js";
8
+ import { budgetNote, inScope, outcome, qualityOf, } from "../rule.js";
9
+ const RULE_ID = "joggle/structural-collapse";
10
+ /** Which labels mean this rule is violated -- the read and the calibration share it. */
11
+ const VIOLATIONS = { verdict: ["one_concept"] };
12
+ // Two names, one type, and the compiler said so.
13
+ //
14
+ // `one-concept-one-type` starts from a NAME and asks whether its meanings
15
+ // diverged. This is the other direction: the checker proved two declarations are
16
+ // mutually assignable and share a member-sorted fingerprint, so the drift is in
17
+ // the VOCABULARY -- one concept carrying two names -- and no text comparison can
18
+ // see it. `User` and `Account` with the same members read as two things.
19
+ //
20
+ // The PROOF is the compiler's and is not asked about. The judgment is the one the
21
+ // proof cannot make: two names for one idea, or two ideas that happen to share a
22
+ // shape today? A group is only formed when the fingerprint has content (a group
23
+ // of every `any` is not a concept) and assignability holds both ways.
24
+ /** The kinds whose resolved type is a shape rather than a value. */
25
+ const isTypeLike = (unit) => unit.kind === "interface" || unit.kind === "type" || unit.kind === "class" || unit.kind === "enum";
26
+ /** The names of a group, in a stable order. */
27
+ const namesOf = (units) => [...new Set(units.map((unit) => unit.name))].sort((left, right) => left.localeCompare(right));
28
+ /** A resolved type, cut to the length a finding's help can carry. */
29
+ export const structuralCollapse = {
30
+ id: RULE_ID,
31
+ severity: "info",
32
+ description: "Differently named declarations the compiler proves are one type.",
33
+ judged: true,
34
+ move: "contract",
35
+ onUnavailable: "report",
36
+ messages: messages({
37
+ same_type: "{{names}} resolve to one type under different names.",
38
+ same_type_help: "The compiler proves them structurally identical and mutually assignable: {{structural}}. One concept should have one name; if these are two concepts, give one of them a difference the type can carry, not a second spelling of the same shape.{{tail}}{{unverified}}",
39
+ }),
40
+ plan: Effect.fn("joggle/structural-collapse")(function* (workspace, scope) {
41
+ const report = reporter(structuralCollapse, locator(workspace));
42
+ const groups = new Map();
43
+ for (const unit of workspace.units) {
44
+ if (!isTypeLike(unit))
45
+ continue;
46
+ const facts = unit.typeFacts;
47
+ if (facts === undefined || facts.identicalGroup === null)
48
+ continue;
49
+ const existing = groups.get(facts.identicalGroup);
50
+ if (existing === undefined)
51
+ groups.set(facts.identicalGroup, [unit]);
52
+ else
53
+ existing.push(unit);
54
+ }
55
+ const candidates = [...groups.values()]
56
+ // One name declared twice is `duplicate-implementation`'s finding, and it is
57
+ // the better one: there the copy is the problem. Here the vocabulary is.
58
+ .filter((group) => namesOf(group).length > 1)
59
+ .filter((group) => group.some((unit) => inScope(scope, unit.file)))
60
+ .sort((left, right) => (namesOf(left)[0] ?? "").localeCompare(namesOf(right)[0] ?? ""));
61
+ if (candidates.length === 0) {
62
+ const resolved = workspace.units.filter((unit) => unit.typeFacts !== undefined).length;
63
+ return {
64
+ plans: [],
65
+ read: () => outcome([], [
66
+ resolved === 0
67
+ ? "no declaration carried a resolved type to prove identity with"
68
+ : "no two differently named declarations were proven to be one type",
69
+ ]),
70
+ };
71
+ }
72
+ const judged = candidates.slice(0, policy.structuralCollapse.maxFindings);
73
+ const overBudget = candidates
74
+ .slice(policy.structuralCollapse.maxFindings)
75
+ .map((group) => ({
76
+ ruleId: RULE_ID,
77
+ subject: namesOf(group).join(" / "),
78
+ stage: "budget",
79
+ reason: "past the budget of " + String(policy.structuralCollapse.maxFindings) + " groups",
80
+ }));
81
+ const atoms = yield* Atoms;
82
+ const planned = yield* Effect.forEach(judged, (group) => Effect.gen(function* () {
83
+ const names = namesOf(group);
84
+ const first = [...group].sort((left, right) => left.file.localeCompare(right.file))[0];
85
+ const structural = first?.typeFacts?.structural ?? "";
86
+ const id = yield* atoms.add({
87
+ names,
88
+ structural: shortType(structural),
89
+ count: group.length,
90
+ files: [...new Set(group.map((unit) => unit.file))].slice(0, policy.evidence.maxListedPaths),
91
+ declarations: group.slice(0, policy.evidence.maxMembers).map((unit) => ({
92
+ name: unit.name,
93
+ kind: unit.kind,
94
+ file: unit.file,
95
+ line: unit.location.line,
96
+ display: shortType(unit.typeFacts?.display ?? ""),
97
+ })),
98
+ });
99
+ const plan = {
100
+ ruleId: RULE_ID,
101
+ subject: names.join(" / "),
102
+ concerns: [...new Set(group.map((unit) => unit.file))],
103
+ atoms: [id],
104
+ violations: VIOLATIONS,
105
+ decisions: {
106
+ verdict: Decision.classify({
107
+ instructions: [
108
+ "`atoms[" + id + "].declarations` are declarations with different names that the compiler proves are ONE type: they are mutually assignable in both directions and share the member-sorted fingerprint `atoms[" + id + "].structural`.",
109
+ "Is this one idea that acquired two names, or two ideas that happen to have the same shape today?",
110
+ "Answer `one_concept` when the names are two spellings of one thing: one name should be kept and imported everywhere.",
111
+ "Answer `two_concepts` when the declarations name genuinely different things that only coincide now -- a wire payload and a domain shape, a snapshot and a projection.",
112
+ ].join("\n"),
113
+ criteria: {
114
+ one_concept: "One idea, two names. Keep one name and import it.",
115
+ two_concepts: "Two ideas that share a shape. Keep both names.",
116
+ },
117
+ }),
118
+ },
119
+ read: (answers) => answers,
120
+ };
121
+ return { group, id, plan };
122
+ }));
123
+ return {
124
+ plans: planned.map((entry) => entry.plan),
125
+ read: (answers) => {
126
+ const verdicts = verdictsOf(answers);
127
+ const diagnostics = [];
128
+ const drops = [...overBudget];
129
+ planned.forEach((entry, index) => {
130
+ const { group } = entry;
131
+ const subject = namesOf(group).join(" / ");
132
+ const verdict = verdictOf(verdicts[index]?.["verdict"], VIOLATIONS.verdict);
133
+ if (verdict === undefined) {
134
+ diagnostics.push(findingFor({ report, group, confidence: undefined, unverified: "no judgement was available" }));
135
+ return;
136
+ }
137
+ if (verdict.label !== "one_concept") {
138
+ drops.push({
139
+ ruleId: RULE_ID,
140
+ subject,
141
+ stage: "declined",
142
+ reason: "the two names are two concepts that share a shape",
143
+ });
144
+ return;
145
+ }
146
+ const quality = qualityOf({
147
+ score: verdict.probability,
148
+ margin: verdict.margin,
149
+ confidence: verdict.confidence,
150
+ });
151
+ if (quality.quality === "drop") {
152
+ drops.push({ ruleId: RULE_ID, subject, stage: "gated", reason: quality.reason });
153
+ return;
154
+ }
155
+ diagnostics.push(findingFor({
156
+ report,
157
+ group,
158
+ confidence: verdict.confidence,
159
+ unverified: undefined,
160
+ review: quality.quality === "review",
161
+ }));
162
+ });
163
+ return outcome(diagnostics, budgetNote({
164
+ unitKind: "type groups",
165
+ judged: policy.structuralCollapse.maxFindings,
166
+ candidates: candidates.length,
167
+ sample: candidates
168
+ .slice(policy.structuralCollapse.maxFindings)
169
+ .map((group) => namesOf(group).join(" / ")),
170
+ }), drops);
171
+ },
172
+ };
173
+ }),
174
+ };
175
+ const findingFor = ({ report, group, confidence, unverified, review = false, }) => {
176
+ const names = namesOf(group);
177
+ const first = [...group].sort((left, right) => left.file.localeCompare(right.file))[0];
178
+ const structural = first?.typeFacts?.structural ?? "";
179
+ const files = [...new Set(group.map((unit) => unit.file))].sort((left, right) => left.localeCompare(right));
180
+ const tail = files.length <= policy.evidence.maxListedPaths
181
+ ? ""
182
+ : " Declared in " + files.slice(0, policy.evidence.maxListedPaths).join(", ") + " and more.";
183
+ return report({
184
+ about: first ?? { file: "", start: 0 },
185
+ messageId: "same_type",
186
+ data: {
187
+ names: names.map((name) => "`" + name + "`").join(", "),
188
+ structural: shortType(structural),
189
+ tail,
190
+ unverified: unverified === undefined ? "" : " Not verified: " + unverified + ".",
191
+ },
192
+ helpId: "same_type_help",
193
+ identity: [RULE_ID, names.join("\u0000")].join("\u0000"),
194
+ judged: unverified === undefined,
195
+ confidence,
196
+ severity: review ? "info" : "warn",
197
+ });
198
+ };
@@ -0,0 +1,205 @@
1
+ import { Effect } from "effect";
2
+ import { Decision } from "effect/ai";
3
+ import { Atoms } from "../atoms.js";
4
+ import { policy } from "../policy.js";
5
+ import { verdictsOf } from "../plans.js";
6
+ import { locator, messages, reporter } from "../reporting.js";
7
+ import { budgetNote, declined, marginOfAnswer, outcome, qualityOf, } from "../rule.js";
8
+ // meta-allow: no-pattern-classifier -- the operation pairs are a DECLARED convention
9
+ // in policy.temporalCoupling.pairs, not a fact derivable from the code: which
10
+ // operations acquire and release is knowledge about resource APIs, and the rule's
11
+ // judgement (is this acquire unpaired?) is still the model's. docs/rule-coupling.md.
12
+ const RULE_ID = "joggle/temporal-coupling";
13
+ /**
14
+ * A function that calls one half of a paired operation without the other.
15
+ *
16
+ * The CANDIDATE is structural and exact: a function that calls `lock` and not
17
+ * `unlock`, matched by the resolved call names inside its own span. That is a
18
+ * fact, and code computes it for free.
19
+ *
20
+ * Whether it is a problem is not a fact. `lock` may acquire a mutex, or it may
21
+ * be the name of something that is not a lock; the release may be the caller's
22
+ * job; the two names may share a stem and mean two different things. The old Rust
23
+ * tool answered that with a threshold and reported every match. The answer is a
24
+ * judgement, so the model makes it.
25
+ *
26
+ * The pairs are deliberately few. `start` and `stop` are not here: a function
27
+ * called `startTimer` calls `start`, and the `stop` lives elsewhere by design.
28
+ */
29
+ const { pairs: PAIRS } = policy.temporalCoupling;
30
+ /** The method name at the end of a resolved call: `a/b.ts#this.lock` is `lock`. */
31
+ const methodOf = (resolved) => {
32
+ const hash = resolved.lastIndexOf("#");
33
+ const name = hash === -1 ? resolved : resolved.slice(hash + 1);
34
+ const dot = name.lastIndexOf(".");
35
+ return dot === -1 ? name : name.slice(dot + 1);
36
+ };
37
+ /** The two questions about one declaration, pointing at its atom by id. */
38
+ const temporalReview = (id) => ({
39
+ verdict: Decision.classify({
40
+ instructions: [
41
+ `\`atoms[${id}].declaration.name\` calls \`atoms[${id}].declaration.present\` and not \`atoms[${id}].declaration.missing\`.`,
42
+ `Choose \`resource_needs_release\` when \`atoms[${id}].declaration.present\` acquires or opens something that \`atoms[${id}].declaration.missing\` would release or close, and the declaration does not release it another way.`,
43
+ "Choose `released_elsewhere` when the release is deliberate and elsewhere: the declaration returns the resource, or releasing is the caller's job, or another call in the declaration releases it.",
44
+ "Choose `unrelated_names` when the two names are not a pair -- they are different operations that happen to share a stem.",
45
+ "Choose `no_issue` when there is nothing to fix.",
46
+ ].join("\n"),
47
+ criteria: {
48
+ resource_needs_release: "It acquires something it must release, and does not.",
49
+ released_elsewhere: "The release is elsewhere by design.",
50
+ unrelated_names: "The names are not a pair.",
51
+ no_issue: "Nothing to fix.",
52
+ },
53
+ }),
54
+ worth_fixing: Decision.probability({
55
+ instructions: `Would the missing release cause a real problem a reviewer should fix? The declaration is \`atoms[${id}].declaration.name\` in \`atoms[${id}].declaration.path\`.`,
56
+ criteria: { false: "No, it would not.", true: "Yes, it would." },
57
+ }),
58
+ });
59
+ const candidatesIn = (workspace, scope) => {
60
+ const found = [];
61
+ for (const file of workspace.files) {
62
+ if (scope.changed !== undefined && !scope.changed.has(file.path))
63
+ continue;
64
+ for (const unit of file.units) {
65
+ if (unit.kind !== "function" || unit.calls.length === 0)
66
+ continue;
67
+ const methods = unit.calls.map(methodOf);
68
+ for (const [present, missing] of PAIRS) {
69
+ if (methods.includes(present) && !methods.includes(missing))
70
+ found.push({ unit, present, missing });
71
+ }
72
+ }
73
+ }
74
+ return found;
75
+ };
76
+ export const temporalCoupling = {
77
+ id: RULE_ID,
78
+ severity: "warn",
79
+ description: "A function that acquires something it may not release.",
80
+ judged: true,
81
+ onUnavailable: "propagate",
82
+ messages: messages({
83
+ unpaired_operations: "{{name}} calls {{present}}() without {{missing}}() in the same scope.",
84
+ unpaired_operations_help: "If {{present}} throws, {{missing}} never runs. Put them in a try/finally, or make one helper own both halves.{{review}}",
85
+ }),
86
+ plan: Effect.fn("joggle/temporal-coupling")(function* (workspace, scope) {
87
+ const report = reporter(temporalCoupling, locator(workspace));
88
+ const candidates = candidatesIn(workspace, scope);
89
+ if (candidates.length === 0) {
90
+ return {
91
+ plans: [],
92
+ read: () => outcome([], ["no function called one half of a paired operation"]),
93
+ };
94
+ }
95
+ const budget = policy.temporalCoupling.maxDeclarations;
96
+ const judged = candidates.slice(0, budget);
97
+ const label = (candidate) => candidate.unit.name + " (" + candidate.unit.file + ")";
98
+ const atoms = yield* Atoms;
99
+ const planned = [];
100
+ for (const candidate of judged) {
101
+ const id = yield* atoms.add({
102
+ declaration: {
103
+ name: candidate.unit.name,
104
+ path: candidate.unit.file,
105
+ source: candidate.unit.text.slice(0, policy.evidence.maxSourceChars),
106
+ present: candidate.present,
107
+ missing: candidate.missing,
108
+ },
109
+ });
110
+ planned.push({
111
+ candidate,
112
+ plan: {
113
+ ruleId: RULE_ID,
114
+ subject: label(candidate),
115
+ concerns: [candidate.unit.file],
116
+ atoms: [id],
117
+ violations: { verdict: ["resource_needs_release"] },
118
+ decisions: temporalReview(id),
119
+ read: (answers) => answers,
120
+ },
121
+ });
122
+ }
123
+ const overflow = candidates.slice(budget).map((candidate) => ({
124
+ ruleId: RULE_ID,
125
+ subject: label(candidate),
126
+ stage: "budget",
127
+ reason: "past the budget of " + budget + " paired-operation candidates",
128
+ }));
129
+ return {
130
+ plans: planned.map((entry) => entry.plan),
131
+ read: (answers) => {
132
+ const verdicts = verdictsOf(answers);
133
+ const diagnostics = [];
134
+ const drops = [...overflow];
135
+ planned.forEach((entry, index) => {
136
+ const candidate = entry.candidate;
137
+ const answer = verdicts[index];
138
+ if (answer === undefined) {
139
+ drops.push({
140
+ ruleId: RULE_ID,
141
+ subject: label(candidate),
142
+ stage: "unreadable",
143
+ reason: "the response did not judge this declaration",
144
+ });
145
+ return;
146
+ }
147
+ const verdict = answer["verdict"];
148
+ const worth = answer["worth_fixing"];
149
+ if (verdict === undefined || !("label" in verdict)) {
150
+ drops.push({
151
+ ruleId: RULE_ID,
152
+ subject: label(candidate),
153
+ stage: "unreadable",
154
+ reason: "the response did not contain a verdict",
155
+ });
156
+ return;
157
+ }
158
+ if (declined(verdict.label) || verdict.label === "released_elsewhere" || verdict.label === "unrelated_names") {
159
+ drops.push({
160
+ ruleId: RULE_ID,
161
+ subject: label(candidate),
162
+ stage: "declined",
163
+ reason: "the model says " + verdict.label.replace(/_/g, " "),
164
+ });
165
+ return;
166
+ }
167
+ const probability = worth !== undefined && "probability" in worth ? worth.probability : undefined;
168
+ const confidence = verdict.confidence ?? 1;
169
+ const quality = qualityOf({
170
+ score: probability ?? confidence,
171
+ margin: marginOfAnswer(verdict),
172
+ confidence,
173
+ });
174
+ if (quality.quality === "drop") {
175
+ drops.push({ ruleId: RULE_ID, subject: label(candidate), stage: "gated", reason: quality.reason });
176
+ return;
177
+ }
178
+ const review = quality.quality === "review";
179
+ diagnostics.push(report({
180
+ about: candidate.unit,
181
+ messageId: "unpaired_operations",
182
+ data: {
183
+ name: candidate.unit.name,
184
+ present: candidate.present,
185
+ missing: candidate.missing,
186
+ review: review ? " For review: " + quality.reason + "." : "",
187
+ },
188
+ helpId: "unpaired_operations_help",
189
+ identity: [RULE_ID, candidate.unit.file, candidate.unit.name, candidate.present].join("\u0000"),
190
+ confidence,
191
+ score: probability ?? confidence,
192
+ judged: true,
193
+ severity: review ? "info" : "warn",
194
+ }));
195
+ });
196
+ return outcome(diagnostics, budgetNote({
197
+ unitKind: "paired-operation candidates",
198
+ judged: budget,
199
+ candidates: candidates.length,
200
+ sample: candidates.slice(budget).map(label),
201
+ }), drops);
202
+ },
203
+ };
204
+ })
205
+ };
@@ -0,0 +1,198 @@
1
+ import { Effect, Option } from "effect";
2
+ import { Decision } from "effect/ai";
3
+ import { Atoms } from "../atoms.js";
4
+ import { policy } from "../policy.js";
5
+ import { verdictsOf } from "../plans.js";
6
+ import { locator, messages, reporter } from "../reporting.js";
7
+ import { budgetNote, inScope, outcome, qualityOf, } from "../rule.js";
8
+ import { verdictOf } from "../verdict.js";
9
+ const RULE_ID = "joggle/types-over-logic";
10
+ // A guard clause on a value whose type should carry the guarantee.
11
+ //
12
+ // The rule this repository kept needing: a problem is chased down by ADDING
13
+ // LOGIC -- another `if`, another check -- where refining a type (a brand, a
14
+ // refined schema, a non-nullable type parsed once) would make the check
15
+ // unnecessary and the class of bug impossible. `parse, don't validate` as a
16
+ // finding rather than a principle.
17
+ //
18
+ // Two facts, and neither classifies:
19
+ //
20
+ // the guard an AST `if` whose branch returns or throws, and the references
21
+ // its test names (`file.facts.guards`)
22
+ // the type the CHECKER's resolved type for that reference, from the trace
23
+ //
24
+ // An earlier version matched `if (!x)` and `x === null` against the source and
25
+ // kept a hand-written set of "wide" type names. That decided the question Jev is
26
+ // for, and it is coupled to how this repository spells a guard
27
+ // (`docs/rule-coupling.md`). The shape is syntax, the type is the checker's, and
28
+ // what it MEANS is asked.
29
+ //
30
+ // It needs the trace: without one there is no type to ask about, and the rule
31
+ // says so rather than guessing from the text. `joggle check --types`.
32
+ const carriesAnInvariant = (fact) =>
33
+ // Not a concrete object type -- a primitive, `any`, `unknown`, or a union --
34
+ // or an object that admits a missing value. Read from the checker's flags and
35
+ // union members, which are the checker's own vocabulary, not this repository's.
36
+ !fact.flags.includes("Object") ||
37
+ fact.members.some((member) => member === "null" || member === "undefined");
38
+ /** The resolved type of a reference, by its full dotted name then its last segment. */
39
+ const typeOf = ({ workspace, file, line, ref, }) => {
40
+ const found = workspace.types.at(file, line, ref) ??
41
+ workspace.types.at(file, line, ref.slice(ref.lastIndexOf(".") + 1));
42
+ return found === undefined ? Option.none() : Option.some(found);
43
+ };
44
+ export const typesOverLogic = {
45
+ id: RULE_ID,
46
+ severity: "info",
47
+ description: "A runtime guard on a value whose type should carry the guarantee.",
48
+ judged: true,
49
+ move: "expand",
50
+ onUnavailable: "report",
51
+ messages: messages({
52
+ guard_not_type: "{{name}} guards `{{value}}` (`{{declared}}`) with a check a type could carry.",
53
+ guard_not_type_help: "Parse the value once at the boundary into a narrower type -- a branded id, a validated schema type, a non-nullable type -- and every guard like this one disappears. If the check is genuinely the boundary, pin that decision so it is not asked again.{{unverified}}",
54
+ }),
55
+ plan: Effect.fn("joggle/types-over-logic")(function* (workspace, scope) {
56
+ const report = reporter(typesOverLogic, locator(workspace));
57
+ if (workspace.types.sites === 0) {
58
+ return {
59
+ plans: [],
60
+ read: () => outcome([], [
61
+ "no type trace reached this run, so a guard's value has no resolved type to ask about: run with --types",
62
+ ]),
63
+ };
64
+ }
65
+ const candidates = [];
66
+ for (const file of workspace.files) {
67
+ if (scope.changed !== undefined && !inScope(scope, file.path))
68
+ continue;
69
+ for (const guard of file.facts.guards) {
70
+ if (!guard.exits)
71
+ continue;
72
+ const unit = file.units.find((entry) => guard.start >= entry.start && guard.end <= entry.end);
73
+ if (unit === undefined)
74
+ continue;
75
+ for (const ref of guard.refs) {
76
+ const fact = typeOf({ workspace, file: file.path, line: unit.location.line, ref });
77
+ if (Option.isNone(fact) || !carriesAnInvariant(fact.value))
78
+ continue;
79
+ candidates.push({ unit, file: file.path, guard, ref, fact: fact.value });
80
+ // One question per guard: the same `if` does not become two findings.
81
+ break;
82
+ }
83
+ }
84
+ }
85
+ if (candidates.length === 0) {
86
+ return {
87
+ plans: [],
88
+ read: () => outcome([], [
89
+ "no guard clause stands in for a type on a value the checker resolved",
90
+ ]),
91
+ };
92
+ }
93
+ const budget = policy.evidence.maxMembers * 16;
94
+ const judged = candidates.slice(0, budget);
95
+ const overBudget = candidates.slice(budget).map((candidate) => ({
96
+ ruleId: RULE_ID,
97
+ subject: candidate.unit.name,
98
+ stage: "budget",
99
+ reason: "past the budget of " + String(budget) + " guards",
100
+ }));
101
+ const textOf = new Map(workspace.files.map((file) => [file.path, file.text]));
102
+ const atoms = yield* Atoms;
103
+ const planned = yield* Effect.forEach(judged, (candidate) => Effect.gen(function* () {
104
+ const text = textOf.get(candidate.file) ?? "";
105
+ const id = yield* atoms.add({
106
+ declaration: { name: candidate.unit.name, file: candidate.file, line: candidate.unit.location.line },
107
+ value: candidate.ref,
108
+ declaredType: candidate.fact.display,
109
+ guard: text.slice(candidate.guard.start, Math.min(candidate.guard.end, candidate.guard.start + 240)),
110
+ source: candidate.unit.text.slice(0, policy.evidence.maxSourceChars),
111
+ });
112
+ const plan = {
113
+ ruleId: RULE_ID,
114
+ subject: candidate.unit.name + " (" + candidate.file + ")",
115
+ concerns: [candidate.file],
116
+ atoms: [id],
117
+ violations: { verdict: ["type_should_carry_it"] },
118
+ decisions: {
119
+ verdict: Decision.classify({
120
+ instructions: [
121
+ `\`atoms[${id}].source\` is a function. It guards \`atoms[${id}].value\`, which the checker resolved to \`atoms[${id}].declaredType\`, with \`atoms[${id}].guard\`.`,
122
+ "A guard clause narrows a value the type left wide. Does the type itself establish an invariant, or is the check the boundary where the value is genuinely narrowed?",
123
+ "Answer `type_should_carry_it` when the value could be parsed once at the boundary into a narrower type -- a branded id, a validated schema type, a non-nullable type -- so that this check and every later one like it disappears and the class of bug becomes impossible.",
124
+ "Answer `boundary_check` ONLY when the function's own job is to turn untrusted input into a typed value: a raw or unparsed argument, network data, a schema decode. A function that takes an already-typed value and narrows it is NOT a boundary.",
125
+ "Answer `runtime_condition` ONLY when the guard tests state a type cannot hold: a flag, a network result, a value looked up at run time.",
126
+ ].join("\n"),
127
+ criteria: {
128
+ type_should_carry_it: "A type should carry it. Parse once at the boundary and brand it.",
129
+ boundary_check: "This is the boundary. The check establishes the type.",
130
+ runtime_condition: "Runtime state, not a type invariant.",
131
+ },
132
+ }),
133
+ },
134
+ read: (answers) => answers,
135
+ };
136
+ return { candidate, plan };
137
+ }), { concurrency: "unbounded" });
138
+ return {
139
+ plans: planned.map((entry) => entry.plan),
140
+ read: (answers) => {
141
+ const verdicts = verdictsOf(answers);
142
+ const diagnostics = [];
143
+ const drops = [...overBudget];
144
+ planned.forEach((entry, index) => {
145
+ const { candidate } = entry;
146
+ const subject = candidate.unit.name + " (" + candidate.file + ")";
147
+ const verdict = verdictOf(verdicts[index]?.["verdict"], ["type_should_carry_it"]);
148
+ if (verdict === undefined) {
149
+ diagnostics.push(findingFor(report, candidate, undefined, "no judgement was available"));
150
+ return;
151
+ }
152
+ if (verdict.label !== "type_should_carry_it") {
153
+ drops.push({
154
+ ruleId: RULE_ID,
155
+ subject,
156
+ stage: "declined",
157
+ reason: verdict.label === "boundary_check"
158
+ ? "this is the parse boundary"
159
+ : "the guard tests runtime state",
160
+ });
161
+ return;
162
+ }
163
+ const quality = qualityOf({
164
+ score: verdict.probability,
165
+ margin: verdict.margin,
166
+ confidence: verdict.confidence,
167
+ });
168
+ if (quality.quality === "drop") {
169
+ drops.push({ ruleId: RULE_ID, subject, stage: "gated", reason: quality.reason });
170
+ return;
171
+ }
172
+ diagnostics.push(findingFor(report, candidate, verdict.confidence, undefined));
173
+ });
174
+ return outcome(diagnostics, budgetNote({
175
+ unitKind: "guards",
176
+ judged: budget,
177
+ candidates: candidates.length,
178
+ sample: candidates.slice(budget).map((candidate) => candidate.unit.name),
179
+ }), drops);
180
+ },
181
+ };
182
+ }),
183
+ };
184
+ const findingFor = (report, candidate, confidence, unverifiedReason) => report({
185
+ about: { file: candidate.file, start: candidate.guard.start },
186
+ messageId: "guard_not_type",
187
+ data: {
188
+ name: candidate.unit.name,
189
+ value: candidate.ref,
190
+ declared: candidate.fact.display,
191
+ unverified: unverifiedReason === undefined ? "" : " Not verified: " + unverifiedReason + ".",
192
+ },
193
+ helpId: "guard_not_type_help",
194
+ identity: [RULE_ID, candidate.file, candidate.unit.name, candidate.ref].join("\u0000"),
195
+ judged: unverifiedReason === undefined,
196
+ confidence,
197
+ severity: "info",
198
+ });