diff --git a/alembic/versions/0128_rule_enforcement.py b/alembic/versions/0128_rule_enforcement.py new file mode 100644 index 00000000..d5bbd282 --- /dev/null +++ b/alembic/versions/0128_rule_enforcement.py @@ -0,0 +1,48 @@ +"""rule enforcement and salience — what a rule does when it arrives, and how much it outranks + +Revision ID: 0128 +Revises: 0127 +Create Date: 2026-11-22 + +Two declared columns on a rule, read by the one function that orders what +reaches a moment: + +- `enforcement`: `enforce` (the act itself is checked), `hold` (the reply or act + waits for one read), `inform` (a line beside the work). Every existing rule + starts as `inform`; declaring which ones hold is the author's call. +- `salience`: `high`, `normal`, `low` — the author's ranking among rules of + the same enforcement. +""" +import sqlalchemy as sa +from alembic import op + +revision = "0128" +down_revision = "0127" +branch_labels = None +depends_on = None + +_ENFORCEMENTS = ("enforce", "hold", "inform") +_SALIENCES = ("high", "normal", "low") + + +def _in_list(column: str, values: tuple[str, ...]) -> str: + return f"{column} IN ({', '.join(repr(v) for v in values)})" + + +def upgrade() -> None: + op.add_column("rules", sa.Column("enforcement", sa.Text(), nullable=False, server_default="inform")) + op.add_column("rules", sa.Column("salience", sa.Text(), nullable=False, server_default="normal")) + op.create_check_constraint("ck_rules_enforcement", "rules", _in_list("enforcement", _ENFORCEMENTS)) + op.create_check_constraint("ck_rules_salience", "rules", _in_list("salience", _SALIENCES)) + # A preference claims no force: it is how work is liked done, not a bar. + op.create_check_constraint( + "ck_rules_preference_informs", "rules", "kind <> 'preference' OR enforcement = 'inform'", + ) + + +def downgrade() -> None: + op.drop_constraint("ck_rules_preference_informs", "rules", type_="check") + op.drop_constraint("ck_rules_salience", "rules", type_="check") + op.drop_constraint("ck_rules_enforcement", "rules", type_="check") + op.drop_column("rules", "salience") + op.drop_column("rules", "enforcement") diff --git a/alembic/versions/0129_rule_deliveries.py b/alembic/versions/0129_rule_deliveries.py new file mode 100644 index 00000000..1261c430 --- /dev/null +++ b/alembic/versions/0129_rule_deliveries.py @@ -0,0 +1,42 @@ +"""rule deliveries — each rule line a session was shown, and whether it was opened after + +Revision ID: 0129 +Revises: 0128 +Create Date: 2026-11-22 + +One row per rule line delivered to a session, with the open stamped on the +delivery it followed. The open rate per rule and moment is read from it, both +for the ordering of what reaches a moment and for the adherence readout. +""" +import sqlalchemy as sa +from alembic import op + +revision = "0129" +down_revision = "0128" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "rule_deliveries", + sa.Column("id", sa.BigInteger(), primary_key=True), + sa.Column("user_id", sa.BigInteger(), nullable=False), + sa.Column("session_id", sa.Text(), nullable=False), + sa.Column("rule_id", sa.BigInteger(), nullable=False), + sa.Column("source", sa.Text(), nullable=False), + sa.Column("at", sa.Text(), nullable=False), + sa.Column("form", sa.Text(), nullable=False), + sa.Column("delivered_at", sa.DateTime(timezone=True), nullable=False, + server_default=sa.func.now()), + sa.Column("opened_at", sa.DateTime(timezone=True), nullable=True), + sa.CheckConstraint("form IN ('full', 'repeat')", name="ck_rule_deliveries_form"), + ) + op.create_index("ix_rule_deliveries_session_rule", "rule_deliveries", + ["user_id", "session_id", "rule_id", "delivered_at"]) + op.create_index("ix_rule_deliveries_rule_at", "rule_deliveries", ["rule_id", "at"]) + op.create_index("ix_rule_deliveries_delivered_at", "rule_deliveries", ["delivered_at"]) + + +def downgrade() -> None: + op.drop_table("rule_deliveries") diff --git a/alembic/versions/0130_rule_triggers.py b/alembic/versions/0130_rule_triggers.py new file mode 100644 index 00000000..c0504d29 --- /dev/null +++ b/alembic/versions/0130_rule_triggers.py @@ -0,0 +1,38 @@ +"""rule triggers — typed predicates on the act that deliver a rule, checked in code + +Revision ID: 0130 +Revises: 0129 +Create Date: 2026-11-22 + +A trigger is a kind (tool, path, command, keyword) and a pattern, optionally +scoped to a moment. Unscoped, it delivers the rule on any act that matches; +scoped, it makes the rule's mount on that moment conditional on the act +matching. Matched in code against the act, never by embedding. +""" +import sqlalchemy as sa +from alembic import op + +revision = "0130" +down_revision = "0129" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "rule_triggers", + sa.Column("rule_id", sa.BigInteger(), + sa.ForeignKey("rules.id", ondelete="CASCADE"), primary_key=True), + sa.Column("kind", sa.Text(), primary_key=True), + sa.Column("pattern", sa.Text(), primary_key=True), + sa.Column("moment", sa.Text(), primary_key=True, server_default=""), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=True), + sa.CheckConstraint( + "kind IN ('tool', 'path', 'command', 'keyword')", name="ck_rule_triggers_kind", + ), + sa.CheckConstraint("length(pattern) > 0", name="ck_rule_triggers_pattern"), + ) + + +def downgrade() -> None: + op.drop_table("rule_triggers") diff --git a/frontend/src/api/rulebooks.ts b/frontend/src/api/rulebooks.ts index 06b96c1d..7f20f6b1 100644 --- a/frontend/src/api/rulebooks.ts +++ b/frontend/src/api/rulebooks.ts @@ -54,6 +54,26 @@ export interface RulebookTopic { */ export type RuleKind = "rule" | "preference"; +/** + * What a rule does when it arrives, declared by its author. `inform` puts a + * line beside the work; `hold` makes the reply or act it governs wait for one + * read; `enforce` checks the act itself. A preference is always `inform`. + */ +export type RuleEnforcement = "enforce" | "hold" | "inform"; +/** How a rule ranks among rules of the same enforcement at a crowded moment. */ +export type RuleSalience = "high" | "normal" | "low"; +/** What a trigger is matched against on the act: the tool called, a path it + * touches, the head of a command it runs, or a word in what it writes. */ +export type RuleTriggerKind = "tool" | "path" | "command" | "keyword"; +/** A typed predicate on the act, checked exactly. With no `moment` it + * delivers the rule on any matching act; with one, it makes the rule's + * mount on that moment conditional on the act matching. */ +export interface RuleTrigger { + kind: RuleTriggerKind; + pattern: string; + moment?: string; +} + /** A new record opened from somewhere that already knows what it is for — * "Adjust this" on a reply shape opens a preference mounted on that shape's * moment. The editor applies it once, when creating. */ @@ -70,6 +90,8 @@ export interface Rule { title: string; statement: string; kind: RuleKind; + enforcement: RuleEnforcement; + salience: RuleSalience; /** WHEN this rule fires — the trigger, not the instruction. */ when_to_apply: string; why: string; @@ -94,6 +116,8 @@ export interface Rule { /** The moments this rule arrives at whenever they happen, * in catalog order. Present only when the rule is mounted. */ moments?: string[]; + /** Present only when the rule has triggers. */ + triggers?: RuleTrigger[]; relations?: RuleRelation[]; /** The lessons that point at this rule — the concrete * situations judged instances of it, plus any suggested and awaiting a @@ -113,6 +137,10 @@ export interface RuleHeader { topic_id: number | null; /** Unconditional on the wire (services.rulebooks.rule_brief). */ kind: RuleKind; + /** Unconditional on the wire, like `kind`. */ + enforcement: RuleEnforcement; + /** Present only when raised or lowered from `normal`. */ + salience?: RuleSalience; /** A date (YYYY-MM-DD), not a timestamp. */ updated_at: string | null; when_to_apply?: string; @@ -217,6 +245,8 @@ export interface RuleWrite { /** Writable from the editor: a preference is not a lesser rule, it is a * different force, and the person writing it is the one who knows which. */ kind: RuleKind; + enforcement: RuleEnforcement; + salience: RuleSalience; when_to_apply: string; why: string; how_to_apply: string; @@ -224,6 +254,8 @@ export interface RuleWrite { system_ids: number[]; /** Replaces the set; [] unmounts the rule from every moment. */ moments: string[]; + /** Replaces the set; [] clears every trigger. */ + triggers: RuleTrigger[]; arose_from_id: number | null; verify_with: string; expires_when: string; diff --git a/frontend/src/components/rules/RuleEditorSlideOver.vue b/frontend/src/components/rules/RuleEditorSlideOver.vue index 8eff520b..ff0f1423 100644 --- a/frontend/src/components/rules/RuleEditorSlideOver.vue +++ b/frontend/src/components/rules/RuleEditorSlideOver.vue @@ -6,7 +6,11 @@ import { useMomentsStore } from "@/stores/moments"; import RuleHistoryPanel from "@/components/rules/RuleHistoryPanel.vue"; import RuleHomePicker from "@/components/rules/RuleHomePicker.vue"; import { apiErrorMessage } from "@/api/client"; -import { listRulebooks, listTopics, type Rule, type RuleKind, type RulePreset } from "@/api/rulebooks"; +import { + listRulebooks, listTopics, + type Rule, type RuleEnforcement, type RuleKind, type RulePreset, type RuleSalience, + type RuleTrigger, type RuleTriggerKind, +} from "@/api/rulebooks"; const props = defineProps<{ ruleId: number | null; @@ -26,6 +30,14 @@ const whenToApply = ref(""); // followed too faithfully, where a rule mislabelled as a preference is one a // session may quietly rewrite. const kind = ref("rule"); +// The server's defaults: a line beside the work, at normal rank. +const enforcement = ref("inform"); +const salience = ref("normal"); +// A preference carries no force but `inform`, and the server refuses any +// other, so switching kind settles it here rather than as a failed save. +watch(kind, (k) => { + if (k === "preference") enforcement.value = "inform"; +}); const systemIds = ref([]); // The moments this rule is mounted on. Catalog moments are // ticked; a named procedure's moment (`skill.`) is typed, since its @@ -39,6 +51,44 @@ const momentCatalog = computed(() => momentsStore.data?.moments ?? []); const procedureMoments = computed(() => ruleMoments.value.filter((m) => m.startsWith(SKILL_PREFIX)), ); +// The acts this rule is triggered by, checked exactly on the server. +const triggers = ref([]); +const triggerKind = ref("path"); +const triggerPattern = ref(""); +const triggerMoment = ref(""); +const triggerError = ref(""); +const TRIGGER_KINDS: { value: RuleTriggerKind; label: string; placeholder: string }[] = [ + { value: "path", label: "Path", placeholder: "alembic/versions/*.py — a file the act touches" }, + { value: "command", label: "Command", placeholder: "git push — the head of a command it runs" }, + { value: "tool", label: "Tool", placeholder: "update_task — the tool it calls" }, + { value: "keyword", label: "Keyword", placeholder: "migration — a word in what it writes" }, +]; +const triggerPlaceholder = computed( + () => TRIGGER_KINDS.find((k) => k.value === triggerKind.value)?.placeholder ?? "", +); + +function triggerLabel(t: RuleTrigger) { + return TRIGGER_KINDS.find((k) => k.value === t.kind)?.label ?? t.kind; +} + +function addTrigger() { + const pattern = triggerPattern.value.trim().replace(/\s+/g, " "); + if (!pattern) return; + const moment = triggerMoment.value || undefined; + const same = (t: RuleTrigger) => + t.kind === triggerKind.value && t.pattern === pattern && (t.moment ?? "") === (moment ?? ""); + if (triggers.value.some(same)) { + triggerError.value = "This rule already has that trigger."; + return; + } + triggerError.value = ""; + triggers.value.push({ kind: triggerKind.value, pattern, ...(moment ? { moment } : {}) }); + triggerPattern.value = ""; +} + +function removeTrigger(at: number) { + triggers.value.splice(at, 1); +} const why = ref(""); const howToApply = ref(""); const verifyWith = ref(""); @@ -123,8 +173,11 @@ async function load() { statement.value = r.statement; whenToApply.value = r.when_to_apply || ""; kind.value = r.kind; + enforcement.value = r.enforcement ?? "inform"; + salience.value = r.salience ?? "normal"; systemIds.value = (r.systems ?? []).map((sys) => sys.id); ruleMoments.value = [...(r.moments ?? [])]; + triggers.value = (r.triggers ?? []).map((t) => ({ ...t })); why.value = r.why || ""; howToApply.value = r.how_to_apply || ""; verifyWith.value = r.verify_with || ""; @@ -135,8 +188,11 @@ async function load() { statement.value = ""; whenToApply.value = props.preset?.whenToApply ?? ""; kind.value = props.preset?.kind ?? "rule"; + enforcement.value = "inform"; + salience.value = "normal"; systemIds.value = []; ruleMoments.value = [...(props.preset?.moments ?? [])]; + triggers.value = []; why.value = ""; howToApply.value = ""; verifyWith.value = ""; @@ -144,6 +200,9 @@ async function load() { } procedureDraft.value = ""; procedureError.value = ""; + triggerPattern.value = ""; + triggerMoment.value = ""; + triggerError.value = ""; await Promise.all([canon.fetchCatalog(), momentsStore.load(), loadHomes()]); } @@ -181,12 +240,16 @@ async function save() { statement: statement.value, when_to_apply: whenToApply.value, kind: kind.value, + enforcement: enforcement.value, + salience: salience.value, // Always sent, so clearing the last area actually clears it — the server // reads a list as "these ARE the areas now". system_ids: systemIds.value, // Always sent, for system_ids' reason: the server reads the list as the // whole set, so unticking the last moment actually unmounts the rule. moments: ruleMoments.value, + // Always sent, for the same reason: the list is the whole set. + triggers: triggers.value, why: why.value, how_to_apply: howToApply.value, // Always sent, including empty. The REST door maps "" to NULL, so @@ -271,6 +334,38 @@ watch(() => props.ruleId, load); preference.

+
+ When it arrives + +

A preference arrives as a line beside the work.

+ +

Sessions rewrite preferences without asking, which is what makes them stay current. Every rewrite is kept, and @@ -342,6 +437,55 @@ watch(() => props.ruleId, load);

{{ procedureError }}

+
+ Acts that trigger it +

+ Matched exactly against what the work does, not by resemblance: a + path it touches, a command it runs, a tool it calls, a word in what it + writes. With no moment, the rule arrives on any act that matches. + With a moment, it arrives at that moment only when the act matches, + so a rule about migrations can sit where files change without arriving + at every edit. +

+
    +
  • + {{ triggerLabel(t) }} + {{ t.pattern }} + at {{ t.moment }} + +
  • +
+

No triggers: this rule arrives by its moments and by resemblance.

+
+ + + + +
+

{{ triggerError }}

+
+
Areas this rule is about