fix(bootstrap): stop a retired plugin build from downgrading the dashboard
`claude plugin update` unpacks the new version into a new cache directory and says "Restart to apply changes". A Claude Code process that was already running does not: it keeps loading the OLD directory, hooks and all. Every session such a process opened then ran the OLD plugin-bootstrap, which saw a state.json naming a different root, concluded the server had to be replaced, repointed agenthub.service at itself and restarted the dashboard onto the version the user had just upgraded away from. The dashboard reported the old version and offered the update again — once per session, forever, while installed_plugins.json and the cache both said the new version was installed. A /agenthub-update from that session "succeeded" and changed nothing. - `supersededBy()` reads Claude Code's installed_plugins.json. When a SIBLING cache directory is the recorded install, the bootstrap logs one line and returns "superseded" — no deps, no unit, no server. `--force` does not override it: the self-update chain forces from the NEW directory, which is never superseded, so the only --force refused is a deliberate downgrade. It cannot hand over either — the process it would replace is the one loading it — so the log line says to restart Claude Code. - Matched by sibling directory, not by the <plugin>@<marketplace> key: correct without parsing a cache path or trusting a name. A phantom entry (installPath that no longer exists) is ignored rather than wedging the bootstrap shut. Also adds `pruneRetiredPluginRoots()`, since the same updates leave a full copy of the repo — node_modules and all — per release; twelve of them measured 1.7 GB on one machine. It runs after writeState, so a bad prune cannot cost the record of a good bootstrap, and it protects four independent readings of "in use": this build, every installPath Claude Code records, the directory agenthub.service names (`unitRoot`, foreign unit included), and any directory still named in the user's settings.json hooks — that last one is the un-restarted process above, seen from the other side. Plus the 2 newest survivors as a rollback cushion, and nothing at all outside ~/.claude/plugins/cache/.
This commit is contained in:
+196
-6
@@ -14,8 +14,14 @@
|
||||
* scoped to this session, same as before.
|
||||
*
|
||||
* Everything writable lives under `~/.claude/agenthub/runtime/` — NOT in
|
||||
* the plugin cache, which Claude Code garbage-collects and replaces wholesale
|
||||
* on every plugin update.
|
||||
* the plugin cache, which Claude Code replaces wholesale on every plugin
|
||||
* update. The one thing this file does reach into the cache for is deleting
|
||||
* the copies those updates leave behind (`pruneRetiredPluginRoots`).
|
||||
*
|
||||
* A bootstrap that is no longer the installed build does nothing at all
|
||||
* (`supersededBy`): an old cache directory, still loaded by a Claude Code
|
||||
* process that has not been restarted, would otherwise repoint systemd at
|
||||
* itself and downgrade the dashboard once per session, forever.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -40,14 +46,65 @@ function runtimeDir() {
|
||||
return path.join(getDataDir(), "runtime");
|
||||
}
|
||||
|
||||
function pluginVersion() {
|
||||
function pluginVersion(root = PLUGIN_ROOT) {
|
||||
try {
|
||||
return require(path.join(PLUGIN_ROOT, "package.json")).version;
|
||||
return require(path.join(root, "package.json")).version;
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------- superseded plugin build */
|
||||
|
||||
/** Claude Code's own record of which build of each plugin is installed. */
|
||||
function installedPluginsPath() {
|
||||
return path.join(getClaudeHome(), "plugins", "installed_plugins.json");
|
||||
}
|
||||
|
||||
/**
|
||||
* The build Claude Code has installed IN PLACE OF this one, or null when this
|
||||
* build is the installed one (or when there is no such record to read).
|
||||
*
|
||||
* `claude plugin update` unpacks the new version into a new cache directory and
|
||||
* says "Restart to apply changes" — but a Claude Code process that was already
|
||||
* running keeps loading the OLD directory, hooks and all. Every session it
|
||||
* opens from then on runs the OLD bootstrap, which happily repoints the systemd
|
||||
* unit at itself and restarts the dashboard onto the version the user just
|
||||
* upgraded away from. The dashboard then reports the old version and offers the
|
||||
* update again — forever, once per session, until Claude Code is restarted.
|
||||
*
|
||||
* So a bootstrap that is no longer the installed build does NOTHING. It cannot
|
||||
* hand over either: the process it would have to replace is the one loading it.
|
||||
*
|
||||
* Matched by SIBLING directory rather than by `<plugin>@<marketplace>` key: the
|
||||
* builds of one plugin are exactly the directories beside this one, and that
|
||||
* holds without parsing a cache path or trusting a name. An entry naming a
|
||||
* directory that no longer exists is ignored — a phantom must never wedge a
|
||||
* bootstrap shut.
|
||||
*/
|
||||
function supersededBy(root = PLUGIN_ROOT) {
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(fs.readFileSync(installedPluginsPath(), "utf8"));
|
||||
} catch {
|
||||
return null; // no record, unreadable, or not a plugin install at all
|
||||
}
|
||||
const siblings = path.dirname(root);
|
||||
const found = [];
|
||||
for (const entries of Object.values((data && data.plugins) || {})) {
|
||||
for (const entry of entries || []) {
|
||||
const installed =
|
||||
entry && typeof entry.installPath === "string" ? path.resolve(entry.installPath) : null;
|
||||
if (!installed) continue;
|
||||
// This build IS installed (possibly at one scope among several) — the
|
||||
// whole question is settled, whatever any other entry says.
|
||||
if (installed === root) return null;
|
||||
if (path.dirname(installed) === siblings && fs.existsSync(installed)) found.push(installed);
|
||||
}
|
||||
}
|
||||
return found[0] || null;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ state */
|
||||
|
||||
function statePath(rt = runtimeDir()) {
|
||||
@@ -447,16 +504,133 @@ function autoInstallSkillPlugins(rt, { force = false } = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ plugin-cache pruning */
|
||||
|
||||
/** How many retired builds to leave behind, newest first, as a rollback cushion. */
|
||||
const KEEP_RETIRED_ROOTS = 2;
|
||||
|
||||
/**
|
||||
* Delete the cache directories earlier updates left behind.
|
||||
*
|
||||
* Claude Code unpacks every plugin update into a NEW directory beside the old
|
||||
* one and does not reliably remove the old. A machine that tracks releases
|
||||
* closely ends up with a dozen full copies of this repo — node_modules and all
|
||||
* — which is what this clears.
|
||||
*
|
||||
* This is the one place anything here touches the plugin cache, and the file
|
||||
* header's "never write into the cache" rule is about the RUNTIME living
|
||||
* outside it, not about leaving retired copies forever. Everything still in use
|
||||
* is protected, by four independent readings of "in use":
|
||||
*
|
||||
* - this build;
|
||||
* - every build Claude Code records as installed, at any scope;
|
||||
* - the directory our systemd unit runs from, foreign unit included;
|
||||
* - any directory still named in the user's `settings.json` hooks — a Claude
|
||||
* Code process that has not been restarted is still executing from there,
|
||||
* and deleting it would break that session's hooks mid-flight. (This is
|
||||
* exactly the directory `supersededBy` describes, seen from the other side.)
|
||||
*
|
||||
* …plus the newest `KEEP_RETIRED_ROOTS` of whatever is left, so a rollback has
|
||||
* something to roll back to. Best effort throughout: a directory that will not
|
||||
* delete is left alone, never an error.
|
||||
*
|
||||
* @returns {number} how many directories were removed
|
||||
*/
|
||||
function pruneRetiredPluginRoots(rt, root = PLUGIN_ROOT) {
|
||||
// Only inside Claude Code's plugin cache. For a git checkout the parent
|
||||
// directory holds the user's own work and is never ours to delete from.
|
||||
const cacheMarker = `${path.sep}plugins${path.sep}cache${path.sep}`;
|
||||
if (!root.includes(cacheMarker)) return 0;
|
||||
const cacheDir = path.dirname(root);
|
||||
|
||||
const keep = new Set([root]);
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(installedPluginsPath(), "utf8"));
|
||||
for (const entries of Object.values((data && data.plugins) || {})) {
|
||||
for (const entry of entries || []) {
|
||||
if (entry && typeof entry.installPath === "string")
|
||||
keep.add(path.resolve(entry.installPath));
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* no record to read — the other three protections still apply */
|
||||
}
|
||||
try {
|
||||
const unitRoot = require("./systemd-service").unitRoot("agenthub");
|
||||
if (unitRoot) keep.add(path.resolve(unitRoot));
|
||||
} catch {
|
||||
/* best effort */
|
||||
}
|
||||
let settings = "";
|
||||
try {
|
||||
settings = fs.readFileSync(getSettingsPath(), "utf8");
|
||||
} catch {
|
||||
/* no settings file — nothing pinned by a hook */
|
||||
}
|
||||
|
||||
let dirs;
|
||||
try {
|
||||
dirs = fs.readdirSync(cacheDir, { withFileTypes: true });
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const retired = dirs
|
||||
.filter((d) => d.isDirectory())
|
||||
.map((d) => path.join(cacheDir, d.name))
|
||||
.filter((dir) => !keep.has(dir) && !settings.includes(dir))
|
||||
.map((dir) => {
|
||||
let at = 0;
|
||||
try {
|
||||
at = fs.statSync(dir).mtimeMs;
|
||||
} catch {
|
||||
/* unreadable sorts oldest, so it goes first */
|
||||
}
|
||||
return { dir, at };
|
||||
})
|
||||
.sort((a, b) => b.at - a.at)
|
||||
.slice(KEEP_RETIRED_ROOTS);
|
||||
|
||||
let removed = 0;
|
||||
for (const { dir } of retired) {
|
||||
try {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
removed += 1;
|
||||
} catch {
|
||||
/* in use, read-only, whatever — leaving it is always safe */
|
||||
}
|
||||
}
|
||||
if (removed) {
|
||||
log(rt, `removed ${removed} retired plugin cache ${removed === 1 ? "copy" : "copies"}`);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
/**
|
||||
* The real work. Runs detached from the SessionStart hook, so its only channel
|
||||
* is the log file; `/agenthub-update` runs it in the foreground with `force`, which
|
||||
* reinstalls dependencies and restarts the server unconditionally.
|
||||
*
|
||||
* @returns {"ok"|"locked"|"node-too-old"|"install-failed"}
|
||||
* @returns {"ok"|"locked"|"node-too-old"|"install-failed"|"superseded"}
|
||||
*/
|
||||
function bootstrap(rt = runtimeDir(), { force = false } = {}) {
|
||||
fs.mkdirSync(rt, { recursive: true });
|
||||
|
||||
// First, and ahead of the lock: a retired build has nothing to do and must
|
||||
// not take the lock to discover it. `force` does NOT override this — the
|
||||
// plugin-update chain runs `--force` from the NEW cache directory, which is
|
||||
// never superseded, so the only `--force` this can refuse is one that would
|
||||
// downgrade the user on purpose.
|
||||
const newer = supersededBy();
|
||||
if (newer) {
|
||||
log(
|
||||
rt,
|
||||
`this build (${pluginVersion()}) has been replaced by ${pluginVersion(newer)} — doing nothing. ` +
|
||||
`Restart Claude Code so it loads the new one; until then this session keeps running the old plugin.`
|
||||
);
|
||||
return "superseded";
|
||||
}
|
||||
|
||||
if (!nodeVersionOk()) {
|
||||
log(
|
||||
rt,
|
||||
@@ -621,6 +795,10 @@ function bootstrap(rt = runtimeDir(), { force = false } = {}) {
|
||||
},
|
||||
rt
|
||||
);
|
||||
|
||||
// After the state is durable, so a prune that goes wrong cannot also cost
|
||||
// us the record of a bootstrap that went right.
|
||||
pruneRetiredPluginRoots(rt);
|
||||
return "ok";
|
||||
} finally {
|
||||
releaseLock(rt);
|
||||
@@ -657,7 +835,14 @@ if (require.main === module) {
|
||||
// npm output and the result.
|
||||
const result = bootstrap(runtimeDir(), { force });
|
||||
if (force) {
|
||||
console.log(result === "ok" ? "AgentHub runtime refreshed." : `bootstrap: ${result}`);
|
||||
console.log(
|
||||
result === "ok"
|
||||
? "AgentHub runtime refreshed."
|
||||
: result === "superseded"
|
||||
? "A newer AgentHub plugin build is already installed — this one did nothing on purpose.\n" +
|
||||
"Restart Claude Code so it loads the new build, then try again."
|
||||
: `bootstrap: ${result}`
|
||||
);
|
||||
if (result !== "ok") process.exitCode = 1;
|
||||
}
|
||||
} else {
|
||||
@@ -672,6 +857,11 @@ if (require.main === module) {
|
||||
module.exports = {
|
||||
MIN_NODE,
|
||||
LOCK_STALE_MS,
|
||||
KEEP_RETIRED_ROOTS,
|
||||
supersededBy,
|
||||
pruneRetiredPluginRoots,
|
||||
installedPluginsPath,
|
||||
pluginVersion,
|
||||
runtimeDir,
|
||||
statePath,
|
||||
readState,
|
||||
|
||||
@@ -85,6 +85,24 @@ function unitIsStale(name, root) {
|
||||
return !body.includes(`\nWorkingDirectory=${root}\n`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The directory our unit actually runs from, or null when there is no unit.
|
||||
*
|
||||
* Deliberately does NOT require the marker: a FOREIGN unit named `agenthub` is
|
||||
* not ours to rewrite, but whatever directory it runs from is still a directory
|
||||
* nothing here may delete. The one caller is the plugin-cache pruner.
|
||||
*/
|
||||
function unitRoot(name) {
|
||||
let body;
|
||||
try {
|
||||
body = fs.readFileSync(unitPath(name), "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const match = body.match(/^WorkingDirectory=(.*)$/m);
|
||||
return match ? match[1].trim() : null;
|
||||
}
|
||||
|
||||
/** Is the unit currently running? Costs a `systemctl` call — never call it
|
||||
* from the fast path. */
|
||||
function unitIsActive(name) {
|
||||
@@ -209,6 +227,7 @@ module.exports = {
|
||||
systemctlAvailable,
|
||||
unitIsOurs,
|
||||
unitIsStale,
|
||||
unitRoot,
|
||||
unitIsActive,
|
||||
writeUserService,
|
||||
restartUserService,
|
||||
|
||||
Reference in New Issue
Block a user