@r_masseater/oxlint-plugin-decision 0.6.0 → 0.7.0

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 (50) hide show
  1. package/README.md +6 -3
  2. package/dist/{src-CknkhDKf.mjs → app-Bso1uwY5.mjs} +18 -142
  3. package/dist/app-Bso1uwY5.mjs.map +1 -0
  4. package/dist/cloudflare-worker.mjs +6 -182
  5. package/dist/cloudflare-worker.mjs.map +1 -1
  6. package/dist/decision-BtTZ52be.mjs +643 -0
  7. package/dist/decision-BtTZ52be.mjs.map +1 -0
  8. package/dist/{presets-CxYinkkJ.mjs → define-presets-clyqLZxo.mjs} +197 -17
  9. package/dist/define-presets-clyqLZxo.mjs.map +1 -0
  10. package/dist/index-BOrpK3Iv.d.mts +89 -0
  11. package/dist/{index-DiH-hZUS.d.mts → index-Cgg-w0hb.d.mts} +5 -7
  12. package/dist/index-D7VrRpTx.d.mts +6 -0
  13. package/dist/index.d.mts +2 -1
  14. package/dist/index.mjs +1 -1
  15. package/dist/openrouter-app.d.mts +8 -4
  16. package/dist/openrouter-app.mjs +1 -89
  17. package/dist/openrouter-worker.mjs +5 -36
  18. package/dist/openrouter-worker.mjs.map +1 -1
  19. package/dist/preset-plugin-AAwedMeS.mjs +10 -0
  20. package/dist/preset-plugin-AAwedMeS.mjs.map +1 -0
  21. package/dist/presets/ai-slop.d.mts +4 -13
  22. package/dist/presets/ai-slop.mjs +3 -183
  23. package/dist/presets/ai-slop.mjs.map +1 -1
  24. package/dist/presets/index.d.mts +2 -78
  25. package/dist/presets/index.mjs +1 -1
  26. package/dist/presets/recommended.d.mts +2 -1
  27. package/dist/presets/recommended.mjs +3 -2
  28. package/dist/presets/recommended.mjs.map +1 -1
  29. package/dist/presets/review-only.d.mts +2 -1
  30. package/dist/presets/review-only.mjs +3 -2
  31. package/dist/presets/review-only.mjs.map +1 -1
  32. package/dist/presets/strict.d.mts +2 -1
  33. package/dist/presets/strict.mjs +3 -2
  34. package/dist/presets/strict.mjs.map +1 -1
  35. package/dist/serve-decisions-CjlhvYm7.mjs +290 -0
  36. package/dist/serve-decisions-CjlhvYm7.mjs.map +1 -0
  37. package/package.json +4 -4
  38. package/skills/write-decision-rules/SKILL.md +15 -14
  39. package/skills/write-decision-rules/references/tuning.md +1 -1
  40. package/dist/openrouter-app.mjs.map +0 -1
  41. package/dist/presets-CxYinkkJ.mjs.map +0 -1
  42. package/dist/runtime-CICpEidL.mjs +0 -271
  43. package/dist/runtime-CICpEidL.mjs.map +0 -1
  44. package/dist/select-bvQylrUt.mjs +0 -12
  45. package/dist/select-bvQylrUt.mjs.map +0 -1
  46. package/dist/serve-decisions-BM0bUWWe.mjs +0 -119
  47. package/dist/serve-decisions-BM0bUWWe.mjs.map +0 -1
  48. package/dist/src-CknkhDKf.mjs.map +0 -1
  49. package/dist/wire-CRD1mSAo.mjs +0 -251
  50. package/dist/wire-CRD1mSAo.mjs.map +0 -1
@@ -0,0 +1,643 @@
1
+ import { Array, Boolean, Cause, Config, Console, DateTime, Effect, Exit, Function, Match, Number as Number$1, Option, Order, Predicate, Record, Result, Schema, String as String$1, pipe } from "effect";
2
+ // src/entities/decision/model/schema.ts
3
+ const NONE = 0;
4
+ const MINIMUM_LABELS = 2;
5
+ const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(NONE));
6
+ const Probability = Schema.Finite.check(Schema.isBetween({
7
+ minimum: 0,
8
+ maximum: 1
9
+ }));
10
+ const CONFIDENT = .8;
11
+ const Cutoff = Schema.Finite.check(Schema.isBetween({
12
+ minimum: CONFIDENT,
13
+ maximum: 1
14
+ }, { message: `cutoff must be between ${CONFIDENT} and 1` }));
15
+ const TargetSchema = Schema.Literals([
16
+ "function",
17
+ "call",
18
+ "jsx",
19
+ "file"
20
+ ]);
21
+ const CiBehaviorSchema = Schema.Literals(["skip", "fail"]);
22
+ const ExplainSettingSchema = Schema.Union([Schema.Boolean, Schema.Literals(["text", "json"])]);
23
+ const EnclosingKindSchema = Schema.Literals([
24
+ "function",
25
+ "class",
26
+ "block"
27
+ ]);
28
+ const RuleContextSchema = Schema.Union([
29
+ Schema.Struct({ scope: Schema.Literals([
30
+ "node",
31
+ "file",
32
+ "comment"
33
+ ]) }),
34
+ Schema.Struct({
35
+ scope: Schema.Literal("lines"),
36
+ before: Schema.optionalKey(NonNegativeInt),
37
+ after: Schema.optionalKey(NonNegativeInt)
38
+ }),
39
+ Schema.Struct({
40
+ scope: Schema.Literal("enclosing"),
41
+ kind: EnclosingKindSchema
42
+ })
43
+ ]);
44
+ const SeveritySchema = Schema.Literals([
45
+ "info",
46
+ "warn",
47
+ "error"
48
+ ]);
49
+ const Label = Schema.NonEmptyString;
50
+ const BooleanAnswer = Schema.Struct({ kind: Schema.Literal("boolean") });
51
+ const ClassifyAnswer = Schema.Struct({
52
+ kind: Schema.Literal("classify"),
53
+ labels: Schema.Record(Label, Schema.String).check(Schema.isMinProperties(MINIMUM_LABELS)),
54
+ report: Schema.NonEmptyArray(Label)
55
+ }).check(Schema.makeFilter(({ labels, report }) => pipe(report, Array.every((label) => Record.has(labels, label))), { message: "every label in report must be one of labels" }));
56
+ const SeverityAnswer = Schema.Struct({
57
+ kind: Schema.Literal("severity"),
58
+ minimum: Schema.optionalKey(SeveritySchema)
59
+ });
60
+ const RuleAnswerSchema = Schema.Union([
61
+ BooleanAnswer,
62
+ ClassifyAnswer,
63
+ SeverityAnswer
64
+ ]);
65
+ // src/entities/decision/model/answer.ts
66
+ const DATA_FIRST_ARITY$6 = 2;
67
+ const YES = "yes";
68
+ const DEFAULT_MINIMUM = "warn";
69
+ const SEVERITY_CRITERIA = {
70
+ none: "No problem",
71
+ info: "Worth noting, but not a problem",
72
+ warn: "Likely a problem",
73
+ error: "Clearly a problem"
74
+ };
75
+ const SEVERITY_ORDER = Record.keys(SEVERITY_CRITERIA);
76
+ const BOOLEAN_ANSWER = { kind: "boolean" };
77
+ const decodeAnswer = Schema.decodeUnknownResult(RuleAnswerSchema);
78
+ const decodeRuleAnswer = (answer) => {
79
+ const decoded = decodeAnswer(answer);
80
+ if (Result.isSuccess(decoded)) return Result.succeed(decoded.success);
81
+ return Result.fail(decoded.failure.message);
82
+ };
83
+ const NoulAnswerSchema = Schema.Struct({
84
+ type: Schema.Literal("noul"),
85
+ noul: Probability
86
+ });
87
+ const ChoiceAnswerSchema = Schema.Struct({
88
+ type: Schema.Literal("choice"),
89
+ choice: Schema.String,
90
+ probabilities: Schema.optional(Schema.Record(Schema.String, Probability))
91
+ });
92
+ const AnswerSchema = Schema.Union([NoulAnswerSchema, ChoiceAnswerSchema]);
93
+ const decodeNoul = Schema.decodeOption(NoulAnswerSchema);
94
+ const decodeChoice = Schema.decodeOption(ChoiceAnswerSchema);
95
+ const isNoul = (answer) => answer.type === "noul";
96
+ const isChoice = (answer) => answer.type === "choice";
97
+ const noulOf = (answer) => Option.fromUndefinedOr(answer).pipe(Option.filter(isNoul), Option.flatMap(decodeNoul));
98
+ const choiceOf = (answer) => Option.fromUndefinedOr(answer).pipe(Option.filter(isChoice), Option.flatMap(decodeChoice));
99
+ const probabilityOfChoice = ({ choice, probabilities }) => Option.fromUndefinedOr(probabilities).pipe(Option.flatMap((byLabel) => Option.fromUndefinedOr(byLabel[choice])));
100
+ const questionFor = Function.dual(DATA_FIRST_ARITY$6, (answer, instructions) => {
101
+ switch (answer.kind) {
102
+ case "classify": return {
103
+ type: "choice",
104
+ instructions: `${instructions} Select the label that fits best.`,
105
+ criteria: answer.labels
106
+ };
107
+ case "severity": return {
108
+ type: "choice",
109
+ instructions: `${instructions} Rate how serious the problem is, and select none if there is no problem.`,
110
+ criteria: SEVERITY_CRITERIA
111
+ };
112
+ case "boolean": return {
113
+ type: "noul",
114
+ instructions
115
+ };
116
+ default: return {
117
+ type: "noul",
118
+ instructions
119
+ };
120
+ }
121
+ });
122
+ const choiceVerdictOf = (criteria, answer) => choiceOf(answer).pipe(Option.filter(({ choice }) => Record.has(criteria, choice)), Option.flatMap((chosen) => Option.map(probabilityOfChoice(chosen), (probability) => ({
123
+ answer: chosen.choice,
124
+ probability
125
+ }))));
126
+ const verdictOf = Function.dual(DATA_FIRST_ARITY$6, (question, answer) => {
127
+ if (question.type === "choice") return choiceVerdictOf(question.criteria, answer);
128
+ return noulOf(answer).pipe(Option.map(({ noul }) => ({
129
+ answer: YES,
130
+ probability: noul
131
+ })));
132
+ });
133
+ const severityMatches = ({ minimum = DEFAULT_MINIMUM }, label) => SEVERITY_ORDER.indexOf(label) >= SEVERITY_ORDER.indexOf(minimum);
134
+ const answerMatches = (answer, label) => {
135
+ switch (answer.kind) {
136
+ case "classify": return answer.report.includes(label);
137
+ case "severity": return severityMatches(answer, label);
138
+ case "boolean": return label === YES;
139
+ default: return false;
140
+ }
141
+ };
142
+ const isReported = Function.dual(DATA_FIRST_ARITY$6, (rule, verdict) => verdict.probability >= rule.cutoff && answerMatches(rule.answer, verdict.answer));
143
+ // src/entities/decision/model/location.ts
144
+ const DATA_FIRST_ARITY$5 = 2;
145
+ const DATA_FIRST_ARITY_3$3 = 3;
146
+ const CHOICE_OPTION_LIMIT = 254;
147
+ const FIRST_LINE$3 = 1;
148
+ const MINIMUM_WIDTH = 1;
149
+ const UNKNOWN_CHOICE = "unknown";
150
+ const sourceLines = (text) => String$1.split(text, /\r\n|[\n\r\u2028\u2029]/u);
151
+ const locates = (match) => Predicate.isNotUndefined(match.rule.location) && !match.truncated;
152
+ const EVERY_LINE = {
153
+ start: FIRST_LINE$3,
154
+ end: Number.POSITIVE_INFINITY
155
+ };
156
+ const isWithin = (line, within) => Number$1.between(line, {
157
+ minimum: within.start,
158
+ maximum: within.end
159
+ });
160
+ const rangeKey = ({ start, end }) => Boolean.match(start === end, {
161
+ onTrue: () => `L${String(start)}`,
162
+ onFalse: () => `L${String(start)}-L${String(end)}`
163
+ });
164
+ const rangeLabel = ({ start, end }) => Boolean.match(start === end, {
165
+ onTrue: () => `Line ${String(start)}`,
166
+ onFalse: () => `Lines ${String(start)} to ${String(end)}`
167
+ });
168
+ const rangeOf = (group) => ({
169
+ start: Array.headNonEmpty(group).line,
170
+ end: Array.lastNonEmpty(group).line
171
+ });
172
+ const numberedLines = (snippet) => pipe(sourceLines(snippet), Array.map((text, index) => ({
173
+ text,
174
+ line: Number$1.sum(index, FIRST_LINE$3)
175
+ })));
176
+ const locationCandidates = Function.dual(DATA_FIRST_ARITY$5, (snippet, within) => {
177
+ const lines = pipe(numberedLines(snippet), Array.filter(({ text, line }) => String$1.trim(text).length >= FIRST_LINE$3 && isWithin(line, within)));
178
+ const width = Math.max(MINIMUM_WIDTH, Math.ceil(lines.length / CHOICE_OPTION_LIMIT));
179
+ return Record.fromEntries(pipe(Array.chunksOf(lines, width), Array.map((group) => {
180
+ const range = rangeOf(group);
181
+ return [rangeKey(range), range];
182
+ })));
183
+ });
184
+ const locationQuestion = Function.dual(DATA_FIRST_ARITY_3$3, (match, ref, candidates) => ({
185
+ type: "choice",
186
+ instructions: `Consider only the numbered source in state.snippets.${ref}. If it violates this rule, select the line (or range containing that line) to annotate. Rule: ${match.rule.question} Location: ${match.rule.location.question} If multiple violations exist, select the earliest one. Select ${UNKNOWN_CHOICE} if no violation exists or its location is unclear.`,
187
+ criteria: {
188
+ ...Record.fromEntries(pipe(Record.toEntries(candidates), Array.map(([key, range]) => [key, rangeLabel(range)]))),
189
+ [UNKNOWN_CHOICE]: "No clear source location for this violation"
190
+ }
191
+ }));
192
+ const validChoice = Function.dual(DATA_FIRST_ARITY$5, (answer, criteria) => Option.exists(choiceOf(answer), (chosen) => Record.has(criteria, chosen.choice) && Option.isSome(probabilityOfChoice(chosen))));
193
+ const selectedLocation = Function.dual(DATA_FIRST_ARITY_3$3, (answer, candidates, cutoff) => choiceOf(answer).pipe(Option.filter((chosen) => Option.exists(probabilityOfChoice(chosen), (probability) => Number$1.isGreaterThanOrEqualTo(probability, cutoff))), Option.flatMap(({ choice }) => Option.fromUndefinedOr(candidates[choice]))));
194
+ const locationOfLine = Function.dual(DATA_FIRST_ARITY$5, (snippet, line) => {
195
+ const text = Option.getOrElse(Array.get(sourceLines(snippet), Number$1.decrement(line)), () => "");
196
+ return {
197
+ start: {
198
+ line,
199
+ column: Option.getOrElse(String$1.search(/\S/u)(text), () => Number$1.decrement(FIRST_LINE$3))
200
+ },
201
+ end: {
202
+ line,
203
+ column: String$1.trimEnd(text).length
204
+ }
205
+ };
206
+ });
207
+ // src/entities/decision/model/nodes.ts
208
+ const FIRST_LINE$2 = 1;
209
+ const FIRST_COLUMN = 0;
210
+ const TARGET_NODE_TYPES = {
211
+ function: [
212
+ "FunctionDeclaration",
213
+ "FunctionExpression",
214
+ "ArrowFunctionExpression"
215
+ ],
216
+ call: ["CallExpression"],
217
+ jsx: ["JSXElement"],
218
+ file: ["Program"]
219
+ };
220
+ const NAMED_PARENTS = {
221
+ VariableDeclarator: "init",
222
+ Property: "value",
223
+ MethodDefinition: "value",
224
+ PropertyDefinition: "value"
225
+ };
226
+ const NAMED_PARENT_TYPES = new Set(Record.keys(NAMED_PARENTS));
227
+ const isNamedParentType = (type) => NAMED_PARENT_TYPES.has(type);
228
+ const ANONYMOUS_FUNCTIONS = /* @__PURE__ */ new Set(["FunctionExpression", "ArrowFunctionExpression"]);
229
+ const holdsAsName = (parent, node) => {
230
+ if (!isNamedParentType(parent.type)) return false;
231
+ const field = NAMED_PARENTS[parent.type];
232
+ return ANONYMOUS_FUNCTIONS.has(node.type) && parent[field] === node;
233
+ };
234
+ const snippetNodeFor = (node) => Option.fromNullishOr(node.parent).pipe(Option.filter((parent) => holdsAsName(parent, node)), Option.getOrElse(() => node));
235
+ const headOf = (text, line, column) => {
236
+ const [first] = String$1.split(text, "\n");
237
+ return {
238
+ start: {
239
+ line,
240
+ column
241
+ },
242
+ end: {
243
+ line,
244
+ column: column + first.length
245
+ }
246
+ };
247
+ };
248
+ const REPORT_LOC = {
249
+ function: (node, text) => headOf(text, node.loc.start.line, node.loc.start.column),
250
+ call: (node) => node.loc,
251
+ jsx: (node) => Option.getOrElse(Option.fromNullishOr(node.openingElement), () => node).loc,
252
+ file: (_node, text) => headOf(text, FIRST_LINE$2, FIRST_COLUMN)
253
+ };
254
+ // src/entities/decision/model/context.ts
255
+ const DATA_FIRST_ARITY_3$2 = 3;
256
+ const DEFAULT_LINES = 5;
257
+ const FIRST_LINE$1 = 1;
258
+ const LAST = 1;
259
+ const END = 1;
260
+ const ENCLOSING_TYPES = {
261
+ function: [
262
+ "FunctionDeclaration",
263
+ "FunctionExpression",
264
+ "ArrowFunctionExpression"
265
+ ],
266
+ class: ["ClassDeclaration", "ClassExpression"],
267
+ block: [
268
+ "BlockStatement",
269
+ "StaticBlock",
270
+ "Program"
271
+ ]
272
+ };
273
+ const ancestorsOf = (node) => Array.unfold(Option.fromNullishOr(node.parent), (current) => current.pipe(Option.map((ancestor) => [ancestor, Option.fromNullishOr(ancestor.parent)])));
274
+ const enclosingText = (context, node, kind) => Array.findFirst(ancestorsOf(node), (ancestor) => ENCLOSING_TYPES[kind].includes(ancestor.type)).pipe(Option.match({
275
+ onNone: () => context.sourceCode.text,
276
+ onSome: (ancestor) => context.sourceCode.getText(ancestor)
277
+ }));
278
+ const linesAround = (context, node, { before = DEFAULT_LINES, after = DEFAULT_LINES }) => {
279
+ const lines = sourceLines(context.sourceCode.text);
280
+ const first = Math.max(FIRST_LINE$1, node.loc.start.line - before);
281
+ const last = Math.min(lines.length, node.loc.end.line + after);
282
+ return pipe(lines, Array.drop(first - FIRST_LINE$1), Array.take(last - first + FIRST_LINE$1), Array.map((text, index) => `L${String(first + index)}| ${text}`), Array.join("\n"));
283
+ };
284
+ const DECLARING_PARENTS = /* @__PURE__ */ new Set([
285
+ "VariableDeclaration",
286
+ "ExportNamedDeclaration",
287
+ "ExportDefaultDeclaration"
288
+ ]);
289
+ const declarationOf = (node) => Option.fromNullishOr(node.parent).pipe(Option.filter((parent) => DECLARING_PARENTS.has(parent.type)), Option.match({
290
+ onNone: () => node,
291
+ onSome: declarationOf
292
+ }));
293
+ const leadingOf = (text, comments, until) => Option.match(Array.last(comments), {
294
+ onNone: () => [],
295
+ onSome: (last) => {
296
+ if (String$1.isNonEmpty(String$1.trim(String$1.slice(last.end, until)(text)))) return [];
297
+ return [...leadingOf(text, Array.dropRight(comments, LAST), last.start), last];
298
+ }
299
+ });
300
+ const commentedTextOf = (context, node) => {
301
+ const { text } = context.sourceCode;
302
+ const named = snippetNodeFor(node);
303
+ const [start] = declarationOf(named).range;
304
+ const before = pipe(context.sourceCode.getAllComments(), Array.filter((comment) => comment.type !== "Shebang" && comment.end <= start));
305
+ return Array.match(leadingOf(text, before, start), {
306
+ onEmpty: () => Option.none(),
307
+ onNonEmpty: ([first]) => Option.some(String$1.slice(first.start, named.range[END])(text))
308
+ });
309
+ };
310
+ const isCommented = ({ context: wanted }) => Predicate.isNotUndefined(wanted) && wanted.scope === "comment";
311
+ const commentedSnippetOf = Function.dual(DATA_FIRST_ARITY_3$2, (context, node, rule) => Option.flatMap(Option.liftPredicate(rule, isCommented), () => commentedTextOf(context, node)));
312
+ const lacksComment = Function.dual(DATA_FIRST_ARITY_3$2, (context, node, rule) => isCommented(rule) && Option.isNone(commentedTextOf(context, node)));
313
+ const contextOf = Function.dual(DATA_FIRST_ARITY_3$2, (context, node, rule) => {
314
+ if (rule.scope === "lines") return Option.some(linesAround(context, node, rule));
315
+ if (rule.scope === "enclosing") return Option.some(enclosingText(context, node, rule.kind));
316
+ return Option.liftPredicate(context.sourceCode.text, () => rule.scope === "file");
317
+ });
318
+ // src/entities/decision/model/name.ts
319
+ const DATA_FIRST_ARITY_3$1 = 3;
320
+ const heldName = (node) => Option.flatMap(Option.fromNullishOr(node.parent), (parent) => Match.value(parent).pipe(Match.when({ type: "VariableDeclarator" }, (holder) => Option.liftPredicate(holder.id, () => holder.init === node)), Match.when({ type: Match.is("Property", "MethodDefinition", "PropertyDefinition") }, (holder) => Option.liftPredicate(holder.key, () => holder.value === node)), Match.orElse(() => Option.none())));
321
+ const nameNodeOf = (node) => Match.value(node).pipe(Match.when({ type: Match.is("FunctionDeclaration", "FunctionExpression") }, (fn) => Option.orElse(Option.fromNullishOr(fn.id), () => heldName(fn))), Match.when({ type: "ArrowFunctionExpression" }, heldName), Match.when({ type: Match.is("CallExpression", "NewExpression") }, (call) => Option.some(call.callee)), Match.when({ type: "JSXElement" }, (element) => Option.some(element.openingElement.name)), Match.orElse(() => Option.none()));
322
+ const nameOf = (node, context) => Option.getOrUndefined(Option.map(nameNodeOf(node), (name) => String$1.slice(name.start, name.end)(context.sourceCode.text)));
323
+ const isSelected = Function.dual(DATA_FIRST_ARITY_3$1, (context, node, { select }) => Option.match(Option.fromUndefinedOr(select), {
324
+ onNone: () => true,
325
+ onSome: (selects) => selects(node, {
326
+ name: nameOf(node, context),
327
+ context
328
+ })
329
+ }));
330
+ // src/entities/decision/model/options.ts
331
+ const DATA_FIRST_ARITY_3 = 3;
332
+ const DATA_FIRST_ARITY$4 = 2;
333
+ const PREFIX = "oxlint-plugin-decision";
334
+ const PROVIDER_SEPARATOR = "/";
335
+ const ONE_RULE = 1;
336
+ const DEFAULTS = {
337
+ ci: "fail",
338
+ timeoutMs: 1e4,
339
+ maxSnippetChars: 4e3,
340
+ model: "cloudflare/@cf/cloudflare/clef-flash",
341
+ env: {},
342
+ explain: false
343
+ };
344
+ const isSelector = (input) => Predicate.isFunction(input);
345
+ const RULE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
346
+ const ModelSpecSchema = Schema.Union([Schema.NonEmptyString, Schema.NonEmptyArray(Schema.NonEmptyString)]);
347
+ const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
348
+ const RuleId = Schema.NonEmptyString.check(Schema.isPattern(RULE_ID, { message: "id must be lowercase words joined by hyphens" }));
349
+ const OptionsSchema = Schema.Struct({
350
+ ci: Schema.optionalKey(CiBehaviorSchema),
351
+ timeoutMs: Schema.optionalKey(PositiveInt),
352
+ maxSnippetChars: Schema.optionalKey(PositiveInt),
353
+ model: Schema.optionalKey(ModelSpecSchema),
354
+ env: Schema.optionalKey(Schema.Record(Schema.NonEmptyString, Schema.NonEmptyString)),
355
+ explain: Schema.optionalKey(ExplainSettingSchema)
356
+ });
357
+ const RuleSchema = Schema.Struct({
358
+ id: RuleId,
359
+ target: TargetSchema,
360
+ question: Schema.NonEmptyString,
361
+ cutoff: Cutoff,
362
+ message: Schema.optionalKey(Schema.NonEmptyString),
363
+ select: Schema.optionalKey(Schema.declare(isSelector)),
364
+ location: Schema.optionalKey(Schema.Struct({
365
+ question: Schema.NonEmptyString,
366
+ cutoff: Cutoff
367
+ })),
368
+ model: Schema.optionalKey(ModelSpecSchema),
369
+ context: Schema.optionalKey(RuleContextSchema),
370
+ answer: Schema.optionalKey(Schema.Unknown)
371
+ });
372
+ const STRICT = { onExcessProperty: "error" };
373
+ const decodeOptions = Schema.decodeUnknownResult(OptionsSchema, STRICT);
374
+ const decodeRule = Schema.decodeUnknownResult(RuleSchema, STRICT);
375
+ const taggedError = Schema.TaggedError;
376
+ var OptionsError = class extends taggedError()("OptionsError", { message: Schema.String }) {};
377
+ const optionsError = (message) => OptionsError.make({ message: `${PREFIX}: ${message}` });
378
+ const modelIdsOf = (spec) => Array.dedupe(Array.ensure(spec));
379
+ const splitModelId = (id) => {
380
+ const [provider, ...rest] = String$1.split(id, PROVIDER_SEPARATOR);
381
+ const model = pipe(rest, Array.join(PROVIDER_SEPARATOR));
382
+ return Option.liftPredicate([provider, model], ([left, right]) => String$1.isNonEmpty(left) && String$1.isNonEmpty(right));
383
+ };
384
+ const acceptedModel = (ref) => {
385
+ const { models, name } = ref.provider;
386
+ if (Predicate.isNotUndefined(models) && !models.test(ref.model)) throw optionsError(`model "${ref.id}" is not a decision model that the "${name}" provider accepts`);
387
+ return ref;
388
+ };
389
+ const resolveModel = Function.dual(DATA_FIRST_ARITY$4, (id, providers) => acceptedModel(splitModelId(id).pipe(Option.flatMap(([name, model]) => Option.map(Option.fromUndefinedOr(providers[name]), (provider) => ({
390
+ id,
391
+ provider,
392
+ model
393
+ }))), Option.getOrThrowWith(() => optionsError(`model "${id}" must be "<provider>/<model>" with a provider from: ${pipe(Record.keys(providers), Array.join(", "))}`)))));
394
+ const duplicateIdOf = (rules) => Array.findFirst(Record.toEntries(Array.groupBy(rules, ({ id }) => id)), ([, same]) => same.length > ONE_RULE).pipe(Option.map(([id]) => id));
395
+ const answerOf = (rule) => {
396
+ if (Predicate.isUndefined(rule.answer)) return BOOLEAN_ANSWER;
397
+ return Result.getOrThrowWith(decodeRuleAnswer(rule.answer), (issue) => optionsError(`rule "${rule.id}" has an invalid answer: ${issue}`));
398
+ };
399
+ const checked = Function.dual(DATA_FIRST_ARITY_3, (decode, input, what) => Result.getOrThrowWith(decode(input), (issue) => optionsError(`invalid ${what}: ${issue.message}`)));
400
+ const checkRule = (rule) => {
401
+ checked(decodeRule, rule, `rule "${rule.id}"`);
402
+ if (Predicate.isNotUndefined(rule.location) && rule.target !== "file") throw optionsError("location is supported only for file rules");
403
+ answerOf(rule);
404
+ return rule;
405
+ };
406
+ const checkRules = (rules) => {
407
+ if (!Array.isReadonlyArrayNonEmpty(rules)) throw optionsError("rules must list at least one rule");
408
+ Option.map(duplicateIdOf(rules), (duplicate) => {
409
+ throw optionsError(`rule id "${duplicate}" is used more than once`);
410
+ });
411
+ return pipe(rules, Array.map((rule) => checkRule(rule)));
412
+ };
413
+ const resolveRule = (fallback, providers) => (rule) => ({
414
+ ...rule,
415
+ answer: answerOf(rule),
416
+ models: pipe(modelIdsOf(rule.model ?? fallback), Array.map((id) => resolveModel(id, providers)))
417
+ });
418
+ const settingsFrom = (settings) => {
419
+ if (Predicate.isUndefined(settings)) return {};
420
+ return checked(decodeOptions, settings, "settings");
421
+ };
422
+ const resolveOptions = Function.dual(DATA_FIRST_ARITY_3, ({ options, settings }, rules, providers) => {
423
+ const fromCode = checked(decodeOptions, options, "createDecisionPlugin options");
424
+ const { model, ...merged } = {
425
+ ...DEFAULTS,
426
+ ...fromCode,
427
+ ...settingsFrom(settings)
428
+ };
429
+ return {
430
+ ci: merged.ci,
431
+ timeoutMs: merged.timeoutMs,
432
+ maxSnippetChars: merged.maxSnippetChars,
433
+ env: merged.env,
434
+ explain: merged.explain,
435
+ rules: pipe(checkRules(rules), Array.map((rule) => resolveRule(model, providers)(rule)))
436
+ };
437
+ });
438
+ // src/entities/decision/model/request.ts
439
+ const DATA_FIRST_ARITY$3 = 2;
440
+ const FIRST_LINE = 1;
441
+ const LOCATION_SUFFIX = "_location";
442
+ const TRUNCATION_MARKER = "/* ...truncated */";
443
+ const refAt = (index) => `s${String(index)}`;
444
+ const locationRefOf = (ref) => `${ref}${LOCATION_SUFFIX}`;
445
+ const snippetRefOf = (questionId) => Boolean.match(String$1.endsWith(LOCATION_SUFFIX)(questionId), {
446
+ onTrue: () => String$1.slice(Number$1.decrement(FIRST_LINE), -9)(questionId),
447
+ onFalse: () => questionId
448
+ });
449
+ const truncateSnippet = Function.dual(DATA_FIRST_ARITY$3, (text, maxChars) => Boolean.match(text.length <= maxChars, {
450
+ onTrue: () => text,
451
+ onFalse: () => `${String$1.slice(Number$1.decrement(FIRST_LINE), maxChars)(text)}${TRUNCATION_MARKER}`
452
+ }));
453
+ const numbered = (snippet) => pipe(numberedLines(snippet), Array.map(({ text, line }) => `L${String(line)}| ${text}`), Array.join("\n"));
454
+ const contextNote = (match, ref) => {
455
+ if (Predicate.isUndefined(match.context)) return "";
456
+ return ` state.contexts.${ref} shows the source around it; use it only to understand the snippet.`;
457
+ };
458
+ const mainQuestionFor = (match, ref) => [ref, questionFor(match.rule.answer, `Consider only snippet "${ref}" in state.snippets.${contextNote(match, ref)} ${match.rule.question}`)];
459
+ const questionsFor = (match, ref) => {
460
+ if (!locates(match)) return [mainQuestionFor(match, ref)];
461
+ return [mainQuestionFor(match, ref), [locationRefOf(ref), locationQuestion(match, ref, locationCandidates(match.snippet, EVERY_LINE))]];
462
+ };
463
+ const snippetFor = (match) => {
464
+ if (locates(match)) return numbered(match.snippet);
465
+ return match.snippet;
466
+ };
467
+ const contextsOf = (matches) => {
468
+ const contexts = pipe(matches, Array.flatMap((match, index) => Option.toArray(Option.map(Option.fromUndefinedOr(match.context), (text) => [refAt(index), text]))));
469
+ if (Array.isReadonlyArrayEmpty(contexts)) return {};
470
+ return { contexts: Record.fromEntries(contexts) };
471
+ };
472
+ const buildRequest = Function.dual(DATA_FIRST_ARITY$3, (model, matches) => ({
473
+ model,
474
+ state: {
475
+ snippets: Record.fromEntries(pipe(matches, Array.map((match, index) => [refAt(index), snippetFor(match)]))),
476
+ ...contextsOf(matches)
477
+ },
478
+ questions: Record.fromEntries(pipe(matches, Array.flatMap((match, index) => questionsFor(match, refAt(index)))))
479
+ }));
480
+ const choiceQuestionsOf$1 = (request) => pipe(Record.toEntries(request.questions), Array.flatMap(([id, question]) => {
481
+ if (question.type === "choice") return [[id, question.criteria]];
482
+ return [];
483
+ }));
484
+ const mainQuestionsOf = (request) => pipe(Record.toEntries(request.questions), Array.filter(([id]) => !String$1.endsWith(LOCATION_SUFFIX)(id)));
485
+ const resultOf = (answers, [ref, question]) => [ref, Option.getOrThrowWith(verdictOf(question, answers[ref]), () => /* @__PURE__ */ new Error(`response has no valid answer for "${ref}"`))];
486
+ const parseVerdicts = Function.dual(DATA_FIRST_ARITY$3, (response, request) => {
487
+ const { model, answers } = Option.getOrThrowWith(Option.liftPredicate(response, ({ model: served }) => String$1.isNonEmpty(served)), () => /* @__PURE__ */ new Error("response has no model id"));
488
+ return {
489
+ model,
490
+ results: Record.fromEntries(pipe(mainQuestionsOf(request), Array.map((entry) => resultOf(answers, entry)))),
491
+ answers,
492
+ complete: pipe(choiceQuestionsOf$1(request), Array.every(([id, criteria]) => validChoice(answers[id], criteria)))
493
+ };
494
+ });
495
+ // src/entities/decision/model/runtime.ts
496
+ const DATA_FIRST_ARITY$2 = 2;
497
+ const encodeJson = Schema.encodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
498
+ const toJson = (value) => Option.getOrElse(encodeJson(value), () => String(value));
499
+ const nowMs = () => DateTime.toEpochMillis(DateTime.nowUnsafe());
500
+ const runOrElse = Function.dual(DATA_FIRST_ARITY$2, (effect, fallback) => Exit.match(Effect.runSyncExit(effect), {
501
+ onSuccess: (value) => value,
502
+ onFailure: (cause) => fallback(Cause.squash(cause))
503
+ }));
504
+ const envOf = (name) => runOrElse(Config.option(Config.NonEmptyString(name)), () => Option.none()).pipe(Option.map((value) => String$1.trim(value)), Option.filter(String$1.isNonEmpty));
505
+ const envNameOf = Function.dual(DATA_FIRST_ARITY$2, (env, name) => env[name] ?? name);
506
+ const failsInCi = (options) => options.ci === "fail" && Option.isSome(envOf("CI"));
507
+ const warned = /* @__PURE__ */ new Set();
508
+ const warnOnce = Function.dual(DATA_FIRST_ARITY$2, (reason, message) => {
509
+ if (warned.has(reason)) return;
510
+ warned.add(reason);
511
+ Effect.runFork(Console.warn(`${PREFIX}: ${message}`));
512
+ });
513
+ const messageOf = (error) => {
514
+ if (error instanceof Error) return error.message;
515
+ return String(error);
516
+ };
517
+ const captured = Function.dual(DATA_FIRST_ARITY$2, (match, name) => match.pipe(Option.flatMap((found) => Option.fromNullishOr(found.groups)), Option.flatMap((groups) => Option.fromNullishOr(groups[name]))));
518
+ // src/entities/decision/model/wire-choice.ts
519
+ const DATA_FIRST_ARITY$1 = 2;
520
+ const RESPAN_MODELS = ["respan/"];
521
+ const OPTION_SEPARATOR = "__";
522
+ const CERTAIN = 1;
523
+ const NO_SEVERITY = "none";
524
+ const isRespan = (model) => pipe(RESPAN_MODELS, Array.some((prefix) => String$1.startsWith(prefix)(model)));
525
+ const optionIdOf = Function.dual(DATA_FIRST_ARITY$1, (id, label) => `${id}${OPTION_SEPARATOR}${label}`);
526
+ const isSeverityScale = (criteria) => pipe(Record.keys(criteria), Array.join(",")) === pipe(SEVERITY_ORDER, Array.join(","));
527
+ const levelsAboveNone = (criteria) => pipe(Record.toEntries(criteria), Array.filter(([label]) => label !== NO_SEVERITY));
528
+ const byYes = Order.mapInput(Order.Number, ({ yes }) => yes);
529
+ const scoreOf = (answers, id, label) => Option.map(noulOf(answers[optionIdOf(id, label)]), ({ noul }) => ({
530
+ label,
531
+ yes: noul
532
+ }));
533
+ const scoresOf = (answers, id, labels) => pipe(labels, Array.map((label) => scoreOf(answers, id, label)), Option.all, Option.flatMap((scores) => Option.liftPredicate(scores, Array.isArrayNonEmpty)));
534
+ const probabilitiesOf = (scores) => Record.fromEntries(pipe(scores, Array.map(({ label, yes }) => [label, yes])));
535
+ const choiceAnswer = (choice, probabilities) => ({
536
+ type: "choice",
537
+ choice,
538
+ probabilities
539
+ });
540
+ const bestLabel = (scores) => choiceAnswer(Array.max(scores, byYes).label, probabilitiesOf(scores));
541
+ const atLeast = (scores) => pipe(scores, Array.map(({ label }, index) => ({
542
+ label,
543
+ yes: Math.max(...pipe(scores.slice(index), Array.map(({ yes }) => yes)))
544
+ })));
545
+ const severityLevel = (scores) => {
546
+ const cumulative = atLeast(scores);
547
+ const probabilities = {
548
+ [NO_SEVERITY]: Number$1.subtract(CERTAIN, Array.headNonEmpty(cumulative).yes),
549
+ ...probabilitiesOf(cumulative)
550
+ };
551
+ const reached = pipe(cumulative, Array.findLast(({ yes }) => yes >= CONFIDENT));
552
+ return choiceAnswer(Option.match(reached, {
553
+ onNone: () => NO_SEVERITY,
554
+ onSome: ({ label }) => label
555
+ }), probabilities);
556
+ };
557
+ const labelsAsked = (criteria) => {
558
+ if (isSeverityScale(criteria)) return pipe(levelsAboveNone(criteria), Array.map(([label]) => label));
559
+ return Record.keys(criteria);
560
+ };
561
+ const choiceFromYesNo = (answers, [id, { criteria }]) => {
562
+ const collapse = Boolean.match(isSeverityScale(criteria), {
563
+ onTrue: () => severityLevel,
564
+ onFalse: () => bestLabel
565
+ });
566
+ return scoresOf(answers, id, labelsAsked(criteria)).pipe(Option.map((scores) => [id, collapse(scores)]), Option.toArray);
567
+ };
568
+ const choiceQuestionsOf = (request) => pipe(Record.toEntries(request.questions), Array.flatMap(([id, question]) => {
569
+ if (question.type === "choice") return [[id, question]];
570
+ return [];
571
+ }));
572
+ const collapseChoices = Function.dual(DATA_FIRST_ARITY$1, (request, answers) => ({
573
+ ...answers,
574
+ ...Record.fromEntries(pipe(choiceQuestionsOf(request), Array.flatMap((entry) => choiceFromYesNo(answers, entry))))
575
+ }));
576
+ const withChoices = Function.dual(DATA_FIRST_ARITY$1, (request, answers) => {
577
+ if (!isRespan(request.model)) return answers;
578
+ return collapseChoices(request, answers);
579
+ });
580
+ // src/entities/decision/model/wire.ts
581
+ const DATA_FIRST_ARITY = 2;
582
+ const MAX_QUESTIONS = 64;
583
+ const sectionsOf = (name, entries) => pipe(Record.toEntries(entries), Array.map(([ref, text]) => `state.${name}.${ref}:\n${text}`));
584
+ const stateAsText = ({ snippets, contexts = {} }) => pipe([...sectionsOf("snippets", snippets), ...sectionsOf("contexts", contexts)], Array.join("\n\n"));
585
+ const only = (entries, ref) => Option.match(Option.fromUndefinedOr(entries[ref]), {
586
+ onNone: () => ({}),
587
+ onSome: (text) => ({ [ref]: text })
588
+ });
589
+ const stateOf = ({ snippets, contexts }, ref) => {
590
+ if (Predicate.isUndefined(contexts)) return { snippets: only(snippets, ref) };
591
+ return {
592
+ snippets: only(snippets, ref),
593
+ contexts: only(contexts, ref)
594
+ };
595
+ };
596
+ const optionText = (label, description) => Option.match(Option.fromNullishOr(description), {
597
+ onNone: () => `"${label}"`,
598
+ onSome: (text) => `"${label}" (${text})`
599
+ });
600
+ const labelQuestion = (instructions, label, description) => ({
601
+ type: "noul",
602
+ instructions: `${instructions} Does the label ${optionText(label, description)} fit?`
603
+ });
604
+ const levelQuestion = (instructions, label, description) => ({
605
+ type: "noul",
606
+ instructions: `${instructions} Is it at least as serious as ${optionText(label, description)}?`
607
+ });
608
+ const yesNoQuestionsOf = (id, { instructions, criteria }) => {
609
+ if (isSeverityScale(criteria)) return pipe(levelsAboveNone(criteria), Array.map(([label, description]) => [optionIdOf(id, label), levelQuestion(instructions, label, description)]));
610
+ return pipe(Record.toEntries(criteria), Array.map(([label, description]) => [optionIdOf(id, label), labelQuestion(instructions, label, description)]));
611
+ };
612
+ const asYesNo = ([id, question]) => {
613
+ if (question.type === "choice") return yesNoQuestionsOf(id, question);
614
+ return [[id, question]];
615
+ };
616
+ const perSnippet = (wiresOf) => (request) => {
617
+ const bySnippet = Array.groupBy(Record.toEntries(request.questions), ([id]) => snippetRefOf(id));
618
+ const wires = pipe(Record.toEntries(bySnippet), Array.flatMap(([ref, questions]) => wiresOf(ref, questions)));
619
+ if (Array.isReadonlyArrayNonEmpty(wires)) return wires;
620
+ return [request];
621
+ };
622
+ const yesNoRequestsFor = (request) => perSnippet((ref, questions) => [{
623
+ model: request.model,
624
+ state: stateAsText(stateOf(request.state, ref)),
625
+ questions: Record.fromEntries(pipe(questions, Array.flatMap((entry) => asYesNo(entry))))
626
+ }])(request);
627
+ const snippetRequestsFor = (request) => perSnippet((ref, questions) => pipe(Array.chunksOf(questions, MAX_QUESTIONS), Array.map((chunk) => ({
628
+ model: request.model,
629
+ state: stateOf(request.state, ref),
630
+ questions: Record.fromEntries(chunk)
631
+ }))))(request);
632
+ const wireRequestsFor = (request) => {
633
+ if (isRespan(request.model)) return yesNoRequestsFor(request);
634
+ return [request];
635
+ };
636
+ const merging = (collapse) => (request, responses) => ({
637
+ ...Array.headNonEmpty(responses),
638
+ answers: collapse(request, pipe(responses, Array.flatMap(({ answers }) => Record.toEntries(answers)), Record.fromEntries))
639
+ });
640
+ const mergeResponses = Function.dual(DATA_FIRST_ARITY, merging(withChoices));
641
+ export { contextOf as A, selectedLocation as B, checked as C, resolveOptions as D, resolveModel as E, EVERY_LINE as F, isReported as H, locates as I, locationCandidates as L, REPORT_LOC as M, TARGET_NODE_TYPES as N, isSelected as O, snippetNodeFor as P, locationOfLine as R, checkRules as S, optionsError as T, AnswerSchema as V, refAt as _, captured as a, PREFIX as b, failsInCi as c, runOrElse as d, toJson as f, parseVerdicts as g, locationRefOf as h, yesNoRequestsFor as i, lacksComment as j, commentedSnippetOf as k, messageOf as l, buildRequest as m, snippetRequestsFor as n, envNameOf as o, warnOnce as p, wireRequestsFor as r, envOf as s, mergeResponses as t, nowMs as u, truncateSnippet as v, modelIdsOf as w, STRICT as x, ModelSpecSchema as y, locationQuestion as z };
642
+
643
+ //# sourceMappingURL=decision-BtTZ52be.mjs.map