All files / src/objects Governance.tsx

89.04% Statements 65/73
81.25% Branches 78/96
100% Functions 11/11
90.9% Lines 60/66

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307                                                                                                                                                                                                                                        22x             22x                   22x         62x     62x 62x 62x                   22x       67x 35x 63x 62x           22x           22x 5x 5x           22x         5x 4x     22x 12x 12x                 22x         103x 103x 61x 61x   42x 27x   15x 2x     2x 2x   13x 6x     1x 1x   5x   2x 2x       3x     3x 3x   7x         7x     5x   5x           5x             5x 5x       2x   2x                       22x 30x 15x 15x               22x     30x             45x 30x    
import { formatUsd } from "@/components/cost/format";
import { RuleLayer, RuleScope } from "@/objects/Rule";
import type { SettledWeb } from "@/objects/WebSearch";
import { describeSettledWeb } from "@/util/webSearchReport";
 
/** Types for the governance activity log — `GET /app/rules/activity`.
 *
 *  One record per *applicable rule per invocation*, whether or not it
 *  matched. That is what the log is for: an action with nothing to do emits
 *  no event, so a log built from events alone would make a redaction rule
 *  over a clean prompt look exactly like a rule that was never evaluated. */
 
/** Which side of the invocation the rule was evaluated against. */
export type GovernancePhase = "input" | "output";
 
/** What came of one rule being evaluated. */
export type GovernanceOutcome =
  /** The rule refused the invocation. */
  | "blocked"
  /** It matched and its actions changed something. */
  | "applied"
  /** It matched, its actions ran, and there was nothing to do. */
  | "no_change"
  /** Its conditions did not hold, so no action ran. */
  | "not_matched";
 
/** Which service carried the rule out. */
export type GovernanceEnforcedIn = "core" | "ai";
 
export interface GovernanceEvent {
  id: string;
  owner_user_id?: string | null;
 
  /** Denormalised: the event has to stay readable after the rule is renamed
   *  or deleted, which is exactly when it matters most. */
  rule_id?: string | null;
  rule_name?: string | null;
  rule_version?: number | null;
  layer: RuleLayer;
  scope_type?: RuleScope | null;
  scope_id?: string | null;
 
  phase: GovernancePhase;
  outcome: GovernanceOutcome;
  enforced_in: GovernanceEnforcedIn;
  /** Action types that ran, in order. Empty when the conditions did not hold. */
  actions: string[];
  /** Per-action specifics keyed by action type — redaction kinds and counts, a
   *  block's message, the figures a quota was judged against. Never the text
   *  that matched: the log of a redaction is not a copy of what was redacted. */
  detail: Record<string, Record<string, unknown>>;
 
  /** The turn this evaluation belongs to. Both phases of one message share
   *  it — a conversation has many turns, so its id cannot group them. */
  invocation_id?: string | null;
  execution_type?: string | null;
  conversation_id?: string | null;
  message_id?: string | null;
  agent_id?: string | null;
  ai_model_id?: string | null;
 
  created_at?: string | null;
}
 
/** Every rule that ran on one message, and what each came to.
 *
 *  The unit the log is read in: a row per rule is what happened, a card per
 *  turn is what somebody monitoring several agents is actually looking at. */
export interface GovernanceGroup {
  invocation_id?: string | null;
  occurred_at?: string | null;
  execution_type?: string | null;
  /** What to open to read the message these rules ran on. Filled in after
   *  the turn is persisted, so absent for one that never was. */
  conversation_id?: string | null;
  message_id?: string | null;
  agent_id?: string | null;
  ai_model_id?: string | null;
  /** The agent's name, resolved server-side. Null once it is deleted — the
   *  events outlive it, which is exactly when the log matters most. */
  subject?: string | null;
  /** Counts per outcome within this turn. */
  outcomes: Partial<Record<GovernanceOutcome, number>>;
  events: GovernanceEvent[];
}
 
/** Counts per outcome over the *filtered* set, not the page on screen. */
export interface GovernanceActivitySummary {
  blocked: number;
  applied: number;
  no_change: number;
  not_matched: number;
  total: number;
}
 
export interface GovernanceActivityList {
  /** One page of invocations, newest first. `total` counts turns, not events:
   *  the page pages by turn so a group is never cut in half. */
  groups: GovernanceGroup[];
  total: number;
  summary: GovernanceActivitySummary;
}
 
export interface GovernanceActivityQuery {
  rule_id?: string;
  layer?: RuleLayer;
  phase?: GovernancePhase;
  outcome?: GovernanceOutcome;
  execution_type?: string;
  conversation_id?: string;
  days?: number;
  limit?: number;
  offset?: number;
}
 
/** What each outcome means, in the words the page shows under the badge. */
export const OUTCOME_LABELS: Record<GovernanceOutcome, string> = {
  blocked: "Blocked",
  applied: "Acted",
  no_change: "Nothing to do",
  not_matched: "Didn't apply",
};
 
export const OUTCOME_HINTS: Record<GovernanceOutcome, string> = {
  blocked: "The rule refused this invocation.",
  applied: "The rule matched and changed something.",
  no_change: "The rule matched and its actions found nothing to do.",
  not_matched: "The rule was evaluated; its conditions did not hold.",
};
 
/** How a PII kind reads in a count: its catalogue labels when known. */
export type PiiKindLabels = Record<string, { label: string; plural: string }>;
 
const plural = (
  count: number,
  kind: string,
  labels: PiiKindLabels | undefined,
) => {
  const known = labels?.[kind];
  // A kind the catalogue does not name (it has not loaded, or the detector
  // was retired) still reads as words rather than a key.
  const one = known?.label ?? kind.replace(/_/g, " ");
  const many = known?.plural ?? `${one}s`;
  return `${count} ${count === 1 ? one : many}`;
};
 
/**
 * What a redaction actually removed, in words: "2 email addresses, 1 NHS
 * number". `labels` are the detectors' own names for each kind, from the rule
 * catalogue (`usePiiKinds`). Returns an empty string when the action removed
 * nothing, which is the `no_change` case and is described by the outcome
 * itself.
 */
export const describeRedactions = (
  redacted: unknown,
  labels?: PiiKindLabels,
): string => {
  if (!redacted || typeof redacted !== "object") return "";
  return Object.entries(redacted as Record<string, number>)
    .filter(([, count]) => typeof count === "number" && count > 0)
    .map(([kind, count]) => plural(count, kind, labels))
    .join(", ");
};
 
/** "this month", "today" … for a quota's period; "in the window" for a
 *  trailing one, and for events recorded before quotas had periods. */
const PERIOD_PHRASES: Record<string, string> = {
  day: "today",
  week: "this week",
  month: "this month",
};
 
const periodPhrase = (values: Record<string, unknown>): string => {
  const phrase = PERIOD_PHRASES[String(values.period ?? "")] ?? "in the window";
  return values.share === "per_member" ? `${phrase}, for this member` : phrase;
};
 
/** Whether a quota was under its allowance, passed it and let the call
 *  through (`warned`), or reached it — an event under the limit is recorded
 *  too, with its figures, and must not read as a refusal. */
const quotaState = (
  values: Record<string, unknown>,
  under: boolean,
  noun: string,
): string => {
  if (values.warned) return `${noun} passed, call let through`;
  return under ? `Under the ${noun.toLowerCase()}` : `${noun} reached`;
};
 
const usd = (value: unknown): string => {
  const amount = Number(value);
  return Number.isFinite(amount) ? formatUsd(amount) : `$${String(value)}`;
};
 
/**
 * One line saying what an action did, for the row under the rule's name.
 *
 * Reads the detail block the backend kept rather than re-deriving anything:
 * the figures are the evidence, and the page's job is to phrase them.
 */
export const describeAction = (
  action: string,
  detail: Record<string, unknown> | undefined,
  labels?: PiiKindLabels,
): string => {
  const values = detail ?? {};
  if (action === "filter_pii" || action === "redact_pii") {
    const removed = describeRedactions(values.redacted, labels);
    return removed ? `Redacted ${removed}` : "Found no PII to redact";
  }
  if (action === "block") {
    return values.message ? `Blocked: ${String(values.message)}` : "Blocked";
  }
  if (action === "rate_limit") {
    Iif (values.used === undefined || values.limit === undefined) {
      return "Rate limit reached";
    }
    const figures = `${String(values.used)} of ${String(values.limit)} ${periodPhrase(values)}`;
    return `${quotaState(values, Number(values.used) < Number(values.limit), "Rate limit")} — ${figures}`;
  }
  if (action === "cost_cap") {
    if (values.stopped_mid_turn) {
      // svc-ai stopped the turn at what was left of the cap (X-Spend-Limit).
      const spent =
        values.spent_usd !== undefined ? `, after ${usd(values.spent_usd)}` : "";
      return `Stopped mid-turn at the ${usd(values.limit_usd)} left${spent}`;
    }
    if (values.reserve_usd !== undefined) {
      // Room to finish: less was left than a turn here usually costs.
      const short = `${usd(values.remaining_usd)} left, less than a typical turn (${usd(values.reserve_usd)})`;
      return values.warned
        ? `Call let through with ${short}`
        : `Refused — ${short}`;
    }
    Iif (values.spent_usd === undefined || values.cap_usd === undefined) {
      return "Cost cap reached";
    }
    const figures = `${usd(values.spent_usd)} of ${usd(values.cap_usd)} ${periodPhrase(values)}`;
    return `${quotaState(values, Number(values.spent_usd) < Number(values.cap_usd), "Cost cap")} — ${figures}`;
  }
  Iif (action === "flag_for_review") {
    return values.reviewer
      ? `Flagged for ${String(values.reviewer)} to review`
      : "Flagged for review";
  }
  if (action === "trusted_sources" || action === "blocked_sources") {
    // A Tools rule sets the run's web sources; its detail is the rule's own
    // list, not what the turn searched for.
    const domains = Array.isArray(values.domains) ? values.domains.map(String) : [];
    const named =
      domains.length === 0
        ? "no sources"
        : domains.length <= 3
          ? domains.join(", ")
          : `${domains.slice(0, 3).join(", ")} and ${domains.length - 3} more`;
    const base =
      action === "blocked_sources"
        ? `Ruled out ${named} on the web`
        : values.only
          ? `Limited the web to ${named}`
          : `Put ${named} first on the web`;
    // Settled after the run (svc-core `web_search_summary.settle`): what it
    // did to the turn's searches, in counts. Rows from before then have none.
    const web = values.web as SettledWeb | undefined;
    return web && typeof web === "object"
      ? describeSettledWeb(base, web, action, !!values.only)
      : base;
  }
  Eif (action === "withhold") {
    // The rule's message is kept; the answer never is, here.
    return values.review
      ? "Withheld the answer and sent it to review"
      : "Withheld the answer";
  }
  // `log` was removed as an action (svc-core migration 79); events recorded
  // before then still carry it.
  if (action === "log") return "Logged the invocation";
  return action.replace(/_/g, " ");
};
 
/** What a turn ran against, for the card header: the agent's name when it is
 *  still there, and otherwise what kind of invocation it was. */
export const describeSubject = (group: GovernanceGroup): string => {
  if (group.subject) return group.subject;
  Iif (group.agent_id) return "Deleted agent";
  Eif (group.execution_type === "model") return "Direct model prompt";
  return group.execution_type
    ? `${group.execution_type[0].toUpperCase()}${group.execution_type.slice(1)} run`
    : "Invocation";
};
 
/** The one-line verdict on a whole turn, strongest outcome first: a blocked
 *  invocation is the headline even when four other rules stood aside. */
export const describeGroupOutcome = (
  group: GovernanceGroup,
): { outcome: GovernanceOutcome; label: string } => {
  const order: GovernanceOutcome[] = [
    "blocked",
    "applied",
    "no_change",
    "not_matched",
  ];
  const outcome =
    order.find((key) => (group.outcomes[key] ?? 0) > 0) ?? "not_matched";
  return { outcome, label: OUTCOME_LABELS[outcome] };
};