1 +import assert from "node:assert/strict";
2 +import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3 +import { tmpdir } from "node:os";
4 +import path from "node:path";
5 +import { test } from "node:test";
9 + assertEquivalentStorage,
24 +<tr><th>Prozess</th><th>Document Owner</th><th>Risk Owner</th><th>Asset Owner</th><th>Klassifizierung</th><th>Status</th><th>Geprüft von</th><th>Geprüft am</th><th>Freigegeben von</th><th>Freigegeben am</th></tr>
26 +<td><a href="/wiki/spaces/RD/pages/101/Alpha">Alpha & Beta</a></td>
27 +<td><a data-account-id="owner-1">Kathi Borrmann</a></td><td>Risk</td><td>Asset</td><td>Intern</td><td>Prüfung</td>
28 +<td><a data-account-id="oliver">Oliver Krylow</a></td><td>20.08.2026</td><td>Release</td><td>21.08.2026</td>
31 +<td data-content-id="102"><a href="/wiki/spaces/GA/pages/102/Draft">Draft</a></td>
32 +<td><a data-account-id="oliver">Oliver Krylow</a></td><td>Risk</td><td>Asset</td><td>Intern</td><td>Entwurf</td>
33 +<td></td><td></td><td></td><td></td>
36 +<td><a href="/wiki/spaces/isp/pages/103/Old">Old</a></td>
37 +<td><a data-account-id="oliver">Oliver Krylow</a></td><td>Risk</td><td>Asset</td><td>Intern</td><td>Freigegeben</td>
38 +<td><a data-account-id="oliver">Oliver Krylow</a></td><td>25.08.2025</td><td>Release</td><td>26.08.2025</td>
42 +test("parses IMS report rows and entities", () => {
43 + const rows = parseReportHtml(reportHtml);
44 + assert.equal(rows.length, 3);
45 + assert.deepEqual(rows[0], {
47 + title: "Alpha & Beta",
48 + href: "/wiki/spaces/RD/pages/101/Alpha",
50 + documentOwner: "Kathi Borrmann",
51 + documentOwnerIds: ["owner-1"],
54 + assetOwner: "Asset",
56 + classification: "Intern",
58 + reviewer: "Oliver Krylow",
59 + reviewerIds: ["oliver"],
60 + reviewedAt: "20.08.2026",
61 + releasedBy: "Release",
62 + releasedAt: "21.08.2026",
64 + assert.equal(rows[1].id, "102");
67 +test("builds distinct reviewer and owner worklists with RD first", () => {
68 + const rows = parseReportHtml(reportHtml);
69 + const reviewer = selectWorklist(rows, { mode: "reviewer", person: "ignored", accountId: "oliver", area: "all", today: "2026-08-27" });
70 + assert.deepEqual(reviewer.candidates.map((row) => [row.id, row.reasons]), [["101", ["awaiting-review"]]]);
72 + const owner = selectWorklist(rows, { mode: "owner", person: "ignored", accountId: "oliver", area: "all", today: "2026-08-27" });
73 + assert.deepEqual(owner.candidates.map((row) => row.id), ["103", "102"]);
74 + assert.deepEqual(owner.candidates[0].reasons, ["self-reviewer", "annual-review-due"]);
75 + assert.deepEqual(owner.candidates[1].reasons, ["draft", "missing-reviewer"]);
77 + const nearName = [{ ...rows[1], documentOwner: "Max Anna Meyer", documentOwnerIds: [] }];
78 + assert.equal(selectWorklist(nearName, { mode: "owner", person: "Anna Meyer", area: "all", today: "2026-08-27" }).roleMatchCount, 0);
81 +test("rejects impossible German calendar dates", () => {
82 + assert.equal(parseDate("31.02.2026"), undefined);
83 + assert.equal(parseDate("2026-02-29"), undefined);
84 + assert.equal(parseDate("29.02.2024")?.toISOString(), "2024-02-29T00:00:00.000Z");
85 + assert.equal(parseDate("2024-02-29")?.toISOString(), "2024-02-29T00:00:00.000Z");
88 +test("parses the policy baseline and detects version changes", async () => {
89 + const baseline = parseBaseline(`
90 +- Instruction page: \`540606500\`, version \`24\`, [Instructions](https://site.example/wiki/x/a)
91 +- Announcement: \`1437532339\`, version \`1\`, [Announcement](https://site.example/wiki/x/b)
92 +- Worklist report: \`899153943\`, [Report](https://site.example/wiki/x/c)
94 + assert.equal(baseline.baseUrl, "https://site.example");
96 + async get(requestPath) {
97 + return { version: { number: requestPath.includes("blogposts") ? 2 : 24 } };
100 + const result = await checkPolicy(client, baseline);
101 + assert.equal(result.changed, true);
102 + assert.deepEqual(result.sources.map((source) => source.changed), [false, true]);
105 +test("extracts row and matrix IMS headers", () => {
106 + const rows = `<table><tr><th>Status:</th><td>Prüfung</td></tr><tr><td>Geprüft von</td><td>Marcus Storre</td></tr></table>`;
107 + assert.deepEqual(parseHeaderHtml(rows), { Status: "Prüfung", "Geprüft von": "Marcus Storre" });
108 + const matrix = `<table><tr><th>Document Owner</th><th>Risk Owner</th></tr><tr><td>Oliver Krylow</td><td>Marcus Storre</td></tr></table>`;
109 + assert.deepEqual(parseHeaderHtml(matrix), { "Document Owner": "Oliver Krylow", "Risk Owner": "Marcus Storre" });
112 +test("check-plan is read-only and apply requires the separate mutation gate", () => {
113 + assert.equal(parseCli(["check-plan", "plan.json"]).allowMutation, false);
114 + assert.throws(() => parseCli(["apply", "plan.json", "--expected-version", "7", "--plan-sha256", "a".repeat(64)]), /--allow-mutation/);
115 + assert.throws(() => parseCli(["apply", "plan.json", "--expected-version", "7", "--allow-mutation"]), /--plan-sha256/);
118 +test("locks the exact validated plan bytes", (t) => {
119 + const dir = mkdtempSync(path.join(tmpdir(), "ims-plan-test-"));
120 + t.after(() => rmSync(dir, { recursive: true, force: true }));
121 + const file = path.join(dir, "plan.json");
122 + writeFileSync(file, JSON.stringify({
124 + expectedVersion: 7,
125 + operations: [{ kind: "page", versionComment: "geprüft", replacements: [{ from: "old", to: "new" }], expect: { contains: ["new"] } }],
127 + const first = readPlan(file);
128 + writeFileSync(file, `${first.source}\n`);
129 + const second = readPlan(file);
130 + assert.notEqual(first.sha256, second.sha256);
131 + assert.deepEqual(first.plan, second.plan);
134 +test("rejects plan and replacement shapes that could silently broaden a write", () => {
135 + assert.throws(() => validatePlan({ pageId: "x", expectedVersion: 1, operations: [] }), /pageId/);
136 + assert.throws(() => validatePlan({ pageId: "1", expectedVersion: 1, operations: [{ kind: "page", versionComment: "x", replacements: [] }] }), /lacks replacements/);
137 + assert.throws(() => validatePlan({ pageId: "1", expectedVersion: 1, operations: [{ kind: "page", versionComment: "x", replacements: [{ from: "a", to: "b" }], expect: { contains: "b" } }] }), /expect.contains/);
138 + assert.throws(() => validatePlan({ pageId: "1", expectedVersion: 1, operations: [{ kind: "page", versionComment: "x", replacements: [{ from: "a", to: "b" }] }] }), /at least one expectation/);
139 + assert.throws(() => validatePlan({ pageId: "1", expectedVersion: 1, operations: [
140 + { kind: "page", versionComment: "x", replacements: [{ from: "a", to: "b" }], expect: { contains: ["b"] } },
141 + { kind: "inline-comment", target: "b", text: "fix" },
142 + ] }), /must precede/);
143 + assert.throws(() => applyReplacements("one old", [{ from: "old", to: "new", count: 2 }]), /found 1/);
145 + () => applyReplacements('<ac:inline-comment-marker ac:ref="marker">old</ac:inline-comment-marker>', [{ from: '<ac:inline-comment-marker ac:ref="marker">old</ac:inline-comment-marker>', to: "new" }]),
146 + /inline-comment markers/,
150 +test("accepts server-only storage attributes but rejects semantic drift", () => {
151 + const expected = '<p><ac:link><ri:user ri:account-id="person" /></ac:link>Hello</p>';
152 + const normalized = '<p data-local-id="server"><ac:link ac:local-id="server"><ri:user ri:account-id="person" /></ac:link>Hello</p>';
153 + assert.doesNotThrow(() => assertEquivalentStorage(expected, normalized));
154 + assert.throws(() => assertEquivalentStorage(expected, normalized.replace("person", "other")), /differs/);
155 + assert.throws(() => assertEquivalentStorage("<p>Hello <strong>world</strong></p>", "<p>Hello<strong>world</strong></p>"), /differs/);
157 + const links = '<p><ac:link><ri:page ri:space-key="RD" ri:content-title="Rules" /></ac:link>One <ac:link><ri:page ri:space-key="GA" ri:content-title="Rules" /></ac:link>Two</p>';
158 + const swapped = links.replace('ri:space-key="RD"', 'ri:space-key="TEMP"').replace('ri:space-key="GA"', 'ri:space-key="RD"').replace('ri:space-key="TEMP"', 'ri:space-key="GA"');
159 + assert.throws(() => assertEquivalentStorage(links, swapped), /differs/);
162 +test("applies a version-gated page plan and emits an exact receipt", async () => {
167 + spaceId: "space-1",
168 + version: { number: 3, message: "before" },
169 + body: { storage: { value: '<table><tr><th>Status</th><td>Prüfung</td></tr></table><p><ac:inline-comment-marker ac:ref="keep">Old</ac:inline-comment-marker></p>' } },
170 + _links: { webui: "/wiki/spaces/RD/pages/123/Process" },
174 + async get(requestPath) {
175 + assert.match(requestPath, /pages\/123\?body-format=storage/);
176 + return structuredClone(page);
178 + async mutate(method, requestPath, body) {
180 + assert.equal(method, "PUT");
181 + assert.equal(requestPath, "wiki/api/v2/pages/123");
182 + assert.equal(body.spaceId, "space-1");
185 + version: structuredClone(body.version),
186 + body: { storage: { value: body.body.value.replace("<p>", '<p data-local-id="server">') } },
188 + return structuredClone(page);
191 + const plan = validatePlan({
193 + expectedVersion: 3,
196 + versionComment: "Rechtschreibkorrektur",
197 + replacements: [{ from: "Old", to: "New" }],
198 + expect: { contains: ["New"], notContains: ["Old"] },
201 + const receipt = await applyPlan(plan, client, "https://site.example");
202 + assert.equal(mutations, 1);
203 + assert.deepEqual(receipt, {
206 + operations: [{ kind: "page", version: 4, versionComment: "Rechtschreibkorrektur", validation: "passed" }],
207 + inlineComments: [],
208 + validation: "passed",
209 + url: "https://site.example/wiki/spaces/RD/pages/123/Process",
211 + versionComment: "Rechtschreibkorrektur",
212 + header: { Status: "Prüfung" },
216 +test("stops before mutation on version drift", async () => {
220 + return { id: "123", version: { number: 8 }, body: { storage: { value: "old" } } };
226 + const plan = validatePlan({ pageId: "123", expectedVersion: 7, operations: [{ kind: "page", versionComment: "x", replacements: [{ from: "old", to: "new" }], expect: { contains: ["new"] } }] });
227 + await assert.rejects(applyPlan(plan, client, "https://site.example"), /version drift/);
228 + assert.equal(mutations, 0);
231 +test("creates and verifies an inline comment and its page marker", async () => {
232 + let storage = "<p>Before exact target after</p>";
233 + const page = (representation) => ({
237 + version: { number: 5, message: "before" },
238 + body: representation === "storage"
239 + ? { storage: { value: storage } }
240 + : { atlas_doc_format: { value: JSON.stringify({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "Before exact " }, { type: "text", text: "target after" }] }] }) } },
241 + _links: { webui: "/wiki/pages/123" },
245 + async get(requestPath) {
246 + if (requestPath.includes("inline-comments/c1")) return structuredClone(comment);
247 + if (requestPath.includes("/inline-comments?")) return { results: [{ id: "c1" }] };
248 + if (requestPath.includes("atlas_doc_format")) return page("atlas_doc_format");
249 + return page("storage");
251 + async mutate(method, requestPath, body) {
252 + assert.equal(method, "POST");
253 + assert.equal(requestPath, "wiki/api/v2/inline-comments");
254 + assert.equal(body.inlineCommentProperties.textSelection, "exact target");
255 + storage = storage.replace("exact target", '<ac:inline-comment-marker ac:ref="marker-1">exact target</ac:inline-comment-marker>');
259 + resolutionStatus: "open",
260 + body: { storage: { value: "<p>Prüfung nötig</p>" } },
261 + properties: { inlineOriginalSelection: "exact target", inlineMarkerRef: "marker-1" },
263 + return { id: "c1" };
266 + const plan = validatePlan({
268 + expectedVersion: 5,
269 + operations: [{ kind: "inline-comment", target: "exact target", text: "Prüfung nötig" }],
271 + const receipt = await applyPlan(plan, client, "https://site.example");
272 + assert.equal(receipt.validation, "passed");
273 + assert.deepEqual(receipt.inlineComments, [{ id: "c1", target: "exact target", markerRef: "marker-1", validation: "passed" }]);
274 + assert.match(storage, /inline-comment-marker/);
277 +test("rejects a snapshot changed during supplementary reads", async () => {
278 + let storageReads = 0;
280 + async get(requestPath) {
281 + if (requestPath.endsWith("?body-format=storage")) {
283 + return { id: "123", title: "Process", version: { number: storageReads === 1 ? 9 : 10 }, body: { storage: { value: "<p>Storage</p>" } } };
285 + if (requestPath.endsWith("?body-format=view")) return { id: "123", version: { number: 9 }, body: { view: { value: "<p>View</p>" } } };
286 + return { results: [] };
289 + await assert.rejects(createSnapshot(client, "123", "https://site.example"), /changed during snapshot/);
292 +test("captures one version-consistent page snapshot", async () => {
294 + async get(requestPath) {
295 + if (requestPath.endsWith("?body-format=storage")) return {
298 + version: { number: 9, message: "x" },
299 + body: { storage: { value: "<p>Storage</p>" } },
300 + _links: { webui: "/wiki/pages/123" },
302 + if (requestPath.endsWith("?body-format=view")) return {
304 + version: { number: 9 },
305 + body: { view: { value: "<table><tr><th>Status</th><td>Entwurf</td></tr></table>" } },
307 + if (requestPath.includes("/labels")) return [{ results: [{ name: "ims-dokument" }] }];
308 + if (requestPath.includes("/inline-comments")) return { results: [{ id: "i1" }] };
309 + if (requestPath.includes("/footer-comments")) return { results: [{ id: "f1" }] };
310 + if (requestPath.includes("/attachments")) return { results: [{ id: "a1" }] };
311 + throw new Error(`Unexpected path: ${requestPath}`);
314 + const snapshot = await createSnapshot(client, "123", "https://site.example");
315 + assert.equal(snapshot.url, "https://site.example/wiki/pages/123");
316 + assert.deepEqual(snapshot.header, { Status: "Entwurf" });
317 + assert.deepEqual(snapshot.labels, [{ name: "ims-dokument" }]);
318 + assert.equal(snapshot.body.storage, "<p>Storage</p>");
319 + assert.match(snapshot.body.storageSha256, /^[0-9a-f]{64}$/);