Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): stop reading repo content as skill work (PRD-8087) (#3629)
tim-inkeepf2f94b5f5907
diff --git a/packages/app/src/components/navigation-targets.test.ts b/packages/app/src/components/navigation-targets.test.tsindex d28066d91..864398d1d 100644--- a/packages/app/src/components/navigation-targets.test.ts+++ b/packages/app/src/components/navigation-targets.test.ts@@ -1,5 +1,9 @@import { DOCUMENT_OPEN_BYTE_LIMIT } from '@inkeep/open-knowledge-core';-import { describe, expect, test } from 'vitest';+import { afterEach, describe, expect, test } from 'vitest';+import {+ __resetKnownProjectSkillDirsForTests,+ setKnownProjectSkillDirs,+} from '@/lib/known-skill-dirs';import {deriveKnownFolderPaths,docNameForNavigationTarget,@@ -13,6 +17,10 @@ import {} from './navigation-targets';describe('isSkillFocusedTarget', () => {+ afterEach(() => {+ __resetKnownProjectSkillDirsForTests();+ });+const doc = (docName: string): ResolvedNavigationTarget => ({kind: 'doc',target: docName,@@ -34,17 +42,33 @@ describe('isSkillFocusedTarget', () => {expect(isSkillFocusedTarget(doc('__skill__/global/demo'))).toBe(true);});- test('true for a bundle reached through a symlinked skill dir', () => {+ test('true for a bundle reached through a symlinked skill dir, once the list names it', () => {// A skill dir can be a symlink to somewhere else inside the content dir, so// the same bytes also index under the real path. Following a `references/…`// link out of the skill can land on that name — same file, no dot-dir — and// dropping to Files there looked like the Skills surface had broken.+ //+ // Nothing in that path distinguishes it from ordinary repo content, so the+ // real location is what settles it: `/api/skills` reports the alias as+ // `path` and this location as `canonicalPath`.+ setKnownProjectSkillDirs(new Set(['plugins/ok/skills/bake-lume-golden']));expect(isSkillFocusedTarget(doc('plugins/ok/skills/bake-lume-golden/references/version-pinning')),).toBe(true);expect(isSkillFocusedTarget(doc('plugins/ok/skills/bake-lume-golden/SKILL'))).toBe(true);});+ test('false for an unregistered bundle-shaped path', () => {+ // A repo that AUTHORS skills keeps bundles at an ordinary path and installs+ // copies into the host roots. The authored files are content — classifying+ // them as skill work pulled the sidebar off Files on nearly every click,+ // onto a surface whose tree has no row for them.+ expect(+ isSkillFocusedTarget(doc('packages/design-ai/skills/ooui/references/layout-and-interaction')),+ ).toBe(false);+ expect(isSkillFocusedTarget(doc('packages/design-ai/skills/ooui/SKILL'))).toBe(false);+ });+test('false for plain docs, folders, assets, and no target', () => {expect(isSkillFocusedTarget(doc('notes/daily'))).toBe(false);expect(isSkillFocusedTarget({ kind: 'folder', target: 'docs', folderPath: 'docs' })).toBe(diff --git a/packages/app/src/editor/DocumentContext.dom.test.tsx b/packages/app/src/editor/DocumentContext.dom.test.tsxindex 53e1c0984..7f892611f 100644--- a/packages/app/src/editor/DocumentContext.dom.test.tsx+++ b/packages/app/src/editor/DocumentContext.dom.test.tsx@@ -6,6 +6,10 @@ import { afterEach, describe, expect, test, vi } from 'vitest';import { Toaster } from '@/components/ui/sonner';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';import { hashFromAssetPath } from '@/lib/doc-hash';+import {+ __resetKnownProjectSkillDirsForTests,+ setKnownProjectSkillDirs,+} from '@/lib/known-skill-dirs';import { emitLocalMenuAction } from '@/lib/local-menu-action-bus';import {consumeHashNavigationSuppression,@@ -30,6 +34,16 @@ vi.doMock('@/lib/use-collab-url', () => ({}),}));+// The surface decision reads the known-skill-dirs store, which `useSkills`+// publishes. Mocking the hook is what makes the "list has not landed yet" ->+// "list landed" transition drivable from a test: the provider subscribes to this+// status, so flipping it is what re-runs the per-surface tracking effect.+let mockSkillsStatus: 'idle' | 'loading' | 'ready' = 'idle';++vi.doMock('@/hooks/use-skills', () => ({+ useSkills: () => ({ status: mockSkillsStatus, data: [] }),+}));+const { DocumentProvider, useDocumentContext } = await import('./DocumentContext');const PINNED_TAB_ID = docTabId('Pinned.md');@@ -1983,3 +1997,74 @@ describe('DocumentContext skills-surface new tabs', () => {expect(activeNewTabId()).toBe(first);});});++describe('DocumentContext skills-surface classification without a loaded skills list', () => {+ afterEach(() => {+ mockSkillsStatus = 'idle';+ __resetKnownProjectSkillDirsForTests();+ window.localStorage.clear();+ window.location.hash = '';+ cleanup();+ });++ function seedSingleDocSession(tabId: string) {+ window.localStorage.setItem(+ localTabSessionStorageKey(window.location.origin),+ JSON.stringify(+ persistedTabSession([tabId], [], tabId, new Date('2026-05-13T00:00:00.000Z').toISOString()),+ ),+ );+ }++ // The reported bug, at the rendering level: a repo that authors skills keeps+ // bundles at an ordinary path. Those files are content, so the sidebar must+ // stay on Files when one is active.+ test('an ordinary doc under a non-dot skills/ dir leaves the surface on Files', async () => {+ seedSingleDocSession(+ docTabId('packages/design-ai/skills/ooui/references/layout-and-interaction'),+ );+ mockCollabUrl = 'ws://localhost:1234';++ render(+ <DocumentProvider>+ <CloseActiveHarness />+ </DocumentProvider>,+ );++ await waitFor(() => expect(screen.getByTestId('skill-focused')).toBeTruthy());+ expect(screen.getByTestId('skill-focused').textContent).toBe('false');+ });++ // The regression the review caught: a bundle whose only evidence is+ // /api/skills classifies as Files before the list lands. That answer must not+ // outlive the list — the provider subscribes to the hook's status, so arrival+ // re-derives the surface.+ test('an aliased bundle doc re-derives to Skills when the list lands', async () => {+ seedSingleDocSession(docTabId('plugins/ok/skills/bake-lume-golden/SKILL'));+ mockCollabUrl = 'ws://localhost:1234';++ const { rerender } = render(+ <DocumentProvider>+ <CloseActiveHarness />+ </DocumentProvider>,+ );++ // Pre-list: shape is all there is, and a non-dot path is indistinguishable+ // from ordinary repo content.+ await waitFor(() => expect(screen.getByTestId('skill-focused')).toBeTruthy());+ expect(screen.getByTestId('skill-focused').textContent).toBe('false');++ // The list lands and names the dir.+ setKnownProjectSkillDirs(new Set(['plugins/ok/skills/bake-lume-golden']));+ mockSkillsStatus = 'ready';+ await act(async () => {+ rerender(+ <DocumentProvider>+ <CloseActiveHarness />+ </DocumentProvider>,+ );+ });++ await waitFor(() => expect(screen.getByTestId('skill-focused').textContent).toBe('true'));+ });+});diff --git a/packages/app/src/editor/DocumentContext.tsx b/packages/app/src/editor/DocumentContext.tsxindex b173b547f..e1bd26061 100644--- a/packages/app/src/editor/DocumentContext.tsx+++ b/packages/app/src/editor/DocumentContext.tsx@@ -8,6 +8,7 @@ import { createContext, type ReactNode, use, useEffect, useRef, useState } fromimport type { ResolvedNavigationTarget } from '@/components/navigation-targets';import { docNameForNavigationTarget, isSkillFocusedTarget } from '@/components/navigation-targets';import { consumePrewarmClick } from '@/components/prewarm-correlation';+import { useSkills } from '@/hooks/use-skills';import {assetPathFromHash,docNameFromHash,@@ -838,6 +839,22 @@ export function DocumentProvider({ children }: { children: ReactNode }) {currentPane.openTabs,currentPane.newTabIds,);+ // Subscribed, not consumed: the Files/Skills surface decision reads the+ // project's known skill dirs synchronously via `isSkillBundleShapedPath`, and+ // `useSkills` is what publishes them. Mounting it HERE (unconditionally) does+ // two things nothing else does:+ //+ // - re-renders this provider when `/api/skills` lands, so `skillFocused`+ // recomputes for a symlinked or custom-rooted bundle instead of sitting on+ // the shape-only answer until an unrelated render happens to occur;+ // - breaks the circular gate — `EditorTabs` fetches only when it already+ // recognises a skill tab, so a doc recognisable ONLY through the list would+ // never trigger the fetch that recognises it.+ //+ // Costs no extra request in the default configuration: `SkillsSidebarSection`+ // already calls `useSkills` on every render and mounts whenever the Skills+ // section is enabled, and the hook shares one module-level in-flight request.+ const skillsListStatus = useSkills().status;const [skillsSidebar, setSkillsSidebarState] = useState<boolean | null>(null);// Per-surface active-tab memory: switching Files/Skills restores the tab you// last had active in that surface (or clears to its empty/home state). Kept in@@ -985,11 +1002,24 @@ export function DocumentProvider({ children }: { children: ReactNode }) {// Remember the active tab per surface so a Files↔Skills toggle can restore it.// Runs on every activeTabId change (incl. session restore) so both surfaces// stay current even before the first toggle.+ //+ // Also re-runs when the skills list settles. A tab restored on first paint is+ // filed before `/api/skills` answers, so a bundle known only to that list lands+ // under `files`; leaving it there survives into localStorage and pulls the+ // toggle straight back across on every press. Re-filing on arrival — and+ // releasing the slot it was wrongly filed under — is what keeps the pre-list+ // guess from outliving the answer.+ //+ // biome-ignore lint/correctness/useExhaustiveDependencies: `skillsListStatus` is a re-run trigger, not an input — the body reads the list through `isSkillTabId`, which is not reactive on its own.useEffect(() => {if (!activeTabId) return;const mode = isSkillTabId(activeTabId) ? 'skills' : 'files';+ const previousMode = mode === 'skills' ? 'files' : 'skills';activeTabByModeRef.current[mode] = activeTabId;- }, [activeTabId]);+ if (activeTabByModeRef.current[previousMode] === activeTabId) {+ activeTabByModeRef.current[previousMode] = null;+ }+ }, [activeTabId, skillsListStatus]);// Show only the current surface's tabs. Filtering here (not in EditorTabs)// keeps the strip, keyboard cycle/jump, and drag-reorder all consistent;diff --git a/packages/app/src/editor/editor-tabs.test.ts b/packages/app/src/editor/editor-tabs.test.tsindex c16e316cb..b5d493e0a 100644--- a/packages/app/src/editor/editor-tabs.test.ts+++ b/packages/app/src/editor/editor-tabs.test.ts@@ -1,4 +1,8 @@-import { describe, expect, test, vi } from 'vitest';+import { afterEach, describe, expect, test, vi } from 'vitest';+import {+ __resetKnownProjectSkillDirsForTests,+ setKnownProjectSkillDirs,+} from '@/lib/known-skill-dirs';import {addPinnedTab,applyDragPinMutation,@@ -782,6 +786,39 @@ describe('preview-tab integration', () => {skills: skillTab,});});++ test('a skills tab known only from /api/skills survives a parse that runs before the list', () => {+ // The session is read synchronously from localStorage on first paint; the+ // skills list is a network round trip away. For a bundle whose ONLY evidence+ // is that list — a symlinked or custom-rooted one, at a non-dot path — the+ // pre-list answer is "not a skill", and dropping the slot here would persist+ // that guess: the parse feeds `activeTabByModeRef`, the persist effect writes+ // the ref straight back out, and the Skills toggle then opens its empty home+ // instead of the doc the user left open.+ //+ // So the parse must be LOSSLESS while classification is still unanswerable,+ // and strict again once the list has settled.+ const fileTab = docTabId('docs/a');+ const aliasedSkillTab = docTabId('plugins/ok/skills/bake-lume-golden/SKILL');+ const state = createEditorTabSessionState(+ editorWorkspace([fileTab, aliasedSkillTab], [], aliasedSkillTab),+ { files: fileTab, skills: aliasedSkillTab },+ () => new Date('2026-05-06T00:00:00Z'),+ );++ // List not yet loaded: keep it rather than guess.+ expect(parseEditorTabSessionState(state).activeTabByMode.skills).toBe(aliasedSkillTab);++ // List settled and it IS a skill dir: still kept, now on the evidence.+ setKnownProjectSkillDirs(new Set(['plugins/ok/skills/bake-lume-golden']));+ expect(parseEditorTabSessionState(state).activeTabByMode.skills).toBe(aliasedSkillTab);++ // List settled and it is NOT a skill dir: the stale-state guard applies again.+ setKnownProjectSkillDirs(new Set(['.claude/skills/other']));+ expect(parseEditorTabSessionState(state).activeTabByMode.skills).toBeNull();++ __resetKnownProjectSkillDirsForTests();+ });});describe('applyDragPinMutation — drag-mutable pin state', () => {@@ -927,22 +964,72 @@ describe('skill discriminators reject template content shapes', () => {// skills.sh carries `tests.md` + `mocking.md` at its root. Those are ordinary// content docs, so the surface decision is the only thing keeping the sidebar// on Skills when the user clicks one straight after installing.- const companionDocs = [+ // Dot-rooted bundles are matched by SHAPE — no skills list needed, which is+ // what keeps first paint correct (the tab-session parser runs before any fetch).+ const dotRootedCompanionDocs = ['.claude/skills/tdd/mocking','.claude/skills/tdd/tests','.agents/skills/grill-me/GUIDE',- 'plugins/ok/skills/demo/notes/deep',];- test('isSkillBundleShapedPath is true for companion docs inside a bundle', () => {- for (const doc of companionDocs) expect(isSkillBundleShapedPath(doc)).toBe(true);+ // A bundle reached by a path no host root names — the symlink-alias case: a+ // repo keeping bundles in `plugins/<x>/skills/` and linking them into+ // `.agents/`. Shape cannot see this; only `/api/skills` (`canonicalPath`) can.+ const aliasedCompanionDoc = 'plugins/ok/skills/demo/notes/deep';++ afterEach(() => {+ __resetKnownProjectSkillDirsForTests();});- test('isSkillTabId keeps a bundle companion doc on the Skills surface', () => {- for (const doc of companionDocs) expect(isSkillTabId(docTabId(doc))).toBe(true);+ test('isSkillBundleShapedPath is true for companion docs inside a dot-rooted bundle', () => {+ for (const doc of dotRootedCompanionDocs) expect(isSkillBundleShapedPath(doc)).toBe(true);+ });++ test('isSkillTabId keeps a dot-rooted bundle companion doc on the Skills surface', () => {+ for (const doc of dotRootedCompanionDocs) expect(isSkillTabId(docTabId(doc))).toBe(true);+ });++ test('an aliased bundle needs the skills list, and gets the surface once it lands', () => {+ // Before `/api/skills` answers, shape is all there is — and a non-dot path+ // is indistinguishable from ordinary repo content, so it reads as Files.+ expect(isSkillBundleShapedPath(aliasedCompanionDoc)).toBe(false);++ setKnownProjectSkillDirs(new Set(['plugins/ok/skills/demo']));+ expect(isSkillBundleShapedPath(aliasedCompanionDoc)).toBe(true);+ expect(isSkillTabId(docTabId(aliasedCompanionDoc))).toBe(true);});test('isSkillBundleShapedPath is false for the bundle dir itself', () => {expect(isSkillBundleShapedPath('.claude/skills/tdd')).toBe(false);+ // Also when the list names it: a doc AT the bundle dir is not a file inside one.+ setKnownProjectSkillDirs(new Set(['.claude/skills/tdd', 'plugins/ok/skills/demo']));+ expect(isSkillBundleShapedPath('.claude/skills/tdd')).toBe(false);+ expect(isSkillBundleShapedPath('plugins/ok/skills/demo')).toBe(false);+ });++ // A repo that authors skills keeps bundles at an ordinary path and+ // installs copies into the host roots. Those authored files are content: the+ // reporter browsed them in Files and the sidebar kept pulling him to Skills,+ // where the tree has no row for them. Nothing about the path shape can tell+ // them apart from a real skill — only whether OK knows the dir.+ test('ordinary repo content under a non-dot skills/ dir stays on the Files surface', () => {+ const authoredContent = [+ 'packages/design-ai/skills/ooui/references/layout-and-interaction',+ 'packages/design-ai/skills/ooui/SKILL',+ 'packages/design-ai/skills/animate/RECIPES',+ 'skills/README',+ 'docs/skills/overview/index',+ ];+ for (const doc of authoredContent) {+ expect(isSkillBundleShapedPath(doc)).toBe(false);+ expect(isSkillTabId(docTabId(doc))).toBe(false);+ }++ // Registering one of them as a skill root is the ONLY thing that changes it.+ setKnownProjectSkillDirs(new Set(['packages/design-ai/skills/ooui']));+ expect(+ isSkillBundleShapedPath('packages/design-ai/skills/ooui/references/layout-and-interaction'),+ ).toBe(true);+ expect(isSkillBundleShapedPath('packages/design-ai/skills/animate/RECIPES')).toBe(false);});});diff --git a/packages/app/src/editor/editor-tabs.ts b/packages/app/src/editor/editor-tabs.tsindex 93a9cd5a6..8c009a31f 100644--- a/packages/app/src/editor/editor-tabs.ts+++ b/packages/app/src/editor/editor-tabs.ts@@ -14,6 +14,7 @@ import {type SkillPreviewFlavor,type SkillPreviewHashTarget,} from '@/lib/doc-hash';+import { getKnownProjectSkillDirs, knownSkillDirsSettled } from '@/lib/known-skill-dirs';import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';import { skillDisplayName } from '@/lib/skill-scope';import {@@ -41,14 +42,27 @@ export interface EditorTabSessionState {focusedPaneId: string;}-/** An open-tab id valid for `surface`, else null (guards stale/hand-edited state). */+/** An open-tab id valid for `surface`, else null (guards stale/hand-edited state).+ *+ * The surface check is skipped for the skills slot until `/api/skills` has+ * answered once. This parse runs on FIRST PAINT, synchronously off localStorage,+ * while the list is still in flight — so a bundle whose only evidence is that+ * list (symlinked, or at a registered custom root, both of which sit at non-dot+ * paths) reads as Files here. Dropping the slot on that reading does not just+ * lose a classification, it PERSISTS one: the parse feeds `activeTabByModeRef`,+ * the persist effect writes the ref back to localStorage, and the Skills toggle+ * then opens its empty home instead of the doc the user left open. Keeping the+ * value until the answer is real makes the pre-list parse lossless; once the+ * list settles the guard applies in full.+ */function surfaceActiveTab(value: unknown,surface: 'files' | 'skills',openTabs: readonly string[],): string | null {if (typeof value !== 'string' || !openTabs.includes(value)) return null;- return isSkillTabId(value) === (surface === 'skills') ? value : null;+ if (isSkillTabId(value) === (surface === 'skills')) return value;+ return surface === 'skills' && !knownSkillDirsSettled() ? value : null;}/** A fresh empty session — factory (not a shared const) so callers can't alias it. */@@ -396,14 +410,46 @@ export function isSkillDocName(docName: string): boolean {/*** A bundle laid out like a skill but reached by a path `isSkillDocName` does not- * name — the host roots it knows all start with a dot (`.claude/skills/…`).+ * name. Drives the Files/Skills SURFACE decision only.+ *+ * Two halves, and both are load-bearing:+ *+ * SHAPE — a skills dir under a DOT-directory root. Every project root in+ * `EDITOR_PROJECT_SKILL_ROOT` is one (`.claude`, `.cursor`, `.codex`, `.github`,+ * `.opencode`, `.pi`), as is the `.agents` hub. The dot anchor is what keeps+ * ordinary repo content out: a repo that keeps its own markdown under+ * `packages/<x>/skills/<name>/` is authoring files, not addressing OK skills,+ * and reading it as skill work hijacked the sidebar away from Files on nearly+ * every click.*- * A skill dir can be a SYMLINK to somewhere else inside the content dir (a repo- * that keeps its skills in `plugins/<x>/skills/` and links them into `.agents/`).- * Both paths then index as documents, and a relative link in the body can resolve- * to the real one — same bytes, a name that reads as ordinary content. Following- * a reference out of a skill would drop the sidebar to Files, which looked like- * the Skills surface had broken.+ * DATA — bundle dirs `/api/skills` actually reported for this project. Covers+ * what no path shape can see:+ * 1. A skill dir that is a SYMLINK to elsewhere in the content dir (a repo+ * keeping bundles in `plugins/<x>/skills/` and linking them into+ * `.agents/`). Both paths index as documents and a relative link in the+ * body resolves to the real, non-dot one; `canonicalPath` names it.+ * 2. A ledger-registered custom root, which is not required to be dotted.+ *+ * Neither half subsumes the other. `/api/skills` returns one row per content+ * identity and `path` names only the ELECTED CANONICAL dir — same-content copies+ * live in `hosts`/`copyDirs` — so a doc under a non-canonical copy is absent from+ * the data, and shape is what catches it. That covers the copies fan-out actually+ * writes, which land in editor host dirs (`.agents/skills/x/...` when `.claude`+ * won election).+ *+ * KNOWN GAP: a copy at a NON-dot CUSTOM root is named by neither half and reads+ * as Files. A custom root always loses canonical election (it is absent from+ * `SKILL_CANONICAL_PRECEDENCE`), so its dir never appears as `path`; being a copy+ * rather than a symlink, it gets no `canonicalPath` either; and being un-dotted,+ * shape misses it. It surfaces only as `customPlacements`/`hosts`, which this+ * predicate deliberately does NOT read: those are recorded against `projectDir`+ * while doc names are `contentDir`-relative, and under a configured `content.dir`+ * the two differ — reading them would trade a narrow miss for a wrong prefix.+ *+ * Stays synchronous and TOTAL: this is reached from the `useState` initializer+ * that parses the persisted tab session on first paint, before any fetch. An+ * empty known-dirs set degrades to the shape answer; it never yields "unknown",+ * which would drop a persisted `activeTabByMode.skills` entry at parse time.** Deliberately NOT folded into `isSkillDocName`: that parser also feeds the CC1* link index and managed-artifact resolution, where a looser shape would mint@@ -417,10 +463,20 @@ export function isSkillDocName(docName: string): boolean {* user clicked one — right after installing, when the tree has the bundle* expanded and those rows are the obvious thing to click.*/-const SKILL_BUNDLE_SHAPED_PATH = /(?:^|\/)skills\/[^/]+\/.+$/;+const SKILL_BUNDLE_ROOT_PATH = /(?:^|\/)\.[A-Za-z0-9_-]+\/skills\/[^/]+\/.+$/;export function isSkillBundleShapedPath(docName: string): boolean {- return SKILL_BUNDLE_SHAPED_PATH.test(docName);+ if (SKILL_BUNDLE_ROOT_PATH.test(docName)) return true;+ const known = getKnownProjectSkillDirs();+ if (known.size === 0) return false;+ // Walk ancestors from the parent dir up. Starting at the PARENT (not+ // `docName` itself) is what keeps a bundle dir addressed as a doc —+ // `.claude/skills/tdd` — from matching itself: the dir is a skill, a document+ // AT that name is not a file inside one.+ for (let cut = docName.lastIndexOf('/'); cut > 0; cut = docName.lastIndexOf('/', cut - 1)) {+ if (known.has(docName.slice(0, cut))) return true;+ }+ return false;}/**diff --git a/packages/app/src/hooks/use-skills.ts b/packages/app/src/hooks/use-skills.tsindex c6a7c0877..cfa5c0748 100644--- a/packages/app/src/hooks/use-skills.ts+++ b/packages/app/src/hooks/use-skills.ts@@ -6,6 +6,7 @@ import {subscribeToDocumentsChanged,subscribeToSkillsChanged,} from '@/lib/documents-events';+import { projectSkillBundleDirs, setKnownProjectSkillDirs } from '@/lib/known-skill-dirs';import { parseApiError } from '@/lib/parse-api-error';import type { AsyncState } from './use-folder-config';@@ -196,6 +197,11 @@ export function useSkills(options?: { enabled?: boolean }): AsyncState<readonlyreturn;}lastKnownSkills = parsed.data.skills;+ // The Files/Skills surface predicates read this synchronously, outside+ // render (`isSkillBundleShapedPath`). Publishing it here — rather than+ // deriving it in a component — is what lets a symlinked or+ // custom-rooted bundle keep its surface without a path-shape guess.+ setKnownProjectSkillDirs(projectSkillBundleDirs(parsed.data.skills));setState({ status: 'ready', data: parsed.data.skills });}).catch((err: unknown) => {diff --git a/packages/app/src/lib/known-skill-dirs.test.ts b/packages/app/src/lib/known-skill-dirs.test.tsnew file mode 100644index 000000000..fba7cd20b--- /dev/null+++ b/packages/app/src/lib/known-skill-dirs.test.ts@@ -0,0 +1,70 @@+import type { SkillsListEntry } from '@inkeep/open-knowledge-core';+import { describe, expect, test } from 'vitest';+import { projectSkillBundleDirs } from '@/lib/known-skill-dirs';++/**+ * The two filters here are the load-bearing ones, and neither is visible in the+ * shape of the output — a regression in either produces a set that still looks+ * plausible while classifying the wrong documents.+ */+describe('projectSkillBundleDirs', () => {+ const entry = (over: Partial<SkillsListEntry>): SkillsListEntry => ({+ scope: 'project',+ name: 'demo',+ path: '.claude/skills/demo/SKILL.md',+ installed: true,+ hosts: [],+ ...over,+ });++ test('takes the bundle DIR, not the SKILL.md file path', () => {+ expect(projectSkillBundleDirs([entry({})]).has('.claude/skills/demo')).toBe(true);+ expect(projectSkillBundleDirs([entry({})]).has('.claude/skills/demo/SKILL.md')).toBe(false);+ });++ test('excludes global-scope rows, which collide byte-for-byte with project doc names', () => {+ // `.agents/skills/shared/SKILL.md` is a real HOME-relative path for a global+ // skill AND a real contentDir-relative doc name for a project one. Nothing in+ // the string separates them, so `scope` is the only discriminator — without+ // it a global skill silently claims a project document, which is this bug+ // running in the opposite direction.+ const dirs = projectSkillBundleDirs([+ entry({ scope: 'global', name: 'shared', path: '.agents/skills/shared/SKILL.md' }),+ entry({ scope: 'project', name: 'owned', path: '.agents/skills/owned/SKILL.md' }),+ ]);+ expect(dirs.has('.agents/skills/shared')).toBe(false);+ expect(dirs.has('.agents/skills/owned')).toBe(true);+ });++ test('excludes managed rows, whose path is projectDir-relative not contentDir-relative', () => {+ // Under a configured `content.dir` the built-in row's base differs from every+ // other project row's, so its path is not a valid doc-name prefix. Built-ins+ // sit at dot-roots, where shape covers them anyway.+ const dirs = projectSkillBundleDirs([+ entry({+ managed: true,+ name: 'open-knowledge',+ path: '.claude/skills/open-knowledge/SKILL.md',+ }),+ ]);+ expect(dirs.has('.claude/skills/open-knowledge')).toBe(false);+ });++ test('includes both the alias and the canonical location of a symlinked bundle', () => {+ // Both index as documents, so the surface must not depend on which one the+ // user reached.+ const dirs = projectSkillBundleDirs([+ entry({+ name: 'linked',+ path: '.agents/skills/linked/SKILL.md',+ canonicalPath: 'plugins/ok/skills/linked/SKILL.md',+ }),+ ]);+ expect(dirs.has('.agents/skills/linked')).toBe(true);+ expect(dirs.has('plugins/ok/skills/linked')).toBe(true);+ });++ test('a path with no directory component contributes nothing', () => {+ expect(projectSkillBundleDirs([entry({ path: 'SKILL.md' })]).size).toBe(0);+ });+});diff --git a/packages/app/src/lib/known-skill-dirs.ts b/packages/app/src/lib/known-skill-dirs.tsnew file mode 100644index 000000000..752039495--- /dev/null+++ b/packages/app/src/lib/known-skill-dirs.ts@@ -0,0 +1,85 @@+import type { SkillsListEntry } from '@inkeep/open-knowledge-core';++/**+ * The project-scoped bundle dirs OK actually knows to be skills — the data half+ * of the Files/Skills surface decision (`isSkillBundleShapedPath`).+ *+ * Plain module state, not React state, because the predicates that read it run+ * OUTSIDE render: `isSkillTabId` is reached from the `useState` initializer that+ * parses the persisted tab session on first paint, before any fetch has+ * happened. The predicates therefore must stay synchronous and total — an empty+ * set means "nothing known yet", never "not a skill", and the shape half answers+ * alone until `/api/skills` lands.+ *+ * Written by `useSkills` as the list settles; read by the surface predicates.+ * One project per renderer (the desktop spawns a BrowserWindow per project and+ * focuses an existing window rather than reusing one — `window-manager.ts`), so+ * module scope cannot leak one project's dirs into another's.+ */+let knownDirs: ReadonlySet<string> = new Set();++/**+ * Has `/api/skills` answered at least once this session?+ *+ * An empty `knownDirs` is ambiguous on its own: it means "no project skills"+ * AND "the list has not landed yet", and the two demand opposite handling at+ * the one place that writes DURABLE state. The tab-session parse runs on first+ * paint, synchronously off localStorage, while the list is a network round trip+ * away — so a doc whose only evidence is the list classifies as Files there. If+ * the parse acted on that, it would drop the remembered Skills tab and the+ * persist effect would write the guess back out, making a timing artifact+ * permanent. This flag lets that one call site stay lossless until the answer is+ * real, without weakening the guard for projects that legitimately have none.+ */+let settled = false;++/** Bundle dirs of every project-scope skill in a `/api/skills` payload.+ *+ * Three properties of that payload drive the filtering, and all three bite:+ *+ * - `path` is the SKILL.md FILE, not the bundle dir — so it is `dirname`d.+ * - GLOBAL rows are home-relative and collide byte-for-byte with project doc+ * names (`.agents/skills/foo/SKILL.md` is both a real home path and a real+ * contentDir-relative doc name). `scope` is the ONLY discriminator, so a+ * global row must never enter this set or it would claim a project document.+ * - The built-in row is `projectDir`-relative while every other project row is+ * `contentDir`-relative, so under a configured `content.dir` it is not a+ * valid doc-name prefix. Built-ins live at dot-roots anyway, where the shape+ * half already covers them.+ *+ * `canonicalPath` is included alongside `path`: for a symlinked bundle they are+ * the alias and the real contentDir-relative location, and BOTH index as+ * documents.+ */+export function projectSkillBundleDirs(skills: readonly SkillsListEntry[]): ReadonlySet<string> {+ const dirs = new Set<string>();+ for (const skill of skills) {+ if (skill.scope !== 'project') continue;+ if (skill.managed === true) continue;+ for (const filePath of [skill.path, skill.canonicalPath]) {+ if (filePath === undefined) continue;+ const slash = filePath.lastIndexOf('/');+ if (slash > 0) dirs.add(filePath.slice(0, slash));+ }+ }+ return dirs;+}++export function getKnownProjectSkillDirs(): ReadonlySet<string> {+ return knownDirs;+}++export function knownSkillDirsSettled(): boolean {+ return settled;+}++export function setKnownProjectSkillDirs(next: ReadonlySet<string>): void {+ knownDirs = next;+ settled = true;+}++/** Test-only reset — module state outlives a single test file's renders. */+export function __resetKnownProjectSkillDirsForTests(): void {+ knownDirs = new Set();+ settled = false;+}diff --git a/packages/app/src/lib/managed-artifact-doc-name.test.ts b/packages/app/src/lib/managed-artifact-doc-name.test.tsindex 6c1d940d0..27627628c 100644--- a/packages/app/src/lib/managed-artifact-doc-name.test.ts+++ b/packages/app/src/lib/managed-artifact-doc-name.test.ts@@ -1,6 +1,11 @@import type { SkillsListEntry } from '@inkeep/open-knowledge-core';-import { describe, expect, test } from 'vitest';+import { afterEach, describe, expect, test } from 'vitest';import { filterOpenTabsForKnownTargets, isSkillTabId } from '@/editor/editor-tabs';+import {+ __resetKnownProjectSkillDirsForTests,+ projectSkillBundleDirs,+ setKnownProjectSkillDirs,+} from '@/lib/known-skill-dirs';import { skillEntryFileLiveDocName, skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';/**@@ -59,6 +64,10 @@ describe('skillEntryFileLiveDocName', () => {});describe('an aliased skill tab survives a page-list sync', () => {+ afterEach(() => {+ __resetKnownProjectSkillDirsForTests();+ });+// `/api/pages` lists the canonical name only. The tab has to survive either// way now (skill docs are the reconciler's to close), but the doc the sidebar// opens must still be the indexed one — opening the alias would put a second@@ -74,6 +83,24 @@ describe('an aliased skill tab survives a page-list sync', () => {test('the canonical name still classifies as a Skills-surface tab', () => {// Otherwise the tab survives but lands in the Files tab strip.+ //+ // The canonical location is an ORDINARY path — nothing in `plugins/ok/skills/…`+ // distinguishes it from a repo that merely keeps markdown under a folder+ // called `skills`. So the surface decision reads the same+ // `/api/skills` entry the doc name was built from: `canonicalPath` is what+ // makes this location a skill, and no path-shape guess can substitute.+ setKnownProjectSkillDirs(projectSkillBundleDirs([aliased]));expect(isSkillTabId(skillEntryLiveDocName(aliased))).toBe(true);});++ test('the derived set carries the alias dir as well as the canonical one', () => {+ // `path` and `canonicalPath` both index as documents, so both belong in the+ // set. Asserted at the SET level on purpose: `.agents/skills/bug-triage/SKILL`+ // is already a skill doc by shape (`.agents` is a host root), so asserting+ // `isSkillTabId` on it would pass with the seeding removed — it would pin the+ // dot-root half while reading like a check of the derivation.+ expect(projectSkillBundleDirs([aliased])).toEqual(+ new Set(['.agents/skills/bug-triage', 'plugins/ok/skills/bug-triage']),+ );+ });});