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 | 18x 18x 18x 42x 18x 103x 18x 7x 7x 8x 8x 7x 8x 8x 8x 8x 26x 8x 2x 8x 8x 7x 8x 8x 27x 25x 25x 27x 34x 34x 8x 27x 66x 66x 33x 13x 13x 28x 13x 3x 12x 6x 7x 16x 18x 176x 11x 7x 4x 144x 144x 8x 8x 8x | import { GovernanceOutcome, OUTCOME_LABELS } from "@/objects/Governance";
import type {
RuleTraceEvaluation,
RuleTraceEvent,
RuleTraceResult,
} from "@/objects/Model";
import { layerOf } from "@/apps/user/pages/rules/ruleLayer";
import type { RuleLayer } from "@/objects/Rule";
/**
* Reading the result of a `__policy__` / `__audit__` trace node — the rules
* run before the model (Access, Input) and after it (Output).
*
* svc-core records every applicable rule and its outcome on the node
* (`evaluations`), so a turn governed by five rules shows five — including
* the ones that stood aside and the redactors that found nothing to redact.
* Traces persisted before that carry only `events`, one per action that ran,
* and those are rebuilt into the same shape here so both render through one
* view. What cannot be rebuilt — the rules that did not match — simply is not
* there, which is the truth about an old trace.
*/
/** Strongest first: the order a node's rules are read in, and the order its
* summary names outcomes in. */
export const RULE_OUTCOME_ORDER: GovernanceOutcome[] = [
"blocked",
"applied",
"no_change",
"not_matched",
];
/** The type a trace from before layers implies, by phase — what `layerOf`
* reads it through: an Access rule by its actions, else Input. */
const LEGACY_TYPE_BY_PHASE: Record<"input" | "output", string> = {
input: "policy",
output: "audit",
};
/** A traced evaluation's layer: its own, else the one its stored type (or,
* older still, its node's phase) and its actions say. */
const layerFor = (
evaluation: { layer?: string | null; rule_type?: string | null; actions?: string[] },
phase: "input" | "output",
): RuleLayer =>
layerOf({
...evaluation,
rule_type: evaluation.rule_type ?? LEGACY_TYPE_BY_PHASE[phase],
}) ?? (phase === "output" ? "output" : "input");
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
/** Only the keys worth showing, mirroring svc-core's `DETAIL_KEYS`. */
const DETAIL_KEYS = new Set([
"redacted",
"message",
"reviewer",
"limit",
"used",
"cap_usd",
"spent_usd",
"window_seconds",
]);
/** Evaluations rebuilt from a legacy node's action events, one per rule. */
function evaluationsFromEvents(
events: RuleTraceEvent[],
phase: "input" | "output",
): RuleTraceEvaluation[] {
const byRule = new Map<string, RuleTraceEvent[]>();
for (const event of events) {
const key = String(event.rule_id ?? event.rule ?? "");
byRule.set(key, [...(byRule.get(key) ?? []), event]);
}
return Array.from(byRule.values()).map((ruleEvents) => {
const [first] = ruleEvents;
const detail: RuleTraceEvaluation["detail"] = {};
for (const event of ruleEvents) {
const kept = Object.fromEntries(
Object.entries(event).filter(
([key, value]) =>
DETAIL_KEYS.has(key) && value !== undefined && value !== "",
),
);
if (Object.keys(kept).length > 0) {
detail[event.action] = { ...detail[event.action], ...kept };
}
}
const outcome: GovernanceOutcome = ruleEvents.some(
(e) => e.action === "block",
)
? "blocked"
: ruleEvents.some((e) => e.changed !== false)
? "applied"
: "no_change";
const actions = ruleEvents.map((e) => e.action);
return {
rule: first.rule ?? null,
rule_id: first.rule_id ?? null,
layer: layerFor({ actions }, phase),
outcome,
actions,
detail,
};
});
}
/**
* Every rule a policy/audit node recorded, strongest outcome first.
*
* Within one outcome the backend's order is kept — priority, then narrowest
* scope — because that is the order the rules actually ran in.
*/
export function ruleEvaluations(
nodeId: string,
result: unknown,
): RuleTraceEvaluation[] {
if (!isRecord(result)) return [];
const payload = result as RuleTraceResult;
const phase =
payload.phase ?? (nodeId === "__audit__" ? "output" : "input");
const evaluations =
Array.isArray(payload.evaluations) && payload.evaluations.length > 0
? payload.evaluations.filter(isRecord).map((evaluation) => {
const actions = Array.isArray(evaluation.actions)
? evaluation.actions
: [];
return {
...evaluation,
layer: layerFor({ ...evaluation, actions }, phase),
actions,
detail: isRecord(evaluation.detail) ? evaluation.detail : {},
};
})
: evaluationsFromEvents(
(Array.isArray(payload.events) ? payload.events : []).filter(
(event) => isRecord(event) && !!event.action,
),
phase,
);
const rank = (outcome: GovernanceOutcome) => {
const index = RULE_OUTCOME_ORDER.indexOf(outcome);
return index === -1 ? RULE_OUTCOME_ORDER.length : index;
};
// Array.prototype.sort is stable, so ties keep the order the rules ran in.
return [...evaluations].sort((a, b) => rank(a.outcome) - rank(b.outcome));
}
/** How many rules came to each outcome. Outcomes that did not occur are absent. */
export function ruleOutcomeCounts(
evaluations: RuleTraceEvaluation[],
): Partial<Record<GovernanceOutcome, number>> {
const counts: Partial<Record<GovernanceOutcome, number>> = {};
for (const { outcome } of evaluations) {
counts[outcome] = (counts[outcome] ?? 0) + 1;
}
return counts;
}
/** One line for a stage chip or card header: "1 acted · 3 didn't apply". */
export function ruleOutcomeSummaryText(
evaluations: RuleTraceEvaluation[],
): string {
const counts = ruleOutcomeCounts(evaluations);
return RULE_OUTCOME_ORDER.filter((outcome) => (counts[outcome] ?? 0) > 0)
.map(
(outcome) => `${counts[outcome]} ${OUTCOME_LABELS[outcome].toLowerCase()}`,
)
.join(" · ");
}
/** The strongest thing any rule in the node did — the node's headline. */
export function strongestRuleOutcome(
evaluations: RuleTraceEvaluation[],
): GovernanceOutcome | null {
const counts = ruleOutcomeCounts(evaluations);
return RULE_OUTCOME_ORDER.find((outcome) => (counts[outcome] ?? 0) > 0) ?? null;
}
/** Whether a node id is one of the two rule-enforcement nodes. */
export const isRuleNodeId = (nodeId: string): boolean =>
nodeId === "__policy__" || nodeId === "__audit__";
/**
* What a rule covers, in words that are true of *this* invocation: a pinned
* rule only applies when its target is part of the invocation, so a rule
* pinned to an agent that governed this turn was pinned to this agent.
*/
export function describeTraceScope(
scopeType: string | null | undefined,
scopeId: string | null | undefined,
): string {
if (!scopeType || scopeType === "global" || scopeType === "global_") {
return "Global";
}
return scopeId ? `This ${scopeType}` : `Every ${scopeType}`;
}
/**
* The rules a pipeline stage recorded, or null when it is not a rule stage.
*
* Reads the stage's latest result: a stream corrects a policy node in place
* once svc-ai reports its own enforcement, and the last word is the one that
* stands.
*/
export function stageRuleEvaluations(stage: {
node_ids: string[];
attempts: { execution: { node_id: string; system_result?: unknown } }[];
}): RuleTraceEvaluation[] | null {
const [nodeId] = stage.node_ids;
if (!nodeId || !isRuleNodeId(nodeId)) return null;
const latest = [...stage.attempts]
.reverse()
.find((attempt) => attempt.execution.system_result);
return latest ? ruleEvaluations(nodeId, latest.execution.system_result) : [];
}
|