@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
@@ -0,0 +1,190 @@
1
+ import { Effect } from "effect";
2
+ import { Decision } from "effect/ai";
3
+ import { Atoms } from "../atoms.js";
4
+ import { policy } from "../policy.js";
5
+ import { verdictsOf } from "../plans.js";
6
+ import { locator, messages, reporter } from "../reporting.js";
7
+ import { budgetNote, inScope, outcome, qualityOf, } from "../rule.js";
8
+ import { readsIn } from "../sql.js";
9
+ import { verdictOf } from "../verdict.js";
10
+ const RULE_ID = "joggle/invariant-has-a-reconciler";
11
+ // An exported check over stored rows, and no repair path beside it.
12
+ //
13
+ // The deterministic half is structural: an exported function, a table read, and
14
+ // enough body to be a check rather than a getter. There is no list of words that
15
+ // mean "invariant" -- `sum`, `balance` and `reconcile` are the property names of
16
+ // one repository, and the point of the rule is to find the checks whose names
17
+ // nobody thought to make memorable.
18
+ //
19
+ // A domain package of pure functions offers LOCAL correctness. An invariant that
20
+ // spans rows and time cannot be parsed into existence at a boundary; it is
21
+ // detected, repaired, and the residual reported. `detect_only` is the finding.
22
+ export const invariantHasAReconciler = {
23
+ id: RULE_ID,
24
+ severity: "warn",
25
+ description: "An exported check over stored rows with no repair path.",
26
+ judged: true,
27
+ onUnavailable: "report",
28
+ messages: messages({
29
+ detectOnly: "`{{unit}}` can tell that `{{tables}}` violates an invariant, and nothing restores it.",
30
+ detectOnly_help: "An invariant that spans rows and time cannot be parsed into existence at a boundary. Declare it once, detect it, and name the path that repairs it -- or say that the repair is a human decision, which is a path with an authority.{{unverified}}",
31
+ }),
32
+ plan: Effect.fn("joggle/invariant-has-a-reconciler")(function* (workspace, scope) {
33
+ const report = reporter(invariantHasAReconciler, locator(workspace));
34
+ const candidates = [];
35
+ for (const file of workspace.files) {
36
+ if (scope.changed !== undefined && !inScope(scope, file.path))
37
+ continue;
38
+ const tables = readsIn(file.text);
39
+ if (tables.length === 0)
40
+ continue;
41
+ for (const unit of file.units) {
42
+ if (!unit.exported || unit.kind !== "function")
43
+ continue;
44
+ // A getter is not an invariant: it has no body to check anything with.
45
+ if (unit.tokens.length < policy.strata.minInvariantTokens)
46
+ continue;
47
+ candidates.push({ unit, tables });
48
+ }
49
+ }
50
+ if (candidates.length === 0) {
51
+ return {
52
+ plans: [],
53
+ read: () => outcome([], [
54
+ "no exported function over stored rows was found",
55
+ ]),
56
+ };
57
+ }
58
+ const judged = candidates.slice(0, policy.strata.maxCandidates);
59
+ const overBudget = candidates
60
+ .slice(policy.strata.maxCandidates)
61
+ .map((candidate) => ({
62
+ ruleId: RULE_ID,
63
+ subject: candidate.unit.name,
64
+ stage: "budget",
65
+ reason: "past the budget of " + String(policy.strata.maxCandidates) + " checks",
66
+ }));
67
+ const atoms = yield* Atoms;
68
+ const planned = yield* Effect.forEach(judged, (candidate) => Effect.gen(function* () {
69
+ const id = yield* atoms.add({
70
+ check: {
71
+ unit: candidate.unit.name,
72
+ file: candidate.unit.file,
73
+ tables: [...candidate.tables],
74
+ },
75
+ source: candidate.unit.text.slice(0, policy.evidence.maxSourceChars),
76
+ });
77
+ const plan = {
78
+ ruleId: RULE_ID,
79
+ subject: candidate.unit.name,
80
+ concerns: [candidate.unit.file],
81
+ atoms: [id],
82
+ violations: { verdict: ["detect_only"] },
83
+ decisions: {
84
+ verdict: Decision.classify({
85
+ instructions: {
86
+ question: "If stored data violates this, what restores it?",
87
+ check: `\`atoms[${id}].check.unit\` reads \`atoms[${id}].check.tables\`.`,
88
+ compare: [
89
+ `atoms[${id}].check`,
90
+ `atoms[${id}].source`,
91
+ ],
92
+ focus: "Read what the function DOES with the rows. A predicate that returns a report is `detect_only`; a function that also writes a correction, emits a repair command, or names the human authority who decides is `repair_path`. A validation that must stay manual because repair needs a person's decision is `repair_path` too: naming that authority IS the path. `not_an_invariant` is a read that checks nothing that spans rows or time.",
93
+ },
94
+ criteria: {
95
+ repair_path: {
96
+ means: "Something restores the invariant: a repair write, a reconciliation job, or a named human authority who decides.",
97
+ excludes: "A check that only reports the violation.",
98
+ },
99
+ detect_only: {
100
+ means: "The code can see that the books do not balance and can do nothing about it.",
101
+ excludes: "A repair path, including one that ends at a person.",
102
+ },
103
+ not_an_invariant: {
104
+ means: "The function is a read or a projection, not a property over rows and time.",
105
+ excludes: "A check whose violation has a defined repair.",
106
+ },
107
+ },
108
+ }),
109
+ },
110
+ read: (answers) => answers,
111
+ };
112
+ return { candidate, plan };
113
+ }), { concurrency: "unbounded" });
114
+ return {
115
+ plans: planned.map((entry) => entry.plan),
116
+ read: (answers) => {
117
+ const verdicts = verdictsOf(answers);
118
+ const diagnostics = [];
119
+ const drops = [...overBudget];
120
+ planned.forEach((entry, index) => {
121
+ const { candidate } = entry;
122
+ const verdict = verdictOf(verdicts[index]?.["verdict"], ["detect_only"]);
123
+ if (verdict === undefined) {
124
+ diagnostics.push(findingFor({
125
+ report,
126
+ entry,
127
+ confidence: undefined,
128
+ unverifiedReason: "no judgement was available",
129
+ }));
130
+ return;
131
+ }
132
+ if (verdict.label !== "detect_only") {
133
+ drops.push({
134
+ ruleId: RULE_ID,
135
+ subject: candidate.unit.name,
136
+ stage: "declined",
137
+ reason: verdict.label === "repair_path"
138
+ ? "a repair path exists"
139
+ : "not an invariant",
140
+ });
141
+ return;
142
+ }
143
+ const quality = qualityOf({
144
+ score: verdict.probability,
145
+ margin: verdict.margin,
146
+ confidence: verdict.confidence,
147
+ });
148
+ if (quality.quality === "drop") {
149
+ drops.push({
150
+ ruleId: RULE_ID,
151
+ subject: candidate.unit.name,
152
+ stage: "gated",
153
+ reason: quality.reason,
154
+ });
155
+ return;
156
+ }
157
+ diagnostics.push(findingFor({
158
+ report,
159
+ entry,
160
+ confidence: verdict.confidence,
161
+ unverifiedReason: undefined,
162
+ review: quality.quality === "review",
163
+ }));
164
+ });
165
+ return outcome(diagnostics, budgetNote({
166
+ unitKind: "checks",
167
+ judged: judged.length,
168
+ candidates: candidates.length,
169
+ sample: candidates
170
+ .slice(policy.strata.maxCandidates)
171
+ .map((candidate) => candidate.unit.name),
172
+ }), drops);
173
+ },
174
+ };
175
+ }),
176
+ };
177
+ const findingFor = ({ report, entry, confidence, unverifiedReason, review = false, }) => report({
178
+ about: entry.candidate.unit,
179
+ messageId: "detectOnly",
180
+ data: {
181
+ unit: entry.candidate.unit.name,
182
+ tables: entry.candidate.tables.join(", "),
183
+ unverified: unverifiedReason === undefined ? "" : " Not verified: " + unverifiedReason + ".",
184
+ },
185
+ helpId: "detectOnly_help",
186
+ identity: [RULE_ID, entry.candidate.unit.file, entry.candidate.unit.name].join("\u0000"),
187
+ judged: unverifiedReason === undefined,
188
+ confidence,
189
+ severity: review ? "info" : "warn",
190
+ });
@@ -0,0 +1,234 @@
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, declined, outcome, qualityOf, } from "../rule.js";
9
+ // meta-allow: no-pattern-classifier -- `termsOf` tokenises prose -- a capitalised word, a sentence end -- which is
10
+ // unavoidable text parsing of a doc block, not a classification of the code. docs/rule-coupling.md.
11
+ const RULE_ID = "joggle/language-drift";
12
+ /**
13
+ * The label that means "none of these words is a concept".
14
+ *
15
+ * A reserved word, not `none`: the candidate words come from prose, and a doc block that
16
+ * says `None` mid-sentence becomes the term `none`. With `none` as the sentinel the two
17
+ * collide into one label, and Effect 4.0.5 rejects a `Classify` with fewer than two labels
18
+ * — a real crash the older line allowed. An underscore cannot survive `termsOf`, so this
19
+ * label can never be a candidate.
20
+ */
21
+ const NO_CONCEPT = "no_concept";
22
+ /**
23
+ * A domain word the prose uses and the code does not.
24
+ *
25
+ * The CANDIDATE is structural: a capitalized word the doc blocks repeat and no
26
+ * declaration, path or import uses. That is a fact, and a cheap one.
27
+ *
28
+ * The JUDGEMENT is whether the word names a domain concept the code calls
29
+ * something else. A stopword list cannot answer it -- the first version reported
30
+ * "whether", "what" and "every", and no list makes a heuristic correct. So the
31
+ * model picks the concept, or says none, and code reports what it picked.
32
+ *
33
+ * The words are the Choice's options, one per candidate, so the answer names
34
+ * which one is a concept rather than only that one exists.
35
+ */
36
+ const wordsOf = (name) => name
37
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
38
+ .split(/[^A-Za-z0-9]+/)
39
+ .map((word) => word.toLowerCase())
40
+ .filter((word) => word.length > 0);
41
+ /** The capitalized words that are not at the start of a sentence. */
42
+ const termsOf = (doc) => {
43
+ const words = doc.split(/\s+/);
44
+ const terms = [];
45
+ for (let index = 0; index < words.length; index += 1) {
46
+ const raw = words[index] ?? "";
47
+ const clean = /^[^A-Za-z0-9]*([A-Z][A-Za-z0-9]{3,})/.exec(raw)?.[1];
48
+ if (clean === undefined)
49
+ continue;
50
+ const previous = words[index - 1] ?? "";
51
+ if (index === 0 || previous === "" || /[.:;!?]$/.test(previous))
52
+ continue;
53
+ // Split a camel-cased word the same way a declaration name is split, so
54
+ // prose that writes `SortedByDate` is compared as `sorted`/`by`/`date` and
55
+ // not as one lowercase blob that no name can ever contain.
56
+ // No stop-list: whether a word is a domain concept is the QUESTION, and a
57
+ // hand-maintained list of tech words was deciding it (docs/rule-coupling.md).
58
+ for (const part of wordsOf(clean))
59
+ terms.push(part);
60
+ }
61
+ return terms;
62
+ };
63
+ /** The one question about a file, pointing at its atom by id. */
64
+ const languageReview = (id, words) => {
65
+ const criteria = {
66
+ [NO_CONCEPT]: "None of these is a concept the code names differently.",
67
+ };
68
+ for (const word of words)
69
+ criteria[word] = "The prose says \"" + word + "\" and no name uses it.";
70
+ return {
71
+ concept: Decision.classify({
72
+ instructions: [
73
+ `The doc blocks of \`atoms[${id}].file.path\` repeat the words in \`atoms[${id}].file.words\`, and no declaration, path or import uses any of them.`,
74
+ "Which one, if any, names a concept this code calls something else?",
75
+ "Choose a word when the prose is naming a thing -- an entity, a process, a rule -- and the code names that thing differently.",
76
+ "Choose `" + NO_CONCEPT + "` when the words are ordinary English, the technology stack, or something the code does not model at all.",
77
+ ].join("\n"),
78
+ criteria,
79
+ }),
80
+ };
81
+ };
82
+ const candidatesIn = (workspace, scope) => {
83
+ const identifiers = new Set();
84
+ for (const unit of workspace.units) {
85
+ for (const word of wordsOf(unit.name))
86
+ identifiers.add(word);
87
+ for (const segment of unit.file.split("/"))
88
+ for (const word of wordsOf(segment))
89
+ identifiers.add(word);
90
+ }
91
+ for (const file of workspace.files) {
92
+ for (const imported of file.importStatements) {
93
+ for (const name of imported.names)
94
+ for (const word of wordsOf(name))
95
+ identifiers.add(word);
96
+ }
97
+ }
98
+ const found = [];
99
+ for (const file of workspace.files) {
100
+ if (scope.changed !== undefined && !scope.changed.has(file.path))
101
+ continue;
102
+ const counts = new Map();
103
+ const docs = [];
104
+ for (const unit of file.units) {
105
+ if (unit.doc === undefined)
106
+ continue;
107
+ docs.push(unit.doc.slice(0, policy.evidence.maxDocChars));
108
+ for (const term of termsOf(unit.doc)) {
109
+ if (identifiers.has(term))
110
+ continue;
111
+ counts.set(term, (counts.get(term) ?? 0) + 1);
112
+ }
113
+ }
114
+ const words = [...counts.entries()]
115
+ .filter(([, count]) => count >= policy.languageDrift.minMentions)
116
+ .map(([word]) => word)
117
+ .sort((left, right) => left.localeCompare(right));
118
+ if (words.length > 0)
119
+ found.push({ source: file, words, docs });
120
+ }
121
+ return found;
122
+ };
123
+ export const languageDrift = {
124
+ id: RULE_ID,
125
+ severity: "info",
126
+ description: "A domain word the prose uses and the code never names.",
127
+ judged: true,
128
+ move: "expand",
129
+ onUnavailable: "propagate",
130
+ messages: messages({
131
+ prose_word_not_named: 'The prose says "{{word}}", and no declaration, path or import uses the word.',
132
+ prose_word_not_named_help: "Either the code is named for something else, or the prose describes a concept the code has not named. The first is drift; the second is a missing name.",
133
+ }),
134
+ plan: Effect.fn("joggle/language-drift")(function* (workspace, scope) {
135
+ const report = reporter(languageDrift, locator(workspace));
136
+ const candidates = candidatesIn(workspace, scope);
137
+ if (candidates.length === 0) {
138
+ return {
139
+ plans: [],
140
+ read: () => outcome([], ["every domain word in the prose is also a word in a name"]),
141
+ };
142
+ }
143
+ const budget = policy.languageDrift.maxFiles;
144
+ const judged = candidates.slice(0, budget);
145
+ const atoms = yield* Atoms;
146
+ const planned = [];
147
+ for (const candidate of judged) {
148
+ const id = yield* atoms.add({
149
+ file: {
150
+ path: candidate.source.path,
151
+ words: candidate.words,
152
+ docs: candidate.docs.join("\n\n"),
153
+ },
154
+ });
155
+ planned.push({
156
+ candidate,
157
+ plan: {
158
+ ruleId: RULE_ID,
159
+ subject: candidate.source.path,
160
+ concerns: [candidate.source.path],
161
+ atoms: [id],
162
+ violations: { concept: candidate.words },
163
+ decisions: languageReview(id, candidate.words),
164
+ read: (answers) => answers,
165
+ },
166
+ });
167
+ }
168
+ const overflow = candidates.slice(budget).map((candidate) => ({
169
+ ruleId: RULE_ID,
170
+ subject: candidate.source.path,
171
+ stage: "budget",
172
+ reason: "past the budget of " + budget + " files with prose words",
173
+ }));
174
+ return {
175
+ plans: planned.map((entry) => entry.plan),
176
+ read: (answers) => {
177
+ const verdicts = verdictsOf(answers);
178
+ const diagnostics = [];
179
+ const drops = [...overflow];
180
+ planned.forEach((entry, index) => {
181
+ const candidate = entry.candidate;
182
+ const answer = verdicts[index];
183
+ if (answer === undefined) {
184
+ drops.push({ ruleId: RULE_ID, subject: candidate.source.path, stage: "unreadable", reason: "the response did not judge this file" });
185
+ return;
186
+ }
187
+ const concept = answer["concept"];
188
+ const verdict = verdictOf(concept, candidate.words);
189
+ if (verdict === undefined) {
190
+ drops.push({ ruleId: RULE_ID, subject: candidate.source.path, stage: "unreadable", reason: "the response did not contain a verdict" });
191
+ return;
192
+ }
193
+ if (verdict.label === NO_CONCEPT || declined(verdict.label)) {
194
+ drops.push({ ruleId: RULE_ID, subject: candidate.source.path, stage: "declined", reason: "none of the words names a concept" });
195
+ return;
196
+ }
197
+ const quality = qualityOf({
198
+ score: verdict.probability,
199
+ margin: verdict.margin,
200
+ confidence: verdict.confidence,
201
+ });
202
+ // This rule asks a model to guess whether an English word in a comment is
203
+ // a domain concept, and it is the noisiest one it has. A confident answer
204
+ // is a finding; an unsure one is the model saying it cannot tell, and a
205
+ // file-level notice at confidence 0.56 is noise. So only `act` is
206
+ // reported -- unlike the duplicate rules, where an unsure answer still
207
+ // points at two declarations a reader can compare.
208
+ if (quality.quality === "drop") {
209
+ drops.push({ ruleId: RULE_ID, subject: candidate.source.path, stage: "gated", reason: quality.reason });
210
+ return;
211
+ }
212
+ const review = quality.quality === "review";
213
+ diagnostics.push(report({
214
+ about: candidate.source,
215
+ messageId: "prose_word_not_named",
216
+ data: { word: verdict.label ?? "" },
217
+ helpId: "prose_word_not_named_help",
218
+ identity: [RULE_ID, verdict.label].join("\u0000"),
219
+ confidence: verdict.confidence ?? 1,
220
+ score: verdict.probability,
221
+ judged: true,
222
+ severity: review ? "info" : "warn",
223
+ }));
224
+ });
225
+ return outcome(diagnostics, budgetNote({
226
+ unitKind: "files with prose words",
227
+ judged: budget,
228
+ candidates: candidates.length,
229
+ sample: candidates.slice(budget).map((candidate) => candidate.source.path),
230
+ }), drops);
231
+ },
232
+ };
233
+ })
234
+ };
@@ -0,0 +1,189 @@
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
+ import { unitFields } from "../workspace.js";
10
+ const RULE_ID = "joggle/meaning-switched-by-flag";
11
+ export const meaningSwitchedByFlag = {
12
+ id: RULE_ID,
13
+ severity: "warn",
14
+ description: "One field standing for two things, switched by a sibling flag.",
15
+ judged: true,
16
+ move: "expand",
17
+ onUnavailable: "report",
18
+ messages: messages({
19
+ switched: "{{unit}} branches on `{{flag}}`, a boolean on {{owner}} whose fields include {{fields}}.",
20
+ switched_help: "If a value's meaning depends on `{{flag}}`, it is two things wearing one name: model it as a union (or two named fields) so the reader cannot take the wrong reading. The breakdown and the total drifted apart because each was read under a different flag.{{unverified}}",
21
+ }),
22
+ plan: Effect.fn("joggle/meaning-switched-by-flag")(function* (workspace, scope) {
23
+ const report = reporter(meaningSwitchedByFlag, locator(workspace));
24
+ // The boolean flags, by name, with the row type they sit on.
25
+ const flags = new Map();
26
+ for (const unit of workspace.units) {
27
+ if (unit.kind !== "interface" && unit.kind !== "type")
28
+ continue;
29
+ for (const [field, annotation] of unit.fieldTypes) {
30
+ // `fieldTypes` keeps the annotation with its colon: ": boolean".
31
+ if (annotation.replace(/^\s*:\s*/, "").trim() !== "boolean")
32
+ continue;
33
+ if (!flags.has(field)) {
34
+ flags.set(field, { field, unitName: unit.name, file: unit.file, fields: unitFields(unit) });
35
+ }
36
+ }
37
+ }
38
+ if (flags.size === 0) {
39
+ return {
40
+ plans: [],
41
+ read: () => outcome([], ["no declared field is a boolean, so there is no flag to branch on"]),
42
+ };
43
+ }
44
+ const candidates = [];
45
+ for (const file of workspace.files) {
46
+ if (scope.changed !== undefined && !inScope(scope, file.path))
47
+ continue;
48
+ for (const guard of file.facts.guards) {
49
+ const unit = file.units.find((entry) => guard.start >= entry.start && guard.end <= entry.end);
50
+ if (unit === undefined)
51
+ continue;
52
+ if (unit.text.length > policy.evidence.maxSourceChars)
53
+ continue;
54
+ const named = guard.refs
55
+ .map((ref) => ref.slice(ref.lastIndexOf(".") + 1))
56
+ .map((name) => flags.get(name))
57
+ .find((flag) => flag !== undefined);
58
+ if (named === undefined)
59
+ continue;
60
+ candidates.push({ unit, guard, flag: named });
61
+ }
62
+ }
63
+ if (candidates.length === 0) {
64
+ return {
65
+ plans: [],
66
+ read: () => outcome([], ["no guard branches on a field another declaration types as a boolean"]),
67
+ };
68
+ }
69
+ const budget = policy.evidence.maxMembers * 12;
70
+ const judged = candidates.slice(0, budget);
71
+ const overBudget = candidates.slice(budget).map((candidate) => ({
72
+ ruleId: RULE_ID,
73
+ subject: candidate.unit.name,
74
+ stage: "budget",
75
+ reason: "past the budget of " + String(budget) + " flag branches",
76
+ }));
77
+ const textOf = new Map(workspace.files.map((file) => [file.path, file.text]));
78
+ const atoms = yield* Atoms;
79
+ const planned = yield* Effect.forEach(judged, (candidate) => Effect.gen(function* () {
80
+ const text = textOf.get(candidate.unit.file) ?? "";
81
+ const id = yield* atoms.add({
82
+ branch: {
83
+ unit: candidate.unit.name,
84
+ file: candidate.unit.file,
85
+ guard: text.slice(candidate.guard.start, Math.min(candidate.guard.end, candidate.guard.start + 200)),
86
+ },
87
+ flag: { ...candidate.flag, fields: [...candidate.flag.fields] },
88
+ source: candidate.unit.text.slice(0, policy.evidence.maxSourceChars),
89
+ });
90
+ const plan = {
91
+ ruleId: RULE_ID,
92
+ subject: candidate.unit.name + " (on " + candidate.flag.field + ")",
93
+ concerns: [candidate.unit.file, candidate.flag.file],
94
+ atoms: [id],
95
+ violations: { verdict: ["meaning_switched"] },
96
+ decisions: {
97
+ verdict: Decision.classify({
98
+ instructions: [
99
+ `\`atoms[${id}].source\` branches on \`atoms[${id}].flag.field\` (\`atoms[${id}].branch.guard\`).`,
100
+ `That field is a \`boolean\` on \`atoms[${id}].flag.unitName\`, whose fields are \`atoms[${id}].flag.fields\`.`,
101
+ "Does a value's MEANING depend on the flag -- is the same field standing for two different things, one under each reading?",
102
+ "Answer `meaning_switched` when a sibling field means one thing when the flag is true and another when it is false, so it should be a union or two named fields.",
103
+ "Answer `independent` when the flag selects behaviour but no value changes meaning -- a permission, a route, a branch with its own result.",
104
+ "Answer `appropriate` when the flag and the value genuinely belong together as written.",
105
+ ].join("\n"),
106
+ criteria: {
107
+ meaning_switched: "One name, two meanings, switched by the flag. Model it as a union.",
108
+ independent: "The flag selects behaviour; no value changes meaning.",
109
+ appropriate: "The flag and the value belong together.",
110
+ },
111
+ }),
112
+ },
113
+ read: (answers) => answers,
114
+ };
115
+ return { candidate, plan };
116
+ }), { concurrency: "unbounded" });
117
+ return {
118
+ plans: planned.map((entry) => entry.plan),
119
+ read: (answers) => {
120
+ const verdicts = verdictsOf(answers);
121
+ const diagnostics = [];
122
+ const drops = [...overBudget];
123
+ planned.forEach((entry, index) => {
124
+ const { candidate } = entry;
125
+ const subject = candidate.unit.name + " (on " + candidate.flag.field + ")";
126
+ const verdict = verdictOf(verdicts[index]?.["verdict"], ["meaning_switched"]);
127
+ if (verdict === undefined) {
128
+ diagnostics.push(findingFor({
129
+ report,
130
+ entry,
131
+ confidence: undefined,
132
+ unverifiedReason: "no judgement was available",
133
+ }));
134
+ return;
135
+ }
136
+ if (verdict.label !== "meaning_switched") {
137
+ drops.push({
138
+ ruleId: RULE_ID,
139
+ subject,
140
+ stage: "declined",
141
+ reason: verdict.label === "independent"
142
+ ? "the flag selects behaviour; no value changes meaning"
143
+ : "the flag and the value belong together",
144
+ });
145
+ return;
146
+ }
147
+ const quality = qualityOf({
148
+ score: verdict.probability,
149
+ margin: verdict.margin,
150
+ confidence: verdict.confidence,
151
+ });
152
+ if (quality.quality === "drop") {
153
+ drops.push({ ruleId: RULE_ID, subject, stage: "gated", reason: quality.reason });
154
+ return;
155
+ }
156
+ diagnostics.push(findingFor({
157
+ report,
158
+ entry,
159
+ confidence: verdict.confidence,
160
+ unverifiedReason: undefined,
161
+ review: quality.quality === "review",
162
+ }));
163
+ });
164
+ return outcome(diagnostics, budgetNote({
165
+ unitKind: "flag branches",
166
+ judged: budget,
167
+ candidates: candidates.length,
168
+ sample: candidates.slice(budget).map((candidate) => candidate.unit.name),
169
+ }), drops);
170
+ },
171
+ };
172
+ }),
173
+ };
174
+ const findingFor = ({ report, entry, confidence, unverifiedReason, review = false, }) => report({
175
+ about: { file: entry.candidate.unit.file, start: entry.candidate.guard.start },
176
+ messageId: "switched",
177
+ data: {
178
+ unit: entry.candidate.unit.name,
179
+ flag: entry.candidate.flag.field,
180
+ owner: entry.candidate.flag.unitName,
181
+ fields: entry.candidate.flag.fields.slice(0, 8).join(", "),
182
+ unverified: unverifiedReason === undefined ? "" : " Not verified: " + unverifiedReason + ".",
183
+ },
184
+ helpId: "switched_help",
185
+ identity: [RULE_ID, entry.candidate.unit.file, entry.candidate.unit.name, entry.candidate.flag.field].join("\u0000"),
186
+ judged: unverifiedReason === undefined,
187
+ confidence,
188
+ severity: review ? "info" : "warn",
189
+ });