@r_masseater/oxlint-plugin-decision 0.0.1 → 0.0.3

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.
package/dist/index.mjs CHANGED
@@ -1,6 +1,10 @@
1
- import { C as TARGET_NODE_TYPES, E as isReported, S as SCHEMA, T as snippetNodeFor, _ as warnOnce, a as locationQuestion, b as PREFIX, c as refAt, d as sourceLines, f as truncateSnippet, g as runOrElse, h as messageOf, i as locationOfLine, l as selectedLocation, m as failsInCi, n as locates, o as locationRefOf, p as envOf, r as locationCandidates, s as parseVerdicts, t as buildRequest, v as DEFAULTS, w as resolveOptions, x as REPORT_LOC, y as OptionsError } from "./request-Dg8fyV-u.mjs";
2
- import { Array, Effect, Option } from "effect";
1
+ import { A as resolveOptions, C as REPORT_LOC, D as checked, E as checkRules, N as isReported, O as modelIdsOf, S as PREFIX, T as TARGET_NODE_TYPES, _ as messageOf, a as locationCandidates, b as ModelSpecSchema, c as locationRefOf, d as selectedLocation, f as sourceLines, g as failsInCi, h as envOf, i as locates, j as snippetNodeFor, k as resolveModel, l as parseVerdicts, m as envNameOf, n as wireRequestsFor, o as locationOfLine, p as truncateSnippet, r as buildRequest, s as locationQuestion, u as refAt, v as runOrElse, w as STRICT, x as OptionsError, y as warnOnce } from "./wire-BGb5iQa9.mjs";
2
+ import { Array, Boolean, Console, Effect, Function, Match, Option, Predicate, Schema, String as String$1, pipe } from "effect";
3
3
  import { createSyncFn } from "synckit";
4
+ //#region src/define.ts
5
+ const defineDecisionRule = (rule) => rule;
6
+ const defineProvider = (provider) => provider;
7
+ //#endregion
4
8
  //#region src/openrouter.ts
5
9
  const BACKSTOP_MS = 6e4;
6
10
  const SYNCKIT_TIMEOUT = "Internal error: Atomics.wait() failed: timed-out";
@@ -17,21 +21,55 @@ const reasonOf = (error) => {
17
21
  if (message === SYNCKIT_TIMEOUT) return "timeout";
18
22
  return `network: ${message}`;
19
23
  };
24
+ const ask = (inputs) => runOrElse(Effect.sync(() => workerCall()(inputs)), (cause) => pipe(inputs, Array.map(() => ({
25
+ ok: false,
26
+ reason: reasonOf(cause)
27
+ }))));
20
28
  const openRouter = {
21
29
  name: "openrouter",
22
30
  requiredEnv: ["OPENROUTER_API_KEY"],
23
- decide: (input) => runOrElse(Effect.try({
24
- try: () => workerCall()(input),
25
- catch: reasonOf
26
- }), (cause) => ({
27
- ok: false,
28
- reason: reasonOf(cause)
29
- }))
31
+ decide: (input) => Array.headNonEmpty(ask([input])),
32
+ decideAll: (inputs) => Array.match(inputs, {
33
+ onEmpty: () => [],
34
+ onNonEmpty: (some) => ask(some)
35
+ })
36
+ };
37
+ //#endregion
38
+ //#region src/override.ts
39
+ const RuleOverrideSchema = Schema.Struct({ model: Schema.optionalKey(ModelSpecSchema) });
40
+ const RULE_OPTIONS_SCHEMA = [{
41
+ type: "object",
42
+ additionalProperties: false,
43
+ properties: { model: { oneOf: [{
44
+ type: "string",
45
+ minLength: 1
46
+ }, {
47
+ type: "array",
48
+ minItems: 1,
49
+ items: {
50
+ type: "string",
51
+ minLength: 1
52
+ }
53
+ }] } }
54
+ }];
55
+ const decodeOverride = Schema.decodeUnknownResult(RuleOverrideSchema, STRICT);
56
+ const overrideRule = (rule, raw, providers) => {
57
+ if (Predicate.isUndefined(raw)) return rule;
58
+ const { model } = checked(decodeOverride, raw, `options for rule "${rule.id}"`);
59
+ return {
60
+ ...rule,
61
+ models: Option.match(Option.fromUndefinedOr(model), {
62
+ onNone: () => rule.models,
63
+ onSome: (spec) => modelIdsOf(spec).map((id) => resolveModel(id, providers))
64
+ })
65
+ };
30
66
  };
31
67
  //#endregion
32
68
  //#region src/context.ts
33
69
  const DEFAULT_LINES = 5;
34
70
  const FIRST_LINE = 1;
71
+ const LAST = 1;
72
+ const END = 1;
35
73
  const ENCLOSING_TYPES = {
36
74
  function: [
37
75
  "FunctionDeclaration",
@@ -56,29 +94,220 @@ const linesAround = (context, node, { before = DEFAULT_LINES, after = DEFAULT_LI
56
94
  const last = Math.min(lines.length, node.loc.end.line + after);
57
95
  return lines.slice(first - FIRST_LINE, last).map((text, index) => `L${String(first + index)}| ${text}`).join("\n");
58
96
  };
97
+ const DECLARING_PARENTS = /* @__PURE__ */ new Set([
98
+ "VariableDeclaration",
99
+ "ExportNamedDeclaration",
100
+ "ExportDefaultDeclaration"
101
+ ]);
102
+ const declarationOf = (node) => Option.fromNullishOr(node.parent).pipe(Option.filter((parent) => DECLARING_PARENTS.has(parent.type)), Option.match({
103
+ onNone: () => node,
104
+ onSome: declarationOf
105
+ }));
106
+ const leadingOf = (text, comments, until) => Option.match(Array.last(comments), {
107
+ onNone: () => [],
108
+ onSome: (last) => {
109
+ if (String$1.isNonEmpty(text.slice(last.end, until).trim())) return [];
110
+ return [...leadingOf(text, Array.dropRight(comments, LAST), last.start), last];
111
+ }
112
+ });
113
+ const commentedTextOf = (context, node) => {
114
+ const { text } = context.sourceCode;
115
+ const named = snippetNodeFor(node);
116
+ const [start] = declarationOf(named).range;
117
+ const before = context.sourceCode.getAllComments().filter((comment) => comment.type !== "Shebang" && comment.end <= start);
118
+ return Array.match(leadingOf(text, before, start), {
119
+ onEmpty: () => Option.none(),
120
+ onNonEmpty: ([first]) => Option.some(text.slice(first.start, named.range[END]))
121
+ });
122
+ };
123
+ const isCommented = ({ context: wanted }) => Predicate.isNotUndefined(wanted) && wanted.scope === "comment";
124
+ const commentedSnippetOf = (context, node, rule) => Option.flatMap(Option.liftPredicate(rule, isCommented), () => commentedTextOf(context, node));
125
+ const lacksComment = (context, node, rule) => isCommented(rule) && Option.isNone(commentedTextOf(context, node));
59
126
  const contextOf = (context, node, rule) => {
60
127
  if (rule.scope === "lines") return Option.some(linesAround(context, node, rule));
61
128
  if (rule.scope === "enclosing") return Option.some(enclosingText(context, node, rule.kind));
62
129
  return Option.liftPredicate(context.sourceCode.text, () => rule.scope === "file");
63
130
  };
64
131
  //#endregion
132
+ //#region src/name.ts
133
+ const none = () => Option.none();
134
+ 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(none)));
135
+ 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(none));
136
+ const nameOf = (node, context) => Option.getOrUndefined(Option.map(nameNodeOf(node), (name) => context.sourceCode.text.slice(name.start, name.end)));
137
+ const isSelected = (context, node, { select }) => Option.match(Option.fromUndefinedOr(select), {
138
+ onNone: () => true,
139
+ onSome: (selects) => selects(node, {
140
+ name: nameOf(node, context),
141
+ context
142
+ })
143
+ });
144
+ //#endregion
145
+ //#region src/explain.ts
146
+ const EXPLAIN_ENV = "OXLINT_DECISION_EXPLAIN";
147
+ const OFF_VALUES = /* @__PURE__ */ new Set([
148
+ "0",
149
+ "false",
150
+ "off",
151
+ "no"
152
+ ]);
153
+ const STATE_HEAD_CHARS = 60;
154
+ const DECIMALS$1 = 2;
155
+ const OPTION_SEPARATOR = "__";
156
+ const FIRST = 1;
157
+ const START = 0;
158
+ const COLUMN_BASE = 1;
159
+ const SEPARATOR = /^[/\\]/u;
160
+ const relativeTo = (root, filename) => Boolean.match(String$1.isNonEmpty(root) && filename.startsWith(root) && SEPARATOR.test(filename.slice(root.length)), {
161
+ onTrue: () => filename.slice(root.length + FIRST),
162
+ onFalse: () => filename
163
+ });
164
+ const fromSetting = (setting) => Match.value(setting).pipe(Match.when("json", () => "json"), Match.when(true, () => "text"), Match.when("text", () => "text"), Match.orElse(() => "off"));
165
+ const fromEnv = (value) => Match.value(value.toLowerCase()).pipe(Match.when("json", () => "json"), Match.when((lower) => OFF_VALUES.has(lower), () => "off"), Match.orElse(() => "text"));
166
+ const explainModeOf = (setting) => Option.match(envOf(EXPLAIN_ENV), {
167
+ onNone: () => fromSetting(setting),
168
+ onSome: fromEnv
169
+ });
170
+ const probabilitiesIn = (answer) => {
171
+ if (answer.type === "noul") return Option.some({ yes: answer.noul });
172
+ if (answer.type === "UNKNOWN") return Option.none();
173
+ return Option.fromUndefinedOr(answer.probabilities);
174
+ };
175
+ const probabilitiesOf = (answer) => Option.fromUndefinedOr(answer).pipe(Option.flatMap(probabilitiesIn), Option.getOrElse(() => ({})));
176
+ const asksAbout = (ref, id) => id.split(OPTION_SEPARATOR, FIRST).includes(ref);
177
+ const sentFor = (sent, ref) => sent.flatMap((wire) => Object.entries(wire.questions).filter(([id]) => asksAbout(ref, id)));
178
+ const stateTextOf = (sent, ref, snippet) => Array.findFirst(sent, (wire) => Object.keys(wire.questions).some((id) => asksAbout(ref, id))).pipe(Option.map(({ state }) => state), Option.filter(Predicate.isString), Option.getOrElse(() => snippet));
179
+ const summaryOf = (text) => ({
180
+ chars: text.length,
181
+ head: text.replaceAll(/\s+/gu, " ").trim().slice(START, STATE_HEAD_CHARS)
182
+ });
183
+ const baseOf = ({ pass, sent }, match, { ref, loc }) => {
184
+ const questions = sentFor(sent, ref);
185
+ return (answers) => ({
186
+ file: relativeTo(pass.cwd, pass.filename),
187
+ line: loc.start.line,
188
+ column: loc.start.column + COLUMN_BASE,
189
+ rule: match.rule.id,
190
+ model: pass.model,
191
+ cutoff: match.rule.cutoff,
192
+ durationMs: pass.durationMs,
193
+ state: summaryOf(stateTextOf(sent, ref, match.snippet)),
194
+ questions: questions.map(([id, question]) => ({
195
+ id,
196
+ question: question.instructions,
197
+ probabilities: probabilitiesOf(answers[id])
198
+ }))
199
+ });
200
+ };
201
+ const fixed = (value) => value.toFixed(DECIMALS$1);
202
+ const cachedText = (cached) => Option.match(Option.fromUndefinedOr(cached), {
203
+ onNone: () => "unknown",
204
+ onSome: (hit) => Boolean.match(hit, {
205
+ onTrue: () => "yes",
206
+ onFalse: () => "no"
207
+ })
208
+ });
209
+ const probabilitiesText = (probabilities) => Option.match(Array.match(Object.entries(probabilities), {
210
+ onEmpty: () => Option.none(),
211
+ onNonEmpty: (entries) => Option.some(entries.map(([label, value]) => `${label}=${fixed(value)}`).join(" "))
212
+ }), {
213
+ onNone: () => "(no answer)",
214
+ onSome: (text) => text
215
+ });
216
+ const verdictText = (explanation) => {
217
+ if (Predicate.isNotUndefined(explanation.error)) return `error: ${explanation.error}`;
218
+ const outcome = Boolean.match(explanation.reported, {
219
+ onTrue: () => "reported",
220
+ onFalse: () => "not reported"
221
+ });
222
+ const cutoff = `cutoff ${fixed(explanation.cutoff)}`;
223
+ return Option.match(Option.fromUndefinedOr(explanation.verdict), {
224
+ onNone: () => `no verdict, ${cutoff}, ${outcome}`,
225
+ onSome: ({ answer, probability }) => `${answer} ${fixed(probability)}, ${cutoff}, ${outcome}`
226
+ });
227
+ };
228
+ const servedText = (served) => Option.match(Option.fromUndefinedOr(served), {
229
+ onNone: () => "",
230
+ onSome: (id) => ` (served ${id})`
231
+ });
232
+ const asText = (explanation) => [
233
+ `${PREFIX} explain: ${explanation.file}:${String(explanation.line)}:${String(explanation.column)} [${explanation.rule}] ${explanation.model}${servedText(explanation.served)} cached=${cachedText(explanation.cached)} ${String(explanation.durationMs)}ms`,
234
+ ` state: ${String(explanation.state.chars)} chars ${JSON.stringify(explanation.state.head)}`,
235
+ ...explanation.questions.map(({ id, question, probabilities }) => ` ${id}: ${probabilitiesText(probabilities)}\n ${question}`),
236
+ ` verdict: ${verdictText(explanation)}`
237
+ ].join("\n");
238
+ const printerFor = (mode) => (explanation) => {
239
+ const line = Boolean.match(mode === "json", {
240
+ onTrue: () => JSON.stringify(explanation),
241
+ onFalse: () => asText(explanation)
242
+ });
243
+ Effect.runFork(Console.error(line));
244
+ };
245
+ const explaining = (pass, mode) => {
246
+ const sent = wireRequestsFor(pass.request);
247
+ const print = printerFor(mode);
248
+ return {
249
+ outcome: (match, at, { served, answers, cached, verdict, reported }) => {
250
+ print({
251
+ ...baseOf({
252
+ pass,
253
+ sent
254
+ }, match, at)(answers),
255
+ served,
256
+ ...Option.match(Option.fromUndefinedOr(cached), {
257
+ onNone: () => ({}),
258
+ onSome: (hit) => ({ cached: hit })
259
+ }),
260
+ ...Option.match(verdict, {
261
+ onNone: () => ({}),
262
+ onSome: (found) => ({ verdict: found })
263
+ }),
264
+ reported
265
+ });
266
+ },
267
+ failure: (matches, reason) => {
268
+ for (const [index, match] of matches.entries()) {
269
+ const at = {
270
+ ref: refAt(index),
271
+ loc: match.loc
272
+ };
273
+ print({
274
+ ...baseOf({
275
+ pass,
276
+ sent
277
+ }, match, at)({}),
278
+ reported: false,
279
+ error: reason
280
+ });
281
+ }
282
+ }
283
+ };
284
+ };
285
+ const SILENT = {
286
+ outcome: Function.constVoid,
287
+ failure: Function.constVoid
288
+ };
289
+ const explainerFor = (pass) => Match.value(explainModeOf(pass.setting)).pipe(Match.when("off", () => SILENT), Match.orElse((mode) => explaining(pass, mode)));
290
+ //#endregion
65
291
  //#region src/locate.ts
66
292
  const MINIMUM_TIMEOUT_MS = 1;
67
293
  const remainingMs = (deadline) => Math.max(MINIMUM_TIMEOUT_MS, deadline - Date.now());
68
- const fetchVerdicts = (asking, request) => {
69
- const result = asking.model.provider.decide({
70
- request,
71
- timeoutMs: remainingMs(asking.deadline)
72
- });
294
+ const verdictsOf = (result, request) => {
73
295
  if (!result.ok) return result;
74
296
  return runOrElse(Effect.sync(() => ({
75
297
  ok: true,
76
- verdicts: parseVerdicts(result.response, request)
298
+ verdicts: parseVerdicts(result.response, request),
299
+ cached: result.cached
77
300
  })), (cause) => ({
78
301
  ok: false,
79
302
  reason: messageOf(cause)
80
303
  }));
81
304
  };
305
+ const inputOf = (asking, request) => ({
306
+ request,
307
+ timeoutMs: remainingMs(asking.deadline),
308
+ env: asking.env
309
+ });
310
+ const fetchVerdicts = (asking, request) => verdictsOf(asking.model.provider.decide(inputOf(asking, request)), request);
82
311
  const isRange = (location) => Option.exists(location, ({ start, end }) => start !== end);
83
312
  const refineOnce = ({ asking, match, ref, state }, within) => {
84
313
  const questionId = locationRefOf(ref);
@@ -129,22 +358,22 @@ const locateMatch = (asking, match, { ref, verdicts, request }) => {
129
358
  //#region src/report.ts
130
359
  const DECIMALS = 2;
131
360
  const degrade = (pass, reason) => {
132
- if (failsInCi(pass.options)) throw new OptionsError(`${reason} (${pass.context.filename})`);
133
- warnOnce(reason, `${reason} (${pass.context.filename})`);
361
+ if (failsInCi(pass.options)) throw new OptionsError(`${reason} (${pass.filename})`);
362
+ warnOnce(reason, `${reason} (${pass.filename})`);
134
363
  };
135
364
  const reportFailure = (pass, failure) => {
136
365
  if (failsInCi(pass.options)) {
137
- pass.context.report({
366
+ pass.contextOf(failure.match).report({
138
367
  loc: failure.loc,
139
368
  messageId: "unlocated",
140
369
  data: {
141
- id: failure.id,
370
+ id: failure.match.rule.id,
142
371
  reason: failure.reason
143
372
  }
144
373
  });
145
374
  return;
146
375
  }
147
- warnOnce(failure.reason, `${failure.reason} (${pass.context.filename})`);
376
+ warnOnce(failure.reason, `${failure.reason} (${pass.filename})`);
148
377
  };
149
378
  const locate = (answered, match, { ref, failed }) => {
150
379
  if (failed) return {
@@ -156,62 +385,140 @@ const locate = (answered, match, { ref, failed }) => {
156
385
  ref
157
386
  });
158
387
  };
388
+ const outcomeOf = (answered, match, ref) => {
389
+ const verdict = Option.fromUndefinedOr(answered.verdicts.results[ref]);
390
+ return {
391
+ served: `${answered.asking.model.provider.name}/${answered.verdicts.model}`,
392
+ cached: answered.cached,
393
+ answers: answered.verdicts.answers,
394
+ verdict,
395
+ reported: Option.exists(verdict, (found) => isReported(match.rule, found))
396
+ };
397
+ };
398
+ const reportMatch = (pass, answered, { match, ref, failed }) => {
399
+ const outcome = outcomeOf(answered, match, ref);
400
+ const { verdict } = outcome;
401
+ if (!outcome.reported || Option.isNone(verdict)) {
402
+ answered.explainer.outcome(match, {
403
+ ref,
404
+ loc: match.loc
405
+ }, outcome);
406
+ return Option.none();
407
+ }
408
+ const located = locate(answered, match, {
409
+ ref,
410
+ failed
411
+ });
412
+ const at = {
413
+ ref,
414
+ loc: located.loc
415
+ };
416
+ answered.explainer.outcome(match, at, outcome);
417
+ pass.contextOf(match).report({
418
+ loc: located.loc,
419
+ messageId: "yes",
420
+ data: {
421
+ id: match.rule.id,
422
+ model: `${pass.model.provider.name}/${answered.verdicts.model}`,
423
+ answer: verdict.value.answer,
424
+ score: verdict.value.probability.toFixed(DECIMALS),
425
+ cutoff: match.rule.cutoff.toFixed(DECIMALS),
426
+ question: match.rule.message ?? match.rule.question
427
+ }
428
+ });
429
+ return located.failure;
430
+ };
159
431
  const reportMatches = (pass, answered) => {
160
432
  let failure = Option.none();
161
433
  for (const [index, match] of pass.matches.entries()) {
162
- const ref = refAt(index);
163
- const verdict = Option.fromUndefinedOr(answered.verdicts.results[ref]);
164
- if (Option.isSome(verdict) && isReported(match.rule, verdict.value)) {
165
- const located = locate(answered, match, {
166
- ref,
167
- failed: Option.isSome(failure)
168
- });
169
- failure = Option.orElse(failure, () => located.failure.pipe(Option.map((reason) => ({
170
- id: match.rule.id,
171
- loc: match.loc,
172
- reason
173
- }))));
174
- pass.context.report({
175
- loc: located.loc,
176
- messageId: "yes",
177
- data: {
178
- id: match.rule.id,
179
- model: `${pass.model.provider.name}/${answered.verdicts.model}`,
180
- answer: verdict.value.answer,
181
- score: verdict.value.probability.toFixed(DECIMALS),
182
- cutoff: match.rule.cutoff.toFixed(DECIMALS),
183
- question: match.rule.question
184
- }
185
- });
186
- }
434
+ const located = reportMatch(pass, answered, {
435
+ match,
436
+ ref: refAt(index),
437
+ failed: Option.isSome(failure)
438
+ });
439
+ failure = Option.orElse(failure, () => located.pipe(Option.map((reason) => ({
440
+ match,
441
+ loc: match.loc,
442
+ reason
443
+ }))));
187
444
  }
188
445
  return failure;
189
446
  };
190
- const reportModel = (pass) => {
191
- const asking = {
447
+ const explainPassOf = (pass, { request, durationMs }) => ({
448
+ setting: pass.options.explain,
449
+ cwd: Option.match(Array.head(pass.matches), {
450
+ onNone: () => "",
451
+ onSome: (match) => pass.contextOf(match).cwd
452
+ }),
453
+ filename: pass.filename,
454
+ model: pass.model.id,
455
+ request,
456
+ durationMs
457
+ });
458
+ const explainerOf = (pass, timed) => explainerFor(explainPassOf(pass, timed));
459
+ const prepare = (pass) => ({
460
+ pass,
461
+ asking: {
192
462
  model: pass.model,
193
- deadline: pass.deadline
194
- };
195
- const request = buildRequest(pass.model.model, pass.matches);
196
- const result = fetchVerdicts(asking, request);
463
+ deadline: pass.deadline,
464
+ env: pass.options.env
465
+ },
466
+ request: buildRequest(pass.model.model, pass.matches)
467
+ });
468
+ const reportAnswer = ({ pass, asking, request }, { decided, durationMs }) => {
469
+ const explainer = explainerOf(pass, {
470
+ request,
471
+ durationMs
472
+ });
473
+ const result = verdictsOf(decided, request);
197
474
  if (!result.ok) {
475
+ explainer.failure(pass.matches, result.reason);
198
476
  degrade(pass, result.reason);
199
477
  return;
200
478
  }
201
- const failure = reportMatches(pass, {
479
+ Option.map(reportMatches(pass, {
480
+ ...result,
202
481
  asking,
203
- verdicts: result.verdicts,
204
- request
482
+ request,
483
+ explainer
484
+ }), (failure) => {
485
+ reportFailure(pass, failure);
486
+ });
487
+ };
488
+ const decideWith = (provider, prepared) => {
489
+ const inputs = prepared.map(({ asking, request }) => inputOf(asking, request));
490
+ return Option.match(Option.fromUndefinedOr(provider.decideAll), {
491
+ onNone: () => inputs.map((input) => provider.decide(input)),
492
+ onSome: (decideAll) => decideAll(inputs)
493
+ });
494
+ };
495
+ const reportProvider = (prepared) => {
496
+ const { provider } = Array.headNonEmpty(prepared).pass.model;
497
+ const started = performance.now();
498
+ const results = decideWith(provider, prepared);
499
+ const durationMs = Math.round(performance.now() - started);
500
+ const answers = Boolean.match(results.length === prepared.length, {
501
+ onTrue: () => results,
502
+ onFalse: () => prepared.map(() => ({
503
+ ok: false,
504
+ reason: `provider ${provider.name} returned ${String(results.length)} results for ${String(prepared.length)} requests`
505
+ }))
506
+ });
507
+ for (const [one, decided] of Array.zip(prepared, answers)) reportAnswer(one, {
508
+ decided,
509
+ durationMs
205
510
  });
206
- if (Option.isSome(failure)) reportFailure(pass, failure.value);
511
+ };
512
+ const reportModels = (passes) => {
513
+ const byProvider = Array.groupBy(passes.map((pass) => prepare(pass)), ({ pass }) => pass.model.provider.name);
514
+ for (const prepared of Object.values(byProvider)) reportProvider(prepared);
207
515
  };
208
516
  //#endregion
209
517
  //#region src/visitor.ts
210
- const NODE_TYPES = Object.values(TARGET_NODE_TYPES).flat();
211
518
  const raisedMissing = /* @__PURE__ */ new Set();
212
- const missingEnvOf = (provider) => provider.requiredEnv.filter((name) => Option.isNone(envOf(name)));
519
+ const missingEnvOf = (options, provider) => provider.requiredEnv.map((name) => envNameOf(options.env, name)).filter((name) => Option.isNone(envOf(name)));
213
520
  const isAvailable = (options, { provider }) => {
214
- const missingNames = missingEnvOf(provider);
521
+ const missingNames = missingEnvOf(options, provider);
215
522
  if (Array.isReadonlyArrayEmpty(missingNames)) return true;
216
523
  const missing = missingNames.join(", ");
217
524
  if (!failsInCi(options)) warnOnce(`missing:${provider.name}`, `${missing} is not set, skipping ${provider.name} models`);
@@ -221,8 +528,7 @@ const isAvailable = (options, { provider }) => {
221
528
  }
222
529
  return false;
223
530
  };
224
- const availableModels = (options) => [...new Map(options.rules.flatMap((rule) => rule.models).map((model) => [model.id, model])).values()].filter((model) => isAvailable(options, model));
225
- const rulesFor = (options, type) => options.rules.filter((rule) => TARGET_NODE_TYPES[rule.target].includes(type));
531
+ const availableModels = (batch) => [...new Map(Object.values(batch.rules).flatMap((rule) => rule.models).map((model) => [model.id, model])).values()].filter((model) => isAvailable(batch.options, model));
226
532
  const snippetOf = (context, node) => {
227
533
  if (node.type === "Program") return context.sourceCode.text;
228
534
  return context.sourceCode.getText(node);
@@ -233,7 +539,7 @@ const namedSnippetOf = (context, node) => {
233
539
  return context.sourceCode.getText(named);
234
540
  };
235
541
  const matchOf = (context, node, { rule, options }) => {
236
- const text = namedSnippetOf(context, node);
542
+ const text = Option.getOrElse(commentedSnippetOf(context, node, rule), () => namedSnippetOf(context, node));
237
543
  const surrounding = contextOf(context, node, rule.context ?? { scope: "node" });
238
544
  return {
239
545
  ...Option.match(surrounding, {
@@ -246,99 +552,161 @@ const matchOf = (context, node, { rule, options }) => {
246
552
  truncated: text.length > options.maxSnippetChars
247
553
  };
248
554
  };
249
- const finish = (context, collected) => {
250
- if (Array.isReadonlyArrayNonEmpty(collected.dropped)) {
251
- const dropped = collected.dropped.length;
252
- warnOnce(`capped:${context.filename}`, `${String(collected.matches.length + dropped)} matches exceeded maxMatchesPerFile=${String(collected.options.maxMatchesPerFile)}, ${String(dropped)} not checked (${context.filename})`);
253
- }
254
- const deadline = Date.now() + collected.options.timeoutMs;
255
- for (const model of collected.models) {
256
- const matches = collected.matches.filter(({ rule }) => rule.models.some(({ id }) => id === model.id));
257
- if (Array.isReadonlyArrayNonEmpty(matches)) reportModel({
258
- context,
259
- options: collected.options,
260
- model,
261
- matches,
262
- deadline
555
+ const contextOfRule = (batch, id) => Option.getOrThrow(Option.fromUndefinedOr(batch.contexts[id]));
556
+ const finish = (batch) => {
557
+ const [first] = Object.values(batch.contexts);
558
+ if (Predicate.isUndefined(first)) return;
559
+ const deadline = Date.now() + batch.options.timeoutMs;
560
+ const passes = availableModels(batch).flatMap((model) => {
561
+ const matches = batch.matches.filter(({ rule }) => rule.models.some(({ id }) => id === model.id));
562
+ return Array.match(matches, {
563
+ onEmpty: () => [],
564
+ onNonEmpty: (some) => [{
565
+ contextOf: (match) => contextOfRule(batch, match.rule.id),
566
+ filename: first.filename,
567
+ options: batch.options,
568
+ model,
569
+ matches: some,
570
+ deadline
571
+ }]
263
572
  });
264
- }
265
- };
266
- const startFile = (options) => {
267
- const models = availableModels(options);
268
- if (Array.isReadonlyArrayEmpty(models)) return Option.none();
269
- return Option.some({
270
- options,
271
- models,
272
- matches: [],
273
- dropped: []
274
573
  });
574
+ reportModels(passes);
275
575
  };
276
- const visitorFor = (optionsFor) => (context) => {
576
+ const ruleIn = (batch, id) => Option.getOrThrow(Array.findFirst(batch.options.rules, (rule) => rule.id === id));
577
+ const sharedFile = (optionsFor, ruleFor) => {
578
+ let current = Option.none();
579
+ const start = (context) => {
580
+ const batch = {
581
+ options: optionsFor(context.settings),
582
+ contexts: {},
583
+ rules: {},
584
+ matches: [],
585
+ exiting: false,
586
+ exits: 0
587
+ };
588
+ current = Option.some(batch);
589
+ return batch;
590
+ };
591
+ return {
592
+ join: (context, id) => {
593
+ const batch = Option.match(current, {
594
+ onNone: () => start(context),
595
+ onSome: (open) => {
596
+ if (open.exiting) return start(context);
597
+ return open;
598
+ }
599
+ });
600
+ const [options] = context.options;
601
+ const rule = ruleFor(ruleIn(batch, id), options);
602
+ batch.contexts[id] = context;
603
+ batch.rules[id] = rule;
604
+ return {
605
+ batch,
606
+ rule
607
+ };
608
+ },
609
+ leave: () => {
610
+ if (Option.isNone(current)) return;
611
+ const batch = current.value;
612
+ batch.exits += 1;
613
+ if (batch.exits >= Object.keys(batch.contexts).length) current = Option.none();
614
+ if (!batch.exiting) {
615
+ batch.exiting = true;
616
+ finish(batch);
617
+ }
618
+ }
619
+ };
620
+ };
621
+ const isSkipped = (context, node, rule) => !isSelected(context, node, rule) || lacksComment(context, node, rule);
622
+ const visitorFor = (shared, { id, target }) => (context) => {
277
623
  let file = Option.none();
278
- const collect = (type, node) => {
624
+ const collect = (node) => {
279
625
  if (Option.isNone(file)) return;
280
- const state = file.value;
281
- for (const rule of rulesFor(state.options, type)) if (state.matches.length >= state.options.maxMatchesPerFile) state.dropped.push(rule.id);
282
- else state.matches.push(matchOf(context, node, {
626
+ const { batch, rule } = file.value;
627
+ if (isSkipped(context, node, rule)) return;
628
+ batch.matches.push(matchOf(context, node, {
283
629
  rule,
284
- options: state.options
630
+ options: batch.options
285
631
  }));
286
632
  };
633
+ const nodeTypes = TARGET_NODE_TYPES[target];
287
634
  return {
288
- ...Object.fromEntries(NODE_TYPES.map((type) => [type, (node) => {
289
- collect(type, node);
635
+ ...Object.fromEntries(nodeTypes.map((type) => [type, (node) => {
636
+ collect(node);
290
637
  }])),
291
638
  Program: (node) => {
292
- const raw = Option.getOrUndefined(Array.head(context.options));
293
- file = startFile(optionsFor(raw));
294
- collect("Program", node);
639
+ file = Option.some(shared.join(context, id));
640
+ if (target === "file") collect(node);
295
641
  },
296
642
  "Program:exit": () => {
297
- const done = file;
298
643
  file = Option.none();
299
- if (Option.isSome(done)) finish(context, done.value);
644
+ shared.leave();
300
645
  }
301
646
  };
302
647
  };
303
648
  //#endregion
304
649
  //#region src/plugin.ts
305
- const META = {
650
+ const DEFAULT_NAME = "decision";
651
+ const metaOf = (rule) => ({
306
652
  type: "problem",
307
- docs: { description: "Ask decision models a plain-English question about matched code and report when the answer the rule cares about clears its cutoff." },
308
- schema: [SCHEMA],
309
- defaultOptions: [DEFAULTS],
653
+ docs: { description: rule.question },
654
+ schema: RULE_OPTIONS_SCHEMA,
310
655
  messages: {
311
656
  yes: "[{{id}}] {{model}} answered {{answer}} ({{score}} >= {{cutoff}}): {{question}}",
312
657
  unlocated: `${PREFIX}: {{reason}} while refining the location of [{{id}}]; the finding is reported at the file level`
313
658
  }
659
+ });
660
+ const SETUP_ONLY = /* @__PURE__ */ new Set([
661
+ "name",
662
+ "rules",
663
+ "providers"
664
+ ]);
665
+ const optionsOf = (setup) => Object.fromEntries(Object.entries(setup).filter(([key]) => !SETUP_ONLY.has(key)));
666
+ const memoized = (resolve) => {
667
+ const resolved = /* @__PURE__ */ new Map();
668
+ return (settings) => {
669
+ const key = JSON.stringify([settings]);
670
+ const cached = resolved.get(key);
671
+ if (Predicate.isNotUndefined(cached)) return cached;
672
+ const fresh = resolve(settings);
673
+ resolved.set(key, fresh);
674
+ return fresh;
675
+ };
314
676
  };
315
- const isOptions = (raw) => typeof raw === "object" && raw !== null;
316
- const createDecisionPlugin = (setup = {}) => {
317
- const providers = Object.fromEntries([openRouter, ...setup.providers ?? []].map((provider) => [provider.name, provider]));
677
+ const memoizedRules = (providers) => {
318
678
  const resolved = /* @__PURE__ */ new WeakMap();
319
- const resolve = (options) => resolveOptions(options, setup.rules ?? [], providers);
320
- const optionsFor = (raw) => {
321
- if (!isOptions(raw)) return resolve({});
322
- return Option.getOrElse(Option.fromUndefinedOr(resolved.get(raw)), () => {
323
- const options = resolve(raw);
324
- resolved.set(raw, options);
325
- return options;
326
- });
679
+ return (rule, options) => {
680
+ const known = resolved.get(rule) ?? /* @__PURE__ */ new Map();
681
+ resolved.set(rule, known);
682
+ const key = JSON.stringify([options]);
683
+ const cached = known.get(key);
684
+ if (Predicate.isNotUndefined(cached)) return cached;
685
+ const fresh = overrideRule(rule, options, providers);
686
+ known.set(key, fresh);
687
+ return fresh;
327
688
  };
689
+ };
690
+ const createDecisionPlugin = (setup) => {
691
+ const name = setup.name ?? DEFAULT_NAME;
692
+ const providers = Object.fromEntries([openRouter, ...setup.providers ?? []].map((provider) => [provider.name, provider]));
693
+ const rules = checkRules(setup.rules);
694
+ const options = optionsOf(setup);
695
+ const resolve = memoized((settings) => resolveOptions({
696
+ options,
697
+ settings
698
+ }, rules, providers));
699
+ resolve({});
700
+ const shared = sharedFile((settings) => resolve(settings[name]), memoizedRules(providers));
328
701
  return {
329
- meta: { name: setup.name ?? "decision" },
330
- rules: { ask: {
331
- meta: META,
332
- createOnce: visitorFor(optionsFor)
333
- } }
702
+ meta: { name },
703
+ rules: Object.fromEntries(rules.map((rule) => [rule.id, {
704
+ meta: metaOf(rule),
705
+ createOnce: visitorFor(shared, rule)
706
+ }]))
334
707
  };
335
708
  };
336
709
  //#endregion
337
- //#region src/define.ts
338
- const defineDecisionRule = (rule) => rule;
339
- const defineProvider = (provider) => provider;
340
- //#endregion
341
- //#region src/index.ts
342
- const plugin = createDecisionPlugin();
343
- //#endregion
344
- export { createDecisionPlugin, plugin as default, defineDecisionRule, defineProvider, openRouter };
710
+ export { createDecisionPlugin, defineDecisionRule, defineProvider, openRouter };
711
+
712
+ //# sourceMappingURL=index.mjs.map