@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,190 @@
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, inScope, outcome, qualityOf, } from "../rule.js";
8
+ import { verdictOf } from "../verdict.js";
9
+ const RULE_ID = "joggle/schema-excludes-domain-value";
10
+ export const schemaExcludesDomainValue = {
11
+ id: RULE_ID,
12
+ severity: "warn",
13
+ description: "A wire schema that cannot hold a value the domain produces.",
14
+ judged: true,
15
+ onUnavailable: "report",
16
+ messages: messages({
17
+ excludes: "`{{field}}` is `{{schema}}` in the wire schema and `{{annotation}}` in {{unit}}.",
18
+ excludes_help: "A `number` admits Infinity and NaN; `{{schema}}` does not, so an encode of one dies at the boundary and takes the whole response with it. Make the schema admit what the domain produces -- a `NullOr`, a finite guard at the producer -- or make the domain produce what the schema admits.{{unverified}}",
19
+ }),
20
+ plan: Effect.fn("joggle/schema-excludes-domain-value")(function* (workspace, scope) {
21
+ const report = reporter(schemaExcludesDomainValue, locator(workspace));
22
+ // The domain's declared fields, by name.
23
+ const domainFields = new Map();
24
+ for (const unit of workspace.units) {
25
+ if (unit.kind !== "interface" && unit.kind !== "type")
26
+ continue;
27
+ for (const [field, annotation] of unit.fieldTypes) {
28
+ const declared = annotation.replace(/\s+/g, " ").trim();
29
+ if (!declared.includes("number"))
30
+ continue;
31
+ const fields = domainFields.get(field) ?? [];
32
+ fields.push({ field, unitName: unit.name, file: unit.file, annotation: declared });
33
+ domainFields.set(field, fields);
34
+ }
35
+ }
36
+ if (domainFields.size === 0) {
37
+ return {
38
+ plans: [],
39
+ read: () => outcome([], ["no declared field is annotated `number`, so no schema can exclude one"]),
40
+ };
41
+ }
42
+ const candidates = [];
43
+ for (const file of workspace.files) {
44
+ if (scope.changed !== undefined && !inScope(scope, file.path))
45
+ continue;
46
+ for (const object of file.facts.objects) {
47
+ if (!object.declared)
48
+ continue;
49
+ for (const [field, chain] of Object.entries(object.schemas)) {
50
+ // `Finite` and `Int` exclude a value `number` admits. The frame is the
51
+ // library's; which value the producer yields is the question.
52
+ if (!chain.includes("Finite") && !chain.includes("Int"))
53
+ continue;
54
+ const domains = domainFields.get(field) ?? [];
55
+ const domain = domains.find((entry) => entry.file !== file.path) ?? domains[0];
56
+ if (domain === undefined)
57
+ continue;
58
+ candidates.push({
59
+ field,
60
+ schemaFile: file.path,
61
+ chain,
62
+ context: file.text.slice(object.start, Math.min(object.start + 200, object.start + 200)),
63
+ domain,
64
+ });
65
+ }
66
+ }
67
+ }
68
+ if (candidates.length === 0) {
69
+ return {
70
+ plans: [],
71
+ read: () => outcome([], [
72
+ "no schema field excludes a value that a domain field of the same name admits",
73
+ ]),
74
+ };
75
+ }
76
+ const budget = policy.evidence.maxMembers * 12;
77
+ const judged = candidates.slice(0, budget);
78
+ const overBudget = candidates.slice(budget).map((candidate) => ({
79
+ ruleId: RULE_ID,
80
+ subject: candidate.field,
81
+ stage: "budget",
82
+ reason: "past the budget of " + String(budget) + " schema fields",
83
+ }));
84
+ const atoms = yield* Atoms;
85
+ const planned = yield* Effect.forEach(judged, (candidate) => Effect.gen(function* () {
86
+ const id = yield* atoms.add({
87
+ field: candidate.field,
88
+ schema: { file: candidate.schemaFile, chain: [...candidate.chain], context: candidate.context },
89
+ domain: { ...candidate.domain },
90
+ });
91
+ const plan = {
92
+ ruleId: RULE_ID,
93
+ subject: candidate.field + " (" + candidate.schemaFile + ")",
94
+ concerns: [candidate.schemaFile, candidate.domain.file],
95
+ atoms: [id],
96
+ violations: { verdict: ["excludes"] },
97
+ decisions: {
98
+ verdict: Decision.classify({
99
+ instructions: [
100
+ `The wire schema declares \`atoms[${id}].field\` as \`atoms[${id}].schema.chain\` (\`atoms[${id}].schema.file\`): \`atoms[${id}].schema.context\`.`,
101
+ `The domain declares the same field as \`atoms[${id}].domain.annotation\` in \`atoms[${id}].domain.unitName\`.`,
102
+ "`number` admits Infinity and NaN; `Finite` and `Int` do not. Does the code that produces this field yield a value the schema rejects?",
103
+ "Answer `excludes` when the producer can yield Infinity, NaN or a fraction the schema rejects, so an encode of it dies at the boundary.",
104
+ "Answer `agrees` when the producer cannot: the value is guarded, computed from finite inputs, or a `number` that is always finite.",
105
+ "Answer `not_applicable` when the two fields are not the same value, or the schema is not the one that encodes it.",
106
+ ].join("\n"),
107
+ criteria: {
108
+ excludes: "The producer can yield a value the schema rejects.",
109
+ agrees: "The producer cannot; the values agree.",
110
+ not_applicable: "Not the same value, or not this schema.",
111
+ },
112
+ }),
113
+ },
114
+ read: (answers) => answers,
115
+ };
116
+ return { candidate, plan };
117
+ }), { concurrency: "unbounded" });
118
+ return {
119
+ plans: planned.map((entry) => entry.plan),
120
+ read: (answers) => {
121
+ const verdicts = verdictsOf(answers);
122
+ const diagnostics = [];
123
+ const drops = [...overBudget];
124
+ planned.forEach((entry, index) => {
125
+ const { candidate } = entry;
126
+ const subject = candidate.field + " (" + candidate.schemaFile + ")";
127
+ const verdict = verdictOf(verdicts[index]?.["verdict"], ["excludes"]);
128
+ if (verdict === undefined) {
129
+ diagnostics.push(findingFor({
130
+ report,
131
+ entry,
132
+ confidence: undefined,
133
+ unverifiedReason: "no judgement was available",
134
+ }));
135
+ return;
136
+ }
137
+ if (verdict.label !== "excludes") {
138
+ drops.push({
139
+ ruleId: RULE_ID,
140
+ subject,
141
+ stage: "declined",
142
+ reason: verdict.label === "agrees"
143
+ ? "the producer cannot yield a value the schema rejects"
144
+ : "not the same value",
145
+ });
146
+ return;
147
+ }
148
+ const quality = qualityOf({
149
+ score: verdict.probability,
150
+ margin: verdict.margin,
151
+ confidence: verdict.confidence,
152
+ });
153
+ if (quality.quality === "drop") {
154
+ drops.push({ ruleId: RULE_ID, subject, stage: "gated", reason: quality.reason });
155
+ return;
156
+ }
157
+ diagnostics.push(findingFor({
158
+ report,
159
+ entry,
160
+ confidence: verdict.confidence,
161
+ unverifiedReason: undefined,
162
+ review: quality.quality === "review",
163
+ }));
164
+ });
165
+ return outcome(diagnostics, budgetNote({
166
+ unitKind: "schema fields",
167
+ judged: budget,
168
+ candidates: candidates.length,
169
+ sample: candidates.slice(budget).map((candidate) => candidate.field),
170
+ }), drops);
171
+ },
172
+ };
173
+ }),
174
+ };
175
+ const findingFor = ({ report, entry, confidence, unverifiedReason, review = false, }) => report({
176
+ about: { file: entry.candidate.schemaFile, start: 0 },
177
+ messageId: "excludes",
178
+ data: {
179
+ field: entry.candidate.field,
180
+ schema: entry.candidate.chain.join(" > "),
181
+ annotation: entry.candidate.domain.annotation,
182
+ unit: entry.candidate.domain.unitName,
183
+ unverified: unverifiedReason === undefined ? "" : " Not verified: " + unverifiedReason + ".",
184
+ },
185
+ helpId: "excludes_help",
186
+ identity: [RULE_ID, entry.candidate.schemaFile, entry.candidate.field, entry.candidate.domain.file].join("\u0000"),
187
+ judged: unverifiedReason === undefined,
188
+ confidence,
189
+ severity: review ? "info" : "warn",
190
+ });
@@ -0,0 +1,204 @@
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
+ const RULE_ID = "joggle/shallow-module";
9
+ /**
10
+ * A file with a wide surface and little behind it.
11
+ *
12
+ * The CANDIDATE is structural: a file that exports more than a few things over a
13
+ * thin body. That is a fact, and the ratio is exact.
14
+ *
15
+ * Whether it is a problem is not. Ousterhout's deep module is a simple interface
16
+ * over a complex implementation; a wide interface over a thin one may be a grab
17
+ * bag, or it may be a barrel file, a set of type re-exports, or a module whose
18
+ * whole job is a thin facade. The old Rust tool reported every file under the
19
+ * ratio. The verdict is a judgement, so the model makes it.
20
+ *
21
+ * The export names and the source are the state: the model can see what the file
22
+ * promises, which is what decides whether the promises belong together.
23
+ */
24
+ const implementationLines = (text) => text.split("\n").filter((line) => {
25
+ const trimmed = line.trim();
26
+ if (trimmed === "")
27
+ return false;
28
+ if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*"))
29
+ return false;
30
+ if (trimmed.startsWith("import ") || trimmed.startsWith("} from "))
31
+ return false;
32
+ if (trimmed.startsWith("export interface ") || trimmed.startsWith("export type "))
33
+ return false;
34
+ return true;
35
+ }).length;
36
+ /** The two questions about one file, pointing at its atom by id. */
37
+ const moduleReview = (id) => ({
38
+ grab_bag: Decision.probability({
39
+ instructions: [
40
+ `Is \`atoms[${id}].module.path\` a grab bag rather than a module with one job?`,
41
+ `\`atoms[${id}].module.exports\` are the names it promises and \`atoms[${id}].module.implementation\` is the number of lines behind them.`,
42
+ "Answer true when the exports are unrelated things that happen to live in one file, so a reader has to open it to find out what it is for.",
43
+ "Answer false when the file has one job: a facade over a subsystem, a barrel of related types, a collection of small helpers for one domain, or a file whose thinness is deliberate.",
44
+ "A wide file is not automatically a grab bag. Judge whether the exports belong together, not how many there are.",
45
+ ].join("\n"),
46
+ criteria: {
47
+ false: "The exports belong together.",
48
+ true: "It is a grab bag.",
49
+ },
50
+ }),
51
+ job: Decision.classify({
52
+ instructions: [
53
+ `What is the single job of \`atoms[${id}].module.path\`, if it has one?`,
54
+ "Choose `no_issue` when the exports are unrelated things that happen to share a file.",
55
+ ].join("\n"),
56
+ criteria: {
57
+ facade: "A simple interface over a subsystem.",
58
+ related_helpers: "Small helpers that serve one domain.",
59
+ type_surface: "A barrel of related types or re-exports.",
60
+ no_issue: "The exports do not belong together.",
61
+ },
62
+ }),
63
+ });
64
+ export const shallowModule = {
65
+ id: RULE_ID,
66
+ severity: "info",
67
+ description: "A file with many exports and little implementation behind them.",
68
+ judged: true,
69
+ move: "expand",
70
+ onUnavailable: "propagate",
71
+ messages: messages({
72
+ grab_bag: "{{file}} exports {{exports}} thing(s) over {{lines}} implementation line(s), and they are a grab bag rather than one job.",
73
+ grab_bag_help: "A deep module is a simple interface over a complex implementation. This is the other way round. Move the exports to where their work lives, or give the file the implementation that earns them.{{review}}",
74
+ }),
75
+ plan: Effect.fn("joggle/shallow-module")(function* (workspace, scope) {
76
+ const report = reporter(shallowModule, locator(workspace));
77
+ const candidates = workspace.files.filter((file) => {
78
+ if (scope.changed !== undefined && !scope.changed.has(file.path))
79
+ return false;
80
+ const exports = file.units.filter((unit) => unit.exported).length;
81
+ if (exports < policy.shallowModule.minExports)
82
+ return false;
83
+ return implementationLines(file.text) / exports < policy.shallowModule.minDepth;
84
+ });
85
+ if (candidates.length === 0) {
86
+ return {
87
+ plans: [],
88
+ read: () => outcome([], [
89
+ "no file exported " +
90
+ policy.shallowModule.minExports +
91
+ " or more things over a thin body",
92
+ ]),
93
+ };
94
+ }
95
+ const budget = policy.shallowModule.maxFiles;
96
+ const judged = candidates.slice(0, budget);
97
+ const atoms = yield* Atoms;
98
+ const planned = [];
99
+ for (const file of judged) {
100
+ const exports = file.units.filter((unit) => unit.exported).map((unit) => unit.name);
101
+ const id = yield* atoms.add({
102
+ module: {
103
+ path: file.path,
104
+ exports,
105
+ implementation: implementationLines(file.text),
106
+ source: file.text.slice(0, policy.evidence.maxSourceChars * 4),
107
+ },
108
+ });
109
+ planned.push({
110
+ file,
111
+ plan: {
112
+ ruleId: RULE_ID,
113
+ subject: file.path,
114
+ concerns: [file.path],
115
+ atoms: [id],
116
+ violations: { grab_bag: [] },
117
+ decisions: moduleReview(id),
118
+ // The answer map IS this plan's result: one verdict per decision.
119
+ read: (answers) => answers,
120
+ },
121
+ });
122
+ }
123
+ const overflow = candidates.slice(budget).map((file) => ({
124
+ ruleId: RULE_ID,
125
+ subject: file.path,
126
+ stage: "budget",
127
+ reason: "past the budget of " + budget + " wide, thin files",
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 file = entry.file;
137
+ const answer = verdicts[index];
138
+ if (answer === undefined) {
139
+ drops.push({
140
+ ruleId: RULE_ID,
141
+ subject: file.path,
142
+ stage: "unreadable",
143
+ reason: "the response did not judge this file",
144
+ });
145
+ return;
146
+ }
147
+ const grab = answer["grab_bag"];
148
+ const job = answer["job"];
149
+ if (grab === undefined || !("probability" in grab) || job === undefined || !("label" in job)) {
150
+ drops.push({
151
+ ruleId: RULE_ID,
152
+ subject: file.path,
153
+ stage: "unreadable",
154
+ reason: "the response did not contain a verdict",
155
+ });
156
+ return;
157
+ }
158
+ if (declined(job.label)) {
159
+ drops.push({
160
+ ruleId: RULE_ID,
161
+ subject: file.path,
162
+ stage: "declined",
163
+ reason: "the exports belong together",
164
+ });
165
+ return;
166
+ }
167
+ const quality = qualityOf({
168
+ score: grab.probability,
169
+ margin: marginOfAnswer(job),
170
+ confidence: job.confidence,
171
+ });
172
+ if (quality.quality === "drop") {
173
+ drops.push({ ruleId: RULE_ID, subject: file.path, stage: "gated", reason: quality.reason });
174
+ return;
175
+ }
176
+ const review = quality.quality === "review";
177
+ const exports = file.units.filter((unit) => unit.exported).length;
178
+ diagnostics.push(report({
179
+ about: file,
180
+ messageId: "grab_bag",
181
+ data: {
182
+ file: file.path,
183
+ exports,
184
+ lines: implementationLines(file.text),
185
+ review: review ? " For review: " + quality.reason + "." : "",
186
+ },
187
+ helpId: "grab_bag_help",
188
+ identity: [RULE_ID, file.path].join("\u0000"),
189
+ confidence: job.confidence ?? 1,
190
+ score: grab.probability,
191
+ judged: true,
192
+ severity: review ? "info" : "warn",
193
+ }));
194
+ });
195
+ return outcome(diagnostics, budgetNote({
196
+ unitKind: "wide, thin files",
197
+ judged: budget,
198
+ candidates: candidates.length,
199
+ sample: candidates.slice(budget).map((file) => file.path),
200
+ }), drops);
201
+ },
202
+ };
203
+ }),
204
+ };
@@ -0,0 +1,237 @@
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, inScope, outcome, qualityOf, } from "../rule.js";
8
+ import { returnTypesOf } from "../result.js";
9
+ import { verdictOf } from "../verdict.js";
10
+ const RULE_ID = "joggle/single-path";
11
+ /**
12
+ * Whether a printed return type can BE a string.
13
+ *
14
+ * The filter above removes the scalars; this keeps only the helpers whose return
15
+ * is a string, so an object, a `Set<string>` or a `string[]` is not offered just
16
+ * because a `string` appears somewhere inside it. `Set<string>` is not a string
17
+ * and cannot be the single string path; `string`, `string | undefined` and
18
+ * `Promise<string>` are.
19
+ */
20
+ const stringCapable = (type) => {
21
+ const trimmed = type.trim();
22
+ return trimmed === "string" || trimmed === "Promise<string>" || trimmed.split("|").some((member) => member.trim() === "string");
23
+ };
24
+ /**
25
+ * Whether a declaration's recorded returns leave it a candidate.
26
+ *
27
+ * Unknown -- no type layer, no recorded return, an untyped return -- keeps the
28
+ * helper: a filter must never lose a real path. A helper whose every recorded
29
+ * return is a known non-string type is not the single string path.
30
+ */
31
+ const canBuildString = (types) => types.length === 0 || types.some((type) => type === undefined || stringCapable(type));
32
+ /** How many files call each declaration, from the resolved call graph. */
33
+ const callersOf = (workspace) => {
34
+ const callerFiles = new Map();
35
+ for (const unit of workspace.units) {
36
+ for (const call of unit.calls) {
37
+ const files = callerFiles.get(call) ?? new Set();
38
+ files.add(unit.file);
39
+ callerFiles.set(call, files);
40
+ }
41
+ }
42
+ return callerFiles;
43
+ };
44
+ export const singlePath = {
45
+ id: RULE_ID,
46
+ severity: "warn",
47
+ description: "A value built longhand beside the helper that already builds it.",
48
+ judged: true,
49
+ move: "contract",
50
+ onUnavailable: "report",
51
+ messages: messages({
52
+ inline_derivation: "{{unit}} builds a string here (`{{snippet}}`) though this file already uses {{helpers}}.",
53
+ inline_derivation_help: "Call the helper instead of building the string here, if it produces the same value. Two spellings of one display value drift: the second rounds differently, keeps a sign on a zero, or uses another locale, and the difference is invisible until two screens are compared.{{unverified}}",
54
+ }),
55
+ plan: Effect.fn("joggle/single-path")(function* (workspace, scope, context) {
56
+ const report = reporter(singlePath, locator(workspace));
57
+ const callerFiles = callersOf(workspace);
58
+ const byIdentity = new Map();
59
+ for (const unit of workspace.units)
60
+ byIdentity.set(unit.file + "#" + unit.name, unit);
61
+ const textOf = new Map(workspace.files.map((file) => [file.path, file.text]));
62
+ const filesByPath = new Map(workspace.files.map((file) => [file.path, file]));
63
+ const candidates = [];
64
+ for (const file of workspace.files) {
65
+ if (scope.changed !== undefined && !inScope(scope, file.path))
66
+ continue;
67
+ // The helpers this file already calls and other files call too: a function
68
+ // the file uses is a function it can use again, and a helper only this file
69
+ // calls is not yet a shared path.
70
+ const used = new Set();
71
+ for (const unit of file.units)
72
+ for (const call of unit.calls)
73
+ used.add(call);
74
+ const helpers = [];
75
+ for (const identity of used) {
76
+ const callers = callerFiles.get(identity);
77
+ if (callers === undefined || callers.size < 2)
78
+ continue;
79
+ const declaration = byIdentity.get(identity);
80
+ if (declaration === undefined)
81
+ continue;
82
+ if (!canBuildString(returnTypesOf(declaration, filesByPath.get(declaration.file), context.nodeTypes)))
83
+ continue;
84
+ helpers.push({
85
+ name: declaration.name,
86
+ file: declaration.file,
87
+ body: declaration.text.slice(0, 240),
88
+ });
89
+ }
90
+ if (helpers.length === 0)
91
+ continue;
92
+ const bounded = helpers.slice(0, policy.evidence.maxMembers);
93
+ const helperNames = new Set(helpers.map((helper) => helper.name));
94
+ for (const unit of file.units) {
95
+ if (helperNames.has(unit.name))
96
+ continue; // the helper is where the string belongs
97
+ if (unit.text.length > policy.evidence.maxSourceChars)
98
+ continue;
99
+ for (const site of file.facts.stringSites) {
100
+ if (site.start < unit.start || site.end > unit.end)
101
+ continue;
102
+ candidates.push({ unit, file: file.path, site, helpers: bounded });
103
+ }
104
+ }
105
+ }
106
+ if (candidates.length === 0) {
107
+ return {
108
+ plans: [],
109
+ read: () => outcome([], [
110
+ "no file builds a string while calling a helper that more than one file uses, so there was no single path to compare it with",
111
+ ]),
112
+ };
113
+ }
114
+ const budget = policy.evidence.maxMembers * 16;
115
+ const judged = candidates.slice(0, budget);
116
+ const overBudget = candidates.slice(budget).map((candidate) => ({
117
+ ruleId: RULE_ID,
118
+ subject: candidate.unit.name,
119
+ stage: "budget",
120
+ reason: "past the budget of " + String(budget) + " string sites",
121
+ }));
122
+ const atoms = yield* Atoms;
123
+ const planned = yield* Effect.forEach(judged, (candidate) => Effect.gen(function* () {
124
+ const text = textOf.get(candidate.file) ?? "";
125
+ const id = yield* atoms.add({
126
+ site: {
127
+ unit: candidate.unit.name,
128
+ file: candidate.file,
129
+ refs: [...candidate.site.refs],
130
+ source: text.slice(candidate.site.start, Math.min(candidate.site.end, candidate.site.start + 160)),
131
+ },
132
+ helpers: [...candidate.helpers],
133
+ });
134
+ const plan = {
135
+ ruleId: RULE_ID,
136
+ subject: candidate.unit.name + " (" + candidate.file + ")",
137
+ concerns: [candidate.file, ...candidate.helpers.map((helper) => helper.file)],
138
+ atoms: [id],
139
+ violations: { verdict: ["reimplements"] },
140
+ decisions: {
141
+ verdict: Decision.classify({
142
+ instructions: [
143
+ `\`atoms[${id}].site.source\`, in \`atoms[${id}].site.unit\`, builds a string. The references it interpolates are \`atoms[${id}].site.refs\`.`,
144
+ `These helpers are already used in this file and across files: \`atoms[${id}].helpers\` (each with its body).`,
145
+ "Does the inline string re-implement one of them?",
146
+ "Answer `reimplements` when a listed helper produces the same value and the site should call it -- the rounding, the sign, the locale or the zero are the same question asked twice.",
147
+ "Answer `legitimate_local` when no listed helper covers this case: a different unit, locale or format, or a value a helper would render wrongly.",
148
+ "Answer `not_a_derivation` when the string is not a derived display value at all.",
149
+ ].join("\n"),
150
+ criteria: {
151
+ reimplements: "One of the helpers does this. Call it.",
152
+ legitimate_local: "No helper covers this case.",
153
+ not_a_derivation: "Not a derived display value.",
154
+ },
155
+ }),
156
+ },
157
+ read: (answers) => answers,
158
+ };
159
+ return { candidate, plan };
160
+ }), { concurrency: "unbounded" });
161
+ return {
162
+ plans: planned.map((entry) => entry.plan),
163
+ read: (answers) => {
164
+ const verdicts = verdictsOf(answers);
165
+ const diagnostics = [];
166
+ const drops = [...overBudget];
167
+ planned.forEach((entry, index) => {
168
+ const { candidate } = entry;
169
+ const subject = candidate.unit.name + " (" + candidate.file + ")";
170
+ const verdict = verdictOf(verdicts[index]?.["verdict"], ["reimplements"]);
171
+ if (verdict === undefined) {
172
+ diagnostics.push(findingFor({
173
+ report,
174
+ entry,
175
+ confidence: undefined,
176
+ unverifiedReason: "no judgement was available",
177
+ }));
178
+ return;
179
+ }
180
+ if (verdict.label !== "reimplements") {
181
+ drops.push({
182
+ ruleId: RULE_ID,
183
+ subject,
184
+ stage: "declined",
185
+ reason: verdict.label === "legitimate_local"
186
+ ? "no helper covers this case"
187
+ : "not a derived display value",
188
+ });
189
+ return;
190
+ }
191
+ const quality = qualityOf({
192
+ score: verdict.probability,
193
+ margin: verdict.margin,
194
+ confidence: verdict.confidence,
195
+ });
196
+ if (quality.quality === "drop") {
197
+ drops.push({ ruleId: RULE_ID, subject, stage: "gated", reason: quality.reason });
198
+ return;
199
+ }
200
+ const review = quality.quality === "review";
201
+ diagnostics.push(findingFor({
202
+ report,
203
+ entry,
204
+ confidence: verdict.confidence,
205
+ unverifiedReason: undefined,
206
+ review,
207
+ }));
208
+ });
209
+ return outcome(diagnostics, budgetNote({
210
+ unitKind: "string sites",
211
+ judged: budget,
212
+ candidates: candidates.length,
213
+ sample: candidates.slice(budget).map((candidate) => candidate.unit.name),
214
+ }), drops);
215
+ },
216
+ };
217
+ }),
218
+ };
219
+ const findingFor = ({ report, entry, confidence, unverifiedReason, review = false, }) => {
220
+ const names = entry.candidate.helpers.slice(0, 4).map((helper) => helper.name);
221
+ const listed = names.length <= 1 ? (names[0] ?? "a helper") : names.slice(0, -1).join(", ") + " or " + names.at(-1);
222
+ return report({
223
+ about: { file: entry.candidate.file, start: entry.candidate.site.start },
224
+ messageId: "inline_derivation",
225
+ data: {
226
+ unit: entry.candidate.unit.name,
227
+ snippet: entry.candidate.site.refs.join(", "),
228
+ helpers: listed,
229
+ unverified: unverifiedReason === undefined ? "" : " Not verified: " + unverifiedReason + ".",
230
+ },
231
+ helpId: "inline_derivation_help",
232
+ identity: [RULE_ID, entry.candidate.file, entry.candidate.unit.name, String(entry.candidate.site.start)].join("\u0000"),
233
+ judged: unverifiedReason === undefined,
234
+ confidence,
235
+ severity: review ? "info" : "warn",
236
+ });
237
+ };