pi-permission-classifier 0.5.2 → 0.6.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.
package/src/reviewer.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * The auto-classifier reviewer: the `Authorizer` chain link this package
3
- * registers as `"classifier"`.
2
+ * The LLM judge: a chat model reads each ask and reports allow, deny, or
3
+ * defer. It runs inside the permission-judge link when the mode includes it.
4
4
  *
5
5
  * The decision runs top to bottom, deferring at the first miss so the cheap
6
6
  * gates short-circuit before any model call:
@@ -16,13 +16,16 @@
16
16
  * 4. the judge model and its auth resolve (else defer, recorded),
17
17
  * 5. the guidance seam selects the operator and trusted-project guidance
18
18
  * files for this ask (a throw defers, recorded — no model call),
19
- * 6. the model reviews the ask facts plus guidance and its verdict is
20
- * returned uncapped.
19
+ * 6. the user intent seam gives the user's own messages, or none,
20
+ * 7. the model reviews the ask facts plus guidance and, with intent, the
21
+ * user's messages.
21
22
  *
22
- * Every failure path defers — more prompting, never less (ADR 0007
23
- * invariant). Each reviewed ask writes exactly one `classifier.decision`
24
- * review entry; raw model replies and the cheap short-circuits go to the
25
- * debug log.
23
+ * Once a config is loaded, every outcome from step 3 on goes through the
24
+ * verdict policy, which applies the link's `verdicts` and `onError`
25
+ * settings. A failure never allows: it defers, or denies with a fixed reason
26
+ * under `onError` deny. Each reviewed ask writes exactly one
27
+ * `classifier.decision` review entry tagged `judge: "llm"`; raw model
28
+ * replies and the cheap short-circuits go to the debug log.
26
29
  */
27
30
 
28
31
  import type { Model } from "@earendil-works/pi-ai";
@@ -38,7 +41,14 @@ import type { ClassifierConfig } from "./config-schema";
38
41
  import { extractFullCommandContext, type FullCommandContext } from "./context";
39
42
  import type { GuidanceSelection } from "./guidance";
40
43
  import type { HealthOutcome } from "./health";
41
- import { type CompleteFn, reviewAsk } from "./model-review";
44
+ import { type CompleteFn, type ReviewOutcome, reviewAsk } from "./model-review";
45
+ import type { UserIntent } from "./user-intent";
46
+ import {
47
+ applyVerdictPolicy,
48
+ type FailureKind,
49
+ type LinkOutcome,
50
+ type VerdictPolicy,
51
+ } from "./verdict-policy";
42
52
 
43
53
  /**
44
54
  * Surface families the engine caps to defer; the classifier never even asks.
@@ -50,16 +60,23 @@ import { type CompleteFn, reviewAsk } from "./model-review";
50
60
  const EXCLUDED_SURFACE_FAMILIES = ["path", "external_directory"] as const;
51
61
 
52
62
  /** Whether `surface` is the bare name or a directional member of an excluded family. */
53
- function isExcludedSurface(surface: string): boolean {
63
+ export function isExcludedSurface(surface: string): boolean {
54
64
  return EXCLUDED_SURFACE_FAMILIES.some(
55
65
  (family) => surface === family || surface.startsWith(`${family}_`),
56
66
  );
57
67
  }
58
68
 
59
69
  /** Review-log event: one positive decision record per reviewed ask. */
60
- const DECISION_EVENT = "classifier.decision";
70
+ export const DECISION_EVENT = "classifier.decision";
71
+ /** The judge tag every decision entry of this reviewer carries. */
72
+ const JUDGE_TAG = "llm";
73
+ /**
74
+ * The recorded reason when `allow-defer` turns a model deny into defer: the
75
+ * judge worked, the setting withheld the deny.
76
+ */
77
+ export const DENY_CAPPED_REASON = "deny-capped";
61
78
  /** Debug-log event: a cheap short-circuit before the model stage. */
62
- const SHORT_CIRCUIT_EVENT = "classifier.short_circuit";
79
+ export const SHORT_CIRCUIT_EVENT = "classifier.short_circuit";
63
80
  /** Debug-log event: the raw model reply, gated behind `debugLog`. */
64
81
  const MODEL_REPLY_EVENT = "classifier.model_reply";
65
82
 
@@ -72,6 +89,9 @@ type PreModelDeferReason =
72
89
  | "context-over-budget"
73
90
  | "guidance-load-failed";
74
91
 
92
+ /** The policy when no config can be read: the schema defaults. */
93
+ const DEFAULT_POLICY: VerdictPolicy = { verdicts: "allow-deny-defer", onError: "defer" };
94
+
75
95
  /** Model-call outcomes that count against the circuit breaker. */
76
96
  const BREAKER_FAILURE_REASONS = new Set(["timeout", "call-failed"]);
77
97
 
@@ -115,6 +135,12 @@ export interface ClassifierReviewerDeps {
115
135
  * Absent means no guidance. A throw defers the ask (guidance-load-failed).
116
136
  */
117
137
  getGuidance?: () => GuidanceSelection;
138
+ /**
139
+ * User intent seam: called once per judged ask right before the model
140
+ * call, with whether the ask was forwarded. Absent, undefined or a throw
141
+ * means no user block.
142
+ */
143
+ getUserIntent?: (forwarded: boolean) => UserIntent | undefined;
118
144
  /**
119
145
  * Outcome seam: called once per `classifier.decision` entry with the
120
146
  * verdict and defer reason, after the entry is logged. Never called for
@@ -146,7 +172,7 @@ function report(deps: ClassifierReviewerDeps, outcome: HealthOutcome): void {
146
172
  export function createClassifierReviewer(
147
173
  deps: ClassifierReviewerDeps,
148
174
  ): Authorizer["authorize"] {
149
- const breaker = deps.breaker ?? new CircuitBreaker();
175
+ const breaker = deps.breaker ?? new CircuitBreaker("llm");
150
176
 
151
177
  return async (details, _query, log) => {
152
178
  // What the guidance stage selected, so the backstop entry below can say
@@ -157,17 +183,20 @@ export function createClassifierReviewer(
157
183
  } catch {
158
184
  // The unconditional backstop: whatever threw — an injected seam
159
185
  // rejecting instead of returning ok:false, a malformed details bag,
160
- // even the log itself — the ask defers (more prompting, never less).
186
+ // even the log itself — is an internal-error failure under the
187
+ // link's onError, and never an allow.
188
+ const verdict = backstopVerdict(deps);
161
189
  try {
162
190
  const context = extractFullCommandContext(details.payload);
163
191
  log.review(DECISION_EVENT, {
192
+ judge: JUDGE_TAG,
164
193
  requestId: details.requestId,
165
194
  surface: gateSurfaceOf(details) ?? null,
166
195
  value: details.payload?.request?.value ?? null,
167
196
  modelCalled: false,
168
197
  modelId: null,
169
198
  latencyMs: null,
170
- verdict: "defer",
199
+ verdict: verdict.kind,
171
200
  deferReason: "internal-error",
172
201
  ...contextFields(false, context),
173
202
  ...guidanceFields(trail.guidance),
@@ -176,11 +205,33 @@ export function createClassifierReviewer(
176
205
  // The log failed too; there is nothing left to record on.
177
206
  }
178
207
  report(deps, { verdict: "defer", deferReason: "internal-error" });
179
- return { kind: "defer" };
208
+ return verdict;
180
209
  }
181
210
  };
182
211
  }
183
212
 
213
+ /**
214
+ * The backstop verdict: internal-error under the configured policy, or the
215
+ * defaults when even reading the config throws. Never an allow.
216
+ */
217
+ function backstopVerdict(deps: ClassifierReviewerDeps): AuthorizerVerdict {
218
+ let policy = DEFAULT_POLICY;
219
+ try {
220
+ const config = deps.getConfig();
221
+ if (config) {
222
+ policy = policyOf(config);
223
+ }
224
+ } catch {
225
+ // Keep the defaults.
226
+ }
227
+ return applyVerdictPolicy({ kind: "failure", failure: "internal-error" }, policy);
228
+ }
229
+
230
+ /** The classifier link's verdict policy from its config. */
231
+ function policyOf(config: ClassifierConfig): VerdictPolicy {
232
+ return { verdicts: config.verdicts, onError: config.onError };
233
+ }
234
+
184
235
  async function decide(
185
236
  deps: ClassifierReviewerDeps,
186
237
  breaker: CircuitBreaker,
@@ -195,7 +246,7 @@ async function decide(
195
246
 
196
247
  const config = deps.getConfig();
197
248
  if (!config) {
198
- return deferWith(deps, log, {
249
+ return recordPreModel(deps, log, undefined, {
199
250
  requestId,
200
251
  surface: surface ?? null,
201
252
  value,
@@ -205,8 +256,11 @@ async function decide(
205
256
  });
206
257
  }
207
258
 
259
+ const policy = policyOf(config);
260
+
208
261
  if (surface === undefined) {
209
262
  log.debug(SHORT_CIRCUIT_EVENT, {
263
+ judge: JUDGE_TAG,
210
264
  requestId,
211
265
  reason: "undeterminable-surface",
212
266
  });
@@ -214,6 +268,7 @@ async function decide(
214
268
  }
215
269
  if (isExcludedSurface(surface)) {
216
270
  log.debug(SHORT_CIRCUIT_EVENT, {
271
+ judge: JUDGE_TAG,
217
272
  requestId,
218
273
  surface,
219
274
  reason: "excluded-surface",
@@ -221,11 +276,11 @@ async function decide(
221
276
  return { kind: "defer" };
222
277
  }
223
278
  // The budget gate: an over-budget full command is never rendered,
224
- // not even truncated — the ask defers to the human with the measurements on
225
- // record. Decided before the breaker and model stages: it is a property of
226
- // the ask and the config alone.
279
+ // not even truncated. The ask is uncertain under the policy, with the
280
+ // measurements on record. Decided before the breaker and model stages: it
281
+ // is a property of the ask and the config alone.
227
282
  if (context !== null && context.bytes > config.contextBudgetBytes) {
228
- return deferWith(deps, log, {
283
+ return recordPreModel(deps, log, policy, {
229
284
  requestId,
230
285
  surface,
231
286
  value,
@@ -236,7 +291,7 @@ async function decide(
236
291
  }
237
292
 
238
293
  if (breaker.isOpen()) {
239
- return deferWith(deps, log, {
294
+ return recordPreModel(deps, log, policy, {
240
295
  requestId,
241
296
  surface,
242
297
  value,
@@ -252,7 +307,7 @@ async function decide(
252
307
  ? registry?.find(config.provider, config.model)
253
308
  : deps.getSessionModel();
254
309
  if (!registry || !model) {
255
- return deferWith(deps, log, {
310
+ return recordPreModel(deps, log, policy, {
256
311
  requestId,
257
312
  surface,
258
313
  value,
@@ -268,7 +323,7 @@ async function decide(
268
323
 
269
324
  const auth = await registry.getApiKeyAndHeaders(model);
270
325
  if (!auth.ok) {
271
- return deferWith(deps, log, {
326
+ return recordPreModel(deps, log, policy, {
272
327
  requestId,
273
328
  surface,
274
329
  value,
@@ -287,7 +342,7 @@ async function decide(
287
342
  guidance = deps.getGuidance?.() ?? EMPTY_GUIDANCE;
288
343
  trail.guidance = guidance;
289
344
  } catch {
290
- return deferWith(deps, log, {
345
+ return recordPreModel(deps, log, policy, {
291
346
  requestId,
292
347
  surface,
293
348
  value,
@@ -297,6 +352,7 @@ async function decide(
297
352
  });
298
353
  }
299
354
 
355
+ const userIntent = userIntentFor(deps.getUserIntent, details);
300
356
  const outcome = await reviewAsk({
301
357
  details,
302
358
  config,
@@ -306,6 +362,7 @@ async function decide(
306
362
  headers: auth.headers,
307
363
  context,
308
364
  guidance: guidance.included,
365
+ ...(userIntent === undefined ? {} : { userIntent }),
309
366
  });
310
367
  if (
311
368
  outcome.deferReason !== undefined &&
@@ -325,41 +382,84 @@ async function decide(
325
382
  // One reason for both the decision entry and the health seam, so the two
326
383
  // can never disagree. Set on every defer model-review produces; the
327
384
  // fallback only guards the type.
328
- const deferReason =
385
+ const modelDeferReason =
329
386
  outcome.verdict.kind === "defer"
330
387
  ? (outcome.deferReason ?? "unrecognized-verdict")
331
388
  : null;
389
+ const verdict = applyVerdictPolicy(linkOutcomeOf(outcome), policy);
390
+ const deferReason =
391
+ modelDeferReason ??
392
+ (outcome.verdict.kind === "deny" && verdict.kind === "defer"
393
+ ? DENY_CAPPED_REASON
394
+ : null);
332
395
  log.review(DECISION_EVENT, {
396
+ judge: JUDGE_TAG,
333
397
  requestId,
334
398
  surface,
335
399
  value,
336
400
  modelCalled: true,
337
401
  modelId,
338
402
  latencyMs: outcome.latencyMs,
339
- verdict: outcome.verdict.kind,
403
+ verdict: verdict.kind,
340
404
  deferReason,
341
405
  ...contextFields(context !== null, context),
342
406
  ...guidanceFields(guidance),
343
407
  });
408
+ // Health folds in what the judge did, not what the policy made of it, so
409
+ // a failure counts under onError deny too.
344
410
  report(
345
411
  deps,
346
- outcome.verdict.kind === "defer"
347
- ? { verdict: "defer", deferReason: deferReason ?? "unrecognized-verdict" }
348
- : { verdict: outcome.verdict.kind },
412
+ modelDeferReason !== null
413
+ ? { verdict: "defer", deferReason: modelDeferReason }
414
+ : { verdict: outcome.verdict.kind as "allow" | "deny" },
349
415
  );
350
- // Returned uncapped: the engine envelope, not this link, owns any
351
- // downgrade.
352
- return outcome.verdict;
416
+ return verdict;
353
417
  }
354
418
 
355
419
  /**
356
- * Record a pre-model defer as a positive `classifier.decision` entry and
357
- * return the defer verdict — so a resolution failure leaves evidence on
358
- * record, not a silent absence.
420
+ * The user intent for an ask through a judge's seam, or undefined. An ask
421
+ * whose requester facts are missing counts as forwarded, and a throwing seam
422
+ * gives no intent.
359
423
  */
360
- function deferWith(
424
+ export function userIntentFor(
425
+ getUserIntent: ((forwarded: boolean) => UserIntent | undefined) | undefined,
426
+ details: PromptPermissionDetails,
427
+ ): UserIntent | undefined {
428
+ try {
429
+ return getUserIntent?.(details.payload?.request?.requester?.forwarded !== false);
430
+ } catch {
431
+ return undefined;
432
+ }
433
+ }
434
+
435
+ /**
436
+ * Reduce a model review to a link outcome. A timeout or failed call is a
437
+ * failure; every other defer (the model's own, a reply with no tool call,
438
+ * an unknown verdict) is uncertain.
439
+ */
440
+ function linkOutcomeOf(outcome: ReviewOutcome): LinkOutcome {
441
+ switch (outcome.verdict.kind) {
442
+ case "allow":
443
+ return { kind: "allow" };
444
+ case "deny":
445
+ return { kind: "deny", reason: outcome.verdict.reason ?? "" };
446
+ case "defer":
447
+ return outcome.deferReason === "timeout" || outcome.deferReason === "call-failed"
448
+ ? { kind: "failure", failure: outcome.deferReason }
449
+ : { kind: "uncertain" };
450
+ }
451
+ }
452
+
453
+ /**
454
+ * Record a pre-model outcome as a positive `classifier.decision` entry and
455
+ * return its verdict under the policy, so a resolution failure leaves
456
+ * evidence on record, not a silent absence. With no policy (no config) the
457
+ * ask defers.
458
+ */
459
+ function recordPreModel(
361
460
  deps: ClassifierReviewerDeps,
362
461
  log: AuthorizerLog,
462
+ policy: VerdictPolicy | undefined,
363
463
  entry: {
364
464
  requestId: string;
365
465
  surface: string | null;
@@ -369,20 +469,34 @@ function deferWith(
369
469
  context: FullCommandContext | null;
370
470
  },
371
471
  ): AuthorizerVerdict {
472
+ const verdict: AuthorizerVerdict =
473
+ policy === undefined || entry.deferReason === "no-config"
474
+ ? { kind: "defer" }
475
+ : applyVerdictPolicy(preModelOutcome(entry.deferReason), policy);
372
476
  log.review(DECISION_EVENT, {
477
+ judge: JUDGE_TAG,
373
478
  requestId: entry.requestId,
374
479
  surface: entry.surface,
375
480
  value: entry.value,
376
481
  modelCalled: false,
377
482
  modelId: entry.modelId,
378
483
  latencyMs: null,
379
- verdict: "defer",
484
+ verdict: verdict.kind,
380
485
  deferReason: entry.deferReason,
381
486
  ...contextFields(false, entry.context),
382
487
  ...guidanceFields(EMPTY_GUIDANCE),
383
488
  });
384
489
  report(deps, { verdict: "defer", deferReason: entry.deferReason });
385
- return { kind: "defer" };
490
+ return verdict;
491
+ }
492
+
493
+ /** A pre-model reason as a link outcome: over-budget, or a failure. */
494
+ function preModelOutcome(
495
+ reason: Exclude<PreModelDeferReason, "no-config">,
496
+ ): LinkOutcome {
497
+ return reason === "context-over-budget"
498
+ ? { kind: "over-budget" }
499
+ : { kind: "failure", failure: reason satisfies FailureKind };
386
500
  }
387
501
 
388
502
  /**
@@ -390,7 +504,7 @@ function deferWith(
390
504
  * measurements are logged — bytes and a hash prefix — never the text, so the
391
505
  * review log stays free of command content beyond the gated value itself.
392
506
  */
393
- function contextFields(
507
+ export function contextFields(
394
508
  included: boolean,
395
509
  context: FullCommandContext | null,
396
510
  ): {
@@ -406,14 +520,14 @@ function contextFields(
406
520
  }
407
521
 
408
522
  /** No guidance: the render before the seam runs, and after it fails. */
409
- const EMPTY_GUIDANCE: GuidanceSelection = { included: [], dropped: [] };
523
+ export const EMPTY_GUIDANCE: GuidanceSelection = { included: [], dropped: [] };
410
524
 
411
525
  /**
412
526
  * The two guidance lists every decision entry carries. Included files are
413
527
  * logged by path, bytes, and hash prefix — never their content — and dropped
414
528
  * files by path, bytes, and the rule that excluded them.
415
529
  */
416
- function guidanceFields(guidance: GuidanceSelection): {
530
+ export function guidanceFields(guidance: GuidanceSelection): {
417
531
  guidanceIncluded: { path: string; bytes: number; hash12: string }[];
418
532
  guidanceDropped: { path: string; bytes: number; reason: string }[];
419
533
  } {
@@ -436,6 +550,6 @@ function guidanceFields(guidance: GuidanceSelection): {
436
550
  * when present, else the display surface; `undefined` when neither is set
437
551
  * (undeterminable — defer without a model call).
438
552
  */
439
- function gateSurfaceOf(details: PromptPermissionDetails): string | undefined {
553
+ export function gateSurfaceOf(details: PromptPermissionDetails): string | undefined {
440
554
  return details.accessIntent?.surface ?? details.surface ?? undefined;
441
555
  }