Files
coucou/brain/tests/patterns.test.ts
T
Claude 5747c57790 Memory › Patterns: never lose the cards, same-height cards, a turning refresh arrow
- "Read again" emptied the page: from the app, the index read failed, brain took that for
  "no conversations" and dropped every project from the cache. A database that can't be read
  now throws (readAllConversations); the cache is never emptied all at once; a project whose
  Claude calls all failed keeps what it had; a merge reply that keeps nothing keeps the list.
  `brain patterns --json` prints {error}, and the page shows the reason above the cards.
- The cards found before stay on the page while Claude reads again.
- Every card has the same rows and line counts (title and description on two lines, the files
  line, the weekly bars, three conversations), so the grid is even.
- "Read again" is now a round arrow: it lights up under the pointer and turns while it works.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LJm3SRL9k3gBPaVtfPhwcT
2026-11-28 15:51:58 +00:00

221 lines
12 KiB
TypeScript

/**
* Patterns: the tasks you keep asking Claude to do, that could become skills.
* The LLM is replaced by a fake, so these tests check the plumbing: what is sent, how the reply
* is read, the cache, the skill draft and its installation (backup of an existing skill).
*/
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import Database from "better-sqlite3";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { BrainConfig } from "../src/config.js";
import { rawDbPath } from "../src/rawindex.js";
import {
applyMerge, buildPatternPrompt, buildSkillPrompt, collectProjects, findPatterns, generateSkill, installSkill,
isProgrammatic, parsePatternReply, parseSkillReply, readPatterns, slug,
} from "../src/patterns.js";
import { looksLikeProject, snapshotProject } from "../src/project-files.js";
let dir: string;
let config: BrainConfig;
function seed(rows: { conv: string; title: string; date: string; project: string; msgs: [string, string][] }[]) {
const p = rawDbPath(config);
fs.mkdirSync(path.dirname(p), { recursive: true });
const db = new Database(p);
db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS raw_messages USING fts5(
conv_id UNINDEXED, conv_title UNINDEXED, conv_date UNINDEXED, conv_link UNINDEXED,
msg_index UNINDEXED, role UNINDEXED, source UNINDEXED, project UNINDEXED, text)`);
const ins = db.prepare(`INSERT INTO raw_messages (conv_id, conv_title, conv_date, conv_link, msg_index, role, source, project, text)
VALUES (?, ?, ?, '', ?, ?, 'desktop', ?, ?)`);
for (const r of rows) r.msgs.forEach(([role, text], i) => ins.run(r.conv, r.title, r.date, i, role, r.project, text));
db.close();
}
const reels = (n: number) => Array.from({ length: n }, (_, i) => ({
conv: `r${i}`, title: `Reel ${i}`, date: `2026-11-${String(10 + i).padStart(2, "0")}`, project: "reels",
msgs: [["human", `Recrée ce reel dans ma DA, voici la vidéo ${i}. Clé sk-ant-api03-${"x".repeat(40)}`], ["claude", "Voici le montage."]] as [string, string][],
}));
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), "patterns"));
config = {
brainPath: dir, claudeProjectsPath: path.join(dir, "none"), repoPaths: [],
chunkModel: "sonnet", mergeModel: "opus", maxChunkTokens: 100000, language: "fr", repoAliases: {},
};
seed([...reels(5), { conv: "x1", title: "Seul", date: "2026-11-01", project: "tiny", msgs: [["human", "une fois"]] }]);
});
afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));
describe("patterns", () => {
it("groups conversations by project, skips tiny projects, masks secrets", () => {
const projects = collectProjects(config);
expect(projects.map(p => p.projet)).toEqual(["reels"]);
const prompt = buildPatternPrompt("reels", projects[0]!.items);
expect(prompt).toContain("Recrée ce reel dans ma DA");
expect(prompt).not.toContain("sk-ant-api03");
});
it("keeps only patterns found in at least 3 conversations", () => {
const items = collectProjects(config)[0]!.items;
const got = parsePatternReply(
'blabla {"patterns":[{"nom":"Recréer un Reel dans ma DA","description":"À partir d\'un autre Reel","conversations":[0,1,2,3,99]},{"nom":"Rare","conversations":[0,1]}]}',
"reels", items);
expect(got).toHaveLength(1);
expect(got[0]!.count).toBe(4);
expect(got[0]!.id).toBe(slug("reels-Recréer un Reel dans ma DA"));
});
it("caches the analysis and only reads a project again when it changes", () => {
let calls = 0;
const llm = () => { calls++; return '{"patterns":[{"nom":"Recréer un Reel dans ma DA","description":"d","conversations":[0,1,2]}]}'; };
expect(findPatterns(config, llm).patterns).toHaveLength(1);
expect(calls).toBe(1);
findPatterns(config, llm);
expect(calls).toBe(1); // nothing changed: no LLM call
expect(readPatterns(config).stale).toBe(0);
seed([{ conv: "r9", title: "Reel 9", date: "2026-11-27", project: "reels", msgs: [["human", "encore un"]] }]);
expect(readPatterns(config).stale).toBe(1); // the page can offer to refresh
findPatterns(config, llm);
expect(calls).toBe(2);
});
it("writes a skill draft, then installs it with a backup of an existing one", () => {
const id = findPatterns(config, () => '{"patterns":[{"nom":"Recréer un Reel dans ma DA","description":"d","conversations":[0,1,2]}]}').patterns[0]!.id;
let sent = "";
const md = "---\nname: recreer-reel-da\ndescription: Quand je donne un Reel à refaire dans ma DA\n---\n# Recréer un Reel\n";
const draft = generateSkill(config, id, p => { sent = p; return JSON.stringify({ name: "recreer-reel-da", markdown: md }); });
expect(sent).toContain("MOI : Recrée ce reel");
expect(sent).not.toContain("sk-ant-api03");
expect(fs.readFileSync(draft.path, "utf8")).toBe(md);
const skills = path.join(dir, "claude-skills");
fs.mkdirSync(path.join(skills, "recreer-reel-da"), { recursive: true });
fs.writeFileSync(path.join(skills, "recreer-reel-da", "SKILL.md"), "old");
const inst = installSkill(config, id, skills);
expect(fs.readFileSync(inst.path, "utf8")).toBe(md);
expect(inst.backup && fs.readFileSync(inst.backup, "utf8")).toBe("old");
expect(readPatterns(config).patterns[0]!.installe).toBe(true);
});
it("rejects a skill reply that is not a SKILL.md", () => {
expect(parseSkillReply('{"name":"x","markdown":"pas de front matter"}')).toBeNull();
});
it("never sends brain's own runs and marks its prompts as internal", () => {
expect(isProgrammatic("<!-- coucou-brain-internal -->\nAnalyse")).toBe(true);
expect(isProgrammatic("Génère 6 à 10 keywords de recherche FR+EN pour chaque élément.")).toBe(true);
expect(isProgrammatic("Recrée ce reel dans ma DA")).toBe(false);
expect(buildPatternPrompt("reels", collectProjects(config)[0]!.items)).toMatch(/^<!-- coucou-brain-internal -->/);
});
it("merges the same task found in two projects into one pattern", () => {
const mk = (projet: string, nom: string, ids: string[]) => ({
id: slug(`${projet}-${nom}`), nom, description: "", projet, count: ids.length, freqJours: null, histogram: [],
conversations: ids.map((id, i) => ({ id, titre: id, date: `2026-11-0${i + 1}` })),
});
const list = [mk("claude.ai", "Trier les mails du matin", ["a", "b", "c"]), mk("Reels", "Trier la boîte mail du matin", ["c", "d", "e"]), mk("x", "Autre", ["f", "g", "h"])];
const out = applyMerge('{"groupes":[{"nom":"Trier les mails du matin","description":"d","membres":[0,1]},{"nom":"Autre","membres":[2]}]}', list)!;
expect(out).toHaveLength(2);
expect(out[0]!.count).toBe(5); // a b c d e, c counted once
expect(out[0]!.projet).toBe("claude.ai, Reels");
expect(out[1]!.id).toBe(list[2]!.id); // a task alone keeps its id
});
it("tells the skill writer that the newest conversation wins and to invent no link", () => {
const pat = { id: "x", nom: "Refaire un Reel", description: "d", projet: "reels", conversations: [], count: 3, freqJours: 2, histogram: [] };
const prompt = buildSkillPrompt(pat as any, "### 2026-11-28 — t\nMOI : salut");
expect(prompt).toMatch(/la plus récente l'emporte/);
expect(prompt).toMatch(/N'écris aucun lien/);
});
describe("project files", () => {
let proj: string;
beforeEach(() => {
// a real project folder, and the Claude Code session that ran in it
proj = path.join(dir, "app");
fs.mkdirSync(path.join(proj, "scripts"), { recursive: true });
fs.mkdirSync(path.join(proj, ".claude", "skills", "deploy"), { recursive: true });
fs.writeFileSync(path.join(proj, "CLAUDE.md"), `# App\nEvery release adds its CHANGELOG section and a row in the README. Token ghp_${"a".repeat(36)}`);
fs.writeFileSync(path.join(proj, "scripts", "release.sh"), "#!/bin/sh");
fs.writeFileSync(path.join(proj, ".claude", "skills", "deploy", "SKILL.md"), "---\nname: deploy\ndescription: Déployer le site\n---\n");
const enc = path.join(config.claudeProjectsPath, proj.replace(/[\\/]/g, "-"));
fs.mkdirSync(enc, { recursive: true });
fs.writeFileSync(path.join(enc, "s1.jsonl"), JSON.stringify({ type: "user", cwd: proj }) + "\n");
seed([{ conv: "a1", title: "Bug", date: "2026-11-20", project: "app", msgs: [["human", "corrige ce bug"]] }]);
});
it("reads a few files of a real project, masks secrets, never the home folder", () => {
const snap = snapshotProject(proj);
expect(snap.text).toContain("Every release adds its CHANGELOG");
expect(snap.text).not.toContain("ghp_aaaa");
expect(snap.sources).toEqual(expect.arrayContaining(["CLAUDE.md", "scripts/release.sh"]));
expect(looksLikeProject(os.homedir())).toBe(false);
expect(looksLikeProject(path.join(dir, "none"))).toBe(false);
});
it("keeps a project with one conversation when its files show a routine, and sends its skills", () => {
const app = collectProjects(config).find(p => p.projet === "app");
expect(app?.fichiers?.sources).toContain("CLAUDE.md");
let sent = "";
const llm = (prompt: string) => {
if (prompt.includes("« app »")) { sent = prompt; return '{"patterns":[{"nom":"Préparer une release","description":"d","conversations":[],"fichiers":["CLAUDE.md","inventé.md"]}]}'; }
return '{"patterns":[]}';
};
const got = findPatterns(config, llm).patterns.find(p => p.projet === "app")!;
expect(sent).toContain("--- scripts/\nrelease.sh");
expect(sent).toContain("- deploy : Déployer le site");
expect(got.sources).toEqual(["CLAUDE.md"]); // a file Claude made up does not count
expect(got.count).toBe(0);
fs.writeFileSync(path.join(proj, "scripts", "build.sh"), "#!/bin/sh");
expect(readPatterns(config).stale).toBe(1); // the files changed: look again
});
it("drops a pattern with too few conversations and no real file behind it", () => {
expect(parsePatternReply('{"patterns":[{"nom":"X","conversations":[0],"fichiers":["nope.md"]}]}', "app", [], Date.now(), ["CLAUDE.md"])).toHaveLength(0);
});
});
it("says when the app should analyse by itself, and never runs twice at once", () => {
expect(readPatterns(config).due).toBe(true); // never analysed
let calls = 0;
const llm = () => { calls++; return '{"patterns":[]}'; };
findPatterns(config, llm);
expect(readPatterns(config).due).toBe(false);
seed([{ conv: "r9", title: "Reel 9", date: "2026-11-27", project: "reels", msgs: [["human", "encore"]] }]);
expect(readPatterns(config).due).toBe(false); // changed, but analysed a moment ago
expect(readPatterns(config, Date.now() + 7 * 3_600_000).due).toBe(true);
fs.writeFileSync(path.join(dir, ".state", "patterns.lock"), "123");
const before = calls;
expect(findPatterns(config, llm).running).toBe(true);
expect(calls).toBe(before);
expect(readPatterns(config).due).toBe(false);
});
it("never loses what it found when the index can't be read or Claude doesn't answer", () => {
const good = () => '{"patterns":[{"nom":"Recréer un Reel dans ma DA","description":"d","conversations":[0,1,2]}]}';
expect(findPatterns(config, good).patterns).toHaveLength(1);
// Claude unreachable: an error, and the page keeps its cards
seed([{ conv: "r9", title: "Reel 9", date: "2026-11-27", project: "reels", msgs: [["human", "encore"]] }]);
expect(() => findPatterns(config, () => { throw new Error("spawn claude ENOENT"); })).toThrow(/ENOENT/);
expect(readPatterns(config).patterns).toHaveLength(1);
// the index can't be read: an error, never "you have no conversations"
fs.writeFileSync(rawDbPath(config), "not a database");
expect(() => findPatterns(config, good)).toThrow(/index illisible/);
const r = readPatterns(config);
expect(r.patterns).toHaveLength(1);
expect(r.error).toMatch(/index illisible/);
expect(r.due).toBe(false);
});
it("keeps the list when the merge reply keeps nothing", () => {
let n = 0;
seed([{ conv: "t1", title: "T", date: "2026-11-02", project: "tiny", msgs: [["human", "x"]] }, { conv: "t2", title: "T", date: "2026-11-03", project: "tiny", msgs: [["human", "x"]] }]);
const llm = (prompt: string) => {
if (prompt.includes("Regroupe")) return '{"groupes":[]}';
n++;
return n === 1 ? '{"patterns":[{"nom":"A","conversations":[0,1,2]}]}' : '{"patterns":[{"nom":"B","conversations":[0,1,2]}]}';
};
expect(findPatterns(config, llm).patterns.length).toBe(2);
});
});