diff --git a/scripts/memory_dedup.py b/scripts/memory_dedup.py index 412ea23..dd39c32 100644 --- a/scripts/memory_dedup.py +++ b/scripts/memory_dedup.py @@ -88,22 +88,44 @@ def dump_entities() -> list[dict]: sys.exit(f"psql failed: {out.stderr.strip()}") return json.loads(out.stdout.strip()) -def read_fm(p: Path) -> dict: +def read_fm(p: Path, strict: bool = False) -> dict: """Scoped frontmatter field reader — mirrors src/file-sync.ts :: readFrontmatterField. Matching is confined to the `---...---` block (or the first 800 chars when no fence is found), so a same-named key in the BODY (e.g. a memory documenting `tier: HOT` as prose) is never picked up. Values have surrounding quotes stripped, so `tier: "HOT"` parses the same as `tier: HOT`. + + `strict=True` is for paths that DELETE on the result (main()'s T1/T2), like + readFrontmatterField's `{ strict: true }`: a real `---` block is required + (LF or CRLF), only top-level keys count, and there is no 800-char fallback, + so a body line or another key's nested `pg_id` never selects a file. When + in doubt every field is None and the file lands in T4_REVIEW, untouched. + + `pgid` is lower-cased here, once, because Postgres returns uuids + lower-case: every by-id lookup then matches a hand-edited upper-case pg_id. + file-sync.ts instead returns the raw value and lower-cases where it + compares (validPgIds, updateMemoryIndex, findFilesByPgId). Either way, + both sides of every comparison are lower-case. """ t = p.read_text(errors="replace") - m = re.match(r"^---\n(.*?)\n---", t, re.S) - blk = m.group(1) if m else t[:800] - def g(k): - mm = re.search(rf"^\s*{k}\s*:\s*(.+)$", blk, re.M) - return mm.group(1).strip().strip('"').strip("'") if mm else None + if strict: + # `??` tries an EMPTY block first, so `---\n---` closes on line 2; the + # closing fence must be a whole line, so `---foo` does not close it. + m = re.match(r"?\s*---\r?\n((?:.*?\r?\n)??)---[ \t]*(?:\r?\n|$)", t, re.S) + blk = m.group(1) if m else "" + key_re = r"^{k}:[ \t]*(.+?)\r?$" # colon right after the key, as in TS + else: + m = re.match(r"^---\n(.*?)\n---", t, re.S) + blk = m.group(1) if m else t[:800] + key_re = r"^\s*{k}\s*:\s*(.+)$" + + def g(k: str) -> str | None: + mm = re.search(key_re.format(k=k), blk, re.M) + return (mm.group(1).strip().strip('"').strip("'") or None) if mm else None + pgid = g("pg_id") return { - "pgid": g("pg_id"), "name": g("name"), "type": g("type"), + "pgid": pgid.lower() if pgid else pgid, "name": g("name"), "type": g("type"), "tier": g("tier"), "temperature": g("temperature"), } @@ -161,6 +183,28 @@ def home_has_file(e: dict) -> str | None: _FETCH = object() # sentinel: "resolve the map yourself" +# A pg_id must be a real 8-4-4-4-12 uuid before it joins the batch: one id that +# passes a looser [0-9a-fA-F-]{36} filter but fails Postgres's ::uuid cast (36 hex +# chars, no dashes) fails the WHOLE ::uuid[] batch, and every memory silently +# falls back to frontmatter ranking. Ids come back lower-cased because Postgres +# returns uuids lower-case and the lookup below uses the same form, so a +# hand-edited upper-case id still resolves. Must match UUID_RE / validPgIds in +# src/file-sync.ts. +UUID_RE = re.compile( + r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}" +) + + +def valid_pg_ids(pg_ids: list[str]) -> list[str]: + """Keep only well-formed uuids, lower-cased; report the rest on stderr + (they need repair).""" + ok = [i.lower() for i in pg_ids if UUID_RE.fullmatch(i)] + bad = len(pg_ids) - len(ok) + if bad: + print(f"[memory_dedup] skipped {bad} malformed pg_id(s)", file=sys.stderr) + return ok + + def fetch_thermal_by_pgid( pg_ids: list[str], timeout: int = 30, url: str | None = None ) -> dict[str, tuple[str, float]] | None: @@ -187,7 +231,7 @@ def fetch_thermal_by_pgid( Must match src/file-sync.ts :: fetchThermalByPgId. """ - ids = ",".join(i for i in pg_ids if re.fullmatch(r"[0-9a-fA-F-]{36}", i)) + ids = ",".join(valid_pg_ids(pg_ids)) if not ids: return None try: @@ -197,7 +241,7 @@ def fetch_thermal_by_pgid( return None # Nothing is interpolated into the SQL: the id list travels as a psql # variable, so psql owns the quoting and the ::uuid[] cast makes Postgres - # reject anything that is not a uuid. The regex above is a second gate. + # reject anything that is not a uuid. valid_pg_ids() is the gate before it. # # The query goes in on STDIN, not via -c: psql only performs :'var' # interpolation on lexed input, and -c is sent verbatim (verified 2026-08-16 @@ -287,7 +331,8 @@ def regen_index(thermal: object = _FETCH) -> int: if resolved is not None: orphans = 0 for e in entries: - row = resolved.get(e["pgid"]) if e["pgid"] else None + # Defensive: read_fm is the normalisation point and already lower-cases. + row = resolved.get(str(e["pgid"]).lower()) if e["pgid"] else None if row: e["rank"] = TIER_RANK.get(row[0].upper(), UNKNOWN_TIER_RANK) e["temp"] = row[1] @@ -334,8 +379,9 @@ def main(): present = {p.name for p in files} tiers = defaultdict(list) for f in files: - fi = read_fm(f) - ent = by_id.get(fi["pgid"]) if fi["pgid"] else None + # strict: T1/T2 below are deleted under --apply. + fi = read_fm(f, strict=True) + ent = by_id.get(fi["pgid"]) if fi["pgid"] else None # read_fm lower-cases if fi["pgid"] and ent is None: tiers["T4_REVIEW"].append((f.name, f"dangling pg_id {fi['pgid'][:8]}")); continue if ent is None: diff --git a/src/file-sync.ts b/src/file-sync.ts index 41c500b..9349d03 100644 --- a/src/file-sync.ts +++ b/src/file-sync.ts @@ -436,15 +436,20 @@ export async function syncToFile( * is the only stable cross-rename anchor, so we glob the dir and read * frontmatter to surface every file pointing at this entity. * - * Frontmatter-only match: the regex is anchored to a line so a `pg_id` - * mention in the body cannot trigger a false delete. + * Reads pg_id with readFrontmatterField in strict mode: only a TOP-LEVEL key + * inside a real `---` block (LF or CRLF) counts, so a body line, a file with + * no frontmatter, or another key's nested `pg_id` can never trigger a delete. + * The value is compared case-insensitively: Postgres returns uuids + * lower-case, so a hand-edited upper-case pg_id is the same entity. */ function findFilesByPgId(dir: string, pgId: string): string[] { - if (!existsSync(dir)) { + const want = pgId.trim().toLowerCase(); + // An empty id would equal the '' readFrontmatterField returns for every + // file WITHOUT a pg_id, and the caller deletes what this returns. + if (!want || !existsSync(dir)) { return []; } const matches: string[] = []; - const pattern = new RegExp(`^pg_id:[ \\t]*${pgId}\\s*$`, 'm'); for (const file of readdirSync(dir)) { if (!file.endsWith('.md') || file === 'MEMORY.md') { continue; @@ -452,7 +457,7 @@ function findFilesByPgId(dir: string, pgId: string): string[] { const fullPath = join(dir, file); try { const content = readFileSync(fullPath, 'utf-8'); - if (pattern.test(content)) { + if (readFrontmatterField(content, 'pg_id', { strict: true }).toLowerCase() === want) { matches.push(fullPath); } } catch { @@ -543,7 +548,24 @@ export async function syncMerge( * * @internal — exported for tests; not part of the MCP surface. */ -export function readFrontmatterField(content: string, key: string): string { +export function readFrontmatterField( + content: string, + key: string, + { strict = false }: { strict?: boolean } = {}, +): string { + // strict (for paths that DELETE on a match): a real `---` block is required + // (LF or CRLF), and only a top-level key counts. No first-800-chars + // fallback and no nested fallback, so a body line or another key's nested + // field can never select a file. When in doubt the file is kept. + if (strict) { + // `??` tries an EMPTY block first, so `---\n---` closes on line 2 instead + // of running on to a later `---` rule in the body; the closing fence must + // be a whole line, so `---foo` does not close the block. + const block = content.match(/^\uFEFF?\s*---\r?\n((?:[\s\S]*?\r?\n)??)---[ \t]*(?:\r?\n|$)/)?.[1]; + if (block === undefined) return ''; + const flat = block.match(new RegExp(`^${key}:[ \\t]*(.*)$`, 'm')); + return (flat?.[1] ?? '').trim().replace(/^["']|["']$/g, ''); + } const block = content.match(/^\uFEFF?\s*---\n([\s\S]*?)\n---/)?.[1] ?? content.slice(0, 800); const flat = block.match(new RegExp(`^${key}:[ \\t]*(.*)$`, 'm')); const nested = flat ? null : block.match(new RegExp(`^[ \\t]+${key}:[ \\t]*(.*)$`, 'm')); @@ -554,6 +576,25 @@ export function readFrontmatterField(content: string, key: string): string { export type ThermalRow = { tier: string; temperature: number }; export type ThermalMap = Map; +/** + * A pg_id must be a real 8-4-4-4-12 uuid before it joins the batch: one id that + * passes a looser `[0-9a-fA-F-]{36}` filter but fails Postgres's `::uuid` cast + * (36 hex chars, no dashes) fails the WHOLE `::uuid[]` batch, and every memory + * silently falls back to frontmatter ranking. Ids come back lower-cased because + * Postgres returns uuids lower-case and the index lookup uses the same form, so + * a hand-edited upper-case id still resolves. Must match `UUID_RE` / + * `valid_pg_ids` in scripts/memory_dedup.py. + */ +const UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/; + +/** Keep only well-formed uuids, lower-cased; report the rest on stderr (they need repair). */ +export function validPgIds(pgIds: string[]): string[] { + const ok = pgIds.filter(id => UUID_RE.test(id)).map(id => id.toLowerCase()); + const bad = pgIds.length - ok.length; + if (bad > 0) process.stderr.write(`[file-sync] skipped ${bad} malformed pg_id(s)\n`); + return ok; +} + /** * Batch-resolve live thermal state for the entities an index rebuild is about * to rank. ONE query per rebuild, never one per file. @@ -574,7 +615,7 @@ export type ThermalMap = Map; * then never exit. */ export async function fetchThermalByPgId(pgIds: string[]): Promise { - const ids = pgIds.filter(id => /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(id)); + const ids = validPgIds(pgIds); if (ids.length === 0) return null; try { // db.js MUST be imported before the DATABASE_URL check: importing it is what @@ -686,7 +727,7 @@ export async function updateMemoryIndex( if (resolved) { let orphans = 0; for (const e of entries) { - const row = e.pgId ? resolved.get(e.pgId) : undefined; + const row = e.pgId ? resolved.get(e.pgId.toLowerCase()) : undefined; if (row) { const t = row.tier.toUpperCase(); e.rank = t in TIER_RANK ? TIER_RANK[t] : UNKNOWN_TIER_RANK; diff --git a/tests/file-sync.test.ts b/tests/file-sync.test.ts index 0047ade..edc21f5 100644 --- a/tests/file-sync.test.ts +++ b/tests/file-sync.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; import { existsSync, mkdirSync, @@ -17,6 +17,7 @@ import { truncateDescription, updateMemoryIndex, fetchThermalByPgId, + validPgIds, syncToFile, removeFile, syncMerge, @@ -516,6 +517,54 @@ describe('updateMemoryIndex', () => { // orphan and re-cut the index on filename alone. expect(await fetchThermalByPgId([])).toBeNull(); }); + + it('validPgIds drops ids that would fail the ::uuid cast and fail the whole batch', () => { + const good = 'abcdef00-0000-4000-8000-000000000001'; // letters, so upper-casing differs + const write = vi.spyOn(process.stderr, 'write').mockImplementation(() => true); + try { + // The last two bad ids embed a valid uuid: they pin the ^...$ anchoring. + const bad = ['a'.repeat(36), '-'.repeat(36), `x${good}`, `${good}0`]; + expect(validPgIds([good, ...bad, good.toUpperCase()])).toEqual([good, good]); + expect(write).toHaveBeenCalledWith('[file-sync] skipped 4 malformed pg_id(s)\n'); + } finally { + write.mockRestore(); + } + }); + + it('fetchThermalByPgId filters through validPgIds before any DB work', async () => { + // The return is null with or without the filter in a test env, so the + // helper's stderr report is what tells a bypass apart. + const write = vi.spyOn(process.stderr, 'write').mockImplementation(() => true); + try { + expect(await fetchThermalByPgId(['a'.repeat(36)])).toBeNull(); + expect(write).toHaveBeenCalledWith('[file-sync] skipped 1 malformed pg_id(s)\n'); + } finally { + write.mockRestore(); + } + }); + + it('an upper-case pg_id resolves against the lower-case row Postgres returns', async () => { + const dir = makeTmpDir(); + try { + const upper = '0000000A-0000-4000-8000-000000000001'; + writeFileSync( + join(dir, 'a.md'), + `---\nname: a\ndescription: da\ntype: reference\ntier: COLD\ntemperature: 0\npg_id: ${upper}\n---\nbody\n`, + 'utf-8', + ); + const thermal = new Map([[upper.toLowerCase(), { tier: 'HOT', temperature: 0.9 }]]); + const err = vi.spyOn(process.stderr, 'write').mockImplementation(() => true); + try { + await updateMemoryIndex(dir, thermal); + // A missed lookup is reported on stderr as an orphan; a resolved row is not. + expect(err.mock.calls.some(c => String(c[0]).includes('no matching entity'))).toBe(false); + } finally { + err.mockRestore(); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); }); describe('removeFile pg_id glob', () => { @@ -679,6 +728,90 @@ describe('removeFile pg_id glob', () => { } }); + it('deletes an orphan whose pg_id differs only by case, and nothing else', async () => { + const { source, dir, projectDir } = makeIsolatedSource(); + try { + const pgId = 'abcdef01-1111-4111-8111-111111111111'; + await syncToFile({ + id: pgId, name: 'cased', type: 'fact', observations: 'b', source, + temperature: 0.5, tier: 'WARM', + }); + const upperOrphan = join(dir, 'fact_cased-old.md'); + writeFileSync(upperOrphan, frontmatter('cased-old', 'fact', pgId.toUpperCase()), 'utf-8'); + // A longer id that merely STARTS with this one must not match. + const prefixBystander = join(dir, 'fact_prefix.md'); + writeFileSync(prefixBystander, frontmatter('prefix', 'fact', `${pgId}0`), 'utf-8'); + // The id appearing only in the BODY must not match either. + const bodyBystander = join(dir, 'fact_mentions.md'); + writeFileSync( + bodyBystander, + frontmatter('mentions', 'fact', '22222222-2222-4222-8222-222222222222', `pg_id: ${pgId}`), + 'utf-8', + ); + // A file with no pg_id at all must survive too. + const noIdBystander = join(dir, 'fact_noid.md'); + writeFileSync(noIdBystander, '---\nname: noid\ntype: fact\n---\n\nbody\n', 'utf-8'); + // Delete-path shapes a lenient reader would match. Each mentions the id + // OUTSIDE a top-level frontmatter key, so each must survive: + const crlfBody = join(dir, 'fact_crlf-body.md'); // CRLF: fence must still be found + writeFileSync(crlfBody, `---\r\nname: crlf\r\ntype: fact\r\n---\r\n\r\npg_id: ${pgId}\r\n`, 'utf-8'); + const noFence = join(dir, 'fact_nofence.md'); // no frontmatter: nothing to read + writeFileSync(noFence, `just notes\npg_id: ${pgId}\n`, 'utf-8'); + const nested = join(dir, 'fact_nested.md'); // nested under another key + writeFileSync(nested, `---\nname: nested\ntype: fact\nrelated:\n pg_id: ${pgId}\n---\n\nb\n`, 'utf-8'); + const emptyFm = join(dir, 'fact_emptyfm.md'); // empty frontmatter, then a body rule + writeFileSync(emptyFm, `---\n---\npg_id: ${pgId}\n---\nmore\n`, 'utf-8'); + // ...while a CRLF file whose TOP-LEVEL pg_id is the entity's goes with it. + const crlfOrphan = join(dir, 'fact_crlf-orphan.md'); + writeFileSync(crlfOrphan, `---\r\nname: crlf-old\r\ntype: fact\r\npg_id: ${pgId.toUpperCase()}\r\n---\r\n\r\nb\r\n`, 'utf-8'); + // `---foo` is not a closing fence: never closed, the file is kept... + const notClosed = join(dir, 'fact_not-closed.md'); + writeFileSync(notClosed, `---\nname: nc\n---foo\npg_id: ${pgId}\n`, 'utf-8'); + // ...and with a real fence after it, the pg_id is a top-level key: swept. + const closedLater = join(dir, 'fact_closed-later.md'); + writeFileSync(closedLater, `---\nname: cl\n---foo\npg_id: ${pgId}\n---\nb\n`, 'utf-8'); + // Quoted value, BOM and stray spaces: same entity, swept with it. + const quotedOrphan = join(dir, 'fact_quoted-orphan.md'); + writeFileSync(quotedOrphan, `\uFEFF---\nname: q\ntype: fact\npg_id: "${pgId}" \n---\n\nb\n`, 'utf-8'); + + await removeFile({ + id: pgId, name: 'cased', type: 'fact', observations: 'b', source, + temperature: 0.5, tier: 'WARM', + }); + + expect(existsSync(join(dir, 'fact_cased.md'))).toBe(false); + expect(existsSync(upperOrphan)).toBe(false); + expect(existsSync(prefixBystander)).toBe(true); + expect(existsSync(bodyBystander)).toBe(true); + expect(existsSync(noIdBystander)).toBe(true); + expect(existsSync(crlfBody)).toBe(true); + expect(existsSync(noFence)).toBe(true); + expect(existsSync(nested)).toBe(true); + expect(existsSync(emptyFm)).toBe(true); + expect(existsSync(crlfOrphan)).toBe(false); + expect(existsSync(notClosed)).toBe(true); + expect(existsSync(closedLater)).toBe(false); + expect(existsSync(quotedOrphan)).toBe(false); + } finally { + rmSync(projectDir, { recursive: true, force: true }); + } + }); + + it('an empty id never sweeps the files that have no pg_id', async () => { + const { source, dir, projectDir } = makeIsolatedSource(); + try { + const noIdFile = join(dir, 'fact_noid.md'); + writeFileSync(noIdFile, '---\nname: noid\ntype: fact\n---\n\nbody\n', 'utf-8'); + await removeFile({ + id: '', name: 'something-else', type: 'fact', observations: 'b', source, + temperature: 0.5, tier: 'WARM', + }); + expect(existsSync(noIdFile)).toBe(true); + } finally { + rmSync(projectDir, { recursive: true, force: true }); + } + }); + it('syncToFile removes stale same-pg_id files left by a rename', async () => { const { source, dir, projectDir } = makeIsolatedSource(); try { @@ -688,6 +821,9 @@ describe('removeFile pg_id glob', () => { // Pre-existing file under the OLD slug, same entity. const orphanPath = join(dir, 'fact_old-name.md'); writeFileSync(orphanPath, frontmatter('old-name', 'fact', pgId, 'stale'), 'utf-8'); + // A second stale copy whose pg_id was hand-edited to upper case. + const upperOrphanPath = join(dir, 'fact_older-name.md'); + writeFileSync(upperOrphanPath, frontmatter('older-name', 'fact', pgId.toUpperCase(), 'stale'), 'utf-8'); // Bystander with a different pg_id — must survive. const bystanderPath = join(dir, 'fact_unrelated.md'); @@ -706,6 +842,7 @@ describe('removeFile pg_id glob', () => { expect(existsSync(join(dir, 'fact_new-name.md'))).toBe(true); expect(existsSync(orphanPath)).toBe(false); + expect(existsSync(upperOrphanPath)).toBe(false); expect(existsSync(bystanderPath)).toBe(true); // Exactly one file on disk carries this entity's pg_id. diff --git a/tests/test_memory_dedup.py b/tests/test_memory_dedup.py index ba70236..47bdd1c 100644 --- a/tests/test_memory_dedup.py +++ b/tests/test_memory_dedup.py @@ -128,6 +128,39 @@ def test_missing_pgid_is_none(self, tmp_path): assert fm["name"] == "No Id" assert fm["type"] == "project" + def test_pgid_is_lower_cased_but_other_fields_are_not(self, tmp_path): + p = tmp_path / "feedback_z.md" + p.write_text("---\nname: Mixed\ntype: feedback\ntier: HOT\npg_id: ABCDEF01-2222\n---\nb", "utf-8") + fm = md.read_fm(p) + assert (fm["pgid"], fm["name"], fm["tier"]) == ("abcdef01-2222", "Mixed", "HOT") + + @pytest.mark.parametrize( + ("label", "text", "want"), + [ + ("top-level LF", "---\nname: N\npg_id: AB-1\n---\nb", "ab-1"), + ("top-level CRLF", "---\r\nname: N\r\npg_id: AB-1\r\n---\r\nb", "ab-1"), + ("quoted", '---\npg_id: "AB-1"\n---\nb', "ab-1"), + ("BOM", "\ufeff---\npg_id: ab-1\n---\nb", "ab-1"), + ("no fence, id in body", "notes\npg_id: ab-1\n", None), + ("nested key only", "---\nrelated:\n pg_id: ab-1\n---\nb", None), + ("body after empty block", "---\n---\npg_id: ab-1\n", None), + ("---foo does not close", "---\nname: N\n---foo\npg_id: ab-1\n---\nb", "ab-1"), + ("never closed", "---\nname: N\n---foo\npg_id: ab-1\n", None), + ("space before colon", "---\npg_id : ab-1\n---\nb", None), + ("empty value", "---\npg_id: \"\"\n---\nb", None), + ], + ) + def test_strict_reads_only_a_top_level_key_in_a_real_block(self, tmp_path, label, text, want): + p = tmp_path / "f.md" + p.write_bytes(text.encode()) + assert md.read_fm(p, strict=True)["pgid"] == want, label + + def test_strict_nested_id_does_not_shadow_the_top_level_one(self, tmp_path): + p = tmp_path / "f.md" + p.write_text("---\nrelated:\n pg_id: aaaa\npg_id: BBBB\n---\nb", "utf-8") + assert md.read_fm(p, strict=True)["pgid"] == "bbbb" + assert md.read_fm(p)["pgid"] == "aaaa" # lenient (index ranking) is unchanged + # --------------------------------------------------------------------------- # # Index line budget — degradation when the memory dir grows past the cap @@ -208,6 +241,29 @@ def test_orphan_pgid_ranks_at_zero_not_frontmatter(self, tmp_path, monkeypatch): assert "- reference: n0 — d-n0\n" not in out assert "- reference: n168 — d-n168" in out + def test_uppercase_pgid_resolves_against_lowercase_row(self, tmp_path, monkeypatch): + """Postgres returns uuids lower-case; a hand-edited upper-case pg_id must + still find its row, not rank as an orphan at 0 and fall off the index.""" + monkeypatch.setattr(md, "MEMDIR", tmp_path) + for i in range(169): + pg_id = f"00000000-0000-4000-8000-{i:012d}" + if i == 0: + pg_id = f"0000000A-0000-4000-8000-{i:012d}" + (tmp_path / f"z-{i:03d}.md").write_text( + f"---\nname: n{i}\ndescription: d-n{i}\ntype: reference\n" + f"temperature: 1\ntier: HOT\npg_id: {pg_id}\n---\n\nbody\n" + ) + thermal = { + f"00000000-0000-4000-8000-{i:012d}": ("HOT", 0.5 + i / 1000) + for i in range(1, 169) + } + thermal["0000000a-0000-4000-8000-000000000000"] = ("HOT", 0.99) + md.regen_index(thermal=thermal) + + out = (tmp_path / "MEMORY.md").read_text() + assert "- reference: n0 — d-n0\n" in out + assert "- reference: n1 — d-n1\n" not in out + def test_falls_back_to_frontmatter_when_thermal_is_none(self, tmp_path, monkeypatch): monkeypatch.setattr(md, "MEMDIR", tmp_path) (tmp_path / "a.md").write_text( @@ -225,6 +281,20 @@ def test_fetch_thermal_returns_none_for_empty_id_list(self): """ assert md.fetch_thermal_by_pgid([]) is None + def test_valid_pg_ids_rejects_dashless_hex_and_reports_it(self, capsys): + """36 hex chars with no dashes passes a loose [0-9a-fA-F-]{36} filter but + fails Postgres's ::uuid cast, which would fail the WHOLE batch.""" + good = "abcdef00-0000-4000-8000-000000000001" # letters, so upper() differs + bad = ["a" * 36, "-" * 36, "x" + good, good + "0"] # last two: anchoring + assert md.valid_pg_ids([good, *bad, good.upper()]) == [good, good] + assert "skipped 4 malformed pg_id(s)" in capsys.readouterr().err + + def test_fetch_thermal_skips_db_when_every_id_is_malformed(self, monkeypatch): + def no_psql(*a, **k): + raise AssertionError("psql must not run for an all-malformed batch") + monkeypatch.setattr(md.subprocess, "run", no_psql) + assert md.fetch_thermal_by_pgid(["a" * 36], url="postgresql://u@h/db") is None + def test_drops_cold_before_warm(self, tmp_path, monkeypatch): monkeypatch.setattr(md, "MEMDIR", tmp_path) _memo(tmp_path, "a-warm.md", "keep-warm", "WARM", 0.5) @@ -401,6 +471,39 @@ def test_report_mode_touches_nothing(reconcile_env, monkeypatch, capsys): assert "KEEP: 2" in out +def test_uppercase_pgid_is_not_t4_dangling(reconcile_env, monkeypatch, capsys): + """A hand-edited upper-case pg_id of a live entity must resolve (Postgres + returns uuids lower-case), not land in T4_REVIEW as dangling.""" + monkeypatch.setattr(md, "APPLY", False) + memdir = reconcile_env["memdir"] + e_keep = reconcile_env["entities"][0] + # The fixture ids are all digits, so swap in a letter to give upper() a + # case to change; the entity row keeps it lower-case, as Postgres returns it. + upper = e_keep["id"].replace("1", "A", 1).upper() + e_keep["id"] = upper.lower() + _fm_file(memdir / "feedback_keep-me.md", name="Keep Me", etype="feedback", pgid=upper) + md.main() + out = capsys.readouterr().out + assert "KEEP: 2" in out + assert "T4_REVIEW: 2" in out # only the fixture's own two + + +def test_apply_never_deletes_on_a_body_or_nested_pg_id(reconcile_env, monkeypatch, capsys): + """--apply deletes T1/T2, so classification reads pg_id strictly: a file + that only MENTIONS a live id (no fence, or a nested key) is T4, kept.""" + monkeypatch.setattr(md, "APPLY", True) + memdir = reconcile_env["memdir"] + dup_id = reconcile_env["entities"][1]["id"].upper() + (memdir / "notes_nofence.md").write_text(f"notes\npg_id: {dup_id}\nname: Dup Entity\n", "utf-8") + (memdir / "notes_nested.md").write_text( + f"---\nrelated:\n pg_id: {dup_id}\n name: Dup Entity\n---\nb\n", "utf-8" + ) + md.main() + present = {p.name for p in memdir.glob("*.md")} + assert {"notes_nofence.md", "notes_nested.md"} <= present + assert "T4_REVIEW: 4" in capsys.readouterr().out + + def test_apply_deletes_only_t1_t2_regenerates_t3_keeps_t4(reconcile_env, monkeypatch): monkeypatch.setattr(md, "APPLY", True) memdir = reconcile_env["memdir"]