repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat: collect Pi migration evidence

d604262814709cd7a62a21cb96cb8156ada98e2d

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (2)

.pi/skills/modernize/scripts/audit.mjs

Added
new file mode 100644
1 +#!/usr/bin/env node
3 +import { spawnSync } from "node:child_process";
4 +import { createHash } from "node:crypto";
5 +import {
6 + accessSync,
7 + constants,
8 + existsSync,
9 + readFileSync,
10 + realpathSync,
11 +} from "node:fs";
12 +import path from "node:path";
13 +import { pathToFileURL } from "node:url";
15 +const PACKAGE = "@earendil-works/pi-coding-agent";
16 +const REGISTRY_URL =
17 + "https://registry.npmjs.org/@earendil-works%2Fpi-coding-agent/latest";
18 +const MIGRATION_SECTIONS = new Set([
19 + "breaking changes",
20 + "changed",
21 + "deprecated",
22 + "removed",
23 +]);
24 +const MIGRATION_WORDS =
25 + /\b(breaking|deprecat\w*|migrat\w*|remov\w*|renam\w*|replac\w*|no longer|instead of|must now)\b/i;
27 +function versionParts(value) {
28 + const match = /^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(value.trim());
29 + if (!match) throw new Error(`invalid semantic version: ${value}`);
30 + return match.slice(1, 4).map(Number);
33 +export function compareVersions(left, right) {
34 + const a = versionParts(left);
35 + const b = versionParts(right);
36 + for (let index = 0; index < 3; index++) {
37 + if (a[index] !== b[index]) return a[index] > b[index] ? 1 : -1;
38 + }
39 + return 0;
42 +export function assertLatest(localVersion, latestVersion) {
43 + if (compareVersions(localVersion, latestVersion) !== 0) {
44 + throw new Error(
45 + `installed Pi ${localVersion} is not latest ${latestVersion}; update Pi before modernizing`,
46 + );
47 + }
50 +export function parseChangelog(markdown) {
51 + const releases = [];
52 + let release;
53 + let section;
54 + let bullet;
56 + const flushBullet = () => {
57 + if (bullet && section) section.bullets.push(bullet.trim());
58 + bullet = undefined;
59 + };
61 + for (const line of markdown.split(/\r?\n/)) {
62 + const releaseMatch = /^## \[(\d+\.\d+\.\d+(?:[-+][^\]]+)?)\]/.exec(line);
63 + if (releaseMatch) {
64 + flushBullet();
65 + release = { version: releaseMatch[1], sections: [] };
66 + releases.push(release);
67 + section = undefined;
68 + continue;
69 + }
70 + if (/^## /.test(line)) {
71 + flushBullet();
72 + release = undefined;
73 + section = undefined;
74 + continue;
75 + }
76 + const sectionMatch = /^### (.+?)\s*$/.exec(line);
77 + if (sectionMatch && release) {
78 + flushBullet();
79 + section = { name: sectionMatch[1], bullets: [] };
80 + release.sections.push(section);
81 + continue;
82 + }
83 + const bulletMatch = /^- (.+)$/.exec(line);
84 + if (bulletMatch && section) {
85 + flushBullet();
86 + bullet = bulletMatch[1];
87 + continue;
88 + }
89 + if (bullet && line.trim() && !/^#{1,6} /.test(line)) {
90 + bullet += ` ${line.trim()}`;
91 + }
92 + }
93 + flushBullet();
94 + if (releases.length === 0)
95 + throw new Error("changelog contains no release sections");
96 + return releases;
99 +export function extractCandidates(markdown, { afterVersion, throughVersion }) {
100 + const candidates = [];
101 + for (const release of parseChangelog(markdown)) {
102 + if (compareVersions(release.version, afterVersion) <= 0) continue;
103 + if (compareVersions(release.version, throughVersion) > 0) continue;
104 + for (const section of release.sections) {
105 + const migrationSection = MIGRATION_SECTIONS.has(
106 + section.name.toLowerCase(),
107 + );
108 + for (const text of section.bullets) {
109 + if (!migrationSection && !MIGRATION_WORDS.test(text)) continue;
110 + candidates.push({
111 + version: release.version,
112 + section: section.name,
113 + text,
114 + });
118 + return candidates;
121 +export function collectPackageVersions(lock) {
122 + const packages =
123 + lock && typeof lock === "object" && lock.packages ? lock.packages : {};
124 + return Object.entries(packages)
125 + .flatMap(([location, value]) => {
126 + const marker = "node_modules/@earendil-works/";
127 + const index = location.lastIndexOf(marker);
128 + if (index === -1 || !value || typeof value !== "object") return [];
129 + const name = location.slice(index + "node_modules/".length);
130 + return typeof value.version === "string"
131 + ? [{ name, version: value.version }]
132 + : [];
133 + })
134 + .sort((a, b) => a.name.localeCompare(b.name));
137 +export function parseGitFiles(raw) {
138 + return raw.split("\0").filter(Boolean);
141 +function run(command, args, options = {}) {
142 + const result = spawnSync(command, args, {
143 + encoding: "utf8",
144 + maxBuffer: 64 * 1024 * 1024,
145 + ...options,
146 + });
147 + if (result.error) throw result.error;
148 + if (result.status !== 0) {
149 + throw new Error(
150 + `${command} ${args.join(" ")} failed: ${(result.stderr || result.stdout).trim()}`,
151 + );
153 + return result.stdout;
156 +function executableOnPath(name) {
157 + const extensions =
158 + process.platform === "win32"
159 + ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";")
160 + : [""];
161 + for (const directory of (process.env.PATH ?? "").split(path.delimiter)) {
162 + if (!directory) continue;
163 + for (const extension of extensions) {
164 + const candidate = path.join(directory, `${name}${extension}`);
165 + try {
166 + accessSync(candidate, constants.X_OK);
167 + return realpathSync(candidate);
168 + } catch {
169 + // Try the next PATH candidate.
173 + throw new Error(`${name} executable not found on PATH`);
176 +function installedChangelog(executable) {
177 + let directory = path.dirname(executable);
178 + for (let depth = 0; depth < 6; depth++) {
179 + const candidate = path.join(directory, "CHANGELOG.md");
180 + if (existsSync(candidate)) return candidate;
181 + const parent = path.dirname(directory);
182 + if (parent === directory) break;
183 + directory = parent;
185 + throw new Error(`installed Pi changelog not found near ${executable}`);
188 +async function fetchJson(url) {
189 + const response = await fetch(url, {
190 + headers: { "user-agent": "pi-ext-modernize" },
191 + signal: AbortSignal.timeout(30_000),
192 + });
193 + if (!response.ok)
194 + throw new Error(`fetch ${url} failed: HTTP ${response.status}`);
195 + return response.json();
198 +async function fetchText(url) {
199 + const response = await fetch(url, {
200 + headers: { "user-agent": "pi-ext-modernize" },
201 + signal: AbortSignal.timeout(30_000),
202 + });
203 + if (!response.ok)
204 + throw new Error(`fetch ${url} failed: HTTP ${response.status}`);
205 + return response.text();
208 +function source(kind, location, text) {
209 + return {
210 + kind,
211 + location,
212 + bytes: Buffer.byteLength(text),
213 + sha256: createHash("sha256").update(text).digest("hex"),
214 + };
217 +function oldestVersion(packages, fallback) {
218 + return packages.reduce(
219 + (oldest, item) =>
220 + compareVersions(item.version, oldest) < 0 ? item.version : oldest,
221 + fallback,
222 + );
225 +function mergeCandidates(groups) {
226 + const merged = new Map();
227 + for (const { source: sourceName, candidates } of groups) {
228 + for (const candidate of candidates) {
229 + const key = `${candidate.version}\0${candidate.section}\0${candidate.text}`;
230 + const current = merged.get(key);
231 + if (current) current.sources.push(sourceName);
232 + else merged.set(key, { ...candidate, sources: [sourceName] });
235 + return [...merged.values()].sort((a, b) =>
236 + compareVersions(a.version, b.version),
237 + );
240 +async function main() {
241 + const repo = process.cwd();
242 + const executable = executableOnPath("pi");
243 + const localVersion = run(executable, ["--version"]).trim();
244 + const metadata = await fetchJson(REGISTRY_URL);
245 + if (!metadata || typeof metadata.version !== "string")
246 + throw new Error(`registry response for ${PACKAGE} has no version`);
247 + const latestVersion = metadata.version;
248 + assertLatest(localVersion, latestVersion);
250 + const localChangelogPath = installedChangelog(executable);
251 + const localChangelog = readFileSync(localChangelogPath, "utf8");
252 + const remoteChangelogUrl = `https://raw.githubusercontent.com/earendil-works/pi/v${latestVersion}/packages/coding-agent/CHANGELOG.md`;
253 + const remoteChangelog = await fetchText(remoteChangelogUrl);
254 + parseChangelog(localChangelog);
255 + parseChangelog(remoteChangelog);
257 + const lockPath = path.join(repo, "package-lock.json");
258 + const packages = existsSync(lockPath)
259 + ? collectPackageVersions(JSON.parse(readFileSync(lockPath, "utf8")))
260 + : [];
261 + const afterVersion = oldestVersion(packages, localVersion);
262 + const interval = { afterVersion, throughVersion: latestVersion };
263 + const candidates = mergeCandidates([
265 + source: "installed",
266 + candidates: extractCandidates(localChangelog, interval),
267 + },
269 + source: "remote",
270 + candidates: extractCandidates(remoteChangelog, interval),
271 + },
272 + ]);
273 + const files = parseGitFiles(
274 + run(
275 + "git",
276 + ["ls-files", "-z", "--cached", "--others", "--exclude-standard"],
278 + cwd: repo,
279 + },
280 + ),
281 + );
283 + process.stdout.write(
284 + `${JSON.stringify(
286 + schemaVersion: 1,
287 + status: "ok",
288 + repo,
289 + local: { version: localVersion, executable },
290 + latest: { version: latestVersion, registry: REGISTRY_URL },
291 + interval,
292 + packages,
293 + sources: [
294 + source("installed", localChangelogPath, localChangelog),
295 + source("remote", remoteChangelogUrl, remoteChangelog),
296 + ],
297 + candidates,
298 + files,
299 + },
300 + null,
301 + 2,
302 + )}\n`,
303 + );
306 +const invoked = process.argv[1]
307 + ? import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href
308 + : false;
309 +if (invoked) {
310 + main().catch((error) => {
311 + process.stderr.write(
312 + `${JSON.stringify({
313 + schemaVersion: 1,
314 + status: "failed",
315 + reason: error instanceof Error ? error.message : String(error),
316 + })}\n`,
317 + );
318 + process.exitCode = 1;
319 + });

.pi/skills/modernize/scripts/audit.test.mjs

Added
new file mode 100644
1 +import assert from "node:assert/strict";
2 +import test from "node:test";
3 +import {
4 + assertLatest,
5 + collectPackageVersions,
6 + compareVersions,
7 + extractCandidates,
8 + parseChangelog,
9 + parseGitFiles,
10 +} from "./audit.mjs";
12 +const changelog = `# Changelog
14 +## [2.0.0] - 2026-07-13
16 +### Added
18 +- Added harmless sparkle output.
20 +### Changed
22 +- Renamed \`oldCall()\` to \`newCall()\`.
24 +### Fixed
26 +- Removed the obsolete \`legacyOption\` request field.
27 +- Fixed ordinary rendering noise.
29 +## [1.5.0] - 2026-07-01
31 +### Breaking Changes
33 +- Replace \`alpha()\` with \`beta()\`.
35 +## [1.0.0] - 2026-06-01
37 +### Added
39 +- Initial release.
40 +`;
42 +test("parses release sections newest first", () => {
43 + assert.deepEqual(
44 + parseChangelog(changelog).map(({ version }) => version),
45 + ["2.0.0", "1.5.0", "1.0.0"],
46 + );
47 +});
49 +test("extracts migration sections and keyword bullets in the version interval", () => {
50 + assert.deepEqual(
51 + extractCandidates(changelog, {
52 + afterVersion: "1.5.0",
53 + throughVersion: "2.0.0",
54 + }).map(({ section, text }) => [section, text]),
55 + [
56 + ["Changed", "Renamed `oldCall()` to `newCall()`."],
57 + ["Fixed", "Removed the obsolete `legacyOption` request field."],
58 + ],
59 + );
60 +});
62 +test("rejects changelogs without release sections", () => {
63 + assert.throws(() => parseChangelog("# Changelog\n\nNothing yet."), /release/);
64 +});
66 +test("compares semantic versions numerically", () => {
67 + assert.equal(compareVersions("0.80.10", "0.80.6"), 1);
68 + assert.equal(compareVersions("0.80.6", "0.80.6"), 0);
69 + assert.equal(compareVersions("0.79.9", "0.80.1"), -1);
70 +});
72 +test("fails when installed Pi is not latest", () => {
73 + assert.doesNotThrow(() => assertLatest("0.80.6", "0.80.6"));
74 + assert.throws(() => assertLatest("0.80.5", "0.80.6"), /not latest/);
75 +});
77 +test("collects resolved earendil Pi package versions", () => {
78 + assert.deepEqual(
79 + collectPackageVersions({
80 + packages: {
81 + "node_modules/@earendil-works/pi-ai": { version: "0.80.4" },
82 + "node_modules/@earendil-works/pi-coding-agent": {
83 + version: "0.80.6",
84 + },
85 + "node_modules/vitest": { version: "4.1.9" },
86 + },
87 + }),
88 + [
89 + { name: "@earendil-works/pi-ai", version: "0.80.4" },
90 + { name: "@earendil-works/pi-coding-agent", version: "0.80.6" },
91 + ],
92 + );
93 +});
95 +test("parses Git NUL file lists", () => {
96 + assert.deepEqual(parseGitFiles("a.ts\0dir/b.md\0\0"), ["a.ts", "dir/b.md"]);
97 +});