Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): CLI-wide walk-up to enclosing .ok/config.yml when run in a subdirectory (#1730)
mike-inkeep22f0bb86b0a6
diff --git a/.changeset/cli-walk-up-project-root.md b/.changeset/cli-walk-up-project-root.mdnew file mode 100644index 000000000..f7aade361--- /dev/null+++ b/.changeset/cli-walk-up-project-root.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++Lifecycle commands (`ok start`, `stop`, `status`, `clean`, `ui`, `mcp`, `preview`, and bare `ok`) now work from any subdirectory of an initialized project. The CLI walks up to the nearest enclosing `.ok/config.yml` — the same resolution the MCP server uses, so both always agree on which project (and which `server.lock`) a directory belongs to — and boots with that root's config instead of failing with "This directory isn't set up yet." When the resolved root differs from your current directory, the CLI prints `[ok] Using Open Knowledge project at <root>` so the project scope is always visible. Nested projects compose: the walk stops at the closest ancestor, so a subtree you've separately run `ok init` in keeps its own root. Directories with no enclosing project still get the "run `ok init` first" message, and scaffolding commands (`ok init`, `seed`, `clone`) keep their existing current-directory semantics.diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.tsindex 4bddee662..a791efd4a 100644--- a/packages/cli/src/cli.ts+++ b/packages/cli/src/cli.ts@@ -46,6 +46,7 @@ import { syncCommand } from './commands/sync.ts';import { uiCommand } from './commands/ui.ts';import { PACKAGE_VERSION } from './constants.ts';import { loadConfig } from './index.ts';+import { recordInvocationCwd, resolveProjectAnchor } from './project-anchor.ts';import { buildVersionNotice } from './version-notice.ts';const program = new Command();@@ -87,7 +88,15 @@ programprocess.env.OK_CONSOLE_LEVEL = level;}- const { config } = loadConfig(cwd);+ const subcommandName = thisCommand.args?.[0];+ const anchorRoot = resolveProjectAnchor(subcommandName, process.cwd());+ if (anchorRoot !== null) {+ recordInvocationCwd(process.cwd());+ process.chdir(anchorRoot);+ console.error(`[ok] Using Open Knowledge project at ${anchorRoot}`);+ }++ const { config } = loadConfig(anchorRoot ?? cwd);resolvedConfig = config;const commandName = thisCommand.args?.[0] ?? thisCommand.name() ?? 'cli';diff --git a/packages/cli/src/commands/stop.ts b/packages/cli/src/commands/stop.tsindex 88114c13e..2ac594493 100644--- a/packages/cli/src/commands/stop.ts+++ b/packages/cli/src/commands/stop.ts@@ -1,5 +1,7 @@+import { resolve } from 'node:path';import { type Config, isProcessAlive, resolveLockDir } from '@inkeep/open-knowledge-server';import { Command } from 'commander';+import { getInvocationCwd } from '../project-anchor.ts';import { discoverLockDirs } from '../utils/process-scan.ts';import { inspectLock, type LockState } from './lock-state.ts';import { runPs } from './ps.ts';@@ -187,7 +189,7 @@ export function stopCommand(getConfig: () => Config): Command {return;}- const lockDir = resolveLockDir(target);+ const lockDir = resolveLockDir(resolve(getInvocationCwd(), target));executeStop(lockDir);});}diff --git a/packages/cli/src/project-anchor.test.ts b/packages/cli/src/project-anchor.test.tsnew file mode 100644index 000000000..f79b19bd6--- /dev/null+++ b/packages/cli/src/project-anchor.test.ts@@ -0,0 +1,241 @@+import { afterAll, afterEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { hostname, tmpdir } from 'node:os';+import { join } from 'node:path';+import { getInvocationCwd, recordInvocationCwd, resolveProjectAnchor } from './project-anchor.ts';++const CLI_PACKAGE_ROOT = import.meta.dir.replace(/\/src$/, '');++const cleanups: string[] = [];+afterAll(() => {+ for (const dir of cleanups) {+ rmSync(dir, { recursive: true, force: true });+ }+});++function makeFixture(): string {+ const dir = mkdtempSync(join(tmpdir(), 'ok-anchor-'));+ cleanups.push(dir);+ return dir;+}++function makeProjectRoot(dir: string, configYaml = ''): void {+ mkdirSync(join(dir, '.ok'), { recursive: true });+ writeFileSync(join(dir, '.ok', 'config.yml'), configYaml);+}++describe('resolveProjectAnchor — command gating', () => {+ const stubHit = () => ({ rootPath: '/proj', distance: 2 });++ test.each([+ 'start',+ 'stop',+ 'status',+ 'clean',+ 'ui',+ 'mcp',+ 'preview',+ ])('anchors lifecycle command %s', (name) => {+ expect(resolveProjectAnchor(name, '/proj/sub/dir', stubHit)).toBe('/proj');+ });++ test('anchors the bare-`ok` dispatch (undefined command name)', () => {+ expect(resolveProjectAnchor(undefined, '/proj/sub/dir', stubHit)).toBe('/proj');+ });++ test.each([+ 'init',+ 'seed',+ 'clone',+ 'open',+ 'ps',+ 'auth',+ 'config',+ 'diagnose',+ ])('keeps literal-cwd semantics for %s without probing the filesystem', (name) => {+ let called = false;+ const probe = () => {+ called = true;+ return stubHit();+ };+ expect(resolveProjectAnchor(name, '/proj/sub/dir', probe)).toBeNull();+ expect(called).toBe(false);+ });++ test('returns null when cwd is itself the project root (distance 0)', () => {+ expect(+ resolveProjectAnchor('start', '/proj', () => ({ rootPath: '/proj', distance: 0 })),+ ).toBeNull();+ });++ test('returns null when no enclosing project exists', () => {+ expect(resolveProjectAnchor('start', '/nowhere', () => null)).toBeNull();+ });+});++describe('invocation cwd', () => {+ afterEach(() => recordInvocationCwd(null));++ test('defaults to process.cwd() before any anchoring', () => {+ expect(getInvocationCwd()).toBe(process.cwd());+ });++ test('returns the recorded pre-anchor directory after recordInvocationCwd', () => {+ recordInvocationCwd('/proj/sub');+ expect(getInvocationCwd()).toBe('/proj/sub');+ });+});++describe('resolveProjectAnchor — real filesystem walk', () => {+ test('resolves the nearest enclosing project root from a subdirectory', () => {+ const root = makeFixture();+ makeProjectRoot(root);+ const sub = join(root, 'a', 'b');+ mkdirSync(sub, { recursive: true });++ expect(resolveProjectAnchor('start', sub)).toBe(root);+ });++ test('closest-ancestor-wins: a nested project stops the walk', () => {+ const outer = makeFixture();+ makeProjectRoot(outer);+ const inner = join(outer, 'a');+ makeProjectRoot(inner);+ const sub = join(inner, 'b');+ mkdirSync(sub, { recursive: true });++ expect(resolveProjectAnchor('start', sub)).toBe(inner);+ });++ test('a bare .ok/ directory without config.yml is not a project root', () => {+ const root = makeFixture();+ makeProjectRoot(root);+ const sub = join(root, 'a');+ mkdirSync(join(sub, '.ok'), { recursive: true });+ const deeper = join(sub, 'b');+ mkdirSync(deeper, { recursive: true });++ expect(resolveProjectAnchor('start', deeper)).toBe(root);+ });++ test('returns null when no ancestor is a project root', () => {+ const dir = makeFixture();+ const sub = join(dir, 'a', 'b');+ mkdirSync(sub, { recursive: true });++ expect(resolveProjectAnchor('start', sub)).toBeNull();+ });+});++function spawnCli(args: string[]): { exitCode: number | null; stdout: string; stderr: string } {+ const result = Bun.spawnSync({+ cmd: [+ 'bun',+ '--conditions=development',+ '-e',+ `+ process.argv = [process.execPath, process.cwd() + '/src/cli.ts', ...${JSON.stringify(args)}];+ await import('./src/cli.ts');+ `,+ ],+ cwd: CLI_PACKAGE_ROOT,+ env: { ...process.env, NO_COLOR: '1', OK_BUNDLE_PROXY: '0' },+ stdin: 'ignore',+ timeout: 25_000,+ });+ return {+ exitCode: result.exitCode,+ stdout: result.stdout.toString(),+ stderr: result.stderr.toString(),+ };+}++describe('CLI preAction project anchoring (cold spawn)', () => {+ test('`ok status` from a subdirectory anchors to the root and prints the disclosure line', () => {+ const root = makeFixture();+ makeProjectRoot(root);+ const sub = join(root, 'notes', 'daily');+ mkdirSync(sub, { recursive: true });++ const { exitCode, stdout, stderr } = spawnCli(['--cwd', sub, 'status', '--json']);++ expect(exitCode).toBe(0);+ expect(stderr).toContain(`[ok] Using Open Knowledge project at ${realpathSync(root)}`);+ const report = JSON.parse(stdout);+ expect(report).toHaveProperty('server');+ }, 30_000);++ test('`ok preview` from a subdirectory loads the ROOT config, not defaults', () => {+ const root = makeFixture();+ makeProjectRoot(root, 'content:\n dir: docs\n');+ mkdirSync(join(root, 'docs'), { recursive: true });+ writeFileSync(join(root, 'docs', 'hello.md'), '# hello\n');+ const sub = join(root, 'unrelated', 'deep');+ mkdirSync(sub, { recursive: true });++ const { exitCode, stdout, stderr } = spawnCli(['--cwd', sub, 'preview']);++ expect(exitCode).toBe(0);+ expect(stderr).toContain(`[ok] Using Open Knowledge project at ${realpathSync(root)}`);+ expect(stdout).toContain('hello.md');+ }, 30_000);++ test('no disclosure line when cwd is already the project root', () => {+ const root = makeFixture();+ makeProjectRoot(root);++ const { exitCode, stderr } = spawnCli(['--cwd', root, 'status', '--json']);++ expect(exitCode).toBe(0);+ expect(stderr).not.toContain('Using Open Knowledge project at');+ }, 30_000);++ test('`ok stop <relative-dir>` resolves the target against the invocation cwd, not the anchored root', () => {+ const root = makeFixture();+ makeProjectRoot(root);+ const sub = join(root, 'sub');+ const targetDir = join(sub, 'target');+ mkdirSync(join(targetDir, '.ok', 'local'), { recursive: true });++ const sleeper = Bun.spawn(['sleep', '60']);+ try {+ writeFileSync(+ join(targetDir, '.ok', 'local', 'server.lock'),+ JSON.stringify({ pid: sleeper.pid, port: 4242, hostname: hostname() }),+ );++ const { exitCode, stdout, stderr } = spawnCli(['--cwd', sub, 'stop', './target']);++ expect(exitCode).toBe(0);+ expect(stderr).toContain(`[ok] Using Open Knowledge project at ${realpathSync(root)}`);+ expect(stdout).toContain(`Stopped: server (pid=${sleeper.pid}, port=4242)`);+ } finally {+ sleeper.kill();+ }+ }, 30_000);++ test('`ok mcp` from a subdirectory keeps stdout clean for JSON-RPC', () => {+ const root = makeFixture();+ makeProjectRoot(root);+ const sub = join(root, 'notes');+ mkdirSync(sub, { recursive: true });++ const { exitCode, stdout, stderr } = spawnCli(['--cwd', sub, 'mcp']);++ expect(exitCode).toBe(0);+ expect(stderr).toContain(`[ok] Using Open Knowledge project at ${realpathSync(root)}`);+ expect(stdout).toBe('');+ }, 30_000);++ test('non-anchored commands keep literal-cwd semantics from a subdirectory', () => {+ const root = makeFixture();+ makeProjectRoot(root);+ const sub = join(root, 'notes');+ mkdirSync(sub, { recursive: true });++ const { exitCode, stderr } = spawnCli(['--cwd', sub, 'ps', '--json']);++ expect(exitCode).toBe(0);+ expect(stderr).not.toContain('Using Open Knowledge project at');+ }, 30_000);+});diff --git a/packages/cli/src/project-anchor.ts b/packages/cli/src/project-anchor.tsnew file mode 100644index 000000000..3e3142df8--- /dev/null+++ b/packages/cli/src/project-anchor.ts@@ -0,0 +1,34 @@+import { findEnclosingProjectRoot } from '@inkeep/open-knowledge-server';++const PROJECT_ANCHORED_COMMANDS: ReadonlySet<string> = new Set([+ 'start',+ 'stop',+ 'status',+ 'clean',+ 'ui',+ 'mcp',+ 'preview',+]);++export function resolveProjectAnchor(+ commandName: string | undefined,+ cwd: string,+ findRoot: typeof findEnclosingProjectRoot = findEnclosingProjectRoot,+): string | null {+ if (commandName !== undefined && !PROJECT_ANCHORED_COMMANDS.has(commandName)) {+ return null;+ }+ const hit = findRoot(cwd);+ if (hit === null || hit.distance === 0) return null;+ return hit.rootPath;+}++let invocationCwd: string | null = null;++export function recordInvocationCwd(cwd: string | null): void {+ invocationCwd = cwd;+}++export function getInvocationCwd(): string {+ return invocationCwd ?? process.cwd();+}