All files / src/objects Rule.tsx

100% Statements 63/63
87.27% Branches 48/55
100% Functions 24/24
100% Lines 52/52

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 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530                                                                                                                                                                                                                                                                                                                                                                                                                                                                              29x                                                                                                                                                                                                             29x                                                           29x       154x 33x 33x 12x   24x                   29x         112x 112x 12x 112x 112x       29x     134x 134x             29x   15x       29x 21x                     29x       1673x       29x     1675x 1675x   2034x 1352x                       29x     366x 574x       29x       117x                       29x         104x 104x 90x 32x 28x   104x       29x     202x 202x                 29x 6x 6x                           29x 18x 18x 31x 15x     18x    
import { AIGenerated, Resource, SystemManaged } from "./Doc";
 
/**
 * Where in a request a rule acts, in the order a request meets them: whether
 * it may run at all, what the model reads, what people receive. Each layer's
 * label and the question it answers come from the catalogue (svc-core
 * `app/services/rules/layers.py`); `rules/ruleLayer.ts` holds how one looks.
 * Replaced the policy / audit types (svc-core migration 105).
 */
export type RuleLayer = "access" | "input" | "tools" | "output";
 
/**
 * What a rule governs.
 *
 * Deliberately `string`-backed rather than a closed union used for control
 * flow: the set lives in svc-core's scope registry and is served by
 * `GET /app/rules/catalogue`, for the same reason condition fields are. The
 * union is kept for autocompletion on the values that exist today, but nothing
 * branches on it — the picker, the filters and the labels all render from the
 * catalogue, so a scope added to the backend appears without a release here.
 *
 * `organisation` and `project` are *ownership* scopes: no invocation names one
 * directly, but every governed resource belongs to one, so a rule written
 * there reaches everything inside it.
 */
export type RuleScope =
  | "global"
  | "organisation"
  | "project"
  | "model"
  | "agent"
  | "skill"
  | "worker";
 
/**
 * Where a condition is evaluated, and therefore what it can see.
 *
 * Access and Input rules run before the model is called, Output rules after
 * it returns. The catalogue uses this to
 * decide which fields to offer for a given rule type — which is what stops a
 * policy rule being written against `response`, a value that does not exist
 * until after the model has already answered.
 */
export type RulePhase = "input" | "output";
 
/** The shape of a value, on both sides of a comparison. */
export type RuleValueType =
  | "text"
  | "number"
  | "enum"
  | "boolean"
  | "list"
  | "none";
 
/**
 * A condition field key — e.g. `prompt`, `prompt_tokens`, `pii_detected`.
 *
 * Deliberately `string` rather than a union. The set of fields lives in
 * svc-core's registry and is served by `GET /app/rules/catalogue`; pinning a
 * union here would mean every backend widening needed a matching frontend
 * release, which is the drift this catalogue exists to remove.
 */
export type ConditionField = string;
 
/** A comparison operator key — e.g. `eq`, `gt`, `matches`, `has_any`. */
export type ConditionOperator = string;
 
/** An action type key — e.g. `block`, `redact_pii`, `fallback`. */
export type ActionType = string;
 
export interface RuleCondition {
  field: ConditionField;
  operator: ConditionOperator;
  value: string | boolean;
}
 
export interface RuleAction {
  type: ActionType;
  [key: string]: unknown;
}
 
/**
 * A governance rule. A **built-in** rule (`is_system`) governs nobody: it is
 * a definition CHAIN-R maintains, and a user adopts it by creating a rule of
 * their own from it, which records the built-in and the release it started
 * from (`based_on_rule_id`, `based_on_version`).
 */
export interface Rule extends Resource, AIGenerated, SystemManaged {
  name: string;
  description?: string;
  layer: RuleLayer;
  scope_type: RuleScope;
  scope_id?: string;
  conditions: RuleCondition[];
  actions: RuleAction[];
  is_active: boolean;
  priority: number;
  /** What each action does, in words ("Caps spend at $100 a month"), one
   *  per action in order — svc-core's `Action.summarise`. */
  summaries?: string[];
  created_at: string;
  updated_at: string;
  based_on_rule_id?: string | null;
  based_on_version?: number | null;
  /** Applies in every project of its owner, declared or not (svc-core
   *  `app/services/inheritance.py`). Not for a project's own rule. */
  required_for_projects?: boolean;
  origin?: "own" | "inherited" | "required" | "built_in" | null;
  home_workspace?: string | null;
  /** On `GET /rules/{id}` only: whether the caller may change it here — a
   *  Governance editor of the workspace that owns it, in that workspace;
   *  never a built-in, nor what a project inherits or is required to apply. */
  can_change?: boolean;
  /** On `GET /rules/{id}` only: the name of the workspace that owns it,
   *  where a reader who may not change it is sent to ask. */
  home_workspace_name?: string | null;
}
 
export interface RuleCreate {
  name: string;
  description?: string;
  layer: RuleLayer;
  scope_type: RuleScope;
  scope_id?: string;
  conditions: RuleCondition[];
  actions: RuleAction[];
  is_active: boolean;
  priority: number;
  owner_user_id?: string | null;
  owner_organisation_id?: string | null;
  owner_project_id?: string | null;
  /** The built-in this rule was started from. The server records which
   *  release of it; the content is whatever the form holds. */
  based_on_rule_id?: string;
  /** An organisation's or person's rule that applies in every one of its
   *  projects, declared or not. */
  required_for_projects?: boolean;
}
 
export interface RuleUpdate {
  required_for_projects?: boolean;
  name?: string;
  description?: string;
  layer?: RuleLayer;
  scope_type?: RuleScope;
  scope_id?: string;
  conditions?: RuleCondition[];
  actions?: RuleAction[];
  is_active?: boolean;
  priority?: number;
}
 
// ─── Vocabulary catalogue ─────────────────────────────────────────────────────
//
// The grammar a rule may be written in, served from svc-core's registries by
// `GET /app/rules/catalogue`. The rule builder renders from this rather than
// from hard-coded lists, so a condition field or action added to the backend
// appears in the UI without a frontend release — and, more importantly, the
// UI can never offer something the engine cannot evaluate.
 
/** One comparison a condition can make. */
export interface RuleOperatorSpec {
  key: ConditionOperator;
  label: string;
  description: string;
  /** Field value types this operator may be paired with. */
  applies_to: RuleValueType[];
  /**
   * What to collect as the comparison value. `list` means a comma-separated
   * set; `none` means the operator is unary and the value input is hidden.
   */
  operand: RuleValueType;
}
 
/** One value a condition can be written against. */
export interface RuleFieldSpec {
  key: ConditionField;
  label: string;
  description: string;
  /** Grouping for the field picker — `content`, `invocation`, `cost`, … */
  group: string;
  value_type: RuleValueType;
  phases: RulePhase[];
  /**
   * Closed value set — an `enum` field's choices, or the members a `list`
   * field can hold; empty otherwise.
   */
  options: string[];
  /**
   * The catalogue section describing `options` (`"pii_kinds"`), so the
   * builder shows each one's label and group rather than a bare key.
   */
  vocabulary?: string | null;
  /** Operator keys legal for this field, precomputed by the backend. */
  operators: ConditionOperator[];
}
 
/** One configurable parameter on an action block. */
/** Another parameter holding a value (`ActionParam.shown_when`). */
export interface RuleParamCondition {
  param: string;
  value: string;
}
 
export interface RuleActionParamSpec {
  key: string;
  label: string;
  value_type: RuleValueType;
  description: string;
  required: boolean;
  default: unknown;
  options: string[];
  /**
   * The kind of resource the value names by id (`"dataset"`), so the builder
   * offers a picker rather than an id field. Checked at save time: an id
   * that resolves to nothing is refused, like a scope pinned to nothing.
   */
  resource?: string | null;
  /** The catalogue section describing `options` (`"pii_kinds"`). */
  vocabulary?: string | null;
  /**
   * Shown only while another parameter holds this value — a trailing
   * window's length, only for the trailing period.
   */
  shown_when?: RuleParamCondition | null;
  /** What each item of a list is (`"domain"`), for an input that reads it
   *  as one. Null for plain text. */
  item?: string | null;
}
 
/** A list parameter whose items are web domains — a Tools rule's sources. */
export const DOMAIN_ITEM = "domain";
 
/** One choice a parameter offers, as the builder labels it. */
export interface RuleVocabularyEntry {
  key: string;
  label: string;
  description?: string;
  /** For a quota period: whether it starts again at a boundary. */
  calendar?: boolean | null;
}
 
/**
 * Where an action can be carried out.
 *
 * `both` runs in svc-core and svc-ai alike. `core_only` needs state only
 * svc-core has — the usage ledger behind rate limits and cost caps — so it is
 * resolved before the request is sent and never forwarded.
 */
export type RuleActionEnforcement = "both" | "core_only";
 
/** One effect a matched rule can have. */
export interface RuleActionSpec {
  type: ActionType;
  label: string;
  description: string;
  layer: RuleLayer;
  enforced_in: RuleActionEnforcement;
  params: RuleActionParamSpec[];
}
 
/** One layer of a request, with the fields and actions its rules may use. */
export interface RuleLayerSpec {
  layer: RuleLayer;
  label: string;
  /** The question its rules answer ("May it run?"). */
  summary: string;
  /** When its rules run and what they can do. */
  description: string;
  /** 1-based place in the flow. */
  position: number;
  phase: RulePhase;
  fields: RuleFieldSpec[];
  actions: RuleActionSpec[];
}
 
/** One kind of thing a rule can be written about. */
export interface RuleScopeSpec {
  key: RuleScope;
  label: string;
  description: string;
  /**
   * How narrowly the scope aims, broad (0) to narrow. Orders the picker, and
   * orders rules at equal priority inside the engine.
   */
  specificity: number;
  /** False for `global`, which has exactly one of itself. */
  targets_resource: boolean;
  /** Label for the "every resource of this kind" option. */
  plural: string;
}
 
/** One resource a rule can be pinned to. */
export interface RuleScopeTarget {
  id: string;
  label: string;
  scope_type: RuleScope;
}
 
/**
 * Everything the current user may scope a rule to, by scope.
 *
 * One request rather than the builder fanning out to six routers — and the
 * same payload resolves a stored `scope_id` into a name, so a scoped rule
 * reads as "Support Agent" instead of a UUID.
 */
export interface RuleScopeTargets {
  targets: Partial<Record<RuleScope, RuleScopeTarget[]>>;
}
 
/**
 * One kind of personal data svc-core's PII detectors know — what a field or
 * parameter with `vocabulary: "pii_kinds"` holds.
 */
export interface PiiKindSpec {
  key: string;
  /** As it reads mid-sentence ("email address", "IBAN"). */
  label: string;
  plural: string;
  /** One value in its commonest written form. */
  example: string;
  /** What qualifies the example ("after a keyword such as 'BSN'"). */
  note: string;
  description: string;
  /** Where the identifier is issued — how a picker groups kinds. */
  region: string;
  region_label: string;
  category: string;
  category_label: string;
  /** Part of what a rule redacts when it names no kinds. */
  default: boolean;
}
 
/** The vocabulary name a field or parameter holding PII kinds declares. */
export const PII_KINDS_VOCABULARY = "pii_kinds";
 
export interface RuleCatalogue {
  /**
   * Listed once; which fields each may pair with is recorded on every
   * field's `operators`.
   */
  operators: RuleOperatorSpec[];
  scopes: RuleScopeSpec[];
  /** In flow order. */
  layers: RuleLayerSpec[];
  /** The detectors' registry, for the PII pickers and redaction counts. */
  pii_kinds?: PiiKindSpec[];
  /** The quota actions' choices: period, whose usage, what happens when
   *  reached, which kinds of work. */
  quota_periods?: RuleVocabularyEntry[];
  quota_shares?: RuleVocabularyEntry[];
  quota_responses?: RuleVocabularyEntry[];
  /** A cost cap's room to finish a turn (`reserve`). */
  quota_reserves?: RuleVocabularyEntry[];
  /** When a cost cap alerts, in the inbox (`alert_at`). */
  quota_alerts?: RuleVocabularyEntry[];
  execution_types?: RuleVocabularyEntry[];
}
 
/**
 * The labelled choices a catalogue section holds, or none when the section
 * is absent or is not a list of `{key, label}` (the PII kinds have their
 * own picker).
 */
export const vocabularyEntries = (
  catalogue: RuleCatalogue | null | undefined,
  vocabulary: string | null | undefined,
): RuleVocabularyEntry[] => {
  if (!catalogue || !vocabulary) return [];
  const section = (catalogue as unknown as Record<string, unknown>)[vocabulary];
  if (!Array.isArray(section)) return [];
  return section.filter(
    (entry): entry is RuleVocabularyEntry =>
      !!entry &&
      typeof entry === "object" &&
      typeof (entry as RuleVocabularyEntry).key === "string" &&
      typeof (entry as RuleVocabularyEntry).label === "string",
  );
};
 
/** Whether a parameter applies to an action as it stands: one that depends
 *  on another (`shown_when`) only while that one holds the value — its own
 *  default when it is unset. */
export const paramShown = (
  param: RuleActionParamSpec,
  action: RuleAction,
  spec: RuleActionSpec | undefined,
): boolean => {
  const when = param.shown_when;
  if (!when) return true;
  const other = spec?.params.find((p) => p.key === when.param);
  const current = action[when.param] ?? other?.default ?? "";
  return String(current) === when.value;
};
 
/** PII kinds from the catalogue, or none if it is absent or malformed. */
export const piiKinds = (
  catalogue: RuleCatalogue | null | undefined,
): PiiKindSpec[] => {
  const kinds = catalogue?.pii_kinds;
  return Array.isArray(kinds) ? kinds.filter((kind) => !!kind?.key) : [];
};
 
/**
 * A stored list value — the builder keeps one as comma-separated text — as
 * its members, trimmed and without blanks.
 */
export const parseListValue = (value: unknown): string[] =>
  (Array.isArray(value) ? value.map(String) : String(value ?? "").split(","))
    .map((item) => item.trim())
    .filter(Boolean);
 
/** Capitalises the first letter only: "IBAN" stays "IBAN". */
export const sentenceCase = (text: string): string =>
  text ? text[0].toUpperCase() + text.slice(1) : text;
 
/**
 * The spec for one rule type, or undefined if the catalogue has not loaded.
 *
 * Every array access is guarded independently, not just `catalogue` itself.
 * An optional chain on the outer object says nothing about the shape inside
 * it, and a body that is merely *present* but not the expected shape — a
 * transport that answers `[]`, a proxy error page, a truncated response — is
 * the case that blanks the whole builder rather than degrading it.
 */
export const ruleLayerSpec = (
  catalogue: RuleCatalogue | null | undefined,
  layer: RuleLayer,
): RuleLayerSpec | undefined =>
  ruleLayerSpecs(catalogue).find((spec) => spec.layer === layer);
 
/** Every layer's spec, in flow order, or none if the catalogue is absent or
 *  malformed — guarded as every catalogue read is. */
export const ruleLayerSpecs = (
  catalogue: RuleCatalogue | null | undefined,
): RuleLayerSpec[] => {
  const layers = catalogue?.layers;
  return Array.isArray(layers)
    ? layers
        .filter((spec): spec is RuleLayerSpec => !!spec?.layer)
        .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))
    : [];
};
 
/**
 * Scope specs from the catalogue, broadest first, or none if it is absent or
 * malformed.
 *
 * Guarded like every other catalogue read: a transport that answers `[]`, a
 * proxy error page or a truncated response must degrade the scope picker, not
 * blank the builder around it.
 */
export const ruleScopes = (
  catalogue: RuleCatalogue | null | undefined,
): RuleScopeSpec[] => {
  const scopes = catalogue?.scopes;
  return Array.isArray(scopes) ? scopes.filter((scope) => !!scope?.key) : [];
};
 
/** The spec for one scope, or undefined when the catalogue has not loaded. */
export const ruleScopeSpec = (
  catalogue: RuleCatalogue | null | undefined,
  scope: RuleScope,
): RuleScopeSpec | undefined =>
  ruleScopes(catalogue).find((spec) => spec.key === scope);
 
/**
 * How a rule's scope reads to a person.
 *
 * Three cases, and they are genuinely different: a global rule governs
 * everything, an unpinned rule governs every resource of its kind, and a
 * pinned one governs exactly one — which is worth naming. The name comes from
 * the targets payload; a pin whose resource no longer resolves falls back to
 * the kind rather than showing a bare UUID, because a deleted target is
 * exactly when the label matters and the id tells the reader nothing.
 */
export const describeScope = (
  rule: Pick<Rule, "scope_type" | "scope_id">,
  catalogue?: RuleCatalogue | null,
  targets?: RuleScopeTargets | null,
): string => {
  const spec = ruleScopeSpec(catalogue, rule.scope_type);
  if (spec && !spec.targets_resource) return spec.label;
  if (!rule.scope_id) return spec?.plural ?? `All ${rule.scope_type}s`;
  const named = targets?.targets?.[rule.scope_type]?.find(
    (target) => target.id === rule.scope_id,
  );
  return named ? named.label : (spec?.plural ?? `All ${rule.scope_type}s`);
};
 
/** Operators from the catalogue, or none if it is absent or malformed. */
export const ruleOperators = (
  catalogue: RuleCatalogue | null | undefined,
): RuleOperatorSpec[] => {
  const operators = catalogue?.operators;
  return Array.isArray(operators) ? operators : [];
};
 
/**
 * A blank condition for a layer, using the first field the backend offers.
 *
 * Falls back to `always` — the one field guaranteed to exist in every phase —
 * so the builder still produces a valid condition before the catalogue loads.
 */
export const blankCondition = (spec?: RuleLayerSpec): RuleCondition => {
  const field = spec?.fields?.[0];
  return {
    field: field?.key ?? "always",
    operator: field?.operators?.[0] ?? "eq",
    value: "",
  };
};
 
/**
 * A blank action for `ruleType`, pre-filled with each parameter's default.
 *
 * Defaults come from the backend rather than being restated here, so a
 * block rule's message and a review flag's reviewer read the same in the
 * builder as they do when the engine applies them.
 */
export const blankAction = (actionSpec?: RuleActionSpec): RuleAction => {
  const action: RuleAction = { type: actionSpec?.type ?? "" };
  actionSpec?.params?.forEach((param) => {
    if (param.default !== null && param.default !== undefined) {
      action[param.key] = param.default;
    }
  });
  return action;
};