Skip to content

armgit / bla

Public Imported from GitHub
0

🛡️ BLA (Blind LLM Agents) — Adversarial defense shield that protects binaries, Electron apps, JS bundles, Python, and WebAssembly against AI reverse-engineering agents like REA. Poison -> Exhaust -> Hallucinate.

fix(setup,mcp,doctor,release): native client config adapters, ownership backups, MCP schema validation, doctor readiness, and release consistency (Fixes #8, Fixes #9, Fixes #10, Fixes #11, Fixes #12)

qybaihecef7ee323e2d
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 1a99ac5..5ea936a 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -9,6 +9,11 @@ on:
- "v*"
workflow_dispatch:
inputs:
+ version:
+ description: "Expected release version (must match package.json after optional bump)"
+ required: false
+ default: ""
+ type: string
bump:
description: "Optional version bump before publishing (none | patch | minor | major)"
required: false
@@ -60,15 +65,66 @@ jobs:
git commit -m "chore(release): bump bla-agents to v${VERSION}"
git push origin HEAD:main
- - name: Check if current package.json version is already on npm
+ - name: Verify version, trigger tag, and target tag commit consistency
id: check_npm
+ env:
+ DISPATCH_VERSION: ${{ inputs.version }}
+ TRIGGER_REF: ${{ github.ref }}
run: |
+ set -euo pipefail
LOCAL_VERSION=$(node -p "require('./package.json').version")
- NPM_VERSION=$(npm view bla-agents version 2>/dev/null || echo "none")
- echo "local_version=$LOCAL_VERSION" >> "$GITHUB_OUTPUT"
- echo "npm_version=$NPM_VERSION" >> "$GITHUB_OUTPUT"
- echo "tag=bla-agents-$LOCAL_VERSION" >> "$GITHUB_OUTPUT"
- if [ "$LOCAL_VERSION" != "$NPM_VERSION" ] || [ "${{ github.event_name }}" = "workflow_dispatch" ] || [[ "${{ github.ref }}" == refs/tags/* ]]; then
+ HEAD_SHA=$(git rev-parse HEAD)
+ TAG="bla-agents-${LOCAL_VERSION}"
+
+ # 1. Verify workflow_dispatch version input matches manifest if provided
+ if [ -n "${DISPATCH_VERSION}" ]; then
+ NORM_DISPATCH="${DISPATCH_VERSION#v}"
+ NORM_DISPATCH="${NORM_DISPATCH#bla-agents-}"
+ if [ "${NORM_DISPATCH}" != "${LOCAL_VERSION}" ]; then
+ echo "::error::workflow_dispatch version '${DISPATCH_VERSION}' does not match package.json version '${LOCAL_VERSION}'"
+ exit 1
+ fi
+ fi
+
+ # 2. Verify trigger tag matches manifest if triggered by refs/tags/*
+ if [[ "${TRIGGER_REF}" == refs/tags/* ]]; then
+ RAW_TAG="${TRIGGER_REF#refs/tags/}"
+ if [[ "${RAW_TAG}" == bla-agents-* ]]; then
+ TAG_VER="${RAW_TAG#bla-agents-}"
+ elif [[ "${RAW_TAG}" == v* ]]; then
+ TAG_VER="${RAW_TAG#v}"
+ else
+ echo "::error::Unsupported release tag format '${RAW_TAG}'"
+ exit 1
+ fi
+ if [ "${TAG_VER}" != "${LOCAL_VERSION}" ]; then
+ echo "::error::Trigger tag '${RAW_TAG}' does not match package.json version '${LOCAL_VERSION}'"
+ exit 1
+ fi
+ fi
+
+ # 3. Verify existing remote/local tag points to current HEAD_SHA
+ EXISTING_TAG_SHA=""
+ if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null 2>&1; then
+ git fetch origin "refs/tags/${TAG}:refs/tags/${TAG}" --force
+ EXISTING_TAG_SHA=$(git rev-list -n 1 "${TAG}")
+ elif git rev-parse "${TAG}" >/dev/null 2>&1; then
+ EXISTING_TAG_SHA=$(git rev-list -n 1 "${TAG}")
+ fi
+
+ if [ -n "${EXISTING_TAG_SHA}" ] && [ "${EXISTING_TAG_SHA}" != "${HEAD_SHA}" ]; then
+ echo "::error::Existing tag '${TAG}' points to ${EXISTING_TAG_SHA}, which differs from checkout commit ${HEAD_SHA}. Refusing cross-commit release."
+ exit 1
+ fi
+
+ PRIMARY_NPM_VERSION=$(npm view "bla-agents@${LOCAL_VERSION}" version 2>/dev/null || echo "none")
+ ALIAS_NPM_VERSION=$(npm view "bla-shield@${LOCAL_VERSION}" version 2>/dev/null || echo "none")
+ echo "local_version=${LOCAL_VERSION}" >> "$GITHUB_OUTPUT"
+ echo "head_sha=${HEAD_SHA}" >> "$GITHUB_OUTPUT"
+ echo "existing_tag_sha=${EXISTING_TAG_SHA}" >> "$GITHUB_OUTPUT"
+ echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
+
+ if [ "${LOCAL_VERSION}" != "${PRIMARY_NPM_VERSION}" ] || [ "${LOCAL_VERSION}" != "${ALIAS_NPM_VERSION}" ] || [ "${{ github.event_name }}" = "workflow_dispatch" ] || [[ "${TRIGGER_REF}" == refs/tags/* ]]; then
echo "should_publish=true" >> "$GITHUB_OUTPUT"
else
echo "should_publish=false" >> "$GITHUB_OUTPUT"
@@ -82,44 +138,90 @@ jobs:
npm test
npm run benchmark
- - name: Package bla-agents release artifact
+ - name: Pack primary and alias release tarballs & verify consistency
+ if: steps.check_npm.outputs.should_publish == 'true'
+ env:
+ DISPATCH_VERSION: ${{ inputs.version }}
+ TRIGGER_REF: ${{ github.ref }}
+ HEAD_SHA: ${{ steps.check_npm.outputs.head_sha }}
+ EXISTING_TAG_SHA: ${{ steps.check_npm.outputs.existing_tag_sha }}
+ run: |
+ node --input-type=module -e '
+ import { readFileSync } from "node:fs";
+ import { BLA_IDENTITY } from "./dist/identity.js";
+ import { packDualReleaseTarballs, verifyReleaseConsistency } from "./dist/core/release-plan.js";
+ const pkg = JSON.parse(readFileSync("./package.json", "utf8"));
+ const packed = packDualReleaseTarballs(process.cwd(), "./release-assets");
+ const plan = verifyReleaseConsistency({
+ packageVersion: pkg.version,
+ identityVersion: BLA_IDENTITY.version,
+ dispatchVersion: process.env.DISPATCH_VERSION || null,
+ triggerRef: process.env.TRIGGER_REF || null,
+ headSha: process.env.HEAD_SHA,
+ existingTagSha: process.env.EXISTING_TAG_SHA || null,
+ tarballSha256: packed.primary.sha256,
+ aliasTarballSha256: packed.alias.sha256,
+ });
+ console.log("Release plan verified:", JSON.stringify(plan, null, 2));
+ '
+ cat release-assets/SHA256SUMS.txt
+
+ - name: Publish bla-agents and bla-shield tarballs to npm
if: steps.check_npm.outputs.should_publish == 'true'
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+ VERSION: ${{ steps.check_npm.outputs.local_version }}
run: |
- mkdir -p release-assets
- npm pack --pack-destination release-assets
- cd release-assets
- shasum -a 256 *.tgz > SHA256SUMS.txt
- cat SHA256SUMS.txt
+ set -euo pipefail
+ PRIMARY_TGZ="./release-assets/bla-agents-${VERSION}.tgz"
+ ALIAS_TGZ="./release-assets/bla-shield-${VERSION}.tgz"
+
+ if npm view "bla-agents@${VERSION}" version >/dev/null 2>&1; then
+ echo "bla-agents@${VERSION} is already published on npm; skipping primary publish."
+ else
+ npm publish "${PRIMARY_TGZ}" --provenance --access public \
+ || npm publish "${PRIMARY_TGZ}" --access public
+ fi
- - name: Create or update GitHub Release
+ if npm view "bla-shield@${VERSION}" version >/dev/null 2>&1; then
+ echo "bla-shield@${VERSION} is already published on npm; skipping alias publish."
+ else
+ npm publish "${ALIAS_TGZ}" --provenance --access public \
+ || npm publish "${ALIAS_TGZ}" --access public
+ fi
+
+ - name: Create or idempotently verify GitHub Release (no cross-commit clobber)
if: steps.check_npm.outputs.should_publish == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAG: ${{ steps.check_npm.outputs.tag }}
VERSION: ${{ steps.check_npm.outputs.local_version }}
+ HEAD_SHA: ${{ steps.check_npm.outputs.head_sha }}
run: |
+ set -euo pipefail
if ! git rev-parse "$TAG" >/dev/null 2>&1; then
- git tag "$TAG"
- git push origin "$TAG" || true
+ git tag "$TAG" "$HEAD_SHA"
+ git push origin "$TAG"
+ else
+ TAG_SHA=$(git rev-list -n 1 "$TAG")
+ if [ "$TAG_SHA" != "$HEAD_SHA" ]; then
+ echo "::error::Tag $TAG points to $TAG_SHA instead of $HEAD_SHA"
+ exit 1
+ fi
+ git push origin "$TAG"
fi
+
if gh release view "$TAG" >/dev/null 2>&1; then
- gh release upload "$TAG" release-assets/* --clobber
+ mkdir -p existing-release-assets
+ gh release download "$TAG" --dir existing-release-assets --pattern "SHA256SUMS.txt"
+ if ! cmp -s release-assets/SHA256SUMS.txt existing-release-assets/SHA256SUMS.txt; then
+ echo "::error::Existing GitHub Release '$TAG' has different SHA256SUMS.txt; refusing to clobber release assets."
+ exit 1
+ fi
+ echo "GitHub Release '$TAG' already exists with identical SHA-256 digests."
else
gh release create "$TAG" release-assets/* \
+ --verify-tag \
--title "bla-agents: v${VERSION}" \
--generate-notes
fi
-
- - name: Publish bla-agents to npm (Trusted Publishing OIDC or NPM_TOKEN)
- if: steps.check_npm.outputs.should_publish == 'true'
- env:
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- run: |
- LOCAL_VERSION="${{ steps.check_npm.outputs.local_version }}"
- if npm view "bla-agents@${LOCAL_VERSION}" version >/dev/null 2>&1; then
- echo "bla-agents@${LOCAL_VERSION} is already published on npm."
- else
- npm publish --provenance --access public \
- || npm publish --access public \
- || (rm -f "${NPM_CONFIG_USERCONFIG:-$HOME/.npmrc}" && unset NODE_AUTH_TOKEN && npm publish --provenance --access public)
- fi
diff --git a/src/cli.ts b/src/cli.ts
index 8bd4432..df12620 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -218,7 +218,7 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
const doc = runDoctor();
if (parsed.json) console.log(JSON.stringify(doc, null, 2));
else console.log(formatDoctorReport(doc));
- return 0;
+ return doc.healthy ? 0 : 1;
}
case "update": {
diff --git a/src/core/release-plan.ts b/src/core/release-plan.ts
new file mode 100644
index 0000000..5a0255c
--- /dev/null
+++ b/src/core/release-plan.ts
@@ -0,0 +1,389 @@
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { basename, join, resolve } from "node:path";
+
+export type ReleaseConsistencyErrorCode =
+ | "INVALID_PACKAGE_VERSION"
+ | "IDENTITY_VERSION_MISMATCH"
+ | "DISPATCH_VERSION_MISMATCH"
+ | "TRIGGER_TAG_MISMATCH"
+ | "INVALID_COMMIT_SHA"
+ | "TAG_COMMIT_MISMATCH"
+ | "INVALID_TARBALL_HASH"
+ | "ASSET_HASH_CONFLICT";
+
+export class ReleaseConsistencyError extends Error {
+ public readonly code: ReleaseConsistencyErrorCode;
+
+ public constructor(code: ReleaseConsistencyErrorCode, message: string) {
+ super(message);
+ this.name = "ReleaseConsistencyError";
+ this.code = code;
+ }
+}
+
+export interface ReleaseConsistencyInput {
+ readonly packageVersion: string;
+ readonly identityVersion?: string | null;
+ readonly dispatchVersion?: string | null;
+ readonly triggerRef?: string | null;
+ readonly headSha: string;
+ readonly existingTagSha?: string | null;
+ readonly tarballSha256: string;
+ readonly existingReleaseAssetSha256?: string | null;
+ readonly aliasTarballSha256?: string | null;
+ readonly existingAliasReleaseAssetSha256?: string | null;
+}
+
+export interface ReleaseConsistencyPlan {
+ readonly version: string;
+ readonly canonicalTag: string;
+ readonly headSha: string;
+ readonly tagAction: "create" | "verify-existing-idempotent";
+ readonly releaseAssetAction: "upload-new" | "skip-identical";
+ readonly tarballSha256: string;
+ readonly aliasTarballSha256: string | null;
+}
+
+const SEMVER_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
+const GIT_SHA_RE = /^[0-9a-f]{7,40}$/i;
+const SHA256_RE = /^[0-9a-f]{64}$/i;
+
+export function verifyReleaseConsistency(
+ input: ReleaseConsistencyInput,
+): ReleaseConsistencyPlan {
+ const pkgVer = (input.packageVersion ?? "").trim();
+ if (!SEMVER_RE.test(pkgVer)) {
+ throw new ReleaseConsistencyError(
+ "INVALID_PACKAGE_VERSION",
+ `Invalid package.json version '${input.packageVersion}': expected strict semver (X.Y.Z)`,
+ );
+ }
+
+ if (input.identityVersion !== undefined && input.identityVersion !== null) {
+ const idVer = input.identityVersion.trim();
+ if (idVer !== pkgVer) {
+ throw new ReleaseConsistencyError(
+ "IDENTITY_VERSION_MISMATCH",
+ `BLA_IDENTITY.version '${idVer}' does not match package.json version '${pkgVer}'`,
+ );
+ }
+ }
+
+ const headSha = (input.headSha ?? "").trim().toLowerCase();
+ if (!GIT_SHA_RE.test(headSha)) {
+ throw new ReleaseConsistencyError(
+ "INVALID_COMMIT_SHA",
+ `Invalid checkout commit SHA '${input.headSha}'`,
+ );
+ }
+
+ const tarballSha256 = (input.tarballSha256 ?? "").trim().toLowerCase();
+ if (!SHA256_RE.test(tarballSha256)) {
+ throw new ReleaseConsistencyError(
+ "INVALID_TARBALL_HASH",
+ `Invalid tarball SHA-256 digest '${input.tarballSha256}'`,
+ );
+ }
+
+ let aliasTarballSha256: string | null = null;
+ if (input.aliasTarballSha256 !== undefined && input.aliasTarballSha256 !== null) {
+ aliasTarballSha256 = input.aliasTarballSha256.trim().toLowerCase();
+ if (!SHA256_RE.test(aliasTarballSha256)) {
+ throw new ReleaseConsistencyError(
+ "INVALID_TARBALL_HASH",
+ `Invalid alias tarball SHA-256 digest '${input.aliasTarballSha256}'`,
+ );
+ }
+ }
+
+ // 1. Validate workflow_dispatch version input if provided
+ if (input.dispatchVersion !== undefined && input.dispatchVersion !== null) {
+ const rawDispatch = input.dispatchVersion.trim();
+ if (rawDispatch.length > 0 && rawDispatch !== "none") {
+ const normalizedDispatch = rawDispatch.startsWith("v")
+ ? rawDispatch.slice(1)
+ : rawDispatch.startsWith("bla-agents-")
+ ? rawDispatch.slice("bla-agents-".length)
+ : rawDispatch;
+ if (normalizedDispatch !== pkgVer) {
+ throw new ReleaseConsistencyError(
+ "DISPATCH_VERSION_MISMATCH",
+ `workflow_dispatch version input '${rawDispatch}' does not match package.json version '${pkgVer}'`,
+ );
+ }
+ }
+ }
+
+ // 2. Validate trigger tag ref if triggered by a tag push
+ if (input.triggerRef !== undefined && input.triggerRef !== null) {
+ const ref = input.triggerRef.trim();
+ if (
+ ref.startsWith("refs/tags/") ||
+ ref.startsWith("bla-agents-") ||
+ /^v\d+\./.test(ref)
+ ) {
+ const tagName = ref.startsWith("refs/tags/") ? ref.slice("refs/tags/".length) : ref;
+ let extractedVersion: string | null = null;
+ if (tagName.startsWith("bla-agents-")) {
+ extractedVersion = tagName.slice("bla-agents-".length);
+ } else if (tagName.startsWith("v")) {
+ extractedVersion = tagName.slice(1);
+ }
+ if (!extractedVersion || extractedVersion !== pkgVer) {
+ throw new ReleaseConsistencyError(
+ "TRIGGER_TAG_MISMATCH",
+ `Trigger tag '${tagName}' does not match package.json version '${pkgVer}'`,
+ );
+ }
+ }
+ }
+
+ const canonicalTag = `bla-agents-${pkgVer}`;
+
+ // 3. Verify existing tag commit matches checkout commit
+ let tagAction: ReleaseConsistencyPlan["tagAction"] = "create";
+ if (
+ input.existingTagSha !== undefined &&
+ input.existingTagSha !== null &&
+ input.existingTagSha.trim().length > 0
+ ) {
+ const existingSha = input.existingTagSha.trim().toLowerCase();
+ if (!GIT_SHA_RE.test(existingSha)) {
+ throw new ReleaseConsistencyError(
+ "INVALID_COMMIT_SHA",
+ `Invalid existing tag commit SHA '${input.existingTagSha}'`,
+ );
+ }
+ if (existingSha !== headSha) {
+ throw new ReleaseConsistencyError(
+ "TAG_COMMIT_MISMATCH",
+ `Existing tag '${canonicalTag}' points to commit ${existingSha}, which differs from checkout commit ${headSha}; refusing cross-commit release overwrite`,
+ );
+ }
+ tagAction = "verify-existing-idempotent";
+ }
+
+ // 4. Verify existing release asset SHA-256 matches packed tarball SHA-256
+ let releaseAssetAction: ReleaseConsistencyPlan["releaseAssetAction"] = "upload-new";
+ if (
+ input.existingReleaseAssetSha256 !== undefined &&
+ input.existingReleaseAssetSha256 !== null &&
+ input.existingReleaseAssetSha256.trim().length > 0
+ ) {
+ const existingAssetHash = input.existingReleaseAssetSha256.trim().toLowerCase();
+ if (existingAssetHash !== tarballSha256) {
+ throw new ReleaseConsistencyError(
+ "ASSET_HASH_CONFLICT",
+ `Existing release asset SHA-256 (${existingAssetHash}) differs from packed tarball SHA-256 (${tarballSha256}); refusing to clobber`,
+ );
+ }
+ releaseAssetAction = "skip-identical";
+ }
+
+ if (
+ aliasTarballSha256 !== null &&
+ input.existingAliasReleaseAssetSha256 !== undefined &&
+ input.existingAliasReleaseAssetSha256 !== null &&
+ input.existingAliasReleaseAssetSha256.trim().length > 0
+ ) {
+ const existingAliasHash = input.existingAliasReleaseAssetSha256.trim().toLowerCase();
+ if (existingAliasHash !== aliasTarballSha256) {
+ throw new ReleaseConsistencyError(
+ "ASSET_HASH_CONFLICT",
+ `Existing alias release asset SHA-256 (${existingAliasHash}) differs from packed alias tarball SHA-256 (${aliasTarballSha256}); refusing to clobber`,
+ );
+ }
+ }
+
+ return {
+ version: pkgVer,
+ canonicalTag,
+ headSha,
+ tagAction,
+ releaseAssetAction,
+ tarballSha256,
+ aliasTarballSha256,
+ };
+}
+
+export interface PackagePublishInputState {
+ readonly primaryPublished: boolean;
+ readonly aliasPublished?: boolean;
+ readonly primaryTarballSha256?: string;
+ readonly publishedPrimarySha256?: string | null;
+ readonly aliasTarballSha256?: string;
+ readonly publishedAliasSha256?: string | null;
+}
+
+export interface NpmPublishRetryPlan {
+ readonly primaryAction: "publish" | "skip-already-published";
+ readonly aliasAction: "publish" | "skip-already-published";
+ readonly shouldPublishPrimary: boolean;
+ readonly shouldPublishAlias: boolean;
+ readonly requiresPublish: boolean;
+ readonly allCompletedAfterPlan: boolean;
+}
+
+/**
+ * Computes an idempotent dual-package (`bla-agents` primary + `bla-shield` alias)
+ * npm publish plan so that a retry after `primary` succeeds and `alias` fails
+ * safely completes `alias` without failing on `primary` or clobbering different bytes.
+ */
+export function planNpmPublishRetry(state: PackagePublishInputState): NpmPublishRetryPlan {
+ if (
+ state.primaryPublished &&
+ state.primaryTarballSha256 &&
+ state.publishedPrimarySha256 &&
+ state.primaryTarballSha256.trim().toLowerCase() !==
+ state.publishedPrimarySha256.trim().toLowerCase()
+ ) {
+ throw new ReleaseConsistencyError(
+ "ASSET_HASH_CONFLICT",
+ `Published primary package SHA-256 (${state.publishedPrimarySha256}) differs from local tarball SHA-256 (${state.primaryTarballSha256})`,
+ );
+ }
+
+ if (
+ state.aliasPublished &&
+ state.aliasTarballSha256 &&
+ state.publishedAliasSha256 &&
+ state.aliasTarballSha256.trim().toLowerCase() !==
+ state.publishedAliasSha256.trim().toLowerCase()
+ ) {
+ throw new ReleaseConsistencyError(
+ "ASSET_HASH_CONFLICT",
+ `Published alias package SHA-256 (${state.publishedAliasSha256}) differs from local alias tarball SHA-256 (${state.aliasTarballSha256})`,
+ );
+ }
+
+ const shouldPublishPrimary = !state.primaryPublished;
+ const shouldPublishAlias = !(state.aliasPublished ?? false);
+
+ return {
+ primaryAction: shouldPublishPrimary ? "publish" : "skip-already-published",
+ aliasAction: shouldPublishAlias ? "publish" : "skip-already-published",
+ shouldPublishPrimary,
+ shouldPublishAlias,
+ requiresPublish: shouldPublishPrimary || shouldPublishAlias,
+ allCompletedAfterPlan: true,
+ };
+}
+
+export interface PackedPackageArtifact {
+ readonly packageName: string;
+ readonly version: string;
+ readonly tarballPath: string;
+ readonly tarballFilename: string;
+ readonly sha256: string;
+}
+
+export interface DualPackResult {
+ readonly version: string;
+ readonly primary: PackedPackageArtifact;
+ readonly alias: PackedPackageArtifact;
+ readonly sha256SumsPath: string;
+}
+
+function sha256File(filePath: string): string {
+ return createHash("sha256").update(readFileSync(filePath)).digest("hex");
+}
+
+/**
+ * Packs both `bla-agents` (primary) and `bla-shield` (alias) tarballs into `outDir`
+ * without mutating the repository working tree, and writes `SHA256SUMS.txt`.
+ */
+export function packDualReleaseTarballs(repoDir: string, outDir: string): DualPackResult {
+ const absRepo = resolve(repoDir);
+ const absOut = resolve(outDir);
+ mkdirSync(absOut, { recursive: true });
+
+ const pkgJsonPath = join(absRepo, "package.json");
+ if (!existsSync(pkgJsonPath)) {
+ throw new Error(`package.json not found in '${absRepo}'`);
+ }
+ const pkgJson = JSON.parse(readFileSync(pkgJsonPath, "utf8")) as {
+ name: string;
+ version: string;
+ };
+ const version = pkgJson.version;
+
+ // 1. Pack primary (`bla-agents-<version>.tgz`) directly into `absOut`
+ execFileSync("npm", ["pack", "--pack-destination", absOut], {
+ cwd: absRepo,
+ stdio: "pipe",
+ });
+
+ const primaryFilename = `bla-agents-${version}.tgz`;
+ const primaryPath = join(absOut, primaryFilename);
+ if (!existsSync(primaryPath)) {
+ throw new Error(`Expected packed tarball at '${primaryPath}'`);
+ }
+ const primarySha256 = sha256File(primaryPath);
+
+ // 2. Build alias (`bla-shield-<version>.tgz`) in an isolated temp staging directory
+ const stageDir = mkdtempSync(join(tmpdir(), "bla-alias-pack-"));
+ try {
+ execFileSync("tar", ["-xzf", primaryPath, "-C", stageDir], {
+ stdio: "pipe",
+ });
+ const unpackedPkgDir = join(stageDir, "package");
+ const unpackedPkgJsonPath = join(unpackedPkgDir, "package.json");
+ const unpackedPkg = JSON.parse(readFileSync(unpackedPkgJsonPath, "utf8")) as Record<
+ string,
+ unknown
+ >;
+ unpackedPkg.name = "bla-shield";
+ writeFileSync(unpackedPkgJsonPath, JSON.stringify(unpackedPkg, null, 2) + "\n", "utf8");
+
+ execFileSync("npm", ["pack", "--pack-destination", absOut, "--ignore-scripts"], {
+ cwd: unpackedPkgDir,
+ stdio: "pipe",
+ });
+ } finally {
+ rmSync(stageDir, { recursive: true, force: true });
+ }
+
+ const aliasFilename = `bla-shield-${version}.tgz`;
+ const aliasPath = join(absOut, aliasFilename);
+ if (!existsSync(aliasPath)) {
+ throw new Error(`Expected packed alias tarball at '${aliasPath}'`);
+ }
+ const aliasSha256 = sha256File(aliasPath);
+
+ const sha256SumsPath = join(absOut, "SHA256SUMS.txt");
+ const sumsContent = [
+ `${primarySha256} ${basename(primaryPath)}`,
+ `${aliasSha256} ${basename(aliasPath)}`,
+ "",
+ ].join("\n");
+ writeFileSync(sha256SumsPath, sumsContent, "utf8");
+
+ return {
+ version,
+ primary: {
+ packageName: "bla-agents",
+ version,
+ tarballPath: primaryPath,
+ tarballFilename: primaryFilename,
+ sha256: primarySha256,
+ },
+ alias: {
+ packageName: "bla-shield",
+ version,
+ tarballPath: aliasPath,
+ tarballFilename: aliasFilename,
+ sha256: aliasSha256,
+ },
+ sha256SumsPath,
+ };
+}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index f5ec83a..03c0ef4 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -31,7 +31,65 @@ export interface JsonRpcResponse {
};
}
-export const BLA_MCP_TOOLS = Object.freeze([
+export interface McpPropertySchema {
+ readonly type: "string" | "boolean" | "number";
+ readonly description?: string;
+ readonly enum?: readonly string[];
+}
+
+export interface McpToolDefinition {
+ readonly name: string;
+ readonly description: string;
+ readonly inputSchema: {
+ readonly type: "object";
+ readonly properties: Readonly<Record<string, McpPropertySchema | undefined>>;
+ readonly required?: readonly string[];
+ readonly additionalProperties?: boolean;
+ };
+}
+
+export interface McpPromptArgumentDefinition {
+ readonly name: string;
+ readonly description: string;
+ readonly required: boolean;
+}
+
+export interface McpPromptDefinition {
+ readonly name: string;
+ readonly description: string;
+ readonly arguments: readonly McpPromptArgumentDefinition[];
+}
+
+export interface McpEngineHandlers {
+ readonly defendTarget: typeof defendTarget;
+ readonly auditTarget: typeof auditTarget;
+ readonly protectTarget: typeof protectTarget;
+ readonly verifyTarget: typeof verifyTarget;
+ readonly runShowcaseBenchmark: typeof runShowcaseBenchmark;
+ readonly emitCompileTimeNativeHeader: typeof emitCompileTimeNativeHeader;
+ readonly runDoctor: typeof runDoctor;
+ readonly inspectReleaseExposure: typeof inspectReleaseExposure;
+ readonly initBlaConfig: typeof initBlaConfig;
+}
+
+const DEFAULT_ENGINE_HANDLERS: McpEngineHandlers = Object.freeze({
+ defendTarget,
+ auditTarget,
+ protectTarget,
+ verifyTarget,
+ runShowcaseBenchmark,
+ emitCompileTimeNativeHeader,
+ runDoctor,
+ inspectReleaseExposure,
+ initBlaConfig,
+});
+
+export const SUPPORTED_MCP_PROTOCOL_VERSIONS = Object.freeze([
+ "2024-11-05",
+ "2025-03-26",
+] as const);
+
+export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([
{
name: "bla_defend",
description:
@@ -58,6 +116,7 @@ export const BLA_MCP_TOOLS = Object.freeze([
},
},
required: ["input_path"],
+ additionalProperties: false,
},
},
{
@@ -73,6 +132,7 @@ export const BLA_MCP_TOOLS = Object.freeze([
},
},
required: ["path"],
+ additionalProperties: false,
},
},
{
@@ -101,6 +161,7 @@ export const BLA_MCP_TOOLS = Object.freeze([
},
},
required: ["input_path"],
+ additionalProperties: false,
},
},
{
@@ -120,15 +181,17 @@ export const BLA_MCP_TOOLS = Object.freeze([
},
},
required: ["target_path"],
+ additionalProperties: false,
},
},
{
name: "bla_benchmark",
description:
- "Runs the 5-target Counter-REA Showcase Benchmark (DX-Ball Sound-Pan, Notion Electron Clipboard ASAR, Enterprise License Guard, WebAssembly Crypto Core, and Native ELF64 Binary) and returns Before vs. After metrics.",
+ "Runs the Counter-REA Showcase Benchmark suite and returns Before vs. After metrics.",
inputSchema: {
type: "object",
properties: {},
+ additionalProperties: false,
},
},
{
@@ -149,6 +212,7 @@ export const BLA_MCP_TOOLS = Object.freeze([
},
},
required: ["language"],
+ additionalProperties: false,
},
},
{
@@ -157,7 +221,13 @@ export const BLA_MCP_TOOLS = Object.freeze([
"Checks readiness of all BLA protection engines and agent MCP registrations.",
inputSchema: {
type: "object",
- properties: {},
+ properties: {
+ home_dir: {
+ type: "string",
+ description: "Optional home directory path to inspect",
+ },
+ },
+ additionalProperties: false,
},
},
{
@@ -171,8 +241,17 @@ export const BLA_MCP_TOOLS = Object.freeze([
type: "string",
description: "Path to the build directory or artifact to inspect",
},
+ max_files: {
+ type: "number",
+ description: "Optional maximum number of files to scan",
+ },
+ max_total_bytes: {
+ type: "number",
+ description: "Optional maximum total bytes to scan",
+ },
},
required: ["path"],
+ additionalProperties: false,
},
},
{
@@ -184,20 +263,210 @@ export const BLA_MCP_TOOLS = Object.freeze([
properties: {
directory: {
type: "string",
- description: "Target project directory (defaults to current working directory)",
+ description: "Target project directory (pass '.' explicitly for current directory)",
},
overwrite: {
type: "boolean",
description: "Overwrite an existing bla.config.json if present",
},
},
+ required: ["directory"],
+ additionalProperties: false,
},
},
]);
+export const BLA_MCP_PROMPTS: readonly McpPromptDefinition[] = Object.freeze([
+ {
+ name: "shield-against-rea",
+ description:
+ "Audit a build artifact for REA exposure, apply BLA's adversarial shield, and verify the token bankruptcy factor.",
+ arguments: [
+ {
+ name: "target_path",
+ description: "Path to the build artifact or directory",
+ required: true,
+ },
+ ],
+ },
+ {
+ name: "bla-hardening-workflow",
+ description:
+ "Step-by-step release hardening checklist using bla_inspect_release, bla_audit, bla_protect, and bla_verify.",
+ arguments: [
+ {
+ name: "target_path",
+ description: "Path to the build artifact or directory",
+ required: true,
+ },
+ ],
+ },
+ {
+ name: "bla-counter-rea",
+ description:
+ "Evaluate REA reverse-engineering exposure and plan defensive hardening for a software artifact.",
+ arguments: [
+ {
+ name: "target_path",
+ description: "Path to the build artifact or directory",
+ required: true,
+ },
+ ],
+ },
+]);
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+export function validateMcpToolCall(
+ params: unknown,
+):
+ | {
+ readonly ok: true;
+ readonly tool: McpToolDefinition;
+ readonly args: Record<string, unknown>;
+ }
+ | {
+ readonly ok: false;
+ readonly code: -32601 | -32602;
+ readonly message: string;
+ } {
+ if (!isPlainObject(params)) {
+ return {
+ ok: false,
+ code: -32602,
+ message: "Invalid params: tool call params must be a JSON object",
+ };
+ }
+
+ if (typeof params.name !== "string" || params.name.trim().length === 0) {
+ return {
+ ok: false,
+ code: -32602,
+ message: "Invalid params: tool 'name' must be a non-empty string",
+ };
+ }
+
+ const tool = BLA_MCP_TOOLS.find((t) => t.name === params.name);
+ if (!tool) {
+ return {
+ ok: false,
+ code: -32602,
+ message: `Invalid params: unknown BLA MCP tool '${params.name}'`,
+ };
+ }
+
+ const rawArgs = params.arguments;
+ const requiredFields = tool.inputSchema.required ?? [];
+
+ if (rawArgs === undefined) {
+ if (requiredFields.length > 0) {
+ return {
+ ok: false,
+ code: -32602,
+ message: `Invalid params for '${tool.name}': missing required arguments (${requiredFields.join(", ")})`,
+ };
+ }
+ return { ok: true, tool, args: {} };
+ }
+
+ if (!isPlainObject(rawArgs)) {
+ return {
+ ok: false,
+ code: -32602,
+ message: `Invalid params for '${tool.name}': 'arguments' must be a JSON object`,
+ };
+ }
+
+ // Reject unexpected properties when additionalProperties is false
+ const allowedProps = tool.inputSchema.properties;
+ for (const key of Object.keys(rawArgs)) {
+ if (!(key in allowedProps)) {
+ return {
+ ok: false,
+ code: -32602,
+ message: `Invalid params for '${tool.name}': unknown argument '${key}'`,
+ };
+ }
+ }
+
+ // Validate required properties
+ for (const reqKey of requiredFields) {
+ if (!(reqKey in rawArgs) || rawArgs[reqKey] === undefined || rawArgs[reqKey] === null) {
+ return {
+ ok: false,
+ code: -32602,
+ message: `Invalid params for '${tool.name}': missing required argument '${reqKey}'`,
+ };
+ }
+ }
+
+ // Validate types, non-empty strings, numbers, booleans, and enums
+ for (const [key, val] of Object.entries(rawArgs)) {
+ if (val === undefined) continue;
+ const propSchema = allowedProps[key];
+ if (!propSchema) continue;
+
+ if (propSchema.type === "string") {
+ if (typeof val !== "string") {
+ return {
+ ok: false,
+ code: -32602,
+ message: `Invalid params for '${tool.name}': argument '${key}' must be a string, received ${val === null ? "null" : typeof val}`,
+ };
+ }
+ if (val.trim().length === 0) {
+ return {
+ ok: false,
+ code: -32602,
+ message: `Invalid params for '${tool.name}': argument '${key}' must be a non-empty string`,
+ };
+ }
+ if (propSchema.enum && !propSchema.enum.includes(val)) {
+ return {
+ ok: false,
+ code: -32602,
+ message: `Invalid params for '${tool.name}': argument '${key}' must be one of [${propSchema.enum.join(", ")}], received '${val}'`,
+ };
+ }
+ } else if (propSchema.type === "boolean") {
+ if (typeof val !== "boolean") {
+ return {
+ ok: false,
+ code: -32602,
+ message: `Invalid params for '${tool.name}': argument '${key}' must be a boolean`,
+ };
+ }
+ } else if (propSchema.type === "number") {
+ if (typeof val !== "number" || !Number.isFinite(val) || val <= 0) {
+ return {
+ ok: false,
+ code: -32602,
+ message: `Invalid params for '${tool.name}': argument '${key}' must be a positive finite number`,
+ };
+ }
+ }
+ }
+
+ return { ok: true, tool, args: rawArgs };
+}
+
export async function handleMcpRequest(
req: JsonRpcRequest,
+ handlers: McpEngineHandlers = DEFAULT_ENGINE_HANDLERS,
): Promise<JsonRpcResponse | null> {
+ if (!isPlainObject(req) || req.jsonrpc !== "2.0" || typeof req.method !== "string") {
+ return {
+ jsonrpc: "2.0",
+ id: isPlainObject(req) && (typeof req.id === "string" || typeof req.id === "number") ? req.id : null,
+ error: {
+ code: -32600,
+ message: "Invalid Request: expected JSON-RPC 2.0 request object",
+ },
+ };
+ }
+
// Notifications without an `id` do not produce a response
if (req.id === undefined) {
return null;
@@ -205,12 +474,39 @@ export async function handleMcpRequest(
try {
switch (req.method) {
- case "initialize":
+ case "initialize": {
+ if (req.params !== undefined && !isPlainObject(req.params)) {
+ return {
+ jsonrpc: "2.0",
+ id: req.id,
+ error: {
+ code: -32602,
+ message: "Invalid params: initialize params must be an object",
+ },
+ };
+ }
+ const requestedVersion = req.params?.protocolVersion;
+ if (requestedVersion !== undefined && typeof requestedVersion !== "string") {
+ return {
+ jsonrpc: "2.0",
+ id: req.id,
+ error: {
+ code: -32602,
+ message: "Invalid params: protocolVersion must be a string",
+ },
+ };
+ }
+ const negotiatedVersion =
+ typeof requestedVersion === "string" &&
+ (SUPPORTED_MCP_PROTOCOL_VERSIONS as readonly string[]).includes(requestedVersion)
+ ? requestedVersion
+ : "2024-11-05";
+
return {
jsonrpc: "2.0",
id: req.id,
result: {
- protocolVersion: "2024-11-05",
+ protocolVersion: negotiatedVersion,
capabilities: {
tools: {},
prompts: {},
@@ -221,6 +517,7 @@ export async function handleMcpRequest(
},
},
};
+ }
case "ping":
return {
@@ -243,32 +540,97 @@ export async function handleMcpRequest(
jsonrpc: "2.0",
id: req.id,
result: {
- prompts: [
+ prompts: BLA_MCP_PROMPTS,
+ },
+ };
+
+ case "prompts/get": {
+ if (!isPlainObject(req.params) || typeof req.params.name !== "string") {
+ return {
+ jsonrpc: "2.0",
+ id: req.id,
+ error: {
+ code: -32602,
+ message: "Invalid params: prompts/get requires a string 'name'",
+ },
+ };
+ }
+ const promptDef = BLA_MCP_PROMPTS.find((p) => p.name === req.params!.name);
+ if (!promptDef) {
+ return {
+ jsonrpc: "2.0",
+ id: req.id,
+ error: {
+ code: -32602,
+ message: `Invalid params: unknown prompt '${req.params.name}'`,
+ },
+ };
+ }
+ const promptArgs = req.params.arguments;
+ if (!isPlainObject(promptArgs)) {
+ return {
+ jsonrpc: "2.0",
+ id: req.id,
+ error: {
+ code: -32602,
+ message: `Invalid params: prompt '${promptDef.name}' requires an 'arguments' object`,
+ },
+ };
+ }
+ for (const argSpec of promptDef.arguments) {
+ if (argSpec.required) {
+ const val = promptArgs[argSpec.name];
+ if (typeof val !== "string" || val.trim().length === 0) {
+ return {
+ jsonrpc: "2.0",
+ id: req.id,
+ error: {
+ code: -32602,
+ message: `Invalid params: prompt '${promptDef.name}' requires non-empty string argument '${argSpec.name}'`,
+ },
+ };
+ }
+ }
+ }
+ const targetPath = String(promptArgs.target_path);
+ return {
+ jsonrpc: "2.0",
+ id: req.id,
+ result: {
+ description: promptDef.description,
+ messages: [
{
- name: "shield-against-rea",
- description:
- "Audit a build artifact for REA exposure, apply BLA's adversarial shield, and verify the token bankruptcy factor.",
- arguments: [
- {
- name: "target_path",
- description: "Path to the build artifact or directory",
- required: true,
- },
- ],
+ role: "user",
+ content: {
+ type: "text",
+ text: `Inspect and audit '${targetPath}' using bla_inspect_release and bla_audit, then review findings before applying bla_protect or bla_defend and verifying with bla_verify.`,
+ },
},
],
},
};
+ }
case "tools/call": {
- const params = req.params ?? {};
- const name = String(params.name ?? "");
- const args = (params.arguments as Record<string, unknown> | undefined) ?? {};
+ const validated = validateMcpToolCall(req.params);
+ if (!validated.ok) {
+ return {
+ jsonrpc: "2.0",
+ id: req.id,
+ error: {
+ code: validated.code,
+ message: validated.message,
+ },
+ };
+ }
+ const { tool, args } = validated;
+ const name = tool.name;
let payload: unknown;
+
if (name === "bla_defend") {
- payload = defendTarget({
- inputPath: String(args.input_path ?? ""),
+ payload = handlers.defendTarget({
+ inputPath: args.input_path as string,
...(typeof args.output_path === "string"
? { outputPath: args.output_path }
: {}),
@@ -279,10 +641,10 @@ export async function handleMcpRequest(
emitManifest: Boolean(args.emit_manifest),
});
} else if (name === "bla_audit") {
- payload = auditTarget(String(args.path ?? ""));
+ payload = handlers.auditTarget(args.path as string);
} else if (name === "bla_protect") {
- payload = protectTarget({
- inputPath: String(args.input_path ?? ""),
+ payload = handlers.protectTarget({
+ inputPath: args.input_path as string,
...(typeof args.output_path === "string" ? { outputPath: args.output_path } : {}),
...(typeof args.intensity === "string"
? { intensity: args.intensity as ProtectionIntensity }
@@ -290,15 +652,15 @@ export async function handleMcpRequest(
...(typeof args.seed === "string" ? { seed: args.seed } : {}),
});
} else if (name === "bla_verify") {
- payload = verifyTarget(
- String(args.target_path ?? ""),
+ payload = handlers.verifyTarget(
+ args.target_path as string,
typeof args.original_path === "string" ? args.original_path : undefined,
);
} else if (name === "bla_benchmark") {
- payload = await runShowcaseBenchmark();
+ payload = await handlers.runShowcaseBenchmark();
} else if (name === "bla_emit_headers") {
- payload = emitCompileTimeNativeHeader(
- (args.language as NativeHeaderLanguage) ?? "c",
+ payload = handlers.emitCompileTimeNativeHeader(
+ args.language as NativeHeaderLanguage,
{
...(typeof args.intensity === "string"
? { intensity: args.intensity as ProtectionIntensity }
@@ -306,23 +668,16 @@ export async function handleMcpRequest(
},
);
} else if (name === "bla_doctor") {
- payload = runDoctor();
+ payload = handlers.runDoctor(
+ typeof args.home_dir === "string" ? args.home_dir : undefined,
+ );
} else if (name === "bla_inspect_release") {
- payload = inspectReleaseExposure(String(args.path ?? ""));
+ payload = handlers.inspectReleaseExposure(args.path as string);
} else if (name === "bla_init") {
- payload = initBlaConfig(
- typeof args.directory === "string" ? args.directory : process.cwd(),
+ payload = handlers.initBlaConfig(
+ args.directory as string,
Boolean(args.overwrite),
);
- } else {
- return {
- jsonrpc: "2.0",
- id: req.id,
- error: {
- code: -32601,
- message: `Unknown BLA MCP tool: ${name}`,
- },
- };
}
return {
@@ -369,27 +724,38 @@ export async function handleMcpRequest(
}
/**
- * Starts the BLA MCP server over stdio (supporting newline-delimited JSON-RPC).
+ * Starts the BLA MCP server over stdio (supporting newline-delimited JSON-RPC 2.0).
*/
export function startMcpStdioServer(): void {
let buffer = "";
+ let processingQueue = Promise.resolve();
process.stdin.setEncoding("utf8");
- process.stdin.on("data", async (chunk: string) => {
+ process.stdin.on("data", (chunk: string) => {
buffer += chunk;
let newlineIdx: number;
while ((newlineIdx = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, newlineIdx).trim();
buffer = buffer.slice(newlineIdx + 1);
if (!line || line.startsWith("Content-Length:")) continue;
- try {
- const req = JSON.parse(line) as JsonRpcRequest;
- const res = await handleMcpRequest(req);
- if (res !== null) {
- process.stdout.write(JSON.stringify(res) + "\n");
+ processingQueue = processingQueue.then(async () => {
+ try {
+ const req = JSON.parse(line) as JsonRpcRequest;
+ const res = await handleMcpRequest(req);
+ if (res !== null) {
+ process.stdout.write(JSON.stringify(res) + "\n");
+ }
+ } catch {
+ const parseErr: JsonRpcResponse = {
+ jsonrpc: "2.0",
+ id: null,
+ error: {
+ code: -32700,
+ message: "Parse error",
+ },
+ };
+ process.stdout.write(JSON.stringify(parseErr) + "\n");
}
- } catch {
- // Ignore unparseable line
- }
+ });
}
});
}
diff --git a/src/setup/clients.ts b/src/setup/clients.ts
index 1bf6354..2b83a31 100644
--- a/src/setup/clients.ts
+++ b/src/setup/clients.ts
@@ -1,6 +1,7 @@
-import { existsSync } from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
-import { dirname, join } from "node:path";
+import { join } from "node:path";
+import { BLA_IDENTITY } from "../identity.js";
export type SupportedAgentClientId =
| "claude_code"
@@ -14,107 +15,1412 @@ export type SupportedAgentClientId =
| "opencode"
| "copilot_cli";
+export type AiClientId =
+ | SupportedAgentClientId
+ | "claude-code"
+ | "claude-desktop"
+ | "gemini-cli"
+ | "copilot-cli";
+
+export type ClientConfigFormat =
+ | "json-mcpServers"
+ | "json-vscode"
+ | "json-opencode"
+ | "toml-codex";
+
+export interface McpServerRegistration {
+ readonly command: string;
+ readonly args: readonly string[];
+ readonly type?: string;
+ readonly enabled?: boolean;
+}
+
+export interface ConfigReadResult {
+ readonly status: "valid" | "missing" | "malformed" | "invalid_entry" | "not_configured";
+ readonly entry: McpServerRegistration | null;
+ readonly rawEntry?: unknown;
+ readonly error?: string;
+ readonly otherServersCount: number;
+}
+
+export interface ClientConfigAdapter {
+ readonly format: ClientConfigFormat;
+ readServer(rawContent: string, serverName?: string): ConfigReadResult;
+ upsertServer(
+ rawContent: string | null,
+ serverName: string,
+ reg: McpServerRegistration,
+ ): string;
+ removeServer(
+ rawContent: string,
+ serverName: string,
+ ): { readonly content: string; readonly removed: boolean };
+}
+
export interface AgentClientDefinition {
readonly id: SupportedAgentClientId;
readonly displayName: string;
readonly configPath: string;
readonly skillDirectory: string;
readonly detected: boolean;
+ readonly format: ClientConfigFormat;
+ readonly probePaths: readonly string[];
+}
+
+export interface ClientCompatibilityMatrixEntry {
+ readonly clientId: SupportedAgentClientId;
+ readonly displayName: string;
+ readonly format: ClientConfigFormat;
+ readonly rootKey: string;
+ readonly configPathTemplate: string;
+ readonly schemaVersion: string;
+ readonly officialSpecUrl: string;
+ readonly verificationMode: "automated-stdio-smoke" | "schema-and-fixture-verified";
+ readonly verifiedClientVersion: string;
+}
+
+export const CLIENT_COMPATIBILITY_MATRIX: readonly ClientCompatibilityMatrixEntry[] = Object.freeze([
+ {
+ clientId: "claude_code",
+ displayName: "Claude Code",
+ format: "json-mcpServers",
+ rootKey: "mcpServers",
+ configPathTemplate: "~/.claude.json",
+ schemaVersion: "claude-code-mcp-v1",
+ officialSpecUrl: "https://docs.anthropic.com/en/docs/claude-code/mcp",
+ verificationMode: "automated-stdio-smoke",
+ verifiedClientVersion: "1.0.x (automated stdio protocol + schema fixture)",
+ },
+ {
+ clientId: "claude_desktop",
+ displayName: "Claude Desktop",
+ format: "json-mcpServers",
+ rootKey: "mcpServers",
+ configPathTemplate: "~/Library/Application Support/Claude/claude_desktop_config.json",
+ schemaVersion: "claude-desktop-mcp-v1",
+ officialSpecUrl: "https://modelcontextprotocol.io/quickstart/user",
+ verificationMode: "schema-and-fixture-verified",
+ verifiedClientVersion: "0.9.x (GUI client — schema fixture verified, runtime unverified in headless CI)",
+ },
+ {
+ clientId: "cursor",
+ displayName: "Cursor",
+ format: "json-mcpServers",
+ rootKey: "mcpServers",
+ configPathTemplate: "~/.cursor/mcp.json",
+ schemaVersion: "cursor-mcp-v1",
+ officialSpecUrl: "https://docs.cursor.com/context/model-context-protocol",
+ verificationMode: "schema-and-fixture-verified",
+ verifiedClientVersion: "0.48.x (GUI client — schema fixture verified, runtime unverified in headless CI)",
+ },
+ {
+ clientId: "codex",
+ displayName: "Codex CLI",
+ format: "toml-codex",
+ rootKey: "mcp_servers",
+ configPathTemplate: "~/.codex/config.toml",
+ schemaVersion: "codex-config-toml-v1",
+ officialSpecUrl: "https://developers.openai.com/codex/mcp/",
+ verificationMode: "automated-stdio-smoke",
+ verifiedClientVersion: "0.1.x (TOML [mcp_servers.bla] spec + automated stdio smoke)",
+ },
+ {
+ clientId: "gemini_cli",
+ displayName: "Gemini CLI",
+ format: "json-mcpServers",
+ rootKey: "mcpServers",
+ configPathTemplate: "~/.gemini/settings.json",
+ schemaVersion: "gemini-cli-settings-v1",
+ officialSpecUrl: "https://github.com/google-gemini/gemini-cli",
+ verificationMode: "automated-stdio-smoke",
+ verifiedClientVersion: "0.1.x (settings.json mcpServers + automated stdio smoke)",
+ },
+ {
+ clientId: "antigravity",
+ displayName: "Google Antigravity",
+ format: "json-mcpServers",
+ rootKey: "mcpServers",
+ configPathTemplate: "~/.gemini/antigravity/mcp_config.json",
+ schemaVersion: "antigravity-mcp-v1",
+ officialSpecUrl: "https://idx.dev",
+ verificationMode: "schema-and-fixture-verified",
+ verifiedClientVersion: "2.0.x (mcpServers schema fixture verified)",
+ },
+ {
+ clientId: "windsurf",
+ displayName: "Windsurf",
+ format: "json-mcpServers",
+ rootKey: "mcpServers",
+ configPathTemplate: "~/.codeium/windsurf/mcp_config.json",
+ schemaVersion: "windsurf-mcp-v1",
+ officialSpecUrl: "https://docs.windsurf.com/windsurf/mcp",
+ verificationMode: "schema-and-fixture-verified",
+ verifiedClientVersion: "1.6.x (GUI client — schema fixture verified, runtime unverified in headless CI)",
+ },
+ {
+ clientId: "vscode",
+ displayName: "VS Code",
+ format: "json-vscode",
+ rootKey: "servers",
+ configPathTemplate: "<UserConfig>/Code/User/mcp.json",
+ schemaVersion: "vscode-mcp-servers-v1",
+ officialSpecUrl: "https://code.visualstudio.com/docs/agent-customization/mcp-servers",
+ verificationMode: "schema-and-fixture-verified",
+ verifiedClientVersion: "1.99+ (user-profile mcp.json 'servers' schema fixture verified; GUI runtime unverified in CI)",
+ },
+ {
+ clientId: "opencode",
+ displayName: "OpenCode",
+ format: "json-opencode",
+ rootKey: "mcp",
+ configPathTemplate: "~/.config/opencode/opencode.json",
+ schemaVersion: "opencode-mcp-local-v1",
+ officialSpecUrl: "https://opencode.ai/docs/mcp-servers/",
+ verificationMode: "automated-stdio-smoke",
+ verifiedClientVersion: "0.1.x (opencode.json mcp.bla local command array + automated stdio smoke)",
+ },
+ {
+ clientId: "copilot_cli",
+ displayName: "GitHub Copilot CLI",
+ format: "json-mcpServers",
+ rootKey: "mcpServers",
+ configPathTemplate: "~/.copilot/mcp-config.json",
+ schemaVersion: "copilot-cli-mcp-v1",
+ officialSpecUrl: "https://docs.github.com/en/copilot",
+ verificationMode: "schema-and-fixture-verified",
+ verifiedClientVersion: "1.0.x (mcpServers schema fixture verified)",
+ },
+]);
+
+const CLIENT_ID_ALIASES: Readonly<Record<string, SupportedAgentClientId>> = Object.freeze({
+ claude_code: "claude_code",
+ "claude-code": "claude_code",
+ claude_desktop: "claude_desktop",
+ "claude-desktop": "claude_desktop",
+ cursor: "cursor",
+ codex: "codex",
+ gemini_cli: "gemini_cli",
+ "gemini-cli": "gemini_cli",
+ windsurf: "windsurf",
+ antigravity: "antigravity",
+ vscode: "vscode",
+ "vs-code": "vscode",
+ opencode: "opencode",
+ copilot_cli: "copilot_cli",
+ "copilot-cli": "copilot_cli",
+});
+
+export function normalizeClientId(id: string): SupportedAgentClientId | null {
+ return CLIENT_ID_ALIASES[id.trim().toLowerCase()] ?? null;
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+/**
+ * Strip inline `#` comments outside quoted strings on a single TOML line.
+ */
+function stripTomlInlineComment(line: string): {
+ readonly code: string;
+ readonly unclosedQuote: boolean;
+} {
+ let inDouble = false;
+ let inSingle = false;
+ let escaped = false;
+ for (let i = 0; i < line.length; i++) {
+ const ch = line[i]!;
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+ if (inDouble) {
+ if (ch === "\\") {
+ escaped = true;
+ } else if (ch === '"') {
+ inDouble = false;
+ }
+ continue;
+ }
+ if (inSingle) {
+ if (ch === "'") {
+ inSingle = false;
+ }
+ continue;
+ }
+ if (ch === '"') {
+ inDouble = true;
+ } else if (ch === "'") {
+ inSingle = true;
+ } else if (ch === "#") {
+ return { code: line.slice(0, i).trim(), unclosedQuote: false };
+ }
+ }
+ return { code: line.trim(), unclosedQuote: inDouble || inSingle };
+}
+
+function parseTomlStringLiteral(raw: string): { readonly ok: true; readonly value: string } | { readonly ok: false } {
+ const trimmed = raw.trim();
+ if (trimmed.length < 2) return { ok: false };
+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
+ try {
+ const parsed: unknown = JSON.parse(trimmed);
+ if (typeof parsed === "string") {
+ return { ok: true, value: parsed };
+ }
+ } catch {
+ return { ok: false };
+ }
+ return { ok: false };
+ }
+ if (trimmed.startsWith("'") && trimmed.endsWith("'")) {
+ const inner = trimmed.slice(1, -1);
+ if (inner.includes("'")) return { ok: false };
+ return { ok: true, value: inner };
+ }
+ return { ok: false };
+}
+
+function parseTomlStringArray(raw: string): { readonly ok: true; readonly values: string[] } | { readonly ok: false } {
+ const trimmed = raw.trim();
+ if (!trimmed.startsWith("[") || !trimmed.endsWith("]")) {
+ return { ok: false };
+ }
+ const inner = trimmed.slice(1, -1).trim();
+ if (inner.length === 0) {
+ return { ok: true, values: [] };
+ }
+
+ const items: string[] = [];
+ let current = "";
+ let inDouble = false;
+ let inSingle = false;
+ let escaped = false;
+ let depth = 0;
+
+ for (let i = 0; i < inner.length; i++) {
+ const ch = inner[i]!;
+ if (escaped) {
+ current += ch;
+ escaped = false;
+ continue;
+ }
+ if (inDouble) {
+ current += ch;
+ if (ch === "\\") escaped = true;
+ else if (ch === '"') inDouble = false;
+ continue;
+ }
+ if (inSingle) {
+ current += ch;
+ if (ch === "'") inSingle = false;
+ continue;
+ }
+ if (ch === '"') {
+ inDouble = true;
+ current += ch;
+ } else if (ch === "'") {
+ inSingle = true;
+ current += ch;
+ } else if (ch === "[") {
+ depth++;
+ current += ch;
+ } else if (ch === "]") {
+ depth--;
+ if (depth < 0) return { ok: false };
+ current += ch;
+ } else if (ch === "," && depth === 0) {
+ const parsedItem = parseTomlStringLiteral(current);
+ if (!parsedItem.ok) return { ok: false };
+ items.push(parsedItem.value);
+ current = "";
+ } else {
+ current += ch;
+ }
+ }
+
+ if (inDouble || inSingle || depth !== 0) {
+ return { ok: false };
+ }
+
+ if (current.trim().length > 0) {
+ const parsedItem = parseTomlStringLiteral(current);
+ if (!parsedItem.ok) return { ok: false };
+ items.push(parsedItem.value);
+ }
+
+ return { ok: true, values: items };
+}
+
+interface ParsedTomlSectionRange {
+ readonly name: string;
+ readonly headerLineIndex: number;
+ readonly endLineIndex: number;
+ readonly assignments: ReadonlyMap<string, string>;
+}
+
+function inspectCodexTomlDocument(
+ rawToml: string,
+):
+ | {
+ readonly ok: true;
+ readonly lines: readonly string[];
+ readonly sections: readonly ParsedTomlSectionRange[];
+ readonly topLevelAssignments: ReadonlyMap<string, string>;
+ }
+ | {
+ readonly ok: false;
+ readonly error: string;
+ } {
+ const lines = rawToml.split(/\r?\n/);
+ const sections: {
+ name: string;
+ headerLineIndex: number;
+ endLineIndex: number;
+ assignments: Map<string, string>;
+ }[] = [];
+ const topLevelAssignments = new Map<string, string>();
+ let currentSection: {
+ name: string;
+ headerLineIndex: number;
+ endLineIndex: number;
+ assignments: Map<string, string>;
+ } | null = null;
+
+ let pendingKey: string | null = null;
+ let pendingArrayBuffer = "";
+ let bracketBalance = 0;
+
+ const countArrayBracketsOutsideQuotes = (code: string): { delta: number; valid: boolean } => {
+ let delta = 0;
+ let inDouble = false;
+ let inSingle = false;
+ let escaped = false;
+ for (let i = 0; i < code.length; i++) {
+ const ch = code[i]!;
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+ if (inDouble) {
+ if (ch === "\\") escaped = true;
+ else if (ch === '"') inDouble = false;
+ continue;
+ }
+ if (inSingle) {
+ if (ch === "'") inSingle = false;
+ continue;
+ }
+ if (ch === '"') inDouble = true;
+ else if (ch === "'") inSingle = true;
+ else if (ch === "[") delta++;
+ else if (ch === "]") delta--;
+ }
+ return { delta, valid: !inDouble && !inSingle };
+ };
+
+ for (let idx = 0; idx < lines.length; idx++) {
+ const rawLine = lines[idx]!;
+ const stripped = stripTomlInlineComment(rawLine);
+ if (stripped.unclosedQuote) {
+ return { ok: false, error: `Malformed TOML at line ${idx + 1}: unclosed string quote` };
+ }
+ const code = stripped.code;
+ if (code.length === 0) continue;
+
+ if (pendingKey !== null) {
+ const bracketCheck = countArrayBracketsOutsideQuotes(code);
+ if (!bracketCheck.valid) {
+ return { ok: false, error: `Malformed TOML array at line ${idx + 1}` };
+ }
+ pendingArrayBuffer += " " + code;
+ bracketBalance += bracketCheck.delta;
+ if (bracketBalance < 0) {
+ return { ok: false, error: `Malformed TOML at line ${idx + 1}: unexpected closing bracket` };
+ }
+ if (bracketBalance === 0) {
+ const targetMap = currentSection ? currentSection.assignments : topLevelAssignments;
+ targetMap.set(pendingKey, pendingArrayBuffer.trim());
+ pendingKey = null;
+ pendingArrayBuffer = "";
+ }
+ continue;
+ }
+
+ if (code.startsWith("[")) {
+ if (!code.endsWith("]")) {
+ return { ok: false, error: `Malformed TOML table header at line ${idx + 1}: '${code}'` };
+ }
+ const isArrayOfTables = code.startsWith("[[") && code.endsWith("]]");
+ const tableName = (isArrayOfTables ? code.slice(2, -2) : code.slice(1, -1)).trim();
+ if (tableName.length === 0 || tableName.includes("[") || tableName.includes("]")) {
+ return { ok: false, error: `Invalid TOML table header at line ${idx + 1}: '${code}'` };
+ }
+ if (currentSection) {
+ currentSection.endLineIndex = idx;
+ }
+ currentSection = {
+ name: tableName,
+ headerLineIndex: idx,
+ endLineIndex: lines.length,
+ assignments: new Map<string, string>(),
+ };
+ sections.push(currentSection);
+ continue;
+ }
+
+ const eqIdx = code.indexOf("=");
+ if (eqIdx <= 0) {
+ return { ok: false, error: `Malformed TOML statement at line ${idx + 1}: '${code}'` };
+ }
+
+ const key = code.slice(0, eqIdx).trim();
+ const val = code.slice(eqIdx + 1).trim();
+ if (!/^[A-Za-z0-9_.-]+$/.test(key) && !(key.startsWith('"') && key.endsWith('"'))) {
+ return { ok: false, error: `Invalid TOML key '${key}' at line ${idx + 1}` };
+ }
+ if (val.length === 0) {
+ return { ok: false, error: `Empty TOML value for key '${key}' at line ${idx + 1}` };
+ }
+
+ if (val.startsWith("[")) {
+ const bracketCheck = countArrayBracketsOutsideQuotes(val);
+ if (!bracketCheck.valid || bracketCheck.delta < 0) {
+ return { ok: false, error: `Malformed TOML array for key '${key}' at line ${idx + 1}` };
+ }
+ if (bracketCheck.delta > 0) {
+ pendingKey = key;
+ pendingArrayBuffer = val;
+ bracketBalance = bracketCheck.delta;
+ continue;
+ }
+ } else if (val.startsWith("{")) {
+ if (!val.endsWith("}")) {
+ return { ok: false, error: `Unclosed TOML inline table for key '${key}' at line ${idx + 1}` };
+ }
+ } else if (val.startsWith('"') || val.startsWith("'")) {
+ const parsedStr = parseTomlStringLiteral(val);
+ if (!parsedStr.ok) {
+ return { ok: false, error: `Invalid TOML string literal for key '${key}' at line ${idx + 1}` };
+ }
+ } else if (
+ val !== "true" &&
+ val !== "false" &&
+ !/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(val) &&
+ !/^\d{4}-\d{2}-\d{2}/.test(val)
+ ) {
+ return { ok: false, error: `Invalid TOML literal '${val}' for key '${key}' at line ${idx + 1}` };
+ }
+
+ const targetMap = currentSection ? currentSection.assignments : topLevelAssignments;
+ targetMap.set(key, val);
+ }
+
+ if (pendingKey !== null || bracketBalance !== 0) {
+ return { ok: false, error: `Malformed TOML: unclosed multiline array for key '${pendingKey}'` };
+ }
+
+ // Schema check: top-level `mcp_servers` cannot be a scalar or array
+ const topLevelMcpServers = topLevelAssignments.get("mcp_servers");
+ if (topLevelMcpServers !== undefined && !topLevelMcpServers.startsWith("{")) {
+ return {
+ ok: false,
+ error: "Invalid Codex config.toml schema: 'mcp_servers' must be a table, not a scalar or array",
+ };
+ }
+
+ return {
+ ok: true,
+ lines,
+ sections,
+ topLevelAssignments,
+ };
+}
+
+export function readCodexTomlMcp(
+ rawToml: string,
+ serverName: string = BLA_IDENTITY.mcpServerName,
+): ConfigReadResult {
+ const inspected = inspectCodexTomlDocument(rawToml);
+ if (!inspected.ok) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: inspected.error,
+ otherServersCount: 0,
+ };
+ }
+
+ const targetTable = `mcp_servers.${serverName}`;
+ let otherServersCount = 0;
+ let targetSection: ParsedTomlSectionRange | undefined;
+
+ for (const sec of inspected.sections) {
+ if (sec.name === targetTable) {
+ targetSection = sec;
+ } else if (sec.name.startsWith("mcp_servers.")) {
+ const remainder = sec.name.slice("mcp_servers.".length);
+ if (remainder.length > 0 && !remainder.includes(".")) {
+ otherServersCount++;
+ }
+ } else if (sec.name === "mcp_servers") {
+ const inlineBla = sec.assignments.get(serverName);
+ if (inlineBla !== undefined && !inlineBla.startsWith("{")) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: `Invalid Codex config.toml schema: '[mcp_servers].${serverName}' must be a table`,
+ otherServersCount,
+ };
+ }
+ }
+ }
+
+ if (!targetSection) {
+ return {
+ status: "not_configured",
+ entry: null,
+ otherServersCount,
+ };
+ }
+
+ const rawCommand = targetSection.assignments.get("command");
+ if (rawCommand === undefined) {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ error: `Codex [${targetTable}] is missing required 'command' string`,
+ otherServersCount,
+ };
+ }
+
+ const parsedCommand = parseTomlStringLiteral(rawCommand);
+ if (!parsedCommand.ok || parsedCommand.value.trim().length === 0) {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ error: `Codex [${targetTable}].command must be a non-empty string`,
+ otherServersCount,
+ };
+ }
+
+ let parsedArgs: string[] = [];
+ const rawArgs = targetSection.assignments.get("args");
+ if (rawArgs !== undefined) {
+ const arrRes = parseTomlStringArray(rawArgs);
+ if (!arrRes.ok) {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ error: `Codex [${targetTable}].args must be an array of strings`,
+ otherServersCount,
+ };
+ }
+ parsedArgs = arrRes.values;
+ }
+
+ const rawEnabled = targetSection.assignments.get("enabled");
+ if (rawEnabled === "false") {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ error: `Codex [${targetTable}] is explicitly disabled (enabled = false)`,
+ otherServersCount,
+ };
+ }
+
+ return {
+ status: "valid",
+ entry: {
+ command: parsedCommand.value,
+ args: parsedArgs,
+ },
+ rawEntry: Object.fromEntries(targetSection.assignments.entries()),
+ otherServersCount,
+ };
+}
+
+export function writeCodexTomlMcp(
+ rawToml: string | null,
+ serverName: string,
+ reg: McpServerRegistration,
+): string {
+ const existing = rawToml ?? "";
+ if (existing.trim().length > 0) {
+ const inspected = inspectCodexTomlDocument(existing);
+ if (!inspected.ok) {
+ throw new Error(inspected.error);
+ }
+ const targetTable = `mcp_servers.${serverName}`;
+ for (const sec of inspected.sections) {
+ if (sec.name === "mcp_servers") {
+ const inlineVal = sec.assignments.get(serverName);
+ if (inlineVal !== undefined && !inlineVal.startsWith("{")) {
+ throw new Error(
+ `Invalid Codex config.toml schema: '[mcp_servers].${serverName}' is not a table`,
+ );
+ }
+ }
+ }
+
+ const formattedSectionLines = [
+ `[${targetTable}]`,
+ `command = ${JSON.stringify(reg.command)}`,
+ `args = [${reg.args.map((a) => JSON.stringify(a)).join(", ")}]`,
+ ];
+
+ const existingSection = inspected.sections.find((s) => s.name === targetTable);
+ if (existingSection) {
+ // Preserve trailing comments before the next section header
+ let replaceEnd = existingSection.endLineIndex;
+ while (
+ replaceEnd > existingSection.headerLineIndex + 1 &&
+ (inspected.lines[replaceEnd - 1]!.trim() === "" ||
+ inspected.lines[replaceEnd - 1]!.trim().startsWith("#"))
+ ) {
+ if (inspected.lines[replaceEnd - 1]!.trim().startsWith("#")) {
+ break;
+ }
+ replaceEnd--;
+ }
+ const before = inspected.lines.slice(0, existingSection.headerLineIndex);
+ const after = inspected.lines.slice(replaceEnd);
+ const combined = [...before, ...formattedSectionLines, ...(after.length > 0 ? ["", ...after] : [])];
+ return combined.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
+ }
+
+ const trimmedExisting = existing.trimEnd();
+ return `${trimmedExisting}\n\n${formattedSectionLines.join("\n")}\n`;
+ }
+
+ return [
+ `[mcp_servers.${serverName}]`,
+ `command = ${JSON.stringify(reg.command)}`,
+ `args = [${reg.args.map((a) => JSON.stringify(a)).join(", ")}]`,
+ "",
+ ].join("\n");
+}
+
+export function removeCodexTomlMcp(
+ rawToml: string,
+ serverName: string = BLA_IDENTITY.mcpServerName,
+): { readonly content: string; readonly removed: boolean } {
+ const inspected = inspectCodexTomlDocument(rawToml);
+ if (!inspected.ok) {
+ throw new Error(inspected.error);
+ }
+ const targetTable = `mcp_servers.${serverName}`;
+ const existingSection = inspected.sections.find((s) => s.name === targetTable);
+ if (!existingSection) {
+ return { content: rawToml, removed: false };
+ }
+
+ const before = inspected.lines.slice(0, existingSection.headerLineIndex);
+ const after = inspected.lines.slice(existingSection.endLineIndex);
+ const joined = [...before, ...after].join("\n").replace(/\n{3,}/g, "\n\n").trimEnd();
+ return {
+ content: joined.length > 0 ? `${joined}\n` : "",
+ removed: true,
+ };
+}
+
+function createJsonMcpServersAdapter(): ClientConfigAdapter {
+ return {
+ format: "json-mcpServers",
+ readServer(rawContent: string, serverName: string = BLA_IDENTITY.mcpServerName): ConfigReadResult {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawContent);
+ } catch (err) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: `Malformed JSON configuration: ${err instanceof Error ? err.message : String(err)}`,
+ otherServersCount: 0,
+ };
+ }
+ if (!isPlainObject(parsed)) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: "Invalid configuration schema: root value must be a JSON object",
+ otherServersCount: 0,
+ };
+ }
+ if (parsed.mcpServers === undefined) {
+ return {
+ status: "not_configured",
+ entry: null,
+ otherServersCount: 0,
+ };
+ }
+ if (!isPlainObject(parsed.mcpServers)) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: "Invalid configuration schema: 'mcpServers' must be a JSON object",
+ otherServersCount: 0,
+ };
+ }
+ const servers = parsed.mcpServers;
+ const otherServersCount = Object.keys(servers).filter((k) => k !== serverName).length;
+ if (!(serverName in servers)) {
+ return {
+ status: "not_configured",
+ entry: null,
+ otherServersCount,
+ };
+ }
+ const rawEntry = servers[serverName];
+ if (!isPlainObject(rawEntry)) {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ rawEntry,
+ error: `Invalid MCP server entry '${serverName}': must be a JSON object`,
+ otherServersCount,
+ };
+ }
+ if (typeof rawEntry.command !== "string" || rawEntry.command.trim().length === 0) {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ rawEntry,
+ error: `Invalid MCP server entry '${serverName}': 'command' must be a non-empty string`,
+ otherServersCount,
+ };
+ }
+ let args: string[] = [];
+ if (rawEntry.args !== undefined) {
+ if (!Array.isArray(rawEntry.args) || !rawEntry.args.every((a) => typeof a === "string")) {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ rawEntry,
+ error: `Invalid MCP server entry '${serverName}': 'args' must be an array of strings`,
+ otherServersCount,
+ };
+ }
+ args = [...rawEntry.args];
+ }
+ if (rawEntry.disabled === true || rawEntry.enabled === false) {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ rawEntry,
+ error: `MCP server entry '${serverName}' is disabled`,
+ otherServersCount,
+ };
+ }
+ return {
+ status: "valid",
+ entry: {
+ command: rawEntry.command,
+ args,
+ },
+ rawEntry,
+ otherServersCount,
+ };
+ },
+ upsertServer(rawContent: string | null, serverName: string, reg: McpServerRegistration): string {
+ let root: Record<string, unknown> = {};
+ if (rawContent !== null && rawContent.trim().length > 0) {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawContent);
+ } catch (err) {
+ throw new Error(
+ `Malformed JSON configuration: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ if (!isPlainObject(parsed)) {
+ throw new Error("Invalid configuration schema: root value must be a JSON object");
+ }
+ if (parsed.mcpServers !== undefined && !isPlainObject(parsed.mcpServers)) {
+ throw new Error("Invalid configuration schema: 'mcpServers' must be a JSON object");
+ }
+ root = { ...parsed };
+ }
+ const existingServers = isPlainObject(root.mcpServers) ? { ...root.mcpServers } : {};
+ existingServers[serverName] = {
+ command: reg.command,
+ args: [...reg.args],
+ };
+ root.mcpServers = existingServers;
+ return JSON.stringify(root, null, 2) + "\n";
+ },
+ removeServer(rawContent: string, serverName: string): { readonly content: string; readonly removed: boolean } {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawContent);
+ } catch (err) {
+ throw new Error(
+ `Malformed JSON configuration: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ if (!isPlainObject(parsed)) {
+ throw new Error("Invalid configuration schema: root value must be a JSON object");
+ }
+ if (parsed.mcpServers !== undefined && !isPlainObject(parsed.mcpServers)) {
+ throw new Error("Invalid configuration schema: 'mcpServers' must be a JSON object");
+ }
+ if (!isPlainObject(parsed.mcpServers) || !(serverName in parsed.mcpServers)) {
+ return { content: rawContent, removed: false };
+ }
+ const nextServers = { ...parsed.mcpServers };
+ delete nextServers[serverName];
+ const nextRoot: Record<string, unknown> = { ...parsed, mcpServers: nextServers };
+ return {
+ content: JSON.stringify(nextRoot, null, 2) + "\n",
+ removed: true,
+ };
+ },
+ };
+}
+
+function createJsonVscodeAdapter(): ClientConfigAdapter {
+ return {
+ format: "json-vscode",
+ readServer(rawContent: string, serverName: string = BLA_IDENTITY.mcpServerName): ConfigReadResult {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawContent);
+ } catch (err) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: `Malformed VS Code mcp.json: ${err instanceof Error ? err.message : String(err)}`,
+ otherServersCount: 0,
+ };
+ }
+ if (!isPlainObject(parsed)) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: "Invalid VS Code mcp.json schema: root value must be a JSON object",
+ otherServersCount: 0,
+ };
+ }
+ if (parsed.servers === undefined) {
+ if ("mcpServers" in parsed) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: "Invalid VS Code user-profile mcp.json schema: expected root key 'servers', found 'mcpServers'",
+ otherServersCount: 0,
+ };
+ }
+ return {
+ status: "not_configured",
+ entry: null,
+ otherServersCount: 0,
+ };
+ }
+ if (!isPlainObject(parsed.servers)) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: "Invalid VS Code mcp.json schema: 'servers' must be a JSON object",
+ otherServersCount: 0,
+ };
+ }
+ const servers = parsed.servers;
+ const otherServersCount = Object.keys(servers).filter((k) => k !== serverName).length;
+ if (!(serverName in servers)) {
+ return {
+ status: "not_configured",
+ entry: null,
+ otherServersCount,
+ };
+ }
+ const rawEntry = servers[serverName];
+ if (!isPlainObject(rawEntry)) {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ rawEntry,
+ error: `Invalid VS Code MCP server entry '${serverName}': must be a JSON object`,
+ otherServersCount,
+ };
+ }
+ if (rawEntry.type !== undefined && rawEntry.type !== "stdio") {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ rawEntry,
+ error: `Invalid VS Code MCP server entry '${serverName}': 'type' must be 'stdio'`,
+ otherServersCount,
+ };
+ }
+ if (typeof rawEntry.command !== "string" || rawEntry.command.trim().length === 0) {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ rawEntry,
+ error: `Invalid VS Code MCP server entry '${serverName}': 'command' must be a non-empty string`,
+ otherServersCount,
+ };
+ }
+ let args: string[] = [];
+ if (rawEntry.args !== undefined) {
+ if (!Array.isArray(rawEntry.args) || !rawEntry.args.every((a) => typeof a === "string")) {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ rawEntry,
+ error: `Invalid VS Code MCP server entry '${serverName}': 'args' must be an array of strings`,
+ otherServersCount,
+ };
+ }
+ args = [...rawEntry.args];
+ }
+ return {
+ status: "valid",
+ entry: {
+ type: "stdio",
+ command: rawEntry.command,
+ args,
+ },
+ rawEntry,
+ otherServersCount,
+ };
+ },
+ upsertServer(rawContent: string | null, serverName: string, reg: McpServerRegistration): string {
+ let root: Record<string, unknown> = {};
+ if (rawContent !== null && rawContent.trim().length > 0) {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawContent);
+ } catch (err) {
+ throw new Error(
+ `Malformed VS Code mcp.json: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ if (!isPlainObject(parsed)) {
+ throw new Error("Invalid VS Code mcp.json schema: root value must be a JSON object");
+ }
+ if (parsed.servers !== undefined && !isPlainObject(parsed.servers)) {
+ throw new Error("Invalid VS Code mcp.json schema: 'servers' must be a JSON object");
+ }
+ root = { ...parsed };
+ }
+ const existingServers = isPlainObject(root.servers) ? { ...root.servers } : {};
+ existingServers[serverName] = {
+ type: "stdio",
+ command: reg.command,
+ args: [...reg.args],
+ };
+ root.servers = existingServers;
+ return JSON.stringify(root, null, 2) + "\n";
+ },
+ removeServer(rawContent: string, serverName: string): { readonly content: string; readonly removed: boolean } {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawContent);
+ } catch (err) {
+ throw new Error(
+ `Malformed VS Code mcp.json: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ if (!isPlainObject(parsed)) {
+ throw new Error("Invalid VS Code mcp.json schema: root value must be a JSON object");
+ }
+ if (parsed.servers !== undefined && !isPlainObject(parsed.servers)) {
+ throw new Error("Invalid VS Code mcp.json schema: 'servers' must be a JSON object");
+ }
+ if (!isPlainObject(parsed.servers) || !(serverName in parsed.servers)) {
+ return { content: rawContent, removed: false };
+ }
+ const nextServers = { ...parsed.servers };
+ delete nextServers[serverName];
+ const nextRoot: Record<string, unknown> = { ...parsed, servers: nextServers };
+ return {
+ content: JSON.stringify(nextRoot, null, 2) + "\n",
+ removed: true,
+ };
+ },
+ };
+}
+
+function createJsonOpencodeAdapter(): ClientConfigAdapter {
+ return {
+ format: "json-opencode",
+ readServer(rawContent: string, serverName: string = BLA_IDENTITY.mcpServerName): ConfigReadResult {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawContent);
+ } catch (err) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: `Malformed OpenCode configuration: ${err instanceof Error ? err.message : String(err)}`,
+ otherServersCount: 0,
+ };
+ }
+ if (!isPlainObject(parsed)) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: "Invalid OpenCode configuration schema: root value must be a JSON object",
+ otherServersCount: 0,
+ };
+ }
+ if (parsed.mcp === undefined) {
+ if ("mcpServers" in parsed) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: "Invalid OpenCode configuration schema: expected root key 'mcp', found 'mcpServers'",
+ otherServersCount: 0,
+ };
+ }
+ return {
+ status: "not_configured",
+ entry: null,
+ otherServersCount: 0,
+ };
+ }
+ if (!isPlainObject(parsed.mcp)) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: "Invalid OpenCode configuration schema: 'mcp' must be a JSON object",
+ otherServersCount: 0,
+ };
+ }
+ const mcp = parsed.mcp;
+ const otherServersCount = Object.keys(mcp).filter((k) => k !== serverName).length;
+ if (!(serverName in mcp)) {
+ return {
+ status: "not_configured",
+ entry: null,
+ otherServersCount,
+ };
+ }
+ const rawEntry = mcp[serverName];
+ if (!isPlainObject(rawEntry)) {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ rawEntry,
+ error: `Invalid OpenCode MCP entry '${serverName}': must be a JSON object`,
+ otherServersCount,
+ };
+ }
+ if (rawEntry.type !== "local") {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ rawEntry,
+ error: `Invalid OpenCode MCP entry '${serverName}': 'type' must be 'local'`,
+ otherServersCount,
+ };
+ }
+ if (
+ !Array.isArray(rawEntry.command) ||
+ rawEntry.command.length === 0 ||
+ !rawEntry.command.every((c) => typeof c === "string" && c.length > 0) ||
+ rawEntry.command[0].trim().length === 0
+ ) {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ rawEntry,
+ error: `Invalid OpenCode MCP entry '${serverName}': 'command' must be a non-empty string array`,
+ otherServersCount,
+ };
+ }
+ if (rawEntry.enabled !== undefined && typeof rawEntry.enabled !== "boolean") {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ rawEntry,
+ error: `Invalid OpenCode MCP entry '${serverName}': 'enabled' must be a boolean`,
+ otherServersCount,
+ };
+ }
+ if (rawEntry.enabled === false) {
+ return {
+ status: "invalid_entry",
+ entry: null,
+ rawEntry,
+ error: `OpenCode MCP entry '${serverName}' is disabled (enabled: false)`,
+ otherServersCount,
+ };
+ }
+ const cmdArray = rawEntry.command as string[];
+ return {
+ status: "valid",
+ entry: {
+ type: "local",
+ command: cmdArray[0]!,
+ args: cmdArray.slice(1),
+ enabled: rawEntry.enabled ?? true,
+ },
+ rawEntry,
+ otherServersCount,
+ };
+ },
+ upsertServer(rawContent: string | null, serverName: string, reg: McpServerRegistration): string {
+ let root: Record<string, unknown> = {};
+ if (rawContent !== null && rawContent.trim().length > 0) {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawContent);
+ } catch (err) {
+ throw new Error(
+ `Malformed OpenCode configuration: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ if (!isPlainObject(parsed)) {
+ throw new Error("Invalid OpenCode configuration schema: root value must be a JSON object");
+ }
+ if (parsed.mcp !== undefined && !isPlainObject(parsed.mcp)) {
+ throw new Error("Invalid OpenCode configuration schema: 'mcp' must be a JSON object");
+ }
+ root = { ...parsed };
+ }
+ const existingMcp = isPlainObject(root.mcp) ? { ...root.mcp } : {};
+ existingMcp[serverName] = {
+ type: "local",
+ command: [reg.command, ...reg.args],
+ enabled: reg.enabled ?? true,
+ };
+ root.mcp = existingMcp;
+ return JSON.stringify(root, null, 2) + "\n";
+ },
+ removeServer(rawContent: string, serverName: string): { readonly content: string; readonly removed: boolean } {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawContent);
+ } catch (err) {
+ throw new Error(
+ `Malformed OpenCode configuration: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ if (!isPlainObject(parsed)) {
+ throw new Error("Invalid OpenCode configuration schema: root value must be a JSON object");
+ }
+ if (parsed.mcp !== undefined && !isPlainObject(parsed.mcp)) {
+ throw new Error("Invalid OpenCode configuration schema: 'mcp' must be a JSON object");
+ }
+ if (!isPlainObject(parsed.mcp) || !(serverName in parsed.mcp)) {
+ return { content: rawContent, removed: false };
+ }
+ const nextMcp = { ...parsed.mcp };
+ delete nextMcp[serverName];
+ const nextRoot: Record<string, unknown> = { ...parsed, mcp: nextMcp };
+ return {
+ content: JSON.stringify(nextRoot, null, 2) + "\n",
+ removed: true,
+ };
+ },
+ };
+}
+
+function createTomlCodexAdapter(): ClientConfigAdapter {
+ return {
+ format: "toml-codex",
+ readServer(rawContent: string, serverName: string = BLA_IDENTITY.mcpServerName): ConfigReadResult {
+ return readCodexTomlMcp(rawContent, serverName);
+ },
+ upsertServer(rawContent: string | null, serverName: string, reg: McpServerRegistration): string {
+ return writeCodexTomlMcp(rawContent, serverName, reg);
+ },
+ removeServer(rawContent: string, serverName: string): { readonly content: string; readonly removed: boolean } {
+ return removeCodexTomlMcp(rawContent, serverName);
+ },
+ };
+}
+
+const ADAPTERS: Readonly<Record<ClientConfigFormat, ClientConfigAdapter>> = Object.freeze({
+ "json-mcpServers": createJsonMcpServersAdapter(),
+ "json-vscode": createJsonVscodeAdapter(),
+ "json-opencode": createJsonOpencodeAdapter(),
+ "toml-codex": createTomlCodexAdapter(),
+});
+
+const CLIENT_FORMAT_MAP: Readonly<Record<SupportedAgentClientId, ClientConfigFormat>> = Object.freeze({
+ claude_code: "json-mcpServers",
+ claude_desktop: "json-mcpServers",
+ cursor: "json-mcpServers",
+ codex: "toml-codex",
+ gemini_cli: "json-mcpServers",
+ antigravity: "json-mcpServers",
+ windsurf: "json-mcpServers",
+ vscode: "json-vscode",
+ opencode: "json-opencode",
+ copilot_cli: "json-mcpServers",
+});
+
+export function getClientConfigAdapter(
+ clientOrFormat: SupportedAgentClientId | ClientConfigFormat | AgentClientDefinition | string,
+): ClientConfigAdapter {
+ if (typeof clientOrFormat === "object" && clientOrFormat !== null && "format" in clientOrFormat) {
+ return ADAPTERS[clientOrFormat.format];
+ }
+ if (typeof clientOrFormat === "string") {
+ if (clientOrFormat in ADAPTERS) {
+ return ADAPTERS[clientOrFormat as ClientConfigFormat];
+ }
+ const normalized = normalizeClientId(clientOrFormat);
+ if (normalized) {
+ return ADAPTERS[CLIENT_FORMAT_MAP[normalized]];
+ }
+ }
+ return ADAPTERS["json-mcpServers"];
+}
+
+export function readClientMcpConfig(
+ configPath: string,
+ format: ClientConfigFormat,
+ serverName: string = BLA_IDENTITY.mcpServerName,
+): ConfigReadResult {
+ if (!existsSync(configPath)) {
+ return {
+ status: "missing",
+ entry: null,
+ otherServersCount: 0,
+ };
+ }
+ let rawContent: string;
+ try {
+ rawContent = readFileSync(configPath, "utf8");
+ } catch (err) {
+ return {
+ status: "malformed",
+ entry: null,
+ error: `Failed to read configuration file '${configPath}': ${err instanceof Error ? err.message : String(err)}`,
+ otherServersCount: 0,
+ };
+ }
+ return getClientConfigAdapter(format).readServer(rawContent, serverName);
}
export function resolveSupportedAgentClients(
home: string = homedir(),
platform: NodeJS.Platform = process.platform,
+ env?: NodeJS.ProcessEnv,
): readonly AgentClientDefinition[] {
+ const winAppData =
+ env?.APPDATA && env.APPDATA.trim().length > 0
+ ? env.APPDATA
+ : join(home, "AppData", "Roaming");
+
+ const xdgConfigHome =
+ env?.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.trim().length > 0
+ ? env.XDG_CONFIG_HOME
+ : join(home, ".config");
+
const claudeDesktopDir =
platform === "darwin"
? join(home, "Library", "Application Support", "Claude")
: platform === "win32"
- ? join(process.env.APPDATA ?? join(home, "AppData", "Roaming"), "Claude")
- : join(home, ".config", "Claude");
+ ? join(winAppData, "Claude")
+ : join(xdgConfigHome, "Claude");
const vscodeDir =
platform === "darwin"
? join(home, "Library", "Application Support", "Code", "User")
: platform === "win32"
- ? join(process.env.APPDATA ?? join(home, "AppData", "Roaming"), "Code", "User")
- : join(home, ".config", "Code", "User");
+ ? join(winAppData, "Code", "User")
+ : join(xdgConfigHome, "Code", "User");
+
+ const opencodeDir = join(xdgConfigHome, "opencode");
const rawDefs: {
id: SupportedAgentClientId;
displayName: string;
configPath: string;
- markerPath: string;
+ format: ClientConfigFormat;
+ probePaths: readonly string[];
skillDirectory: string;
}[] = [
{
id: "claude_code",
displayName: "Claude Code",
configPath: join(home, ".claude.json"),
- markerPath: join(home, ".claude"),
+ format: "json-mcpServers",
+ // Never probe `dirname(configPath)` because for `~/.claude.json` that is `home` itself!
+ probePaths: [join(home, ".claude.json"), join(home, ".claude")],
skillDirectory: join(home, ".claude", "skills", "blind-llm-agents"),
},
{
id: "claude_desktop",
displayName: "Claude Desktop",
configPath: join(claudeDesktopDir, "claude_desktop_config.json"),
- markerPath: claudeDesktopDir,
+ format: "json-mcpServers",
+ probePaths: [join(claudeDesktopDir, "claude_desktop_config.json"), claudeDesktopDir],
skillDirectory: join(home, ".agents", "skills", "blind-llm-agents"),
},
{
id: "cursor",
displayName: "Cursor",
configPath: join(home, ".cursor", "mcp.json"),
- markerPath: join(home, ".cursor"),
+ format: "json-mcpServers",
+ probePaths: [join(home, ".cursor", "mcp.json"), join(home, ".cursor")],
skillDirectory: join(home, ".cursor", "skills", "blind-llm-agents"),
},
{
id: "codex",
displayName: "Codex CLI",
- configPath: join(home, ".codex", "mcp.json"),
- markerPath: join(home, ".codex"),
+ configPath: join(home, ".codex", "config.toml"),
+ format: "toml-codex",
+ probePaths: [join(home, ".codex", "config.toml"), join(home, ".codex")],
skillDirectory: join(home, ".codex", "skills", "blind-llm-agents"),
},
{
id: "gemini_cli",
displayName: "Gemini CLI",
configPath: join(home, ".gemini", "settings.json"),
- markerPath: join(home, ".gemini"),
+ format: "json-mcpServers",
+ probePaths: [join(home, ".gemini", "settings.json"), join(home, ".gemini")],
skillDirectory: join(home, ".gemini", "skills", "blind-llm-agents"),
},
{
id: "antigravity",
displayName: "Google Antigravity",
configPath: join(home, ".gemini", "antigravity", "mcp_config.json"),
- markerPath: join(home, ".gemini", "antigravity"),
+ format: "json-mcpServers",
+ probePaths: [
+ join(home, ".gemini", "antigravity", "mcp_config.json"),
+ join(home, ".gemini", "antigravity"),
+ ],
skillDirectory: join(home, ".gemini", "antigravity", "skills", "blind-llm-agents"),
},
{
id: "windsurf",
displayName: "Windsurf",
configPath: join(home, ".codeium", "windsurf", "mcp_config.json"),
- markerPath: join(home, ".codeium", "windsurf"),
+ format: "json-mcpServers",
+ probePaths: [
+ join(home, ".codeium", "windsurf", "mcp_config.json"),
+ join(home, ".codeium", "windsurf"),
+ ],
skillDirectory: join(home, ".agents", "skills", "blind-llm-agents"),
},
{
id: "vscode",
displayName: "VS Code",
configPath: join(vscodeDir, "mcp.json"),
- markerPath: vscodeDir,
+ format: "json-vscode",
+ probePaths: [join(vscodeDir, "mcp.json"), vscodeDir],
skillDirectory: join(home, ".agents", "skills", "blind-llm-agents"),
},
{
id: "opencode",
displayName: "OpenCode",
- configPath: join(home, ".config", "opencode", "opencode.json"),
- markerPath: join(home, ".config", "opencode"),
+ configPath: join(opencodeDir, "opencode.json"),
+ format: "json-opencode",
+ probePaths: [join(opencodeDir, "opencode.json"), opencodeDir],
skillDirectory: join(home, ".agents", "skills", "blind-llm-agents"),
},
{
id: "copilot_cli",
displayName: "GitHub Copilot CLI",
configPath: join(home, ".copilot", "mcp-config.json"),
- markerPath: join(home, ".copilot"),
+ format: "json-mcpServers",
+ probePaths: [join(home, ".copilot", "mcp-config.json"), join(home, ".copilot")],
skillDirectory: join(home, ".agents", "skills", "blind-llm-agents"),
},
];
@@ -124,6 +1430,18 @@ export function resolveSupportedAgentClients(
displayName: def.displayName,
configPath: def.configPath,
skillDirectory: def.skillDirectory,
- detected: existsSync(def.markerPath) || existsSync(def.configPath) || existsSync(dirname(def.configPath)),
+ format: def.format,
+ probePaths: def.probePaths,
+ detected: def.probePaths.some((p) => existsSync(p)),
}));
}
+
+export function detectInstalledClients(
+ home: string = homedir(),
+ platform: NodeJS.Platform = process.platform,
+ env?: NodeJS.ProcessEnv,
+): SupportedAgentClientId[] {
+ return resolveSupportedAgentClients(home, platform, env)
+ .filter((c) => c.detected)
+ .map((c) => c.id);
+}
diff --git a/src/setup/doctor.ts b/src/setup/doctor.ts
index 73d5044..e13a85f 100644
--- a/src/setup/doctor.ts
+++ b/src/setup/doctor.ts
@@ -1,68 +1,467 @@
-import { existsSync, readFileSync } from "node:fs";
-import { join } from "node:path";
+import { spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { accessSync, constants, existsSync, readFileSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { delimiter, dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { getDatabaseSyncClass } from "../core/sqlite-runtime.js";
import { BLA_IDENTITY, REA_INTERNAL_LIMITS } from "../identity.js";
-import { resolveSupportedAgentClients } from "./clients.js";
+import { protectZipOrApkBuffer } from "../shields/formats/archive.js";
+import { packAsarBuffer } from "../shields/formats/asar.js";
+import { protectNativeBinary } from "../shields/formats/native.js";
+import { protectPythonSource } from "../shields/formats/python.js";
+import { protectWasmBinary } from "../shields/formats/wasm.js";
+import { transformJavaScriptWithBlaShield } from "../shields/javascript/ast-shield.js";
+import {
+ readClientMcpConfig,
+ resolveSupportedAgentClients,
+ type ClientConfigFormat,
+ type SupportedAgentClientId,
+} from "./clients.js";
+import { readInstallManifest, resolveBundledSkillContent } from "./setup.js";
+
+export type EngineHealthStatus = "ready" | "degraded" | "unavailable";
+export type DoctorClientCheckState = "pass" | "warn" | "fail" | "not_checked";
+export type DoctorConfigStatus =
+ | "valid"
+ | "missing"
+ | "malformed"
+ | "invalid_entry"
+ | "not_configured";
+export type DoctorHandshakeStatus = "verified" | "failed" | "not_checked";
+export type DoctorSkillStatus = "installed" | "missing" | "modified";
+
+export interface DoctorClientDiagnostic {
+ readonly id: SupportedAgentClientId;
+ readonly displayName: string;
+ readonly format: ClientConfigFormat;
+ readonly configPath: string;
+ readonly skillPath: string;
+ readonly detected: boolean;
+ readonly installed: boolean;
+ readonly configured: boolean;
+ readonly configStatus: DoctorConfigStatus;
+ readonly command: string | null;
+ readonly args: readonly string[];
+ readonly commandResolvable: boolean;
+ readonly command_resolvable: boolean;
+ readonly handshakeStatus: DoctorHandshakeStatus;
+ readonly handshakeVerified: boolean;
+ readonly handshake_verified: boolean;
+ readonly mcpRegistered: boolean;
+ readonly skillInstalled: boolean;
+ readonly skillStatus: DoctorSkillStatus;
+ readonly status: DoctorClientCheckState;
+ readonly issues: readonly string[];
+}
+
+export interface DoctorOptions {
+ readonly homeDir?: string;
+ readonly platform?: NodeJS.Platform;
+ readonly env?: NodeJS.ProcessEnv;
+ readonly pathEnv?: string;
+ readonly verifyHandshake?: boolean;
+ readonly handshakeTimeoutMs?: number;
+ readonly sqliteAvailableOverride?: boolean;
+}
export interface DoctorDiagnosticReport {
readonly healthy: boolean;
+ readonly exitCode: 0 | 1;
+ readonly status: "pass" | "warn" | "fail";
readonly blaVersion: string;
readonly nodeVersion: string;
readonly platform: string;
+ readonly arch: string;
readonly engines: {
- readonly javascriptAstShield: "ready";
- readonly electronAsarPacker: "ready";
- readonly wasmBinaryShield: "ready";
- readonly pythonPycMarshalShield: "ready";
- readonly nativeElfMachoPeShield: "ready";
- readonly zipApkArchiveShield: "ready";
+ readonly javascriptAstShield: EngineHealthStatus;
+ readonly electronAsarPacker: EngineHealthStatus;
+ readonly wasmBinaryShield: EngineHealthStatus;
+ readonly pythonPycMarshalShield: EngineHealthStatus;
+ readonly nativeElfMachoPeShield: EngineHealthStatus;
+ readonly zipApkArchiveShield: EngineHealthStatus;
+ readonly sqliteRuntime: EngineHealthStatus;
+ readonly astParser: EngineHealthStatus;
+ readonly asarPacker: EngineHealthStatus;
+ readonly wasmLeb128: EngineHealthStatus;
+ readonly pythonMarshal: EngineHealthStatus;
+ readonly nativeBinary: EngineHealthStatus;
};
readonly reaLimitsTargeted: typeof REA_INTERNAL_LIMITS;
- readonly agentClients: readonly {
- readonly id: string;
- readonly displayName: string;
- readonly detected: boolean;
- readonly mcpRegistered: boolean;
- readonly skillInstalled: boolean;
- }[];
+ readonly agentClients: readonly DoctorClientDiagnostic[];
+ readonly clients: readonly DoctorClientDiagnostic[];
+ readonly issues: readonly string[];
+}
+
+function sha256Hex(content: string | Buffer): string {
+ return createHash("sha256").update(content).digest("hex");
+}
+
+function isExecutableFile(filePath: string, platform: NodeJS.Platform): boolean {
+ try {
+ if (!existsSync(filePath)) return false;
+ const st = statSync(filePath);
+ if (!st.isFile()) return false;
+ if (platform !== "win32") {
+ accessSync(filePath, constants.X_OK);
+ }
+ return true;
+ } catch {
+ return false;
+ }
}
-export function runDoctor(homeDir?: string): DoctorDiagnosticReport {
- const clients = resolveSupportedAgentClients(homeDir);
- const agentStatuses = clients.map((c) => {
- let mcpRegistered = false;
- if (existsSync(c.configPath)) {
+export function isCommandResolvable(
+ command: string | null | undefined,
+ pathEnv: string = process.env.PATH ?? "",
+ platform: NodeJS.Platform = process.platform,
+): boolean {
+ if (!command || typeof command !== "string") return false;
+ const trimmed = command.trim();
+ if (trimmed.length === 0) return false;
+
+ // Path-qualified executable
+ if (trimmed.includes("/") || trimmed.includes("\\")) {
+ return isExecutableFile(trimmed, platform);
+ }
+
+ const dirs = pathEnv
+ .split(delimiter)
+ .map((d) => d.trim())
+ .filter((d) => d.length > 0);
+
+ const extensions =
+ platform === "win32"
+ ? (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
+ .split(";")
+ .map((e) => e.trim())
+ .filter(Boolean)
+ : [""];
+
+ for (const dir of dirs) {
+ if (platform === "win32" && !trimmed.includes(".")) {
+ for (const ext of extensions) {
+ if (isExecutableFile(join(dir, `${trimmed}${ext}`), platform)) {
+ return true;
+ }
+ }
+ }
+ if (isExecutableFile(join(dir, trimmed), platform)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+function probeLocalMcpHandshake(
+ command: string,
+ args: readonly string[],
+ timeoutMs: number = 3000,
+): boolean {
+ try {
+ const thisDir = dirname(fileURLToPath(import.meta.url));
+ const distCli = resolve(thisDir, "../../dist/cli.js");
+
+ let execCmd = command;
+ let execArgs = [...args];
+
+ // Never execute arbitrary unknown commands or network `npx` downloads during doctor probes.
+ // Only allow trusted local Node/BLA invocations.
+ const baseCmd = command.split(/[/\\]/).pop() ?? "";
+ if (baseCmd === "npx" || baseCmd === "npx.cmd") {
+ if (!existsSync(distCli)) {
+ return false;
+ }
+ execCmd = process.execPath;
+ execArgs = [distCli, "mcp"];
+ } else if (
+ baseCmd !== "node" &&
+ baseCmd !== "node.exe" &&
+ command !== process.execPath &&
+ baseCmd !== "bla" &&
+ baseCmd !== "bla-agents" &&
+ baseCmd !== "bla-shield"
+ ) {
+ return false;
+ }
+
+ const initRequest =
+ JSON.stringify({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: "2024-11-05",
+ capabilities: {},
+ clientInfo: { name: "bla-doctor-probe", version: BLA_IDENTITY.version },
+ },
+ }) + "\n";
+
+ const proc = spawnSync(execCmd, execArgs, {
+ input: initRequest,
+ encoding: "utf8",
+ timeout: timeoutMs,
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+
+ if (proc.error || !proc.stdout) return false;
+ const lines = proc.stdout
+ .split(/\r?\n/)
+ .map((l) => l.trim())
+ .filter(Boolean);
+ for (const line of lines) {
+ const parsed = JSON.parse(line) as {
+ jsonrpc?: string;
+ id?: number;
+ result?: { serverInfo?: { name?: string } };
+ };
+ if (parsed.jsonrpc === "2.0" && parsed.id === 1 && parsed.result?.serverInfo?.name === "bla") {
+ return true;
+ }
+ }
+ return false;
+ } catch {
+ return false;
+ }
+}
+
+function checkEngines(sqliteOverride?: boolean): DoctorDiagnosticReport["engines"] {
+ let javascriptAstShield: EngineHealthStatus = "ready";
+ try {
+ const out = transformJavaScriptWithBlaShield("const __blaProbe = 1;\n", {
+ intensity: "stealth",
+ seed: "doctor-probe",
+ });
+ if (!out || typeof out.code !== "string" || out.code.length === 0) {
+ javascriptAstShield = "unavailable";
+ }
+ } catch {
+ javascriptAstShield = "unavailable";
+ }
+
+ const electronAsarPacker: EngineHealthStatus =
+ typeof packAsarBuffer === "function" ? "ready" : "unavailable";
+
+ let wasmBinaryShield: EngineHealthStatus = "ready";
+ try {
+ const minimalWasm = Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]);
+ const res = protectWasmBinary(minimalWasm);
+ if (!res || res.buffer.byteLength < 8) {
+ wasmBinaryShield = "unavailable";
+ }
+ } catch {
+ wasmBinaryShield = "unavailable";
+ }
+
+ let pythonPycMarshalShield: EngineHealthStatus = "ready";
+ try {
+ const pyOut = protectPythonSource("def _probe():\n return 1\n", {
+ intensity: "stealth",
+ seed: "doctor-probe",
+ });
+ if (!pyOut || typeof pyOut.code !== "string" || pyOut.code.length === 0) {
+ pythonPycMarshalShield = "unavailable";
+ }
+ } catch {
+ pythonPycMarshalShield = "unavailable";
+ }
+
+ const nativeElfMachoPeShield: EngineHealthStatus =
+ typeof protectNativeBinary === "function" ? "ready" : "unavailable";
+
+ const zipApkArchiveShield: EngineHealthStatus =
+ typeof protectZipOrApkBuffer === "function" ? "ready" : "unavailable";
+
+ let sqliteRuntime: EngineHealthStatus = "ready";
+ if (typeof sqliteOverride === "boolean") {
+ sqliteRuntime = sqliteOverride ? "ready" : "unavailable";
+ } else {
+ try {
+ const DbClass = getDatabaseSyncClass();
+ if (typeof DbClass !== "function") {
+ sqliteRuntime = "unavailable";
+ }
+ } catch {
+ sqliteRuntime = "unavailable";
+ }
+ }
+
+ return {
+ javascriptAstShield,
+ electronAsarPacker,
+ wasmBinaryShield,
+ pythonPycMarshalShield,
+ nativeElfMachoPeShield,
+ zipApkArchiveShield,
+ sqliteRuntime,
+ astParser: javascriptAstShield,
+ asarPacker: electronAsarPacker,
+ wasmLeb128: wasmBinaryShield,
+ pythonMarshal: pythonPycMarshalShield,
+ nativeBinary: nativeElfMachoPeShield,
+ };
+}
+
+export function runDoctor(homeDirOrOptions?: string | DoctorOptions): DoctorDiagnosticReport {
+ const options: DoctorOptions =
+ typeof homeDirOrOptions === "string"
+ ? { homeDir: homeDirOrOptions }
+ : (homeDirOrOptions ?? {});
+
+ const home = options.homeDir ?? homedir();
+ const platform = options.platform ?? process.platform;
+ const pathEnv = options.pathEnv ?? options.env?.PATH ?? process.env.PATH ?? "";
+ const clients = resolveSupportedAgentClients(home, platform, options.env);
+ const manifest = readInstallManifest(home);
+ const bundledSkillSha256 = sha256Hex(resolveBundledSkillContent());
+
+ const engines = checkEngines(options.sqliteAvailableOverride);
+ const globalIssues: string[] = [];
+
+ for (const [engineName, status] of Object.entries(engines)) {
+ if (status === "unavailable") {
+ globalIssues.push(`Engine '${engineName}' is unavailable in current runtime (${process.version})`);
+ }
+ }
+
+ const agentStatuses: DoctorClientDiagnostic[] = clients.map((c) => {
+ const clientIssues: string[] = [];
+ const skillPath = join(c.skillDirectory, "SKILL.md");
+ const readRes = readClientMcpConfig(c.configPath, c.format, BLA_IDENTITY.mcpServerName);
+
+ const configStatus: DoctorConfigStatus = readRes.status;
+ const configured = configStatus === "valid" && readRes.entry !== null;
+ const command = readRes.entry?.command ?? null;
+ const args = readRes.entry?.args ?? [];
+
+ if (configStatus === "malformed") {
+ clientIssues.push(
+ readRes.error ?? `Malformed configuration file for ${c.displayName} at '${c.configPath}'`,
+ );
+ } else if (configStatus === "invalid_entry") {
+ clientIssues.push(
+ readRes.error ?? `Invalid '${BLA_IDENTITY.mcpServerName}' MCP entry for ${c.displayName}`,
+ );
+ }
+
+ const commandResolvable =
+ configured && command !== null ? isCommandResolvable(command, pathEnv, platform) : false;
+
+ if (configured && !commandResolvable) {
+ clientIssues.push(
+ `Configured MCP command '${command}' for ${c.displayName} is not resolvable on disk or PATH`,
+ );
+ }
+
+ let skillInstalled = false;
+ let skillStatus: DoctorSkillStatus = "missing";
+ if (existsSync(skillPath)) {
try {
- const parsed = JSON.parse(readFileSync(c.configPath, "utf8")) as Record<string, unknown>;
- const servers = parsed.mcpServers as Record<string, unknown> | undefined;
- mcpRegistered = Boolean(servers && BLA_IDENTITY.mcpServerName in servers);
+ const rawSkill = readFileSync(skillPath, "utf8");
+ if (rawSkill.trim().length > 0) {
+ skillInstalled = true;
+ const currentSha = sha256Hex(rawSkill);
+ const manifestRec = manifest.clients[c.id];
+ if (
+ currentSha === bundledSkillSha256 ||
+ (manifestRec && manifestRec.writtenSkillSha256 === currentSha)
+ ) {
+ skillStatus = "installed";
+ } else {
+ skillStatus = "modified";
+ }
+ }
} catch {
- mcpRegistered = false;
+ skillInstalled = false;
+ skillStatus = "missing";
+ }
+ }
+
+ if (configured && !skillInstalled) {
+ clientIssues.push(`MCP server is configured for ${c.displayName}, but SKILL.md is missing at '${skillPath}'`);
+ }
+
+ let handshakeStatus: DoctorHandshakeStatus = "not_checked";
+ let handshakeVerified = false;
+ if (options.verifyHandshake && configured && commandResolvable && command !== null) {
+ handshakeVerified = probeLocalMcpHandshake(command, args, options.handshakeTimeoutMs ?? 3000);
+ handshakeStatus = handshakeVerified ? "verified" : "failed";
+ if (!handshakeVerified) {
+ clientIssues.push(`MCP stdio initialize handshake failed for ${c.displayName}`);
}
}
- const skillInstalled = existsSync(join(c.skillDirectory, "SKILL.md"));
+
+ const mcpRegistered =
+ configured && commandResolvable && handshakeStatus !== "failed";
+
+ let status: DoctorClientCheckState = "not_checked";
+ if (configStatus === "malformed" || configStatus === "invalid_entry") {
+ status = "fail";
+ } else if (configured) {
+ if (!commandResolvable || !skillInstalled || handshakeStatus === "failed") {
+ status = "fail";
+ } else if (skillStatus === "modified") {
+ status = "warn";
+ } else {
+ status = "pass";
+ }
+ } else {
+ status = "not_checked";
+ }
+
+ for (const issue of clientIssues) {
+ globalIssues.push(`[${c.id}] ${issue}`);
+ }
+
return {
id: c.id,
displayName: c.displayName,
+ format: c.format,
+ configPath: c.configPath,
+ skillPath,
detected: c.detected,
+ installed: c.detected,
+ configured,
+ configStatus,
+ command,
+ args,
+ commandResolvable,
+ command_resolvable: commandResolvable,
+ handshakeStatus,
+ handshakeVerified,
+ handshake_verified: handshakeVerified,
mcpRegistered,
skillInstalled,
+ skillStatus,
+ status,
+ issues: clientIssues,
};
});
+ const anyEngineUnavailable = Object.values(engines).some((s) => s === "unavailable");
+ const anyClientFailed = agentStatuses.some((c) => c.status === "fail");
+ const anyClientWarn = agentStatuses.some((c) => c.status === "warn");
+
+ const healthy = !anyEngineUnavailable && !anyClientFailed;
+ const overallStatus: DoctorDiagnosticReport["status"] = !healthy
+ ? "fail"
+ : anyClientWarn
+ ? "warn"
+ : "pass";
+
return {
- healthy: true,
+ healthy,
+ exitCode: healthy ? 0 : 1,
+ status: overallStatus,
blaVersion: BLA_IDENTITY.version,
nodeVersion: process.version,
- platform: `${process.platform}-${process.arch}`,
- engines: {
- javascriptAstShield: "ready",
- electronAsarPacker: "ready",
- wasmBinaryShield: "ready",
- pythonPycMarshalShield: "ready",
- nativeElfMachoPeShield: "ready",
- zipApkArchiveShield: "ready",
- },
+ platform: `${platform}-${process.arch}`,
+ arch: process.arch,
+ engines,
reaLimitsTargeted: REA_INTERNAL_LIMITS,
agentClients: agentStatuses,
+ clients: agentStatuses,
+ issues: globalIssues,
};
}
diff --git a/src/setup/setup.ts b/src/setup/setup.ts
index ed1ca6e..1985ca5 100644
--- a/src/setup/setup.ts
+++ b/src/setup/setup.ts
@@ -1,38 +1,239 @@
-import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { createHash } from "node:crypto";
+import {
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ renameSync,
+ rmdirSync,
+ unlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { BLA_IDENTITY } from "../identity.js";
import {
+ getClientConfigAdapter,
+ normalizeClientId,
resolveSupportedAgentClients,
type AgentClientDefinition,
+ type ClientConfigFormat,
+ type McpServerRegistration,
type SupportedAgentClientId,
} from "./clients.js";
+export type ClientSelectionSource = "explicit" | "auto-discovered" | "default-all";
+export type SetupSelectionMode = "explicit" | "discovered" | "all-default";
+
export interface PlannedSetupAction {
readonly clientId: SupportedAgentClientId;
readonly displayName: string;
+ readonly format: ClientConfigFormat;
readonly configPath: string;
readonly backupPath: string | null;
readonly skillPath: string;
readonly mcpCommand: string;
readonly mcpArgs: readonly string[];
+ readonly clientDetected: boolean;
+ readonly selectionSource: ClientSelectionSource;
+ readonly status: "planned" | "applied" | "error" | "conflict";
+ readonly applied: boolean;
+ readonly error?: string;
}
+export type ClientSetupResult = PlannedSetupAction;
+
export interface SetupRunOptions {
- readonly clientIds?: readonly SupportedAgentClientId[];
+ readonly clientIds?: readonly (SupportedAgentClientId | string)[];
+ readonly clients?: readonly (SupportedAgentClientId | string)[];
readonly allDetected?: boolean;
+ readonly onlyDetected?: boolean;
+ readonly includeUndetected?: boolean;
readonly dryRun?: boolean;
readonly yes?: boolean;
+ readonly force?: boolean;
readonly homeDir?: string;
+ readonly platform?: NodeJS.Platform;
+ readonly env?: NodeJS.ProcessEnv;
+ readonly mcpCommand?: string;
+ readonly mcpArgs?: readonly string[];
}
+export type SetupOptions = SetupRunOptions;
+
export interface SetupRunResult {
- readonly status: "planned" | "applied";
+ readonly status: "planned" | "applied" | "error" | "conflict" | "partial";
readonly actions: readonly PlannedSetupAction[];
+ readonly results: readonly PlannedSetupAction[];
+ readonly discoveredClients: readonly SupportedAgentClientId[];
+ readonly explicitClients: readonly SupportedAgentClientId[];
+ readonly selectionMode: SetupSelectionMode;
+ readonly manifestPath: string | null;
readonly message: string;
}
-function resolveBundledSkillContent(): string {
+export type SetupReport = SetupRunResult;
+
+export interface InstalledClientRecord {
+ readonly clientId: SupportedAgentClientId;
+ readonly configPath: string;
+ readonly format: ClientConfigFormat;
+ readonly configExistedBefore: boolean;
+ readonly backupPath: string | null;
+ readonly backupSha256: string | null;
+ readonly writtenConfigSha256: string;
+ readonly writtenEntry: McpServerRegistration;
+ readonly writtenEntryHash: string;
+ readonly skillPath: string;
+ readonly skillDirectory: string;
+ readonly skillExistedBefore: boolean;
+ readonly skillDirectoryExistedBefore: boolean;
+ readonly writtenSkillSha256: string;
+ readonly installedAt: string;
+}
+
+export interface BlaInstallManifest {
+ readonly version: 1;
+ readonly updatedAt: string;
+ readonly clients: Record<string, InstalledClientRecord>;
+}
+
+export interface ClientUninstallResult {
+ readonly clientId: SupportedAgentClientId;
+ readonly configPath: string;
+ readonly skillPath: string;
+ readonly mcpRemoved: boolean;
+ readonly skillRemoved: boolean;
+ readonly status: "removed" | "noop" | "conflict" | "error";
+ readonly conflictReason?: string;
+ readonly error?: string;
+}
+
+export interface UninstallRunOptions {
+ readonly homeDir?: string;
+ readonly platform?: NodeJS.Platform;
+ readonly env?: NodeJS.ProcessEnv;
+ readonly clientIds?: readonly (SupportedAgentClientId | string)[];
+ readonly clients?: readonly (SupportedAgentClientId | string)[];
+ readonly force?: boolean;
+}
+
+export interface UninstallRunResult {
+ readonly removedClients: readonly string[];
+ readonly results: readonly ClientUninstallResult[];
+ readonly conflicts: readonly ClientUninstallResult[];
+}
+
+function sha256Hex(content: string | Buffer): string {
+ return createHash("sha256").update(content).digest("hex");
+}
+
+function hashMcpEntry(entry: McpServerRegistration): string {
+ return sha256Hex(
+ JSON.stringify({
+ command: entry.command,
+ args: [...entry.args],
+ }),
+ );
+}
+
+function isBlaOwnedMcpEntry(entry: McpServerRegistration): boolean {
+ const cmd = entry.command.trim();
+ const joinedArgs = entry.args.join(" ");
+ if (
+ cmd === "bla" ||
+ cmd === "bla-agents" ||
+ cmd === "bla-shield" ||
+ cmd.endsWith("/bla") ||
+ cmd.endsWith("\\bla") ||
+ cmd.endsWith("/bla-agents") ||
+ cmd.endsWith("\\bla-agents") ||
+ cmd.endsWith("/bla-shield") ||
+ cmd.endsWith("\\bla-shield")
+ ) {
+ return true;
+ }
+ if (
+ joinedArgs.includes(BLA_IDENTITY.packageName) ||
+ joinedArgs.includes(BLA_IDENTITY.packageAlias) ||
+ joinedArgs.includes("dist/cli.js") ||
+ joinedArgs.includes("src/cli.ts")
+ ) {
+ return true;
+ }
+ return false;
+}
+
+function writeFileAtomicSync(targetPath: string, content: string | Buffer): void {
+ const dir = dirname(targetPath);
+ mkdirSync(dir, { recursive: true });
+ const tmpPath = `${targetPath}.bla-tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
+ try {
+ writeFileSync(tmpPath, content);
+ renameSync(tmpPath, targetPath);
+ } catch (err) {
+ try {
+ if (existsSync(tmpPath)) {
+ unlinkSync(tmpPath);
+ }
+ } catch {
+ // Ignore cleanup failure
+ }
+ throw err;
+ }
+}
+
+export function getInstallManifestPath(home: string = homedir()): string {
+ return join(home, ".bla", "install-manifest.json");
+}
+
+export function readInstallManifest(home: string = homedir()): BlaInstallManifest {
+ const manifestPath = getInstallManifestPath(home);
+ if (!existsSync(manifestPath)) {
+ return {
+ version: 1,
+ updatedAt: new Date(0).toISOString(),
+ clients: {},
+ };
+ }
+ try {
+ const parsed = JSON.parse(readFileSync(manifestPath, "utf8")) as Partial<BlaInstallManifest>;
+ if (
+ parsed &&
+ parsed.version === 1 &&
+ typeof parsed.clients === "object" &&
+ parsed.clients !== null &&
+ !Array.isArray(parsed.clients)
+ ) {
+ return {
+ version: 1,
+ updatedAt: typeof parsed.updatedAt === "string" ? parsed.updatedAt : new Date().toISOString(),
+ clients: { ...parsed.clients } as Record<string, InstalledClientRecord>,
+ };
+ }
+ } catch {
+ // Corrupted manifest falls back to empty state
+ }
+ return {
+ version: 1,
+ updatedAt: new Date(0).toISOString(),
+ clients: {},
+ };
+}
+
+function writeInstallManifest(home: string, manifest: BlaInstallManifest): string {
+ const manifestPath = getInstallManifestPath(home);
+ const updated: BlaInstallManifest = {
+ version: 1,
+ updatedAt: new Date().toISOString(),
+ clients: manifest.clients,
+ };
+ writeFileAtomicSync(manifestPath, JSON.stringify(updated, null, 2) + "\n");
+ return manifestPath;
+}
+
+export function resolveBundledSkillContent(): string {
try {
const thisDir = dirname(fileURLToPath(import.meta.url));
const candidate = resolve(thisDir, "../../.agents/skills/blind-llm-agents/SKILL.md");
@@ -57,109 +258,564 @@ function resolveBundledSkillContent(): string {
].join("\n");
}
+export const generateBlaSkillMarkdown = resolveBundledSkillContent;
+
export function runSetup(options: SetupRunOptions = {}): SetupRunResult {
- const allClients = resolveSupportedAgentClients(options.homeDir);
+ const home = options.homeDir ?? homedir();
+ const allClients = resolveSupportedAgentClients(home, options.platform, options.env);
+ const discoveredClients = allClients.filter((c) => c.detected).map((c) => c.id);
+
+ const requestedList = options.clientIds ?? options.clients;
+ const explicitClients: SupportedAgentClientId[] = [];
+ if (requestedList && requestedList.length > 0) {
+ for (const rawId of requestedList) {
+ const norm = normalizeClientId(String(rawId));
+ if (norm && !explicitClients.includes(norm)) {
+ explicitClients.push(norm);
+ }
+ }
+ }
+
let selected: AgentClientDefinition[];
+ let selectionMode: SetupSelectionMode;
+ let selectionSource: ClientSelectionSource;
- if (options.clientIds && options.clientIds.length > 0) {
- const set = new Set(options.clientIds);
+ if (requestedList && requestedList.length > 0) {
+ const set = new Set(explicitClients);
selected = allClients.filter((c) => set.has(c.id));
- } else if (options.allDetected) {
- selected = allClients.filter((c) => c.detected);
+ selectionMode = "explicit";
+ selectionSource = "explicit";
+ } else if (options.includeUndetected) {
+ selected = [...allClients];
+ selectionMode = "all-default";
+ selectionSource = "default-all";
} else {
selected = allClients.filter((c) => c.detected);
- if (selected.length === 0) {
- selected = allClients.filter((c) => c.id === "claude_code" || c.id === "cursor");
- }
+ selectionMode = "discovered";
+ selectionSource = "auto-discovered";
}
- const actions: PlannedSetupAction[] = selected.map((c) => ({
- clientId: c.id,
- displayName: c.displayName,
- configPath: c.configPath,
- backupPath: existsSync(c.configPath) ? `${c.configPath}.bla-backup` : null,
- skillPath: join(c.skillDirectory, "SKILL.md"),
- mcpCommand: "npx",
- mcpArgs: ["-y", `${BLA_IDENTITY.packageName}@latest`, "mcp"],
- }));
-
- if (options.dryRun || !options.yes) {
+ const mcpCommand = options.mcpCommand ?? "npx";
+ const mcpArgs = options.mcpArgs ? [...options.mcpArgs] : ["-y", `${BLA_IDENTITY.packageName}@latest`, "mcp"];
+
+ const isDryRunOrPlanOnly = options.dryRun === true || options.yes === false;
+ if (isDryRunOrPlanOnly) {
+ const plannedActions: PlannedSetupAction[] = selected.map((c) => ({
+ clientId: c.id,
+ displayName: c.displayName,
+ format: c.format,
+ configPath: c.configPath,
+ backupPath: existsSync(c.configPath) ? `${c.configPath}.bla-backup` : null,
+ skillPath: join(c.skillDirectory, "SKILL.md"),
+ mcpCommand,
+ mcpArgs,
+ clientDetected: c.detected,
+ selectionSource,
+ status: "planned",
+ applied: false,
+ }));
+
return {
status: "planned",
- actions,
+ actions: plannedActions,
+ results: plannedActions,
+ discoveredClients,
+ explicitClients,
+ selectionMode,
+ manifestPath: null,
message: options.dryRun
- ? `Dry-run complete: ${actions.length} agent client(s) planned. Run with --yes to apply.`
- : `Planned setup for ${actions.length} detected agent client(s). Pass --yes to write MCP registrations and skills.`,
+ ? `Dry-run complete: ${plannedActions.length} agent client(s) planned. Run with --yes to apply.`
+ : `Planned setup for ${plannedActions.length} agent client(s). Pass --yes to write MCP registrations and skills.`,
};
}
const skillContent = resolveBundledSkillContent();
+ const expectedSkillSha256 = sha256Hex(skillContent);
+ const manifest = readInstallManifest(home);
+ const updatedManifestClients: Record<string, InstalledClientRecord> = { ...manifest.clients };
+ const completedActions: PlannedSetupAction[] = [];
+ let anyApplied = false;
+ let anyError = false;
+ let anyConflict = false;
+
+ for (const client of selected) {
+ const adapter = getClientConfigAdapter(client.format);
+ const skillPath = join(client.skillDirectory, "SKILL.md");
+ const backupPathCandidate = `${client.configPath}.bla-backup`;
+ const configExistedBefore = existsSync(client.configPath);
+ const skillDirectoryExistedBefore = existsSync(client.skillDirectory);
+ const skillExistedBefore = existsSync(skillPath);
+
+ let existingRawContent: string | null = null;
+ if (configExistedBefore) {
+ try {
+ existingRawContent = readFileSync(client.configPath, "utf8");
+ } catch (err) {
+ anyError = true;
+ completedActions.push({
+ clientId: client.id,
+ displayName: client.displayName,
+ format: client.format,
+ configPath: client.configPath,
+ backupPath: null,
+ skillPath,
+ mcpCommand,
+ mcpArgs,
+ clientDetected: client.detected,
+ selectionSource,
+ status: "error",
+ applied: false,
+ error: `Permission or I/O error reading '${client.configPath}': ${err instanceof Error ? err.message : String(err)}`,
+ });
+ continue;
+ }
- for (const action of actions) {
- mkdirSync(dirname(action.configPath), { recursive: true });
- let existingConfig: Record<string, unknown> = {};
- if (existsSync(action.configPath)) {
- if (action.backupPath) {
- copyFileSync(action.configPath, action.backupPath);
+ const readRes = adapter.readServer(existingRawContent, BLA_IDENTITY.mcpServerName);
+ if (readRes.status === "malformed") {
+ anyError = true;
+ completedActions.push({
+ clientId: client.id,
+ displayName: client.displayName,
+ format: client.format,
+ configPath: client.configPath,
+ backupPath: null,
+ skillPath,
+ mcpCommand,
+ mcpArgs,
+ clientDetected: client.detected,
+ selectionSource,
+ status: "error",
+ applied: false,
+ error: readRes.error ?? `Malformed configuration file: '${client.configPath}'`,
+ });
+ continue;
}
+
+ if (readRes.status === "invalid_entry" && !options.force) {
+ const prevManifestRecord = updatedManifestClients[client.id];
+ if (!prevManifestRecord) {
+ anyError = true;
+ completedActions.push({
+ clientId: client.id,
+ displayName: client.displayName,
+ format: client.format,
+ configPath: client.configPath,
+ backupPath: null,
+ skillPath,
+ mcpCommand,
+ mcpArgs,
+ clientDetected: client.detected,
+ selectionSource,
+ status: "error",
+ applied: false,
+ error:
+ readRes.error ??
+ `Invalid existing '${BLA_IDENTITY.mcpServerName}' MCP entry in '${client.configPath}'`,
+ });
+ continue;
+ }
+ }
+
+ if (readRes.status === "valid" && readRes.entry && !options.force) {
+ const prevManifestRecord = updatedManifestClients[client.id];
+ const entryHash = hashMcpEntry(readRes.entry);
+ const ownedByManifest = prevManifestRecord?.writtenEntryHash === entryHash;
+ const ownedBySignature = isBlaOwnedMcpEntry(readRes.entry);
+ const matchesRequested =
+ readRes.entry.command === mcpCommand &&
+ JSON.stringify(readRes.entry.args) === JSON.stringify(mcpArgs);
+ if (!ownedByManifest && !ownedBySignature && !matchesRequested) {
+ anyConflict = true;
+ completedActions.push({
+ clientId: client.id,
+ displayName: client.displayName,
+ format: client.format,
+ configPath: client.configPath,
+ backupPath: null,
+ skillPath,
+ mcpCommand,
+ mcpArgs,
+ clientDetected: client.detected,
+ selectionSource,
+ status: "conflict",
+ applied: false,
+ error: `Existing non-BLA MCP server '${BLA_IDENTITY.mcpServerName}' in '${client.configPath}'; refusing to overwrite without force`,
+ });
+ continue;
+ }
+ }
+ }
+
+ // Check skillPath ownership BEFORE writing config or skill
+ if (skillExistedBefore && !options.force) {
+ let existingSkillContent: Buffer;
try {
- existingConfig = JSON.parse(readFileSync(action.configPath, "utf8")) as Record<string, unknown>;
- } catch {
- existingConfig = {};
+ existingSkillContent = readFileSync(skillPath);
+ } catch (err) {
+ anyError = true;
+ completedActions.push({
+ clientId: client.id,
+ displayName: client.displayName,
+ format: client.format,
+ configPath: client.configPath,
+ backupPath: null,
+ skillPath,
+ mcpCommand,
+ mcpArgs,
+ clientDetected: client.detected,
+ selectionSource,
+ status: "error",
+ applied: false,
+ error: `Failed to read existing skill file '${skillPath}': ${err instanceof Error ? err.message : String(err)}`,
+ });
+ continue;
+ }
+
+ const currentSkillHash = sha256Hex(existingSkillContent);
+ const ownedByAnyManifestClient = Object.values(updatedManifestClients).some(
+ (rec) => rec.skillPath === skillPath && rec.writtenSkillSha256 === currentSkillHash,
+ );
+ if (currentSkillHash !== expectedSkillSha256 && !ownedByAnyManifestClient) {
+ anyConflict = true;
+ completedActions.push({
+ clientId: client.id,
+ displayName: client.displayName,
+ format: client.format,
+ configPath: client.configPath,
+ backupPath: null,
+ skillPath,
+ mcpCommand,
+ mcpArgs,
+ clientDetected: client.detected,
+ selectionSource,
+ status: "conflict",
+ applied: false,
+ error: `Existing custom or user-modified SKILL.md at '${skillPath}'; refusing to overwrite without force`,
+ });
+ continue;
}
}
- const mcpServers =
- typeof existingConfig.mcpServers === "object" && existingConfig.mcpServers !== null
- ? { ...(existingConfig.mcpServers as Record<string, unknown>) }
- : {};
+ // Prepare new config content via client adapter before touching disk
+ const registration: McpServerRegistration = {
+ command: mcpCommand,
+ args: mcpArgs,
+ };
+
+ let nextConfigContent: string;
+ try {
+ nextConfigContent = adapter.upsertServer(
+ existingRawContent,
+ BLA_IDENTITY.mcpServerName,
+ registration,
+ );
+ } catch (err) {
+ anyError = true;
+ completedActions.push({
+ clientId: client.id,
+ displayName: client.displayName,
+ format: client.format,
+ configPath: client.configPath,
+ backupPath: null,
+ skillPath,
+ mcpCommand,
+ mcpArgs,
+ clientDetected: client.detected,
+ selectionSource,
+ status: "error",
+ applied: false,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ continue;
+ }
- mcpServers[BLA_IDENTITY.mcpServerName] = {
- command: action.mcpCommand,
- args: [...action.mcpArgs],
+ // Non-clobbering backup: ONLY create `${configPath}.bla-backup` if it does not already exist!
+ let recordedBackupPath: string | null = null;
+ let recordedBackupSha256: string | null = null;
+ try {
+ if (configExistedBefore && existingRawContent !== null) {
+ recordedBackupPath = backupPathCandidate;
+ if (!existsSync(backupPathCandidate)) {
+ writeFileAtomicSync(backupPathCandidate, existingRawContent);
+ recordedBackupSha256 = sha256Hex(existingRawContent);
+ } else {
+ recordedBackupSha256 = sha256Hex(readFileSync(backupPathCandidate));
+ }
+ }
+
+ writeFileAtomicSync(client.configPath, nextConfigContent);
+ writeFileAtomicSync(skillPath, skillContent);
+ } catch (err) {
+ anyError = true;
+ completedActions.push({
+ clientId: client.id,
+ displayName: client.displayName,
+ format: client.format,
+ configPath: client.configPath,
+ backupPath: recordedBackupPath,
+ skillPath,
+ mcpCommand,
+ mcpArgs,
+ clientDetected: client.detected,
+ selectionSource,
+ status: "error",
+ applied: false,
+ error: `Failed to write configuration or skill for '${client.id}': ${err instanceof Error ? err.message : String(err)}`,
+ });
+ continue;
+ }
+
+ const prevRecord = updatedManifestClients[client.id];
+ updatedManifestClients[client.id] = {
+ clientId: client.id,
+ configPath: client.configPath,
+ format: client.format,
+ configExistedBefore: prevRecord ? prevRecord.configExistedBefore : configExistedBefore,
+ backupPath: recordedBackupPath ?? prevRecord?.backupPath ?? null,
+ backupSha256: recordedBackupSha256 ?? prevRecord?.backupSha256 ?? null,
+ writtenConfigSha256: sha256Hex(nextConfigContent),
+ writtenEntry: registration,
+ writtenEntryHash: hashMcpEntry(registration),
+ skillPath,
+ skillDirectory: client.skillDirectory,
+ skillExistedBefore: prevRecord ? prevRecord.skillExistedBefore : skillExistedBefore,
+ skillDirectoryExistedBefore: prevRecord
+ ? prevRecord.skillDirectoryExistedBefore
+ : skillDirectoryExistedBefore,
+ writtenSkillSha256: expectedSkillSha256,
+ installedAt: new Date().toISOString(),
};
- existingConfig.mcpServers = mcpServers;
- writeFileSync(action.configPath, JSON.stringify(existingConfig, null, 2) + "\n", "utf8");
+ anyApplied = true;
+ completedActions.push({
+ clientId: client.id,
+ displayName: client.displayName,
+ format: client.format,
+ configPath: client.configPath,
+ backupPath: recordedBackupPath,
+ skillPath,
+ mcpCommand,
+ mcpArgs,
+ clientDetected: client.detected,
+ selectionSource,
+ status: "applied",
+ applied: true,
+ });
+ }
- mkdirSync(dirname(action.skillPath), { recursive: true });
- writeFileSync(action.skillPath, skillContent, "utf8");
+ let manifestPath: string | null = null;
+ if (anyApplied) {
+ manifestPath = writeInstallManifest(home, {
+ version: 1,
+ updatedAt: new Date().toISOString(),
+ clients: updatedManifestClients,
+ });
+ }
+
+ let overallStatus: SetupRunResult["status"] = "applied";
+ if (anyError || anyConflict) {
+ if (anyApplied) {
+ overallStatus = "partial";
+ } else if (anyConflict && !anyError) {
+ overallStatus = "conflict";
+ } else {
+ overallStatus = "error";
+ }
}
+ const appliedCount = completedActions.filter((a) => a.applied).length;
return {
- status: "applied",
- actions,
- message: `Configured BLA MCP server and skill for ${actions.length} agent client(s). Restart your agent to load BLA tools.`,
+ status: overallStatus,
+ actions: completedActions,
+ results: completedActions,
+ discoveredClients,
+ explicitClients,
+ selectionMode,
+ manifestPath,
+ message:
+ overallStatus === "applied"
+ ? `Configured BLA MCP server and skill for ${appliedCount} agent client(s). Restart your agent to load BLA tools.`
+ : `Completed setup with status '${overallStatus}' (${appliedCount}/${completedActions.length} applied).`,
};
}
-export function runUninstall(options: { readonly homeDir?: string } = {}): {
- readonly removedClients: readonly string[];
-} {
- const allClients = resolveSupportedAgentClients(options.homeDir);
- const removed: string[] = [];
+export function runUninstall(options: UninstallRunOptions = {}): UninstallRunResult {
+ const home = options.homeDir ?? homedir();
+ const allClients = resolveSupportedAgentClients(home, options.platform, options.env);
+ const requestedList = options.clientIds ?? options.clients;
+
+ let targetClients: readonly AgentClientDefinition[] = allClients;
+ if (requestedList && requestedList.length > 0) {
+ const normalizedSet = new Set<SupportedAgentClientId>();
+ for (const rawId of requestedList) {
+ const norm = normalizeClientId(String(rawId));
+ if (norm) normalizedSet.add(norm);
+ }
+ targetClients = allClients.filter((c) => normalizedSet.has(c.id));
+ }
+
+ const manifest = readInstallManifest(home);
+ const remainingManifestClients: Record<string, InstalledClientRecord> = { ...manifest.clients };
+ const bundledSkillHash = sha256Hex(resolveBundledSkillContent());
+
+ const removedClients: string[] = [];
+ const results: ClientUninstallResult[] = [];
+ const conflicts: ClientUninstallResult[] = [];
+
+ for (const client of targetClients) {
+ const adapter = getClientConfigAdapter(client.format);
+ const skillPath = join(client.skillDirectory, "SKILL.md");
+ const manifestRecord = remainingManifestClients[client.id];
+
+ let mcpRemoved = false;
+ let skillRemoved = false;
+ let conflictReason: string | undefined;
+ let errorMsg: string | undefined;
- for (const client of allClients) {
+ // 1. Check and remove MCP registration if owned by BLA
if (existsSync(client.configPath)) {
+ let rawConfig: string | null = null;
+ try {
+ rawConfig = readFileSync(client.configPath, "utf8");
+ } catch (err) {
+ errorMsg = `Failed to read '${client.configPath}': ${err instanceof Error ? err.message : String(err)}`;
+ }
+
+ if (rawConfig !== null) {
+ const readRes = adapter.readServer(rawConfig, BLA_IDENTITY.mcpServerName);
+ if (readRes.status === "malformed") {
+ conflictReason =
+ readRes.error ?? `Malformed configuration at '${client.configPath}'; refusing to modify`;
+ } else if (readRes.status === "invalid_entry") {
+ if (manifestRecord || options.force) {
+ try {
+ const rem = adapter.removeServer(rawConfig, BLA_IDENTITY.mcpServerName);
+ if (rem.removed) {
+ writeFileAtomicSync(client.configPath, rem.content);
+ mcpRemoved = true;
+ }
+ } catch (err) {
+ errorMsg = err instanceof Error ? err.message : String(err);
+ }
+ } else {
+ conflictReason =
+ readRes.error ??
+ `Invalid non-BLA entry '${BLA_IDENTITY.mcpServerName}' in '${client.configPath}'; refusing to remove`;
+ }
+ } else if (readRes.status === "valid" && readRes.entry) {
+ const entryHash = hashMcpEntry(readRes.entry);
+ const ownedByManifest = manifestRecord?.writtenEntryHash === entryHash;
+ const ownedBySignature = isBlaOwnedMcpEntry(readRes.entry);
+ if (!ownedByManifest && !ownedBySignature && !options.force) {
+ conflictReason = `MCP entry '${BLA_IDENTITY.mcpServerName}' in '${client.configPath}' was not installed by BLA; preserving custom entry`;
+ } else {
+ try {
+ const rem = adapter.removeServer(rawConfig, BLA_IDENTITY.mcpServerName);
+ if (rem.removed) {
+ writeFileAtomicSync(client.configPath, rem.content);
+ mcpRemoved = true;
+ }
+ } catch (err) {
+ errorMsg = err instanceof Error ? err.message : String(err);
+ }
+ }
+ }
+ }
+ }
+
+ // If MCP removal succeeded (or config had no conflicting BLA entry), check skill removal
+ const canRemoveManifestRecord = !conflictReason && !errorMsg;
+ if (canRemoveManifestRecord && manifestRecord) {
+ delete remainingManifestClients[client.id];
+ }
+
+ // Check if another still-installed client in manifest (or another client not targeted in this uninstall) shares `skillPath`
+ const targetIdsSet = new Set(targetClients.map((c) => c.id));
+ const sharedByOtherRemainingManifestClient = Object.values(remainingManifestClients).some(
+ (rec) => rec.clientId !== client.id && rec.skillPath === skillPath && !targetIdsSet.has(rec.clientId),
+ );
+
+ if (!sharedByOtherRemainingManifestClient && existsSync(skillPath)) {
try {
- const parsed = JSON.parse(readFileSync(client.configPath, "utf8")) as Record<string, unknown>;
- if (
- typeof parsed.mcpServers === "object" &&
- parsed.mcpServers !== null &&
- BLA_IDENTITY.mcpServerName in (parsed.mcpServers as Record<string, unknown>)
- ) {
- delete (parsed.mcpServers as Record<string, unknown>)[BLA_IDENTITY.mcpServerName];
- writeFileSync(client.configPath, JSON.stringify(parsed, null, 2) + "\n", "utf8");
- removed.push(client.id);
+ const currentSkillSha = sha256Hex(readFileSync(skillPath));
+ const ownedByThisManifest =
+ manifestRecord !== undefined && manifestRecord.writtenSkillSha256 === currentSkillSha;
+ const ownedByAnyManifest = Object.values(manifest.clients).some(
+ (rec) => rec.skillPath === skillPath && rec.writtenSkillSha256 === currentSkillSha,
+ );
+ const ownedByFallbackUnmodified =
+ manifestRecord === undefined && mcpRemoved && currentSkillSha === bundledSkillHash;
+
+ if (ownedByThisManifest || ownedByAnyManifest || ownedByFallbackUnmodified || options.force) {
+ unlinkSync(skillPath);
+ skillRemoved = true;
+ // Only remove `client.skillDirectory` if it is now completely empty!
+ if (existsSync(client.skillDirectory)) {
+ const remainingFiles = readdirSync(client.skillDirectory);
+ if (remainingFiles.length === 0) {
+ rmdirSync(client.skillDirectory);
+ }
+ }
+ } else if (manifestRecord !== undefined || mcpRemoved) {
+ conflictReason =
+ conflictReason ??
+ `Skill file '${skillPath}' was modified after installation; preserving user changes`;
+ } else {
+ conflictReason =
+ conflictReason ??
+ `Skill file '${skillPath}' is not owned by BLA; preserving custom skill`;
}
- } catch {
- // Ignore malformed
+ } catch (err) {
+ errorMsg =
+ errorMsg ??
+ `Failed to inspect or remove skill '${skillPath}': ${err instanceof Error ? err.message : String(err)}`;
}
}
- if (existsSync(client.skillDirectory)) {
- rmSync(client.skillDirectory, { recursive: true, force: true });
+
+ if (mcpRemoved) {
+ removedClients.push(client.id);
}
+
+ const itemStatus: ClientUninstallResult["status"] = errorMsg
+ ? "error"
+ : conflictReason
+ ? "conflict"
+ : mcpRemoved || skillRemoved
+ ? "removed"
+ : "noop";
+
+ const itemResult: ClientUninstallResult = {
+ clientId: client.id,
+ configPath: client.configPath,
+ skillPath,
+ mcpRemoved,
+ skillRemoved,
+ status: itemStatus,
+ ...(conflictReason ? { conflictReason } : {}),
+ ...(errorMsg ? { error: errorMsg } : {}),
+ };
+
+ results.push(itemResult);
+ if (itemStatus === "conflict" || itemStatus === "error") {
+ conflicts.push(itemResult);
+ }
+ }
+
+ // Persist updated manifest if it existed or has remaining records
+ const manifestPath = getInstallManifestPath(home);
+ if (existsSync(manifestPath) || Object.keys(remainingManifestClients).length > 0) {
+ writeInstallManifest(home, {
+ version: 1,
+ updatedAt: new Date().toISOString(),
+ clients: remainingManifestClients,
+ });
}
- return { removedClients: removed };
+ return {
+ removedClients,
+ results,
+ conflicts,
+ };
}
+
+export const uninstallSetup = runUninstall;
diff --git a/tests/setup-mcp-doctor-release.test.ts b/tests/setup-mcp-doctor-release.test.ts
new file mode 100644
index 0000000..2942697
--- /dev/null
+++ b/tests/setup-mcp-doctor-release.test.ts
@@ -0,0 +1,936 @@
+import { spawn, spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { BLA_IDENTITY } from "../src/identity.js";
+import {
+ packDualReleaseTarballs,
+ planNpmPublishRetry,
+ ReleaseConsistencyError,
+ verifyReleaseConsistency,
+} from "../src/core/release-plan.js";
+import {
+ BLA_MCP_PROMPTS,
+ BLA_MCP_TOOLS,
+ handleMcpRequest,
+ type JsonRpcResponse,
+ type McpEngineHandlers,
+} from "../src/mcp/server.js";
+import {
+ CLIENT_COMPATIBILITY_MATRIX,
+ detectInstalledClients,
+ readCodexTomlMcp,
+ resolveSupportedAgentClients,
+} from "../src/setup/clients.js";
+import { runDoctor } from "../src/setup/doctor.js";
+import {
+ getInstallManifestPath,
+ readInstallManifest,
+ runSetup,
+ runUninstall,
+} from "../src/setup/setup.js";
+
+const tempDirs: string[] = [];
+
+function makeTempDir(prefix: string = "bla-issue-8-12-"): string {
+ const dir = mkdtempSync(join(tmpdir(), prefix));
+ tempDirs.push(dir);
+ return dir;
+}
+
+function sha256File(filePath: string): string {
+ return createHash("sha256").update(readFileSync(filePath)).digest("hex");
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const dir of tempDirs.splice(0)) {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+describe("Issue #8: Native Client Config Formats, Accurate Detection & Cross-Platform Fixtures", () => {
+ it("does not detect any installed clients in an empty fakeHome and separates explicit vs discovered selection", () => {
+ const emptyHome = makeTempDir("bla-empty-home-");
+
+ // 1. Empty home must never falsely detect Claude Code or any other client
+ expect(detectInstalledClients(emptyHome)).toEqual([]);
+ const defs = resolveSupportedAgentClients(emptyHome);
+ expect(defs.every((d) => d.detected === false)).toBe(true);
+
+ // 2. Running setup without explicit clients on an empty home discovers 0 clients and writes nothing
+ const autoSetup = runSetup({ homeDir: emptyHome, yes: true });
+ expect(autoSetup.discoveredClients).toEqual([]);
+ expect(autoSetup.explicitClients).toEqual([]);
+ expect(autoSetup.selectionMode).toBe("discovered");
+ expect(autoSetup.actions).toEqual([]);
+
+ // 3. Running setup with explicit clients reports discoveredClients: [] separately from explicitClients
+ const explicitSetup = runSetup({
+ homeDir: emptyHome,
+ clientIds: ["claude_code", "codex"],
+ yes: true,
+ });
+ expect(explicitSetup.status).toBe("applied");
+ expect(explicitSetup.selectionMode).toBe("explicit");
+ expect(explicitSetup.discoveredClients).toEqual([]);
+ expect(explicitSetup.explicitClients).toEqual(["claude_code", "codex"]);
+ expect(explicitSetup.actions.every((a) => a.selectionSource === "explicit")).toBe(true);
+ expect(explicitSetup.actions.every((a) => a.clientDetected === false)).toBe(true);
+ });
+
+ it("writes native Codex TOML (~/.codex/config.toml), VS Code servers JSON, and OpenCode mcp local array JSON while preserving comments and unrelated keys", () => {
+ const fakeHome = makeTempDir("bla-native-formats-");
+
+ // Seed Codex config.toml with comments, top-level keys, and another MCP server
+ const codexDir = join(fakeHome, ".codex");
+ mkdirSync(codexDir, { recursive: true });
+ const codexConfigPath = join(codexDir, "config.toml");
+ const initialCodexToml = [
+ "# Codex user configuration comment",
+ 'model = "o3"',
+ 'approval_policy = "on-request"',
+ "",
+ "[mcp_servers.git]",
+ 'command = "uvx"',
+ 'args = ["mcp-server-git", "--repository", "."]',
+ "",
+ ].join("\n");
+ writeFileSync(codexConfigPath, initialCodexToml, "utf8");
+
+ // Seed VS Code user-profile mcp.json with `inputs` and an existing `servers` entry
+ const vscodeClient = resolveSupportedAgentClients(fakeHome).find((c) => c.id === "vscode")!;
+ mkdirSync(join(vscodeClient.configPath, ".."), { recursive: true });
+ writeFileSync(
+ vscodeClient.configPath,
+ JSON.stringify(
+ {
+ inputs: [{ id: "token", type: "promptString", description: "API Token" }],
+ servers: {
+ existing_stdio: {
+ type: "stdio",
+ command: "node",
+ args: ["./existing-server.js"],
+ },
+ },
+ },
+ null,
+ 2,
+ ) + "\n",
+ "utf8",
+ );
+
+ // Seed OpenCode opencode.json with $schema, theme, and an existing `mcp` entry
+ const opencodeClient = resolveSupportedAgentClients(fakeHome).find((c) => c.id === "opencode")!;
+ mkdirSync(join(opencodeClient.configPath, ".."), { recursive: true });
+ writeFileSync(
+ opencodeClient.configPath,
+ JSON.stringify(
+ {
+ $schema: "https://opencode.ai/config.json",
+ theme: "tokyonight",
+ mcp: {
+ memory: {
+ type: "local",
+ command: ["npx", "-y", "@modelcontextprotocol/server-memory"],
+ enabled: true,
+ },
+ },
+ },
+ null,
+ 2,
+ ) + "\n",
+ "utf8",
+ );
+
+ // Auto-discovery should now detect exactly codex, vscode, and opencode
+ expect(detectInstalledClients(fakeHome).sort()).toEqual(["codex", "opencode", "vscode"]);
+
+ const res = runSetup({
+ homeDir: fakeHome,
+ onlyDetected: true,
+ yes: true,
+ });
+ expect(res.status).toBe("applied");
+ expect(res.selectionMode).toBe("discovered");
+ expect([...res.discoveredClients].sort()).toEqual(["codex", "opencode", "vscode"]);
+
+ // Verify Codex native ~/.codex/config.toml independently of BLA's adapter
+ expect(existsSync(join(codexDir, "mcp.json"))).toBe(false);
+ const writtenToml = readFileSync(codexConfigPath, "utf8");
+ expect(readCodexTomlMcp(writtenToml).status).toBe("valid");
+ expect(writtenToml).toContain("# Codex user configuration comment");
+ expect(writtenToml).toContain('model = "o3"');
+ expect(writtenToml).toContain("[mcp_servers.git]");
+ expect(writtenToml).toContain("[mcp_servers.bla]");
+ expect(writtenToml).toContain('command = "npx"');
+ expect(writtenToml).toContain('args = ["-y", "bla-agents@latest", "mcp"]');
+
+ // Verify VS Code native mcp.json uses root key `servers` (NOT `mcpServers`)
+ const writtenVscode = JSON.parse(readFileSync(vscodeClient.configPath, "utf8")) as Record<
+ string,
+ unknown
+ >;
+ expect(writtenVscode.mcpServers).toBeUndefined();
+ expect(writtenVscode.inputs).toEqual([
+ { id: "token", type: "promptString", description: "API Token" },
+ ]);
+ const vscodeServers = writtenVscode.servers as Record<string, unknown>;
+ expect(vscodeServers.existing_stdio).toBeDefined();
+ expect(vscodeServers.bla).toEqual({
+ type: "stdio",
+ command: "npx",
+ args: ["-y", "bla-agents@latest", "mcp"],
+ });
+
+ // Verify OpenCode native opencode.json uses root key `mcp` with `type: "local"` and `command` array
+ const writtenOpencode = JSON.parse(readFileSync(opencodeClient.configPath, "utf8")) as Record<
+ string,
+ unknown
+ >;
+ expect(writtenOpencode.mcpServers).toBeUndefined();
+ expect(writtenOpencode.$schema).toBe("https://opencode.ai/config.json");
+ expect(writtenOpencode.theme).toBe("tokyonight");
+ const opencodeMcp = writtenOpencode.mcp as Record<string, unknown>;
+ expect(opencodeMcp.memory).toBeDefined();
+ expect(opencodeMcp.bla).toEqual({
+ type: "local",
+ command: ["npx", "-y", "bla-agents@latest", "mcp"],
+ enabled: true,
+ });
+ });
+
+ it("resolves Linux, macOS, and Windows client paths with spaces in homeDir and exposes the compatibility matrix", () => {
+ const baseTmp = makeTempDir("bla-platform-paths-");
+ const spacedHome = join(baseTmp, "User Home With Spaces");
+ mkdirSync(spacedHome, { recursive: true });
+
+ const darwinClients = resolveSupportedAgentClients(spacedHome, "darwin");
+ const linuxClients = resolveSupportedAgentClients(spacedHome, "linux", {
+ XDG_CONFIG_HOME: join(spacedHome, ".xdg config"),
+ });
+ const winClients = resolveSupportedAgentClients(spacedHome, "win32", {
+ APPDATA: join(spacedHome, "AppData", "Roaming"),
+ });
+
+ expect(darwinClients.find((c) => c.id === "vscode")?.configPath).toBe(
+ join(spacedHome, "Library", "Application Support", "Code", "User", "mcp.json"),
+ );
+ expect(linuxClients.find((c) => c.id === "vscode")?.configPath).toBe(
+ join(spacedHome, ".xdg config", "Code", "User", "mcp.json"),
+ );
+ expect(linuxClients.find((c) => c.id === "opencode")?.configPath).toBe(
+ join(spacedHome, ".xdg config", "opencode", "opencode.json"),
+ );
+ expect(winClients.find((c) => c.id === "vscode")?.configPath).toBe(
+ join(spacedHome, "AppData", "Roaming", "Code", "User", "mcp.json"),
+ );
+
+ expect(CLIENT_COMPATIBILITY_MATRIX.length).toBe(10);
+ expect(CLIENT_COMPATIBILITY_MATRIX.find((m) => m.clientId === "codex")?.format).toBe(
+ "toml-codex",
+ );
+ expect(CLIENT_COMPATIBILITY_MATRIX.find((m) => m.clientId === "vscode")?.rootKey).toBe(
+ "servers",
+ );
+ expect(CLIENT_COMPATIBILITY_MATRIX.find((m) => m.clientId === "opencode")?.rootKey).toBe(
+ "mcp",
+ );
+ });
+});
+
+describe("Issue #9: Fail-Closed Config Parsing, Non-Clobbering Backups & Ownership-Checked Uninstall", () => {
+ it("refuses to overwrite malformed JSON/TOML or invalid schema configs and preserves original bytes and hashes", () => {
+ const fakeHome = makeTempDir("bla-malformed-");
+
+ // 1. Malformed JSON in .claude.json
+ const claudePath = join(fakeHome, ".claude.json");
+ writeFileSync(claudePath, '{ "mcpServers": { "broken": true, ', "utf8");
+ const claudeOriginalSha = sha256File(claudePath);
+
+ // 2. Malformed TOML in .codex/config.toml
+ const codexDir = join(fakeHome, ".codex");
+ mkdirSync(codexDir, { recursive: true });
+ const codexPath = join(codexDir, "config.toml");
+ writeFileSync(codexPath, '[mcp_servers.unclosed\ncommand = "npx"\n', "utf8");
+ const codexOriginalSha = sha256File(codexPath);
+
+ // 3. Schema type error in Cursor mcp.json (`mcpServers` is an array instead of object)
+ const cursorDir = join(fakeHome, ".cursor");
+ mkdirSync(cursorDir, { recursive: true });
+ const cursorPath = join(cursorDir, "mcp.json");
+ writeFileSync(cursorPath, '{"mcpServers": ["not-an-object"]}\n', "utf8");
+ const cursorOriginalSha = sha256File(cursorPath);
+
+ const res = runSetup({
+ homeDir: fakeHome,
+ clientIds: ["claude_code", "codex", "cursor"],
+ yes: true,
+ });
+
+ expect(res.status).toBe("error");
+ expect(res.actions.every((a) => a.status === "error" && a.applied === false)).toBe(true);
+
+ // Byte-for-byte SHA-256 must remain identical
+ expect(sha256File(claudePath)).toBe(claudeOriginalSha);
+ expect(sha256File(codexPath)).toBe(codexOriginalSha);
+ expect(sha256File(cursorPath)).toBe(cursorOriginalSha);
+
+ // Skills must NOT have been written for any failed client
+ for (const action of res.actions) {
+ expect(existsSync(action.skillPath)).toBe(false);
+ }
+ });
+
+ it("never clobbers the original .bla-backup recovery point across repeated setup runs", () => {
+ const fakeHome = makeTempDir("bla-backup-preserve-");
+ const claudePath = join(fakeHome, ".claude.json");
+ const backupPath = `${claudePath}.bla-backup`;
+
+ const originalContent = JSON.stringify(
+ {
+ customSetting: "preserve-me-forever",
+ mcpServers: {
+ customServer: { command: "node", args: ["custom.js"] },
+ },
+ },
+ null,
+ 2,
+ );
+ writeFileSync(claudePath, originalContent, "utf8");
+ const originalSha = sha256File(claudePath);
+
+ // First setup creates `.bla-backup`
+ const first = runSetup({
+ homeDir: fakeHome,
+ clientIds: ["claude_code"],
+ yes: true,
+ });
+ expect(first.status).toBe("applied");
+ expect(existsSync(backupPath)).toBe(true);
+ expect(sha256File(backupPath)).toBe(originalSha);
+
+ // Second setup modifies `.claude.json` again, but MUST NOT overwrite `.bla-backup`
+ const second = runSetup({
+ homeDir: fakeHome,
+ clientIds: ["claude_code"],
+ mcpCommand: "node",
+ mcpArgs: ["dist/cli.js", "mcp"],
+ yes: true,
+ });
+ expect(second.status).toBe("applied");
+ expect(sha256File(backupPath)).toBe(originalSha);
+
+ // Even if `.claude.json` becomes malformed later and setup is run a third time, `.bla-backup` is untouched
+ writeFileSync(claudePath, "{ malformed json", "utf8");
+ const third = runSetup({
+ homeDir: fakeHome,
+ clientIds: ["claude_code"],
+ yes: true,
+ });
+ expect(third.status).toBe("error");
+ expect(sha256File(backupPath)).toBe(originalSha);
+
+ // Verify install manifest was recorded atomically
+ expect(existsSync(getInstallManifestPath(fakeHome))).toBe(true);
+ const manifest = readInstallManifest(fakeHome);
+ expect(manifest.clients.claude_code?.backupSha256).toBe(originalSha);
+ });
+
+ it("preserves user-note.txt, custom SKILL.md, modified SKILL.md, shared skillDirectory, and custom 'bla' MCP servers on uninstall", () => {
+ const fakeHome = makeTempDir("bla-uninstall-ownership-");
+
+ // Case A: User manually created `.agents/skills/blind-llm-agents/user-note.txt` WITHOUT installing BLA
+ const sharedSkillDir = join(fakeHome, ".agents", "skills", "blind-llm-agents");
+ mkdirSync(sharedSkillDir, { recursive: true });
+ const userNotePath = join(sharedSkillDir, "user-note.txt");
+ writeFileSync(userNotePath, "Important user research notes - DO NOT DELETE\n", "utf8");
+
+ const uninstallBeforeInstall = runUninstall({ homeDir: fakeHome });
+ expect(uninstallBeforeInstall.removedClients).toEqual([]);
+ expect(existsSync(userNotePath)).toBe(true);
+
+ // Case B: Multiple clients sharing `.agents/skills/blind-llm-agents` (`windsurf` and `vscode`)
+ const setupShared = runSetup({
+ homeDir: fakeHome,
+ clientIds: ["windsurf", "vscode"],
+ yes: true,
+ });
+ expect(setupShared.status).toBe("applied");
+ const sharedSkillMd = join(sharedSkillDir, "SKILL.md");
+ expect(existsSync(sharedSkillMd)).toBe(true);
+
+ // Uninstalling ONLY `windsurf` must keep `SKILL.md` because `vscode` still owns it
+ const partialUninstall = runUninstall({
+ homeDir: fakeHome,
+ clientIds: ["windsurf"],
+ });
+ expect(partialUninstall.removedClients).toEqual(["windsurf"]);
+ expect(existsSync(sharedSkillMd)).toBe(true);
+ expect(existsSync(userNotePath)).toBe(true);
+
+ // Uninstalling `vscode` removes `SKILL.md`, but preserves `user-note.txt` and `sharedSkillDir`!
+ const secondUninstall = runUninstall({
+ homeDir: fakeHome,
+ clientIds: ["vscode"],
+ });
+ expect(secondUninstall.removedClients).toEqual(["vscode"]);
+ expect(existsSync(sharedSkillMd)).toBe(false);
+ expect(existsSync(userNotePath)).toBe(true);
+
+ // Case C: User modifies `SKILL.md` after installing `cursor`
+ runSetup({ homeDir: fakeHome, clientIds: ["cursor"], yes: true });
+ const cursorSkillPath = join(fakeHome, ".cursor", "skills", "blind-llm-agents", "SKILL.md");
+ writeFileSync(cursorSkillPath, "# Custom user edits to SKILL.md\n", "utf8");
+ const modifiedUninstall = runUninstall({ homeDir: fakeHome, clientIds: ["cursor"] });
+ expect(modifiedUninstall.conflicts.length).toBe(1);
+ expect(existsSync(cursorSkillPath)).toBe(true);
+
+ // Case D: User has a custom non-BLA MCP server named `bla` in `.claude.json`
+ const claudePath = join(fakeHome, ".claude.json");
+ writeFileSync(
+ claudePath,
+ JSON.stringify({
+ mcpServers: {
+ bla: { command: "/opt/my-unrelated-bla-binary", args: ["--serve"] },
+ },
+ }),
+ "utf8",
+ );
+ const customUninstall = runUninstall({ homeDir: fakeHome, clientIds: ["claude_code"] });
+ expect(customUninstall.conflicts.some((c) => c.clientId === "claude_code")).toBe(true);
+ const preservedClaude = JSON.parse(readFileSync(claudePath, "utf8")) as {
+ mcpServers: { bla: { command: string } };
+ };
+ expect(preservedClaude.mcpServers.bla.command).toBe("/opt/my-unrelated-bla-binary");
+ });
+
+ it("performs zero filesystem writes when dryRun is true", () => {
+ const fakeHome = makeTempDir("bla-dryrun-");
+ const res = runSetup({
+ homeDir: fakeHome,
+ clientIds: ["claude_code", "codex", "vscode", "opencode"],
+ dryRun: true,
+ yes: true,
+ });
+ expect(res.status).toBe("planned");
+ for (const action of res.actions) {
+ expect(existsSync(action.configPath)).toBe(false);
+ expect(existsSync(action.skillPath)).toBe(false);
+ }
+ expect(existsSync(getInstallManifestPath(fakeHome))).toBe(false);
+ });
+});
+
+describe("Issue #10: MCP Runtime Argument Validation, Prompts Contract & Subprocess Stdio Verification", () => {
+ it("rejects missing, empty, non-string, and invalid-enum arguments across all MCP tools with -32602 and zero engine/FS side effects", async () => {
+ const spyHandlers: McpEngineHandlers = {
+ defendTarget: vi.fn(),
+ auditTarget: vi.fn(),
+ protectTarget: vi.fn(),
+ verifyTarget: vi.fn(),
+ runShowcaseBenchmark: vi.fn(),
+ emitCompileTimeNativeHeader: vi.fn(),
+ runDoctor: vi.fn(),
+ inspectReleaseExposure: vi.fn(),
+ initBlaConfig: vi.fn(),
+ };
+
+ const invalidCalls: Array<{ name: string; arguments: unknown }> = [
+ { name: "bla_audit", arguments: {} },
+ { name: "bla_audit", arguments: { path: "" } },
+ { name: "bla_audit", arguments: { path: " " } },
+ { name: "bla_audit", arguments: { path: null } },
+ { name: "bla_audit", arguments: { path: 123 } },
+ { name: "bla_audit", arguments: { path: {} } },
+ { name: "bla_protect", arguments: {} },
+ { name: "bla_protect", arguments: { input_path: "" } },
+ { name: "bla_protect", arguments: { input_path: "./a.js", intensity: "invalid-preset" } },
+ { name: "bla_defend", arguments: {} },
+ { name: "bla_defend", arguments: { input_path: null } },
+ { name: "bla_defend", arguments: { input_path: "./a.js", emit_manifest: "yes" } },
+ { name: "bla_verify", arguments: {} },
+ { name: "bla_verify", arguments: { target_path: "" } },
+ { name: "bla_emit_headers", arguments: {} },
+ { name: "bla_emit_headers", arguments: { language: "python" } },
+ { name: "bla_inspect_release", arguments: {} },
+ { name: "bla_inspect_release", arguments: { path: "./dist", max_files: -5 } },
+ { name: "bla_init", arguments: {} },
+ { name: "bla_init", arguments: { directory: "" } },
+ { name: "bla_doctor", arguments: { home_dir: "" } },
+ { name: "bla_benchmark", arguments: { unexpected: true } },
+ ];
+
+ for (const [idx, call] of invalidCalls.entries()) {
+ const res = await handleMcpRequest(
+ {
+ jsonrpc: "2.0",
+ id: idx + 1,
+ method: "tools/call",
+ params: call,
+ },
+ spyHandlers,
+ );
+ expect(res?.error?.code).toBe(-32602);
+ }
+
+ // Prove ZERO engine handlers were invoked for any invalid call
+ for (const fn of Object.values(spyHandlers)) {
+ expect(fn).not.toHaveBeenCalled();
+ }
+
+ // Prove explicit `path: "."` is distinguished from missing `path`
+ await handleMcpRequest(
+ {
+ jsonrpc: "2.0",
+ id: 999,
+ method: "tools/call",
+ params: {
+ name: "bla_audit",
+ arguments: { path: "." },
+ },
+ },
+ spyHandlers,
+ );
+ expect(spyHandlers.auditTarget).toHaveBeenCalledWith(".");
+ });
+
+ it("implements prompts/get for all advertised prompts in prompts/list and validates required arguments", async () => {
+ const listRes = await handleMcpRequest({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "prompts/list",
+ });
+ const prompts = (listRes?.result as { prompts: typeof BLA_MCP_PROMPTS }).prompts;
+ expect(prompts.length).toBeGreaterThanOrEqual(1);
+
+ for (const p of prompts) {
+ const getRes = await handleMcpRequest({
+ jsonrpc: "2.0",
+ id: 2,
+ method: "prompts/get",
+ params: {
+ name: p.name,
+ arguments: { target_path: "./dist/app.js" },
+ },
+ });
+ expect(getRes?.error).toBeUndefined();
+ const result = getRes?.result as {
+ description: string;
+ messages: Array<{ role: string; content: { type: string; text: string } }>;
+ };
+ expect(result.messages.length).toBeGreaterThan(0);
+ expect(result.messages[0]?.content.text).toContain("./dist/app.js");
+
+ // Missing target_path must return -32602
+ const badRes = await handleMcpRequest({
+ jsonrpc: "2.0",
+ id: 3,
+ method: "prompts/get",
+ params: {
+ name: p.name,
+ arguments: {},
+ },
+ });
+ expect(badRes?.error?.code).toBe(-32602);
+ }
+ });
+
+ it("completes end-to-end stdio protocol exchange with a real `node dist/cli.js mcp` child process", async () => {
+ const fixtureDir = makeTempDir("bla-stdio-fixture-");
+ const sampleJs = join(fixtureDir, "sample.js");
+ writeFileSync(sampleJs, "export function add(a, b) { return a + b; }\n", "utf8");
+
+ const cliPath = resolve(process.cwd(), "dist/cli.js");
+ if (!existsSync(cliPath)) {
+ const buildRes = spawnSync("npm", ["run", "build"], {
+ cwd: process.cwd(),
+ stdio: "pipe",
+ });
+ expect(buildRes.status).toBe(0);
+ }
+
+ const child = spawn(process.execPath, [cliPath, "mcp"], {
+ cwd: fixtureDir,
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+
+ const stdoutLines: string[] = [];
+ let buffer = "";
+
+ const collectResponses = new Promise<void>((resolvePromise, rejectPromise) => {
+ const timer = setTimeout(() => {
+ child.kill();
+ rejectPromise(new Error(`Timed out waiting for MCP stdio responses. Got: ${stdoutLines.length}`));
+ }, 10000);
+
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ buffer += chunk;
+ let idx: number;
+ while ((idx = buffer.indexOf("\n")) >= 0) {
+ const line = buffer.slice(0, idx).trim();
+ buffer = buffer.slice(idx + 1);
+ if (line.length > 0) {
+ stdoutLines.push(line);
+ if (stdoutLines.length >= 5) {
+ clearTimeout(timer);
+ resolvePromise();
+ }
+ }
+ }
+ });
+
+ child.on("error", (err) => {
+ clearTimeout(timer);
+ rejectPromise(err);
+ });
+ });
+
+ const requests = [
+ {
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: "2024-11-05",
+ capabilities: {},
+ clientInfo: { name: "bla-stdio-test-client", version: "1.0.0" },
+ },
+ },
+ // Notification without `id` must NOT emit a response line
+ {
+ jsonrpc: "2.0",
+ method: "notifications/initialized",
+ },
+ {
+ jsonrpc: "2.0",
+ id: 2,
+ method: "tools/list",
+ },
+ {
+ jsonrpc: "2.0",
+ id: 3,
+ method: "prompts/get",
+ params: {
+ name: "shield-against-rea",
+ arguments: { target_path: sampleJs },
+ },
+ },
+ {
+ jsonrpc: "2.0",
+ id: 4,
+ method: "tools/call",
+ params: {
+ name: "bla_audit",
+ arguments: { path: sampleJs },
+ },
+ },
+ {
+ jsonrpc: "2.0",
+ id: 5,
+ method: "tools/call",
+ params: {
+ name: "bla_audit",
+ arguments: {},
+ },
+ },
+ ];
+
+ for (const req of requests) {
+ child.stdin.write(JSON.stringify(req) + "\n");
+ }
+
+ await collectResponses;
+ child.kill();
+
+ // Every line on stdout must be valid JSON-RPC 2.0
+ expect(stdoutLines.length).toBe(5);
+ const parsedResponses = stdoutLines.map((l) => JSON.parse(l) as JsonRpcResponse);
+ expect(parsedResponses.map((r) => r.id)).toEqual([1, 2, 3, 4, 5]);
+
+ expect(parsedResponses[0]?.result).toMatchObject({
+ protocolVersion: "2024-11-05",
+ serverInfo: { name: "bla", version: BLA_IDENTITY.version },
+ });
+ expect(
+ (parsedResponses[1]?.result as { tools: unknown[] }).tools.length,
+ ).toBe(BLA_MCP_TOOLS.length);
+ expect(parsedResponses[2]?.error).toBeUndefined();
+ expect((parsedResponses[3]?.result as { isError: boolean }).isError).toBe(false);
+ expect(parsedResponses[4]?.error?.code).toBe(-32602);
+ });
+});
+
+describe("Issue #11: Doctor Real Readiness Checks & Command/Config/Skill/Handshake Diagnostics", () => {
+ it("reports healthy: false and mcpRegistered: false when bla.command is '/no/such/command' and skill is missing", () => {
+ const fakeHome = makeTempDir("bla-doctor-broken-cmd-");
+ writeFileSync(
+ join(fakeHome, ".claude.json"),
+ JSON.stringify({
+ mcpServers: {
+ bla: {
+ command: "/no/such/command",
+ args: ["mcp"],
+ },
+ },
+ }),
+ "utf8",
+ );
+
+ const report = runDoctor(fakeHome);
+ expect(report.healthy).toBe(false);
+ expect(report.exitCode).toBe(1);
+ expect(report.status).toBe("fail");
+
+ const claudeDiag = report.agentClients.find((c) => c.id === "claude_code")!;
+ expect(claudeDiag.detected).toBe(true);
+ expect(claudeDiag.configured).toBe(true);
+ expect(claudeDiag.commandResolvable).toBe(false);
+ expect(claudeDiag.mcpRegistered).toBe(false);
+ expect(claudeDiag.skillInstalled).toBe(false);
+ expect(claudeDiag.handshakeStatus).toBe("not_checked");
+ expect(claudeDiag.status).toBe("fail");
+ });
+
+ it("distinguishes malformed config, invalid schema, missing skill, healthy setup, and unavailable runtime engine", () => {
+ // 1. Malformed TOML in Codex
+ const homeMalformed = makeTempDir("bla-doc-malformed-");
+ mkdirSync(join(homeMalformed, ".codex"), { recursive: true });
+ writeFileSync(join(homeMalformed, ".codex", "config.toml"), "[mcp_servers.bla\n", "utf8");
+ const docMalformed = runDoctor(homeMalformed);
+ expect(docMalformed.healthy).toBe(false);
+ expect(docMalformed.exitCode).toBe(1);
+ expect(docMalformed.agentClients.find((c) => c.id === "codex")?.configStatus).toBe("malformed");
+
+ // 2. Wrong root schema key in VS Code (`mcpServers` instead of `servers`)
+ const homeWrongSchema = makeTempDir("bla-doc-schema-");
+ const vscodeDef = resolveSupportedAgentClients(homeWrongSchema).find((c) => c.id === "vscode")!;
+ mkdirSync(join(vscodeDef.configPath, ".."), { recursive: true });
+ writeFileSync(
+ vscodeDef.configPath,
+ JSON.stringify({ mcpServers: { bla: { command: "npx", args: [] } } }),
+ "utf8",
+ );
+ const docWrongSchema = runDoctor(homeWrongSchema);
+ expect(docWrongSchema.healthy).toBe(false);
+ expect(docWrongSchema.agentClients.find((c) => c.id === "vscode")?.configStatus).toBe(
+ "malformed",
+ );
+
+ // 3. Valid MCP config with resolvable command (`process.execPath`), but missing SKILL.md
+ const homeNoSkill = makeTempDir("bla-doc-noskill-");
+ writeFileSync(
+ join(homeNoSkill, ".claude.json"),
+ JSON.stringify({
+ mcpServers: {
+ bla: { command: process.execPath, args: ["dist/cli.js", "mcp"] },
+ },
+ }),
+ "utf8",
+ );
+ const docNoSkill = runDoctor(homeNoSkill);
+ expect(docNoSkill.healthy).toBe(false);
+ const claudeNoSkill = docNoSkill.agentClients.find((c) => c.id === "claude_code")!;
+ expect(claudeNoSkill.configured).toBe(true);
+ expect(claudeNoSkill.commandResolvable).toBe(true);
+ expect(claudeNoSkill.skillInstalled).toBe(false);
+ expect(claudeNoSkill.status).toBe("fail");
+
+ // 4. Healthy setup with resolvable command and installed skill
+ const homeHealthy = makeTempDir("bla-doc-healthy-");
+ runSetup({
+ homeDir: homeHealthy,
+ clientIds: ["claude_code", "codex", "vscode", "opencode"],
+ mcpCommand: process.execPath,
+ mcpArgs: [resolve(process.cwd(), "dist/cli.js"), "mcp"],
+ yes: true,
+ });
+ const docHealthy = runDoctor({
+ homeDir: homeHealthy,
+ verifyHandshake: true,
+ });
+ expect(docHealthy.healthy).toBe(true);
+ expect(docHealthy.exitCode).toBe(0);
+ const claudeHealthy = docHealthy.agentClients.find((c) => c.id === "claude_code")!;
+ expect(claudeHealthy.status).toBe("pass");
+ expect(claudeHealthy.handshakeStatus).toBe("verified");
+ expect(claudeHealthy.handshakeVerified).toBe(true);
+
+ // 5. Degraded/unavailable SQLite runtime engine
+ const docNoSqlite = runDoctor({
+ homeDir: homeHealthy,
+ sqliteAvailableOverride: false,
+ });
+ expect(docNoSqlite.engines.sqliteRuntime).toBe("unavailable");
+ expect(docNoSqlite.healthy).toBe(false);
+ expect(docNoSqlite.exitCode).toBe(1);
+ });
+});
+
+describe("Issue #12: Release Version, Tag, Commit & Tarball Consistency + Dual Tarball Smoke Verification", () => {
+ const validSha256 = "a".repeat(64);
+ const altSha256 = "b".repeat(64);
+ const headSha = "66be143f2ba81816186ca310513a90aa042e5940";
+ const otherCommitSha = "1111111f2ba81816186ca310513a90aa042e5940";
+
+ it("enforces version, dispatch input, trigger tag, existing tag commit, and release asset SHA-256 consistency", () => {
+ // 1. Matching configuration succeeds
+ const plan = verifyReleaseConsistency({
+ packageVersion: "1.1.0",
+ identityVersion: "1.1.0",
+ dispatchVersion: "1.1.0",
+ triggerRef: "refs/tags/bla-agents-1.1.0",
+ headSha,
+ existingTagSha: headSha,
+ tarballSha256: validSha256,
+ existingReleaseAssetSha256: validSha256,
+ });
+ expect(plan.canonicalTag).toBe("bla-agents-1.1.0");
+ expect(plan.tagAction).toBe("verify-existing-idempotent");
+ expect(plan.releaseAssetAction).toBe("skip-identical");
+
+ // 2. Mismatched workflow_dispatch version fails
+ expect(() =>
+ verifyReleaseConsistency({
+ packageVersion: "1.1.0",
+ dispatchVersion: "1.2.0",
+ headSha,
+ tarballSha256: validSha256,
+ }),
+ ).toThrowError(ReleaseConsistencyError);
+
+ // 3. Mismatched v-tag fails
+ expect(() =>
+ verifyReleaseConsistency({
+ packageVersion: "1.1.0",
+ triggerRef: "refs/tags/v1.0.9",
+ headSha,
+ tarballSha256: validSha256,
+ }),
+ ).toThrowError(ReleaseConsistencyError);
+
+ // 4. Existing tag pointing to a different commit fails
+ expect(() =>
+ verifyReleaseConsistency({
+ packageVersion: "1.1.0",
+ headSha,
+ existingTagSha: otherCommitSha,
+ tarballSha256: validSha256,
+ }),
+ ).toThrowError(ReleaseConsistencyError);
+
+ // 5. Existing release asset with different SHA-256 fails (no clobber)
+ expect(() =>
+ verifyReleaseConsistency({
+ packageVersion: "1.1.0",
+ headSha,
+ existingTagSha: headSha,
+ tarballSha256: validSha256,
+ existingReleaseAssetSha256: altSha256,
+ }),
+ ).toThrowError(ReleaseConsistencyError);
+
+ // 6. Dual-package retry plan: primary already published, alias failed previously
+ const retryPlan = planNpmPublishRetry({
+ primaryPublished: true,
+ aliasPublished: false,
+ primaryTarballSha256: validSha256,
+ publishedPrimarySha256: validSha256,
+ aliasTarballSha256: altSha256,
+ });
+ expect(retryPlan.primaryAction).toBe("skip-already-published");
+ expect(retryPlan.aliasAction).toBe("publish");
+ expect(retryPlan.shouldPublishPrimary).toBe(false);
+ expect(retryPlan.shouldPublishAlias).toBe(true);
+ });
+
+ it("packs both bla-agents and bla-shield tarballs and verifies exports, 3 bin entrypoints, and read-only doctor in clean temp dirs", () => {
+ const outDir = makeTempDir("bla-release-pack-");
+ const packed = packDualReleaseTarballs(process.cwd(), outDir);
+
+ expect(existsSync(packed.primary.tarballPath)).toBe(true);
+ expect(existsSync(packed.alias.tarballPath)).toBe(true);
+ expect(existsSync(packed.sha256SumsPath)).toBe(true);
+
+ const sumsText = readFileSync(packed.sha256SumsPath, "utf8");
+ expect(sumsText).toContain(`${packed.primary.sha256} ${packed.primary.tarballFilename}`);
+ expect(sumsText).toContain(`${packed.alias.sha256} ${packed.alias.tarballFilename}`);
+
+ for (const artifact of [packed.primary, packed.alias]) {
+ const unpackDir = makeTempDir(`bla-unpack-${artifact.packageName}-`);
+ const tarRes = spawnSync("tar", ["-xzf", artifact.tarballPath, "-C", unpackDir], {
+ stdio: "pipe",
+ });
+ expect(tarRes.status).toBe(0);
+ symlinkSync(
+ join(process.cwd(), "node_modules"),
+ join(unpackDir, "node_modules"),
+ "dir",
+ );
+
+ const pkgRoot = join(unpackDir, "package");
+ const pkgManifest = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8")) as {
+ name: string;
+ version: string;
+ bin: Record<string, string>;
+ exports: Record<string, { default?: string; import?: string; types: string }>;
+ };
+
+ expect(pkgManifest.name).toBe(artifact.packageName);
+ expect(pkgManifest.version).toBe(BLA_IDENTITY.version);
+
+ // Verify all 3 bin entrypoints exist in the packed artifact
+ expect(Object.keys(pkgManifest.bin).sort()).toEqual(["bla", "bla-agents", "bla-shield"]);
+ for (const relBin of Object.values(pkgManifest.bin)) {
+ expect(existsSync(join(pkgRoot, relBin))).toBe(true);
+ }
+
+ // Verify exports (`.` and `./bundler`) exist in the packed artifact
+ const rootEntry = pkgManifest.exports["."]!.default ?? pkgManifest.exports["."]!.import!;
+ const bundlerEntry =
+ pkgManifest.exports["./bundler"]!.default ?? pkgManifest.exports["./bundler"]!.import!;
+ expect(existsSync(join(pkgRoot, rootEntry))).toBe(true);
+ expect(existsSync(join(pkgRoot, pkgManifest.exports["."]!.types))).toBe(true);
+ expect(existsSync(join(pkgRoot, bundlerEntry))).toBe(true);
+ expect(existsSync(join(pkgRoot, pkgManifest.exports["./bundler"]!.types))).toBe(true);
+
+ // Verify read-only `doctor --json` and MCP `initialize` against unpacked dist/cli.js
+ const docRun = spawnSync(
+ process.execPath,
+ [join(pkgRoot, "dist/cli.js"), "doctor", "--json"],
+ {
+ encoding: "utf8",
+ timeout: 5000,
+ env: { ...process.env, HOME: unpackDir },
+ },
+ );
+ expect(docRun.status).toBe(0);
+ const docJson = JSON.parse(docRun.stdout) as { blaVersion: string; healthy: boolean };
+ expect(docJson.blaVersion).toBe(BLA_IDENTITY.version);
+ expect(docJson.healthy).toBe(true);
+
+ // Verify MCP initialize against unpacked dist/cli.js
+ const mcpInit = spawnSync(
+ process.execPath,
+ [join(pkgRoot, "dist/cli.js"), "mcp"],
+ {
+ input: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize" }) + "\n",
+ encoding: "utf8",
+ timeout: 5000,
+ },
+ );
+ expect(mcpInit.stdout.trim()).toContain('"protocolVersion":"2024-11-05"');
+ }
+ });
+});