Sync upstream v3.2.4: slim install refs, a crash-safe installer, Change project restarts the agent (v3.2.4)

AI Assisted
This commit is contained in:
jparkerweb committed 2026-12-03 15:17:47 -08:00
1 parent 50319aa332
commit f997a82c4d
45 files changed
+7851 -306

No files matched your search

+731
View File
@@ -0,0 +1,731 @@
'use strict';
// The canonical skills store, written once per install: every skill is copied into a staging
// folder beside the store, checked byte for byte, then swapped in with a backup and a journal,
// so an interrupted install can be put back or finished. The skills CLI then links agents to the
// store; it never copies the tree again. Zero dependencies, CommonJS.
//
// Layout, for a scope's store `<base>/.agents/skills`:
// <base>/.agents/skills/<name>/ one canonical copy per skill
// <base>/.agents/skills/.plan2code-canonical.json the validity manifest (metadata, not a skill)
// <base>/.agents/.skills-stage-<pid>-<timestamp>/ a stage, while it is built
// <base>/.agents/.skills-backup-<operation>/ the replaced skills, while a swap runs
// <base>/.agents/.plan2code-canonical-journal.json what a swap has done so far
const crypto = require('crypto');
const fs = require('fs');
const os = require('os');
const path = require('path');
const MANIFEST_NAME = '.plan2code-canonical.json';
const JOURNAL_NAME = '.plan2code-canonical-journal.json';
const STAGE_PREFIX = '.skills-stage-';
const BACKUP_PREFIX = '.skills-backup-';
const MANIFEST_VERSION = 1;
const SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
// Ours, as everywhere else in the installer: `plan2code` itself or `plan2code-<name>`.
const OUR_NAME = /^plan2code(?:-|$)/;
/** The skills CLI's canonical store for a scope: `<home>/.agents/skills` globally, `<cwd>/.agents/skills` in a project. */
function canonicalRoot(scope, cwd = process.cwd(), home = os.homedir()) {
return path.join(scope === 'global' ? home : cwd, '.agents', 'skills');
}
function manifestPath(root) {
return path.join(root, MANIFEST_NAME);
}
function journalPath(root) {
return path.join(path.dirname(root), JOURNAL_NAME);
}
/** An error with a `code` the installer can name. */
function canonicalError(code, message, extra = {}) {
return Object.assign(new Error(message), { code }, extra);
}
/** The lstat of `file`, or null when nothing is there. Never follows a link. */
function lstatOrNull(file) {
try {
return fs.lstatSync(file);
} catch {
return null;
}
}
function readJson(file) {
try {
return JSON.parse(fs.readFileSync(file, 'utf8'));
} catch {
return null;
}
}
// Windows briefly refuses a rename over a file that was just replaced (an indexer or virus
// scanner still has it open): EPERM, EACCES or EBUSY that clear within milliseconds.
const TRANSIENT_RENAME = new Set(['EPERM', 'EACCES', 'EBUSY']);
const RENAME_ATTEMPTS = 8;
/** Block for `ms` milliseconds without spinning. */
function pause(ms) {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
/** fs.renameSync, retried with a growing pause while Windows reports the source or target busy. */
function renameWithRetry(from, to) {
for (let attempt = 1; ; attempt++) {
try {
fs.renameSync(from, to);
return;
} catch (err) {
if (process.platform !== 'win32' || !TRANSIENT_RENAME.has(err.code) || attempt >= RENAME_ATTEMPTS) throw err;
pause(10 * attempt);
}
}
}
/** A rename Windows refused because something holds the folder (a terminal or Explorer in it, a scanner). */
function isLockError(err) {
return process.platform === 'win32' && err && TRANSIENT_RENAME.has(err.code);
}
/**
* Make `dest` hold exactly what `src` holds without renaming `dest` itself: copy every file over
* it, then remove what `src` does not have. The fallback for a skill folder Windows will not let
* go of, as the skills CLI did before (it copied over a folder it could not remove).
*/
function replaceInPlace(src, dest) {
fs.mkdirSync(dest, { recursive: true });
fs.cpSync(src, dest, { recursive: true, force: true });
const prune = (from, into) => {
for (const entry of fs.readdirSync(into, { withFileTypes: true })) {
const there = path.join(from, entry.name);
const here = path.join(into, entry.name);
const keep = lstatOrNull(there);
if (!keep) fs.rmSync(here, { recursive: true, force: true });
else if (entry.isDirectory() && keep.isDirectory()) prune(there, here);
}
};
prune(src, dest);
}
/** Write JSON through a temp file and a rename, so a reader never sees half a file. */
function writeJsonAtomic(file, value) {
fs.mkdirSync(path.dirname(file), { recursive: true });
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
try {
fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n');
renameWithRetry(tmp, file);
} catch (err) {
try {
fs.rmSync(tmp, { force: true });
} catch {}
throw err;
}
}
function sha256(buffer) {
return crypto.createHash('sha256').update(buffer).digest('hex');
}
/** One hash for a set of `{ rel: sha256 }`: the sorted relative paths with their file hashes. */
function treeHashOf(hashes) {
const hash = crypto.createHash('sha256');
for (const rel of Object.keys(hashes).sort()) hash.update(`${rel}\0${hashes[rel]}\n`);
return hash.digest('hex');
}
/** Refuse a name that could leave the store (`..`, separators) or is not a plain skill folder name. */
function assertSkillName(name) {
if (typeof name !== 'string' || !SKILL_NAME.test(name) || name.includes('..')) {
throw canonicalError('bad-name', `Refusing skill name ${JSON.stringify(name)}: not a plain folder name`);
}
}
/**
* Every regular file under `dir` as sorted forward-slash paths relative to it. A symlink or
* junction anywhere (lstat sees both as links) is refused rather than followed, as is anything
* that is neither a file nor a folder.
*/
// Files an OS writes into any folder a person opens: not part of a skill, never a reason to call
// the store changed.
const OS_JUNK = new Set(['.DS_Store', 'Thumbs.db', 'desktop.ini']);
function listTree(dir) {
const files = [];
const walk = (current, rel) => {
for (const name of fs.readdirSync(current).sort()) {
if (OS_JUNK.has(name)) continue;
const full = path.join(current, name);
const relPath = rel ? `${rel}/${name}` : name;
const stat = fs.lstatSync(full);
if (stat.isSymbolicLink()) throw canonicalError('link-in-tree', `Refusing ${full}: links are not copied`);
if (stat.isDirectory()) walk(full, relPath);
else if (stat.isFile()) files.push(relPath);
else throw canonicalError('special-file', `Refusing ${full}: not a regular file`);
}
};
walk(dir, '');
return files.sort();
}
/** `{ rel: sha256 }` for a skill folder, with every rel prefixed by `prefix/` when given. */
function hashTree(dir, prefix = '') {
const hashes = {};
for (const rel of listTree(dir)) hashes[prefix ? `${prefix}/${rel}` : rel] = sha256(fs.readFileSync(path.join(dir, ...rel.split('/'))));
return hashes;
}
/** The hash of one skill folder, or null when it is missing, a link, or holds a link. */
function skillTreeHash(dir) {
const stat = lstatOrNull(dir);
if (!stat || stat.isSymbolicLink() || !stat.isDirectory()) return null;
try {
return treeHashOf(hashTree(dir));
} catch {
return null;
}
}
// ---------------------------------------------------------------------------------------------
// Journal
// ---------------------------------------------------------------------------------------------
const JOURNAL_OPS = ['staged', 'backup-created', 'canonical-swapped', 'committed', 'rolled-back'];
function readJournal(root) {
const journal = readJson(journalPath(root));
return journal && Array.isArray(journal.records) ? journal : null;
}
/**
* Add one record to the journal beside `root` (written atomically): `{ op, scope, operationId,
* skill, source, destination, at }` plus any `extra`. `op` is one of JOURNAL_OPS.
*/
function journalRecord(root, { op, scope, operationId, skill = null, source = null, destination = null, extra = {} }) {
if (!JOURNAL_OPS.includes(op)) throw canonicalError('bad-journal-op', `Unknown journal operation ${op}`);
const file = journalPath(root);
const current = readJournal(root);
const journal = current && current.operationId === operationId ? current : { version: MANIFEST_VERSION, scope, operationId, root, records: [] };
const record = { op, scope, operationId, skill, source, destination, at: new Date().toISOString(), ...extra };
journal.records.push(record);
writeJsonAtomic(file, journal);
return record;
}
function removeJournal(root) {
fs.rmSync(journalPath(root), { force: true });
}
// ---------------------------------------------------------------------------------------------
// Manifest
// ---------------------------------------------------------------------------------------------
/** The validity manifest in a scope's store, or null when there is none or it is unreadable. */
function readCanonicalManifest(scope, cwd = process.cwd(), home = os.homedir()) {
const manifest = readJson(manifestPath(canonicalRoot(scope, cwd, home)));
return manifest && typeof manifest === 'object' && !Array.isArray(manifest) ? manifest : null;
}
/**
* Whether the store for `scope` holds a complete, current copy of every expected skill:
* `{ complete, problems, manifest }`. Complete means a manifest marked complete with no journal,
* naming each expected skill, each one a real folder (never a link) whose files hash to the
* recorded tree hash, and, when `version` is given, written for that version.
*/
function validateCanonicalManifest(scope, expectedNames, { cwd = process.cwd(), home = os.homedir(), version = null } = {}) {
const root = canonicalRoot(scope, cwd, home);
const manifest = readCanonicalManifest(scope, cwd, home);
const problems = [];
if (!manifest) problems.push('no manifest');
else {
if (manifest.complete !== true) problems.push('manifest not complete');
if (manifest.journal) problems.push('a swap did not finish');
if (version && manifest.version !== version) problems.push(`manifest is for ${manifest.version || 'no version'}`);
const skills = manifest.skills && typeof manifest.skills === 'object' ? manifest.skills : {};
for (const name of expectedNames) {
if (typeof skills[name] !== 'string') {
problems.push(`${name}: not in the manifest`);
continue;
}
const actual = skillTreeHash(path.join(root, name));
if (actual === null) problems.push(`${name}: missing`);
else if (actual !== skills[name]) problems.push(`${name}: changed on disk`);
}
}
return { complete: problems.length === 0, problems, manifest };
}
// ---------------------------------------------------------------------------------------------
// Stage
// ---------------------------------------------------------------------------------------------
/** Remove a folder, returning a warning line instead of throwing. */
function removeQuietly(dir, warnings) {
try {
fs.rmSync(dir, { recursive: true, force: true });
} catch (err) {
warnings.push(`Could not remove ${dir}: ${err.message}`);
}
}
/**
* Copy every expected skill from `builtDir` into a new stage beside the store, once each, and
* check the copy against the source before anything in the store changes. Refuses a missing
* skill, a name that could leave the store, and any link inside the built tree. Returns
* `{ stageDir, scope, root, operationId, names, files, hashes, skills, treeHash, manifest }`:
* `files` the sorted relative paths, `hashes` their sha256, `skills` each skill's tree hash.
*/
function stageCanonicalSkills({ scope, builtDir, expectedNames, cwd = process.cwd(), home = os.homedir(), version = null, sourceRef = null }) {
const root = canonicalRoot(scope, cwd, home);
const names = [...new Set(expectedNames)].sort();
for (const name of names) assertSkillName(name);
for (const name of names) {
const stat = lstatOrNull(path.join(builtDir, name));
if (!stat) throw canonicalError('missing-skill', `The build has no ${name} skill`);
if (stat.isSymbolicLink() || !stat.isDirectory()) throw canonicalError('link-in-tree', `Refusing ${path.join(builtDir, name)}: not a plain folder`);
}
const operationId = `${process.pid}-${Date.now()}`;
const stageDir = path.join(path.dirname(root), `${STAGE_PREFIX}${operationId}`);
fs.mkdirSync(stageDir, { recursive: true });
try {
const hashes = {};
const sizes = {};
const skills = {};
for (const name of names) {
const source = path.join(builtDir, name);
const own = {};
for (const rel of listTree(source)) {
const from = path.join(source, ...rel.split('/'));
const to = path.join(stageDir, name, ...rel.split('/'));
const bytes = fs.readFileSync(from);
fs.mkdirSync(path.dirname(to), { recursive: true });
fs.writeFileSync(to, bytes);
own[rel] = sha256(bytes);
hashes[`${name}/${rel}`] = own[rel];
sizes[`${name}/${rel}`] = bytes.length;
}
skills[name] = treeHashOf(own);
}
// The copy is checked before the store is touched: byte counts first, then the hashes.
for (const [rel, hash] of Object.entries(hashes)) {
const copied = path.join(stageDir, ...rel.split('/'));
const stat = lstatOrNull(copied);
if (!stat || !stat.isFile() || stat.size !== sizes[rel]) throw canonicalError('stage-mismatch', `The staged copy of ${rel} has the wrong size`);
if (sha256(fs.readFileSync(copied)) !== hash) throw canonicalError('stage-mismatch', `The staged copy of ${rel} does not match the build`);
}
const files = Object.keys(hashes).sort();
const treeHash = treeHashOf(hashes);
const manifest = { version, sourceRef, complete: false, skills, files: Object.fromEntries(files.map((rel) => [rel, hashes[rel]])), treeHash, journal: null };
writeJsonAtomic(path.join(stageDir, MANIFEST_NAME), manifest);
journalRecord(root, { op: 'staged', scope, operationId, source: builtDir, destination: stageDir });
return { stageDir, scope, root, operationId, names, files, hashes, skills, treeHash, manifest };
} catch (err) {
removeQuietly(stageDir, []);
throw err;
}
}
/** Check a stage on disk still matches what was staged: every file present with its hash. */
function validateStage(stage) {
for (const name of stage.names) {
let hashes;
try {
hashes = hashTree(path.join(stage.stageDir, name), name);
} catch {
return false;
}
const expected = Object.keys(stage.hashes).filter((rel) => rel.startsWith(`${name}/`));
if (Object.keys(hashes).length !== expected.length) return false;
for (const rel of expected) if (hashes[rel] !== stage.hashes[rel]) return false;
}
return true;
}
// ---------------------------------------------------------------------------------------------
// Commit
// ---------------------------------------------------------------------------------------------
/** Put one swapped skill back as it was: drop the new copy, then return the backup or the link. */
function restoreEntry(entry, root, rename) {
const dest = path.join(root, entry.name);
if (entry.inPlace) {
// The folder could not be moved, so its old files were copied aside and are copied back.
if (entry.backup && lstatOrNull(entry.backup)) replaceInPlace(entry.backup, dest);
return;
}
if (entry.swapped) {
const stat = lstatOrNull(dest);
if (stat && stat.isSymbolicLink()) fs.unlinkSync(dest);
else if (stat) fs.rmSync(dest, { recursive: true, force: true });
}
if (entry.backup && lstatOrNull(entry.backup)) rename(entry.backup, dest);
else if (entry.linkTarget) fs.symlinkSync(entry.linkTarget, dest, process.platform === 'win32' ? 'junction' : 'dir');
}
/**
* Swap a validated stage into the store. Each existing expected skill moves to a backup folder
* (a link is removed itself, never followed, and its target remembered), then its staged copy
* is renamed in. Any failure puts back every skill already swapped, records `rolled-back`, and
* throws with `retryable: true`. A skill folder Windows will not let go of is written over in place
* instead (replaceInPlace), its old files copied aside first. Success finalizes (finalizeCommit).
* `options.rename`, `options.isLock` and
* `options.hooks.afterSwap(name)` let tests inject a failure or an interruption.
*/
function commitCanonicalSkills(stage, options = {}) {
const rename = options.rename || renameWithRetry;
const isLock = options.isLock || isLockError;
const hooks = options.hooks || {};
const { root, scope, operationId } = stage;
if (!validateStage(stage)) throw canonicalError('stage-mismatch', 'The staged skills changed before the swap; nothing in the store was touched', { retryable: true });
fs.mkdirSync(root, { recursive: true });
const previousManifest = readJson(manifestPath(root));
const backupDir = path.join(path.dirname(root), `${BACKUP_PREFIX}${operationId}`);
const done = [];
try {
// While the swap runs the store is not complete, whatever happens to this process.
writeJsonAtomic(manifestPath(root), { ...(previousManifest || {}), complete: false, journal: operationId });
fs.mkdirSync(backupDir, { recursive: true });
for (const name of stage.names) {
const dest = path.join(root, name);
const entry = { name, backup: null, linkTarget: null, swapped: false };
done.push(entry);
const stat = lstatOrNull(dest);
if (stat && stat.isSymbolicLink()) {
try {
entry.linkTarget = fs.readlinkSync(dest);
} catch {}
fs.unlinkSync(dest);
journalRecord(root, { op: 'backup-created', scope, operationId, skill: name, source: dest, destination: null, extra: { link: entry.linkTarget } });
} else if (stat) {
const backup = path.join(backupDir, name);
try {
rename(dest, backup);
} catch (err) {
if (!isLock(err)) throw err;
// Held open: keep a copy of the old files for a rollback, then write the new ones over it.
fs.cpSync(dest, backup, { recursive: true });
entry.backup = backup;
entry.inPlace = true;
journalRecord(root, { op: 'backup-created', scope, operationId, skill: name, source: dest, destination: backup, extra: { inPlace: true } });
replaceInPlace(path.join(stage.stageDir, name), dest);
entry.swapped = true;
journalRecord(root, { op: 'canonical-swapped', scope, operationId, skill: name, source: path.join(stage.stageDir, name), destination: dest, extra: { inPlace: true } });
if (hooks.afterSwap) hooks.afterSwap(name);
continue;
}
entry.backup = backup;
journalRecord(root, { op: 'backup-created', scope, operationId, skill: name, source: dest, destination: backup });
}
rename(path.join(stage.stageDir, name), dest);
entry.swapped = true;
journalRecord(root, { op: 'canonical-swapped', scope, operationId, skill: name, source: path.join(stage.stageDir, name), destination: dest });
if (hooks.afterSwap) hooks.afterSwap(name);
}
// Checked and recorded inside the swap, so a mismatch or a failed manifest write rolls back too.
verifySwapped(stage);
writeJsonAtomic(manifestPath(root), { version: stage.manifest.version, sourceRef: stage.manifest.sourceRef, complete: true, skills: stage.skills, journal: null });
} catch (err) {
const rollbackErrors = [];
for (const entry of done.reverse()) {
try {
restoreEntry(entry, root, rename);
journalRecord(root, { op: 'rolled-back', scope, operationId, skill: entry.name, source: entry.backup, destination: path.join(root, entry.name) });
} catch (restoreErr) {
rollbackErrors.push(`${entry.name}: ${restoreErr.message}`);
}
}
if (rollbackErrors.length === 0) {
// Everything is back as it was, so the old manifest is true again.
try {
if (previousManifest) writeJsonAtomic(manifestPath(root), previousManifest);
else fs.rmSync(manifestPath(root), { force: true });
} catch {}
removeQuietly(stage.stageDir, []);
removeQuietly(backupDir, []);
}
throw canonicalError('commit-failed', `Could not swap the skills into ${root}: ${err.message}`, { retryable: true, cause: err, rollbackErrors });
}
return finalizeCommit(stage, backupDir);
}
/**
* The last step of a swap, once the store matched the stage and the complete manifest
* `{ version, sourceRef, complete: true, skills, journal: null }` is written: record `committed`,
* then clear the stage, the backups and the journal. A cleanup that fails is a warning only: the
* store is already complete.
*/
function verifySwapped(stage) {
for (const name of stage.names) {
if (skillTreeHash(path.join(stage.root, name)) !== stage.skills[name]) {
throw canonicalError('commit-mismatch', `${name} in ${stage.root} does not match what was staged`, { retryable: true });
}
}
}
function finalizeCommit(stage, backupDir) {
const { root, scope, operationId } = stage;
const warnings = [];
try {
journalRecord(root, { op: 'committed', scope, operationId, source: stage.stageDir, destination: root });
} catch (err) {
warnings.push(`Could not record the finished swap: ${err.message}`);
}
removeQuietly(stage.stageDir, warnings);
if (backupDir) removeQuietly(backupDir, warnings);
try {
removeJournal(root);
} catch (err) {
warnings.push(`Could not remove the journal: ${err.message}`);
}
return { complete: true, root, skills: stage.skills, warnings };
}
// ---------------------------------------------------------------------------------------------
// Reconcile
// ---------------------------------------------------------------------------------------------
/**
* Whether an earlier run left anything beside a scope's store: a journal, a stage (a run killed
* mid-copy leaves one before its first journal record) or a backup folder.
*/
function hasCanonicalResidue(scope, cwd = process.cwd(), home = os.homedir()) {
const root = canonicalRoot(scope, cwd, home);
const left = residue(root);
return fs.existsSync(journalPath(root)) || left.stages.length > 0 || left.backups.length > 0;
}
/** Whether `pid` is another process that is still running (console-stage.js's rule). */
function otherProcessAlive(pid) {
if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid) return false;
try {
process.kill(pid, 0);
return true;
} catch (err) {
return err.code === 'EPERM';
}
}
/** The pid in a stage or backup folder's name (`<prefix><pid>-<timestamp>`), or null. */
function residuePid(name, prefix) {
const match = /^(\d+)-\d+$/.exec(name.slice(prefix.length));
return match ? Number(match[1]) : null;
}
/**
* Stage and backup folders left beside the store, by kind. A folder whose install is still running
* in another process (the app's update beside a terminal's, say) is not residue: it is counted in
* `live` and never touched, so two installs at once cannot delete each other's work.
*/
function residue(root) {
const parent = path.dirname(root);
let names = [];
try {
names = fs.readdirSync(parent);
} catch {}
let live = 0;
const left = (prefix) =>
names
.filter((n) => n.startsWith(prefix))
.filter((n) => {
if (!otherProcessAlive(residuePid(n, prefix))) return true;
live++;
return false;
})
.map((n) => path.join(parent, n));
const stages = left(STAGE_PREFIX);
const backups = left(BACKUP_PREFIX);
return { stages, backups, live };
}
/**
* After an interruption, put back each backed-up expected skill whose canonical folder is gone
* (the swap stopped between moving the old copy out and the new one in). Returns the names restored.
*/
function restoreOrphanedBackups(root, backups, expectedNames) {
const expected = new Set(expectedNames);
const restored = [];
for (const backupDir of backups) {
let names = [];
try {
names = fs.readdirSync(backupDir);
} catch {}
for (const name of names) {
const dest = path.join(root, name);
if (!expected.has(name) || lstatOrNull(dest)) continue;
try {
fs.mkdirSync(root, { recursive: true });
renameWithRetry(path.join(backupDir, name), dest);
restored.push(name);
} catch {}
}
}
return restored;
}
/** Whether `builtDir` holds a folder for every expected skill. */
function builtSourceAvailable(builtDir, expectedNames) {
if (!builtDir) return false;
return expectedNames.every((name) => {
const stat = lstatOrNull(path.join(builtDir, name));
return Boolean(stat && stat.isDirectory() && !stat.isSymbolicLink());
});
}
/**
* Find and repair what an interrupted or damaged install left: stage folders, an unfinished
* journal, backups, skills that changed on disk or are missing. A complete store with nothing
* left over returns `{ complete: true }` without copying anything. Otherwise orphaned backups
* are put back first; then, with the built skills at hand, the store is staged and committed
* again (`repaired: true`), or, without them, `{ complete: false, issues }` says what is wrong.
* Leftover stages, backups and journal are removed only once the store is complete.
*/
function reconcileCanonicalSkills(scope, builtDir, expectedNames, { cwd = process.cwd(), home = os.homedir(), version = null, sourceRef = null } = {}) {
const root = canonicalRoot(scope, cwd, home);
const issues = [];
const left = residue(root);
if (left.stages.length) issues.push(`${left.stages.length} unfinished stage(s)`);
if (left.backups.length) issues.push(`${left.backups.length} backup folder(s)`);
if (fs.existsSync(journalPath(root))) issues.push('an unfinished journal');
const restored = restoreOrphanedBackups(root, left.backups, expectedNames);
if (restored.length) issues.push(`restored ${restored.join(', ')} from a backup`);
const check = validateCanonicalManifest(scope, expectedNames, { cwd, home, version });
issues.push(...check.problems);
const clearResidue = () => {
const warnings = [];
for (const dir of [...left.stages, ...left.backups]) removeQuietly(dir, warnings);
// The journal is shared: while another install is running, it is that install's to clear.
if (left.live === 0) {
try {
removeJournal(root);
} catch (err) {
warnings.push(`Could not remove the journal: ${err.message}`);
}
}
return warnings;
};
if (check.complete) {
if (issues.length === 0) return { complete: true, repaired: false, issues };
return { complete: true, repaired: false, issues, warnings: clearResidue() };
}
if (!builtSourceAvailable(builtDir, expectedNames)) return { complete: false, repaired: false, issues };
const stage = stageCanonicalSkills({ scope, builtDir, expectedNames, cwd, home, version, sourceRef });
const committed = commitCanonicalSkills(stage);
return { complete: true, repaired: true, issues, warnings: [...committed.warnings, ...clearResidue()] };
}
// ---------------------------------------------------------------------------------------------
// Retired skills
// ---------------------------------------------------------------------------------------------
/**
* The Plan2Code skills in a scope's store this build no longer has: every entry whose name
* starts with `plan2code` and is not expected (folders, stray copies without a SKILL.md, and
* links). Expected names are always kept.
*/
function retiredSkillNames(scope, expectedNames, { cwd = process.cwd(), home = os.homedir() } = {}) {
const root = canonicalRoot(scope, cwd, home);
const keep = new Set(expectedNames);
let names = [];
try {
names = fs.readdirSync(root);
} catch {}
return names.filter((name) => OUR_NAME.test(name) && !keep.has(name) && SKILL_NAME.test(name)).sort();
}
/**
* Remove retired skills from the store, once the skills CLI has been asked to unlink them: a link
* is unlinked itself, a folder removed. Returns `{ removed, warnings }`.
*/
function removeRetiredCanonical(scope, retiredNames, { cwd = process.cwd(), home = os.homedir() } = {}) {
const root = canonicalRoot(scope, cwd, home);
const removed = [];
const warnings = [];
for (const name of retiredNames) {
if (!OUR_NAME.test(name) || !SKILL_NAME.test(name)) continue;
const entry = path.join(root, name);
const stat = lstatOrNull(entry);
if (!stat) continue;
try {
if (stat.isSymbolicLink()) fs.unlinkSync(entry);
else fs.rmSync(entry, { recursive: true, force: true });
removed.push(name);
} catch (err) {
warnings.push(`Could not remove ${entry}: ${err.message}`);
}
}
return { removed, warnings };
}
/** Unlink every `plan2code*` link in the store whose target is gone (the link itself, never what it pointed at). */
function sweepBrokenLinks(scope, { cwd = process.cwd(), home = os.homedir() } = {}) {
const root = canonicalRoot(scope, cwd, home);
const removed = [];
let names = [];
try {
names = fs.readdirSync(root);
} catch {}
for (const name of names) {
if (!OUR_NAME.test(name)) continue;
const entry = path.join(root, name);
const stat = lstatOrNull(entry);
if (!stat || !stat.isSymbolicLink() || fs.existsSync(entry)) continue;
try {
fs.unlinkSync(entry);
removed.push(name);
} catch {}
}
return removed;
}
/**
* Everything this module adds beside a store, for an uninstall: the manifest, the journal and any
* stage or backup folder an interrupted run left. Skill folders are the caller's to remove.
* Returns `{ removed, failed }` (paths, and `path: message` lines).
*/
function removeCanonicalMetadata(root) {
const result = { removed: [], failed: [] };
const targets = [manifestPath(root), journalPath(root)];
try {
for (const name of fs.readdirSync(path.dirname(root))) {
if (name.startsWith(STAGE_PREFIX) || name.startsWith(BACKUP_PREFIX)) targets.push(path.join(path.dirname(root), name));
}
} catch {}
for (const target of targets) {
if (!lstatOrNull(target)) continue;
try {
fs.rmSync(target, { recursive: true, force: true });
result.removed.push(target);
} catch (err) {
result.failed.push(`${target}: ${err.message}`);
}
}
return result;
}
module.exports = {
removeCanonicalMetadata,
MANIFEST_NAME,
JOURNAL_NAME,
canonicalRoot,
journalPath,
readJournal,
journalRecord,
stageCanonicalSkills,
commitCanonicalSkills,
reconcileCanonicalSkills,
hasCanonicalResidue,
validateCanonicalManifest,
readCanonicalManifest,
retiredSkillNames,
removeRetiredCanonical,
sweepBrokenLinks,
skillTreeHash,
};
+470
View File
@@ -0,0 +1,470 @@
'use strict';
// The shared console, installed as one validated folder per version: the built tree is copied
// into a stage beside the version folder, checked byte for byte, marked complete last, then
// renamed into place with the old folder kept as a backup until the new one validates. A folder a
// running server holds open is replaced in place instead, and says so. Zero dependencies, CommonJS.
//
// Layout, under the console home (~/.plan2code/console, or PLAN2CODE_CONSOLE_HOME):
// <version>/ the installed console
// <version>/.plan2code-console-manifest.json every file with its sha256 and byte count
// <version>/.complete written last: the version and when
// <version>.install-<pid>-<timestamp>/ a stage, while it is built
// <version>.backup-<pid>-<timestamp>/ the replaced folder, while a swap runs
// console-dir the path of the current version folder
// Nothing else in the home (sessions/, looks.json, workspaces.json, runtime files) is touched.
const crypto = require('crypto');
const fs = require('fs');
const os = require('os');
const path = require('path');
const MANIFEST_NAME = '.plan2code-console-manifest.json';
const COMPLETE_NAME = '.complete';
const POINTER_NAME = 'console-dir';
const MANIFEST_VERSION = 1;
const VERSION_DIR = /^\d+\.\d+\.\d+$/;
const RESIDUE = /^(\d+\.\d+\.\d+)\.(install|backup)-(\d+)-(\d+)$/;
// The codes a rename gets when a running server or the platform holds the folder open.
const LOCKED = new Set(['EPERM', 'EACCES', 'EBUSY']);
const RENAME_ATTEMPTS = 8;
const DEFAULT_OPS = {
rename: (from, to) => fs.renameSync(from, to),
rm: (target, options) => fs.rmSync(target, options),
cp: (from, to, options) => fs.cpSync(from, to, options),
};
/**
* The folder the shared console lives in: PLAN2CODE_CONSOLE_HOME when set (the console's own
* override, which the tests use), else ~/.plan2code/console. Read when called, never at load.
*/
function consoleHomeDir(env = process.env) {
return env.PLAN2CODE_CONSOLE_HOME || path.join(os.homedir(), '.plan2code', 'console');
}
/** An error with a `code` the installer can name. */
function consoleError(code, message, extra = {}) {
return Object.assign(new Error(message), { code }, extra);
}
function lstatOrNull(file) {
try {
return fs.lstatSync(file);
} catch {
return null;
}
}
function readJson(file) {
try {
return JSON.parse(fs.readFileSync(file, 'utf8'));
} catch {
return null;
}
}
function sha256(buffer) {
return crypto.createHash('sha256').update(buffer).digest('hex');
}
function assertVersion(version) {
if (typeof version !== 'string' || !VERSION_DIR.test(version)) {
throw consoleError('bad-version', `Refusing console version ${JSON.stringify(version)}: not x.y.z`);
}
}
/** Block for `ms` milliseconds without spinning. */
function pause(ms) {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
/** A rename, retried with a growing pause while Windows reports the folder busy for a moment. */
function renameWithRetry(rename, from, to) {
for (let attempt = 1; ; attempt++) {
try {
rename(from, to);
return;
} catch (err) {
if (process.platform !== 'win32' || !LOCKED.has(err.code) || attempt >= RENAME_ATTEMPTS) throw err;
pause(10 * attempt);
}
}
}
/** Write text through a temp file and a rename, so a reader never sees half a file. */
function writeFileAtomic(file, text) {
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
try {
fs.writeFileSync(tmp, text);
renameWithRetry(DEFAULT_OPS.rename, tmp, file);
} catch (err) {
try {
fs.rmSync(tmp, { force: true });
} catch {}
throw err;
}
}
/** Remove a folder, adding a warning line instead of throwing. */
function removeQuietly(dir, warnings, rm = DEFAULT_OPS.rm) {
try {
rm(dir, { recursive: true, force: true });
return true;
} catch (err) {
warnings.push(`Could not remove ${dir}: ${err.message}`);
return false;
}
}
/**
* Every regular file under `dir` as sorted forward-slash paths relative to it, leaving out the
* two markers at its top. A link anywhere is refused rather than followed.
*/
function listTree(dir) {
const files = [];
const walk = (current, rel) => {
for (const name of fs.readdirSync(current).sort()) {
if (!rel && (name === MANIFEST_NAME || name === COMPLETE_NAME)) continue;
const full = path.join(current, name);
const relPath = rel ? `${rel}/${name}` : name;
const stat = fs.lstatSync(full);
if (stat.isSymbolicLink()) throw consoleError('link-in-tree', `Refusing ${full}: links are not copied`);
if (stat.isDirectory()) walk(full, relPath);
else if (stat.isFile()) files.push(relPath);
else throw consoleError('special-file', `Refusing ${full}: not a regular file`);
}
};
walk(dir, '');
return files.sort();
}
/**
* Check a console folder against its own manifest: `{ complete, problems, manifest, marker }`.
* Complete means a manifest for `version`, every file it lists present with its byte count and
* hash, and a `.complete` for the same version. `hashes: false` checks the byte counts only, for a
* folder whose bytes were already hashed and only renamed since.
*/
function verifyConsoleDir(dir, version, { hashes = true } = {}) {
const problems = [];
const manifest = readJson(path.join(dir, MANIFEST_NAME));
const marker = readJson(path.join(dir, COMPLETE_NAME));
if (!manifest || !Array.isArray(manifest.files)) problems.push('no manifest');
else {
if (manifest.version !== version) problems.push(`manifest is for ${manifest.version || 'no version'}`);
for (const entry of manifest.files) {
const file = path.join(dir, ...String(entry.path).split('/'));
const stat = lstatOrNull(file);
if (!stat || !stat.isFile()) problems.push(`${entry.path}: missing`);
else if (stat.size !== entry.bytes || (hashes && sha256(fs.readFileSync(file)) !== entry.sha256)) problems.push(`${entry.path}: changed on disk`);
}
}
if (!marker) problems.push('no .complete');
else if (marker.version !== version) problems.push(`.complete is for ${marker.version || 'no version'}`);
return { complete: problems.length === 0, problems, manifest, marker };
}
/** A folder from before the markers: valid only with console.mjs and its version in version.txt or version.json. */
function preMarkerValid(dir, version) {
if (!fs.existsSync(path.join(dir, 'console.mjs'))) return false;
let text = null;
try {
text = fs.readFileSync(path.join(dir, 'version.txt'), 'utf8').trim();
} catch {}
if (text === version) return true;
const json = readJson(path.join(dir, 'version.json'));
return Boolean(json && json.version === version);
}
/**
* How one version folder stands: `{ state, problems }`, state `missing`, `complete` (markers that
* verify), `pre-marker` (no markers, but console.mjs and a matching version file) or `incomplete`.
*/
function destState(dir, version) {
const stat = lstatOrNull(dir);
if (!stat) return { state: 'missing', problems: ['not installed'] };
if (stat.isSymbolicLink() || !stat.isDirectory()) return { state: 'incomplete', problems: ['not a plain folder'] };
const hasMarkers = fs.existsSync(path.join(dir, MANIFEST_NAME)) || fs.existsSync(path.join(dir, COMPLETE_NAME));
if (!hasMarkers) {
return preMarkerValid(dir, version)
? { state: 'pre-marker', problems: [] }
: { state: 'incomplete', problems: ['no .complete, and no console.mjs with a matching version file'] };
}
const verified = verifyConsoleDir(dir, version);
return verified.complete ? { state: 'complete', problems: [] } : { state: 'incomplete', problems: verified.problems };
}
/** Whether the folder for `version` is a usable console: complete with markers, or a valid pre-marker one. */
function isCompleteConsoleInstall({ version, home = consoleHomeDir() } = {}) {
assertVersion(version);
const { state } = destState(path.join(home, version), version);
return state === 'complete' || state === 'pre-marker';
}
/** The stages and backups an earlier run left in the home, each `{ name, dir, version, kind, pid }`. */
function listResidue(home) {
let entries = [];
try {
entries = fs.readdirSync(home, { withFileTypes: true });
} catch {
return [];
}
const found = [];
for (const entry of entries) {
const m = RESIDUE.exec(entry.name);
if (!m || !entry.isDirectory()) continue;
found.push({ name: entry.name, dir: path.join(home, entry.name), version: m[1], kind: m[2], pid: Number(m[3]), at: Number(m[4]) });
}
return found.sort((a, b) => b.at - a.at);
}
/** Whether another process with this pid is running (a concurrent install still building its stage). */
function otherProcessAlive(pid) {
if (pid === process.pid) return false;
try {
process.kill(pid, 0);
return true;
} catch (err) {
return err.code === 'EPERM';
}
}
function readPointer(home) {
try {
return fs.readFileSync(path.join(home, POINTER_NAME), 'utf8').trim() || null;
} catch {
return null;
}
}
/**
* Everything about the console install for `version`: `{ version, home, dest, state, complete,
* problems, staging, backups, pointer, pointerOk }`. `staging` lists stages left behind for any
* version (never usable once their run ended), `backups` the backups of this version. Complete
* means a usable folder, `console-dir` naming it, and no stage or backup of this version left.
*/
function consoleInstallState({ version, home = consoleHomeDir() } = {}) {
assertVersion(version);
const dest = path.join(home, version);
const { state, problems } = destState(dest, version);
const residue = listResidue(home);
const staging = residue.filter((r) => r.kind === 'install');
const backups = residue.filter((r) => r.kind === 'backup' && r.version === version);
const pointer = readPointer(home);
const pointerOk = pointer !== null && path.resolve(pointer) === path.resolve(dest);
const all = [...problems];
if (!pointerOk) all.push(pointer ? `console-dir names ${pointer}` : 'no console-dir');
for (const s of staging.filter((r) => r.version === version)) all.push(`an interrupted copy is left in ${s.name}`);
for (const b of backups) all.push(`a backup is left in ${b.name}`);
const usable = state === 'complete' || state === 'pre-marker';
return { version, home, dest, state, complete: usable && all.length === 0, problems: all, staging, backups, pointer, pointerOk };
}
/** A new, empty `<version>.install-<pid>-<timestamp>` folder; a name taken in the same millisecond moves on a step. */
function makeStageDir(home, version) {
const start = Date.now();
for (let step = 0; ; step++) {
const stageDir = path.join(home, `${version}.install-${process.pid}-${start + step}`);
try {
fs.mkdirSync(stageDir);
return stageDir;
} catch (err) {
if (err.code !== 'EEXIST' || step >= 9) throw err;
}
}
}
/**
* Copy the built console at `source` into `<version>.install-<pid>-<timestamp>` under `home`, write
* the manifest, check every copied file against it, and only then write `.complete`. Refuses a
* source without console.mjs; a failed stage is removed. Returns `{ stageDir, home, version, dest,
* source, manifest }`.
*/
function stageConsole({ version, source, home = consoleHomeDir() } = {}) {
assertVersion(version);
if (!source || !fs.existsSync(path.join(source, 'console.mjs'))) throw consoleError('not-built', `${source} is not built`);
fs.mkdirSync(home, { recursive: true });
const stageDir = makeStageDir(home, version);
try {
const files = [];
for (const rel of listTree(source)) {
const from = path.join(source, ...rel.split('/'));
const to = path.join(stageDir, ...rel.split('/'));
fs.mkdirSync(path.dirname(to), { recursive: true });
// copyFileSync, not a write of the bytes read: on Windows the platform copy is several
// times faster than writing each new file, and the hash below still checks the copy.
fs.copyFileSync(from, to);
const bytes = fs.readFileSync(from);
files.push({ path: rel, sha256: sha256(bytes), bytes: bytes.length });
}
const manifest = { manifestVersion: MANIFEST_VERSION, version, files };
fs.writeFileSync(path.join(stageDir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + '\n');
// The copy is checked before the marker goes in: a stage without .complete is never used.
for (const entry of files) {
const copied = path.join(stageDir, ...entry.path.split('/'));
const stat = lstatOrNull(copied);
if (!stat || !stat.isFile() || stat.size !== entry.bytes || sha256(fs.readFileSync(copied)) !== entry.sha256) {
throw consoleError('stage-mismatch', `The staged copy of ${entry.path} does not match the build`);
}
}
fs.writeFileSync(path.join(stageDir, COMPLETE_NAME), JSON.stringify({ version, completedAt: new Date().toISOString() }) + '\n');
return { stageDir, home, version, dest: path.join(home, version), source, manifest };
} catch (err) {
removeQuietly(stageDir, []);
throw err;
}
}
/**
* Finish or undo what an earlier run left for `version` before a new commit: remove stages that
* are not `keep` (and not still being built by another running install); with a complete folder
* in place remove its backups; with none, put the newest backup that is usable back. Returns
* `{ removed, restored, warnings }`.
*/
function recoverConsoleInstall({ version, home, keep = null, ops = DEFAULT_OPS }) {
const warnings = [];
const removed = [];
let restored = null;
for (const stage of listResidue(home).filter((r) => r.kind === 'install')) {
if (keep && path.resolve(stage.dir) === path.resolve(keep)) continue;
if (otherProcessAlive(stage.pid)) continue;
if (removeQuietly(stage.dir, warnings, ops.rm)) removed.push(stage.name);
}
const dest = path.join(home, version);
const backups = listResidue(home).filter((r) => r.kind === 'backup' && r.version === version);
const { state } = destState(dest, version);
if (state !== 'complete' && state !== 'pre-marker') {
const usable = backups.find((b) => {
const s = destState(b.dir, version).state;
return s === 'complete' || s === 'pre-marker';
});
if (usable) {
try {
if (state !== 'missing') ops.rm(dest, { recursive: true, force: true });
renameWithRetry(ops.rename, usable.dir, dest);
restored = usable.name;
} catch (err) {
warnings.push(`Could not put back the backup ${usable.name}: ${err.message}`);
}
}
}
if (restored || state === 'complete' || state === 'pre-marker') {
for (const b of backups) {
if (b.name === restored) continue;
if (removeQuietly(b.dir, warnings, ops.rm)) removed.push(b.name);
}
}
return { removed, restored, warnings };
}
/**
* Remove the stages and backups other versions left behind (an update interrupted on its way to a
* version that never went in), keeping `keepVersion`'s, which commitConsole() recovers, and any
* stage another running install is still building. Returns `{ removed, warnings }`.
*/
function sweepConsoleResidue({ home = consoleHomeDir(), keepVersion } = {}) {
const warnings = [];
const removed = [];
for (const entry of listResidue(home)) {
if (entry.version === keepVersion || otherProcessAlive(entry.pid)) continue;
if (removeQuietly(entry.dir, warnings)) removed.push(entry.name);
}
return { removed, warnings };
}
/** The in-place copy for a folder that cannot be renamed: everything but .complete, then .complete. */
function copyInPlace(stage, ops) {
try {
ops.rm(stage.dest, { recursive: true, force: true });
} catch {
// A running server holds files open on Windows: the copy below overwrites them in place.
}
ops.cp(stage.stageDir, stage.dest, { recursive: true, force: true, filter: (from) => path.basename(from) !== COMPLETE_NAME || path.dirname(from) !== stage.stageDir });
ops.cp(path.join(stage.stageDir, COMPLETE_NAME), path.join(stage.dest, COMPLETE_NAME), { force: true });
}
/**
* Put a validated stage in place as `<version>`. With no folder there the stage is renamed in;
* with one, it is renamed to `<version>.backup-<pid>-<timestamp>`, the stage renamed in, and the
* backup removed once the new folder validates. A rename a lock refuses falls back to copying the
* stage over the folder in place, verified the same way (`fallbackUsed`, with a warning). Leftovers
* from an earlier run are recovered first. `console-dir` is written through a temp file and a
* rename. Returns `{ committed, dest, backupDir, fallbackUsed, warnings, recovered }`.
*/
function commitConsole(stage, { ops: given = {} } = {}) {
const ops = { ...DEFAULT_OPS, ...given };
const { version, home, dest, stageDir } = stage;
assertVersion(version);
// stageConsole() hashed every copied file; here the stage only has to be whole still.
const stageCheck = verifyConsoleDir(stageDir, version, { hashes: false });
if (!stageCheck.complete) throw consoleError('stage-invalid', `The staged console is not complete: ${stageCheck.problems.join('; ')}`);
const recovered = recoverConsoleInstall({ version, home, keep: stageDir, ops });
const warnings = [...recovered.warnings];
let backupDir = null;
let fallbackUsed = false;
const fallback = (err) => {
if (!LOCKED.has(err.code)) throw err;
copyInPlace(stage, ops);
fallbackUsed = true;
warnings.push(`The console in ${dest} is in use (${err.code}), so it was copied over in place instead of swapped; restart any open console to use the new one`);
};
if (!lstatOrNull(dest)) {
try {
renameWithRetry(ops.rename, stageDir, dest);
} catch (err) {
fallback(err);
}
} else {
const candidate = path.join(home, `${version}.backup-${process.pid}-${Date.now()}`);
let movedAside = false;
try {
renameWithRetry(ops.rename, dest, candidate);
movedAside = true;
backupDir = candidate;
renameWithRetry(ops.rename, stageDir, dest);
} catch (err) {
if (movedAside && !lstatOrNull(dest)) {
try {
renameWithRetry(ops.rename, candidate, dest);
backupDir = null;
} catch {
// The backup stays beside the folder; the next run puts it back.
}
}
fallback(err);
}
}
// A rename moves the hashed stage as it is; a copy in place is hashed again.
const check = verifyConsoleDir(dest, version, { hashes: fallbackUsed });
if (!check.complete) {
if (backupDir && lstatOrNull(backupDir)) {
try {
ops.rm(dest, { recursive: true, force: true });
renameWithRetry(ops.rename, backupDir, dest);
backupDir = null;
} catch {}
}
throw consoleError('commit-invalid', `The installed console in ${dest} did not validate: ${check.problems.join('; ')}`);
}
if (backupDir && lstatOrNull(backupDir)) removeQuietly(backupDir, warnings, ops.rm);
if (lstatOrNull(stageDir)) removeQuietly(stageDir, warnings, ops.rm);
writeFileAtomic(path.join(home, POINTER_NAME), `${dest}\n`);
return { committed: true, dest, backupDir, fallbackUsed, warnings, recovered };
}
module.exports = {
MANIFEST_NAME,
COMPLETE_NAME,
POINTER_NAME,
consoleHomeDir,
stageConsole,
commitConsole,
consoleInstallState,
isCompleteConsoleInstall,
verifyConsoleDir,
sweepConsoleResidue,
};
+248
View File
@@ -0,0 +1,248 @@
'use strict';
// The adaptive skills CLI runner: which exact `skills` version this Node can run, where npx
// already cached that version, and how to run it. Zero dependencies, CommonJS, so install.js can
// require it from a fresh npx copy before anything else is installed.
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawn, spawnSync } = require('child_process');
// Exact pins only, never `latest` or a range: a new skills release can never change an install
// between two runs of the same Plan2Code. 1.7.x needs Node 22.20.0+, so older Node (down to
// Plan2Code's own Node 18 floor) runs the last 1.5.x.
const SKILLS_CLI_PINS = Object.freeze({ legacy: '1.5.18', current: '1.7.6', nodeFloor: '22.20.0' });
/**
* `{ numbers: [major, minor, patch], prerelease }` from a version like `v22.20.0` or
* `22.20.0-rc.1`, or null when it is not one.
*/
function parseVersion(version) {
const match = /^v?(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?/.exec(String(version || '').trim());
return match ? { numbers: [Number(match[1]), Number(match[2]), Number(match[3])], prerelease: Boolean(match[4]) } : null;
}
/** Negative, zero or positive as `a` is below, equal to or above `b` (both `[major, minor, patch]`). */
function compareVersions(a, b) {
for (let i = 0; i < 3; i++) {
if (a[i] !== b[i]) return a[i] - b[i];
}
return 0;
}
/**
* The skills CLI version for this Node: the legacy pin below the floor (or an unreadable version),
* the current one at or above it. A prerelease of the floor itself (`22.20.0-rc.1`) is below it,
* as semver orders them.
*/
function selectSkillsCliVersion(nodeVersion = process.versions.node) {
const node = parseVersion(nodeVersion);
const floor = parseVersion(SKILLS_CLI_PINS.nodeFloor);
if (!node) return SKILLS_CLI_PINS.legacy;
const order = compareVersions(node.numbers, floor.numbers);
return order > 0 || (order === 0 && !node.prerelease) ? SKILLS_CLI_PINS.current : SKILLS_CLI_PINS.legacy;
}
/** A value from `env` by its name in any case (Windows environments are case-insensitive). */
function envValue(env, name) {
if (!env) return '';
if (typeof env[name] === 'string' && env[name]) return env[name];
const wanted = name.toLowerCase();
for (const [key, value] of Object.entries(env)) {
if (key.toLowerCase() === wanted && typeof value === 'string' && value) return value;
}
return '';
}
/**
* The npm cache folders to look in, most likely first: `npm_config_cache` when set, then the
* platform default (`%LocalAppData%/npm-cache` on Windows, `~/.npm` elsewhere), then the
* `%AppData%/npm-cache` older npm versions used on Windows. Pure: reads only its arguments.
*/
function npmCacheCandidates(env = process.env, platform = process.platform, home = os.homedir()) {
const join = platform === 'win32' ? path.win32.join : path.posix.join;
const candidates = [];
const configured = envValue(env, 'npm_config_cache');
if (configured) candidates.push(configured);
if (platform === 'win32') {
candidates.push(join(envValue(env, 'LOCALAPPDATA') || join(home, 'AppData', 'Local'), 'npm-cache'));
candidates.push(join(envValue(env, 'APPDATA') || join(home, 'AppData', 'Roaming'), 'npm-cache'));
} else {
candidates.push(join(home, '.npm'));
}
return [...new Set(candidates)];
}
/** A JSON file's contents, or null when it is missing or not JSON. */
function readJson(file) {
try {
return JSON.parse(fs.readFileSync(file, 'utf8'));
} catch {
return null;
}
}
/**
* The CLI file of a cached `skills@<pin>` in one npx folder (`<cache>/_npx/<hash>`), or null.
* The package must name exactly the pin, carry bin/cli.mjs, and have each dependency it declares
* installed beside it: a half-written cache entry is no hit.
*/
function cachedCliIn(npxDir, pin) {
const modules = path.join(npxDir, 'node_modules');
const pkg = readJson(path.join(modules, 'skills', 'package.json'));
if (!pkg || pkg.version !== pin) return null;
const cliFile = path.join(modules, 'skills', 'bin', 'cli.mjs');
try {
if (!fs.statSync(cliFile).isFile()) return null;
} catch {
return null;
}
const deps = pkg.dependencies && typeof pkg.dependencies === 'object' ? Object.keys(pkg.dependencies) : [];
for (const dep of deps) {
if (!fs.existsSync(path.join(modules, ...dep.split('/'), 'package.json'))) return null;
}
return cliFile;
}
/**
* How to run `skills@<pin>`: straight from npx's cache when an exact copy is already there
* (`{ kind: "cached", executable, argsPrefix: [cliFile], pin }`), otherwise through npx
* (`{ kind: "npx", command: "npx", argsPrefix: ["--yes", "skills@<pin>"], pin }`). The cache
* is only a shortcut: the npx folder names are npm's private hashes, so every one is scanned,
* and anything unreadable falls back to npx.
*/
function resolveSkillsCli(pin, options = {}) {
const { env = process.env, platform = process.platform, home = os.homedir(), execPath = process.execPath } = options;
const caches = options.caches || npmCacheCandidates(env, platform, home);
for (const cache of caches) {
const npxRoot = path.join(cache, '_npx');
let entries;
try {
entries = fs.readdirSync(npxRoot, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries.filter((e) => e.isDirectory()).map((e) => e.name).sort()) {
const cliFile = cachedCliIn(path.join(npxRoot, entry), pin);
if (cliFile) return { kind: 'cached', executable: execPath, argsPrefix: [cliFile], pin };
}
}
return { kind: 'npx', command: 'npx', argsPrefix: ['--yes', `skills@${pin}`], pin };
}
/** One argument quoted for cmd.exe when it needs it (spaces or cmd's special characters). */
function quoteForCmd(arg) {
const text = String(arg);
if (text && !/[\s"&|<>^()%!]/.test(text)) return text;
return `"${text.replace(/"/g, '""')}"`;
}
/**
* What to spawn for `cli` and `args`: `{ file, args, shell }`. The cached CLI runs node directly
* with an argument list, so nothing passes through a shell. npx on Windows is npx.cmd, which
* only a shell can start, so there the whole line is quoted for cmd.exe; elsewhere npx is a
* plain executable and runs without a shell too.
*/
function spawnPlan(cli, args, platform = process.platform) {
const full = [...cli.argsPrefix, ...args];
if (cli.kind === 'cached') return { file: cli.executable, args: full, shell: false };
if (platform === 'win32') return { file: [cli.command, ...full].map(quoteForCmd).join(' '), args: [], shell: true };
return { file: cli.command, args: full, shell: false };
}
/** The environment a CLI run gets: the caller's, with npm's `npm notice` lines kept quiet. */
function cliEnv(env = process.env) {
return { ...env, npm_config_loglevel: 'error' };
}
/**
* Run the CLI and wait: `{ ok, output }`, the trimmed stdout on success, stdout and stderr
* together on a failure. Output is captured, never streamed: the CLI prints a banner and a box
* per agent that the installer's own summary replaces.
*/
function execSkillsCliSyncOnce(cli, args, { env = process.env, platform = process.platform, cwd } = {}) {
const plan = spawnPlan(cli, args, platform);
const result = spawnSync(plan.file, plan.args, {
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'pipe'],
env: cliEnv(env),
shell: plan.shell,
windowsHide: true,
cwd,
});
const stdout = result.stdout || '';
const stderr = result.stderr || '';
if (result.error) return { ok: false, output: `${stdout}\n${stderr || result.error.message}`.trim() };
return result.status === 0 ? { ok: true, output: stdout.trim() } : { ok: false, output: `${stdout}\n${stderr}`.trim() };
}
/** execSkillsCliSync without blocking, so a spinner can tick while the CLI works. Same `{ ok, output }`. */
function execSkillsCliAsyncOnce(cli, args, { env = process.env, platform = process.platform, cwd } = {}) {
return new Promise((resolve) => {
const plan = spawnPlan(cli, args, platform);
let stdout = '';
let stderr = '';
let child;
try {
child = spawn(plan.file, plan.args, {
shell: plan.shell,
stdio: ['pipe', 'pipe', 'pipe'],
env: cliEnv(env),
windowsHide: true,
cwd,
});
} catch (err) {
resolve({ ok: false, output: err.message });
return;
}
child.stdin.end();
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.on('error', (err) => resolve({ ok: false, output: `${stdout}\n${stderr || err.message}`.trim() }));
child.on('close', (code) => {
resolve(code === 0 ? { ok: true, output: stdout.trim() } : { ok: false, output: `${stdout}\n${stderr}`.trim() });
});
});
}
/** The command a person can paste to run the same thing by hand: always the npx form, with the pin. */
function skillsCliDisplay(pin) {
return `npx --yes skills@${pin}`;
}
// A cached copy npm pruned part of (a dependency gone from its node_modules) fails before it does
// anything; that copy is never fixed by running it again, so the same pin goes through npx instead.
const BROKEN_CACHED_CLI = /Cannot find (?:module|package)|ERR_MODULE_NOT_FOUND|MODULE_NOT_FOUND/;
/** The npx form of a cached CLI, for when the cached copy is broken. */
function npxFallback(cli) {
return { kind: 'npx', command: 'npx', argsPrefix: ['--yes', `skills@${cli.pin}`], pin: cli.pin };
}
/** Run the CLI and wait: `{ ok, output }`. A broken cached copy is retried once through npx. */
function execSkillsCliSync(cli, args, options = {}) {
const result = execSkillsCliSyncOnce(cli, args, options);
if (result.ok || cli.kind !== 'cached' || !BROKEN_CACHED_CLI.test(result.output)) return result;
return execSkillsCliSyncOnce(options.fallback || npxFallback(cli), args, options);
}
/** Run the CLI without blocking: resolves `{ ok, output }`. A broken cached copy is retried once through npx. */
async function execSkillsCliAsync(cli, args, options = {}) {
const result = await execSkillsCliAsyncOnce(cli, args, options);
if (result.ok || cli.kind !== 'cached' || !BROKEN_CACHED_CLI.test(result.output)) return result;
return execSkillsCliAsyncOnce(options.fallback || npxFallback(cli), args, options);
}
module.exports = {
SKILLS_CLI_PINS,
selectSkillsCliVersion,
npmCacheCandidates,
resolveSkillsCli,
spawnPlan,
execSkillsCliSync,
execSkillsCliAsync,
skillsCliDisplay,
};
+71
View File
@@ -0,0 +1,71 @@
'use strict';
const fs = require('fs');
const path = require('path');
function cleanFields(fields) {
const out = {};
for (const [key, value] of Object.entries(fields || {})) {
if (value !== undefined) out[key] = value;
}
return out;
}
function createTiming({ outputPath, ref, version, mode } = {}) {
const target = outputPath !== undefined ? outputPath : process.env.PLAN2CODE_BENCH_JSON || null;
const active = Boolean(target);
const base = cleanFields({ ref, version, mode });
function write(record) {
if (!active) return null;
try {
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.appendFileSync(target, `${JSON.stringify(record)}\n`, 'utf8');
return record;
} catch {
return null;
}
}
function timingEvent(name, extra = {}) {
if (!active || typeof name !== 'string' || !name) return null;
return write({ event: name, at: new Date().toISOString(), ...base, ...cleanFields(extra) });
}
function timingDuration(name, startMark, extra = {}) {
const durationMs = typeof startMark === 'number' ? Math.max(0, performance.now() - startMark) : 0;
return timingEvent(name, { ...extra, durationMs });
}
return { active, outputPath: target, timingEvent, timingDuration };
}
function timingEvent(name, extra = {}) {
return createTiming().timingEvent(name, extra);
}
function timingDuration(name, startMark, extra = {}) {
return createTiming().timingDuration(name, startMark, extra);
}
function readTimingEvents(file) {
let text;
try {
text = fs.readFileSync(file, 'utf8');
} catch {
return [];
}
const events = [];
for (const line of text.split(/\r?\n/)) {
if (!line.trim()) continue;
try {
const event = JSON.parse(line);
if (event && typeof event === 'object' && !Array.isArray(event)) events.push(event);
} catch {
// Malformed lines are ignored so one partial write does not hide later events.
}
}
return events;
}
module.exports = { createTiming, timingEvent, timingDuration, readTimingEvents };
+88 -39
View File
@@ -1678,48 +1678,75 @@ function spawnCommand(file, args, options) {
* npx's exit code through. No agent starts. That one install updates the skills, this launcher
* and the desktop app (when it is installed) together, so the three never drift apart.
*
* It installs the newest `vX.Y.Z` release tag, found with the same `git ls-remote --tags` rule
* the console's release check uses (update-check.mjs, copied beside this file), so a person is
* never moved onto work a published release does not have yet. `--main` is the old behavior (the
* tip of `main`); `--tag <ref>` installs that tag or branch (the desktop app's Update skills
* button pins the app's own tag this way, and it is how to go back to an earlier release);
* `--force` reinstalls even when the version is already current. `--main`, and a `--tag` naming a
* branch rather than a vX.Y.Z release, always reinstall: unreleased work keeps the last release's
* version, so the installer's "Already on" check would otherwise install nothing.
* It installs the newest release, found in one `git ls-remote --tags --heads` snapshot read with
* the rules of update-check.mjs (copied beside this file), so a person is never moved onto work a
* published release does not have yet. A release is named by its logical `vX.Y.Z` everywhere the
* person reads it, while npx fetches its slim immutable `install-vX.Y.Z` tag when the snapshot
* advertises one (the plain tag otherwise). `--main` is the old behavior (the tip of `main`);
* `--tag <ref>` installs that tag or branch (the desktop app's Update skills button pins the app's
* own tag this way, and it is how to go back to an earlier release: a `vX.Y.Z` there is mapped to
* its install tag the same way, and falls back to the plain tag when the snapshot has none or
* cannot be read); `--force` reinstalls even when the version is already current. `--main`, and a
* `--tag` naming a branch rather than a vX.Y.Z release, always reinstall: unreleased work keeps
* the last release's version, so the installer's "Already on" check would otherwise install
* nothing.
*/
async function runUpdate({ tag, main, force } = {}) {
let ref = tag;
if (ref === undefined && !main) {
const latest = await newestReleaseTag();
if (!latest) {
async function runUpdate({ tag, main, force, notice } = {}) {
if (notice) console.log(c.dim(notice));
const release = tag !== undefined && RELEASE_TAG.test(tag);
let refs;
if (tag === undefined && !main) {
refs = await newestRelease();
if (!refs) {
console.error(`${ce.red('plan2code:')} could not find the newest Plan2Code release (git ls-remote did not answer).`);
console.error('Check your network, then run plan2code update again, or use --main (the newest work, not a release) or --tag <release> (for example --tag v3.0.2).');
return process.exit(1);
}
ref = `v${latest}`;
} else if (release) {
const found = await readRefSnapshot();
refs = (found && found.checker.installRefForRelease(tag, found.snapshot)) || { releaseRef: tag, fetchRef: tag };
} else if (tag !== undefined) {
refs = { fetchRef: tag };
}
console.log(ref === undefined ? 'Updating Plan2Code to the newest work on main...' : `Updating Plan2Code to ${ref}...`);
console.log(refs ? `Updating Plan2Code to ${refs.releaseRef || refs.fetchRef}...` : 'Updating Plan2Code to the newest work on main...');
console.log(c.dim('One update covers the skills, the plan2code command and the desktop app (when installed).'));
console.log(c.dim('npx fetches it quietly first, which can take a minute or two.'));
const unreleased = main || (tag !== undefined && !/^v\d+\.\d+\.\d+$/.test(tag));
return runInstaller(['--update', ...(force || unreleased ? ['--force'] : [])], ref);
const unreleased = main || (tag !== undefined && !release);
return runInstaller(['--update', ...(force || unreleased ? ['--force'] : [])], refs);
}
/** A logical release ref, `vX.Y.Z`. */
const RELEASE_TAG = /^v\d+\.\d+\.\d+$/;
/**
* One `git ls-remote --tags --heads` snapshot, parsed: `{ checker, snapshot }` with `checker` the
* update-check.mjs module (beside this file once installed, or in the repository's web-console
* folder when run from a checkout), or null when it cannot be read. PLAN2CODE_LS_REMOTE_FILE
* names a file holding `git ls-remote` output to use instead of asking git: the tests' stand-in
* for the network. Nothing is cached: each update asks once.
*/
async function readRefSnapshot() {
try {
const file = [path.join(__dirname, 'update-check.mjs'), path.join(__dirname, '..', 'web-console', 'update-check.mjs')].find((f) => fs.existsSync(f));
if (!file) return null;
const checker = await import(require('url').pathToFileURL(file).href);
const stub = process.env.PLAN2CODE_LS_REMOTE_FILE;
const text = stub ? fs.readFileSync(stub, 'utf8') : await checker.runLsRemote();
if (typeof text !== 'string') return null;
return { checker, snapshot: checker.parseLsRemoteSnapshot(text) };
} catch {
return null;
}
}
/**
* The newest release's version (X.Y.Z), or null when it cannot be found. The tag list comes from
* update-check.mjs's own `git ls-remote --tags` run and its own pick, beside this file once
* installed (or in the repository's web-console folder when run from a checkout).
* PLAN2CODE_LS_REMOTE_FILE names a file holding `git ls-remote --tags` output to use instead of
* asking git: the tests' stand-in for the network.
* The newest release as update-check.mjs's chooseReleaseRef() maps it, `{ releaseRef, fetchRef,
* synthetic, version }`, or null when it cannot be found.
*/
async function newestReleaseTag() {
async function newestRelease() {
try {
const checker = [path.join(__dirname, 'update-check.mjs'), path.join(__dirname, '..', 'web-console', 'update-check.mjs')].find((file) => fs.existsSync(file));
if (!checker) return null;
const mod = await import(require('url').pathToFileURL(checker).href);
const stub = process.env.PLAN2CODE_LS_REMOTE_FILE;
const text = stub ? fs.readFileSync(stub, 'utf8') : await mod.runLsRemote();
return mod.latestTag(text);
const found = await readRefSnapshot();
return found ? found.checker.chooseReleaseRef(found.snapshot) : null;
} catch {
return null;
}
@@ -1734,21 +1761,28 @@ async function newestReleaseTag() {
*/
async function runUninstall(flags) {
console.log('Uninstalling Plan2Code...');
const latest = await newestReleaseTag();
return runInstaller(['--uninstall', ...flags], latest ? `v${latest}` : undefined);
return runInstaller(['--uninstall', ...flags], (await newestRelease()) || undefined);
}
/** Run install.js through npx with the given flags, passing npx's exit code through. */
function runInstaller(installerArgs, tag) {
/**
* Run install.js through npx with the given flags, passing npx's exit code through. `refs` is a
* ref name (the fetch ref), or `{ fetchRef, releaseRef }` when the fetched ref stands for a
* logical release; neither means the tip of main.
*/
function runInstaller(installerArgs, refs) {
const { fetchRef, releaseRef } = typeof refs === 'string' ? { fetchRef: refs } : refs || {};
const npx = findOnPath('npx');
if (!npx) {
console.error(`${ce.red('plan2code:')} npx was not found on your PATH. It comes with Node.js 18+ (https://nodejs.org).`);
return process.exit(127);
}
const spec = tag ? `git+${REPO_URL}#${tag}` : `git+${REPO_URL}`;
const spec = fetchRef ? `git+${REPO_URL}#${fetchRef}` : `git+${REPO_URL}`;
// The ref was picked on purpose (main included): install.js's release redirect, there for
// launchers older than the release channel, must leave this run where it is.
const env = { ...process.env, PLAN2CODE_INSTALL_REF: tag || 'main' };
// launchers older than the release channel, must leave this run where it is. The logical
// release travels beside it, so an `install-vX.Y.Z` fetch still knows it is `vX.Y.Z`.
const env = { ...process.env, PLAN2CODE_INSTALL_REF: fetchRef || 'main' };
if (releaseRef) env.PLAN2CODE_RELEASE_REF = releaseRef;
else delete env.PLAN2CODE_RELEASE_REF;
const child = spawnCommand(npx, ['--yes', '--allow-git=all', spec, ...installerArgs], { stdio: 'inherit', env });
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
process.on(signal, () => {});
@@ -1802,7 +1836,19 @@ async function releaseNotice() {
} catch {}
}
/** `{ tag, main, force }` from the words after `update`, or `{ error }` naming what is wrong. */
/**
* A `--tag` value as the update uses it: an exact `install-vX.Y.Z` (the fetch ref of a release)
* becomes its logical `vX.Y.Z` with a one-line `notice`, so going back is always by release name;
* any other `install-v...` is `{ error }`; every other branch or tag is left as it is, `{ ref }`.
*/
function normalizeUpdateTagInput(ref) {
if (typeof ref !== 'string' || !ref.startsWith('install-v')) return { ref };
const m = /^install-(v\d+\.\d+\.\d+)$/.exec(ref);
if (!m) return { error: `${ref} is not a release install tag: use --tag with the release, for example --tag v3.0.2` };
return { ref: m[1], notice: `${ref} is how release ${m[1]} is fetched; updating by its release name, ${m[1]}.` };
}
/** `{ tag, main, force, notice? }` from the words after `update`, or `{ error }` naming what is wrong. */
function parseUpdateArgs(args) {
const out = { main: false, force: false };
for (let i = 0; i < args.length; i++) {
@@ -1812,7 +1858,10 @@ function parseUpdateArgs(args) {
else if (arg === '--tag') {
const ref = args[i + 1];
if (!ref || ref.startsWith('--')) return { error: '--tag needs a release or branch, for example --tag v3.0.2' };
out.tag = ref;
const normalized = normalizeUpdateTagInput(ref);
if (normalized.error) return { error: normalized.error };
out.tag = normalized.ref;
if (normalized.notice) out.notice = normalized.notice;
i++;
} else return { error: `unknown option for update: ${arg}` };
}
@@ -2024,4 +2073,4 @@ async function launch() {
// Run only when invoked directly; requiring the file (the tests do) is load-only.
if (require.main === module) launch();
module.exports = { nodeVersionProblem, usageText, droppedForApp, bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd, sameFolder, readRecent, pushRecent, listRecent, recordFolder, folderMenuRows, folderMenuPick, isEmptyFolder };
module.exports = { nodeVersionProblem, usageText, normalizeUpdateTagInput, droppedForApp, bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd, sameFolder, readRecent, pushRecent, listRecent, recordFolder, folderMenuRows, folderMenuPick, isEmptyFolder };
+104 -13
View File
@@ -1,10 +1,13 @@
// Plan2Code Web Console - is a newer Plan2Code release out?
//
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
// release tag is "latest". The server
// starts this at boot and never waits on it; the answer, failures included, is
// cached for an hour so a burst of sessions asks GitHub once.
// `git ls-remote --tags --heads` needs no API token and no rate-limited REST
// call, rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
// release tag is "latest". The same one snapshot also carries the synthetic
// `install-vX.Y.Z` tags and the branch heads, which the launcher and the
// installer read to pick the ref npx fetches (`chooseReleaseRef()`,
// `installRefForRelease()`). The server starts this at boot and never waits on
// it; the answer, failures included, is cached for an hour so a burst of
// sessions asks GitHub once.
//
// Nothing here reads, stores or sends a credential: git authenticates itself,
// with every prompt turned off so a missing login fails fast instead of
@@ -21,7 +24,11 @@ export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
export const CACHE_MS = 60 * 60 * 1000;
const SEMVER = /^\d+\.\d+\.\d+$/;
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
// The ref starts the line or follows the sha's whitespace: with `--heads` in the same answer, a
// branch named like `x/refs/tags/v9.9.9` must never read as release 9.9.9.
const TAG_REF = /(?:^|\s)refs\/tags\/v(\d+\.\d+\.\d+)$/;
const SNAPSHOT_LINE = /^([0-9a-f]{40})\s+refs\/(tags|heads)\/(\S+)$/i;
const RELEASE_TAG = /^(install-)?v(\d+\.\d+\.\d+)$/;
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
export function compareVersions(a, b) {
@@ -35,9 +42,13 @@ export function compareVersions(a, b) {
}
/**
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
* pre-releases or other tag names are ignored. Null when nothing matches.
* The highest `vX.Y.Z` tag in `git ls-remote` output, without the `v`.
* Peeled lines (`^{}`), `install-vX.Y.Z` tags, branch heads, pre-releases and
* other tag names never match, so an annotated tag counts once. Null when
* nothing matches. This is the plain-release compatibility API the console
* notice uses: it keeps its own line scan rather than going through
* `parseLsRemoteSnapshot()`, whose stricter sha check and peeled-line
* evidence would change what it has always answered.
*/
export function latestTag(text) {
if (typeof text !== "string") return null;
@@ -49,6 +60,84 @@ export function latestTag(text) {
return best;
}
/**
* One `git ls-remote --tags --heads` answer, parsed: `{ tags, peeledTags,
* installTags, heads }`. `tags` and `installTags` map a version (`X.Y.Z`) to
* the sha its `vX.Y.Z` or `install-vX.Y.Z` ref line names; `peeledTags` maps a
* tag name (`v3.1.2`, `install-v3.1.2`) to the commit on its `^{}` line, which
* only annotated tags have; `heads` maps a branch name to its commit. Shas are
* lowercased. Malformed lines and tags of neither shape are skipped; anything
* but a string gives an empty snapshot.
*/
export function parseLsRemoteSnapshot(text) {
const snapshot = { tags: {}, peeledTags: {}, installTags: {}, heads: {} };
if (typeof text !== "string") return snapshot;
for (const line of text.split(/\r?\n/)) {
const m = SNAPSHOT_LINE.exec(line.trim());
if (!m) continue;
const sha = m[1].toLowerCase();
if (m[2] === "heads") {
snapshot.heads[m[3]] = sha;
continue;
}
const peeled = m[3].endsWith("^{}");
const name = peeled ? m[3].slice(0, -3) : m[3];
const tag = RELEASE_TAG.exec(name);
if (!tag) continue;
if (peeled) snapshot.peeledTags[name] = sha;
else (tag[1] ? snapshot.installTags : snapshot.tags)[tag[2]] = sha;
}
return snapshot;
}
/** Whether the snapshot advertises the tag `name` (`vX.Y.Z` or `install-vX.Y.Z`): its ref line or its peeled line. */
function hasTag(snapshot, name) {
const m = RELEASE_TAG.exec(name);
const refs = (m[1] ? snapshot.installTags : snapshot.tags) || {};
return Object.hasOwn(refs, m[2]) || Object.hasOwn(snapshot.peeledTags || {}, name);
}
/**
* The ref npx should fetch for the logical release `vX.Y.Z` (`X.Y.Z` reads the
* same): `{ releaseRef: "vX.Y.Z", fetchRef: "install-vX.Y.Z", synthetic: true }`
* when the snapshot advertises the slim install tag, `{ releaseRef, fetchRef:
* "vX.Y.Z", synthetic: false }` when it advertises only the plain tag, and
* null when it advertises neither. Chosen by ref name, never by commit; an
* annotated tag's peeled line counts as evidence of its tag.
*/
export function installRefForRelease(version, snapshot) {
if (typeof version !== "string" || !snapshot) return null;
const bare = version.startsWith("v") ? version.slice(1) : version;
if (!SEMVER.test(bare)) return null;
const releaseRef = `v${bare}`;
if (hasTag(snapshot, `install-${releaseRef}`)) return { releaseRef, fetchRef: `install-${releaseRef}`, synthetic: true };
if (hasTag(snapshot, releaseRef)) return { releaseRef, fetchRef: releaseRef, synthetic: false };
return null;
}
/**
* The release a default update installs: always the numerically newest plain
* `vX.Y.Z`, the same release latestTag() reports to the banner, the launcher
* notice and the app, fetched as its slim `install-vX.Y.Z` when that tag
* exists and as the full plain tag when it does not (a release published
* before its install ref, or whose ref publication failed). Never an older
* release because only it has an install tag: that would roll a user back.
* `{ releaseRef, fetchRef, synthetic, version }` with `version` as `X.Y.Z`, or
* null when the snapshot holds no plain release at all.
*/
export function chooseReleaseRef(snapshot) {
if (!snapshot) return null;
const plain = new Set(Object.keys(snapshot.tags || {}));
for (const name of Object.keys(snapshot.peeledTags || {})) {
const m = RELEASE_TAG.exec(name);
if (m && !m[1]) plain.add(m[2]);
}
const version = [...plain].reduce((best, v) => (best === null || compareVersions(v, best) > 0 ? v : best), null);
if (version === null) return null;
const synthetic = hasTag(snapshot, `install-v${version}`);
return { releaseRef: `v${version}`, fetchRef: synthetic ? `install-v${version}` : `v${version}`, synthetic, version };
}
function readCache(cacheFile, now) {
try {
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
@@ -73,9 +162,11 @@ function writeCache(cacheFile, data) {
}
/**
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
* window, no prompt.
* `git ls-remote --tags --heads` against the repo, one call for the release
* tags, the synthetic install tags and the branch heads: resolves its stdout,
* or null when git is missing, fails, or is still going after `timeoutMs`. No
* shell, no window, no prompt. Readers that want releases only (`latestTag()`)
* skip the head lines.
*/
export function runLsRemote({ timeoutMs = 10000 } = {}) {
return new Promise((resolve) => {
@@ -90,7 +181,7 @@ export function runLsRemote({ timeoutMs = 10000 } = {}) {
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
let child;
try {
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
child = spawn("git", ["ls-remote", "--tags", "--heads", REPO_URL], {
shell: false,
windowsHide: true,
stdio: ["ignore", "pipe", "ignore"],