Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .beads/interactions.jsonl
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@
{"id":"int-bb37cfc61169ad85aa3958ba85b7e68a","kind":"field_change","created_at":"2026-08-19T10:08:50.364592698Z","actor":"AhravDutta","issue_id":"magic-context-78o.4","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"U3+U4 complete: worker lifecycle, registration gate, both authorities routed through evaluator"}}
{"id":"int-8a8d0c6c0c23a94136bc9fc3dd01dfbe","kind":"field_change","created_at":"2026-08-19T10:57:58.025193278Z","actor":"AhravDutta","issue_id":"magic-context-78o.5","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"U5 complete: fixtures, PARITY docs, gates run; PR #12 opened"}}
{"id":"int-5e823206f8ceb5bf66fd3aa18d93f908","kind":"field_change","created_at":"2026-08-19T10:57:58.309666212Z","actor":"AhravDutta","issue_id":"magic-context-78o","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Plan implemented end-to-end; PR https://github.com/ahrav/magic-context/pull/12"}}
{"id":"int-06cf4fbb14e9768e72fe2b7ad892208c","kind":"field_change","created_at":"2026-08-20T03:07:24.326017645Z","actor":"AhravDutta","issue_id":"magic-context-c50.5","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Internal mc-host TypeScript client implemented and all consumers migrated; PR https://github.com/ahrav/magic-context/pull/15"}}
2 changes: 1 addition & 1 deletion .beads/issues.jsonl

Large diffs are not rendered by default.

25 changes: 25 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,31 @@ jobs:
- name: Test
run: bun run --cwd packages/pi-plugin test

mc-host-client-interop:
name: mc-host client interop (Bun + Node 24)
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v5

- uses: oven-sh/setup-bun@v2
with:
bun-version: latest

- uses: actions/setup-node@v4
with:
node-version: "24"

- name: Install dependencies
run: bun install --frozen-lockfile

- name: Adversarial scenarios (Bun)
working-directory: packages/plugin
run: bun scripts/run-mc-host-client-adversarial.ts

- name: Adversarial scenarios (Node 24)
run: bun run --cwd packages/plugin test:mc-host-client:node

check-dashboard:
name: Check (dashboard)
runs-on: ubuntu-latest
Expand Down
15 changes: 6 additions & 9 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
},
"dependencies": {
"@clack/prompts": "^1.6.0",
"@cortexkit/subc-client": "0.4.1",
"comment-json": "^5.0.0",
"jsonc-parser": "^3.3.1"
},
Expand Down
17 changes: 12 additions & 5 deletions packages/e2e-tests/src/rust-runner/hermetic-subc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import {
} from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { SubcClient, type BindIdentity } from "@cortexkit/subc-client";
import { SubcClient, type BindIdentity } from "@magic-context/core/shared/mc-host-client";

const REPO_ROOT = resolve(import.meta.dir, "../../../..");
const MODULE_ID = "magic-context";
Expand Down Expand Up @@ -694,13 +694,12 @@ export class HermeticSubcStack {
route = await client.routeOpen(
{ kind: "tool_provider", module_id: MODULE_ID },
identity,
{ consumerIdentity: null },
);
const response = await client.request(route, { method, v: 1, session_id: sessionId });
return (response && typeof response === "object" ? response : {}) as Record<string, unknown>;
} catch (error) {
client.close();
if (this.statusClient === client) this.statusClient = null;
await client.closeAsync().catch(() => undefined);
throw error;
} finally {
if (route) await client.closeRoute(route).catch(() => undefined);
Expand Down Expand Up @@ -734,7 +733,14 @@ export class HermeticSubcStack {
*/
assertModuleNotSupervised(): void {
const configPath = join(this.daemonConfigDir, "cortexkit", "subc.jsonc");
const config = JSON.parse(readFileSync(configPath, "utf8")) as { modules?: unknown };
let config: { modules?: unknown };
try {
config = JSON.parse(readFileSync(configPath, "utf8")) as { modules?: unknown };
} catch (error) {
throw new Error(
`Rust outage drill precondition failed: unreadable daemon config ${configPath}: ${error}`,
);
}
if (
config.modules === null ||
typeof config.modules !== "object" ||
Expand Down Expand Up @@ -816,8 +822,9 @@ export class HermeticSubcStack {

/** Hard teardown. Safe to call more than once; never throws. */
async stop(): Promise<void> {
this.statusClient?.close();
const statusClient = this.statusClient;
this.statusClient = null;
if (statusClient) await statusClient.closeAsync().catch(() => undefined);
try {
await this.killModuleAndWait();
} catch {
Expand Down
1 change: 0 additions & 1 deletion packages/pi-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
"prepublishOnly": "bun run build"
},
"dependencies": {
"@cortexkit/subc-client": "0.4.1",
"@huggingface/transformers": "^4.1.0",
"@jitl/quickjs-singlefile-cjs-release-asyncify": "0.32.0",
"ai-tokenizer": "^1.0.6",
Expand Down
4 changes: 3 additions & 1 deletion packages/plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@
"check:tui-compiled": "bun run build:tui && git diff --exit-code -- src/tui-compiled && test -z \"$(git status --porcelain -- src/tui-compiled)\"",
"typecheck": "tsc -p ../retina-local-fs/tsconfig.build.json && tsc --noEmit && tsc -p tsconfig.scripts.json",
"test": "bun test",
"test:mc-host-client:node": "bun scripts/run-mc-host-client-node.ts adversarial",
"smoke:mc-host-client:bun": "bun scripts/smoke-mc-host-client.ts",
"smoke:mc-host-client:node": "bun scripts/run-mc-host-client-node.ts smoke",
"lint": "biome check .",
"bench:retrieval": "bun scripts/benchmark-retrieval.ts",
"bench:retrieval:check": "bun scripts/benchmark-retrieval.ts check --profile ci",
Expand All @@ -50,7 +53,6 @@
"prepublishOnly": "bun run build && bun run build:tui"
},
"dependencies": {
"@cortexkit/subc-client": "0.4.1",
"@huggingface/transformers": "^4.1.0",
"@jitl/quickjs-singlefile-cjs-release-asyncify": "0.32.0",
"@opencode-ai/plugin": "^1.17.11",
Expand Down
58 changes: 32 additions & 26 deletions packages/plugin/scripts/drive-preseed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
*/
import { homedir } from "node:os";
import { join, dirname } from "node:path";
import { existsSync, readFileSync } from "node:fs";
import { SubcClient } from "@cortexkit/subc-client";
import { readFileSync } from "node:fs";
import { SubcClient } from "../src/shared/mc-host-client";

const args = process.argv.slice(2);
const session = args[0];
Expand All @@ -25,34 +25,40 @@ const connectionFile =
connIdx >= 0
? args[connIdx + 1]
: join(homedir(), ".local", "share", "cortexkit", "ckdev-rig", "runtime", "subc-connection.json");
if (!existsSync(connectionFile)) {
console.error(`connection file missing: ${connectionFile}`);
const payloadPath = join(dirname(new URL(import.meta.url).pathname), "drive-preseed-payload.json");
let payload: { compartments: unknown[] };
try {
payload = JSON.parse(readFileSync(payloadPath, "utf8")) as { compartments: unknown[] };
} catch (error) {
console.error(`failed to read preseed payload ${payloadPath}:`, error);
process.exit(1);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const payloadPath = join(dirname(new URL(import.meta.url).pathname), "drive-preseed-payload.json");
const payload = JSON.parse(readFileSync(payloadPath, "utf8")) as {
compartments: unknown[];
};

const client = await SubcClient.connect({ connectionFile, handshakeTimeoutMs: 10_000 });
const route = await client.routeOpen(
{ kind: "tool_provider", module_id: "magic-context" },
{ project_root: process.cwd(), harness: "opencode", session },
);
const body = {
kind: "state_import",
v: 1,
session_id: session,
import_id: `drive-preseed-${Date.now()}`,
batch_seq: 0,
batch_count: 1,
compartments: payload.compartments,
};
console.log(`preseed inputs: session=${session} conn=${connectionFile} payload=${payloadPath} compartments=${payload.compartments.length}`);
const response = await client.request(route, body, { timeoutMs: 30_000 });
console.log("state_import response:", JSON.stringify(response, null, 2));
await client.closeRoute(route).catch(() => undefined);
client.close();
try {
const route = await client.routeOpen(
{ kind: "tool_provider", module_id: "magic-context" },
{ project_root: process.cwd(), harness: "opencode", session },
);
try {
const body = {
kind: "state_import",
v: 1,
session_id: session,
import_id: `drive-preseed-${Date.now()}`,
batch_seq: 0,
batch_count: 1,
compartments: payload.compartments,
};
console.log(`preseed inputs: session=${session} conn=${connectionFile} payload=${payloadPath} compartments=${payload.compartments.length}`);
const response = await client.request(route, body, { timeoutMs: 30_000 });
console.log("state_import response:", JSON.stringify(response, null, 2));
} finally {
await client.closeRoute(route).catch(() => undefined);
}
} finally {
await client.closeAsync().catch(() => undefined);
}
console.log(`
acceptance checks (run read-only, between beats):
sqlite3 -readonly ~/.local/share/cortexkit/ckdev-rig/data/cortexkit/magic-context/store.db \\
Expand Down
92 changes: 92 additions & 0 deletions packages/plugin/scripts/mc-host-client-boundary.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { describe, expect, test } from "bun:test";
import * as fs from "node:fs";
import * as path from "node:path";

/**
* Dependency-boundary gate: production packages must not depend on or import
* `@cortexkit/subc-client`. Only `PROVIDER_EXCEPTION` may import it.
*/

const NPM_CLIENT = "@cortexkit/subc-client";
const repoRoot = path.resolve(import.meta.dir, "..", "..", "..");

const PRODUCTION_PACKAGES = ["packages/plugin", "packages/cli", "packages/pi-plugin"];

const PROVIDER_EXCEPTION = "packages/e2e-tests/src/rust-runner/fake-broca.ts";

/** IMPORT_PATTERN matches import, export-from, require, and dynamic-import specifiers for NPM_CLIENT. */
const IMPORT_PATTERN =
/(?:from\s*["']@cortexkit\/subc-client["']|import\s*\(\s*["']@cortexkit\/subc-client["']\s*\)|require\s*\(\s*["']@cortexkit\/subc-client["']\s*\)|import\s*["']@cortexkit\/subc-client["'])/;

function* walkSourceFiles(dir: string): Generator<string> {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.name === "node_modules" || entry.name === "dist" || entry.name.startsWith("."))
continue;
const full = path.join(dir, entry.name);
if (entry.isDirectory()) yield* walkSourceFiles(full);
else if (/\.(ts|tsx|js|mjs|cjs)$/.test(entry.name)) yield full;
}
}

function manifestDependencies(packageDir: string): Record<string, string> {
const manifest = JSON.parse(
fs.readFileSync(path.join(repoRoot, packageDir, "package.json"), "utf-8"),
) as Record<string, Record<string, string> | undefined>;
return {
...manifest.dependencies,
...manifest.devDependencies,
...manifest.optionalDependencies,
...manifest.peerDependencies,
};
}

describe("mc-host-client dependency boundary", () => {
test("production manifests do not depend on the npm client", () => {
for (const pkg of PRODUCTION_PACKAGES) {
expect(
Object.keys(manifestDependencies(pkg)),
`${pkg}/package.json must not declare ${NPM_CLIENT}`,
).not.toContain(NPM_CLIENT);
}
});

test("production and consumer-side sources do not import the npm client", () => {
const offenders: string[] = [];
for (const pkg of [...PRODUCTION_PACKAGES, "packages/e2e-tests"]) {
const root = path.join(repoRoot, pkg);
if (!fs.existsSync(root)) continue;
for (const file of walkSourceFiles(root)) {
const relative = path.relative(repoRoot, file);
if (relative === PROVIDER_EXCEPTION) continue;
if (IMPORT_PATTERN.test(fs.readFileSync(file, "utf-8"))) offenders.push(relative);
}
}
expect(offenders, `only ${PROVIDER_EXCEPTION} may import ${NPM_CLIENT}`).toEqual([]);
});

test("the E2E provider exception still holds the one permitted import", () => {
const source = fs.readFileSync(path.join(repoRoot, PROVIDER_EXCEPTION), "utf-8");
expect(IMPORT_PATTERN.test(source)).toBe(true);
expect(Object.keys(manifestDependencies("packages/e2e-tests"))).toContain(NPM_CLIENT);
});

test("lockfile resolves the npm client only through the E2E package", () => {
const lock = fs.readFileSync(path.join(repoRoot, "bun.lock"), "utf-8");
const references = lock.split("\n").filter((line) => line.includes(NPM_CLIENT));
expect(references.length).toBeGreaterThan(0);
for (const pkg of PRODUCTION_PACKAGES) {
const manifest = JSON.parse(
fs.readFileSync(path.join(repoRoot, pkg, "package.json"), "utf-8"),
) as { name: string };
// bun.lock lists each workspace's dependencies on its workspace
// entry line, so no production package name may share a line with
// the npm client.
for (const line of references) {
expect(
line.includes(`"${manifest.name}"`),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Lockfile assertion passes vacuously due to multiline format

In bun.lock, dependency mappings and package entries reside on distinct lines. Checking line.includes("\"" + manifest.name + "\"") on individual lines containing @cortexkit/subc-client will always evaluate to false, regardless of whether a production package declared the npm client dependency. Parse the lockfile JSON or check workspace package blocks directly.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2b0c179. Confirmed the per-line check was vacuous — bun.lock puts dependency mappings and workspace names on separate lines. The test now parses the lockfile's blocks (trailing commas stripped) and asserts is the only workspace declaring the npm client, which also strengthens the positive direction.

`bun.lock ties ${NPM_CLIENT} to ${manifest.name}`,
).toBe(false);
}
}
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
Loading