@autotelic/joggle 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/JOGGLE.md +634 -0
  2. package/LICENSE +21 -0
  3. package/README.md +88 -2
  4. package/bin/joggle.js +6 -0
  5. package/dist/answer-store.js +305 -0
  6. package/dist/architecture.js +190 -0
  7. package/dist/ask.js +184 -0
  8. package/dist/astro.js +75 -0
  9. package/dist/atoms.js +76 -0
  10. package/dist/bundles.js +156 -0
  11. package/dist/calibration.js +60 -0
  12. package/dist/candidates.js +561 -0
  13. package/dist/canonical.js +24 -0
  14. package/dist/cascade.js +98 -0
  15. package/dist/check.js +854 -0
  16. package/dist/cluster.js +69 -0
  17. package/dist/config.js +195 -0
  18. package/dist/content-mappers.js +83 -0
  19. package/dist/decision.js +203 -0
  20. package/dist/fingerprint.js +61 -0
  21. package/dist/git.js +127 -0
  22. package/dist/gitignore.js +65 -0
  23. package/dist/glob.js +51 -0
  24. package/dist/imports.js +153 -0
  25. package/dist/jsonc.js +95 -0
  26. package/dist/main.js +630 -0
  27. package/dist/manifest.js +42 -0
  28. package/dist/meta.js +170 -0
  29. package/dist/moves.js +47 -0
  30. package/dist/operation.js +133 -0
  31. package/dist/parsecache.js +264 -0
  32. package/dist/plans.js +425 -0
  33. package/dist/plugin.js +71 -0
  34. package/dist/plugins.js +136 -0
  35. package/dist/policy.js +676 -0
  36. package/dist/presets/composition.js +32 -0
  37. package/dist/report.js +474 -0
  38. package/dist/reporting.js +132 -0
  39. package/dist/result.js +28 -0
  40. package/dist/roles.js +303 -0
  41. package/dist/rule.js +194 -0
  42. package/dist/rules/append-only-honoured.js +190 -0
  43. package/dist/rules/bundle-conformance.js +245 -0
  44. package/dist/rules/call-pattern.js +209 -0
  45. package/dist/rules/cluster-verdict.js +700 -0
  46. package/dist/rules/compose-types.js +250 -0
  47. package/dist/rules/data-error-as-outage.js +482 -0
  48. package/dist/rules/declared-staleness.js +242 -0
  49. package/dist/rules/dependency-fit.js +297 -0
  50. package/dist/rules/deviation-has-a-shape.js +225 -0
  51. package/dist/rules/doc-matches-code.js +191 -0
  52. package/dist/rules/duplicate-call-run.js +240 -0
  53. package/dist/rules/duplicate-implementation.js +89 -0
  54. package/dist/rules/duplicate-meaning.js +130 -0
  55. package/dist/rules/fact-or-derivation.js +202 -0
  56. package/dist/rules/field-type-drift.js +373 -0
  57. package/dist/rules/generic-carries-a-caller.js +198 -0
  58. package/dist/rules/hoist-to-domain.js +288 -0
  59. package/dist/rules/import-architecture.js +393 -0
  60. package/dist/rules/index.js +105 -0
  61. package/dist/rules/inferred-over-recorded.js +214 -0
  62. package/dist/rules/intent-drift.js +286 -0
  63. package/dist/rules/invariant-has-a-reconciler.js +190 -0
  64. package/dist/rules/language-drift.js +234 -0
  65. package/dist/rules/meaning-switched-by-flag.js +189 -0
  66. package/dist/rules/module-direction.js +231 -0
  67. package/dist/rules/name-as-address.js +216 -0
  68. package/dist/rules/name-the-primitive.js +203 -0
  69. package/dist/rules/naming-drift.js +218 -0
  70. package/dist/rules/nullability-drift.js +220 -0
  71. package/dist/rules/object-shape.js +280 -0
  72. package/dist/rules/one-concept-one-type.js +243 -0
  73. package/dist/rules/page-needs-composition.js +227 -0
  74. package/dist/rules/reimplemented-primitive.js +283 -0
  75. package/dist/rules/reversal.js +264 -0
  76. package/dist/rules/rule-judgment.js +252 -0
  77. package/dist/rules/schema-excludes-domain-value.js +190 -0
  78. package/dist/rules/shallow-module.js +204 -0
  79. package/dist/rules/single-path.js +237 -0
  80. package/dist/rules/structural-collapse.js +198 -0
  81. package/dist/rules/temporal-coupling.js +205 -0
  82. package/dist/rules/types-over-logic.js +198 -0
  83. package/dist/rules/unaccounted-drop.js +190 -0
  84. package/dist/rules/unbounded-default-read.js +227 -0
  85. package/dist/run-cache.js +132 -0
  86. package/dist/schema.js +285 -0
  87. package/dist/similarity.js +119 -0
  88. package/dist/source.js +30 -0
  89. package/dist/sql.js +34 -0
  90. package/dist/stages.js +39 -0
  91. package/dist/state.js +65 -0
  92. package/dist/testing.js +131 -0
  93. package/dist/tsconfig-scope.js +32 -0
  94. package/dist/tsgo.js +127 -0
  95. package/dist/typefacts.js +455 -0
  96. package/dist/typetrace.js +283 -0
  97. package/dist/verdict.js +65 -0
  98. package/dist/vocabulary.js +365 -0
  99. package/dist/workspace.js +1963 -0
  100. package/extensions/joggle.ts +454 -0
  101. package/package.json +85 -3
package/dist/roles.js ADDED
@@ -0,0 +1,303 @@
1
+ import { Effect, Option, Order, Schema } from "effect";
2
+ import * as AiError from "effect/ai/AiError";
3
+ import { Decision, DecisionModel } from "effect/ai";
4
+ import { isUnreachable } from "./decision.js";
5
+ import { policy } from "./policy.js";
6
+ import { budgetNote } from "./rule.js";
7
+ import { moduleRoles, rankOfLabel, RoleRanking } from "./vocabulary.js";
8
+ /*
9
+ * What each module is for, and where that role sits, asked once and shared.
10
+ *
11
+ * This was inside `hoist-to-domain`, which classifies a module before asking
12
+ * about its declarations. A second rule now needs the same answers, and the
13
+ * judgement cache is content-addressed, so the second reader pays a replay rather
14
+ * than a call: same module, same evidence, same question, same key.
15
+ *
16
+ * It is also the INFERRED replacement for a declared layering. A layering
17
+ * computed from the import graph can never be violated by the import graph -- a
18
+ * topological order respects every edge by construction -- so direction needs an
19
+ * order from somewhere else. That order used to be `roleRank`, a hand-ranked
20
+ * table in this file; it is now a question (`roleQuestions.rank`), because a
21
+ * rank is a taste about what "domain" means and a repository whose UI is the
22
+ * product would have been reported upside down.
23
+ */
24
+ /**
25
+ * The module a declaration belongs to.
26
+ *
27
+ * Four path segments, not the package. `services/rest` contains both
28
+ * `src/routes` and `src/domain`, and asking whether the package is a transport
29
+ * edge has no answer; four segments separates the two inside one package, which
30
+ * is the line being looked for.
31
+ */
32
+ export const moduleOf = (unit) => {
33
+ // The DIRECTORY, never the file.
34
+ //
35
+ // Four segments was right about the depth -- it separates `services/rest/src/
36
+ // routes` from `services/rest/src/domain` inside one package -- and wrong about
37
+ // the last segment. Taking the whole path when it was short made a file its own
38
+ // module, so two files in one directory became an upward dependency between two
39
+ // modules: `src/shared/is-node.ts` importing `src/shared/structural.ts` was
40
+ // reported as utilities importing library core.
41
+ const directories = unit.file.split("/").slice(0, -1);
42
+ return directories.length <= 4 ? directories.join("/") : directories.slice(0, 4).join("/");
43
+ };
44
+ /**
45
+ * The package a specifier names: `react`, `@oxlint/plugins`, `effect/...`.
46
+ *
47
+ * Shared with the dependency check, which learned it first: `fastify-cli/start.js`
48
+ * is a path INTO `fastify-cli`, and comparing raw specifiers reports subpath
49
+ * imports as undeclared.
50
+ */
51
+ export const packageNameOf = (specifier) => {
52
+ const parts = specifier.split("/");
53
+ const [first, second] = parts;
54
+ if (first === undefined)
55
+ return specifier;
56
+ return first.startsWith("@") && second !== undefined ? first + "/" + second : first;
57
+ };
58
+ /**
59
+ * What the repository actually depends on, from its manifests and its imports.
60
+ *
61
+ * The material that separates `../react` from `@react`. A directory called
62
+ * `react` and the React framework have the same name and nothing else in common,
63
+ * and a model reading a path cannot tell which it is looking at -- but the
64
+ * repository can: the framework is a declared dependency, or an unresolved
65
+ * specifier some file imports, and a directory is neither.
66
+ */
67
+ export const externalNames = (workspace) => {
68
+ const names = new Set();
69
+ for (const manifest of workspace.manifests.values()) {
70
+ for (const declared of manifest.declares)
71
+ names.add(declared);
72
+ }
73
+ for (const edge of workspace.imports.edges) {
74
+ if (edge.resolution === "resolved")
75
+ continue;
76
+ if (edge.specifier.startsWith(".") || edge.specifier.startsWith("/"))
77
+ continue;
78
+ if (edge.specifier.startsWith("node:"))
79
+ continue;
80
+ names.add(packageNameOf(edge.specifier));
81
+ }
82
+ return names;
83
+ };
84
+ /** Every module in the workspace, with the declarations it holds. */
85
+ export const modulesOf = (workspace) => {
86
+ const modules = new Map();
87
+ for (const unit of workspace.units) {
88
+ const path = moduleOf(unit);
89
+ const existing = modules.get(path);
90
+ if (existing === undefined)
91
+ modules.set(path, [unit]);
92
+ else
93
+ existing.push(unit);
94
+ }
95
+ return modules;
96
+ };
97
+ export const moduleDecisions = {
98
+ role: Decision.classify({
99
+ instructions: [
100
+ "What is `module.path` for?",
101
+ "Inspect `module` and `repository`.",
102
+ "`repository` describes what this codebase is trying to be. Classify the module by what it IS, not by whether it is doing it well: a route directory full of business rules is still a transport edge.",
103
+ "Choose `utilities` when it is a generic helper with no business meaning.",
104
+ ].join("\n"),
105
+ criteria: moduleRoles,
106
+ }),
107
+ };
108
+ /** The evidence panel, as a Schema, because it is exactly what the model is asked about. */
109
+ const ModuleEvidence = Schema.Struct({
110
+ repository: Schema.optionalKey(Schema.String),
111
+ module: Schema.Struct({
112
+ path: Schema.String,
113
+ declarations: Schema.Number,
114
+ examples: Schema.Array(Schema.String),
115
+ imports: Schema.Array(Schema.String),
116
+ shares_a_name_with_a_dependency: Schema.NullOr(Schema.String),
117
+ /**
118
+ * The roles of the modules that import this one, when they have been
119
+ * decided. This is the material `derives_from` needs: machinery whose only
120
+ * importers are edges sits below them, and the answer is a fact about who
121
+ * depends on it rather than a constant in a table.
122
+ */
123
+ imported_by: Schema.Array(Schema.String),
124
+ }),
125
+ });
126
+ const ModuleClassification = Decision.make({
127
+ input: ModuleEvidence,
128
+ decisions: moduleDecisions,
129
+ });
130
+ /**
131
+ * One question per module, batched, cached, and reported.
132
+ *
133
+ * A module nobody could classify is a drop with a reason rather than a silence:
134
+ * every module skipped here is a module the callers below cannot reason about.
135
+ */
136
+ export const classifyModules = (workspace, context, ruleId) => Effect.gen(function* () {
137
+ const modules = modulesOf(workspace);
138
+ const listed = [...modules.entries()]
139
+ .sort((left, right) => left[0].localeCompare(right[0]))
140
+ .slice(0, policy.moduleRoles.maxModules);
141
+ if (listed.length === 0) {
142
+ return { roles: new Map(), ranks: new Map(), notes: ["no module to classify"], drops: [] };
143
+ }
144
+ const names = externalNames(workspace);
145
+ // Which file belongs to which module, so an import can be attributed to the
146
+ // module that makes it.
147
+ const ownerOf = new Map();
148
+ for (const [path, units] of listed) {
149
+ for (const unit of units)
150
+ ownerOf.set(unit.file, path);
151
+ }
152
+ // What each module imports from outside the repository. A module called
153
+ // `react` whose files import only type packages is not a rendering edge, and
154
+ // this is how the model can see that rather than infer it from the name.
155
+ const externalByModule = new Map();
156
+ for (const edge of workspace.imports.edges) {
157
+ if (edge.resolution === "resolved")
158
+ continue;
159
+ if (edge.specifier.startsWith(".") || edge.specifier.startsWith("/"))
160
+ continue;
161
+ if (edge.specifier.startsWith("node:"))
162
+ continue;
163
+ const module = ownerOf.get(edge.importer);
164
+ if (module === undefined)
165
+ continue;
166
+ const found = externalByModule.get(module) ?? new Set();
167
+ found.add(packageNameOf(edge.specifier));
168
+ externalByModule.set(module, found);
169
+ }
170
+ // Who imports each module, as paths. The classification can name a module's
171
+ // role but not its rank; `derives_from` needs the importers, and computing
172
+ // them here means the rank question gets them without a second graph walk.
173
+ const importersByModule = new Map();
174
+ for (const edge of workspace.imports.edges) {
175
+ if (edge.resolution === "unresolved")
176
+ continue;
177
+ const from = ownerOf.get(edge.importer);
178
+ const to = ownerOf.get(edge.to);
179
+ if (from === undefined || to === undefined || from === to)
180
+ continue;
181
+ const found = importersByModule.get(to) ?? new Set();
182
+ found.add(from);
183
+ importersByModule.set(to, found);
184
+ }
185
+ const answered = yield* Effect.forEach(listed, ([path, units]) => {
186
+ // A module whose last path segment matches something the repository
187
+ // depends on. `null` is the useful answer: nothing here is called that.
188
+ const last = path.split("/").at(-1) ?? path;
189
+ const collision = names.has(last) ? last : null;
190
+ const repository = context.config.evidence?.repository;
191
+ const panel = {
192
+ module: {
193
+ path,
194
+ declarations: units.length,
195
+ examples: [...new Set(units.map((unit) => unit.file))].slice(0, policy.evidence.maxListedPaths),
196
+ imports: [...(externalByModule.get(path) ?? [])]
197
+ .sort(Order.String)
198
+ .slice(0, policy.evidence.maxListedPaths),
199
+ shares_a_name_with_a_dependency: collision,
200
+ // The module paths that import this one. The rank question uses them
201
+ // for `derives_from`, which is the one position that is a fact about
202
+ // the graph rather than a taste about the words.
203
+ imported_by: [...(importersByModule.get(path) ?? [])]
204
+ .sort((left, right) => left.localeCompare(right))
205
+ .slice(0, policy.evidence.maxListedPaths),
206
+ },
207
+ };
208
+ const evidence = repository === undefined ? panel : { ...panel, repository };
209
+ return DecisionModel.decide(ModuleClassification, { input: evidence }).pipe(Effect.map((result) => Option.some(result.answers.role.label)),
210
+ // One candidate that cannot be read is a drop for that candidate, not a
211
+ // failed run: the other modules still deserve an answer. A model that
212
+ // was never reached is different -- the whole rule steps aside.
213
+ Effect.catchIf((error) => !isUnreachable(error), () => Effect.succeed(Option.none())));
214
+ }, { concurrency: policy.decision.requestConcurrency });
215
+ const roles = new Map();
216
+ const drops = [];
217
+ listed.forEach(([path, units], index) => {
218
+ const role = answered[index];
219
+ if (role === undefined || Option.isNone(role)) {
220
+ for (const _unit of units) {
221
+ drops.push({
222
+ ruleId,
223
+ subject: path,
224
+ stage: "unreadable",
225
+ reason: "the module could not be classified",
226
+ });
227
+ }
228
+ return;
229
+ }
230
+ roles.set(path, role.value);
231
+ });
232
+ // ROUND TWO: where does each role sit? One question over the whole set,
233
+ // because "machinery whose only importers are edges sits below an edge" is a
234
+ // statement about the set and answering it per module throws the set away.
235
+ const distinct = [...new Set(roles.values())].sort((left, right) => left.localeCompare(right));
236
+ const ranks = yield* rankRoles(workspace, context, distinct);
237
+ const unclassified = listed.filter(([path]) => !roles.has(path)).length;
238
+ return {
239
+ roles,
240
+ ranks,
241
+ notes: [
242
+ listed.length +
243
+ " module(s) classified" +
244
+ (unclassified === 0 ? "" : ", " + unclassified + " unreadable"),
245
+ ...(ranks.size === 0
246
+ ? ["the roles could not be ordered, so no direction was checked"]
247
+ : ["roles ordered lowest first: " + orderOf(ranks)]),
248
+ ...budgetNote({
249
+ unitKind: "modules",
250
+ judged: policy.moduleRoles.maxModules,
251
+ candidates: modules.size,
252
+ sample: [...modules.keys()].slice(policy.moduleRoles.maxModules),
253
+ }),
254
+ ],
255
+ drops,
256
+ };
257
+ });
258
+ /**
259
+ * The order the roles sit in, asked for once.
260
+ *
261
+ * A `Choice` can only name one winner, so the question names the LOWEST role in
262
+ * this repository and the rest of the order is derived from the ranks above it:
263
+ * the model answers which role is bottom, and the labels' own numeric order
264
+ * does the rest. `derives_from` is the exception -- it is a statement about who
265
+ * imports this module, and it resolves to `domain` or `edge` by looking at the
266
+ * importers, which is the one part that is a fact.
267
+ *
268
+ * A run with no model key gets an empty map, and every caller treats that as
269
+ * "no order known" rather than guessing one. A rank nobody asked for is the
270
+ * table this replaced.
271
+ */
272
+ const rankRoles = (workspace, context, distinct) => Effect.gen(function* () {
273
+ if (distinct.length === 0)
274
+ return new Map();
275
+ const repository = context.config.evidence?.repository;
276
+ const panel = { roles: [...distinct] };
277
+ const evidence = repository === undefined ? panel : { ...panel, repository };
278
+ const decided = yield* DecisionModel.decide(RoleRanking, { input: evidence });
279
+ const lowest = decided.answers.order.label;
280
+ const ranks = new Map();
281
+ // The answer names the bottom; everything else keeps the relative order the
282
+ // labels encode, shifted so the named bottom is zero.
283
+ const base = rankOfLabel[lowest];
284
+ if (base === undefined)
285
+ return ranks;
286
+ for (const role of distinct) {
287
+ const rank = rankOfLabel[role];
288
+ if (rank === undefined)
289
+ continue;
290
+ ranks.set(role, rank - base);
291
+ }
292
+ return ranks;
293
+ });
294
+ /** The order, for the note. */
295
+ const orderOf = (ranks) => [...ranks.entries()]
296
+ .sort((left, right) => left[1] - right[1] || left[0].localeCompare(right[0]))
297
+ .map(([role]) => role.replace(/_/g, " "))
298
+ .join(" below ");
299
+ /** The role of the module a file belongs to, if it has one. */
300
+ export const roleOfFile = (roles, workspace, file) => {
301
+ const unit = workspace.units.find((candidate) => candidate.file === file);
302
+ return unit === undefined ? undefined : roles.get(moduleOf(unit));
303
+ };
package/dist/rule.js ADDED
@@ -0,0 +1,194 @@
1
+ import { policy } from "./policy.js";
2
+ /** A rule's whole result: its findings, its notes, and the candidates it dropped. */
3
+ export const outcome = (diagnostics, notes = [], drops = []) => ({ diagnostics, notes, drops });
4
+ /**
5
+ * Turn a rule's unjudged findings into a count.
6
+ *
7
+ * A repository without a model key can ask for `count`: the rule still ran and
8
+ * the candidates are real, but printing each one as an unverified warning is
9
+ * noise it does not want. The unverified findings become one note, so the funnel
10
+ * still says how many there were, and the judged findings (there are none when
11
+ * the whole run had no answer) stay. This is the repository's answer to "do not
12
+ * print the candidates", not a claim that the rule found nothing.
13
+ */
14
+ export const countUnjudged = (result, reason) => {
15
+ const unverified = result.diagnostics.filter((entry) => !entry.judged);
16
+ if (unverified.length === 0)
17
+ return result;
18
+ return {
19
+ diagnostics: result.diagnostics.filter((entry) => entry.judged),
20
+ notes: [...result.notes, unverified.length + " candidate(s) were not judged: " + reason],
21
+ drops: result.drops,
22
+ };
23
+ };
24
+ export const everyFile = { changed: undefined, moved: undefined };
25
+ /**
26
+ * True when this declaration's CONTENT is in scope for the run.
27
+ *
28
+ * The default, and what every rule that reads a declaration's body or name
29
+ * wants. A pure rename is deliberately not in scope: its content was already
30
+ * here under another name.
31
+ */
32
+ export const inScope = (scope, file) => scope.changed === undefined || scope.changed.has(file);
33
+ /**
34
+ * True when this file is in scope for a rule that reads the IMPORT GRAPH.
35
+ *
36
+ * A moved file's content is not new, but its edges are: a move can put a module
37
+ * on the wrong side of a boundary it used to respect. So graph rules see the
38
+ * union, and content rules see `changed` alone.
39
+ */
40
+ export const inGraphScope = (scope, file) => scope.changed === undefined || scope.changed.has(file) || (scope.moved?.has(file) ?? false);
41
+ /**
42
+ * Declare a deterministic rule.
43
+ *
44
+ * Identity today, and the seam where a rule gains a name, a severity or a
45
+ * validated shape without every rule file changing.
46
+ */
47
+ export const defineRule = (rule) => rule;
48
+ /**
49
+ * Standard wording for a bound a rule hit, so that no rule invents its own and
50
+ * no reader has to guess whether silence meant "nothing there".
51
+ */
52
+ export const budgetNote = ({ unitKind, judged, candidates, sample }) => candidates <= judged
53
+ ? []
54
+ : [
55
+ `${candidates - judged} of ${candidates} ${unitKind} were not judged (budget ${judged}). Largest unjudged: ${sample.join("; ")}`,
56
+ ];
57
+ /** One line for the producer rules: how many bundles were well formed. */
58
+ export const bundleNote = ({ bundles, broken }) => bundles === 0 ? [] : [`${bundles - broken} of ${bundles} composition bundle(s) follow the pattern`];
59
+ /**
60
+ * Sweep a size-ordered list, visiting only the pairs that could clear a
61
+ * similarity threshold.
62
+ *
63
+ * Kept as the reference implementation: it compares every pair inside the size
64
+ * window, so it is complete by construction. `allPairs` in similarity.ts uses
65
+ * prefix filtering to avoid the quadratic count, and a test asserts the two
66
+ * report the same pairs. When they disagree, this one is right.
67
+ *
68
+ * Jaccard(A, B) >= t implies |A| / |B| >= t, because the intersection cannot be
69
+ * larger than the smaller side. So once the list is sorted by size, each left
70
+ * item has a known window of right items and the scan can stop at the first item
71
+ * past it. That is a completeness-preserving filter: unlike sorting pairs by
72
+ * score and slicing, it cannot drop a pair that would have qualified.
73
+ */
74
+ export const sweep = (ordered, size, threshold, visit) => {
75
+ let compared = 0;
76
+ for (let i = 0; i < ordered.length; i += 1) {
77
+ const left = ordered[i];
78
+ if (left === undefined)
79
+ continue;
80
+ const smaller = size(left.item);
81
+ if (smaller === 0 || threshold <= 0)
82
+ continue;
83
+ const limit = smaller / threshold;
84
+ for (let j = i + 1; j < ordered.length; j += 1) {
85
+ const right = ordered[j];
86
+ if (right === undefined)
87
+ break;
88
+ if (size(right.item) > limit)
89
+ break;
90
+ compared += 1;
91
+ visit(left, right);
92
+ }
93
+ }
94
+ return compared;
95
+ };
96
+ /** Build one diagnostic, with the fields every finding carries. */
97
+ export const finding = (input) => {
98
+ // Built field by field rather than with conditional spreads: an empty-object
99
+ // spread hides the omission, and a reader has to reason about two shapes to
100
+ // see that a field is optional.
101
+ const diagnostic = {
102
+ ruleId: input.ruleId,
103
+ severity: input.severity,
104
+ message: input.message,
105
+ location: input.location,
106
+ judged: input.judged,
107
+ };
108
+ if (input.help !== undefined)
109
+ diagnostic.help = input.help;
110
+ if (input.confidence !== undefined)
111
+ diagnostic.confidence = input.confidence;
112
+ if (input.score !== undefined)
113
+ diagnostic.score = input.score;
114
+ if (input.identity !== undefined)
115
+ diagnostic.identity = input.identity;
116
+ if (input.repair !== undefined)
117
+ diagnostic.repair = input.repair;
118
+ if (input.stoppedAt !== undefined)
119
+ diagnostic.stoppedAt = input.stoppedAt;
120
+ if (input.panel !== undefined)
121
+ diagnostic.panel = input.panel;
122
+ if (input.move !== undefined)
123
+ diagnostic.move = input.move;
124
+ return diagnostic;
125
+ };
126
+ /*
127
+ * The one question every rule asks, and the only answer code reads.
128
+ *
129
+ * It lived in each rule file until joggle reported its own copy of it three
130
+ * times. That is the tool working: the shape was identical, the names were
131
+ * identical, and nothing about the three copies was intentional.
132
+ */
133
+ /**
134
+ * The names a judged question uses to decline, and the only two there are.
135
+ *
136
+ * The TypeSafe docs put `noIssue` in the mechanism map for EVERY dimension --
137
+ * "The selected evidence does not support a concrete correctness issue". It sits
138
+ * beside `condition` and `state` as a member of the vocabulary the model chooses
139
+ * from, not as a low score or an absent answer. So a decline is an ANSWER, and
140
+ * code can read it as one; that is the whole point. A question with no way to
141
+ * decline still gets answered, just with a small number that means nothing.
142
+ *
143
+ * This rule set had four names for two ideas -- `not_duplication`, `distinct`,
144
+ * `keep_local`, `none` -- which meant no shared reader, and no place to see that
145
+ * a question could not say "this is fine". Two names now, used everywhere:
146
+ *
147
+ * no_issue there is no problem here
148
+ * not_applicable the rule is looking at the wrong kind of thing
149
+ *
150
+ * A question that offers either documents it in `instructions.fallback`, so the
151
+ * decline is stated rather than left to be inferred from the option list.
152
+ */
153
+ export const decline = { noIssue: "no_issue", notApplicable: "not_applicable" };
154
+ /** Every name that means "no finding", for tests and for reading a vocabulary. */
155
+ export const declineNames = [decline.noIssue, decline.notApplicable];
156
+ /**
157
+ * True when a Choice declined.
158
+ *
159
+ * An absent choice is NOT a decline: it is silence, and the two are treated
160
+ * differently downstream -- a decline means the rule looked and found nothing,
161
+ * silence means the rule never got an answer.
162
+ */
163
+ export const declined = (choice) => choice === decline.noIssue || choice === decline.notApplicable;
164
+ /** Winner minus runner-up in a classify answer's own distribution. */
165
+ export const marginOfAnswer = (answer) => {
166
+ const ranked = Object.values(answer.probabilities).sort((left, right) => right - left);
167
+ const [first, second] = ranked;
168
+ if (first === undefined)
169
+ return 1;
170
+ return second === undefined ? 1 : first - second;
171
+ };
172
+ /**
173
+ * Which range an answer falls in.
174
+ *
175
+ * A judgement that fails its floor is not a worse judgement, it is not a
176
+ * judgement: callers treat it exactly as they treat an absent answer, which is
177
+ * what keeps one gate from having to know how each rule degrades. A judgement
178
+ * that is merely uncertain is still a judgement, and is reported.
179
+ */
180
+ export const qualityOf = (input) => {
181
+ const round = (value) => value.toFixed(2);
182
+ if (input.score < policy.decision.gates.probabilityFloor) {
183
+ return { quality: "drop", reason: `the yes/no question answered no (${round(input.score)})` };
184
+ }
185
+ if (input.margin !== undefined && input.margin < policy.decision.gates.minMargin) {
186
+ return { quality: "review", reason: `the choice was not decisive (margin ${round(input.margin)})` };
187
+ }
188
+ if (input.confidence !== undefined && input.confidence < policy.decision.gates.reviewFloor) {
189
+ return { quality: "review", reason: `the answer was not certain (confidence ${round(input.confidence)})` };
190
+ }
191
+ return { quality: "act", reason: "" };
192
+ };
193
+ /** Short, human-readable "file:line:col" for messages. */
194
+ export const at = (location) => `${location.file}:${location.line}:${location.column}`;