Files
2026-11-16 04:21:21 -07:00

365 lines
12 KiB
TypeScript

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);
});