All files / src/components/chat/ExecutionPipeline RuleEvaluationList.tsx

96.42% Statements 27/28
81.08% Branches 30/37
100% Functions 9/9
96.42% Lines 27/28

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                                                                            16x           16x     2x 2x   8x   4x                         16x     7x     7x                                 16x     7x 7x 7x     7x 7x 7x 5x     7x                                                                               5x                                                   16x       2x 2x   2x     2x   2x               2x                     4x                                  
import { usePiiKinds } from "@/hooks/usePiiKinds";
import { ruleLayerMeta } from "@/apps/user/pages/rules/ruleLayer";
import {
  encodeResourceId,
  GOVERNANCE_OUTCOME,
  StatusBadge,
} from "@/components/detail";
import {
  describeAction,
  GovernanceOutcome,
  OUTCOME_HINTS,
  OUTCOME_LABELS,
} from "@/objects/Governance";
import { RuleTraceEvaluation, RuleTraceResult } from "@/objects/Model";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import {
  describeTraceScope,
  RULE_OUTCOME_ORDER,
  ruleEvaluations,
  ruleOutcomeCounts,
} from "@/util/ruleTrace";
import React from "react";
import { Link } from "react-router-dom";
 
/**
 * The body of a policy or audit stage: every rule that applied to the turn,
 * and what each one came to.
 *
 * It used to list only the action events that fired, which in practice meant
 * one line — the rule that acted — with no sign of the rules that were checked
 * and stood aside, and a redactor over a clean prompt described as having
 * redacted PII. The node now carries every evaluation, so this reads like a row
 * of Governance → Rules → Activity: the same outcome words, the same badge
 * colours, the same phrasing of what an action did.
 *
 * Shared by the chat execution pipeline and the Activity page's trace panel.
 */
 
const PHASE_COPY: Record<"input" | "output", { subject: string }> = {
  input: { subject: "the prompt" },
  output: { subject: "the response" },
};
 
/** The outcome counts across the node, strongest first. */
export const RuleOutcomeSummary: React.FC<{
  evaluations: RuleTraceEvaluation[];
}> = ({ evaluations }) => {
  const counts = ruleOutcomeCounts(evaluations);
  return (
    <div className="flex items-center gap-1 flex-wrap">
      {RULE_OUTCOME_ORDER.filter((outcome) => (counts[outcome] ?? 0) > 0).map(
        (outcome) => (
          <StatusBadge
            key={outcome}
            status={outcome}
            scale={GOVERNANCE_OUTCOME}
            label={`${counts[outcome]} ${OUTCOME_LABELS[outcome].toLowerCase()}`}
            size="xs"
          />
        ),
      )}
    </div>
  );
};
 
const RuleName: React.FC<{ evaluation: RuleTraceEvaluation }> = ({
  evaluation,
}) => {
  const name = evaluation.rule ?? "Untitled rule";
  // Linked while there is an id to link to; the rule may since have been
  // deleted, in which case its page says so — the trace outlives the rule.
  return evaluation.rule_id ? (
    <Link
      to={APP_ROUTES.USER.GOVERNANCE.RULES.id.replace(
        ROUTE_PARAMS.RULE.id,
        encodeResourceId(evaluation.rule_id),
      )}
      className="font-semibold text-gray-800 dark:text-gray-100 truncate hover:underline"
    >
      {name}
    </Link>
  ) : (
    <span className="font-semibold text-gray-800 dark:text-gray-100 truncate">
      {name}
    </span>
  );
};
 
const RuleRow: React.FC<{ evaluation: RuleTraceEvaluation }> = ({
  evaluation,
}) => {
  const meta = ruleLayerMeta(evaluation.layer);
  const Icon = meta.Icon;
  const outcome: GovernanceOutcome = evaluation.outcome;
  // A rule that stood aside is the unremarkable case: one quiet line, so a
  // turn governed by ten rules still reads at a glance.
  const quiet = outcome === "not_matched";
  const { byKey } = usePiiKinds();
  const lines = evaluation.actions.map((action) =>
    describeAction(action, evaluation.detail?.[action], byKey),
  );
 
  return (
    <li
      className={`flex items-start gap-2 px-2 py-1.5 rounded-md border text-[11px] ${
        quiet
          ? "border-gray-100 dark:border-gray-700/60 bg-transparent"
          : "border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800"
      }`}
    >
      <Icon
        className={`size-3.5 shrink-0 mt-px ${
          quiet
            ? "text-gray-300 dark:text-gray-600"
            : "text-gray-500 dark:text-gray-400"
        }`}
        aria-label={meta.label}
      />
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-1.5 min-w-0">
          <RuleName evaluation={evaluation} />
          {evaluation.rule_version != null && (
            <span className="font-mono text-[10px] text-gray-400 dark:text-gray-500 shrink-0">
              v{evaluation.rule_version}
            </span>
          )}
          <span className="flex-1" />
          <span className="hidden sm:inline text-[10px] text-gray-400 dark:text-gray-500 shrink-0">
            {describeTraceScope(evaluation.scope_type, evaluation.scope_id)}
          </span>
          <StatusBadge
            status={outcome}
            scale={GOVERNANCE_OUTCOME}
            label={OUTCOME_LABELS[outcome] ?? outcome}
            size="xs"
            className="shrink-0"
          />
        </div>
        {!quiet &&
          (lines.length > 0 ? (
            <ul className="mt-0.5 space-y-0.5">
              {lines.map((line, i) => (
                <li
                  key={i}
                  className="text-gray-600 dark:text-gray-300 break-words"
                >
                  {line}
                </li>
              ))}
            </ul>
          ) : (
            <p className="mt-0.5 text-gray-500 dark:text-gray-400">
              {OUTCOME_HINTS[outcome]}
            </p>
          ))}
        {(evaluation.enforced_in === "ai" ||
          evaluation.enforced_in === "both") && (
          <p className="mt-0.5 text-[10px] text-gray-400 dark:text-gray-500">
            {evaluation.enforced_in === "both"
              ? "Also enforced inside the run"
              : "Enforced inside the run"}
          </p>
        )}
      </div>
    </li>
  );
};
 
const RuleEvaluationList: React.FC<{
  nodeId: string;
  result: unknown;
}> = ({ nodeId, result }) => {
  const evaluations = ruleEvaluations(nodeId, result);
  const payload = (result ?? {}) as RuleTraceResult;
  const phase =
    payload.phase ?? (nodeId === "__audit__" ? "output" : "input");
  // A trace written before every evaluation was recorded knows only the
  // rules that acted. Say so, rather than let the list imply it is complete.
  const legacy = !Array.isArray(payload.evaluations);
 
  Iif (evaluations.length === 0) {
    return (
      <p className="text-[11px] text-gray-400 dark:text-gray-500 italic">
        No rules applied to {PHASE_COPY[phase].subject}.
      </p>
    );
  }
 
  return (
    <div className="space-y-1.5">
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500">
          {evaluations.length} rule{evaluations.length === 1 ? "" : "s"} on{" "}
          {PHASE_COPY[phase].subject}
        </span>
        <RuleOutcomeSummary evaluations={evaluations} />
      </div>
      <ul className="space-y-1">
        {evaluations.map((evaluation, i) => (
          <RuleRow
            key={evaluation.rule_id ?? `${evaluation.rule}-${i}`}
            evaluation={evaluation}
          />
        ))}
      </ul>
      {legacy && (
        <p className="text-[10px] text-gray-400 dark:text-gray-500 italic">
          Recorded before every evaluated rule was traced — only rules that
          acted are shown.
        </p>
      )}
    </div>
  );
};
 
export default RuleEvaluationList;