@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,373 @@
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 { verdictOf } from "../verdict.js";
8
+ import { budgetNote, outcome, qualityOf, } from "../rule.js";
9
+ import { words } from "../candidates.js";
10
+ const RULE_ID = "joggle/field-type-drift";
11
+ /** Which labels mean this rule is violated -- the read and the calibration share it. */
12
+ const VIOLATIONS = { verdict: ["drift", "two_concepts"] };
13
+ // One field name declared with two incompatible types.
14
+ //
15
+ // A field name is a promise about meaning. When `projectId` is a `string` in one
16
+ // declaration and a `number` in another, code that moves between them compiles
17
+ // against whichever it imported and fails against the other.
18
+ //
19
+ // What is deterministic is the detection. Field types are compared after the
20
+ // index's own resolution (indexed access, local alias, union), a nullability
21
+ // difference counts, raw mirrors are skipped, and only declarations that can
22
+ // reach each other are related. What is a JUDGEMENT is what the disagreement
23
+ // means: one concept declared twice, two concepts sharing a name, or a deliberate
24
+ // difference that breaks nothing.
25
+ //
26
+ // That judgement is the one this rule used to make for the reader, and it is the
27
+ // reason the migration is cautious: an earlier experiment asking a concept
28
+ // question here produced MORE findings, not fewer (the model answered "one
29
+ // concept" about 85% of the time), so the question is worded to let it decline
30
+ // (`compatible`) and a non-decisive answer is flagged rather than printed. See
31
+ // `docs/type-resolution.md`.
32
+ const related = ({ one, two, workspace, reachable, isTest, }) => {
33
+ if (one.file === two.file)
34
+ return true;
35
+ if (isTest(one.file) !== isTest(two.file))
36
+ return false;
37
+ if (reachable.has(one.file + "\u0000" + two.file))
38
+ return true;
39
+ if (reachable.has(two.file + "\u0000" + one.file))
40
+ return true;
41
+ const packageOf = (file) => {
42
+ const cut = file.lastIndexOf("/");
43
+ return workspace.manifests.get(cut === -1 ? "." : file.slice(0, cut))?.name ?? "";
44
+ };
45
+ const leftPackage = packageOf(one.file);
46
+ return leftPackage !== "" && leftPackage === packageOf(two.file);
47
+ };
48
+ export const fieldTypeDrift = {
49
+ id: RULE_ID,
50
+ severity: "warn",
51
+ description: "One field name declared with different, incompatible types.",
52
+ judged: true,
53
+ move: "expand",
54
+ onUnavailable: "report",
55
+ messages: messages({
56
+ two_types: "{{unit}} has a field declared with two incompatible types.",
57
+ single_drift: "`{{field}}` is `{{leftType}}` in {{leftUnit}} and `{{rightType}}` in {{rightUnit}}.",
58
+ many_drifts: "{{count}} field(s) of {{unit}} disagree with another declaration: {{fields}}.",
59
+ value_drift: "`{{field}}` allows {{leftValues}} in {{leftUnit}} and {{rightValues}} in {{rightUnit}}.",
60
+ value_drift_help: "{{lead}}The value sets differ, so a value that is valid in one declaration is not valid in the other.{{unverified}}",
61
+ drift_help: "{{lead}}{{where}}.{{unverified}}",
62
+ }),
63
+ plan: Effect.fn("joggle/field-type-drift")(function* (workspace, scope) {
64
+ const report = reporter(fieldTypeDrift, locator(workspace));
65
+ const byField = new Map();
66
+ for (const unit of workspace.units) {
67
+ if (unit.kind !== "interface" && unit.kind !== "type")
68
+ continue;
69
+ // The field LIST is the declaration's own; the field's TYPE is the
70
+ // compiler's when there is one. An annotation is what the author promised,
71
+ // and the resolved member is what the compiler enforces -- indexed access,
72
+ // local aliases and imported re-exports all collapse to one printed type,
73
+ // which is the comparison this rule has always been trying to make.
74
+ const resolved = unit.typeFacts;
75
+ for (const [field, annotation] of unit.fieldTypes) {
76
+ const member = resolved?.members.find((entry) => entry.name === field);
77
+ const type = member === undefined
78
+ ? annotation.replace(/^\s*:\s*/, "").replace(/\s+/g, " ").trim()
79
+ : member.type;
80
+ if (type === "" || type === field)
81
+ continue;
82
+ const types = byField.get(field) ?? new Map();
83
+ const declarations = types.get(type) ?? [];
84
+ declarations.push({
85
+ type,
86
+ variants: member === undefined ? [] : member.variants,
87
+ unitName: unit.name,
88
+ file: unit.file,
89
+ line: unit.location.line,
90
+ });
91
+ types.set(type, declarations);
92
+ byField.set(field, types);
93
+ }
94
+ }
95
+ if (byField.size === 0) {
96
+ return {
97
+ plans: [],
98
+ read: () => outcome([], ["no interface or type alias declared a field with a type to compare"]),
99
+ };
100
+ }
101
+ const reachable = new Set();
102
+ for (const edge of workspace.imports.edges) {
103
+ if (edge.resolution === "resolved")
104
+ reachable.add(edge.importer + "\u0000" + edge.to);
105
+ }
106
+ const isTest = (file) => policy.testFiles.test(file);
107
+ const minWords = policy.fieldTypeDrift.minWords;
108
+ // Group by the declaration the finding is anchored to: a type with five
109
+ // drifting fields is one thing a reader has to decide, not five.
110
+ const groups = new Map();
111
+ let unrelated = 0;
112
+ let drifted = 0;
113
+ // The fact this rule collects: one field name whose declared annotation
114
+ // differs between two declarations. Whether that difference is drift or a
115
+ // deliberate variant is the QUESTION -- this used to be decided in code, by a
116
+ // little text type-parser (a word-subset test for compatibility, a regex for
117
+ // `null`, name patterns for raw mirrors), which is meaning decided in code
118
+ // (docs/rule-coupling.md). The generator keeps the fact; the model keeps the
119
+ // judgement it was already being asked for.
120
+ for (const [field, types] of byField) {
121
+ if (types.size < 2)
122
+ continue;
123
+ // A single-word field is a generic slot: `id`, `name`, `type`, `files`
124
+ // mean whatever their declaration says, and two of them with different
125
+ // types are two concepts, not one that drifted. A name of two words or
126
+ // more is a concept -- `supervisorRate`, `regularPayTotal` -- and one
127
+ // concept with two types is the defect. The policy says this; the rule
128
+ // read the map and forgot it, so every `paths`, `id` and `plan` in the
129
+ // tree was compared as if it named a concept.
130
+ if (words(field).length < minWords)
131
+ continue;
132
+ const entries = [...types.values()]
133
+ .map((declarations) => declarations[0])
134
+ .filter((declaration) => declaration !== undefined);
135
+ let chosen;
136
+ for (let left = 0; left < entries.length && chosen === undefined; left += 1) {
137
+ for (let right = left + 1; right < entries.length; right += 1) {
138
+ const one = entries[left];
139
+ const two = entries[right];
140
+ if (one === undefined || two === undefined)
141
+ continue;
142
+ if (one.file === two.file && one.unitName === two.unitName)
143
+ continue;
144
+ if (!related({ one, two, workspace, reachable, isTest })) {
145
+ unrelated += 1;
146
+ continue;
147
+ }
148
+ chosen = [one, two];
149
+ break;
150
+ }
151
+ }
152
+ if (chosen === undefined)
153
+ continue;
154
+ const left = chosen[0];
155
+ const right = chosen[1];
156
+ if (scope.changed !== undefined && !(scope.changed.has(left.file) || scope.changed.has(right.file))) {
157
+ continue;
158
+ }
159
+ drifted += 1;
160
+ const key = left.file + "\u0000" + String(left.line);
161
+ const group = groups.get(key) ?? { file: left.file, line: left.line, unitName: left.unitName, drifts: [] };
162
+ group.drifts.push({ field, oneDecl: left, twoDecl: right });
163
+ groups.set(key, group);
164
+ }
165
+ if (groups.size === 0) {
166
+ return {
167
+ plans: [],
168
+ read: () => outcome([], [
169
+ byField.size + " field name(s) across the type declarations; none with incompatible types" +
170
+ (unrelated > 0
171
+ ? ", " + unrelated + " skipped because the declarations cannot reach each other"
172
+ : ""),
173
+ ]),
174
+ };
175
+ }
176
+ const candidates = [...groups.values()];
177
+ const judged = candidates.slice(0, policy.fieldTypeDrift.maxFindings);
178
+ const overBudget = candidates
179
+ .slice(policy.fieldTypeDrift.maxFindings)
180
+ .map((group) => ({
181
+ ruleId: RULE_ID,
182
+ subject: group.unitName + " (" + group.file + ":" + String(group.line) + ")",
183
+ stage: "budget",
184
+ reason: "past the budget of " + String(policy.fieldTypeDrift.maxFindings) + " declarations",
185
+ }));
186
+ const atoms = yield* Atoms;
187
+ const planned = yield* Effect.forEach(judged, (group) => Effect.gen(function* () {
188
+ // The state is the drifts themselves, bounded, each with the two
189
+ // declarations and the resolved types, which is what the question needs.
190
+ const drifts = group.drifts.slice(0, 5).map((drift) => ({
191
+ field: drift.field,
192
+ left: {
193
+ unit: drift.oneDecl.unitName,
194
+ file: drift.oneDecl.file,
195
+ line: drift.oneDecl.line,
196
+ type: drift.oneDecl.type,
197
+ values: drift.oneDecl.variants,
198
+ },
199
+ right: {
200
+ unit: drift.twoDecl.unitName,
201
+ file: drift.twoDecl.file,
202
+ line: drift.twoDecl.line,
203
+ type: drift.twoDecl.type,
204
+ values: drift.twoDecl.variants,
205
+ },
206
+ }));
207
+ const id = yield* atoms.add({ declaration: { unit: group.unitName, file: group.file, line: group.line }, drifts });
208
+ const plan = {
209
+ ruleId: RULE_ID,
210
+ subject: group.unitName + " (" + group.file + ":" + String(group.line) + ")",
211
+ concerns: [...new Set(group.drifts.flatMap((drift) => [drift.oneDecl.file, drift.twoDecl.file]))],
212
+ atoms: [id],
213
+ violations: VIOLATIONS,
214
+ decisions: {
215
+ verdict: Decision.classify({
216
+ instructions: [
217
+ `\`atoms[${id}].drifts\` lists field(s) declared with two different types in two declarations that can reach each other.`,
218
+ "What does each disagreement mean?",
219
+ "Answer `drift` when the same concept is written with two incompatible types, so code that moves between the declarations breaks.",
220
+ "Answer `two_concepts` when one name has been reused for two different things, so one of them should be renamed.",
221
+ "Answer `compatible` when the difference is deliberate and nothing breaks -- a raw or unparsed mirror, a wider or partial variant, a type that only reads differently.",
222
+ "When a side has a non-empty `values` list, that is the exact set the declaration allows. Two sets where one contains the other are one vocabulary written incompletely; two disjoint sets are two vocabularies sharing a field name.",
223
+ ].join("\n"),
224
+ criteria: {
225
+ drift: "One concept, two incompatible types. Share one declaration of it.",
226
+ two_concepts: "One name, two different things. Rename one.",
227
+ compatible: "A deliberate difference. Nothing breaks.",
228
+ },
229
+ }),
230
+ },
231
+ read: (answers) => answers,
232
+ };
233
+ return { group, id, plan };
234
+ }), { concurrency: "unbounded" });
235
+ return {
236
+ plans: planned.map((value) => value.plan),
237
+ read: (answers) => {
238
+ const verdicts = verdictsOf(answers);
239
+ const diagnostics = [];
240
+ const drops = [...overBudget];
241
+ planned.forEach((value, index) => {
242
+ const { group } = value;
243
+ const subject = group.unitName + " (" + group.file + ":" + String(group.line) + ")";
244
+ const answer = verdicts[index];
245
+ const verdict = verdictOf(answer?.["verdict"], VIOLATIONS.verdict);
246
+ if (verdict === undefined) {
247
+ diagnostics.push(findingFor({
248
+ report,
249
+ group,
250
+ confidence: undefined,
251
+ unverifiedReason: "no judgement was available",
252
+ }));
253
+ return;
254
+ }
255
+ if (verdict.label !== "drift" && verdict.label !== "two_concepts") {
256
+ drops.push({
257
+ ruleId: RULE_ID,
258
+ subject,
259
+ stage: "declined",
260
+ reason: "the difference is deliberate and nothing breaks",
261
+ });
262
+ return;
263
+ }
264
+ const quality = qualityOf({
265
+ score: verdict.probability,
266
+ margin: verdict.margin,
267
+ confidence: verdict.confidence,
268
+ });
269
+ if (quality.quality === "drop") {
270
+ drops.push({
271
+ ruleId: RULE_ID,
272
+ subject,
273
+ stage: "gated",
274
+ reason: quality.reason,
275
+ });
276
+ return;
277
+ }
278
+ const review = quality.quality === "review";
279
+ const renamed = verdict.label === "two_concepts";
280
+ diagnostics.push(findingFor({
281
+ report,
282
+ group,
283
+ confidence: verdict.confidence,
284
+ unverifiedReason: undefined,
285
+ renamed,
286
+ review,
287
+ }));
288
+ });
289
+ return outcome(diagnostics, [
290
+ byField.size + " field name(s) across the type declarations; " + drifted + " with incompatible types",
291
+ ...(unrelated > 0
292
+ ? [
293
+ unrelated +
294
+ " were skipped: the two declarations are in different packages and neither imports the other",
295
+ ]
296
+ : []),
297
+ ...budgetNote({
298
+ unitKind: "declarations",
299
+ judged: policy.fieldTypeDrift.maxFindings,
300
+ candidates: candidates.length,
301
+ sample: candidates
302
+ .slice(policy.fieldTypeDrift.maxFindings)
303
+ .map((group) => group.unitName),
304
+ }),
305
+ ], drops);
306
+ },
307
+ };
308
+ }),
309
+ };
310
+ const findingFor = ({ report, group, confidence, unverifiedReason, renamed = false, review = false, }) => {
311
+ const first = group.drifts[0];
312
+ if (first === undefined) {
313
+ return report({
314
+ about: { file: group.file, line: group.line, column: 1 },
315
+ messageId: "two_types",
316
+ data: { unit: group.unitName },
317
+ judged: false,
318
+ });
319
+ }
320
+ const where = group.drifts
321
+ .map((drift) => drift.field +
322
+ ": " +
323
+ drift.oneDecl.file +
324
+ ":" +
325
+ String(drift.oneDecl.line) +
326
+ " and " +
327
+ drift.twoDecl.file +
328
+ ":" +
329
+ String(drift.twoDecl.line))
330
+ .join("; ");
331
+ const listed = group.drifts
332
+ .slice(0, 3)
333
+ .map((drift) => "`" + drift.field + "` (`" + drift.oneDecl.type + "` vs `" + drift.twoDecl.type + "`)")
334
+ .join(", ") +
335
+ (group.drifts.length > 3 ? ", and " + String(group.drifts.length - 3) + " more" : "");
336
+ // A value set is a stronger sentence than a type: when both sides were proven
337
+ // literal, the finding names the values, because that is what a reader has to
338
+ // reconcile and what a type comparison cannot see.
339
+ const provenValues = first.oneDecl.variants.length > 0 &&
340
+ first.twoDecl.variants.length > 0 &&
341
+ group.drifts.length === 1;
342
+ return report({
343
+ about: { file: group.file, line: group.line, column: 1 },
344
+ messageId: provenValues ? "value_drift" : group.drifts.length === 1 ? "single_drift" : "many_drifts",
345
+ data: {
346
+ unit: group.unitName,
347
+ count: group.drifts.length,
348
+ fields: listed,
349
+ field: first.field,
350
+ leftType: first.oneDecl.type,
351
+ leftUnit: first.oneDecl.unitName,
352
+ rightType: first.twoDecl.type,
353
+ rightUnit: first.twoDecl.unitName,
354
+ leftValues: first.oneDecl.variants.join(" | "),
355
+ rightValues: first.twoDecl.variants.join(" | "),
356
+ lead: renamed
357
+ ? "One name, two different things. Rename one of them so each field name means one thing. "
358
+ : "One field name, two incompatible types. If they are one concept, share one declaration of it; if they are two concepts, give them two names. ",
359
+ where,
360
+ unverified: unverifiedReason === undefined ? "" : " Not verified: " + unverifiedReason + ".",
361
+ },
362
+ helpId: provenValues ? "value_drift_help" : "drift_help",
363
+ identity: [
364
+ RULE_ID,
365
+ group.file,
366
+ String(group.line),
367
+ ...group.drifts.map((drift) => drift.field).sort((left, right) => left.localeCompare(right)),
368
+ ].join("\u0000"),
369
+ judged: unverifiedReason === undefined,
370
+ confidence,
371
+ severity: review ? "info" : "warn",
372
+ });
373
+ };
@@ -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 } from "../reporting.js";
7
+ import { budgetNote, inScope, outcome, qualityOf, } from "../rule.js";
8
+ import { verdictOf } from "../verdict.js";
9
+ const RULE_ID = "joggle/generic-carries-a-caller";
10
+ export const genericCarriesACaller = {
11
+ id: RULE_ID,
12
+ severity: "warn",
13
+ description: "A shared unit that states one caller's fact.",
14
+ judged: true,
15
+ move: "expand",
16
+ onUnavailable: "report",
17
+ messages: messages({
18
+ caller_fact: '{{unit}} writes "{{value}}" though {{count}} file(s) use it.',
19
+ caller_fact_help: "Pass it in. A unit two callers share cannot know one caller's label, route or copy: the next caller gets the first caller's words, and the fix is a parameter rather than a second literal.{{unverified}}",
20
+ }),
21
+ plan: Effect.fn("joggle/generic-carries-a-caller")(function* (workspace, scope) {
22
+ const report = reporter(genericCarriesACaller, locator(workspace));
23
+ // Who uses a unit: the files that CALL it and the files that RENDER it. A
24
+ // JSX component is rendered, not called, so a graph built from calls alone
25
+ // would miss exactly the review case -- a shared `<YearColumns>` footer.
26
+ const callerFiles = new Map();
27
+ const addCaller = (key, file) => {
28
+ const files = callerFiles.get(key) ?? new Set();
29
+ files.add(file);
30
+ callerFiles.set(key, files);
31
+ };
32
+ for (const unit of workspace.units) {
33
+ for (const call of unit.calls)
34
+ addCaller(call, unit.file);
35
+ }
36
+ for (const file of workspace.files) {
37
+ for (const name of file.facts.jsx)
38
+ addCaller(name, file.path);
39
+ }
40
+ const candidates = [];
41
+ for (const file of workspace.files) {
42
+ if (scope.changed !== undefined && !inScope(scope, file.path))
43
+ continue;
44
+ for (const unit of file.units) {
45
+ if (!unit.exported)
46
+ continue;
47
+ if (unit.text.length > policy.evidence.maxSourceChars)
48
+ continue;
49
+ const byIdentity = callerFiles.get(unit.file + "#" + unit.name) ?? new Set();
50
+ const byName = callerFiles.get(unit.name) ?? new Set();
51
+ const callers = [...new Set([...byIdentity, ...byName])].filter((caller) => caller !== unit.file);
52
+ if (callers.length < 2)
53
+ continue;
54
+ const inside = file.facts.literals.filter((literal) => literal.start >= unit.start &&
55
+ literal.end <= unit.end &&
56
+ // A word, not a path or a symbol: the shape of a piece of copy.
57
+ literal.value.length >= 4 &&
58
+ literal.value.split("").some((character) => character >= "a" && character <= "z"));
59
+ for (const literal of inside.slice(0, 3)) {
60
+ candidates.push({
61
+ unit,
62
+ value: literal.value,
63
+ start: literal.start,
64
+ callers: callers.slice(0, policy.evidence.maxMembers).map((caller) => ({ file: caller })),
65
+ });
66
+ }
67
+ }
68
+ }
69
+ if (candidates.length === 0) {
70
+ return {
71
+ plans: [],
72
+ read: () => outcome([], [
73
+ "no shared unit writes a string while two or more files depend on it",
74
+ ]),
75
+ };
76
+ }
77
+ const budget = policy.evidence.maxMembers * 12;
78
+ const judged = candidates.slice(0, budget);
79
+ const overBudget = candidates.slice(budget).map((candidate) => ({
80
+ ruleId: RULE_ID,
81
+ subject: candidate.unit.name,
82
+ stage: "budget",
83
+ reason: "past the budget of " + String(budget) + " shared literals",
84
+ }));
85
+ const textOf = new Map(workspace.files.map((file) => [file.path, file.text]));
86
+ const atoms = yield* Atoms;
87
+ const planned = yield* Effect.forEach(judged, (candidate) => Effect.gen(function* () {
88
+ const text = textOf.get(candidate.unit.file) ?? "";
89
+ const id = yield* atoms.add({
90
+ literal: {
91
+ value: candidate.value,
92
+ unit: candidate.unit.name,
93
+ file: candidate.unit.file,
94
+ context: text.slice(Math.max(0, candidate.start - 60), candidate.start + 90),
95
+ },
96
+ callers: [...candidate.callers],
97
+ source: candidate.unit.text.slice(0, policy.evidence.maxSourceChars),
98
+ });
99
+ const plan = {
100
+ ruleId: RULE_ID,
101
+ subject: candidate.unit.name + ' ("' + candidate.value + '")',
102
+ concerns: [candidate.unit.file, ...candidate.callers.map((caller) => caller.file)],
103
+ atoms: [id],
104
+ violations: { verdict: ["names_a_caller"] },
105
+ decisions: {
106
+ verdict: Decision.classify({
107
+ instructions: [
108
+ `\`atoms[${id}].source\` is the body of \`atoms[${id}].literal.unit\`, which ${candidate.callers.length} files call.`,
109
+ `It writes the string \`atoms[${id}].literal.value\`, in this context: \`atoms[${id}].literal.context\`.`,
110
+ "Is that string one caller's fact, which belongs to the caller as a parameter?",
111
+ "Answer `names_a_caller` when the string is a label, a route, a heading or copy that belongs to one of the callers and would be wrong for another.",
112
+ "Answer `general` when the string is the unit's own -- a generic message, a separator, a key -- and every caller means the same thing by it.",
113
+ "Answer `shared_vocabulary` when the string is a constant the whole codebase shares, so it does not vary by caller.",
114
+ ].join("\n"),
115
+ criteria: {
116
+ names_a_caller: "One caller's words. Pass them in.",
117
+ general: "The unit's own words; every caller means the same.",
118
+ shared_vocabulary: "A codebase-wide constant.",
119
+ },
120
+ }),
121
+ },
122
+ read: (answers) => answers,
123
+ };
124
+ return { candidate, plan };
125
+ }), { concurrency: "unbounded" });
126
+ return {
127
+ plans: planned.map((entry) => entry.plan),
128
+ read: (answers) => {
129
+ const verdicts = verdictsOf(answers);
130
+ const diagnostics = [];
131
+ const drops = [...overBudget];
132
+ planned.forEach((entry, index) => {
133
+ const { candidate } = entry;
134
+ const subject = candidate.unit.name + ' ("' + candidate.value + '")';
135
+ const verdict = verdictOf(verdicts[index]?.["verdict"], ["names_a_caller"]);
136
+ if (verdict === undefined) {
137
+ diagnostics.push(findingFor({
138
+ report,
139
+ entry,
140
+ confidence: undefined,
141
+ unverifiedReason: "no judgement was available",
142
+ }));
143
+ return;
144
+ }
145
+ if (verdict.label !== "names_a_caller") {
146
+ drops.push({
147
+ ruleId: RULE_ID,
148
+ subject,
149
+ stage: "declined",
150
+ reason: verdict.label === "shared_vocabulary"
151
+ ? "a codebase-wide constant"
152
+ : "the unit's own words",
153
+ });
154
+ return;
155
+ }
156
+ const quality = qualityOf({
157
+ score: verdict.probability,
158
+ margin: verdict.margin,
159
+ confidence: verdict.confidence,
160
+ });
161
+ if (quality.quality === "drop") {
162
+ drops.push({ ruleId: RULE_ID, subject, stage: "gated", reason: quality.reason });
163
+ return;
164
+ }
165
+ const review = quality.quality === "review";
166
+ diagnostics.push(findingFor({
167
+ report,
168
+ entry,
169
+ confidence: verdict.confidence,
170
+ unverifiedReason: undefined,
171
+ review,
172
+ }));
173
+ });
174
+ return outcome(diagnostics, budgetNote({
175
+ unitKind: "shared literals",
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, entry, confidence, unverifiedReason, review = false, }) => report({
185
+ about: { file: entry.candidate.unit.file, start: entry.candidate.start },
186
+ messageId: "caller_fact",
187
+ data: {
188
+ unit: entry.candidate.unit.name,
189
+ value: entry.candidate.value,
190
+ count: entry.candidate.callers.length,
191
+ unverified: unverifiedReason === undefined ? "" : " Not verified: " + unverifiedReason + ".",
192
+ },
193
+ helpId: "caller_fact_help",
194
+ identity: [RULE_ID, entry.candidate.unit.file, entry.candidate.unit.name, entry.candidate.value].join("\u0000"),
195
+ judged: unverifiedReason === undefined,
196
+ confidence,
197
+ severity: review ? "info" : "warn",
198
+ });