@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,700 @@
1
+ import { Effect, Order, Schema } from "effect";
2
+ import * as AiError from "effect/ai/AiError";
3
+ import { Decision, DecisionModel } from "effect/ai";
4
+ import { Atoms } from "../atoms.js";
5
+ import { isUnreachable } from "../decision.js";
6
+ import { cascadeOf } from "../cascade.js";
7
+ import { derivedOperation, describeOperation, permitted, relationshipOf, settle, } from "../operation.js";
8
+ import { answerPlans, PlanAnswers } from "../plans.js";
9
+ import { locator, messages, reporter } from "../reporting.js";
10
+ import { policy } from "../policy.js";
11
+ import { canImport, sharedLayerFor } from "../architecture.js";
12
+ import { declined, everyFile, marginOfAnswer, qualityOf, } from "../rule.js";
13
+ import { duplicateVocabulary } from "../vocabulary.js";
14
+ import { namesOf } from "../cluster.js";
15
+ /**
16
+ * The members actually described to the model.
17
+ *
18
+ * A capped prefix of the cluster, so the member ids stay aligned -- but ORDERED so
19
+ * the members this run is about come first. A cluster is sorted by path, and a
20
+ * scoped run is asking about the declarations that MOVED: in a cluster of forty
21
+ * where the changed one sorts thirtieth, a plain prefix shows the model the
22
+ * cluster without the change, and the change is the whole question. The kept
23
+ * member could not even be the one that moved.
24
+ */
25
+ export const describedMembers = (cluster, scope) => {
26
+ const changed = scope.changed;
27
+ const ordered = changed === undefined
28
+ ? cluster.members
29
+ : [...cluster.members].sort((left, right) => Number(changed.has(right.file)) - Number(changed.has(left.file)));
30
+ return ordered.slice(0, policy.evidence.maxMembers);
31
+ };
32
+ /**
33
+ * One declaration as the model sees it.
34
+ *
35
+ * The resolved type is added only when the run asked for a trace, and that is
36
+ * deliberate: the state is the judgement cache key, so an unconditional field
37
+ * would invalidate every verdict made before the type layer existed. A run
38
+ * without `--types` sends exactly the panel it always did; a run with it sends a
39
+ * richer one and earns its own verdicts.
40
+ */
41
+ const declarationEvidence = (member) => {
42
+ const evidence = {
43
+ symbol: member.name,
44
+ kind: member.kind,
45
+ path: member.file,
46
+ line: member.location.line,
47
+ source: member.text.slice(0, policy.evidence.maxSourceChars),
48
+ documented: member.doc !== undefined,
49
+ doc: member.doc?.slice(0, policy.evidence.maxDocChars) ?? null,
50
+ types: member.typeRefs,
51
+ };
52
+ const facts = member.typeFacts;
53
+ if (facts === undefined)
54
+ return evidence;
55
+ return {
56
+ ...evidence,
57
+ resolved: {
58
+ display: facts.display,
59
+ // The fingerprint and the group are the two fields a judge can compare
60
+ // without reading source: same structural, two names for one type.
61
+ structural: facts.structural,
62
+ flags: facts.flags,
63
+ alias: facts.alias,
64
+ members: facts.members.slice(0, policy.evidence.maxMembers),
65
+ variants: facts.variants.slice(0, policy.evidence.maxMembers),
66
+ bases: facts.bases.slice(0, 8),
67
+ value: facts.value,
68
+ identicalGroup: facts.identicalGroup,
69
+ },
70
+ };
71
+ };
72
+ const describedNote = (cluster, described) => described.length < cluster.members.length
73
+ ? ` The cluster has ${cluster.members.length} members in total; only ${described.length} are shown, and only those can be chosen.`
74
+ : "";
75
+ /**
76
+ * The line that points the model at the compiler's answer, when the run has one.
77
+ *
78
+ * The TypeSafe docs are explicit that a question should name the part of the
79
+ * state it is about, with a backticked path. The resolved type is the one part of
80
+ * this panel that is a compiler fact rather than source text, so the question
81
+ * names it and says what it means -- otherwise the model reads `source` and never
82
+ * looks at `resolved`.
83
+ *
84
+ * Empty when the run had no trace, so a run without `--types` sends the questions
85
+ * it always did and keeps its cached verdicts.
86
+ */
87
+ const resolvedNote = (described) => described.some((member) => member.typeFacts !== undefined)
88
+ ? "The compiler resolved each declaration's type; each entry of `atoms` carries it on `resolved`. `resolved.structural` is the member-sorted fingerprint, and a non-null `resolved.identicalGroup` is the compiler proving two declarations are mutually assignable and structurally identical. Two identical resolved types are one type written twice; two different ones are two types that only read alike."
89
+ : "";
90
+ /**
91
+ * The shared question for exact and near duplicates: is one of these redundant?
92
+ *
93
+ * Both rules ask it because for them it is the same question -- the declarations
94
+ * are the same shape or near enough that the only thing left is intent.
95
+ */
96
+ export const collapseQuestionnaire = ({ cluster, described, workspace, }) => Effect.gen(function* () {
97
+ const atoms = yield* Atoms;
98
+ // What the repository permits here. A fact, so the model cannot propose a
99
+ // merge across a package boundary.
100
+ const operations = permitted(workspace, cluster.members);
101
+ // The package relationship is a fact about the manifests, not a judgement:
102
+ // asking a model to infer it from paths asked it to repeat the code's work.
103
+ const relationship = relationshipOf(workspace, cluster.members);
104
+ const ids = yield* atoms.addAll(described.map((member) => declarationEvidence(member)));
105
+ const facts = yield* atoms.add({
106
+ identical: cluster.identical,
107
+ overlap: Number(cluster.overlap.toFixed(3)),
108
+ relationship,
109
+ // The material a panel would need before judging where a thing belongs.
110
+ // No configuration: the paths are in the graph and the relationships are
111
+ // in the paths.
112
+ files: [...new Set(cluster.members.map((member) => member.file))],
113
+ common_directory: commonDirectory(cluster.members.map((member) => member.file)),
114
+ count: cluster.members.length,
115
+ described: described.length,
116
+ });
117
+ const refs = ids.map((id) => `atoms[${id}]`).join(", ");
118
+ const criteria = {};
119
+ described.forEach((member, index) => {
120
+ criteria[`member_${index}`] =
121
+ `Keep member_${index}: ` + "`atoms[" + (ids[index] ?? "") + "]` — " + member.name + ", " + member.kind + ", in " + member.file + ".";
122
+ });
123
+ const note = describedNote(cluster, described);
124
+ const resolved = resolvedNote(described);
125
+ return {
126
+ atoms: [...ids, facts],
127
+ // The Noul is the violation: its probability IS P(redundant), so the
128
+ // violating set is empty. Calibration reduces this decision.
129
+ violations: { redundant: [] },
130
+ decisions: {
131
+ redundant: Decision.probability({
132
+ instructions: [
133
+ `Are the ${cluster.members.length} declarations named by \`${refs}\` one thing written repeatedly? Each has a \`source\`.`,
134
+ "Answer yes only if a reader is worse off for there being more than one.",
135
+ resolved,
136
+ ]
137
+ .filter((line) => line !== "")
138
+ .join(" "),
139
+ criteria: duplicateVocabulary.redundant,
140
+ }),
141
+ role: Decision.classify({
142
+ instructions: [
143
+ "What IS this declaration, apart from the fact that it is duplicated?",
144
+ `Inspect \`${refs}\`.`,
145
+ "Answer about what the declaration IS, not about what should happen to it. Two copies of a wire contract are correct; two copies of a domain concept are the defect. This answer decides which of those this is.",
146
+ "Choose `implementation_detail` when it is a helper with no meaning of its own.",
147
+ ].join("\n"),
148
+ criteria: duplicateVocabulary.role,
149
+ }),
150
+ verdict: Decision.classify({
151
+ instructions: [
152
+ `What should happen to the declarations named by \`${refs}\`?`,
153
+ cluster.identical
154
+ ? `They are syntactically identical, including property names and types.${note}`
155
+ : `They are up to ${Math.round(cluster.overlap * 100)}% structurally similar but not identical.${note}`,
156
+ "Choose `no_issue` when the similarity is coincidence rather than repetition.",
157
+ "Choose `keep_variants` when the repetition is deliberate, so one copy should not replace the other: a special case of a general routine, or a stable shape a framework requires.",
158
+ "Which operations this repository can actually make is already decided from the import graph and appears in the `prescription` options. Answer about intent, not about what is possible.",
159
+ resolved,
160
+ ]
161
+ .filter((line) => line !== "")
162
+ .join("\n"),
163
+ criteria: duplicateVocabulary.verdict,
164
+ }),
165
+ consequence: Decision.rate({
166
+ instructions: [
167
+ `Would a reader be better off if the declarations named by \`${refs}\` were one?`,
168
+ "Answer about the EFFECT of the duplication, not about whether it exists. Two identical helpers that nobody will ever change are still one thing.",
169
+ "Choose the level that fits, lowest to highest:",
170
+ "`no_difference`: nobody would notice either way; the copies are stable and independent.",
171
+ "`slightly_clearer`: one copy would read a little better, but nothing is at stake.",
172
+ "`meaningfully_better`: sharing one would remove work or stop the copies diverging.",
173
+ "`removes_a_hazard`: the copies will diverge and cause a bug, or already have.",
174
+ ].join("\n"),
175
+ criteria: duplicateVocabulary.consequenceLevels,
176
+ }),
177
+ canonical: Decision.classify({
178
+ instructions: `If one of them should be kept, which one? The declarations are \`${refs}\`. Choose the declaration that best fits this codebase's conventions, its location, and its name.`,
179
+ criteria,
180
+ }),
181
+ difference: Decision.classify({
182
+ instructions: [
183
+ `The declarations named by \`${refs}\` are not identical. What IS the difference between them?`,
184
+ "Inspect their `source`.",
185
+ "Choose `value` when they are one thing with a different constant, option or parameter, so one of them could take the other's value.",
186
+ "Choose `meaning` when they are two concepts that happen to read alike.",
187
+ ].join("\n"),
188
+ criteria: duplicateVocabulary.difference,
189
+ }),
190
+ // The prescription, asked rather than tabulated. The operation options
191
+ // the graph permits are in the criteria, so the model cannot propose a
192
+ // merge across a package boundary -- the same guard `permitted` gave the
193
+ // table, now enforced on the answer instead of before the question.
194
+ prescription: Decision.classify({
195
+ instructions: [
196
+ `What should be done about the declarations named by \`${refs}\`?`,
197
+ "Answer with the ONE thing a reviewer should do, having read what they are and where they live.",
198
+ `The operations the import graph permits here are: ${operations.join(", ") || "none"}. \`atoms[${facts}].files\` lists every file involved.`,
199
+ "Choose `share_a_contract` when both sides must keep agreeing but no permitted operation is available, so one shared contract is the answer.",
200
+ "Choose `leave_it` when the repetition is framework-required or stable enough that changing it costs more than it saves.",
201
+ ].join("\n"),
202
+ criteria: duplicateVocabulary.prescription,
203
+ }),
204
+ operation: Decision.classify({
205
+ instructions: [
206
+ `What should happen to the declarations named by \`${refs}\`?`,
207
+ "Answer with the one that fits what they ARE and where they live.",
208
+ "Choose `no_issue` when nothing should change.",
209
+ ].join("\n"),
210
+ criteria: {
211
+ ...Object.fromEntries(operations.map((operation) => [operation, describeOperation(operation)])),
212
+ no_issue: "Leave them as they are.",
213
+ },
214
+ }),
215
+ },
216
+ read: (answers) => {
217
+ const verdict = answers["verdict"];
218
+ if (verdict === undefined || !("label" in verdict))
219
+ return undefined;
220
+ const redundant = answers["redundant"];
221
+ const redundancy = redundant !== undefined && "probability" in redundant
222
+ ? redundant.probability
223
+ : (verdict.confidence ?? 1);
224
+ const role = answers["role"];
225
+ // The prescription is the model's answer; the table that used to derive it
226
+ // is gone. `prescriptionFor` remains for the unverified path and for tests.
227
+ const prescribed = answers["prescription"];
228
+ const prescriptionKind = prescribed !== undefined && "label" in prescribed ? prescribed.label : undefined;
229
+ const prescription = prescribed !== undefined && "label" in prescribed
230
+ ? // SAFETY: the label is the model's choice among this vocabulary's own
231
+ // criteria, which DecisionModel validated before returning it, so the
232
+ // index is always a key of the table. `?? undefined` keeps an outside
233
+ // label a miss rather than a defect.
234
+ duplicateVocabulary.prescription[prescribed.label] ?? undefined
235
+ : role === undefined || !("label" in role)
236
+ ? undefined
237
+ : prescriptionFor({ role: role.label, relationship });
238
+ // Ranked by consequence, gated by redundancy. A finding that does not
239
+ // matter is still a finding and still reported; it sorts last.
240
+ //
241
+ // The Score answers with a probability-weighted position on its levels, so
242
+ // the position is normalised onto [0, 1] -- the same range a Noul would
243
+ // have given, with the degrees kept.
244
+ const consequence = answers["consequence"];
245
+ const span = duplicateVocabulary.consequenceLevels.length - 1;
246
+ const score = consequence !== undefined && "rating" in consequence
247
+ ? span <= 0
248
+ ? 0
249
+ : consequence.rating / span
250
+ : redundancy;
251
+ const margin = marginOfAnswer(verdict);
252
+ const confidence = verdict.confidence ?? 1;
253
+ // The difference between the copies, and the model's own read of the
254
+ // operation. The two together settle it, and their disagreement is
255
+ // reported rather than resolved.
256
+ const differenceAnswer = answers["difference"];
257
+ const difference = differenceAnswer !== undefined &&
258
+ "label" in differenceAnswer &&
259
+ (differenceAnswer.label === "value" || differenceAnswer.label === "meaning")
260
+ ? differenceAnswer.label
261
+ : "unclear";
262
+ const operationAnswer = answers["operation"];
263
+ const proposed = operationAnswer !== undefined &&
264
+ "label" in operationAnswer &&
265
+ (operationAnswer.label === "merge" || operationAnswer.label === "move")
266
+ ? operationAnswer.label
267
+ : undefined;
268
+ const derived = derivedOperation({ candidate: "duplicated", oneThing: redundancy, difference });
269
+ const settled = settle({
270
+ derived,
271
+ proposed,
272
+ margin: operationAnswer !== undefined && "label" in operationAnswer ? marginOfAnswer(operationAnswer) : 1,
273
+ confidence: operationAnswer !== undefined && "confidence" in operationAnswer
274
+ ? operationAnswer.confidence
275
+ : undefined,
276
+ });
277
+ // `keep_variants` is a decision about the declarations; a decline is a
278
+ // decision about the question. Both suppress the finding, and only the
279
+ // second says the rule should not have asked.
280
+ if (verdict.label === "keep_variants" || declined(verdict.label)) {
281
+ return {
282
+ keep: undefined,
283
+ confidence,
284
+ score,
285
+ redundancy,
286
+ margin,
287
+ prescription,
288
+ prescriptionKind,
289
+ derived,
290
+ panel: panelFromAnswers(answers, { derived, agreement: "drop" }),
291
+ operation: undefined,
292
+ agreement: "drop",
293
+ settled: "the model said " + verdict.label,
294
+ };
295
+ }
296
+ const canonical = answers["canonical"];
297
+ const index = canonical === undefined || !("label" in canonical)
298
+ ? 0
299
+ : Number.parseInt(canonical.label.replace("member_", ""), 10);
300
+ return {
301
+ keep: Number.isNaN(index) ? 0 : index,
302
+ confidence,
303
+ score,
304
+ redundancy,
305
+ margin,
306
+ prescription,
307
+ prescriptionKind,
308
+ derived,
309
+ panel: panelFromAnswers(answers, {
310
+ operation: settled.operation,
311
+ derived,
312
+ agreement: settled.quality,
313
+ }),
314
+ operation: settled.operation,
315
+ agreement: settled.quality,
316
+ settled: settled.reason,
317
+ };
318
+ },
319
+ };
320
+ });
321
+ /** The deepest directory every one of these files sits inside. */
322
+ const commonDirectory = (paths) => {
323
+ const split = paths.map((file) => file.split("/").slice(0, -1));
324
+ const first = split[0];
325
+ if (first === undefined)
326
+ return ".";
327
+ let depth = 0;
328
+ for (let index = 0; index < first.length; index += 1) {
329
+ if (split.every((parts) => parts[index] === first[index]))
330
+ depth = index + 1;
331
+ else
332
+ break;
333
+ }
334
+ return depth === 0 ? "." : first.slice(0, depth).join("/");
335
+ };
336
+ /**
337
+ * What to do about it, from what the declaration IS and how the files relate.
338
+ *
339
+ * This is the whole judgement, and it is decided in code. The model answers two
340
+ * questions it can actually answer -- what is this, and how do these files
341
+ * relate -- and the prescription follows from the pair. No repository has to
342
+ * declare its boundaries for this to work, which is the point: a hand-maintained
343
+ * map of a codebase's architecture goes stale the moment someone moves a
344
+ * directory, and the paths say the same thing for free.
345
+ *
346
+ * The two rows that matter are the same duplication with opposite answers. A
347
+ * wire contract repeated across a service boundary is CORRECT -- two services
348
+ * share a shape, not a module. A domain concept repeated across one is the
349
+ * defect the architecture exists to prevent.
350
+ */
351
+ export const prescriptionFor = ({ role, relationship }) => {
352
+ if (relationship === "same_package") {
353
+ return "Delete the copies and import one: these files can reach each other.";
354
+ }
355
+ if (role === "wire_contract") {
356
+ return "Expected: these declarations sit in different packages, so one cannot replace the other. Give both sides a shared contracts package if they must agree, and leave it alone if they must not.";
357
+ }
358
+ if (role === "domain_concept") {
359
+ return "The same concept in two deployables that cannot import each other, which is the case a shared package exists for. Move the concept into one both depend on.";
360
+ }
361
+ if (role === "framework_glue") {
362
+ return "Framework shapes are repeated per file by construction. If these are framework glue, leave them.";
363
+ }
364
+ return "Different deployables and not a contract: hoist the shared part into a package both can depend on, or accept the duplication.";
365
+ };
366
+ /**
367
+ * What to do about it, given who may import whom.
368
+ *
369
+ * Used when there is no judgement to read a role from -- an unverified finding
370
+ * still deserves advice -- and when a repository has declared its layers, which
371
+ * is a fact worth using even though it is no longer required.
372
+ *
373
+ * "Delete the copies and import one" is only advice if the copies can reach the
374
+ * one being kept, and across a package boundary they usually cannot. On one
375
+ * repository 78 of 261 duplicate findings told a Remix app to import a type from
376
+ * a Fastify service, and 67 of those were the frontend and the backend pointing
377
+ * at each other. The duplication was real and the prescription was impossible,
378
+ * which is the worst combination: a reader who tries it learns to ignore the
379
+ * tool.
380
+ *
381
+ * The relationship is decidable from the declared layers, so it is decided here
382
+ * rather than asked about. The model answers whether the declarations are one
383
+ * thing; where the one thing should LIVE is a fact about the repository.
384
+ */
385
+ const prescription = (layers, cluster, keep, drops) => {
386
+ if (drops.every((unit) => canImport({ layers, importer: unit.file, to: keep.file }))) {
387
+ return `Delete or import instead of redeclaring: ${memberList(drops)}.`;
388
+ }
389
+ const shared = sharedLayerFor(layers, cluster.members.map((member) => member.file));
390
+ if (shared !== undefined) {
391
+ return `None of these may import the others, so hoist the declaration into ${shared.name} and import it from all of them: ${memberList(drops)}.`;
392
+ }
393
+ return `These sit in layers that cannot see each other and share nothing below them. Extract a shared package, or accept the duplication as a contract: ${memberList(drops)}.`;
394
+ };
395
+ const memberList = (units) => {
396
+ const shown = units.slice(0, policy.evidence.maxListedPaths);
397
+ const rest = units.length - shown.length;
398
+ const listed = shown.map((unit) => `${unit.file}:${unit.location.line}`).join(", ");
399
+ return rest > 0 ? `${listed} and ${rest} more` : listed;
400
+ };
401
+ /**
402
+ * A stable name for a finding, for comparing one run against the next.
403
+ *
404
+ * Membership and the kept symbol, never line numbers: code moves constantly and
405
+ * a baseline that reports every edit as new is a baseline nobody reads.
406
+ */
407
+ const identityOf = (ruleId, cluster, keep) => [ruleId, keep.name, ...[...new Set(cluster.members.map((m) => m.file))].sort(Order.String)].join("\u0000");
408
+ /** Prescriptions that mean expected duplication: reported, but as a notice. */
409
+ const EXPECTED_DUPLICATION = new Set(["leave_it", "share_a_contract"]);
410
+ /** Every cluster rule reports through these. */
411
+ const CLUSTER_MESSAGES = messages({
412
+ unverified: "{{subject}}.",
413
+ unverified_help: "Keep `{{keep}}` ({{keepAt}}) and import it elsewhere. Not verified: {{reason}}.{{shape}} Duplicates: {{duplicates}}.",
414
+ duplicate: "{{subject}} — keep `{{keep}}` in {{keepAt}}{{extra}}.",
415
+ duplicate_help: "{{prescription}}{{shape}} {{dependents}}.{{review}}",
416
+ });
417
+ /** Bind a cluster rule's messages to a workspace's locator. */
418
+ export const clusterReporter = (rule, workspace) => reporter({ id: rule.ruleId, severity: rule.severity, judged: true, messages: CLUSTER_MESSAGES, move: rule.move }, locator(workspace));
419
+ /**
420
+ * Build the finding for a cluster whose judgement was unavailable.
421
+ *
422
+ * @param {UnverifiedFindingInput} payload - The report, rule, cluster, and reason.
423
+ * @returns {Diagnostic | undefined} The finding, or undefined when the cluster is not a pair.
424
+ */
425
+ export const unverifiedFinding = ({ report, rule, cluster, reason = "no judgement was available", }) => {
426
+ const keep = cluster.members[0];
427
+ const drops = cluster.members.slice(1);
428
+ const first = drops[0];
429
+ if (keep === undefined || first === undefined)
430
+ return undefined;
431
+ return report({
432
+ about: first,
433
+ messageId: "unverified",
434
+ data: {
435
+ subject: rule.nameOf(cluster),
436
+ keep: keep.name,
437
+ keepAt: keep.file + ":" + keep.location.line,
438
+ reason,
439
+ shape: shapeOnlyNote(cluster),
440
+ duplicates: memberList(drops),
441
+ },
442
+ helpId: "unverified_help",
443
+ identity: identityOf(rule.ruleId, cluster, keep),
444
+ judged: false,
445
+ severity: rule.severity,
446
+ });
447
+ };
448
+ /**
449
+ * The caveat a shape-only cluster earns.
450
+ *
451
+ * Empty when the cluster has types to stand on. Otherwise it says what the
452
+ * finding actually rests on, because in a JavaScript codebase this is the COMMON
453
+ * case rather than the exception: nothing in the declaration says what it
454
+ * operates on, so two shapes matching is all the evidence there is. The finding
455
+ * is still true; saying what it rests on is the difference between a weaker
456
+ * finding and a misleading one.
457
+ */
458
+ const shapeOnlyNote = (cluster) => cluster.typed
459
+ ? ""
460
+ : " No member carries a type annotation, so only the shape could be compared.";
461
+ /**
462
+ * Who depends on the declaration being kept.
463
+ *
464
+ * This is the sentence that used to be a wish. "Keep X and import it here" is
465
+ * only true advice if we know what imports the copy going away, and until the
466
+ * graph existed we had never checked.
467
+ */
468
+ const dependents = (imports, unit) => {
469
+ const named = imports.importersOfName(unit.file, unit.name);
470
+ const files = [...new Set(named.map((edge) => edge.importer))];
471
+ if (files.length === 0) {
472
+ return imports.importersOf.get(unit.file) === undefined
473
+ ? "nothing in the analysed set imports this file"
474
+ : `no file imports \`${unit.name}\` by name`;
475
+ }
476
+ const shown = files.slice(0, policy.evidence.maxListedPaths).join(", ");
477
+ const more = files.length > policy.evidence.maxListedPaths
478
+ ? ` and ${files.length - policy.evidence.maxListedPaths} more`
479
+ : "";
480
+ return `${files.length} file${files.length === 1 ? "" : "s"} import \`${unit.name}\`: ${shown}${more}`;
481
+ };
482
+ /** One cluster's plan, ready for the engine. */
483
+ export const planCluster = (rule, cluster, scope, workspace) => Effect.gen(function* () {
484
+ const described = describedMembers(cluster, scope);
485
+ if (described.length === 0)
486
+ return undefined;
487
+ const questionnaire = yield* rule.questionnaire({ cluster, described, workspace });
488
+ return {
489
+ ruleId: rule.ruleId,
490
+ subject: rule.nameOf(cluster),
491
+ concerns: cluster.members.map((member) => member.file),
492
+ atoms: questionnaire.atoms,
493
+ decisions: questionnaire.decisions,
494
+ violations: questionnaire.violations,
495
+ read: questionnaire.read,
496
+ };
497
+ });
498
+ /* Turn a verdict into a finding, or into silence. Pure, so it is testable alone. */
499
+ /**
500
+ * A candidate the rule looked at and did not report.
501
+ *
502
+ * Returned alongside the finding rather than counted separately, so the reason a
503
+ * candidate was dropped is produced by the same code that decides to drop it. A
504
+ * second pass that re-derives the reason is a second chance to disagree.
505
+ */
506
+ export const dropOf = (rule, cluster, stage, reason) => ({ ruleId: rule.ruleId, subject: rule.nameOf(cluster), stage, reason });
507
+ /**
508
+ * The questions behind one cluster's verdict, as the finding reports them.
509
+ *
510
+ * The panel is the observability the blog argues for: a reader can see which
511
+ * judgement moved the outcome, rather than one summary confidence standing in
512
+ * for nine answers. Absent when no answer map exists (an unverified finding).
513
+ */
514
+ export const panelFromAnswers = (answers, figures) => {
515
+ const panel = {
516
+ answers: Object.entries(answers).map(([question, answer]) => {
517
+ // Rate first: it has probabilities too, and asking about `label` before it
518
+ // narrows a Rate answer to never.
519
+ if ("rating" in answer) {
520
+ const positions = Object.values(answer.probabilities);
521
+ return positions.length === 0
522
+ ? { question, label: String(answer.rating) }
523
+ : { question, label: String(answer.rating), probability: Math.max(...positions) };
524
+ }
525
+ if ("label" in answer) {
526
+ const probability = answer.probabilities[answer.label];
527
+ return probability === undefined
528
+ ? { question, label: answer.label }
529
+ : { question, label: answer.label, probability };
530
+ }
531
+ if ("probability" in answer)
532
+ return { question, probability: answer.probability };
533
+ return { question };
534
+ }),
535
+ };
536
+ if (figures.operation !== undefined)
537
+ panel.operation = figures.operation;
538
+ if (figures.derived !== undefined)
539
+ panel.derived = figures.derived;
540
+ if (figures.agreement !== undefined)
541
+ panel.agreement = figures.agreement;
542
+ return panel;
543
+ };
544
+ /**
545
+ * Turn a cluster's verdict into a finding, or into silence.
546
+ *
547
+ * @param input.rule - the rule, for its id, severity and messages.
548
+ * @param input.workspace - the loaded workspace, for repair cascades.
549
+ * @param input.cluster - the cluster being judged.
550
+ * @param input.verdict - the judgement, or undefined when none was available.
551
+ * @param input.layers - the declared layering, for the unverified fallback.
552
+ * @returns the finding, or the reason there is none.
553
+ */
554
+ export const findingFor = ({ rule, workspace, cluster, verdict, layers, }) => {
555
+ const imports = workspace.imports;
556
+ const report = clusterReporter(rule, workspace);
557
+ if (verdict === undefined) {
558
+ const fallback = rule.onUnavailable === "report" ? unverifiedFinding({ report, rule, cluster }) : undefined;
559
+ return fallback === undefined
560
+ ? { drop: dropOf(rule, cluster, "unreadable", "no judgement available") }
561
+ : { diagnostic: fallback };
562
+ }
563
+ if (verdict.keep === undefined) {
564
+ return { drop: dropOf(rule, cluster, "declined", "the model found nothing to change") };
565
+ }
566
+ // A verdict that fails its gates is not a worse verdict, it is not a verdict.
567
+ // Handling it exactly like an absent answer means one gate serves every rule,
568
+ // and each rule keeps the degrade behaviour it already declared: a provable
569
+ // finding is still reported, marked unverified with the reason; a guessed one
570
+ // stays silent. The gate never has to know which rule it is in.
571
+ const quality = qualityOf({
572
+ score: verdict.redundancy,
573
+ margin: verdict.margin,
574
+ confidence: verdict.confidence,
575
+ });
576
+ if (quality.quality === "drop") {
577
+ const fallback = rule.onUnavailable === "report"
578
+ ? unverifiedFinding({ report, rule, cluster, reason: quality.reason })
579
+ : undefined;
580
+ return fallback === undefined
581
+ ? { drop: dropOf(rule, cluster, "gated", quality.reason) }
582
+ : { diagnostic: fallback };
583
+ }
584
+ // Two ways to land in review: the redundancy gate was not decisive, or the
585
+ // table and the model disagreed about the operation.
586
+ const review = quality.quality === "review" || verdict.agreement === "review";
587
+ const keep = cluster.members[verdict.keep] ?? cluster.members[0];
588
+ if (keep === undefined) {
589
+ return { drop: dropOf(rule, cluster, "no_evidence", "the chosen member is not in the cluster") };
590
+ }
591
+ const drops = cluster.members.filter((member) => member !== keep);
592
+ const first = drops[0];
593
+ if (first === undefined) {
594
+ return { drop: dropOf(rule, cluster, "no_evidence", "keeping every member leaves nothing to drop") };
595
+ }
596
+ const names = namesOf(cluster);
597
+ const extra = names.length > 1 ? ` (also named ${names.filter((name) => name !== keep.name).join(", ")})` : "";
598
+ // The smaller form, and what it costs. The cascade is a graph walk, so it is
599
+ // exact, and an operation with no cascade is an operation that costs nothing.
600
+ const repair = verdict.operation === undefined
601
+ ? undefined
602
+ : {
603
+ operation: verdict.operation,
604
+ keep: keep.location,
605
+ remove: drops.map((member) => member.location),
606
+ cascade: cascadeOf(workspace, keep, drops),
607
+ complete: true,
608
+ settled: verdict.settled,
609
+ };
610
+ return {
611
+ diagnostic: report({
612
+ about: first,
613
+ messageId: "duplicate",
614
+ data: {
615
+ subject: rule.nameOf(cluster),
616
+ keep: keep.name,
617
+ keepAt: keep.file + ":" + keep.location.line,
618
+ extra,
619
+ // The model's answer when there is one, the declared layers when there
620
+ // are not. A repository that configures nothing still gets advice.
621
+ prescription: verdict.prescription ?? prescription(layers, cluster, keep, drops),
622
+ shape: shapeOnlyNote(cluster),
623
+ dependents: dependents(imports, keep),
624
+ review: review ? " For review: " + quality.reason + "." : "",
625
+ },
626
+ helpId: "duplicate_help",
627
+ identity: identityOf(rule.ruleId, cluster, keep),
628
+ confidence: verdict.confidence,
629
+ score: verdict.score,
630
+ judged: true,
631
+ panel: verdict.panel,
632
+ repair,
633
+ severity: review || EXPECTED_DUPLICATION.has(verdict.prescriptionKind ?? "")
634
+ ? "info"
635
+ : rule.severity,
636
+ }),
637
+ };
638
+ };
639
+ /**
640
+ * Build every cluster's plan, without answering anything.
641
+ *
642
+ * The phase is separate from the answer so the engine can collect plans from
643
+ * every planned rule and answer them in one request. A rule that answered its own
644
+ * plans could not share a request with another, which is the whole point.
645
+ */
646
+ export const planClusters = (rule, clusters, scope, workspace) => Effect.gen(function* () {
647
+ const unreadable = [];
648
+ const planned = [];
649
+ const built = yield* Effect.forEach(clusters, (cluster) => planCluster(rule, cluster, scope, workspace), {
650
+ concurrency: "unbounded",
651
+ });
652
+ clusters.forEach((cluster, index) => {
653
+ const plan = built[index];
654
+ if (plan === undefined) {
655
+ unreadable.push(dropOf(rule, cluster, "no_evidence", "no member could be described to the model"));
656
+ return;
657
+ }
658
+ planned.push({ cluster, plan });
659
+ });
660
+ return { unreadable, planned };
661
+ });
662
+ /** Turn a phase's answers into findings, in the phase's own order. */
663
+ export const readClusters = (rule, workspace, phase, layers, answers) => {
664
+ // SAFETY: the phase built these plans, so every answer is a ClusterVerdict its
665
+ // own questionnaire produced. The engine erased the type only to batch rules
666
+ // together, and the order is the phase's own order.
667
+ const verdicts = answers;
668
+ const diagnostics = [];
669
+ const drops = [...phase.unreadable];
670
+ phase.planned.forEach((entry, index) => {
671
+ const outcome = findingFor({
672
+ rule,
673
+ workspace,
674
+ cluster: entry.cluster,
675
+ verdict: verdicts[index],
676
+ layers,
677
+ });
678
+ if (outcome.diagnostic !== undefined)
679
+ diagnostics.push(outcome.diagnostic);
680
+ if (outcome.drop !== undefined)
681
+ drops.push(outcome.drop);
682
+ });
683
+ return { diagnostics, drops };
684
+ };
685
+ /**
686
+ * Plan and answer one rule's clusters, when the rule does not want batching.
687
+ *
688
+ * A planned rule does not use this; it hands its plans to the engine. This is for
689
+ * a rule that is the only judge in a run, or a test that wants one call's worth of
690
+ * behaviour.
691
+ */
692
+ export const assessClusters = (rule, workspace, clusters, layers = [], scope = everyFile) => Effect.gen(function* () {
693
+ const phase = yield* planClusters(rule, clusters, scope, workspace);
694
+ if (phase.planned.length === 0)
695
+ return { diagnostics: [], drops: phase.unreadable };
696
+ // A fact-based rule still reports its facts when the model was never reached;
697
+ // a guess-based rule steps aside and the engine reports it as skipped.
698
+ const verdicts = yield* answerPlans(phase.planned.map((entry) => entry.plan)).pipe(Effect.catchIf((error) => rule.onUnavailable === "report" || !isUnreachable(error), () => Effect.succeed(phase.planned.map(() => undefined))));
699
+ return readClusters(rule, workspace, phase, layers, verdicts);
700
+ });