Pointers once a session; the code index knows what each test guards; a reviewing-tests skill #237
@@ -0,0 +1,63 @@
|
|||||||
|
"""code_shape_guards, code_shape_guard_reviews, and the removal verdicts
|
||||||
|
|
||||||
|
Revision ID: 0140
|
||||||
|
Revises: 0139
|
||||||
|
Create Date: 2026-12-01
|
||||||
|
|
||||||
|
What each test guards, read by the coverage sync from the repo archive, so
|
||||||
|
the ledger can show tests that guard the same thing from different files:
|
||||||
|
- code_shape_guards: test shape -> guarded shape, or -> a repo path.
|
||||||
|
Mechanical, rebuilt by every sync, not backed up.
|
||||||
|
- code_shape_guard_reviews: a group judged to be distinct behaviours.
|
||||||
|
- code_shapes.covered_by_id: the shape a `redundant` row is covered by.
|
||||||
|
- code_shapes.test_signals: a test's weak-test signals from the last sync.
|
||||||
|
The statuses `redundant` and `unused` need no schema change: status is a
|
||||||
|
plain text column.
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0140"
|
||||||
|
down_revision = "0139"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("code_shapes", sa.Column(
|
||||||
|
"covered_by_id", sa.Integer(),
|
||||||
|
sa.ForeignKey("code_shapes.id", ondelete="SET NULL"), nullable=True,
|
||||||
|
))
|
||||||
|
op.add_column("code_shapes", sa.Column(
|
||||||
|
"test_signals", sa.Text(), nullable=False, server_default="",
|
||||||
|
))
|
||||||
|
op.create_table(
|
||||||
|
"code_shape_guards",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("test_id", sa.Integer(), sa.ForeignKey("code_shapes.id", ondelete="CASCADE"), nullable=False),
|
||||||
|
sa.Column("guarded_id", sa.Integer(), sa.ForeignKey("code_shapes.id", ondelete="CASCADE"), nullable=True),
|
||||||
|
sa.Column("path", sa.Text(), nullable=True),
|
||||||
|
sa.Column("basis", sa.Text(), nullable=False, server_default="static"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_code_shape_guards_test", "code_shape_guards", ["test_id"])
|
||||||
|
op.create_index("ix_code_shape_guards_guarded", "code_shape_guards", ["guarded_id"])
|
||||||
|
op.create_table(
|
||||||
|
"code_shape_guard_reviews",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("project_id", sa.Integer(), sa.ForeignKey("projects.id", ondelete="CASCADE"), nullable=False),
|
||||||
|
sa.Column("group_key", sa.Text(), nullable=False),
|
||||||
|
sa.Column("verdict", sa.Text(), nullable=False, server_default="distinct"),
|
||||||
|
sa.Column("reason", sa.Text(), nullable=False, server_default=""),
|
||||||
|
sa.Column("reviewed_by", sa.Text(), nullable=False),
|
||||||
|
sa.Column("reviewed_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")),
|
||||||
|
sa.UniqueConstraint("project_id", "group_key", name="uq_code_shape_guard_reviews_group"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("code_shape_guard_reviews")
|
||||||
|
op.drop_index("ix_code_shape_guards_guarded", table_name="code_shape_guards")
|
||||||
|
op.drop_index("ix_code_shape_guards_test", table_name="code_shape_guards")
|
||||||
|
op.drop_table("code_shape_guards")
|
||||||
|
op.drop_column("code_shapes", "test_signals")
|
||||||
|
op.drop_column("code_shapes", "covered_by_id")
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
/**
|
||||||
|
* Tests that guard the same thing from different files — the coverage card's
|
||||||
|
* merge-or-remove queue. Each group lists what its tests exercise and, per
|
||||||
|
* test, weak-test signals read from its body. A group is a candidate, not a
|
||||||
|
* verdict: the reviewer either marks one test redundant (naming the test in
|
||||||
|
* the group that covers it) or keeps them all, with a reason either way.
|
||||||
|
*/
|
||||||
|
import { ref, onMounted, watch } from "vue";
|
||||||
|
import { apiGet, apiPost, apiErrorMessage } from "@/api/client";
|
||||||
|
import { useToastStore } from "@/stores/toast";
|
||||||
|
|
||||||
|
interface ShapeRef {
|
||||||
|
id: number;
|
||||||
|
path: string;
|
||||||
|
symbol: string;
|
||||||
|
}
|
||||||
|
interface GroupTest extends ShapeRef {
|
||||||
|
status: string;
|
||||||
|
signals: string[];
|
||||||
|
}
|
||||||
|
interface Group {
|
||||||
|
key: string;
|
||||||
|
guards: ShapeRef[];
|
||||||
|
tests: GroupTest[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const props = defineProps<{ projectId: number; canWrite: boolean }>();
|
||||||
|
const emit = defineEmits<{ (e: "changed"): void }>();
|
||||||
|
const toast = useToastStore();
|
||||||
|
|
||||||
|
const groups = ref<Group[]>([]);
|
||||||
|
const count = ref(0);
|
||||||
|
const loading = ref(false);
|
||||||
|
const error = ref<string | null>(null);
|
||||||
|
const open = ref(false);
|
||||||
|
|
||||||
|
// One form at a time: keeping a whole group, or marking one test redundant.
|
||||||
|
const activeKey = ref<string | null>(null);
|
||||||
|
const mode = ref<"keep" | "redundant">("keep");
|
||||||
|
const testId = ref<number | null>(null);
|
||||||
|
const coverId = ref<number | null>(null);
|
||||||
|
const reason = ref("");
|
||||||
|
const saving = ref(false);
|
||||||
|
|
||||||
|
const SIGNAL_HELP: Record<string, string> = {
|
||||||
|
signature: "Checks how the code is declared (its parameters), not what it does",
|
||||||
|
"mock-only": "Asserts only that mocks were called",
|
||||||
|
"source-text": "Reads source code as text",
|
||||||
|
};
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
loading.value = true;
|
||||||
|
error.value = null;
|
||||||
|
try {
|
||||||
|
const res = await apiGet<{ count: number; groups: Group[] }>(
|
||||||
|
`/api/projects/${props.projectId}/test-guards`,
|
||||||
|
);
|
||||||
|
groups.value = res.groups;
|
||||||
|
count.value = res.count;
|
||||||
|
} catch (e) {
|
||||||
|
error.value = apiErrorMessage(e, "Could not load the test groups");
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function startKeep(g: Group) {
|
||||||
|
activeKey.value = g.key;
|
||||||
|
mode.value = "keep";
|
||||||
|
reason.value = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function startRedundant(g: Group, t: GroupTest) {
|
||||||
|
activeKey.value = g.key;
|
||||||
|
mode.value = "redundant";
|
||||||
|
testId.value = t.id;
|
||||||
|
coverId.value = g.tests.find((x) => x.id !== t.id)?.id ?? null;
|
||||||
|
reason.value = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancel() {
|
||||||
|
activeKey.value = null;
|
||||||
|
reason.value = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submit(g: Group) {
|
||||||
|
if (!reason.value.trim() || saving.value) return;
|
||||||
|
saving.value = true;
|
||||||
|
try {
|
||||||
|
if (mode.value === "keep") {
|
||||||
|
await apiPost(`/api/projects/${props.projectId}/test-guards/review`, {
|
||||||
|
test_ids: g.tests.map((t) => t.id),
|
||||||
|
reason: reason.value.trim(),
|
||||||
|
});
|
||||||
|
toast.show("Group kept — it leaves the list until a test joins or leaves it");
|
||||||
|
} else {
|
||||||
|
await apiPost(`/api/projects/${props.projectId}/test-guards/redundant`, {
|
||||||
|
test_id: testId.value,
|
||||||
|
covered_by_id: coverId.value,
|
||||||
|
reason: reason.value.trim(),
|
||||||
|
});
|
||||||
|
toast.show("Marked redundant — delete the test, and the next refresh retires its row");
|
||||||
|
}
|
||||||
|
cancel();
|
||||||
|
await load();
|
||||||
|
emit("changed");
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(apiErrorMessage(e, "Could not record the verdict"), "error");
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function label(s: ShapeRef): string {
|
||||||
|
return `${s.path.split("/").pop()} · ${s.symbol}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(load);
|
||||||
|
watch(() => props.projectId, load);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="tg">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn-ghost btn-inline tg-toggle"
|
||||||
|
:aria-expanded="open"
|
||||||
|
aria-controls="tg-groups"
|
||||||
|
@click="open = !open"
|
||||||
|
>
|
||||||
|
{{ open ? "▾" : "▸" }} Tests guarding the same thing
|
||||||
|
<span class="tg-count">{{ count }}</span>
|
||||||
|
</button>
|
||||||
|
<div v-if="open" id="tg-groups" class="tg-body">
|
||||||
|
<p class="tg-intro">
|
||||||
|
Tests in different files that exercise exactly the same code. Read them:
|
||||||
|
if one checks nothing the other doesn't, mark it redundant and delete it;
|
||||||
|
if each checks something of its own, keep them all and say what.
|
||||||
|
</p>
|
||||||
|
<p v-if="loading" class="tg-note">Loading…</p>
|
||||||
|
<p v-else-if="error" class="tg-error" role="alert">{{ error }}</p>
|
||||||
|
<p v-else-if="!groups.length" class="tg-note">
|
||||||
|
No tests guard the same thing from different files.
|
||||||
|
</p>
|
||||||
|
<ul v-else class="tg-list">
|
||||||
|
<li v-for="g in groups" :key="g.key" class="tg-group">
|
||||||
|
<div class="tg-guards">
|
||||||
|
<span class="tg-label">Guard</span>
|
||||||
|
<code v-for="s in g.guards" :key="s.id" :title="s.path">{{ s.symbol }}</code>
|
||||||
|
</div>
|
||||||
|
<ul class="tg-tests">
|
||||||
|
<li v-for="t in g.tests" :key="t.id" class="tg-test">
|
||||||
|
<code :title="t.path">{{ label(t) }}</code>
|
||||||
|
<span
|
||||||
|
v-for="sig in t.signals"
|
||||||
|
:key="sig"
|
||||||
|
class="tg-signal"
|
||||||
|
:title="SIGNAL_HELP[sig] || sig"
|
||||||
|
>{{ sig }}</span>
|
||||||
|
<button
|
||||||
|
v-if="canWrite"
|
||||||
|
type="button"
|
||||||
|
class="btn-ghost btn-inline"
|
||||||
|
@click="startRedundant(g, t)"
|
||||||
|
>Redundant…</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<button
|
||||||
|
v-if="canWrite && activeKey !== g.key"
|
||||||
|
type="button"
|
||||||
|
class="btn-ghost btn-inline"
|
||||||
|
@click="startKeep(g)"
|
||||||
|
>Keep all…</button>
|
||||||
|
<form v-if="activeKey === g.key" class="tg-form" @submit.prevent="submit(g)">
|
||||||
|
<label v-if="mode === 'redundant'" class="tg-field">
|
||||||
|
<span>Covered by</span>
|
||||||
|
<select v-model="coverId">
|
||||||
|
<option
|
||||||
|
v-for="t in g.tests.filter((x) => x.id !== testId)"
|
||||||
|
:key="t.id"
|
||||||
|
:value="t.id"
|
||||||
|
>{{ label(t) }}</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="tg-field">
|
||||||
|
<span>{{ mode === "keep"
|
||||||
|
? "What each test checks that the others don't"
|
||||||
|
: "What the covering test checks that this one also checked" }}</span>
|
||||||
|
<textarea v-model="reason" rows="2" required></textarea>
|
||||||
|
</label>
|
||||||
|
<div class="tg-actions">
|
||||||
|
<button type="submit" class="btn-primary btn-compact" :disabled="!reason.trim() || saving">
|
||||||
|
{{ mode === "keep" ? "Keep all" : "Mark redundant" }}
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn-ghost btn-compact" @click="cancel">Cancel</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<p v-if="count > groups.length" class="tg-note">
|
||||||
|
Showing {{ groups.length }} of {{ count }}, largest first.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.tg { display: flex; flex-direction: column; gap: var(--fs-space-2); }
|
||||||
|
.tg-toggle { align-self: flex-start; }
|
||||||
|
.tg-count {
|
||||||
|
margin-left: var(--fs-space-1);
|
||||||
|
padding: 0 var(--fs-space-2);
|
||||||
|
border-radius: var(--fs-radius-pill);
|
||||||
|
border: 1px solid var(--fs-border-color);
|
||||||
|
color: var(--fs-text-secondary);
|
||||||
|
}
|
||||||
|
.tg-body { display: flex; flex-direction: column; gap: var(--fs-space-2); }
|
||||||
|
.tg-intro, .tg-note { color: var(--fs-text-tertiary); margin: 0; }
|
||||||
|
.tg-error { color: var(--fs-status-cancelled-fg); margin: 0; }
|
||||||
|
.tg-list, .tg-tests { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
|
||||||
|
.tg-group {
|
||||||
|
border: 1px solid var(--fs-border-color);
|
||||||
|
border-radius: var(--fs-radius-md);
|
||||||
|
padding: var(--fs-space-2) var(--fs-space-3);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--fs-space-2);
|
||||||
|
}
|
||||||
|
.tg-guards, .tg-test { display: flex; flex-wrap: wrap; align-items: center; gap: var(--fs-space-2); }
|
||||||
|
.tg-label { color: var(--fs-text-tertiary); }
|
||||||
|
code { font-family: var(--fs-font-mono); color: var(--fs-text-primary); }
|
||||||
|
.tg-signal {
|
||||||
|
padding: 0 var(--fs-space-2);
|
||||||
|
border-radius: var(--fs-radius-pill);
|
||||||
|
background: var(--fs-status-todo-bg);
|
||||||
|
color: var(--fs-status-todo-fg);
|
||||||
|
}
|
||||||
|
.tg-form { display: flex; flex-direction: column; gap: var(--fs-space-2); }
|
||||||
|
.tg-field { display: flex; flex-direction: column; gap: var(--fs-space-1); color: var(--fs-text-secondary); }
|
||||||
|
.tg-actions { display: flex; gap: var(--fs-space-2); }
|
||||||
|
</style>
|
||||||
@@ -18,6 +18,7 @@ import { canWriteRecord } from "@/utils/permission";
|
|||||||
import ProjectRulesTab from "@/components/rules/ProjectRulesTab.vue";
|
import ProjectRulesTab from "@/components/rules/ProjectRulesTab.vue";
|
||||||
import SystemsSection from "@/components/SystemsSection.vue";
|
import SystemsSection from "@/components/SystemsSection.vue";
|
||||||
import InceptionCard from "@/components/InceptionCard.vue";
|
import InceptionCard from "@/components/InceptionCard.vue";
|
||||||
|
import TestGuardReview from "@/components/TestGuardReview.vue";
|
||||||
import { fmtDate } from "@/utils/dateFormat";
|
import { fmtDate } from "@/utils/dateFormat";
|
||||||
import type { InceptionDecision, InceptionRecord } from "@/api/inception";
|
import type { InceptionDecision, InceptionRecord } from "@/api/inception";
|
||||||
import {
|
import {
|
||||||
@@ -498,6 +499,10 @@ interface Coverage {
|
|||||||
divergent?: number;
|
divergent?: number;
|
||||||
divergence?: Divergence[];
|
divergence?: Divergence[];
|
||||||
recheck?: number;
|
recheck?: number;
|
||||||
|
// Same-guard test groups awaiting a verdict (TestGuardReview).
|
||||||
|
test_groups?: number;
|
||||||
|
// The suite by what it protects.
|
||||||
|
tests?: { linked: number; unlinked: number; redundant: number } | null;
|
||||||
}
|
}
|
||||||
interface Divergence {
|
interface Divergence {
|
||||||
path: string;
|
path: string;
|
||||||
@@ -834,7 +839,7 @@ async function confirmDelete() {
|
|||||||
</div>
|
</div>
|
||||||
<div v-if="coverage.counts" class="coverage-gaps">
|
<div v-if="coverage.counts" class="coverage-gaps">
|
||||||
<span
|
<span
|
||||||
v-for="k in ['canonical', 'instance', 'variant', 'exempt', 'scoped']"
|
v-for="k in ['canonical', 'instance', 'variant', 'exempt', 'redundant', 'unused', 'scoped', 'test']"
|
||||||
:key="k"
|
:key="k"
|
||||||
>
|
>
|
||||||
<span v-if="coverage.counts[k]" class="coverage-gap-chip">
|
<span v-if="coverage.counts[k]" class="coverage-gap-chip">
|
||||||
@@ -888,6 +893,26 @@ async function confirmDelete() {
|
|||||||
{{ coverage.recheck }} to recheck
|
{{ coverage.recheck }} to recheck
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div
|
||||||
|
v-if="coverage.tests && (coverage.tests.linked || coverage.tests.unlinked || coverage.tests.redundant)"
|
||||||
|
class="coverage-gaps"
|
||||||
|
title="Each test case is linked to the code it exercises. Linked tests are accounted for by what they guard; a test linked to nothing is in the todo until someone says what it protects."
|
||||||
|
>
|
||||||
|
<span class="coverage-gaps-label">Tests:</span>
|
||||||
|
<span class="coverage-gap-chip">{{ coverage.tests.linked }} linked</span>
|
||||||
|
<span v-if="coverage.tests.unlinked" class="coverage-gap-chip">
|
||||||
|
{{ coverage.tests.unlinked }} guarding nothing found
|
||||||
|
</span>
|
||||||
|
<span v-if="coverage.tests.redundant" class="coverage-gap-chip">
|
||||||
|
{{ coverage.tests.redundant }} redundant
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<TestGuardReview
|
||||||
|
v-if="coverage.test_groups"
|
||||||
|
:project-id="projectId"
|
||||||
|
:can-write="!!project && canWriteRecord(project.permission)"
|
||||||
|
@changed="loadCoverage"
|
||||||
|
/>
|
||||||
</template>
|
</template>
|
||||||
<p v-else class="coverage-empty">
|
<p v-else class="coverage-empty">
|
||||||
Not measured yet — Refresh reads the bound repo's definitions into
|
Not measured yet — Refresh reads the bound repo's definitions into
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "grimoire",
|
"name": "grimoire",
|
||||||
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
|
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon, reviewing-tests), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
|
||||||
"version": "2026.11.28.2315",
|
"version": "2026.12.01.0344",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "Bryan Van Deusen"
|
"name": "Bryan Van Deusen"
|
||||||
},
|
},
|
||||||
|
|||||||
+2
-1
@@ -17,7 +17,8 @@ instance into a first-class Claude Code extension:
|
|||||||
any client's package would ship: using-grimoire, writing-plans, reporting-back
|
any client's package would ship: using-grimoire, writing-plans, reporting-back
|
||||||
(reply to the operator in a shape that says where the work stands),
|
(reply to the operator in a shape that says where the work stands),
|
||||||
systematic-debugging, verification, brainstorming, reusing-code (record and
|
systematic-debugging, verification, brainstorming, reusing-code (record and
|
||||||
recall reusable code as snippets), shape-accounting and family-canon.
|
recall reusable code as snippets), shape-accounting, family-canon and
|
||||||
|
reviewing-tests (give every test one verdict and prove the survivors fail).
|
||||||
Replaces superpowers.
|
Replaces superpowers.
|
||||||
- **Your Grimoire Processes as skills** — saved Processes are synced into local
|
- **Your Grimoire Processes as skills** — saved Processes are synced into local
|
||||||
`~/.claude/skills/grimoire-proc-*` stubs that auto-surface by relevance; the
|
`~/.claude/skills/grimoire-proc-*` stubs that auto-surface by relevance; the
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ once, in the **`using-grimoire`** skill: reach for it at the start of the sessio
|
|||||||
and whenever you are unsure what Grimoire expects. Each tool's contract is in its
|
and whenever you are unsure what Grimoire expects. Each tool's contract is in its
|
||||||
description, and the process skills (writing-plans, reporting-back,
|
description, and the process skills (writing-plans, reporting-back,
|
||||||
reusing-code, systematic-debugging, verification, brainstorming,
|
reusing-code, systematic-debugging, verification, brainstorming,
|
||||||
shape-accounting, family-canon) carry their arcs.
|
shape-accounting, family-canon, reviewing-tests) carry their arcs.
|
||||||
|
|
||||||
What only Claude Code needs said:
|
What only Claude Code needs said:
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
---
|
||||||
|
name: reviewing-tests
|
||||||
|
description: Use when a test suite needs reviewing rather than growing — the operator asks to review, prune or tighten tests, CI is slow and the suite only ever grows, the coverage line counts test groups guarding the same thing or tests guarding nothing found, or a project's test standard asks for a review. Triggers on "review the tests", "prune the suite", "too many tests", "redundant tests", "CI is slow", "test standard". Gives each test one verdict, proves the survivors still fail, and lists every removal with its reason.
|
||||||
|
metadata:
|
||||||
|
moments: work.verify
|
||||||
|
---
|
||||||
|
|
||||||
|
# Reviewing a test suite
|
||||||
|
|
||||||
|
Every change adds tests and nothing removes them, so a suite left alone only
|
||||||
|
grows: each test costs every CI run, forever, whether or not it still
|
||||||
|
protects anything. A review is the subtraction pass. It gives every test one
|
||||||
|
verdict, keeps the ones that earn their place, and leaves a record good
|
||||||
|
enough that any removal can be argued back.
|
||||||
|
|
||||||
|
## The standard comes from the project, not from this skill
|
||||||
|
|
||||||
|
Look for the project's own test standard first: a family idea it has
|
||||||
|
adopted (`enter_project` lists ideas under `family`; `get_family_adoption`
|
||||||
|
reads the project's answer), a rule, or a note — `search` for "test
|
||||||
|
standard" in the project. Review against it, and use the test levels it
|
||||||
|
names (unit, database, web, …) for "move" below. With no standard recorded,
|
||||||
|
the verdicts below are the floor; agree the project's levels with the
|
||||||
|
operator before moving any test, and offer to record them so the next review
|
||||||
|
starts from them.
|
||||||
|
|
||||||
|
## Before: the numbers you will compare against
|
||||||
|
|
||||||
|
Write these into the review's task before touching anything:
|
||||||
|
|
||||||
|
- tests **collected**, from a real run's summary (not files, not a grep: a
|
||||||
|
file that fails to collect reads exactly like a pass);
|
||||||
|
- lines of test code;
|
||||||
|
- CI time, from the last few green runs on the main working branch;
|
||||||
|
- the coverage line's test figures: linked, guarding nothing found,
|
||||||
|
redundant, and the number of groups guarding the same thing.
|
||||||
|
|
||||||
|
## Area by area
|
||||||
|
|
||||||
|
Take one area at a time, the project's Systems or its test directories, and
|
||||||
|
finish it before starting the next. In each area:
|
||||||
|
|
||||||
|
1. **Read what the ledger already knows.** `list_shapes(path=<area>)` lists
|
||||||
|
the test cases; a `test` status means the refresh linked it to something
|
||||||
|
it guards, `unclassified` means it is linked to nothing. `test_guard_groups`
|
||||||
|
lists tests in different files that guard exactly the same thing, each
|
||||||
|
with its `signals`: `signature` (pins how code is declared), `mock-only`
|
||||||
|
(asserts only that mocks were called), `source-text` (reads source as
|
||||||
|
text). Signals point at what to read first; they never decide a verdict.
|
||||||
|
2. **Read every test** and give it one verdict:
|
||||||
|
- **keep** — it protects something a user or caller relies on, and
|
||||||
|
nothing else in the suite protects it;
|
||||||
|
- **merge** — it checks one case of a behaviour other tests also check:
|
||||||
|
fold them into one table of cases;
|
||||||
|
- **rewrite** — the subject is right and the check is weak: it pins a
|
||||||
|
name, a signature or a mock call where it should pin an outcome;
|
||||||
|
- **move** — it sits at a level the project's standard puts elsewhere;
|
||||||
|
- **remove** — another test checks everything it checks
|
||||||
|
(`redundant`, naming that test), or what it protects no longer matters
|
||||||
|
to anyone (`unused`).
|
||||||
|
3. **Record the verdicts where they are kept.** Removals go in the ledger:
|
||||||
|
`classify_shapes` with `status="redundant"` and `covered_by` {path,
|
||||||
|
symbol} for a test another covers, `status="unused"` for one nothing
|
||||||
|
needs, a reason on each. A group judged to be distinct behaviours goes to
|
||||||
|
`review_test_group` with what each test checks that the others don't. A
|
||||||
|
test linked to nothing and kept says what it guards in an `exempt` reason.
|
||||||
|
4. **Break what the survivors claim to protect.** Choose three to five
|
||||||
|
behaviours the kept tests guard, break each one deliberately in the
|
||||||
|
product code, and confirm the tests go red; then revert. Run them where
|
||||||
|
the project's own rules say tests run. A test that stays green while its
|
||||||
|
behaviour is broken protects nothing, whatever its name says: rewrite it
|
||||||
|
or remove it.
|
||||||
|
5. **Land the area as one change** that does nothing but this review, so it
|
||||||
|
can be reverted alone. Behaviour changes found on the way are their own
|
||||||
|
issues, never folded in.
|
||||||
|
|
||||||
|
## After
|
||||||
|
|
||||||
|
- Rerun the same numbers and put them beside the baseline in the review's
|
||||||
|
task.
|
||||||
|
- List every removed test with its verdict and reason, in that task's log.
|
||||||
|
The list is what lets someone argue one back.
|
||||||
|
- A test is never removed to make a red build green. A failing test is a
|
||||||
|
finding about the code until a reading says otherwise.
|
||||||
|
|
||||||
|
## Report
|
||||||
|
|
||||||
|
Lead with the numbers (tests, lines, CI time, before and after), then the
|
||||||
|
removals by area with their reasons, then what the deliberate breaks proved
|
||||||
|
and anything they caught. A test found guarding a real bug's absence that
|
||||||
|
nobody knew about is the most valuable line in the report; say so plainly.
|
||||||
@@ -24,6 +24,10 @@ row carries a status:
|
|||||||
unreachable from any other file). Accounted for without a
|
unreachable from any other file). Accounted for without a
|
||||||
judgment; still proposed against, grouped and flagged; any judgment you
|
judgment; still proposed against, grouped and flagged; any judgment you
|
||||||
make overrides it. Not the todo.
|
make overrides it. Not the todo.
|
||||||
|
- `redundant` — should be removed: `covered_by` names the shape that already
|
||||||
|
does its job. **Reason required.** Delete the code; the next sync retires
|
||||||
|
the row.
|
||||||
|
- `unused` — should be removed: nothing needs it. **Reason required.**
|
||||||
- `unclassified` — nobody has judged it yet. **This is the todo list.**
|
- `unclassified` — nobody has judged it yet. **This is the todo list.**
|
||||||
|
|
||||||
## The loop
|
## The loop
|
||||||
@@ -181,6 +185,17 @@ Three questions the ledger answers mechanically:
|
|||||||
one and record the verdict with `classify_shapes` — `instance` if it is,
|
one and record the verdict with `classify_shapes` — `instance` if it is,
|
||||||
otherwise what it actually is.
|
otherwise what it actually is.
|
||||||
|
|
||||||
|
## Tests that guard the same thing
|
||||||
|
|
||||||
|
Every refresh links each test to the shapes its body exercises (mocks
|
||||||
|
excluded), and the coverage line's "N test groups guarding the same thing —
|
||||||
|
test_guard_groups" counts tests in different files that guard exactly the
|
||||||
|
same set. A group is a candidate: read the tests, then mark one `redundant`
|
||||||
|
with the test that covers it, or `review_test_group` with what each checks
|
||||||
|
that the others don't. Each test's `signals` (signature, mock-only,
|
||||||
|
source-text) are evidence for that reading, never a verdict.
|
||||||
|
A whole-suite pass is its own procedure: the reviewing-tests skill.
|
||||||
|
|
||||||
## What this buys
|
## What this buys
|
||||||
|
|
||||||
Divergence becomes mechanical: when button B appears where button A is canon,
|
Divergence becomes mechanical: when button B appears where button A is canon,
|
||||||
|
|||||||
@@ -108,7 +108,7 @@ _READ_ONLY_TOOLS = frozenset({
|
|||||||
"list_repo_bindings",
|
"list_repo_bindings",
|
||||||
# The shape ledger's todo query. Reads only — classify_shapes is
|
# The shape ledger's todo query. Reads only — classify_shapes is
|
||||||
# the write, and it is deliberately NOT here.
|
# the write, and it is deliberately NOT here.
|
||||||
"list_shapes", "shape_history", "stamps_to_review",
|
"list_shapes", "shape_history", "stamps_to_review", "test_guard_groups",
|
||||||
# The retrieval telemetry readout. Aggregates two log tables and
|
# The retrieval telemetry readout. Aggregates two log tables and
|
||||||
# writes nothing. Listed explicitly because its name carries no read
|
# writes nothing. Listed explicitly because its name carries no read
|
||||||
# prefix, so the completeness test below cannot derive it — the same
|
# prefix, so the completeness test below cannot derive it — the same
|
||||||
@@ -196,7 +196,7 @@ _WRITE_TOOLS = frozenset({
|
|||||||
"merge_snippets", "unmerge_snippet",
|
"merge_snippets", "unmerge_snippet",
|
||||||
"create_process", "update_process", "delete_process",
|
"create_process", "update_process", "delete_process",
|
||||||
"classify_shapes", "classify_shapes_by_rule", "confirm_shape_proposals",
|
"classify_shapes", "classify_shapes_by_rule", "confirm_shape_proposals",
|
||||||
"refresh_pattern_coverage", "move_path",
|
"refresh_pattern_coverage", "move_path", "review_test_group",
|
||||||
# design systems
|
# design systems
|
||||||
"create_design_system", "update_design_system", "delete_design_system",
|
"create_design_system", "update_design_system", "delete_design_system",
|
||||||
"create_design_token", "update_design_token", "delete_design_token",
|
"create_design_token", "update_design_token", "delete_design_token",
|
||||||
|
|||||||
@@ -26,6 +26,11 @@ async def classify_shapes(
|
|||||||
- `variant` of snippet N — a deliberate, named departure. `reason`
|
- `variant` of snippet N — a deliberate, named departure. `reason`
|
||||||
(the why) is REQUIRED; it is the record.
|
(the why) is REQUIRED; it is the record.
|
||||||
- `exempt` — judged genuinely one-off. `reason` REQUIRED.
|
- `exempt` — judged genuinely one-off. `reason` REQUIRED.
|
||||||
|
- `redundant` — should be removed: another shape already does its
|
||||||
|
job. `covered_by` {path, symbol} names that shape and `reason` says
|
||||||
|
why it covers this one — for a test, what the covering test checks
|
||||||
|
that this one also checked. test_guard_groups lists the candidates.
|
||||||
|
- `unused` — should be removed: nothing needs it. `reason` REQUIRED.
|
||||||
- `canonical` of snippet N — this row IS the snippet's reference
|
- `canonical` of snippet N — this row IS the snippet's reference
|
||||||
(rarely set by hand; the coverage sync stamps these mechanically).
|
(rarely set by hand; the coverage sync stamps these mechanically).
|
||||||
- `unclassified` — withdraw a judgment; the shape rejoins the todo.
|
- `unclassified` — withdraw a judgment; the shape rejoins the todo.
|
||||||
@@ -38,7 +43,7 @@ async def classify_shapes(
|
|||||||
Args:
|
Args:
|
||||||
project_id: The project whose ledger is being judged.
|
project_id: The project whose ledger is being judged.
|
||||||
classifications: Objects of {path, symbol, status, kind?, snippet_id?,
|
classifications: Objects of {path, symbol, status, kind?, snippet_id?,
|
||||||
idea_id?, reason?, reason_code?}. path+symbol name the shape exactly as
|
idea_id?, reason?, reason_code?, covered_by?}. path+symbol name the shape exactly as
|
||||||
list_shapes shows it; kind ("sym"/"css") narrows when one file
|
list_shapes shows it; kind ("sym"/"css") narrows when one file
|
||||||
defines both. snippet_id is required for canonical/instance/
|
defines both. snippet_id is required for canonical/instance/
|
||||||
variant — or idea_id, a family idea: the shape is then judged
|
variant — or idea_id, a family idea: the shape is then judged
|
||||||
@@ -46,7 +51,7 @@ async def classify_shapes(
|
|||||||
language, or its first reference when none is in that language
|
language, or its first reference when none is in that language
|
||||||
(an idea is shared across languages: a Python shape can be an
|
(an idea is shared across languages: a Python shape can be an
|
||||||
instance of an idea whose reference is Go). reason is required
|
instance of an idea whose reference is Go). reason is required
|
||||||
for variant/exempt. reason_code is
|
for variant/exempt/redundant/unused. reason_code is
|
||||||
an OPTIONAL index beside the prose (one of: scoped-css,
|
an OPTIONAL index beside the prose (one of: scoped-css,
|
||||||
one-off-handler, test-helper, convention-plumbing, pure-helper,
|
one-off-handler, test-helper, convention-plumbing, pure-helper,
|
||||||
generated, script, typed-record) so the ledger can be filtered
|
generated, script, typed-record) so the ledger can be filtered
|
||||||
@@ -106,7 +111,11 @@ async def list_shapes(
|
|||||||
(fed by the coverage refresh). Filters compose:
|
(fed by the coverage refresh). Filters compose:
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
status: canonical | instance | variant | exempt | scoped | unclassified.
|
status: canonical | instance | variant | exempt | redundant | unused |
|
||||||
|
scoped | test | unclassified. `test` is the sync's stamp on a
|
||||||
|
test case linked to what it guards; a test case linked to
|
||||||
|
nothing stays `unclassified`. `redundant`/`unused` are the removal
|
||||||
|
verdicts: the row stays until the code goes.
|
||||||
`scoped` is the sync's mechanical stamp on one-offs by
|
`scoped` is the sync's mechanical stamp on one-offs by
|
||||||
construction (a Vue component's scoped <style> rules and its
|
construction (a Vue component's scoped <style> rules and its
|
||||||
<script setup> functions): accounted for, not judged, still
|
<script setup> functions): accounted for, not judged, still
|
||||||
@@ -440,10 +449,64 @@ async def move_path(project_id: int, from_path: str, to_path: str) -> dict:
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
async def test_guard_groups(project_id: int, top: int = 10) -> dict:
|
||||||
|
"""Tests that guard exactly the same thing from different files — the
|
||||||
|
suite's merge-or-remove queue.
|
||||||
|
|
||||||
|
Each coverage refresh reads, for every test in the project's bound repos
|
||||||
|
(a definition named test* in a test file), which product shapes its body
|
||||||
|
reaches — directly or through test helpers, mocks excluded — and groups
|
||||||
|
tests whose sets match exactly across files. Within one file a shared
|
||||||
|
subject is a table of cases, so it never forms a group.
|
||||||
|
|
||||||
|
A group is a candidate, not a verdict. Read the tests, then either:
|
||||||
|
- classify_shapes one of them `redundant` with `covered_by` naming the
|
||||||
|
test that checks everything it checks, and a reason — then delete it;
|
||||||
|
- review_test_group with the reason each test earns its place, which
|
||||||
|
takes the group out of this list until a test joins or leaves it.
|
||||||
|
|
||||||
|
Each test carries `signals`, weak-test evidence from its body (never a
|
||||||
|
verdict on its own): `signature` pins how the code is declared,
|
||||||
|
`mock-only` asserts only that mocks were called, `source-text` reads
|
||||||
|
source as text.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
project_id: The project whose suite to read.
|
||||||
|
top: How many groups to return, largest first; `count` says how many
|
||||||
|
there are.
|
||||||
|
|
||||||
|
Returns {"count": N, "groups": [{"key", "guards": [{id, path, symbol}],
|
||||||
|
"tests": [{id, path, symbol, status, signals}]}]}.
|
||||||
|
"""
|
||||||
|
from grimoire.services import access
|
||||||
|
from grimoire.services import test_guards
|
||||||
|
|
||||||
|
uid = current_user_id()
|
||||||
|
if not await access.can_read_project(uid, project_id):
|
||||||
|
raise ValueError(f"project {project_id} not found")
|
||||||
|
return await test_guards.guard_groups(project_id, top=max(0, min(top, 100)))
|
||||||
|
|
||||||
|
|
||||||
|
async def review_test_group(project_id: int, test_ids: list[int], reason: str) -> dict:
|
||||||
|
"""Record that a group from test_guard_groups guards distinct behaviours
|
||||||
|
and every test in it stays. The group leaves the list until a test joins
|
||||||
|
or leaves it.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
project_id: The project the tests belong to.
|
||||||
|
test_ids: The group's test ids, as test_guard_groups lists them.
|
||||||
|
reason: What each test checks that the others do not. Required.
|
||||||
|
"""
|
||||||
|
from grimoire.services import test_guards
|
||||||
|
|
||||||
|
uid = current_user_id()
|
||||||
|
return await test_guards.review_group(uid, project_id, test_ids, reason=reason, by="agent")
|
||||||
|
|
||||||
|
|
||||||
def register(mcp) -> None:
|
def register(mcp) -> None:
|
||||||
for fn in (
|
for fn in (
|
||||||
classify_shapes, classify_shapes_by_rule, list_shapes,
|
classify_shapes, classify_shapes_by_rule, list_shapes,
|
||||||
refresh_pattern_coverage, confirm_shape_proposals, shape_history,
|
refresh_pattern_coverage, confirm_shape_proposals, shape_history,
|
||||||
stamps_to_review, move_path,
|
stamps_to_review, move_path, test_guard_groups, review_test_group,
|
||||||
):
|
):
|
||||||
mcp.tool(name=fn.__name__)(fn)
|
mcp.tool(name=fn.__name__)(fn)
|
||||||
|
|||||||
@@ -91,7 +91,10 @@ from grimoire.models.rule_moment_judgment import RuleMomentJudgment # noqa: E40
|
|||||||
from grimoire.models.rule_field_judgment import RuleFieldJudgment # noqa: E402, F401
|
from grimoire.models.rule_field_judgment import RuleFieldJudgment # noqa: E402, F401
|
||||||
from grimoire.models.repo_binding import RepoBinding # noqa: E402, F401
|
from grimoire.models.repo_binding import RepoBinding # noqa: E402, F401
|
||||||
from grimoire.models.forge_connection import ForgeConnection # noqa: E402, F401
|
from grimoire.models.forge_connection import ForgeConnection # noqa: E402, F401
|
||||||
from grimoire.models.code_shape import CodeShape, CodeShapeConsumer, CodeShapeEvent, CodeShapeUse # noqa: E402, F401
|
from grimoire.models.code_shape import ( # noqa: E402, F401
|
||||||
|
CodeShape, CodeShapeConsumer, CodeShapeEvent, CodeShapeGuard, CodeShapeGuardReview,
|
||||||
|
CodeShapeUse,
|
||||||
|
)
|
||||||
from grimoire.models.system import System, RecordSystem # noqa: E402, F401
|
from grimoire.models.system import System, RecordSystem # noqa: E402, F401
|
||||||
from grimoire.models.design_system import DesignSystem, DesignToken # noqa: E402, F401
|
from grimoire.models.design_system import DesignSystem, DesignToken # noqa: E402, F401
|
||||||
# After notes, projects and rulebook topics: family canon foreign-keys all
|
# After notes, projects and rulebook topics: family canon foreign-keys all
|
||||||
|
|||||||
@@ -23,8 +23,24 @@ from grimoire.models.base import TimestampMixin, iso
|
|||||||
# accounted for without a human judging them, so `exempt` keeps meaning "a
|
# accounted for without a human judging them, so `exempt` keeps meaning "a
|
||||||
# person looked"; the proposer, derive grouping and divergence still see them,
|
# person looked"; the proposer, derive grouping and divergence still see them,
|
||||||
# and any judgment (instance/variant/exempt) overrides the stamp.
|
# and any judgment (instance/variant/exempt) overrides the stamp.
|
||||||
SHAPE_STATUSES = ("canonical", "instance", "variant", "exempt", "scoped", "unclassified")
|
#
|
||||||
SHAPE_CLASSIFIERS = ("agent", "audit", "hook", "mechanical", "import")
|
# `redundant` and `unused` are the two verdicts that say a shape should GO:
|
||||||
|
# redundant names the shape that already covers it (`covered_by_id` — for a
|
||||||
|
# test, the test that guards the same thing more fully), unused says nothing
|
||||||
|
# needs it. Both take a reason. The row stays until the code is removed and
|
||||||
|
# the next sync marks it vanished, which is how the verdict is carried out.
|
||||||
|
#
|
||||||
|
# `test` is the sync's mechanical stamp on a test case that is linked to
|
||||||
|
# something it guards (services/test_guards): accounted for by what it
|
||||||
|
# protects, without anyone judging it one-off. A test case linked to nothing
|
||||||
|
# stays `unclassified`, the todo, because nothing says what it is for. Any
|
||||||
|
# judgment overrides the stamp, and losing every link withdraws it.
|
||||||
|
SHAPE_STATUSES = (
|
||||||
|
"canonical", "instance", "variant", "exempt", "redundant", "unused",
|
||||||
|
"scoped", "test", "unclassified",
|
||||||
|
)
|
||||||
|
# `person` is a judgment made in the web UI.
|
||||||
|
SHAPE_CLASSIFIERS = ("agent", "audit", "hook", "mechanical", "import", "person")
|
||||||
|
|
||||||
# The reason catalogue: an OPTIONAL code beside the prose reason on
|
# The reason catalogue: an OPTIONAL code beside the prose reason on
|
||||||
# variant/exempt rows, so the ledger can be filtered and aggregated by kind
|
# variant/exempt rows, so the ledger can be filtered and aggregated by kind
|
||||||
@@ -147,6 +163,13 @@ class CodeShape(Base, TimestampMixin):
|
|||||||
diverges_from: Mapped[int | None] = mapped_column(
|
diverges_from: Mapped[int | None] = mapped_column(
|
||||||
BigInteger, ForeignKey("notes.id", ondelete="SET NULL"), nullable=True
|
BigInteger, ForeignKey("notes.id", ondelete="SET NULL"), nullable=True
|
||||||
)
|
)
|
||||||
|
# A `redundant` row's cover: the shape that does its job already.
|
||||||
|
covered_by_id: Mapped[int | None] = mapped_column(
|
||||||
|
Integer, ForeignKey("code_shapes.id", ondelete="SET NULL"), nullable=True
|
||||||
|
)
|
||||||
|
# A test's weak-test signals from the last sync (services/test_guards
|
||||||
|
# SIGNALS), comma-separated; evidence for a reviewer, never a verdict.
|
||||||
|
test_signals: Mapped[str] = mapped_column(Text, default="")
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def proposal(self) -> dict | None:
|
def proposal(self) -> dict | None:
|
||||||
@@ -184,6 +207,8 @@ class CodeShape(Base, TimestampMixin):
|
|||||||
"classified_sha": self.classified_sha,
|
"classified_sha": self.classified_sha,
|
||||||
"recheck_at": iso(self.recheck_at),
|
"recheck_at": iso(self.recheck_at),
|
||||||
"diverges_from": self.diverges_from,
|
"diverges_from": self.diverges_from,
|
||||||
|
"covered_by_id": self.covered_by_id,
|
||||||
|
"test_signals": [x for x in (self.test_signals or "").split(",") if x],
|
||||||
"created_at": iso(self.created_at),
|
"created_at": iso(self.created_at),
|
||||||
"updated_at": iso(self.updated_at),
|
"updated_at": iso(self.updated_at),
|
||||||
}
|
}
|
||||||
@@ -213,6 +238,8 @@ class CodeShape(Base, TimestampMixin):
|
|||||||
out["diverges_from"] = self.diverges_from
|
out["diverges_from"] = self.diverges_from
|
||||||
if self.recheck_at is not None:
|
if self.recheck_at is not None:
|
||||||
out["recheck"] = True
|
out["recheck"] = True
|
||||||
|
if self.covered_by_id is not None:
|
||||||
|
out["covered_by_id"] = self.covered_by_id
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
@@ -366,3 +393,70 @@ class CodeShapeEvent(Base):
|
|||||||
"commit": self.commit,
|
"commit": self.commit,
|
||||||
"at": iso(self.at),
|
"at": iso(self.at),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# How a guard edge was established. `static` is the coverage sync's read of
|
||||||
|
# a test's body (services/test_guards.link_tests); the vocabulary is a list
|
||||||
|
# so a later basis has a name without a schema change.
|
||||||
|
GUARD_BASES = ("static",)
|
||||||
|
|
||||||
|
|
||||||
|
class CodeShapeGuard(Base):
|
||||||
|
"""One guard edge: a test shape -> what it exercises. Either another
|
||||||
|
shape (`guarded_id`) or, when the test names a repo file in a string
|
||||||
|
(reads its source, runs a script), that file's `path`.
|
||||||
|
|
||||||
|
Mechanical and fully recomputable: every coverage sync rebuilds a repo's
|
||||||
|
edges from its archive, so the table is not backed up (see
|
||||||
|
services/backup._NOT_INCLUDED). Cascades with both shapes.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "code_shape_guards"
|
||||||
|
__table_args__ = (
|
||||||
|
Index("ix_code_shape_guards_test", "test_id"),
|
||||||
|
Index("ix_code_shape_guards_guarded", "guarded_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
test_id: Mapped[int] = mapped_column(
|
||||||
|
Integer, ForeignKey("code_shapes.id", ondelete="CASCADE"), nullable=False
|
||||||
|
)
|
||||||
|
guarded_id: Mapped[int | None] = mapped_column(
|
||||||
|
Integer, ForeignKey("code_shapes.id", ondelete="CASCADE"), nullable=True
|
||||||
|
)
|
||||||
|
path: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
basis: Mapped[str] = mapped_column(Text, nullable=False, default="static")
|
||||||
|
|
||||||
|
|
||||||
|
class CodeShapeGuardReview(Base):
|
||||||
|
"""A reviewed group of tests that guard the same thing, judged to be
|
||||||
|
distinct behaviours worth keeping. Keyed by its members
|
||||||
|
(test_guards.group_key), so a test joining or leaving the group puts it
|
||||||
|
back in front of a reviewer. A judgment, so it is backed up."""
|
||||||
|
|
||||||
|
__tablename__ = "code_shape_guard_reviews"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("project_id", "group_key", name="uq_code_shape_guard_reviews_group"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
project_id: Mapped[int] = mapped_column(
|
||||||
|
Integer, ForeignKey("projects.id", ondelete="CASCADE"), nullable=False
|
||||||
|
)
|
||||||
|
group_key: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
verdict: Mapped[str] = mapped_column(Text, nullable=False, default="distinct")
|
||||||
|
reason: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||||
|
reviewed_by: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
reviewed_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, default=lambda: datetime.now(timezone.utc)
|
||||||
|
)
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"project_id": self.project_id,
|
||||||
|
"group_key": self.group_key,
|
||||||
|
"verdict": self.verdict,
|
||||||
|
"reason": self.reason,
|
||||||
|
"reviewed_by": self.reviewed_by,
|
||||||
|
"reviewed_at": iso(self.reviewed_at),
|
||||||
|
}
|
||||||
|
|||||||
@@ -227,6 +227,73 @@ async def refresh_coverage_route(project_id: int):
|
|||||||
return jsonify({"coverage": coverage})
|
return jsonify({"coverage": coverage})
|
||||||
|
|
||||||
|
|
||||||
|
@projects_bp.route("/<int:project_id>/test-guards", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
async def test_guard_groups_route(project_id: int):
|
||||||
|
"""Tests that guard the same thing from different files, not yet
|
||||||
|
reviewed — the coverage card's merge-or-remove queue."""
|
||||||
|
from grimoire.services import test_guards
|
||||||
|
|
||||||
|
uid = get_current_user_id()
|
||||||
|
if await get_project_for_user(uid, project_id) is None:
|
||||||
|
return not_found("Project")
|
||||||
|
return jsonify(await test_guards.guard_groups(project_id))
|
||||||
|
|
||||||
|
|
||||||
|
@projects_bp.route("/<int:project_id>/test-guards/review", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
async def review_test_group_route(project_id: int):
|
||||||
|
"""Keep every test in a group: body {"test_ids": [...], "reason": "..."}."""
|
||||||
|
from grimoire.services import test_guards
|
||||||
|
|
||||||
|
uid = get_current_user_id()
|
||||||
|
data = await request.get_json() or {}
|
||||||
|
try:
|
||||||
|
review = await test_guards.review_group(
|
||||||
|
uid, project_id, data.get("test_ids") or [],
|
||||||
|
reason=data.get("reason") or "", by="person",
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
return jsonify({"error": str(exc)}), 400
|
||||||
|
return jsonify(review)
|
||||||
|
|
||||||
|
|
||||||
|
@projects_bp.route("/<int:project_id>/test-guards/redundant", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
async def mark_test_redundant_route(project_id: int):
|
||||||
|
"""Judge one test redundant: body {"test_id", "covered_by_id", "reason"}.
|
||||||
|
The same verdict classify_shapes records, made by a person."""
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from grimoire.models import async_session
|
||||||
|
from grimoire.models.code_shape import CodeShape
|
||||||
|
from grimoire.services import shape_ledger
|
||||||
|
|
||||||
|
from grimoire.services import access
|
||||||
|
|
||||||
|
uid = get_current_user_id()
|
||||||
|
if not await access.can_write_project(uid, project_id):
|
||||||
|
return not_found("Project")
|
||||||
|
data = await request.get_json() or {}
|
||||||
|
ids = [int(data.get("test_id") or 0), int(data.get("covered_by_id") or 0)]
|
||||||
|
async with async_session() as session:
|
||||||
|
rows = {r.id: r for r in (await session.execute(
|
||||||
|
select(CodeShape).where(CodeShape.project_id == project_id, CodeShape.id.in_(ids))
|
||||||
|
)).scalars().all()}
|
||||||
|
if any(i not in rows for i in ids):
|
||||||
|
return jsonify({"error": "both tests must be live shapes of this project"}), 400
|
||||||
|
test, cover = rows[ids[0]], rows[ids[1]]
|
||||||
|
try:
|
||||||
|
out = await shape_ledger.classify_shapes(uid, project_id, [{
|
||||||
|
"path": test.path, "symbol": test.symbol, "kind": test.kind,
|
||||||
|
"status": "redundant", "reason": data.get("reason") or "",
|
||||||
|
"covered_by": {"path": cover.path, "symbol": cover.symbol},
|
||||||
|
}], via="person")
|
||||||
|
except ValueError as exc:
|
||||||
|
return jsonify({"error": str(exc)}), 400
|
||||||
|
return jsonify(out)
|
||||||
|
|
||||||
|
|
||||||
@projects_bp.route("/<int:project_id>/forge", methods=["PUT"])
|
@projects_bp.route("/<int:project_id>/forge", methods=["PUT"])
|
||||||
@login_required
|
@login_required
|
||||||
async def set_project_forge_route(project_id: int):
|
async def set_project_forge_route(project_id: int):
|
||||||
|
|||||||
@@ -29,7 +29,9 @@ from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
|
|||||||
from grimoire.models.lesson_situation import LessonSituation
|
from grimoire.models.lesson_situation import LessonSituation
|
||||||
from grimoire.models.rule_field_judgment import RuleFieldJudgment
|
from grimoire.models.rule_field_judgment import RuleFieldJudgment
|
||||||
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
|
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
|
||||||
from grimoire.models.code_shape import CodeShape, CodeShapeEvent, CodeShapeUse
|
from grimoire.models.code_shape import (
|
||||||
|
CodeShape, CodeShapeEvent, CodeShapeGuardReview, CodeShapeUse,
|
||||||
|
)
|
||||||
from grimoire.models.project import Project
|
from grimoire.models.project import Project
|
||||||
from grimoire.models.repo_binding import RepoBinding
|
from grimoire.models.repo_binding import RepoBinding
|
||||||
from grimoire.models.rulebook import (
|
from grimoire.models.rulebook import (
|
||||||
@@ -124,7 +126,11 @@ logger = logging.getLogger(__name__)
|
|||||||
# v31 lesson_situations: the moments and triggers each lesson arrives at,
|
# v31 lesson_situations: the moments and triggers each lesson arrives at,
|
||||||
# with the proposals waiting and the rejections that stop a value being
|
# with the proposals waiting and the rejections that stop a value being
|
||||||
# proposed again. Nothing in the lesson's text records them.
|
# proposed again. Nothing in the lesson's text records them.
|
||||||
BACKUP_VERSION = 31
|
# v32 code_shape_guard_reviews, groups of same-guard tests judged to be
|
||||||
|
# distinct behaviours, and code_shapes.covered_by_id, the shape a
|
||||||
|
# `redundant` verdict names. Lose them and every reviewed group is put
|
||||||
|
# back in front of a reviewer, and every redundant verdict loses its why.
|
||||||
|
BACKUP_VERSION = 32
|
||||||
|
|
||||||
# Every table this backup carries, by its REAL name. Paired with _NOT_INCLUDED
|
# Every table this backup carries, by its REAL name. Paired with _NOT_INCLUDED
|
||||||
# below, these two lists must together account for the entire schema — which is
|
# below, these two lists must together account for the entire schema — which is
|
||||||
@@ -141,6 +147,8 @@ _BACKED_UP = [
|
|||||||
"note_usage_events", "repo_bindings", "note_supersessions",
|
"note_usage_events", "repo_bindings", "note_supersessions",
|
||||||
# The shape ledger, its history and its consumption edges.
|
# The shape ledger, its history and its consumption edges.
|
||||||
"code_shapes", "code_shape_events", "code_shape_uses",
|
"code_shapes", "code_shape_events", "code_shape_uses",
|
||||||
|
# Groups of tests that guard the same thing, reviewed and kept.
|
||||||
|
"code_shape_guard_reviews",
|
||||||
# The global area catalog. Global, not
|
# The global area catalog. Global, not
|
||||||
# user-scoped, so it rides in EVERY export — including a single-user
|
# user-scoped, so it rides in EVERY export — including a single-user
|
||||||
# one, whose Systems would otherwise restore unmapped.
|
# one, whose Systems would otherwise restore unmapped.
|
||||||
@@ -223,6 +231,9 @@ _NOT_INCLUDED = [
|
|||||||
# rebuilt from the repo archive by every coverage sync, and carries no
|
# rebuilt from the repo archive by every coverage sync, and carries no
|
||||||
# judgment — the first refresh after a restore recreates it exactly.
|
# judgment — the first refresh after a restore recreates it exactly.
|
||||||
"code_shape_consumers",
|
"code_shape_consumers",
|
||||||
|
# Derived the same way: which shapes each test exercises, read from the
|
||||||
|
# repo archive by every coverage sync.
|
||||||
|
"code_shape_guards",
|
||||||
# Not a section: the full backup carries the one value in its header as
|
# Not a section: the full backup carries the one value in its header as
|
||||||
# `instance_id`, and a restore decides from it rather than copying a row.
|
# `instance_id`, and a restore decides from it rather than copying a row.
|
||||||
"instance_identity",
|
"instance_identity",
|
||||||
@@ -321,9 +332,12 @@ _COLUMN_EXCLUSIONS: dict[str, set[str]] = {
|
|||||||
# derived data is regenerated, never restored.
|
# derived data is regenerated, never restored.
|
||||||
"proposed_snippet_id", "proposal_basis", "proposal_score",
|
"proposed_snippet_id", "proposal_basis", "proposal_score",
|
||||||
"proposal_group", "proposed_at", "proposed_sha",
|
"proposal_group", "proposed_at", "proposed_sha",
|
||||||
|
# A test's weak-test signals: recomputed by every sync from the body.
|
||||||
|
"test_signals",
|
||||||
},
|
},
|
||||||
"code_shape_events": set(),
|
"code_shape_events": set(),
|
||||||
"code_shape_uses": set(),
|
"code_shape_uses": set(),
|
||||||
|
"code_shape_guard_reviews": {"id"},
|
||||||
# Matched on SLUG at restore, like canonical_systems: a target install
|
# Matched on SLUG at restore, like canonical_systems: a target install
|
||||||
# already seeded the standard platforms from its migrations.
|
# already seeded the standard platforms from its migrations.
|
||||||
"platforms": {"deleted_at", "deleted_batch_id", "id", "created_at", "updated_at"},
|
"platforms": {"deleted_at", "deleted_batch_id", "id", "created_at", "updated_at"},
|
||||||
@@ -419,9 +433,15 @@ _IMPORT_COLUMN_EXCLUSIONS: dict[str, set[str]] = {
|
|||||||
# next refresh recomputes it against the restored snippet ids.
|
# next refresh recomputes it against the restored snippet ids.
|
||||||
"proposed_snippet_id", "proposal_basis", "proposal_score",
|
"proposed_snippet_id", "proposal_basis", "proposal_score",
|
||||||
"proposal_group", "proposed_at", "proposed_sha",
|
"proposal_group", "proposed_at", "proposed_sha",
|
||||||
|
# Not exported: recomputed by the next sync.
|
||||||
|
"test_signals",
|
||||||
|
# Reason 3: it points at another shape of this restore, possibly one
|
||||||
|
# placed after this row, so it is patched once every shape has an id.
|
||||||
|
"covered_by_id",
|
||||||
},
|
},
|
||||||
"code_shape_events": {"id"},
|
"code_shape_events": {"id"},
|
||||||
"code_shape_uses": {"id"},
|
"code_shape_uses": {"id"},
|
||||||
|
"code_shape_guard_reviews": {"id"},
|
||||||
"platforms": {"id", "deleted_at", "deleted_batch_id", "created_at", "updated_at"},
|
"platforms": {"id", "deleted_at", "deleted_batch_id", "created_at", "updated_at"},
|
||||||
# `platform_id` IS set, from the exported slug.
|
# `platform_id` IS set, from the exported slug.
|
||||||
"project_platforms": set(),
|
"project_platforms": set(),
|
||||||
@@ -608,7 +628,9 @@ def _retrieval_tuning_event_rows(rows) -> list[dict]:
|
|||||||
|
|
||||||
|
|
||||||
def _code_shape_rows(rows) -> list[dict]:
|
def _code_shape_rows(rows) -> list[dict]:
|
||||||
return [r.to_dict() for r in rows]
|
# A test's signals are recomputed by every sync from its body, so they
|
||||||
|
# stay out like the proposer's columns do.
|
||||||
|
return [{k: v for k, v in r.to_dict().items() if k != "test_signals"} for r in rows]
|
||||||
|
|
||||||
|
|
||||||
def _code_shape_event_rows(rows) -> list[dict]:
|
def _code_shape_event_rows(rows) -> list[dict]:
|
||||||
@@ -619,6 +641,10 @@ def _code_shape_use_rows(rows) -> list[dict]:
|
|||||||
return [r.to_dict() for r in rows]
|
return [r.to_dict() for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def _code_shape_guard_review_rows(rows) -> list[dict]:
|
||||||
|
return [r.to_dict() for r in rows]
|
||||||
|
|
||||||
|
|
||||||
def _repo_binding_rows(rows) -> list[dict]:
|
def _repo_binding_rows(rows) -> list[dict]:
|
||||||
return [
|
return [
|
||||||
# `ref` is the branch this binding's ledger follows. Without it a
|
# `ref` is the branch this binding's ledger follows. Without it a
|
||||||
@@ -1135,6 +1161,9 @@ async def export_full_backup() -> dict:
|
|||||||
code_shape_events = (await session.execute(
|
code_shape_events = (await session.execute(
|
||||||
select(CodeShapeEvent).order_by(CodeShapeEvent.at, CodeShapeEvent.id)
|
select(CodeShapeEvent).order_by(CodeShapeEvent.at, CodeShapeEvent.id)
|
||||||
)).scalars().all()
|
)).scalars().all()
|
||||||
|
code_shape_guard_reviews = (await session.execute(
|
||||||
|
select(CodeShapeGuardReview).order_by(CodeShapeGuardReview.id)
|
||||||
|
)).scalars().all()
|
||||||
code_shape_uses = (await session.execute(
|
code_shape_uses = (await session.execute(
|
||||||
select(CodeShapeUse).order_by(CodeShapeUse.shape_id, CodeShapeUse.snippet_id, CodeShapeUse.id)
|
select(CodeShapeUse).order_by(CodeShapeUse.shape_id, CodeShapeUse.snippet_id, CodeShapeUse.id)
|
||||||
)).scalars().all()
|
)).scalars().all()
|
||||||
@@ -1213,6 +1242,7 @@ async def export_full_backup() -> dict:
|
|||||||
"code_shapes": _code_shape_rows(code_shapes),
|
"code_shapes": _code_shape_rows(code_shapes),
|
||||||
"code_shape_events": _code_shape_event_rows(code_shape_events),
|
"code_shape_events": _code_shape_event_rows(code_shape_events),
|
||||||
"code_shape_uses": _code_shape_use_rows(code_shape_uses),
|
"code_shape_uses": _code_shape_use_rows(code_shape_uses),
|
||||||
|
"code_shape_guard_reviews": _code_shape_guard_review_rows(code_shape_guard_reviews),
|
||||||
**_family_sections(
|
**_family_sections(
|
||||||
platforms, project_platforms, family_ideas, family_idea_platforms,
|
platforms, project_platforms, family_ideas, family_idea_platforms,
|
||||||
family_idea_references, family_adoptions, family_decisions,
|
family_idea_references, family_adoptions, family_decisions,
|
||||||
@@ -1317,6 +1347,10 @@ async def export_user_backup(user_id: int) -> dict:
|
|||||||
select(CodeShapeEvent).where(CodeShapeEvent.project_id.in_(project_ids))
|
select(CodeShapeEvent).where(CodeShapeEvent.project_id.in_(project_ids))
|
||||||
.order_by(CodeShapeEvent.at, CodeShapeEvent.id)
|
.order_by(CodeShapeEvent.at, CodeShapeEvent.id)
|
||||||
)).scalars().all() if project_ids else []
|
)).scalars().all() if project_ids else []
|
||||||
|
code_shape_guard_reviews = (await session.execute(
|
||||||
|
select(CodeShapeGuardReview).where(CodeShapeGuardReview.project_id.in_(project_ids))
|
||||||
|
.order_by(CodeShapeGuardReview.id)
|
||||||
|
)).scalars().all() if project_ids else []
|
||||||
code_shape_uses = (await session.execute(
|
code_shape_uses = (await session.execute(
|
||||||
select(CodeShapeUse).join(CodeShape, CodeShape.id == CodeShapeUse.shape_id)
|
select(CodeShapeUse).join(CodeShape, CodeShape.id == CodeShapeUse.shape_id)
|
||||||
.where(CodeShape.project_id.in_(project_ids))
|
.where(CodeShape.project_id.in_(project_ids))
|
||||||
@@ -1516,6 +1550,7 @@ async def export_user_backup(user_id: int) -> dict:
|
|||||||
"code_shapes": _code_shape_rows(code_shapes),
|
"code_shapes": _code_shape_rows(code_shapes),
|
||||||
"code_shape_events": _code_shape_event_rows(code_shape_events),
|
"code_shape_events": _code_shape_event_rows(code_shape_events),
|
||||||
"code_shape_uses": _code_shape_use_rows(code_shape_uses),
|
"code_shape_uses": _code_shape_use_rows(code_shape_uses),
|
||||||
|
"code_shape_guard_reviews": _code_shape_guard_review_rows(code_shape_guard_reviews),
|
||||||
**_family_sections(
|
**_family_sections(
|
||||||
platforms, project_platforms, family_ideas, family_idea_platforms,
|
platforms, project_platforms, family_ideas, family_idea_platforms,
|
||||||
family_idea_references, family_adoptions, family_decisions,
|
family_idea_references, family_adoptions, family_decisions,
|
||||||
@@ -2346,6 +2381,22 @@ def _build_code_shape_event(row: dict, maps: _Maps) -> CodeShapeEvent | None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_code_shape_guard_review(row: dict, maps: _Maps) -> CodeShapeGuardReview | None:
|
||||||
|
"""A reviewed group rides its project. Its key names the member tests by
|
||||||
|
path and symbol, not by id, so it needs no re-mapping."""
|
||||||
|
pid = maps.projects.get(row.get("project_id", 0))
|
||||||
|
if pid is None:
|
||||||
|
return None
|
||||||
|
return CodeShapeGuardReview(
|
||||||
|
project_id=pid,
|
||||||
|
group_key=row.get("group_key", ""),
|
||||||
|
verdict=row.get("verdict", "distinct"),
|
||||||
|
reason=row.get("reason", ""),
|
||||||
|
reviewed_by=row.get("reviewed_by", ""),
|
||||||
|
reviewed_at=_dt(row.get("reviewed_at")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _build_code_shape_use(row: dict, maps: _Maps) -> CodeShapeUse | None:
|
def _build_code_shape_use(row: dict, maps: _Maps) -> CodeShapeUse | None:
|
||||||
"""Consumption edges ride their shape AND their snippet — both ends
|
"""Consumption edges ride their shape AND their snippet — both ends
|
||||||
must have survived, or the edge is no longer a fact."""
|
must have survived, or the edge is no longer a fact."""
|
||||||
@@ -2552,7 +2603,7 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
|
|||||||
"system_usage_events": 0,
|
"system_usage_events": 0,
|
||||||
"repo_bindings": 0,
|
"repo_bindings": 0,
|
||||||
"note_supersessions": 0, "code_shapes": 0, "code_shape_events": 0,
|
"note_supersessions": 0, "code_shapes": 0, "code_shape_events": 0,
|
||||||
"code_shape_uses": 0, "canonical_systems": 0,
|
"code_shape_uses": 0, "code_shape_guard_reviews": 0, "canonical_systems": 0,
|
||||||
"rule_systems": 0, "rule_moments": 0, "rule_moment_judgments": 0,
|
"rule_systems": 0, "rule_moments": 0, "rule_moment_judgments": 0,
|
||||||
"rule_triggers": 0, "rule_field_judgments": 0,
|
"rule_triggers": 0, "rule_field_judgments": 0,
|
||||||
"rule_relations": 0, "rule_versions": 0,
|
"rule_relations": 0, "rule_versions": 0,
|
||||||
@@ -2984,6 +3035,21 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
|
|||||||
session.add(edge)
|
session.add(edge)
|
||||||
stats["code_shape_uses"] += 1
|
stats["code_shape_uses"] += 1
|
||||||
|
|
||||||
|
# v32: a redundant verdict's cover, once every shape has its new id.
|
||||||
|
for cs_data in data.get("code_shapes", []):
|
||||||
|
cover = maps.shapes.get(cs_data.get("covered_by_id") or 0)
|
||||||
|
placed = maps.shapes.get(int(cs_data["id"])) if cs_data.get("id") else None
|
||||||
|
if cover and placed:
|
||||||
|
shape = await session.get(CodeShape, placed)
|
||||||
|
if shape is not None:
|
||||||
|
shape.covered_by_id = cover
|
||||||
|
for rv in data.get("code_shape_guard_reviews", []):
|
||||||
|
review = _build_code_shape_guard_review(rv, maps)
|
||||||
|
if review is None:
|
||||||
|
continue
|
||||||
|
session.add(review)
|
||||||
|
stats["code_shape_guard_reviews"] += 1
|
||||||
|
|
||||||
# v10: a project's design-system pointer and its inception record ride
|
# v10: a project's design-system pointer and its inception record ride
|
||||||
# the project but point at design systems and rulebooks restored AFTER
|
# the project but point at design systems and rulebooks restored AFTER
|
||||||
# it — so they are written last, with ids re-mapped. An id that did
|
# it — so they are written last, with ids re-mapped. An id that did
|
||||||
@@ -3044,7 +3110,7 @@ _CATALOG_TABLES = ("canonical_systems", "platforms")
|
|||||||
# longer holds, so a rollback clears them and the backfills rebuild them.
|
# longer holds, so a rollback clears them and the backfills rebuild them.
|
||||||
_DERIVED_TABLES = (
|
_DERIVED_TABLES = (
|
||||||
"note_embeddings", "rule_embeddings", "milestone_embeddings",
|
"note_embeddings", "rule_embeddings", "milestone_embeddings",
|
||||||
"system_embeddings", "code_shape_consumers",
|
"system_embeddings", "code_shape_consumers", "code_shape_guards",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -663,6 +663,9 @@ class ArchiveScan(NamedTuple):
|
|||||||
# AndroidManifest.xml, a Dockerfile — so detection reads the names here
|
# AndroidManifest.xml, a Dockerfile — so detection reads the names here
|
||||||
# rather than re-walking the tarball.
|
# rather than re-walking the tarball.
|
||||||
paths: tuple[str, ...] = ()
|
paths: tuple[str, ...] = ()
|
||||||
|
# Each test file's imports, for linking tests to what they guard
|
||||||
|
# (services/test_guards). None when the scan read no test file.
|
||||||
|
test_files: dict | None = None
|
||||||
|
|
||||||
|
|
||||||
def definitions_from_archive(blob: bytes) -> list[ArchiveShape]:
|
def definitions_from_archive(blob: bytes) -> list[ArchiveShape]:
|
||||||
@@ -679,8 +682,11 @@ def scan_archive(blob: bytes) -> ArchiveScan:
|
|||||||
that component is stripped so paths match recorded snippet locations,
|
that component is stripped so paths match recorded snippet locations,
|
||||||
which are repo-relative. Non-UTF-8 files are binaries and skipped.
|
which are repo-relative. Non-UTF-8 files are binaries and skipped.
|
||||||
"""
|
"""
|
||||||
|
from grimoire.services import test_guards
|
||||||
|
|
||||||
shapes: list[ArchiveShape] = []
|
shapes: list[ArchiveShape] = []
|
||||||
references: dict[str, dict[str, int]] = {}
|
references: dict[str, dict[str, int]] = {}
|
||||||
|
test_files: dict = {}
|
||||||
paths: list[str] = []
|
paths: list[str] = []
|
||||||
with tarfile.open(fileobj=io.BytesIO(blob), mode="r:gz") as tar:
|
with tarfile.open(fileobj=io.BytesIO(blob), mode="r:gz") as tar:
|
||||||
for member in tar:
|
for member in tar:
|
||||||
@@ -714,7 +720,17 @@ def scan_archive(blob: bytes) -> ArchiveScan:
|
|||||||
)
|
)
|
||||||
if refs:
|
if refs:
|
||||||
references[path] = refs
|
references[path] = refs
|
||||||
return ArchiveScan(shapes, references, tuple(paths))
|
if test_guards.is_test_path(path):
|
||||||
|
test_files[path] = test_guards.read_test_file(text)
|
||||||
|
# A spec whose cases are calls gets one row of its own, the
|
||||||
|
# whole file as its body, so the linker can read what it
|
||||||
|
# guards.
|
||||||
|
if test_guards.is_call_style_spec(path, text, (d.name for d in defs)) \
|
||||||
|
and not any(d.name == file_stem(path) for d in defs):
|
||||||
|
shapes.append(ArchiveShape(
|
||||||
|
path, "file", file_stem(path), f"file {path}", "", text,
|
||||||
|
))
|
||||||
|
return ArchiveScan(shapes, references, tuple(paths), test_files)
|
||||||
|
|
||||||
|
|
||||||
# --- matching shapes against recorded locations ------------------------------
|
# --- matching shapes against recorded locations ------------------------------
|
||||||
@@ -848,6 +864,22 @@ async def compute_coverage(
|
|||||||
await shape_ledger.sync_repo_consumers(project_id, key, scan.references)
|
await shape_ledger.sync_repo_consumers(project_id, key, scan.references)
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.warning("consumer map sync failed for %s", key, exc_info=True)
|
logger.warning("consumer map sync failed for %s", key, exc_info=True)
|
||||||
|
# What each test guards, from the same bodies. Mechanical and
|
||||||
|
# recomputable like the consumer map, so it cannot fail the refresh.
|
||||||
|
try:
|
||||||
|
from grimoire.services import test_guards
|
||||||
|
|
||||||
|
links = test_guards.link_tests(
|
||||||
|
[test_guards.Def(d.path, d.name, d.body) for d in definitions if d.kind == "sym"],
|
||||||
|
scan.test_files or {}, scan.paths,
|
||||||
|
file_tests=[
|
||||||
|
test_guards.Def(d.path, d.name, d.body) for d in definitions
|
||||||
|
if d.kind == "file" and d.body and test_guards.is_test_path(d.path)
|
||||||
|
],
|
||||||
|
)
|
||||||
|
await test_guards.sync_repo_guards(project_id, key, links)
|
||||||
|
except Exception:
|
||||||
|
logger.warning("test guard sync failed for %s", key, exc_info=True)
|
||||||
# Propose while the bodies are in hand — the one moment they exist.
|
# Propose while the bodies are in hand — the one moment they exist.
|
||||||
# Canonical marking below only touches rows the proposer leaves
|
# Canonical marking below only touches rows the proposer leaves
|
||||||
# alone (a canon's own location never gets a proposal), so the order
|
# alone (a canon's own location never gets a proposal), so the order
|
||||||
@@ -912,7 +944,7 @@ async def compute_coverage(
|
|||||||
# repo that was unreachable today still has live rows, and they count.
|
# repo that was unreachable today still has live rows, and they count.
|
||||||
rows = await shape_ledger.live_rows(project_id)
|
rows = await shape_ledger.live_rows(project_id)
|
||||||
counts = {"canonical": 0, "instance": 0, "variant": 0, "exempt": 0,
|
counts = {"canonical": 0, "instance": 0, "variant": 0, "exempt": 0,
|
||||||
"scoped": 0, "unclassified": 0}
|
"redundant": 0, "unused": 0, "scoped": 0, "test": 0, "unclassified": 0}
|
||||||
for row in rows:
|
for row in rows:
|
||||||
counts[row.status] = counts.get(row.status, 0) + 1
|
counts[row.status] = counts.get(row.status, 0) + 1
|
||||||
by_repo: dict[str, dict[str, int]] = {}
|
by_repo: dict[str, dict[str, int]] = {}
|
||||||
@@ -950,6 +982,16 @@ async def compute_coverage(
|
|||||||
except Exception:
|
except Exception:
|
||||||
logger.warning("stamp review read failed", exc_info=True)
|
logger.warning("stamp review read failed", exc_info=True)
|
||||||
review = {}
|
review = {}
|
||||||
|
# Tests that guard the same thing from different files, not yet reviewed:
|
||||||
|
# the suite's merge-or-remove queue.
|
||||||
|
try:
|
||||||
|
from grimoire.services import test_guards
|
||||||
|
|
||||||
|
test_groups = (await test_guards.guard_groups(project_id, top=0))["count"]
|
||||||
|
tests = await test_guards.test_summary(project_id)
|
||||||
|
except Exception:
|
||||||
|
logger.warning("test guard groups read failed", exc_info=True)
|
||||||
|
test_groups, tests = 0, None
|
||||||
# The write-time figure: how often the end-of-turn
|
# The write-time figure: how often the end-of-turn
|
||||||
# question was put on this project, and how often it was walked past.
|
# question was put on this project, and how often it was walked past.
|
||||||
# An audit reads the ledger; this reads whether the reflex held.
|
# An audit reads the ledger; this reads whether the reflex held.
|
||||||
@@ -977,6 +1019,10 @@ async def compute_coverage(
|
|||||||
# The consumer map's negative space: live css rules
|
# The consumer map's negative space: live css rules
|
||||||
# no template names — None when the map has no evidence of templates.
|
# no template names — None when the map has no evidence of templates.
|
||||||
"unused_css": unused_css,
|
"unused_css": unused_css,
|
||||||
|
# Same-guard test groups awaiting a verdict (test_guard_groups).
|
||||||
|
"test_groups": test_groups,
|
||||||
|
# The suite by what it protects: {linked, unlinked, redundant}.
|
||||||
|
"tests": tests,
|
||||||
"proposer": proposer_stats,
|
"proposer": proposer_stats,
|
||||||
# The divergence readout: new shapes where a different canon
|
# The divergence readout: new shapes where a different canon
|
||||||
# dominates, and judged shapes whose bodies moved since they were
|
# dominates, and judged shapes whose bodies moved since they were
|
||||||
@@ -1121,7 +1167,8 @@ def coverage_line(coverage: dict) -> str:
|
|||||||
counts = coverage.get("counts") or {}
|
counts = coverage.get("counts") or {}
|
||||||
breakdown = " · ".join(
|
breakdown = " · ".join(
|
||||||
f"{counts[k]} {k}"
|
f"{counts[k]} {k}"
|
||||||
for k in ("canonical", "instance", "variant", "exempt", "scoped")
|
for k in ("canonical", "instance", "variant", "exempt", "redundant", "unused",
|
||||||
|
"scoped", "test")
|
||||||
if counts.get(k)
|
if counts.get(k)
|
||||||
)
|
)
|
||||||
line = (
|
line = (
|
||||||
@@ -1172,6 +1219,11 @@ def coverage_line(coverage: dict) -> str:
|
|||||||
if coverage.get("unused_css"):
|
if coverage.get("unused_css"):
|
||||||
n_u = coverage["unused_css"]
|
n_u = coverage["unused_css"]
|
||||||
standing.append(f"{n_u} unused class{'es' if n_u != 1 else ''}")
|
standing.append(f"{n_u} unused class{'es' if n_u != 1 else ''}")
|
||||||
|
if coverage.get("test_groups"):
|
||||||
|
n_g = coverage["test_groups"]
|
||||||
|
standing.append(
|
||||||
|
f"{n_g} test group{'s' if n_g != 1 else ''} guarding the same thing — test_guard_groups"
|
||||||
|
)
|
||||||
if unclassified:
|
if unclassified:
|
||||||
line += f"; {unclassified} unclassified"
|
line += f"; {unclassified} unclassified"
|
||||||
if standing:
|
if standing:
|
||||||
@@ -1181,6 +1233,12 @@ def coverage_line(coverage: dict) -> str:
|
|||||||
line += ", largest: " + ", ".join(gaps)
|
line += ", largest: " + ", ".join(gaps)
|
||||||
elif standing:
|
elif standing:
|
||||||
line += f"; standing: {', '.join(standing)}"
|
line += f"; standing: {', '.join(standing)}"
|
||||||
|
tests = coverage.get("tests") or {}
|
||||||
|
if any(tests.values()):
|
||||||
|
line += (
|
||||||
|
f"; tests: {tests.get('linked', 0)} linked · {tests.get('unlinked', 0)} "
|
||||||
|
f"guarding nothing found · {tests.get('redundant', 0)} redundant"
|
||||||
|
)
|
||||||
if coverage.get("recheck"):
|
if coverage.get("recheck"):
|
||||||
line += f"; {coverage['recheck']} judged shape{'s' if coverage['recheck'] != 1 else ''} changed since judged — recheck"
|
line += f"; {coverage['recheck']} judged shape{'s' if coverage['recheck'] != 1 else ''} changed since judged — recheck"
|
||||||
# Rows the hook asserted on evidence below the ledger's floor. They do
|
# Rows the hook asserted on evidence below the ledger's floor. They do
|
||||||
|
|||||||
@@ -81,6 +81,7 @@ BUNDLED_SKILL_MOMENTS: dict[str, tuple[str, ...]] = {
|
|||||||
"shape-accounting": ("work.record",),
|
"shape-accounting": ("work.record",),
|
||||||
"reporting-back": ("reply.report",),
|
"reporting-back": ("reply.report",),
|
||||||
"family-canon": ("work.record",),
|
"family-canon": ("work.record",),
|
||||||
|
"reviewing-tests": ("work.verify",),
|
||||||
}
|
}
|
||||||
|
|
||||||
# A stored process arrives as the skill `grimoire-proc-<slug>`
|
# A stored process arrives as the skill `grimoire-proc-<slug>`
|
||||||
|
|||||||
@@ -137,14 +137,18 @@ def record_surfaced(
|
|||||||
return
|
return
|
||||||
_schedule(rows)
|
_schedule(rows)
|
||||||
# The same lines, against the session a plugin door is delivering to. A
|
# The same lines, against the session a plugin door is delivering to. A
|
||||||
# synced skill is not a line in front of the session, so it is left out.
|
# synced skill is not a line in front of the session, and a pointer is
|
||||||
|
# booked as `pointed` by the door that names it, so both are left out.
|
||||||
if source not in _NOT_A_LINE:
|
if source not in _NOT_A_LINE:
|
||||||
from grimoire.services import record_deliveries
|
from grimoire.services import record_deliveries
|
||||||
record_deliveries.record(user_id, note_ids, source)
|
record_deliveries.record(user_id, note_ids, source)
|
||||||
|
|
||||||
|
|
||||||
# Surfacing sources that put nothing in front of the session as a line.
|
# Surfacing sources that put nothing in front of the session as a line:
|
||||||
_NOT_A_LINE = frozenset({"process_skill_sync"})
|
# a synced skill, and the snippets beside an edited file, which are named by
|
||||||
|
# id in a pointer line (its door records them as `pointed`). Booking these
|
||||||
|
# as `pushed` too would count each delivery twice.
|
||||||
|
_NOT_A_LINE = frozenset({"process_skill_sync", "write_path_place"})
|
||||||
|
|
||||||
|
|
||||||
def record_pulled(
|
def record_pulled(
|
||||||
|
|||||||
@@ -852,13 +852,12 @@ async def build_autoinject_hint(
|
|||||||
# What else cleared the floor, named by id only. Recorded as `pointed`
|
# What else cleared the floor, named by id only. Recorded as `pointed`
|
||||||
# rather than surfaced: no line was spent on these, so an open that
|
# rather than surfaced: no line was spent on these, so an open that
|
||||||
# follows says whether a pointer is enough.
|
# follows says whether a pointer is enough.
|
||||||
pointer = record_kinds.pointer_line(pointers, POINTER_LEAD)
|
pointer = await _point(user_id, pointers, POINTER_LEAD, "auto_inject_pointer")
|
||||||
if pointer:
|
if pointer:
|
||||||
lines.append(pointer[0])
|
lines.append(pointer[0])
|
||||||
parts.append(hook_payload.Part(
|
parts.append(hook_payload.Part(
|
||||||
text=pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(pointer[1])},
|
text=pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(pointer[1])},
|
||||||
))
|
))
|
||||||
record_deliveries_svc.record(user_id, pointer[1], "auto_inject_pointer", way=POINTED)
|
|
||||||
|
|
||||||
# A lookup, not a ranking, so it writes no retrieval_logs row — there is no
|
# A lookup, not a ranking, so it writes no retrieval_logs row — there is no
|
||||||
# score or bar to tune — and its surfacings are its own source, which is
|
# score or bar to tune — and its surfacings are its own source, which is
|
||||||
@@ -877,6 +876,31 @@ async def build_autoinject_hint(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def _point(
|
||||||
|
user_id: int, pointers: dict[str, list[int]], lead: str, source: str,
|
||||||
|
) -> tuple[str, list[int]] | None:
|
||||||
|
"""One pointer line, naming each record at most once a session, booked
|
||||||
|
under `source` as `pointed`; None when nothing is left to name.
|
||||||
|
|
||||||
|
A pointer is for a record the session has not met. The plugin's own
|
||||||
|
ledger of what a session has seen holds only the records given a line,
|
||||||
|
so without this a record named by id comes back on every edit and every
|
||||||
|
message. A handoff note can then be named dozens of times in one session,
|
||||||
|
and a line that repeats on every turn stops being read. The server's
|
||||||
|
delivery ledger knows every record shown or pointed at in the session,
|
||||||
|
whatever the plugin version, so that is what is asked. Outside a plugin
|
||||||
|
request there is no session, nothing is left out, and nothing is booked.
|
||||||
|
"""
|
||||||
|
ids = [i for kind_ids in pointers.values() for i in kind_ids]
|
||||||
|
had = await record_deliveries_svc.delivered_this_session(user_id, ids)
|
||||||
|
if had:
|
||||||
|
pointers = {k: [i for i in v if i not in had] for k, v in pointers.items()}
|
||||||
|
pointer = record_kinds.pointer_line(pointers, lead)
|
||||||
|
if pointer:
|
||||||
|
record_deliveries_svc.record(user_id, pointer[1], source, way=POINTED)
|
||||||
|
return pointer
|
||||||
|
|
||||||
|
|
||||||
async def _origins(notes, project_id: int | None) -> dict[int, str]:
|
async def _origins(notes, project_id: int | None) -> dict[int, str]:
|
||||||
"""{note id: project title} for the records here from a project other
|
"""{note id: project title} for the records here from a project other
|
||||||
than the session's. Empty with no session project, where every record is
|
than the session's. Empty with no session project, where every record is
|
||||||
@@ -1901,7 +1925,9 @@ async def build_write_path_hint(
|
|||||||
entry.append(f"> ↳ {passage}")
|
entry.append(f"> ↳ {passage}")
|
||||||
parts[-1] = replace(parts[-1], text="\n".join(entry))
|
parts[-1] = replace(parts[-1], text="\n".join(entry))
|
||||||
|
|
||||||
place_pointer = record_kinds.pointer_line({"snippet": placed}, PLACE_POINTER_LEAD)
|
place_pointer = await _point(
|
||||||
|
user_id, {"snippet": placed}, PLACE_POINTER_LEAD, "write_path_place",
|
||||||
|
)
|
||||||
place_named: list[int] = []
|
place_named: list[int] = []
|
||||||
if place_pointer:
|
if place_pointer:
|
||||||
place_named = place_pointer[1]
|
place_named = place_pointer[1]
|
||||||
@@ -1910,15 +1936,13 @@ async def build_write_path_hint(
|
|||||||
text=place_pointer[0], block="pointer",
|
text=place_pointer[0], block="pointer",
|
||||||
ids={hook_payload.NOTE: tuple(place_named)},
|
ids={hook_payload.NOTE: tuple(place_named)},
|
||||||
))
|
))
|
||||||
record_deliveries_svc.record(user_id, place_named, "write_path_place", way=POINTED)
|
|
||||||
|
|
||||||
pointer = record_kinds.pointer_line(pointers, POINTER_LEAD)
|
pointer = await _point(user_id, pointers, POINTER_LEAD, "write_path_pointer")
|
||||||
if pointer:
|
if pointer:
|
||||||
lines.append(pointer[0])
|
lines.append(pointer[0])
|
||||||
parts.append(hook_payload.Part(
|
parts.append(hook_payload.Part(
|
||||||
text=pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(pointer[1])},
|
text=pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(pointer[1])},
|
||||||
))
|
))
|
||||||
record_deliveries_svc.record(user_id, pointer[1], "write_path_pointer", way=POINTED)
|
|
||||||
|
|
||||||
if suggested:
|
if suggested:
|
||||||
lines.append(_suggest_line(path, suggested))
|
lines.append(_suggest_line(path, suggested))
|
||||||
|
|||||||
@@ -301,6 +301,7 @@ async def provisional_row(
|
|||||||
async def _judge(
|
async def _judge(
|
||||||
session, row: CodeShape, *, status: str, snippet_id: int | None,
|
session, row: CodeShape, *, status: str, snippet_id: int | None,
|
||||||
by: str | None, reason: str | None, at: datetime, reason_code: str | None = None,
|
by: str | None, reason: str | None, at: datetime, reason_code: str | None = None,
|
||||||
|
covered_by_id: int | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Apply a judgment to a row — the ONE place a status is set — and write
|
"""Apply a judgment to a row — the ONE place a status is set — and write
|
||||||
its history. Clears what a judgment settles: the standing proposal, the
|
its history. Clears what a judgment settles: the standing proposal, the
|
||||||
@@ -310,6 +311,7 @@ async def _judge(
|
|||||||
withdrawal too."""
|
withdrawal too."""
|
||||||
row.status = status
|
row.status = status
|
||||||
row.snippet_id = snippet_id if status in _NEEDS_TARGET else None
|
row.snippet_id = snippet_id if status in _NEEDS_TARGET else None
|
||||||
|
row.covered_by_id = covered_by_id if status == "redundant" else None
|
||||||
row.reason = (reason or "").strip() or None
|
row.reason = (reason or "").strip() or None
|
||||||
row.reason_code = (reason_code or "").strip() or None
|
row.reason_code = (reason_code or "").strip() or None
|
||||||
row.classified_by = by if status != "unclassified" else None
|
row.classified_by = by if status != "unclassified" else None
|
||||||
@@ -621,12 +623,19 @@ async def live_rows(project_id: int) -> list[CodeShape]:
|
|||||||
|
|
||||||
# Statuses an explicit classification may set. All five: setting a row back to
|
# Statuses an explicit classification may set. All five: setting a row back to
|
||||||
# `unclassified` is how a judgment is deliberately withdrawn.
|
# `unclassified` is how a judgment is deliberately withdrawn.
|
||||||
_SETTABLE = ("canonical", "instance", "variant", "exempt", "unclassified")
|
_SETTABLE = (
|
||||||
|
"canonical", "instance", "variant", "exempt", "redundant", "unused", "unclassified",
|
||||||
|
)
|
||||||
|
# Statuses that are a verdict on the shape itself and take a reason: a
|
||||||
|
# deliberate departure, a one-off, and the two removal verdicts.
|
||||||
|
_NEEDS_REASON = ("variant", "exempt", "redundant", "unused")
|
||||||
|
|
||||||
# Who may appear as the classifier on this path. `hook` and `mechanical` are
|
# Who may appear as the classifier on this path. `hook` and `mechanical` are
|
||||||
# server-internal feeds (steps 5-6) — a caller claiming them would launder a
|
# server-internal feeds (steps 5-6) — a caller claiming them would launder a
|
||||||
# judgment as machinery.
|
# judgment as machinery.
|
||||||
_CALLER_VIAS = ("agent", "audit", "import")
|
_CALLER_VIAS = ("agent", "audit", "import")
|
||||||
|
# The web UI's own judgments, which only the routes may claim.
|
||||||
|
_PERSON_VIA = "person"
|
||||||
|
|
||||||
|
|
||||||
def validate_classifications(items: list[dict]) -> str | None:
|
def validate_classifications(items: list[dict]) -> str | None:
|
||||||
@@ -657,11 +666,21 @@ def validate_classifications(items: list[dict]) -> str | None:
|
|||||||
f"classifications[{i}]: status {status!r} needs snippet_id (or idea_id) — "
|
f"classifications[{i}]: status {status!r} needs snippet_id (or idea_id) — "
|
||||||
"the snippet this shape is (or departs from)"
|
"the snippet this shape is (or departs from)"
|
||||||
)
|
)
|
||||||
if status in ("variant", "exempt") and not (item.get("reason") or "").strip():
|
if status in _NEEDS_REASON and not (item.get("reason") or "").strip():
|
||||||
return (
|
return (
|
||||||
f"classifications[{i}]: status {status!r} needs a reason — "
|
f"classifications[{i}]: status {status!r} needs a reason — "
|
||||||
"the WHY is the record"
|
"the WHY is the record"
|
||||||
)
|
)
|
||||||
|
cover = item.get("covered_by")
|
||||||
|
if status == "redundant":
|
||||||
|
if not isinstance(cover, dict) or not (cover.get("path") or "").strip() \
|
||||||
|
or not (cover.get("symbol") or "").strip():
|
||||||
|
return (
|
||||||
|
f"classifications[{i}]: status 'redundant' needs covered_by "
|
||||||
|
"{path, symbol} — the shape that already does its job"
|
||||||
|
)
|
||||||
|
if (cover["path"].strip(), cover["symbol"].strip()) == (path, symbol):
|
||||||
|
return f"classifications[{i}]: a shape cannot be covered by itself"
|
||||||
code = (item.get("reason_code") or "").strip()
|
code = (item.get("reason_code") or "").strip()
|
||||||
if code and code not in REASON_CODES:
|
if code and code not in REASON_CODES:
|
||||||
return (
|
return (
|
||||||
@@ -708,7 +727,7 @@ async def classify_shapes(
|
|||||||
from grimoire.services import access
|
from grimoire.services import access
|
||||||
from grimoire.services import snippets as snippets_svc
|
from grimoire.services import snippets as snippets_svc
|
||||||
|
|
||||||
if via not in _CALLER_VIAS:
|
if via not in _CALLER_VIAS and via != _PERSON_VIA:
|
||||||
raise ValueError(f"via must be one of: {', '.join(_CALLER_VIAS)}")
|
raise ValueError(f"via must be one of: {', '.join(_CALLER_VIAS)}")
|
||||||
classifications = await _resolve_ideas(user_id, classifications)
|
classifications = await _resolve_ideas(user_id, classifications)
|
||||||
error = validate_classifications(classifications)
|
error = validate_classifications(classifications)
|
||||||
@@ -779,13 +798,27 @@ async def classify_shapes(
|
|||||||
})
|
})
|
||||||
continue
|
continue
|
||||||
status = item["status"]
|
status = item["status"]
|
||||||
|
cover_id = None
|
||||||
|
if status == "redundant":
|
||||||
|
# The cover is a live row of this project, resolved exactly
|
||||||
|
# like the shape being judged; a cover no row matches is an
|
||||||
|
# error, because a redundant verdict without its cover is the
|
||||||
|
# one claim nobody can check.
|
||||||
|
cover = item["covered_by"]
|
||||||
|
covers = by_key.get((cover["path"].strip(), cover["symbol"].strip())) or []
|
||||||
|
if not covers:
|
||||||
|
raise ValueError(
|
||||||
|
f"covered_by {cover['path']}::{cover['symbol']} matches no live shape "
|
||||||
|
f"in project {project_id}"
|
||||||
|
)
|
||||||
|
cover_id = covers[0].id
|
||||||
for row in matches:
|
for row in matches:
|
||||||
touched.update(x for x in (row.snippet_id, item.get("snippet_id")) if x)
|
touched.update(x for x in (row.snippet_id, item.get("snippet_id")) if x)
|
||||||
await _judge(
|
await _judge(
|
||||||
session, row, status=status,
|
session, row, status=status,
|
||||||
snippet_id=int(item["snippet_id"]) if status in _NEEDS_TARGET else None,
|
snippet_id=int(item["snippet_id"]) if status in _NEEDS_TARGET else None,
|
||||||
by=via, reason=item.get("reason"), at=now,
|
by=via, reason=item.get("reason"), at=now,
|
||||||
reason_code=item.get("reason_code"),
|
reason_code=item.get("reason_code"), covered_by_id=cover_id,
|
||||||
)
|
)
|
||||||
if item.get("uses"):
|
if item.get("uses"):
|
||||||
await record_uses(session, row, item["uses"], basis=via,
|
await record_uses(session, row, item["uses"], basis=via,
|
||||||
@@ -3002,8 +3035,15 @@ async def unjudged_shapes(
|
|||||||
async with async_session() as session:
|
async with async_session() as session:
|
||||||
rows = (await session.execute(query)).scalars().all()
|
rows = (await session.execute(query)).scalars().all()
|
||||||
by_key = {(r.path, r.kind, r.symbol): r for r in rows}
|
by_key = {(r.path, r.kind, r.symbol): r for r in rows}
|
||||||
|
from grimoire.services.test_guards import is_test_case
|
||||||
|
|
||||||
out: list[dict] = []
|
out: list[dict] = []
|
||||||
for path, kind, name in wanted:
|
for path, kind, name in wanted:
|
||||||
|
# A test case is accounted for by what it guards: the refresh links
|
||||||
|
# it and stamps it `test`, so the writer is not asked to call it a
|
||||||
|
# one-off.
|
||||||
|
if is_test_case(path, name, kind):
|
||||||
|
continue
|
||||||
row = by_key.get((path, kind, name))
|
row = by_key.get((path, kind, name))
|
||||||
if row is not None and _is_judged(row):
|
if row is not None and _is_judged(row):
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -0,0 +1,600 @@
|
|||||||
|
"""What each test guards — read from the repo, without running anything.
|
||||||
|
|
||||||
|
The shape ledger accounts for every definition in a bound repo; this module
|
||||||
|
adds the one relation a test suite needs and nothing else in the ledger
|
||||||
|
says: which product shapes a test exercises. With it the ledger can show
|
||||||
|
tests that guard exactly the same thing from different files — candidates
|
||||||
|
for a merge or a removal — and give each a verdict (`redundant`, naming the
|
||||||
|
test that covers it, or `unused`) the same way it judges any other shape.
|
||||||
|
|
||||||
|
Grimoire runs no tests and owns no test runner, so the link is read
|
||||||
|
statically from the archive the coverage refresh already walks, language by
|
||||||
|
the same regex extractor the ledger uses:
|
||||||
|
|
||||||
|
- **A test** is a definition in a test file (see `is_test_path`) whose name
|
||||||
|
starts with `test` in any case: Python's `test_*`, Go's `Test*`, a JUnit
|
||||||
|
or xUnit `test*` method. A test file whose cases are calls rather than
|
||||||
|
definitions (`it(...)` in a JS/TS spec) yields no test shapes here;
|
||||||
|
its links are by path, through the files it reads.
|
||||||
|
- **What it reaches**: every identifier in its body, strings and comments
|
||||||
|
blanked, that names a product definition (a non-test file) — directly,
|
||||||
|
or through a helper defined in a test file, followed transitively.
|
||||||
|
Strings are blanked so a patch target (`patch("pkg.mod.name")`,
|
||||||
|
`patch.object(mod, "name")`) does not count: a mocked function is the
|
||||||
|
one thing the test does NOT exercise.
|
||||||
|
- **Resolution** needs the test file to name the defining module: its
|
||||||
|
file stem (`plugin_context`, `format`), or for a package file (`__init__`,
|
||||||
|
`index`, `mod`, any Go file) its directory. A bare name match is not
|
||||||
|
enough — `get` and `run` are defined somewhere in every repo, and every
|
||||||
|
test calls something with those names.
|
||||||
|
- **Hubs** — the session factory, the user model — are reached from a
|
||||||
|
large share of test files, so they say nothing about what one test
|
||||||
|
guards; they are dropped before grouping.
|
||||||
|
- **Paths**: a string literal in the body naming a repo file (exactly, or
|
||||||
|
by a basename unique in the repo) links the test to that file — how a
|
||||||
|
test that reads source text, or runs a script, says what it guards.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import re
|
||||||
|
from collections import defaultdict
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Iterable, NamedTuple
|
||||||
|
|
||||||
|
# Directory names that hold tests, in the conventions the ledger meets.
|
||||||
|
_TEST_DIRS = frozenset({"tests", "test", "__tests__", "spec", "specs", "testing"})
|
||||||
|
# File names that are tests wherever they live.
|
||||||
|
_TEST_FILE_RE = re.compile(
|
||||||
|
r"(?:^test_.+|.+_test|.+[._-](?:test|spec)|.+Tests?|.+Spec)\.[A-Za-z0-9]+$"
|
||||||
|
)
|
||||||
|
_TEST_NAME_RE = re.compile(r"^test", re.IGNORECASE)
|
||||||
|
_IDENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
||||||
|
_STR_RE = re.compile(r"""'([^'\\\n]*)'|"([^"\\\n]*)"|`([^`]*)`""")
|
||||||
|
# A file whose module is its directory rather than its own name.
|
||||||
|
_PACKAGE_STEMS = frozenset({"__init__", "index", "mod", "main", "lib"})
|
||||||
|
|
||||||
|
# A guarded shape reached from at least this share of the repo's linked
|
||||||
|
# test files (and at least _HUB_MIN_FILES of them) is infrastructure, not a
|
||||||
|
# subject. Measured on Grimoire's own suite: the session factory, the user
|
||||||
|
# and project models and a few fixtures sit far above it, and the busiest
|
||||||
|
# genuine subject below.
|
||||||
|
_HUB_SHARE = 0.08
|
||||||
|
_HUB_MIN_FILES = 8
|
||||||
|
|
||||||
|
# Weak-test signals: evidence a reviewer reads beside a group, never a
|
||||||
|
# verdict. Each is a regex over the test's own body.
|
||||||
|
SIGNALS = {
|
||||||
|
# The test pins how the code is declared rather than what it does.
|
||||||
|
"signature": re.compile(r"\binspect\.signature\(|\bgetfullargspec\(|\breflect\.TypeOf\("),
|
||||||
|
# The test reads source text.
|
||||||
|
"source-text": re.compile(
|
||||||
|
r"\.read_text\(|\breadFileSync\(|\bos\.ReadFile\(|\.rglob\(|\bast\.parse\("
|
||||||
|
),
|
||||||
|
}
|
||||||
|
_MOCK_ASSERT_RE = re.compile(
|
||||||
|
r"\.assert_(?:called|awaited|not_called|not_awaited|any_call|has_calls)\w*\(|toHaveBeenCalled"
|
||||||
|
)
|
||||||
|
_PLAIN_ASSERT_RE = re.compile(r"^\s*assert\b|\bexpect\((?![^\n]*toHaveBeenCalled)", re.MULTILINE)
|
||||||
|
|
||||||
|
|
||||||
|
def is_test_path(path: str) -> bool:
|
||||||
|
"""Is this repo file part of a test suite?"""
|
||||||
|
parts = path.split("/")
|
||||||
|
if any(p in _TEST_DIRS for p in parts[:-1]):
|
||||||
|
return True
|
||||||
|
return bool(_TEST_FILE_RE.match(parts[-1]))
|
||||||
|
|
||||||
|
|
||||||
|
def is_test_name(name: str) -> bool:
|
||||||
|
return bool(_TEST_NAME_RE.match(name))
|
||||||
|
|
||||||
|
|
||||||
|
# A spec written as calls — `it("…", …)`, `test("…", …)` — defines no
|
||||||
|
# test-named function, so the file is the unit: one ledger row per spec.
|
||||||
|
_TEST_CALL_RE = re.compile(r"^\s*(?:it|test)(?:\.\w+)?\s*\(", re.MULTILINE)
|
||||||
|
|
||||||
|
|
||||||
|
def is_call_style_spec(path: str, text: str, names: Iterable[str]) -> bool:
|
||||||
|
"""A test file whose cases are calls, not definitions."""
|
||||||
|
return (
|
||||||
|
is_test_path(path)
|
||||||
|
and not any(is_test_name(n) for n in names)
|
||||||
|
and _TEST_CALL_RE.search(text) is not None
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def is_test_case(path: str, symbol: str, kind: str) -> bool:
|
||||||
|
"""Is this ledger row a test case: a test-named definition in a test
|
||||||
|
file, or a call-style spec file's own row?"""
|
||||||
|
if not is_test_path(path):
|
||||||
|
return False
|
||||||
|
return kind == "file" or (kind == "sym" and is_test_name(symbol))
|
||||||
|
|
||||||
|
|
||||||
|
def test_signals(body: str) -> list[str]:
|
||||||
|
"""The weak-test signals a test's body shows, sorted."""
|
||||||
|
out = [name for name, rx in SIGNALS.items() if rx.search(body)]
|
||||||
|
if _MOCK_ASSERT_RE.search(body) and not _PLAIN_ASSERT_RE.search(body):
|
||||||
|
out.append("mock-only")
|
||||||
|
return sorted(out)
|
||||||
|
|
||||||
|
|
||||||
|
def file_tokens(text: str) -> frozenset[str]:
|
||||||
|
"""Every identifier in a file, strings included: how a test file names
|
||||||
|
the modules it imports (`from pkg.services import x`,
|
||||||
|
`import { y } from '../lib/format'`)."""
|
||||||
|
return frozenset(_IDENT_RE.findall(text))
|
||||||
|
|
||||||
|
|
||||||
|
_REF_RE = re.compile(r"(?:\b([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*)?\b([A-Za-z_][A-Za-z0-9_]*)")
|
||||||
|
# `from pkg import mod as m` / `import pkg.mod as m` / `import * as m from '…/mod'`.
|
||||||
|
_PY_ALIAS_RE = re.compile(r"\b([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)")
|
||||||
|
_JS_ALIAS_RE = re.compile(
|
||||||
|
r"\bas\s+([A-Za-z_$][\w$]*)\s+from\s+['\"][^'\"]*?([A-Za-z_][\w-]*)(?:\.[a-z]+)?['\"]"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# An import statement: Python's `import a.b` / `from a.b import (x, y)`
|
||||||
|
# (parenthesised lists span lines), JS/TS `import … from '…'`, a CommonJS
|
||||||
|
# `require('…')`. Indented ones count — a test may import inside its body.
|
||||||
|
_IMPORT_RE = re.compile(
|
||||||
|
r"^[ \t]*(?:from[ \t]+[\w.]+[ \t]+import[ \t]*(?:\([^)]*\)|[^\n]*)"
|
||||||
|
r"|import[ \t]+(?:[^\n;]*?from[ \t]*['\"][^'\"]+['\"]|\{[^}]*\}[^\n]*|[^\n]*))"
|
||||||
|
r"|\brequire\(\s*['\"][^'\"]+['\"]\s*\)",
|
||||||
|
re.MULTILINE,
|
||||||
|
)
|
||||||
|
# What a mock replaces: `patch("pkg.mod.name")`, `patch.object(mod, "name")`,
|
||||||
|
# `monkeypatch.setattr(mod, "name", …)`. The named function is the one thing
|
||||||
|
# the test does not exercise.
|
||||||
|
_PATCHED_RE = re.compile(
|
||||||
|
r"\b(?:patch(?:\.object)?|setattr)\(\s*(?:[\w.]+\s*,\s*)?['\"]([\w.]+)['\"]"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def module_aliases(text: str) -> dict[str, str]:
|
||||||
|
"""{alias: module name} a test file binds: `pc` → `plugin_context`."""
|
||||||
|
out = {alias: name for name, alias in _PY_ALIAS_RE.findall(text)}
|
||||||
|
out.update({alias: name for alias, name in _JS_ALIAS_RE.findall(text)})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def imported_names(text: str) -> frozenset[str]:
|
||||||
|
"""Every identifier in a file's import statements — the names it
|
||||||
|
imports and the module paths it imports them from."""
|
||||||
|
return frozenset(
|
||||||
|
tok for stmt in _IMPORT_RE.findall(text) for tok in _IDENT_RE.findall(stmt)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def patched_names(body: str) -> set[str]:
|
||||||
|
"""The names a body mocks out, by their last dotted segment."""
|
||||||
|
return {target.rsplit(".", 1)[-1] for target in _PATCHED_RE.findall(body)}
|
||||||
|
|
||||||
|
|
||||||
|
def references(body: str) -> list[tuple[str, str]]:
|
||||||
|
"""(qualifier, name) for every identifier in a masked body: `pc.run`
|
||||||
|
gives ("pc", "run"), a bare `run` gives ("", "run")."""
|
||||||
|
return [(q or "", n) for q, n in _REF_RE.findall(body)]
|
||||||
|
|
||||||
|
|
||||||
|
def _stem(path: str) -> str:
|
||||||
|
return path.rsplit("/", 1)[-1].rsplit(".", 1)[0]
|
||||||
|
|
||||||
|
|
||||||
|
def _module_names(path: str) -> tuple[str, ...]:
|
||||||
|
"""The names a test file uses for the module defined at `path`."""
|
||||||
|
stem = _stem(path)
|
||||||
|
parent = path.rsplit("/", 2)[-2] if path.count("/") >= 1 else ""
|
||||||
|
if stem in _PACKAGE_STEMS or path.endswith(".go"):
|
||||||
|
return (parent,) if parent else ()
|
||||||
|
return (stem,)
|
||||||
|
|
||||||
|
|
||||||
|
class Def(NamedTuple):
|
||||||
|
path: str
|
||||||
|
name: str
|
||||||
|
body: str
|
||||||
|
|
||||||
|
|
||||||
|
class Links(NamedTuple):
|
||||||
|
"""One repo's guard links, keyed by (path, name) of the test."""
|
||||||
|
|
||||||
|
shapes: dict[tuple[str, str], set[tuple[str, str]]] # test → guarded (path, name)
|
||||||
|
paths: dict[tuple[str, str], set[str]] # test → repo files named
|
||||||
|
signals: dict[tuple[str, str], list[str]] # test → weak signals
|
||||||
|
hubs: set[tuple[str, str]] # guarded shapes dropped as hubs
|
||||||
|
|
||||||
|
|
||||||
|
class TestFile(NamedTuple):
|
||||||
|
"""What resolution needs from a test file: the identifiers in its
|
||||||
|
import statements (`imported_names`) and the module aliases it binds
|
||||||
|
(`module_aliases`)."""
|
||||||
|
|
||||||
|
tokens: frozenset[str]
|
||||||
|
aliases: dict[str, str]
|
||||||
|
|
||||||
|
|
||||||
|
def read_test_file(text: str) -> TestFile:
|
||||||
|
return TestFile(imported_names(text), module_aliases(text))
|
||||||
|
|
||||||
|
|
||||||
|
def _same_package(test_path: str, path: str) -> bool:
|
||||||
|
"""A Go test shares its package with the code beside it, and calls it
|
||||||
|
unqualified with no import."""
|
||||||
|
return (
|
||||||
|
test_path.endswith(".go") and path.endswith(".go")
|
||||||
|
and test_path.rsplit("/", 1)[0] == path.rsplit("/", 1)[0]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def link_tests(
|
||||||
|
defs: Iterable[Def],
|
||||||
|
files: dict[str, TestFile],
|
||||||
|
repo_paths: Iterable[str] = (),
|
||||||
|
*,
|
||||||
|
file_tests: Iterable[Def] = (),
|
||||||
|
blank=None,
|
||||||
|
) -> Links:
|
||||||
|
"""Link each test in a repo to what it guards. Pure: `defs` are the
|
||||||
|
repo's symbol definitions with their bodies, `files` each test file read
|
||||||
|
by `read_test_file`, `repo_paths` every file in the tree. `blank` masks
|
||||||
|
strings and comments out of a body; it defaults to the coverage
|
||||||
|
extractor's own pass so the two read code the same way. `file_tests`
|
||||||
|
are call-style spec files, each a test whose body is the whole file.
|
||||||
|
|
||||||
|
A qualified reference `q.name` counts only when `q` is the defining
|
||||||
|
module, by name or through an alias the file binds (`pc` for
|
||||||
|
`plugin_context`): `subprocess.run` and `row.moment` are calls on
|
||||||
|
something else that happens to share a product name. A bare `name`
|
||||||
|
counts when the file imports it from the defining module (or, in Go,
|
||||||
|
shares the defining file's package) and does not define `name` itself.
|
||||||
|
A name the body mocks out does not count either way."""
|
||||||
|
if blank is None:
|
||||||
|
from grimoire.services.coverage import _blank_spans as blank
|
||||||
|
|
||||||
|
product: dict[str, list[str]] = defaultdict(list) # name → defining paths
|
||||||
|
helpers: dict[str, list[Def]] = defaultdict(list) # name → test-file defs
|
||||||
|
tests: list[Def] = []
|
||||||
|
for d in defs:
|
||||||
|
if is_test_path(d.path):
|
||||||
|
helpers[d.name].append(d)
|
||||||
|
if is_test_name(d.name):
|
||||||
|
tests.append(d)
|
||||||
|
else:
|
||||||
|
product[d.name].append(d.path)
|
||||||
|
for d in file_tests:
|
||||||
|
helpers[d.name].append(d)
|
||||||
|
tests.append(d)
|
||||||
|
|
||||||
|
own_names: dict[str, set[str]] = defaultdict(set) # test file → names it defines
|
||||||
|
for name, ds in helpers.items():
|
||||||
|
for d in ds:
|
||||||
|
own_names[d.path].add(name)
|
||||||
|
empty = TestFile(frozenset(), {})
|
||||||
|
|
||||||
|
def resolve(
|
||||||
|
refs: list[tuple[str, str]], f: TestFile, local: set[str], test_path: str,
|
||||||
|
) -> set[tuple[str, str]]:
|
||||||
|
out: set[tuple[str, str]] = set()
|
||||||
|
for qual, name in refs:
|
||||||
|
if not qual and name in local:
|
||||||
|
continue
|
||||||
|
for path in product.get(name, ()):
|
||||||
|
mods = _module_names(path)
|
||||||
|
if qual:
|
||||||
|
ok = qual in mods or f.aliases.get(qual) in mods
|
||||||
|
else:
|
||||||
|
ok = _same_package(test_path, path) or (
|
||||||
|
name in f.tokens and any(m in f.tokens for m in mods)
|
||||||
|
)
|
||||||
|
if ok:
|
||||||
|
out.add((path, name))
|
||||||
|
return out
|
||||||
|
|
||||||
|
# Direct reach and helper calls of every test-file definition.
|
||||||
|
direct: dict[tuple[str, str], set[tuple[str, str]]] = {}
|
||||||
|
calls: dict[tuple[str, str], set[tuple[str, str]]] = {}
|
||||||
|
for name, ds in helpers.items():
|
||||||
|
for d in ds:
|
||||||
|
key = (d.path, d.name)
|
||||||
|
if key in direct:
|
||||||
|
continue
|
||||||
|
mocked = patched_names(d.body)
|
||||||
|
refs = [r for r in references(blank(d.body)) if r[1] != d.name]
|
||||||
|
f = files.get(d.path, empty)
|
||||||
|
direct[key] = {
|
||||||
|
g for g in resolve(refs, f, own_names[d.path], d.path) if g[1] not in mocked
|
||||||
|
}
|
||||||
|
called: set[tuple[str, str]] = set()
|
||||||
|
for qual, t in refs:
|
||||||
|
cands = helpers.get(t)
|
||||||
|
if not cands:
|
||||||
|
continue
|
||||||
|
own = [c for c in cands if c.path == d.path and not qual]
|
||||||
|
named = [
|
||||||
|
c for c in cands
|
||||||
|
if (qual and (qual in _module_names(c.path)
|
||||||
|
or f.aliases.get(qual) in _module_names(c.path)))
|
||||||
|
or (not qual and any(m in f.tokens for m in _module_names(c.path)))
|
||||||
|
]
|
||||||
|
pick = own or named or (cands if len(cands) == 1 and not qual else [])
|
||||||
|
called.update((c.path, c.name) for c in pick)
|
||||||
|
calls[key] = called
|
||||||
|
|
||||||
|
def closure(key: tuple[str, str]) -> set[tuple[str, str]]:
|
||||||
|
seen, stack, out = {key}, [key], set()
|
||||||
|
while stack:
|
||||||
|
k = stack.pop()
|
||||||
|
out |= direct.get(k, set())
|
||||||
|
for c in calls.get(k, ()):
|
||||||
|
if c not in seen and not is_test_name(c[1]):
|
||||||
|
seen.add(c)
|
||||||
|
stack.append(c)
|
||||||
|
return out
|
||||||
|
|
||||||
|
reach = {(t.path, t.name): closure((t.path, t.name)) for t in tests}
|
||||||
|
|
||||||
|
# Hubs: guarded shapes reached from a large share of linked test files.
|
||||||
|
files_per: dict[tuple[str, str], set[str]] = defaultdict(set)
|
||||||
|
for (path, _name), guarded in reach.items():
|
||||||
|
for g in guarded:
|
||||||
|
files_per[g].add(path)
|
||||||
|
linked_files = {p for (p, _n), g in reach.items() if g}
|
||||||
|
bar = max(_HUB_MIN_FILES, _HUB_SHARE * len(linked_files))
|
||||||
|
hubs = {g for g, files in files_per.items() if len(files) >= bar}
|
||||||
|
shapes = {k: g - hubs for k, g in reach.items()}
|
||||||
|
|
||||||
|
# Paths: string literals that name a repo file.
|
||||||
|
all_paths = set(repo_paths)
|
||||||
|
by_base: dict[str, list[str]] = defaultdict(list)
|
||||||
|
for p in all_paths:
|
||||||
|
by_base[p.rsplit("/", 1)[-1]].append(p)
|
||||||
|
path_links: dict[tuple[str, str], set[str]] = {}
|
||||||
|
signals: dict[tuple[str, str], list[str]] = {}
|
||||||
|
for t in tests:
|
||||||
|
key = (t.path, t.name)
|
||||||
|
named: set[str] = set()
|
||||||
|
for m in _STR_RE.finditer(t.body):
|
||||||
|
lit = next(g for g in m.groups() if g is not None).strip().lstrip("./")
|
||||||
|
if not lit or " " in lit or "." not in lit:
|
||||||
|
continue
|
||||||
|
if lit in all_paths:
|
||||||
|
named.add(lit)
|
||||||
|
elif "/" not in lit and len(by_base.get(lit, ())) == 1:
|
||||||
|
named.add(by_base[lit][0])
|
||||||
|
path_links[key] = named
|
||||||
|
signals[key] = test_signals(t.body)
|
||||||
|
return Links(shapes, path_links, signals, hubs)
|
||||||
|
|
||||||
|
|
||||||
|
def group_key(members: Iterable[tuple[str, str]]) -> str:
|
||||||
|
"""A group's identity: its member tests by (path, symbol). A test joining
|
||||||
|
or leaving makes a new group, so a review of the old one does not silence
|
||||||
|
the new; names rather than row ids, so a review survives a restore."""
|
||||||
|
joined = "\n".join(sorted(f"{p}::{s}" for p, s in set(members)))
|
||||||
|
return hashlib.sha1(joined.encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def same_guard_groups(
|
||||||
|
tests: Iterable[tuple[int, str, frozenset[int]]],
|
||||||
|
) -> list[tuple[frozenset[int], list[int]]]:
|
||||||
|
"""Tests that guard exactly the same non-empty set of shapes from more
|
||||||
|
than one file: `tests` are (test shape id, path, guarded shape ids).
|
||||||
|
Within one file a shared subject is a table of cases, so a group must
|
||||||
|
span files. Largest first."""
|
||||||
|
by_set: dict[frozenset[int], list[tuple[int, str]]] = defaultdict(list)
|
||||||
|
for tid, path, guarded in tests:
|
||||||
|
if guarded:
|
||||||
|
by_set[guarded].append((tid, path))
|
||||||
|
out = [
|
||||||
|
(guarded, sorted(tid for tid, _p in members))
|
||||||
|
for guarded, members in by_set.items()
|
||||||
|
if len({p for _t, p in members}) > 1
|
||||||
|
]
|
||||||
|
out.sort(key=lambda g: (-len(g[1]), g[1][0]))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# --- the ledger side ---------------------------------------------------------
|
||||||
|
|
||||||
|
# Statuses whose test has had its verdict: it leaves every group.
|
||||||
|
_SETTLED = ("redundant", "unused")
|
||||||
|
_TEST_REASON = (
|
||||||
|
"a test case linked to what it guards (stamped by the coverage sync); "
|
||||||
|
"test_guard_groups lists the ones guarding the same thing"
|
||||||
|
)
|
||||||
|
# How many groups a readout carries; the count says how many there are.
|
||||||
|
GROUPS_SHOWN = 25
|
||||||
|
|
||||||
|
|
||||||
|
async def sync_repo_guards(project_id: int, repo_key: str, links: Links) -> int:
|
||||||
|
"""Rebuild one repo's guard edges and test signals from `links`. Edges
|
||||||
|
hang on live rows only, like the consumer map, and are replaced whole
|
||||||
|
each sync. Returns how many edges stand afterwards."""
|
||||||
|
from sqlalchemy import delete, select
|
||||||
|
|
||||||
|
from grimoire.models import async_session
|
||||||
|
from grimoire.models.code_shape import CodeShape, CodeShapeGuard
|
||||||
|
|
||||||
|
async with async_session() as session:
|
||||||
|
rows = (await session.execute(
|
||||||
|
select(CodeShape).where(
|
||||||
|
CodeShape.project_id == project_id,
|
||||||
|
CodeShape.repo_key == repo_key,
|
||||||
|
CodeShape.vanished_at.is_(None),
|
||||||
|
)
|
||||||
|
)).scalars().all()
|
||||||
|
ids = {(r.path, r.symbol): r.id for r in rows if r.kind in ("sym", "file")}
|
||||||
|
by_key = {(r.path, r.symbol): r for r in rows if r.kind in ("sym", "file")}
|
||||||
|
all_ids = [r.id for r in rows]
|
||||||
|
if all_ids:
|
||||||
|
await session.execute(delete(CodeShapeGuard).where(CodeShapeGuard.test_id.in_(all_ids)))
|
||||||
|
edges = 0
|
||||||
|
for key, guarded in links.shapes.items():
|
||||||
|
tid = ids.get(key)
|
||||||
|
if tid is None:
|
||||||
|
continue
|
||||||
|
for g in guarded:
|
||||||
|
gid = ids.get(g)
|
||||||
|
if gid is not None:
|
||||||
|
session.add(CodeShapeGuard(test_id=tid, guarded_id=gid, basis="static"))
|
||||||
|
edges += 1
|
||||||
|
for path in links.paths.get(key, ()):
|
||||||
|
session.add(CodeShapeGuard(test_id=tid, path=path, basis="static"))
|
||||||
|
edges += 1
|
||||||
|
for r in rows:
|
||||||
|
sig = ",".join(links.signals.get((r.path, r.symbol), ())) if r.kind in ("sym", "file") else ""
|
||||||
|
if (r.test_signals or "") != sig:
|
||||||
|
r.test_signals = sig
|
||||||
|
# The `test` stamp follows the links: on while a test case guards
|
||||||
|
# something, withdrawn when it guards nothing, never over a judgment.
|
||||||
|
from grimoire.services.shape_ledger import _judge
|
||||||
|
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
for key, guarded in links.shapes.items():
|
||||||
|
row = by_key.get(key)
|
||||||
|
if row is None:
|
||||||
|
continue
|
||||||
|
linked = bool(guarded) or bool(links.paths.get(key))
|
||||||
|
if linked and row.status == "unclassified":
|
||||||
|
await _judge(session, row, status="test", snippet_id=None,
|
||||||
|
by="mechanical", reason=_TEST_REASON, at=now)
|
||||||
|
elif not linked and row.status == "test":
|
||||||
|
await _judge(session, row, status="unclassified", snippet_id=None,
|
||||||
|
by=None, reason=None, at=now)
|
||||||
|
await session.commit()
|
||||||
|
return edges
|
||||||
|
|
||||||
|
|
||||||
|
async def test_summary(project_id: int) -> dict:
|
||||||
|
"""{linked, unlinked, redundant} over a project's live test cases: linked
|
||||||
|
to something they guard, linked to nothing, judged redundant."""
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from grimoire.models import async_session
|
||||||
|
from grimoire.models.code_shape import CodeShape, CodeShapeGuard
|
||||||
|
|
||||||
|
async with async_session() as session:
|
||||||
|
rows = (await session.execute(
|
||||||
|
select(CodeShape.id, CodeShape.path, CodeShape.symbol, CodeShape.kind, CodeShape.status)
|
||||||
|
.where(CodeShape.project_id == project_id, CodeShape.vanished_at.is_(None))
|
||||||
|
)).all()
|
||||||
|
cases = {r[0]: r for r in rows if is_test_case(r[1], r[2], r[3])}
|
||||||
|
guarded = set((await session.execute(
|
||||||
|
select(CodeShapeGuard.test_id).where(CodeShapeGuard.test_id.in_(list(cases)))
|
||||||
|
)).scalars().all()) if cases else set()
|
||||||
|
out = {"linked": 0, "unlinked": 0, "redundant": 0}
|
||||||
|
for tid, r in cases.items():
|
||||||
|
if r[4] == "redundant":
|
||||||
|
out["redundant"] += 1
|
||||||
|
elif tid in guarded:
|
||||||
|
out["linked"] += 1
|
||||||
|
else:
|
||||||
|
out["unlinked"] += 1
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _shape_ref(row) -> dict:
|
||||||
|
return {"id": row.id, "path": row.path, "symbol": row.symbol}
|
||||||
|
|
||||||
|
|
||||||
|
async def guard_groups(project_id: int, *, top: int = GROUPS_SHOWN) -> dict:
|
||||||
|
"""Tests that guard exactly the same shapes from more than one file, and
|
||||||
|
have not been reviewed as distinct: {"count", "groups": [...]}, largest
|
||||||
|
first. Each group carries what its tests guard and, per test, its weak
|
||||||
|
signals, status and the key a review is recorded under."""
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from grimoire.models import async_session
|
||||||
|
from grimoire.models.code_shape import CodeShape, CodeShapeGuard, CodeShapeGuardReview
|
||||||
|
|
||||||
|
async with async_session() as session:
|
||||||
|
rows = (await session.execute(
|
||||||
|
select(CodeShape).where(
|
||||||
|
CodeShape.project_id == project_id, CodeShape.vanished_at.is_(None),
|
||||||
|
)
|
||||||
|
)).scalars().all()
|
||||||
|
by_id = {r.id: r for r in rows}
|
||||||
|
edges = (await session.execute(
|
||||||
|
select(CodeShapeGuard.test_id, CodeShapeGuard.guarded_id).where(
|
||||||
|
CodeShapeGuard.test_id.in_(list(by_id)),
|
||||||
|
CodeShapeGuard.guarded_id.is_not(None),
|
||||||
|
)
|
||||||
|
)).all() if by_id else []
|
||||||
|
reviewed = set((await session.execute(
|
||||||
|
select(CodeShapeGuardReview.group_key).where(
|
||||||
|
CodeShapeGuardReview.project_id == project_id,
|
||||||
|
)
|
||||||
|
)).scalars().all())
|
||||||
|
guarded: dict[int, set[int]] = defaultdict(set)
|
||||||
|
for tid, gid in edges:
|
||||||
|
if gid in by_id:
|
||||||
|
guarded[tid].add(gid)
|
||||||
|
tests = [
|
||||||
|
(tid, by_id[tid].path, frozenset(g))
|
||||||
|
for tid, g in guarded.items()
|
||||||
|
if by_id[tid].status not in _SETTLED
|
||||||
|
]
|
||||||
|
out = []
|
||||||
|
for g, members in same_guard_groups(tests):
|
||||||
|
key = group_key((by_id[t].path, by_id[t].symbol) for t in members)
|
||||||
|
if key in reviewed:
|
||||||
|
continue
|
||||||
|
out.append({
|
||||||
|
"key": key,
|
||||||
|
"guards": sorted((_shape_ref(by_id[x]) for x in g), key=lambda d: (d["path"], d["symbol"])),
|
||||||
|
"tests": [
|
||||||
|
{**_shape_ref(by_id[t]), "status": by_id[t].status,
|
||||||
|
"signals": [x for x in (by_id[t].test_signals or "").split(",") if x]}
|
||||||
|
for t in members
|
||||||
|
],
|
||||||
|
})
|
||||||
|
return {"count": len(out), "groups": out[:top] if top else []}
|
||||||
|
|
||||||
|
|
||||||
|
async def review_group(
|
||||||
|
user_id: int, project_id: int, test_ids: list[int], *, reason: str, by: str,
|
||||||
|
) -> dict:
|
||||||
|
"""Record that a group's tests guard distinct behaviours and all stay.
|
||||||
|
The group is named by its members; a test joining or leaving it later
|
||||||
|
puts it back in the readout."""
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from grimoire.models import async_session
|
||||||
|
from grimoire.models.code_shape import CodeShape, CodeShapeGuardReview
|
||||||
|
from grimoire.services import access
|
||||||
|
|
||||||
|
reason = (reason or "").strip()
|
||||||
|
if not reason:
|
||||||
|
raise ValueError("a review needs a reason — what each test guards that the others do not")
|
||||||
|
ids = sorted({int(t) for t in test_ids or []})
|
||||||
|
if len(ids) < 2:
|
||||||
|
raise ValueError("a group has at least two tests")
|
||||||
|
if not await access.can_write_project(user_id, project_id):
|
||||||
|
raise ValueError(f"project {project_id} not found or no write access")
|
||||||
|
async with async_session() as session:
|
||||||
|
rows = (await session.execute(
|
||||||
|
select(CodeShape).where(
|
||||||
|
CodeShape.project_id == project_id, CodeShape.id.in_(ids),
|
||||||
|
CodeShape.vanished_at.is_(None),
|
||||||
|
)
|
||||||
|
)).scalars().all()
|
||||||
|
if len(rows) != len(ids):
|
||||||
|
missing = sorted(set(ids) - {r.id for r in rows})
|
||||||
|
raise ValueError(f"no live shape in project {project_id} has id(s) {missing}")
|
||||||
|
key = group_key((r.path, r.symbol) for r in rows)
|
||||||
|
existing = (await session.execute(
|
||||||
|
select(CodeShapeGuardReview).where(
|
||||||
|
CodeShapeGuardReview.project_id == project_id,
|
||||||
|
CodeShapeGuardReview.group_key == key,
|
||||||
|
)
|
||||||
|
)).scalar_one_or_none()
|
||||||
|
review = existing or CodeShapeGuardReview(project_id=project_id, group_key=key)
|
||||||
|
review.verdict = "distinct"
|
||||||
|
review.reason = reason
|
||||||
|
review.reviewed_by = by
|
||||||
|
if existing is None:
|
||||||
|
session.add(review)
|
||||||
|
await session.commit()
|
||||||
|
return review.to_dict()
|
||||||
@@ -103,6 +103,7 @@ WRITE_TARGETS: dict[str, dict[str, str]] = {
|
|||||||
"confirm_shape_proposals": {"project_id": PROJECT},
|
"confirm_shape_proposals": {"project_id": PROJECT},
|
||||||
"refresh_pattern_coverage": {"project_id": PROJECT},
|
"refresh_pattern_coverage": {"project_id": PROJECT},
|
||||||
"move_path": {"project_id": PROJECT},
|
"move_path": {"project_id": PROJECT},
|
||||||
|
"review_test_group": {"project_id": PROJECT},
|
||||||
# design systems belong to their owner, not to a project; choosing one for
|
# design systems belong to their owner, not to a project; choosing one for
|
||||||
# a project is that project's write.
|
# a project is that project's write.
|
||||||
"create_design_system": {},
|
"create_design_system": {},
|
||||||
|
|||||||
@@ -308,6 +308,14 @@ TOPICS: tuple[Topic, ...] = (
|
|||||||
("family_hint", "get_family_adoption", "resolve_family_conflict", "precedent"),
|
("family_hint", "get_family_adoption", "resolve_family_conflict", "precedent"),
|
||||||
"write the reason so a session in another project can tell whether the same fact holds there",
|
"write the reason so a session in another project can tell whether the same fact holds there",
|
||||||
),
|
),
|
||||||
|
# Reviewing a suite: one verdict per test, deliberate breaks, every
|
||||||
|
# removal listed. The verdict vocabulary itself is product text on
|
||||||
|
# classify_shapes; the skill owns when to review and how.
|
||||||
|
Topic("a review gives every test one verdict and proves the survivors fail",
|
||||||
|
"skill:reviewing-tests",
|
||||||
|
("test_guard_groups", "review_test_group", "covered_by"),
|
||||||
|
"a test that stays green while its behaviour is broken protects nothing",
|
||||||
|
),
|
||||||
# ── per-tool contracts and in-band behaviour — owned by the server ──
|
# ── per-tool contracts and in-band behaviour — owned by the server ──
|
||||||
Topic("closing a task cues the report", "docstrings", ("report_back",), "reporting this to the operator?"),
|
Topic("closing a task cues the report", "docstrings", ("report_back",), "reporting this to the operator?"),
|
||||||
# The agent is the judge. Two topics, not one, because they fire
|
# The agent is the judge. Two topics, not one, because they fire
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
"""Real-Postgres tests for test-guard links: the `test` stamp, the groups,
|
||||||
|
a redundant verdict, and a kept group.
|
||||||
|
|
||||||
|
What the pure tests can't prove: that a sync stamps a linked test case and
|
||||||
|
withdraws the stamp when its links go, never over a judgment, and that the
|
||||||
|
group readout honours verdicts and reviews held in the database. Ledger rows
|
||||||
|
are seeded through the same sync the coverage walk uses; no forge needed.
|
||||||
|
"""
|
||||||
|
import pytest
|
||||||
|
import pytest_asyncio
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from grimoire.models import async_session
|
||||||
|
from grimoire.models.code_shape import CodeShape
|
||||||
|
from grimoire.models.project import Project
|
||||||
|
from grimoire.services import test_guards as tg
|
||||||
|
from grimoire.services.shape_ledger import classify_shapes, sync_repo_shapes
|
||||||
|
from tests.helpers import ensure_user
|
||||||
|
|
||||||
|
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
|
||||||
|
|
||||||
|
REPO = "git.example.com/alice/widget"
|
||||||
|
CHARGE = ("src/billing.py", "charge")
|
||||||
|
A = ("tests/test_a.py", "test_charges")
|
||||||
|
B = ("tests/test_b.py", "test_also_charges")
|
||||||
|
LONE = ("tests/test_c.py", "test_reads_nothing")
|
||||||
|
SHAPES = [(p, "sym", s) for p, s in (CHARGE, A, B, LONE)]
|
||||||
|
|
||||||
|
|
||||||
|
def _links(*, a_links: bool = True) -> tg.Links:
|
||||||
|
shapes = {A: {CHARGE} if a_links else set(), B: {CHARGE}, LONE: set()}
|
||||||
|
return tg.Links(shapes, {k: set() for k in shapes}, {k: [] for k in shapes}, set())
|
||||||
|
|
||||||
|
|
||||||
|
@pytest_asyncio.fixture
|
||||||
|
async def seeded():
|
||||||
|
async with async_session() as s:
|
||||||
|
owner = await ensure_user(s, "guards_owner")
|
||||||
|
project = Project(user_id=owner.id, title="Guards target")
|
||||||
|
s.add(project)
|
||||||
|
await s.flush()
|
||||||
|
ids = {"owner": owner.id, "pid": project.id}
|
||||||
|
await s.commit()
|
||||||
|
await sync_repo_shapes(ids["pid"], REPO, SHAPES, seen_marker="main")
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
async def _rows(pid: int) -> dict[tuple[str, str], CodeShape]:
|
||||||
|
async with async_session() as s:
|
||||||
|
rows = (await s.execute(select(CodeShape).where(CodeShape.project_id == pid))).scalars().all()
|
||||||
|
return {(r.path, r.symbol): r for r in rows}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_a_linked_test_case_is_stamped_and_loses_the_stamp_with_its_links(seeded):
|
||||||
|
pid = seeded["pid"]
|
||||||
|
await tg.sync_repo_guards(pid, REPO, _links())
|
||||||
|
rows = await _rows(pid)
|
||||||
|
assert rows[A].status == "test" and rows[A].classified_by == "mechanical"
|
||||||
|
# Linked to nothing: still the todo, because nothing says what it is for.
|
||||||
|
assert rows[LONE].status == "unclassified"
|
||||||
|
assert await tg.test_summary(pid) == {"linked": 2, "unlinked": 1, "redundant": 0}
|
||||||
|
|
||||||
|
await tg.sync_repo_guards(pid, REPO, _links(a_links=False))
|
||||||
|
assert (await _rows(pid))[A].status == "unclassified"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_the_stamp_never_overrides_a_judgment(seeded):
|
||||||
|
pid, owner = seeded["pid"], seeded["owner"]
|
||||||
|
await classify_shapes(owner, pid, [{"path": A[0], "symbol": A[1], "status": "exempt",
|
||||||
|
"reason": "a smoke check kept on purpose"}])
|
||||||
|
await tg.sync_repo_guards(pid, REPO, _links())
|
||||||
|
assert (await _rows(pid))[A].status == "exempt"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_a_group_leaves_the_readout_once_a_test_is_judged_redundant(seeded):
|
||||||
|
pid, owner = seeded["pid"], seeded["owner"]
|
||||||
|
await tg.sync_repo_guards(pid, REPO, _links())
|
||||||
|
groups = await tg.guard_groups(pid)
|
||||||
|
assert groups["count"] == 1
|
||||||
|
assert {(t["path"], t["symbol"]) for t in groups["groups"][0]["tests"]} == {A, B}
|
||||||
|
|
||||||
|
await classify_shapes(owner, pid, [{
|
||||||
|
"path": A[0], "symbol": A[1], "status": "redundant",
|
||||||
|
"covered_by": {"path": B[0], "symbol": B[1]},
|
||||||
|
"reason": "test_also_charges makes the same call and checks the total too",
|
||||||
|
}])
|
||||||
|
rows = await _rows(pid)
|
||||||
|
assert rows[A].covered_by_id == rows[B].id
|
||||||
|
assert (await tg.guard_groups(pid))["count"] == 0
|
||||||
|
assert (await tg.test_summary(pid))["redundant"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_a_kept_group_leaves_the_readout_until_its_members_change(seeded):
|
||||||
|
pid, owner = seeded["pid"], seeded["owner"]
|
||||||
|
await tg.sync_repo_guards(pid, REPO, _links())
|
||||||
|
rows = await _rows(pid)
|
||||||
|
await tg.review_group(owner, pid, [rows[A].id, rows[B].id],
|
||||||
|
reason="one checks the amount, the other the receipt", by="agent")
|
||||||
|
assert (await tg.guard_groups(pid))["count"] == 0
|
||||||
|
|
||||||
|
# A third test joins: a new group, back in front of a reviewer.
|
||||||
|
links = _links()
|
||||||
|
links.shapes[LONE] = {CHARGE}
|
||||||
|
await tg.sync_repo_guards(pid, REPO, links)
|
||||||
|
assert (await tg.guard_groups(pid))["count"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
async def test_the_end_of_turn_question_asks_about_product_code_not_test_cases(seeded):
|
||||||
|
from grimoire.services.shape_ledger import unjudged_shapes
|
||||||
|
|
||||||
|
asked = await unjudged_shapes(seeded["pid"], [
|
||||||
|
(A[0], "sym", A[1]), (CHARGE[0], "sym", CHARGE[1]),
|
||||||
|
])
|
||||||
|
assert [(x["path"], x["symbol"]) for x in asked] == [CHARGE]
|
||||||
@@ -482,7 +482,8 @@ async def test_coverage_measures_the_tree_exactly_and_caches(seeded):
|
|||||||
assert coverage["accounted"] == 2
|
assert coverage["accounted"] == 2
|
||||||
assert coverage["unclassified"] == 2
|
assert coverage["unclassified"] == 2
|
||||||
assert coverage["counts"] == {
|
assert coverage["counts"] == {
|
||||||
"canonical": 2, "instance": 0, "variant": 0, "exempt": 0, "scoped": 0,
|
"canonical": 2, "instance": 0, "variant": 0, "exempt": 0,
|
||||||
|
"redundant": 0, "unused": 0, "scoped": 0, "test": 0,
|
||||||
}
|
}
|
||||||
assert coverage["estimate"] is True
|
assert coverage["estimate"] is True
|
||||||
assert coverage["repos"] == [{
|
assert coverage["repos"] == [{
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""A pointer line names a record once a session, and is counted once.
|
||||||
|
|
||||||
|
A pointer line names, by id, records that cleared the floor but got no line
|
||||||
|
of their own. The plugin's ledger of what a session has seen holds only the
|
||||||
|
records given a line, so the server asks its own delivery ledger which
|
||||||
|
records this session was already shown or pointed at, and leaves those out.
|
||||||
|
Without that a handoff note is named again on every edit and every message.
|
||||||
|
|
||||||
|
And each delivery is booked once: the snippets beside an edited file are
|
||||||
|
named in a pointer line, so they are `pointed`, never also `pushed`.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from grimoire.services import note_usage
|
||||||
|
from grimoire.services import plugin_context as pc
|
||||||
|
from tests.helpers import fake_note
|
||||||
|
from tests.test_autoinject_context import _menu
|
||||||
|
|
||||||
|
# Six equally close notes: the menu shows its top three, and the rest are
|
||||||
|
# named in the pointer line.
|
||||||
|
HITS = [(0.8 - i * 0.001, fake_note(id=20 + i, title=f"a note {i}", note_type="note", user_id=1))
|
||||||
|
for i in range(6)]
|
||||||
|
|
||||||
|
|
||||||
|
async def _pointer(ledger: set[int]) -> tuple[list[int], MagicMock]:
|
||||||
|
"""The ids the auto-inject pointer line names, given what the session's
|
||||||
|
delivery ledger already holds, and the booking call."""
|
||||||
|
booked = MagicMock()
|
||||||
|
with patch.object(pc.record_deliveries_svc, "delivered_this_session",
|
||||||
|
AsyncMock(return_value=set(ledger))), \
|
||||||
|
patch.object(pc.record_deliveries_svc, "record", booked):
|
||||||
|
out = await _menu(HITS, [], {})
|
||||||
|
line = next((ln for ln in out.splitlines() if pc.POINTER_LEAD in ln), "")
|
||||||
|
return [int(i) for i in re.findall(r"#(\d+)", line)], booked
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_a_pointer_names_what_the_session_has_not_met():
|
||||||
|
named, booked = await _pointer(set())
|
||||||
|
assert named, "six close notes and a menu of three should leave a pointer line"
|
||||||
|
booked.assert_called_once()
|
||||||
|
assert list(booked.call_args.args[1]) == named
|
||||||
|
assert booked.call_args.args[2] == "auto_inject_pointer"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_a_record_already_pointed_at_this_session_is_not_named_again():
|
||||||
|
first, _ = await _pointer(set())
|
||||||
|
again, booked = await _pointer({first[0]})
|
||||||
|
assert first[0] not in again
|
||||||
|
assert set(again) == set(first) - {first[0]}
|
||||||
|
# Only what the line names is booked, so the ledger stays a record of
|
||||||
|
# what the session actually saw.
|
||||||
|
assert first[0] not in booked.call_args.args[1]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_no_line_when_the_session_has_met_every_record_it_would_name():
|
||||||
|
first, _ = await _pointer(set())
|
||||||
|
again, booked = await _pointer(set(first))
|
||||||
|
assert again == []
|
||||||
|
booked.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
# --- each delivery booked once --------------------------------------------
|
||||||
|
|
||||||
|
def _booked_for(source: str) -> MagicMock:
|
||||||
|
booked = MagicMock()
|
||||||
|
with patch.object(note_usage, "_schedule"), \
|
||||||
|
patch("grimoire.services.record_deliveries.record", booked):
|
||||||
|
note_usage.record_surfaced(user_id=1, note_ids=[7], source=source, project_id=2)
|
||||||
|
return booked
|
||||||
|
|
||||||
|
|
||||||
|
def test_snippets_beside_an_edited_file_are_not_also_booked_as_pushed():
|
||||||
|
# Their door books them as `pointed` when it names them.
|
||||||
|
_booked_for("write_path_place").assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_line_shown_in_full_is_booked_as_pushed():
|
||||||
|
# The same call books an ordinary line, so the test above is about the
|
||||||
|
# place arm and not about booking being switched off.
|
||||||
|
_booked_for("write_path_sync").assert_called_once()
|
||||||
@@ -22,7 +22,7 @@ def test_backup_version_is_current():
|
|||||||
"""The bump is the point of the test — a payload section added without
|
"""The bump is the point of the test — a payload section added without
|
||||||
moving the version produces backups that are structurally different and
|
moving the version produces backups that are structurally different and
|
||||||
indistinguishable by inspection."""
|
indistinguishable by inspection."""
|
||||||
assert backup.BACKUP_VERSION == 31
|
assert backup.BACKUP_VERSION == 32
|
||||||
|
|
||||||
|
|
||||||
def _exportable_note(**over):
|
def _exportable_note(**over):
|
||||||
@@ -139,7 +139,9 @@ def _column_guard_targets():
|
|||||||
FamilyAdoption, FamilyDecision, FamilyIdea, FamilyIdeaPlatform,
|
FamilyAdoption, FamilyDecision, FamilyIdea, FamilyIdeaPlatform,
|
||||||
FamilyIdeaReference, Platform, ProjectPlatform,
|
FamilyIdeaReference, Platform, ProjectPlatform,
|
||||||
)
|
)
|
||||||
from grimoire.models.code_shape import CodeShape, CodeShapeEvent, CodeShapeUse
|
from grimoire.models.code_shape import (
|
||||||
|
CodeShape, CodeShapeEvent, CodeShapeGuardReview, CodeShapeUse,
|
||||||
|
)
|
||||||
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
|
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
|
||||||
from grimoire.models.lesson_situation import LessonSituation
|
from grimoire.models.lesson_situation import LessonSituation
|
||||||
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
|
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
|
||||||
@@ -200,6 +202,9 @@ def _column_guard_targets():
|
|||||||
"code_shapes": (CodeShape, backup._code_shape_rows),
|
"code_shapes": (CodeShape, backup._code_shape_rows),
|
||||||
"code_shape_events": (CodeShapeEvent, backup._code_shape_event_rows),
|
"code_shape_events": (CodeShapeEvent, backup._code_shape_event_rows),
|
||||||
"code_shape_uses": (CodeShapeUse, backup._code_shape_use_rows),
|
"code_shape_uses": (CodeShapeUse, backup._code_shape_use_rows),
|
||||||
|
"code_shape_guard_reviews": (
|
||||||
|
CodeShapeGuardReview, backup._code_shape_guard_review_rows,
|
||||||
|
),
|
||||||
"platforms": (Platform, backup._platform_rows),
|
"platforms": (Platform, backup._platform_rows),
|
||||||
"project_platforms": (
|
"project_platforms": (
|
||||||
ProjectPlatform, lambda rows: backup._project_platform_rows(rows, _AnySlug()),
|
ProjectPlatform, lambda rows: backup._project_platform_rows(rows, _AnySlug()),
|
||||||
@@ -331,6 +336,7 @@ def _import_guard_targets():
|
|||||||
"code_shapes": backup._build_code_shape,
|
"code_shapes": backup._build_code_shape,
|
||||||
"code_shape_events": backup._build_code_shape_event,
|
"code_shape_events": backup._build_code_shape_event,
|
||||||
"code_shape_uses": backup._build_code_shape_use,
|
"code_shape_uses": backup._build_code_shape_use,
|
||||||
|
"code_shape_guard_reviews": backup._build_code_shape_guard_review,
|
||||||
"platforms": backup._build_platform,
|
"platforms": backup._build_platform,
|
||||||
"project_platforms": backup._build_project_platform,
|
"project_platforms": backup._build_project_platform,
|
||||||
"family_ideas": backup._build_family_idea,
|
"family_ideas": backup._build_family_idea,
|
||||||
@@ -600,6 +606,8 @@ async def test_export_full_backup_contains_every_declared_section():
|
|||||||
"rule_field_judgments",
|
"rule_field_judgments",
|
||||||
# v31: the moments and triggers each lesson arrives at.
|
# v31: the moments and triggers each lesson arrives at.
|
||||||
"lesson_situations",
|
"lesson_situations",
|
||||||
|
# v32: reviewed groups of same-guard tests.
|
||||||
|
"code_shape_guard_reviews",
|
||||||
# v25: family canon.
|
# v25: family canon.
|
||||||
"platforms", "project_platforms", "family_ideas",
|
"platforms", "project_platforms", "family_ideas",
|
||||||
"family_idea_platforms", "family_idea_references",
|
"family_idea_platforms", "family_idea_references",
|
||||||
|
|||||||
@@ -29,10 +29,11 @@ def test_the_todo_state_is_the_default():
|
|||||||
assert CodeShape.__table__.c.status.default.arg == "unclassified"
|
assert CodeShape.__table__.c.status.default.arg == "unclassified"
|
||||||
assert "unclassified" in SHAPE_STATUSES
|
assert "unclassified" in SHAPE_STATUSES
|
||||||
assert set(SHAPE_STATUSES) == {
|
assert set(SHAPE_STATUSES) == {
|
||||||
"canonical", "instance", "variant", "exempt", "scoped", "unclassified",
|
"canonical", "instance", "variant", "exempt", "redundant", "unused",
|
||||||
|
"scoped", "test", "unclassified",
|
||||||
}
|
}
|
||||||
assert set(SHAPE_CLASSIFIERS) == {
|
assert set(SHAPE_CLASSIFIERS) == {
|
||||||
"agent", "audit", "hook", "mechanical", "import",
|
"agent", "audit", "hook", "mechanical", "import", "person",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,199 @@
|
|||||||
|
"""What a test guards, read from the repo, and the verdicts that act on it.
|
||||||
|
|
||||||
|
The coverage refresh links every test (a test-named definition in a test
|
||||||
|
file) to the product shapes its body exercises, so the ledger can show tests
|
||||||
|
in different files that guard exactly the same thing. These pin the reading
|
||||||
|
rules: what counts as a reference, what does not, and how groups form.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from grimoire.services import shape_ledger
|
||||||
|
from grimoire.services import test_guards as tg
|
||||||
|
from grimoire.services.coverage import coverage_line
|
||||||
|
|
||||||
|
PRODUCT = [
|
||||||
|
tg.Def("src/app/billing.py", "charge", "def charge(amount):\n return amount\n"),
|
||||||
|
tg.Def("src/app/billing.py", "refund", "def refund(amount):\n return -amount\n"),
|
||||||
|
tg.Def("src/app/runner.py", "run", "def run():\n pass\n"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _test(path: str, name: str, body: str) -> tg.Def:
|
||||||
|
return tg.Def(path, name, f"def {name}():\n{body}")
|
||||||
|
|
||||||
|
|
||||||
|
def _links(*tests: tg.Def, files: dict[str, str] | None = None, paths=()):
|
||||||
|
files = files or {}
|
||||||
|
read = {p: tg.read_test_file(text) for p, text in files.items()}
|
||||||
|
return tg.link_tests([*PRODUCT, *tests], read, paths)
|
||||||
|
|
||||||
|
|
||||||
|
IMPORTS = "from app import billing as b\nfrom app.billing import charge\n"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_test_file_is_recognised_by_its_directory_or_its_name():
|
||||||
|
for path in ("tests/test_x.py", "pkg/x_test.go", "web/src/a.spec.ts",
|
||||||
|
"web/src/__tests__/a.ts", "src/FooTest.java"):
|
||||||
|
assert tg.is_test_path(path), path
|
||||||
|
for path in ("src/app/billing.py", "src/contest.py", "web/src/latest.ts"):
|
||||||
|
assert not tg.is_test_path(path), path
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_call_through_the_modules_alias_links_the_test_to_it():
|
||||||
|
t = _test("tests/test_a.py", "test_pays", " assert b.charge(3) == 3\n")
|
||||||
|
links = _links(t, files={"tests/test_a.py": IMPORTS})
|
||||||
|
assert links.shapes[("tests/test_a.py", "test_pays")] == {("src/app/billing.py", "charge")}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_call_on_something_else_with_a_product_name_does_not_link():
|
||||||
|
# `subprocess.run` shares a name with app.runner.run, and is not it.
|
||||||
|
t = _test("tests/test_a.py", "test_shells_out", " subprocess.run(['x'])\n")
|
||||||
|
links = _links(t, files={"tests/test_a.py": "import subprocess\nfrom app import runner\n"})
|
||||||
|
assert links.shapes[("tests/test_a.py", "test_shells_out")] == set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_bare_name_links_only_when_the_file_imports_it():
|
||||||
|
t = _test("tests/test_a.py", "test_pays", " assert charge(3) == 3\n refund(1)\n")
|
||||||
|
links = _links(t, files={"tests/test_a.py": IMPORTS})
|
||||||
|
# charge is imported by name; refund is not, so a bare `refund` is not it.
|
||||||
|
assert links.shapes[("tests/test_a.py", "test_pays")] == {("src/app/billing.py", "charge")}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_mocked_function_is_not_guarded():
|
||||||
|
body = (
|
||||||
|
" with patch('app.billing.refund'):\n"
|
||||||
|
" b.charge(1)\n"
|
||||||
|
" b.refund(1)\n"
|
||||||
|
)
|
||||||
|
t = _test("tests/test_a.py", "test_pays", body)
|
||||||
|
links = _links(t, files={"tests/test_a.py": IMPORTS})
|
||||||
|
assert links.shapes[("tests/test_a.py", "test_pays")] == {("src/app/billing.py", "charge")}
|
||||||
|
|
||||||
|
|
||||||
|
def test_reach_follows_a_helper_in_another_test_file():
|
||||||
|
helper = tg.Def("tests/helpers.py", "_pay", "def _pay():\n return b.charge(1)\n")
|
||||||
|
t = _test("tests/test_a.py", "test_pays_via_helper", " assert _pay() == 1\n")
|
||||||
|
links = _links(helper, t, files={
|
||||||
|
"tests/helpers.py": "from app import billing as b\n",
|
||||||
|
"tests/test_a.py": "from tests.helpers import _pay\n",
|
||||||
|
})
|
||||||
|
assert links.shapes[("tests/test_a.py", "test_pays_via_helper")] == {
|
||||||
|
("src/app/billing.py", "charge"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_go_test_reaches_its_own_package_without_an_import():
|
||||||
|
code = tg.Def("pkg/bill/bill.go", "Charge", "func Charge(n int) int {\n\treturn n\n}\n")
|
||||||
|
t = tg.Def("pkg/bill/bill_test.go", "TestCharge",
|
||||||
|
"func TestCharge(t *testing.T) {\n\tif Charge(1) != 1 { t.Fail() }\n}\n")
|
||||||
|
links = tg.link_tests([code, t], {"pkg/bill/bill_test.go": tg.read_test_file("")})
|
||||||
|
assert links.shapes[("pkg/bill/bill_test.go", "TestCharge")] == {("pkg/bill/bill.go", "Charge")}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_shape_reached_from_most_test_files_is_a_hub_and_drops_out():
|
||||||
|
files, tests = {}, []
|
||||||
|
for i in range(10):
|
||||||
|
path = f"tests/test_{i}.py"
|
||||||
|
files[path] = IMPORTS
|
||||||
|
# Every file reaches charge; only one reaches refund.
|
||||||
|
tests.append(_test(path, "test_x", " b.charge(1)\n" + (" b.refund(1)\n" if i == 0 else "")))
|
||||||
|
links = _links(*tests, files=files)
|
||||||
|
assert ("src/app/billing.py", "charge") in links.hubs
|
||||||
|
assert links.shapes[("tests/test_0.py", "test_x")] == {("src/app/billing.py", "refund")}
|
||||||
|
assert links.shapes[("tests/test_5.py", "test_x")] == set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_string_naming_a_repo_file_links_the_test_to_that_path():
|
||||||
|
t = _test("tests/test_a.py", "test_reads_the_script",
|
||||||
|
" text = open('scripts/release.sh').read()\n assert 'x' in text\n")
|
||||||
|
links = _links(t, files={"tests/test_a.py": ""},
|
||||||
|
paths=["scripts/release.sh", "src/app/billing.py"])
|
||||||
|
assert links.paths[("tests/test_a.py", "test_reads_the_script")] == {"scripts/release.sh"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_weak_signals_are_read_from_the_body():
|
||||||
|
assert tg.test_signals(" params = inspect.signature(f).parameters\n assert params\n") == ["signature"]
|
||||||
|
assert tg.test_signals(" f()\n mock.assert_called_once()\n") == ["mock-only"]
|
||||||
|
# A plain assert beside a mock check is a real check, so no signal.
|
||||||
|
assert tg.test_signals(" f()\n mock.assert_called_once()\n assert out == 1\n") == []
|
||||||
|
assert tg.test_signals(" text = path.read_text()\n assert 'x' in text\n") == ["source-text"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_group_spans_files_and_one_file_never_forms_one():
|
||||||
|
same = frozenset({1, 2})
|
||||||
|
groups = tg.same_guard_groups([
|
||||||
|
(10, "tests/test_a.py", same),
|
||||||
|
(11, "tests/test_b.py", same),
|
||||||
|
(12, "tests/test_c.py", frozenset({3})),
|
||||||
|
(13, "tests/test_c.py", frozenset({3})),
|
||||||
|
(14, "tests/test_d.py", frozenset()),
|
||||||
|
])
|
||||||
|
assert groups == [(same, [10, 11])]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_group_is_named_by_its_members_in_any_order():
|
||||||
|
a = tg.group_key([("tests/a.py", "test_1"), ("tests/b.py", "test_2")])
|
||||||
|
assert a == tg.group_key([("tests/b.py", "test_2"), ("tests/a.py", "test_1")])
|
||||||
|
# A test joining the group makes it a new group, back in front of a reviewer.
|
||||||
|
assert a != tg.group_key([("tests/a.py", "test_1"), ("tests/b.py", "test_2"), ("tests/c.py", "test_3")])
|
||||||
|
|
||||||
|
|
||||||
|
def _item(**over):
|
||||||
|
base = {"path": "tests/test_a.py", "symbol": "test_x", "status": "redundant",
|
||||||
|
"reason": "test_y checks the same call and more",
|
||||||
|
"covered_by": {"path": "tests/test_b.py", "symbol": "test_y"}}
|
||||||
|
base.update(over)
|
||||||
|
return base
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_redundant_verdict_names_its_cover_and_its_reason():
|
||||||
|
assert shape_ledger.validate_classifications([_item()]) is None
|
||||||
|
assert "covered_by" in shape_ledger.validate_classifications([_item(covered_by=None)])
|
||||||
|
assert "reason" in shape_ledger.validate_classifications([_item(reason="")])
|
||||||
|
assert "itself" in shape_ledger.validate_classifications(
|
||||||
|
[_item(covered_by={"path": "tests/test_a.py", "symbol": "test_x"})]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_unused_verdict_needs_a_reason():
|
||||||
|
item = {"path": "src/a.py", "symbol": "f", "status": "unused"}
|
||||||
|
assert "reason" in shape_ledger.validate_classifications([item])
|
||||||
|
assert shape_ledger.validate_classifications([{**item, "reason": "nothing calls it"}]) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_coverage_line_names_the_removal_verdicts_and_the_test_groups():
|
||||||
|
line = coverage_line({
|
||||||
|
"accounted": 10, "total": 10, "unclassified": 0,
|
||||||
|
"counts": {"exempt": 7, "redundant": 2, "unused": 1},
|
||||||
|
"test_groups": 3, "computed_at": "2026-12-01T00:00:00+00:00",
|
||||||
|
})
|
||||||
|
assert "2 redundant" in line and "1 unused" in line
|
||||||
|
assert "3 test groups guarding the same thing" in line
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_test_case_is_a_test_named_definition_or_a_call_style_spec_file():
|
||||||
|
assert tg.is_test_case("tests/test_a.py", "test_x", "sym")
|
||||||
|
assert not tg.is_test_case("tests/test_a.py", "_helper", "sym")
|
||||||
|
assert not tg.is_test_case("src/app/billing.py", "test_mode", "sym")
|
||||||
|
assert tg.is_test_case("web/src/a.spec.ts", "a.spec", "file")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_spec_written_as_calls_is_one_test_and_links_by_its_imports():
|
||||||
|
text = "import { charge } from '../app/billing'\n\nit('charges', () => {\n expect(charge(1)).toBe(1)\n})\n"
|
||||||
|
assert tg.is_call_style_spec("web/src/billing.spec.ts", text, [])
|
||||||
|
# A file that defines test-named functions is read per function instead.
|
||||||
|
assert not tg.is_call_style_spec("tests/test_a.py", "def test_x():\n pass\n", ["test_x"])
|
||||||
|
spec = tg.Def("web/src/billing.spec.ts", "billing.spec", text)
|
||||||
|
product = tg.Def("web/app/billing.ts", "charge", "export function charge(n) {\n return n\n}\n")
|
||||||
|
links = tg.link_tests([product], {spec.path: tg.read_test_file(text)}, file_tests=[spec])
|
||||||
|
assert links.shapes[(spec.path, "billing.spec")] == {("web/app/billing.ts", "charge")}
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_coverage_line_counts_tests_by_what_they_guard():
|
||||||
|
line = coverage_line({
|
||||||
|
"accounted": 10, "total": 12, "unclassified": 2, "counts": {"test": 8},
|
||||||
|
"tests": {"linked": 8, "unlinked": 2, "redundant": 1},
|
||||||
|
"computed_at": "2026-12-01T00:00:00+00:00",
|
||||||
|
})
|
||||||
|
assert "8 test" in line
|
||||||
|
assert "tests: 8 linked · 2 guarding nothing found · 1 redundant" in line
|
||||||
Reference in New Issue
Block a user