3 +import { spawnSync }
from "node:child_process";
4 +import { createHash }
from "node:crypto";
12 +import path
from "node:path";
13 +import { pathToFileURL }
from "node:url";
15 +const PACKAGE
= "@earendil-works/pi-coding-agent";
17 + "https://registry.npmjs.org/@earendil-works%2Fpi-coding-agent/latest";
18 +const MIGRATION_SECTIONS
= new Set([
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;
42 +export function assertLatest(localVersion, latestVersion) {
43 + if (compareVersions(localVersion, latestVersion)
!== 0) {
45 + `installed Pi ${localVersion}
is not latest ${latestVersion}
; update Pi before modernizing`,
50 +export function parseChangelog(markdown) {
51 + const releases
= [];
56 + const flushBullet = ()
=> {
57 + if (bullet
&& section) section.bullets.push(bullet.trim());
61 + for (
const line
of markdown.split(
/\r?\n/)) {
62 + const releaseMatch
= /^## \[(\d+\.\d+\.\d+(?:[-+][^\]]+)?)\]/.exec(line);
65 + release
= { version: releaseMatch[
1], sections: [] };
66 + releases.push(release);
67 + section
= undefined;
70 + if (
/^## /.test(line)) {
72 + release
= undefined;
73 + section
= undefined;
76 + const sectionMatch
= /^### (.+?)\s*$/.exec(line);
77 + if (sectionMatch
&& release) {
79 + section
= { name: sectionMatch[
1], bullets: [] };
80 + release.sections.push(section);
83 + const bulletMatch
= /^- (.+)$/.exec(line);
84 + if (bulletMatch
&& section) {
86 + bullet
= bulletMatch[
1];
89 + if (bullet
&& line.trim()
&& !/^#{1,6} /.test(line)) {
90 + bullet
+= ` ${line.trim()}
`;
94 + if (releases.length
=== 0)
95 + throw new Error(
"changelog contains no release sections");
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(),
108 + for (
const text
of section.bullets) {
109 + if (
!migrationSection
&& !MIGRATION_WORDS.test(text))
continue;
111 + version: release.version,
112 + section: section.name,
121 +export function collectPackageVersions(lock) {
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 }]
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, {
144 + maxBuffer:
64 * 1024 * 1024,
147 + if (result.error)
throw result.error;
148 + if (result.status
!== 0) {
150 + `${command}
${args.join(
" ")}
failed: ${(result.stderr
|| result.stdout).trim()}
`,
153 + return result.stdout;
156 +function executableOnPath(name) {
158 + process.
platform === "win32" 159 + ? (
process.
env.PATHEXT
?? ".EXE;.CMD;.BAT").split(
";")
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}
`);
166 + accessSync(candidate, constants.X_OK);
167 + return realpathSync(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),
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),
204 + throw new Error(
`fetch ${url}
failed: HTTP ${response.status}
`);
205 + return response.text();
208 +function source(kind, location, text) {
212 + bytes:
Buffer.byteLength(text),
213 + sha256: createHash(
"sha256").update(text).digest(
"hex"),
217 +function oldestVersion(packages, fallback) {
218 + return packages.reduce(
220 + compareVersions(item.version, oldest)
< 0 ? item.version
: oldest,
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),
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")))
261 + const afterVersion
= oldestVersion(packages, localVersion);
262 + const interval
= { afterVersion, throughVersion: latestVersion };
263 + const candidates
= mergeCandidates([
265 + source:
"installed",
266 + candidates: extractCandidates(localChangelog, interval),
270 + candidates: extractCandidates(remoteChangelog, interval),
273 + const files
= parseGitFiles(
276 + [
"ls-files",
"-z",
"--cached",
"--others",
"--exclude-standard"],
283 + process.
stdout.write(
289 + local: { version: localVersion, executable },
290 + latest: { version: latestVersion, registry: REGISTRY_URL },
294 + source(
"installed", localChangelogPath, localChangelog),
295 + source(
"remote", remoteChangelogUrl, remoteChangelog),
306 +const invoked
= process.
argv[
1]
307 + ? import.meta.url
=== pathToFileURL(path.resolve(
process.
argv[
1])).href
310 + main().catch((error)
=> {
311 + process.
stderr.write(
312 + `${
JSON.
stringify({
315 + reason: error
instanceof Error ? error.message
: String(error),
318 + process.
exitCode = 1;