@r_masseater/oxlint-plugin-decision 0.8.0 → 0.8.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 (43) hide show
  1. package/README.md +5 -0
  2. package/dist/{app-UakaWKAT.mjs → app-D2bguKZ_.mjs} +137 -27
  3. package/dist/app-D2bguKZ_.mjs.map +1 -0
  4. package/dist/claim-rule-B0LCcxxc.mjs +36 -0
  5. package/dist/claim-rule-B0LCcxxc.mjs.map +1 -0
  6. package/dist/cloudflare-worker.mjs +111 -2
  7. package/dist/cloudflare-worker.mjs.map +1 -1
  8. package/dist/{index-HOwrGbIA.d.mts → index-B4wX62VC.d.mts} +2 -2
  9. package/dist/{index-C0Twu0w7.d.mts → index-CK88FBE5.d.mts} +666 -319
  10. package/dist/index.d.mts +1 -1
  11. package/dist/index.mjs +1 -1
  12. package/dist/{define-presets-yflVt8vT.mjs → preset-plugin-MKdvpXxa.mjs} +11 -214
  13. package/dist/preset-plugin-MKdvpXxa.mjs.map +1 -0
  14. package/dist/presets/ai-slop.d.mts +2 -2
  15. package/dist/presets/ai-slop.mjs +179 -2
  16. package/dist/presets/ai-slop.mjs.map +1 -1
  17. package/dist/presets/index.d.mts +1 -1
  18. package/dist/presets/index.mjs +1 -1
  19. package/dist/presets/recommended.d.mts +1 -1
  20. package/dist/presets/recommended.mjs +1 -2
  21. package/dist/presets/recommended.mjs.map +1 -1
  22. package/dist/presets/review-only.d.mts +1 -1
  23. package/dist/presets/review-only.mjs +1 -2
  24. package/dist/presets/review-only.mjs.map +1 -1
  25. package/dist/presets/strict.d.mts +1 -1
  26. package/dist/presets/strict.mjs +1 -2
  27. package/dist/presets/strict.mjs.map +1 -1
  28. package/dist/serve-decisions-D6M-l2uy.mjs +232 -0
  29. package/dist/serve-decisions-D6M-l2uy.mjs.map +1 -0
  30. package/dist/typesafe-worker.mjs +20 -2
  31. package/dist/typesafe-worker.mjs.map +1 -1
  32. package/dist/{decision-B7hahWHz.mjs → wire-CKpt_MBX.mjs} +11 -134
  33. package/dist/wire-CKpt_MBX.mjs.map +1 -0
  34. package/package.json +23 -21
  35. package/skills/write-decision-rules/SKILL.md +0 -1
  36. package/skills/write-decision-rules/references/tuning.md +2 -2
  37. package/dist/app-UakaWKAT.mjs.map +0 -1
  38. package/dist/decision-B7hahWHz.mjs.map +0 -1
  39. package/dist/define-presets-yflVt8vT.mjs.map +0 -1
  40. package/dist/preset-plugin-ClpEFUN5.mjs +0 -10
  41. package/dist/preset-plugin-ClpEFUN5.mjs.map +0 -1
  42. package/dist/serve-decisions-DYGwLMft.mjs +0 -287
  43. package/dist/serve-decisions-DYGwLMft.mjs.map +0 -1
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { C as Target, S as Severity, _ as RuleAnswer, a as DecisionOptions, b as SelectMatch, c as DecisionRequest, d as EnclosingKind, f as ExplainSetting, g as Question, h as NoulQuestion, i as CiBehavior, l as DecisionResponse, m as ModelSpec, n as defineDecisionRule, o as DecisionPlugin, p as Frozen, r as ChoiceQuestion, s as DecisionPluginSetup, t as createDecisionPlugin, u as DecisionRule, v as RuleContext, w as DecisionModel, x as SelectedNode, y as RuleLocation } from "./index-C0Twu0w7.mjs";
1
+ import { C as Target, S as Severity, _ as RuleAnswer, a as DecisionOptions, b as SelectMatch, c as DecisionRequest, d as EnclosingKind, f as ExplainSetting, g as Question, h as NoulQuestion, i as CiBehavior, l as DecisionResponse, m as ModelSpec, n as defineDecisionRule, o as DecisionPlugin, p as Frozen, r as ChoiceQuestion, s as DecisionPluginSetup, t as createDecisionPlugin, u as DecisionRule, v as RuleContext, w as DecisionModel, x as SelectedNode, y as RuleLocation } from "./index-CK88FBE5.mjs";
2
2
  export { type ChoiceQuestion, type CiBehavior, type DecisionModel, type DecisionOptions, type DecisionPlugin, type DecisionPluginSetup, type DecisionRequest, type DecisionResponse, type DecisionRule, type EnclosingKind, type ExplainSetting, type Frozen, type ModelSpec, type NoulQuestion, type Question, type RuleAnswer, type RuleContext, type RuleLocation, type SelectMatch, type SelectedNode, type Severity, type Target, createDecisionPlugin, defineDecisionRule };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export { t as createDecisionPlugin, n as defineDecisionRule } from "./app-UakaWKAT.mjs";
1
+ export { t as createDecisionPlugin, n as defineDecisionRule } from "./app-D2bguKZ_.mjs";
@@ -1,215 +1,6 @@
1
- import "./decision-B7hahWHz.mjs";
2
- import { n as defineDecisionRule } from "./app-UakaWKAT.mjs";
3
- import { Array, Function, Match, Option, Predicate, Record, String, pipe } from "effect";
4
- // src/features/define-presets/lib/select.ts
5
- const DATA_FIRST_ARITY = 2;
6
- const dualSelect = (select) => Function.dual(DATA_FIRST_ARITY, select);
7
- const childrenOf = (node) => pipe(Record.toEntries(node), Array.filter(([key]) => key !== "parent"), Array.flatMap(([, value]) => Array.ensure(value)), Array.filter((value) => Predicate.hasProperty(value, "type")));
8
- const descendantsOf = (node) => [node, ...pipe(childrenOf(node), Array.flatMap((child) => descendantsOf(child)))];
9
- const containing = (test) => (node) => pipe(descendantsOf(node), Array.some((found) => test(found)));
10
- const ofType = (...types) => (node) => types.includes(node.type);
11
- const identifierOf = (node) => Match.value(node).pipe(Match.when({ type: "Identifier" }, (identifier) => Option.some(identifier.name)), Match.orElse(() => Option.none()));
12
- // src/features/define-presets/lib/ai-slop-select.ts
13
- const isPlaceholderValue = ofType("Literal", "TemplateLiteral", "ArrayExpression", "ObjectExpression");
14
- const isFallbackOperator = (node) => Match.value(node).pipe(Match.when({
15
- type: "LogicalExpression",
16
- operator: "??"
17
- }, () => true), Match.when({
18
- type: "LogicalExpression",
19
- operator: "||"
20
- }, (logical) => isPlaceholderValue(logical.right)), Match.when({
21
- type: "AssignmentExpression",
22
- operator: "??="
23
- }, () => true), Match.when({
24
- type: "AssignmentExpression",
25
- operator: "||="
26
- }, () => true), Match.orElse(() => false));
27
- const isTypeofCheck = (node) => Match.value(node).pipe(Match.when({
28
- type: "UnaryExpression",
29
- operator: "typeof"
30
- }, () => true), Match.orElse(() => false));
31
- const isConstAssertion = (annotation) => Match.value(annotation).pipe(Match.when({
32
- type: "TSTypeReference",
33
- typeName: {
34
- type: "Identifier",
35
- name: "const"
36
- }
37
- }, () => true), Match.orElse(() => false));
38
- const isCast = (node) => Match.value(node).pipe(Match.when({ type: "TSAsExpression" }, (cast) => !isConstAssertion(cast.typeAnnotation)), Match.when({ type: "TSTypeAssertion" }, () => true), Match.when({ type: "TSNonNullExpression" }, () => true), Match.orElse(() => false));
39
- const bodyOf = (node) => Match.value(node).pipe(Match.when({ type: "FunctionDeclaration" }, (fn) => Option.fromNullishOr(fn.body)), Match.when({ type: "FunctionExpression" }, (fn) => Option.fromNullishOr(fn.body)), Match.when({ type: "ArrowFunctionExpression" }, (fn) => Option.some(fn.body)), Match.orElse(() => Option.none()));
40
- const statementsOf = (body) => Match.value(body).pipe(Match.when({ type: "BlockStatement" }, (block) => block.body), Match.orElse((expression) => [expression]));
41
- const ONE_STATEMENT = 1;
42
- const isCall = ofType("CallExpression", "NewExpression");
43
- const parentOf = (node) => Option.fromNullishOr(node.parent);
44
- const isArgument = (node) => Option.exists(parentOf(node), isCall);
45
- const isOptionOfCall = (node) => parentOf(node).pipe(Option.filter(ofType("Property")), Option.flatMap(parentOf), Option.filter(ofType("ObjectExpression")), Option.exists(isArgument));
46
- const isCallback = Predicate.or(isArgument, isOptionOfCall);
47
- const isDeclared = Predicate.not(isCallback);
48
- const isShort = (node) => Option.exists(bodyOf(node), (body) => statementsOf(body).length <= ONE_STATEMENT);
49
- const hasAtMostOneStatement = Predicate.and(isDeclared, isShort);
50
- const expressionOf = (statement) => Match.value(statement).pipe(Match.when({ type: "ReturnStatement" }, (returned) => Option.fromNullishOr(returned.argument)), Match.when({ type: "ExpressionStatement" }, (expression) => Option.some(expression.expression)), Match.orElse((other) => Option.some(other)));
51
- const awaitedOf = (expression) => Match.value(expression).pipe(Match.when({ type: "AwaitExpression" }, (awaited) => awaited.argument), Match.orElse((plain) => plain));
52
- const isForwardingStatement = (statements) => Option.exists(Option.flatMap(Array.head(statements), expressionOf), (expression) => awaitedOf(expression).type === "CallExpression");
53
- const isSingleCall = (node) => Option.exists(bodyOf(node), (body) => isForwardingStatement(statementsOf(body)));
54
- const paramsOf = (node) => Match.value(node).pipe(Match.when({ type: "FunctionDeclaration" }, (fn) => fn.params), Match.when({ type: "FunctionExpression" }, (fn) => fn.params), Match.when({ type: "ArrowFunctionExpression" }, (fn) => fn.params), Match.orElse(() => []));
55
- const nameOf = (node) => Match.value(node).pipe(Match.when({ type: "SpreadElement" }, (spread) => identifierOf(spread.argument)), Match.when({ type: "RestElement" }, (rest) => identifierOf(rest.argument)), Match.orElse((plain) => identifierOf(plain)));
56
- const argumentsOf = (node) => bodyOf(node).pipe(Option.flatMap((body) => Array.head(statementsOf(body))), Option.flatMap(expressionOf), Option.map(awaitedOf), Option.flatMap((expression) => Match.value(expression).pipe(Match.when({ type: "CallExpression" }, (call) => Option.some(call.arguments)), Match.orElse(() => Option.none()))));
57
- const isForwardedArgument = (names) => (argument) => Match.value(argument).pipe(Match.when({ type: "Literal" }, () => true), Match.orElse((other) => Option.exists(nameOf(other), (name) => names.includes(name))));
58
- const passesExactly = (names) => Predicate.and((passed) => pipe(passed, Array.every((argument) => isForwardedArgument(names)(argument))), (passed) => {
59
- const passedNames = Array.getSomes(pipe(passed, Array.map((argument) => nameOf(argument))));
60
- return pipe(names, Array.every((name) => passedNames.includes(name)));
61
- });
62
- const passesParamsUnchanged = (node) => pipe(paramsOf(node), Array.map((param) => nameOf(param)), Option.all, Option.exists((names) => Option.exists(argumentsOf(node), passesExactly(names))));
63
- const forwardsOneCall = Predicate.and(Predicate.and(hasAtMostOneStatement, isSingleCall), passesParamsUnchanged);
64
- const declaredTypeOf = (param) => Match.value(param).pipe(Match.when({ type: "AssignmentPattern" }, (assigned) => declaredTypeOf(assigned.left)), Match.when({ type: "TSParameterProperty" }, (property) => declaredTypeOf(property.parameter)), Match.when({ typeAnnotation: { type: "TSTypeAnnotation" } }, (typed) => Option.some(typed.typeAnnotation.typeAnnotation)), Match.orElse(() => Option.none()));
65
- const isOpenType = ofType("TSUnknownKeyword", "TSAnyKeyword");
66
- const hasNarrowParameter = (node) => pipe(paramsOf(node), Array.some((param) => Option.exists(declaredTypeOf(param), Predicate.not(isOpenType))));
67
- const typeParameterNamesOf = (node) => Match.value(node).pipe(Match.when({ typeParameters: { type: "TSTypeParameterDeclaration" } }, (generic) => pipe(generic.typeParameters.params, Array.map((parameter) => parameter.name.name))), Match.orElse(() => []));
68
- const referencedNameOf = (type) => Match.value(type).pipe(Match.when({
69
- type: "TSTypeReference",
70
- typeName: { type: "Identifier" }
71
- }, (reference) => Option.some(reference.typeName.name)), Match.orElse(() => Option.none()));
72
- const isGenericParameter = (node, param) => Option.exists(Option.flatMap(declaredTypeOf(param), referencedNameOf), (name) => typeParameterNamesOf(node).includes(name));
73
- const returnedOf = (node) => Option.flatMap(bodyOf(node), (body) => Option.flatMap(Array.head(statementsOf(body)), expressionOf));
74
- const returnedNameOf = (node) => Option.flatMap(returnedOf(node), identifierOf);
75
- const returnsParameter = (node, param) => Option.exists(Option.all([returnedNameOf(node), identifierOf(param)]), ([returned, given]) => returned === given);
76
- const ONE_PARAMETER = 1;
77
- const onlyParameterOf = (node) => Option.liftPredicate(paramsOf(node), (params) => params.length === ONE_PARAMETER).pipe(Option.flatMap(Array.head));
78
- const isGenericIdentity = (node) => onlyParameterOf(node).pipe(Option.filter((param) => isGenericParameter(node, param)), Option.exists((param) => returnsParameter(node, param)));
79
- const mayBePlaceholder = Predicate.and(hasAtMostOneStatement, Predicate.not(isGenericIdentity));
80
- const isGuard = Predicate.or(ofType("IfStatement", "ConditionalExpression", "ChainExpression", "TryStatement"), isTypeofCheck);
81
- const hasGuard = Predicate.and(hasNarrowParameter, containing(isGuard));
82
- const hasFallback = dualSelect(containing(Predicate.or(isFallbackOperator, ofType("AssignmentPattern"))));
83
- const hasCast = dualSelect(containing(isCast));
84
- // src/features/define-presets/lib/comment-select.ts
85
- const commentsIn = (node, { context }) => {
86
- const [start, end] = node.range;
87
- return pipe(context.sourceCode.getAllComments(), Array.filter((comment) => comment.start >= start && comment.end <= end), Array.map((comment) => comment.value));
88
- };
89
- const hasCommentInside = dualSelect((node, match) => Array.isReadonlyArrayNonEmpty(commentsIn(node, match)));
90
- const SUPPRESSIONS = [
91
- "eslint-disable",
92
- "oxlint-disable",
93
- "@ts-ignore",
94
- "@ts-expect-error",
95
- "@ts-nocheck",
96
- "fallow-ignore"
97
- ];
98
- const hasSuppression = dualSelect((node, match) => pipe(commentsIn(node, match), Array.some((comment) => pipe(SUPPRESSIONS, Array.some((word) => String.includes(word)(comment))))));
99
- // src/features/define-presets/model/ai-slop-rules.ts
100
- const CUTOFF = .8;
101
- const slopRule = ({ ask, flag, pass, ...rule }) => defineDecisionRule({
102
- target: "function",
103
- cutoff: CUTOFF,
104
- ...rule,
105
- message: ask,
106
- question: `${ask}\n\nAnswer yes when: ${flag}\n\nAnswer no when: ${pass}`
107
- });
108
- const redundantGuard = slopRule({
109
- id: "redundant-guard",
110
- select: hasGuard,
111
- ask: "This function checks one of its own parameters for a case that the parameter's declared type already rules out, so the check can never change what happens.",
112
- flag: "A parameter whose type annotation is non-optional and non-nullable, such as `user: User` or `name: string`, is compared with null or undefined, has its `typeof` tested against the type it is already declared as, or is read with `?.`.",
113
- pass: "No parameter is checked against its own declared type. Checks on local variables do not count: a local that holds the result of `Map.get`, `find`, `JSON.parse` or any other call, or a value annotated `unknown`, can really be missing or of another type, so checking it is necessary. Parameters of plain JavaScript have no declared type, so any check on them is allowed."
114
- });
115
- const defaultMasksMissingValue = slopRule({
116
- id: "default-masks-missing-value",
117
- select: hasFallback,
118
- ask: "This function replaces a value that should always be present with a made-up default, so a missing value is hidden instead of reported.",
119
- flag: "A `??` or `||` default, or a default parameter, stands in for data the rest of the code treats as required, such as an id, a user, a price, a config entry or a response field, with a placeholder like 'unknown', '', 0, [] or {} that later code will use as if it were real; or a chain of two or more fallbacks (`a ?? b ?? c`) picks among sources with no sign of why that order is right.",
120
- pass: "Every default is a value the domain genuinely allows when the input is absent, such as an optional setting with a documented default, an empty list for an optional filter, or a display label for an optional field; or the missing case is reported, thrown or returned to the caller instead of being filled in."
121
- });
122
- const passThroughWrapper = slopRule({
123
- id: "pass-through-wrapper",
124
- select: forwardsOneCall,
125
- ask: "This function only forwards its arguments to another function and returns the result, adding no behaviour of its own.",
126
- flag: "The body is a single call that receives every parameter exactly as it came in, in the same order, or with an extra argument that is always the same constant, and returns or awaits the result unchanged, so callers could call the inner function directly.",
127
- pass: "The function changes something on the way: it transforms an argument before passing it on (for example trimming, lower-casing, converting or validating it), transforms the result, binds a dependency, adapts to a different signature a caller requires, or it is an entry point that a framework or another package calls by name."
128
- });
129
- const placeholderImplementation = slopRule({
130
- id: "placeholder-implementation",
131
- select: mayBePlaceholder,
132
- ask: "This function is a stand-in that pretends to do its job: it returns a fixed value or does nothing where its name promises real work.",
133
- flag: "The body is empty, only logs, or only holds a TODO while the name promises an action; a validator, checker or permission function always returns true or always returns false; a function named after a computation returns a hard-coded number, string or object; or a branch the name promises to handle silently does nothing.",
134
- pass: "The body does the work its name promises, even simply. An intentional no-op whose name says so (noop, ignore, a default callback), an abstract method meant to be overridden, and a test double inside test code are not placeholders."
135
- });
136
- const commentRestatesCode = slopRule({
137
- id: "comment-restates-code",
138
- select: hasCommentInside,
139
- ask: "A comment inside this function only translates the next line of code into words and adds no reason, unit, or constraint.",
140
- flag: "A comment repeats the code in words, such as `// increment the counter` over `count += 1`, `// loop over the items` over a for loop, or `// return the total` over a return; deleting it would leave a reader knowing exactly as much.",
141
- pass: "Every comment says something the code cannot say on its own: why it is done this way (often with `because` or `so`), a fact about the outside world such as a billing rule, an API quirk or a standard, a unit, or an invariant. Lint directive comments such as `eslint-disable` are not judged here."
142
- });
143
- const commentNarratesHistory = slopRule({
144
- id: "comment-narrates-history",
145
- select: hasCommentInside,
146
- ask: "A comment inside this function records how the code came to be, or speaks to the person who asked for the change, instead of describing the code as it stands.",
147
- flag: "A comment says what was added, changed, removed, fixed or kept for compatibility (`added X`, `changed to Y`, `previously`, `now uses`, `new:`), marks the code as a stopgap (`temporary`, `for now`, `quick fix`, `hack until`), mentions a date, a ticket in progress, a model or a conversation, or addresses a reader as if replying (`as requested`, `here we`, `note that I`).",
148
- pass: "Every comment describes the code as it is now and would still be true and useful to a reader who never saw the earlier version or the conversation. A TODO that names a concrete missing case is a description of the code, not history."
149
- });
150
- const docRestatesSignature = slopRule({
151
- id: "doc-restates-signature",
152
- context: { scope: "comment" },
153
- ask: "The comment above this function contains nothing except the function's name and parameter names reworded.",
154
- flag: "Every sentence of the comment can be rebuilt from the signature alone, such as `Gets the order.`, `@param id - the id`, `@returns the order` or `Creates a new instance.`",
155
- pass: "At least one sentence states behaviour the signature does not show, such as what is returned when nothing matches, when it fails, a unit or range, a side effect, or how values are compared."
156
- });
157
- const castInsteadOfNarrowing = slopRule({
158
- id: "cast-instead-of-narrowing",
159
- select: hasCast,
160
- ask: "This function uses a type assertion (`as`, `<T>` or a non-null `!`) to silence the type checker where the value is not known to have that type.",
161
- flag: "The asserted type is not established by anything on the path: data from parsing, I/O, `unknown`, `any` or a wider union is cast to a specific shape without a check, a possibly missing value gets `!` without a preceding check or a guarantee from the API, or the cast goes through `unknown` (`as unknown as T`) to force an unrelated type.",
162
- pass: "Each assertion states something the code has just established or the API guarantees, such as a cast after a type guard, a DOM element looked up by a selector that the same module creates, or a literal narrowed for an overload; `as const` is not a cast."
163
- });
164
- const suppressionInsteadOfFix = slopRule({
165
- id: "suppression-instead-of-fix",
166
- select: hasSuppression,
167
- ask: "A lint or type-check suppression comment inside this function hides a problem that the code next to it could simply fix.",
168
- flag: "The directive gives no reason after the rule name, or the line it silences has a direct local fix, such as handling a floating promise, typing a value instead of `any`, removing an unused variable, or narrowing instead of `@ts-ignore`.",
169
- pass: "Every directive is followed by `--` or a comment with a reason explaining why the rule does not fit this line, such as output a command-line tool prints on purpose, a wrong third-party type, or generated code."
170
- });
171
- const reinventsBuiltin = slopRule({
172
- id: "reinvents-builtin",
173
- select: isDeclared,
174
- ask: "This function contains a hand-written loop or algorithm that re-implements something the JavaScript standard library or the platform already provides.",
175
- flag: "A loop or manual algorithm in the body does what one built-in call does: de-duplicating with an array and includes instead of a Set, deep copying instead of structuredClone, grouping instead of Object.groupBy, building query strings instead of URLSearchParams, formatting numbers or dates instead of Intl, padding instead of padStart, flattening instead of flat, or finding the last match instead of findLast.",
176
- pass: "The function has no such hand-written loop: it already calls the built-in directly (for example `new Set`, `structuredClone`, `reduce` or `Intl`), or its loop does domain work that no single built-in does. A chain of built-in array methods such as `filter`, `map`, `flatMap` and `flat` already uses the built-ins."
177
- });
178
- const aiSlopRules = [
179
- redundantGuard,
180
- defaultMasksMissingValue,
181
- passThroughWrapper,
182
- placeholderImplementation,
183
- commentRestatesCode,
184
- commentNarratesHistory,
185
- docRestatesSignature,
186
- castInsteadOfNarrowing,
187
- suppressionInsteadOfFix,
188
- reinventsBuiltin
189
- ];
190
- // src/features/define-presets/lib/claim-rule.ts
191
- const questionOf = ({ ask, yes, no, note }) => pipe([
192
- ask,
193
- `It is true when: ${yes}`,
194
- `It is false when: ${no}`,
195
- note
196
- ], Array.filter((part) => Predicate.isNotUndefined(part)), Array.join("\n\n"));
197
- const claimRule = ({ ask, yes, no, note, ...rule }) => defineDecisionRule({
198
- target: "function",
199
- ...rule,
200
- message: ask,
201
- question: questionOf({
202
- ask,
203
- yes,
204
- no,
205
- note
206
- })
207
- });
208
- const COMMENT = { scope: "comment" };
209
- const ENCLOSING_FUNCTION = {
210
- scope: "enclosing",
211
- kind: "function"
212
- };
1
+ import { n as defineDecisionRule, t as createDecisionPlugin } from "./app-D2bguKZ_.mjs";
2
+ import { a as dualSelect, i as containing, n as ENCLOSING_FUNCTION, o as identifierOf, r as claimRule, s as ofType, t as COMMENT } from "./claim-rule-B0LCcxxc.mjs";
3
+ import { Array, Match, Option, Predicate, String, pipe } from "effect";
213
4
  // src/features/define-presets/lib/claim-select.ts
214
5
  const WORD_STARTS = /* @__PURE__ */ new Set(["", ...String.split("_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", "")]);
215
6
  const NEXT_CHARACTER = 1;
@@ -545,6 +336,12 @@ const presets = {
545
336
  strict,
546
337
  reviewOnly
547
338
  };
548
- export { varNameDescribesValue as A, reinventsBuiltin as B, errorMessageMatchesCondition as C, logMessageMatchesEvent as D, logLevelMatchesEvent as E, defaultMasksMissingValue as F, docRestatesSignature as I, passThroughWrapper as L, castInsteadOfNarrowing as M, commentNarratesHistory as N, pureNameIsPure as O, commentRestatesCode as P, placeholderImplementation as R, docErrorsMatchBody as S, idempotentName as T, suppressionInsteadOfFix as V, untrustedInputRisk as _, describeNamesSubject as a, commentDescribesBlock as b, testMocksSubject as c, domainNaming as d, nameMatchesBehavior as f, preferSchemaValidation as g, noPromptInjection as h, strict as i, aiSlopRules as j, safeNameIsSafe as k, testNameDescribesCode as l, noPiiInLogs as m, recommended as n, snapshotOnlyBehaviourClaim as o, noHardcodedSecrets as p, reviewOnly as r, testClaims as s, presets as t, testNameVerifiesClaim as u, catchHidesFailure as v, fnNamePromises as w, commentDescribesDeclaration as x, codeClaims as y, redundantGuard as z };
339
+ // src/app/preset-plugin.ts
340
+ const PLUGIN_NAME = "decision-presets";
341
+ const presetPlugin = (rules) => createDecisionPlugin({
342
+ name: PLUGIN_NAME,
343
+ rules
344
+ });
345
+ export { safeNameIsSafe as A, docErrorsMatchBody as C, logLevelMatchesEvent as D, idempotentName as E, logMessageMatchesEvent as O, commentDescribesDeclaration as S, fnNamePromises as T, preferSchemaValidation as _, strict as a, codeClaims as b, testClaims as c, testNameVerifiesClaim as d, domainNaming as f, noPromptInjection as g, noPiiInLogs as h, reviewOnly as i, varNameDescribesValue as j, pureNameIsPure as k, testMocksSubject as l, noHardcodedSecrets as m, presets as n, describeNamesSubject as o, nameMatchesBehavior as p, recommended as r, snapshotOnlyBehaviourClaim as s, presetPlugin as t, testNameDescribesCode as u, untrustedInputRisk as v, errorMessageMatchesCondition as w, commentDescribesBlock as x, catchHidesFailure as y };
549
346
 
550
- //# sourceMappingURL=define-presets-yflVt8vT.mjs.map
347
+ //# sourceMappingURL=preset-plugin-MKdvpXxa.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preset-plugin-MKdvpXxa.mjs","names":["Str","Arr"],"sources":["../src/features/define-presets/lib/claim-select.ts","../src/features/define-presets/model/code-claims.ts","../src/features/define-presets/model/rules.ts","../src/features/define-presets/model/test-claims.ts","../src/features/define-presets/model/presets.ts","../src/app/preset-plugin.ts"],"sourcesContent":["import { Array as Arr, Match, Option, Predicate, String as Str, pipe } from \"effect\";\n\nimport type { SelectedNode } from \"#/entities/decision/index.ts\";\n\nimport { containing, dualSelect, identifierOf, ofType } from \"./select.ts\";\nimport type { DualSelect, NodeTest, Select } from \"./select.ts\";\n\nconst WORD_STARTS: ReadonlySet<string> = new Set([\n \"\",\n ...Str.split(\"_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\", \"\"),\n]);\n\nconst NEXT_CHARACTER = 1;\n\nconst startsWithWord =\n (word: string): Predicate.Predicate<string> =>\n (name) =>\n Predicate.and(\n (text: string) => Str.startsWith(word)(text),\n (text: string) => WORD_STARTS.has(Str.slice(word.length, word.length + NEXT_CHARACTER)(text)),\n )(name);\n\nconst endsWith =\n (word: string): Predicate.Predicate<string> =>\n (name) =>\n Str.endsWith(word)(name);\n\nexport interface NameWords {\n readonly prefixes: readonly string[];\n readonly suffixes?: readonly string[];\n}\n\nexport const namedLike = ({ prefixes, suffixes = [] }: NameWords): Select => {\n const matchers = [\n ...pipe(\n prefixes,\n Arr.map((word) => startsWithWord(word)),\n ),\n ...pipe(\n suffixes,\n Arr.map((word) => endsWith(word)),\n ),\n ];\n return (_node, { name }) =>\n Option.exists(Option.fromUndefinedOr(name), (found) =>\n pipe(\n matchers,\n Arr.some((matches) => matches(found)),\n ),\n );\n};\n\nconst rootOf = (callee: SelectedNode): Option.Option<string> =>\n Match.value(callee).pipe(\n Match.when({ type: \"MemberExpression\", computed: false }, (member) => rootOf(member.object)),\n Match.orElse(identifierOf),\n );\n\nconst calleeOf = (node: SelectedNode): Option.Option<SelectedNode> =>\n Match.value(node).pipe(\n Match.when({ type: \"CallExpression\" }, (call) => Option.some(call.callee)),\n Match.orElse(() => Option.none()),\n );\n\nconst callingAny =\n (roots: readonly string[]): Select =>\n (node) =>\n Option.exists(Option.flatMap(calleeOf(node), rootOf), (root) => roots.includes(root));\n\nconst LOG_LEVELS: ReadonlySet<string> = new Set([\n \"trace\",\n \"debug\",\n \"verbose\",\n \"info\",\n \"log\",\n \"warn\",\n \"warning\",\n \"error\",\n \"fatal\",\n]);\n\nconst lastNameOf = (node: SelectedNode): Option.Option<string> =>\n Match.value(node).pipe(\n Match.when({ type: \"MemberExpression\", computed: false }, (member) =>\n identifierOf(member.property),\n ),\n Match.orElse(identifierOf),\n );\n\nconst isLogger = (name: string): boolean =>\n Arr.some([\"console\", \"log\"], (word) => Str.includes(word)(Str.toLowerCase(name)));\n\ninterface LogCall {\n readonly level: Option.Option<string>;\n readonly logger: Option.Option<string>;\n}\n\nconst logCallOf = (callee: SelectedNode): Option.Option<LogCall> =>\n Match.value(callee).pipe(\n Match.when({ type: \"MemberExpression\", computed: false }, (member) =>\n Option.some({ level: identifierOf(member.property), logger: lastNameOf(member.object) }),\n ),\n Match.orElse(() => Option.none()),\n );\n\nexport const isLogCall: DualSelect = dualSelect((node) =>\n Option.exists(Option.flatMap(calleeOf(node), logCallOf), ({ level, logger }) =>\n Predicate.and(\n () => Option.exists(level, (found) => LOG_LEVELS.has(found)),\n () => Option.exists(logger, isLogger),\n )(node),\n ),\n);\n\nconst isCatchName = (name: SelectedNode): boolean =>\n Match.value(name).pipe(\n Match.when({ type: \"Identifier\" }, (identifier) => Str.startsWith(\"catch\")(identifier.name)),\n Match.orElse(() => false),\n );\n\nconst isCatch: NodeTest = (node) =>\n Match.value(node).pipe(\n Match.when({ type: \"CatchClause\" }, () => true),\n Match.when({ type: \"MemberExpression\", computed: false }, (member) =>\n isCatchName(member.property),\n ),\n Match.when({ type: \"Property\", computed: false }, (property) => isCatchName(property.key)),\n Match.orElse(() => false),\n );\n\nexport const hasCatch: DualSelect = dualSelect(containing(isCatch));\n\nconst hasCallbackArgument: Select = (node) =>\n Match.value(node).pipe(\n Match.when({ type: \"CallExpression\" }, (call) =>\n pipe(\n call.arguments,\n Arr.some((argument) => ofType(\"ArrowFunctionExpression\", \"FunctionExpression\")(argument)),\n ),\n ),\n Match.orElse(() => false),\n );\n\nexport const isTestCall: DualSelect = dualSelect((node, match) =>\n pipe(\n [callingAny([\"it\", \"test\"]), hasCallbackArgument],\n Arr.every((select) => select(node, match)),\n ),\n);\n\nexport const isDescribeCall: DualSelect = dualSelect(callingAny([\"describe\"]));\n","import type { DecisionRule } from \"#/entities/decision/index.ts\";\nimport {\n COMMENT,\n ENCLOSING_FUNCTION,\n claimRule,\n} from \"#/features/define-presets/lib/claim-rule.ts\";\nimport { hasCatch, isLogCall, namedLike } from \"#/features/define-presets/lib/claim-select.ts\";\n\nexport const fnNamePromises = claimRule({\n id: \"fn-name-promises\",\n cutoff: 0.8,\n ask: \"The body of this function does something materially different from what its name promises.\",\n yes: \"Someone who read only the name and the parameter list would be wrong about what this function does: it returns a different kind of thing than the name suggests (a count that is a list, a predicate that is a number), it changes state when the name says it only reads, checks, looks up or serialises, it can fail or return nothing when the name promises a value, it handles only a narrower case than the name claims, it never performs an effect or repetition the name names (a drain or remove that leaves the container as it was, a retry that tries once), it computes something no reading of the name accounts for, or it does substantial work the name does not mention at all, such as writing what it was asked to read.\",\n no: \"The name and parameter list describe what the body actually does. Someone who read only them would not be surprised by the body, even if a longer or more specific name could be imagined. A terse or conventional name (run, handle, take, len, fmt, toString, a getter) that the body fits is not a violation, and a comment inside the body that is wrong about the body is a wrong comment, not a wrong name.\",\n});\n\nexport const pureNameIsPure = claimRule({\n id: \"pure-name-is-pure\",\n cutoff: 0.8,\n select: namedLike({ prefixes: [\"compute\", \"calculate\", \"derive\", \"format\", \"to\", \"parse\"] }),\n ask: \"This function's name presents it as a computation of a result from its inputs, but its body changes state outside itself or performs I/O.\",\n yes: \"The body mutates an argument or something reachable through one, assigns to a module-level binding, a field of `this` or an object it did not create, stores something it computed into a cache, Map, Set or other store that outlives the call, logs, emits or increments a metric, or reads or writes a file, network, database, environment, clock or random source, directly or through a call whose name or arguments show it does so (fetch, a path, a URL, a query, send, save). One such read or write on any path is enough.\",\n no: \"The body derives its result from its parameters, from `this`, from module-level values it only reads, and from dependencies it obtains, and returns it. A mutable local accumulator, a copy of an argument that is then modified, and a local object built up and returned are not effects outside the function.\",\n note: \"Obtaining a dependency (a module, a client, a parser handed back by a loader) is not an effect; using an acquired client to fetch, read, write or send is. A body that puts its own result into a cache that outlives the call is an effect even when it is only memoisation.\",\n});\n\nexport const safeNameIsSafe = claimRule({\n id: \"safe-name-is-safe\",\n cutoff: 0.8,\n select: namedLike({\n prefixes: [\"safe\", \"try\"],\n suffixes: [\"OrNull\", \"OrDefault\", \"OrUndefined\"],\n }),\n ask: \"This function's name says that failure is absorbed and reported as a value, but its body has a path on which a failure escapes as a throw or a rejection.\",\n yes: \"A failure of the kind the name promises to absorb can reach the caller as an exception or a rejected promise: the operation that can fail is outside any try, the catch rethrows or throws a new error, a failing case is detected and answered with a throw instead of the null, undefined, default, false or result value the name promises, or the fallback itself is computed by something that can fail.\",\n no: \"Every failure of the kind the name refers to is turned into the value the name promises: null, undefined, a default, a boolean, or a result object the caller can inspect. A body that cannot fail at all, and so has nothing to catch, honours the name.\",\n note: \"A throw on a programmer error, such as an argument of the wrong type, is not the failure such a name promises to absorb. Logging before returning the fallback is fine.\",\n});\n\nexport const idempotentName = claimRule({\n id: \"idempotent-name\",\n cutoff: 0.8,\n select: namedLike({ prefixes: [\"ensure\", \"upsert\", \"setup\", \"install\", \"register\"] }),\n ask: \"This function's name says a repeated call is harmless, but calling it a second time with the same arguments leaves a different result from calling it once.\",\n yes: \"The body performs its effect without finding out whether it is already in place, and repeating the effect accumulates or fails: it appends to a list or adds a listener, creates a record, index, table, column or resource that would then exist twice or make the second creation fail, inserts where a matching row may already be, or runs a step that is not itself safe to repeat, with no existence check, no keyed overwrite and no guard that makes the second call a no-op.\",\n no: \"A second call finds the effect already in place and leaves the state as the first call left it: the body checks for existence before acting, writes by key so a repeat overwrites the same entry, assigns rather than appends, uses an operation that is inherently repeatable (put, set, mkdir with recursive, CREATE IF NOT EXISTS, ON CONFLICT), returns early on a flag it sets, or has no effect at all beyond its return value.\",\n note: \"A helper whose own name says it is repeat-safe (ensure*, upsert*, put*, set*) is assumed to be. Logging on each call, or returning a fresh object each call, is not a different result.\",\n});\n\nexport const catchHidesFailure = claimRule({\n id: \"catch-hides-failure\",\n cutoff: 0.8,\n select: hasCatch,\n ask: \"A catch block in this function hides a failure the function's caller needed to know about.\",\n yes: \"The catch block neither rethrows, returns an error value the signature admits, nor reports through a channel the function is documented to use; it returns a default, an empty value, a made-up value or nothing, or only logs, and the function's name or return type promises a real result: a value that was fetched, parsed or computed, or an operation such as a save or a send that the caller will assume happened.\",\n no: \"The function has no catch block; or the failure is propagated (rethrown, wrapped, or logged and then rethrown); converted into a value the caller can distinguish from success, such as a Result or null when the return type admits it; or absorbed where absorbing is the point: a cleanup or best-effort step after the real result is in hand, a fallback to the next attempt or source, a catch that swallows only the case in which the goal already holds, or a top-level entry point that reports and exits with a non-zero status. A function named safe*, try* or *OrNull has promised to absorb failure.\",\n});\n\nexport const errorMessageMatchesCondition = claimRule({\n id: \"error-message-matches-condition\",\n cutoff: 0.8,\n ask: \"The message given to an error thrown in this function misdescribes the condition that leads to the throw.\",\n yes: \"The message names a different cause, value, operation or expectation than the condition guarding the throw actually checks: it says a thing is missing when the check is about its permission, form or range; it names one field or operand when the condition tests another; it names one failure (a timeout, an expiry) when the status or state tested is a different one; it states a bound or direction the condition does not test; or it is a copy of another throw's message in the same function and describes that throw's condition rather than this one.\",\n no: \"The function throws nothing with a message; or every message describes the condition that leads to its throw, whether it states the failed requirement, its consequence, or the intent the check serves. A message that is short, generic or lacks detail is not wrong, only unhelpful. A message that quotes the offending input, names what cannot proceed, or wraps a caught error with the name of the operation that failed, is a match.\",\n});\n\nexport const logLevelMatchesEvent = claimRule({\n id: \"log-level-matches-event\",\n target: \"call\",\n cutoff: 0.8,\n select: isLogCall,\n context: ENCLOSING_FUNCTION,\n ask: \"The level of this log call misstates the severity of what the surrounding code is handling at that point.\",\n yes: \"The call is at info, debug or trace but sits on a path where the operation has failed and the function gives up, rethrows, exits, discards data or returns a failure the caller must act on; the call is at debug or trace for an outcome the function reports to its caller, such as a refusal; the call is at error or fatal but sits on the ordinary success path or on a routine, expected branch such as a cache miss or a validation failure; or the call is at warn but the code immediately exits or throws with no recovery.\",\n no: \"The level fits what the code around the call shows: error or warn where something went wrong that an operator should see, even if the function recovers from it; info for routine outcomes; debug or trace for per-item progress and chatter; warn for a degraded or transient condition the code goes on to handle. Whether the message text is well written is not the question.\",\n});\n\nexport const logMessageMatchesEvent = claimRule({\n id: \"log-message-matches-event\",\n target: \"call\",\n cutoff: 0.8,\n select: isLogCall,\n context: ENCLOSING_FUNCTION,\n ask: \"The message of this log call misdescribes the event at the point in the code where the call sits.\",\n yes: \"What the message says happened is not what the code path shows at that point: it reports an outcome as done before the operation that produces it runs, or on the branch where that operation failed or was skipped; it names an action (a retry, a deletion, a cache hit, a send) that the path does not perform; it reports a count of what was selected or attempted as the count of what was deleted, sent or written; it interpolates a value that is not what the message calls it; or it names a kind of thing other than the one the surrounding code acts on.\",\n no: \"The message is true of the point where it sits: an intent phrased before the operation, a completion phrased after it, a failure on the branch that fails, a templated message whose values are what it calls them, or a terse message on the path it describes. A message that is vague or could say more is not wrong. Whether the level fits is not the question.\",\n});\n\nexport const commentDescribesBlock = claimRule({\n id: \"comment-describes-block\",\n cutoff: 0.8,\n ask: \"A comment inside this function makes a claim about the code beneath it that the code contradicts.\",\n yes: \"The comment says what the code beneath it does, and the code does something else: a count, limit, number of attempts or delay that differs from the code's; a direction, order, sign, rounding or unit that is not the one the code uses; a condition the code tests the other way round; or a step the comment says happens here that the code beneath it does not perform.\",\n no: \"The function has no comment inside its body; or every specific claim in each comment holds for the code beneath it, meaning the run of statements down to the next comment or the end of the block. A comment that gives a reason outside the code, says what the whole function is for, is vague, or summarises the code loosely but not wrongly, makes no claim the code can contradict. A comment at the end of a line belongs to that line.\",\n});\n\nexport const commentDescribesDeclaration = claimRule({\n id: \"comment-describes-declaration\",\n cutoff: 0.8,\n context: COMMENT,\n ask: \"The comment directly above this function claims something that is not true of the code.\",\n yes: \"A specific claim the comment makes is contradicted by the code: it names a different operation, direction, rounding, ordering or unit than the code uses, it states a return value or guarantee the code does not provide, it describes a side effect the code does not perform or omits one it does, it gives a count, limit or default that differs from the code's, or it refers to a parameter, field or function that the code no longer has.\",\n no: \"Every specific claim the comment makes holds for the code below it. A comment that is vague, redundant or says less than it could is not a false comment. A section heading or divider names the part of the file that starts there and makes no claim about the function.\",\n note: \"Only a comment that ends on the line just before the function, or just before the export or declaration that holds it, is directly above it; a comment followed by other code belongs to that code. Judge only claims the code can confirm or contradict. A comment about a caller's obligations, about performance, or about history is not checkable here.\",\n});\n\nexport const docErrorsMatchBody = claimRule({\n id: \"doc-errors-match-body\",\n cutoff: 0.8,\n context: COMMENT,\n ask: \"The failure contract stated in the documentation right above this function (what it says the function throws, rejects with, or returns in place of a result when something goes wrong, and under what condition) is contradicted by the body.\",\n yes: \"The documentation names a failure the body cannot produce: it says the function throws a named error and the body returns null, a default or a success value on that condition instead. Or it names the wrong failure: a different error type or a different condition than the one the body checks before failing. Or the body explicitly fails on its own (a throw, an assert, or a null or default returned in place of a result) under a condition the documentation says nothing about. Or the documentation says the function never throws and the body has a throw.\",\n no: \"The documentation states no failure contract; or every failure the documentation names is one the body produces under the condition named, and every explicit failure the body writes is covered somewhere in the documentation. A failure described at the level of intent is honoured by whatever mechanism the body uses. A fallback the documentation describes, such as a default when a file is absent, is a documented outcome.\",\n note: \"The snippet starts with the documentation directly above the function, and that documentation is what is judged. An error that merely passes through unchanged from a callee is the callee's failure, not a clause this body owes, unless the documentation says the function cannot fail.\",\n});\n\nexport const varNameDescribesValue = claimRule({\n id: \"var-name-describes-value\",\n cutoff: 0.8,\n ask: \"A binding declared in this function has a name that misdescribes the value it is bound to.\",\n yes: \"The name states a type, unit, shape, quantity or meaning that the initializer does not produce: a plural name bound to a single item or a singular name bound to a collection, a name that reads as a boolean bound to something that is not one, a name naming one unit while the value is in another, a name saying it holds a value while it holds a function or a promise, or a name describing a different thing entirely from what the initializer computes.\",\n no: \"Every name is an accurate description of what its initializer produces, even if it is terse or a clearer name could be imagined. Being short or generic is not a mismatch. A plural name on a number names the count of those things; an accumulator, index or buffer name is a convention, not a claim.\",\n});\n\nexport const codeClaims = [\n fnNamePromises,\n pureNameIsPure,\n safeNameIsSafe,\n idempotentName,\n catchHidesFailure,\n errorMessageMatchesCondition,\n logLevelMatchesEvent,\n logMessageMatchesEvent,\n commentDescribesBlock,\n commentDescribesDeclaration,\n docErrorsMatchBody,\n varNameDescribesValue,\n] as const satisfies readonly DecisionRule[];\n","import { defineDecisionRule } from \"#/entities/decision/index.ts\";\nimport { namedLike } from \"#/features/define-presets/lib/claim-select.ts\";\n\nexport const noPiiInLogs = defineDecisionRule({\n id: \"no-pii-in-logs\",\n target: \"call\",\n question:\n \"Does this call write personal data, such as an email or phone number, to a log or console?\",\n cutoff: 0.8,\n});\n\nexport const noPromptInjection = defineDecisionRule({\n id: \"no-prompt-injection\",\n target: \"function\",\n question:\n \"Does this function build a language model prompt by concatenating untrusted user input into the instructions?\",\n cutoff: 0.8,\n});\n\nexport const noHardcodedSecrets = defineDecisionRule({\n id: \"no-hardcoded-secrets\",\n target: \"file\",\n question:\n \"Does this file contain a hard-coded secret, such as an API key, password, or private token, as a literal value?\",\n cutoff: 0.8,\n});\n\nexport const nameMatchesBehavior = defineDecisionRule({\n id: \"name-matches-behavior\",\n target: \"function\",\n select: namedLike({\n prefixes: [\"get\", \"find\", \"load\", \"fetch\", \"read\", \"lookup\", \"query\", \"list\", \"search\"],\n }),\n question:\n \"Does this function's name describe only reading or fetching data (for example get, find, load or fetch), while its body also changes or announces something on the side, such as writing to a database or file, logging, or sending a message? Sending the request that fetches the data, such as calling an API or a model and reading its answer, is the fetching itself and does not count.\",\n cutoff: 0.8,\n});\n\nexport const untrustedInputRisk = defineDecisionRule({\n id: \"untrusted-input-risk\",\n target: \"function\",\n question:\n \"Does this function splice untrusted input, such as a user message or request parameter, into the same string as a SQL query, shell command, eval code, HTML, or language model instructions, instead of passing it as a separate parameter or field? Count input as untrusted only when it comes from outside the program, such as a request, a user message, a form, or a file or response the program does not control; a parameter whose origin is not shown counts when its name or type marks it as user or request data. Text taken from the program's own rule definitions, settings, constants or cache is not untrusted, and JSON.parse is not eval.\",\n cutoff: 0.8,\n answer: { kind: \"severity\", minimum: \"warn\" },\n});\n\nexport const domainNaming = defineDecisionRule({\n id: \"domain-naming\",\n target: \"function\",\n question:\n \"Is this function named after a mechanism word such as Manager, Processor, Handler, Helper, Data, Info, handle, process, or do, while its body works on one specific business concept, such as an invoice, an order, or a refund, that the name should call by its domain name instead? Code whose subject is a generic mechanism, such as HTTP, files, the command line, or framework glue, does not count.\",\n cutoff: 0.8,\n});\n\nexport const preferSchemaValidation = defineDecisionRule({\n id: \"prefer-schema-validation\",\n target: \"function\",\n question:\n \"Does this function check the shape or values of untyped data, such as parsed JSON, a request body, config, or an API response, with a long hand-written chain of typeof, instanceof, in, or field checks joined by && or ||, where a schema from a validation library would state the same rules more simply? A single simple check does not count.\",\n cutoff: 0.8,\n});\n","import type { DecisionRule } from \"#/entities/decision/index.ts\";\nimport { claimRule } from \"#/features/define-presets/lib/claim-rule.ts\";\nimport { isDescribeCall, isTestCall } from \"#/features/define-presets/lib/claim-select.ts\";\n\nexport const describeNamesSubject = claimRule({\n id: \"describe-names-subject\",\n cutoff: 0.8,\n target: \"call\",\n select: isDescribeCall,\n ask: \"The tests inside this describe block exercise something other than what its title names.\",\n yes: \"The title names a specific function, method, class or module and no test in the block calls, constructs or otherwise reaches it: every test calls a differently named sibling instead; or the title names a behaviour and no test makes that behaviour happen or observes it.\",\n no: \"What the title names is what the tests exercise, directly or through something that reaches it: a feature tested through a public function of another name, a class tested through its factory or an instance created in beforeEach, a title that is a file name, a scenario or a sentence when the tests are about it, or an abbreviation or synonym of what the tests call.\",\n});\n\nexport const testNameDescribesCode = claimRule({\n id: \"test-name-describes-code\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"The operation, input or outcome this test exercises is not the one the test's name names.\",\n yes: \"The operation the code calls is not the one the name says; the input or case the code sets up is not the one the name states (three units where the name says above ten); the outcome the code expects is the opposite of the one the name implies; the name promises a throw or a rejection where the code expects an ordinary value; or the name refers to something that the code never calls and never checks.\",\n no: \"The code calls the operation the name says, on the input the name says, and expects the kind of outcome the name says, however weak the assertion is. A one-word title, a synonym for the operation's name, and setup that calls other operations before the named one are all fine.\",\n});\n\nexport const testNameVerifiesClaim = claimRule({\n id: \"test-name-verifies-claim\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"This test would still pass if the behaviour its name claims were broken.\",\n yes: \"The body does not establish what the name claims: it asserts nothing at all, it asserts something that would hold whether or not the named behaviour worked, it checks an incidental property such as a length or a type instead of the named behaviour itself, or it never sets up the case the name is about.\",\n no: \"The body contains at least one assertion that would fail if the named behaviour were broken. A name that claims only that something renders or matches a snapshot is established by the snapshot; a name that claims an interaction with a collaborator is established by an assertion on that call; a name that claims only that something does not throw is established by calling it.\",\n});\n\nexport const snapshotOnlyBehaviourClaim = claimRule({\n id: \"snapshot-only-behaviour-claim\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"This test's name claims a specific behaviour, but the body only compares a snapshot.\",\n yes: \"The title asserts a property of the output (an ordering, an element hidden or shown, a state rendered under a condition, a format applied) and the only assertions are toMatchSnapshot, toMatchInlineSnapshot or toMatchFileSnapshot over a whole rendering, so nothing isolates the named property.\",\n no: \"The body uses no snapshot; or the title claims only that the output matches a snapshot or renders, or only names the input; or at least one assertion targets the named behaviour directly; or the inline snapshot is a short literal that is itself the named outcome.\",\n});\n\nexport const testMocksSubject = claimRule({\n id: \"test-mocks-subject\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"The behaviour this test's name attributes to the code under test is performed by a mock or stub whose canned value the assertion reads back unchanged.\",\n yes: \"The title says the code under test computes, derives or returns something, but the function or module that would do it is replaced (vi.mock or jest.mock with a fake, mockReturnValue or mockResolvedValue, a stubbed global) and the value the assertion checks can be traced to that stub's configuration with none of the subject's own logic in between. The assertion then checks the test's own setup.\",\n no: \"The body mocks nothing; or the stub stands in for a collaborator the code under test calls (the network, the clock, a repository, a mailer) and the assertion checks what the real code did with the stub's output; or the title is itself about the collaborator; or the spy has no replacement value and the real method runs.\",\n});\n\nexport const testClaims = [\n describeNamesSubject,\n testNameDescribesCode,\n testNameVerifiesClaim,\n snapshotOnlyBehaviourClaim,\n testMocksSubject,\n] as const satisfies readonly DecisionRule[];\n","import type { DecisionRule } from \"#/entities/decision/index.ts\";\n\nimport {\n catchHidesFailure,\n commentDescribesBlock,\n commentDescribesDeclaration,\n docErrorsMatchBody,\n errorMessageMatchesCondition,\n fnNamePromises,\n idempotentName,\n logLevelMatchesEvent,\n logMessageMatchesEvent,\n pureNameIsPure,\n safeNameIsSafe,\n varNameDescribesValue,\n} from \"./code-claims.ts\";\nimport {\n domainNaming,\n nameMatchesBehavior,\n noHardcodedSecrets,\n noPiiInLogs,\n noPromptInjection,\n preferSchemaValidation,\n untrustedInputRisk,\n} from \"./rules.ts\";\nimport {\n describeNamesSubject,\n snapshotOnlyBehaviourClaim,\n testMocksSubject,\n testNameDescribesCode,\n testNameVerifiesClaim,\n} from \"./test-claims.ts\";\n\nexport type Preset = readonly [DecisionRule, ...DecisionRule[]];\n\nexport const recommended: Preset = [noPiiInLogs, noPromptInjection, noHardcodedSecrets];\n\nexport const strict: Preset = [\n ...recommended,\n nameMatchesBehavior,\n untrustedInputRisk,\n pureNameIsPure,\n safeNameIsSafe,\n idempotentName,\n catchHidesFailure,\n testNameVerifiesClaim,\n testMocksSubject,\n];\n\nexport const reviewOnly: Preset = [\n domainNaming,\n preferSchemaValidation,\n fnNamePromises,\n commentDescribesDeclaration,\n commentDescribesBlock,\n docErrorsMatchBody,\n errorMessageMatchesCondition,\n logLevelMatchesEvent,\n logMessageMatchesEvent,\n varNameDescribesValue,\n describeNamesSubject,\n testNameDescribesCode,\n snapshotOnlyBehaviourClaim,\n];\n\nexport const presets = { recommended, strict, reviewOnly } as const satisfies Readonly<\n Record<string, Preset>\n>;\n","import { createDecisionPlugin } from \"@r_masseater/oxlint-plugin-decision\";\nimport type { DecisionPlugin } from \"@r_masseater/oxlint-plugin-decision\";\n\nimport type { Preset } from \"#/features/define-presets/index.ts\";\n\nconst PLUGIN_NAME = \"decision-presets\";\n\nexport const presetPlugin = (rules: Preset): DecisionPlugin =>\n createDecisionPlugin({ name: PLUGIN_NAME, rules });\n"],"mappings":";;;;AAOA,MAAM,8BAAmC,IAAI,IAAI,CAC/C,IACA,GAAGA,OAAI,MAAM,yCAAyC,EAAE,CAC1D,CAAC;AAED,MAAM,iBAAiB;AAEvB,MAAM,kBACH,UACA,SACC,UAAU,KACP,SAAiBA,OAAI,WAAW,IAAI,CAAC,CAAC,IAAI,IAC1C,SAAiB,YAAY,IAAIA,OAAI,MAAM,KAAK,QAAQ,KAAK,SAAS,cAAc,CAAC,CAAC,IAAI,CAAC,CAC9F,CAAC,CAAC,IAAI;AAEV,MAAM,YACH,UACA,SACCA,OAAI,SAAS,IAAI,CAAC,CAAC,IAAI;AAO3B,MAAa,aAAa,EAAE,UAAU,WAAW,CAAC,QAA2B;CAC3E,MAAM,WAAW,CACf,GAAG,KACD,UACAC,MAAI,KAAK,SAAS,eAAe,IAAI,CAAC,CACxC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BAAuB,UAAU;CAC5C,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,wBAAwB,UAAU;CAC7C,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,wBAAwB,UAAU;CAC7C,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,6BAA6B,UAAU;CAClD,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,mBAAmB,UAAU;CACxC,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,aAAa;CACxB;CACA;CACA;CACA;CACA;AACF;;ACzBA,MAAa,cAAsB;CAAC;CAAa;CAAmB;AAAkB;AAEtF,MAAa,SAAiB;CAC5B,GAAG;CACH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,aAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,UAAU;CAAE;CAAa;CAAQ;AAAW;;AC5DzD,MAAM,cAAc;AAEpB,MAAa,gBAAgB,UAC3B,qBAAqB;CAAE,MAAM;CAAa;AAAM,CAAC"}
@@ -1,5 +1,5 @@
1
- import { o as DecisionPlugin } from "../index-C0Twu0w7.mjs";
2
- import { B as redundantGuard, F as commentRestatesCode, H as suppressionInsteadOfFix, I as defaultMasksMissingValue, L as docRestatesSignature, M as aiSlopRules, N as castInsteadOfNarrowing, P as commentNarratesHistory, R as passThroughWrapper, V as reinventsBuiltin, z as placeholderImplementation } from "../index-HOwrGbIA.mjs";
1
+ import { o as DecisionPlugin } from "../index-CK88FBE5.mjs";
2
+ import { B as redundantGuard, F as commentRestatesCode, H as suppressionInsteadOfFix, I as defaultMasksMissingValue, L as docRestatesSignature, M as aiSlopRules, N as castInsteadOfNarrowing, P as commentNarratesHistory, R as passThroughWrapper, V as reinventsBuiltin, z as placeholderImplementation } from "../index-B4wX62VC.mjs";
3
3
  declare const plugin: DecisionPlugin;
4
4
  export { aiSlopRules, castInsteadOfNarrowing, commentNarratesHistory, commentRestatesCode, plugin as default, defaultMasksMissingValue, docRestatesSignature, passThroughWrapper, placeholderImplementation, redundantGuard, reinventsBuiltin, suppressionInsteadOfFix };
5
5
  //# sourceMappingURL=ai-slop.d.mts.map
@@ -1,5 +1,182 @@
1
- import { t as createDecisionPlugin } from "../app-UakaWKAT.mjs";
2
- import { B as reinventsBuiltin, F as defaultMasksMissingValue, I as docRestatesSignature, L as passThroughWrapper, M as castInsteadOfNarrowing, N as commentNarratesHistory, P as commentRestatesCode, R as placeholderImplementation, V as suppressionInsteadOfFix, j as aiSlopRules, z as redundantGuard } from "../define-presets-yflVt8vT.mjs";
1
+ import { t as createDecisionPlugin } from "../app-D2bguKZ_.mjs";
2
+ import { a as dualSelect, i as containing, o as identifierOf, r as claimRule, s as ofType } from "../claim-rule-B0LCcxxc.mjs";
3
+ import { Array, Match, Option, Predicate, String, pipe } from "effect";
4
+ // src/features/define-presets/lib/ai-slop-select.ts
5
+ const isPlaceholderValue = ofType("Literal", "TemplateLiteral", "ArrayExpression", "ObjectExpression");
6
+ const isFallbackOperator = (node) => Match.value(node).pipe(Match.when({
7
+ type: "LogicalExpression",
8
+ operator: "??"
9
+ }, () => true), Match.when({
10
+ type: "LogicalExpression",
11
+ operator: "||"
12
+ }, (logical) => isPlaceholderValue(logical.right)), Match.when({
13
+ type: "AssignmentExpression",
14
+ operator: "??="
15
+ }, () => true), Match.when({
16
+ type: "AssignmentExpression",
17
+ operator: "||="
18
+ }, () => true), Match.orElse(() => false));
19
+ const isTypeofCheck = (node) => Match.value(node).pipe(Match.when({
20
+ type: "UnaryExpression",
21
+ operator: "typeof"
22
+ }, () => true), Match.orElse(() => false));
23
+ const isConstAssertion = (annotation) => Match.value(annotation).pipe(Match.when({
24
+ type: "TSTypeReference",
25
+ typeName: {
26
+ type: "Identifier",
27
+ name: "const"
28
+ }
29
+ }, () => true), Match.orElse(() => false));
30
+ const isCast = (node) => Match.value(node).pipe(Match.when({ type: "TSAsExpression" }, (cast) => !isConstAssertion(cast.typeAnnotation)), Match.when({ type: "TSTypeAssertion" }, () => true), Match.when({ type: "TSNonNullExpression" }, () => true), Match.orElse(() => false));
31
+ const bodyOf = (node) => Match.value(node).pipe(Match.when({ type: "FunctionDeclaration" }, (fn) => Option.fromNullishOr(fn.body)), Match.when({ type: "FunctionExpression" }, (fn) => Option.fromNullishOr(fn.body)), Match.when({ type: "ArrowFunctionExpression" }, (fn) => Option.some(fn.body)), Match.orElse(() => Option.none()));
32
+ const statementsOf = (body) => Match.value(body).pipe(Match.when({ type: "BlockStatement" }, (block) => block.body), Match.orElse((expression) => [expression]));
33
+ const ONE_STATEMENT = 1;
34
+ const isCall = ofType("CallExpression", "NewExpression");
35
+ const parentOf = (node) => Option.fromNullishOr(node.parent);
36
+ const isArgument = (node) => Option.exists(parentOf(node), isCall);
37
+ const isOptionOfCall = (node) => parentOf(node).pipe(Option.filter(ofType("Property")), Option.flatMap(parentOf), Option.filter(ofType("ObjectExpression")), Option.exists(isArgument));
38
+ const isCallback = Predicate.or(isArgument, isOptionOfCall);
39
+ const isDeclared = Predicate.not(isCallback);
40
+ const isShort = (node) => Option.exists(bodyOf(node), (body) => statementsOf(body).length <= ONE_STATEMENT);
41
+ const hasAtMostOneStatement = Predicate.and(isDeclared, isShort);
42
+ const expressionOf = (statement) => Match.value(statement).pipe(Match.when({ type: "ReturnStatement" }, (returned) => Option.fromNullishOr(returned.argument)), Match.when({ type: "ExpressionStatement" }, (expression) => Option.some(expression.expression)), Match.orElse((other) => Option.some(other)));
43
+ const awaitedOf = (expression) => Match.value(expression).pipe(Match.when({ type: "AwaitExpression" }, (awaited) => awaited.argument), Match.orElse((plain) => plain));
44
+ const isForwardingStatement = (statements) => Option.exists(Option.flatMap(Array.head(statements), expressionOf), (expression) => awaitedOf(expression).type === "CallExpression");
45
+ const isSingleCall = (node) => Option.exists(bodyOf(node), (body) => isForwardingStatement(statementsOf(body)));
46
+ const paramsOf = (node) => Match.value(node).pipe(Match.when({ type: "FunctionDeclaration" }, (fn) => fn.params), Match.when({ type: "FunctionExpression" }, (fn) => fn.params), Match.when({ type: "ArrowFunctionExpression" }, (fn) => fn.params), Match.orElse(() => []));
47
+ const nameOf = (node) => Match.value(node).pipe(Match.when({ type: "SpreadElement" }, (spread) => identifierOf(spread.argument)), Match.when({ type: "RestElement" }, (rest) => identifierOf(rest.argument)), Match.orElse((plain) => identifierOf(plain)));
48
+ const argumentsOf = (node) => bodyOf(node).pipe(Option.flatMap((body) => Array.head(statementsOf(body))), Option.flatMap(expressionOf), Option.map(awaitedOf), Option.flatMap((expression) => Match.value(expression).pipe(Match.when({ type: "CallExpression" }, (call) => Option.some(call.arguments)), Match.orElse(() => Option.none()))));
49
+ const isForwardedArgument = (names) => (argument) => Match.value(argument).pipe(Match.when({ type: "Literal" }, () => true), Match.orElse((other) => Option.exists(nameOf(other), (name) => names.includes(name))));
50
+ const passesExactly = (names) => Predicate.and((passed) => pipe(passed, Array.every((argument) => isForwardedArgument(names)(argument))), (passed) => {
51
+ const passedNames = Array.getSomes(pipe(passed, Array.map((argument) => nameOf(argument))));
52
+ return pipe(names, Array.every((name) => passedNames.includes(name)));
53
+ });
54
+ const passesParamsUnchanged = (node) => pipe(paramsOf(node), Array.map((param) => nameOf(param)), Option.all, Option.exists((names) => Option.exists(argumentsOf(node), passesExactly(names))));
55
+ const forwardsOneCall = Predicate.and(Predicate.and(hasAtMostOneStatement, isSingleCall), passesParamsUnchanged);
56
+ const declaredTypeOf = (param) => Match.value(param).pipe(Match.when({ type: "AssignmentPattern" }, (assigned) => declaredTypeOf(assigned.left)), Match.when({ type: "TSParameterProperty" }, (property) => declaredTypeOf(property.parameter)), Match.when({ typeAnnotation: { type: "TSTypeAnnotation" } }, (typed) => Option.some(typed.typeAnnotation.typeAnnotation)), Match.orElse(() => Option.none()));
57
+ const isOpenType = ofType("TSUnknownKeyword", "TSAnyKeyword");
58
+ const hasNarrowParameter = (node) => pipe(paramsOf(node), Array.some((param) => Option.exists(declaredTypeOf(param), Predicate.not(isOpenType))));
59
+ const typeParameterNamesOf = (node) => Match.value(node).pipe(Match.when({ typeParameters: { type: "TSTypeParameterDeclaration" } }, (generic) => pipe(generic.typeParameters.params, Array.map((parameter) => parameter.name.name))), Match.orElse(() => []));
60
+ const referencedNameOf = (type) => Match.value(type).pipe(Match.when({
61
+ type: "TSTypeReference",
62
+ typeName: { type: "Identifier" }
63
+ }, (reference) => Option.some(reference.typeName.name)), Match.orElse(() => Option.none()));
64
+ const isGenericParameter = (node, param) => Option.exists(Option.flatMap(declaredTypeOf(param), referencedNameOf), (name) => typeParameterNamesOf(node).includes(name));
65
+ const returnedOf = (node) => Option.flatMap(bodyOf(node), (body) => Option.flatMap(Array.head(statementsOf(body)), expressionOf));
66
+ const returnedNameOf = (node) => Option.flatMap(returnedOf(node), identifierOf);
67
+ const returnsParameter = (node, param) => Option.exists(Option.all([returnedNameOf(node), identifierOf(param)]), ([returned, given]) => returned === given);
68
+ const ONE_PARAMETER = 1;
69
+ const onlyParameterOf = (node) => Option.liftPredicate(paramsOf(node), (params) => params.length === ONE_PARAMETER).pipe(Option.flatMap(Array.head));
70
+ const isGenericIdentity = (node) => onlyParameterOf(node).pipe(Option.filter((param) => isGenericParameter(node, param)), Option.exists((param) => returnsParameter(node, param)));
71
+ const mayBePlaceholder = Predicate.and(hasAtMostOneStatement, Predicate.not(isGenericIdentity));
72
+ const isGuard = Predicate.or(ofType("IfStatement", "ConditionalExpression", "ChainExpression", "TryStatement"), isTypeofCheck);
73
+ const hasGuard = Predicate.and(hasNarrowParameter, containing(isGuard));
74
+ const isFallback = Predicate.or(isFallbackOperator, ofType("AssignmentPattern"));
75
+ const hasFallback = dualSelect(containing(isFallback));
76
+ const hasCast = dualSelect(containing(isCast));
77
+ // src/features/define-presets/lib/comment-select.ts
78
+ const commentsIn = (node, { context }) => {
79
+ const [start, end] = node.range;
80
+ return pipe(context.sourceCode.getAllComments(), Array.filter((comment) => comment.start >= start && comment.end <= end), Array.map((comment) => comment.value));
81
+ };
82
+ const hasCommentInside = dualSelect((node, match) => Array.isReadonlyArrayNonEmpty(commentsIn(node, match)));
83
+ const SUPPRESSIONS = [
84
+ "eslint-disable",
85
+ "oxlint-disable",
86
+ "@ts-ignore",
87
+ "@ts-expect-error",
88
+ "@ts-nocheck",
89
+ "fallow-ignore"
90
+ ];
91
+ const hasSuppression = dualSelect((node, match) => pipe(commentsIn(node, match), Array.some((comment) => pipe(SUPPRESSIONS, Array.some((word) => String.includes(word)(comment))))));
92
+ // src/features/define-presets/model/ai-slop-rules.ts
93
+ const CUTOFF = .8;
94
+ const slopRule = (rule) => claimRule({
95
+ cutoff: CUTOFF,
96
+ ...rule
97
+ });
98
+ const redundantGuard = slopRule({
99
+ id: "redundant-guard",
100
+ select: hasGuard,
101
+ ask: "This function checks one of its own parameters for a case that the parameter's declared type already rules out, so the check can never change what happens.",
102
+ yes: "A parameter whose type annotation is non-optional and non-nullable, such as `user: User` or `name: string`, is compared with null or undefined, has its `typeof` tested against the type it is already declared as, or is read with `?.`.",
103
+ no: "No parameter is checked against its own declared type. Checks on local variables do not count: a local that holds the result of `Map.get`, `find`, `JSON.parse` or any other call, or a value annotated `unknown`, can really be missing or of another type, so checking it is necessary. Parameters of plain JavaScript have no declared type, so any check on them is allowed."
104
+ });
105
+ const defaultMasksMissingValue = slopRule({
106
+ id: "default-masks-missing-value",
107
+ select: hasFallback,
108
+ ask: "This function replaces a value that should always be present with a made-up default, so a missing value is hidden instead of reported.",
109
+ yes: "A `??` or `||` default, or a default parameter, stands in for data the rest of the code treats as required, such as an id, a user, a price, a config entry or a response field, with a placeholder like 'unknown', '', 0, [] or {} that later code will use as if it were real; or a chain of two or more fallbacks (`a ?? b ?? c`) picks among sources with no sign of why that order is right.",
110
+ no: "Every default is a value the domain genuinely allows when the input is absent, such as an optional setting with a documented default, an empty list for an optional filter, or a display label for an optional field; or the missing case is reported, thrown or returned to the caller instead of being filled in."
111
+ });
112
+ const passThroughWrapper = slopRule({
113
+ id: "pass-through-wrapper",
114
+ select: forwardsOneCall,
115
+ ask: "This function only forwards its arguments to another function and returns the result, adding no behaviour of its own.",
116
+ yes: "The body is a single call that receives every parameter exactly as it came in, in the same order, or with an extra argument that is always the same constant, and returns or awaits the result unchanged, so callers could call the inner function directly.",
117
+ no: "The function changes something on the way: it transforms an argument before passing it on (for example trimming, lower-casing, converting or validating it), transforms the result, binds a dependency, adapts to a different signature a caller requires, or it is an entry point that a framework or another package calls by name."
118
+ });
119
+ const placeholderImplementation = slopRule({
120
+ id: "placeholder-implementation",
121
+ select: mayBePlaceholder,
122
+ ask: "This function is a stand-in that pretends to do its job: it returns a fixed value or does nothing where its name promises real work.",
123
+ yes: "The body is empty, only logs, or only holds a TODO while the name promises an action; a validator, checker or permission function always returns true or always returns false; a function named after a computation returns a hard-coded number, string or object; or a branch the name promises to handle silently does nothing.",
124
+ no: "The body does the work its name promises, even simply. An intentional no-op whose name says so (noop, ignore, a default callback), an abstract method meant to be overridden, and a test double inside test code are not placeholders."
125
+ });
126
+ const commentRestatesCode = slopRule({
127
+ id: "comment-restates-code",
128
+ select: hasCommentInside,
129
+ ask: "A comment inside this function only translates the next line of code into words and adds no reason, unit, or constraint.",
130
+ yes: "A comment repeats the code in words, such as `// increment the counter` over `count += 1`, `// loop over the items` over a for loop, or `// return the total` over a return; deleting it would leave a reader knowing exactly as much.",
131
+ no: "Every comment says something the code cannot say on its own: why it is done this way (often with `because` or `so`), a fact about the outside world such as a billing rule, an API quirk or a standard, a unit, or an invariant. Lint directive comments such as `eslint-disable` are not judged here."
132
+ });
133
+ const commentNarratesHistory = slopRule({
134
+ id: "comment-narrates-history",
135
+ select: hasCommentInside,
136
+ ask: "A comment inside this function records how the code came to be, or speaks to the person who asked for the change, instead of describing the code as it stands.",
137
+ yes: "A comment says what was added, changed, removed, fixed or kept for compatibility (`added X`, `changed to Y`, `previously`, `now uses`, `new:`), marks the code as a stopgap (`temporary`, `for now`, `quick fix`, `hack until`), mentions a date, a ticket in progress, a model or a conversation, or addresses a reader as if replying (`as requested`, `here we`, `note that I`).",
138
+ no: "Every comment describes the code as it is now and would still be true and useful to a reader who never saw the earlier version or the conversation. A TODO that names a concrete missing case is a description of the code, not history."
139
+ });
140
+ const docRestatesSignature = slopRule({
141
+ id: "doc-restates-signature",
142
+ context: { scope: "comment" },
143
+ ask: "The comment above this function contains nothing except the function's name and parameter names reworded.",
144
+ yes: "Every sentence of the comment can be rebuilt from the signature alone, such as `Gets the order.`, `@param id - the id`, `@returns the order` or `Creates a new instance.`",
145
+ no: "At least one sentence states behaviour the signature does not show, such as what is returned when nothing matches, when it fails, a unit or range, a side effect, or how values are compared."
146
+ });
147
+ const castInsteadOfNarrowing = slopRule({
148
+ id: "cast-instead-of-narrowing",
149
+ select: hasCast,
150
+ ask: "This function uses a type assertion (`as`, `<T>` or a non-null `!`) to silence the type checker where the value is not known to have that type.",
151
+ yes: "The asserted type is not established by anything on the path: data from parsing, I/O, `unknown`, `any` or a wider union is cast to a specific shape without a check, a possibly missing value gets `!` without a preceding check or a guarantee from the API, or the cast goes through `unknown` (`as unknown as T`) to force an unrelated type.",
152
+ no: "Each assertion states something the code has just established or the API guarantees, such as a cast after a type guard, a DOM element looked up by a selector that the same module creates, or a literal narrowed for an overload; `as const` is not a cast."
153
+ });
154
+ const suppressionInsteadOfFix = slopRule({
155
+ id: "suppression-instead-of-fix",
156
+ select: hasSuppression,
157
+ ask: "A lint or type-check suppression comment inside this function hides a problem that the code next to it could simply fix.",
158
+ yes: "The directive gives no reason after the rule name, or the line it silences has a direct local fix, such as handling a floating promise, typing a value instead of `any`, removing an unused variable, or narrowing instead of `@ts-ignore`.",
159
+ no: "Every directive is followed by `--` or a comment with a reason explaining why the rule does not fit this line, such as output a command-line tool prints on purpose, a wrong third-party type, or generated code."
160
+ });
161
+ const reinventsBuiltin = slopRule({
162
+ id: "reinvents-builtin",
163
+ select: isDeclared,
164
+ ask: "This function contains a hand-written loop or algorithm that re-implements something the JavaScript standard library or the platform already provides.",
165
+ yes: "A loop or manual algorithm in the body does what one built-in call does: de-duplicating with an array and includes instead of a Set, deep copying instead of structuredClone, grouping instead of Object.groupBy, building query strings instead of URLSearchParams, formatting numbers or dates instead of Intl, padding instead of padStart, flattening instead of flat, or finding the last match instead of findLast.",
166
+ no: "The function has no such hand-written loop: it already calls the built-in directly (for example `new Set`, `structuredClone`, `reduce` or `Intl`), or its loop does domain work that no single built-in does. A chain of built-in array methods such as `filter`, `map`, `flatMap` and `flat` already uses the built-ins."
167
+ });
168
+ const aiSlopRules = [
169
+ redundantGuard,
170
+ defaultMasksMissingValue,
171
+ passThroughWrapper,
172
+ placeholderImplementation,
173
+ commentRestatesCode,
174
+ commentNarratesHistory,
175
+ docRestatesSignature,
176
+ castInsteadOfNarrowing,
177
+ suppressionInsteadOfFix,
178
+ reinventsBuiltin
179
+ ];
3
180
  // src/app/ai-slop.ts
4
181
  const plugin = createDecisionPlugin({
5
182
  name: "decision-ai-slop",