Skip to content

Build your personal knowledge base with Trilium Notes

5.3 KB
Raw Blame
import { existsSync, readFileSync } from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import { afterEach, describe, expect, it } from "vitest";

import { getSkillsSummary, readSkill, registerSkillReader, SKILLS } from "./skills.js";

/**
 * This file's directory, taken apart rather than composed with
 * `new URL(…, import.meta.url)`: core's specs run under the standalone project
 * too, whose browser-flavoured Vite config rewrites that expression into a
 * dev-server asset URL (`http://localhost:3000/@fs/…`) that no filesystem call
 * can use.
 */
const HERE = dirname(fileURLToPath(import.meta.url));
const SKILLS_DIR = join(HERE, "../../assets/llm/skills");

/** Restore the "no host has registered anything" state the module starts in. */
function clearReader() {
    registerSkillReader(() => null);
}

afterEach(clearReader);

describe("llm skill sheets", () => {
    it("ships a markdown sheet for every catalogued skill", () => {
        // The catalog is the contract between core and both readers: an entry with
        // no file behind it is a tool call that fails at the far end of a chat.
        for (const file of SKILLS.flatMap((skill) => [ skill.file, skill.reference ?? [] ]).flat()) {
            expect(existsSync(join(SKILLS_DIR, file)), `missing sheet: ${file}`).toBe(true);
        }
    });

    it("appends the API reference to a sheet that has one", () => {
        registerSkillReader((file) => ({ "backend_scripting.md": "SHEET\n", "backend_scripting_api.md": "REFERENCE" })[file] ?? null);
        expect(readSkill("backend_scripting")).toBe("SHEET\n\nREFERENCE");

        // A host without the reference still serves the sheet.
        registerSkillReader((file) => file === "backend_scripting.md" ? "SHEET" : null);
        expect(readSkill("backend_scripting")).toBe("SHEET");
    });

    it("keeps each API reference in step with script_api.ts", () => {
        // Each reference is generated by `pnpm edit-docs:sync-docs`; a member added to or removed
        // from script_api.ts without a sync since fails here.
        const source = interfaceMembers(readFileSync(join(HERE, "../../../../commons/src/lib/script_api.ts"), "utf-8"), true);
        for (const reference of SKILLS.flatMap((skill) => skill.reference ?? [])) {
            const generated = interfaceMembers(readFileSync(join(SKILLS_DIR, reference), "utf-8"), false);
            expect(generated.size, reference).toBeGreaterThan(0);
            for (const [ name, members ] of generated) {
                const declared = source.get(`Script${name}`) ?? source.get(name);
                expect(declared, `${reference}: ${name} is not in script_api.ts`).toBeDefined();
                expect([ ...members ].sort(), `${reference}: ${name}`).toEqual([ ...(declared ?? []) ].sort());
            }
        }
    });

    it("asks the host's reader for the catalogued file name", () => {
        const asked: string[] = [];
        registerSkillReader((file) => {
            asked.push(file);
            return file === "search_syntax.md" ? "SHEET" : null;
        });

        expect(readSkill("search_syntax")).toBe("SHEET");
        expect(asked).toEqual(["search_syntax.md"]);
    });

    it("answers with nothing for a skill outside the catalog, without troubling the reader", () => {
        let asked = false;
        registerSkillReader(() => { asked = true; return "SHEET"; });

        expect(readSkill("no_such_skill")).toBeNull();
        expect(asked).toBe(false);
    });

    it("answers with nothing where no host has registered a reader", () => {
        clearReader();
        expect(readSkill("search_syntax")).toBeNull();
    });

    it("summarises the skills inline, never as a bulleted list", () => {
        // Bullets of `- name: description` read as a tool catalog to some models
        // (notably Gemini), which then invent calls to the skill names.
        const summary = getSkillsSummary();
        expect(summary).not.toContain("\n");
        for (const skill of SKILLS) {
            expect(summary).toContain(`"${skill.name}"`);
        }
    });
});

/**
 * The member names of each interface in TypeScript source, one member per line at a 4-space indent.
 * With `skipDeprecated`, a member whose doc comment carries `@deprecated` is left out, as the
 * generated references leave it out.
 */
function interfaceMembers(source: string, skipDeprecated: boolean) {
    const interfaces = new Map<string, Set<string>>();
    let members: Set<string> | undefined;
    let comment = "";
    for (const line of source.split("\n")) {
        const start = /^(?:export )?interface (\w+)/.exec(line);
        if (start) {
            members = new Set();
            interfaces.set(start[1], members);
            continue;
        }
        if (line.startsWith("}")) {
            members = undefined;
            continue;
        }

        if (/^ {4}\/\*\*/.test(line)) {
            comment = "";
        }
        if (/^ {4}(\/\*\*| \*)/.test(line)) {
            comment += line;
            continue;
        }
        const member = /^ {4}(?:readonly )?([\w$]+)[?(<:]/.exec(line);
        if (members && member) {
            if (!skipDeprecated || !comment.includes("@deprecated")) {
                members.add(member[1]);
            }
            comment = "";
        }
    }
    return interfaces;
}