repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

feat(ims): add deterministic process maintenance tooling

21595ac7c0e742a134315b02f4f7bbd06f5887cf

Oliver Krylow <o.krylow@isp-insoft.de> ·

unsigned

Browse filesCompare with HEAD

Changed files (6)

pi/agent/skills/ims-process-review/SKILL.md

Modified
2 2 name: ims-process-review
3 -description: "Use for Confluence IMS/ISO process reviews. Triggers: IMS, ISO-Prozess, ims-dokument, Prozessprüfung, Prozessreport, Prüfung, Freigabe."
3 +description: "Use for Confluence IMS/ISO process reviews and Document Owner maintenance. Triggers: IMS, ISO-Prozess, ims-dokument, Prozessprüfung, Prozessreport, Prüfung, Freigabe."
6 6 # IMS Process Review
8 -Review IMS processes according to the current official workflow.
8 +Maintain and review IMS processes according to the current official workflow.
9 9 Oliver decides operational truth; never demand evidence.
11 11 ## Boundaries
13 -- Load the available Atlassian skill before any Confluence operation and delegate all access details to it.
14 -- Do not prescribe a transport or command here.
15 -- Do not use browser automation.
13 +- Use `scripts/ims.mjs` for deterministic policy checks, worklists,
14 + snapshots, approved writes, and validation.
15 +- Never use browser automation.
16 16 - Process one page at a time after collecting the complete worklist.
17 -- Require explicit confirmation for each process before any mutation.
18 -- A referenced document remains read-only context. Changing it requires a separate plan and confirmation; IMS documents independently follow this workflow.
17 +- Referenced documents remain read-only context.
18 + Changing one requires its own plan and confirmation;
19 + IMS documents independently follow this workflow.
20 +- A yearly review is the maximum interval,
21 + not a prohibition on an earlier review.
22 +- A Document Owner cannot formally review their own document.
23 +- `Geprüft von` names the person who actually performs the current review.
24 + Never rewrite historical review attribution to make it appear valid.
26 +## Choose the mode
28 +Choose explicitly before analysis:
30 +- **Reviewer:** Oliver is `Geprüft von` and the page is in `Prüfung`.
31 +- **Owner:** Oliver is `Document Owner` and must prepare, correct,
32 + or initiate a review cycle.
33 +- **Direct page:** classify Oliver's role from the current IMS header,
34 + then follow the matching mode.
20 36 ## Start every run
38 +From this skill directory:
22 40 1. Read [the policy baseline](references/policy-baseline.md).
23 -2. Reload both policy sources and compare their current versions with the baseline.
24 -3. If either version changed, show a compact policy diff, stop, ask Oliver for interpretation, and propose the exact baseline or skill update. Even a change with no relevant policy delta requires confirmation before continuing.
25 -4. Build the complete worklist from current pages labeled `ims-dokument` where `Geprüft von` is Oliver and `Status` is `Prüfung`.
26 -5. Search all official report areas: `isp`, `GA`, `RD`, `CS`, and `SM`. Treat the `R&D` page hierarchy as report area `RD`. Sort `RD` first, but omit no area.
27 -6. List malformed or incomplete IMS headers separately only within Oliver's candidate set; do not audit all IMS headers.
41 +2. Run `node scripts/ims.mjs policy`.
42 +3. If either policy version changed, show a compact version diff and stop.
43 + Ask Oliver for interpretation and propose the exact baseline or skill
44 + update.
45 + Even a change without an apparent policy delta requires confirmation.
46 +4. Run `node scripts/ims.mjs worklist --mode reviewer` or
47 + `node scripts/ims.mjs worklist --mode owner`.
48 +5. Use the complete report result across `isp`, `GA`, `RD`, `CS`, and `SM`.
49 + Treat `R&D` as `RD`; sort `RD` first and omit no area.
50 +6. List malformed or incomplete IMS headers separately,
51 + only within Oliver's candidate set.
29 -## Review one process
53 +Owner candidates include drafts, missing or self-assigned reviewers,
54 +malformed headers, and documents at the annual limit.
55 +An earlier direct review remains valid even when it is absent from the
56 +automatic owner worklist.
31 -Capture the current page version before analysis, then check:
58 +## Capture one process
60 +Run `node scripts/ims.mjs snapshot PAGE_ID` before analysis.
61 +Use that single-version snapshot to check:
33 63 - required IMS header structure and values;
34 64 - internal contradictions;
35 -- contradictions with all other current `ims-dokument` pages, checking directly referenced pages first;
65 +- contradictions with other current `ims-dokument` pages,
66 + checking directly referenced pages first;
36 67 - accessible links and references;
37 68 - spelling, grammar, formal ISP wording, and formatting;
38 69 - existing open inline comments as non-blocking context.
40 -Mark inaccessible links `unverifiziert`, never `defekt`, and do not reject solely because access is unavailable.
41 -Treat non-IMS targets only as links to verify. Do not inspect Jira issues, databases, files, or external sources for semantic evidence unless Oliver explicitly asks.
42 -Do not infer operational truth beyond Oliver's statements and current IMS documents.
71 +Mark inaccessible links `unverifiziert`, never `defekt`.
72 +Do not reject solely because access is unavailable.
73 +Treat non-IMS targets only as links to verify.
74 +Do not inspect Jira issues, databases, files, or external sources for
75 +semantic evidence unless Oliver explicitly asks.
76 +Do not infer operational truth beyond Oliver's statements and current IMS
77 +documents.
79 +## Owner mode
81 +Present each semantic or operational concern as one concrete question.
82 +Discuss one question at a time and accumulate Oliver's decisions.
83 +Do not turn an unconfirmed hypothesis into a finding.
85 +Classify changes:
87 +- Meaning-neutral wording, spelling, grammar, and formatting may remain in
88 + the current status.
89 +- Semantic, logical, or process changes require `Entwurf`.
90 +- A malformed IMS header requires an exact repair in `Entwurf`;
91 + reload and restart after validation.
92 +- Review and release dates describe an attested version.
93 + Clear obsolete dates when beginning a renewed cycle;
94 + do not preserve them as current evidence after semantic change.
96 +When the document is ready:
98 +- set `Geprüft von` to the actual future reviewer,
99 + who must differ from the Document Owner;
100 +- set `Status` to `Prüfung`;
101 +- after `Entwurf`, use version comment `zur Prüfung freigegeben`;
102 +- for an unchanged annual renewal moved directly to `Prüfung`,
103 + clear `Geprüft am` and `Freigegeben am`,
104 + then use `Prozess geprüft und auf Prüfung gesetzt`.
106 +## Reviewer mode
44 108 Classify findings:
46 -- Meaning-neutral wording, spelling, grammar, and formatting may be corrected while the page remains in `Prüfung`.
47 -- Never propose inline comments for meaning-neutral findings; include them in the direct correction diff.
48 -- Any semantic or logical change to an IMS document, including a referenced page, requires that document to enter `Entwurf` under a separately confirmed plan.
49 -- Never reconstruct a malformed IMS header automatically. Propose an exact repair as a separate `Entwurf` version; after confirmation and validation, reload and restart the review.
110 +- Meaning-neutral wording, spelling, grammar, and formatting may be corrected
111 + while the page remains in `Prüfung`.
112 +- Never create inline comments for meaning-neutral findings;
113 + include them in the direct correction diff.
114 +- Any semantic or logical change requires `Entwurf`.
115 +- The reviewer creates inline comments for approved semantic findings.
116 +- Existing open comments are context and do not block a new review.
51 -## Proposal
118 +If accepted:
53 -Before writing, show:
120 +1. Save meaning-neutral corrections as a separate version with comment
121 + `Rechtschreibkorrektur`, then validate it.
122 +2. Set `Geprüft am` to today's local date.
123 +3. Set `Status` to `Freigabe` with version comment `geprüft`.
124 +4. Keep all owner assignments unchanged.
55 -1. page title, URL, area, and captured version;
56 -2. existing open inline comments for context;
57 -3. every finding and its classification;
58 -4. one short readable rendered-text diff covering every planned body change;
59 -5. each proposed inline comment with its exact quoted target and intended text;
60 -6. every planned metadata transition and version comment;
61 -7. the resulting verdict: `Freigabe` or `Entwurf`.
126 +If rejected:
63 -One explicit OK for that process authorizes only the complete displayed plan, including all displayed corrections, comments, metadata changes, and ordered writes.
128 +1. Create and validate every approved inline comment.
129 +2. Only after all comments and page markers are visible,
130 + set `Status` to `Entwurf` with version comment
131 + `zurück in Entwurf, da Korrektur notwendig`.
132 +3. If any comment fails, leave status unchanged and report exactly which
133 + comments exist or are missing.
65 -## Apply an accepted process
135 +The Document Owner processes and closes comments,
136 +then returns the page to `Prüfung`.
67 -If only meaning-neutral corrections are planned:
138 +## Freeze the plan
69 -1. Save them as a separate version with version comment `Rechtschreibkorrektur`.
70 -2. Validate that version before continuing.
140 +Before any write, show:
72 -Then reload the page and set:
142 +1. title, direct URL, area, role, and captured version;
143 +2. existing open inline comments;
144 +3. each finding, its classification, and Oliver's decisions;
145 +4. one readable rendered-text diff covering every planned body change;
146 +5. each inline comment with exact quoted target and text;
147 +6. every metadata transition and version comment;
148 +7. ordered writes and resulting status.
74 -- `Geprüft am` to today's local date;
75 -- `Status` to `Freigabe`;
76 -- version comment to `geprüft`.
150 +Create one plan JSON for exactly one page.
151 +Use the schema from `node scripts/ims.mjs --help`.
78 -Keep all owner assignments unchanged.
153 +- `ok` accepts and freezes the displayed plan;
154 + it never authorizes a write.
155 +- After `ok`, run `node scripts/ims.mjs check-plan PLAN.json`
156 + and report its hash.
157 +- Only a later explicit `go` authorizes `apply` for that exact page,
158 + version, plan file, and hash.
159 +- Any plan change invalidates the hash and requires a new display and `ok`.
80 -## Apply a rejected process
161 +## Apply and validate
82 -1. Create all approved inline comments and verify each one.
83 -2. If any comment fails, leave page status unchanged, report exactly which comments exist or are missing, and wait before retrying.
84 -3. Only after every planned comment is verified, set `Status` to `Entwurf` with version comment `zurück in Entwurf, da Korrektur notwendig`.
163 +After `go`, run:
86 -The Document Owner processes and closes comments, then returns the page to `Prüfung`.
87 -Existing open comments do not block a new review.
165 +```text
166 +node scripts/ims.mjs apply PLAN.json \
167 + --expected-version VERSION \
168 + --plan-sha256 HASH \
169 + --allow-mutation
170 +```
89 -## Mutation safety
91 -Immediately before every write, verify that the source version still matches the version just analyzed or reloaded.
92 -If it changed, stop and regenerate the analysis and proposal.
94 -After every write, require:
96 -- version increment exactly `+1`;
97 -- exact planned version comment;
98 -- exact planned rendered content, structure, and metadata changes, ignoring server-only storage normalization;
99 -- unchanged unplanned content and owner assignments;
100 -- visible attachment of every planned inline comment to its exact target in the final rendered page.
102 -On validation failure, stop and report the observed state.
103 -Never roll back automatically; propose a separately confirmed correction version.
172 +The helper must stop on version drift, ambiguous replacements,
173 +missing comment targets, marker loss, unexpected version comments,
174 +or semantic storage differences.
175 +Never roll back automatically.
176 +A failed post-write validation requires an observed-state report
177 +and a separately confirmed correction plan.
105 179 ## Receipt
107 -After every document mutation, include its direct human-clickable URL in the next response.
108 -For each completed process, report page link, resulting version, status, `Geprüft am`, version comment, inline-comment result, and validation result.
181 +After every mutation, include the direct page URL in the next response.
182 +For each completed page, report resulting version, status, `Geprüft am`,
183 +version comment, inline-comment result, plan hash, and validation result.

pi/agent/skills/ims-process-review/package.json

Added
new file mode 100644
1 +{
2 + "name": "ims-process-review-skill",
3 + "version": "0.1.0",
4 + "private": true,
5 + "type": "module",
6 + "scripts": {
7 + "test": "node --test scripts/*.test.mjs"
8 + }
9 +}

pi/agent/skills/ims-process-review/scripts/atlassian-request.mjs

Added
new file mode 100644
1 +#!/usr/bin/env node
2 +import { spawnSync } from "node:child_process";
3 +import { realpathSync } from "node:fs";
4 +import { readFile } from "node:fs/promises";
5 +import { fileURLToPath } from "node:url";
7 +const METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
8 +const MUTATIONS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
10 +export function parseArgs(argv) {
11 + const args = [...argv];
12 + let method = "GET";
13 + if (METHODS.has(args[0]?.toUpperCase())) method = args.shift().toUpperCase();
15 + const options = {
16 + method,
17 + path: undefined,
18 + bodyFile: undefined,
19 + profile: undefined,
20 + paginate: false,
21 + maxPages: 100,
22 + allowMutation: false,
23 + };
25 + while (args.length) {
26 + const arg = args.shift();
27 + switch (arg) {
28 + case "--body":
29 + options.bodyFile = requiredValue(arg, args.shift());
30 + break;
31 + case "--profile":
32 + options.profile = requiredValue(arg, args.shift());
33 + break;
34 + case "--paginate":
35 + options.paginate = true;
36 + break;
37 + case "--max-pages": {
38 + const value = Number(requiredValue(arg, args.shift()));
39 + if (!Number.isSafeInteger(value) || value < 1) throw new Error("--max-pages must be a positive integer");
40 + options.maxPages = value;
41 + break;
42 + }
43 + case "--allow-mutation":
44 + options.allowMutation = true;
45 + break;
46 + case "--help":
47 + options.help = true;
48 + break;
49 + default:
50 + if (arg.startsWith("--")) throw new Error(`Unknown option: ${arg}`);
51 + if (options.path) throw new Error(`Unexpected argument: ${arg}`);
52 + options.path = arg;
53 + }
54 + }
56 + if (options.help) return options;
57 + if (!options.path) throw new Error("Request path is required");
58 + if (MUTATIONS.has(method) && !options.allowMutation) throw new Error(`${method} requires --allow-mutation`);
59 + if (options.bodyFile && method === "GET") throw new Error("GET does not accept --body");
60 + if (options.paginate && method !== "GET") throw new Error("--paginate requires GET");
61 + return options;
64 +function requiredValue(option, value) {
65 + if (!value || value.startsWith("--")) throw new Error(`${option} requires a value`);
66 + return value;
69 +export function selectConnection(profiles, profileName, env = process.env) {
70 + const selected = profileName
71 + ? profiles.find((profile) => profile.name === profileName)
72 + : profiles.find((profile) => profile.is_default) ?? profiles[0];
73 + if (profileName && !selected && (!env.ATLASSIAN_BASE_URL || !env.ATLASSIAN_EMAIL)) {
74 + throw new Error(`Unknown Atlassian profile: ${profileName}`);
75 + }
76 + const baseUrl = env.ATLASSIAN_BASE_URL ?? selected?.base_url;
77 + const email = env.ATLASSIAN_EMAIL ?? selected?.email;
78 + if (!baseUrl || !email) throw new Error("Atlassian base URL and email are unavailable");
79 + return { baseUrl, email };
82 +export function resolveRequestUrl(path, baseUrl) {
83 + const base = new URL(baseUrl);
84 + if (base.protocol !== "https:" && !["localhost", "127.0.0.1", "::1"].includes(base.hostname)) {
85 + throw new Error(`Refusing non-HTTPS Atlassian base URL: ${base.origin}`);
86 + }
87 + const url = new URL(path, base);
88 + if (url.origin !== base.origin) throw new Error(`Refusing to send Atlassian credentials to ${url.origin}`);
89 + return url;
92 +export function nextPageUrl(body, currentUrl) {
93 + const linked = body?._links?.next ?? body?.links?.next ?? body?.nextPage ?? (typeof body?.next === "string" ? body.next : undefined);
94 + if (linked) return new URL(linked, currentUrl);
96 + if (Number.isFinite(body?.startAt) && Number.isFinite(body?.maxResults) && Number.isFinite(body?.total)) {
97 + const startAt = body.startAt + body.maxResults;
98 + if (startAt < body.total) {
99 + const next = new URL(currentUrl);
100 + next.searchParams.set("startAt", String(startAt));
101 + return next;
105 + if (body?.nextPageToken && body?.isLast !== true) {
106 + const next = new URL(currentUrl);
107 + next.searchParams.set("nextPageToken", body.nextPageToken);
108 + return next;
110 + return undefined;
113 +export async function requestJson(url, init, fetchImpl = fetch) {
114 + const response = await fetchImpl(url, { ...init, redirect: "manual" });
115 + const text = await response.text();
116 + if (response.status >= 300 && response.status < 400) {
117 + throw new Error(`${init.method} ${url}: redirect ${response.status} refused`);
119 + if (!response.ok) throw new Error(`${init.method} ${url}: HTTP ${response.status}${text ? `\n${text}` : ""}`);
120 + if (!text) return null;
121 + try {
122 + return JSON.parse(text);
123 + } catch {
124 + return text;
128 +export async function runRequest(options, connection, token, fetchImpl = fetch) {
129 + if (!token) throw new Error("ATLASSIAN_API_TOKEN or JIRA_API_TOKEN is required");
130 + const firstUrl = resolveRequestUrl(options.path, connection.baseUrl);
131 + const headers = {
132 + Accept: "application/json",
133 + Authorization: `Basic ${Buffer.from(`${connection.email}:${token}`).toString("base64")}`,
134 + };
135 + let body;
136 + if (options.bodyFile) {
137 + const input = await readFile(options.bodyFile, "utf8");
138 + body = JSON.stringify(JSON.parse(input));
139 + headers["Content-Type"] = "application/json";
141 + const init = { method: options.method, headers, body };
142 + if (!options.paginate) return requestJson(firstUrl, init, fetchImpl);
144 + const pages = [];
145 + let url = firstUrl;
146 + for (let page = 1; ; page++) {
147 + pages.push(await requestJson(url, init, fetchImpl));
148 + const next = nextPageUrl(pages.at(-1), url);
149 + if (!next) return pages;
150 + if (page >= options.maxPages) throw new Error(`Pagination exceeded --max-pages ${options.maxPages}`);
151 + url = resolveRequestUrl(next.href, connection.baseUrl);
155 +function loadProfiles() {
156 + const result = spawnSync("atlassian-cli", ["auth", "list", "--format", "json"], {
157 + encoding: "utf8",
158 + windowsHide: true,
159 + });
160 + if (result.status !== 0) throw new Error(result.stderr.trim() || "atlassian-cli auth list failed");
161 + return JSON.parse(result.stdout);
164 +function usage() {
165 + return `Usage: node atlassian-request.mjs [METHOD] PATH [options]
167 +METHOD defaults to GET. PATH must resolve to the configured Atlassian origin.
168 +On Windows Bash, use relative paths without a leading slash.
170 +Options:
171 + --body FILE JSON request body
172 + --profile NAME atlassian-cli profile
173 + --paginate fetch all GET pages and output an array of responses
174 + --max-pages NUMBER pagination limit, default 100
175 + --allow-mutation required for POST, PUT, PATCH, and DELETE
176 + --help show this help`;
179 +async function main() {
180 + const options = parseArgs(process.argv.slice(2));
181 + if (options.help) {
182 + console.log(usage());
183 + return;
185 + const profiles = process.env.ATLASSIAN_BASE_URL && process.env.ATLASSIAN_EMAIL ? [] : loadProfiles();
186 + const connection = selectConnection(profiles, options.profile);
187 + const token = process.env.ATLASSIAN_API_TOKEN ?? process.env.JIRA_API_TOKEN;
188 + const result = await runRequest(options, connection, token);
189 + console.log(typeof result === "string" ? result : JSON.stringify(result, null, 2));
192 +if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
193 + main().catch((error) => {
194 + console.error(error.message);
195 + process.exit(1);
196 + });

pi/agent/skills/ims-process-review/scripts/atlassian-request.test.mjs

Added
new file mode 100644
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";
6 +import {
7 + nextPageUrl,
8 + parseArgs,
9 + requestJson,
10 + resolveRequestUrl,
11 + runRequest,
12 + selectConnection,
13 +} from "./atlassian-request.mjs";
15 +function response(body, status = 200, headers = { "content-type": "application/json" }) {
16 + return new Response(typeof body === "string" ? body : JSON.stringify(body), { status, headers });
19 +test("parses GET defaults and pagination options", () => {
20 + assert.deepEqual(parseArgs(["/wiki/api/v2/pages", "--paginate", "--max-pages", "4", "--profile", "work"]), {
21 + method: "GET",
22 + path: "/wiki/api/v2/pages",
23 + bodyFile: undefined,
24 + profile: "work",
25 + paginate: true,
26 + maxPages: 4,
27 + allowMutation: false,
28 + });
29 +});
31 +test("requires explicit mutation permission", () => {
32 + assert.throws(() => parseArgs(["POST", "/wiki/api/v2/pages"]), /requires --allow-mutation/);
33 + assert.equal(parseArgs(["POST", "/wiki/api/v2/pages", "--allow-mutation"]).method, "POST");
34 + assert.throws(() => parseArgs(["GET", "/x", "--body", "body.json"]), /GET does not accept --body/);
35 + assert.throws(() => parseArgs(["PATCH", "/x", "--allow-mutation", "--paginate"]), /--paginate requires GET/);
36 +});
38 +test("selects profiles with environment overrides", () => {
39 + const profiles = [
40 + { name: "one", base_url: "https://one.example/", email: "one@example.com" },
41 + { name: "two", base_url: "https://two.example/", email: "two@example.com", is_default: true },
42 + ];
43 + assert.deepEqual(selectConnection(profiles), { baseUrl: "https://two.example/", email: "two@example.com" });
44 + assert.deepEqual(selectConnection(profiles, "one"), { baseUrl: "https://one.example/", email: "one@example.com" });
45 + assert.deepEqual(selectConnection([], undefined, {
46 + ATLASSIAN_BASE_URL: "https://env.example/",
47 + ATLASSIAN_EMAIL: "env@example.com",
48 + }), { baseUrl: "https://env.example/", email: "env@example.com" });
49 + assert.throws(() => selectConnection(profiles, "missing"), /Unknown Atlassian profile/);
50 +});
52 +test("keeps credentials on the configured HTTPS origin", () => {
53 + assert.equal(resolveRequestUrl("/wiki/api/v2/pages", "https://site.example/").href, "https://site.example/wiki/api/v2/pages");
54 + assert.throws(() => resolveRequestUrl("https://evil.example/x", "https://site.example/"), /Refusing to send/);
55 + assert.throws(() => resolveRequestUrl("/x", "http://site.example/"), /Refusing non-HTTPS/);
56 + assert.equal(resolveRequestUrl("/x", "http://127.0.0.1:1234/").href, "http://127.0.0.1:1234/x");
57 +});
59 +test("sends authenticated GET and parses JSON", async () => {
60 + let observed;
61 + const result = await runRequest(
62 + parseArgs(["/wiki/api/v2/pages/1"]),
63 + { baseUrl: "https://site.example/", email: "person@example.com" },
64 + "secret",
65 + async (url, init) => {
66 + observed = { url: url.href, init };
67 + return response({ id: "1" });
68 + },
69 + );
70 + assert.deepEqual(result, { id: "1" });
71 + assert.equal(observed.url, "https://site.example/wiki/api/v2/pages/1");
72 + assert.equal(observed.init.method, "GET");
73 + assert.equal(observed.init.headers.Authorization, `Basic ${Buffer.from("person@example.com:secret").toString("base64")}`);
74 + assert.equal(observed.init.redirect, "manual");
75 +});
77 +test("sends JSON body files for explicitly allowed mutations", async (t) => {
78 + const dir = mkdtempSync(path.join(tmpdir(), "atlassian-request-"));
79 + t.after(() => rmSync(dir, { recursive: true, force: true }));
80 + const bodyFile = path.join(dir, "body.json");
81 + writeFileSync(bodyFile, '{"value": 1}\n');
82 + let observed;
83 + const options = parseArgs(["POST", "/wiki/api/v2/pages", "--body", bodyFile, "--allow-mutation"]);
84 + const result = await runRequest(options, { baseUrl: "https://site.example/", email: "person@example.com" }, "secret", async (_url, init) => {
85 + observed = init;
86 + return response({ created: true }, 201);
87 + });
88 + assert.deepEqual(result, { created: true });
89 + assert.equal(observed.body, '{"value":1}');
90 + assert.equal(observed.headers["Content-Type"], "application/json");
91 +});
93 +test("follows linked pagination and returns complete response pages", async () => {
94 + const seen = [];
95 + const result = await runRequest(
96 + parseArgs(["/wiki/api/v2/pages?limit=1", "--paginate"]),
97 + { baseUrl: "https://site.example/", email: "person@example.com" },
98 + "secret",
99 + async (url) => {
100 + seen.push(url.href);
101 + return seen.length === 1
102 + ? response({ results: [{ id: "1" }], _links: { next: "/wiki/api/v2/pages?limit=1&cursor=next" } })
103 + : response({ results: [{ id: "2" }], _links: {} });
104 + },
105 + );
106 + assert.equal(result.length, 2);
107 + assert.deepEqual(result.flatMap((page) => page.results), [{ id: "1" }, { id: "2" }]);
108 + assert.equal(seen[1], "https://site.example/wiki/api/v2/pages?limit=1&cursor=next");
109 +});
111 +test("recognizes numeric and token pagination", () => {
112 + assert.equal(nextPageUrl({ startAt: 0, maxResults: 50, total: 51 }, new URL("https://site.example/rest?startAt=0")).href, "https://site.example/rest?startAt=50");
113 + assert.equal(nextPageUrl({ nextPageToken: "abc", isLast: false }, new URL("https://site.example/rest")).href, "https://site.example/rest?nextPageToken=abc");
114 + assert.equal(nextPageUrl({ startAt: 50, maxResults: 50, total: 51 }, new URL("https://site.example/rest")), undefined);
115 +});
117 +test("fails instead of returning partial pagination", async () => {
118 + const options = parseArgs(["/wiki/api/v2/pages", "--paginate", "--max-pages", "1"]);
119 + await assert.rejects(
120 + runRequest(options, { baseUrl: "https://site.example/", email: "person@example.com" }, "secret", async () => response({ _links: { next: "/next" } })),
121 + /Pagination exceeded/,
122 + );
123 +});
125 +test("reports HTTP failures, rejects redirects, and preserves text responses", async () => {
126 + await assert.rejects(requestJson(new URL("https://site.example/x"), { method: "GET" }, async () => response("denied", 403, { "content-type": "text/plain" })), /HTTP 403\ndenied/);
127 + await assert.rejects(requestJson(new URL("https://site.example/x"), { method: "GET" }, async () => response("", 302)), /redirect 302 refused/);
128 + assert.equal(await requestJson(new URL("https://site.example/x"), { method: "GET" }, async () => response("plain", 200, { "content-type": "text/plain" })), "plain");
129 +});

pi/agent/skills/ims-process-review/scripts/ims.mjs

Added
new file mode 100644
1 +#!/usr/bin/env node
2 +import { spawnSync } from "node:child_process";
3 +import { createHash } from "node:crypto";
4 +import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
5 +import { tmpdir } from "node:os";
6 +import path from "node:path";
7 +import { fileURLToPath } from "node:url";
9 +const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
10 +const SKILL_DIR = path.dirname(SCRIPT_DIR);
11 +const BASELINE_FILE = path.join(SKILL_DIR, "references", "policy-baseline.md");
12 +const REQUEST_HELPER = path.join(SCRIPT_DIR, "atlassian-request.mjs");
13 +const OFFICIAL_AREAS = ["RD", "isp", "GA", "CS", "SM"];
14 +const DEFAULT_PERSON = "Oliver Krylow";
15 +const DEFAULT_ACCOUNT_ID = "619fbba4744c4d0069c8a49c";
16 +const HEADER_FIELDS = new Map([
17 + ["document owner", "Document Owner"],
18 + ["risk owner", "Risk Owner"],
19 + ["asset owner", "Asset Owner"],
20 + ["klassifizierung", "Klassifizierung"],
21 + ["status", "Status"],
22 + ["geprüft von", "Geprüft von"],
23 + ["geprüft am", "Geprüft am"],
24 + ["freigegeben von", "Freigegeben von"],
25 + ["freigegeben am", "Freigegeben am"],
26 +]);
28 +export function parseCli(argv) {
29 + const args = [...argv];
30 + const command = args.shift();
31 + const options = {
32 + command,
33 + positionals: [],
34 + profile: undefined,
35 + mode: undefined,
36 + person: "Oliver Krylow",
37 + accountId: undefined,
38 + area: "all",
39 + today: undefined,
40 + expectedVersion: undefined,
41 + planSha256: undefined,
42 + allowMutation: false,
43 + help: command === "--help" || command === "-h",
44 + };
46 + while (args.length) {
47 + const arg = args.shift();
48 + switch (arg) {
49 + case "--profile":
50 + options.profile = requiredValue(arg, args.shift());
51 + break;
52 + case "--mode":
53 + options.mode = requiredValue(arg, args.shift());
54 + break;
55 + case "--person":
56 + options.person = requiredValue(arg, args.shift());
57 + break;
58 + case "--account-id":
59 + options.accountId = requiredValue(arg, args.shift());
60 + break;
61 + case "--area":
62 + options.area = normalizeArea(requiredValue(arg, args.shift()));
63 + break;
64 + case "--today":
65 + options.today = requiredValue(arg, args.shift());
66 + break;
67 + case "--expected-version": {
68 + const value = Number(requiredValue(arg, args.shift()));
69 + if (!Number.isSafeInteger(value) || value < 1) throw new Error("--expected-version must be a positive integer");
70 + options.expectedVersion = value;
71 + break;
72 + }
73 + case "--plan-sha256":
74 + options.planSha256 = requiredValue(arg, args.shift()).toLowerCase();
75 + break;
76 + case "--allow-mutation":
77 + options.allowMutation = true;
78 + break;
79 + case "--help":
80 + case "-h":
81 + options.help = true;
82 + break;
83 + default:
84 + if (arg.startsWith("--")) throw new Error(`Unknown option: ${arg}`);
85 + options.positionals.push(arg);
86 + }
87 + }
89 + if (options.help) return options;
90 + if (!command) throw new Error("Command is required");
91 + if (!new Set(["policy", "worklist", "snapshot", "check-plan", "apply"]).has(command)) {
92 + throw new Error(`Unknown command: ${command}`);
93 + }
94 + if (command === "worklist" && !new Set(["owner", "reviewer"]).has(options.mode)) {
95 + throw new Error("worklist requires --mode owner|reviewer");
96 + }
97 + if (command === "snapshot" && options.positionals.length !== 1) throw new Error("snapshot requires PAGE_ID");
98 + if (new Set(["check-plan", "apply"]).has(command) && options.positionals.length !== 1) {
99 + throw new Error(`${command} requires PLAN.json`);
101 + if (command === "apply") {
102 + if (!options.allowMutation) throw new Error("apply requires --allow-mutation");
103 + if (!options.expectedVersion) throw new Error("apply requires --expected-version");
104 + if (!/^[0-9a-f]{64}$/.test(options.planSha256 ?? "")) throw new Error("apply requires --plan-sha256");
105 + } else if (options.allowMutation) {
106 + throw new Error("--allow-mutation is valid only with apply");
108 + return options;
111 +function requiredValue(option, value) {
112 + if (!value || value.startsWith("--")) throw new Error(`${option} requires a value`);
113 + return value;
116 +export function normalizeArea(value) {
117 + if (value.toLowerCase() === "all") return "all";
118 + if (value.toLowerCase() === "isp") return "isp";
119 + if (value.toUpperCase() === "R&D") return "RD";
120 + const upper = value.toUpperCase();
121 + if (!OFFICIAL_AREAS.includes(upper)) throw new Error(`Unknown IMS area: ${value}`);
122 + return upper;
125 +export function parseBaseline(markdown) {
126 + const source = (label, kind) => {
127 + const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
128 + const match = markdown.match(new RegExp(`- ${escaped}: ` + "`(\\d+)`(?:, version `(\\d+)`)?[^\\n]*\\((https://[^)]+)\\)"));
129 + if (!match) throw new Error(`Policy baseline lacks ${label}`);
130 + return { kind, id: match[1], version: match[2] ? Number(match[2]) : undefined, url: match[3] };
131 + };
132 + const instruction = source("Instruction page", "page");
133 + const announcement = source("Announcement", "blogpost");
134 + const report = source("Worklist report", "page");
135 + return {
136 + instruction,
137 + announcement,
138 + report,
139 + baseUrl: new URL(instruction.url).origin,
140 + };
143 +export async function checkPolicy(client, baseline) {
144 + const checked = [];
145 + for (const [name, source] of [["instruction", baseline.instruction], ["announcement", baseline.announcement]]) {
146 + const current = await client.get(`wiki/api/v2/${source.kind === "blogpost" ? "blogposts" : "pages"}/${source.id}`);
147 + checked.push({
148 + name,
149 + id: source.id,
150 + url: source.url,
151 + baselineVersion: source.version,
152 + currentVersion: current.version?.number,
153 + changed: current.version?.number !== source.version,
154 + });
156 + return { changed: checked.some((source) => source.changed), sources: checked };
159 +const ENTITY_MAP = new Map([
160 + ["amp", "&"],
161 + ["lt", "<"],
162 + ["gt", ">"],
163 + ["quot", '"'],
164 + ["apos", "'"],
165 + ["nbsp", " "],
166 + ["auml", "ä"],
167 + ["ouml", "ö"],
168 + ["uuml", "ü"],
169 + ["Auml", "Ä"],
170 + ["Ouml", "Ö"],
171 + ["Uuml", "Ü"],
172 + ["szlig", "ß"],
173 +]);
175 +export function decodeEntities(value) {
176 + return value.replace(/&(#x[0-9a-f]+|#\d+|[a-zA-Z]+);/g, (entity, key) => {
177 + if (key.startsWith("#x")) return String.fromCodePoint(Number.parseInt(key.slice(2), 16));
178 + if (key.startsWith("#")) return String.fromCodePoint(Number(key.slice(1)));
179 + return ENTITY_MAP.get(key) ?? entity;
180 + });
183 +export function plainTextFromHtml(html) {
184 + return normalizeWhitespace(decodeEntities(String(html).replace(/<br\s*\/?\s*>/gi, " ").replace(/<[^>]*>/g, " ")));
187 +function normalizeWhitespace(value) {
188 + return String(value).replace(/\s+/g, " ").trim();
191 +function cellsFromRow(rowHtml) {
192 + return [...rowHtml.matchAll(/<t[dh]\b[^>]*>([\s\S]*?)<\/t[dh]>/gi)].map((match) => match[1]);
195 +function attrValues(html, name) {
196 + const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
197 + return [...String(html).matchAll(new RegExp(`${escaped}\\s*=\\s*(["'])(.*?)\\1`, "gi"))].map((match) => decodeEntities(match[2]));
200 +function accountIds(html) {
201 + return sortedUnique([...attrValues(html, "data-account-id"), ...attrValues(html, "ri:account-id")]);
204 +function firstHref(html) {
205 + return attrValues(html, "href")[0];
208 +function normalizeReportArea(href) {
209 + const value = href?.match(/\/spaces\/([^/?#]+)/i)?.[1];
210 + if (!value) return undefined;
211 + try {
212 + return normalizeArea(decodeURIComponent(value));
213 + } catch {
214 + return value;
218 +export function parseReportHtml(html) {
219 + const rows = [];
220 + for (const match of String(html).matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)) {
221 + const cells = cellsFromRow(match[1]);
222 + if (cells.length < 10) continue;
223 + const href = firstHref(cells[0]);
224 + const id = attrValues(cells[0], "data-content-id")[0]
225 + ?? href?.match(/\/pages\/(\d+)/)?.[1]
226 + ?? href?.match(/[?&]pageId=(\d+)/)?.[1];
227 + if (!id) continue;
228 + rows.push({
229 + id,
230 + title: plainTextFromHtml(cells[0]),
231 + href,
232 + area: normalizeReportArea(href),
233 + documentOwner: plainTextFromHtml(cells[1]),
234 + documentOwnerIds: accountIds(cells[1]),
235 + riskOwner: plainTextFromHtml(cells[2]),
236 + riskOwnerIds: accountIds(cells[2]),
237 + assetOwner: plainTextFromHtml(cells[3]),
238 + assetOwnerIds: accountIds(cells[3]),
239 + classification: plainTextFromHtml(cells[4]),
240 + status: plainTextFromHtml(cells[5]),
241 + reviewer: plainTextFromHtml(cells[6]),
242 + reviewerIds: accountIds(cells[6]),
243 + reviewedAt: plainTextFromHtml(cells[7]),
244 + releasedBy: plainTextFromHtml(cells[8]),
245 + releasedAt: plainTextFromHtml(cells[9]),
246 + });
248 + return rows;
251 +function matchesPerson(text, ids, person, accountId) {
252 + return accountId ? ids.includes(accountId) : normalizeWhitespace(text) === normalizeWhitespace(person);
255 +function malformedFields(row) {
256 + return [
257 + ["documentOwner", row.documentOwner],
258 + ["riskOwner", row.riskOwner],
259 + ["assetOwner", row.assetOwner],
260 + ["classification", row.classification],
261 + ["status", row.status],
262 + ].filter(([, value]) => !value).map(([field]) => field);
265 +export function parseDate(value) {
266 + if (!value) return undefined;
267 + const german = value.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})$/);
268 + const iso = value.match(/^(\d{4})-(\d{2})-(\d{2})$/);
269 + const parts = german
270 + ? { day: Number(german[1]), month: Number(german[2]) - 1, year: Number(german[3]) }
271 + : iso
272 + ? { day: Number(iso[3]), month: Number(iso[2]) - 1, year: Number(iso[1]) }
273 + : undefined;
274 + if (parts) {
275 + const date = new Date(Date.UTC(parts.year, parts.month, parts.day));
276 + return date.getUTCFullYear() === parts.year && date.getUTCMonth() === parts.month && date.getUTCDate() === parts.day ? date : undefined;
278 + const timestamp = Date.parse(value);
279 + return Number.isNaN(timestamp) ? undefined : new Date(timestamp);
282 +function annualReviewDue(row, today) {
283 + const date = parseDate(row.releasedAt || row.reviewedAt);
284 + if (!date) return false;
285 + const threshold = new Date(today);
286 + threshold.setUTCFullYear(threshold.getUTCFullYear() - 1);
287 + return date <= threshold;
290 +function areaRank(area) {
291 + const index = OFFICIAL_AREAS.indexOf(area);
292 + return index < 0 ? OFFICIAL_AREAS.length : index;
295 +export function selectWorklist(rows, options) {
296 + const mode = options.mode;
297 + const person = options.person ?? DEFAULT_PERSON;
298 + const accountId = options.accountId ?? (person === DEFAULT_PERSON ? DEFAULT_ACCOUNT_ID : undefined);
299 + const area = options.area ?? "all";
300 + const today = options.today ? new Date(`${options.today}T00:00:00Z`) : new Date();
301 + if (Number.isNaN(today.valueOf())) throw new Error(`Invalid --today: ${options.today}`);
303 + const candidates = [];
304 + let roleMatchCount = 0;
305 + for (const row of rows) {
306 + if (area !== "all" && row.area !== area) continue;
307 + const malformed = malformedFields(row);
308 + const reasons = [];
309 + if (mode === "reviewer") {
310 + if (!matchesPerson(row.reviewer, row.reviewerIds, person, accountId)) continue;
311 + roleMatchCount += 1;
312 + if (row.status !== "Prüfung") continue;
313 + reasons.push("awaiting-review");
314 + } else {
315 + if (!matchesPerson(row.documentOwner, row.documentOwnerIds, person, accountId)) continue;
316 + roleMatchCount += 1;
317 + if (row.status === "Entwurf") reasons.push("draft");
318 + if (!row.reviewer) reasons.push("missing-reviewer");
319 + if (matchesPerson(row.reviewer, row.reviewerIds, person, accountId)) reasons.push("self-reviewer");
320 + if (annualReviewDue(row, today)) reasons.push("annual-review-due");
321 + if (row.status === "Freigegeben" && !parseDate(row.releasedAt || row.reviewedAt)) reasons.push("missing-review-date");
322 + if (malformed.length) reasons.push("malformed-header");
323 + if (!reasons.length) continue;
325 + candidates.push({ ...row, reasons, malformedFields: malformed });
327 + candidates.sort((left, right) => areaRank(left.area) - areaRank(right.area) || left.title.localeCompare(right.title, "de"));
328 + return {
329 + mode,
330 + person,
331 + area,
332 + roleMatchCount,
333 + candidates,
334 + malformed: candidates.filter((row) => row.malformedFields.length),
335 + };
338 +export function parseHeaderHtml(html) {
339 + const header = {};
340 + const keyFor = (cell) => HEADER_FIELDS.get(plainTextFromHtml(cell).toLowerCase().replace(/:$/, ""));
341 + const tables = [...String(html).matchAll(/<table\b[^>]*>([\s\S]*?)<\/table>/gi)].map((match) => match[1]);
342 + for (const table of tables) {
343 + const rows = [...table.matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)].map((match) => cellsFromRow(match[1]));
344 + for (let index = 0; index + 1 < rows.length; index++) {
345 + const keys = rows[index].map(keyFor);
346 + const values = rows[index + 1];
347 + if (keys.length >= 2 && keys.every(Boolean) && values.length >= keys.length) {
348 + keys.forEach((key, cell) => {
349 + if (header[key] === undefined) header[key] = plainTextFromHtml(values[cell]);
350 + });
351 + index += 1;
354 + for (const row of rows) {
355 + if (row.length !== 2) continue;
356 + const key = keyFor(row[0]);
357 + if (key && !keyFor(row[1]) && header[key] === undefined) header[key] = plainTextFromHtml(row[1]);
360 + return header;
363 +function pageBody(page, representation) {
364 + const value = page.body?.[representation]?.value;
365 + if (typeof value !== "string") throw new Error(`Page ${page.id ?? "?"} lacks ${representation} body`);
366 + return value;
369 +function flattenResults(response) {
370 + const pages = Array.isArray(response) ? response : [response];
371 + return pages.flatMap((page) => page?.results ?? []);
374 +function pageUrl(page, baseUrl) {
375 + const webui = page._links?.webui;
376 + if (webui && /^https?:/i.test(webui)) return webui;
377 + const base = page._links?.base ?? baseUrl;
378 + if (webui && base) return new URL(webui, `${base.replace(/\/$/, "")}/`).href;
379 + return `${baseUrl.replace(/\/$/, "")}/wiki/pages/viewpage.action?pageId=${page.id}`;
382 +export async function createSnapshot(client, pageId, baseUrl) {
383 + const storagePage = await client.get(`wiki/api/v2/pages/${pageId}?body-format=storage`);
384 + const capturedVersion = storagePage.version?.number;
385 + const viewPage = await client.get(`wiki/api/v2/pages/${pageId}?body-format=view`);
386 + if (viewPage.version?.number !== capturedVersion) throw new Error(`Page version changed during snapshot: ${capturedVersion} -> ${viewPage.version?.number}`);
387 + const labels = flattenResults(await client.get(`wiki/api/v2/pages/${pageId}/labels?limit=100`, { paginate: true }));
388 + const inlineComments = flattenResults(await client.get(`wiki/api/v2/pages/${pageId}/inline-comments?resolution-status=open&body-format=storage&limit=100`, { paginate: true }));
389 + const footerComments = flattenResults(await client.get(`wiki/api/v2/pages/${pageId}/footer-comments?body-format=storage&limit=100`, { paginate: true }));
390 + const attachments = flattenResults(await client.get(`wiki/api/v2/pages/${pageId}/attachments?limit=100`, { paginate: true }));
391 + const storage = pageBody(storagePage, "storage");
392 + const view = pageBody(viewPage, "view");
393 + const confirmedPage = await client.get(`wiki/api/v2/pages/${pageId}?body-format=storage`);
394 + const confirmedStorage = pageBody(confirmedPage, "storage");
395 + if (confirmedPage.version?.number !== capturedVersion || hashText(confirmedStorage) !== hashText(storage)) {
396 + throw new Error(`Page changed during snapshot after version ${capturedVersion}`);
398 + return {
399 + pageId: String(storagePage.id),
400 + title: storagePage.title,
401 + url: pageUrl(storagePage, baseUrl),
402 + version: storagePage.version,
403 + header: parseHeaderHtml(view),
404 + labels,
405 + inlineComments,
406 + footerComments,
407 + attachments,
408 + body: {
409 + storage,
410 + view,
411 + storageSha256: hashText(storage),
412 + viewSha256: hashText(view),
413 + },
414 + };
417 +export function extractMarkerRefs(storage) {
418 + return sortedUnique([...String(storage).matchAll(/<ac:inline-comment-marker\b[^>]*\bac:ref\s*=\s*(["'])(.*?)\1/gi)].map((match) => match[2]));
421 +const SERVER_STORAGE_ATTRIBUTES = new Set(["local-id", "data-local-id", "ac:local-id", "data-macro-id", "ac:macro-id"]);
423 +function normalizeStorage(storage) {
424 + const tokens = [];
425 + for (const match of String(storage).matchAll(/<[^>]*>|[^<]+/g)) {
426 + const token = match[0];
427 + if (!token.startsWith("<")) {
428 + const text = decodeEntities(token).replaceAll("\r\n", "\n");
429 + if (text.trim()) tokens.push(`#${text}`);
430 + continue;
432 + const closing = token.match(/^<\s*\/\s*([^\s>]+)/);
433 + if (closing) {
434 + tokens.push(`</${closing[1].toLowerCase()}>`);
435 + continue;
437 + const opening = token.match(/^<\s*([^\s/>]+)([\s\S]*?)(\/?)\s*>$/);
438 + if (!opening) {
439 + tokens.push(token);
440 + continue;
442 + const attributes = [...opening[2].matchAll(/([^\s=/>]+)\s*=\s*(["'])(.*?)\2/g)]
443 + .map((attribute) => [attribute[1].toLowerCase(), decodeEntities(attribute[3])])
444 + .filter(([name]) => !SERVER_STORAGE_ATTRIBUTES.has(name))
445 + .sort(([leftName, leftValue], [rightName, rightValue]) => leftName.localeCompare(rightName) || leftValue.localeCompare(rightValue));
446 + tokens.push(`<${opening[1].toLowerCase()} ${JSON.stringify(attributes)}${opening[3] ? "/" : ""}>`);
448 + return tokens;
451 +export function assertEquivalentStorage(expected, actual) {
452 + const expectedNormalized = normalizeStorage(expected);
453 + const actualNormalized = normalizeStorage(actual);
454 + if (JSON.stringify(expectedNormalized) !== JSON.stringify(actualNormalized)) {
455 + const error = new Error("Stored page differs from the planned semantic structure");
456 + error.expectedNormalized = expectedNormalized;
457 + error.actualNormalized = actualNormalized;
458 + throw error;
462 +export function applyReplacements(storage, replacements) {
463 + let result = storage;
464 + const markersBefore = extractMarkerRefs(storage);
465 + for (const replacement of replacements) {
466 + const expectedCount = replacement.count ?? 1;
467 + if (!replacement.from) throw new Error("Replacement from must be non-empty");
468 + if (!Number.isSafeInteger(expectedCount) || expectedCount < 1) throw new Error("Replacement count must be a positive integer");
469 + const actualCount = result.split(replacement.from).length - 1;
470 + if (actualCount !== expectedCount) {
471 + throw new Error(`Replacement expected ${expectedCount} occurrence(s), found ${actualCount}: ${replacement.from}`);
473 + result = result.split(replacement.from).join(replacement.to);
475 + const markersAfter = extractMarkerRefs(result);
476 + if (JSON.stringify(markersBefore) !== JSON.stringify(markersAfter)) throw new Error("Page replacement would remove or change inline-comment markers");
477 + return result;
480 +export function validatePlan(value) {
481 + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Plan must be an object");
482 + const pageId = String(value.pageId ?? "");
483 + if (!/^\d+$/.test(pageId)) throw new Error("Plan pageId must be numeric");
484 + if (!Number.isSafeInteger(value.expectedVersion) || value.expectedVersion < 1) throw new Error("Plan expectedVersion must be a positive integer");
485 + if (!Array.isArray(value.operations) || !value.operations.length) throw new Error("Plan operations must be non-empty");
486 + let pageOperationSeen = false;
487 + const operations = value.operations.map((operation, index) => {
488 + if (operation?.kind === "page") {
489 + pageOperationSeen = true;
490 + if (!operation.versionComment) throw new Error(`Page operation ${index} lacks versionComment`);
491 + if (!Array.isArray(operation.replacements) || !operation.replacements.length) throw new Error(`Page operation ${index} lacks replacements`);
492 + for (const replacement of operation.replacements) {
493 + if (typeof replacement.from !== "string" || typeof replacement.to !== "string") throw new Error(`Page operation ${index} has an invalid replacement`);
494 + if (replacement.count !== undefined && (!Number.isSafeInteger(replacement.count) || replacement.count < 1)) throw new Error(`Page operation ${index} has an invalid replacement count`);
496 + const contains = operation.expect?.contains ?? [];
497 + const notContains = operation.expect?.notContains ?? [];
498 + if (!Array.isArray(contains) || contains.some((entry) => typeof entry !== "string")) throw new Error(`Page operation ${index} has invalid expect.contains`);
499 + if (!Array.isArray(notContains) || notContains.some((entry) => typeof entry !== "string")) throw new Error(`Page operation ${index} has invalid expect.notContains`);
500 + if (!contains.length && !notContains.length) throw new Error(`Page operation ${index} requires at least one expectation`);
501 + return {
502 + kind: "page",
503 + versionComment: operation.versionComment,
504 + replacements: operation.replacements.map((replacement) => ({ ...replacement })),
505 + expect: { contains, notContains },
506 + };
508 + if (operation?.kind === "inline-comment") {
509 + if (pageOperationSeen) throw new Error("Inline-comment operations must precede every page operation");
510 + if (typeof operation.target !== "string" || !operation.target || typeof operation.text !== "string" || !operation.text) throw new Error(`Inline-comment operation ${index} requires target and text`);
511 + const matchCount = operation.matchCount ?? 1;
512 + const matchIndex = operation.matchIndex ?? 0;
513 + if (!Number.isSafeInteger(matchCount) || matchCount < 1) throw new Error(`Inline-comment operation ${index} has invalid matchCount`);
514 + if (!Number.isSafeInteger(matchIndex) || matchIndex < 0 || matchIndex >= matchCount) throw new Error(`Inline-comment operation ${index} has invalid matchIndex`);
515 + return { kind: "inline-comment", target: operation.target, text: operation.text, matchCount, matchIndex };
517 + throw new Error(`Operation ${index} has unknown kind`);
518 + });
519 + return { pageId, expectedVersion: value.expectedVersion, operations };
522 +export function readPlan(planFile) {
523 + const source = readFileSync(planFile, "utf8");
524 + return { source, sha256: hashText(source), plan: validatePlan(JSON.parse(source)) };
527 +function collectAdfTexts(value, texts = []) {
528 + if (Array.isArray(value)) {
529 + for (const child of value) collectAdfTexts(child, texts);
530 + } else if (value && typeof value === "object") {
531 + if (value.type === "text" && typeof value.text === "string") texts.push(value.text);
532 + for (const child of Object.values(value)) collectAdfTexts(child, texts);
534 + return texts;
537 +const ADF_TEXT_BLOCKS = new Set(["paragraph", "heading", "codeBlock"]);
539 +function collectAdfBlocks(value, blocks = []) {
540 + if (Array.isArray(value)) {
541 + for (const child of value) collectAdfBlocks(child, blocks);
542 + } else if (value && typeof value === "object") {
543 + if (ADF_TEXT_BLOCKS.has(value.type)) blocks.push(collectAdfTexts(value).join(""));
544 + else for (const child of value.content ?? []) collectAdfBlocks(child, blocks);
546 + return blocks;
549 +function textSelectionCount(adf, target) {
550 + const blocks = collectAdfBlocks(adf);
551 + const renderedBlocks = blocks.length ? blocks : [collectAdfTexts(adf).join("")];
552 + return renderedBlocks.reduce((count, text) => count + text.split(target).length - 1, 0);
555 +function escapeHtml(value) {
556 + return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
559 +function assertExpectation(storage, expect) {
560 + const text = plainTextFromHtml(storage);
561 + for (const expected of expect.contains) {
562 + if (!text.includes(normalizeWhitespace(expected))) throw new Error(`Validated page lacks expected text: ${expected}`);
564 + for (const forbidden of expect.notContains) {
565 + if (text.includes(normalizeWhitespace(forbidden))) throw new Error(`Validated page still contains forbidden text: ${forbidden}`);
569 +async function requireVersion(client, pageId, expectedVersion, representation = "storage") {
570 + const page = await client.get(`wiki/api/v2/pages/${pageId}?body-format=${representation}`);
571 + if (page.version?.number !== expectedVersion) {
572 + throw new Error(`Page version drift: expected ${expectedVersion}, found ${page.version?.number}`);
574 + return page;
577 +async function createInlineComment(client, pageId, expectedVersion, operation) {
578 + const adfPage = await requireVersion(client, pageId, expectedVersion, "atlas_doc_format");
579 + const adf = JSON.parse(pageBody(adfPage, "atlas_doc_format"));
580 + const count = textSelectionCount(adf, operation.target);
581 + if (count !== operation.matchCount) {
582 + throw new Error(`Inline-comment target expected ${operation.matchCount} occurrence(s), found ${count}: ${operation.target}`);
584 + const created = await client.mutate("POST", "wiki/api/v2/inline-comments", {
585 + pageId,
586 + body: { representation: "storage", value: `<p>${escapeHtml(operation.text)}</p>` },
587 + inlineCommentProperties: {
588 + textSelection: operation.target,
589 + textSelectionMatchCount: operation.matchCount,
590 + textSelectionMatchIndex: operation.matchIndex,
591 + },
592 + });
593 + const verified = await client.get(`wiki/api/v2/inline-comments/${created.id}?body-format=storage&include-properties=true&include-version=true`);
594 + const selection = verified.properties?.inlineOriginalSelection ?? verified.properties?.["inline-original-selection"];
595 + const markerRef = verified.properties?.inlineMarkerRef ?? verified.properties?.["inline-marker-ref"];
596 + if (String(verified.pageId) !== pageId || verified.resolutionStatus !== "open") throw new Error(`Inline comment ${created.id} has unexpected page or status`);
597 + if (plainTextFromHtml(verified.body?.storage?.value ?? "") !== normalizeWhitespace(operation.text)) throw new Error(`Inline comment ${created.id} body validation failed`);
598 + if (selection !== operation.target || !markerRef) throw new Error(`Inline comment ${created.id} selection validation failed`);
599 + const storagePage = await requireVersion(client, pageId, expectedVersion, "storage");
600 + if (!extractMarkerRefs(pageBody(storagePage, "storage")).includes(markerRef)) throw new Error(`Inline comment ${created.id} marker is not visible in page storage`);
601 + const open = flattenResults(await client.get(`wiki/api/v2/pages/${pageId}/inline-comments?resolution-status=open&body-format=storage&limit=100`, { paginate: true }));
602 + if (!open.some((comment) => String(comment.id) === String(created.id))) throw new Error(`Inline comment ${created.id} is absent from the open-comment list`);
603 + return { id: String(created.id), target: operation.target, markerRef, validation: "passed" };
606 +export async function applyPlan(plan, client, baseUrl) {
607 + let version = plan.expectedVersion;
608 + const receipt = {
609 + pageId: plan.pageId,
610 + initialVersion: version,
611 + operations: [],
612 + inlineComments: [],
613 + validation: "pending",
614 + };
615 + try {
616 + let current = await requireVersion(client, plan.pageId, version, "storage");
617 + receipt.url = pageUrl(current, baseUrl);
618 + for (const operation of plan.operations) {
619 + current = await requireVersion(client, plan.pageId, version, "storage");
620 + if (operation.kind === "inline-comment") {
621 + const comment = await createInlineComment(client, plan.pageId, version, operation);
622 + receipt.inlineComments.push(comment);
623 + receipt.operations.push({ kind: operation.kind, id: comment.id, validation: "passed" });
624 + continue;
626 + if (!current.spaceId) throw new Error(`Page ${plan.pageId} lacks spaceId required for update`);
627 + const before = pageBody(current, "storage");
628 + const intended = applyReplacements(before, operation.replacements);
629 + await client.mutate("PUT", `wiki/api/v2/pages/${plan.pageId}`, {
630 + id: plan.pageId,
631 + status: current.status ?? "current",
632 + title: current.title,
633 + spaceId: current.spaceId,
634 + body: { representation: "storage", value: intended },
635 + version: { number: version + 1, message: operation.versionComment },
636 + });
637 + const verified = await requireVersion(client, plan.pageId, version + 1, "storage");
638 + const actual = pageBody(verified, "storage");
639 + if (verified.version?.message !== operation.versionComment) throw new Error(`Version ${version + 1} has unexpected version comment`);
640 + assertEquivalentStorage(intended, actual);
641 + assertExpectation(actual, operation.expect);
642 + version += 1;
643 + receipt.operations.push({ kind: operation.kind, version, versionComment: operation.versionComment, validation: "passed" });
645 + const finalPage = await requireVersion(client, plan.pageId, version, "storage");
646 + const finalStorage = pageBody(finalPage, "storage");
647 + receipt.finalVersion = version;
648 + receipt.versionComment = finalPage.version?.message ?? "";
649 + receipt.header = parseHeaderHtml(finalStorage);
650 + receipt.validation = "passed";
651 + return receipt;
652 + } catch (error) {
653 + receipt.finalVersion = version;
654 + receipt.validation = "failed";
655 + error.receipt = receipt;
656 + throw error;
660 +export function createAtlassianClient({ profile, helper = REQUEST_HELPER, spawn = spawnSync } = {}) {
661 + const run = (requestArgs, body) => {
662 + let dir;
663 + try {
664 + const args = [helper, ...requestArgs];
665 + if (body !== undefined) {
666 + dir = mkdtempSync(path.join(tmpdir(), "ims-request-"));
667 + const bodyFile = path.join(dir, "body.json");
668 + writeFileSync(bodyFile, JSON.stringify(body));
669 + args.push("--body", bodyFile, "--allow-mutation");
671 + if (profile) args.push("--profile", profile);
672 + const result = spawn(process.execPath, args, { encoding: "utf8", windowsHide: true, maxBuffer: 50 * 1024 * 1024 });
673 + if (result.error) throw result.error;
674 + if (result.status !== 0) throw new Error(result.stderr.trim() || `Atlassian request exited ${result.status}`);
675 + return result.stdout.trim() ? JSON.parse(result.stdout) : null;
676 + } finally {
677 + if (dir) rmSync(dir, { recursive: true, force: true });
679 + };
680 + return {
681 + get(requestPath, options = {}) {
682 + return run([requestPath, ...(options.paginate ? ["--paginate"] : [])]);
683 + },
684 + mutate(method, requestPath, body) {
685 + return run([method, requestPath], body);
686 + },
687 + };
690 +function hashText(value) {
691 + return createHash("sha256").update(value).digest("hex");
694 +function sortedUnique(values) {
695 + return [...new Set(values.filter((value) => value !== undefined && value !== ""))].sort();
698 +function usage() {
699 + return `Usage: node scripts/ims.mjs COMMAND [options]
701 +Commands:
702 + policy [--profile NAME]
703 + worklist --mode owner|reviewer [--person NAME] [--account-id ID] [--area all|RD|isp|GA|CS|SM] [--today YYYY-MM-DD] [--profile NAME]
704 + snapshot PAGE_ID [--profile NAME]
705 + check-plan PLAN.json
706 + apply PLAN.json --expected-version N --plan-sha256 HASH --allow-mutation [--profile NAME]
708 +check-plan and every command except apply are read-only. apply accepts this plan shape:
710 + "pageId": "123",
711 + "expectedVersion": 7,
712 + "operations": [
714 + "kind": "inline-comment",
715 + "target": "exact rendered selection",
716 + "text": "Comment text",
717 + "matchCount": 1,
718 + "matchIndex": 0
719 + },
721 + "kind": "page",
722 + "versionComment": "zurück in Entwurf, da Korrektur notwendig",
723 + "replacements": [{ "from": "exact storage fragment", "to": "replacement", "count": 1 }],
724 + "expect": { "contains": ["expected rendered text"], "notContains": ["removed rendered text"] }
729 +Run check-plan after plan approval. Run apply only after a separate explicit go and pass the unchanged hash.`;
732 +async function main() {
733 + const options = parseCli(process.argv.slice(2));
734 + if (options.help) {
735 + console.log(usage());
736 + return;
738 + const baseline = parseBaseline(readFileSync(BASELINE_FILE, "utf8"));
739 + if (options.command === "check-plan") {
740 + const loaded = readPlan(options.positionals[0]);
741 + console.log(JSON.stringify({
742 + pageId: loaded.plan.pageId,
743 + expectedVersion: loaded.plan.expectedVersion,
744 + operations: loaded.plan.operations.length,
745 + planSha256: loaded.sha256,
746 + mutation: false,
747 + }, null, 2));
748 + return;
750 + if (options.command === "apply") {
751 + const loaded = readPlan(options.positionals[0]);
752 + if (loaded.plan.expectedVersion !== options.expectedVersion) throw new Error(`Plan expectedVersion ${loaded.plan.expectedVersion} differs from --expected-version ${options.expectedVersion}`);
753 + if (loaded.sha256 !== options.planSha256) throw new Error(`Plan hash mismatch: expected ${options.planSha256}, found ${loaded.sha256}`);
754 + const receipt = await applyPlan(loaded.plan, createAtlassianClient(options), baseline.baseUrl);
755 + console.log(JSON.stringify(receipt, null, 2));
756 + return;
758 + const client = createAtlassianClient(options);
759 + if (options.command === "policy") {
760 + const result = await checkPolicy(client, baseline);
761 + console.log(JSON.stringify(result, null, 2));
762 + if (result.changed) process.exitCode = 2;
763 + return;
765 + if (options.command === "worklist") {
766 + const report = await client.get(`wiki/rest/api/content/${baseline.report.id}?expand=body.export_view%2Cversion`);
767 + const rows = parseReportHtml(report.body?.export_view?.value ?? "");
768 + const result = selectWorklist(rows, options);
769 + console.log(JSON.stringify({ reportId: baseline.report.id, reportVersion: report.version?.number, rowCount: rows.length, ...result }, null, 2));
770 + return;
772 + if (options.command === "snapshot") {
773 + if (!/^\d+$/.test(options.positionals[0])) throw new Error("PAGE_ID must be numeric");
774 + console.log(JSON.stringify(await createSnapshot(client, options.positionals[0], baseline.baseUrl), null, 2));
778 +if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
779 + main().catch((error) => {
780 + if (error.receipt) console.error(JSON.stringify({ error: error.message, receipt: error.receipt }, null, 2));
781 + else console.error(error.message);
782 + process.exit(1);
783 + });

pi/agent/skills/ims-process-review/scripts/ims.test.mjs

Added
new file mode 100644
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";
6 +import {
7 + applyPlan,
8 + applyReplacements,
9 + assertEquivalentStorage,
10 + checkPolicy,
11 + createSnapshot,
12 + parseBaseline,
13 + parseCli,
14 + parseDate,
15 + parseHeaderHtml,
16 + parseReportHtml,
17 + readPlan,
18 + selectWorklist,
19 + validatePlan,
20 +} from "./ims.mjs";
22 +const reportHtml = `
23 +<table><tbody>
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>
25 +<tr>
26 +<td><a href="/wiki/spaces/RD/pages/101/Alpha">Alpha &amp; 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>
29 +</tr>
30 +<tr>
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>
34 +</tr>
35 +<tr>
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>
39 +</tr>
40 +</tbody></table>`;
42 +test("parses IMS report rows and entities", () => {
43 + const rows = parseReportHtml(reportHtml);
44 + assert.equal(rows.length, 3);
45 + assert.deepEqual(rows[0], {
46 + id: "101",
47 + title: "Alpha & Beta",
48 + href: "/wiki/spaces/RD/pages/101/Alpha",
49 + area: "RD",
50 + documentOwner: "Kathi Borrmann",
51 + documentOwnerIds: ["owner-1"],
52 + riskOwner: "Risk",
53 + riskOwnerIds: [],
54 + assetOwner: "Asset",
55 + assetOwnerIds: [],
56 + classification: "Intern",
57 + status: "Prüfung",
58 + reviewer: "Oliver Krylow",
59 + reviewerIds: ["oliver"],
60 + reviewedAt: "20.08.2026",
61 + releasedBy: "Release",
62 + releasedAt: "21.08.2026",
63 + });
64 + assert.equal(rows[1].id, "102");
65 +});
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);
79 +});
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");
86 +});
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)
93 +`);
94 + assert.equal(baseline.baseUrl, "https://site.example");
95 + const client = {
96 + async get(requestPath) {
97 + return { version: { number: requestPath.includes("blogposts") ? 2 : 24 } };
98 + },
99 + };
100 + const result = await checkPolicy(client, baseline);
101 + assert.equal(result.changed, true);
102 + assert.deepEqual(result.sources.map((source) => source.changed), [false, true]);
103 +});
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" });
110 +});
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/);
116 +});
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({
123 + pageId: "123",
124 + expectedVersion: 7,
125 + operations: [{ kind: "page", versionComment: "geprüft", replacements: [{ from: "old", to: "new" }], expect: { contains: ["new"] } }],
126 + }));
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);
132 +});
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/);
144 + assert.throws(
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/,
147 + );
148 +});
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/);
160 +});
162 +test("applies a version-gated page plan and emits an exact receipt", async () => {
163 + let page = {
164 + id: "123",
165 + title: "Process",
166 + status: "current",
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" },
171 + };
172 + let mutations = 0;
173 + const client = {
174 + async get(requestPath) {
175 + assert.match(requestPath, /pages\/123\?body-format=storage/);
176 + return structuredClone(page);
177 + },
178 + async mutate(method, requestPath, body) {
179 + mutations += 1;
180 + assert.equal(method, "PUT");
181 + assert.equal(requestPath, "wiki/api/v2/pages/123");
182 + assert.equal(body.spaceId, "space-1");
183 + page = {
184 + ...page,
185 + version: structuredClone(body.version),
186 + body: { storage: { value: body.body.value.replace("<p>", '<p data-local-id="server">') } },
187 + };
188 + return structuredClone(page);
189 + },
190 + };
191 + const plan = validatePlan({
192 + pageId: "123",
193 + expectedVersion: 3,
194 + operations: [{
195 + kind: "page",
196 + versionComment: "Rechtschreibkorrektur",
197 + replacements: [{ from: "Old", to: "New" }],
198 + expect: { contains: ["New"], notContains: ["Old"] },
199 + }],
200 + });
201 + const receipt = await applyPlan(plan, client, "https://site.example");
202 + assert.equal(mutations, 1);
203 + assert.deepEqual(receipt, {
204 + pageId: "123",
205 + initialVersion: 3,
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",
210 + finalVersion: 4,
211 + versionComment: "Rechtschreibkorrektur",
212 + header: { Status: "Prüfung" },
213 + });
214 +});
216 +test("stops before mutation on version drift", async () => {
217 + let mutations = 0;
218 + const client = {
219 + async get() {
220 + return { id: "123", version: { number: 8 }, body: { storage: { value: "old" } } };
221 + },
222 + async mutate() {
223 + mutations += 1;
224 + },
225 + };
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);
229 +});
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) => ({
234 + id: "123",
235 + title: "Process",
236 + status: "current",
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" },
242 + });
243 + let comment;
244 + const client = {
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");
250 + },
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>');
256 + comment = {
257 + id: "c1",
258 + pageId: "123",
259 + resolutionStatus: "open",
260 + body: { storage: { value: "<p>Pr&uuml;fung n&ouml;tig</p>" } },
261 + properties: { inlineOriginalSelection: "exact target", inlineMarkerRef: "marker-1" },
262 + };
263 + return { id: "c1" };
264 + },
265 + };
266 + const plan = validatePlan({
267 + pageId: "123",
268 + expectedVersion: 5,
269 + operations: [{ kind: "inline-comment", target: "exact target", text: "Prüfung nötig" }],
270 + });
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/);
275 +});
277 +test("rejects a snapshot changed during supplementary reads", async () => {
278 + let storageReads = 0;
279 + const client = {
280 + async get(requestPath) {
281 + if (requestPath.endsWith("?body-format=storage")) {
282 + storageReads += 1;
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: [] };
287 + },
288 + };
289 + await assert.rejects(createSnapshot(client, "123", "https://site.example"), /changed during snapshot/);
290 +});
292 +test("captures one version-consistent page snapshot", async () => {
293 + const client = {
294 + async get(requestPath) {
295 + if (requestPath.endsWith("?body-format=storage")) return {
296 + id: "123",
297 + title: "Process",
298 + version: { number: 9, message: "x" },
299 + body: { storage: { value: "<p>Storage</p>" } },
300 + _links: { webui: "/wiki/pages/123" },
301 + };
302 + if (requestPath.endsWith("?body-format=view")) return {
303 + id: "123",
304 + version: { number: 9 },
305 + body: { view: { value: "<table><tr><th>Status</th><td>Entwurf</td></tr></table>" } },
306 + };
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}`);
312 + },
313 + };
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}$/);
320 +});