RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-03 00:23:07 -07:00
commit 5557443ed1
818 changed files with 239368 additions and 0 deletions
+79
View File
@@ -0,0 +1,79 @@
// An in-memory workspace for the tests of the native Project Management feature. It records each read.
import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts";
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
import { newTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { cardsMarker, privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
import type { TaskFields, Workspace } from "../../../../src/lib/features/pm/model/model.ts";
export interface MemoryWorkspace extends Workspace {
files: Map<string, string>;
/** Each path that a read asked for, in order. A `readMany` row counts as one read. */
reads: string[];
/** Each folder that a listing asked for. */
lists: string[];
/** The number of Markdown listings. */
markdownLists: number;
}
export function memoryWorkspace(initial: Record<string, string> = {}): MemoryWorkspace {
const files = new Map(Object.entries(initial));
const reads: string[] = [], lists: string[] = [];
const parent = (path: string) => path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
const workspace: MemoryWorkspace = {
files, reads, lists, markdownLists: 0,
async list(path = "") {
lists.push(path);
const names = new Map<string, "file" | "folder">();
for (const file of files.keys()) {
if (path && !file.startsWith(path + "/")) continue;
const rest = path ? file.slice(path.length + 1) : file;
const name = rest.split("/")[0];
names.set(name, rest.includes("/") ? "folder" : "file");
}
return [...names].map(([name, kind]) => ({ name, rel_path: path ? `${path}/${name}` : name, kind }));
},
async listMarkdown() {
workspace.markdownLists++;
return [...files.keys()].filter(path => /\.(md|markdown|mdown)$/i.test(path) && !path.startsWith(".")).sort();
},
async read(path) {
reads.push(path);
if (!files.has(path)) throw new Error(`Missing file: ${path}`);
return files.get(path)!;
},
async readMany(paths) {
reads.push(...paths);
return paths.map(path => files.has(path) ? { path, source: files.get(path) } : { path, error: "Missing file" });
},
async readOptional(path) {
reads.push(path);
return files.get(path) ?? null;
},
async write(path, contents, expected) {
if (files.get(path) !== expected) throw new Error(`The file changed: ${path}`);
files.set(path, contents);
},
async create(path, contents) {
if (files.has(path)) throw new Error(`The file exists: ${path}`);
void parent(path);
files.set(path, contents);
},
};
return workspace;
}
export const fields = (extra: Partial<TaskFields> = {}): TaskFields => ({ status: "todo", tags: [], sessions: [], archived: false, ...extra });
/** A workspace with hidden storage: one board `board` and the given cards. */
export function hiddenWorkspace(cards: { id: string; title: string; fields?: Partial<TaskFields> }[] = [], extra: Record<string, string> = {}) {
const board = defaultBoard("board");
const files: Record<string, string> = {
[privateRulesPath]: "*\n",
[cardsMarker]: "*\n",
[catalogPath]: JSON.stringify({ schema: 1, boards: [{ name: "Board", value: board }] }, null, 2) + "\n",
...extra,
};
for (const card of cards) files[cardPath(card.id)] = newTask(card.title, fields({ title: card.title, placements: { board: { listId: "todo" } }, ...card.fields }), "Body", card.id).source;
return memoryWorkspace(files);
}
+66
View File
@@ -0,0 +1,66 @@
import test from "node:test";
import assert from "node:assert/strict";
import { allTaskColumns, allTaskGroups } from "../../../../src/lib/features/pm/model/all-tasks.ts";
import { defaultBoard, type BoardDocument } from "../../../../src/lib/features/pm/storage/board.ts";
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import type { TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
const board = (id: string): BoardDocument => ({ id, path: `${id}.md`, name: id, source: "", value: defaultBoard(id) });
const task = (title: string, placements: TaskFields["placements"]) => {
const note = newTask(title, { status: "todo", archived: false, tags: [], sessions: [], placements });
return readTask(`${title}.md`, note.source)!;
};
test("All tasks merges list names, preserves custom lists, and includes every matching card once", () => {
const a = board("A"), b = board("B"), c = board("C");
a.value.lists.push({ id: "review", name: "Review", status: null, collapsed: true });
b.value.lists[0].name = " To Do ";
b.value.lists[0].id = "different-id";
c.value.lists[0].maxCards = 2;
const shared = task("Shared", { A: { listId: "todo" }, B: { listId: "different-id" } });
const other = task("Other", { C: { listId: "todo" } });
const review = task("Review", { A: { listId: "review" }, C: { listId: "todo" } });
const unlisted = task("Unlisted", { A: { listId: "removed" }, B: { listId: null } });
const orphan = task("Orphan", { deleted: { listId: "todo" } });
const original = JSON.stringify({ boards: [a, b, c], tasks: [shared, other, review, unlisted, orphan] });
const columns = allTaskColumns([a, b, c], [shared, other, review, unlisted, orphan]);
assert.equal(columns.length, 5);
assert.deepEqual(columns.find(c => c.list?.name === "To do")?.tasks, [shared, other, review, orphan]);
assert.deepEqual(columns.find(c => c.list?.name === "Review")?.tasks, [review]);
assert.deepEqual(columns.find(c => !c.list)?.tasks, [unlisted]);
assert.equal(columns.find(c => c.list?.name === "Review")?.list?.collapsed, false);
assert.equal(columns.find(c => c.list?.name === "To do")?.list?.maxCards, undefined);
assert.equal(columns.find(c => c.list?.name === "To do")?.allowCreate, false);
assert.equal(JSON.stringify({ boards: [a, b, c], tasks: [shared, other, review, unlisted, orphan] }), original);
});
test("matching list IDs with different names remain separate and empty lists stay visible", () => {
const a = board("A"), b = board("B");
b.value.lists[0].name = "Backlog";
const columns = allTaskColumns([a, b], []);
assert.deepEqual(columns.map(c => c.list?.name), ["To do", "In progress", "Done", "Backlog"]);
assert.equal(new Set(columns.map(c => c.list?.id)).size, 4);
});
test("cards on archived boards remain visible and empty workspaces retain default lists", () => {
const archived = { ...board("Archived"), archived: true };
const card = task("Archived board card", { Archived: { listId: "todo" } });
const columns = allTaskColumns([archived], [card]);
assert.deepEqual(columns[0].tasks, [card]);
assert.equal(columns.length, 3);
assert.equal(columns[0].allowCreate, true);
assert.equal(allTaskColumns([], []).length, 3);
});
test("board dividers name shared memberships once and separate cards without active boards", () => {
const a = board("A"), b = board("B");
a.value.lists.push({ id: "review", name: "Review", status: null, collapsed: false });
const shared = task("Shared", { A: { listId: "todo" }, B: { listId: "todo" } });
const separate = task("Separate", { A: { listId: "review" }, B: { listId: "todo" } });
const orphan = task("Orphan", { deleted: { listId: "todo" } });
const columns = allTaskColumns([a, b], [shared, separate, orphan]);
const todo = columns.find(column => column.list?.name === "To do")!;
assert.deepEqual(allTaskGroups([a, b], todo).map(group => [group.name, group.tasks.map(task => task.title)]), [
["A · B", ["Shared"]], ["B", ["Separate"]], ["No active board", ["Orphan"]],
]);
assert.deepEqual(allTaskGroups([a, b], columns.find(column => column.list?.name === "Review")!).map(group => group.name), ["A"]);
});
@@ -0,0 +1,60 @@
import test from "node:test";
import assert from "node:assert/strict";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
import { cardsMarker, privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
function fixture(count = 3) {
const files = new Map<string, string>([[cardsMarker, "*\n"], [privateRulesPath, "*\n"]]);
const ids = Array.from({ length: count }, () => crypto.randomUUID());
for (const [index, id] of ids.entries()) files.set(cardPath(id), newTask(`Card ${index}`, {
title: `Card ${index}`, status: "todo", tags: [], sessions: [], archived: false,
...(index === 0 ? { links: [{ taskId: ids[1], relation: "blocks" }, { taskId: ids[2], relation: "relates" }] as const } : {}),
}, "Keep body", id).source);
let batches = 0, singleReads = 0;
const workspace: Workspace = {
async listMarkdown() { return []; },
async list() { return [...files.keys()].filter(path => path.endsWith(".md")).map(path => ({ name: path.split("/").at(-1)!, rel_path: path, kind: "file" })); },
async read(path) { singleReads++; return files.get(path)!; },
async readOptional(path) { return files.get(path) ?? null; },
async readMany(paths) { assert.ok(paths.length <= 64); batches++; return paths.map(path => ({ path, source: files.get(path) })); },
async write(path, source, expected) { assert.equal(files.get(path), expected); files.set(path, source); },
async create(path, source) { assert.equal(files.has(path), false); files.set(path, source); },
};
return { files, ids, workspace, counts: () => ({ batches, singleReads }) };
}
test("1000 cards use 16 bounded reads and share parsed cards between board views", async t => {
const f = fixture(1000), store = new TaskStore(f.workspace);
let started = performance.now();
await store.reload();
t.diagnostic(`Initial 1000-card parse: ${Math.round(performance.now() - started)} ms`);
assert.deepEqual(f.counts(), { batches: 16, singleReads: 0 });
const first = store.tasks[0];
const next = new TaskStore(f.workspace);
started = performance.now(); await next.reload();
t.diagnostic(`Switch with unchanged sources: ${Math.round(performance.now() - started)} ms`);
assert.equal(next.tasks[0], first);
started = performance.now(); await next.save(first, { body: "Changed body" });
t.diagnostic(`Save with full conflict scan: ${Math.round(performance.now() - started)} ms`);
assert.deepEqual(f.counts(), { batches: 48, singleReads: 0 });
const stale = next.tasks.find(task => task.id === first.id)!;
f.files.set(stale.path, editTask(stale, { body: "External body" }));
await assert.rejects(next.save(stale, { body: "Overwrite" }), /changed/);
assert.equal(readTask(stale.path, f.files.get(stale.path)!)!.body, "External body");
});
test("incoming unlink preserves unrelated links and rejects stale source cards", async () => {
const f = fixture(), store = new TaskStore(f.workspace); await store.reload();
const source = store.tasks.find(task => task.id === f.ids[0])!;
await store.unlinkIncoming(f.ids[1], [source]);
const saved = readTask(source.path, f.files.get(source.path)!)!;
assert.deepEqual(saved.links, [{ taskId: f.ids[2], relation: "relates" }]);
assert.equal(saved.body, "Keep body");
await store.unlinkIncoming(f.ids[1], [source]); // A retry is harmless.
f.files.set(saved.path, editTask(saved, { body: "External change" }));
await assert.rejects(store.unlinkIncoming(f.ids[2], [saved]), /linked card changed/);
assert.deepEqual(readTask(saved.path, f.files.get(saved.path)!)!.links, saved.links);
});
+237
View File
@@ -0,0 +1,237 @@
import test from "node:test";
import assert from "node:assert/strict";
import { BoardStore, newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import type { Workspace, TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
const fields: TaskFields = {
status: "todo",
tags: [],
sessions: [],
archived: false,
};
function fixture() {
const source = newBoardSource();
const files = new Map<string, string>([["Board.md", source]]);
const reference = { id: parseBoard(source).id, path: "Board.md" };
const workspace: Workspace = {
async readOptional(path) {
return files.get(path) ?? null;
},
async read(path) {
if (!files.has(path)) throw Error("Missing");
return files.get(path)!;
},
async create(path, text) {
if (files.has(path)) throw Error("Exists");
files.set(path, text);
},
async write(path, text, expected) {
if (files.get(path) !== expected) throw Error("Conflict");
files.set(path, text);
},
async list(parent = "") {
return [...files.keys()]
.filter((path) => !path.startsWith("."))
.map((path) => ({ name: path, rel_path: path, kind: "file" }));
},
};
return { files, workspace, reference };
}
test("list names, completion mapping, order, and collapse survive reload", async () => {
const { workspace, reference } = fixture();
const board = new BoardStore(workspace, reference);
await board.reload();
await board.add("Review", null);
const review = board.value.lists.at(-1)!;
await board.edit(review.id, "Approved", "done");
await board.move(review.id, 0);
await board.collapse(review.id);
const reopened = new BoardStore(workspace, reference);
await reopened.reload();
assert.deepEqual(reopened.value.lists[0], {
id: review.id,
name: "Approved",
status: "done",
collapsed: true,
});
await assert.rejects(reopened.add("approved", null), /already exists/);
});
test("list maximum survives edits and reload, rejects invalid values, and can be removed", async () => {
const { workspace, reference } = fixture();
const board = new BoardStore(workspace, reference);
await board.reload();
await board.setLimit("todo", 2);
await board.edit("todo", "Next", "todo");
await board.collapse("todo");
await board.reload();
assert.equal(board.value.lists[0].maxCards, 2);
for (const invalid of [0, -1, 1.5, Infinity, NaN, Number.MAX_SAFE_INTEGER + 1])
await assert.rejects(board.setLimit("todo", invalid), /whole number/);
const source = newBoardSource().replace("collapsed: false", "collapsed: false\n maxCards: -2");
assert.throws(() => parseBoard(source), /invalid list/);
await board.setLimit("todo");
await board.reload();
assert.equal(board.value.lists[0].maxCards, undefined);
});
test("deleting a populated list preserves notes and sends its cards to Unlisted", async () => {
const { workspace, files, reference } = fixture();
const note = newTask(
"Keep me",
{ ...fields, placements: { [reference.id]: { listId: "todo" } } },
"Keep the body",
);
files.set("Keep me.md", note.source);
const store = new TaskStore(workspace, reference);
await store.reload();
await store.changeBoard(() => store.board.remove("todo"));
assert.equal(store.board.listFor(store.tasks[0]), undefined);
assert.equal(files.get("Keep me.md"), note.source);
await store.board.add("Replacement", null);
assert.equal(store.board.listFor(store.tasks[0]), undefined);
assert.equal(
store.board.listFor({ status: "todo", listId: undefined }),
undefined,
);
});
test("moving a card stores its list and completion in one guarded note write", async () => {
const { workspace, files, reference } = fixture();
const note = newTask("Task", fields);
files.set("Task.md", note.source);
const store = new TaskStore(workspace, reference);
await store.reload();
await store.moveTask(store.tasks[0], "done");
const saved = readTask("Task.md", files.get("Task.md")!)!;
assert.equal(saved.placements?.[reference.id].listId, "done");
assert.equal(saved.status, "done");
assert.equal(saved.id, store.tasks[0].id);
await store.moveTask(store.tasks[0], null);
assert.equal(store.board.listFor(store.tasks[0]), undefined);
assert.equal(store.tasks[0].status, "todo");
});
test("stale list edits do not overwrite another board revision", async () => {
const { workspace, files, reference } = fixture();
const first = new BoardStore(workspace, reference),
second = new BoardStore(workspace, reference);
await first.reload();
await second.reload();
await first.add("Review", null);
const saved = files.get("Board.md");
await assert.rejects(second.add("Other", null), /changed/);
assert.equal(files.get("Board.md"), saved);
});
test("malformed or future board files stay untouched", async () => {
const { workspace, files, reference } = fixture();
const text = newBoardSource().replace("schema: 1", "schema: 2");
files.set("Board.md", text);
const board = new BoardStore(workspace, reference);
await assert.rejects(board.reload(), /unsupported/);
await assert.rejects(board.add("Oops", null), /Open an available board/);
assert.equal(files.get("Board.md"), text);
});
test("deleting all lists remains empty after reload and allows a new list", async () => {
const { workspace, reference } = fixture();
const board = new BoardStore(workspace, reference);
await board.reload();
for (const id of ["todo", "doing", "done"]) await board.remove(id);
const next = new BoardStore(workspace, reference);
await next.reload();
assert.equal(next.value.lists.length, 0);
await next.add("First", null);
assert.equal(next.value.lists[0].name, "First");
});
test("All tasks cannot save board lists", async () => {
const { workspace, reference } = fixture();
const board = new BoardStore(workspace);
await board.reload();
await assert.rejects(board.add("Review", null), /Open an available board/);
assert.equal(board.value.lists.length, 3);
});
test("archiving a list scopes by board placement and preserves status, bodies, and other memberships", async () => {
const { workspace, files, reference } = fixture();
const sourceBoard = files.get(reference.path);
for (const [title, placements] of [
["Target", { [reference.id]: { listId: "todo" }, other: { listId: "doing" } }],
["Other list", { [reference.id]: { listId: "doing" } }],
["Other board", { other: { listId: "todo" } }],
] as const) {
const task = newTask(title, { ...fields, placements }, "Keep body");
files.set(task.path, task.source);
}
const store = new TaskStore(workspace, reference);
await store.reload();
const original = store.tasks.find(task => task.title === "Target")!;
await store.archiveList("todo");
await store.reload();
const archived = store.tasks.find(task => task.title === "Target")!;
assert.equal(archived.archived, true);
assert.equal(archived.status, original.status);
assert.deepEqual(archived.placements, original.placements);
assert.equal(archived.body, original.body);
assert.equal(store.tasks.filter(task => task.archived).length, 1);
assert.equal(files.get(reference.path), sourceBoard);
await store.archiveList("todo");
await assert.rejects(store.archiveList("missing"), /unavailable/);
});
test("board image appearance survives legacy saves and hidden catalog saves independently", async () => {
const { workspace, reference } = fixture();
const board = new BoardStore(workspace, reference); await board.reload();
const appearance = { overlay: -0.4, position: "bottom right", size: "contain" } as const;
await board.update(value => { value.backgroundImage = "11111111-1111-4111-8111-111111111111"; value.backgroundAppearance = appearance; });
await board.reload(); assert.equal(board.value.backgroundImage, "11111111-1111-4111-8111-111111111111"); assert.deepEqual(board.value.backgroundAppearance, appearance);
const store = new TaskStore(workspace); await store.reload(); const hidden = await store.createBoard("Hidden");
const managed = new BoardStore(workspace, hidden); await managed.reload();
await managed.update(value => { value.backgroundImage = "22222222-2222-4222-8222-222222222222"; value.backgroundAppearance = { overlay: 0.7, position: "top", size: "auto" }; });
await managed.reload(); assert.equal(managed.value.backgroundImage, "22222222-2222-4222-8222-222222222222"); assert.equal(managed.value.backgroundAppearance!.overlay, 0.7);
await board.reload(); assert.deepEqual(board.value.backgroundAppearance, appearance);
});
test("leaving a Done rule reopens a card and neutral moves preserve manual completion", async () => {
const { workspace, files, reference } = fixture();
const note = newTask("Task", { ...fields, status: "done", placements: { [reference.id]: { listId: "done" } } });
files.set("Task.md", note.source);
const store = new TaskStore(workspace, reference); await store.reload();
await store.changeBoard(() => store.board.add("Review", null));
const review = store.board.value.lists.at(-1)!.id;
await store.moveTask(store.tasks[0], review);
await store.reload();
assert.equal(store.tasks[0].status, "todo");
assert.equal(store.tasks[0].placements![reference.id].listId, review);
await store.save(store.tasks[0], { status: "done" });
await store.moveTask(store.tasks[0], null);
await store.reload();
assert.equal(store.tasks[0].status, "done");
await store.changeBoard(() => store.board.edit(review, "Review", "doing"));
await store.moveTask(store.tasks[0], review);
await store.reload(); assert.equal(store.tasks[0].status, "doing");
await store.moveTask(store.tasks[0], "todo");
await store.changeBoard(() => store.board.edit(review, "Review", null));
await store.save(store.tasks[0], { listId: review }, true);
await store.reload(); assert.equal(store.tasks[0].status, "todo");
assert.equal(store.board.value.lists.find(list => list.id === review)!.status, null);
});
test("overview creation writes one assigned card and rejects stale destinations without extra cards", async () => {
const { workspace, files, reference } = fixture();
const store = new TaskStore(workspace);
await store.reload();
await store.create("Assigned card", { ...fields, listId: "doing" }, "Card body", reference.id);
const task = store.tasks.find(task => task.title === "Assigned card")!;
assert.equal(task.placements?.[reference.id].listId, "doing");
assert.equal(Object.keys(task.placements ?? {}).length, 1);
assert.equal(task.body.trim(), "Card body");
const snapshot = new Map(files);
await assert.rejects(store.create("Missing board", fields, "", "missing"), /active board/);
await assert.rejects(store.create("Missing list", { ...fields, listId: "missing" }, "", reference.id), /list no longer exists/);
assert.deepEqual(files, snapshot);
files.delete("Board.md");
const afterDelete = new Map(files);
await assert.rejects(store.create("Deleted board", fields, "", reference.id), /active board/);
assert.deepEqual(files, afterDelete);
});
@@ -0,0 +1,75 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { priorities, type TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
import { renderMarkdown } from "../../../../src/lib/features/pm/model/markdown.ts";
const fields: TaskFields = {
status: "todo",
tags: [],
labels: ["high-priority"],
sessions: [],
archived: false,
};
test("priority round-trips independently of labels and survives unrelated changes", () => {
for (const priority of [...priorities, null]) {
const note = newTask("Priority card", { ...fields, priority });
const task = readTask(note.path, note.source)!;
assert.equal(task.priority, priority);
const changed = readTask(
note.path,
editTask(task, { status: "doing", listId: "review", body: "Edited" }),
)!;
assert.equal(changed.priority, priority);
assert.deepEqual(changed.labels, fields.labels);
}
});
test("unrelated edits preserve absent priority and explicit removal writes null", () => {
const note = newTask("Legacy", fields);
const task = readTask(note.path, note.source)!;
assert.doesNotMatch(editTask(task, { body: "Edit" }), /priority:/);
const cleared = editTask(task, { priority: null });
assert.match(cleared, /priority: null/);
assert.deepEqual(readTask(note.path, cleared)!.labels, fields.labels);
assert.throws(
() => newTask("Invalid", { ...fields, priority: "urgent" as never }),
/priority/,
);
});
test("Markdown preview escapes HTML and rejects active links and external images", () => {
const result = renderMarkdown(
"# Heading\n\n**Bold**\n\n<script>alert(1)</script>\n\n[x](javascript:alert(1))\n\n![remote](https://example.com/tracker.png)\n\n![image](pm-image:12345678-1234-1234-1234-123456789abc)\n\n[safe](https://example.com)",
);
assert.match(result, /<h1>Heading<\/h1>/);
assert.match(result, /<strong>Bold<\/strong>/);
assert.doesNotMatch(result, /<script|src=|href="javascript:/);
assert.match(result, /data-pm-image="12345678-1234-1234-1234-123456789abc"/);
assert.match(result, /rel="noopener noreferrer"/);
});
test("covers, subtasks, and card links round-trip without changing other fields", () => {
const coverImage = "12345678-1234-1234-1234-123456789abc";
const subtasks = [{ id: "subtask", title: "Check the change", done: true }];
const links = [{ taskId: "dependency", relation: "blocked-by" as const }];
const note = newTask("Relationships", { ...fields, coverImage, subtasks, links });
const task = readTask(note.path, note.source)!;
assert.deepEqual(task.subtasks, subtasks); assert.deepEqual(task.links, links); assert.equal(task.coverImage, coverImage);
const edited = readTask(note.path, editTask(task, { body: "Revised", priority: "lowest" }))!;
assert.deepEqual(edited.subtasks, subtasks); assert.deepEqual(edited.links, links); assert.equal(edited.coverImage, coverImage);
assert.throws(() => editTask(task, { coverImage: "../outside.png" }), /image/);
assert.throws(() => editTask(task, { subtasks: [...subtasks, ...subtasks] }), /unique ID/);
assert.throws(() => editTask(task, { links: [...links, ...links] }), /once/);
});
test("attachments round-trip independently of description edits and reject duplicate or invalid IDs", () => {
const attachments = [{ id: "12345678-1234-1234-1234-123456789abc", name: "Screenshot.png" }];
const note = newTask("Attached image", { ...fields, attachments }, "Description");
const task = readTask(note.path, note.source)!;
assert.deepEqual(task.attachments, attachments);
const changed = readTask(note.path, editTask(task, { body: "", status: "doing" }))!;
assert.deepEqual(changed.attachments, attachments);
assert.equal(changed.body, "");
assert.deepEqual(readTask(note.path, editTask(changed, { attachments: [] }))!.attachments, []);
assert.throws(() => editTask(task, { attachments: [...attachments, ...attachments] }), /unique image ID/);
assert.throws(() => editTask(task, { attachments: [{ id: "../outside", name: "Image" }] }), /unique image ID/);
});
@@ -0,0 +1,69 @@
import test from "node:test";
import assert from "node:assert/strict";
import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { validateFields, type TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
const fields: TaskFields = {
status: "todo",
tags: [],
sessions: [],
archived: false,
};
test("optional card fields survive moves and can be removed without changing other note data", () => {
const note = newTask(
"Customer work",
{
...fields,
color: "purple",
assignees: ["Alex", "Northwind"],
customFields: [
{ name: "Customer ID", value: "0012" },
{ name: "Contact", value: "[email protected]" },
],
},
"Keep **these details**.\n",
);
const source = note.source.replace(
" schema: 1",
" extra: keep-me # future property\n schema: 1",
);
const task = readTask(note.path, source)!;
assert.equal(task.color, "purple");
assert.deepEqual(task.assignees, ["Alex", "Northwind"]);
assert.equal(task.customFields?.[0].value, "0012");
const moved = readTask(
note.path,
editTask(task, { status: "done", listId: "done" }),
)!;
assert.deepEqual(moved.customFields, task.customFields);
assert.equal(moved.color, "purple");
const cleared = editTask(moved, {
color: undefined,
assignees: [],
customFields: [],
});
assert.ok(cleared.includes("extra: keep-me # future property"));
assert.equal(readTask(note.path, cleared)!.body, task.body);
assert.equal(readTask(note.path, cleared)!.color, undefined);
assert.deepEqual(readTask(note.path, cleared)!.customFields, []);
});
test("invalid optional fields and duplicate names cannot enter saved notes", () => {
for (const patch of [
{ color: "url(bad)" },
{ assignees: "Alex" },
{ assignees: [1] },
{ customFields: [null] },
{ customFields: [{ name: "", value: "x" }] },
{
customFields: [
{ name: "ID", value: "1" },
{ name: " id ", value: "2" },
],
},
])
assert.throws(() => validateFields({ ...fields, ...patch } as TaskFields));
const old = newTask("Basic", fields);
assert.equal(readTask(old.path, old.source)!.color, undefined);
});
@@ -0,0 +1,296 @@
import test from "node:test";
import assert from "node:assert/strict";
import { newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { adoptNote, editTask, newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { cardOrder, orderBetween } from "../../../../src/lib/features/pm/storage/order.ts";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { isHiddenCard } from "../../../../src/lib/features/pm/storage/persistence.ts";
import type { TaskFields, Workspace } from "../../../../src/lib/features/pm/model/model.ts";
const fields: TaskFields = {
status: "todo",
tags: [],
sessions: [],
archived: false,
};
function fixture() {
const board = newBoardSource();
const files = new Map([["Board.md", board]]);
const reads: string[] = [],
lists: string[] = [],
writes: string[] = [];
const workspace: Workspace = {
async readOptional(path) {
return files.get(path) ?? null;
},
async list(parent = "") {
lists.push(parent);
const entries = new Map();
for (const path of files.keys()) {
const prefix = parent ? parent + "/" : "";
if (!path.startsWith(prefix)) continue;
const parts = path.slice(prefix.length).split("/");
entries.set(parts[0], {
name: parts[0],
rel_path: prefix + parts[0],
kind: parts.length > 1 ? "folder" : "file",
});
}
return [...entries.values()];
},
async read(path) {
reads.push(path);
if (!files.has(path)) throw new Error("Missing note");
return files.get(path)!;
},
async write(path, source, expected) {
assert.equal(files.get(path), expected);
writes.push(path);
files.set(path, source);
},
async create(path, source) {
if (files.has(path)) throw new Error("Exists");
files.set(path, source);
},
};
const reference = { id: parseBoard(board).id, path: "Board.md" };
return {
files,
reads,
lists,
writes,
workspace,
reference,
store: new TaskStore(workspace, reference),
};
}
test("card creation reads one board and does not scan unrelated notes after loading", async () => {
const { store, files, lists, reads } = fixture();
for (let index = 0; index < 300; index++)
files.set(`Archive/Note ${index}.md`, "Plain note");
await store.reload();
lists.length = reads.length = 0;
await store.create("New card", fields, "Details");
assert.deepEqual(lists, []);
assert.deepEqual(reads, ["Board.md"]);
assert.equal(store.scopedTasks[0].title, "New card");
assert.equal(store.scopedTasks[0].body, "Details");
await store.create("New card", fields, "Second");
assert.equal(store.scopedTasks.length, 2);
assert.equal(store.scopedTasks[0].body, "Details");
});
test("creation checks the current list before writing a card", async () => {
const { store, files } = fixture();
await store.reload();
await store.board.remove("todo");
const snapshot = new Map(files);
await assert.rejects(
store.create("Missing list", { ...fields, listId: "todo" }, ""),
/list no longer exists/,
);
assert.deepEqual(files, snapshot);
assert.equal(store.tasks.length, 0);
});
test("a background scan cannot replace a newly created card with an older snapshot", async () => {
const { store, workspace } = fixture();
await store.reload();
const list = workspace.list;
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
workspace.list = async (path) => {
const snapshot = await list(path);
await gate;
return snapshot;
};
const pending = store.reload();
await store.create("Keep new card", fields, "");
release();
await pending;
assert.deepEqual(
store.scopedTasks.map((task) => task.title),
["Keep new card"],
);
});
test("title edits preserve the filename, identity, metadata, and body", async () => {
const { store, files } = fixture();
await store.create("Original", fields, "Keep **Markdown**.\n");
const original = store.tasks[0];
files.set(
original.path,
original.source.replace("---\n", "---\nowner: Ada # keep\n"),
);
await store.reload();
await store.save(store.tasks[0], { title: "Edited: title / shared" });
const updated = store.tasks[0];
assert.equal(updated.title, "Edited: title / shared");
assert.equal(updated.id, original.id);
assert.equal(updated.path, original.path);
assert.equal(updated.body, original.body);
assert.match(updated.source, /owner: Ada # keep/);
assert.equal([...files.keys()].filter(isHiddenCard).length, 1);
await store.reload();
assert.equal(store.tasks[0].title, updated.title);
await assert.rejects(store.save(original, { title: "Stale" }), /changed/);
await assert.rejects(
store.save(store.tasks[0], { title: " " }),
/card title/,
);
assert.equal(readTask(original.path, original.source)!.title, "Original");
});
test("legacy notes with long filenames remain editable before a card title is set", () => {
const path = "Long existing note ".repeat(8).trim() + ".md";
const source = adoptNote(path, "Existing description");
const task = readTask(path, source)!;
assert.equal(task.title, path.slice(0, -3));
const edited = readTask(path, editTask(task, { status: "doing" }))!;
assert.equal(edited.title, task.title);
assert.equal(edited.status, "doing");
});
test("cards retain insertion order and can move before, between, and after other cards", async () => {
const { store, workspace, reference, writes } = fixture();
for (const name of ["Zulu", "Alpha", "Middle"])
await store.create(name, fields, "");
const names = () => store.cardsInList("todo").map((task) => task.title);
const task = (title: string) =>
store.tasks.find((task) => task.title === title)!;
assert.deepEqual(names(), ["Zulu", "Alpha", "Middle"]);
await store.save(task("Middle"), { status: "done" });
const middle = task("Middle");
writes.length = 0;
await store.moveTask(middle, "todo", task("Zulu").id);
assert.deepEqual(writes, [middle.path]);
assert.equal(task("Middle").status, "done");
assert.deepEqual(names(), ["Middle", "Zulu", "Alpha"]);
await store.moveTask(task("Alpha"), "todo", task("Zulu").id);
assert.deepEqual(names(), ["Middle", "Alpha", "Zulu"]);
await store.moveTask(task("Middle"), "todo", null);
assert.deepEqual(names(), ["Alpha", "Zulu", "Middle"]);
await store.save(task("Zulu"), {
title: "A renamed card",
listId: "todo",
tags: ["release"],
});
const reopened = new TaskStore(workspace, reference);
await reopened.reload();
assert.deepEqual(
reopened.cardsInList("todo").map((task) => task.title),
["Alpha", "A renamed card", "Middle"],
);
});
test("card order stays independent in each board and All tasks", async () => {
const { store, files, workspace, reference } = fixture();
const secondSource = newBoardSource();
files.set("Second.md", secondSource);
const second = new TaskStore(workspace, {
id: parseBoard(secondSource).id,
path: "Second.md",
});
for (const name of ["Alpha", "Beta", "Gamma"]) {
await store.create(
name,
{ ...fields, due: { date: "2026-10-08" } },
"Shared details",
);
await second.adopt(store.tasks.find((task) => task.title === name)!.path);
}
await store.reload();
const gamma = store.tasks.find((task) => task.title === "Gamma")!;
const secondPlacement = gamma.placements![second.board.reference!.id];
await store.moveTask(
gamma,
"todo",
store.tasks.find((task) => task.title === "Alpha")!.id,
);
await second.reload();
assert.deepEqual(
second.cardsInList("todo").map((task) => task.title),
["Alpha", "Beta", "Gamma"],
);
assert.deepEqual(
second.tasks.find((task) => task.id === gamma.id)!.placements![
second.board.reference!.id
],
secondPlacement,
);
const all = new TaskStore(workspace);
await all.reload();
await all.moveTask(all.tasks[1], "todo", all.tasks[0].id);
assert.deepEqual(
all.cardsInList("todo").map((task) => task.title),
["Beta", "Alpha", "Gamma"],
);
await store.reload();
assert.deepEqual(
store.cardsInList("todo").map((task) => task.title),
["Gamma", "Alpha", "Beta"],
);
await store.moveTask(store.cardsInList("todo")[0], "done", null);
const moved = store.cardsInList("done")[0];
assert.equal(moved.status, "done");
assert.deepEqual(moved.due, { date: "2026-10-08" });
assert.equal(moved.body, "Shared details");
assert.equal(moved.placements![reference.id].listId, "done");
});
test("failed or stale order writes keep card data intact", async () => {
const { store, workspace, files } = fixture();
await store.create("Alpha", fields, "");
await store.create("Beta", fields, "");
const [alpha, beta] = store.cardsInList("todo");
const snapshot = new Map(files);
workspace.write = async () => {
throw new Error("Disk failure");
};
await assert.rejects(store.moveTask(beta, "todo", alpha.id), /Disk failure/);
assert.deepEqual(files, snapshot);
assert.deepEqual(
store.cardsInList("todo").map((task) => task.title),
["Alpha", "Beta"],
);
await assert.rejects(
store.moveTask(beta, "todo", "missing"),
/target card moved/,
);
files.set(beta.path, editTask(beta, { body: "External change" }));
await assert.rejects(store.moveTask(beta, "todo", alpha.id), /changed/);
});
test("ordering handles repeated narrow gaps, legacy notes, and matching saved ranks", () => {
let upper = "j";
for (let index = 0; index < 1200; index++) {
const rank = orderBetween("i", upper);
assert.ok("i" < rank && rank < upper);
assert.match(rank, /^[0-9a-z]*[1-9a-z]$/);
upper = rank;
}
const alphaNote = newTask(
"Alpha",
fields,
"",
"00000000-0000-4000-8000-000000000001",
);
const betaNote = newTask(
"Beta",
fields,
"",
"00000000-0000-4000-8000-000000000002",
);
const alpha = readTask(alphaNote.path, alphaNote.source)!;
const beta = readTask(betaNote.path, betaNote.source)!;
assert.ok(cardOrder(alpha) < cardOrder(beta));
assert.equal(cardOrder(alpha), cardOrder({ ...alpha, title: "Zulu" }));
alpha.order = beta.order = "i";
const between = orderBetween(cardOrder(alpha), cardOrder(beta));
const inserted = cardOrder({ ...alpha, id: "new", order: between });
assert.ok(cardOrder(alpha) < inserted && inserted < cardOrder(beta));
assert.throws(() => editTask(alpha, { order: "invalid!" }), /order/);
});
+198
View File
@@ -0,0 +1,198 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readTask, editTask, newTask, adoptNote } from "../../../../src/lib/features/pm/storage/notes.ts";
import {
addDays,
dayDistance,
validDate,
type Workspace,
type TaskFields,
} from "../../../../src/lib/features/pm/model/model.ts";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { isHiddenCard } from "../../../../src/lib/features/pm/storage/persistence.ts";
const fields: TaskFields = {
status: "todo",
tags: [],
sessions: [],
archived: false,
};
function memory(initial: Record<string, string> = {}) {
const files = new Map(Object.entries(initial));
const workspace: Workspace = {
async readOptional(path) {
return files.get(path) ?? null;
},
async list(parent = "") {
const entries = new Map();
for (const path of files.keys()) {
const prefix = parent ? `${parent}/` : "";
if (!path.startsWith(prefix)) continue;
const parts = path.slice(prefix.length).split("/");
entries.set(parts[0], {
name: parts[0],
rel_path: `${prefix}${parts[0]}`,
kind: parts.length > 1 ? "folder" : "file",
});
}
return [...entries.values()];
},
async read(path) {
const text = files.get(path);
if (text === undefined) throw Error("Missing file");
return text;
},
async write(path, text, expected) {
assert.equal(files.get(path), expected, "Changed on disk");
files.set(path, text);
},
async create(path, text) {
if (files.has(path)) throw Error("Exists");
files.set(path, text);
},
};
return { workspace, files };
}
test("tasks round trip with a stable ID, description, deadline, plan, and sessions", () => {
const note = newTask(
"Launch",
{
...fields,
due: { date: "2026-10-30" },
plan: { start: "2026-10-05", end: "2026-10-31" },
sessions: [
{
id: "session-1",
start: "2026-10-08T16:00:00Z",
end: "2026-10-08T17:00:00Z",
timeZone: "America/Vancouver",
},
],
},
"Keep **Markdown**.\n",
);
const task = readTask(note.path, note.source)!;
const moved = readTask(note.path, editTask(task, { status: "doing" }))!;
assert.equal(moved.id, task.id);
assert.equal(moved.body, task.body);
assert.deepEqual(moved.plan, task.plan);
assert.deepEqual(moved.sessions, task.sessions);
assert.deepEqual(moved.due, task.due);
assert.equal(moved.status, "doing");
});
test("metadata edits preserve unknown properties, comments, and the exact body", () => {
const source =
'\uFEFF---\r\nowner: Ada # keep this\r\nrunestone_pm:\r\n schema: 1\r\n id: stable\r\n kind: task\r\n status: todo # workflow\r\n future: {value: 12}\r\n plan:\r\n start: "2026-10-04"\r\n end: "2026-10-08"\r\n custom: untouched\r\n---\r\n# Body\r\n\r\n- [ ] Keep spacing \r\n';
const original = readTask("Note.md", source)!;
const next = editTask(original, {
status: "doing",
plan: { start: "2026-10-05", end: "2026-10-09" },
});
assert.equal(readTask("Note.md", next)!.body, original.body);
assert.match(next, /owner: Ada # keep this/);
assert.match(next, /# workflow/);
assert.match(next, /future:/);
assert.match(next, /custom: untouched/);
assert.ok(next.startsWith("\uFEFF"));
assert.ok(!/(?<!\r)\n/.test(next));
});
test("adding an existing note preserves its content and does not duplicate its identity", () => {
const source = "---\ncategory: reference\n---\nOriginal body\n";
const adopted = adoptNote("Existing.md", source),
task = readTask("Existing.md", adopted)!;
assert.equal(task.body, "Original body\n");
assert.match(adopted, /category: reference/);
assert.equal(adoptNote("Existing.md", adopted), adopted);
});
test("unsupported metadata and invalid dates are rejected without rewriting a note", () => {
const note = newTask("Task", fields);
assert.throws(
() => readTask(note.path, note.source.replace("schema: 1", "schema: 2")),
/unsupported/,
);
assert.throws(
() =>
readTask(
note.path,
note.source.replace("status: todo", "status: unknown"),
),
/status/,
);
assert.throws(
() =>
editTask(readTask(note.path, note.source)!, {
due: { date: "2026-02-30" },
}),
/deadline/,
);
assert.throws(
() => adoptNote("Bad.md", "---\nkey: 1\nkey: 2\n---\nBody"),
/YAML/,
);
assert.throws(() => newTask("../escape", fields), /name/);
assert.throws(() => newTask("CON", fields), /name/);
assert.throws(
() =>
newTask("Task", {
...fields,
plan: { start: "2026-10-10", end: "2026-10-09" },
}),
/end/,
);
});
test("date arithmetic preserves whole dates over leap years and daylight-saving boundaries", () => {
assert.equal(addDays("2024-02-28", 1), "2024-02-29");
assert.equal(addDays("2026-12-31", 1), "2027-01-01");
assert.equal(dayDistance("2026-03-07", "2026-03-09"), 2);
assert.equal(dayDistance("2026-10-31", "2026-11-02"), 2);
assert.equal(validDate("2026-02-29"), false);
});
test("save and reload use one note, and archive retains its file", async () => {
const { files, workspace } = memory();
const store = new TaskStore(workspace);
await store.create("Launch", fields, "Description");
assert.equal([...files.keys()].filter(isHiddenCard).length, 1);
const original = store.tasks[0];
await store.save(original, { status: "done", archived: true });
const reopened = new TaskStore(workspace);
await reopened.reload();
assert.equal(reopened.tasks[0].id, original.id);
assert.equal(reopened.tasks[0].status, "done");
assert.equal(reopened.tasks[0].archived, true);
assert.equal([...files.keys()].filter(isHiddenCard).length, 1);
});
test("stale edits cannot overwrite external changes", async () => {
const { workspace, files } = memory();
const store = new TaskStore(workspace);
await store.create("Task", fields, "Original");
const original = store.tasks[0];
const external = editTask(original, { body: "External change" });
files.set(original.path, external);
await assert.rejects(store.save(original, { status: "done" }), /changed/);
assert.equal(files.get(original.path), external);
});
test("duplicate identities are excluded and blocked even when introduced after reload", async () => {
const note = newTask("Task", fields);
const { workspace, files } = memory({ [note.path]: note.source });
const store = new TaskStore(workspace);
await store.reload();
const original = store.tasks[0];
files.set("Copy.md", note.source);
await assert.rejects(store.save(original, { status: "done" }), /duplicate/);
assert.equal(store.tasks.length, 0);
assert.match(store.issues[0], /Duplicate/);
assert.equal(files.get(note.path), note.source);
});
test("duplicate card titles preserve both cards and disposal blocks new writes", async () => {
const { workspace, files } = memory();
const store = new TaskStore(workspace);
await store.create("Task", fields, "Original");
const first = store.tasks[0];
await store.create("Task", fields, "Second card");
assert.equal(store.tasks.length, 2);
assert.equal(files.get(first.path), first.source);
assert.equal(new Set(store.tasks.map((task) => task.id)).size, 2);
store.dispose();
await assert.rejects(store.create("Later", fields, ""), /closed/);
});
@@ -0,0 +1,63 @@
import test from "node:test";
import assert from "node:assert/strict";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { deletedCardsPath } from "../../../../src/lib/features/pm/storage/deleted-cards.ts";
import { migrateCards } from "../../../../src/lib/features/pm/storage/cards.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
function fixture() {
const note = newTask("Delete me", { status: "todo", tags: [], sessions: [], archived: false,
placements: { first: { listId: "todo" }, second: { listId: "doing" } } }, "Keep this source");
const task = readTask("Delete me.md", note.source)!;
const parent = newTask("Related", { status: "todo", tags: [], sessions: [], archived: false,
links: [{ taskId: task.id, relation: "relates" }], subtasks: [{ id: "sub", taskId: task.id, title: task.title, done: false }] }, "");
const files = new Map([[task.path, note.source], ["Related.md", parent.source]]);
let fail = false;
const workspace: Workspace = {
async list(folder = "") { return [...files.keys()].filter(path => folder ? path.startsWith(`${folder}/`) : !path.startsWith(".")).map(path => ({ name: path.split("/").at(-1)!, rel_path: path, kind: "file" })); },
async read(path) { if (!files.has(path)) throw Error("Missing"); return files.get(path)!; },
async readOptional(path) { return files.get(path) ?? null; },
async create(path, source) { if (fail || files.has(path)) throw Error("Write failed"); files.set(path, source); },
async write(path, source, expected) { if (fail) throw Error("Write failed"); assert.equal(files.get(path), expected); files.set(path, source); },
};
return { task, files, workspace, setFailure() { fail = true; } };
}
test("confirmed deletion removes legacy and migrated cards from all scopes and retains source records", async () => {
for (const migrate of [false, true]) {
const { workspace, files, task } = fixture();
if (migrate) await migrateCards(workspace, [task]);
const store = new TaskStore(workspace); await store.reload();
const before = new Map(files);
await store.deleteCard(store.tasks.find(item => item.id === task.id)!);
assert.deepEqual(store.tasks.map(item => item.title), ["Related"]);
for (const [path, source] of before) assert.equal(files.get(path), source);
assert.deepEqual(JSON.parse(files.get(deletedCardsPath)!).ids, [task.id]);
const fresh = new TaskStore(workspace); await fresh.reload();
assert.equal(fresh.tasks.some(item => item.id === task.id), false);
await assert.rejects(fresh.openSubtask(fresh.tasks[0].id, "sub"), /unavailable/);
assert.equal(fresh.tasks[0].links![0].taskId, task.id);
await assert.rejects(fresh.save(task, { archived: false }), /changed|duplicate/);
}
});
test("stale cards and failed deletion writes preserve the card", async () => {
const stale = fixture(); const store = new TaskStore(stale.workspace); await store.reload();
stale.files.set(stale.task.path, stale.task.source + "External edit\n");
await assert.rejects(store.deleteCard(stale.task), /changed/);
assert.equal(stale.files.has(deletedCardsPath), false);
const failed = fixture(); const next = new TaskStore(failed.workspace); await next.reload();
failed.setFailure(); await assert.rejects(next.deleteCard(failed.task), /Write failed/);
await next.reload(); assert.equal(next.tasks.length, 2);
});
test("damaged deletion records block card access instead of restoring deleted cards", async () => {
const { workspace, files } = fixture();
for (const source of ['{', '{"schema":2,"ids":[]}', '{"schema":1,"ids":[4]}']) {
files.set(deletedCardsPath, source);
const store = new TaskStore(workspace); await store.reload();
assert.equal(store.tasks.length, 0);
assert.ok(store.issues.some(issue => issue.startsWith("Deleted cards:")));
}
});
@@ -0,0 +1,108 @@
// The image data of description drafts: an image in an unsaved description survives a close, and a discard leaves no image data.
import test from "node:test";
import assert from "node:assert/strict";
import { DescriptionDraft } from "../../../../src/lib/features/pm/storage/description-draft.ts";
import { imageMarkdown, imagePath, saveImages } from "../../../../src/lib/features/pm/storage/images.ts";
import { privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
import { memoryWorkspace } from "./_memory.ts";
const one = "12345678-1234-1234-1234-123456789abc";
const two = "87654321-1234-1234-1234-123456789abc";
const data = "data:image/png;base64,aGVsbG8=";
const other = "data:image/gif;base64,R0lGOD==";
/** A workspace that records the path of each write and creation, in order. */
function recorded() {
const workspace = memoryWorkspace({ [privateRulesPath]: "*\n" });
const writes: string[] = [];
const { write, create } = workspace;
workspace.write = async (path, contents, expected) => { await write(path, contents, expected); writes.push(path); };
workspace.create = async (path, contents) => { await create!(path, contents); writes.push(path); };
return { workspace, writes };
}
test("a draft from an earlier version, without an image record, still loads", async () => {
const { workspace } = recorded();
const draft = new DescriptionDraft(workspace, "task");
workspace.files.set(draft.path, JSON.stringify({ schema: 1, body: `Old ${imageMarkdown("a.png", one)}` }) + "\n");
const reopened = new DescriptionDraft(workspace, "task");
assert.equal(await reopened.load(), `Old ${imageMarkdown("a.png", one)}`);
assert.deepEqual(await reopened.loadImages(), new Map());
await reopened.save("Newer text");
assert.equal(workspace.files.has(reopened.imagesPath), false, "A draft without images makes no image record");
});
test("the draft keeps the data of its unsaved images, and the image folder stays empty", async () => {
const { workspace, writes } = recorded();
const draft = new DescriptionDraft(workspace, "task");
await draft.loadImages();
const body = `Text\n${imageMarkdown("a.png", one)}`;
await draft.save(body, new Map([[one, data]]));
assert.deepEqual(writes, [draft.imagesPath, draft.path], "The image data comes before the reference");
assert.equal([...workspace.files.keys()].some(path => path.startsWith(".runestone/pm/images/")), false);
// A text change does not write the image data again.
await draft.save(`${body}\nMore`, new Map([[one, data]]));
assert.deepEqual(writes, [draft.imagesPath, draft.path, draft.path]);
const reopened = new DescriptionDraft(workspace, "task");
assert.equal(await reopened.load(), `${body}\nMore`);
assert.deepEqual(await reopened.loadImages(), new Map([[one, data]]));
// A later save writes the image file from the restored data.
assert.deepEqual(await saveImages(workspace, body, await reopened.loadImages()), [one]);
assert.match(workspace.files.get(imagePath(one))!, /data:image\/png;base64,aGVsbG8=/);
});
test("a removed image keeps its data until the text without the reference is saved", async () => {
const { workspace, writes } = recorded();
const draft = new DescriptionDraft(workspace, "task");
await draft.loadImages();
await draft.save(`${imageMarkdown("a.png", one)}\n${imageMarkdown("b.gif", two)}`, new Map([[one, data], [two, other]]));
writes.length = 0;
await draft.save(imageMarkdown("a.png", one), new Map([[one, data]]));
assert.deepEqual(writes, [draft.path, draft.imagesPath]);
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[one, data]]));
// An image that replaces another one: the record holds both images while the text changes.
writes.length = 0;
await draft.save(imageMarkdown("b.gif", two), new Map([[two, other]]));
assert.deepEqual(writes, [draft.imagesPath, draft.path, draft.imagesPath]);
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[two, other]]));
});
test("a discarded draft keeps no image data and writes no image file", async () => {
const { workspace, writes } = recorded();
const draft = new DescriptionDraft(workspace, "task");
await draft.loadImages();
await draft.save(imageMarkdown("a.png", one), new Map([[one, data]]));
writes.length = 0;
await draft.save(null, new Map([[one, data]]));
assert.deepEqual(writes, [draft.path, draft.imagesPath], "The text goes first, so that no saved reference loses its data");
assert.equal(await new DescriptionDraft(workspace, "task").load(), null);
assert.equal(workspace.files.get(draft.imagesPath), JSON.stringify({ schema: 1, images: {} }) + "\n");
assert.equal([...workspace.files.keys()].some(path => path.startsWith(".runestone/pm/images/")), false);
});
test("an invalid image record stops the draft, and a stale writer cannot overwrite the images", async () => {
const { workspace } = recorded();
const draft = new DescriptionDraft(workspace, "task");
for (const images of [null, [], { "../secret": data }, { [one]: "data:image/svg+xml;base64,PHN2Zz4=" }]) {
workspace.files.set(draft.imagesPath, JSON.stringify({ schema: 1, images }));
await assert.rejects(draft.loadImages(), /description draft is invalid/);
}
workspace.files.delete(draft.imagesPath);
const first = new DescriptionDraft(workspace, "task"), second = new DescriptionDraft(workspace, "task");
await first.loadImages();
await second.loadImages();
await first.save(imageMarkdown("a.png", one), new Map([[one, data]]));
await assert.rejects(second.save(imageMarkdown("b.gif", two), new Map([[two, other]])), /exists/);
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[one, data]]));
});
test("an image save includes extra IDs, for example a card cover, and returns the saved IDs", async () => {
const workspace = memoryWorkspace({ [privateRulesPath]: "*\n" });
const pending = new Map([[one, data], [two, other]]);
assert.deepEqual(await saveImages(workspace, "", pending, [], [two]), [two]);
assert.equal(workspace.files.has(imagePath(one)), false);
assert.equal(workspace.files.has(imagePath(two)), true);
});
@@ -0,0 +1,31 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { headingEdit } from "../../../../src/lib/features/pm/model/description-format.ts";
function apply(value: string, start: number, end = start) {
const edit = headingEdit(value, start, end);
return { value: value.slice(0, edit.start) + edit.text + value.slice(edit.end), start: edit.selectionStart, end: edit.selectionEnd };
}
test("Heading formats the caret line and preserves the caret inside its text", () => {
assert.deepEqual(apply("Before\nTyped text\nAfter", 12), { value: "Before\n## Typed text\nAfter", start: 15, end: 15 });
assert.deepEqual(apply("Typed text", 0), { value: "## Typed text", start: 3, end: 3 });
assert.deepEqual(apply("Typed text", 10), { value: "## Typed text", start: 13, end: 13 });
});
test("Heading preserves selected text and formats all selected lines", () => {
assert.deepEqual(apply("One line\nTwo lines\nLast", 2, 12), { value: "## One line\n## Two lines\nLast", start: 5, end: 18 });
assert.deepEqual(apply("One\nTwo", 0, 4), { value: "## One\nTwo", start: 3, end: 7 });
});
test("Heading changes an existing heading without duplicate markers", () => {
assert.deepEqual(apply("# Title", 7), { value: "## Title", start: 8, end: 8 });
assert.deepEqual(apply("## Title", 5), { value: "## Title", start: 5, end: 5 });
assert.deepEqual(apply("### Title", 1), { value: "## Title", start: 3, end: 3 });
});
test("Heading leaves the caret after the marker on empty lines", () => {
assert.deepEqual(apply("", 0), { value: "## ", start: 3, end: 3 });
assert.deepEqual(apply("Text\n", 5), { value: "Text\n## ", start: 8, end: 8 });
assert.deepEqual(apply("\nText", 0), { value: "## \nText", start: 3, end: 3 });
});
+107
View File
@@ -0,0 +1,107 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
imageMarkdown,
imageReferences,
imagePath,
parseImage,
saveImages,
maxImageBytes,
} from "../../../../src/lib/features/pm/storage/images.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
const id = "12345678-1234-1234-1234-123456789abc";
const data = "data:image/png;base64,aGVsbG8=";
test("image references preserve surrounding text and restrict private paths", () => {
const markdown = imageMarkdown("shot [one]\n\\test.png", id);
assert.equal(markdown, `![shot one test.png](pm-image:${id})`);
const body = `Before\n${markdown}\nAfter`;
assert.deepEqual(imageReferences(body), [
{ id, name: "shot one test.png", markdown, index: 7 },
]);
assert.deepEqual(
imageReferences(
"![remote](https://example.com/a.png) ![bad](pm-image:../../secret)",
),
[],
);
assert.throws(() => imagePath("../../secret"), /invalid/);
});
test("saved image data rejects unsupported and executable sources", () => {
assert.equal(parseImage(JSON.stringify({ schema: 1, data })), data);
for (const value of [
null,
{},
{ schema: 1, data: "https://example.com/image.png" },
{ schema: 1, data: "data:image/svg+xml;base64,PHN2Zz4=" },
{ schema: 1, data: "data:image/png;base64,***=" },
])
assert.throws(() => parseImage(JSON.stringify(value)));
assert.throws(
() => parseImage("x".repeat(Math.ceil(maxImageBytes / 3) * 4 + 257)),
/50 MiB/,
);
});
test("save writes only referenced images, protects existing files, and permits retry", async () => {
const files = new Map<string, string>();
const writes: string[] = [];
const workspace: Workspace = {
async list() {
return [];
},
async read(path) {
return files.get(path)!;
},
async readOptional(path) {
return files.get(path) ?? null;
},
async create(path, source) {
if (files.has(path)) throw new Error("Already exists");
files.set(path, source);
writes.push(path);
},
async write() {
throw new Error("Unexpected overwrite");
},
};
const pending = new Map([
[id, data],
["87654321-1234-1234-1234-123456789abc", data],
]);
const body = imageMarkdown("Screenshot", id);
await saveImages(workspace, body, pending);
assert.deepEqual(writes, [".runestone/pm/.gitignore", imagePath(id)]);
await saveImages(workspace, body, pending);
assert.equal(writes.length, 2);
files.set(imagePath(id), "other image");
await assert.rejects(saveImages(workspace, body, pending), /Already exists/);
assert.equal(files.get(imagePath(id)), "other image");
});
test("attachment metadata saves staged images without description references", async () => {
const files = new Map<string, string>();
const workspace: Workspace = {
async list() { return []; },
async read(path) { return files.get(path)!; },
async readOptional(path) { return files.get(path) ?? null; },
async create(path, source) { files.set(path, source); },
async write() { throw new Error("Unexpected overwrite"); },
};
await saveImages(workspace, "", new Map([[id, data]]), [{ id, name: "Attachment.png" }]);
assert.equal(parseImage(files.get(imagePath(id))!), data);
});
test("image storage accepts exactly 50 MiB and rejects one extra byte", async () => {
assert.equal(maxImageBytes, 50 * 1024 * 1024);
const data = `data:image/png;base64,${Buffer.alloc(maxImageBytes).toString("base64")}`;
const files = new Map<string, string>();
const workspace: Workspace = {
async list() { return []; }, async read(path) { return files.get(path)!; }, async readOptional(path) { return files.get(path) ?? null; },
async write() { throw new Error("Unexpected overwrite"); },
async create(path, source) { files.set(path, source); },
};
await saveImages(workspace, "", new Map([[id, data]]), [{ id, name: "large.png" }]);
assert.equal(parseImage(files.get(imagePath(id))!), data);
const tooLarge = `data:image/png;base64,${Buffer.alloc(maxImageBytes + 1).toString("base64")}`;
assert.throws(() => parseImage(JSON.stringify({ schema: 1, data: tooLarge })), /50 MiB/);
});
+364
View File
@@ -0,0 +1,364 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
defaultLabels,
labelsPath,
parseLabels,
validateLabels,
} from "../../../../src/lib/features/pm/storage/labels.ts";
import { newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { editTask, newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import {
validateFields,
type TaskFields,
type Workspace,
} from "../../../../src/lib/features/pm/model/model.ts";
const fields: TaskFields = {
status: "todo",
tags: [],
sessions: [],
archived: false,
};
function fixture() {
const files = new Map<string, string>();
const writes: string[] = [];
const workspace: Workspace = {
async list() {
return [...files.keys()].map((path) => ({
name: path.split("/").at(-1)!,
rel_path: path,
kind: "file",
}));
},
async read(path) {
if (!files.has(path)) throw new Error("Missing file");
return files.get(path)!;
},
async readOptional(path) {
return files.get(path) ?? null;
},
async create(path, source) {
if (files.has(path)) throw new Error("File already exists");
files.set(path, source);
writes.push(path);
},
async write(path, source, expected) {
if (files.get(path) !== expected) throw new Error("File changed");
files.set(path, source);
writes.push(path);
},
};
return { files, writes, workspace, store: new TaskStore(workspace) };
}
test("old notes and custom tags remain independent of saved labels", () => {
const note = newTask(
"Task",
{ ...fields, tags: ["customer, success"], color: "pink" },
"Keep **details**.\n",
);
const source = note.source.replace("---\n", "---\nowner: Ada # keep\n");
const old = readTask(note.path, source)!;
assert.equal(old.labels, undefined);
const labeled = readTask(
note.path,
editTask(old, { labels: ["bug", "feature", "missing-label"] }),
)!;
assert.deepEqual(labeled.labels, ["bug", "feature", "missing-label"]);
const moved = readTask(note.path, editTask(labeled, { status: "doing" }))!;
assert.deepEqual(moved.labels, labeled.labels);
const cleared = readTask(note.path, editTask(moved, { labels: [] }))!;
assert.deepEqual(cleared.labels, []);
assert.deepEqual(cleared.tags, old.tags);
assert.equal(cleared.color, old.color);
assert.equal(cleared.body, old.body);
assert.match(cleared.source, /owner: Ada # keep/);
for (const labels of [null, "bug", [1], [""], ["bug", "bug"], ["bad id"]])
assert.throws(
() => validateFields({ ...fields, labels } as TaskFields),
/label IDs/,
);
});
test("one catalog serves every board and renames leave task files unchanged", async () => {
const { files, workspace, writes } = fixture();
const first = newBoardSource(),
second = newBoardSource();
files.set("First.md", first);
files.set("Second.md", second);
const a = new TaskStore(workspace, {
id: parseBoard(first).id,
path: "First.md",
});
const b = new TaskStore(workspace, {
id: parseBoard(second).id,
path: "Second.md",
});
await a.reload();
assert.deepEqual(a.labels.value, defaultLabels());
assert.equal(files.has(labelsPath), false);
await a.create(
"Shared label",
{ ...fields, labels: ["bug"] },
"Keep details.",
);
const task = a.tasks[0];
await a.saveLabels(
[
...a.labels.value,
{ id: "review", name: " Needs review ", color: "purple" },
],
a.labels.source,
);
await b.reload();
assert.equal(b.labels.value.at(-1)!.name, "Needs review");
assert.deepEqual(b.tasks[0].labels, ["bug"]);
const changed = b.labels.value.map((label) =>
label.id === "bug"
? { ...label, name: "Defect", color: "orange" as const, archived: true }
: label,
);
writes.length = 0;
await b.saveLabels(changed, b.labels.source);
await a.reload();
assert.deepEqual(writes, [labelsPath]);
assert.equal(a.labels.value[0].name, "Defect");
assert.equal(a.labels.value[0].color, "orange");
assert.equal(a.labels.value[0].archived, true);
assert.equal(files.get(task.path), task.source);
});
test("expanded palette colors persist in cards and shared labels", async () => {
const { store, workspace } = fixture();
const colors = [
"amber",
"lime",
"teal",
"cyan",
"indigo",
"magenta",
"brown",
"slate",
"gray",
] as const;
await store.reload();
await store.saveLabels(
[
...defaultLabels(),
...colors.map((color) => ({ id: color, name: color, color })),
],
store.labels.source,
);
for (const color of colors)
await store.create(
`Palette ${color}`,
{ ...fields, color, labels: [color] },
"Keep these details.",
);
const reopened = new TaskStore(workspace);
await reopened.reload();
for (const color of colors) {
const task = reopened.tasks.find(
(task) => task.title === `Palette ${color}`,
)!;
assert.equal(task.color, color);
assert.deepEqual(task.labels, [color]);
assert.equal(task.body, "Keep these details.");
assert.equal(
reopened.labels.value.find((label) => label.id === color)!.color,
color,
);
}
});
test("catalog validation blocks duplicate names, bad colors, IDs, and archive states", () => {
for (const labels of [
null,
{},
[null],
[{ id: "bug", name: "Bug", color: "url(bad)" }],
[{ id: "bug", name: "\nBug", color: "red" }],
[{ id: "bug", name: " ", color: "red" }],
[{ id: "bug", name: "Bug", color: "red", archived: "yes" }],
[
...defaultLabels(),
{ id: "other", name: " BUG ", color: "blue", archived: true },
],
[...defaultLabels(), { id: "bug", name: "Another", color: "blue" }],
])
assert.throws(() => validateLabels(labels));
assert.throws(() => parseLabels('{"schema":2,"labels":[]}'), /schema/);
assert.throws(() => parseLabels("broken json"), /saved labels file/);
assert.deepEqual(parseLabels('{"schema":1,"labels":[]}').labels, []);
});
test("concurrent catalog creation and stale edits cannot replace newer labels", async () => {
const { store, workspace, files } = fixture();
const other = new TaskStore(workspace);
await store.reload();
await other.reload();
await store.saveLabels(defaultLabels(), store.labels.source);
const created = files.get(labelsPath);
await assert.rejects(
other.saveLabels(defaultLabels(), other.labels.source),
/already exists/,
);
assert.equal(files.get(labelsPath), created);
await other.reload();
const expected = other.labels.source;
await store.saveLabels(
store.labels.value.map((label) => ({ ...label, archived: true })),
store.labels.source,
);
const updated = files.get(labelsPath);
await assert.rejects(other.saveLabels(defaultLabels(), expected), /changed/);
assert.equal(files.get(labelsPath), updated);
await store.reload();
await store.saveLabels([], store.labels.source);
assert.deepEqual(store.labels.value, []);
});
test("catalog read failures and invalid files leave task editing available without overwriting the catalog", async () => {
const { store, files, workspace } = fixture();
const task = newTask("Keep task", { ...fields, labels: ["unknown"] });
files.set(task.path, task.source);
files.set(labelsPath, "invalid json");
await store.reload();
assert.equal(store.tasks.length, 1);
assert.match(store.issues.join(" "), /Saved labels/);
assert.equal(store.labels.source, undefined);
await assert.rejects(store.saveLabels(defaultLabels(), null), /unavailable/);
await store.save(store.tasks[0], { status: "done" });
assert.equal(files.get(labelsPath), "invalid json");
assert.deepEqual(store.tasks[0].labels, ["unknown"]);
workspace.readOptional = async () => {
throw new Error("Permission denied");
};
await store.reload();
assert.match(store.issues.join(" "), /Permission denied/);
await assert.rejects(store.saveLabels(defaultLabels(), null), /unavailable/);
});
test("catalog writes preserve unknown metadata and propagate filesystem errors", async () => {
const { store, files, workspace } = fixture();
const source = JSON.stringify({
schema: 1,
future: { keep: true },
labels: defaultLabels().map((label) => ({ ...label, extra: "keep" })),
});
files.set(labelsPath, source);
await store.reload();
await store.saveLabels(store.labels.value, store.labels.source);
const data = JSON.parse(files.get(labelsPath)!);
assert.deepEqual(data.future, { keep: true });
assert.equal(data.labels[0].extra, "keep");
const before = files.get(labelsPath);
workspace.write = async () => {
throw new Error("Disk full");
};
await assert.rejects(
store.saveLabels(defaultLabels(), store.labels.source),
/Disk full/,
);
assert.equal(store.labels.source, before);
assert.equal(files.get(labelsPath), before);
});
test("a pending scan cannot replace saved label edits", async () => {
const { store, workspace } = fixture();
await store.reload();
let release!: () => void, entered!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const started = new Promise<void>((resolve) => {
entered = resolve;
});
const read = workspace.readOptional!;
let blocked = false;
workspace.readOptional = async (path) => {
if (path !== labelsPath || blocked) return read(path);
blocked = true;
const source = await read(path);
entered();
await gate;
return source;
};
const pending = store.reload();
await started;
await store.saveLabels(
[...defaultLabels(), { id: "new", name: "New label", color: "pink" }],
null,
);
release();
await pending;
assert.equal(store.labels.value.at(-1)!.id, "new");
assert.notEqual(store.labels.source, null);
});
test("older workspaces can read catalogs through listing but cannot create without create support", async () => {
const { store, workspace, files } = fixture();
delete workspace.readOptional;
delete workspace.create;
await store.reload();
await assert.rejects(
store.saveLabels(defaultLabels(), null),
/Update RuneStone/,
);
files.set(labelsPath, JSON.stringify({ schema: 1, labels: defaultLabels() }));
await store.reload();
assert.deepEqual(store.labels.value, defaultLabels());
store.dispose();
await assert.rejects(
store.saveLabels(defaultLabels(), store.labels.source),
/closed/,
);
});
test("deleting labels clears active, archived, unlisted, and shared cards while preserving unrelated data", async () => {
const { store, files, workspace } = fixture();
for (let index = 0; index < 4; index++) {
const task = newTask(`Card ${index}`, {
...fields, archived: index === 1, labels: ["bug", "feature", "unknown"], tags: ["bug"],
placements: index === 2 ? {} : { a: { listId: "todo", order: "m" }, b: { listId: null } },
}, "Keep **body**.");
files.set(task.path, task.source);
}
await store.reload();
await store.saveLabels(store.labels.value.filter(label => label.id !== "bug"), store.labels.source);
const reopened = new TaskStore(workspace);
await reopened.reload();
assert.equal(reopened.tasks.length, 4);
for (const task of reopened.tasks) {
assert.deepEqual(task.labels, ["feature", "unknown"]);
assert.deepEqual(task.tags, ["bug"]);
assert.equal(task.body, "Keep **body**.");
}
assert.equal(reopened.tasks[1].archived, true);
assert.deepEqual(reopened.tasks[0].placements, { a: { listId: "todo", order: "m" }, b: { listId: null } });
assert.equal(reopened.labels.value.some(label => label.id === "bug"), false);
});
test("failed label deletion keeps definitions and allows guarded retry", async () => {
const { store, files, workspace } = fixture();
for (const name of ["A", "B"]) {
const task = newTask(name, { ...fields, labels: ["bug"] }, "Keep body");
files.set(task.path, task.source);
}
await store.reload();
const next = store.labels.value.filter(label => label.id !== "bug");
const write = workspace.write;
workspace.write = async (path, source, expected) => {
if (path === store.tasks.find(task => task.title === "B")!.path) throw new Error("Disk full");
return write(path, source, expected);
};
await assert.rejects(store.saveLabels(next, store.labels.source), /Disk full/);
assert.equal(store.labels.value.some(label => label.id === "bug"), true);
assert.deepEqual(store.tasks.find(task => task.title === "B")!.labels, ["bug"]);
workspace.write = write;
await store.saveLabels(next, store.labels.source);
await store.reload();
assert.equal(store.tasks.every(task => !task.labels?.includes("bug")), true);
});
+118
View File
@@ -0,0 +1,118 @@
// The legacy format: the native feature finds visible boards, task notes, and the root label file, and offers the
// migration. The migration of the offer is the migration of the plugin, with its backups.
import test from "node:test";
import assert from "node:assert/strict";
import { findLegacy, hasLegacy, mentionsProjectData } from "../../../../src/lib/features/pm/storage/legacy.ts";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { boardMarkdown, catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts";
import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
import { deletedCardsPath } from "../../../../src/lib/features/pm/storage/deleted-cards.ts";
import { labelsPath, legacyLabelsPath } from "../../../../src/lib/features/pm/storage/labels.ts";
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { isHiddenCard } from "../../../../src/lib/features/pm/storage/persistence.ts";
import { fields, hiddenWorkspace, memoryWorkspace } from "./_memory.ts";
const labels = JSON.stringify({ schema: 1, labels: [{ id: "bug", name: "Bug", color: "red" }] });
test("only notes that name runestone_pm in their properties count as Project Management data", () => {
assert.equal(mentionsProjectData("---\nrunestone_pm:\n kind: task\n---\n"), true);
assert.equal(mentionsProjectData(String.fromCharCode(0xfeff) + "---\r\ntitle: x\r\nrunestone_pm: {}\r\n---\r\n"), true);
assert.equal(mentionsProjectData("# Plan\nrunestone_pm: in the body\n"), false);
assert.equal(mentionsProjectData("---\ntitle: x\n---\nrunestone_pm: in the body\n"), false);
assert.equal(mentionsProjectData("---\nother_runestone_pm: x\n---\n"), false);
});
test("an empty workspace or a migrated workspace has nothing to offer", async () => {
assert.equal(hasLegacy(await findLegacy(memoryWorkspace({ "Notes/Plain.md": "# Plain\n" }))), false);
const workspace = hiddenWorkspace([{ id: "hidden", title: "Hidden" }]);
assert.deepEqual(await findLegacy(workspace), { boards: [], cards: [], invalid: [], labels: false });
});
test("visible boards, task notes, and the root label file are found without a parse of plain notes", async () => {
const board = defaultBoard("visible-board");
const workspace = memoryWorkspace({
"Boards/Plan.md": boardMarkdown(board),
"Tasks/Write.md": newTask("Write", fields(), "Body", "write").source,
"Notes/Plain.md": "---\ntitle: [broken yaml\n---\nPlain note.\n",
"Notes/Broken.md": "---\nrunestone_pm: [\n---\n",
[legacyLabelsPath]: labels,
});
const content = await findLegacy(workspace);
assert.deepEqual(content, { boards: ["Boards/Plan.md"], cards: ["Tasks/Write.md"], invalid: ["Notes/Broken.md"], labels: true });
assert.equal(hasLegacy(content), true);
});
test("migrated, deleted, and already saved data does not count again", async () => {
const board = defaultBoard("old-board");
const workspace = hiddenWorkspace([{ id: "copied", title: "Copied" }], {
"Old.md": boardMarkdown(board),
"Gone.md": boardMarkdown(defaultBoard("gone-board")),
"Copied.md": newTask("Copied", fields(), "", "copied").source,
"Deleted.md": newTask("Deleted", fields(), "", "deleted").source,
[deletedCardsPath]: JSON.stringify({ schema: 1, ids: ["deleted"] }),
[legacyLabelsPath]: labels,
[labelsPath]: labels,
});
const catalog = JSON.parse(workspace.files.get(catalogPath)!);
catalog.boards.push({ name: "Old", value: board });
catalog.deletedBoardIds = ["gone-board"];
workspace.files.set(catalogPath, JSON.stringify(catalog));
assert.deepEqual(await findLegacy(workspace), { boards: [], cards: [], invalid: [], labels: false });
});
test("the offer migrates every legacy board, task note, and the label file with backups, and changes no original", async () => {
const board = defaultBoard("visible-board");
const originals = {
"Boards/Plan.md": boardMarkdown(board),
"Tasks/Write.md": newTask("Write", fields({ placements: { "visible-board": { listId: "todo" } } }), "Body", "write").source,
"Tasks/Read.md": newTask("Read", fields(), "", "read").source,
[legacyLabelsPath]: labels,
};
const workspace = memoryWorkspace(originals);
// The native view sees nothing before the migration.
const hidden = new TaskStore(workspace, undefined, { legacy: false });
await hidden.reload();
assert.equal(hidden.tasks.length, 0);
assert.equal(hidden.boards.length, 0);
// The offer: a legacy store migrates all boards, the labels, and every visible task note.
const legacy = new TaskStore(workspace, undefined, { legacy: true });
await legacy.reload();
const files = await legacy.migrateStorage(legacy.tasks.filter(task => !isHiddenCard(task.path)).map(task => task.id));
legacy.dispose();
assert.deepEqual(files.map(file => file.path).sort(), ["Boards/Plan.md", "Tasks/Read.md", "Tasks/Write.md", legacyLabelsPath].sort());
for (const file of files) assert.equal(workspace.files.get(file.backup), file.source);
for (const [path, source] of Object.entries(originals)) assert.equal(workspace.files.get(path), source, path);
assert.equal(hasLegacy(await findLegacy(workspace)), false);
await hidden.reload();
assert.deepEqual(hidden.tasks.map(task => task.id).sort(), ["read", "write"]);
assert.deepEqual(hidden.boards.map(item => [item.id, item.name]), [["visible-board", "Plan"]]);
assert.deepEqual(hidden.labels.value.map(label => label.id), ["bug"]);
});
test("Add existing note copies a plain note into a private card and leaves the note unchanged", async () => {
const note = "---\ntags: [keep]\n---\n# Research\nDetails.\n";
const workspace = hiddenWorkspace([], { "Notes/Research.md": note });
const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false });
await store.reload();
const card = await store.adopt("Notes/Research.md");
assert.equal(workspace.files.get("Notes/Research.md"), note);
assert.equal(card.path, cardPath(card.id));
assert.equal(card.title, "Research");
assert.equal(card.body, "# Research\nDetails.\n");
assert.equal(card.placements?.board.listId, "todo");
assert.match(workspace.files.get(card.path)!, /^tags: \[ keep \]$/m);
assert.deepEqual(store.tasks.map(task => task.id), [card.id]);
// A legacy task note migrates with a backup and keeps its ID.
const legacyNote = newTask("Legacy", fields(), "Old body", "legacy-id").source;
workspace.files.set("Notes/Legacy.md", legacyNote);
const migrated = await store.adopt("Notes/Legacy.md");
assert.equal(migrated.id, "legacy-id");
assert.equal(migrated.path, cardPath("legacy-id"));
assert.equal(workspace.files.get("Notes/Legacy.md"), legacyNote);
assert.equal(workspace.files.get(".runestone/pm/backups/Notes/Legacy.md"), legacyNote);
assert.equal(readTask(migrated.path, workspace.files.get(migrated.path)!)!.placements?.board.listId, "todo");
// A second add of the same note finds the same card.
assert.equal((await store.adopt("Notes/Legacy.md")).path, migrated.path);
assert.equal(store.tasks.length, 2);
});
@@ -0,0 +1,514 @@
import test from "node:test";
import assert from "node:assert/strict";
import { newBoardSource, parseBoard, boardDocument } from "../../../../src/lib/features/pm/storage/board.ts";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newTask, readTask, adoptNote } from "../../../../src/lib/features/pm/storage/notes.ts";
import type { Workspace, TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
const fields: TaskFields = {
status: "todo",
tags: ["shared"],
sessions: [
{
id: "session",
start: "2026-10-08T16:00:00Z",
end: "2026-10-08T17:00:00Z",
timeZone: "America/Vancouver",
},
],
due: { date: "2026-10-30" },
plan: { start: "2026-10-05", end: "2026-10-31" },
archived: false,
};
function fixture() {
const first = newBoardSource(),
second = newBoardSource();
const files = new Map<string, string>([
["Project/Launch.md", first],
["Project/Personal.md", second],
["Task.md", newTask("Task", fields, "Keep this description.").source],
]);
let fail = false;
const writes: string[] = [];
const workspace: Workspace = {
async readOptional(path) {
return files.get(path) ?? null;
},
async list(parent = "") {
const entries = new Map();
for (const path of files.keys()) {
const prefix = parent ? parent + "/" : "";
if (!path.startsWith(prefix)) continue;
const parts = path.slice(prefix.length).split("/");
entries.set(parts[0], {
name: parts[0],
rel_path: prefix + parts[0],
kind: parts.length > 1 ? "folder" : "file",
});
}
return [...entries.values()];
},
async read(path) {
const source = files.get(path);
if (source === undefined) throw Error("Missing");
return source;
},
async write(path, source, expected) {
if (fail) throw Error("Disk failure");
assert.equal(files.get(path), expected);
writes.push(path);
files.set(path, source);
},
async create(path, source) {
if (files.has(path)) throw Error("Exists");
files.set(path, source);
},
};
const a = new TaskStore(workspace, {
id: parseBoard(first).id,
path: "Project/Launch.md",
});
const b = new TaskStore(workspace, {
id: parseBoard(second).id,
path: "Project/Personal.md",
});
const all = new TaskStore(workspace);
return {
files,
workspace,
a,
b,
all,
writes,
failWrites() {
fail = true;
},
};
}
test("a shared task synchronizes status lists and keeps one schedule", async () => {
const { a, b, all, files, writes } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await a.reload();
const original = a.tasks[0];
writes.length = 0;
await a.moveTask(original, "done");
await b.reload();
await all.reload();
assert.deepEqual(writes, ["Task.md"]);
assert.equal(a.board.listFor(a.scopedTasks[0])?.id, "done");
assert.equal(b.board.listFor(b.scopedTasks[0])?.id, "done");
assert.equal(b.scopedTasks[0].status, "done");
assert.equal(all.scopedTasks.length, 1);
assert.equal(all.scopedTasks[0].id, original.id);
assert.deepEqual(all.scopedTasks[0].plan, fields.plan);
assert.deepEqual(all.scopedTasks[0].sessions, fields.sessions);
assert.deepEqual(all.scopedTasks[0].due, fields.due);
assert.equal(all.scopedTasks[0].body, original.body);
assert.equal(files.size, 3);
await b.save(b.scopedTasks[0], { due: { date: "2026-11-01" } });
await a.reload();
assert.equal(a.scopedTasks[0].due?.date, "2026-11-01");
});
test("leaving a Done list reopens completion and removal affects only one board", async () => {
const { a, b, all } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await a.reload();
await a.moveTask(a.tasks[0], "done");
await a.changeBoard(() => a.board.add("This week", null));
await a.moveTask(a.tasks[0], a.board.value.lists.at(-1)!.id);
assert.equal(a.tasks[0].status, "todo");
await a.removeFromBoard(a.tasks[0]);
assert.equal(a.scopedTasks.length, 0);
await b.reload();
await all.reload();
assert.equal(b.scopedTasks.length, 1);
assert.equal(all.scopedTasks.length, 1);
assert.equal(all.scopedTasks[0].archived, false);
});
test("All tasks moves synchronize memberships in one write and append to destination lists", async () => {
const { a, b, all, writes } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await a.create("Existing done", { ...fields, status: "done" }, "");
await all.reload();
const task = all.tasks.find((task) => task.title === "Task")!;
writes.length = 0;
await all.moveTask(task, "done");
assert.deepEqual(writes, ["Task.md"]);
for (const board of [a, b]) {
await board.reload();
const saved = board.scopedTasks.find((item) => item.id === task.id)!;
assert.equal(saved.status, "done");
assert.equal(board.board.listFor(saved)?.id, "done");
assert.deepEqual(saved.sessions, task.sessions);
assert.deepEqual(saved.plan, task.plan);
assert.deepEqual(saved.due, task.due);
assert.equal(saved.body, task.body);
}
assert.deepEqual(
a.cardsInList("done").map((task) => task.title),
["Existing done", "Task"],
);
assert.deepEqual(
b.scopedTasks.map((task) => task.title),
["Task"],
);
});
test("status changes use each board's designated list and preserve unmatched placements", async () => {
const { a, b, all } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await a.changeBoard(() => a.board.add("Released", "done"));
const destination = a.board.value.lists.at(-1)!.id;
await a.changeBoard(() =>
a.board.update((board) => {
board.defaults.done = destination;
}),
);
await b.changeBoard(() => b.board.remove("done"));
await all.reload();
const previous = all.tasks[0].placements![b.board.reference!.id];
await all.save(all.tasks[0], { status: "done" });
await a.reload();
await b.reload();
assert.equal(a.board.listFor(a.tasks[0])?.id, destination);
assert.deepEqual(b.tasks[0].placements![b.board.reference!.id], previous);
assert.equal(b.tasks[0].status, "done");
});
test("status changes preserve absent memberships and unavailable board placements", async () => {
const { a, b, all, files } = fixture();
await a.adopt("Task.md");
await all.reload();
await all.moveTask(all.tasks[0], "doing");
assert.equal(
Object.hasOwn(all.tasks[0].placements!, b.board.reference!.id),
false,
);
await a.reload();
const previous = a.tasks[0].placements![a.board.reference!.id];
files.delete("Project/Launch.md");
await all.moveTask(all.tasks[0], "done");
assert.deepEqual(all.tasks[0].placements![a.board.reference!.id], previous);
});
test("failed All tasks moves preserve every placement and the shared status", async () => {
const { a, b, all, files, failWrites } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await all.reload();
const before = all.tasks[0];
failWrites();
await assert.rejects(all.moveTask(before, "done"), /Disk failure/);
assert.equal(files.get("Task.md"), before.source);
assert.deepEqual(all.tasks[0], before);
});
test("board creation does not collect every workspace task", async () => {
const { a, b } = fixture();
await a.reload();
await b.reload();
assert.equal(a.scopedTasks.length, 0);
await a.create("New", fields, "");
await b.reload();
assert.equal(a.scopedTasks.length, 1);
assert.equal(b.scopedTasks.length, 0);
assert.equal(a.board.listFor(a.scopedTasks[0])?.id, "todo");
});
test("moving or deleting a board never moves or deletes its tasks", async () => {
const { a, all, files } = fixture();
await a.adopt("Task.md");
const taskSource = files.get("Task.md");
files.set("Elsewhere/Renamed.md", files.get("Project/Launch.md")!);
files.delete("Project/Launch.md");
await a.reload();
assert.equal(a.board.reference?.path, "Elsewhere/Renamed.md");
assert.equal(a.board.name, "Renamed");
assert.equal(a.scopedTasks.length, 1);
files.delete("Elsewhere/Renamed.md");
await a.reload();
await all.reload();
assert.equal(a.board.available, false);
assert.equal(all.scopedTasks.length, 1);
assert.equal(files.get("Task.md"), taskSource);
await assert.rejects(a.create("Lost", fields, ""), /unavailable/);
});
test("invalid and duplicate boards do not block the workspace schedule", async () => {
const { a, all, files } = fixture();
files.set("Copy.md", files.get("Project/Launch.md")!);
files.set(
"Project/Personal.md",
files.get("Project/Personal.md")!.replace("schema: 1", "schema: 99"),
);
await all.reload();
await a.reload();
assert.equal(all.tasks.length, 1);
assert.equal(all.boards.length, 0);
assert.equal(a.board.available, false);
assert.ok(all.issues.some((issue) => issue.includes("Duplicate board ID")));
assert.ok(all.issues.some((issue) => issue.includes("unsupported format")));
});
test("failed placement writes preserve both membership and status", async () => {
const { a, files, failWrites } = fixture();
await a.adopt("Task.md");
const source = files.get("Task.md");
failWrites();
await assert.rejects(a.moveTask(a.tasks[0], "done"), /Disk failure/);
assert.equal(files.get("Task.md"), source);
assert.equal(a.tasks[0].status, "todo");
assert.equal(a.board.listFor(a.tasks[0])?.id, "todo");
});
test("an open stale card cannot overwrite another board's edit", async () => {
const { a, b, files } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await a.reload();
const stale = a.tasks[0];
await b.moveTask(b.tasks[0], "doing");
const source = files.get("Task.md");
await assert.rejects(a.moveTask(stale, "done"), /task changed/);
assert.equal(files.get("Task.md"), source);
});
test("board properties and prose survive edits and boards cannot become task notes", async () => {
const { a, files } = fixture();
const source =
files
.get("Project/Launch.md")!
.replace("runestone_pm:", "owner: Ada # keep\nrunestone_pm:") +
"Board description.\n";
files.set("Project/Launch.md", source);
await a.reload();
await a.changeBoard(() => a.board.add("Review", null));
const saved = files.get("Project/Launch.md")!;
assert.ok(saved.includes("owner: Ada # keep"));
assert.ok(saved.endsWith("Board description.\n"));
assert.equal(readTask("Board.md", saved), null);
assert.throws(() => adoptNote("Board.md", saved), /already contains Project Management data/);
assert.equal(boardDocument("# A normal note", "Board.md"), null);
});
test("renaming a board resolves its current path and preserves shared tasks and lists", async () => {
const { a, b, all, files, writes } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
await a.changeBoard(() => a.board.add("Review", null));
const source = files.get("Project/Launch.md")!;
const taskSource = files.get("Task.md");
files.set("Moved/Launch.md", source);
files.delete("Project/Launch.md");
writes.length = 0;
await a.renameBoard(" Release 1.2 ", async (document, name) => {
assert.equal(document.path, "Moved/Launch.md");
assert.equal(document.id, parseBoard(source).id);
assert.equal(name, "Release 1.2");
files.set("Moved/Release 1.2.md", files.get(document.path)!);
files.delete(document.path);
return "Moved/Release 1.2.md";
});
assert.equal(a.board.name, "Release 1.2");
assert.equal(a.board.reference?.path, "Moved/Release 1.2.md");
assert.equal(a.board.value.lists.at(-1)?.name, "Review");
assert.equal(files.get("Moved/Release 1.2.md"), source);
assert.equal(files.get("Task.md"), taskSource);
assert.deepEqual(writes, []);
await b.reload();
await all.reload();
assert.equal(a.scopedTasks.length, 1);
assert.equal(b.scopedTasks.length, 1);
assert.equal(all.scopedTasks.length, 1);
await a.changeBoard(() => a.board.add("After rename", null));
await a.moveTask(a.scopedTasks[0], "doing");
assert.equal(a.board.listFor(a.scopedTasks[0])?.id, "doing");
});
test("failed renames and unavailable boards preserve workspace files", async () => {
const { a, all, files } = fixture();
await a.reload();
const before = [...files];
await assert.rejects(
a.renameBoard("Personal", async () => {
throw Error("Exists");
}),
/Exists/,
);
assert.equal(a.board.reference?.path, "Project/Launch.md");
assert.deepEqual([...files], before);
const rename = async () => {
assert.fail("Rename must not run");
return "";
};
await assert.rejects(all.renameBoard("All", rename), /available board/);
files.set("Copy.md", files.get("Project/Launch.md")!);
await assert.rejects(a.renameBoard("Duplicate", rename), /available board/);
files.delete("Copy.md");
files.delete("Project/Launch.md");
await assert.rejects(a.renameBoard("Missing", rename), /available board/);
});
test("board transfers preserve metadata and other memberships in one card write", async () => {
const { a, b, all, files, workspace, writes } = fixture();
await a.adopt("Task.md");
await b.adopt("Task.md");
const destination = await a.createBoard("Destination");
const target = new TaskStore(workspace, destination);
await target.reload();
await target.create("Already there", { ...fields, status: "doing" }, "");
await a.reload();
await a.save(a.tasks.find((task) => task.title === "Task")!, {
priority: "high", color: "pink", labels: ["bug"], assignees: ["Ada"],
customFields: [{ name: "Customer", value: "Keep" }],
});
files.set("Task.md", files.get("Task.md")!.replace("runestone_pm:", "owner: Ada # keep\nrunestone_pm:"));
await a.reload();
const before = a.tasks.find((task) => task.title === "Task")!;
writes.length = 0;
await a.transferTask(before, destination.id, "doing");
assert.deepEqual(writes, [before.path]);
assert.equal(a.scopedTasks.length, 0);
await target.reload();
await b.reload();
await all.reload();
const saved = target.tasks.find((task) => task.id === before.id)!;
const { placements: _oldPlacements, source: _oldSource, ...oldDetails } = before;
const { placements: _newPlacements, source: _newSource, ...newDetails } = saved;
assert.deepEqual(newDetails, oldDetails);
assert.deepEqual(saved.placements![b.board.reference!.id], before.placements![b.board.reference!.id]);
assert.equal(Object.hasOwn(saved.placements!, a.board.reference!.id), false);
assert.equal(saved.placements![destination.id].listId, "doing");
assert.ok(saved.source.includes("owner: Ada # keep"));
assert.deepEqual(target.cardsInList("doing").map((task) => task.title), ["Already there", "Task"]);
assert.equal(b.scopedTasks.length, 1);
assert.equal(all.tasks.filter((task) => task.id === before.id).length, 1);
});
test("hidden cards transfer to existing memberships, custom lists, and Unlisted without copies", async () => {
const { a, b, workspace, files } = fixture();
await a.reload();
await a.create("Private", fields, "![Keep image](runestone-pm-image:asset-id)");
const privateCard = a.scopedTasks[0];
assert.ok(privateCard.path.startsWith(".runestone/pm/cards/"));
await a.save(privateCard, { placements: {
...privateCard.placements,
[b.board.reference!.id]: { listId: "todo", order: "a" },
} });
await b.reload();
await b.changeBoard(() => b.board.add("Review", null));
const reviewId = b.board.value.lists.at(-1)!.id;
const before = a.tasks.find((task) => task.id === privateCard.id)!;
const paths = [...files.keys()];
await a.transferTask(before, b.board.reference!.id, reviewId);
await b.reload();
assert.equal(b.scopedTasks.length, 1);
assert.equal(b.board.listFor(b.scopedTasks[0])?.id, reviewId);
assert.equal(b.scopedTasks[0].body, privateCard.body);
assert.deepEqual([...files.keys()], paths);
const managed = await b.createBoard("Unlisted destination");
await b.transferTask(b.scopedTasks[0], managed.id, null);
const target = new TaskStore(workspace, managed);
await target.reload();
assert.equal(target.scopedTasks.length, 1);
assert.equal(target.scopedTasks[0].placements![managed.id].listId, null);
assert.equal(target.scopedTasks[0].status, "todo");
});
test("transfers reject missing, duplicated, deleted, and archived destinations without card changes", async () => {
for (const condition of ["missing", "duplicate", "deleted", "archived", "list"] as const) {
const { a, b, files, workspace, writes } = fixture();
await a.adopt("Task.md");
const before = a.scopedTasks[0];
let destination = b.board.reference!;
if (condition === "missing") files.delete(destination.path);
if (condition === "duplicate") files.set("Copy.md", files.get(destination.path)!);
if (condition === "deleted") {
await b.reload();
await b.changeBoard(() => b.board.deleteBoard());
}
if (condition === "archived") {
destination = await a.createBoard("Archived");
const target = new TaskStore(workspace, destination);
await target.reload();
await target.changeBoard(() => target.board.manage({ archived: true }));
}
if (condition === "list") {
await b.reload();
await b.changeBoard(() => b.board.remove("doing"));
}
writes.length = 0;
await assert.rejects(a.transferTask(before, destination.id, "doing"), /destination/);
assert.equal(files.get(before.path), before.source, condition);
assert.deepEqual(writes, [], condition);
assert.deepEqual(a.scopedTasks[0], before, condition);
}
});
test("transfers require a current source membership and active source board", async () => {
const { a, b, all, files } = fixture();
await all.reload();
await assert.rejects(all.transferTask(all.tasks[0], b.board.reference!.id, "todo"), /active board/);
await a.reload();
await assert.rejects(a.transferTask(a.tasks[0], b.board.reference!.id, "todo"), /no longer belongs/);
await a.adopt("Task.md");
const before = a.scopedTasks[0];
await assert.rejects(a.transferTask(before, a.board.reference!.id, "todo"), /different destination/);
files.delete(a.board.reference!.path);
await assert.rejects(a.transferTask(before, b.board.reference!.id, "todo"), /active board/);
assert.equal(files.get(before.path), before.source);
});
test("stale cards and failed transfer writes preserve every membership", async () => {
const { a, b, files, failWrites, writes } = fixture();
await a.adopt("Task.md");
const stale = a.scopedTasks[0];
await b.reload();
await b.save(b.tasks[0], { body: "An external edit." });
const external = files.get(stale.path);
await assert.rejects(a.transferTask(stale, b.board.reference!.id, "done"), /card changed/);
assert.equal(files.get(stale.path), external);
const current = a.scopedTasks[0];
writes.length = 0;
failWrites();
await assert.rejects(a.transferTask(current, b.board.reference!.id, "done"), /Disk failure/);
assert.equal(files.get(current.path), current.source);
assert.deepEqual(a.scopedTasks[0], current);
assert.deepEqual(writes, []);
});
test("detail board changes save draft fields and membership atomically with stale-write protection", async () => {
const { a, b, files, writes, failWrites } = fixture();
await a.reload(); await a.adopt("Task.md"); await b.reload();
const task = a.tasks[0]; const original = files.get(task.path);
writes.length = 0;
await a.saveToBoard(task, b.board.reference!.id, "doing", { body: "Draft preserved", priority: "highest" });
assert.equal(writes.length, 1);
const changed = readTask(task.path, files.get(task.path)!)!;
assert.equal(changed.body, "Draft preserved"); assert.equal(changed.priority, "highest");
assert.equal(changed.status, "doing"); assert.equal(changed.placements?.[a.board.reference!.id], undefined);
assert.equal(changed.placements?.[b.board.reference!.id]?.listId, "doing");
await assert.rejects(a.saveToBoard(task, b.board.reference!.id, "todo", { body: "Stale draft" }), /changed/);
const saved = files.get(task.path); failWrites();
await assert.rejects(b.saveToBoard(changed, a.board.reference!.id, "todo", { body: "Failed draft" }), /Disk failure/);
assert.equal(files.get(task.path), saved); assert.notEqual(saved, original);
});
test("pasted relative paths reuse one card and reject paths outside the workspace", async () => {
const { a, files } = fixture(); await a.reload();
const original = readTask("Task.md", files.get("Task.md")!)!;
await a.createOrLink("./Task.md", { ...fields, listId: "doing" });
assert.equal(a.tasks.length, 1); assert.equal(a.tasks[0].id, original.id);
assert.equal(a.tasks[0].placements?.[a.board.reference!.id]?.listId, "doing");
const before = new Map(files);
for (const path of ["../Task.md", "D:/Task.md", "/Task.md", "https://example.com/Task.md"])
await assert.rejects(a.createOrLink(path, fields), /relative Markdown path/);
assert.deepEqual(files, before);
});
+187
View File
@@ -0,0 +1,187 @@
// The main-bundle parts of the native Project Management feature: the catalog entry, the board view pattern of the
// session, the settings and their first-start migration, and the board reader of Background and Settings.
import test from "node:test";
import assert from "node:assert/strict";
import { featureEntry, featureOfOwner } from "../../../../src/lib/features/catalog.ts";
import { FeatureSession } from "../../../../src/lib/features/session.ts";
import { migrateFeatures, type LegacyPlugin } from "../../../../src/lib/features/migration.ts";
import type { FeatureContext, FeatureInstance } from "../../../../src/lib/features/types.ts";
import { boardOfView, boardViewId, PLANNING } from "../../../../src/lib/features/pm/views.ts";
import { DEFAULT_PROJECT_MANAGEMENT, migrateProjectManagement, normalizeProjectManagement, readViewStates, VIEW_STATES_KEY, writeViewStates, type ProjectManagementMigrationHost, type ProjectManagementSettings } from "../../../../src/lib/features/pmSettings.ts";
import { BOARD_CATALOG_PATH, parseBoardCatalog, readBoardCatalog, writeDefaultBoard } from "../../../../src/lib/features/pmBoards.ts";
import { SETTINGS_SECTIONS, LEGACY_KEYS } from "../../../../src/lib/settings/store.ts";
import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { parseCatalog } from "../../../../src/lib/features/pm/storage/catalog.ts";
function memoryStorage(initial: Record<string, string> = {}) {
const values = new Map(Object.entries(initial));
return { values, getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } };
}
function context(log: string[] = []): FeatureContext {
return {
openView: id => { log.push(`open ${id}`); }, openFile: async () => {}, onWorkspaceChange: () => () => {},
setViewTitle: (id, title) => { log.push(`title ${id} ${title}`); }, closeView: id => { log.push(`close ${id}`); },
replaceView: (current, next) => { log.push(`replace ${current} ${next}`); },
};
}
test("Project Management keeps the plugin ID, is on by default, and follows its package", () => {
const pm = featureEntry("pm");
assert.equal(pm.owner, "runestone.pm");
assert.equal(featureOfOwner("runestone.pm")?.id, "pm");
assert.equal(pm.defaultOn, true);
assert.equal(pm.followsPackage, true);
assert.deepEqual(pm.views.map(view => [view.id, view.placement, view.launch]), [["planning", "editor", true]]);
assert.deepEqual(pm.documentTypes, [], "The file tree reads no Markdown file for Project Management.");
assert.equal((SETTINGS_SECTIONS as readonly string[]).includes("projectManagement"), true);
assert.equal(LEGACY_KEYS.projectManagement, "runestone.project-management");
});
test("board view IDs are the plugin IDs, and only valid board IDs match", () => {
const id = "0c18bcdc-f41e-4a31-87f4-87c369f398c1";
const view = boardViewId(id);
assert.equal(view, "board-" + Buffer.from(id).toString("hex"));
assert.equal(boardOfView(view), id);
assert.equal(boardOfView(boardViewId("Plan ✓")), "Plan ✓");
for (const other of [PLANNING, "board-", "board-6", "board-zz", "board-ff", "board-41-42", "graph"]) assert.equal(boardOfView(other), null, other);
const pattern = featureEntry("pm").viewPatterns![0].match;
assert.equal(pattern.test(view), true);
assert.equal(pattern.test(PLANNING), false);
assert.equal(pattern.test(view + "x"), false);
});
test("the session answers for board views before the module loads, and gives them the board name later", async () => {
let loads = 0;
const log: string[] = [];
const restored: [string, unknown][] = [];
const mounted: string[] = [];
const instance: FeatureInstance = {
mount: view => { mounted.push(view); return () => {}; },
launch: view => { log.push(`launch ${view}`); },
restoreTabState: (view, state) => { restored.push([view, state]); },
saveTabState: view => ({ view }),
dispose() {},
};
const session = new FeatureSession(featureEntry("pm"), context(log), async () => { loads++; return { start: () => instance }; });
const view = boardViewId("board-a");
assert.equal(session.views.has(view), false);
const pattern = session.patternView(view)!;
assert.equal(pattern.placement, "editor");
assert.equal(pattern.title, "Project Management");
assert.equal(pattern.navigation, false);
assert.equal(pattern.launcher, false);
assert.equal(session.patternView(view), pattern, "One view for each ID");
assert.equal(session.patternView("board-zz"), undefined);
assert.equal(loads, 0, "No module load for a pattern view");
assert.equal(session.setViewTitle(view, "Roadmap"), true);
assert.equal(session.setViewTitle(view, "Roadmap"), false);
assert.equal(session.setViewTitle("planning", "Other"), false, "A catalog view keeps its title");
assert.equal(pattern.title, "Roadmap");
// A tab transfer restores the state, which loads the module.
await pattern.restoreTabState!({ search: "x" });
assert.deepEqual(restored, [[view, { search: "x" }]]);
assert.equal(loads, 1);
assert.deepEqual(pattern.saveTabState!(), { view });
const element = { replaceChildren() {} } as unknown as HTMLElement;
const dispose = await session.mount(boardViewId("board-b"), element);
assert.deepEqual(mounted, [boardViewId("board-b")]);
await dispose();
// The ribbon button launches `planning` through the feature, which chooses the default board.
await session.launch("planning");
assert.deepEqual(log, ["launch planning"]);
await session.stop();
assert.equal(session.patternView(boardViewId("board-c")), undefined, "An off feature makes no views");
});
test("the settings keep 2, 3, or 5 priority levels", () => {
assert.deepEqual(normalizeProjectManagement(undefined), DEFAULT_PROJECT_MANAGEMENT);
assert.deepEqual(normalizeProjectManagement({ priorityLevels: 5, other: 1 }), { priorityLevels: 5 });
assert.deepEqual(normalizeProjectManagement({ priorityLevels: 2 }), { priorityLevels: 2 });
for (const value of [4, "5", null, 0]) assert.deepEqual(normalizeProjectManagement({ priorityLevels: value }), { priorityLevels: 3 });
});
test("view states stay in localStorage, and a write keeps the states of other tabs", () => {
const storage = memoryStorage({ [VIEW_STATES_KEY]: JSON.stringify({ planning: { view: "gantt" } }) });
writeViewStates({ "board-61": { search: "bug" } }, storage);
assert.deepEqual(readViewStates(storage), { planning: { view: "gantt" }, "board-61": { search: "bug" } });
assert.deepEqual(readViewStates(memoryStorage({ [VIEW_STATES_KEY]: "not json" })), {});
});
function pmHost(missing: boolean, storage = memoryStorage()) {
const written: ProjectManagementSettings[] = [];
const host: ProjectManagementMigrationHost & { written: ProjectManagementSettings[] } = {
written, missing: () => missing, storage, write: async value => { written.push(value); },
};
return host;
}
test("the first start makes the section and the view states from the kept plugin settings", async () => {
const legacy: LegacyPlugin = { id: "runestone.pm", installed: true, enabled: true, settings: { priorityLevels: 5, viewStates: { planning: { view: "calendar" } }, other: true } };
const host = pmHost(true);
assert.deepEqual(await migrateProjectManagement(legacy, host), { priorityLevels: 5 });
assert.deepEqual(host.written, [{ priorityLevels: 5 }]);
assert.deepEqual(JSON.parse(host.storage.getItem(VIEW_STATES_KEY)!), { planning: { view: "calendar" } });
// Existing view states in localStorage stay.
const kept = pmHost(true, memoryStorage({ [VIEW_STATES_KEY]: "{\"planning\":{}}" }));
await migrateProjectManagement(legacy, kept);
assert.equal(kept.storage.getItem(VIEW_STATES_KEY), "{\"planning\":{}}");
// Without plugin settings, the defaults apply. A present section stays.
const fresh = pmHost(true);
assert.deepEqual(await migrateProjectManagement(undefined, fresh), DEFAULT_PROJECT_MANAGEMENT);
assert.equal(fresh.storage.getItem(VIEW_STATES_KEY), null);
const present = pmHost(false);
assert.equal(await migrateProjectManagement(legacy, present), null);
assert.deepEqual(present.written, []);
});
test("the feature migration asks for the Project Management package when the section is missing", async () => {
const asked: string[][] = [];
const switches: unknown[] = [];
const host = { read: () => ({ git: true, background: true, terminal: true, pdf: true }), write: async (value: unknown) => { switches.push(value); },
legacy: async (ids: string[]) => { asked.push(ids); return ids.map(id => ({ id, installed: true, enabled: false, settings: { priorityLevels: 2 } })); } };
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
const terminal = { missing: () => false, legacy: () => null, write: async () => {} };
const pm = pmHost(true);
assert.deepEqual(await migrateFeatures(host, background, terminal, pm), ["pm"]);
assert.deepEqual(asked, [["runestone.pm"]]);
assert.deepEqual(switches, [{ git: true, background: true, terminal: true, pdf: true, pm: false }], "The switch follows the disabled package.");
assert.deepEqual(pm.written, [{ priorityLevels: 2 }]);
});
test("the board reader lists the boards of workspace.json without the feature code", async () => {
const value = {
schema: 1, defaultBoardId: "b", defaultBoardPath: "pm-board:b", future: { keep: true },
boards: [{ name: "Roadmap", value: defaultBoard("a") }, { name: "Bugs", value: defaultBoard("b"), archived: true }, { name: "Copy", value: defaultBoard("a") }, { name: "No value" }],
};
const source = JSON.stringify(value);
assert.deepEqual(parseBoardCatalog(source), { source, defaultBoardId: "b", boards: [{ id: "a", name: "Roadmap", archived: false }, { id: "b", name: "Bugs", archived: true }] });
assert.deepEqual(parseBoardCatalog(null), { boards: [], defaultBoardId: null, source: null });
assert.throws(() => parseBoardCatalog("{\"schema\":2,\"boards\":[]}"), /unsupported/);
const reads: string[] = [];
const catalog = await readBoardCatalog(async path => { reads.push(path); return source; });
assert.deepEqual(reads, [BOARD_CATALOG_PATH]);
assert.deepEqual(catalog.boards.map(board => board.id), ["a", "b"]);
});
test("Settings saves the default board with a guarded write and keeps the other keys", async () => {
const files = new Map([[BOARD_CATALOG_PATH, JSON.stringify({ schema: 1, boards: [{ name: "Roadmap", value: defaultBoard("a") }], future: 1 }, null, 2) + "\n"]]);
const read = async (path: string) => files.get(path) ?? null;
const write = async (path: string, contents: string, expected: string) => {
if (files.get(path) !== expected) throw new Error("The file changed.");
files.set(path, contents);
};
await writeDefaultBoard("a", read, write);
const saved = JSON.parse(files.get(BOARD_CATALOG_PATH)!);
assert.equal(saved.defaultBoardId, "a");
assert.equal(saved.defaultBoardPath, "pm-board:a");
assert.equal(saved.future, 1);
// The feature code accepts the file.
assert.equal(parseCatalog(files.get(BOARD_CATALOG_PATH)!).defaultBoardId, "a");
await writeDefaultBoard(null, read, write);
assert.equal(JSON.parse(files.get(BOARD_CATALOG_PATH)!).defaultBoardId, null);
await assert.rejects(writeDefaultBoard("missing", read, write), /unavailable/);
await assert.rejects(writeDefaultBoard("a", read, async () => { throw new Error("The file changed."); }), /changed/);
// Without a catalog, All tasks needs no write.
await writeDefaultBoard(null, async () => null, async () => { throw new Error("no write"); });
});
@@ -0,0 +1,63 @@
import test from "node:test";
import assert from "node:assert/strict";
import { newTask, readTask, editTask, adoptNote } from "../../../../src/lib/features/pm/storage/notes.ts";
import { DescriptionDraft } from "../../../../src/lib/features/pm/storage/description-draft.ts";
import { defaultBoardPath } from "../../../../src/lib/features/pm/model/workspace-default.ts";
import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { catalogPath, boardMarkdown } from "../../../../src/lib/features/pm/storage/catalog.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
function fixture() {
const files = new Map<string, string>();
const workspace: Workspace = {
async list() { throw new Error("No task scan expected"); },
async read(path) { if (!files.has(path)) throw new Error("Missing"); return files.get(path)!; },
async readOptional(path) { return files.get(path) ?? null; },
async create(path, source) { if (files.has(path)) throw new Error("Exists"); files.set(path, source); },
async write(path, source, expected) { if (files.get(path) !== expected) throw new Error("Conflict"); files.set(path, source); },
};
return { files, workspace };
}
const fields = { status: "todo" as const, tags: [], sessions: [], archived: false };
test("new captures record immutable timestamps and existing legacy cards keep an unknown date", () => {
const before = Date.now();
const note = newTask("Timestamp", fields);
const task = readTask(note.path, note.source)!;
assert.ok(Date.parse(task.createdAt!) >= before && Date.parse(task.createdAt!) <= Date.now());
const edited = readTask(task.path, editTask(task, { body: "Updated", status: "done", placements: { next: { listId: "done" } } }))!;
assert.equal(edited.createdAt, task.createdAt);
assert.throws(() => editTask(task, { createdAt: undefined }), /cannot change/);
assert.throws(() => editTask(task, { createdAt: "2026-01-01T00:00:00Z" }), /cannot change/);
assert.ok(Date.parse(readTask("Old.md", adoptNote("Old.md", "Original note"))!.createdAt!) >= before);
const legacy = readTask(note.path, note.source.replace(/^ createdAt:.*\n/m, ""))!;
assert.equal(readTask(legacy.path, editTask(legacy, { title: "Legacy edit" }))!.createdAt, undefined);
assert.equal(adoptNote(legacy.path, legacy.source), legacy.source);
});
test("description drafts persist separately, cancel clears them, and stale writers cannot overwrite drafts", async () => {
const { files, workspace } = fixture();
const draft = new DescriptionDraft(workspace, "task");
assert.equal(await draft.load(), null);
await draft.save("Uncommitted text");
const other = new DescriptionDraft(workspace, "task");
assert.equal(await other.load(), "Uncommitted text");
await draft.save("Newer draft");
await assert.rejects(other.save("Stale draft"), /Conflict/);
await draft.save(null);
assert.equal(await new DescriptionDraft(workspace, "task").load(), null);
assert.ok([...files.keys()].every(path => !path.includes("/cards/")));
});
test("default board resolves without scanning cards and keeps unavailable selections fixed", async () => {
const { files, workspace } = fixture();
const board = defaultBoard("chosen");
const catalog = { schema: 1, boards: [{ name: "Chosen", value: board }], defaultBoardId: "chosen", unknown: "keep" };
files.set(catalogPath, JSON.stringify(catalog));
assert.equal(await defaultBoardPath(workspace), "pm-board:chosen");
files.set(catalogPath, JSON.stringify({ ...catalog, boards: [] }));
assert.equal(await defaultBoardPath(workspace), undefined);
assert.equal(JSON.parse(files.get(catalogPath)!).defaultBoardId, "chosen");
files.set("Legacy.md", boardMarkdown(board));
files.set(catalogPath, JSON.stringify({ ...catalog, boards: [], defaultBoardPath: "Legacy.md" }));
assert.equal(await defaultBoardPath(workspace), "Legacy.md");
files.set(catalogPath, JSON.stringify({ ...catalog, boards: [], defaultBoardPath: "Legacy.md", deletedBoardIds: ["chosen"] }));
assert.equal(await defaultBoardPath(workspace), undefined);
});
@@ -0,0 +1,142 @@
// The hidden mode of the store (`legacy: false`): it reads only `.runestone/pm/`, and a save, a delete, a move,
// or a watcher event reads only the changed files again.
import test from "node:test";
import assert from "node:assert/strict";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
import { catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts";
import { deletedCardsPath } from "../../../../src/lib/features/pm/storage/deleted-cards.ts";
import { labelsPath } from "../../../../src/lib/features/pm/storage/labels.ts";
import { editTask, newTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { newBoardSource } from "../../../../src/lib/features/pm/storage/board.ts";
import { privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
import { fields, hiddenWorkspace } from "./_memory.ts";
const cards = [{ id: "a", title: "Card A" }, { id: "b", title: "Card B" }, { id: "c", title: "Card C" }];
test("the hidden mode reads only .runestone/pm and never a visible Markdown note", async () => {
const workspace = hiddenWorkspace(cards, {
"Notes/Task.md": newTask("Task", fields(), "", "visible").source,
"Board.md": newBoardSource(),
});
const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false });
await store.reload();
assert.equal(store.legacy, false);
assert.deepEqual(store.issues, []);
assert.deepEqual(store.tasks.map(task => task.id), ["a", "b", "c"]);
assert.deepEqual(store.boards.map(board => board.id), ["board"]);
assert.equal(workspace.markdownLists, 0);
assert.ok(workspace.reads.every(path => path.startsWith(".runestone/pm/") || path === "runestone-pm-labels.json"), workspace.reads.join(", "));
assert.equal(workspace.reads.some(path => path.endsWith(".md") && !path.startsWith(".runestone/")), false);
// The legacy mode, for the migration and the skill helper, still reads the visible notes.
const legacy = new TaskStore(workspace);
await legacy.reload();
assert.equal(legacy.legacy, true);
assert.ok(legacy.tasks.some(task => task.id === "visible"));
});
test("a save, a move, and a delete read only the changed card again", async () => {
const workspace = hiddenWorkspace(cards);
const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false });
await store.reload();
const card = (id: string) => store.tasks.find(task => task.id === id)!;
// Each write also checks the Git exclusion file of `.runestone/pm/`. It is not a reload.
const reads = () => workspace.reads.filter(path => path !== privateRulesPath);
workspace.reads.length = 0;
await store.save(card("a"), { body: "Changed" });
assert.deepEqual(reads(), [cardPath("a")]);
assert.equal(card("a").body, "Changed");
workspace.reads.length = 0;
await store.moveTask(card("b"), "doing");
assert.deepEqual(reads(), [cardPath("b")]);
assert.equal(card("b").placements!.board.listId, "doing");
assert.equal(card("b").status, "doing");
workspace.reads.length = 0;
await store.deleteCard(card("c"));
assert.deepEqual(reads().filter(path => path !== deletedCardsPath), [cardPath("c")]);
assert.deepEqual(store.tasks.map(task => task.id), ["a", "b"]);
assert.match(workspace.files.get(deletedCardsPath)!, /"c"/);
});
test("a save still stops when another window changed the card", async () => {
const workspace = hiddenWorkspace(cards);
const store = new TaskStore(workspace, undefined, { legacy: false });
await store.reload();
const card = store.tasks.find(task => task.id === "a")!;
workspace.files.set(cardPath("a"), editTask(card, { body: "Other window" }));
await assert.rejects(store.save(card, { body: "This window" }), /changed/);
assert.equal(store.tasks.find(task => task.id === "a")!.body, "Other window");
});
test("watcher paths read only the changed files of .runestone/pm", async () => {
const workspace = hiddenWorkspace(cards);
const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false });
await store.reload();
// A change outside `.runestone/pm/`, or of images and drafts, reads nothing.
workspace.reads.length = 0; workspace.lists.length = 0;
await store.reloadPaths(["Notes/Plan.md", ".runestone/pm/images/x.json", ".runestone/pm/drafts/61.json", ".runestone/tabs.json"]);
assert.deepEqual(workspace.reads, []);
assert.deepEqual(workspace.lists, []);
// A new card from another window.
workspace.files.set(cardPath("d"), newTask("Card D", fields({ title: "Card D", placements: { board: { listId: "done" } } }), "", "d").source);
workspace.reads.length = 0;
await store.reloadPaths([cardPath("d")]);
assert.deepEqual(workspace.reads, [cardPath("d")]);
assert.deepEqual(store.tasks.map(task => task.id), ["a", "b", "c", "d"]);
// A deleted card file.
workspace.files.delete(cardPath("b"));
workspace.reads.length = 0;
await store.reloadPaths([cardPath("b")]);
assert.deepEqual(workspace.reads, [cardPath("b"), cardPath("b")]);
assert.deepEqual(store.tasks.map(task => task.id), ["a", "c", "d"]);
// A renamed board reads only the catalog.
const catalog = JSON.parse(workspace.files.get(catalogPath)!);
catalog.boards[0].name = "Renamed";
workspace.files.set(catalogPath, JSON.stringify(catalog));
workspace.reads.length = 0;
await store.reloadPaths([catalogPath]);
assert.deepEqual(workspace.reads, [catalogPath]);
assert.equal(store.board.name, "Renamed");
// Labels and deleted cards each read their own file.
workspace.files.set(labelsPath, JSON.stringify({ schema: 1, labels: [{ id: "x", name: "X", color: "red" }] }));
workspace.files.set(deletedCardsPath, JSON.stringify({ schema: 1, ids: ["d"] }));
workspace.reads.length = 0;
await store.reloadPaths([labelsPath, deletedCardsPath]);
assert.deepEqual(workspace.reads.sort(), [deletedCardsPath, labelsPath].sort());
assert.deepEqual(store.labels.value.map(label => label.id), ["x"]);
assert.deepEqual(store.tasks.map(task => task.id), ["a", "c"]);
});
test("an invalid card from a watcher event hides all cards until it is valid again", async () => {
const workspace = hiddenWorkspace(cards);
const store = new TaskStore(workspace, undefined, { legacy: false });
await store.reload();
const valid = workspace.files.get(cardPath("a"))!;
workspace.files.set(cardPath("a"), "---\nrunestone_pm: [\n---\n");
await store.reloadPaths([cardPath("a")]);
assert.deepEqual(store.tasks, []);
assert.match(store.issues.join(" "), /\.runestone\/pm\/cards\/61\.md/);
workspace.files.set(cardPath("a"), valid);
await store.reloadPaths([cardPath("a")]);
assert.deepEqual(store.issues, []);
assert.equal(store.tasks.length, 3);
});
test("a folder change, a marker change, or an unknown change reads everything again", async () => {
const workspace = hiddenWorkspace(cards);
const store = new TaskStore(workspace, undefined, { legacy: false });
await store.reload();
for (const paths of [[".runestone/pm/cards"], [".runestone/pm/cards/.gitignore"], [".runestone"], undefined]) {
workspace.lists.length = 0;
await store.reloadPaths(paths);
assert.deepEqual(workspace.lists, [".runestone/pm/cards"], String(paths));
}
});
@@ -0,0 +1,278 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
mkdtemp,
readFile,
writeFile,
mkdir,
readdir,
rm,
} from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { tmpdir } from "node:os";
import { resolve, join, dirname } from "node:path";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
import { cardOrder } from "../../../../src/lib/features/pm/storage/order.ts";
import {
privateRulesPath,
cardsMarker,
isHiddenCard,
} from "../../../../src/lib/features/pm/storage/persistence.ts";
import { catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts";
import { defaultLabels, labelsPath } from "../../../../src/lib/features/pm/storage/labels.ts";
import type { Workspace, TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
const fields: TaskFields = {
status: "todo",
tags: ["keep"],
labels: ["bug"],
archived: false,
sessions: [],
due: { date: "2026-10-30" },
plan: { start: "2026-10-07", end: "2026-10-10" },
placements: { board: { listId: "todo" } },
};
async function fixture(t: test.TestContext) {
const root = await mkdtemp(join(tmpdir(), "runestone-pm-private-"));
t.after(async () => {
assert.ok(
resolve(root).startsWith(resolve(tmpdir(), "runestone-pm-private-")),
);
await rm(root, { recursive: true, force: true });
});
const file = (path: string) => {
const absolute = resolve(root, path);
assert.ok(
absolute === root ||
absolute.startsWith(root + "/") ||
absolute.startsWith(root + "\\"),
);
return absolute;
};
const workspace: Workspace = {
async readOptional(path) {
try {
return await readFile(file(path), "utf8");
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
throw error;
}
},
async read(path) {
return readFile(file(path), "utf8");
},
async list(path = "") {
return (await readdir(file(path), { withFileTypes: true }))
.filter((entry) => ![".git", ".runestone"].includes(entry.name))
.map((entry) => ({
name: entry.name,
rel_path: (path ? path + "/" : "") + entry.name,
kind: entry.isDirectory() ? "folder" : "file",
}));
},
async create(path, source) {
await mkdir(dirname(file(path)), { recursive: true });
await writeFile(file(path), source, { flag: "wx" });
},
async write(path, source, expected) {
assert.equal(await workspace.read(path), expected, "Changed on disk");
await writeFile(file(path), source);
},
};
const git = (...args: string[]) =>
execFileSync("git", args, {
cwd: root,
encoding: "utf8",
windowsHide: true,
}).trim();
return { root, file, workspace, git, store: new TaskStore(workspace) };
}
test("new cards and other Project Management data stay outside navigation and normal Git staging", async (t) => {
const { store, workspace, git } = await fixture(t);
git("init", "--quiet");
await workspace.create!("README.md", "Shared project\n");
await store.createBoard("Board");
await store.create("Card: / duplicate?", fields, "Private details");
await store.create("Card: / duplicate?", fields, "Second card");
await store.saveLabels(defaultLabels(), store.labels.source);
await store.reload();
assert.equal(store.tasks.length, 2);
assert.equal(new Set(store.tasks.map((task) => task.id)).size, 2);
assert.ok(store.tasks.every((task) => isHiddenCard(task.path)));
assert.deepEqual(
(await workspace.list()).map((entry) => entry.name),
["README.md"],
);
assert.equal(await workspace.readOptional!(".gitignore"), null);
for (const path of [
catalogPath,
labelsPath,
privateRulesPath,
cardsMarker,
...store.tasks.map((task) => task.path),
])
assert.equal(git("check-ignore", "--", path), path);
git("add", ".");
assert.equal(git("ls-files"), "README.md");
});
test("Git protection is installed before data writes and failures preserve privacy", async (t) => {
const { store, workspace } = await fixture(t);
const create = workspace.create!;
const writes: string[] = [];
workspace.create = async (path, source) => {
writes.push(path);
if (path === privateRulesPath)
throw new Error("Cannot create Git exclusion");
await create(path, source);
};
await assert.rejects(store.create("Private", fields, ""), /Git exclusion/);
assert.deepEqual(writes, [privateRulesPath]);
workspace.create = async (path, source) => {
writes.push(path);
await create(path, source);
};
writes.length = 0;
await store.create("Private", fields, "");
assert.deepEqual(writes, [
privateRulesPath,
cardsMarker,
store.tasks[0].path,
]);
});
test("selected legacy cards migrate with exact backups, stable order, and no changes to linked notes", async (t) => {
const { store, workspace, file, git } = await fixture(t);
git("init", "--quiet");
const original = newTask("Existing", fields, "Preserve **body**.\n");
const source = original.source.replace("---\n", "---\nowner: Ada # retain\n");
await workspace.create!(original.path, source);
const linked = newTask("Shared", fields, "Keep as a note");
await workspace.create!("Docs/Shared.md", linked.source);
git("add", ".");
await store.reload();
const before = store.tasks.find((task) => task.title === "Existing")!;
const stale = new TaskStore(workspace);
await stale.reload();
const report = await store.migrateStorage([before.id]);
assert.equal(report.length, 1);
const current = store.tasks.find((task) => task.id === before.id)!;
assert.equal(current.path, cardPath(before.id));
assert.equal(current.title, before.title);
assert.equal(current.body, before.body);
for (const key of [
"status",
"tags",
"labels",
"due",
"plan",
"sessions",
"archived",
] as const)
assert.deepEqual(current[key], before[key]);
assert.equal(cardOrder(current, "board"), cardOrder(before, "board"));
assert.equal(cardOrder(current), cardOrder(before));
assert.equal(await workspace.read(original.path), source);
assert.equal(await workspace.read(report[0].backup), source);
assert.equal(await workspace.read("Docs/Shared.md"), linked.source);
assert.match(current.source, /owner: Ada # retain/);
await assert.rejects(stale.save(before, { status: "done" }), /changed/);
await store.save(current, { title: "Private: edited", status: "doing" });
await store.migrateStorage([before.id]);
assert.equal(
store.tasks.find((task) => task.id === before.id)!.title,
"Private: edited",
);
await rm(file(original.path));
await store.reload();
assert.equal(store.tasks.length, 2);
assert.equal(
store.tasks.find((task) => task.id === before.id)!.status,
"doing",
);
git("add", "-A");
assert.equal(git("ls-files"), "Docs/Shared.md");
});
test("partial card migration resumes without replacing newer hidden edits", async (t) => {
const { workspace, store } = await fixture(t);
for (const title of ["A", "B"]) {
const note = newTask(title, fields);
await workspace.create!(note.path, note.source);
}
await store.reload();
const ids = store.tasks.map((task) => task.id);
const blocked = cardPath(ids[1]);
const create = workspace.create!;
workspace.create = async (path, source) => {
if (path === blocked) throw new Error("Disk full");
await create(path, source);
};
await assert.rejects(store.migrateStorage(ids), /Disk full/);
await store.reload();
assert.equal(store.tasks.length, 2);
const first = store.tasks.find((task) => task.id === ids[0])!;
await store.save(first, { body: "Later edit" });
workspace.create = create;
await store.migrateStorage(ids);
assert.ok(store.tasks.every((task) => isHiddenCard(task.path)));
assert.equal(
store.tasks.find((task) => task.id === ids[0])!.body,
"Later edit",
);
});
test("changed originals block further migration and stale saves without losing either version", async (t) => {
const { workspace, store } = await fixture(t);
const note = newTask("A", fields);
await workspace.create!(note.path, note.source);
await store.reload();
const id = store.tasks[0].id;
await store.migrateStorage([id]);
const hidden = store.tasks[0];
await workspace.write(
note.path,
editTask(readTask(note.path, note.source)!, { body: "Outside edit" }),
note.source,
);
await assert.rejects(store.save(hidden, { status: "done" }), /changed/);
await assert.rejects(store.migrateStorage(), /issues/);
assert.equal(await workspace.read(hidden.path), hidden.source);
});
test("migration retains long filename titles and an existing Project Management ignore file", async (t) => {
const { workspace, store } = await fixture(t);
const note = newTask("A", fields);
const path = "Legacy/" + "a".repeat(130) + ".md";
await workspace.create!(path, note.source);
await workspace.create!(
privateRulesPath,
"# Personal rules\ncache/\n!keep.json\n",
);
await store.reload();
await store.migrateStorage([store.tasks[0].id]);
assert.equal(store.tasks[0].title, "a".repeat(130));
assert.equal(
await workspace.read(privateRulesPath),
"# Personal rules\ncache/\n!keep.json\n# RuneStone Project Management local data\n*\n",
);
});
test("an invalid hidden card cannot fall back to editing its old visible note", async (t) => {
const { workspace, store } = await fixture(t);
const note = newTask("A", fields);
await workspace.create!(note.path, note.source);
await store.reload();
const legacy = store.tasks[0];
await store.migrateStorage([legacy.id]);
const hidden = store.tasks[0];
await workspace.write(hidden.path, "broken data", hidden.source);
await store.reload();
assert.equal(store.tasks.length, 0);
assert.match(store.issues.join(" "), /hidden card ID/);
await assert.rejects(store.save(legacy, { status: "done" }), /changed/);
assert.equal(await workspace.read(note.path), note.source);
});
@@ -0,0 +1,195 @@
import test from "node:test";
import assert from "node:assert/strict";
import { setTimeout as delay } from "node:timers/promises";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
import { newTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { cardsMarker, privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
import { mapConcurrent, scanConcurrency } from "../../../../src/lib/features/pm/storage/scan.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
test("native discovery avoids directory bridge calls and retains save conflicts", async () => {
const boardSource = newBoardSource();
const boardId = parseBoard(boardSource).id;
const id = crypto.randomUUID();
const taskPath = cardPath(id);
const original = newTask(id, {
title: "Latency card", status: "todo", tags: [], sessions: [], archived: false,
placements: { [boardId]: { listId: "todo" } },
}, "Original details", id).source;
const files = new Map([["Board.md", boardSource], [taskPath, original], [cardsMarker, "*\n"], [privateRulesPath, "*\n"]]);
let scans = 0, lists = 0, writes = 0;
let scanFailure = false;
const workspace: Workspace = {
async listMarkdown() {
scans++;
if (scanFailure) throw new Error("Directory unavailable");
return [...files.keys()].filter(path => !path.startsWith(".") && path.endsWith(".md"));
},
async list(path) {
lists++;
assert.equal(path, ".runestone/pm/cards", "Visible folders must use the native listing");
return [{ name: taskPath.split("/").at(-1)!, rel_path: taskPath, kind: "file" }];
},
async read(path) { const value = files.get(path); assert.notEqual(value, undefined); return value!; },
async readOptional(path) { return files.get(path) ?? null; },
async create() { throw new Error("Unexpected create"); },
async write(path, source, expected) { assert.equal(files.get(path), expected); writes++; files.set(path, source); },
};
const store = new TaskStore(workspace, { id: boardId, path: "Board.md" });
await store.reload();
await store.moveTask(store.tasks[0], "doing");
await store.save(store.tasks[0], { body: "Updated details" });
assert.equal(scans, 3);
assert.equal(lists, 3);
assert.equal(writes, 2);
const stale = store.tasks[0];
const external = editTask(stale, { body: "External details" });
files.set(taskPath, external);
await assert.rejects(store.save(stale, { body: "Stale details" }), /changed/);
const current = store.tasks[0];
files.set("Copy.md", current.source);
await assert.rejects(store.moveTask(current, "done"), /duplicate/);
files.delete("Copy.md");
await store.reload();
scanFailure = true;
await assert.rejects(store.save(store.tasks[0], { body: "Blocked details" }), /Directory unavailable/);
assert.equal(files.get(taskPath), external);
assert.equal(writes, 2);
});
test("load, move, and detail saves overlap bounded reads without weakening conflict checks", async (t) => {
const source = newBoardSource();
const boardId = parseBoard(source).id;
const files = new Map([
["Board.md", source],
[cardsMarker, "*\n"],
[privateRulesPath, "*\n"],
]);
for (let index = 0; index < 32; index++) {
files.set(`Notes${index % 4}/Note${index}.md`, "An ordinary note.");
const id = crypto.randomUUID();
files.set(
cardPath(id),
newTask(
id,
{
title: `Card ${index}`,
status: "todo",
tags: [],
sessions: [],
archived: false,
placements: { [boardId]: { listId: "todo" } },
},
"Original details",
id,
).source,
);
}
let active = 0,
peak = 0,
reads = 0;
const readDelay = 15;
const workspace: Workspace = {
async list(parent = "") {
const entries = new Map();
const prefix = parent ? `${parent}/` : "";
for (const path of files.keys()) {
if (!path.startsWith(prefix)) continue;
const parts = path.slice(prefix.length).split("/");
entries.set(parts[0], {
name: parts[0],
rel_path: prefix + parts[0],
kind: parts.length > 1 ? "folder" : "file",
});
}
return [...entries.values()];
},
async read(path) {
reads++;
peak = Math.max(peak, ++active);
try {
await delay(readDelay);
const value = files.get(path);
if (value === undefined) throw new Error("Missing note");
return value;
} finally {
active--;
}
},
async readOptional(path) {
return files.get(path) ?? null;
},
async write(path, source, expected) {
assert.equal(files.get(path), expected);
files.set(path, source);
},
async create(path, source) {
assert.equal(files.has(path), false);
files.set(path, source);
},
};
const store = new TaskStore(workspace, { id: boardId, path: "Board.md" });
for (const [name, action] of [
["load", () => store.reload()],
["move", () => store.moveTask(store.tasks[0], "doing")],
["edit", () => store.save(store.tasks[0], { body: "Updated details" })],
] as const) {
peak = reads = 0;
const started = performance.now();
await action();
const elapsed = performance.now() - started;
assert.equal(reads, 65);
assert.equal(peak, scanConcurrency);
assert.equal(active, 0);
// The serial delay alone is 975 ms. Keep generous headroom for busy runners.
assert.ok(elapsed < reads * readDelay * 0.75, `${name} took ${elapsed} ms`);
t.diagnostic(
`${name}: ${reads} reads, peak ${peak}, ${Math.round(elapsed)} ms (serial delay ${reads * readDelay} ms)`,
);
}
assert.equal(store.tasks[0].body, "Updated details");
assert.equal(store.tasks[0].status, "doing");
const cached = store.tasks[1];
await store.reload();
assert.equal(
store.tasks.find((task) => task.id === cached.id),
cached,
);
const stale = store.tasks[0];
const external = editTask(stale, { body: "External details" });
files.set(stale.path, external);
await assert.rejects(store.save(stale, { body: "Stale details" }), /changed/);
assert.equal(files.get(stale.path), external);
const current = store.tasks.find((task) => task.id === stale.id)!;
files.set("Notes0/Copied card.md", current.source);
await assert.rejects(store.moveTask(current, "done"), /duplicate/);
assert.equal(files.get(current.path), external);
});
test("parallel scanning retains input order and drains pending work on failure", async () => {
let active = 0;
await assert.rejects(
mapConcurrent([0, 1, 2, 3], async (value) => {
active++;
try {
await delay(value === 0 ? 1 : 20);
if (value === 0) throw new Error("Directory unavailable");
return value;
} finally {
active--;
}
}),
/Directory unavailable/,
);
assert.equal(active, 0);
assert.deepEqual(
await mapConcurrent([0, 1, 2, 3], async (value) => {
await delay(4 - value);
return value;
}),
[0, 1, 2, 3],
);
});
@@ -0,0 +1,330 @@
import test from "node:test";
import assert from "node:assert/strict";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newBoardSource, parseBoard, BoardStore } from "../../../../src/lib/features/pm/storage/board.ts";
import {
catalogPath,
createBoard,
readCatalog,
boardKey,
parseCatalog,
} from "../../../../src/lib/features/pm/storage/catalog.ts";
import { migrateStorage } from "../../../../src/lib/features/pm/storage/migration.ts";
import { labelsPath, legacyLabelsPath } from "../../../../src/lib/features/pm/storage/labels.ts";
import { newTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
function fixture() {
const source = newBoardSource() + "Keep the board description.\n";
const id = parseBoard(source).id;
const task = newTask(
"Keep task",
{
status: "doing",
tags: ["tag"],
labels: ["bug"],
archived: false,
sessions: [],
placements: { [id]: { listId: "doing", order: "a" } },
},
"Keep task body.",
);
const files = new Map([
["Project/Launch.md", source],
[task.path, task.source],
[
legacyLabelsPath,
JSON.stringify({
schema: 1,
extra: "keep",
labels: [{ id: "bug", name: "Defect", color: "red" }],
}),
],
]);
let fail = "";
const workspace: Workspace = {
async readOptional(path) {
return files.get(path) ?? null;
},
async read(path) {
if (!files.has(path)) throw new Error("Missing file");
return files.get(path)!;
},
async list(parent = "") {
const entries = new Map();
for (const path of files.keys()) {
const prefix = parent ? parent + "/" : "";
if (!path.startsWith(prefix) || path.startsWith(".")) continue;
const parts = path.slice(prefix.length).split("/");
entries.set(parts[0], {
name: parts[0],
rel_path: prefix + parts[0],
kind: parts.length > 1 ? "folder" : "file",
});
}
return [...entries.values()];
},
async create(path, source) {
if (path === fail) throw new Error("Disk failure");
if (files.has(path)) throw new Error("Exists");
files.set(path, source);
},
async write(path, source, expected) {
if (path === fail) throw new Error("Disk failure");
if (files.get(path) !== expected) throw new Error("Conflict");
files.set(path, source);
},
};
return {
files,
workspace,
id,
task,
source,
setFailure(path: string) {
fail = path;
},
};
}
test("migration backs up exact originals, preserves cards and survives removal of visible metadata", async () => {
const { files, workspace, id, task, source } = fixture();
const originalLabels = files.get(legacyLabelsPath)!;
const store = new TaskStore(workspace, { id, path: "Project/Launch.md" });
const report = await store.migrateStorage();
assert.equal(report.length, 2);
for (const file of report)
assert.equal(files.get(file.backup), files.get(file.path));
assert.equal(files.get("Project/Launch.md"), source);
assert.equal(files.get(task.path), task.source);
assert.equal(store.board.reference?.path, boardKey(id));
assert.equal(store.scopedTasks.length, 1);
assert.equal(store.scopedTasks[0].placements?.[id].order, "a");
assert.equal(store.labels.value[0].name, "Defect");
await store.board.edit("doing", "Building", "doing");
await store.reload();
await store.saveLabels(
[{ id: "bug", name: "Issue", color: "blue" }],
store.labels.source,
);
await store.migrateStorage();
assert.equal(store.board.value.lists[1].name, "Building");
assert.equal(store.labels.value[0].name, "Issue");
assert.equal(files.get(legacyLabelsPath), originalLabels);
files.delete("Project/Launch.md");
files.delete(legacyLabelsPath);
const reopened = new TaskStore(workspace, { id, path: boardKey(id) });
await reopened.reload();
assert.equal(reopened.scopedTasks[0].id, store.tasks[0].id);
assert.equal(reopened.labels.value[0].name, "Issue");
assert.equal(reopened.board.value.lists[1].name, "Building");
assert.equal(reopened.issues.length, 0);
});
test("a label write failure can resume after boards commit without duplicating data", async () => {
const { files, workspace, setFailure } = fixture();
const store = new TaskStore(workspace);
setFailure(labelsPath);
await assert.rejects(store.migrateStorage(), /Disk failure/);
assert.equal((await readCatalog(workspace)).value.boards.length, 1);
assert.ok(files.has(legacyLabelsPath));
setFailure("");
await store.migrateStorage();
assert.equal((await readCatalog(workspace)).value.boards.length, 1);
assert.ok(files.has(labelsPath));
});
test("backup failure prevents migration publication", async () => {
const { files, workspace, setFailure } = fixture();
setFailure(".runestone/pm/backups/Project/Launch.md");
await assert.rejects(
new TaskStore(workspace).migrateStorage(),
/Disk failure/,
);
assert.equal(files.has(catalogPath), false);
assert.equal(files.has(labelsPath), false);
});
test("a legacy editor cannot write its original board after another view migrates it", async () => {
const { files, workspace, id, source } = fixture();
const stale = new BoardStore(workspace, { id, path: "Project/Launch.md" });
await stale.reload();
await new TaskStore(workspace).migrateStorage();
await assert.rejects(stale.add("Old edit", null), /hidden storage/);
assert.equal(files.get("Project/Launch.md"), source);
await stale.reload();
assert.equal(stale.reference?.path, boardKey(id));
await stale.add("New edit", null);
assert.equal(
(await readCatalog(workspace)).value.boards[0].value.lists.at(-1)?.name,
"New edit",
);
});
test("invalid or duplicate originals and conflicting labels block migration without writes", async () => {
for (const kind of [
"duplicate",
"invalid-labels",
"hidden-labels",
"future",
]) {
const { files, workspace, source } = fixture();
if (kind === "duplicate") files.set("Duplicate.md", source);
if (kind === "invalid-labels") files.set(legacyLabelsPath, "broken");
if (kind === "hidden-labels")
files.set(labelsPath, files.get(legacyLabelsPath)!);
if (kind === "future") files.set(catalogPath, '{"schema":99,"boards":[]}');
const before = new Map(files);
await assert.rejects(new TaskStore(workspace).migrateStorage());
assert.deepEqual(files, before);
}
});
test("changed legacy files or damaged backups never receive a successful migration check", async () => {
for (const path of [
"Project/Launch.md",
".runestone/pm/backups/Project/Launch.md",
legacyLabelsPath,
]) {
const { files, workspace } = fixture();
const store = new TaskStore(workspace);
await store.migrateStorage();
files.set(path, files.get(path)! + "\n");
const before = new Map(files);
await assert.rejects(store.migrateStorage());
assert.deepEqual(files, before);
}
});
test("hidden boards rename, archive, restore, and reject stale writes without changing task notes", async () => {
const { files, workspace, task } = fixture();
const reference = await createBoard(workspace, "New board");
const store = new TaskStore(workspace, reference);
await store.reload();
await store.renameBoard("Release");
const stale = new BoardStore(workspace, reference);
await stale.reload();
await store.board.manage({ archived: true });
await assert.rejects(stale.add("Review", null), /changed/);
await store.reload();
assert.equal(store.board.editable, false);
await assert.rejects(
store.create(
"No card",
{ status: "todo", tags: [], sessions: [], archived: false },
"",
),
/Restore/,
);
await store.board.manage({ archived: false });
await store.reload();
assert.equal(store.board.name, "Release");
assert.equal(store.board.editable, true);
assert.equal(files.get(task.path), task.source);
await assert.rejects(createBoard(workspace, "release"), /already exists/);
});
test("hidden data is isolated by workspace and unknown catalog fields survive edits", async () => {
const a = fixture(),
b = fixture();
const reference = await createBoard(a.workspace, "Private");
const value = JSON.parse(a.files.get(catalogPath)!);
value.futureMapping = { externalId: "remote-1" };
a.files.set(catalogPath, JSON.stringify(value));
const board = new BoardStore(a.workspace, reference);
await board.reload();
await board.add("Review", null);
assert.deepEqual(
JSON.parse(a.files.get(catalogPath)!).futureMapping,
value.futureMapping,
);
assert.equal((await readCatalog(b.workspace)).value.boards.length, 0);
});
test("deleting a board preserves cards, other boards, and unknown catalog fields", async () => {
for (const archived of [false, true]) {
const { files, workspace, task, id } = fixture();
const reference = await createBoard(workspace, "Accidental board");
const initial = JSON.parse(files.get(catalogPath)!);
initial.futureMapping = { keep: "value" };
initial.boards[0].archived = archived;
files.set(catalogPath, JSON.stringify(initial));
const store = new TaskStore(workspace, reference);
await store.reload();
await store.changeBoard(() => store.board.deleteBoard());
assert.equal(store.board.available, false);
assert.equal(store.board.editable, false);
assert.equal(files.get(task.path), task.source);
const all = new TaskStore(workspace);
await all.reload();
assert.deepEqual(all.boards.map((board) => board.id), [id]);
assert.equal(all.tasks[0].placements?.[id].listId, "doing");
const catalog = (await readCatalog(workspace)).value;
assert.deepEqual(catalog.boards, []);
assert.deepEqual(catalog.deletedBoardIds, [reference.id]);
assert.deepEqual(catalog.futureMapping, initial.futureMapping);
await assert.rejects(store.board.deleteBoard(), /available/);
}
});
test("deleted legacy and migrated boards stay deleted after reload and migration", async () => {
for (const migrated of [false, true]) {
const { files, workspace, id, source, task } = fixture();
const store = new TaskStore(workspace, { id, path: "Project/Launch.md" });
await store.reload();
const original = store.boards[0];
const stale = new BoardStore(workspace, { id, path: "Project/Launch.md" });
await stale.reload();
if (migrated) await store.migrateStorage();
await store.changeBoard(() => store.board.deleteBoard());
assert.equal(files.get("Project/Launch.md"), source);
assert.equal(files.get(task.path), task.source);
if (migrated) assert.equal(files.get(".runestone/pm/backups/Project/Launch.md"), source);
await assert.rejects(stale.add("Stale list", null), /deleted/);
await assert.rejects(stale.reload(), /deleted/);
assert.equal(stale.available, false);
await assert.rejects(migrateStorage(workspace, [original]), /deleted/);
const all = new TaskStore(workspace);
await all.reload();
assert.equal(all.boards.length, 0);
assert.equal(all.legacyBoards.length, 0);
assert.equal(all.tasks.length, 1);
await all.migrateStorage();
await all.reload();
assert.equal(all.boards.length, 0);
assert.equal(all.issues.length, 0);
}
});
test("changed boards and failed catalog writes block deletion", async () => {
for (const managed of [false, true]) {
const { files, workspace, id, setFailure } = fixture();
const reference = managed ? await createBoard(workspace, "New") : { id, path: "Project/Launch.md" };
const board = new BoardStore(workspace, reference);
await board.reload();
const path = managed ? catalogPath : reference.path;
files.set(path, files.get(path)! + "\n");
const before = new Map(files);
await assert.rejects(board.deleteBoard(), /changed/);
assert.deepEqual(files, before);
await board.reload();
setFailure(catalogPath);
await assert.rejects(board.deleteBoard(), /Disk failure/);
assert.equal(board.available, true);
assert.equal((await readCatalog(workspace)).value.deletedBoardIds, undefined);
}
});
test("a legacy board cannot be deleted from a stale view after migration", async () => {
const { workspace, id } = fixture();
const stale = new BoardStore(workspace, { id, path: "Project/Launch.md" });
await stale.reload();
await new TaskStore(workspace).migrateStorage();
await assert.rejects(stale.deleteBoard(), /hidden storage/);
assert.equal((await readCatalog(workspace)).value.boards.length, 1);
});
test("invalid deletion records fail closed", () => {
for (const deletedBoardIds of ["id", [null], [""], ["id", "id"]])
assert.throws(() => parseCatalog(JSON.stringify({ schema: 1, boards: [], deletedBoardIds })), /deleted board/);
});
@@ -0,0 +1,32 @@
import test from "node:test";
import assert from "node:assert/strict";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
test("subtask promotion retains checklist data and retries without duplicate cards", async () => {
const parent = newTask("Parent", { status: "todo", tags: [], sessions: [], archived: false,
subtasks: [{ id: "child", title: "Child", done: true }], priority: "high" }, "Keep the description");
const files = new Map([["Parent.md", parent.source]]);
const parentId = readTask("Parent.md", parent.source)!.id;
let fail = true;
const workspace: Workspace = {
async list(folder = "") { return [...files.keys()].filter(path => folder ? path.startsWith(`${folder}/`) : !path.startsWith(".")).map(path => ({ name: path.split("/").at(-1)!, rel_path: path, kind: "file" })); },
async read(path) { if (!files.has(path)) throw Error("Missing"); return files.get(path)!; },
async readOptional(path) { return files.get(path) ?? null; },
async create(path, source) { if (files.has(path)) throw Error("Exists"); files.set(path, source); },
async write(path, source, expected) { if (fail) throw Error("Write failed"); assert.equal(files.get(path), expected); files.set(path, source); },
};
const store = new TaskStore(workspace);
await store.reload();
await assert.rejects(store.openSubtask(parentId, "child"), /Write failed/);
fail = false;
const child = await store.openSubtask(parentId, "child");
assert.equal(child.title, "Child"); assert.equal(child.status, "done"); assert.equal(child.priority, undefined);
assert.equal(store.tasks.length, 2);
const saved = readTask("Parent.md", files.get("Parent.md")!)!;
assert.equal(saved.subtasks![0].taskId, child.id);
assert.equal(saved.body, "Keep the description"); assert.equal(saved.priority, "high");
assert.equal((await store.openSubtask(parentId, "child")).id, child.id);
assert.equal(store.tasks.length, 2);
});
@@ -0,0 +1,149 @@
import test from "node:test";
import assert from "node:assert/strict";
import { watchBackground, type BackgroundFrame, type PMBackgroundApi } from "../../../../src/lib/features/pm/model/transient-background.ts";
const frame = (url: string): BackgroundFrame => ({ url, overlay: 0, position: "center", size: "cover" });
function fixture() {
const frames = new Map<string, BackgroundFrame>();
const listeners = new Set<(target: string) => void>();
// The shape of `backgroundHub` in `src/lib/plugins/backgrounds.ts`.
const api: PMBackgroundApi = {
get: target => frames.get(target) ?? null,
subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
};
const set = (target: string, value: BackgroundFrame | null) => {
if (value) frames.set(target, value); else frames.delete(target);
for (const listener of listeners) listener(target);
};
return { api, set, listeners };
}
test("slides override saved images and removal restores them without writes", async () => {
const { api, set, listeners } = fixture();
const seen: (BackgroundFrame | null)[] = [];
let savedReads = 0;
const watcher = watchBackground("pm-board:one", api, async () => { savedReads++; return frame("saved"); }, value => seen.push(value));
await watcher.refresh();
set("pm-board:one", frame("slide"));
assert.equal(seen.at(-1)?.url, "slide");
assert.equal(savedReads, 1);
set("pm-board:one", null);
await Promise.resolve();
assert.equal(seen.at(-1)?.url, "saved");
watcher.dispose();
watcher.dispose();
assert.equal(listeners.size, 0);
});
test("pending saved reads cannot replace a new slide or change a closed mount", async () => {
const { api, set } = fixture();
let resolve!: (value: BackgroundFrame) => void;
const pending = new Promise<BackgroundFrame>(done => { resolve = done; });
const seen: (BackgroundFrame | null)[] = [];
const watcher = watchBackground("pm-all", api, () => pending, value => seen.push(value));
const refresh = watcher.refresh();
set("pm-all", frame("slide"));
resolve(frame("stale"));
await refresh;
assert.deepEqual(seen.map(value => value?.url), ["slide"]);
set("pm-all", null);
watcher.dispose();
await Promise.resolve();
await watcher.refresh();
assert.equal(seen.length, 1);
});
test("late failures cannot clear a slide", async () => {
const { api, set } = fixture();
let reject!: (error: Error) => void;
const pending = new Promise<BackgroundFrame>( (_resolve, fail) => { reject = fail; });
const seen: (BackgroundFrame | null)[] = [];
const watcher = watchBackground("pm-all", api, () => pending, value => seen.push(value));
const refresh = watcher.refresh();
set("pm-all", frame("slide"));
reject(new Error("Missing image"));
await refresh;
assert.deepEqual(seen.map(value => value?.url), ["slide"]);
watcher.dispose();
});
test("split mounts subscribe separately and filter board and all-task targets", async () => {
const { api, set, listeners } = fixture();
const seen = [[], [], []] as (BackgroundFrame | null)[][];
const mounts = ["pm-board:one", "pm-board:two", "pm-all"].map((target, index) =>
watchBackground(target, api, async () => null, value => seen[index].push(value)));
set("pm-board:one", frame("one"));
assert.deepEqual(seen.map(values => values.length), [1, 0, 0]);
mounts[0].dispose();
set("pm-board:two", frame("two"));
set("pm-all", frame("all"));
assert.deepEqual(seen.map(values => values.at(-1)?.url), ["one", "two", "all"]);
mounts[1].dispose(); mounts[2].dispose();
assert.equal(listeners.size, 0);
});
test("all-board slides override saved boards and specific slides retain priority", async () => {
const { api, set } = fixture();
const seen: (BackgroundFrame | null)[] = [];
const watcher = watchBackground("pm-board:one", api, async () => frame("saved"), value => seen.push(value));
await watcher.refresh();
set("pm-all", frame("all"));
assert.equal(seen.at(-1)?.url, "all");
set("pm-board:one", frame("specific"));
set("pm-all", frame("next-all"));
assert.equal(seen.at(-1)?.url, "specific");
set("pm-board:one", null);
assert.equal(seen.at(-1)?.url, "next-all");
set("pm-all", null);
await Promise.resolve();
assert.equal(seen.at(-1)?.url, "saved");
watcher.dispose();
});
test("older hosts use saved images and failures clear the background", async () => {
const seen: (BackgroundFrame | null)[] = [];
let fails = false;
const watcher = watchBackground("pm-all", undefined, async () => {
if (fails) throw new Error("Missing image");
return frame("saved");
}, value => seen.push(value));
await watcher.refresh(); fails = true; await watcher.refresh();
assert.deepEqual(seen.map(value => value?.url ?? null), ["saved", null]);
watcher.dispose();
});
test("shared app slides use one host layer and react to either target changing", async () => {
const { api, set } = fixture();
const seen: (BackgroundFrame | null)[] = [];
const watcher = watchBackground("pm-board:one", api, async () => frame("saved"), value => seen.push(value));
set("pm-all", frame("shared"));
assert.equal(seen.at(-1)?.url, "shared");
set("app", frame("shared"));
assert.equal(seen.at(-1), null);
set("app", frame("next"));
assert.equal(seen.at(-1)?.url, "shared");
set("pm-all", frame("next"));
assert.equal(seen.at(-1), null);
set("pm-board:one", frame("specific"));
assert.equal(seen.at(-1)?.url, "specific");
set("pm-board:one", null);
assert.equal(seen.at(-1), null);
set("app", null);
assert.equal(seen.at(-1)?.url, "next");
watcher.dispose();
});
test("different image appearance and transitions keep an independent PM layer", () => {
const { api, set } = fixture();
const seen: (BackgroundFrame | null)[] = [];
const watcher = watchBackground("pm-all", api, async () => null, value => seen.push(value));
set("app", frame("same"));
for (const difference of [{ blurredUrl: "blob:blur" }, { overlay: 0.4 }, { size: "contain" as const }, { position: "top left" as const },
{ previous: frame("old"), transitionMs: 500 }]) {
set("pm-all", { ...frame("same"), ...difference });
assert.equal(seen.at(-1)?.url, "same");
}
set("app", { ...frame("same"), previous: frame("old"), transitionMs: 500 });
assert.equal(seen.at(-1), null);
watcher.dispose();
});