Skip to content
Open
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
12 changes: 6 additions & 6 deletions packages/cli/src/commands/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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) {
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/runtime/launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 <space> or runtime up");
return spaceId;
}
Expand Down
44 changes: 44 additions & 0 deletions packages/cli/src/runtime/space-binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, RuntimeSpaceBinding>();
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,
Expand Down Expand Up @@ -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<RuntimeSpaceBinding | null> {
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
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/space.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -184,7 +184,7 @@ export function missingSpaceError(): never {
export async function resolveBoundSpace(
options: { cwd?: string; bindingsPath?: string } = {},
): Promise<string | null> {
const bound = await getRuntimeSpaceBinding(
const bound = await findNearestRuntimeSpaceBinding(
options.cwd ?? process.cwd(),
currentIdentityKey(),
options.bindingsPath,
Expand Down
54 changes: 53 additions & 1 deletion packages/cli/tests/runtime-space-binding.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[] = [];

Expand Down Expand Up @@ -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);
});
Loading