feat(plugins): make CCAM installable straight from a Claude Code plugin

Adds a root `ccam` plugin (`.claude-plugin/plugin.json`, `"source": "./"`) so
`/plugin marketplace add` + `/plugin install ccam@...` is enough on a machine
with nothing but Claude Code: no clone, no npm run setup, no manual npm start.

- scripts/plugin-bootstrap.js: SessionStart hook. Fast-path exit, Node >=22.5
  gate (node:sqlite), mkdir lock with stale reclaim, deps installed into
  ~/.claude/agent-dashboard/runtime/ (never the plugin cache), legacy
  checkout-hook cleanup (backed up), ~/.local/bin/ccam launcher, eager UI
  build so client routes like /run work immediately, detached server spawn.
- scripts/plugin-open.js, scripts/plugin-doctor.js: /ccam-open, /ccam-doctor.
- server/index.js: DASHBOARD_CLIENT_DIST override (plugin cache is read-only).
- mcp/build/ is committed (plugin MCP servers start before any bootstrap could
  build them) and kept honest by scripts/check-mcp-build.js (content hash,
  not mtime), enforced by pre-commit when mcp/src changes.
- plugins/ccam-dashboard/.mcp.json moved under plugins/ccam/ with a working
  ${CLAUDE_PLUGIN_ROOT} path (the old relative path never resolved from a
  marketplace-cached subdir).
- Docs: README, INSTALL, SETUP, ARCHITECTURE, CLAUDE.md, docs/PLUGINS.md,
  docs/MCP.md, docs/CLI.md, docs/HOOKS.md.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-08-10 16:05:37 +07:00
parent 5a793e70cc
commit 8a82895c65
59 changed files with 5982 additions and 44 deletions
+85
View File
@@ -0,0 +1,85 @@
/**
* @file Tests scripts/check-mcp-build.js — the freshness gate for the committed
* mcp/build artifact. Content hashing is the whole point: mtimes are meaningless
* after a clone, where every file is stamped at checkout time in arbitrary order.
* Runs against synthetic trees, never the real mcp/.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { describe, it, beforeEach, after } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("fs");
const os = require("os");
const path = require("path");
const { sourceHash, mcpBuildStatus, writeHash } = require("../../scripts/check-mcp-build");
const ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "ccam-mcpbuild-"));
const SRC = path.join(ROOT, "mcp", "src");
const BUILD = path.join(ROOT, "mcp", "build");
function makeTree() {
fs.rmSync(path.join(ROOT, "mcp"), { recursive: true, force: true });
fs.mkdirSync(SRC, { recursive: true });
fs.mkdirSync(BUILD, { recursive: true });
fs.writeFileSync(path.join(SRC, "index.ts"), "export const a = 1;\n");
fs.writeFileSync(path.join(ROOT, "mcp", "package.json"), '{"name":"x"}\n');
fs.writeFileSync(path.join(BUILD, "index.js"), "exports.a = 1;\n");
}
after(() => fs.rmSync(ROOT, { recursive: true, force: true }));
describe("mcp build freshness", () => {
beforeEach(makeTree);
it("fails when the build has no recorded hash", () => {
const status = mcpBuildStatus(ROOT);
assert.equal(status.ok, false);
assert.match(status.reason, /no recorded source hash/);
});
it("passes right after the hash is stamped", () => {
writeHash(ROOT);
assert.equal(mcpBuildStatus(ROOT).ok, true);
});
it("fails when a source file changes after the build", () => {
writeHash(ROOT);
fs.writeFileSync(path.join(SRC, "index.ts"), "export const a = 2;\n");
const status = mcpBuildStatus(ROOT);
assert.equal(status.ok, false);
assert.match(status.reason, /stale/);
});
it("fails when a source file is added after the build", () => {
writeHash(ROOT);
fs.writeFileSync(path.join(SRC, "extra.ts"), "export const b = 1;\n");
assert.equal(mcpBuildStatus(ROOT).ok, false);
});
it("fails when the build output is missing entirely", () => {
writeHash(ROOT);
fs.rmSync(path.join(BUILD, "index.js"));
assert.match(mcpBuildStatus(ROOT).reason, /missing/);
});
it("ignores modification times — only content counts", () => {
const before = sourceHash(ROOT);
const future = Date.now() / 1000 + 10_000;
fs.utimesSync(path.join(SRC, "index.ts"), future, future);
assert.equal(sourceHash(ROOT), before);
});
it("tracks the manifest, so a dependency bump invalidates the build", () => {
writeHash(ROOT);
fs.writeFileSync(path.join(ROOT, "mcp", "package.json"), '{"name":"x","version":"2"}\n');
assert.equal(mcpBuildStatus(ROOT).ok, false);
});
});
describe("the committed mcp/build in this repo", () => {
it("matches mcp/src", () => {
const status = mcpBuildStatus(path.resolve(__dirname, "..", ".."));
assert.equal(status.ok, true, status.reason);
});
});
@@ -0,0 +1,98 @@
/**
* @file Tests the DASHBOARD_CLIENT_DIST override in server/index.js. A plugin
* install runs the server from a read-only plugin cache directory, so the
* client bundle is served from the writable runtime dir instead of the
* checkout's client/dist. Also asserts the API still answers when the
* configured bundle directory does not exist yet (the normal state before
* /ccam-open builds it).
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { describe, it, before, after } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("fs");
const os = require("os");
const path = require("path");
const http = require("http");
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "ccam-clientdist-"));
const DIST = path.join(TMP, "client-dist");
fs.mkdirSync(DIST);
fs.writeFileSync(path.join(DIST, "index.html"), "<!doctype html><title>from-runtime</title>");
// Must be set BEFORE requiring the server: the data dir, discovery file and
// the static mount are all resolved at startup.
process.env.CLAUDE_HOME = TMP;
process.env.DASHBOARD_DB_PATH = path.join(TMP, "test.db");
process.env.DASHBOARD_LIVENESS_PROBE = "0";
process.env.DASHBOARD_CLIENT_DIST = DIST;
const { createApp, startServer } = require("../index");
const { db } = require("../db");
let server;
let BASE;
function get(urlPath) {
return new Promise((resolve, reject) => {
const req = http.get(new URL(urlPath, BASE), (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => resolve({ status: res.statusCode, body }));
});
req.on("error", reject);
});
}
describe("DASHBOARD_CLIENT_DIST override", () => {
before(async () => {
server = await startServer(createApp(), 0);
BASE = `http://127.0.0.1:${server.address().port}`;
});
after(() => {
if (server) server.close();
if (db) db.close();
fs.rmSync(TMP, { recursive: true, force: true });
delete process.env.DASHBOARD_CLIENT_DIST;
});
it("serves index.html from the configured directory", async () => {
const res = await get("/");
assert.equal(res.status, 200);
assert.match(res.body, /from-runtime/);
});
it("keeps the API working alongside the override", async () => {
const res = await get("/api/health");
assert.equal(res.status, 200);
});
});
describe("DASHBOARD_CLIENT_DIST pointing at a missing directory", () => {
let srv;
let base;
before(async () => {
process.env.DASHBOARD_CLIENT_DIST = path.join(TMP, "not-built-yet");
srv = await startServer(createApp(), 0);
base = `http://127.0.0.1:${srv.address().port}`;
});
after(() => {
if (srv) srv.close();
});
it("answers the API and only 404s the UI route", async () => {
const prevBase = BASE;
BASE = base;
try {
const health = await get("/api/health");
assert.equal(health.status, 200);
const ui = await get("/");
assert.equal(ui.status, 404);
} finally {
BASE = prevBase;
}
});
});
+198
View File
@@ -0,0 +1,198 @@
/**
* @file Tests scripts/plugin-bootstrap.js — the SessionStart bootstrap that
* makes a plugin install self-sufficient. Covers the fast path, the Node
* version gate, stale-lock reclaim, legacy hook removal (the duplicate-hook
* double-counting bug) and the CLI launcher's refusal to clobber a foreign
* `ccam`. Every path is exercised against injected temp directories — nothing
* here touches the real $HOME.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { describe, it, beforeEach, after } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("fs");
const os = require("os");
const path = require("path");
const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "ccam-bootstrap-"));
process.env.CLAUDE_HOME = TMP_HOME;
delete process.env.DASHBOARD_DATA_DIR;
const boot = require("../../scripts/plugin-bootstrap");
const RT = path.join(TMP_HOME, "agent-dashboard", "runtime");
function resetRuntime() {
fs.rmSync(RT, { recursive: true, force: true });
fs.mkdirSync(RT, { recursive: true });
}
after(() => {
fs.rmSync(TMP_HOME, { recursive: true, force: true });
});
describe("runtime location", () => {
it("lives under the shared data dir, not the plugin cache", () => {
assert.equal(boot.runtimeDir(), RT);
});
});
describe("node version gate", () => {
it("refuses anything below 22.5 (node:sqlite is the only driver available)", () => {
assert.equal(boot.nodeVersionOk("20.11.0"), false);
assert.equal(boot.nodeVersionOk("22.4.1"), false);
});
it("accepts 22.5 and newer", () => {
assert.equal(boot.nodeVersionOk("22.5.0"), true);
assert.equal(boot.nodeVersionOk("24.0.0"), true);
});
});
describe("fast path", () => {
beforeEach(resetRuntime);
it("is false with no recorded state", () => {
assert.equal(boot.fastPathOk(RT), false);
});
it("is false when the recorded plugin version is stale", () => {
fs.mkdirSync(path.join(RT, "node_modules"), { recursive: true });
boot.writeState({ pluginVersion: "0.0.0-old", depsHash: boot.depsHash() }, RT);
assert.equal(boot.fastPathOk(RT), false);
});
it("is false after a plugin update moved the install to a new cache dir", () => {
const pkg = require("../../package.json");
fs.mkdirSync(path.join(RT, "node_modules"), { recursive: true });
boot.writeState(
{
pluginVersion: pkg.version,
depsHash: boot.depsHash(),
pluginRoot: "/old/plugin/cache/dir",
},
RT
);
assert.equal(boot.fastPathOk(RT), false);
});
it("is false when node_modules is missing even if state matches", () => {
const pkg = require("../../package.json");
boot.writeState({ pluginVersion: pkg.version, depsHash: boot.depsHash() }, RT);
assert.equal(boot.fastPathOk(RT), false);
});
});
describe("bootstrap lock", () => {
beforeEach(resetRuntime);
it("is exclusive while held", () => {
assert.equal(boot.acquireLock(RT), true);
assert.equal(boot.acquireLock(RT), false, "a live lock must not be reclaimed");
boot.releaseLock(RT);
assert.equal(fs.existsSync(boot.lockPath(RT)), false);
});
it("reclaims a lock whose owner is dead", () => {
fs.mkdirSync(boot.lockPath(RT), { recursive: true });
// PID 1 is alive but not ours; use an unused high pid instead.
fs.writeFileSync(path.join(boot.lockPath(RT), "pid"), "999999", "utf8");
assert.equal(boot.lockIsStale(boot.lockPath(RT)), true);
assert.equal(boot.acquireLock(RT), true);
boot.releaseLock(RT);
});
it("reclaims a lock older than the stale timeout even if its pid is alive", () => {
fs.mkdirSync(boot.lockPath(RT), { recursive: true });
fs.writeFileSync(path.join(boot.lockPath(RT), "pid"), String(process.pid), "utf8");
const old = Date.now() - boot.LOCK_STALE_MS - 1000;
fs.utimesSync(boot.lockPath(RT), old / 1000, old / 1000);
assert.equal(boot.lockIsStale(boot.lockPath(RT)), true);
assert.equal(boot.acquireLock(RT), true);
boot.releaseLock(RT);
});
it("treats a lock directory with no pid file as debris", () => {
fs.mkdirSync(boot.lockPath(RT), { recursive: true });
assert.equal(boot.lockIsStale(boot.lockPath(RT)), true);
});
});
describe("legacy hook cleanup", () => {
const settings = path.join(TMP_HOME, "settings-legacy.json");
beforeEach(() => {
fs.rmSync(settings, { force: true });
fs.rmSync(`${settings}.ccam-bak`, { force: true });
});
it("removes checkout-installed hook entries and backs the file up first", () => {
fs.writeFileSync(
settings,
JSON.stringify({
hooks: {
PreToolUse: [
{
matcher: "*",
hooks: [
{ type: "command", command: "node /repo/scripts/hook-handler.js PreToolUse" },
],
},
{ matcher: "*", hooks: [{ type: "command", command: "node /other/tool.js" }] },
],
SessionStart: [
{
hooks: [
{ type: "command", command: "node /repo/scripts/hook-handler.js SessionStart" },
],
},
],
},
})
);
const removed = boot.stripLegacyHooks(settings);
assert.equal(removed, 2);
const after = JSON.parse(fs.readFileSync(settings, "utf8"));
assert.equal(after.hooks.PreToolUse.length, 1, "unrelated hooks must survive");
assert.match(JSON.stringify(after.hooks.PreToolUse), /other\/tool\.js/);
assert.equal(after.hooks.SessionStart, undefined, "an emptied list is dropped");
assert.ok(fs.existsSync(`${settings}.ccam-bak`), "must back up before writing");
});
it("leaves a file with no CCAM hooks untouched and writes no backup", () => {
fs.writeFileSync(settings, JSON.stringify({ hooks: { Stop: [{ hooks: [] }] } }));
assert.equal(boot.stripLegacyHooks(settings), 0);
assert.equal(fs.existsSync(`${settings}.ccam-bak`), false);
});
it("is a no-op when no settings file exists", () => {
assert.equal(boot.stripLegacyHooks(path.join(TMP_HOME, "nope.json")), 0);
});
});
describe("ccam CLI launcher", () => {
const bin = path.join(TMP_HOME, "bin");
const target = path.join(bin, process.platform === "win32" ? "ccam.cmd" : "ccam");
beforeEach(() => {
fs.rmSync(bin, { recursive: true, force: true });
});
it("writes a launcher that points at the plugin's bin/ccam.js", () => {
assert.equal(boot.linkCli(bin), "written");
assert.match(fs.readFileSync(target, "utf8"), /bin[/\\]ccam\.js/);
});
it("is idempotent", () => {
boot.linkCli(bin);
assert.equal(boot.linkCli(bin), "exists");
});
it("never clobbers a ccam it did not write (a linked checkout keeps winning)", () => {
fs.mkdirSync(bin, { recursive: true });
fs.writeFileSync(target, '#!/bin/sh\nexec node /my/checkout/bin/ccam.js "$@"\n');
assert.equal(boot.linkCli(bin), "foreign");
assert.match(fs.readFileSync(target, "utf8"), /my\/checkout/);
});
});
+81 -4
View File
@@ -40,10 +40,18 @@ function listMd(dir) {
}
}
// The marketplace mixes two shapes: the root-source `ccam` plugin (the whole
// repo — hooks, server, CLI, MCP) and ten subdirectory plugins. The root
// plugin's commands live in plugins/ccam/, which is therefore NOT a plugin dir.
const ROOT_PLUGIN = "ccam";
describe("plugin marketplace", () => {
const marketplace = readJson(MARKETPLACE);
const pluginDirs = listDirs(PLUGINS_DIR).sort();
const entryNames = marketplace.plugins.map((p) => p.name).sort();
const pluginDirs = listDirs(PLUGINS_DIR)
.filter((d) => d !== ROOT_PLUGIN)
.sort();
const subdirEntries = marketplace.plugins.filter((p) => p.name !== ROOT_PLUGIN);
const entryNames = subdirEntries.map((p) => p.name).sort();
it("marketplace.json has the required top-level shape", () => {
assert.equal(typeof marketplace.name, "string");
@@ -69,7 +77,7 @@ describe("plugin marketplace", () => {
);
});
for (const entry of marketplace.plugins) {
for (const entry of subdirEntries) {
describe(`entry: ${entry.name}`, () => {
it("has name, path, description, tags", () => {
assert.equal(typeof entry.name, "string");
@@ -154,7 +162,7 @@ describe("plugin marketplace", () => {
);
});
it("contributes at least one skill or agent", () => {
it("contributes at least one skill or agent (subdir plugins only)", () => {
const skills = (() => {
try {
return listDirs(path.join(root, "skills")).length;
@@ -167,4 +175,73 @@ describe("plugin marketplace", () => {
});
});
}
describe(`root plugin: ${ROOT_PLUGIN}`, () => {
const entry = marketplace.plugins.find((p) => p.name === ROOT_PLUGIN);
const manifest = readJson(path.join(REPO_ROOT, ".claude-plugin", "plugin.json"));
it("is declared with the repo root as its source", () => {
assert.ok(entry, "the root ccam entry is missing from marketplace.json");
assert.equal(entry.source, "./");
assert.equal(entry.path, undefined, "a root-source entry must not also carry a path");
assert.ok(Array.isArray(entry.tags) && entry.tags.length > 0);
});
it("has a manifest whose name matches the entry", () => {
assert.equal(manifest.name, ROOT_PLUGIN);
assert.ok(manifest.description.length > 20);
assert.ok(manifest.author && manifest.author.name);
assert.equal(typeof manifest.license, "string");
});
it("wires every hook type through the plugin's own handler path", () => {
const withMatcher = ["PreToolUse", "PostToolUse", "Stop", "SubagentStop", "Notification"];
const withoutMatcher = ["SessionStart", "SessionEnd", "UserPromptSubmit"];
for (const type of [...withMatcher, ...withoutMatcher]) {
const entries = manifest.hooks[type];
assert.ok(Array.isArray(entries) && entries.length, `hook ${type} is not declared`);
const json = JSON.stringify(entries);
assert.match(json, /hook-handler\.js/, `hook ${type} does not call the handler`);
assert.match(
json,
/\$\{CLAUDE_PLUGIN_ROOT\}/,
`hook ${type} must resolve through CLAUDE_PLUGIN_ROOT, not a checkout path`
);
if (withMatcher.includes(type)) {
assert.equal(entries[0].matcher, "*", `hook ${type} needs a matcher`);
} else {
assert.equal(entries[0].matcher, undefined, `hook ${type} takes no matcher`);
}
}
});
it("runs the bootstrap on SessionStart", () => {
assert.match(JSON.stringify(manifest.hooks.SessionStart), /plugin-bootstrap\.js/);
});
it("points at command files that exist and carry a description", () => {
assert.ok(manifest.commands.length >= 3);
for (const rel of manifest.commands) {
const file = path.join(REPO_ROOT, rel);
assert.ok(fs.existsSync(file), `${rel} does not exist`);
const { frontmatter } = parseFrontmatter(fs.readFileSync(file, "utf8"));
assert.ok(frontmatter && frontmatter.description, `${rel} has no description`);
}
});
it("declares an MCP config that exists and resolves through CLAUDE_PLUGIN_ROOT", () => {
const mcpFile = path.join(REPO_ROOT, manifest.mcpServers);
assert.ok(fs.existsSync(mcpFile), `${manifest.mcpServers} does not exist`);
const mcp = readJson(mcpFile);
const args = JSON.stringify(mcp.mcpServers);
assert.match(args, /\$\{CLAUDE_PLUGIN_ROOT\}\/mcp\/build\/index\.js/);
});
it("ships the built MCP server the config points at", () => {
assert.ok(
fs.existsSync(path.join(REPO_ROOT, "mcp", "build", "index.js")),
"mcp/build/index.js must be committed — plugin MCP servers start before any bootstrap can build them"
);
});
});
});