mirror of
https://github.com/citeworthyio/seo-agent.git
synced 2026-08-11 13:22:39 +02:00
Two host-facing senses grow up together. The crawl now stores each page's
JS-free body text (PageSnapshot.text, capped at MAX_SNAPSHOT_TEXT=4000) and
an uncapped word_count — exactly what GPTBot/ClaudeBot see, persisted so
downstream fact-extraction and thin-page senses read stored truth instead of
refetching. schema.sql gains the two nullable columns; existing installs run
the two ALTERs documented in README's 'Upgrading an existing install'.
And AgentDeps gains twinned — a set of page paths the host currently serves
a readable twin for, read only by ai_page_body_empty. The measurement (raw
HTML has no visible body text) stays true of a twinned page; the claim ('AI
crawlers see an empty page here') does not, and only the host knows that. The
path stays sampled — blocked/error senses keep measuring — but the body-empty
finding is withheld at trigger time, so a previously open row auto-resolves
via runRules' existing lifecycle instead of being re-opened and host-resolved
every audit. Absent (every self-hosted deployment) nothing changes anywhere.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
348 lines
16 KiB
TypeScript
348 lines
16 KiB
TypeScript
import { describe, it, expect } from 'vitest';
|
|
import {
|
|
verifyOverrides,
|
|
listPageOverrides,
|
|
overrideVerificationFindings,
|
|
expectedTitle,
|
|
normalizeDelivered,
|
|
normalizeExpected,
|
|
truncateValue,
|
|
servingNeverExisted,
|
|
servingEverObserved,
|
|
} from '../src/verify';
|
|
import { runRules } from '../src/rules';
|
|
import type { PageSnapshot } from '../src/crawl';
|
|
|
|
const snap = (over: Partial<PageSnapshot> & { path: string }): PageSnapshot => ({
|
|
status: 200,
|
|
title: null,
|
|
description: null,
|
|
canonical: null,
|
|
ogImage: null,
|
|
ogType: null,
|
|
jsonldTypes: [],
|
|
noindex: false,
|
|
lastmod: null,
|
|
error: null,
|
|
text: null,
|
|
wordCount: 0,
|
|
...over,
|
|
});
|
|
|
|
// A KV double with real prefix listing + cursor paging, so the paging path is
|
|
// exercised rather than assumed.
|
|
function fakeKv(initial: Record<string, string> = {}, pageSize = 1000) {
|
|
const store = new Map(Object.entries(initial));
|
|
return {
|
|
store,
|
|
kv: {
|
|
get: async (k: string) => store.get(k) ?? null,
|
|
put: async (k: string, v: string) => void store.set(k, v),
|
|
delete: async (k: string) => void store.delete(k),
|
|
list: async ({ prefix, cursor }: { prefix: string; limit?: number; cursor?: string }) => {
|
|
const all = [...store.keys()].filter((k) => k.startsWith(prefix)).sort();
|
|
const start = cursor ? Number(cursor) : 0;
|
|
const slice = all.slice(start, start + pageSize);
|
|
const next = start + pageSize;
|
|
const complete = next >= all.length;
|
|
return { keys: slice.map((name) => ({ name })), list_complete: complete, cursor: complete ? undefined : String(next) };
|
|
},
|
|
} as any,
|
|
};
|
|
}
|
|
|
|
describe('override verification — pure comparison', () => {
|
|
it('fires injection_regression when the delivered title is not the approved one', () => {
|
|
const t = verifyOverrides([{ path: '/a', title: 'Approved Title' }], [snap({ path: '/a', title: 'Old Origin Title' })]);
|
|
expect(t).toHaveLength(1);
|
|
expect(t[0]).toMatchObject({ path: '/a', rule: 'injection_regression', severity: 'critical' });
|
|
expect(t[0].detail).toContain('Approved Title');
|
|
expect(t[0].detail).toContain('Old Origin Title');
|
|
expect(t[0].detail).toContain('title:');
|
|
});
|
|
|
|
it('stays silent when the delivered value matches', () => {
|
|
expect(verifyOverrides([{ path: '/a', title: 'Approved Title' }], [snap({ path: '/a', title: 'Approved Title' })])).toEqual([]);
|
|
});
|
|
|
|
// AUDIT H1 (fixed in v1.15.1): this suite used to pin the WRONG contract — it
|
|
// expected the delivered title to be the stored value PLUS TITLE_BRAND_SUFFIX,
|
|
// on the belief that the site's edge layer appended it. Nothing did: the
|
|
// injector's setInnerContent REPLACES the whole <title> with the stored
|
|
// string. The suffix is now appended at APPLY time (withTitleSuffix in
|
|
// overrides.ts), so the stored value IS the full served value and this sense
|
|
// compares it verbatim.
|
|
it('compares the stored title verbatim — no suffix is added to the expectation', () => {
|
|
// Stored value already carries the suffix (that is what applyOverride wrote).
|
|
expect(verifyOverrides([{ path: '/a', title: 'Core — Acme' }], [snap({ path: '/a', title: 'Core — Acme' })])).toEqual([]);
|
|
// A bare core in KV is served bare — and must NOT be reported as a
|
|
// regression by inventing a suffix that nothing appends.
|
|
expect(verifyOverrides([{ path: '/a', title: 'Core' }], [snap({ path: '/a', title: 'Core' })])).toEqual([]);
|
|
});
|
|
|
|
it('still fires when the delivered title really is something else', () => {
|
|
const t = verifyOverrides([{ path: '/a', title: 'Core — Acme' }], [snap({ path: '/a', title: 'Old Origin Title' })]);
|
|
expect(t).toHaveLength(1);
|
|
expect(t[0].detail).toContain('Core — Acme');
|
|
});
|
|
|
|
it('accepts an entity-encoded delivered value (the injector escapes what it writes)', () => {
|
|
expect(verifyOverrides([{ path: '/a', title: 'Tools & Toys' }], [snap({ path: '/a', title: 'Tools & Toys' })])).toEqual([]);
|
|
expect(
|
|
verifyOverrides([{ path: '/a', description: 'A "quoted" phrase & more' }], [snap({ path: '/a', description: 'A "quoted" phrase & more' })])
|
|
).toEqual([]);
|
|
});
|
|
|
|
// Audit M4: the comparison must be SYMMETRIC. The stored value can itself
|
|
// contain a literal entity (an operator pasted "Tips & Tricks"), which the
|
|
// injector escapes AGAIN on the way out. Decoding only the delivered side
|
|
// would read that as a mismatch and emit a false critical.
|
|
it('decodes BOTH sides — a stored literal entity is not a regression (title lane)', () => {
|
|
expect(
|
|
verifyOverrides([{ path: '/a', title: 'Tips & Tricks' }], [snap({ path: '/a', title: 'Tips &amp; Tricks' })])
|
|
).toEqual([]);
|
|
// …and the description lane, which was already symmetric — keep it that way.
|
|
expect(
|
|
verifyOverrides([{ path: '/a', description: 'Tips & Tricks' }], [snap({ path: '/a', description: 'Tips &amp; Tricks' })])
|
|
).toEqual([]);
|
|
});
|
|
|
|
it('a stored literal entity still fires when a different value is served', () => {
|
|
expect(verifyOverrides([{ path: '/a', title: 'Tips & Tricks' }], [snap({ path: '/a', title: 'Something Else' })])).toHaveLength(1);
|
|
});
|
|
|
|
it('tolerates whitespace re-wrapping inside the delivered title', () => {
|
|
expect(verifyOverrides([{ path: '/a', title: 'A Long Title' }], [snap({ path: '/a', title: ' A Long\n Title ' })])).toEqual([]);
|
|
});
|
|
|
|
it('compares descriptions directly and names the field', () => {
|
|
const t = verifyOverrides([{ path: '/a', description: 'Approved copy.' }], [snap({ path: '/a', description: 'Origin copy.' })]);
|
|
expect(t).toHaveLength(1);
|
|
expect(t[0].detail).toMatch(/description: expected "Approved copy\.", delivered "Origin copy\."/);
|
|
});
|
|
|
|
it('reports a missing delivered value as "nothing" rather than an empty quote', () => {
|
|
const t = verifyOverrides([{ path: '/a', description: 'Approved copy.' }], [snap({ path: '/a', description: null })]);
|
|
expect(t[0].detail).toContain('delivered nothing');
|
|
});
|
|
|
|
it('reports both fields in one finding for one path', () => {
|
|
const t = verifyOverrides([{ path: '/a', title: 'T', description: 'D' }], [snap({ path: '/a', title: 'x', description: 'y' })]);
|
|
expect(t).toHaveLength(1);
|
|
expect(t[0].detail).toContain('title:');
|
|
expect(t[0].detail).toContain('description:');
|
|
});
|
|
|
|
it('skips non-2xx snapshots — head fields are meaningless there', () => {
|
|
for (const status of [0, 301, 404, 500]) {
|
|
expect(verifyOverrides([{ path: '/a', title: 'T' }], [snap({ path: '/a', status, title: 'wrong' })])).toEqual([]);
|
|
}
|
|
});
|
|
|
|
it('skips paths not crawled this run — no evidence either way', () => {
|
|
expect(verifyOverrides([{ path: '/gone', title: 'T' }], [snap({ path: '/a', title: 'T' })])).toEqual([]);
|
|
});
|
|
|
|
it('truncates long values in the detail', () => {
|
|
const long = 'x'.repeat(400);
|
|
const t = verifyOverrides([{ path: '/a', title: long }], [snap({ path: '/a', title: 'short' })]);
|
|
expect(t[0].detail.length).toBeLessThan(400);
|
|
expect(t[0].detail).toContain('…');
|
|
});
|
|
});
|
|
|
|
describe('override verification — helpers', () => {
|
|
it('expectedTitle is the stored value, trimmed — it appends nothing (audit H1)', () => {
|
|
expect(expectedTitle('Core')).toBe('Core');
|
|
expect(expectedTitle(' Core | A ')).toBe('Core | A');
|
|
});
|
|
it('normalizeDelivered decodes entities and folds whitespace', () => {
|
|
expect(normalizeDelivered(' a &\nb ')).toBe('a & b');
|
|
});
|
|
it('normalizeExpected folds whitespace but does NOT decode (audit M4)', () => {
|
|
expect(normalizeExpected(' a &\nb ')).toBe('a & b');
|
|
});
|
|
it('truncateValue keeps short values verbatim', () => {
|
|
expect(truncateValue(' a b ')).toBe('a b');
|
|
});
|
|
});
|
|
|
|
describe('override verification — KV listing', () => {
|
|
it('reads every page override, ignoring resource keys and junk', async () => {
|
|
const { kv } = fakeKv({
|
|
'override:/a': JSON.stringify({ title: 'T' }),
|
|
'override:/b': JSON.stringify({ description: 'D' }),
|
|
'override:/c': '{not json',
|
|
'override:/d': JSON.stringify({}),
|
|
'resource:/llms.txt': JSON.stringify({ contentType: 'text/markdown', body: '# x' }),
|
|
});
|
|
const entries = await listPageOverrides({ overrides: kv });
|
|
expect(entries.map((e) => e.path).sort()).toEqual(['/a', '/b']);
|
|
});
|
|
|
|
it('pages the listing with the cursor until list_complete', async () => {
|
|
const init: Record<string, string> = {};
|
|
for (let i = 0; i < 25; i++) init[`override:/p${String(i).padStart(3, '0')}`] = JSON.stringify({ title: 'T' });
|
|
const { kv } = fakeKv(init, 10); // forces 3 pages
|
|
expect(await listPageOverrides({ overrides: kv })).toHaveLength(25);
|
|
});
|
|
|
|
it('skips resource-only key spaces entirely (resource overrides are out of scope)', async () => {
|
|
const { kv } = fakeKv({ 'resource:/robots.txt': JSON.stringify({ contentType: 'text/plain', body: 'x' }) });
|
|
expect(await listPageOverrides({ overrides: kv })).toEqual([]);
|
|
});
|
|
});
|
|
|
|
describe('override verification — sense wiring', () => {
|
|
const config = { titleBrandSuffix: ' — Acme' } as any;
|
|
|
|
it('end-to-end: KV + snapshots produce the finding', async () => {
|
|
const { kv } = fakeKv({ 'override:/a': JSON.stringify({ title: 'Core' }) });
|
|
const t = await overrideVerificationFindings({ overrides: kv, config }, [snap({ path: '/a', title: 'Stale' })]);
|
|
expect(t).toHaveLength(1);
|
|
expect(t[0].rule).toBe('injection_regression');
|
|
});
|
|
|
|
it('no-ops when the crawl produced no snapshots (no KV read at all)', async () => {
|
|
let listed = false;
|
|
const overrides = { list: async () => ((listed = true), { keys: [], list_complete: true }) } as any;
|
|
expect(await overrideVerificationFindings({ overrides, config }, [])).toEqual([]);
|
|
expect(listed).toBe(false);
|
|
});
|
|
|
|
it('a KV failure is isolated by the pipeline sense wrapper — zero findings, no throw', async () => {
|
|
const overrides = {
|
|
list: async () => {
|
|
throw new Error('KV down');
|
|
},
|
|
} as any;
|
|
await expect(overrideVerificationFindings({ overrides, config }, [snap({ path: '/a' })])).rejects.toThrow('KV down');
|
|
// …and the pipeline's `sense` contract swallows exactly that:
|
|
const extra: any[] = [];
|
|
const sense = async (name: string, fn: () => Promise<any[]>) => {
|
|
try {
|
|
extra.push(...(await fn()));
|
|
} catch {
|
|
/* degraded to zero findings */
|
|
}
|
|
};
|
|
await sense('override_verify', () => overrideVerificationFindings({ overrides, config }, [snap({ path: '/a' })]));
|
|
expect(extra).toEqual([]);
|
|
});
|
|
});
|
|
|
|
// --- Dedupe against the shellTitle detector -----------------------------------
|
|
// Both detectors emit `injection_regression` for the same path. runRules keys
|
|
// triggered findings by (path, rule) and keeps the first occurrence, so exactly
|
|
// one row is inserted. This proves it rather than assuming it.
|
|
describe('dedupe with the shellTitle injection_regression detector', () => {
|
|
function fakeDb() {
|
|
const inserted: any[][] = [];
|
|
const stmt = (sql: string, binds: unknown[] = []): any => ({
|
|
bind: (...b: unknown[]) => stmt(sql, b),
|
|
first: async () => null,
|
|
all: async () => ({ results: [] }),
|
|
run: async () => ({ meta: {} }),
|
|
__sql: sql,
|
|
__binds: binds,
|
|
});
|
|
return {
|
|
inserted,
|
|
db: {
|
|
prepare: (sql: string) => stmt(sql),
|
|
batch: async (statements: any[]) => {
|
|
for (const s of statements) if (/INSERT INTO findings/.test(s.__sql)) inserted.push(s.__binds);
|
|
return [];
|
|
},
|
|
} as any,
|
|
};
|
|
}
|
|
|
|
it('inserts ONE injection_regression when both senses fire for the same path', async () => {
|
|
const { inserted, db } = fakeDb();
|
|
const config = { siteUrl: 'https://acme.test', shellTitle: 'Acme App', titleBrandSuffix: '', articlePathPrefix: '' } as any;
|
|
// The page serves the SPA shell title while an override approves something else.
|
|
const snapshots = [snap({ path: '/a', title: 'Acme App', description: 'A description that is easily long enough to pass the minimum bound here.', canonical: 'https://acme.test/a', ogImage: 'https://acme.test/i.png' })];
|
|
const { kv } = fakeKv({ 'override:/a': JSON.stringify({ title: 'Approved Title' }) });
|
|
const extra = await overrideVerificationFindings({ overrides: kv, config }, snapshots);
|
|
expect(extra).toHaveLength(1);
|
|
|
|
await runRules({ db, config }, 2, snapshots, extra);
|
|
const regressions = inserted.filter((b) => b[3] === 'injection_regression');
|
|
expect(regressions).toHaveLength(1);
|
|
// The verification sense went in first, so its richer detail is what lands.
|
|
expect(regressions[0][5]).toContain('approved override is not being served');
|
|
});
|
|
});
|
|
|
|
// --- The serving-path gate ---------------------------------------------------
|
|
// "Approved override is not being served" reads to a customer as "your SEO layer
|
|
// STOPPED RUNNING". That is only true if it was ever running. The gate closes on
|
|
// POSITIVE knowledge that no serving path ever existed, and on nothing else —
|
|
// every unknown leaves it open, because suppressing a real outage on a failed
|
|
// read is the unrecoverable error and a false alarm is the recoverable one.
|
|
describe('override verification — serving-path gate', () => {
|
|
const config = { titleBrandSuffix: ' — Acme' } as any;
|
|
const withOverride = () => fakeKv({ 'override:/a': JSON.stringify({ title: 'Core' }) });
|
|
const stale = [snap({ path: '/a', title: 'Stale' })];
|
|
|
|
it('everServed:false withholds the findings entirely (and never reads KV)', async () => {
|
|
const { kv } = withOverride();
|
|
let listed = false;
|
|
const overrides = { ...kv, list: async (...a: any[]) => ((listed = true), kv.list(...a)) } as any;
|
|
expect(await overrideVerificationFindings({ overrides, config }, stale, { everServed: false })).toEqual([]);
|
|
expect(listed).toBe(false);
|
|
});
|
|
|
|
it('everServed:true leaves the findings exactly as they were', async () => {
|
|
const { kv } = withOverride();
|
|
const t = await overrideVerificationFindings({ overrides: kv, config }, stale, { everServed: true });
|
|
expect(t).toHaveLength(1);
|
|
expect(t[0].rule).toBe('injection_regression');
|
|
});
|
|
|
|
it('everServed:null (a read we could not make) does NOT gate — unknown fails toward alarming', async () => {
|
|
const { kv } = withOverride();
|
|
const t = await overrideVerificationFindings({ overrides: kv, config }, stale, { everServed: null });
|
|
expect(t).toHaveLength(1);
|
|
});
|
|
|
|
it('absent and explicitly-undefined evidence are identical to today', async () => {
|
|
const { kv } = withOverride();
|
|
expect(await overrideVerificationFindings({ overrides: kv, config }, stale)).toHaveLength(1);
|
|
expect(await overrideVerificationFindings({ overrides: kv, config }, stale, undefined)).toHaveLength(1);
|
|
});
|
|
|
|
it('servingNeverExisted is true for exactly one input', () => {
|
|
expect(servingNeverExisted({ everServed: false })).toBe(true);
|
|
expect(servingNeverExisted({ everServed: true })).toBe(false);
|
|
expect(servingNeverExisted({ everServed: null })).toBe(false);
|
|
expect(servingNeverExisted(undefined)).toBe(false);
|
|
expect(servingNeverExisted(null)).toBe(false);
|
|
});
|
|
|
|
// Withholding must read as "verified nothing wrong", NOT as "did not look":
|
|
// an empty triggered list is what closes rows a previous run opened.
|
|
it('a gated run resolves an injection_regression a previous run opened', async () => {
|
|
const { kv } = withOverride();
|
|
const gated = await overrideVerificationFindings({ overrides: kv, config }, stale, { everServed: false });
|
|
expect(gated).toEqual([]); // → reconcile sees zero triggered → the open row resolves
|
|
});
|
|
});
|
|
|
|
describe('servingEverObserved — the cheap self-derived default', () => {
|
|
const dbWith = (impl: () => any) => ({ prepare: () => ({ first: async () => impl() }) }) as any;
|
|
|
|
it('true when the telemetry table holds any row', async () => {
|
|
expect(await servingEverObserved(dbWith(() => ({ hit: 1 })))).toBe(true);
|
|
});
|
|
|
|
it('false when the read succeeded and found nothing', async () => {
|
|
expect(await servingEverObserved(dbWith(() => null))).toBe(false);
|
|
});
|
|
|
|
it('null — never false — when the read throws', async () => {
|
|
expect(await servingEverObserved(dbWith(() => { throw new Error('no such table: aeo_hits'); }))).toBe(null);
|
|
});
|
|
});
|