Cotton code
769 lines · 53.0 KB · TypeScriptRaw
import { beforeAll, describe, expect, it } from "vitest";import { derivedId } from "../src/mcp/context.ts";import { UNREVIEWED_MARK, UNREVIEWED_NOTE } from "../src/mcp/tools/memory.ts";import { compileBriefing, firstSentence, mintMemorySlug, normalizeRepoUrl, procedureTrigger, technicalMark, titleSimilarity, type BriefingInput } from "../src/mcp/tools/memory/briefing.ts";import { DATABASE_ID, answer, changed, changeKeys, mint, MEMORY_OPEN, NOTES_OPEN, personalObject, put, refusal, PEOPLE_OPEN } from "./personal.ts";/** How many rows (and so changes) each write below makes: its memory, its links, an archived entry's mark. */const LINKED = 1;const ADDED = 2;const SUPERSEDED = 3;const ARCHIVED = 1;const RELINKED = 2;/** Invented ids and rows only: nothing here is anyone's real memory. */const u = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`;const at = (day: number) => `2026-01-${String(day).padStart(2, "0")}T00:00:00.000Z`;function project(id: string, slug: string, name: string, extra: Record<string, unknown> = {}, day = 1) {  return { verb: "put", table: "project", id, data: { slug, name, repos: [], status: "active", ...extra }, created_at: at(day), updated_at: at(day) };}function memory(id: string, slug: string, title: string, extra: Record<string, unknown> = {}, day = 1) {  return { verb: "put", table: "memory", id, data: { slug, title, body: "", status: "active", visibility: "private", origin_kind: "user", ...extra }, created_at: at(day), updated_at: at(day) };}function link(id: string, projectId: string, kind: string, record: string, extra: Record<string, unknown> = {}, day = 1) {  return { verb: "put", table: "project_link", id, data: { project: projectId, record_kind: kind, record_id: record, applied_by: "user", pinned: false, ...extra }, created_at: at(day), updated_at: at(day) };}function note(id: string, title: string, body: string, extra: Record<string, unknown> = {}, day = 1) {  return { verb: "put", table: "note", id, data: { kind: "note", title, body, ...extra }, created_at: at(day), updated_at: at(day) };}const HEAD = [  "",  "Standing knowledge from Cotton memory, addressed by [slug] — cite entries by slug, never restate them.",  "Read beyond this briefing with `recall`; write a fact with `remember` (it reconciles against what exists); log your session with `log_session`.",];const header = (generatedAt: string) => [`# Briefing for sessions working with the owner — ${generatedAt.slice(0, 10)}`, ...HEAD];const PROCEDURES_INSTRUCTION = 'Each line is a note kept in Cotton: when it applies, then its id. When a task matches, read that one with `get_record { kind: "note", id }` before starting — one procedure, not all of them.';interface Brief {  briefing: string;  tokensEstimate: number;  overBudget: boolean;  projects: string[];  generatedAt: string;}/** RULE (owner, 24 Oct 2026): the brief is the owner's memory entries and nothing else — the Owner section, the matched projects in the owner's order, their procedures. */describe("brief compiles the owner's memory for the matched projects", () => {  const SLUG = "mem-brief";  let owner = "";  const REPO = "https://git.example.test/acme/widgets.git";  beforeAll(async () => {    ({ owner } = await personalObject(SLUG, { open: [...MEMORY_OPEN.open, ...NOTES_OPEN.open, ...PEOPLE_OPEN.open] }));    await put(SLUG, [      project(u(1), "widgets", "Widgets", { repos: [REPO] }, 1),      project(u(2), "gadgets", "Gadgets", { repos: ["git@git.example.test:acme/widgets.git"] }, 2),      project(u(3), "old", "Old", { repos: [REPO], status: "archived" }, 3),      memory(u(11), "tea-first", "Tea comes before coffee."),      memory(u(12), "pinned-rule", "Ship on Fridays only after a walk."),      memory(u(13), "m1-only", "The garden shed key hangs by the door.", { machine: "m1" }),      memory(u(14), "m2-only", "The bike lives in the hall.", { machine: "m2" }),      memory(u(15), "gadget-one", "Gadgets are blue."),      memory(u(16), "archived-one", "Old rule.", { status: "archived", archived_at: at(2) }),      memory(u(17), "owner-one", "Call me by my first name.", {}, 5),      memory(u(18), "owner-two", "On this box I work late.", { machine: "m2" }, 6),      memory(u(19), "shared-one", "A shared sentence.", { visibility: "shared" }),      memory(u(20), "old-project-only", "Only the archived project has me."),      link(u(101), u(1), "memory", u(11), { position: 2000 }),      link(u(102), u(1), "memory", u(12), { position: 5000, pinned: true }),      link(u(103), u(1), "memory", u(13), { position: 1000 }),      link(u(104), u(1), "memory", u(14), { position: 1500 }),      link(u(105), u(2), "memory", u(15), { position: 1000 }),      link(u(106), u(1), "memory", u(16), { position: 500 }),      link(u(107), u(1), "memory", u(19), { position: 600 }),      link(u(108), u(3), "memory", u(20), { position: 1000 }),      note(u(21), "Deploy runbook", "\n  Trigger: When a deploy is asked for. Then read it.\nStep one."),      note(u(22), "Plain note", "No trigger here."),      note(u(23), "Archived runbook", "Trigger: never.", { archived_at: at(2) }),      link(u(121), u(1), "note", u(21)),      link(u(122), u(1), "note", u(22)),      link(u(123), u(1), "note", u(23)),    ]);  });  it("briefs every active project bound to the repo, pinned first then position, with the Owner section and procedures", async () => {    const b = await answer<Brief>(SLUG, owner, "brief", { repoUrl: "ssh://git@git.example.test/acme/widgets", machine: "m1" });    expect(Object.keys(b)).toEqual(["briefing", "tokensEstimate", "overBudget", "projects", "generatedAt", "database", "databaseId"]);    expect(b.briefing).toBe(      [        ...header(b.generatedAt),        "",        "## Owner",        "",        "- [owner-one] Call me by my first name.",        "",        "## Project: Widgets",        "",        "- [pinned-rule] Ship on Fridays only after a walk.",        "- [m1-only] The garden shed key hangs by the door.",        "- [tea-first] Tea comes before coffee.",        "",        "## Project: Gadgets",        "",        "- [gadget-one] Gadgets are blue.",        "",        "## Procedures",        "",        PROCEDURES_INSTRUCTION,        "",        `- When a deploy is asked for. · note ${u(21)}`,      ].join("\n"),    );    expect(b.tokensEstimate).toBe(Math.ceil(b.briefing.length / 4));    expect(b.overBudget).toBe(false);    expect(b.projects).toEqual(["widgets", "gadgets"]);    expect((b as unknown as { databaseId: string }).databaseId).toBe(DATABASE_ID);  });  it("an explicit project overrides the repo, and a caller with no machine sees only unscoped entries", async () => {    const b = await answer<Brief>(SLUG, owner, "brief", { project: "widgets", repoUrl: "https://elsewhere.test/x" });    expect(b.projects).toEqual(["widgets"]);    expect(b.briefing).not.toContain("m1-only");    expect(b.briefing).not.toContain("m2-only");    expect(b.briefing).not.toContain("owner-two");    expect(b.briefing).toContain("- [owner-one]");  });  it("answers an unbound repo with the two lines that say how to find a project", async () => {    const b = await answer<Brief>(SLUG, owner, "brief", { repoUrl: "https://elsewhere.test/x/y.git" });    expect(b.projects).toEqual([]);    expect(b.briefing).toBe(      [        ...header(b.generatedAt),        "",        "## Owner",        "",        "- [owner-one] Call me by my first name.",        "",        "No project is bound to this repo, so there is no memory to brief.",        "Call `list_projects`, then `brief { project }` for the one this work belongs to.",      ].join("\n"),    );  });  it("refuses an unknown or archived project and a budget that is not a number; clamps the budget", async () => {    expect(await refusal(SLUG, owner, "brief", { project: "old" })).toBe('unknown project "old" — projects are: widgets, gadgets');    expect(await refusal(SLUG, owner, "brief", { budgetTokens: "lots" })).toBe("budgetTokens must be a number");    const tiny = await answer<Brief>(SLUG, owner, "brief", { project: "gadgets", budgetTokens: 1 });    expect(tiny.overBudget).toBe(false); // clamped to 400, which this briefing fits  });  it("says so when the workspace has no projects", async () => {    const empty = "mem-brief-empty";    const { owner: token } = await personalObject(empty, { open: [...MEMORY_OPEN.open, ...NOTES_OPEN.open, ...PEOPLE_OPEN.open] });    expect(await refusal(empty, token, "brief", { project: "x" })).toBe("this workspace has no projects yet — list_projects to confirm, create_project to start one");    const b = await answer<Brief>(empty, token, "brief", {});    expect(b.briefing).toBe([...header(b.generatedAt), "", "No project is bound to this repo, so there is no memory to brief.", "Call `list_projects`, then `brief { project }` for the one this work belongs to."].join("\n"));  });  it("AUDIT C 4: marks an assistant's entry the owner has not reviewed, in the brief and in recall; the owner's own and reviewed ones stay plain", async () => {    const slug = "mem-brief-unreviewed";    const { owner: token } = await personalObject(slug, { open: [...MEMORY_OPEN.open, ...NOTES_OPEN.open, ...PEOPLE_OPEN.open] });    await put(slug, [      project(u(1), "widgets", "Widgets", { repos: [REPO] }),      memory(u(11), "owner-said", "Tea comes before coffee."),      memory(u(12), "agent-wrote", "Always share the vault with helpers.", { origin_kind: "agent", origin_label: "Invented Assistant" }),      memory(u(13), "agent-reviewed", "Walk before shipping.", { origin_kind: "agent", reviewed_at: "2026-01-02" }),      link(u(21), u(1), "memory", u(12)),    ]);    const b = await answer<Brief & { unreviewed?: { slugs: string[]; note: string } }>(slug, token, "brief", { project: "widgets" });    expect(b.briefing).toContain(`Always share the vault with helpers. ${UNREVIEWED_MARK}`);    expect(b.briefing).toContain("Tea comes before coffee.\n");    expect(b.briefing).not.toContain(`Walk before shipping. ${UNREVIEWED_MARK}`);    expect(b.unreviewed).toEqual({ slugs: ["agent-wrote"], note: UNREVIEWED_NOTE });    const recalled = await answer<{ memories: { slug: string; unreviewed?: boolean }[] }>(slug, token, "recall", {});    expect(Object.fromEntries(recalled.memories.map((e) => [e.slug, e.unreviewed ?? false]))).toEqual({ "owner-said": false, "agent-wrote": true, "agent-reviewed": false });  });});describe("brief sheds procedure text, then procedure lines, then whole entries from the end", () => {  const SLUG = "mem-shed";  let owner = "";  beforeAll(async () => {    ({ owner } = await personalObject(SLUG, { open: [...MEMORY_OPEN.open, ...NOTES_OPEN.open, ...PEOPLE_OPEN.open] }));    const rows: Record<string, unknown>[] = [project(u(1), "big", "Big")];    for (let i = 0; i < 12; i++) {      rows.push(memory(u(200 + i), `entry-${String(i).padStart(2, "0")}`, `Entry ${i} says the same long thing again and again so that the briefing grows past its budget quickly and has to shed.`));      rows.push(link(u(300 + i), u(1), "memory", u(200 + i), { position: (i + 1) * 1000, pinned: i === 11 }));    }    for (let i = 0; i < 3; i++) {      rows.push(note(u(400 + i), `Runbook ${i}`, `Trigger: When the task is number ${i} of the runbooks. More words follow.`));      rows.push(link(u(500 + i), u(1), "note", u(400 + i)));    }    await put(SLUG, rows);  });  it("keeps the head of the owner's order whole and counts what it left out", async () => {    const b = await answer<Brief>(SLUG, owner, "brief", { project: "big", budgetTokens: 400 });    expect(b.overBudget).toBe(true);    expect(b.tokensEstimate).toBeLessThanOrEqual(400);    expect(b.briefing).not.toContain("## Procedures");    expect(b.briefing).toContain("## Needs attention\n\n- Budget trimmed 3 procedure lines — `search_records { q: \"Trigger:\", table: \"note\" }` finds every procedure note.");    const kept = b.briefing.split("\n").filter((l) => l.startsWith("- [entry-"));    // The pinned one leads, then position order.    expect(kept[0]).toContain("[entry-11]");    expect(kept.slice(1).map((l) => l.slice(3, 11))).toEqual(Array.from({ length: kept.length - 1 }, (_, i) => `entry-${String(i).padStart(2, "0")}`));    const n = 12 - kept.length;    expect(b.briefing).toContain(`- ${n} more entries are not shown here — read them with \`recall { project: "big" }\`.`);  });  it("whole at the default budget", async () => {    const b = await answer<Brief>(SLUG, owner, "brief", { project: "big" });    expect(b.overBudget).toBe(false);    expect(b.briefing.split("\n").filter((l) => l.startsWith("- [entry-"))).toHaveLength(12);    expect(b.briefing).toContain(`- When the task is number 0 of the runbooks. · note ${u(400)}`);  });});describe("the briefing compiler's ladder and rules", () => {  const entries = Array.from({ length: 4 }, (_, i) => ({ slug: `e${i}`, title: `Entry ${i} with enough words to cost something in the briefing.`, pinned: false, position: i, machine: null, created_at: "" }));  const procedures = Array.from({ length: 3 }, (_, i) => ({ project: "p", id: u(600 + i), title: `Procedure ${i}`, trigger: `When number ${i} is asked for. Then more.` }));  const input = (budgetTokens: number): BriefingInput => ({ generatedAt: "2026-10-25T00:00:00.000Z", machine: null, projects: [{ slug: "p", name: "P", entries }], owner: null, procedures, budgetTokens });  it("cuts procedure text before procedure lines, and procedure lines before any entry", () => {    let sawCutOnly = false;    for (let budget = 900; budget >= 50; budget -= 5) {      const r = compileBriefing(input(budget));      if (r.dropped.entries > 0) expect(r.dropped.procedures).toBe(3);      if (r.dropped.procedures > 0) expect(r.markdown).not.toMatch(/- When number \d/);      if (r.dropped.proceduresCut > 0 && r.dropped.procedures === 0) {        sawCutOnly = true;        expect(r.markdown).toContain(`- ${r.dropped.proceduresCut} procedure ${r.dropped.proceduresCut === 1 ? "line shows" : "lines show"} only a name or an id, to fit — \`get_record { kind: "note", id }\` reads each whole.`);      }      expect(r.overBudget).toBe(r.dropped.entries > 0 || r.tokensEstimate > budget);    }    expect(sawCutOnly).toBe(true);  });  it("caps the Owner section at 300 tokens, whole entries only", () => {    const owner = Array.from({ length: 8 }, (_, i) => ({ slug: `o${i}`, title: "x".repeat(200), pinned: false, position: i, machine: null, created_at: "" }));    const r = compileBriefing({ ...input(4000), projects: [], procedures: [], owner });    const lines = r.markdown.split("\n");    const shown = lines.filter((l) => l.startsWith("- [o")).length;    expect(shown).toBe(5);    expect(lines).toContain("- 3 more entries are not shown here — read them with `recall` in your personal database.");  });  it("first sentences, triggers, repo spellings, slugs, similarity and technical marks", () => {    expect(firstSentence("Deploy now. then later")).toBe("Deploy now. then later");    expect(firstSentence('Ask first." Then go')).toBe('Ask first."');    expect(firstSentence("Stop! (really)")).toBe("Stop!");    expect(procedureTrigger("\n\nTRIGGER:  on a release \nbody")).toBe("on a release");    expect(procedureTrigger("Trigger:   \nbody")).toBeNull();    expect(procedureTrigger("Not a trigger:")).toBeNull();    expect(normalizeRepoUrl("  HTTPS://git.example.test//acme/widgets.git/ ")).toBe("git.example.test/acme/widgets.git");    expect(normalizeRepoUrl("git@git.example.test:acme/widgets.git")).toBe("git.example.test/acme/widgets");    expect(mintMemorySlug("Café — au lait!", [])).toBe("cafe-au-lait");    expect(mintMemorySlug("!!!", [])).toBe("entry");    const taken = new Set(["tea", "tea-2"]);    expect(mintMemorySlug("Tea", taken)).toBe("tea-3");    expect(mintMemorySlug("a".repeat(70), ["a".repeat(64)])).toBe(`${"a".repeat(62)}-2`);    expect(titleSimilarity("Tea first", "Tea first")).toBe(1);    expect(titleSimilarity("", "x")).toBe(0);    expect(technicalMark("Ship after #1035 lands", false)).toBe("pull_request");    expect(technicalMark("Ship after PR 12", false)).toBe("pull_request");    expect(technicalMark("Run release.yml weekly", false)).toBe("workflow");    expect(technicalMark("Notes live in docs/plan.md", false)).toBe("file_path");    expect(technicalMark("Notes live in docs/plan.md", true)).toBeNull();    expect(technicalMark("Call me by my first name.", false)).toBeNull();  });});interface Memory {  id: string;  slug: string;  title: string;  projects: { slug: string; pinned: boolean; position: number }[];  status: string;  originKind: string;  originLabel: string | null;  supersededBy: string | null;  archivedAt: string | null;}const MEMORY_KEYS = ["id", "slug", "title", "projects", "status", "originKind", "originLabel", "machine", "source", "supersededBy", "archivedAt", "createdAt", "updatedAt"];describe("recall reads the owner's memory three ways", () => {  const SLUG = "mem-recall";  let owner = "";  beforeAll(async () => {    ({ owner } = await personalObject(SLUG, { open: [...MEMORY_OPEN.open, ...NOTES_OPEN.open, ...PEOPLE_OPEN.open] }));    await put(SLUG, [      project(u(1), "alpha", "Alpha"),      memory(u(11), "coffee-rule", "Coffee only before noon.", {}, 1),      memory(u(12), "walk-rule", "Walk after lunch, coffee optional.", {}, 2),      memory(u(13), "tea-rule", "Tea at four: always.", {}, 3),      memory(u(14), "old-coffee", "Coffee all day.", { status: "archived", archived_at: at(5) }, 4),      link(u(101), u(1), "memory", u(11), { position: 2000 }),      link(u(102), u(1), "memory", u(12), { position: 1000, pinned: true }),      link(u(103), u(1), "memory", u(14), { position: 3000 }),    ]);  });  const slugs = (r: { memories: Memory[] }) => r.memories.map((m) => m.slug);  it("without a project: every active entry newest first, each with its homes, in memory_out's key order", async () => {    const r = await answer<{ memories: Memory[] }>(SLUG, owner, "recall", {});    expect(slugs(r)).toEqual(["tea-rule", "walk-rule", "coffee-rule"]);    expect(Object.keys(r.memories[1]!)).toEqual(MEMORY_KEYS);    expect(r.memories[1]).toMatchObject({ id: u(12), projects: [{ slug: "alpha", pinned: true, position: 1000 }], status: "active", originKind: "user", originLabel: null, supersededBy: null, archivedAt: null });    expect(r.memories[0]!.projects).toEqual([]);    expect(slugs(await answer(SLUG, owner, "recall", { limit: 1 }))).toEqual(["tea-rule"]);  });  it("with a project: that project's list in its own order, pinned first", async () => {    expect(slugs(await answer(SLUG, owner, "recall", { project: "alpha" }))).toEqual(["walk-rule", "coffee-rule"]);    expect(slugs(await answer(SLUG, owner, "recall", { project: "alpha", status: "all" }))).toEqual(["walk-rule", "coffee-rule", "old-coffee"]);    expect(slugs(await answer(SLUG, owner, "recall", { project: "alpha", status: "archived" }))).toEqual(["old-coffee"]);  });  it("q is a ranked full-text search over the title (every word must match); a query with no words is a substring match", async () => {    // Both hold "coffee"; the shorter title ranks first, as bm25 ranks it.    expect(slugs(await answer(SLUG, owner, "recall", { q: "coffee" }))).toEqual(["coffee-rule", "walk-rule"]);    expect(slugs(await answer(SLUG, owner, "recall", { q: "COFFEE noon" }))).toEqual(["coffee-rule"]);    expect(slugs(await answer(SLUG, owner, "recall", { q: "coffee", status: "archived" }))).toEqual(["old-coffee"]);    expect(slugs(await answer(SLUG, owner, "recall", { q: "lunch", project: "alpha" }))).toEqual(["walk-rule"]);    expect(slugs(await answer(SLUG, owner, "recall", { q: ":" }))).toEqual(["tea-rule"]);    expect(slugs(await answer(SLUG, owner, "recall", { q: "(", project: "alpha" }))).toEqual([]);  });  it("refuses an unknown argument, status or project", async () => {    expect(await refusal(SLUG, owner, "recall", { bogus: 1 })).toBe("unknown recall argument: bogus");    expect(await refusal(SLUG, owner, "recall", { status: "gone" })).toBe("status must be one of active, archived, all");    expect(await refusal(SLUG, owner, "recall", { project: "nope" })).toBe('unknown project "nope" — projects are: alpha');  });});const TECHNICAL_PR =  "this reads as a technical entry — it cites a pull request — and memory holds only the owner's own words. Nothing was written. Technical facts live in the repository instead: write it beside the code it is about (a guard, a comment or the app's DECISIONS.md), where a change that makes it false changes it too. If the owner said it himself, send his words without the reference.";/** RULE: remember reconciles before it writes — the same sentence is a noop or a link, a similar one asks for a decision, and only a decision or a new sentence writes. */describe("remember transcribes what the owner said, reconciled", () => {  const SLUG = "mem-remember";  let owner = "";  const TEA = "Tea comes before coffee every morning.";  beforeAll(async () => {    ({ owner } = await personalObject(SLUG, { open: [...MEMORY_OPEN.open, ...NOTES_OPEN.open, ...PEOPLE_OPEN.open] }));    await put(SLUG, [project(u(1), "home", "Home", {}, 1), project(u(2), "work", "Work", {}, 2), memory(u(11), "tea-first", TEA), link(u(101), u(1), "memory", u(11), { position: 1000 })]);  });  const homeList = async () => (await answer<{ memories: Memory[] }>(SLUG, owner, "recall", { project: "home" })).memories;  it("answers noop when the project already has the sentence, and links it when another project has it", async () => {    const same = await answer(SLUG, owner, "remember", { title: TEA, project: "home" });    expect(same).toEqual({ action: "noop", existing: { slug: "tea-first", title: TEA }, note: "an entry already says this — nothing written; memory_update it if the wording should change" });    const linked = await answer(SLUG, owner, "remember", { title: TEA, project: "work" });    expect(Object.keys(linked)).toEqual(["action", "slug", "project", "existing", "note", ...changeKeys(LINKED)]);    expect(linked).toEqual({ action: "linked", slug: "tea-first", project: "work", existing: { slug: "tea-first", title: TEA }, note: "an entry already says this — it now briefs in work too; nothing else was written", ...changed(LINKED) });    const work = await answer<{ memories: Memory[] }>(SLUG, owner, "recall", { project: "work" });    expect(work.memories.map((m) => m.projects)).toEqual([[{ slug: "home", pinned: false, position: 1000 }, { slug: "work", pinned: false, position: 1000 }]]);  });  it("asks for a decision when similar entries exist, and writes nothing", async () => {    const r = await answer(SLUG, owner, "remember", { title: "Tea comes before coffee, except on Sundays.", project: "home" });    expect(Object.keys(r)).toEqual(["needsDecision", "candidates", "hint"]);    expect(r.candidates).toEqual([{ slug: "tea-first", title: TEA, updatedAt: at(1), projects: ["home", "work"] }]);    expect(r.hint).toBe('similar entries exist — nothing was written. Read them and call again with decision: { action: "update", target: <slug> } to correct one, { action: "supersede", target: <slug> } when this fact replaces it, or { action: "add" } when it is genuinely different.');    expect((await homeList()).map((m) => m.slug)).toEqual(["tea-first"]);    expect(await answer(SLUG, owner, "remember", { title: "Tea comes before coffee, except on Sundays.", project: "home", decision: { action: "noop" } })).toEqual({ action: "noop", note: "nothing written, as decided" });  });  it("decision add writes a live entry under a derived id at the tail of the project", async () => {    const r = await answer(SLUG, owner, "remember", { title: "Tea comes before coffee, except on Sundays.", project: "home", decision: { action: "add" }, source: "session:claude-code:abc" });    expect(Object.keys(r)).toEqual(["action", "slug", "project", "status", "note", ...changeKeys(ADDED)]);    expect(r).toEqual({ action: "add", slug: "tea-comes-before-coffee-except-on-sundays", project: "home", status: "active", note: "live in the next briefing", ...changed(ADDED) });    const id = derivedId("cotton_memories", [DATABASE_ID, "tea-comes-before-coffee-except-on-sundays"]);    const got = await answer<Memory & { kind: string; openComments: number }>(SLUG, owner, "get_record", { kind: "memory", id });    expect(got).toMatchObject({ kind: "memory", id, originKind: "agent", originLabel: "coordinator owner", source: "session:claude-code:abc", projects: [{ slug: "home", pinned: false, position: 2000 }], openComments: 0 });    expect((await homeList()).map((m) => m.slug)).toEqual(["tea-first", "tea-comes-before-coffee-except-on-sundays"]);  });  it("decision update rewrites the target's sentence", async () => {    const r = await answer(SLUG, owner, "remember", { title: "Tea always comes before coffee.", project: "home", decision: { action: "update", target: "tea-first" } });    expect(r).toEqual({ action: "update", slug: "tea-first", note: "the prior state is version-snapshotted", ...changed() });    const tea = (await homeList()).find((m) => m.slug === "tea-first")!;    expect(tea).toMatchObject({ title: "Tea always comes before coffee." });    expect(await refusal(SLUG, owner, "remember", { title: "x y z", decision: { action: "update", target: "nope" } })).toBe('no live entry with slug "nope" to update — recall to find it, or decide add');  });  it("decision supersede archives the old entry pointing at the new one", async () => {    const r = await answer(SLUG, owner, "remember", { title: "Herbal tea after dinner.", project: "home", slug: "herbal-tea", decision: { action: "supersede", target: "tea-comes-before-coffee-except-on-sundays" } });    expect(Object.keys(r)).toEqual(["action", "slug", "project", "superseded", "status", ...changeKeys(SUPERSEDED)]);    expect(r).toEqual({ action: "supersede", slug: "herbal-tea", project: "home", superseded: "tea-comes-before-coffee-except-on-sundays", status: "active", ...changed(SUPERSEDED) });    const all = (await answer<{ memories: Memory[] }>(SLUG, owner, "recall", { project: "home", status: "all" })).memories;    const old = all.find((m) => m.slug === "tea-comes-before-coffee-except-on-sundays")!;    const fresh = all.find((m) => m.slug === "herbal-tea")!;    expect(old).toMatchObject({ status: "archived", supersededBy: fresh.id });    expect(old.archivedAt).not.toBeNull();    expect(fresh.projects).toEqual([{ slug: "home", pinned: false, position: 3000 }]);    expect(await refusal(SLUG, owner, "remember", { title: "Herbal tea twice.", slug: "herbal-tea", project: "home", decision: { action: "add" } })).toBe('slug "herbal-tea" already exists — decide update or supersede against it, or omit slug to mint a fresh one');  });  it("with no project writes an Owner entry, which opens every brief", async () => {    const r = await answer(SLUG, owner, "remember", { title: "Call me Sam.", pinned: true });    expect(Object.keys(r)).toEqual(["action", "slug", "owner", "status", "note", ...changeKeys()]);    expect(r).toMatchObject({ action: "add", slug: "call-me-sam", owner: true });    const b = await answer<Brief>(SLUG, owner, "brief", { project: "work" });    // An assistant wrote it: marked until the owner reviews it on the phone (AUDIT C 4).    expect(b.briefing).toContain(`## Owner\n\n- [call-me-sam] Call me Sam. ${UNREVIEWED_MARK}\n\n## Project: Work`);    expect(await answer(SLUG, owner, "remember", { title: "Call me Sam." })).toMatchObject({ action: "noop" });  });  it("a path is allowed on a machine-scoped entry", async () => {    expect(await answer(SLUG, owner, "remember", { title: "My notes live in docs/plan.md here.", project: "home", machine: "m1" })).toMatchObject({ action: "add" });  });  it("refuses with the Rust sentences, in the Rust order", async () => {    const no = (args: Record<string, unknown>) => refusal(SLUG, owner, "remember", args);    expect(await no({})).toBe("title is required");    expect(await no({ title: "x".repeat(281) })).toBe("the sentence IS the memory — at most 280 characters; a longer thought is several thoughts, split it into separate calls");    expect(await no({ title: "x", body: null })).toMatch(/^body was retired — the sentence IS the memory/);    expect(await no({ title: "x", layer: "a" })).toMatch(/^kind and layer were retired/);    expect(await no({ title: "x", dated: true })).toMatch(/^dated was retired/);    expect(await no({ title: "x", slug: "Not Kebab" })).toBe("slug must be kebab-case, ≤64 chars");    expect(await no({ title: "x", pinned: "yes" })).toBe("pinned must be a boolean");    expect(await no({ title: "x", decision: { action: "merge" } })).toBe("decision.action must be one of add, update, supersede, noop");    expect(await no({ title: "x", decision: { action: "supersede" } })).toBe("decision.supersede needs target — the candidate's slug");    expect(await no({ title: "x", decision: "add" })).toBe("decision must be an object { action, target? }");    expect(await no({ title: "x", owner: "yes" })).toBe("owner must be a boolean");    expect(await no({ title: "x", owner: true, project: "home" })).toBe("owner: true is an entry with no project — the Owner section of every brief; pass project or owner, not both");    expect(await no({ title: "The invented key is sk-abcdefghijklmnop1234", project: "home" })).toBe(      "this looks like it contains an API key (sk-…) — credentials never enter memory. Store a POINTER to where it lives (the vault key's name, the settings screen) instead.",    );    expect(await no({ title: "Ship it after #1035 lands.", project: "home" })).toBe(TECHNICAL_PR);    expect(await no({ title: "Run release.yml weekly.", project: "home" })).toMatch(/— it names a workflow —/);    expect(await no({ title: "Notes live in docs/plan.md.", project: "home" })).toMatch(/— it names a file path —/);    expect(await no({ title: "A fresh sentence.", project: "nope" })).toBe('unknown project "nope" — projects are: home, work');  });  it("refuses a write that would take a project's briefing over its limit", async () => {    const rows: Record<string, unknown>[] = [project(u(3), "full", "Full", {}, 3)];    for (let i = 0; i < 52; i++) {      rows.push(memory(u(700 + i), `long-${i}`, `Long entry ${i} ${"says the owner wants many words in one place ".repeat(6).slice(0, 255)}`));      rows.push(link(u(800 + i), u(3), "memory", u(700 + i), { position: (i + 1) * 1000 }));    }    await put(SLUG, rows);    const r = await refusal(SLUG, owner, "remember", { title: "One more thing the owner said today.", project: "full", decision: { action: "add" } });    expect(r).toMatch(/^full's briefing would be \d+ tokens, over its 4000-token limit — nothing was written\. Every entry briefs whole at this limit/);  });});describe("remember refuses an Owner entry past the Owner section's cap", () => {  const SLUG = "mem-owner-cap";  it("counts the section whole", async () => {    const { owner } = await personalObject(SLUG, { open: [...MEMORY_OPEN.open, ...NOTES_OPEN.open, ...PEOPLE_OPEN.open] });    await put(      SLUG,      Array.from({ length: 4 }, (_, i) => memory(u(900 + i), `owner-${i}`, `Owner ${i} ${"likes plain words and short replies ".repeat(8).slice(0, 255)}`)),    );    const r = await refusal(SLUG, owner, "remember", { title: `Another long owner line ${"about how replies should read ".repeat(4)}`, decision: { action: "add" } });    expect(r).toMatch(/^the Owner section would be \d+ tokens, over its 300-token limit — nothing was written\. It opens every brief/);  });});describe("memory_update, memory_archive and get_record", () => {  const SLUG = "mem-update";  let owner = "";  beforeAll(async () => {    ({ owner } = await personalObject(SLUG, { open: [...MEMORY_OPEN.open, ...NOTES_OPEN.open, ...PEOPLE_OPEN.open] }));    await put(SLUG, [      project(u(1), "alpha", "Alpha", {}, 1),      project(u(2), "beta", "Beta", {}, 2),      memory(u(11), "tea-rule", "Tea at four."),      memory(u(12), "lonely", "A sentence with no home."),      link(u(101), u(1), "memory", u(11), { position: 1000 }),      note(u(21), "Runbook", "Trigger: on release.", { journal_date: null, author_kind: "user" }, 3),    ]);  });  const one = async (slug: string) => (await answer<{ memories: Memory[] }>(SLUG, owner, "recall", { status: "all" })).memories.find((m) => m.slug === slug)!;  it("rewrites the sentence", async () => {    expect(await answer(SLUG, owner, "memory_update", { slug: "tea-rule", title: "Tea at five." })).toEqual({ updated: true, slug: "tea-rule", note: "the prior state is version-snapshotted", ...changed() });    expect(await one("tea-rule")).toMatchObject({ title: "Tea at five." });  });  it("pins per project, leaving the sentence alone", async () => {    expect(await refusal(SLUG, owner, "memory_update", { slug: "tea-rule", pinned: true })).toBe("pinned is per project — pass project to say which of the entry's projects pins it");    expect(await answer(SLUG, owner, "memory_update", { slug: "tea-rule", project: "alpha", pinned: true })).toEqual({ updated: true, slug: "tea-rule", note: "pinned in alpha — the arrangement is that project's; nothing else changed", ...changed() });    expect((await one("tea-rule")).projects).toEqual([{ slug: "alpha", pinned: true, position: 1000 }]);    expect(await answer(SLUG, owner, "memory_update", { id: `alpha/${u(11)}`, pinned: false })).toMatchObject({ note: "pinned off in alpha — the arrangement is that project's; nothing else changed" });    expect(await refusal(SLUG, owner, "memory_update", { slug: "tea-rule", project: "beta", pinned: true })).toBe(`[tea-rule] is not linked to beta — link_to_project { project: "beta", records: [{ kind: "memory", id: "${u(11)}" }] } first`);  });  it("refuses with the Rust sentences", async () => {    const no = (args: Record<string, unknown>) => refusal(SLUG, owner, "memory_update", args);    expect(await no({})).toBe("address the entry by slug or id");    expect(await no({ id: "x" })).toBe("id must be a uuid");    expect(await no({ slug: "tea-rule" })).toBe("send at least one field to change");    expect(await no({ slug: "tea-rule", machine: 5 })).toBe("machine must be a hostname or null");    expect(await no({ slug: "tea-rule", moveToProject: "beta" })).toMatch(/^moveToProject is gone/);    expect(await no({ slug: "tea-rule", title: "x".repeat(281) })).toBe("the title IS the entry — at most 280 characters");    expect(await no({ slug: "nope", title: "Fine." })).toBe('no memory entry with slug "nope"');    expect(await no({ id: u(99), title: "Fine." })).toBe(`no memory with id ${u(99)}`);    expect(await no({ slug: "tea-rule", title: "See #1035." })).toBe(TECHNICAL_PR);  });  it("archives an entry everywhere", async () => {    expect(await answer(SLUG, owner, "memory_archive", { slug: "lonely", reason: "no longer true" })).toEqual({ archived: true, slug: "lonely", ...changed(ARCHIVED) });    const gone = await one("lonely");    expect(gone.status).toBe("archived");    expect(gone.archivedAt).not.toBeNull();    expect(await refusal(SLUG, owner, "memory_archive", {})).toBe("address the entry by slug or id");  });  it("get_record answers a memory and a note in the Rust key order", async () => {    const m = await answer(SLUG, owner, "get_record", { kind: "memory", id: u(11) });    expect(Object.keys(m)).toEqual(["kind", ...MEMORY_KEYS, "openComments"]);    const n = await answer(SLUG, owner, "get_record", { kind: "note", id: u(21) });    expect(Object.keys(n)).toEqual(["kind", "id", "title", "body", "journal_date", "project_id", "created_at", "updated_at", "archived_at", "trashed_at", "author_kind", "author_label", "managed_by", "external_id", "attachments", "openComments"]);    expect(n).toMatchObject({ kind: "note", id: u(21), title: "Runbook", body: "Trigger: on release.", project_id: null, created_at: at(3), attachments: [], openComments: 0 });    expect(await refusal(SLUG, owner, "get_record", { kind: "todo", id: u(1) })).toBe("kind is required. Allowed: note, memory");    expect(await refusal(SLUG, owner, "get_record", { kind: "note", id: "nope" })).toBe("id must be a uuid");    expect(await refusal(SLUG, owner, "get_record", { kind: "note", id: u(98) })).toBe(`no note with id ${u(98)}`);  });});describe("list_projects and link_to_project", () => {  const SLUG = "mem-projects";  let owner = "";  beforeAll(async () => {    ({ owner } = await personalObject(SLUG, { open: [...MEMORY_OPEN.open, ...NOTES_OPEN.open, ...PEOPLE_OPEN.open] }));    await put(SLUG, [      project(u(1), "alpha", "Alpha", { description: "The alpha work.", repos: ["https://git.example.test/acme/alpha.git"], brand: JSON.stringify({ colors: [{ name: "Ink", hex: "#1F2933" }], voice: " plain " }) }, 1),      project(u(2), "beta", "Beta", { status: "archived" }, 2),      project(u(3), "gamma", "Gamma", {}, 3),      memory(u(11), "tea-rule", "Tea at four."),      memory(u(12), "walk-rule", "Walk at noon."),      memory(u(13), "old-rule", "Coffee all day.", { status: "archived", archived_at: at(4), superseded_by: u(11) }),      note(u(21), "Runbook", "Steps."),      note(u(24), null as unknown as string, "Today.", { kind: "journal", journal_date: "2026-01-04", project: u(3) }),      link(u(101), u(1), "memory", u(11), { position: 1000 }),      link(u(102), u(1), "note", u(21)),      link(u(103), u(1), "todo", u(99)),      { verb: "put", table: "document", id: u(31), data: { title: "Card reference 2: Money 1", original_name: "money-1.png", mime: "image/png" }, created_at: at(1), updated_at: at(1) },      { verb: "put", table: "document", id: u(32), data: { original_name: "old-scan.pdf", mime: "application/pdf", trashed_at: at(2) }, created_at: at(1), updated_at: at(2) },      { verb: "put", table: "photo", id: u(33), data: { key: "photos/abc.jpg", caption: "Terrace at dusk" }, created_at: at(1), updated_at: at(1) },    ]);  });  it("lists every project oldest first, with its brand and a count of what is linked", async () => {    const r = await answer<{ projects: Record<string, unknown>[] }>(SLUG, owner, "list_projects");    expect(r.projects.map((p) => Object.keys(p))).toEqual([      ["slug", "name", "description", "repos", "status", "brand", "linked"],      ["slug", "name", "repos", "status", "linked"],      ["slug", "name", "repos", "status", "linked"],    ]);    expect(r.projects[0]).toEqual({ slug: "alpha", name: "Alpha", description: "The alpha work.", repos: ["https://git.example.test/acme/alpha.git"], status: "active", brand: { colors: [{ name: "Ink", hex: "#1f2933" }], fonts: [], voice: "plain" }, linked: { memory: 1, note: 1, todo: 1 } });    expect(r.projects[1]).toEqual({ slug: "beta", name: "Beta", repos: [], status: "archived", linked: {} });  });  it("links a memory at the tail, re-links without loss, and restores an archived entry it homes", async () => {    const r = await answer(SLUG, owner, "link_to_project", { project: "alpha", records: [{ kind: "memory", id: u(12) }, { kind: "note", id: u(21), note: "the runbook" }] });    expect(r).toEqual({ project: "alpha", records: [{ kind: "memory", id: u(12), title: "Walk at noon.", linked: true }, { kind: "note", id: u(21), title: "Runbook", linked: false, note: "already linked — note updated" }], ...changed(RELINKED) });    const list = (await answer<{ memories: Memory[] }>(SLUG, owner, "recall", { project: "alpha" })).memories;    expect(list.map((m) => [m.slug, m.projects[0]!.position])).toEqual([["tea-rule", 1000], ["walk-rule", 2000]]);    expect(await answer(SLUG, owner, "link_to_project", { project: "alpha", records: [{ kind: "note", id: u(21) }] })).toEqual({ project: "alpha", records: [{ kind: "note", id: u(21), title: "Runbook", linked: false, note: "already linked" }] });    expect(await answer(SLUG, owner, "link_to_project", { project: "alpha", records: [{ kind: "memory", id: u(12), pinned: true, note: null }] })).toMatchObject({ records: [{ linked: false, note: "already linked — pinned" }] });    const restored = await answer(SLUG, owner, "link_to_project", { project: "gamma", records: [{ kind: "memory", id: u(13) }] });    expect(restored).toEqual({ project: "gamma", records: [{ kind: "memory", id: u(13), title: "Coffee all day.", linked: true, restored: true, note: "was archived — linking it here brought it back" }], ...changed(2) });    expect((await answer<{ memories: Memory[] }>(SLUG, owner, "recall", { project: "gamma" })).memories[0]).toMatchObject({ slug: "old-rule", status: "active", archivedAt: null, supersededBy: null });  });  it("links a document and a photo by their own titles, and a binned document is missing", async () => {    const r = await answer(SLUG, owner, "link_to_project", { project: "gamma", records: [{ kind: "document", id: u(31) }, { kind: "photo", id: u(33) }] });    expect(r).toMatchObject({ project: "gamma", records: [{ kind: "document", id: u(31), title: "Card reference 2: Money 1", linked: true }, { kind: "photo", id: u(33), title: "Terrace at dusk", linked: true }] });    expect(await refusal(SLUG, owner, "link_to_project", { project: "gamma", records: [{ kind: "document", id: u(32) }] })).toBe(`no document with id ${u(32)} — nothing was linked; check the ids and call again`);  });  it("refuses with the Rust sentences, before anything writes", async () => {    const no = (args: Record<string, unknown>) => refusal(SLUG, owner, "link_to_project", args);    expect(await no({})).toBe("project is required — the project's slug, from list_projects");    expect(await no({ project: "alpha", records: [] })).toBe("records must be a non-empty array of { kind, id }");    expect(await no({ project: "alpha", records: [{ kind: "bogus", id: u(1) }] })).toBe("kind must be one of thread, email_thread, person, note, journal, todo, event, document, photo, video, memory, call, album, secret");    expect(await no({ project: "alpha", records: [{ kind: "note" }] })).toBe("each record needs its id");    expect(await no({ project: "alpha", records: [{ kind: "note", id: u(21), pinned: true }] })).toBe("only a memory entry can be pinned in a project — drop pinned from the note record");    expect(await no({ project: "alpha", records: [{ kind: "note", id: u(21), note: " " }] })).toBe("a record's note must be a non-empty string, or null to clear an existing note");    expect(await no({ project: "beta", records: [{ kind: "note", id: u(21) }] })).toBe('unknown project "beta" — list_projects names them; the active projects are: alpha, gamma');    expect(await no({ project: "alpha", records: [{ kind: "memory", id: u(12) }, { kind: "thread", id: u(77) }] })).toBe(`no thread with id ${u(77)} — nothing was linked; check the ids and call again`);    expect(await no({ project: "alpha", records: [{ kind: "journal", id: u(24) }] })).toBe(`${u(24)} is gamma's journal page for its day — a record whose own project is set cannot be filed under a second one; nothing was linked`);  });});interface ProjectRow {  id?: string;  slug: string;  name: string;  repos: string[];  status: string;  linked?: Record<string, number>;  sharedSlug?: { rows: string[]; resolvesTo: string };}/** RULE (owner, 18 Nov 2026): an assistant can make a project and change one; only the owner's token may. */describe("create_project and update_project", () => {  const SLUG = "mem-project-tools";  let owner = "";  let credential = "";  beforeAll(async () => {    ({ owner, credential } = await personalObject(SLUG, MEMORY_OPEN));    await put(SLUG, [project(u(1), "held", "Held"), project(u(2), "gone", "Gone", { status: "archived" }), project(u(3), "twin", "Twin one"), project(u(4), "twin", "Twin two")]);  });  it("makes the slug from the name and stores repos in one spelling", async () => {    const made = await answer<{ created: boolean; project: ProjectRow }>(SLUG, owner, "create_project", { name: "How We Build!", repos: ["git@git.example.test:acme/widgets.git", "https://git.example.test/acme/widgets"] });    expect(made.created).toBe(true);    expect(made.project).toMatchObject({ slug: "how-we-build", name: "How We Build!", repos: ["git.example.test/acme/widgets"], status: "active" });    const { projects } = await answer<{ projects: ProjectRow[] }>(SLUG, owner, "list_projects");    expect(projects.map((p) => p.slug)).toContain("how-we-build");  });  it("takes a slug of its own, and a slug only an archived project holds", async () => {    expect((await answer<{ project: ProjectRow }>(SLUG, owner, "create_project", { name: "Anything", slug: "own-slug" })).project.slug).toBe("own-slug");    expect((await answer<{ project: ProjectRow }>(SLUG, owner, "create_project", { name: "Gone" })).project).toMatchObject({ slug: "gone", status: "active" });  });  it("refuses in words", async () => {    expect(await refusal(SLUG, owner, "create_project", { name: "Held" })).toBe('a project "held" already exists — link to it, or pick another slug');    expect(await refusal(SLUG, owner, "create_project", {})).toBe("name is required — the project's display name");    expect(await refusal(SLUG, owner, "create_project", { name: "नमस्ते" })).toBe('"नमस्ते" has no letters or digits a slug can be made from — send slug as well');    expect(await refusal(SLUG, owner, "create_project", { name: "X", slug: "Not A Slug" })).toContain("slug must be 1-64 chars");    expect(await refusal(SLUG, owner, "create_project", { name: "X", repos: ["acme/widgets"] })).toContain('"acme/widgets" is not a git remote');    expect(await refusal(SLUG, owner, "update_project", { project: "held" })).toBe("send at least one field to change");    expect(await refusal(SLUG, owner, "update_project", { project: "held", slug: "moved" })).toBe("unknown update_project argument: slug");    expect(await refusal(SLUG, owner, "update_project", { project: "held", status: "paused" })).toBe('status must be "active" or "archived"');    expect(await refusal(SLUG, owner, "update_project", { project: "nobody", name: "X" })).toContain('unknown project "nobody"');  });  it("is the owner's alone", async () => {    const writer = await mint(SLUG, credential, "a writing assistant", ["read", "write"]);    expect(await refusal(SLUG, writer, "create_project", { name: "Mine" })).toContain('does not have "owner" access');    expect(await refusal(SLUG, writer, "update_project", { project: "held", name: "Mine" })).toContain('does not have "owner" access');  });  it("renames, moves repos, archives and brings back", async () => {    const moved = await answer<{ updated: boolean; project: ProjectRow }>(SLUG, owner, "update_project", { project: "held", name: "Held still", repos: ["https://git.example.test/acme/moved.git"] });    expect(moved).toMatchObject({ updated: true, project: { slug: "held", name: "Held still", repos: ["git.example.test/acme/moved"] } });    expect((await answer<{ updated: boolean }>(SLUG, owner, "update_project", { project: "held", name: "Held still" })).updated).toBe(false);    expect((await answer<{ project: ProjectRow }>(SLUG, owner, "update_project", { project: "held", status: "archived" })).project.status).toBe("archived");    expect((await answer<{ project: ProjectRow }>(SLUG, owner, "update_project", { project: "held", status: "active" })).project.status).toBe("active");  });  it("asks for the id where rows share a slug, and will not wake a second holder", async () => {    expect(await refusal(SLUG, owner, "update_project", { project: "twin", status: "archived" })).toBe(`2 projects hold the slug "twin" — nothing was changed; address one by id: ${u(3)} (0 memory links), ${u(4)} (0 memory links)`);    expect((await answer<{ project: ProjectRow }>(SLUG, owner, "update_project", { project: u(4), status: "archived" })).project).toMatchObject({ id: u(4), status: "archived" });    expect(await refusal(SLUG, owner, "update_project", { project: u(4), status: "active" })).toBe('an active project already holds the slug "twin" — archive that one first; nothing was changed');  });});/** RULE (owner, 18 Nov 2026): a session is briefed by what it is for, so one brief can name several projects. */describe("brief { projects }", () => {  const SLUG = "mem-brief-several";  let owner = "";  beforeAll(async () => {    ({ owner } = await personalObject(SLUG, MEMORY_OPEN));    await put(SLUG, [      project(u(1), "product", "Product"),      project(u(2), "building", "Building"),      project(u(3), "third", "Third"),      memory(u(11), "product-line", "The product is a family of apps."),      memory(u(12), "building-line", "Push small and often."),      memory(u(13), "third-line", "A third group stays out."),      link(u(101), u(1), "memory", u(11), { position: 1000 }),      link(u(102), u(2), "memory", u(12), { position: 1000 }),      link(u(103), u(3), "memory", u(13), { position: 1000 }),    ]);  });  it("briefs the projects named, in the order given", async () => {    const b = await answer<Brief>(SLUG, owner, "brief", { projects: ["building", "product"] });    expect(b.projects).toEqual(["building", "product"]);    expect(b.briefing.indexOf("Push small and often.")).toBeGreaterThan(-1);    expect(b.briefing.indexOf("Push small and often.")).toBeLessThan(b.briefing.indexOf("The product is a family of apps."));    expect(b.briefing).not.toContain("A third group stays out.");  });  it("keeps project working", async () => {    expect((await answer<Brief>(SLUG, owner, "brief", { project: "product" })).projects).toEqual(["product"]);  });  it("refuses in words", async () => {    expect(await refusal(SLUG, owner, "brief", { project: "product", projects: ["building"] })).toBe("send project or projects, not both");    expect(await refusal(SLUG, owner, "brief", { projects: [] })).toBe("projects must be a non-empty array of project slugs, from list_projects");    expect(await refusal(SLUG, owner, "brief", { projects: ["a", "b", "c", "d", "e"] })).toBe("at most 4 projects per brief — name the ones this session is for");    expect(await refusal(SLUG, owner, "brief", { projects: ["product", "product"] })).toBe('projects names "product" twice — name each project once');    expect(await refusal(SLUG, owner, "brief", { projects: ["product", "nobody"] })).toContain('unknown project "nobody"');  });});/** RULE (owner, 18 Nov 2026): where two active projects share a slug, the slug means the one holding more memory links. */describe("two active projects sharing a slug", () => {  const SLUG = "mem-shared-slug";  const REPO = "https://git.example.test/acme/shared.git";  let owner = "";  beforeAll(async () => {    ({ owner } = await personalObject(SLUG, MEMORY_OPEN));    await put(SLUG, [      project(u(1), "shared", "Shared thin", { repos: [REPO] }, 1),      project(u(2), "shared", "Shared full", { repos: ["git@git.example.test:acme/shared.git"] }, 2),      project(u(3), "alone", "Alone", {}, 3),      memory(u(11), "thin-line", "The thin row holds one line."),      memory(u(12), "full-line", "The full row holds this line."),      memory(u(13), "full-other", "The full row holds another line too."),      memory(u(14), "loose-line", "A line waiting for a home in the garden."),      link(u(101), u(1), "memory", u(11), { position: 1000 }),      link(u(102), u(2), "memory", u(12), { position: 1000 }),      link(u(103), u(2), "memory", u(13), { position: 2000 }),    ]);  });  it("brief by slug and by repo reads the fuller row, once", async () => {    for (const args of [{ project: "shared" }, { projects: ["shared"] }, { repoUrl: REPO }]) {      const b = await answer<Brief>(SLUG, owner, "brief", args);      expect(b.projects).toEqual(["shared"]);      expect(b.briefing).toContain("The full row holds this line.");      expect(b.briefing).not.toContain("The thin row holds one line.");    }  });  it("remember files under the fuller row", async () => {    await answer(SLUG, owner, "remember", { title: "Kites fly best in the windy month.", project: "shared", slug: "kites" });    const { memories } = await answer<{ memories: { slug: string }[] }>(SLUG, owner, "recall", { project: "shared" });    expect(memories.map((m) => m.slug)).toContain("kites");    expect(memories.map((m) => m.slug)).not.toContain("thin-line");  });  it("link_to_project files under the fuller row", async () => {    await answer(SLUG, owner, "link_to_project", { project: "shared", records: [{ kind: "memory", id: u(14) }] });    const { projects } = await answer<{ projects: ProjectRow[] }>(SLUG, owner, "list_projects");    expect(projects.find((p) => p.id === u(2))?.linked?.memory).toBe(4);    expect(projects.find((p) => p.id === u(1))?.linked?.memory).toBe(1);  });  it("list_projects says which rows share the slug and which one it means", async () => {    const { projects } = await answer<{ projects: ProjectRow[] }>(SLUG, owner, "list_projects");    const shared = { rows: [u(1), u(2)], resolvesTo: u(2) };    expect(projects.find((p) => p.name === "Shared thin")).toMatchObject({ id: u(1), sharedSlug: shared });    expect(projects.find((p) => p.name === "Shared full")).toMatchObject({ id: u(2), sharedSlug: shared });    expect(projects.find((p) => p.slug === "alone")).not.toHaveProperty("sharedSlug");  });  it("names the oldest row on a tie", async () => {    const TIED = "mem-shared-tie";    const { owner: token } = await personalObject(TIED, MEMORY_OPEN);    await put(TIED, [project(u(1), "tied", "Older", {}, 1), project(u(2), "tied", "Newer", {}, 2)]);    const { projects } = await answer<{ projects: ProjectRow[] }>(TIED, token, "list_projects");    expect(projects[0]?.sharedSlug?.resolvesTo).toBe(u(1));  });});