From 3de6382142589c5b3be495386bb8bab412cfb40a Mon Sep 17 00:00:00 2001 From: ATou <11880502+atou42@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:28:05 +0800 Subject: [PATCH 1/2] fix(cli): inherit nearest bound Space from ancestor directories --- packages/cli/src/commands/runtime.ts | 12 ++--- packages/cli/src/runtime/launch.ts | 6 +-- packages/cli/src/runtime/space-binding.ts | 44 +++++++++++++++ packages/cli/src/space.ts | 4 +- .../cli/tests/runtime-space-binding.test.ts | 54 ++++++++++++++++++- 5 files changed, 108 insertions(+), 12 deletions(-) diff --git a/packages/cli/src/commands/runtime.ts b/packages/cli/src/commands/runtime.ts index 75dc6022e..6ef1db8ea 100644 --- a/packages/cli/src/commands/runtime.ts +++ b/packages/cli/src/commands/runtime.ts @@ -5,7 +5,7 @@ import { createClient } from "../client.js"; import { json as outJson, jsonRequested } from "../output.js"; import { currentIdentityKey } from "../space.js"; import { resolveRuntimeTarget, runtimeUp, parseRuntimeHarnesses, type RuntimeUpOptions } from "../runtime/launch.js"; -import { canonicalRuntimeRoot, getRuntimeSpaceBinding } from "../runtime/space-binding.js"; +import { canonicalRuntimeRoot, findNearestRuntimeSpaceBinding } from "../runtime/space-binding.js"; import { join } from "node:path"; import { RuntimeArchiveStore } from "../runtime/archive-store.js"; import { readNativeConfig, runtimeStateRoot, writeNativeConfig } from "../runtime/native/config.js"; @@ -30,15 +30,15 @@ type ImportStatus = NativeStatus["import"]; const megabytes = (bytes: number) => `${(bytes / 1024 / 1024).toFixed(1)} MB`; -/** The bound Space of a directory, with its running Runtime; import and attach act through it. */ +/** The bound Space of a directory (or nearest bound ancestor), with its running Runtime; import and detach act through it. */ async function boundRuntime(program: Command, dir: string | undefined, space: string | undefined) { const identity = currentIdentityKey(); if (!identity) throw new Error("Sign in first"); - const root = await canonicalRuntimeRoot(dir ?? process.cwd()); - const spaceId = await resolveRuntimeTarget(program, space); - const binding = await getRuntimeSpaceBinding(root, identity); + const targetDir = await canonicalRuntimeRoot(dir ?? process.cwd()); + const spaceId = await resolveRuntimeTarget(program, space, targetDir); + const binding = await findNearestRuntimeSpaceBinding(targetDir, identity); if (!binding || binding.spaceId !== spaceId) throw new Error("Bind this directory with runtime up first"); - return { identity, root, spaceId, directory: runtimeInstanceDirectory(identity, spaceId) }; + return { identity, root: binding.root, spaceId, directory: runtimeInstanceDirectory(identity, spaceId) }; } export function registerRuntime(program: Command) { diff --git a/packages/cli/src/runtime/launch.ts b/packages/cli/src/runtime/launch.ts index 327471a7e..10c920938 100644 --- a/packages/cli/src/runtime/launch.ts +++ b/packages/cli/src/runtime/launch.ts @@ -10,7 +10,7 @@ import type { Command } from "commander"; import { requireAccessToken } from "../auth.js"; import { createClient } from "../client.js"; import { currentIdentityKey, explicitSpace, resolveSpaceRef } from "../space.js"; -import { canonicalRuntimeRoot, getRuntimeSpaceBinding, resolveRuntimeSpace } from "./space-binding.js"; +import { canonicalRuntimeRoot, findNearestRuntimeSpaceBinding, getRuntimeSpaceBinding, resolveRuntimeSpace } from "./space-binding.js"; import { controlRuntimeInstance, requestRuntimeInstance, runtimeInstanceDirectory } from "./instance.js"; import { ensureNativeSync, repairIntegrations } from "./native/attach.js"; import { serializeDiagnosticError, type RuntimeDiagnostic } from "./diagnostics.js"; @@ -57,9 +57,9 @@ async function requestedRuntimeSpace(program: Command, target?: string): Promise return ref ? resolveSpaceRef(ref) : null; } -export async function resolveRuntimeTarget(program: Command, target?: string) { +export async function resolveRuntimeTarget(program: Command, target?: string, cwd = process.cwd()) { const spaceId = await requestedRuntimeSpace(program, target) - ?? (await getRuntimeSpaceBinding(process.cwd(), currentIdentityKey()))?.spaceId; + ?? (await findNearestRuntimeSpaceBinding(cwd, currentIdentityKey()))?.spaceId; if (!spaceId) throw new Error("No directory binding. Use --space or runtime up"); return spaceId; } diff --git a/packages/cli/src/runtime/space-binding.ts b/packages/cli/src/runtime/space-binding.ts index f97819373..4d7e4161d 100644 --- a/packages/cli/src/runtime/space-binding.ts +++ b/packages/cli/src/runtime/space-binding.ts @@ -117,6 +117,33 @@ export function findRuntimeSpaceBinding( return entries.find((binding) => binding.root === root && binding.key === key) ?? null; } +/** + * Find the nearest (deepest) bound Runtime Space containing `cwd` for `key`. + * Walks ancestor directories via `dirname` (like Git), so sibling prefixes such as + * `/work/app-2` never match `/work/app`, and nested bindings override their parent. + */ +export function findContainingRuntimeSpaceBinding( + bindings: RuntimeSpaceBinding[] | RuntimeSpaceBindingsFile, + input: { cwd: string; key: string }, +): RuntimeSpaceBinding | null { + const entries = Array.isArray(bindings) ? bindings : bindings.bindings; + const key = input.key.trim(); + const byRoot = new Map(); + for (const binding of entries) { + if (binding.key === key) byRoot.set(binding.root, binding); + } + if (byRoot.size === 0) return null; + + let current = normalizeRuntimeRoot(input.cwd); + while (true) { + const match = byRoot.get(current); + if (match) return match; + const parent = dirname(current); + if (parent === current) return null; + current = parent; + } +} + function upsertRuntimeSpaceBinding( file: RuntimeSpaceBindingsFile, binding: RuntimeSpaceBinding, @@ -300,6 +327,23 @@ export async function getRuntimeSpaceBinding( return findRuntimeSpaceBinding(file, { root: canonicalRoot, key: key.trim() }); } +export async function findNearestRuntimeSpaceBinding( + cwd: string, + key: string | null | undefined, + path = runtimeSpaceBindingsPath(), +): Promise { + if (!nonEmptyString(key)) return null; + const canonicalCwd = await canonicalRuntimeRoot(cwd); + const file = await readRuntimeSpaceBindings(path); + const trimmedKey = key.trim(); + return ( + findContainingRuntimeSpaceBinding(file, { cwd: canonicalCwd, key: trimmedKey }) + ?? (normalizeRuntimeRoot(cwd) !== canonicalCwd + ? findContainingRuntimeSpaceBinding(file, { cwd, key: trimmedKey }) + : null) + ); +} + /** * Resolve a local Runtime Space without silently creating duplicates. * The per-binding lock covers creation; the shared file is locked only for diff --git a/packages/cli/src/space.ts b/packages/cli/src/space.ts index e713302c4..bf9e78482 100644 --- a/packages/cli/src/space.ts +++ b/packages/cli/src/space.ts @@ -5,7 +5,7 @@ import { join } from "node:path"; import { COHUB_ENVIRONMENTS, HOME_SPACE_SLUG, normalizeBaseUrl, parseSpaceRef, resolveApiBaseUrl, resolveCohubEnvironment } from "@neta-art/cohub"; import { readAuthSession } from "./auth.js"; import { createClient } from "./client.js"; -import { getRuntimeSpaceBinding } from "./runtime/space-binding.js"; +import { findNearestRuntimeSpaceBinding } from "./runtime/space-binding.js"; import { error, handleHttp } from "./output.js"; const CONFIG_DIR = join(homedir(), ".config", "cohub"); @@ -184,7 +184,7 @@ export function missingSpaceError(): never { export async function resolveBoundSpace( options: { cwd?: string; bindingsPath?: string } = {}, ): Promise { - const bound = await getRuntimeSpaceBinding( + const bound = await findNearestRuntimeSpaceBinding( options.cwd ?? process.cwd(), currentIdentityKey(), options.bindingsPath, diff --git a/packages/cli/tests/runtime-space-binding.test.ts b/packages/cli/tests/runtime-space-binding.test.ts index 6a542a6cf..51f53f8d4 100644 --- a/packages/cli/tests/runtime-space-binding.test.ts +++ b/packages/cli/tests/runtime-space-binding.test.ts @@ -4,7 +4,15 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; import { afterEach, test } from "node:test"; -import { canonicalRuntimeRoot, findRuntimeSpaceBinding, parseRuntimeSpaceBindings, resolveRuntimeSpace, withRuntimeSpaceBindingsLock } from "../src/runtime/space-binding.js"; +import { + canonicalRuntimeRoot, + findContainingRuntimeSpaceBinding, + findNearestRuntimeSpaceBinding, + findRuntimeSpaceBinding, + parseRuntimeSpaceBindings, + resolveRuntimeSpace, + withRuntimeSpaceBindingsLock, +} from "../src/runtime/space-binding.js"; const roots: string[] = []; @@ -196,3 +204,47 @@ test("a corrupt binding file fails closed instead of creating another Space", as ); assert.equal(created, false); }); + +test("containing binding walks ancestor directories, prefers deepest nested binding, and ignores sibling prefixes", () => { + const bindings = parseRuntimeSpaceBindings(JSON.stringify({ + version: 1, + bindings: [ + { root: "/work/app", key: "prod:alice", spaceId: "space-root" }, + { root: "/work/app/packages/web", key: "prod:alice", spaceId: "space-web" }, + { root: "/work/app", key: "dev:alice", spaceId: "space-dev" }, + ], + })); + + assert.equal(findContainingRuntimeSpaceBinding(bindings, { cwd: "/work/app", key: "prod:alice" })?.spaceId, "space-root"); + assert.equal(findContainingRuntimeSpaceBinding(bindings, { cwd: "/work/app/packages/cli/src", key: "prod:alice" })?.spaceId, "space-root"); + assert.equal(findContainingRuntimeSpaceBinding(bindings, { cwd: "/work/app/packages/web/src/routes", key: "prod:alice" })?.spaceId, "space-web"); + assert.equal(findContainingRuntimeSpaceBinding(bindings, { cwd: "/work/app/packages/web/src", key: "dev:alice" })?.spaceId, "space-dev"); + assert.equal(findContainingRuntimeSpaceBinding(bindings, { cwd: "/work/app-2/src", key: "prod:alice" }), null); + assert.equal(findContainingRuntimeSpaceBinding(bindings, { cwd: "/work/app/packages/web", key: "prod:bob" }), null); +}); + +test("findNearestRuntimeSpaceBinding resolves subdirectories and symlinked paths against canonical bound roots", async () => { + const base = await tempRoot("cohub-runtime-ancestor-"); + const repo = join(base, "repo"); + const nested = join(repo, "packages", "cli", "src"); + const alias = join(base, "repo-link"); + const bindingsPath = join(base, "runtime-spaces.json"); + await mkdir(nested, { recursive: true }); + await symlink(repo, alias); + + await resolveRuntimeSpace({ + root: repo, + identityKey: "prod:alice", + path: bindingsPath, + explicitSpaceId: "space-repo", + }); + + const fromSubdir = await findNearestRuntimeSpaceBinding(nested, "prod:alice", bindingsPath); + const fromSymlinkSubdir = await findNearestRuntimeSpaceBinding(join(alias, "packages", "cli"), "prod:alice", bindingsPath); + const fromOutside = await findNearestRuntimeSpaceBinding(base, "prod:alice", bindingsPath); + + assert.equal(fromSubdir?.spaceId, "space-repo"); + assert.equal(fromSubdir?.root, await realpath(repo)); + assert.equal(fromSymlinkSubdir?.spaceId, "space-repo"); + assert.equal(fromOutside, null); +}); From 91305c2bb1ae0d7731977bd856252c2b846d663e Mon Sep 17 00:00:00 2001 From: markbang Date: Mon, 23 Nov 2026 07:33:15 +0000 Subject: [PATCH 2/2] fix(cli): guard runtime commands that resolve a parent binding - runtime up notes when a bound parent directory exists and the new Space is separate - import/detach refuse a Runtime or native-sync config that serves another checkout of the same Space - import rejects a file operand; recovery hints name the bound root - drop the redundant non-canonical lookup; document nearest-ancestor resolution - add changeset Cohub Session: https://cohub.live/spaces/5089f055-9dbb-4fcd-b98c-fb232353281a/sessions/b03e6e71-e62e-4589-8f98-bffbf7825137 --- .changeset/cli-subdir-space-binding.md | 5 +++++ docs/local-runtime.md | 2 ++ docs/product/en/developers/cli.md | 3 ++- docs/product/zh/developers/cli.md | 2 +- packages/cli/README.md | 3 ++- packages/cli/src/commands/runtime.ts | 17 ++++++++++++----- packages/cli/src/runtime/launch.ts | 5 +++++ packages/cli/src/runtime/native/daemon.ts | 2 +- packages/cli/src/runtime/space-binding.ts | 9 +-------- 9 files changed, 31 insertions(+), 17 deletions(-) create mode 100644 .changeset/cli-subdir-space-binding.md diff --git a/.changeset/cli-subdir-space-binding.md b/.changeset/cli-subdir-space-binding.md new file mode 100644 index 000000000..3d7b31b1f --- /dev/null +++ b/.changeset/cli-subdir-space-binding.md @@ -0,0 +1,5 @@ +--- +"@neta-art/cohub-cli": patch +--- + +Space-scoped commands and `cohub runtime status/down/logs/detach/import` now use the nearest directory bound with `cohub runtime up`, so they work from subdirectories. `runtime up` inside a bound directory says the new Space is separate from the parent's. diff --git a/docs/local-runtime.md b/docs/local-runtime.md index acac17046..2ca1eb0ed 100644 --- a/docs/local-runtime.md +++ b/docs/local-runtime.md @@ -27,6 +27,8 @@ Space after prompting for a name; later starts offer reuse as the default. `-n` now the boolean shorthand for `--new`, not `--name`. Naming uses `--name `. Even with `-n`, interactive startup shows an existing binding and recommends reuse. An explicit `--space` or `COHUB_SPACE_ID` overrides and updates the directory binding. +Other commands run in a subdirectory use the nearest bound directory, like Git; a nested +binding overrides its parent. `runtime up` itself binds exactly the directory it is given. What a Runtime runs can always call `cohub`: the Runtime puts its own CLI last on `PATH` (a `~/.cache/cohub/cli//cohub` launcher), so a `cohub` already there, such as a global install that diff --git a/docs/product/en/developers/cli.md b/docs/product/en/developers/cli.md index 344419306..d02ecd4d8 100644 --- a/docs/product/en/developers/cli.md +++ b/docs/product/en/developers/cli.md @@ -66,7 +66,8 @@ Sign in once for each custom server, or supply `COHUB_EXECUTION_TOKEN`. | `-h, --help` | Command help | Many workflows need a Space. The CLI uses `-s`, then `COHUB_SPACE_ID`, then the -Space remembered for the current directory by `cohub runtime up`. `` is a +Space remembered by `cohub runtime up` for the current directory or its nearest bound +parent directory. `` is a Space ID, a slug you own such as `home`, or `username/slug`: ```bash diff --git a/docs/product/zh/developers/cli.md b/docs/product/zh/developers/cli.md index 10bc2d5a0..18f1218bf 100644 --- a/docs/product/zh/developers/cli.md +++ b/docs/product/zh/developers/cli.md @@ -60,7 +60,7 @@ COHUB_BASE_URL=https://api.example.com cohub spaces ls | `--json` | 机器可读输出 | | `-h, --help` | 命令帮助 | -很多工作流需要 Space。CLI 依次使用 `-s`、`COHUB_SPACE_ID`,以及 `cohub runtime up` 为当前目录记住的 Space。`` 可以是 Space ID、自己 Space 的 slug(比如 `home`),或 `username/slug`: +很多工作流需要 Space。CLI 依次使用 `-s`、`COHUB_SPACE_ID`,以及 `cohub runtime up` 为当前目录或最近一级已绑定的上级目录记住的 Space。`` 可以是 Space ID、自己 Space 的 slug(比如 `home`),或 `username/slug`: ```bash cohub -s spaces get diff --git a/packages/cli/README.md b/packages/cli/README.md index 0d326b087..98b9fc9d6 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -204,7 +204,8 @@ account, and environment in `~/.config/cohub/runtime-spaces.json`. The first sta and records a local Space after prompting; later starts recommend reuse. `-n` now means `--new` (boolean); use `--name ` for naming. An explicit `--space` or `COHUB_SPACE_ID` overrides and updates the directory binding. `--yes` accepts defaults and local execution; -with explicit `--new`, it creates another Space. +with explicit `--new`, it creates another Space. Other commands run in a subdirectory use +the nearest bound directory, so a nested binding overrides its parent. `-d` runs the same supervisor in the background and returns the URL, PID and log location. Readiness requires both Harness and files. If it is still starting after 30 seconds, exit diff --git a/packages/cli/src/commands/runtime.ts b/packages/cli/src/commands/runtime.ts index 6ef1db8ea..04206fd66 100644 --- a/packages/cli/src/commands/runtime.ts +++ b/packages/cli/src/commands/runtime.ts @@ -5,7 +5,8 @@ import { createClient } from "../client.js"; import { json as outJson, jsonRequested } from "../output.js"; import { currentIdentityKey } from "../space.js"; import { resolveRuntimeTarget, runtimeUp, parseRuntimeHarnesses, type RuntimeUpOptions } from "../runtime/launch.js"; -import { canonicalRuntimeRoot, findNearestRuntimeSpaceBinding } from "../runtime/space-binding.js"; +import { findNearestRuntimeSpaceBinding } from "../runtime/space-binding.js"; +import { stat } from "node:fs/promises"; import { join } from "node:path"; import { RuntimeArchiveStore } from "../runtime/archive-store.js"; import { readNativeConfig, runtimeStateRoot, writeNativeConfig } from "../runtime/native/config.js"; @@ -34,11 +35,16 @@ const megabytes = (bytes: number) => `${(bytes / 1024 / 1024).toFixed(1)} MB`; async function boundRuntime(program: Command, dir: string | undefined, space: string | undefined) { const identity = currentIdentityKey(); if (!identity) throw new Error("Sign in first"); - const targetDir = await canonicalRuntimeRoot(dir ?? process.cwd()); + const targetDir = dir ?? process.cwd(); + if (dir !== undefined && !(await stat(dir)).isDirectory()) throw new Error("Workspace is not a directory"); const spaceId = await resolveRuntimeTarget(program, space, targetDir); const binding = await findNearestRuntimeSpaceBinding(targetDir, identity); if (!binding || binding.spaceId !== spaceId) throw new Error("Bind this directory with runtime up first"); - return { identity, root: binding.root, spaceId, directory: runtimeInstanceDirectory(identity, spaceId) }; + const directory = runtimeInstanceDirectory(identity, spaceId); + // Several checkouts can be bound to one Space, but its running Runtime serves a single root. + const running = await requestRuntimeInstance(directory); + if (running && running.root !== binding.root) throw new Error(`This Space's Runtime serves ${running.root}; run this command there`); + return { identity, root: binding.root, spaceId, directory }; } export function registerRuntime(program: Command) { @@ -89,9 +95,10 @@ export function registerRuntime(program: Command) { .option("--json", "JSON output") .action(async (options: TargetOptions & { harness: string[] }) => { try { - const { identity, spaceId, directory } = await boundRuntime(program, undefined, options.space); + const { identity, root, spaceId, directory } = await boundRuntime(program, undefined, options.space); const stateRoot = runtimeStateRoot(spaceId); const config = await readNativeConfig(stateRoot, identity); + if (config && config.root !== root) throw new Error(`Native sync for this Space was set up in ${config.root}; run this command there`); const paused = options.harness.length ? parseRuntimeHarnesses(options.harness) : config?.harnesses ?? [...LOCAL_HARNESSES]; const harnesses = (config?.harnesses ?? []).filter((harness) => !paused.includes(harness)); if (config) await writeNativeConfig(stateRoot, { ...config, harnesses, codexShared: harnesses.includes("codex") && config.codexShared }); @@ -128,7 +135,7 @@ export function registerRuntime(program: Command) { const filter = { harnesses: options.harness.length ? parseRuntimeHarnesses(options.harness) : [], ...(options.session ? { nativeSessionId: options.session } : {}) }; const control = async (command: string, timeoutMs = 60_000) => { const response = await controlRuntimeInstance(directory, "import", { ...filter, command, concurrency }, timeoutMs); - if (!response) throw new Error("Local Runtime is not running; start it with cohub runtime up"); + if (!response) throw new Error(`Local Runtime is not running; start it with cohub runtime up in ${root}`); return response.result as T; }; const plan = await control("plan"); diff --git a/packages/cli/src/runtime/launch.ts b/packages/cli/src/runtime/launch.ts index 10c920938..acd1115dd 100644 --- a/packages/cli/src/runtime/launch.ts +++ b/packages/cli/src/runtime/launch.ts @@ -148,6 +148,11 @@ export async function runtimeUp(program: Command, dir: string | undefined, optio if (!options.harness.length) harnesses = await installedHarnesses(root, executables); let createNew = Boolean(options.new); let name = resolveLocalSpaceName(root, options.name); + // Other commands here already resolve to the ancestor's Space, so creating a separate one must not be silent. + const ancestor = requested || binding || createNew ? null : await findNearestRuntimeSpaceBinding(root, identity); + if (ancestor) { + process.stderr.write(`\nParent directory ${ancestor.root} is linked to\n ${runtimeWebUrl(ancestor.spaceId)}\nThis directory gets its own Space. To use that one, run \`cohub runtime up\` from the parent directory instead.\n`); + } if (!options.yes) { if (!process.stdin.isTTY) throw new Error("Use --yes to authorize local execution"); const rl = createInterface({ input: process.stdin, output: process.stderr }); diff --git a/packages/cli/src/runtime/native/daemon.ts b/packages/cli/src/runtime/native/daemon.ts index 671068443..8b3761dbc 100644 --- a/packages/cli/src/runtime/native/daemon.ts +++ b/packages/cli/src/runtime/native/daemon.ts @@ -184,7 +184,7 @@ export class NativeRuntime { async control(action: string, message: Record): Promise { if (action === "reload") return await this.reload(); if (action !== "import") throw new Error("Unknown Runtime control request"); - if (!this.synced.length) throw new Error("Native sync is not enabled for this directory; run cohub runtime up"); + if (!this.synced.length) throw new Error(`Native sync is not enabled for ${this.options.root}; run cohub runtime up there`); const filter: ImportFilter = { ...(Array.isArray(message.harnesses) && message.harnesses.length ? { harnesses: message.harnesses as Harness[] } : {}), ...(typeof message.nativeSessionId === "string" && message.nativeSessionId ? { nativeSessionId: message.nativeSessionId } : {}), diff --git a/packages/cli/src/runtime/space-binding.ts b/packages/cli/src/runtime/space-binding.ts index 4d7e4161d..34dee0b2a 100644 --- a/packages/cli/src/runtime/space-binding.ts +++ b/packages/cli/src/runtime/space-binding.ts @@ -132,7 +132,6 @@ export function findContainingRuntimeSpaceBinding( for (const binding of entries) { if (binding.key === key) byRoot.set(binding.root, binding); } - if (byRoot.size === 0) return null; let current = normalizeRuntimeRoot(input.cwd); while (true) { @@ -335,13 +334,7 @@ export async function findNearestRuntimeSpaceBinding( if (!nonEmptyString(key)) return null; const canonicalCwd = await canonicalRuntimeRoot(cwd); const file = await readRuntimeSpaceBindings(path); - const trimmedKey = key.trim(); - return ( - findContainingRuntimeSpaceBinding(file, { cwd: canonicalCwd, key: trimmedKey }) - ?? (normalizeRuntimeRoot(cwd) !== canonicalCwd - ? findContainingRuntimeSpaceBinding(file, { cwd, key: trimmedKey }) - : null) - ); + return findContainingRuntimeSpaceBinding(file, { cwd: canonicalCwd, key }); } /**