@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,288 @@
1
+ import { Effect } from "effect";
2
+ import { Decision } from "effect/ai";
3
+ import { Atoms } from "../atoms.js";
4
+ import { policy } from "../policy.js";
5
+ import { verdictsOf } from "../plans.js";
6
+ import { locator, messages, reporter } from "../reporting.js";
7
+ import { budgetNote, declined, marginOfAnswer, qualityOf, outcome, } from "../rule.js";
8
+ import { classifyModules, moduleOf } from "../roles.js";
9
+ import { dutyVocabulary, EDGE_ROLES, edgeRolesOf, homeVocabulary } from "../vocabulary.js";
10
+ const RULE_ID = "joggle/hoist-to-domain";
11
+ /*
12
+ * Business logic that lives at the edge and belongs in the middle.
13
+ *
14
+ * The other half of a domain migration. `dependency-fit` asks what a package
15
+ * depends on; this asks where the RULES live -- a calculation, an invariant, a
16
+ * decision about the business sitting in a route handler or a React component,
17
+ * where it will be re-implemented the moment a second caller needs it.
18
+ *
19
+ * Nothing here is derived from a config. The candidate filter is structural (a
20
+ * non-trivial exported declaration), and the two judgements are the ones a
21
+ * reviewer actually makes: what IS this declaration, and is this file already
22
+ * where logic like this belongs. The second question is what a declared `domain`
23
+ * layer would have answered, and the model answers it from the path and the
24
+ * prose instead.
25
+ */
26
+ /**
27
+ * Route and framework exports that exist because a framework requires them.
28
+ *
29
+ * A `loader` is not a hoist candidate whatever it contains; the framework asked
30
+ * for it by name. Everything a loader CALLS is fair game, which is why the filter
31
+ * is by name and not by file.
32
+ */
33
+ const isCandidate = (unit) => {
34
+ if (!unit.exported)
35
+ return false;
36
+ if (unit.kind !== "function")
37
+ return false;
38
+ // Names a framework calls by file. Nothing to hoist and nothing to merge,
39
+ // whatever the declaration contains -- the list lives in policy because two
40
+ // rules need it and a second copy is a second thing to update.
41
+ if (policy.frameworkExports.some((name) => name === unit.name))
42
+ return false;
43
+ // Test declarations are compared against each other by the duplicate rules and
44
+ // are candidates for nothing here: a fixture is not a business rule.
45
+ if (unit.test)
46
+ return false;
47
+ // A declaration with nothing in it has no rule in it either.
48
+ if (unit.tokens.length < policy.hoistToDomain.minTokens)
49
+ return false;
50
+ // A React component renders; it does not decide. Components are recognised by
51
+ // the name convention rather than by JSX, because a component can return
52
+ // another component's output and never write a tag itself.
53
+ const first = unit.name[0];
54
+ if (first !== undefined && first >= "A" && first <= "Z")
55
+ return false;
56
+ return true;
57
+ };
58
+ /**
59
+ * Whether everything that uses this declaration is a test.
60
+ *
61
+ * A helper only tests reach for is test support, whatever directory it sits in.
62
+ * `services/db/src/support/seed-kit.js` is not in a test folder and every one of
63
+ * its declarations exists for tests -- and it ranked FIRST, because a seed helper
64
+ * names types, compares values and is imported widely.
65
+ *
66
+ * Derived from the import graph, which already knows who imports what, so this
67
+ * cannot go stale and needs no list of support directories.
68
+ */
69
+ const onlyTestsUse = (unit, workspace) => {
70
+ const importers = workspace.imports.importersOfName(unit.file, unit.name);
71
+ if (importers.length === 0)
72
+ return false;
73
+ return importers.every((edge) => policy.testFiles.test(edge.importer));
74
+ };
75
+ const candidatesIn = (workspace, scope) => workspace.units
76
+ .filter(isCandidate)
77
+ .filter((unit) => !onlyTestsUse(unit, workspace))
78
+ .filter((unit) => scope.changed === undefined || scope.changed.has(unit.file))
79
+ // Ordered by path, NOT by rule-likeness. I built that score and it was worse
80
+ // than nothing: "somebody else imports it" promoted a CRUD delete above an
81
+ // authorization rule, because such a function is imported widely, names types
82
+ // and compares values -- every signal I chose. What separates a rule from a
83
+ // query is what the body DOES, and that is a judgement rather than a shape.
84
+ // Ranking by a guess about it spent the budget on the wrong end of the list.
85
+ //
86
+ .sort((left, right) => left.file.localeCompare(right.file) || left.start - right.start);
87
+ /** The two questions about one declaration, pointing at its atom by id. */
88
+ const hoistReview = (id) => ({
89
+ duty: Decision.classify({
90
+ instructions: [
91
+ `What is \`atoms[${id}].declaration.name\` doing?`,
92
+ `Inspect \`atoms[${id}].declaration\` and \`atoms[${id}].repository\`.`,
93
+ `\`atoms[${id}].repository\` describes what this codebase is trying to be. Judge what this declaration IS, not the directory it sits in: the same calculation is a domain rule in any file. A rule, an invariant or a decision about the business is \`domain_logic\` no matter which file holds it.`,
94
+ "Choose `request_validation` when the rule is about what the endpoint ACCEPTS -- a required field, a range, a mutual exclusion, a 400 -- rather than about the business.",
95
+ "Choose `input_adaptation` when its only job is to reshape input into what another layer (usually the domain's own parser) expects.",
96
+ "Choose `mechanical` for a cache key, an identifier or a lookup table.",
97
+ "Choose `infrastructure` when it takes a database handle (Knex, a transaction, a connection) or runs a query. The domain is pure by design, so moving SQL into it is the wrong repair, however much business logic the query's result carries.",
98
+ "Choose `orchestration` when it mostly calls other things and decides little itself.",
99
+ ].join("\n"),
100
+ criteria: dutyVocabulary,
101
+ }),
102
+ home: Decision.classify({
103
+ instructions: [
104
+ `Is \`atoms[${id}].declaration.path\` already the right home for logic like this?`,
105
+ `Inspect \`atoms[${id}].declaration.path\` and \`atoms[${id}].repository\`.`,
106
+ `Decide by the path and what \`atoms[${id}].repository\` says the architecture is. A route, a component directory or a transport handler is not a home for business rules; a domain or model package is.`,
107
+ ].join("\n"),
108
+ criteria: homeVocabulary,
109
+ }),
110
+ });
111
+ export const hoistToDomain = {
112
+ id: RULE_ID,
113
+ severity: "warn",
114
+ description: "Business logic at the edge that belongs in a domain package.",
115
+ judged: true,
116
+ move: "expand",
117
+ onUnavailable: "report",
118
+ messages: messages({
119
+ rule_at_the_edge: "{{name}} in {{file}} is a rule about the business, living in {{home}}.",
120
+ rule_at_the_edge_help: "Move it into the domain package and import it from here. Business rules at the edge get re-implemented by the next caller, and the two copies then disagree. If this is deliberately local, pin the decision in the config so the question is not asked again.",
121
+ }),
122
+ plan: Effect.fn("joggle/hoist-to-domain")(function* (workspace, scope, context) {
123
+ const report = reporter(hoistToDomain, locator(workspace));
124
+ const all = candidatesIn(workspace, scope);
125
+ // Declared before its first use, not after: a generator's body is one scope and
126
+ // the type checker cannot see the temporal dead zone that produced
127
+ // "Cannot access 'label' before initialization" at runtime.
128
+ const label = (unit) => unit.name + " (" + unit.file + ")";
129
+ if (all.length === 0) {
130
+ return {
131
+ plans: [],
132
+ read: () => outcome([], [
133
+ "no exported declaration was long enough to hold a business rule, so nothing was a hoist candidate",
134
+ ]),
135
+ };
136
+ }
137
+ // ROUND ONE: what is each module for?
138
+ //
139
+ // The same classification `module-direction` uses, shared rather than
140
+ // repeated: one Decision, one answer, and the content-addressed cache makes
141
+ // the second reader free. Business logic at the edge is only a problem at an
142
+ // edge, so a declaration in a domain package or a utility module is not a
143
+ // hoist candidate whatever it contains.
144
+ const classified = yield* classifyModules(workspace, context, RULE_ID);
145
+ const edge = new Map();
146
+ const notAnEdge = [];
147
+ // Derived from the rank the run decided, so a repository whose outer layer is
148
+ // the API rather than the UI gets the right edge. The constant is the
149
+ // fallback for a run that could not order the roles.
150
+ const edgeRoles = classified.ranks.size === 0 ? EDGE_ROLES : edgeRolesOf(classified.ranks);
151
+ for (const unit of all) {
152
+ const path = moduleOf(unit);
153
+ const role = classified.roles.get(path);
154
+ if (role !== undefined && edgeRoles.has(role)) {
155
+ edge.set(path, role);
156
+ continue;
157
+ }
158
+ notAnEdge.push({
159
+ ruleId: RULE_ID,
160
+ subject: label(unit),
161
+ stage: "declined",
162
+ reason: role === undefined
163
+ ? "the module this declaration lives in could not be classified"
164
+ : "this declaration is in a " + role.replace(/_/g, " ") + " module, so there is nothing to hoist it out of",
165
+ });
166
+ }
167
+ const candidates = all.filter((unit) => edge.has(moduleOf(unit)));
168
+ const budget = policy.hoistToDomain.maxDeclarations;
169
+ const judged = candidates.slice(0, budget);
170
+ const overBudget = candidates.slice(budget).map((unit) => ({
171
+ ruleId: RULE_ID,
172
+ subject: label(unit),
173
+ stage: "budget",
174
+ reason: "past the budget of " + budget + " declarations",
175
+ }));
176
+ const atoms = yield* Atoms;
177
+ const planned = [];
178
+ for (const unit of judged) {
179
+ const id = yield* atoms.add({
180
+ repository: context.config.evidence?.repository ?? null,
181
+ // What the module IS, from round one. Every question about a declaration
182
+ // is easier to answer knowing whether it sits in a route handler or a
183
+ // domain package, and round one already paid for the answer.
184
+ module: { path: moduleOf(unit), role: edge.get(moduleOf(unit)) ?? null },
185
+ declaration: {
186
+ name: unit.name,
187
+ path: unit.file,
188
+ line: unit.location.line,
189
+ source: unit.text.slice(0, policy.evidence.maxSourceChars),
190
+ documented: unit.doc !== undefined,
191
+ doc: unit.doc?.slice(0, policy.evidence.maxDocChars) ?? null,
192
+ types: unit.typeRefs,
193
+ },
194
+ });
195
+ planned.push({
196
+ unit,
197
+ plan: {
198
+ ruleId: RULE_ID,
199
+ subject: label(unit),
200
+ concerns: [unit.file],
201
+ atoms: [id],
202
+ violations: { duty: ["domain_logic"] },
203
+ decisions: hoistReview(id),
204
+ read: (answers) => answers,
205
+ },
206
+ });
207
+ }
208
+ return {
209
+ plans: planned.map((entry) => entry.plan),
210
+ read: (answers) => {
211
+ const verdicts = verdictsOf(answers);
212
+ const diagnostics = [];
213
+ const drops = [...notAnEdge, ...overBudget];
214
+ planned.forEach((entry, index) => {
215
+ const unit = entry.unit;
216
+ const answer = verdicts[index];
217
+ if (answer === undefined) {
218
+ drops.push({
219
+ ruleId: RULE_ID,
220
+ subject: label(unit),
221
+ stage: "unreadable",
222
+ reason: "the response did not classify this declaration",
223
+ });
224
+ return;
225
+ }
226
+ const duty = answer["duty"];
227
+ const home = answer["home"];
228
+ if (duty === undefined || !("label" in duty) || home === undefined || !("label" in home)) {
229
+ drops.push({
230
+ ruleId: RULE_ID,
231
+ subject: label(unit),
232
+ stage: "unreadable",
233
+ reason: "the response did not classify this declaration",
234
+ });
235
+ return;
236
+ }
237
+ // A Choice that barely won is not a decision. The duplicate rules have had
238
+ // this gate since it was shown to withhold 11 clusters of unrelated `db*`
239
+ // functions; these two rules were built without it, which is how one of them
240
+ // produced 199 findings on a single repository. The shared gate, so the
241
+ // reasoning sits in one place.
242
+ const quality = qualityOf({
243
+ score: duty.probabilities["domain_logic"] ?? duty.confidence ?? 1,
244
+ margin: marginOfAnswer(duty),
245
+ confidence: duty.confidence,
246
+ });
247
+ if (quality.quality === "drop") {
248
+ drops.push({
249
+ ruleId: RULE_ID,
250
+ subject: label(unit),
251
+ stage: "gated",
252
+ reason: quality.reason,
253
+ });
254
+ return;
255
+ }
256
+ const review = quality.quality === "review";
257
+ if (duty.label !== "domain_logic" || declined(home.label) || home.label === "already_there") {
258
+ drops.push({
259
+ ruleId: RULE_ID,
260
+ subject: label(unit),
261
+ stage: "declined",
262
+ reason: duty.label === "domain_logic"
263
+ ? "the model says this is already where it belongs"
264
+ : "the model says this is " + duty.label,
265
+ });
266
+ return;
267
+ }
268
+ diagnostics.push(report({
269
+ about: unit,
270
+ messageId: "rule_at_the_edge",
271
+ data: { name: unit.name, file: unit.file, home: (home.label ?? "").replace(/_/g, " ") },
272
+ helpId: "rule_at_the_edge_help",
273
+ identity: [RULE_ID, unit.file, unit.name].join("\u0000"),
274
+ confidence: duty.confidence ?? 1,
275
+ judged: true,
276
+ severity: review ? "info" : "warn",
277
+ }));
278
+ });
279
+ return outcome(diagnostics, budgetNote({
280
+ unitKind: "declarations",
281
+ judged: budget,
282
+ candidates: candidates.length,
283
+ sample: candidates.slice(budget).map(label),
284
+ }), drops);
285
+ },
286
+ };
287
+ })
288
+ };