@extenshi/mcp
Version:
Extenshi MCP server — bring the extension catalog (search, security, market research) and pre-publish scanning into your AI tools
415 lines • 16.6 kB
JavaScript
/**
* Where the build map lives and how every client touches it (plan
* 2026-11-03-extension-build-map §6.1).
*
* ONE MAP PER PROJECT, whoever asks. Agents often work on one extension in
* parallel, each in its own git worktree, and `.extenshi/` is usually ignored by
* git, so a per-checkout file would give every agent its own map and the author
* one browser tab per agent. The map therefore lives in the MAIN checkout: from
* a linked worktree, `resolveMapHome` maps the directory to the same path in the
* main working tree. Every agent, from any worktree, reads and writes the same
* `.extenshi/build-map.json` and finds the same server.
*
* Files under `<home>/.extenshi/`:
* build-map.json the state (BuildMapState); written under build-map.lock
* build-map.lock/ held for one read-modify-write; stale after a crash is taken over
* build-map.server.json the running server: pid, port, instance id, shutdown token (0600);
* a stopped server leaves it with pid 0 so the next start reuses the port
* build-map.server.lock/ held while a server starts, so two starts cannot both listen
* build-map.log output of the background server
*
* Writes go to a temporary file in the same directory and are renamed over the
* target, so a reader never sees half a file.
*
* The stdio MCP server (`@extenshi/mcp`) is the map's other client and ships a
* byte-identical copy at tools/extenshi-mcp/src/build-map-store.ts, so both find
* the same home and the same server; build-map-store-sync.test.ts there fails on
* any drift. Edit this file, then copy it over.
*/
import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { mkdir, open, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { BUILD_GRAPH_REVISION, emptyBuildMapState, normalizeBuildMapState, } from '@extenshi/contracts';
export const MAP_DIR = '.extenshi';
export const MAP_STATE_FILE = 'build-map.json';
export const MAP_SERVER_FILE = 'build-map.server.json';
export const MAP_LOG_FILE = 'build-map.log';
const STATE_LOCK = 'build-map.lock';
const SERVER_LOCK = 'build-map.server.lock';
/** Bumped when the page/server protocol changes: a newer CLI replaces an older server instead of reusing it. */
export const MAP_PROTOCOL = 8;
/** The record token, from the owner-only record file: authorizes /api/shutdown and a client's hello. */
export const MAP_TOKEN_HEADER = 'x-extenshi-map-token';
/** Who asks: `cli/<version> graph=<revision>` or `mcp/<version> graph=<revision>` (see mapClientHeader). */
export const MAP_CLIENT_HEADER = 'x-extenshi-map-client';
/** This program as a map client: the graph revision is the one it was built with. */
export const mapClient = (kind, version) => ({
kind,
version,
graph: BUILD_GRAPH_REVISION,
});
export const mapClientHeader = (client) => `${client.kind}/${client.version} graph=${client.graph}`;
export function parseMapClient(value) {
if (typeof value !== 'string' || value.length > 80)
return undefined;
const match = /^(cli|mcp)\/([0-9A-Za-z.+-]{1,40}) graph=(\d{1,6})$/.exec(value);
if (!match)
return undefined;
return { kind: match[1], version: match[2], graph: Number(match[3]) };
}
/** Order of two `x.y.z` versions (a pre-release sorts before its release); undefined when either is not one. */
export function compareVersions(a, b) {
const parse = (v) => /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(v);
const x = parse(a);
const y = parse(b);
if (!x || !y)
return undefined;
for (let i = 1; i <= 3; i++) {
const d = Number(x[i]) - Number(y[i]);
if (d)
return Math.sign(d);
}
if (x[4] === y[4])
return 0;
if (!x[4])
return 1;
if (!y[4])
return -1;
return x[4] < y[4] ? -1 : 1;
}
/**
* How the running map and a client differ. `map_older`: the map draws an older
* graph than the client knows, or — for the CLI, the program that serves the
* map — it runs an older CLI release; `client_older`: the client knows an older
* graph than the map draws. A server from before graph revisions counts as
* revision 0.
*/
export function mapSkew(server, client) {
const graph = server.graph ?? 0;
if (client.graph > graph)
return 'map_older';
if (client.graph < graph)
return 'client_older';
if (client.kind === 'cli' && (compareVersions(client.version, server.version) ?? 0) > 0)
return 'map_older';
return undefined;
}
export const mapPath = (home, file) => path.join(home, MAP_DIR, file);
function git(cwd, args) {
return new Promise((resolve) => {
execFile('git', args, { cwd, timeout: 5_000, windowsHide: true }, (error, stdout) => resolve(error ? undefined : stdout));
});
}
async function isDirectory(location) {
try {
return (await stat(location)).isDirectory();
}
catch {
return false;
}
}
/**
* The map home for `dir`: `dir` itself, unless it sits in a linked git worktree
* whose main working tree has the same directory — then that one. Outside git,
* in a bare-repository worktree or a submodule, the directory stays its own home.
*/
export async function resolveMapHome(dir) {
const real = await realpath(path.resolve(dir));
const own = { home: real, dir: real, worktree: false };
const out = await git(real, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir']);
const [top, common] = (out ?? '').trim().split('\n');
if (!top || !common || path.basename(common) !== '.git')
return own;
let mainRoot;
let topReal;
try {
mainRoot = await realpath(path.dirname(common));
topReal = await realpath(top);
}
catch {
return own;
}
if (mainRoot === topReal)
return own;
const candidate = path.join(mainRoot, path.relative(topReal, real));
if (!(await isDirectory(candidate)))
return own;
return { home: candidate, dir: real, worktree: true };
}
/** Every checkout of the repository `home` belongs to (main first), mapped to the project directory in each. */
export async function projectCheckouts(home) {
const out = await git(home, ['worktree', 'list', '--porcelain']);
const top = (await git(home, ['rev-parse', '--show-toplevel']))?.trim();
if (!out || !top)
return [home];
const relative = path.relative(top, home);
const roots = out
.split('\n')
.filter((line) => line.startsWith('worktree '))
.map((line) => line.slice('worktree '.length));
const dirs = [home];
for (const root of roots) {
const candidate = path.join(root, relative);
if (!dirs.includes(candidate) && (await isDirectory(candidate)))
dirs.push(candidate);
}
return dirs;
}
export function pidAlive(pid) {
if (!Number.isInteger(pid) || pid <= 0)
return false;
try {
process.kill(pid, 0);
return true;
}
catch (error) {
return error.code === 'EPERM';
}
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function readOwner(lockDir) {
try {
return JSON.parse(await readFile(path.join(lockDir, 'owner.json'), 'utf8'));
}
catch {
return undefined; // created a moment ago and not written yet, or a crash in between
}
}
/**
* Whether the lock as it is now may be taken over: its owner died on this
* machine, or it is older than `staleMs` (the critical sections take
* milliseconds). `undefined` when the lock is gone.
*/
async function lockIsStale(lockDir, staleMs) {
const owner = await readOwner(lockDir);
let age;
try {
age = Date.now() - (owner?.at ?? (await stat(lockDir)).mtimeMs);
}
catch {
return undefined;
}
const dead = owner !== undefined && owner.host === os.hostname() && !pidAlive(owner.pid);
return dead || age > staleMs;
}
/**
* Hold `<lockDir>.breaker` while removing `lockDir`. Every removal — a release
* and a takeover alike — happens under it and re-checks the lock it is about to
* remove, so a waiter that judged a dead owner's lock stale a moment ago cannot
* delete the fresh lock another waiter has taken since. The breaker is held for
* a few file operations; one older than 10 s belongs to a process that crashed
* inside them.
*/
async function withBreaker(lockDir, deadline, remove) {
const breaker = `${lockDir}.breaker`;
for (;;) {
try {
await mkdir(breaker);
break;
}
catch (error) {
if (error.code !== 'EEXIST')
throw error;
}
try {
if (Date.now() - (await stat(breaker)).mtimeMs > 10_000)
await rm(breaker, { recursive: true, force: true });
}
catch {
// released while we looked
}
if (Date.now() > deadline)
throw new Error(`${path.basename(breaker)} is held; remove it if no extenshi command runs.`);
await sleep(2 + Math.floor(Math.random() * 8));
}
try {
await remove();
}
finally {
await rm(breaker, { recursive: true, force: true });
}
}
/** Move the lock directory aside, then delete it: after the rename, `mkdir(lockDir)` is free again. */
async function removeLockDir(lockDir) {
const aside = `${lockDir}.gone-${randomUUID()}`;
try {
await rename(lockDir, aside);
}
catch {
return; // already gone
}
await rm(aside, { recursive: true, force: true });
}
/**
* Run `work` holding a directory lock. `mkdir` is atomic, so exactly one
* process creates the directory; its `owner.json` carries a random token. A
* lock whose owner died on this machine, or that is older than `staleMs`, is
* taken over — but the verdict is checked again under the breaker
* (`withBreaker`) before anything is removed, and a release removes the lock
* only while it still carries this holder's token.
*/
export async function withDirLock(lockDir, work, options = {}) {
const timeoutMs = options.timeoutMs ?? 10_000;
const staleMs = options.staleMs ?? 30_000;
const deadline = Date.now() + timeoutMs;
await mkdir(path.dirname(lockDir), { recursive: true });
for (;;) {
try {
await mkdir(lockDir);
break;
}
catch (error) {
if (error.code !== 'EEXIST')
throw error;
}
const stale = await lockIsStale(lockDir, staleMs);
if (stale === undefined)
continue; // released while we looked
if (stale) {
await withBreaker(lockDir, deadline, async () => {
if (await lockIsStale(lockDir, staleMs))
await removeLockDir(lockDir);
});
continue;
}
if (Date.now() > deadline)
throw new Error(`${options.what ?? path.basename(lockDir)} is held by process ${(await readOwner(lockDir))?.pid ?? 'unknown'}. ` +
'If no extenshi command is running, remove the lock directory.');
await sleep(20 + Math.floor(Math.random() * 40));
}
const token = randomUUID();
try {
const owner = { pid: process.pid, host: os.hostname(), at: Date.now(), token };
await writeFile(path.join(lockDir, 'owner.json'), JSON.stringify(owner));
return await work();
}
finally {
await withBreaker(lockDir, Date.now() + 15_000, async () => {
if ((await readOwner(lockDir))?.token === token)
await removeLockDir(lockDir);
});
}
}
/** Write JSON so a concurrent reader sees the old file or the new one, never a mix. */
export async function writeJsonAtomic(file, value, mode = 0o644) {
await mkdir(path.dirname(file), { recursive: true });
const temporary = `${file}.${randomUUID()}.tmp`;
try {
const handle = await open(temporary, 'wx', mode);
try {
await handle.writeFile(`${JSON.stringify(value, null, '\t')}\n`);
await handle.sync();
}
finally {
await handle.close();
}
await rename(temporary, file);
}
finally {
await rm(temporary, { force: true });
}
}
/** Read the state for display: a missing or broken file reads as empty, with the problem named. */
export async function readMapState(home) {
let text;
try {
text = await readFile(mapPath(home, MAP_STATE_FILE), 'utf8');
}
catch (error) {
if (error.code === 'ENOENT')
return { state: emptyBuildMapState(), exists: false };
return { state: emptyBuildMapState(), exists: true, problem: error.message };
}
try {
return { state: normalizeBuildMapState(JSON.parse(text)), exists: true };
}
catch (error) {
return {
state: emptyBuildMapState(),
exists: true,
problem: `${MAP_STATE_FILE}: ${error.message}`,
};
}
}
/**
* Read, change and write the state as one step, under the state lock, so two
* agents reporting at the same moment both land. Refuses to write over a file
* it cannot read rather than replace someone's edit with an empty map.
*/
export async function updateMapState(home, change) {
return withDirLock(mapPath(home, STATE_LOCK), async () => {
const read = await readMapState(home);
if (read.problem)
throw new Error(`Cannot update the build map: ${read.problem}`);
const next = change(read.state) ?? read.state;
await writeJsonAtomic(mapPath(home, MAP_STATE_FILE), next, 0o600);
return next;
}, { what: `${MAP_DIR}/${STATE_LOCK}` });
}
export async function readServerRecord(home) {
try {
const record = JSON.parse(await readFile(mapPath(home, MAP_SERVER_FILE), 'utf8'));
if (typeof record?.port !== 'number' || typeof record?.instance !== 'string')
return undefined;
return record;
}
catch {
return undefined;
}
}
export async function fetchHealth(port, timeoutMs = 1_500, headers) {
try {
const response = await fetch(`http://127.0.0.1:${port}/api/health`, {
signal: AbortSignal.timeout(timeoutMs),
...(headers ? { headers } : {}),
});
if (!response.ok)
return undefined;
return (await response.json());
}
catch {
return undefined;
}
}
/**
* The server recorded for `home`, if it is really up: same machine, process
* alive, and its health answer carries the recorded instance id and home. A
* record left by a crash, by another machine (a synced folder) or a reused pid
* reads as no server. With `client`, the probe also tells the server which
* program asks and which graph it knows, so the map can offer an update when
* an agent works with newer steps than the map draws.
*/
export async function probeServer(home, client) {
const record = await readServerRecord(home);
if (!record || record.host !== os.hostname() || !pidAlive(record.pid))
return undefined;
const health = await fetchHealth(record.port, 1_500, client && record.token
? { [MAP_TOKEN_HEADER]: record.token, [MAP_CLIENT_HEADER]: mapClientHeader(client) }
: undefined);
if (!health || health.instance !== record.instance || health.home !== home)
return undefined;
return {
...record,
version: health.version ?? record.version,
clients: health.clients,
graph: health.graph ?? 0,
...(health.available ? { available: health.available } : {}),
...(health.updating ? { updating: health.updating } : {}),
};
}
export const serverLockPath = (home) => mapPath(home, SERVER_LOCK);
/**
* Mark the server record stopped, but only if it still names `instance` —
* never a successor's. The port stays in it, so the next start binds the same
* address and a tab left open reconnects by itself; pid 0 and no token make it
* read as no server.
*/
export async function retireServerRecord(home, instance) {
const record = await readServerRecord(home);
if (record?.instance !== instance)
return;
await writeJsonAtomic(mapPath(home, MAP_SERVER_FILE), { ...record, pid: 0, token: '', stoppedAt: new Date().toISOString() }, 0o600);
}
//# sourceMappingURL=build-map-store.js.map