feat(8246): the code index links each test to what it guards, and can say redundant or unused
CI & Build / Plugin hooks (push) Successful in 20s
CI & Build / Python lint (push) Successful in 3s
CI & Build / TypeScript typecheck (push) Successful in 41s
CI & Build / Python tests (push) Failing after 2m8s
CI & Build / integration (push) Successful in 2m24s
CI & Build / Build & push image (push) Skipped

Every coverage refresh now reads, for each test in a bound repo, which product
shapes its body exercises: through module aliases and imports, following test
helpers, with mocked names left out and shapes most test files reach dropped as
hubs. Tests in different files that guard exactly the same set form a group.
The project page lists the groups and a person can mark one test redundant,
naming the test that covers it, or keep them all with a reason. Agents get
test_guard_groups and review_test_group, and classify_shapes takes the two new
removal verdicts, redundant (with covered_by) and unused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 21:17:48 -05:00
co-authored by Claude Opus 5.5
parent 134dd68274
commit 865465ce8f
19 changed files with 1412 additions and 27 deletions
+63
View File
@@ -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")
+242
View File
@@ -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>
+10 -1
View File
@@ -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,8 @@ 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;
} }
interface Divergence { interface Divergence {
path: string; path: string;
@@ -834,7 +837,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']"
: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 +891,12 @@ async function confirmDelete() {
{{ coverage.recheck }} to recheck {{ coverage.recheck }} to recheck
</span> </span>
</div> </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 -1
View File
@@ -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), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
"version": "2026.11.28.2315", "version": "2026.12.01.0217",
"author": { "author": {
"name": "Bryan Van Deusen" "name": "Bryan Van Deusen"
}, },
+14
View File
@@ -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,16 @@ 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.
## 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,
+2 -2
View File
@@ -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",
+65 -4
View File
@@ -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,9 @@ 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 | 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 +447,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)
+4 -1
View File
@@ -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
+90 -2
View File
@@ -23,8 +23,18 @@ 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.
SHAPE_STATUSES = (
"canonical", "instance", "variant", "exempt", "redundant", "unused",
"scoped", "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 +157,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 +201,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 +232,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 +387,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),
}
+67
View File
@@ -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):
+68 -4
View File
@@ -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(),
@@ -619,6 +639,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 +1159,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 +1240,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 +1345,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 +1548,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 +2379,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 +2601,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 +3033,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 +3108,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",
) )
+39 -3
View File
@@ -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,9 @@ 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)
return ArchiveScan(shapes, references, tuple(paths), test_files)
# --- matching shapes against recorded locations ------------------------------ # --- matching shapes against recorded locations ------------------------------
@@ -848,6 +856,18 @@ 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,
)
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 +932,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, "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 +970,15 @@ 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"]
except Exception:
logger.warning("test guard groups read failed", exc_info=True)
test_groups = 0
# 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 +1006,8 @@ 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,
"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 +1152,7 @@ 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")
if counts.get(k) if counts.get(k)
) )
line = ( line = (
@@ -1172,6 +1203,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:
+37 -4
View File
@@ -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,
+523
View File
@@ -0,0 +1,523 @@
"""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 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))
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] = (),
*,
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.
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)
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")
# 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 == "sym"}
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 == "sym" else ""
if (r.test_signals or "") != sig:
r.test_signals = sig
await session.commit()
return edges
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()
+1
View File
@@ -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": {},
+2 -1
View File
@@ -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,
} }
assert coverage["estimate"] is True assert coverage["estimate"] is True
assert coverage["repos"] == [{ assert coverage["repos"] == [{
+10 -2
View File
@@ -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",
+3 -2
View File
@@ -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", "unclassified",
} }
assert set(SHAPE_CLASSIFIERS) == { assert set(SHAPE_CLASSIFIERS) == {
"agent", "audit", "hook", "mechanical", "import", "agent", "audit", "hook", "mechanical", "import", "person",
} }
+171
View File
@@ -0,0 +1,171 @@
"""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