Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): refuse $HOME as an `ok init` project root (PRD-8111) (#3634)

tim-inkeep5ce00334ed4b
diff --git a/.changeset/home-is-never-a-project.md b/.changeset/home-is-never-a-project.md
new file mode 100644
index 000000000..485183ca6
--- /dev/null
+++ b/.changeset/home-is-never-a-project.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+"@inkeep/open-knowledge-server": patch
+"@inkeep/open-knowledge-desktop": patch
+---
+
+Your home directory is no longer treated as a project by any entry point. Setting one up there ran `git init` in your home, wrote `config.yml` into `~/.ok/` (OpenKnowledge's own user-global directory), and landed project MCP config and skills on your editors' user-global paths, since at home every editor's project config path IS its global config. The refusal now lives in the two scaffold writers every path goes through, `ensureProjectGit` and `initContent`, so it covers `ok init`, `ok share publish --project-dir`, the desktop's Open Folder confirm, the desktop `ok-init` IPC, and `POST /api/local-op/ok-init`. Picking your home folder in the desktop is refused before the setup dialog opens, which also covers reopening a home "project" left behind by the old bug. And `ok deinit` refuses to run in your home directory, where it used to queue your entire user-global store for removal: `global.yml`, `skills/`, `auth.yml`, `secrets.yml`.
diff --git a/packages/cli/src/commands/deinit.test.ts b/packages/cli/src/commands/deinit.test.ts
index 3815a6cad..135c80d44 100644
--- a/packages/cli/src/commands/deinit.test.ts
+++ b/packages/cli/src/commands/deinit.test.ts
@@ -1,10 +1,18 @@
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { Readable } from 'node:stream';
import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';
-import { describe, expect, test } from 'vitest';
-import { runDeinit } from './deinit.ts';
+import { describe, expect, test, vi } from 'vitest';
+import { deinitCommand, runDeinit } from './deinit.ts';
import { buildManagedServerEntry } from './editors.ts';
const OWN_ENTRY = buildManagedServerEntry({ mode: 'published' });
@@ -14,9 +22,20 @@ function write(path: string, content: string): void {
writeFileSync(path, content);
}
+/**
+ * A temp home containing a temp OK project. The project is a CHILD of `home`
+ * rather than home itself: `runDeinit` now refuses `projectRoot === home`,
+ * because at home `.ok/` is OpenKnowledge's user-global directory rather than a
+ * project marker. The old fixtures passed `home: dir` with `dir` also being the
+ * project, which would trip that refusal in every case.
+ */
+function seedHome(): string {
+ return mkdtempSync(join(tmpdir(), 'ok-deinit-home-'));
+}
+
/** A temp OK project with a realistic footprint + a markdown content file. */
-function seedProject(): string {
- const dir = mkdtempSync(join(tmpdir(), 'ok-deinit-'));
+function seedProject(home: string = seedHome()): string {
+ const dir = mkdtempSync(join(home, 'ok-deinit-'));
write(join(dir, '.ok', 'config.yml'), 'content:\n dir: .\n');
write(join(dir, '.ok', 'local', 'server.lock'), '{}');
write(join(dir, '.okignore'), 'secret.md\n');
@@ -32,9 +51,9 @@ function seedProject(): string {
describe('runDeinit', () => {
test('no-op with a clear message when the dir is not an OK project', async () => {
- const dir = mkdtempSync(join(tmpdir(), 'ok-deinit-'));
+ const dir = mkdtempSync(join(seedHome(), 'ok-deinit-'));
try {
- const result = await runDeinit({ cwd: dir, home: dir, yes: true });
+ const result = await runDeinit({ cwd: dir, home: dirname(dir), yes: true });
expect(result.status).toBe('no-op');
expect(result.exitCode).toBe(0);
} finally {
@@ -45,7 +64,7 @@ describe('runDeinit', () => {
test('dry-run shows the plan and removes nothing', async () => {
const dir = seedProject();
try {
- const result = await runDeinit({ cwd: dir, home: dir, dryRun: true });
+ const result = await runDeinit({ cwd: dir, home: dirname(dir), dryRun: true });
expect(result.status).toBe('dry-run');
expect(result.message).toContain('Remove');
expect(existsSync(join(dir, '.ok'))).toBe(true); // untouched
@@ -59,7 +78,7 @@ describe('runDeinit', () => {
try {
const result = await runDeinit({
cwd: dir,
- home: dir,
+ home: dirname(dir),
confirmStream: Readable.from(['\n']),
});
expect(result.status).toBe('cancelled');
@@ -72,7 +91,7 @@ describe('runDeinit', () => {
test('removes the project footprint while leaving markdown content untouched', async () => {
const dir = seedProject();
try {
- const result = await runDeinit({ cwd: dir, home: dir, yes: true });
+ const result = await runDeinit({ cwd: dir, home: dirname(dir), yes: true });
expect(result.status).toBe('done');
expect(result.exitCode).toBe(0);
// OK footprint gone.
@@ -93,7 +112,7 @@ describe('runDeinit', () => {
test('--json without --yes is rejected (no interactive prompt possible)', async () => {
const dir = seedProject();
try {
- const result = await runDeinit({ cwd: dir, home: dir, json: true });
+ const result = await runDeinit({ cwd: dir, home: dirname(dir), json: true });
expect(result.status).toBe('failed');
expect(result.exitCode).toBe(1);
} finally {
@@ -106,7 +125,7 @@ describe('runDeinit', () => {
try {
const result = await runDeinit({
cwd: dir,
- home: dir,
+ home: dirname(dir),
yes: true,
runRemovalDeps: {
// The project's SIGTERM fails → the stop-server op is `failed`.
@@ -120,3 +139,91 @@ describe('runDeinit', () => {
}
});
});
+
+/**
+ * `cd ~ && ok deinit` used to build a real removal plan: the only precondition
+ * was `existsSync(join(projectRoot, '.ok'))`, and `~/.ok/` exists on every
+ * machine because it is OpenKnowledge's USER-GLOBAL directory. The plan queued
+ * `remove-path` for it, taking `global.yml`, `skills/` (the user's own
+ * unversioned skills), `auth.yml` and `secrets.yml` with it.
+ */
+describe('runDeinit — refuses the home directory', () => {
+ test('refuses instead of planning removal of the user-global ~/.ok', async () => {
+ const home = seedHome();
+ try {
+ // Exactly the shape a real home has: OK's user-global directory, which
+ // the old `.ok` existence check read as a project marker.
+ write(join(home, '.ok', 'global.yml'), 'appearance:\n theme: dark\n');
+ write(join(home, '.ok', 'skills', 'my-skill', 'SKILL.md'), '# mine\n');
+ write(join(home, '.ok', 'auth.yml'), 'token: secret\n');
+
+ // `--yes`: the destructive prompt is exactly what a scripted run skips.
+ const result = await runDeinit({ cwd: home, home, yes: true });
+
+ expect(result.status).toBe('failed');
+ expect(result.exitCode).toBe(64);
+ expect(result.message).toContain('home directory');
+ // The refusal is only worth anything if the store survives it.
+ expect(existsSync(join(home, '.ok', 'global.yml'))).toBe(true);
+ expect(existsSync(join(home, '.ok', 'skills', 'my-skill', 'SKILL.md'))).toBe(true);
+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(true);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('a symlinked spelling of home is refused too', async () => {
+ const home = seedHome();
+ const link = join(tmpdir(), `ok-deinit-home-link-${process.pid}`);
+ try {
+ write(join(home, '.ok', 'global.yml'), 'appearance:\n theme: dark\n');
+ symlinkSync(home, link);
+
+ const result = await runDeinit({ cwd: link, home, yes: true });
+
+ expect(result.status).toBe('failed');
+ expect(result.exitCode).toBe(64);
+ expect(existsSync(join(home, '.ok', 'global.yml'))).toBe(true);
+ } finally {
+ rmSync(link, { force: true });
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('the command action exits 64 rather than 0 at home', async () => {
+ // The refusal is only scriptable if the exit code carries it: an exit 0
+ // would be indistinguishable from the no-op case. Same command-level pin
+ // the init suite has, since the wiring is a separate line from runDeinit's
+ // return value.
+ const home = seedHome();
+ const savedExitCode = process.exitCode;
+ const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+ try {
+ write(join(home, '.ok', 'global.yml'), 'appearance:\n theme: dark\n');
+ vi.stubEnv('HOME', home);
+
+ await deinitCommand().parseAsync([home, '--yes'], { from: 'user' });
+
+ expect(process.exitCode).toBe(64);
+ const printed = stdoutSpy.mock.calls.map((call) => String(call[0])).join('');
+ expect(printed).toContain('home directory');
+ expect(existsSync(join(home, '.ok', 'global.yml'))).toBe(true);
+ } finally {
+ process.exitCode = savedExitCode;
+ stdoutSpy.mockRestore();
+ vi.unstubAllEnvs();
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('still deinits a project that lives inside home', async () => {
+ const home = seedHome();
+ const dir = seedProject(home);
+ try {
+ const result = await runDeinit({ cwd: dir, home, dryRun: true });
+ expect(result.status).toBe('dry-run');
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/src/commands/deinit.ts b/packages/cli/src/commands/deinit.ts
index 073ad2c08..24e8e3cc9 100644
--- a/packages/cli/src/commands/deinit.ts
+++ b/packages/cli/src/commands/deinit.ts
@@ -9,6 +9,7 @@
import { existsSync } from 'node:fs';
import { homedir } from 'node:os';
import { join, resolve } from 'node:path';
+import { isHomeDir } from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import { accent, dim, error as errorColor } from '../ui/colors.ts';
import { confirmDestructive } from '../ui/confirm.ts';
@@ -44,6 +45,26 @@ export async function runDeinit(opts: DeinitOptions = {}): Promise<DeinitResult>
const projectRoot = resolve(opts.cwd ?? process.cwd());
const home = opts.home ?? homedir();
+ // Home is never a project, and here that matters more than anywhere else:
+ // `~/.ok/` is OpenKnowledge's USER-GLOBAL directory, so the `.ok/` existence
+ // check below is satisfied on every machine, and the plan would queue
+ // `remove-path` for `global.yml`, `skills/` (the user's own unversioned
+ // skills), `auth.yml` and `secrets.yml`. `--yes` skips the destructive
+ // prompt, and the plan lines read like ordinary project paths. This is also
+ // the command someone reaches for to undo an `ok init` that anchored them to
+ // home, which is the worst possible place for that hazard.
+ if (isHomeDir(projectRoot, home)) {
+ return {
+ status: 'failed',
+ message:
+ `${errorColor('Refusing to deinit your home directory.')}\n` +
+ ` ${projectRoot}/.ok is OpenKnowledge's user-global directory (global.yml, skills/,\n` +
+ ` auth.yml), not a project. Removing it would delete your global settings and skills.\n` +
+ ` To remove OpenKnowledge everywhere, use 'ok uninstall'.`,
+ exitCode: 64,
+ };
+ }
+
// `.ok/` is the project marker; without it there is no OpenKnowledge footprint
// to remove here (a stray editor-config entry would be handled by uninstall's
// global sweep, not a per-project deinit).
diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.ts
index d8e6671e1..3e15b26a0 100644
--- a/packages/cli/src/commands/init.test.ts
+++ b/packages/cli/src/commands/init.test.ts
@@ -3,6 +3,7 @@ import {
existsSync,
lstatSync,
mkdirSync,
+ mkdtempSync,
readdirSync,
readFileSync,
realpathSync,
@@ -15,7 +16,7 @@ import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { resolveBundleEnabled } from '@inkeep/open-knowledge-core';
import { readBundleDecision } from '@inkeep/open-knowledge-server';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { parse as parseYaml } from 'yaml';
import { loadConfig } from '../config/loader.ts';
import { OK_DIR } from '../constants.ts';
@@ -53,6 +54,7 @@ import {
type EditorMcpResult,
formatInitResult,
formatSharingOutcome,
+ HomeProjectRootError,
initCommand,
MANAGED_FILE_BUILDERS,
readExistingMcpEntry,
@@ -2118,6 +2120,131 @@ describe('runInit — projectRoot threading', () => {
});
});
+// ---------------------------------------------------------------------------
+// runInit — the home directory is never a project root
+// ---------------------------------------------------------------------------
+
+/**
+ * `cd ~ && ok init` set up a project in the user's home directory: `git init`
+ * in `$HOME`, `config.yml` written into `~/.ok/` (OpenKnowledge's own
+ * user-global directory), and — because every project-scope editor path at
+ * home resolves onto that editor's user-global config — the project MCP write
+ * and project skill install landing in `~/.cursor/`, `~/.codex/`, `~/.claude/`.
+ *
+ * The refusal is checked at the resolved projectRoot rather than at `cwd`
+ * because promotion runs first; both spellings must be refused.
+ */
+describe('runInit — refuses the home directory as a project root', () => {
+ let testDir: string;
+ let fakeHome: string;
+ const originalHome = process.env.HOME;
+ const originalPlatform = process.platform;
+ const defaultInstallUserSkill = async () => 'installed' as const;
+
+ beforeEach(() => {
+ testDir = realpathSync(mkdtempSync(join(tmpdir(), 'init-home-refusal-test-')));
+ fakeHome = join(testDir, 'fakehome');
+ mkdirSync(join(fakeHome, '.claude'), { recursive: true });
+ process.env.HOME = fakeHome;
+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ });
+
+ afterEach(() => {
+ Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
+ if (originalHome === undefined) {
+ delete process.env.HOME;
+ } else {
+ process.env.HOME = originalHome;
+ }
+ rmSync(testDir, { recursive: true, force: true });
+ });
+
+ const runAtHome = (cwd: string) =>
+ runInit({
+ cwd,
+ home: fakeHome,
+ installUserSkill: defaultInstallUserSkill,
+ scope: 'project',
+ skills: true,
+ });
+
+ it('throws HomeProjectRootError instead of setting up a project', async () => {
+ await expect(runAtHome(fakeHome)).rejects.toBeInstanceOf(HomeProjectRootError);
+ });
+
+ it('writes nothing at all — no git repo, no .ok/, no project skills', async () => {
+ // The whole point is that the refusal happens BEFORE any side effect, so
+ // this asserts every write site named in the bug report at once.
+ await expect(runAtHome(fakeHome)).rejects.toThrow();
+
+ expect(existsSync(join(fakeHome, '.git'))).toBe(false);
+ expect(existsSync(join(fakeHome, OK_DIR))).toBe(false);
+ expect(existsSync(join(fakeHome, '.okignore'))).toBe(false);
+ for (const hostDir of ['.claude', '.cursor', '.codex']) {
+ expect(existsSync(join(fakeHome, hostDir, 'skills', 'open-knowledge'))).toBe(false);
+ }
+ // The user-global MCP configs the project-scope write would have landed on.
+ expect(existsSync(join(fakeHome, '.cursor', 'mcp.json'))).toBe(false);
+ expect(existsSync(join(fakeHome, '.codex', 'config.toml'))).toBe(false);
+ });
+
+ it('refuses a symlinked spelling of home too', async () => {
+ // Asymmetric on purpose: `cwd` arrives via a symlink while `home` is the
+ // real path, so a plain string compare would let this through.
+ const linkedHome = join(testDir, 'home-link');
+ symlinkSync(fakeHome, linkedHome);
+
+ await expect(runAtHome(linkedHome)).rejects.toBeInstanceOf(HomeProjectRootError);
+ expect(existsSync(join(fakeHome, '.git'))).toBe(false);
+ });
+
+ it('the command action prints the refusal and exits 64 rather than throwing', async () => {
+ // `runInit` throwing is only half the contract. The user-facing half lives
+ // in the command action's catch: a clean message on stderr (no stack) and
+ // EX_USAGE 64, which a script can branch on. Driven in-process against
+ // `initCommand()` — the same idiom `config.test.ts` uses for its exit-code
+ // assertions — so this pins the handler without depending on a built dist.
+ const savedCwd = process.cwd();
+ const savedExitCode = process.exitCode;
+ const stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
+ try {
+ process.chdir(fakeHome);
+
+ await initCommand().parseAsync([], { from: 'user' });
+
+ expect(process.exitCode).toBe(64);
+ const printed = stderrSpy.mock.calls.map((call) => String(call[0])).join('');
+ expect(printed).toContain(
+ 'Refusing to set up an OpenKnowledge project in your home directory',
+ );
+ // A rethrow would surface as an unhandled rejection with a stack instead.
+ expect(printed).not.toContain('at runInit');
+ } finally {
+ process.chdir(savedCwd);
+ // Restore before the assertion can leak exit code 64 to the test runner.
+ process.exitCode = savedExitCode;
+ stderrSpy.mockRestore();
+ }
+ });
+
+ it('still initializes a folder inside home', async () => {
+ // Control: the refusal is scoped to home itself, not to living under it.
+ const project = join(fakeHome, 'notes');
+ mkdirSync(project, { recursive: true });
+
+ const result = await runInit({
+ cwd: project,
+ home: fakeHome,
+ installUserSkill: defaultInstallUserSkill,
+ scope: 'user',
+ skills: true,
+ });
+
+ expect(result.projectRoot).toBe(project);
+ expect(existsSync(join(project, OK_DIR, 'config.yml'))).toBe(true);
+ });
+});
+
// ---------------------------------------------------------------------------
// resolveRequestedContentDir — pure path validation
// ---------------------------------------------------------------------------
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index b9fc9ee64..e06d4e4b7 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -34,6 +34,7 @@ import {
ensureProjectSkillGitignore,
GitNotAvailableError,
GitTooOldError,
+ HomeProjectRootError,
initContent,
installUserSkill,
MCP_SERVER_NAME,
@@ -62,7 +63,7 @@ import { isCollection, parseDocument, stringify as stringifyYaml } from 'yaml';
import { CONFIG_FILENAME, OK_DIR } from '../constants.ts';
import { formatPreviewBlock, type PreviewResult } from '../content/preview.ts';
import { buildPiExtensionSource, makePiManagedFileEntry } from '../integrations/pi-extension.ts';
-import { resolveProjectRoot } from '../integrations/resolve-project-root.ts';
+import { isHomeDir, resolveProjectRoot } from '../integrations/resolve-project-root.ts';
import {
assertProjectPathSafe,
type ProjectSkillResult,
@@ -789,6 +790,14 @@ export class ContentDirError extends Error {
}
}
+/**
+ * Re-exported from the server package, where the scaffold writers throw it.
+ * `runInit` throws the same class earlier (before `ensureProjectGit` can run)
+ * purely so the CLI refuses with its own message and exit code rather than
+ * surfacing a writer-level failure mid-scaffold.
+ */
+export { HomeProjectRootError };
+
/**
* Resolve which user-global bundles `ok init` should enable from the `--skills`
* / `--no-skills` flag: `undefined`/`true` → the onboarding set; `false`
@@ -1687,6 +1696,18 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitCom
// happens here — every other path stays silent.
const resolution = resolveProjectRoot(cwd, { homeDir: options.home });
const projectRoot = resolution.projectRoot;
+ // Refuse the home directory before ANY side effect. Nothing `ok init` does
+ // is scoped correctly there: `ensureProjectGit` would `git init` the user's
+ // home, `initContent` would write `config.yml` into `~/.ok/` (OpenKnowledge's
+ // own user-global directory), and every project-scope editor path resolves
+ // onto that editor's user-global config, so the project MCP write and the
+ // project skill install land in `~/.cursor/`, `~/.codex/` and `~/.claude/`.
+ // The `.ok/config.yml` left behind is the worst part: `findEnclosingProjectRoot`
+ // has no home stop, so every later command run from any non-project directory
+ // under home would anchor to home as its project.
+ if (isHomeDir(projectRoot, options.home ?? homedir())) {
+ throw new HomeProjectRootError(projectRoot);
+ }
const willScaffold = !existsSync(join(projectRoot, OK_DIR));
// `gitRootPromoted` guarantees cwd is a strict descendant of projectRoot, so
// `relative` is non-empty. Captured for the result so `formatInitResult` can
@@ -2670,10 +2691,12 @@ export function initCommand(): Command {
skills: opts.skills,
});
} catch (err) {
- // Invalid `--content-dir` (outside the project, missing, or a file):
- // print the message cleanly and exit EX_USAGE (64) — a usage error,
- // distinct from the git-preflight EX_CONFIG (78) below.
- if (err instanceof ContentDirError) {
+ // Ran somewhere `ok init` cannot mean what the user wants: an
+ // invalid `--content-dir` (outside the project, missing, or a
+ // file), or the home directory as the project root. Print the
+ // message cleanly and exit EX_USAGE (64) — a usage error, distinct
+ // from the git-preflight EX_CONFIG (78) below.
+ if (err instanceof ContentDirError || err instanceof HomeProjectRootError) {
process.stderr.write(`${err.message}\n`);
process.exitCode = 64;
return;
diff --git a/packages/cli/src/commands/share/publish.test.ts b/packages/cli/src/commands/share/publish.test.ts
index cc0dd19c0..66f4be611 100644
--- a/packages/cli/src/commands/share/publish.test.ts
+++ b/packages/cli/src/commands/share/publish.test.ts
@@ -16,8 +16,8 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { Octokit } from '@octokit/rest';
import simpleGit from 'simple-git';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { classifyOctokitError, runPublishFlow } from './publish.ts';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { classifyOctokitError, runPublishFlow, sharePublishCommand } from './publish.ts';
// ─── Octokit fake factory ─────────────────────────────────────────────────────
@@ -491,3 +491,39 @@ describe('runPublishFlow (e2e against bare repo)', () => {
}
});
});
+
+/**
+ * `initContent` refuses `$HOME`, but `runPublishFlow`'s contract is "never
+ * throw on a documented failure mode", so its catch would flatten the refusal
+ * into `init-failed` and erase the message that says what to do about it. The
+ * command wrapper checks first so `--project-dir ~` reads like `ok init` at
+ * home.
+ */
+describe('share publish — refuses --project-dir $HOME', () => {
+ test('prints the actionable refusal and exits 64, not a generic init-failed', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-publish-home-'));
+ const savedExitCode = process.exitCode;
+ const stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
+ // Never reached: the guard sits ahead of token resolution and Octokit.
+ const tokenStore = async () => ({}) as never;
+ try {
+ vi.stubEnv('HOME', home);
+
+ await sharePublishCommand(tokenStore).parseAsync(
+ ['--owner', 'someone', '--name', 'notes', '--visibility', 'private', '--project-dir', home],
+ { from: 'user' },
+ );
+
+ expect(process.exitCode).toBe(64);
+ const printed = stderrSpy.mock.calls.map((call) => String(call[0])).join('');
+ expect(printed).toContain('home directory');
+ expect(printed).toContain('Make a folder for this project');
+ expect(printed).not.toContain('init-failed');
+ } finally {
+ process.exitCode = savedExitCode;
+ stderrSpy.mockRestore();
+ vi.unstubAllEnvs();
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/src/commands/share/publish.ts b/packages/cli/src/commands/share/publish.ts
index 1caa6669c..a02072b50 100644
--- a/packages/cli/src/commands/share/publish.ts
+++ b/packages/cli/src/commands/share/publish.ts
@@ -29,7 +29,12 @@
import { execSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { join, resolve } from 'node:path';
-import { initContent, withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';
+import {
+ HomeProjectRootError,
+ initContent,
+ isHomeDir,
+ withHiddenWindowsConsole,
+} from '@inkeep/open-knowledge-server';
import { Octokit } from '@octokit/rest';
import { Command } from 'commander';
import simpleGit, { type SimpleGit, type SimpleGitOptions } from 'simple-git';
@@ -464,6 +469,18 @@ function emitPublishEvent(json: boolean, result: PublishResult): void {
async function runSharePublish(opts: PublishOptions, tokenStore: TokenStore): Promise<void> {
const { host, owner, name, visibility, description, projectDir, json } = opts;
validateGitHubHost(host);
+ // `initContent` inside the flow refuses `$HOME`, but `runPublishFlow`'s
+ // contract is "never throw on a documented failure mode", so its bare catch
+ // would flatten that refusal into `init-failed` and erase the message that
+ // tells the user what to do. Checked here, in the command wrapper, so
+ // `--project-dir ~` reads like `ok init` at home: the actionable message and
+ // EX_USAGE 64. Adding a `PublishErrorCode` instead would have meant a new
+ // case in the desktop wizard's mapping for a CLI-only input mistake.
+ if (isHomeDir(projectDir)) {
+ process.stderr.write(`${new HomeProjectRootError(resolve(projectDir)).message}\n`);
+ process.exitCode = 64;
+ return;
+ }
const token = await resolveReposToken(host, tokenStore);
if (token == null) {
emitPublishEvent(json, { kind: 'error', code: 'auth-required' });
diff --git a/packages/cli/src/integrations/resolve-project-root.test.ts b/packages/cli/src/integrations/resolve-project-root.test.ts
index 7038503b4..cf2c2b0a4 100644
--- a/packages/cli/src/integrations/resolve-project-root.test.ts
+++ b/packages/cli/src/integrations/resolve-project-root.test.ts
@@ -1,10 +1,11 @@
import { execFile } from 'node:child_process';
-import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { promisify } from 'node:util';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
+ isHomeDir,
type ResolveProjectRootOptions,
type ResolveProjectRootResult,
resolveProjectRoot,
@@ -99,6 +100,9 @@ describe('resolveProjectRoot — ancestor walk wins', () => {
expect(result.defaultContentDir).toBe('.');
});
+ // This pins the WALK only: home is not a project ancestor. It is not a
+ // statement that home is a usable project root — `runInit` refuses that
+ // root outright via `isHomeDir` (see the HomeProjectRootError suite).
test('walk excludes home itself — picking home does not match home/.ok/', () => {
writeOkConfig(fakeHome);
@@ -317,3 +321,22 @@ describe('resolveProjectRoot — integration with real git', () => {
expect(result.defaultContentDir).toBe('.');
});
});
+
+describe('isHomeDir', () => {
+ test('true for home itself, false for a folder inside it', () => {
+ const inside = resolve(fakeHome, 'notes');
+ mkdirSync(inside, { recursive: true });
+
+ expect(isHomeDir(fakeHome, fakeHome)).toBe(true);
+ expect(isHomeDir(inside, fakeHome)).toBe(false);
+ });
+
+ test('a symlinked spelling of home still compares equal', () => {
+ // The reason this is a canonicalizing compare and not `===`: the two
+ // operands reach `runInit` by different routes (`cwd` vs `os.homedir()`).
+ const linked = resolve(tmpReal, 'home-link');
+ symlinkSync(fakeHome, linked);
+
+ expect(isHomeDir(linked, fakeHome)).toBe(true);
+ });
+});
diff --git a/packages/cli/src/integrations/resolve-project-root.ts b/packages/cli/src/integrations/resolve-project-root.ts
index b5e36a279..d4c45ef02 100644
--- a/packages/cli/src/integrations/resolve-project-root.ts
+++ b/packages/cli/src/integrations/resolve-project-root.ts
@@ -30,7 +30,27 @@ import { execFileSync } from 'node:child_process';
import { realpathSync } from 'node:fs';
import { homedir as nodeHomedir } from 'node:os';
import { dirname, isAbsolute, relative, resolve } from 'node:path';
-import { isProjectRoot, withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';
+import {
+ canonicalizeForCompare,
+ isHomeDir,
+ isProjectRoot,
+ withHiddenWindowsConsole,
+} from '@inkeep/open-knowledge-server';
+
+/**
+ * Re-exported so this module stays the CLI's one stop for "how do we classify a
+ * picked directory" — `runInit` refuses the root `isHomeDir` names, and the walk
+ * below is why the fall-through branch can hand back home in the first place.
+ * Both implementations live in the server package: the scaffold writers
+ * (`ensureProjectGit`, `initContent`) enforce the same home invariant for the
+ * four non-CLI entry points, and the server is below both the CLI and the
+ * desktop in the dependency graph, so one `canonicalizeForCompare` replaces
+ * what used to be three byte-identical copies kept in sync by drift comments.
+ *
+ * `canonicalizeForCompare` keeps this import path because `repair-skills`'s
+ * global-config collision gate already imports it from here.
+ */
+export { canonicalizeForCompare, isHomeDir };
const ANCESTOR_WALK_DEPTH_LIMIT = 30;
@@ -62,36 +82,6 @@ export interface ResolveProjectRootOptions {
gitTopLevel?: (cwd: string) => string | null;
}
-/**
- * Canonicalize a path so two spellings of the SAME directory compare equal.
- *
- * Windows keeps a legacy 8.3 alias for most long names (`C:\Users\runneradmin`
- * is also `C:\Users\RUNNER~1`); the forms are different strings that no
- * separator normalization can reconcile. `fs.realpathSync` does NOT expand the
- * alias, `fs.realpathSync.native` does. The operands below arrive by different
- * routes — `home` from `os.homedir()`, `gitRoot` from
- * `git rev-parse --show-toplevel`, which always reports the LONG name — so a
- * short-form home vs a long-form git root makes `relative()` escape with `..`
- * and promotion silently never fires. Real-Windows-verified.
- *
- * Best-effort: falls back to the input if the path cannot be resolved.
- *
- * Mirrored in `packages/desktop/src/main/folder-admission.ts`; the two copies
- * must move together (TypeScript cannot catch drift across packages).
- *
- * Exported so in-package path-equality checks (e.g. `repair-skills`'s
- * global-config collision gate) reuse this one implementation instead of
- * re-deriving the idiom — a re-derived copy loses the `.native` rationale
- * above and silently disarms the guard on Windows.
- */
-export function canonicalizeForCompare(p: string): string {
- try {
- return realpathSync.native(p);
- } catch {
- return p;
- }
-}
-
/**
* Strict descendant — equal-to-home does NOT promote, so a hypothetical
* `~/.git/` (e.g., dotfiles repo) is never picked as the project boundary.
diff --git a/packages/desktop/src/main/folder-admission.test.ts b/packages/desktop/src/main/folder-admission.test.ts
index 97a552f8a..0184c2575 100644
--- a/packages/desktop/src/main/folder-admission.test.ts
+++ b/packages/desktop/src/main/folder-admission.test.ts
@@ -207,6 +207,73 @@ const writeOkConfig = (dir: string, contents = '$schema: x\n'): void => {
writeFileSync(resolve(dir, '.ok/config.yml'), contents);
};
+/**
+ * Picking `$HOME` in the folder picker used to land on the `fresh` branch with
+ * `projectDir === $HOME`: the ancestor walk breaks AT home without testing it,
+ * and git-root promotion is strict-descendant-only, so nothing above rejected
+ * it. Confirming the dialog then ran `ensureProjectGit($HOME)` + `initContent`
+ * + the project-scope editor writes, which at home are the editors'
+ * user-global configs. Rejecting here means the dialog never opens.
+ */
+describe('discoverProject — the home directory is never a project', () => {
+ test('rejects a home pick instead of classifying it fresh', async () => {
+ const result = await discoverProject(fakeHome, {
+ homeDir: fakeHome,
+ gitTopLevel: stubGitTopLevel({}),
+ dirSizeProbe: null,
+ });
+
+ expect(result.kind).toBe('rejected');
+ if (result.kind !== 'rejected') return;
+ expect(result.reason).toBe('home-directory');
+ });
+
+ test('rejects a home that already carries the pre-fix .ok/config.yml', async () => {
+ // `~/.ok/` is OpenKnowledge's user-global directory, so this shape exists
+ // on any machine where the old `ok init` bug fired. Re-opening it must not
+ // resurrect a project at home.
+ writeOkConfig(fakeHome);
+
+ const result = await discoverProject(fakeHome, {
+ homeDir: fakeHome,
+ gitTopLevel: stubGitTopLevel({}),
+ dirSizeProbe: null,
+ });
+
+ expect(result.kind).toBe('rejected');
+ if (result.kind !== 'rejected') return;
+ expect(result.reason).toBe('home-directory');
+ });
+
+ test('rejects a symlinked spelling of home', async () => {
+ const link = resolve(tmpReal, 'home-link');
+ symlinkSync(fakeHome, link);
+
+ const result = await discoverProject(link, {
+ homeDir: fakeHome,
+ gitTopLevel: stubGitTopLevel({}),
+ dirSizeProbe: null,
+ });
+
+ expect(result.kind).toBe('rejected');
+ if (result.kind !== 'rejected') return;
+ expect(result.reason).toBe('home-directory');
+ });
+
+ test('a folder inside home is unaffected', async () => {
+ const project = resolve(fakeHome, 'notes');
+ mkdirSync(project, { recursive: true });
+
+ const result = await discoverProject(project, {
+ homeDir: fakeHome,
+ gitTopLevel: stubGitTopLevel({}),
+ dirSizeProbe: null,
+ });
+
+ expect(result.kind).toBe('fresh');
+ });
+});
+
describe('discoverProject — managed kind (ancestor walk)', () => {
test('returns managed at picked path when .ok/config.yml is at picked', async () => {
const project = resolve(fakeHome, 'project');
@@ -265,16 +332,26 @@ describe('discoverProject — managed kind (ancestor walk)', () => {
expect(result.ancestorPromoted).toBe(true);
});
- test('walk excludes home itself — picking home returns fresh, not managed', async () => {
+ // Was: 'walk excludes home itself — picking home returns fresh, not managed'.
+ // The walk still excludes home, but `fresh` was the wrong destination: it
+ // carried `projectDir === $HOME` into `ensureProjectGit` + `initContent`.
+ // Home is now rejected outright, above the walk (see the home-directory
+ // suite); this case keeps the ancestor-walk half of the original assertion.
+ test('walk excludes home itself — a home .ok/ never promotes a child', async () => {
writeOkConfig(fakeHome);
+ const sub = resolve(fakeHome, 'sub');
+ mkdirSync(sub, { recursive: true });
- const result = await discoverProject(fakeHome, {
+ const result = await discoverProject(sub, {
homeDir: fakeHome,
gitTopLevel: stubGitTopLevel({}),
dirSizeProbe: null,
});
+ // Not `managed` at home — the walk broke before testing it.
expect(result.kind).toBe('fresh');
+ if (result.kind !== 'fresh') return;
+ expect(result.projectDir).toBe(sub);
});
test('legacy .ok/ below git root wins over git-root promotion', async () => {
@@ -605,7 +682,11 @@ describe('discoverProject — type surface', () => {
});
test('RejectionReason union is exhaustively enumerated', () => {
- const allReasons: readonly RejectionReason[] = ['symlink-escape', 'unreadable'];
+ const allReasons: readonly RejectionReason[] = [
+ 'symlink-escape',
+ 'unreadable',
+ 'home-directory',
+ ];
for (const r of allReasons) expect(typeof r).toBe('string');
});
diff --git a/packages/desktop/src/main/folder-admission.ts b/packages/desktop/src/main/folder-admission.ts
index 6072bcff2..b184f80c3 100644
--- a/packages/desktop/src/main/folder-admission.ts
+++ b/packages/desktop/src/main/folder-admission.ts
@@ -19,7 +19,7 @@ import { homedir as nodeHomedir } from 'node:os';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { promisify } from 'node:util';
import { resolveGitDirDetailed } from '@inkeep/open-knowledge-core/shadow-repo-layout';
-import { isProjectRoot } from '@inkeep/open-knowledge-server';
+import { canonicalizeForCompare, isHomeDir, isProjectRoot } from '@inkeep/open-knowledge-server';
const execFileAsync = promisify(execFile);
@@ -120,7 +120,7 @@ export type GitState = 'present' | 'absent' | 'shell-only';
* Reasons `discoverProject` may refuse the picked path. Surfaces to the user
* as a non-consent error dialog rather than feeding into the consent flow.
*/
-export type RejectionReason = 'symlink-escape' | 'unreadable';
+export type RejectionReason = 'symlink-escape' | 'unreadable' | 'home-directory';
/**
* Discriminated result of `discoverProject`. `pickedPath` is preserved on
@@ -248,6 +248,19 @@ export async function discoverProject(
return { kind: 'rejected', reason: 'symlink-escape' };
}
+ // Home is never a project. The ancestor walk below breaks AT home without
+ // testing it, and git-root promotion is strict-descendant-only, so a home
+ // pick used to fall through to `fresh` with `projectDir === $HOME` — and
+ // confirming the dialog then ran `ensureProjectGit($HOME)` + `initContent`
+ // + the project-scope editor writes, which at home are the editors'
+ // user-global configs. Refused up here so the whole flow (dialog included)
+ // never starts, rather than surfacing as a mid-scaffold writer error.
+ // `~/.ok/` is OpenKnowledge's user-global directory, so this also refuses
+ // re-opening a home "project" left behind by the pre-fix `ok init`.
+ if (isHomeDir(realPicked, home)) {
+ return { kind: 'rejected', reason: 'home-directory' };
+ }
+
// Linked-worktree carveout: an UN-initialized linked-worktree root is a
// standalone project regardless of any ancestor's .ok/. A `git worktree
// add .claude/worktrees/feat-bar` produces a worktree at
@@ -347,45 +360,6 @@ function isDescendantOrEqual(child: string, parent: string): boolean {
return rel.length > 0 && !rel.startsWith('..') && !isAbsolute(rel);
}
-/**
- * Canonicalize a path so two spellings of the SAME directory compare equal.
- *
- * Windows keeps a legacy 8.3 alias for most long names (`C:\Users\runneradmin`
- * is also reachable as `C:\Users\RUNNER~1`), and the two forms are different
- * strings that no separator normalization can reconcile — only the filesystem
- * knows they are one directory. `fs.realpathSync` does NOT expand the alias;
- * `fs.realpathSync.native` does (it goes through `GetFinalPathNameByHandle`).
- *
- * This matters because the two operands below arrive by different routes:
- * `home` / the picked path come from `os.homedir()` + `realpathSync`, which
- * preserve whatever form the caller had, while `gitTopLevel` shells out to
- * `git rev-parse --show-toplevel`, which always reports the LONG name. Compare
- * a short-form home against a long-form git root and `relative()` escapes with
- * `..`, so the descendant check says "outside home" for a directory that is
- * plainly inside it — and git-root promotion silently never fires.
- *
- * Verified on a Windows 11 ARM64 VM:
- * realpathSync('…\\OK-SN-~2\\LONGDI~1') -> unchanged (still short)
- * realpathSync.native(same) -> '…\\ok-sn-UtSXeQ\\longdirectoryname'
- * git rev-parse --show-toplevel -> 'C:/Users/…/longdirectoryname/website'
- * relative(shortHome, longGitRoot) -> '..\\..\\ok-sn-…\\website' (escapes)
- *
- * No-op in practice on POSIX, where `.native` and the JS implementation agree.
- * Falls back to the input when the path cannot be resolved (deleted between
- * calls, permission denied) — a best-effort canonicalizer must never be the
- * thing that throws.
- *
- * Mirrored in `packages/cli/src/integrations/resolve-project-root.ts`; the two
- * copies must move together (TypeScript cannot catch drift across packages).
- */
-function canonicalizeForCompare(p: string): string {
- try {
- return realpathSync.native(p);
- } catch {
- return p;
- }
-}
-
/** Strict descendant — equal-to-home does NOT promote. */
function isDescendantOfHome(p: string, home: string): boolean {
const rel = relative(canonicalizeForCompare(home), canonicalizeForCompare(p));
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 26e97a82c..646fdb58b 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -2221,7 +2221,13 @@ async function openProject(
if (discovery.kind === 'rejected') {
dialog.showErrorBox(
'Cannot open this folder',
- `${projectPath}\n\nReason: ${discovery.reason === 'symlink-escape' ? 'Symlink resolves outside its parent directory.' : 'Folder is unreadable or does not exist.'}`,
+ `${projectPath}\n\nReason: ${
+ discovery.reason === 'symlink-escape'
+ ? 'Symlink resolves outside its parent directory.'
+ : discovery.reason === 'home-directory'
+ ? "This is your home directory, not a project. ~/.ok is OpenKnowledge's own user-global folder (settings, skills), and opening a project here would set up git in your home directory and write project config into your editors' global folders. Make a folder for your notes and open that instead."
+ : 'Folder is unreadable or does not exist.'
+ }`,
);
openNavigator();
return;
diff --git a/packages/server/src/home-project-root.test.ts b/packages/server/src/home-project-root.test.ts
new file mode 100644
index 000000000..c3f4f4996
--- /dev/null
+++ b/packages/server/src/home-project-root.test.ts
@@ -0,0 +1,90 @@
+import { existsSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { assertNotHomeProjectRoot, HomeProjectRootError, isHomeDir } from './home-project-root.ts';
+import { initContent } from './init-project.ts';
+import { ensureProjectGit } from './project-git.ts';
+
+let home: string;
+
+beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'ok-home-guard-'));
+});
+
+afterEach(() => {
+ // The writer tests point `os.homedir()` at the fixture; unstub so a later
+ // test in this file can't inherit a HOME that names a deleted directory.
+ vi.unstubAllEnvs();
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('isHomeDir', () => {
+ test('true for home, false for a folder inside it', () => {
+ expect(isHomeDir(home, home)).toBe(true);
+ expect(isHomeDir(join(home, 'notes'), home)).toBe(false);
+ });
+
+ test('a symlinked spelling of home still compares equal', () => {
+ // The two operands reach the writers by different routes (a user-supplied
+ // path or a folder pick vs `os.homedir()`), so `===` is not enough.
+ const link = join(tmpdir(), `ok-home-guard-link-${process.pid}`);
+ try {
+ symlinkSync(home, link);
+ expect(isHomeDir(link, home)).toBe(true);
+ } finally {
+ rmSync(link, { force: true });
+ }
+ });
+
+ test('a relative spelling resolves before comparing', () => {
+ expect(isHomeDir(join(home, 'notes', '..'), home)).toBe(true);
+ });
+});
+
+describe('assertNotHomeProjectRoot', () => {
+ test('throws for home, carrying the resolved path', () => {
+ try {
+ assertNotHomeProjectRoot(home, home);
+ throw new Error('expected a throw');
+ } catch (err) {
+ expect(err).toBeInstanceOf(HomeProjectRootError);
+ expect((err as HomeProjectRootError).projectRoot).toBe(resolve(home));
+ }
+ });
+
+ test('is silent for any other directory', () => {
+ expect(() => assertNotHomeProjectRoot(join(home, 'notes'), home)).not.toThrow();
+ });
+});
+
+/**
+ * The two shared writers every scaffold entry point passes through: `ok init`,
+ * `ok share publish --project-dir`, the desktop Open Folder confirm, the
+ * desktop `ok-init` IPC and `POST /api/local-op/ok-init`. Guarding them is what
+ * makes the refusal hold for the four non-CLI entry points, which have no
+ * `runInit` in front of them.
+ */
+describe('scaffold writers refuse $HOME', () => {
+ test('ensureProjectGit does not git init the home directory', async () => {
+ vi.stubEnv('HOME', home);
+ await expect(ensureProjectGit(home)).rejects.toBeInstanceOf(HomeProjectRootError);
+ expect(existsSync(join(home, '.git'))).toBe(false);
+ });
+
+ test('initContent does not scaffold into the user-global ~/.ok', () => {
+ vi.stubEnv('HOME', home);
+ expect(() => initContent(home)).toThrow(HomeProjectRootError);
+ // `.ok/` at home is the user-global store; a scaffold would drop a project
+ // `config.yml` into it.
+ expect(existsSync(join(home, '.ok', 'config.yml'))).toBe(false);
+ expect(existsSync(join(home, '.okignore'))).toBe(false);
+ });
+
+ test('a project inside home still scaffolds', () => {
+ vi.stubEnv('HOME', home);
+ const project = join(home, 'notes');
+ const result = initContent(project);
+ expect(result.created).toContain('config.yml');
+ });
+});
diff --git a/packages/server/src/home-project-root.ts b/packages/server/src/home-project-root.ts
new file mode 100644
index 000000000..d1416df70
--- /dev/null
+++ b/packages/server/src/home-project-root.ts
@@ -0,0 +1,84 @@
+/**
+ * The one place that answers "is this directory the user's home, and therefore
+ * never a project root?" — and the error every scaffold writer throws when it
+ * is.
+ *
+ * `~/.ok/` is OpenKnowledge's own user-global directory (`global.yml`,
+ * `skills/`, `auth.yml`), so a project at home writes its `config.yml` into the
+ * user-global store. Worse, at home every editor's PROJECT config path resolves
+ * onto that editor's USER-GLOBAL config (`~/.cursor/mcp.json`,
+ * `~/.codex/config.toml`, `~/.claude/skills/`), so project-scope wiring lands on
+ * the user's global install. And `ensureProjectGit` would `git init` the home
+ * directory itself.
+ *
+ * This lives in the server package rather than in any one caller because the
+ * scaffold has five entry points that all pass through `ensureProjectGit` and
+ * `initContent`: `ok init`, `ok share publish --project-dir`, the desktop's
+ * Open Folder confirm, the desktop `ok-init` IPC, and
+ * `POST /api/local-op/ok-init`. A per-caller guard is one copy per entry point
+ * and one more to forget on the next one.
+ */
+
+import { realpathSync } from 'node:fs';
+import { homedir as nodeHomedir } from 'node:os';
+import { resolve } from 'node:path';
+
+/**
+ * Thrown by the scaffold writers when asked to set up a project at `$HOME`.
+ * Callers that own a user-facing surface (the CLI's `ok init`, the desktop
+ * dialogs) catch it to render a clean refusal; everything else propagates.
+ */
+export class HomeProjectRootError extends Error {
+ /** The offending directory, as resolved by the writer that refused. */
+ readonly projectRoot: string;
+
+ constructor(projectRoot: string) {
+ super(
+ `Refusing to set up an OpenKnowledge project in your home directory (${projectRoot}).\n` +
+ ` A project here would run 'git init' in your home directory and write project config\n` +
+ ` and skills into your editors' user-global directories (~/.cursor, ~/.codex, ~/.claude).\n` +
+ ` Make a folder for this project, then run 'ok init' inside it.`,
+ );
+ this.name = 'HomeProjectRootError';
+ this.projectRoot = projectRoot;
+ }
+}
+
+/**
+ * Canonicalize so two spellings of the same directory compare equal.
+ *
+ * `realpathSync.native` rather than `realpathSync`: on Windows the 8.3 alias
+ * (`C:\Users\RUNNER~1` for `C:\Users\runneradmin`) is a different string that no
+ * separator normalization reconciles, and only the native binding expands it.
+ * The operands here arrive by different routes — one from a user-supplied path
+ * or a folder picker, the other from `os.homedir()` — so the alias mismatch is
+ * reachable. Best-effort: falls back to the input when the path cannot be
+ * resolved (a not-yet-created directory resolves to itself, which is correct
+ * for this comparison).
+ *
+ * Exported because the CLI's `resolve-project-root` and the desktop's
+ * `folder-admission` need the identical comparison for their own ancestor
+ * walks. They used to carry byte-identical copies kept in sync by drift
+ * comments; the server package is below both in the dependency graph, so one
+ * export lets TypeScript catch what the comments only asked for politely.
+ */
+export function canonicalizeForCompare(p: string): string {
+ try {
+ return realpathSync.native(p);
+ } catch {
+ return p;
+ }
+}
+
+/** `dir` IS the home directory (any spelling of it). */
+export function isHomeDir(dir: string, home: string = nodeHomedir()): boolean {
+ return canonicalizeForCompare(resolve(dir)) === canonicalizeForCompare(home);
+}
+
+/**
+ * Throw `HomeProjectRootError` when `dir` is the home directory. Call BEFORE
+ * any filesystem side effect, so a refusal leaves nothing behind.
+ */
+export function assertNotHomeProjectRoot(dir: string, home?: string): void {
+ if (isHomeDir(dir, home)) throw new HomeProjectRootError(resolve(dir));
+}
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 963dfeee2..b915fe241 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -224,6 +224,12 @@ export {
type InstalledAgentScheme,
} from './handoff-api.ts';
export { type ProjectHeadState, readProjectHeadState } from './head-watcher.ts';
+export {
+ assertNotHomeProjectRoot,
+ canonicalizeForCompare,
+ HomeProjectRootError,
+ isHomeDir,
+} from './home-project-root.ts';
export {
createStreamingErrorWriter,
errorResponse,
diff --git a/packages/server/src/init-project.ts b/packages/server/src/init-project.ts
index 7ca5bde6e..0d4dc3a33 100644
--- a/packages/server/src/init-project.ts
+++ b/packages/server/src/init-project.ts
@@ -22,6 +22,7 @@ import {
PROJECT_SKILL_PROJECTION_IGNORE_PATHS,
} from '@inkeep/open-knowledge-core';
import { tracedMkdirSync, tracedWriteFileSync } from './fs-traced.ts';
+import { assertNotHomeProjectRoot } from './home-project-root.ts';
/**
* Project config filename inside `.ok/`. Constant lives here (not in core)
@@ -341,6 +342,10 @@ export interface InitContentResult {
* scaffold write to whatever target the attacker chose.
*/
export function initContent(projectDir: string, options?: InitContentOptions): InitContentResult {
+ // `~/.ok/` is OpenKnowledge's user-global directory, so scaffolding a project
+ // at home writes `config.yml` into the user-global store. Refused here rather
+ // than per-caller because this is where all five scaffold entry points meet.
+ assertNotHomeProjectRoot(projectDir);
const okDir = resolve(projectDir, OK_DIR);
const created: string[] = [];
const updated: string[] = [];
diff --git a/packages/server/src/project-git.ts b/packages/server/src/project-git.ts
index 31be15fce..fd97b7b07 100644
--- a/packages/server/src/project-git.ts
+++ b/packages/server/src/project-git.ts
@@ -24,6 +24,7 @@ import {
GitTooOldError,
} from './git-preflight.ts';
import { emitPreflightFailureSpan } from './git-preflight-telemetry.ts';
+import { assertNotHomeProjectRoot } from './home-project-root.ts';
import { getLogger } from './logger.ts';
const execFileAsync = promisify(execFile);
@@ -248,6 +249,10 @@ async function isInsideExistingWorkTree(gitBin: string, cwd: string): Promise<bo
*/
export async function ensureProjectGit(projectRoot: string): Promise<EnsureProjectGitResult> {
const abs = resolve(projectRoot);
+ // `git init` in the user's home directory is the loudest way this goes wrong,
+ // and every scaffold entry point reaches here. Refused before the `.git`
+ // probes so no branch can init, repair, or adopt a repo at home.
+ assertNotHomeProjectRoot(abs);
const gitPath = resolve(abs, '.git');
const headPath = resolve(gitPath, 'HEAD');