Files
FabledGrimoire/frontend/src/api/moments.ts
T
bvandeusenandClaude Opus 5.5 82ffd9a235
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Python tests (push) Failing after 1m49s
CI & Build / integration (push) Successful in 2m4s
CI & Build / Build & push image (push) Skipped
feat(8141): a rule holding the finished reply is recorded as a gate stop too
The end-of-turn reply hold was the one gate the gate_stops table left out.
The server applies the per-session cap before anything holds and the Stop
hook blocks on every reason it is given, so the hook reports each held rule
after blocking, as the tool-call gates do: gate `reply`, tool `reply`, and
where the rule was reached (`rule_at`, new beside `rule_ids` in the
/reply-rules answer: the moment it is mounted on, or `reply_rule` for the
backstop). A section hold names no rule and stays counted by report_check.
Opening the rule clears the stop, and rule_misfired marks it, unchanged.

The readout, the telemetry docstring and the Settings panel name the new gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:32:46 -05:00

399 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { apiGet, apiPost, apiPut, apiDelete } from "@/api/client";
import type { RuleEnforcement, RuleSalience, RuleTrigger } from "@/api/rulebooks";
/**
* The moments of work rules mount on, and the actions that
* reach each one on this install — `GET /api/retrieval/moments`, the payload
* the `list_moments` MCP tool returns, plus the counts the Settings view shows
* beside each moment.
*/
export interface Moment {
name: string;
/** What is happening at this moment. */
means: string;
/** The kinds of action that typically reach it. */
reached_by: string;
}
/** A shape rather than an entry: `skill.<name>`, one moment per procedure. */
export interface MomentFamily {
name: string;
prefix: string;
means: string;
reached_by: string;
}
/** `default` ships with the product; `install` is this install's own. */
export type ActionVia = "default" | "install";
export interface MomentAction {
tool: string;
/** Empty = every call of the tool. A command prefix for a command tool,
* `field=value` pairs for any other. */
match: string;
via: ActionVia;
}
/** A shipped default this install switched off. */
export interface RemovedDefault {
id: number;
tool: string;
match: string;
moment: string;
reason: string | null;
actor: string | null;
created_at: string | null;
}
export interface MomentRuleUsage {
rule_id: number;
/** Null for a rule deleted since it was delivered. */
title: string | null;
delivered: number;
opened: boolean;
}
export interface MomentUsage {
/** How many times a mounted rule arrived at this moment. */
delivered: number;
/** How many distinct rules did. */
rules: number;
/** Of those, how many an agent then opened — an upper bound: a pull records
* the door, not the line that prompted it. */
opened: number;
last_delivered_at: string | null;
/** Each rule delivered here, most delivered first. */
by_rule: MomentRuleUsage[];
}
export interface MomentsPayload {
moments: Moment[];
families: MomentFamily[];
total: number;
actions: Record<string, MomentAction[]>;
removed_defaults: RemovedDefault[];
/** Rules mounted per moment; a moment carrying none is absent. */
mounted: Record<string, number>;
/** The count read failed — `mounted` is empty for that reason, not because
* nothing is mounted. */
mounted_failed?: boolean;
usage: {
by_moment: Record<string, MomentUsage>;
days: number;
/** Same distinction as `mounted_failed`, for the usage read. */
moment_usage_failed?: boolean;
};
}
export interface MappingChange {
tool: string;
match?: string;
moment: string;
reason?: string;
}
export function getMoments(days = 30): Promise<MomentsPayload> {
return apiGet(`/api/retrieval/moments?days=${days}`);
}
export function mapAction(change: MappingChange): Promise<unknown> {
return apiPost("/api/retrieval/moments/mappings", change);
}
/** Query parameters, not a body: DELETE bodies are not reliably sent. */
export function unmapAction(change: MappingChange): Promise<void> {
const q = new URLSearchParams({
tool: change.tool,
match: change.match ?? "",
moment: change.moment,
reason: change.reason ?? "",
});
return apiDelete(`/api/retrieval/moments/mappings?${q.toString()}`);
}
/**
* Proposals about a rule's moments, waiting on a person. A `mount` proposal
* comes from a pass that read the rule, or from the rule being opened just
* after the moment fired. An `unmount` proposal comes from sessions reporting that the mount arrived where it did not
* apply. `GET /api/retrieval/moments/proposals`, the payload the
* `rule_moment_proposals` MCP tool returns.
*/
export type ProposalSource = "pass" | "signal" | "edit" | "misfire";
export interface MisfireReason {
why: string;
reached_by: string;
at: string;
}
export interface MomentProposal {
proposal: "mount" | "unmount";
moment: string;
source: ProposalSource;
why: string;
/** For a misfire, `situations` counts distinct days and `co_surfaced` the reports. */
evidence: { situations: number; projects: number; co_surfaced: number };
created_at: string | null;
/** Unmount proposals only: the newest reasons given, and how often each action reached the moment. */
reasons?: MisfireReason[];
reached_by?: Record<string, number>;
}
export interface RuleProposals {
id: number;
title: string;
kind: string;
statement: string;
when_to_apply: string;
home: "global" | "project";
/** What the rule is mounted on now. */
mounted: string[];
proposals: MomentProposal[];
}
export interface ProposalsPayload {
rules: RuleProposals[];
total: number;
}
export type Verdict = "confirm" | "reject";
export interface MomentJudgment {
rule_id: number;
moment: string;
verdict: Verdict;
note?: string;
}
export interface JudgeResult {
judged: { rule_id: number; moment: string; state: string }[];
refused: { rule_id: number; moment?: string; error: string }[];
}
export function getProposals(ruleId?: number): Promise<ProposalsPayload> {
return apiGet(`/api/retrieval/moments/proposals${ruleId ? `?rule_id=${ruleId}` : ""}`);
}
/**
* A confirm MOUNTS the rule on the moment (on an unmount proposal, keeps it);
* a reject unmounts it if mounted and stops the pair being proposed again.
*/
export function judgeProposals(judgments: MomentJudgment[]): Promise<JudgeResult> {
return apiPost("/api/retrieval/moments/proposals/judge", { judgments });
}
/**
* Suggestions for how strongly a rule arrives (`enforcement`, `salience`) and
* which typed triggers reach it, from a pass that read the rule beside its
* delivery history. Nothing changes until a person confirms one.
* `GET /api/retrieval/weights/proposals`, the payload the
* `rule_weight_proposals` MCP tool returns.
*/
export type WeightField = "enforcement" | "salience" | "trigger";
/** What happened when the rule reached a session, over `days`. */
export interface WeightEvidence {
days?: number;
delivered?: number;
opened?: number;
places?: { at: string; delivered: number; opened: number }[];
pulled?: number;
applied?: number;
departed?: number;
misfire_days?: number;
}
export interface WeightProposal {
field: WeightField;
/** The enforcement or salience name; for a trigger, its stored form. */
value: string;
trigger?: RuleTrigger;
why: string;
source: "pass" | "edit";
evidence: WeightEvidence;
created_at: string | null;
}
export interface RuleWeightProposals {
id: number;
title: string;
kind: string;
statement: string;
when_to_apply: string;
home: "global" | "project";
enforcement: RuleEnforcement;
salience: RuleSalience;
mounted: string[];
triggers: RuleTrigger[];
proposals: WeightProposal[];
}
export interface WeightProposalsPayload {
rules: RuleWeightProposals[];
total: number;
}
export interface WeightJudgment {
rule_id: number;
field: WeightField;
value: string | RuleTrigger;
verdict: Verdict;
note?: string;
}
export interface WeightJudgeResult {
judged: { rule_id: number; field: WeightField; value: string; state: string }[];
refused: { rule_id: number; field?: string; error: string }[];
}
/** One rule at one place, or a sum of them: how many sessions it was in
* force in, opened in, and what each was judged. */
export interface AdherenceCounts {
in_force: number;
opened: number;
followed: number;
/** Read and deliberately not followed, with a stated reason. */
departed: number;
broken: number;
not_applicable: number;
unjudged: number;
}
export interface RuleAdherenceRow extends AdherenceCounts {
rule_id: number;
/** Null for a rule deleted since. */
title: string | null;
by_moment: (AdherenceCounts & { at: string })[];
}
export interface MomentAdherenceRow extends AdherenceCounts {
/** A moment (`work.deliver`) or an arm (`pre_tool_rule`). */
at: string;
by_rule: (AdherenceCounts & { rule_id: number; title: string | null })[];
}
export interface AdherencePayload {
days: number;
totals: AdherenceCounts;
by_rule: RuleAdherenceRow[];
by_moment: MomentAdherenceRow[];
}
/** One door of the kind×moment table: where a record search fires, and
* the kinds of record it may consider. */
export interface RecordKindsDoor {
/** A catalog moment, or `message` for the operator's message. */
door: string;
label: string;
fires: string;
kinds: string[];
default: string[];
/** The user changed this door; otherwise it follows the shipped default. */
changed: boolean;
/** Its lines are recorded per session; a door that answers in a tool
* reply is not, so it has no counts. */
measured: boolean;
/** Lines this door pushed of each kind, and how many were opened. */
evidence: Record<string, WayCounts>;
}
export interface RecordKindsTable {
days: number;
evidence_failed: boolean;
kinds: { kind: string; label: string }[];
doors: RecordKindsDoor[];
}
export function getRecordKinds(days = 30): Promise<RecordKindsTable> {
return apiGet(`/api/retrieval/record-kinds?days=${days}`);
}
/** `kinds: null` puts the door back to its shipped default. */
export function setRecordKinds(door: string, kinds: string[] | null): Promise<RecordKindsTable> {
return apiPut("/api/retrieval/record-kinds", { door, kinds });
}
/** How a record arrived in front of a session. */
export type RecordWay = "pushed" | "pointed" | "asked" | "direct";
export interface WayCounts {
delivered: number;
opened: number;
}
export interface RecordReachKind {
/** `snippet`, `note`, `lesson`, `process`, or `task:<kind>`. */
kind: string;
ways: Record<RecordWay, WayCounts>;
sources: { way: RecordWay; source: string; delivered: number; opened: number }[];
}
export interface RecordReachPayload {
days: number;
sessions: number;
totals: Record<RecordWay, WayCounts>;
by_kind: RecordReachKind[];
}
/** How non-rule records reached sessions: pushed, asked for, or opened directly. */
export function getRecordReach(days = 30): Promise<RecordReachPayload> {
return apiGet(`/api/retrieval/record-reach?days=${days}`);
}
/** The gates that can stop a tool call. */
export type GateName = "enforce" | "hold" | "checkpoint" | "fence" | "reply";
export interface GateCounts {
/** Calls denied, or for the fence, put to the operator. */
stops: number;
/** Calls a hold would have stopped, let through because the session's
* stop budget was spent. */
let_through: number;
/** Stops the session cleared by opening the rule. */
cleared: number;
/** Stops whose rule the session then reported as a misfire. */
misfired: number;
/** Stopped calls that ran after all; for the fence, the operator's yes. */
ran: number;
}
export interface GateRuleRow extends GateCounts {
rule_id: number;
gate: GateName;
/** The moment or arm the rule was reached at. */
at: string | null;
title: string | null;
sessions: number;
last_stopped_at: string | null;
}
export interface GateStopsPayload {
days: number;
by_gate: Record<GateName, GateCounts & { sessions: number }>;
by_rule: GateRuleRow[];
fence: { tool: string; target: string | null; asks: number; ran: number }[];
/** The first stop ever recorded; null when none has been. */
complete_from: string | null;
covers_window: boolean | null;
}
/** How often each gate stood in front of a tool call, and what followed. */
export function getGateStops(days = 30): Promise<GateStopsPayload> {
return apiGet(`/api/retrieval/gate-stops?days=${days}`);
}
/** Whether the rules in force at each moment were followed there. */
export function getAdherence(days = 30): Promise<AdherencePayload> {
return apiGet(`/api/retrieval/adherence?days=${days}`);
}
export function getWeightProposals(ruleId?: number): Promise<WeightProposalsPayload> {
return apiGet(`/api/retrieval/weights/proposals${ruleId ? `?rule_id=${ruleId}` : ""}`);
}
/** A confirm sets the field on the rule (a trigger is added beside its
* others); a reject stops that value being proposed again. */
export function judgeWeightProposals(judgments: WeightJudgment[]): Promise<WeightJudgeResult> {
return apiPost("/api/retrieval/weights/proposals/judge", { judgments });
}