Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions docs/dev/GUY_ISSUE_ACCEPTANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ credentials. No provider, transport, tool, or SDK method was mocked.
The model executed a real bash command (`sleep 3; printf 'TOOL_OK\n'`).

```sh
JCODE_SDK_TEST_MODEL=gpt-6-astra \
node sdk/typescript/test/live-text-framing.mjs ./target/selfdev/jcode
KCODE_SDK_TEST_MODEL=gpt-6-astra \
node sdk/typescript/test/live-text-framing.mjs ./target/selfdev/kcode
```

The test is opt-in because it requires credentials and consumes provider quota.
Expand Down
25 changes: 15 additions & 10 deletions scripts/test_sdk_e2e.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,26 @@ repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"

sdk_dir="$repo_root/sdk/typescript"
socket="${TMPDIR:-/tmp}/jcode-sdk-e2e-$$.sock"
log="${TMPDIR:-/tmp}/jcode-sdk-e2e-$$.log"
# Every path the SDK is handed goes through `assertKcodePath`, which rejects any
# segment matching /^jcode[.-].*|\.jcode.*$/i. A `jcode-sdk-e2e-` prefix made
# `KCODE_API_SOCKET` throw `cross_product_path` before the bridge ever started.
socket="${TMPDIR:-/tmp}/kcode-sdk-e2e-$$.sock"
log="${TMPDIR:-/tmp}/kcode-sdk-e2e-$$.log"

echo "== building SDK =="
npm --prefix "$sdk_dir" install --no-audit --no-fund --silent
npm --prefix "$sdk_dir" run build --silent

# The full binary, for the `launch()` checks: those start a real instance via
# `jcode api-bridge`, which only the shipped binary provides.
echo "== building jcode =="
cargo build --profile selfdev -p jcode --bin jcode
jcode_bin="$repo_root/target/selfdev/jcode"
# `kcode api-bridge`, which only the shipped binary provides. The package and
# the bin target were both renamed to `kcode` in the rebrand; `--bin jcode` no
# longer resolves, so this script could not build at all.
echo "== building kcode =="
cargo build --profile selfdev -p kcode --bin kcode
kcode_bin="$repo_root/target/selfdev/kcode"

echo "== building bridge =="
# The standalone bridge binary, not `jcode api-bridge`, because the full jcode
# The standalone bridge binary, not `kcode api-bridge`, because the full kcode
# binary takes minutes to link and this script must stay fast enough to run
# per-change. The subcommand is a thin wrapper over the same `run_bridge`, and
# `api_bridge_socket_flags_do_not_collide` covers the wiring it adds.
Expand Down Expand Up @@ -70,13 +75,13 @@ KCODE_API_SOCKET="$socket" node "$sdk_dir/test/live-capabilities.mjs"
# isolation they check is a property of a *separate* instance, and running
# them against the shared bridge would prove nothing.
echo "== launching a private instance =="
node "$sdk_dir/test/live-launch.mjs" "$jcode_bin"
node "$sdk_dir/test/live-launch.mjs" "$kcode_bin"

echo "== checking instance isolation and path safety =="
node "$sdk_dir/test/live-isolation.mjs" "$jcode_bin"
node "$sdk_dir/test/live-isolation.mjs" "$kcode_bin"

echo "== checking every documented launch option =="
node "$sdk_dir/test/live-options.mjs" "$jcode_bin"
node "$sdk_dir/test/live-options.mjs" "$kcode_bin"

echo "== bridge log =="
cat "$log"
Expand Down
2 changes: 1 addition & 1 deletion sdk/typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ To verify message framing and concurrent history reads against a real provider
in a private instance, run the opt-in acceptance check from the repository root:

```sh
KCODE_SDK_TEST_MODEL="your-model-id" node sdk/typescript/test/live-text-framing.mjs ./target/selfdev/jcode
KCODE_SDK_TEST_MODEL="your-model-id" node sdk/typescript/test/live-text-framing.mjs ./target/selfdev/kcode
```

This uses your existing provider login and quota, runs one harmless bash tool,
Expand Down
4 changes: 2 additions & 2 deletions sdk/typescript/test/launch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ test("platform runtime packages map to npm platform conventions", async () => {
*/
test("removing an instance home never follows links to real credentials", async () => {
const instance = fs.mkdtempSync(path.join(os.tmpdir(), "kcode-sdk-instance-"));
const precious = fs.mkdtempSync(path.join(os.tmpdir(), "jcode-precious-test-"));
const precious = fs.mkdtempSync(path.join(os.tmpdir(), "kcode-precious-test-"));
fs.mkdirSync(precious, { recursive: true });
fs.writeFileSync(path.join(precious, "auth.json"), '{"token":"keep me"}');

Expand Down Expand Up @@ -62,7 +62,7 @@ test("cleanup refuses arbitrary directories even when asked directly", async ()
});

test("daemon shutdown lookup waits for a delayed registry entry", async () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "jcode-daemon-race-test-"));
const home = fs.mkdtempSync(path.join(os.tmpdir(), "kcode-daemon-race-test-"));
const runtimeDir = path.join(home, "run");
fs.mkdirSync(runtimeDir);
const { waitForDaemonPidForTest } = await import("../dist/launch.js");
Expand Down
146 changes: 146 additions & 0 deletions sdk/typescript/test/live-fixtures.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/**
* The live smoke scripts are the SDK's only coverage of real `launch()`
* behaviour: they start an actual instance, drive a turn, and check isolation,
* credentials, and every documented option. `npm run check` cannot run them,
* because they need a built binary and a provider login.
*
* That gap is how they survived the kcode rebrand still shipping a bare
* `"jcode"` binary default. `assertKcodePath` rejects that on sight, so
* `node test/live-options.mjs` threw `cross_product_path` before it checked a
* single documented option — and the child-daemon knobs were still spelled
* `JCODE_NO_TELEMETRY` and friends, which the daemon no longer reads, so the
* instances under test quietly ran with telemetry and memory enabled.
*
* These assertions run the guard against the values the scripts actually ship,
* so the next rename fails here instead of in someone's terminal.
*/
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { assertKcodePath } from "../dist/product.js";

const here = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(here, "../../..");

const liveScripts = fs
.readdirSync(here)
.filter((name) => name.startsWith("live-") && name.endsWith(".mjs"))
.sort();

/** `process.argv[2] ?? "kcode"`, and the `path.resolve(...)` form around it. */
const DEFAULT_BINARY = /process\.argv\[2\]\s*\?\?\s*"([^"]+)"/u;
const TEST_BINARY_ENV = /\bKCODE_SDK_TEST_BINARY\b/u;

function read(name: string): string {
return fs.readFileSync(path.join(here, name), "utf8");
}

function defaultBinaryOf(source: string): string | undefined {
return DEFAULT_BINARY.exec(source)?.[1];
}

/** Strip shell comments so prose explaining the old name is not read as code. */
function codeLines(script: string): string {
return script
.split("\n")
.filter((line) => !line.trimStart().startsWith("#"))
.join("\n");
}

/**
* `assertKcodePath` resolves against the cwd and then walks up to the nearest
* existing ancestor, so its verdict also depends on the directory the repo was
* cloned into. Resolve from a scratch directory so these assertions are about
* the value a script ships rather than about where someone cloned the repo.
*/
function assertGuardAccepts(label: string, candidate: string): void {
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "kcode-guard-probe-"));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: When os.tmpdir() is under .jcode or jcode, the scratch cwd makes valid relative candidates fail the guard, causing these tests to fail spuriously.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Possible bug

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** sdk/typescript/test/live-fixtures.test.ts
**Line:** 60:60
**Comment:**
	*Possible Bug: When `os.tmpdir()` is under `.jcode` or `jcode`, the scratch cwd makes valid relative candidates fail the guard, causing these tests to fail spuriously.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

const original = process.cwd();
try {
process.chdir(scratch);
assert.doesNotThrow(
() => assertKcodePath(candidate),
`${label} hands assertKcodePath "${candidate}", which it rejects as a cross-product path`,
);
} finally {
process.chdir(original);
fs.rmSync(scratch, { recursive: true, force: true });
}
}

test("the live smoke scripts are all discovered", () => {
// Guards the filter itself: an empty or near-empty list would make every
// assertion below vacuously true, which is how a rename could pass again.
assert.ok(
liveScripts.length >= 8,
`expected the full live-* cohort, found only ${liveScripts.length}: ${liveScripts.join(", ")}`,
);
});

test("exactly one live script takes its binary from the environment", () => {
// live-tools.mjs is opt-in and insists on an absolute path; the rest either
// default to a bare name or connect to a bridge test_sdk_e2e.sh started for
// them. Pinning the count keeps a new env-driven script from appearing with
// nobody checking the knob it reads.
assert.deepEqual(liveScripts.filter((name) => TEST_BINARY_ENV.test(read(name))), ["live-tools.mjs"]);
});

for (const name of liveScripts) {
test(`${name} ships a default binary the guard accepts`, () => {
const source = read(name);
const fallback = defaultBinaryOf(source);
// A script with no argv default is driven by test_sdk_e2e.sh against a
// bridge it already started (live-turn, live-control, live-capabilities)
// and never names a binary, so there is no default left to get wrong.
if (fallback !== undefined) assertGuardAccepts(name, fallback);
});

test(`${name} reads and sets only KCODE_-prefixed knobs`, () => {
const legacy = [...read(name).matchAll(/\bJCODE_[A-Z_]+\b/gu)].map((m) => m[0]);
assert.deepEqual(
[...new Set(legacy)].sort(),
[],
`${name} still uses pre-rebrand env knobs the daemon no longer reads`,
);
});

test(`${name} creates its scratch directories under a kcode prefix`, () => {
// Only the ones that are actually handed to the SDK: a temp dir becomes an
// instance home or a working directory, both of which go through the guard.
for (const prefix of [...read(name).matchAll(/mkdtemp(?:Sync)?\(\s*path\.join\([^,]+,\s*"([^"]+)"/gu)].map((m) => m[1])) {
assertGuardAccepts(`${name} temp prefix`, prefix);
}
});
}

test("the e2e driver builds the kcode binary, not the pre-rebrand name", () => {
const driver = codeLines(fs.readFileSync(path.join(repoRoot, "scripts/test_sdk_e2e.sh"), "utf8"));
assert.match(driver, /cargo build --profile selfdev -p kcode --bin kcode\b/u);
assert.doesNotMatch(driver, /--bin jcode(?![\w-])/u, "the jcode bin target no longer exists in this fork");
});

test("the e2e driver's socket path is one the guard accepts", () => {
const driver = fs.readFileSync(path.join(repoRoot, "scripts/test_sdk_e2e.sh"), "utf8");
const socket = /socket="\$\{TMPDIR:-\/tmp\}\/([^"$]*)/u.exec(driver)?.[1];
assert.ok(socket, "could not read the socket template out of test_sdk_e2e.sh");
assertGuardAccepts("test_sdk_e2e.sh socket", socket);
});

test("the documented opt-in commands name a binary this fork builds", () => {
const docs = [
path.join(repoRoot, "sdk/typescript/README.md"),
path.join(repoRoot, "docs/dev/GUY_ISSUE_ACCEPTANCE.md"),
];
for (const doc of docs) {
const source = fs.readFileSync(doc, "utf8");
const stale = [...source.matchAll(/live-[a-z-]+\.mjs\s+\.\/target\/selfdev\/jcode\b/gu)];
assert.deepEqual(
stale.map((m) => m[0]),
[],
`${path.relative(repoRoot, doc)} still tells a reader to run a jcode binary that no longer exists`,
);
}
});
7 changes: 5 additions & 2 deletions sdk/typescript/test/live-isolation.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* instance returned the real transcripts of the jcode the user runs
* interactively.
*
* Usage: node test/live-isolation.mjs [path-to-jcode-binary]
* Usage: node test/live-isolation.mjs [path-to-kcode-binary]
*/

import assert from "node:assert/strict";
Expand All @@ -16,7 +16,10 @@ import os from "node:os";
import path from "node:path";
import { JcodeClient, userJcodeHome } from "../dist/index.js";

const binary = process.argv[2] ?? "jcode";
// The default must be a name `assertKcodePath` accepts: a bare `jcode` resolves
// to a path segment the guard rejects, so the script would throw
// `cross_product_path` before it checked a single property.
const binary = process.argv[2] ?? "kcode";
const failures = [];
async function step(name, fn) {
try {
Expand Down
11 changes: 7 additions & 4 deletions sdk/typescript/test/live-launch.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,18 @@
* cannot see the user's sessions, it inherits credentials well enough to reach
* a model, and it leaves nothing behind.
*
* Usage: node test/live-launch.mjs [path-to-jcode-binary]
* Usage: node test/live-launch.mjs [path-to-kcode-binary]
*/

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { JcodeClient, userJcodeHome } from "../dist/index.js";

const binary = process.argv[2] ?? "jcode";
// The default must be a name `assertKcodePath` accepts: a bare `jcode` resolves
// to a path segment the guard rejects, so the script would throw
// `cross_product_path` before it checked a single property.
const binary = process.argv[2] ?? "kcode";
const failures = [];
async function step(name, fn) {
try {
Expand Down Expand Up @@ -62,8 +65,8 @@ await step("the instance can reach a model", async () => {
// CI and developer machines often retain a stale default provider alongside
// another valid login. Let the validation choose a known-good route so this
// tests inherited credentials rather than unrelated historical selection.
if (process.env.JCODE_SDK_TEST_MODEL) {
await client.setModel(session.session_id, process.env.JCODE_SDK_TEST_MODEL);
if (process.env.KCODE_SDK_TEST_MODEL) {
await client.setModel(session.session_id, process.env.KCODE_SDK_TEST_MODEL);
}
const turn = await client.run(session.session_id, "Reply with exactly: ISOLATED", {
autoApprove: true,
Expand Down
13 changes: 8 additions & 5 deletions sdk/typescript/test/live-options.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,21 @@
* with nothing behind it. Neither shows up in a suite that only ever launches
* a fresh instance.
*
* Usage: node test/live-options.mjs [path-to-jcode-binary]
* Usage: node test/live-options.mjs [path-to-kcode-binary]
*/

import { JcodeClient } from "../dist/index.js";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

const binary = process.argv[2] ?? "jcode";
// The default must be a name `assertKcodePath` accepts: a bare `jcode` resolves
// to a path segment the guard rejects, so the script would throw
// `cross_product_path` before it documented a single option.
const binary = process.argv[2] ?? "kcode";
// A binary that ignores its arguments and never opens a socket, for the
// startup-timeout check.
const slowBinary = path.join(os.tmpdir(), `jcode-slow-${process.pid}.sh`);
const slowBinary = path.join(os.tmpdir(), `kcode-slow-${process.pid}.sh`);
fs.writeFileSync(slowBinary, "#!/usr/bin/env bash\nsleep 60\n", { mode: 0o755 });
process.once("exit", () => fs.rmSync(slowBinary, { force: true }));

Expand All @@ -35,7 +38,7 @@ const step = async (name, fn) => {

// Every option the README documents should do what it says.
await step("jcodeHome keeps state at a fixed path across runs", async () => {
const home = path.join(os.tmpdir(), "jcode-sdk-option-home");
const home = path.join(os.tmpdir(), "kcode-sdk-option-home");
fs.rmSync(home, { recursive: true, force: true });
const a = await JcodeClient.launch({ binary, jcodeHome: home, workingDir: process.cwd() });
const s = await a.createSession(process.cwd());
Expand Down Expand Up @@ -69,7 +72,7 @@ await step("env reaches the instance", async () => {
const c = await JcodeClient.launch({
binary,
workingDir: process.cwd(),
env: { JCODE_NO_TELEMETRY: "1" },
env: { KCODE_NO_TELEMETRY: "1" },
});
await c.close();
});
Expand Down
28 changes: 17 additions & 11 deletions sdk/typescript/test/live-text-framing.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,34 @@
* Opt-in acceptance check using the real SDK, private daemon, bridge, provider,
* and bash tool. Requires a working provider login. No mocks or shared daemon.
*
* Usage: node sdk/typescript/test/live-text-framing.mjs ./target/selfdev/jcode
* Optional: JCODE_SDK_TEST_MODEL (defaults to the daemon's chosen route).
* Usage: node sdk/typescript/test/live-text-framing.mjs ./target/selfdev/kcode
* Optional: KCODE_SDK_TEST_MODEL (defaults to the daemon's chosen route).
*/
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { JcodeClient } from "../dist/index.js";

const binary = path.resolve(process.argv[2] ?? "target/selfdev/jcode");
const workingDir = fs.mkdtempSync(path.join(process.env.JCODE_SCRATCH_DIR ?? os.tmpdir(), "guy-live-"));
// `target/selfdev/kcode` is the binary cargo actually produces; the pre-rebrand
// `jcode` spelling both pointed at a file that does not exist and named a path
// segment `assertKcodePath` rejects outright.
const binary = path.resolve(process.argv[2] ?? "target/selfdev/kcode");
const workingDir = fs.mkdtempSync(path.join(process.env.KCODE_SCRATCH_DIR ?? os.tmpdir(), "kcode-guy-live-"));
const client = await JcodeClient.launch({
binary,
workingDir,
startupTimeoutMs: 60_000,
inheritStderr: true,
wakeMode: "external",
env: {
JCODE_NO_TELEMETRY: "1",
JCODE_MEMORY_ENABLED: "0",
JCODE_MEMORY_SIDECAR_ENABLED: "0",
JCODE_ACTIVE_PROVIDER: "",
// The daemon reads KCODE_-prefixed knobs; the pre-rebrand JCODE_ spellings
// were inert, so this instance quietly ran with telemetry, memory, and the
// caller's selected provider still enabled.
KCODE_NO_TELEMETRY: "1",
KCODE_MEMORY_ENABLED: "0",
KCODE_MEMORY_SIDECAR_ENABLED: "0",
KCODE_ACTIVE_PROVIDER: "",
},
});
const home = client.instanceHome;
Expand All @@ -37,10 +43,10 @@ try {
assert.ok(client.capabilities.includes("text_framing"), "new bridge must advertise text framing");
assert.equal((await client.listSessions()).length, 0, "instance must be isolated");
const session = await client.createSession(workingDir);
if (process.env.JCODE_SDK_TEST_MODEL) {
await client.setModel(session.session_id, process.env.JCODE_SDK_TEST_MODEL);
if (process.env.KCODE_SDK_TEST_MODEL) {
await client.setModel(session.session_id, process.env.KCODE_SDK_TEST_MODEL);
}
console.log(`Session created, model ${process.env.JCODE_SDK_TEST_MODEL ?? "default"}`);
console.log(`Session created, model ${process.env.KCODE_SDK_TEST_MODEL ?? "default"}`);
const probes = [];
const metrics = [];
let terminalAt;
Expand Down
Loading
Loading