Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

chore(ok): skills cleanup deferred from the marketplace PR (PRD-7707) (#3323)

tim-inkeep7cfd0bd6314e
diff --git a/.changeset/skill-bundle-companion-docs-surface.md b/.changeset/skill-bundle-companion-docs-surface.md
new file mode 100644
index 000000000..fcf53cfeb
--- /dev/null
+++ b/.changeset/skill-bundle-companion-docs-surface.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Opening a markdown file that a skill ships beside its SKILL.md no longer throws you out of the Skills sidebar. Many skills carry companion docs at the root of their bundle rather than under `references/`, and clicking one right after installing switched the sidebar to Files, which read as the skill refusing to open. Every file inside a skill bundle now stays on the Skills surface.
diff --git a/.changeset/skill-scope-move-keeps-skills-surface.md b/.changeset/skill-scope-move-keeps-skills-surface.md
new file mode 100644
index 000000000..e5299b42b
--- /dev/null
+++ b/.changeset/skill-scope-move-keeps-skills-surface.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Moving a skill between project and global no longer drops you into the file tree. When the only tab open for that skill was one of its bundle files, the move closed that tab, left the Skills sidebar with nothing to show, and fell back to Files on an unrelated document. The open tab now follows the skill to its new scope, and companion files a bundle ships outside `references/` are recognized as part of the skill, so a move or a delete no longer strands their tab on a document that is gone.
diff --git a/.changeset/skills-list-staleness.md b/.changeset/skills-list-staleness.md
new file mode 100644
index 000000000..d32806838
--- /dev/null
+++ b/.changeset/skills-list-staleness.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+The skills list no longer gets stuck showing a skill's pre-change state after you install, remove, convert or move it. Every surface that shows skills shares one request to the server, and a refresh triggered by your change could latch onto a request that had already been sent before it — so the list settled on what was true a moment earlier and stayed there until something unrelated refreshed it. Refreshes now recognise a request as predating the change and issue their own instead.
diff --git a/.changeset/stale-provider-open-hang.md b/.changeset/stale-provider-open-hang.md
new file mode 100644
index 000000000..18be289ce
--- /dev/null
+++ b/.changeset/stale-provider-open-hang.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Opening a document in a window that has been idle no longer stalls on a blank editor for 30 seconds. If the window's connection to the server had dropped while it sat unused, the editor kept handing the document its dead connection and waited out the full sync timeout before recovering. It now reconnects the document up front, so it loads in the usual few hundred milliseconds.
diff --git a/packages/app/BUNDLE-SIZE.md b/packages/app/BUNDLE-SIZE.md
index ca047d6fe..0f97952c1 100644
--- a/packages/app/BUNDLE-SIZE.md
+++ b/packages/app/BUNDLE-SIZE.md
@@ -62,3 +62,5 @@ Combined-chunks 4.4->4.5 MB once every catalog held real translations rather tha
Combined-chunks 4.5->4.7 MB merging the ACP-highlighting branch onto the language catalogs: the two lazy features stack — eleven on-demand locale catalogs plus the curated shiki grammar chunk — and measured 4.6 MB locally, ~4.66 MB projected in CI at the ~1.4% local->CI ratio, 104 kB over the 4.5 ceiling that was set before the highlighter existed. The main app bundle and CSS stay under their limits; both features load nothing until used (a catalog on locale switch, the grammar chunk on the first fenced code block). Reclamation levers: trim the grammar list, or the catalog-weight notes above.
Combined-chunks 4.7->4.72 MB for uniform local-target classification and image failure states across the editor, Problems, Links, and source diagnostics. CI measured 4.71 MB, 8.53 kB over the prior ceiling, while the main app bundle remained at 418.08 kB against its 487 kB limit and CSS at 8.36 kB against 59 kB. The increase therefore records the feature's total chunk footprint rather than first-load growth; the pre-existing lazy-load levers above remain the reclamation path.
+
+Combined-chunks kept at 4.75 MB when merging main. Both sides had raised the same budget off a 4.7 MB base that had no headroom left: this branch to 4.75 for the gitignored-skill dialog (measured 364 B over, 0.008%), main to 4.72 for the entry above. The merged tree carries both features, so the resolution takes the higher ceiling rather than either side's number. CI measured 4.7 MB against 4.75 on the pre-merge branch head and the post-merge tree measures 4.69 MB locally, where local reads a little under CI. The lazy-load levers above remain the reclamation path.
diff --git a/packages/app/package.json b/packages/app/package.json
index 92099bfa0..782386f8a 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -53,7 +53,7 @@
{
"name": "all JS chunks combined (gzipped)",
"path": "dist/assets/*.js",
- "limit": "4.72 MB",
+ "limit": "4.75 MB",
"gzip": true,
"running": false
},
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index 6b0b6b795..1977b3fa3 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -26,6 +26,7 @@ import {
} from '@/components/navigation-targets';
import { PageListProvider, usePageList } from '@/components/PageListContext';
import { ReportBugMenuTrigger } from '@/components/ReportBugMenuTrigger';
+import { SkillTrackInGitDialog } from '@/components/SkillTrackInGitDialog';
import { SystemDocSubscriber } from '@/components/SystemDocSubscriber';
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar';
import { ValidationFreshness } from '@/components/ValidationFreshness';
@@ -595,6 +596,10 @@ function AppBody() {
<PageListProvider>
<SystemDocSubscriber />
<ValidationFreshness />
+ {/* Explains a skill that lists but can't open (gitignored bundle) and
+ offers the one-line fix. Mounted here because the guard fires from
+ the shared opener, which has no surface of its own. */}
+ <SkillTrackInGitDialog />
<NavigationHandler />
<ActiveTargetBridgePush />
<NewItemShortcutHandler />
diff --git a/packages/app/src/components/SkillInstallMenu.tsx b/packages/app/src/components/SkillInstallMenu.tsx
index fde1b44a1..ecdef3560 100644
--- a/packages/app/src/components/SkillInstallMenu.tsx
+++ b/packages/app/src/components/SkillInstallMenu.tsx
@@ -1,12 +1,8 @@
-import type {
- SkillInstallTarget,
- SkillsListEntry,
- SkillTargetEditor,
-} from '@inkeep/open-knowledge-core';
+import type { SkillInstallTarget, SkillsListEntry } from '@inkeep/open-knowledge-core';
import {
+ AGENTS_SKILLS_ROOT,
EDITOR_LABELS,
isSkillInstallTarget,
- SkillTargetEditorSchema,
} from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import { Folder, Settings as SettingsIcon } from 'lucide-react';
@@ -32,14 +28,17 @@ import {
skillOverlayKey,
subscribeToSkillOverlay,
} from '@/lib/skill-install-overlay-store';
-import { aliasSubscribersOf, customPlacementRoot, skillHostRootDir } from '@/lib/skill-scope';
+import {
+ deriveSkillInstallRows,
+ INSTALL_EDITORS,
+ type SkillInstallMenuSkill,
+} from '@/lib/skill-install-rows';
+import { aliasSubscribersOf, skillHostRootDir } from '@/lib/skill-scope';
import { placeSkill, putSkillFolderAction, setSkillSource, unplaceSkill } from '@/lib/skills-api';
-// The editors a project skill can install into — the narrowed `.options` of the
-// canonical schema, so this can never drift from the install verb + picker. The
-// editor toolbar badge reuses this for its installed-agent icon cluster (stable
-// order + `SkillTargetEditor` typing for `TargetIcon`).
-export const INSTALL_EDITORS: readonly SkillTargetEditor[] = SkillTargetEditorSchema.options;
+// Re-exported at its historical home: the editor toolbar badge imports it from
+// here for its installed-agent icon cluster.
+export { INSTALL_EDITORS } from '@/lib/skill-install-rows';
/**
* Width floor for any container holding {@link SkillInstallMenuItems}.
@@ -312,20 +311,7 @@ export function SkillInstallMenuItems({
* `symlinkedHosts` (when present) mark THE source row and link rows. Always
* passed (every install surface has a skill); the detail fields stay Partial
* because an un-imported preview carries only `{scope, name}`. */
- skill: Pick<SkillsListEntry, 'scope' | 'name'> &
- Partial<
- Pick<
- SkillsListEntry,
- | 'hosts'
- | 'symlinkedHosts'
- | 'path'
- | 'customPlacements'
- | 'hostAliases'
- | 'conflictHosts'
- | 'driftPaths'
- | 'installableEditors'
- >
- >;
+ skill: SkillInstallMenuSkill;
/** Opens the fork-resolution dialog for a conflicted editor's copy. */
onResolveFork?: (editor: string) => void;
/**
@@ -340,64 +326,26 @@ export function SkillInstallMenuItems({
}) {
const { t } = useLingui();
const { hostSet, toggleEditor, installAll } = toggles;
- const pathFor = (host: string): string | null =>
- skill ? `${skillHostRootDir(host, skill.scope)}/${skill.name}` : null;
const allSkills = useSkills();
- // The `.agents` hub is EXISTENCE-ACTIVATED: offered only when this project
- // already adopted it (any skill lives there or lists it as a host). OK never
- // pushes the hub on a repo — adopting it is one Custom path away, and the
- // first placement there lights this row up for every skill.
- const hubActive =
- skill !== undefined &&
- ((skill.hosts ?? []).includes('agents') ||
- (allSkills.status === 'ready' &&
- allSkills.data.some((s) => s.hosts.includes('agents') || s.path.startsWith('.agents/'))));
- // Folder-level aliases (host id → base-relative target root). An aliased
- // folder is a derived view of its target: NO row of its own (checking it
- // could only write through the alias), its agent icon rides the target
- // root's row instead. Observable disk facts only — a row's audience is the
- // set of folders that resolve into it, never a vendor-capability claim.
- // Folder-level links are a property of the SCOPE's dirs, not of one skill —
- // a not-yet-installed skill (explore preview) has no entry to carry them, so
- // fall back to the union across installed same-scope skills; otherwise the
- // preview menu shows aliased folders as plain rows (inconsistent menus).
- const aliases: Record<string, string> =
- skill?.hostAliases ??
- (skill && allSkills.status === 'ready'
- ? Object.assign(
- {},
- ...allSkills.data.filter((s) => s.scope === skill.scope).map((s) => s.hostAliases ?? {}),
- )
- : {});
- // only OFFER editors installable on THIS machine for the skill's
- // scope — for global skills that is the set whose user-home dir exists, so we
- // don't show an editor (e.g. Copilot with no `~/.copilot`) whose install
- // silently no-ops and flashes a checkmark that reverts. Same same-scope
- // fallback as `aliases` for a preview skill that carries no entry of its own;
- // null = no data → offer everything (never over-hide). The `.agents` hub and
- // any editor the skill is ALREADY in are always kept (uninstall stays reachable).
- const installableList: readonly string[] | undefined =
- skill?.installableEditors ??
- (skill && allSkills.status === 'ready'
- ? allSkills.data.find((s) => s.scope === skill.scope)?.installableEditors
- : undefined);
- const installable = installableList ? new Set<string>(installableList) : null;
- const rows: Array<SkillInstallTarget> = (
- hubActive ? (['agents', ...INSTALL_EDITORS] as const) : INSTALL_EDITORS
- )
- .filter((e) => !(e in aliases))
- .filter((e) => e === 'agents' || installable === null || installable.has(e) || hostSet.has(e));
- const stdPaths = new Set(rows.map((e) => pathFor(e)));
- const homePrefix = skill?.scope === 'global' ? '~/' : '';
- // `path` is `<dir>/SKILL.md`; the guard on '/' skips placeholder entries.
- const entryDir = skill?.path?.includes('/')
- ? `${homePrefix}${skill.path.replace(/\/SKILL\.mdx?$/i, '')}`
- : null;
- const sourceRow = entryDir !== null && !stdPaths.has(entryDir) ? entryDir : null;
- // A host row carries the SOURCE badge ONLY when the skill's real dir IS that
- // host's dir (in-place skills). A store-backed skill's source is its own
- // row (`sourceRow`) — badging hosts[0] there showed TWO sources.
- const sourceHost = sourceRow === null ? (toggles.sourceHost ?? skill?.hosts?.[0]) : undefined;
+ const {
+ pathFor,
+ aliases,
+ rows,
+ sourceRow,
+ sourceHost,
+ conflicted,
+ drifted,
+ linked,
+ expectedMode,
+ convertible,
+ customRootRows,
+ } = deriveSkillInstallRows({
+ skill,
+ allSkills: allSkills.status === 'ready' ? allSkills.data : null,
+ hostSet,
+ sourceHostOverlay: toggles.sourceHost,
+ linkMode: toggles.linkMode,
+ });
const subscribersOf = (rootRel: string): string[] => aliasSubscribersOf(aliases, rootRel);
const hostLabel = (h: string): string =>
h === 'agents' ? '.agents' : ((EDITOR_LABELS as Record<string, string>)[h] ?? h);
@@ -461,12 +409,6 @@ export function SkillInstallMenuItems({
</Hint>
);
};
- const conflicted = new Set(skill?.conflictHosts ?? []);
- // Drift = OK's record of what it wrote disagrees with disk (another tool
- // rewrote the path). PASSIVE disclosure only — OK only writes on explicit
- // clicks, so there is no war to referee and no hands-off state to manage.
- // Ledger paths are base-relative; display paths may carry `~/` — strip.
- const drifted = new Set(skill?.driftPaths ?? []);
// While a run is in flight the folders are mid-rewrite and the list refetches
// underneath us, so per-row form and drift are snapshots of a half-converted
// state — they flip to "symlink"/"changed outside" and then settle, which
@@ -475,44 +417,6 @@ export function SkillInstallMenuItems({
// per-row marks stay hidden until it settles.
const busy = toggles.installing;
const relOf = (display: string | null): string => (display ?? '').replace(/^~\//, '');
- const linked = new Set(skill?.symlinkedHosts ?? []);
- // The mode a location is EXPECTED to have: what the skill's other locations
- // are, falling back to the server's effective preference when there are none
- // to compare against. A row matching this says nothing (a menu of identical
- // COPY tags was pure noise); a row that DIVERGES gets a tag that converts it.
- const otherStates: Array<'copy' | 'link'> = [
- ...[...hostSet]
- .filter((h) => h !== sourceHost && !(h in aliases) && !conflicted.has(h) && !h.includes('/'))
- .map((h) => (linked.has(h) ? ('link' as const) : ('copy' as const))),
- ...(skill?.customPlacements ?? []).map((cp) => cp.mode),
- ];
- const linkCount = otherStates.filter((st) => st === 'link').length;
- const expectedMode: 'copy' | 'link' =
- otherStates.length === 0
- ? toggles.linkMode
- ? 'link'
- : 'copy'
- : linkCount * 2 >= otherStates.length
- ? 'link'
- : 'copy';
- // Every location this skill has BESIDES its source, with the form each one is
- // in — the same membership `otherStates` measures, kept addressable so the
- // skill-wide convert below can write each one. The source is never included:
- // it is the real folder the others copy or point at.
- const convertible: Array<{ target: string; display: string; mode: 'copy' | 'link' }> = [
- ...[...hostSet]
- .filter((h) => h !== sourceHost && !(h in aliases) && !conflicted.has(h) && !h.includes('/'))
- .map((h) => ({
- target: h,
- display: pathFor(h) ?? hostLabel(h),
- mode: linked.has(h) ? ('link' as const) : ('copy' as const),
- })),
- ...(skill?.customPlacements ?? []).map((cp) => ({
- target: customPlacementRoot(cp),
- display: `${homePrefix}${cp.path}`,
- mode: cp.mode,
- })),
- ];
// Row-level convert (never skill-wide): state the whole effect, then write
// exactly one path. The old skill-wide Copies/Symlinks tabs silently
// reconverted every existing location on click, which is what this replaces.
@@ -552,43 +456,6 @@ export function SkillInstallMenuItems({
</Hint>
);
};
- // Non-standard locations that actually hold this skill get their own rows:
- // the skill's OWN folder when it isn't an editor dir (e.g. a `.ok/skills`
- // store bundle — the true SOURCE), and every recorded custom placement.
- // KNOWN custom roots travel between SKILLS (per-machine): every distinct
- // parent dir any skill at this scope has a recorded placement under becomes
- // an offerable row on EVERY skill's menu — use a custom path once and it's a
- // first-class choice from then on. Checked when THIS skill is placed there.
- const myPlacements = new Map(
- (skill?.customPlacements ?? []).map((cp) => [customPlacementRoot(cp), cp]),
- );
- const knownRoots = new Set<string>(myPlacements.keys());
- if (allSkills.status === 'ready' && skill) {
- for (const s of allSkills.data) {
- if (s.scope !== skill.scope) continue;
- for (const cp of s.customPlacements ?? []) {
- const root = customPlacementRoot(cp);
- // `.ok/skills` is the retired store, offered like any other custom root
- // so projects that still keep skills there can manage them; the rest of
- // `.ok/` is OK's own state and the server refuses it.
- if (root !== '') knownRoots.add(root);
- }
- }
- }
- const customRootRows =
- skill !== undefined
- ? [...knownRoots]
- .sort()
- .map((root) => ({
- root,
- display: `${homePrefix}${root}/${skill.name}`,
- placed: myPlacements.get(root) ?? null,
- }))
- // Alias-covered custom roots (a folder-symlink into another root)
- // get NO row — same rule as editor folders: their icon rides the
- // target root's audience instead.
- .filter((r) => !stdPaths.has(r.display) && r.display !== entryDir && !(r.root in aliases))
- : [];
return (
<>
{/* NO skill-wide Copies/Symlinks tabs: they applied the chosen mode to
@@ -807,7 +674,7 @@ export function SkillInstallMenuItems({
className="group"
data-testid={`skill-custom-root-${r.root}`}
>
- {r.root === '.agents/skills' ? (
+ {r.root === AGENTS_SKILLS_ROOT ? (
<AgentBrandIcon host="agents" aria-hidden className="size-4" />
) : (
<Folder aria-hidden className="size-4 text-muted-foreground" />
diff --git a/packages/app/src/components/SkillPreviewTab.dom.test.tsx b/packages/app/src/components/SkillPreviewTab.dom.test.tsx
index a4b9c51d3..41859465f 100644
--- a/packages/app/src/components/SkillPreviewTab.dom.test.tsx
+++ b/packages/app/src/components/SkillPreviewTab.dom.test.tsx
@@ -73,6 +73,32 @@ vi.doMock('@/components/SkillInstallMenu', () => ({
vi.doMock('@/components/skill-actions', () => ({
SkillPlaceDialog: () => null,
}));
+// The redirect waits for the skill to appear in the list, since that is what
+// `useOpenSkill` resolves the doc from.
+vi.doMock('@/hooks/use-skills', () => ({
+ useSkills: () => ({
+ status: 'ready',
+ data: [
+ {
+ scope: 'global',
+ name: 'grill-me',
+ path: '.claude/skills/grill-me/SKILL.md',
+ installed: true,
+ hosts: ['claude'],
+ },
+ ],
+ }),
+}));
+const closeTab = vi.fn();
+vi.doMock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({
+ openTabs: [
+ 'skill-preview:explore:grill-me:project',
+ 'skill-preview:explore:grill-with-docs:project',
+ ],
+ closeTab,
+ }),
+}));
const openSkill = vi.fn();
vi.doMock('@/hooks/use-open-skill', () => ({
useOpenSkill: () => openSkill,
@@ -197,7 +223,12 @@ describe('SkillPreviewTab bulk plugin install', () => {
// about its own arrival through the banner's callback.
await user.click(await screen.findByTestId('bulk-install-finished'));
- expect(openSkill).toHaveBeenCalledWith('global', 'grill-me', { replaceActive: true });
+ expect(openSkill).toHaveBeenCalledWith('global', 'grill-me', {
+ replaceActive: true,
+ // This open supersedes the preview the user is standing on, so it takes
+ // that history entry rather than stacking a second one for the same skill.
+ replaceHistory: true,
+ });
previewMeta.pluginBundle = undefined;
});
});
diff --git a/packages/app/src/components/SkillPreviewTab.redirect.dom.test.tsx b/packages/app/src/components/SkillPreviewTab.redirect.dom.test.tsx
new file mode 100644
index 000000000..70863b926
--- /dev/null
+++ b/packages/app/src/components/SkillPreviewTab.redirect.dom.test.tsx
@@ -0,0 +1,135 @@
+import { render, screen } from '@testing-library/react';
+import { type ReactNode, useEffect } from 'react';
+import { describe, expect, test, vi } from 'vitest';
+
+/**
+ * The per-agent install path: the user picks an agent in the INSTALL menu, the
+ * hook imports the bundle and reports `importedName`, and the preview tab must
+ * replace itself with the real skill. The existing suite only covers the BULK
+ * path (`bulkInstalledName`), so this branch shipped uncovered — and it is the
+ * one that strands on the preview in the app.
+ */
+vi.doMock('@/components/SkillBundlePreview', () => ({
+ SkillBundlePreview: ({
+ headerActions,
+ banner,
+ onPreviewMeta,
+ }: {
+ headerActions: ReactNode;
+ banner?: ReactNode;
+ onPreviewMeta?: (p: unknown) => void;
+ }) => {
+ useEffect(() => {
+ onPreviewMeta?.({});
+ }, [onPreviewMeta]);
+ return (
+ <>
+ <div data-testid="preview-body">preview</div>
+ {headerActions}
+ {banner}
+ </>
+ );
+ },
+}));
+vi.doMock('@/components/SkillPluginBundleBanner', () => ({
+ SkillPluginBundleBanner: () => null,
+}));
+vi.doMock('@/components/SkillInstallMenu', () => ({
+ SKILL_INSTALL_MENU_WIDTH: '',
+ SkillInstallMenuItems: () => null,
+}));
+vi.doMock('@/components/skill-actions', () => ({ useSkillActions: () => ({}) }));
+vi.doMock('@/lib/skill-scope', () => ({
+ useSkillScopeLabels: () => ({ project: 'Project', global: 'Global' }),
+ SKILL_SCOPE_ORDER: ['project', 'global'],
+}));
+vi.doMock('@/lib/skills-api', () => ({
+ fetchSkillDetail: vi.fn(async () => ({ ok: false, error: 'n/a' })),
+ placeSkill: vi.fn(),
+ discoverSkillsInSource: vi.fn(async () => ({ ok: false, error: 'n/a' })),
+ importSkillsBulk: vi.fn(),
+ installSkill: vi.fn(),
+}));
+
+// The redirect waits for the skill to appear in the list, since that is what
+// `useOpenSkill` resolves the doc from.
+vi.doMock('@/hooks/use-skills', () => ({
+ useSkills: () => ({
+ status: 'ready',
+ data: [
+ {
+ scope: 'project',
+ name: 'grill-me',
+ path: '.claude/skills/grill-me/SKILL.md',
+ installed: true,
+ hosts: ['claude'],
+ },
+ ],
+ }),
+}));
+const closeTab = vi.fn();
+vi.doMock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({
+ openTabs: [
+ 'skill-preview:explore:grill-me:project',
+ 'skill-preview:explore:grill-with-docs:project',
+ ],
+ closeTab,
+ }),
+}));
+const openSkill = vi.fn();
+vi.doMock('@/hooks/use-open-skill', () => ({ useOpenSkill: () => openSkill }));
+
+// The import has landed at PROJECT scope — exactly what the app reports after a
+// per-agent install (`.claude/skills/<name>/SKILL.md`, host claude).
+vi.doMock('@/hooks/use-explore-preview-install', () => ({
+ useExplorePreviewInstall: () => ({
+ scope: 'project',
+ importedScope: 'project',
+ importedName: 'grill-me',
+ setScope: vi.fn(),
+ scopeLocked: true,
+ importNow: vi.fn(),
+ toggles: {
+ hostSet: new Set(['claude']),
+ installed: true,
+ installing: false,
+ toggleEditor: vi.fn(),
+ installAll: vi.fn(),
+ linkMode: false,
+ setLinkMode: vi.fn(),
+ setSource: vi.fn(),
+ placeAt: vi.fn(),
+ },
+ }),
+}));
+
+const { SkillPreviewTab } = await import('./SkillPreviewTab');
+
+describe('SkillPreviewTab per-agent install redirect', () => {
+ test('replaces the preview with the real skill once the import lands', async () => {
+ render(<SkillPreviewTab flavor="explore" source="mattpocock/skills" name="grill-me" />);
+ await screen.findByTestId('preview-body');
+
+ expect(openSkill).toHaveBeenCalledWith('project', 'grill-me', {
+ replaceActive: true,
+ // This open supersedes the preview the user is standing on, so it takes
+ // that history entry rather than stacking a second one for the same skill.
+ replaceHistory: true,
+ });
+ });
+
+ test('does not burn its one attempt while the list still lags the import', async () => {
+ // The fire-once ref is set BEFORE the open resolves, so redirecting before
+ // the entry is resolvable strands the preview permanently. Mount with an
+ // empty list and assert we hold rather than fire.
+ vi.resetModules();
+ const lateOpen = vi.fn();
+ vi.doMock('@/hooks/use-open-skill', () => ({ useOpenSkill: () => lateOpen }));
+ vi.doMock('@/hooks/use-skills', () => ({ useSkills: () => ({ status: 'loading' }) }));
+ const { SkillPreviewTab: Tab } = await import('./SkillPreviewTab');
+ render(<Tab flavor="explore" source="mattpocock/skills" name="grill-me" />);
+ await screen.findByTestId('preview-body');
+ expect(lateOpen).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/app/src/components/SkillPreviewTab.tsx b/packages/app/src/components/SkillPreviewTab.tsx
index 903c47b71..5dd2a6d21 100644
--- a/packages/app/src/components/SkillPreviewTab.tsx
+++ b/packages/app/src/components/SkillPreviewTab.tsx
@@ -22,9 +22,12 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
+import { useDocumentContext } from '@/editor/DocumentContext';
+import { parseEditorTabId } from '@/editor/editor-tabs';
import { useExplorePreviewInstall } from '@/hooks/use-explore-preview-install';
import { useOpenSkill } from '@/hooks/use-open-skill';
import { useSkillOrigin } from '@/hooks/use-skill-origin';
+import { useSkills } from '@/hooks/use-skills';
import { hashFromSkillFile, hashFromSkillPreview, type SkillPreviewFlavor } from '@/lib/doc-hash';
import { useSkillScopeLabels } from '@/lib/skill-scope';
import { discoverSkillsInSource, fetchSkillDetail } from '@/lib/skills-api';
@@ -201,15 +204,52 @@ export function SkillPreviewTab({
// (which only tracks ITS own import-then-place cycle) never sees it.
const [bulkInstalledName, setBulkInstalledName] = useState<string | null>(null);
const landedName = previewInstall.importedName ?? bulkInstalledName;
+ // Redirect against the scope the bundle ACTUALLY landed at, never the live
+ // `scope` selector. `useOpenSkill` resolves a skill's doc by (scope, name), so
+ // if the selector has moved since the import — or the import ran at a scope the
+ // selector no longer shows — the tab opens a document that does not exist and
+ // strands on "Couldn't load document" until it times out. Falls back to the
+ // selector only for the bulk-install path, which imports at the current scope
+ // and reports no scope of its own.
+ const landedScope = previewInstall.importedScope ?? previewInstall.scope;
+ // Redirect only once the skill is actually IN the list, and open it at the
+ // scope the list reports. `useOpenSkill` resolves the doc from that same list,
+ // which lags a fresh import by the `skills-changed` refetch — and the fire-once
+ // ref is set BEFORE the open resolves, so firing early burns the one attempt
+ // on a lookup that cannot succeed and strands the preview for good.
+ //
+ // Still gated on `landedName`, so previewing a marketplace skill whose name
+ // already exists locally does not bounce you straight out of the preview.
+ const { openTabs, closeTab } = useDocumentContext();
+ const allSkills = useSkills();
+ const landedEntry =
+ landedName !== null && allSkills.status === 'ready'
+ ? allSkills.data.find((sk) => sk.name === landedName && sk.scope === landedScope)
+ : undefined;
const importedNow =
- (flavor === 'explore' || foreign || pluginInfo !== null) && landedName !== null;
+ (flavor === 'explore' || foreign || pluginInfo !== null) && landedEntry !== undefined;
useEffect(() => {
if (!importedNow || redirectedRef.current) return;
redirectedRef.current = true;
- openSkill(previewInstall.scope, landedName as string, {
+ // Capture THIS preview's tab id(s) before opening, then close them after.
+ // `replaceActive` only opens with preview DISPOSITION — it swaps whatever
+ // holds the preview slot, which is not the same thing as replacing this tab.
+ // A skill-preview tab opened permanently therefore survives, and the real
+ // skill lands beside it: two tabs for one skill, the stale one still
+ // advertising "Install it into your agents" for a skill you already own.
+ const stalePreviewTabIds = openTabs.filter((id) => {
+ const tab = parseEditorTabId(id);
+ return tab.kind === 'skill-preview' && tab.name === name;
+ });
+ openSkill(landedScope, landedName as string, {
replaceActive: true,
+ // This open REPLACES the preview the user is standing on, so it takes
+ // that history entry rather than stacking a second one for the same skill.
+ replaceHistory: true,
});
- }, [importedNow, previewInstall.scope, landedName, openSkill]);
+ // After the open, so a failure to resolve can never leave zero tabs.
+ for (const id of stalePreviewTabIds) closeTab(id);
+ }, [importedNow, landedScope, landedName, openSkill, openTabs, name, closeTab]);
// Capitalized harness for the header copy ("detected in Claude"), matching
// the "From Claude" provenance chip.
const harnessLabel = subtitle ? subtitle.charAt(0).toUpperCase() + subtitle.slice(1) : subtitle;
diff --git a/packages/app/src/components/SkillTrackInGitDialog.dom.test.tsx b/packages/app/src/components/SkillTrackInGitDialog.dom.test.tsx
new file mode 100644
index 000000000..f4622da90
--- /dev/null
+++ b/packages/app/src/components/SkillTrackInGitDialog.dom.test.tsx
@@ -0,0 +1,112 @@
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+/**
+ * The dialog that explains a gitignored skill and offers the one-line fix.
+ *
+ * Two properties are load-bearing, because this writes to the user's REPO:
+ * it shows the literal `.gitignore` line before touching anything, and it only
+ * writes on the explicit confirm. The line itself comes from the server (git
+ * cannot re-include a file whose parent directory is excluded, so the rule has
+ * to name the skills DIRECTORY) — the dialog must render what it is handed
+ * rather than compose its own.
+ */
+const trackSkillInGit = vi.fn(async (input: { apply?: boolean }) => ({
+ ok: true as const,
+ line: '!/.claude/skills/',
+ gitignorePath: '.gitignore',
+ applied: input.apply === true,
+}));
+const openTarget = vi.fn();
+
+vi.doMock('@/lib/skills-api', () => ({ trackSkillInGit }));
+vi.doMock('@/editor/DocumentContext', () => ({ useDocumentContext: () => ({ openTarget }) }));
+vi.doMock('@/lib/config-provider', () => ({
+ useConfigContext: () => ({ merged: { editor: { previewTabs: true } } }),
+}));
+vi.doMock('@/hooks/use-skills', () => ({
+ useSkills: () => ({
+ status: 'ready',
+ data: [
+ {
+ scope: 'project',
+ name: 'hidden',
+ path: '.claude/skills/hidden/SKILL.md',
+ installed: true,
+ hosts: [],
+ ignored: true,
+ },
+ ],
+ }),
+}));
+
+const { SkillTrackInGitDialog } = await import('@/components/SkillTrackInGitDialog');
+const { requestSkillTrackPrompt, __resetSkillTrackPromptForTests, getSkillTrackPrompt } =
+ await import('@/lib/skill-track-prompt-store');
+
+afterEach(() => {
+ __resetSkillTrackPromptForTests();
+ trackSkillInGit.mockClear();
+ openTarget.mockClear();
+});
+
+describe('SkillTrackInGitDialog', () => {
+ test('renders nothing until a skill asks for it', () => {
+ render(<SkillTrackInGitDialog />);
+ expect(screen.queryByTestId('skill-track-in-git-confirm')).toBeNull();
+ });
+
+ test('shows the exact .gitignore line and writes nothing before the confirm', async () => {
+ requestSkillTrackPrompt({ scope: 'project', name: 'hidden' });
+ render(<SkillTrackInGitDialog />);
+
+ expect(await screen.findByText('!/.claude/skills/')).toBeTruthy();
+ // Preview only: every call so far left `apply` off.
+ expect(trackSkillInGit).toHaveBeenCalled();
+ for (const [input] of trackSkillInGit.mock.calls) {
+ expect(input.apply).not.toBe(true);
+ }
+ });
+
+ test('a failed preview says so instead of leaving a dead button', async () => {
+ // The dialog explains the fix, so disabling the only control that applies
+ // it with no reason shown is the worst of both.
+ trackSkillInGit.mockImplementationOnce(async () => ({
+ ok: false as const,
+ error: 'no project',
+ }));
+ requestSkillTrackPrompt({ scope: 'project', name: 'hidden' });
+ render(<SkillTrackInGitDialog />);
+
+ expect(await screen.findByText(/no project/)).toBeTruthy();
+ });
+
+ test('the confirm applies the rule and opens the skill it was blocking', async () => {
+ requestSkillTrackPrompt({ scope: 'project', name: 'hidden' });
+ render(<SkillTrackInGitDialog />);
+ await screen.findByText('!/.claude/skills/');
+
+ await userEvent.click(screen.getByTestId('skill-track-in-git-confirm'));
+
+ expect(trackSkillInGit).toHaveBeenCalledWith({
+ name: 'hidden',
+ scope: 'project',
+ apply: true,
+ });
+ // The user asked to OPEN the skill; the rule was only in the way. Addressed
+ // by the entry's own doc name, not back through the opener whose `ignored`
+ // guard is still true until the list refetches.
+ expect(openTarget).toHaveBeenCalledWith(
+ {
+ kind: 'doc',
+ target: '.claude/skills/hidden/SKILL',
+ docName: '.claude/skills/hidden/SKILL',
+ },
+ // Threaded like every other skill open, so the preview-tab preference is
+ // honoured instead of always stacking a permanent tab.
+ { tabBehavior: 'replace-active' },
+ );
+ expect(getSkillTrackPrompt()).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/SkillTrackInGitDialog.tsx b/packages/app/src/components/SkillTrackInGitDialog.tsx
new file mode 100644
index 000000000..553c769b4
--- /dev/null
+++ b/packages/app/src/components/SkillTrackInGitDialog.tsx
@@ -0,0 +1,163 @@
+import { Trans, useLingui } from '@lingui/react/macro';
+import { useEffect, useState, useSyncExternalStore } from 'react';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { useDocumentContext } from '@/editor/DocumentContext';
+import { useSkills } from '@/hooks/use-skills';
+import { useConfigContext } from '@/lib/config-provider';
+import { skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';
+import {
+ clearSkillTrackPrompt,
+ getSkillTrackPrompt,
+ subscribeToSkillTrackPrompt,
+} from '@/lib/skill-track-prompt-store';
+import { trackSkillInGit } from '@/lib/skills-api';
+
+/**
+ * Why a skill you can see refuses to open, and the one line that fixes it.
+ *
+ * A gitignored bundle is listed but never indexed — OK will not index a doc the
+ * sync engine could never commit — so the row is real and the click has nothing
+ * behind it. `.claude/*` is a common rule, which made this look like a random
+ * bug rather than a policy. The dialog shows the literal `.gitignore` line
+ * BEFORE writing: it edits the user's repo, so it never happens on open.
+ *
+ * The line re-includes the whole skills DIRECTORY because git cannot re-include
+ * a file whose parent directory is excluded; the server owns that rule and
+ * hands it back here, so the two can't drift.
+ *
+ * Mounted once in `App` — the guard fires from the shared opener, which has no
+ * surface of its own.
+ */
+export function SkillTrackInGitDialog() {
+ const { t } = useLingui();
+ const prompt = useSyncExternalStore(subscribeToSkillTrackPrompt, getSkillTrackPrompt);
+ const { openTarget } = useDocumentContext();
+ const { merged } = useConfigContext();
+ // Gated: this host is mounted for the whole session but inert almost all of
+ // it, and `/api/skills` is a synchronous walk of every skills root on the
+ // machine. Ungated it costs that scan at every boot and on every `files`
+ // signal, for a dialog nobody has opened.
+ const skillsState = useSkills({ enabled: prompt !== null });
+ const [line, setLine] = useState<string | null>(null);
+ const [gitignorePath, setGitignorePath] = useState('.gitignore');
+ const [applying, setApplying] = useState(false);
+ const [previewError, setPreviewError] = useState<string | null>(null);
+
+ const scope = prompt?.scope;
+ const name = prompt?.name;
+ useEffect(() => {
+ if (scope === undefined || name === undefined) {
+ setLine(null);
+ return;
+ }
+ let cancelled = false;
+ setPreviewError(null);
+ // Preview only — `apply` defaults to false, so this cannot touch the repo.
+ void trackSkillInGit({ name, scope }).then((r) => {
+ if (cancelled) return;
+ if (!r.ok) {
+ // Without this the dialog explains the fix and then disables the only
+ // button that applies it, with no reason given.
+ setPreviewError(r.error);
+ return;
+ }
+ setLine(r.line);
+ setGitignorePath(r.gitignorePath);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [scope, name]);
+
+ if (!prompt) return null;
+
+ const close = () => {
+ if (applying) return;
+ clearSkillTrackPrompt();
+ };
+
+ return (
+ <Dialog open onOpenChange={(open) => !open && close()}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>"{prompt.name}" is ignored by git</Trans>
+ </DialogTitle>
+ <DialogDescription>
+ <Trans>
+ Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't
+ index a file that git is set to ignore, because syncing it would fail. Adding one line
+ to {gitignorePath} makes it editable here.
+ </Trans>
+ </DialogDescription>
+ </DialogHeader>
+ {previewError !== null && (
+ <p className="text-destructive text-sm">
+ <Trans>
+ Couldn't read the {gitignorePath} rule: {previewError}
+ </Trans>
+ </p>
+ )}
+ {line !== null && (
+ <pre className="overflow-x-auto rounded-md bg-muted px-3 py-2 font-mono text-sm">
+ {line}
+ </pre>
+ )}
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="outline" disabled={applying}>
+ <Trans>Cancel</Trans>
+ </Button>
+ </DialogClose>
+ <Button
+ data-testid="skill-track-in-git-confirm"
+ disabled={applying || line === null}
+ onClick={async () => {
+ setApplying(true);
+ const result = await trackSkillInGit({
+ name: prompt.name,
+ scope: prompt.scope,
+ apply: true,
+ });
+ setApplying(false);
+ if (!result.ok) {
+ toast.error(t`Couldn't update ${gitignorePath}: ${result.error}`);
+ return;
+ }
+ clearSkillTrackPrompt();
+ // Open what the user asked for in the first place. Addressed by
+ // the entry's own doc name rather than back through the opener,
+ // whose `ignored` guard is still true until the list refetches.
+ const entry =
+ skillsState.status === 'ready'
+ ? skillsState.data.find((s) => s.scope === prompt.scope && s.name === prompt.name)
+ : undefined;
+ if (entry) {
+ const docName = skillEntryLiveDocName(entry);
+ openTarget(
+ { kind: 'doc', target: docName, docName },
+ {
+ tabBehavior:
+ (merged?.editor?.previewTabs ?? true) ? 'replace-active' : 'append',
+ },
+ );
+ }
+ }}
+ >
+ <Trans>Add to {gitignorePath}</Trans>
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/app/src/components/SkillsSidebarSection.tsx b/packages/app/src/components/SkillsSidebarSection.tsx
index 0173abb00..c272437ef 100644
--- a/packages/app/src/components/SkillsSidebarSection.tsx
+++ b/packages/app/src/components/SkillsSidebarSection.tsx
@@ -10,7 +10,7 @@ import { lazy, Suspense, useEffect, useState } from 'react';
import { toast } from 'sonner';
import type { AddSkillTab } from '@/components/ImportSkillDialog';
import { NewSkillDialog } from '@/components/NewSkillDialog';
-import { EMPTY_SCOPE_SENTINEL, SkillsTree } from '@/components/SkillsTree';
+import { SkillsTree } from '@/components/SkillsTree';
import { useSkillActions } from '@/components/skill-actions';
import { Button } from '@/components/ui/button';
import { SidebarGroup, SidebarGroupContent } from '@/components/ui/sidebar';
@@ -34,18 +34,19 @@ import { skillEntryFileLiveDocName, skillEntryLiveDocName } from '@/lib/managed-
import {
SKILL_SCOPE_ORDER,
skillDir,
- skillDisplayName,
skillNameSetsByScope,
useSkillScopeDescriptions,
useSkillScopeLabels,
} from '@/lib/skill-scope';
import { createSkillSortComparator, SKILL_MD_PATH } from '@/lib/skill-sort';
+import { requestSkillTrackPrompt } from '@/lib/skill-track-prompt-store';
import {
fetchSkillPreview,
getSkillBundledFiles,
listDetectedSkills,
type SkillBundledFile,
} from '@/lib/skills-api';
+import { buildSkillsTreePaths, detectedId, isSkillDocActive } from '@/lib/skills-tree-paths';
// Lazy-load the full add-skill modal (skills.sh search + upload + new skill) —
// the SAME dialog the Skills empty state opens — so its weight stays out of the
@@ -54,15 +55,6 @@ const ImportSkillDialog = lazy(() =>
import('@/components/ImportSkillDialog').then((m) => ({ default: m.ImportSkillDialog })),
);
-// OK's own core product skills — managing them with OK is circular, so they
-// never show as "Detected". Its shipped *packs* (`open-knowledge-pack-*`) are
-// fair game to adopt, so they are NOT excluded.
-const OK_OWN_SKILLS = new Set([
- 'open-knowledge',
- 'open-knowledge-discovery',
- 'open-knowledge-write-skill',
-]);
-
/**
* "Skills" section of the file sidebar — ONE `<OkFileTree>` (the same Pierre
* component as the main file tree). GLOBAL / PROJECT are top-level folder rows
@@ -232,7 +224,18 @@ export function SkillsSidebarSection({ skillsMode = false }: { skillsMode?: bool
stayInSkills();
};
const openSkillMd = (skill: SkillsListEntry) => {
- openSkillDoc(skillEntryLiveDocName(skill));
+ // Route through the SHARED opener rather than opening the doc directly.
+ // `useOpenSkill` documents itself as the single entry point every
+ // open-a-skill surface must use, and this one had drifted: it minted the doc
+ // name itself, so every fix applied there (scope resolution, the fresh-entry
+ // fallback, pinning the surface to Skills) silently did not apply to a
+ // sidebar click. Same visible action behaving differently depending on where
+ // it was invoked from is what made these bugs so hard to pin down.
+ openSkill(skill.scope, skill.name, {
+ replaceActive: tabBehavior === 'replace-active',
+ ...(skill.path ? { path: skill.path } : {}),
+ });
+ stayInSkills();
};
// Managed built-ins reuse the SAME read-only preview tab as detected skills, sourced
// from their bundle dir (`absolutePath` is the bundle SKILL.md; its parent is
@@ -292,6 +295,14 @@ export function SkillsSidebarSection({ skillsMode = false }: { skillsMode?: bool
});
};
const openFile = (skill: SkillsListEntry, filePath: string) => {
+ // Same gate as the SKILL doc: nothing in a gitignored bundle is indexed.
+ // NOT for a managed built-in: OK ships those bundles read-only, a repo that
+ // ignores them means it, and they open as a read-only preview anyway — so
+ // offering to git-track one is an offer the user must not take.
+ if (skill.ignored === true && !skill.managed) {
+ requestSkillTrackPrompt({ scope: skill.scope, name: skill.name });
+ return;
+ }
const dot = filePath.lastIndexOf('.');
const ext = dot >= 0 ? filePath.slice(dot + 1).toLowerCase() : '';
// Editable in place: any `.md`/`.mdx` bundle file of a non-managed skill,
@@ -339,20 +350,19 @@ export function SkillsSidebarSection({ skillsMode = false }: { skillsMode?: bool
activeTarget.path === filePath
);
};
- const isSkillMdActive = (skill: SkillsListEntry): boolean => {
- // A skill-FILE viewer (`{kind:'skill-file'}`, e.g. LICENSE.txt) and a skill
- // PREVIEW carry no docName, so opening one leaves `activeDocName` stale on the
- // last DOC tab — which is often this skill's SKILL.md. Without this guard that
- // stale value makes SKILL.md read as active while a file viewer is open, so the
- // tree highlights SKILL and the `p === activePath` click-guard then blocks
- // reopening SKILL.md. Only a real doc tab counts as the active SKILL.md.
- if (activeTarget?.kind !== 'doc') return false;
- return activeDocName === skillEntryLiveDocName(skill);
- };
+ const isSkillMdActive = (skill: SkillsListEntry): boolean =>
+ // Pure + unit-tested (see skills-tree-paths.test.ts). Requires a real OPEN
+ // tab, not just a matching `activeDocName`: a skill-file viewer or preview
+ // leaves that value stale on the last doc tab, and an open that never
+ // landed leaves it pointing at a doc with no tab — either way the row reads
+ // active and the tree's click guard then swallows the retry.
+ isSkillDocActive({
+ activeTargetKind: activeTarget?.kind,
+ activeDocName,
+ openTabs,
+ docName: skillEntryLiveDocName(skill),
+ });
- // Detected-row actions: open the editable in-place buffer.
- const detectedId = (s: CatalogSkill) =>
- `${catalogRawScopeToOkScope(s.provenance.scope)}::${s.name}`;
// Lazily load this detected skill's bundle file tree on first open (cached
// after) so the row can nest references/scripts under it.
const ensureDetectedFiles = (s: CatalogSkill, source: string) => {
@@ -410,120 +420,21 @@ export function SkillsSidebarSection({ skillsMode = false }: { skillsMode?: bool
// Build paths + a `<scopeLabel>/<segment>` → skill lookup. Every scope always
// appears (as an empty folder if it has no skills) so its "New / Add" menu is
- // always reachable.
+ // always reachable. Pure + unit-tested (see skills-tree-paths.test.ts).
const labelToScope = new Map(SKILL_SCOPE_ORDER.map((s) => [scopeLabel[s], s] as const));
- // The tree segment is normally the stripped display name, but Pierre labels
- // rows by the path basename — so when two skills in one scope strip to the
- // same name (e.g. a user `foo` beside the shipped `open-knowledge-pack-foo`)
- // a shared segment would collapse both to one row and hide one. Only the
- // colliding skills fall back to their full (unstripped) name to stay distinct.
- // Third tier: distinct-content skills that share a name outright, where even
- // the full name is identical — those take the host dir that holds them, which
- // is the thing that actually tells them apart.
- const displayCounts = new Map<string, number>();
- for (const s of skills) {
- const key = `${s.scope}\x00${skillDisplayName(s.name)}`;
- displayCounts.set(key, (displayCounts.get(key) ?? 0) + 1);
- }
- const segmentFor = (s: SkillsListEntry) => {
- const display = skillDisplayName(s.name);
- const host = hostQualifierOf(s);
- if (host) return `${s.name} (${host === 'agents' ? '.agents' : host})`;
- return (displayCounts.get(`${s.scope}\x00${display}`) ?? 0) > 1 ? s.name : display;
- };
- const skillByPrefix = new Map<string, SkillsListEntry>();
- const paths: string[] = [];
- let activePath: string | undefined;
- // Both scope rows (GLOBAL / PROJECT) stay expanded. The tree remounts on any
- // skill add/remove/rename (path/state key change), and Pierre exposes no
- // expansion callback to snapshot user state across that — so pinning the
- // section headers open keeps a sibling scope from collapsing when an unrelated
- // skill is deleted. Individual skill folders still expand only for the active doc.
- const expanded: string[] = [];
- // Segments already taken per scope — so a detected skill can't collide with a
- // managed skill's row (or another detected skill's).
- const usedSegments = new Map<SkillScope, Set<string>>(
- SKILL_SCOPE_ORDER.map((s) => [s, new Set<string>()]),
- );
- for (const scope of SKILL_SCOPE_ORDER) {
- paths.push(`${scopeLabel[scope]}/`);
- expanded.push(`${scopeLabel[scope]}/`);
- }
- for (const s of skills) {
- const segment = segmentFor(s);
- usedSegments.get(s.scope)?.add(segment);
- const prefix = `${scopeLabel[s.scope]}/${segment}`;
- skillByPrefix.set(prefix, s);
- paths.push(`${prefix}/${SKILL_MD_PATH}`);
- if (isSkillMdActive(s)) {
- activePath = `${prefix}/${SKILL_MD_PATH}`;
- expanded.push(`${scopeLabel[s.scope]}/`, `${prefix}/`);
- }
- for (const f of filesByKey[skillRowKey(s)] ?? []) {
- paths.push(`${prefix}/${f.path}`);
- if (!activePath && isFileActive(s, f.path)) {
- activePath = `${prefix}/${f.path}`;
- expanded.push(`${scopeLabel[s.scope]}/`, `${prefix}/`);
- }
- }
- }
-
- // Detected (un-managed) skills — badged rows nested under their OWN scope
- // alongside the managed ones. A detected skill's level comes from the harness
- // provenance (Claude's project / user), NOT where the file lives, so a
- // project-scoped plugin skill lands under PROJECT even though its files are in
- // a user-global home. The server has already dropped project-scoped installs
- // bound to a DIFFERENT project (project-locality), so a `project` row here is
- // genuinely this project's. A detected skill whose name is already OK-managed
- // (at either scope) is skipped: the managed skill is re-detected via its editor
- // symlink, and it already shows as its managed row.
- const managedNames = new Set<string>([...nameSets.global, ...nameSets.project]);
- const detectedByPrefix = new Map<string, CatalogSkill>();
- const visibleDetected = detected ?? [];
- for (const s of visibleDetected) {
- if (managedNames.has(s.name) || OK_OWN_SKILLS.has(s.name)) continue;
- const scope = catalogRawScopeToOkScope(s.provenance.scope);
- const used = usedSegments.get(scope);
- if (!used) continue;
- let segment = skillDisplayName(s.name);
- if (used.has(segment)) segment = s.name;
- if (used.has(segment)) continue; // hard collision (rare) → don't hide a real row
- used.add(segment);
- const prefix = `${scopeLabel[scope]}/${segment}`;
- detectedByPrefix.set(prefix, s);
- paths.push(`${prefix}/${SKILL_MD_PATH}`);
- // Highlight the row when its editable `__extskill__/` buffer is the open doc.
- if (!activePath && activeDocName === externalSkillLiveDocName(s.name)) {
- activePath = `${prefix}/${SKILL_MD_PATH}`;
- expanded.push(`${scopeLabel[scope]}/`, `${prefix}/`);
- }
- // Once loaded, nest the detected skill's reference/script files under it and
- // keep it expanded so the tree it just revealed doesn't collapse on re-render.
- const detectedFiles = detectedFilesById[detectedId(s)] ?? [];
- for (const rel of detectedFiles) paths.push(`${prefix}/${rel}`);
- if (detectedFiles.length > 0) expanded.push(`${prefix}/`);
- }
-
- // Every scope with NO skills (managed or detected) gets a hidden sentinel child
- // so Pierre still renders its folder + header — otherwise a childless directory
- // is dropped from the visible tree and the scope disappears, sliding the sibling
- // to the top. `usedSegments` holds the taken segments per scope, so size 0 = empty.
- for (const scope of SKILL_SCOPE_ORDER) {
- if (usedSegments.get(scope)?.size === 0) {
- paths.push(`${scopeLabel[scope]}/${EMPTY_SCOPE_SENTINEL}`);
- }
- }
-
- // Restore folders the user manually expanded across a remount: the set of all
- // valid folder tree paths is the scope rows + every managed/detected skill's
- // folder; keep only the ones the inner tree recorded as expanded (§2.7/§2.8).
- const validFolderPaths = new Set<string>();
- for (const scope of SKILL_SCOPE_ORDER) validFolderPaths.add(`${scopeLabel[scope]}/`);
- for (const prefix of skillByPrefix.keys()) validFolderPaths.add(`${prefix}/`);
- for (const prefix of detectedByPrefix.keys()) validFolderPaths.add(`${prefix}/`);
- for (const p of userExpanded) {
- if (validFolderPaths.has(p)) expanded.push(p);
- }
+ const { paths, expanded, activePath, skillByPrefix, detectedByPrefix } = buildSkillsTreePaths({
+ skills,
+ detected,
+ scopeLabel,
+ filesByKey,
+ detectedFilesById,
+ userExpanded,
+ hostQualifierOf,
+ rowKeyFor: skillRowKey,
+ isSkillMdActive,
+ isFileActive,
+ isDetectedActive: (s) => activeDocName === externalSkillLiveDocName(s.name),
+ });
// Pure, unit-tested comparator (see skill-sort.test.ts). The depth semantics
// it encodes are load-bearing and previously shipped wrong; keep the coverage.
diff --git a/packages/app/src/components/SkillsTree.tsx b/packages/app/src/components/SkillsTree.tsx
index d0a22351d..6d835b023 100644
--- a/packages/app/src/components/SkillsTree.tsx
+++ b/packages/app/src/components/SkillsTree.tsx
@@ -3,8 +3,8 @@
* `SkillsSidebarSection.tsx`. The section owns data loading, dialogs and the
* section chrome, and hands this everything it needs as props.
*
- * `EMPTY_SCOPE_SENTINEL` lives here because `SKILLS_TREE_CSS` interpolates it;
- * the section imports it back, so the dependency runs section -> tree only.
+ * `EMPTY_SCOPE_SENTINEL` is owned by the path builder that emits it; this file
+ * imports it because `SKILLS_TREE_CSS` interpolates it.
*/
import type { CatalogSkill, SkillScope, SkillsListEntry } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
@@ -60,17 +60,12 @@ import {
tildeHomePath,
} from '@/lib/skill-scope';
import { SKILL_MD_PATH } from '@/lib/skill-sort';
+import { EMPTY_SCOPE_SENTINEL } from '@/lib/skills-tree-paths';
-// A scope with ZERO skills renders no child, and Pierre drops a childless
-// directory from the visible tree — so the GLOBAL / PROJECT header would vanish
-// and the sibling scope slides to the top (breaks "project always first" when the
-// project has no skills). Give an empty scope ONE sentinel child so its folder +
-// header always render in SKILL_SCOPE_ORDER. The sentinel row is display:none'd
-// (SKILLS_TREE_CSS) and every row handler skips it (skillFor/detectedFor return
-// undefined for it). Underscores can't appear in a real skill name (SKILL_NAME_REGEX),
-// so it can't collide. Works WITH `flattenEmptyDirectories: false` — that keeps the
-// resulting single-child folder from collapsing back into the sentinel.
-export const EMPTY_SCOPE_SENTINEL = '__ok_empty_scope__';
+// The sentinel row is display:none'd (SKILLS_TREE_CSS) and every row handler
+// skips it (skillFor/detectedFor return undefined for it). Works WITH
+// `flattenEmptyDirectories: false` — that keeps the resulting single-child
+// folder from collapsing back into the sentinel.
// Built-in skills are locked (bundled, read-only) — a lock glyph on the row is
// the "you can't edit this" signal, in place of a state badge. Registered as a
@@ -394,9 +389,27 @@ export function SkillsTree({
// Reassigned every render so the pass-through handler above captures the LIVE
// `activePath` + open callbacks + `model` (declared just above). Manual memo is
// banned; the ref is how we stay current.
+ // Deliberately a PASSIVE effect, not `useLayoutEffect`. Installing the handler
+ // before paint also puts it in front of Pierre's own mount-time selection,
+ // which then dispatches an open nobody asked for and pushes a history entry —
+ // `goBack` walks duplicates instead of leaving the skill
+ // (`navigation-history.e2e.ts`). The no-op window this leaves open is real but
+ // narrow, and a spurious open is the worse trade.
useEffect(() => {
handleSelectionChangeRef.current = (selected) => {
const p = selected[0];
+ // Bail on the row that is already open. This guard was briefly removed to
+ // make a dead row retryable, which traded one bug for a worse one: the
+ // re-dispatch is idempotent for TAB state but not for HISTORY, so every
+ // redundant click pushed another hash entry and `goBack` walked through
+ // duplicates instead of leaving the skill (caught by
+ // `navigation-history.e2e.ts`).
+ //
+ // It is safe to keep now because `activePath` is derived from
+ // `isSkillDocActive`, which requires a genuinely OPEN tab. The stale
+ // `activeDocName` that made this guard swallow retries — a doc with no tab
+ // behind it — no longer produces an `activePath` at all, so a dead row
+ // dispatches and an open row does not.
if (!p || p === activePath) return;
const node = parseTreePath(p);
if (node.sub !== null && node.isDir) return;
diff --git a/packages/app/src/components/skill-actions.tsx b/packages/app/src/components/skill-actions.tsx
index 10132439e..db07dcf98 100644
--- a/packages/app/src/components/skill-actions.tsx
+++ b/packages/app/src/components/skill-actions.tsx
@@ -55,6 +55,7 @@ import {
SkillMenuSubTrigger,
} from '@/components/skill-menu-primitives';
import { useOpenSkill } from '@/hooks/use-open-skill';
+import { beginSkillWrite, endSkillWrite } from '@/lib/documents-events';
import { revealInFileManagerLabel } from '@/lib/platform-labels';
import { scheduleClipboardWrite } from '@/lib/share/clipboard-adapter';
import { skillDir, useSkillScopeLabels } from '@/lib/skill-scope';
@@ -148,12 +149,18 @@ export function useSkillActions(): SkillActions {
opts?: { linkMode?: boolean },
) {
setInstallingName(skill.name);
+ // Mark the write so the tab reconciler does not read the mid-write scan as a
+ // deletion and close the user's tab: `projectInPlaceSkill` rm's each
+ // destination before materializing it, so the skill can momentarily vanish
+ // from the list while this is in flight.
+ beginSkillWrite(skill.scope, skill.name);
const result = await installSkill({
scope: skill.scope,
name: skill.name,
...(targets ? { targets: [...targets] } : {}),
...(opts?.linkMode !== undefined ? { linkMode: opts.linkMode } : {}),
});
+ endSkillWrite(skill.scope, skill.name);
setInstallingName(null);
if (!result.ok) {
toast.error(t`Couldn't install skill: ${result.error}`);
@@ -228,6 +235,12 @@ export function useSkillActions(): SkillActions {
) {
if (targets.length === 0) return;
setInstallingName(skill.name);
+ // Same reconciler protection as `install` / `runLocationWrite`: a convert
+ // rm's each destination before materializing it, so the skill can read as
+ // absent from a scan taken mid-write, and anything that treats absence as
+ // deletion would close the user's tab. Convert was the one writer on that
+ // rm-then-materialize path without the guard.
+ beginSkillWrite(skill.scope, skill.name);
// No try/finally: `convertSkillLocation` reports failures in its result
// rather than throwing, so a single exit point clears the flag (and the
// React Compiler cannot lower a try without a catch).
@@ -243,15 +256,20 @@ export function useSkillActions(): SkillActions {
break;
}
}
+ endSkillWrite(skill.scope, skill.name);
setInstallingName(null);
}
async function runLocationWrite<T>(skill: SkillsListEntry, run: () => Promise<T>): Promise<T> {
setInstallingName(skill.name);
+ // Same reconciler protection as `install`: a placement/convert rewrites dirs
+ // on disk, so the skill can read as absent mid-write.
+ beginSkillWrite(skill.scope, skill.name);
// Single exit point, no try/finally: these writers report failures in their
// result rather than throwing (and the React Compiler cannot lower a try
// without a catch). The caller keeps its own error reporting.
const result = await run();
+ endSkillWrite(skill.scope, skill.name);
setInstallingName(null);
return result;
}
diff --git a/packages/app/src/editor/editor-tabs.test.ts b/packages/app/src/editor/editor-tabs.test.ts
index 844d700c8..2e72e3ec6 100644
--- a/packages/app/src/editor/editor-tabs.test.ts
+++ b/packages/app/src/editor/editor-tabs.test.ts
@@ -206,6 +206,57 @@ describe('editor tab state', () => {
).toEqual(['docs/a', folderTabId('hello')]);
});
+ test('filterOpenTabsForKnownTargets keeps the SKILL doc that left the page list', () => {
+ // A scope move deletes the source bundle BEFORE its response lands, so the
+ // source doc stops being a page mid-move. Pruning it there closed the tab
+ // `useMoveSkillScope` was about to repoint; the retarget then matched no
+ // open tab, did nothing, and the skill could not be opened until a reload.
+ // The skills reconciler owns this doc's lifecycle instead.
+ expect(
+ filterOpenTabsForKnownTargets(['.claude/skills/demo/SKILL', 'docs/a', 'deleted'], {
+ pages: new Set(['docs/a']),
+ folderPaths: new Set(),
+ assetPaths: new Set(),
+ }),
+ ).toEqual(['.claude/skills/demo/SKILL', 'docs/a']);
+ });
+
+ test('filterOpenTabsForKnownTargets still prunes a bundle FILE tab', () => {
+ // Deliberately NOT exempt. The reconciler keeps any tab whose SKILL still
+ // exists, so it will never close a `references/*` doc deleted out of band
+ // (an agent, MCP, another client). The page list is that file's only
+ // closer; exempting it would leave a live provider on a deleted file, and
+ // typing into that tab would rematerialise it on disk.
+ expect(
+ filterOpenTabsForKnownTargets(['.claude/skills/demo/references/notes'], {
+ pages: new Set(),
+ folderPaths: new Set(),
+ assetPaths: new Set(),
+ }),
+ ).toEqual([]);
+ });
+
+ test('filterOpenTabsForKnownTargets does not exempt a shape the reconciler cannot parse', () => {
+ // A symlinked bundle's canonical doc (`plugins/x/skills/<name>/SKILL`) is a
+ // REAL page, so it needs no exemption — and exempting it would be worse than
+ // useless: `parseSkillTabDocName` cannot read that shape, so nothing could
+ // ever close the tab once the skill was deleted.
+ expect(
+ filterOpenTabsForKnownTargets(['plugins/ok/skills/demo/SKILL'], {
+ pages: new Set(),
+ folderPaths: new Set(),
+ assetPaths: new Set(),
+ }),
+ ).toEqual([]);
+ expect(
+ filterOpenTabsForKnownTargets(['plugins/ok/skills/demo/SKILL'], {
+ pages: new Set(['plugins/ok/skills/demo/SKILL']),
+ folderPaths: new Set(),
+ assetPaths: new Set(),
+ }),
+ ).toEqual(['plugins/ok/skills/demo/SKILL']);
+ });
+
test('filterOpenTabsForKnownTargets preserves the active missing document draft', () => {
expect(
filterOpenTabsForKnownTargets(['docs/a', 'Untitled', 'deleted'], {
@@ -844,4 +895,27 @@ describe('skill discriminators reject template content shapes', () => {
test('isSkillTabId is false for a template content doc tab', () => {
expect(isSkillTabId(docTabId('docs/.ok/templates/note'))).toBe(false);
});
+
+ // Bundles are free to ship companion markdown beside SKILL.md — `tdd` on
+ // 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 = [
+ '.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);
+ });
+
+ 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 false for the bundle dir itself', () => {
+ expect(isSkillBundleShapedPath('.claude/skills/tdd')).toBe(false);
+ });
});
diff --git a/packages/app/src/editor/editor-tabs.ts b/packages/app/src/editor/editor-tabs.ts
index 9c68b2349..d4b2ead09 100644
--- a/packages/app/src/editor/editor-tabs.ts
+++ b/packages/app/src/editor/editor-tabs.ts
@@ -385,8 +385,15 @@ export function isSkillDocName(docName: string): boolean {
* link index and managed-artifact resolution, where a looser shape would mint
* skill edges for any document that happens to sit at this path. Widening only
* the surface decision keeps the blast radius at "which sidebar is showing".
+ *
+ * Every file under a bundle counts, not just `SKILL` and `references/**`. A
+ * skill is free to ship companion markdown at its bundle root (`tdd` on
+ * skills.sh ships `tests.md` + `mocking.md` beside `SKILL.md`), and those docs
+ * addressed as ordinary content dropped the sidebar to Files the moment the
+ * 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\/[^/]+\/(?:SKILL|references\/.+)$/;
+const SKILL_BUNDLE_SHAPED_PATH = /(?:^|\/)skills\/[^/]+\/.+$/;
export function isSkillBundleShapedPath(docName: string): boolean {
return SKILL_BUNDLE_SHAPED_PATH.test(docName);
@@ -567,6 +574,31 @@ export function filterOpenTabsForKnownTargets(
// coordinates (not a page) — keep it like skill-file so a page-list sync
// doesn't prune the open preview mid-session.
if (tab.kind === 'skill-preview') return true;
+ // The SKILL doc itself is owned by the skills reconciler
+ // (`useReconcileSkillTabs`), which decides against the SKILLS list and holds
+ // off while a write is in flight. The page list is the wrong authority for
+ // it: a scope move deletes the source bundle BEFORE its response lands, so
+ // the doc stops being a page mid-move and pruning it closes the very tab the
+ // move is about to repoint — the retarget then matches nothing and the skill
+ // cannot be opened again until a reload.
+ //
+ // Scoped as narrowly as that reason allows, and no wider:
+ // - the SKILL doc only (`rel === null`). A `references/*` tab keeps riding
+ // the page list, because an external delete (agent, MCP, another client)
+ // has no other closer — the reconciler keeps any tab whose SKILL still
+ // exists, so exempting them would leave a live provider on a deleted
+ // file, and typing in it would rematerialise the file on disk.
+ // - names the reconciler can actually PARSE. Exempting a shape it cannot
+ // read (a canonical `plugins/x/skills/foo/SKILL`, or an ordinary note at
+ // `docs/skills/react/SKILL.md`) would leave a tab nothing can ever close.
+ // Those names are real pages anyway, so the prune leaves them be.
+ // - the core parser directly, NOT the reconciler's `parseSkillTabDocName`
+ // wrapper: that lives in a hook which imports THIS module, and a value
+ // cycle here is what produced the CI "export not found" flake before.
+ // Global skills are managed-artifact docs and are already kept below.
+ if (tab.kind === 'doc' && parseProjectSkillBundleDoc(tab.docName)?.kind === 'skill') {
+ return true;
+ }
const markdownStem = stripMarkdownTabExtension(tab.docName);
return (
pages.has(tab.docName) ||
diff --git a/packages/app/src/editor/provider-pool.test.ts b/packages/app/src/editor/provider-pool.test.ts
index c596f8cdc..46f2c109f 100644
--- a/packages/app/src/editor/provider-pool.test.ts
+++ b/packages/app/src/editor/provider-pool.test.ts
@@ -555,6 +555,59 @@ describe('ProviderPool disconnect recycling', () => {
expect(pool.getActive()?.provider).toBe(originalProvider);
});
+
+ test('open() recycles a pooled entry whose socket already dropped', () => {
+ pool = new ProviderPool(3, DUMMY_WS);
+ const entry = pool.open('doc1');
+ if (!entry) throw new Error('expected entry');
+ pool.setActive('doc1');
+
+ const staleProvider = entry.provider;
+ staleProvider.emit('synced', { state: true });
+ // Socket drop reported as a status change: the pool records the entry as
+ // disconnected without arming the debounced recycle (that only happens on
+ // the 'disconnect' event), which is the state the hit path used to hand
+ // straight back to syncPromise.
+ staleProvider.emit('status', { status: 'disconnected' });
+ expect(entry.syncState).toBe('disconnected');
+
+ const reopened = pool.open('doc1');
+ expect(reopened).not.toBeNull();
+ expect(reopened?.provider).not.toBe(staleProvider);
+ expect(reopened?.syncState).toBe('connecting');
+ expect(pool.getActiveDocName()).toBe('doc1');
+ });
+
+ test('open() re-opens a disconnected background doc from scratch', () => {
+ pool = new ProviderPool(3, DUMMY_WS);
+ pool.open('doc1');
+ pool.setActive('doc1');
+ const background = pool.open('doc2');
+ if (!background) throw new Error('expected entry');
+
+ const staleProvider = background.provider;
+ staleProvider.emit('synced', { state: true });
+ staleProvider.emit('status', { status: 'disconnected' });
+
+ const reopened = pool.open('doc2');
+ expect(reopened?.provider).not.toBe(staleProvider);
+ expect(pool.entries.size).toBe(2);
+ });
+
+ test('open() keeps a disconnected entry that still holds unsynced edits', () => {
+ pool = new ProviderPool(3, DUMMY_WS);
+ const entry = pool.open('doc1');
+ if (!entry) throw new Error('expected entry');
+ pool.setActive('doc1');
+
+ const originalProvider = entry.provider;
+ originalProvider.emit('synced', { state: true });
+ originalProvider.unsyncedChanges = 1;
+ originalProvider.emit('status', { status: 'disconnected' });
+
+ // No buffer-and-replay on this path, so recycling would drop the edit.
+ expect(pool.open('doc1')?.provider).toBe(originalProvider);
+ });
});
describe('ProviderPool dispose', () => {
diff --git a/packages/app/src/editor/provider-pool.ts b/packages/app/src/editor/provider-pool.ts
index 48df5e3a0..6c3745de7 100644
--- a/packages/app/src/editor/provider-pool.ts
+++ b/packages/app/src/editor/provider-pool.ts
@@ -1723,6 +1723,39 @@ export class ProviderPool {
open(docName: string): PoolEntry | null {
if (isSystemDoc(docName)) return null;
+ // A pooled provider whose socket has already dropped can never emit
+ // `synced` again, so handing it back on the hit path parks the caller's
+ // `syncPromise` on an event that cannot arrive: it burns the full sync
+ // timeout, and only then does `DocumentErrorBoundary` recycle the entry
+ // and reload the same doc in a few hundred ms. Do that recovery eagerly
+ // instead. Skipped while the provider still holds unsynced local edits —
+ // this path has no buffer-and-replay (that exists only for
+ // `server-instance-mismatch`), the same reason the debounced
+ // disconnect-recycle re-checks `unsyncedChanges` at fire time. Gated on
+ // `hasSynced` for the same reason that path is: an entry still working
+ // through its first connect is waiting on a sync that its own backoff
+ // will deliver, and recycling it would discard a pending persistence
+ // attach on every open.
+ const pooled = this.entries.get(docName);
+ if (
+ pooled !== undefined &&
+ pooled.kind === 'active' &&
+ pooled.hasSynced &&
+ pooled.syncState === 'disconnected' &&
+ pooled.provider.unsyncedChanges === 0
+ ) {
+ mark('ok/pool/recycle-disconnected-on-open', { docName });
+ this.emitStructuredClientBreadcrumb({
+ event: 'ok-pool-recycle-disconnected-on-open',
+ docName,
+ });
+ this.recycleDisconnectedEntry(docName);
+ // The recycle re-admits the active doc under a fresh provider; any
+ // other doc is simply dropped and the MISS path below rebuilds it.
+ const reopened = this.entries.get(docName);
+ if (reopened !== undefined) return reopened;
+ }
+
const existing = this.entries.get(docName);
if (existing) {
const previousAccessedAt = existing.lastAccessedAt;
diff --git a/packages/app/src/hooks/use-explore-preview-install.scope.dom.test.tsx b/packages/app/src/hooks/use-explore-preview-install.scope.dom.test.tsx
new file mode 100644
index 000000000..c4f4dca2f
--- /dev/null
+++ b/packages/app/src/hooks/use-explore-preview-install.scope.dom.test.tsx
@@ -0,0 +1,69 @@
+import { render } from '@testing-library/react';
+import { describe, expect, test, vi } from 'vitest';
+
+/**
+ * The preview tab redirects into the real skill after import. `useOpenSkill`
+ * resolves a skill's doc by (scope, name), so the redirect MUST use the scope the
+ * bundle actually landed at — not the live `scope` selector, which the user can
+ * move and which can disagree with where the import ran.
+ *
+ * When they disagree the lookup misses, the `replaceActive` swap never happens,
+ * and you get both halves of the reported bug at once: the preview tab survives
+ * (so a second tab appears later) and the doc that was opened does not exist, so
+ * it sits on "Couldn't load document" until the sync times out.
+ */
+describe('preview redirect scope', () => {
+ test('redirects at the scope the import landed at, not the live selector', async () => {
+ vi.resetModules();
+
+ const openSkill = vi.fn();
+ vi.doMock('@/hooks/use-open-skill', () => ({ useOpenSkill: () => openSkill }));
+ // The selector says PROJECT; the import actually landed at GLOBAL.
+ vi.doMock('@/hooks/use-explore-preview-install', () => ({
+ useExplorePreviewInstall: () => ({
+ scope: 'project',
+ importedScope: 'global',
+ importedName: 'grill-me',
+ setScope: vi.fn(),
+ scopeLocked: true,
+ importNow: vi.fn(),
+ toggles: {
+ hostSet: new Set(),
+ installed: false,
+ installing: false,
+ toggleEditor: vi.fn(),
+ installAll: vi.fn(),
+ linkMode: false,
+ setLinkMode: vi.fn(),
+ setSource: vi.fn(),
+ placeAt: vi.fn(),
+ },
+ }),
+ }));
+
+ const { useExplorePreviewInstall } = await import('@/hooks/use-explore-preview-install');
+ const { useOpenSkill } = await import('@/hooks/use-open-skill');
+
+ // Exercise the redirect decision in isolation: the same expression
+ // SkillPreviewTab uses to choose the scope it opens with.
+ function Redirect() {
+ const previewInstall = useExplorePreviewInstall({
+ source: 'mattpocock/skills',
+ name: 'grill-me',
+ initialScope: 'project',
+ marketplace: true,
+ });
+ const open = useOpenSkill();
+ const landedName = previewInstall.importedName;
+ const landedScope = previewInstall.importedScope ?? previewInstall.scope;
+ if (landedName) open(landedScope, landedName, { replaceActive: true });
+ return null;
+ }
+
+ render(<Redirect />);
+
+ expect(openSkill).toHaveBeenCalledWith('global', 'grill-me', { replaceActive: true });
+ // The pre-fix behaviour: opening at 'project' resolves a doc that does not exist.
+ expect(openSkill).not.toHaveBeenCalledWith('project', 'grill-me', expect.anything());
+ });
+});
diff --git a/packages/app/src/hooks/use-explore-preview-install.ts b/packages/app/src/hooks/use-explore-preview-install.ts
index 3aceaab1f..42f3f6d9f 100644
--- a/packages/app/src/hooks/use-explore-preview-install.ts
+++ b/packages/app/src/hooks/use-explore-preview-install.ts
@@ -1,4 +1,8 @@
-import { isSkillInstallTarget, type SkillScope } from '@inkeep/open-knowledge-core';
+import {
+ AGENTS_SKILLS_ROOT,
+ isSkillInstallTarget,
+ type SkillScope,
+} from '@inkeep/open-knowledge-core';
import { useLingui } from '@lingui/react/macro';
import { useRef, useState } from 'react';
import { toast } from 'sonner';
@@ -36,6 +40,12 @@ export function useExplorePreviewInstall({
/** The on-disk skill name once imported (else null) — the caller transitions the
* preview tab into this real skill when the install menu closes. */
importedName: string | null;
+ /** The scope the bundle ACTUALLY landed at, captured at import time (else
+ * null). The caller must redirect against this, not the live `scope` state:
+ * `scope` is a user-settable selector that can move after the import, and
+ * opening a skill resolves its doc by (scope, name), so a disagreement sends
+ * the tab at a document that does not exist. */
+ importedScope: SkillScope | null;
/** Import WITHOUT installing anywhere (the custom-path flow) — returns the
* on-disk name, or null on failure (toast already shown). */
importNow: () => Promise<string | null>;
@@ -44,6 +54,9 @@ export function useExplorePreviewInstall({
const { t } = useLingui();
const [scope, setScope] = useState<SkillScope>(initialScope);
const [importedName, setImportedName] = useState<string | null>(null);
+ // Mirrors `importedScopeRef` into render state so the caller's redirect can
+ // read it; the ref alone is invisible to React.
+ const [importedScope, setImportedScope] = useState<SkillScope | null>(null);
const [hosts, setHosts] = useState<readonly string[]>([]);
const [busy, setBusy] = useState(false);
const liveHostsRef = useRef<readonly string[]>([]);
@@ -73,6 +86,7 @@ export function useExplorePreviewInstall({
}
importedNameRef.current = res.name;
importedScopeRef.current = importScope;
+ setImportedScope(importScope);
setImportedName(res.name);
return res.name;
});
@@ -137,7 +151,7 @@ export function useExplorePreviewInstall({
const result = await placeSkill({
scope: importScope,
name: skillName,
- dir: '.agents/skills',
+ dir: AGENTS_SKILLS_ROOT,
mode: 'copy',
});
if (result.ok) {
@@ -184,6 +198,7 @@ export function useExplorePreviewInstall({
setScope,
scopeLocked: importedName !== null || busy,
importedName,
+ importedScope,
importNow: ensureImported,
toggles,
};
diff --git a/packages/app/src/hooks/use-move-skill-scope.dom.test.tsx b/packages/app/src/hooks/use-move-skill-scope.dom.test.tsx
new file mode 100644
index 000000000..fde8088c8
--- /dev/null
+++ b/packages/app/src/hooks/use-move-skill-scope.dom.test.tsx
@@ -0,0 +1,119 @@
+import { renderHook } from '@testing-library/react';
+import { describe, expect, test, vi } from 'vitest';
+
+/**
+ * A scope move must repoint any open tab at the skill's REAL doc. An in-place
+ * project skill is open at its content path (`.claude/skills/<name>/SKILL`), so
+ * falling back to the store shape (`.ok/skills/<name>/SKILL`) matches no tab:
+ * the retarget silently no-ops and the tab is left on a path the move deletes,
+ * which is what stranded it on "Couldn't load document".
+ *
+ * The list lookup misses ROUTINELY here — `beginOptimisticSkillMove` drops the
+ * source row before this runs — so the fallback is the common path, not the edge.
+ */
+const retarget = vi.fn();
+const setSkillsSidebar = vi.fn();
+
+vi.doMock('@/components/ManagedArtifactProperties', () => ({
+ useManagedArtifactRetarget: () => retarget,
+}));
+vi.doMock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({
+ setSkillsSidebar,
+ // The real in-place project doc is open; the store-shaped name is not.
+ openTabs: ['.claude/skills/improve-codebase-architecture/SKILL'],
+ }),
+}));
+// Deliberately NOT ready: reproduces the lookup miss.
+vi.doMock('@/hooks/use-skills', () => ({ useSkills: () => ({ status: 'loading' }) }));
+vi.doMock('@/lib/skill-scope', () => ({
+ useSkillScopeLabels: () => ({ project: 'Project', global: 'Global' }),
+}));
+const beginSkillWrite = vi.fn();
+const endSkillWrite = vi.fn();
+vi.doMock('@/lib/documents-events', () => ({
+ beginSkillWrite,
+ endSkillWrite,
+ beginOptimisticSkillMove: vi.fn(),
+ endOptimisticSkillMove: vi.fn(),
+}));
+vi.doMock('@/lib/skills-api', () => ({
+ moveSkillScope: vi.fn(async () => ({ ok: true })),
+}));
+
+const { useMoveSkillScope } = await import('./use-move-skill-scope');
+
+describe('useMoveSkillScope retarget source', () => {
+ test('repoints the REAL in-place doc when the skills list lookup misses', async () => {
+ const { result } = renderHook(() => useMoveSkillScope());
+
+ await result.current({ scope: 'project', name: 'improve-codebase-architecture' }, 'global');
+
+ expect(retarget).toHaveBeenCalledTimes(1);
+ const [fromDoc, toDoc] = retarget.mock.calls[0] as [string, string];
+ expect(fromDoc).toBe('.claude/skills/improve-codebase-architecture/SKILL');
+ // The bug: a minted store path matches no open tab, so the retarget no-ops.
+ expect(fromDoc).not.toContain('.ok/skills');
+ expect(toDoc).toBe('__skill__/global/improve-codebase-architecture');
+ // And the surface stays on Skills rather than following into Files.
+ expect(setSkillsSidebar).toHaveBeenCalledWith(true);
+ });
+
+ test('refuses to retarget when no open tab matches the skill', async () => {
+ // The complement of the case above, and the actual safety net: with no
+ // resolvable source we must skip rather than fall back to a guessed name.
+ // Dropping this guard would silently reintroduce the store-shaped phantom.
+ retarget.mockClear();
+ setSkillsSidebar.mockClear();
+ const { result } = renderHook(() => useMoveSkillScope());
+
+ await result.current({ scope: 'project', name: 'not-an-open-tab' }, 'global');
+
+ expect(retarget).not.toHaveBeenCalled();
+ // The move still succeeded, so the surface must still stay on Skills.
+ expect(setSkillsSidebar).toHaveBeenCalledWith(true);
+ });
+});
+
+describe('the write flag is always released', () => {
+ test('a FAILED move releases it too', async () => {
+ // The flag suppresses the tab reconciler while set, so leaking it on the
+ // error path disables tab repair for the session just as surely as leaking
+ // it on success — and a failed move is exactly when the user retries.
+ const api = await import('@/lib/skills-api');
+ vi.mocked(api.moveSkillScope).mockResolvedValueOnce({ ok: false, error: 'nope' });
+ const { result } = renderHook(() => useMoveSkillScope());
+
+ const moved = await result.current(
+ { scope: 'project', name: 'improve-codebase-architecture' },
+ 'global',
+ );
+
+ expect(moved).toBe(false);
+ expect(endSkillWrite).toHaveBeenCalledWith('project', 'improve-codebase-architecture');
+ });
+
+ test('a throwing retarget still ends the write', async () => {
+ // The flag is module state that only a page reload clears, and it SUPPRESSES
+ // the tab reconciler for this skill while set. Leaking it disables the one
+ // thing that repairs a tab left on the pre-move doc: the tab never repoints,
+ // the toolbar keeps deriving its level from the stale doc name, and the
+ // skill stays stuck until the user reloads the window.
+ retarget.mockImplementationOnce(() => {
+ throw new Error('retarget blew up');
+ });
+ const { result } = renderHook(() => useMoveSkillScope());
+
+ const moved = await result.current(
+ { scope: 'project', name: 'improve-codebase-architecture' },
+ 'global',
+ );
+
+ expect(moved).toBe(true);
+ expect(beginSkillWrite).toHaveBeenCalledWith('project', 'improve-codebase-architecture');
+ expect(endSkillWrite).toHaveBeenCalledWith('project', 'improve-codebase-architecture');
+ // The move succeeded, so the surface belongs on Skills even though the tab
+ // repoint threw — otherwise a working move dumps the user into Files.
+ expect(setSkillsSidebar).toHaveBeenCalledWith(true);
+ });
+});
diff --git a/packages/app/src/hooks/use-move-skill-scope.ts b/packages/app/src/hooks/use-move-skill-scope.ts
index 406bd3cff..d9139df9e 100644
--- a/packages/app/src/hooks/use-move-skill-scope.ts
+++ b/packages/app/src/hooks/use-move-skill-scope.ts
@@ -2,8 +2,16 @@ import type { SkillScope } from '@inkeep/open-knowledge-core';
import { useLingui } from '@lingui/react/macro';
import { toast } from 'sonner';
import { useManagedArtifactRetarget } from '@/components/ManagedArtifactProperties';
+import { useDocumentContext } from '@/editor/DocumentContext';
+import { parseEditorTabId } from '@/editor/editor-tabs';
+import { parseSkillTabDocName } from '@/hooks/use-reconcile-skill-tabs';
import { useSkills } from '@/hooks/use-skills';
-import { beginOptimisticSkillMove, endOptimisticSkillMove } from '@/lib/documents-events';
+import {
+ beginOptimisticSkillMove,
+ beginSkillWrite,
+ endOptimisticSkillMove,
+ endSkillWrite,
+} from '@/lib/documents-events';
import { skillEntryLiveDocName, skillLiveDocName } from '@/lib/managed-artifact-doc-name';
import { useSkillScopeLabels } from '@/lib/skill-scope';
import { moveSkillScope } from '@/lib/skills-api';
@@ -21,15 +29,23 @@ export function useMoveSkillScope(): (
const { t } = useLingui();
const scopeLabels = useSkillScopeLabels();
const retarget = useManagedArtifactRetarget();
+ const { setSkillsSidebar, openTabs } = useDocumentContext();
const skillsState = useSkills();
return async (skill, toScope) => {
if (toScope === skill.scope) return false;
// Optimistically drop the source row the instant it's confirmed — the move
// deletes the source last, so without this the row lingers through the copy.
+ // Mark the whole operation, not just the optimistic row-hide. The optimistic
+ // flag is cleared as soon as the request returns, which is BEFORE the
+ // retarget runs and before the list carries the skill at its new scope — so
+ // the reconciler saw it absent from both scopes with no guard set and closed
+ // the tab. Cleared in the single exit below, after the retarget.
+ beginSkillWrite(skill.scope, skill.name);
beginOptimisticSkillMove(skill.scope, skill.name);
const result = await moveSkillScope({ name: skill.name, fromScope: skill.scope, toScope });
endOptimisticSkillMove(skill.scope, skill.name);
if (!result.ok) {
+ endSkillWrite(skill.scope, skill.name);
toast.error(t`Couldn't move skill: ${result.error}`);
return false;
}
@@ -45,14 +61,84 @@ export function useMoveSkillScope(): (
skillsState.status === 'ready'
? skillsState.data.find((sk) => sk.scope === skill.scope && sk.name === skill.name)
: undefined;
- const fromDoc = entry
- ? skillEntryLiveDocName(entry)
- : skillLiveDocName(skill.scope, skill.name);
+ // Resolve the FROM doc from the open tabs when the list lookup misses —
+ // never from `skillLiveDocName`, which mints the store shape
+ // (`.ok/skills/<name>/SKILL`). An in-place project skill is open at its real
+ // content path (`.claude/skills/<name>/SKILL`), so the store name matches no
+ // tab: the retarget silently hits nothing and the tab is left pointing at a
+ // path this move is about to delete. That is the stranded tab on a
+ // non-existent doc, which then sits on "Couldn't load document".
+ //
+ // The lookup misses routinely, not rarely: `beginOptimisticSkillMove` has
+ // already dropped the source row by this point, and the list may still be
+ // refetching. `useOpenSkill` carries the same never-mint-the-store-shape
+ // rule; this is the path that was missing it.
+ const skillTabs = openTabs
+ .map((id) => parseEditorTabId(id))
+ .filter((tab) => {
+ if (tab.kind !== 'doc') return false;
+ const parsed = parseSkillTabDocName(tab.docName);
+ return parsed?.scope === skill.scope && parsed.name === skill.name;
+ });
+ // Prefer the SKILL-level tab, but fall back to a bundle-FILE tab of the same
+ // skill. Clicking a skill and then one of its bundle files leaves the file
+ // tab as the only one for that skill (the file replaces the SKILL preview
+ // tab), and with nothing to repoint the user was left on a doc this move
+ // deletes — the tab reconciler then closed it, emptying the Skills surface,
+ // which fell back to Files. Both shapes land on the same `toDoc`, so a file
+ // tab simply follows its skill to the new scope.
+ const openSkillDoc =
+ skillTabs.find(
+ (tab) => tab.kind === 'doc' && parseSkillTabDocName(tab.docName)?.rel === null,
+ ) ?? skillTabs[0];
+ // An actually-open tab outranks the list entry. `retarget` repoints a tab BY
+ // doc name, so a name no tab carries silently repoints nothing — which is
+ // what happened whenever the open tab was a bundle FILE: the entry resolved
+ // to the skill's SKILL doc, the retarget hit nothing, and the file tab was
+ // left on a doc the move deletes. When no tab is open the retarget is a
+ // no-op either way, so the entry stays as the fallback.
+ const fromDoc =
+ openSkillDoc?.kind === 'doc'
+ ? openSkillDoc.docName
+ : entry
+ ? skillEntryLiveDocName(entry)
+ : // Global skills open at the managed `__skill__/global/<name>` doc, which
+ // is a real resolvable name rather than a minted store path.
+ skill.scope === 'global'
+ ? skillLiveDocName(skill.scope, skill.name)
+ : null;
const toDoc =
toScope === 'project' && result.path !== undefined
? `${result.path.replace(/\/+$/, '')}/SKILL`
: skillLiveDocName(toScope, skill.name);
- retarget(fromDoc, toDoc);
+ // No resolvable source means no open tab to repoint — skip rather than
+ // retarget from a guessed name.
+ //
+ // Guarded because the write flag below is module state that ONLY a reload
+ // clears, and it suppresses the tab reconciler for this skill while set. A
+ // throw in here would therefore disable the very thing that repairs a tab
+ // left on the old scope: the tab never repoints, the toolbar keeps deriving
+ // its level from the stale doc name, and the skill stays unfixable for the
+ // rest of the session. Releasing the flag matters more than the retarget
+ // succeeding — the reconciler can redo a retarget, but not un-leak a flag.
+ try {
+ if (fromDoc !== null) retarget(fromDoc, toDoc);
+ } catch (err) {
+ console.error('[skill-move-scope] retarget failed after a successful move', err);
+ }
+ // Pin the sidebar to Skills, like every other skill mutation (delete, file
+ // delete, rename retarget). A project skill's doc is ordinary project
+ // CONTENT (`.claude/skills/<name>/SKILL`), so retargeting onto it lets the
+ // surface autofollow to Files — the user asks to move a skill and lands in
+ // the file tree instead of on the skill they just moved.
+ //
+ // OUTSIDE the guard: the move already succeeded, so the surface belongs on
+ // Skills whether or not the tab repoint threw. Inside, a throwing retarget
+ // dropped the user into Files on a move that worked.
+ setSkillsSidebar(true);
+ // Released only now: the tab has been repointed and the surface pinned, so
+ // an absent reading after this really is an absence.
+ endSkillWrite(skill.scope, skill.name);
return true;
};
}
diff --git a/packages/app/src/hooks/use-open-skill.dom.test.tsx b/packages/app/src/hooks/use-open-skill.dom.test.tsx
new file mode 100644
index 000000000..76d5a302c
--- /dev/null
+++ b/packages/app/src/hooks/use-open-skill.dom.test.tsx
@@ -0,0 +1,72 @@
+import { renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+/**
+ * The shared opener is where every "open a skill" surface converges, so it owns
+ * the gitignored-bundle gate. Two rules, and both have bitten:
+ * - a gitignored bundle has no doc to open, so raise the explainer instead of
+ * handing the user an empty tab with no reason;
+ * - EXCEPT a managed built-in, which OK ships read-only and a repo that
+ * ignores it means it — offering to git-track one is an offer the user must
+ * not be given.
+ */
+const openTarget = vi.fn();
+const setSkillsSidebar = vi.fn();
+const requestSkillTrackPrompt = vi.fn();
+
+vi.doMock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ openTarget, setSkillsSidebar }),
+}));
+vi.doMock('@/lib/skill-track-prompt-store', () => ({ requestSkillTrackPrompt }));
+vi.doMock('@/lib/skills-api', () => ({ listSkills: vi.fn() }));
+
+const entry = {
+ scope: 'project' as const,
+ name: 'hidden',
+ path: '.claude/skills/hidden/SKILL.md',
+ installed: true,
+ hosts: [],
+};
+let skills: unknown[] = [];
+vi.doMock('@/hooks/use-skills', () => ({ useSkills: () => ({ status: 'ready', data: skills }) }));
+
+const { useOpenSkill } = await import('./use-open-skill');
+
+afterEach(() => {
+ openTarget.mockClear();
+ requestSkillTrackPrompt.mockClear();
+});
+
+describe('useOpenSkill gitignored gate', () => {
+ test('a gitignored skill raises the explainer instead of an empty tab', () => {
+ skills = [{ ...entry, ignored: true }];
+ const { result } = renderHook(() => useOpenSkill());
+ result.current('project', 'hidden');
+
+ expect(requestSkillTrackPrompt).toHaveBeenCalledWith({ scope: 'project', name: 'hidden' });
+ expect(openTarget).not.toHaveBeenCalled();
+ });
+
+ test('a managed built-in is never offered the git-track fix', () => {
+ // Read-only and deliberately excluded: it opens through its own read-only
+ // preview surface, and must not be routed into "add a .gitignore rule".
+ skills = [{ ...entry, ignored: true, managed: true }];
+ const { result } = renderHook(() => useOpenSkill());
+ result.current('project', 'hidden');
+
+ expect(requestSkillTrackPrompt).not.toHaveBeenCalled();
+ expect(openTarget).toHaveBeenCalled();
+ });
+
+ test('an ordinary skill opens, untouched by the gate', () => {
+ skills = [entry];
+ const { result } = renderHook(() => useOpenSkill());
+ result.current('project', 'hidden');
+
+ expect(requestSkillTrackPrompt).not.toHaveBeenCalled();
+ expect(openTarget).toHaveBeenCalledWith(
+ expect.objectContaining({ docName: '.claude/skills/hidden/SKILL' }),
+ undefined,
+ );
+ });
+});
diff --git a/packages/app/src/hooks/use-open-skill.ts b/packages/app/src/hooks/use-open-skill.ts
index d806551c7..c46465b6a 100644
--- a/packages/app/src/hooks/use-open-skill.ts
+++ b/packages/app/src/hooks/use-open-skill.ts
@@ -3,8 +3,13 @@ import { t } from '@lingui/core/macro';
import { toast } from 'sonner';
import { useDocumentContext } from '@/editor/DocumentContext';
import { useSkills } from '@/hooks/use-skills';
-import { hashFromDocName, replaceHashWithoutNavigation } from '@/lib/doc-hash';
+import {
+ hashFromDocName,
+ pushHashWithoutNavigation,
+ replaceHashWithoutNavigation,
+} from '@/lib/doc-hash';
import { skillEntryLiveDocName, skillLiveDocName } from '@/lib/managed-artifact-doc-name';
+import { requestSkillTrackPrompt } from '@/lib/skill-track-prompt-store';
import { listSkills } from '@/lib/skills-api';
/**
@@ -23,9 +28,16 @@ import { listSkills } from '@/lib/skills-api';
export function useOpenSkill(): (
scope: SkillScope,
name: string,
- opts?: { replaceActive?: boolean; path?: string },
+ opts?: {
+ replaceActive?: boolean;
+ path?: string;
+ /** Replace the history entry instead of pushing one — for an open that
+ * SUPERSEDES what the user is looking at (the preview tab becoming the
+ * real skill after an install), not merely one that reuses the tab. */
+ replaceHistory?: boolean;
+ },
) => void {
- const { openTarget } = useDocumentContext();
+ const { openTarget, setSkillsSidebar } = useDocumentContext();
const skillsState = useSkills();
return (scope, name, opts) => {
const open = (docName: string) => {
@@ -36,7 +48,26 @@ export function useOpenSkill(): (
{ kind: 'doc', target: docName, docName },
opts?.replaceActive ? { tabBehavior: 'replace-active' } : undefined,
);
- replaceHashWithoutNavigation(hashFromDocName(docName));
+ // Pin the surface to Skills AFTER the open, never before: committing a tab
+ // re-arms autofollow, so a pin set first is simply overwritten. A PROJECT
+ // skill's doc is ordinary project content (`.claude/skills/<name>/SKILL`),
+ // so autofollow drops the user into the file tree after they asked for a
+ // skill. This is the shared entry point every open-a-skill surface routes
+ // through — sidebar click, create, import, detected-adopt, and the
+ // post-install redirect — so pinning here covers all of them.
+ setSkillsSidebar(true);
+ // PUSH for a user-initiated open; REPLACE only when this open supersedes
+ // the entry the user is standing on.
+ //
+ // Deliberately NOT keyed on `replaceActive`: that means "reuse the TAB"
+ // (the preview-tabs preference, on by default) and says nothing about
+ // history. Conflating them makes every ordinary skill click replace, which
+ // eats the entry it came from — opening a skill from the Skills home
+ // overwrote `#/__skills__`, so Back skipped it and landed on whatever
+ // preceded it. Caught by `navigation-history.e2e.ts`.
+ const hash = hashFromDocName(docName);
+ if (opts?.replaceHistory) replaceHashWithoutNavigation(hash);
+ else pushHashWithoutNavigation(hash);
};
// Entry-first: an existing skill's REAL doc (in-place skills live at
// editor-dir paths, not the store). A fresh create's entry hasn't landed
@@ -45,6 +76,19 @@ export function useOpenSkill(): (
skillsState.status === 'ready'
? skillsState.data.find((sk) => sk.scope === scope && sk.name === name)
: undefined;
+ // A gitignored bundle is listed but never indexed, so there is no doc to
+ // open — every surface that routes through here would otherwise hand the
+ // user an empty tab and no reason. Explain it once, from the one place all
+ // of them come through, and offer the `.gitignore` line that fixes it.
+ // `canonicalPath` present means the bundle is mounted through a symlink and
+ // the server judged `ignored` on the resolved path, which is the one this
+ // opener uses — so the flag and the open agree. Kept explicit because the
+ // two were computed from different paths once, and that combination refused
+ // to open a skill that opened fine.
+ if (entry?.ignored === true && entry.managed !== true) {
+ requestSkillTrackPrompt({ scope: entry.scope, name: entry.name });
+ return;
+ }
if (entry) return open(skillEntryLiveDocName(entry));
if (scope === 'project' && opts?.path) return open(opts.path.replace(/\.mdx?$/i, ''));
// Global: the managed `__skill__/global/<name>` doc resolves store-or-native
diff --git a/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts b/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts
index 3c4576aed..280cdd04f 100644
--- a/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts
+++ b/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts
@@ -220,14 +220,74 @@ describe('computeSkillTabReconcile', () => {
expect(actions).toEqual([{ kind: 'close', docName: '.ok/skills/demo/references/notes' }]);
});
- test('closes a reference FILE tab when its skill moved scope (SKILL tab follows the move)', () => {
- // A file tab is not retargeted (its new-scope doc name is not reconstructed);
- // the SKILL tab retargets to the new scope, so the skill stays open.
+ test('closes a reference FILE tab when its skill moved scope and the SKILL tab carries it', () => {
+ // A file tab is not retargeted to its own new-scope name (that name is not
+ // reconstructed); the SKILL tab retargets to the new scope, so the skill
+ // stays open and the file tab can just close.
const actions = computeSkillTabReconcile(
- ['.ok/skills/demo/references/notes'],
+ ['.ok/skills/demo/SKILL', '.ok/skills/demo/references/notes'],
[{ scope: 'global', name: 'demo', path: '~/.claude/skills/demo/SKILL.md' }],
);
- expect(actions).toEqual([{ kind: 'close', docName: '.ok/skills/demo/references/notes' }]);
+ expect(actions).toEqual([
+ {
+ kind: 'retarget',
+ fromDocName: '.ok/skills/demo/SKILL',
+ toDocName: skillLiveDocName('global', 'demo'),
+ },
+ { kind: 'close', docName: '.ok/skills/demo/references/notes' },
+ ]);
+ });
+
+ // Clicking a skill and then one of its bundle files leaves the FILE tab as the
+ // only tab for that skill — the file replaces the SKILL preview tab. Closing
+ // it on a scope move emptied the Skills surface, which fell back to Files.
+ test('retargets a lone bundle FILE tab to the new scope SKILL doc on a scope move', () => {
+ const actions = computeSkillTabReconcile(
+ ['.claude/skills/demo/mocking'],
+ [{ scope: 'global', name: 'demo', path: '~/.claude/skills/demo/SKILL.md' }],
+ );
+ expect(actions).toEqual([
+ {
+ kind: 'retarget',
+ fromDocName: '.claude/skills/demo/mocking',
+ toDocName: skillLiveDocName('global', 'demo'),
+ },
+ ]);
+ });
+
+ test('promotes only ONE of several lone bundle FILE tabs, closing the rest', () => {
+ const actions = computeSkillTabReconcile(
+ ['.claude/skills/demo/mocking', '.claude/skills/demo/tests'],
+ [{ scope: 'global', name: 'demo', path: '~/.claude/skills/demo/SKILL.md' }],
+ );
+ expect(actions).toEqual([
+ {
+ kind: 'retarget',
+ fromDocName: '.claude/skills/demo/mocking',
+ toDocName: skillLiveDocName('global', 'demo'),
+ },
+ { kind: 'close', docName: '.claude/skills/demo/tests' },
+ ]);
+ });
+
+ // A companion doc lives outside `references/`, so the canonical parsers drop
+ // it. Unseen here, a delete left its tab on a doc that no longer exists.
+ test('closes a companion bundle tab when its skill is deleted', () => {
+ expect(computeSkillTabReconcile(['.claude/skills/demo/mocking'], [])).toEqual([
+ { kind: 'close', docName: '.claude/skills/demo/mocking' },
+ ]);
+ expect(computeSkillTabReconcile(['__skill__/global/demo/mocking'], [])).toEqual([
+ { kind: 'close', docName: '__skill__/global/demo/mocking' },
+ ]);
+ });
+
+ test('leaves a companion bundle tab alone while its skill still exists', () => {
+ expect(
+ computeSkillTabReconcile(
+ ['.claude/skills/demo/mocking'],
+ [{ scope: 'project', name: 'demo', path: '.claude/skills/demo/SKILL.md' }],
+ ),
+ ).toEqual([]);
});
test('ignores non-skill tabs entirely', () => {
@@ -235,3 +295,33 @@ describe('computeSkillTabReconcile', () => {
expect(actions).toEqual([]);
});
});
+
+describe('scope-move window', () => {
+ const projectTab = '.claude/skills/grill-me/SKILL';
+
+ test('does NOT close a skill tab while its move is still in flight', () => {
+ // The window a move passes through: source row optimistically hidden, and
+ // the destination row has not landed. Treating that as a deletion drops the
+ // user's tab, leaving an empty "New tab" with the surface falling to Files.
+ const actions = computeSkillTabReconcile([projectTab], [], () => true);
+ expect(actions).toEqual([]);
+ });
+
+ test('still closes a tab for a skill that is genuinely gone', () => {
+ // The guard must not swallow real deletions — that is what the reconciler
+ // exists for.
+ const actions = computeSkillTabReconcile([projectTab], [], () => false);
+ expect(actions).toEqual([{ kind: 'close', docName: projectTab }]);
+ });
+
+ test('retargets once the skill lands at its new scope', () => {
+ const actions = computeSkillTabReconcile(
+ [projectTab],
+ [{ scope: 'global', name: 'grill-me', path: '.agents/skills/grill-me/SKILL.md' }],
+ () => true,
+ );
+ expect(actions).toEqual([
+ { kind: 'retarget', fromDocName: projectTab, toDocName: '__skill__/global/grill-me' },
+ ]);
+ });
+});
diff --git a/packages/app/src/hooks/use-reconcile-skill-tabs.ts b/packages/app/src/hooks/use-reconcile-skill-tabs.ts
index 725f5da3d..c7070a154 100644
--- a/packages/app/src/hooks/use-reconcile-skill-tabs.ts
+++ b/packages/app/src/hooks/use-reconcile-skill-tabs.ts
@@ -1,6 +1,7 @@
import {
type ManagedArtifactScope,
parseGlobalSkillBundleDoc,
+ parseManagedArtifactName,
parseProjectSkillBundleDoc,
type SkillsListEntry,
} from '@inkeep/open-knowledge-core';
@@ -8,15 +9,31 @@ import { useEffect, useRef } from 'react';
import { useManagedArtifactRetarget } from '@/components/ManagedArtifactProperties';
import { useDocumentContext } from '@/editor/DocumentContext';
import { parseEditorTabId } from '@/editor/editor-tabs';
+import {
+ isOptimisticallyMoving,
+ isSkillWritePending,
+ pendingSkillWritesKey,
+} from '@/lib/documents-events';
import { skillEntryFileLiveDocName, skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';
import { useSkills } from './use-skills';
+/**
+ * Companion markdown a bundle ships OUTSIDE `references/` — `<host>/skills/
+ * <name>/<rel>`. The two canonical parsers admit only `SKILL` and
+ * `references/**`, so without this a companion tab is invisible here and a
+ * scope move or delete leaves it pointing at a doc it just removed. Anchored on
+ * the same leading-dot host segment the canonical project parser uses: this
+ * feeds a CLOSE decision, and a looser shape would evict an ordinary content
+ * doc that merely lives under some `skills/` directory.
+ */
+const PROJECT_SKILL_COMPANION_DOC_RE = /^\.[A-Za-z0-9_-]+\/skills\/([^/]+)\/(.+)$/;
+
/**
* A skill tab's identity parsed from its live doc name. Covers BOTH the
- * SKILL-level doc (`rel: null`) AND a bundle-FILE doc (`references/<rel>`) — a
- * project content doc or a global managed-artifact doc. Returns null when the
- * doc name isn't a skill or skill-file. Recognizing file tabs is what lets a
- * reference-editing tab close when its skill is deleted.
+ * SKILL-level doc (`rel: null`) AND any bundle-FILE doc — a project content doc
+ * or a global managed-artifact doc. Returns null when the doc name isn't a
+ * skill or skill-file. Recognizing file tabs is what lets a bundle-editing tab
+ * close when its skill is deleted.
*/
export function parseSkillTabDocName(
docName: string,
@@ -25,6 +42,16 @@ export function parseSkillTabDocName(
if (project) return { scope: 'project', name: project.name, rel: project.rel };
const global = parseGlobalSkillBundleDoc(docName);
if (global) return { scope: 'global', name: global.name, rel: global.rel };
+ // Managed-artifact names carry any bundle-relative `rel`, so this catches a
+ // global companion (`__skill__/global/<name>/<rel>`) the strict parser drops.
+ const managed = parseManagedArtifactName(docName);
+ if (managed?.kind === 'skill') {
+ return { scope: managed.scope, name: managed.name, rel: managed.rel };
+ }
+ const companion = PROJECT_SKILL_COMPANION_DOC_RE.exec(docName);
+ if (companion) {
+ return { scope: 'project', name: companion[1] as string, rel: companion[2] as string };
+ }
return null;
}
@@ -51,7 +78,10 @@ export function tabIdsForSkill(
*/
export function tabIdsForSkillFile(
openTabIds: ReadonlyArray<string>,
- skill: Pick<SkillsListEntry, 'scope' | 'name' | 'path'>,
+ // `canonicalPath` included deliberately: `skillEntryFileLiveDocName` prefers
+ // it, so a caller passing a literal without it would mint alias-shaped names
+ // that match no open tab and silently select nothing.
+ skill: Pick<SkillsListEntry, 'scope' | 'name' | 'path' | 'canonicalPath'>,
filePath: string,
): string[] {
const liveDocName = skillEntryFileLiveDocName(skill, filePath);
@@ -110,16 +140,33 @@ export type SkillTabReconcileAction =
* new live doc (follows the move);
* - the skill is gone entirely (deleted) → close the tab, INCLUDING a
* reference-FILE tab — the lingering tab a delete used to leave;
- * - a bundle-FILE tab whose skill moved scope → close it (its SKILL tab
- * retargets to the new scope, so the skill stays open).
+ * - a bundle-FILE tab whose skill moved scope → close it, PROVIDED the skill
+ * stays open some other way. Clicking a skill and then one of its bundle
+ * files leaves the file tab as the only one for that skill (the file
+ * replaces the SKILL preview tab), and closing it outright emptied the
+ * Skills surface, which then fell back to Files — the user asked to move a
+ * skill and landed in the file tree. With no SKILL-level tab to carry them,
+ * the first such tab retargets to the new scope's SKILL doc instead.
* A tab whose skill still exists at its own scope is untouched.
*/
export function computeSkillTabReconcile(
openTabDocNames: ReadonlyArray<string>,
skills: ReadonlyArray<Pick<SkillsListEntry, 'name' | 'scope' | 'path'>>,
+ /** Is a write in flight for this skill? While one is, its absence from the
+ * list is not evidence of deletion, so nothing destructive may act on it. */
+ isBusy: (scope: ManagedArtifactScope, name: string) => boolean = (scope, name) =>
+ isOptimisticallyMoving(scope, name) || isSkillWritePending(scope, name),
): SkillTabReconcileAction[] {
const present = new Map(skills.map((s) => [`${s.scope}\u0000${s.name}`, s]));
const actions: SkillTabReconcileAction[] = [];
+ // Skills that already have a SKILL-level tab open to carry the move, plus the
+ // ones a bundle-file tab has been promoted to carry it. One promotion per
+ // skill: a second retarget onto the same doc would duplicate the tab.
+ const carried = new Set<string>();
+ for (const docName of openTabDocNames) {
+ const tab = parseSkillTabDocName(docName);
+ if (tab !== null && tab.rel === null) carried.add(`${tab.scope}\u0000${tab.name}`);
+ }
for (const docName of openTabDocNames) {
const tab = parseSkillTabDocName(docName);
if (!tab) continue;
@@ -137,6 +184,14 @@ export function computeSkillTabReconcile(
fromDocName: docName,
toDocName: skillEntryLiveDocName(moved),
});
+ } else if (isBusy(tab.scope, tab.name)) {
+ } else if (moved !== undefined && !carried.has(`${tab.scope}\u0000${tab.name}`)) {
+ carried.add(`${tab.scope}\u0000${tab.name}`);
+ actions.push({
+ kind: 'retarget',
+ fromDocName: docName,
+ toDocName: skillEntryLiveDocName(moved),
+ });
} else {
actions.push({ kind: 'close', docName });
}
@@ -167,10 +222,15 @@ export function useReconcileSkillTabs(): void {
useEffect(() => {
if (skillsState.status !== 'ready') return;
const skills = skillsState.data;
+ // Pending writes belong in the signature: a guarded close is DEFERRED,
+ // not cancelled, so clearing the flag must re-run this effect. Without it
+ // the list is identical either side of the write, the effect short-
+ // circuits, and "close once it settles" silently becomes "never" —
+ // leaking dead tabs instead of closing them.
const signature = `${openTabs.join('\u0001')}\u0002${skills
.map((s) => `${s.scope}\u0000${s.name}`)
.sort()
- .join('\u0001')}`;
+ .join('\u0001')}\u0002${pendingSkillWritesKey()}`;
if (lastSignatureRef.current === signature) return;
lastSignatureRef.current = signature;
diff --git a/packages/app/src/hooks/use-skill-scope-move.dom.test.tsx b/packages/app/src/hooks/use-skill-scope-move.dom.test.tsx
index 305dedb8f..2169e00e7 100644
--- a/packages/app/src/hooks/use-skill-scope-move.dom.test.tsx
+++ b/packages/app/src/hooks/use-skill-scope-move.dom.test.tsx
@@ -17,11 +17,18 @@ vi.doMock('@lingui/react/macro', () => linguiShim);
const moveSkillScope = vi.fn(async () => ({ ok: true as const, skippedBinaryFiles: [] }));
const retarget = vi.fn(() => {});
+// `useMoveSkillScope` reads DocumentContext to pin the Skills sidebar across a
+// move and to resolve the open tab it must repoint. No provider here, so stub it.
+vi.doMock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ setSkillsSidebar: vi.fn(), openTabs: [] }),
+}));
vi.doMock('@/lib/skills-api', () => ({ moveSkillScope }));
vi.doMock('@/components/ManagedArtifactProperties', () => ({
useManagedArtifactRetarget: () => retarget,
}));
vi.doMock('@/lib/documents-events', () => ({
+ beginSkillWrite: vi.fn(),
+ endSkillWrite: vi.fn(),
beginOptimisticSkillMove: () => {},
endOptimisticSkillMove: () => {},
// Pulled in transitively by use-skills (the move hook now resolves the real
diff --git a/packages/app/src/hooks/use-skills.dom.test.tsx b/packages/app/src/hooks/use-skills.dom.test.tsx
new file mode 100644
index 000000000..2a9e022e5
--- /dev/null
+++ b/packages/app/src/hooks/use-skills.dom.test.tsx
@@ -0,0 +1,238 @@
+import { render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+
+const originalFetch = globalThis.fetch;
+
+function skillsBody(names: readonly string[]) {
+ return {
+ skills: names.map((name) => ({
+ scope: 'project',
+ name,
+ path: `.agents/skills/${name}/SKILL.md`,
+ installed: false,
+ hosts: [],
+ })),
+ truncated: false,
+ };
+}
+
+const jsonResponse = (body: unknown) =>
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+
+/**
+ * `useSkills` keeps its shared list, in-flight request and invalidation
+ * generation in MODULE state, and vitest gives a fresh registry per FILE, not
+ * per test. Without this reset the second test would mount already-`ready` from
+ * the first test's `lastKnownSkills` and its `waitFor` would pass before any
+ * fetch resolved — green for the wrong reason.
+ */
+async function freshModules() {
+ vi.resetModules();
+ const [{ useSkills }, events] = await Promise.all([
+ import('./use-skills'),
+ import('@/lib/documents-events'),
+ ]);
+ return { useSkills, ...events };
+}
+
+describe('useSkills', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ vi.useRealTimers();
+ });
+
+ // The staleness bug: every surface shares ONE in-flight request. A mutation
+ // that lands while that request is in the air used to coalesce onto it, so the
+ // list settled on PRE-write data and never self-healed — the menu kept showing
+ // a skill the user had just removed.
+ //
+ // Both subscription branches (the local skills-changed bus and the cross-client
+ // CC1 `files` signal) route through the same `bump()`, but the WIRING is per
+ // branch: a refactor that dropped the remote one, or broke the
+ // `channels.includes('files')` filter, would regress cross-window mutations
+ // while a local-only test stayed green. So each branch gets its own case.
+ for (const trigger of ['local skills-changed', 'cross-client CC1 files'] as const) {
+ test(`a mutation mid-flight is not served pre-write data (${trigger})`, async () => {
+ const { useSkills, emitSkillsChanged, emitDocumentsChanged } = await freshModules();
+
+ let release: ((body: unknown) => void) | undefined;
+ const first = new Promise<unknown>((resolve) => {
+ release = resolve;
+ });
+
+ // Track concurrency, not just call count: the fix must keep the
+ // single-flight ceiling (one full server scan at a time) while still
+ // refusing to serve pre-write data.
+ let live = 0;
+ let maxLive = 0;
+ const fetchMock = vi
+ .fn()
+ .mockImplementationOnce(async () => {
+ live++;
+ maxLive = Math.max(maxLive, live);
+ try {
+ return jsonResponse(await first);
+ } finally {
+ live--;
+ }
+ })
+ .mockImplementation(async () => {
+ live++;
+ maxLive = Math.max(maxLive, live);
+ try {
+ return jsonResponse(skillsBody(['kept']));
+ } finally {
+ live--;
+ }
+ });
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+
+ function Probe() {
+ const state = useSkills();
+ return (
+ <div data-testid="names">
+ {state.status === 'ready' ? state.data.map((s) => s.name).join(',') : state.status}
+ </div>
+ );
+ }
+
+ render(<Probe />);
+ // Nothing is known yet — proves the module reset actually took, so the
+ // assertions below cannot pass on a previous test's cached list.
+ expect(screen.getByTestId('names').textContent).toBe('loading');
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+
+ // The write lands while request #1 is still in the air, and #1 stays in
+ // the air past the hook's 200 ms coalescing debounce — so the refetch it
+ // schedules is issued while #1 is STILL the shared in-flight promise.
+ if (trigger === 'local skills-changed') emitSkillsChanged();
+ else emitDocumentsChanged(['files']);
+ await new Promise((r) => setTimeout(r, 400));
+
+ // Still exactly one scan: the refetch joined the live request rather than
+ // stacking a second concurrent walk of every skills root.
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+
+ // #1 now lands carrying pre-write data. It must be discarded and re-run,
+ // never handed to the caller.
+ release?.(skillsBody(['kept', 'removed']));
+
+ await waitFor(() => expect(screen.getByTestId('names').textContent).toBe('kept'));
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(maxLive).toBe(1);
+ });
+ }
+
+ // The remote branch is filtered: a signal on an unrelated channel must NOT
+ // invalidate, or every backlink/graph recompute would spin a full skills scan.
+ test('a CC1 signal on an unrelated channel does not trigger a refetch', async () => {
+ const { useSkills, emitDocumentsChanged } = await freshModules();
+
+ const fetchMock = vi.fn().mockImplementation(async () => jsonResponse(skillsBody(['kept'])));
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+
+ function Probe() {
+ const state = useSkills();
+ return <div data-testid="names">{state.status}</div>;
+ }
+
+ render(<Probe />);
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+
+ emitDocumentsChanged(['backlinks']);
+ await new Promise((r) => setTimeout(r, 400));
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('a hung request cannot wedge the shared list', () => {
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ test('carries an abort signal, so a stalled fetch cannot hang forever', async () => {
+ // Every reader joins `inFlightSkills`, and the slot is released only in that
+ // promise's `.finally`. Without a signal, one fetch that never settles
+ // freezes the skills list for the rest of the session — stale rows, stale
+ // toolbar, clicks minting doc names from entries that have since moved —
+ // and only a reload clears it, because the slot is module state.
+ const { useSkills } = await freshModules();
+ const seen: (RequestInit | undefined)[] = [];
+ globalThis.fetch = vi.fn((_url: string, init?: RequestInit) => {
+ seen.push(init);
+ return Promise.resolve(jsonResponse(skillsBody(['a'])));
+ }) as unknown as typeof fetch;
+
+ function Probe() {
+ const state = useSkills();
+ return <div data-testid="s">{state.status}</div>;
+ }
+ render(<Probe />);
+ await waitFor(() => expect(screen.getByTestId('s').textContent).toBe('ready'));
+ expect(seen[0]?.signal).toBeInstanceOf(AbortSignal);
+ });
+
+ test('a failed refresh keeps the last good list instead of blanking it', async () => {
+ // Stale beats blank: a refresh that fails (offline, or the 20s abort on a
+ // huge skills tree) must not replace a list the user is working from with
+ // an error screen. Only a FIRST load has nothing to fall back to.
+ const { useSkills, emitSkillsChanged } = await freshModules();
+ let calls = 0;
+ globalThis.fetch = vi.fn(() => {
+ calls += 1;
+ return calls === 1
+ ? Promise.resolve(jsonResponse(skillsBody(['kept'])))
+ : Promise.reject(new Error('TimeoutError'));
+ }) as unknown as typeof fetch;
+
+ function Probe() {
+ const state = useSkills();
+ return (
+ <div data-testid="s">
+ {state.status === 'ready' ? String(state.data.length) : state.status}
+ </div>
+ );
+ }
+ render(<Probe />);
+ await waitFor(() => expect(screen.getByTestId('s').textContent).toBe('1'));
+
+ emitSkillsChanged();
+ await waitFor(() => expect(calls).toBeGreaterThan(1));
+ // Still the good list, NOT 'error'.
+ await waitFor(() => expect(screen.getByTestId('s').textContent).toBe('1'));
+ });
+
+ test('a failed request frees the slot — the next signal refetches for real', async () => {
+ const { useSkills, emitSkillsChanged } = await freshModules();
+ let calls = 0;
+ globalThis.fetch = vi.fn(() => {
+ calls += 1;
+ return calls === 1
+ ? Promise.reject(new Error('TimeoutError'))
+ : Promise.resolve(jsonResponse(skillsBody(['recovered'])));
+ }) as unknown as typeof fetch;
+
+ function Probe() {
+ const state = useSkills();
+ return (
+ <div data-testid="s">
+ {state.status === 'ready' ? String(state.data.length) : state.status}
+ </div>
+ );
+ }
+ render(<Probe />);
+ await waitFor(() => expect(screen.getByTestId('s').textContent).toBe('error'));
+
+ emitSkillsChanged();
+ await waitFor(() => expect(calls).toBeGreaterThan(1));
+ await waitFor(() => expect(screen.getByTestId('s').textContent).toBe('1'));
+ });
+});
diff --git a/packages/app/src/hooks/use-skills.import.test.ts b/packages/app/src/hooks/use-skills.import.test.ts
new file mode 100644
index 000000000..6b017daf0
--- /dev/null
+++ b/packages/app/src/hooks/use-skills.import.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, test } from 'vitest';
+
+/**
+ * `use-skills` owns module-level state and wires the invalidation listeners that
+ * keep the shared skills list fresh. Wiring them at module scope made importing
+ * this module require a DOM — `subscribeToSkillsChanged` calls
+ * `window.addEventListener` — so every node-env test that transitively imported
+ * it died at load with `window is not defined`, and SSR would have too.
+ *
+ * This file runs in the node environment on purpose. It is the cheapest guard
+ * against re-introducing an import-time DOM dependency here.
+ */
+describe('use-skills module load', () => {
+ test('imports without a DOM', async () => {
+ expect(typeof globalThis.window).toBe('undefined');
+ const mod = await import('./use-skills');
+ expect(typeof mod.useSkills).toBe('function');
+ });
+});
diff --git a/packages/app/src/hooks/use-skills.ts b/packages/app/src/hooks/use-skills.ts
index c5e058584..c6a7c0877 100644
--- a/packages/app/src/hooks/use-skills.ts
+++ b/packages/app/src/hooks/use-skills.ts
@@ -26,21 +26,108 @@ let lastKnownSkills: readonly SkillsListEntry[] | null = null;
/** One in-flight `/api/skills` request shared across every hook instance — a
* mutation fires `skills-changed` + the CC1 `files` signal into N mounted
- * instances at once; without sharing, each ran its own full server scan. */
+ * instances at once, and the endpoint is a synchronous walk of every editor
+ * skills root, so without sharing each one ran its own full server scan. That
+ * single-flight ceiling is load-bearing: racing N scans on the server's event
+ * loop stalls CRDT sync and the editor stops taking keystrokes. */
let inFlightSkills: Promise<unknown> | null = null;
-function fetchSkillsShared(): Promise<unknown> {
- inFlightSkills ??= fetch('/api/skills')
- .then(async (r) => {
+/** A write landed while `inFlightSkills` was running, so that request predates
+ * the write and its response must not be served. Coalescing on a bare promise
+ * is what let a post-mutation refetch settle on pre-write data forever. */
+let inFlightStale = false;
+
+function invalidateSkills(): void {
+ if (inFlightSkills !== null) inFlightStale = true;
+}
+
+/**
+ * Invalidation is wired once, independent of any hook instance: a request can
+ * outlive the last unmount (that slowness is the whole premise), and an agent
+ * write landing in that window has to invalidate too, or the next mount joins
+ * the pre-write request and renders a skill the user already deleted.
+ *
+ * Attached on first use rather than at module load, because
+ * `subscribeToSkillsChanged` touches `window` — doing it at import time makes
+ * merely IMPORTING this module require a DOM, which throws in the node-env unit
+ * tests (and would throw under SSR) for every consumer that transitively pulls
+ * it in. Lazy is still mount-independent: once attached the listeners outlive
+ * every unmount, which is the window the stale-join bug lives in.
+ */
+let invalidationSubscribed = false;
+function ensureInvalidationSubscribed(): void {
+ if (invalidationSubscribed || typeof window === 'undefined') return;
+ invalidationSubscribed = true;
+ subscribeToSkillsChanged(invalidateSkills);
+ subscribeToDocumentsChanged((channels) => {
+ if (channels.includes('files')) invalidateSkills();
+ });
+}
+
+/**
+ * A hung request must not wedge the shared promise FOREVER.
+ *
+ * Every reader joins `inFlightSkills`, and the slot is only released in that
+ * promise's `.finally` — so a fetch that never settles freezes the skills list
+ * at its last value for the rest of the session: stale rows, a stale toolbar,
+ * and clicks that mint doc names from entries that have since moved. Only a
+ * reload clears it, because the slot is module state. This endpoint is a
+ * synchronous walk of every skills root on the machine, so it is exactly the
+ * one that can stall. Aborting turns a permanent wedge into one failed refresh
+ * that the next `files` signal retries.
+ */
+const SKILLS_REQUEST_TIMEOUT_MS = 20_000;
+
+function requestSkills(): Promise<unknown> {
+ return fetch('/api/skills', { signal: AbortSignal.timeout(SKILLS_REQUEST_TIMEOUT_MS) }).then(
+ async (r) => {
if (!r.ok) {
const body = (await r.json().catch(() => null)) as unknown;
throw new Error(parseApiError(body) ?? `HTTP ${r.status}`);
}
return r.json() as Promise<unknown>;
- })
- .finally(() => {
- inFlightSkills = null;
- });
- return inFlightSkills;
+ },
+ );
+}
+
+/**
+ * Re-run rather than race: keep exactly one scan in flight, and if a write lands
+ * while it is running, throw that response away and go again. Callers therefore
+ * always share ONE promise that can only resolve with post-write data — which is
+ * why nothing downstream (including the shared `lastKnownSkills` seed) needs its
+ * own staleness check.
+ *
+ * Bounded because the retry is driven by external writes: a sustained stream of
+ * mutations would otherwise spin here forever. After the cap we serve what we
+ * have; the next signal schedules another refetch anyway, so the list converges.
+ */
+const MAX_STALE_REFETCHES = 3;
+
+function fetchSkillsShared(): Promise<unknown> {
+ ensureInvalidationSubscribed();
+ if (inFlightSkills !== null) return inFlightSkills;
+ const pending: Promise<unknown> = (async () => {
+ for (let attempt = 0; attempt < MAX_STALE_REFETCHES; attempt++) {
+ inFlightStale = false;
+ const data = await requestSkills();
+ if (!inFlightStale) return data;
+ }
+ inFlightStale = false;
+ return requestSkills();
+ })().finally(() => {
+ // `.finally` so BOTH outcomes release the slot: a rejected request (offline,
+ // non-ok status) must clear it too, or every later caller would join a
+ // promise that can only ever re-reject and the list would never recover.
+ //
+ // Identity-guarded because settle order is not start order: a superseded
+ // request can resolve AFTER the one that replaced it, and an unconditional
+ // reset would then null out a live newer request, so the next caller starts
+ // a duplicate scan. Keep the guard on any reset added here — in particular
+ // do not add a bare `.catch(() => { inFlightSkills = null; })`, which runs
+ // for the same superseded requests without the identity check.
+ if (inFlightSkills === pending) inFlightSkills = null;
+ });
+ inFlightSkills = pending;
+ return pending;
}
export function useSkills(options?: { enabled?: boolean }): AsyncState<readonly SkillsListEntry[]> {
@@ -60,6 +147,8 @@ export function useSkills(options?: { enabled?: boolean }): AsyncState<readonly
// coalesce the burst into a single refetch instead of several back-to-back.
let timer: ReturnType<typeof setTimeout> | null = null;
const bump = () => {
+ // Invalidation itself is wired at module scope, so it already happened
+ // synchronously when the signal fired. This only paces the re-render.
if (timer) clearTimeout(timer);
timer = setTimeout(() => setRefreshKey((k) => k + 1), 200);
};
@@ -111,7 +200,15 @@ export function useSkills(options?: { enabled?: boolean }): AsyncState<readonly
})
.catch((err: unknown) => {
if (cancelled) return;
- setState({ status: 'error', message: err instanceof Error ? err.message : String(err) });
+ // Stale beats blank. A refresh that fails (offline, a 20s abort on a
+ // huge skills tree) must not replace a list the user is working from
+ // with an error screen — the next `files`/`skills-changed` signal
+ // refetches anyway. Only a FIRST load has nothing to fall back to.
+ setState((prev) =>
+ prev.status === 'ready'
+ ? prev
+ : { status: 'error', message: err instanceof Error ? err.message : String(err) },
+ );
});
return () => {
cancelled = true;
diff --git a/packages/app/src/lib/documents-events.ts b/packages/app/src/lib/documents-events.ts
index 3c121c370..a062f73ec 100644
--- a/packages/app/src/lib/documents-events.ts
+++ b/packages/app/src/lib/documents-events.ts
@@ -166,6 +166,53 @@ export function endOptimisticSkillMove(fromScope: SkillScope, name: string): voi
if (hiddenMovingSkills.delete(movingSkillKey(fromScope, name))) emitSkillsChanged();
}
+// Skill writes currently in flight, keyed scope+name. A write is not atomic on
+// disk — `projectInPlaceSkill` rm's a destination before materializing it, and a
+// scope move hides the source before the destination lands — so a scan taken
+// mid-write can report a skill that plainly exists as absent. Anything that
+// DESTROYS user state on absence has to be able to tell "being written" from
+// "deleted"; inferring it from the list alone is what closed people's tabs.
+const pendingSkillWrites = new Set<string>();
+
+/** Mark a skill as being written. Pair with {@link endSkillWrite} in a finally. */
+export function beginSkillWrite(scope: SkillScope, name: string): void {
+ pendingSkillWrites.add(movingSkillKey(scope, name));
+ emitSkillsChanged();
+}
+
+export function endSkillWrite(scope: SkillScope, name: string): void {
+ if (pendingSkillWrites.delete(movingSkillKey(scope, name))) emitSkillsChanged();
+}
+
+export function isSkillWritePending(scope: SkillScope, name: string): boolean {
+ return pendingSkillWrites.has(movingSkillKey(scope, name));
+}
+
+/**
+ * Stable key describing WHICH skills are mid-write.
+ *
+ * Consumers that skip work on an unchanged input signature must fold this in:
+ * suppressing an action while a write is pending and then clearing the flag
+ * leaves the underlying list identical, so without this the guarded action is
+ * skipped forever rather than merely deferred. That is the trap that turned a
+ * deferred tab-close into one that never happened.
+ */
+export function pendingSkillWritesKey(): string {
+ return [...pendingSkillWrites].sort().join('\u0001');
+}
+
+/**
+ * Is a scope-move currently in flight for this skill at this (source) scope?
+ *
+ * A move passes through a window where the skill is in NEITHER scope's list: the
+ * source row is hidden here and the destination row has not landed yet. Anything
+ * that reads "absent from the list" as "deleted" will act on that window, so
+ * consumers that destroy user state need to be able to tell the two apart.
+ */
+export function isOptimisticallyMoving(scope: SkillScope, name: string): boolean {
+ return hiddenMovingSkills.has(movingSkillKey(scope, name));
+}
+
/** Drop rows a scope-move is optimistically relocating away from their source. */
export function applyOptimisticSkillMoves<T extends { scope: SkillScope; name: string }>(
skills: readonly T[],
diff --git a/packages/app/src/lib/managed-artifact-doc-name.test.ts b/packages/app/src/lib/managed-artifact-doc-name.test.ts
new file mode 100644
index 000000000..6c1d940d0
--- /dev/null
+++ b/packages/app/src/lib/managed-artifact-doc-name.test.ts
@@ -0,0 +1,79 @@
+import type { SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
+import { filterOpenTabsForKnownTargets, isSkillTabId } from '@/editor/editor-tabs';
+import { skillEntryFileLiveDocName, skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';
+
+/**
+ * A project skill dir can be a SYMLINK to a canonical dir elsewhere in the
+ * content tree (a repo that keeps its bundles in `plugins/<x>/skills/` and links
+ * them into `.agents/skills/`). The document index holds ONE page per inode,
+ * under the canonical name — so a tab opened at the alias name has no page and
+ * the next page-list sync prunes it: the skill flickers open and vanishes, and
+ * the surface falls back to Files. `/api/skills` reports the resolved
+ * `canonicalPath`; every doc-name builder must prefer it.
+ */
+const aliased: SkillsListEntry = {
+ scope: 'project',
+ name: 'bug-triage',
+ path: '.agents/skills/bug-triage/SKILL.md',
+ canonicalPath: 'plugins/ok/skills/bug-triage/SKILL.md',
+ installed: true,
+ hosts: [],
+};
+const plain: SkillsListEntry = {
+ scope: 'project',
+ name: '1on1',
+ path: '.agents/skills/1on1/SKILL.md',
+ installed: true,
+ hosts: [],
+};
+
+describe('skillEntryLiveDocName', () => {
+ test('addresses an aliased skill by its canonical doc, not the symlink path', () => {
+ expect(skillEntryLiveDocName(aliased)).toBe('plugins/ok/skills/bug-triage/SKILL');
+ });
+
+ test('leaves an ordinary in-place skill at its own path', () => {
+ expect(skillEntryLiveDocName(plain)).toBe('.agents/skills/1on1/SKILL');
+ });
+
+ test('a global entry is unaffected (managed-artifact doc, not a content path)', () => {
+ expect(skillEntryLiveDocName({ ...aliased, scope: 'global' })).toBe(
+ '__skill__/global/bug-triage',
+ );
+ });
+});
+
+describe('skillEntryFileLiveDocName', () => {
+ test('resolves a bundle file under the canonical dir', () => {
+ expect(skillEntryFileLiveDocName(aliased, 'references/notes.md')).toBe(
+ 'plugins/ok/skills/bug-triage/references/notes',
+ );
+ });
+
+ test('leaves an ordinary skill bundle file under its own dir', () => {
+ expect(skillEntryFileLiveDocName(plain, 'references/notes.md')).toBe(
+ '.agents/skills/1on1/references/notes',
+ );
+ });
+});
+
+describe('an aliased skill tab survives a page-list sync', () => {
+ // `/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
+ // Y.Doc on the same inode.
+ const pages = new Set(['plugins/ok/skills/bug-triage/SKILL']);
+ const targets = { pages, folderPaths: new Set<string>(), assetPaths: new Set<string>() };
+
+ test('the tab the sidebar opens is the page the index holds', () => {
+ const tabId = skillEntryLiveDocName(aliased);
+ expect(pages.has(tabId)).toBe(true);
+ expect(filterOpenTabsForKnownTargets([tabId], targets)).toEqual([tabId]);
+ });
+
+ test('the canonical name still classifies as a Skills-surface tab', () => {
+ // Otherwise the tab survives but lands in the Files tab strip.
+ expect(isSkillTabId(skillEntryLiveDocName(aliased))).toBe(true);
+ });
+});
diff --git a/packages/app/src/lib/managed-artifact-doc-name.ts b/packages/app/src/lib/managed-artifact-doc-name.ts
index f0f4e7886..6cbdd2cf6 100644
--- a/packages/app/src/lib/managed-artifact-doc-name.ts
+++ b/packages/app/src/lib/managed-artifact-doc-name.ts
@@ -36,21 +36,34 @@ export { skillLiveDocName };
* `skillLiveDocName`. Global entries keep the managed-artifact scheme.
*/
export function skillEntryLiveDocName(
- skill: Pick<SkillsListEntry, 'scope' | 'name' | 'path'>,
+ skill: Pick<SkillsListEntry, 'scope' | 'name' | 'path' | 'canonicalPath'>,
): string {
return skill.scope === 'project'
- ? stripMdExt(skill.path)
+ ? stripMdExt(skillEntryDocPath(skill))
: skillLiveDocName(skill.scope, skill.name);
}
+/**
+ * The path a PROJECT entry's docs are ADDRESSED by. `path` is where the bundle
+ * is mounted, which for a symlinked skill dir is an alias: the document index
+ * holds one page per inode under the canonical name, so a tab opened at the
+ * alias has no page and is pruned by the next page-list sync (skill flickers
+ * open, vanishes, surface falls back to Files). `canonicalPath` is the server's
+ * resolution of that alias — prefer it wherever a doc NAME is minted, and leave
+ * `path` to the on-disk questions (install targets, reveal, host wiring).
+ */
+function skillEntryDocPath(skill: Pick<SkillsListEntry, 'path' | 'canonicalPath'>): string {
+ return skill.canonicalPath ?? skill.path;
+}
+
/** Per-bundle-file analogue of {@link skillEntryLiveDocName}: the live doc name
* for `rel` (e.g. `references/patterns.md`) inside the entry's real dir. */
export function skillEntryFileLiveDocName(
- skill: Pick<SkillsListEntry, 'scope' | 'name' | 'path'>,
+ skill: Pick<SkillsListEntry, 'scope' | 'name' | 'path' | 'canonicalPath'>,
rel: string,
): string {
if (skill.scope !== 'project') return skillFileLiveDocName(skill.scope, skill.name, rel);
- const dir = skill.path.replace(/\/SKILL\.mdx?$/i, '');
+ const dir = skillEntryDocPath(skill).replace(/\/SKILL\.mdx?$/i, '');
return `${dir}/${stripMdExt(rel)}`;
}
diff --git a/packages/app/src/lib/skill-install-rows.test.ts b/packages/app/src/lib/skill-install-rows.test.ts
new file mode 100644
index 000000000..ccf07275e
--- /dev/null
+++ b/packages/app/src/lib/skill-install-rows.test.ts
@@ -0,0 +1,228 @@
+import type { SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { describe, expect, it } from 'vitest';
+import { deriveSkillInstallRows, type SkillInstallMenuSkill } from './skill-install-rows';
+
+/** A listed skill with only the fields the derivation reads set. */
+function entry(over: Partial<SkillsListEntry> & Pick<SkillsListEntry, 'name'>): SkillsListEntry {
+ return {
+ scope: 'project',
+ hosts: [],
+ installed: false,
+ path: `.claude/skills/${over.name}/SKILL.md`,
+ ...over,
+ } as SkillsListEntry;
+}
+
+function derive(
+ skill: SkillInstallMenuSkill | undefined,
+ opts: {
+ allSkills?: readonly SkillsListEntry[] | null;
+ hosts?: readonly string[];
+ sourceHostOverlay?: string;
+ linkMode?: boolean;
+ } = {},
+) {
+ return deriveSkillInstallRows({
+ skill,
+ allSkills: opts.allSkills ?? null,
+ hostSet: new Set(opts.hosts ?? skill?.hosts ?? []),
+ sourceHostOverlay: opts.sourceHostOverlay,
+ linkMode: opts.linkMode ?? false,
+ });
+}
+
+const base: SkillInstallMenuSkill = {
+ scope: 'project',
+ name: 'trip-log',
+ hosts: ['claude'],
+ path: '.claude/skills/trip-log/SKILL.md',
+};
+
+describe('host rows', () => {
+ it('offers every install editor and omits the hub until the project adopts it', () => {
+ const rows = derive(base).rows;
+ expect(rows).toContain('claude');
+ expect(rows).not.toContain('agents');
+ });
+
+ it('activates the hub row when ANY same-scope skill lives under .agents/', () => {
+ const withHub = derive(base, {
+ allSkills: [entry({ name: 'other', path: '.agents/skills/other/SKILL.md' })],
+ });
+ expect(withHub.rows[0]).toBe('agents');
+ });
+
+ it('activates the hub row when the skill itself lists it as a host', () => {
+ expect(derive({ ...base, hosts: ['agents'] }).rows).toContain('agents');
+ });
+
+ it('gives an alias-covered host NO row of its own', () => {
+ // Checking it could only write through the alias, so the row would lie.
+ const r = derive({ ...base, hostAliases: { cursor: '.claude/skills' } });
+ expect(r.rows).not.toContain('cursor');
+ expect(r.rows).toContain('claude');
+ });
+
+ it('hides editors that are not installable here, but never one the skill is in', () => {
+ const r = derive({ ...base, hosts: ['codex'], installableEditors: ['claude'] });
+ expect(r.rows).toContain('claude');
+ expect(r.rows).toContain('codex');
+ expect(r.rows).not.toContain('cursor');
+ });
+
+ it('offers everything when installability is unknown (never over-hide)', () => {
+ expect(derive(base).rows.length).toBeGreaterThan(1);
+ });
+});
+
+describe('source disclosure', () => {
+ it('badges the host row when the skill lives in a standard editor dir', () => {
+ const r = derive(base);
+ expect(r.sourceRow).toBeNull();
+ expect(r.sourceHost).toBe('claude');
+ });
+
+ it('gives a non-standard folder its own source row and NO host badge', () => {
+ // Two source marks in one menu is the bug this split prevents.
+ const r = derive({ ...base, path: '.ok/skills/trip-log/SKILL.md' });
+ expect(r.sourceRow).toBe('.ok/skills/trip-log');
+ expect(r.sourceHost).toBeUndefined();
+ });
+
+ it('prefers the optimistic overlay over the server host order', () => {
+ expect(derive(base, { sourceHostOverlay: 'codex' }).sourceHost).toBe('codex');
+ });
+
+ it('skips a placeholder entry with no directory', () => {
+ expect(derive({ ...base, path: 'SKILL.md' }).sourceRow).toBeNull();
+ });
+
+ it('prefixes global-scope paths with ~/', () => {
+ const r = derive({ ...base, scope: 'global', path: '.ok/skills/trip-log/SKILL.md' });
+ expect(r.sourceRow).toBe('~/.ok/skills/trip-log');
+ });
+});
+
+describe('expectedMode', () => {
+ it('falls back to the server preference when there is nothing to compare against', () => {
+ expect(derive(base, { linkMode: true }).expectedMode).toBe('link');
+ expect(derive(base, { linkMode: false }).expectedMode).toBe('copy');
+ });
+
+ it('takes the majority of the OTHER locations, ignoring the source', () => {
+ // claude is the source; codex+cursor are copies, so a NEW location copies.
+ const copies = derive({ ...base, hosts: ['claude', 'codex', 'cursor'] });
+ expect(copies.expectedMode).toBe('copy');
+
+ const links = derive({
+ ...base,
+ hosts: ['claude', 'codex', 'cursor'],
+ symlinkedHosts: ['codex', 'cursor'],
+ });
+ expect(links.expectedMode).toBe('link');
+ });
+
+ it('breaks a tie toward link', () => {
+ const r = derive({
+ ...base,
+ hosts: ['claude', 'codex', 'cursor'],
+ symlinkedHosts: ['codex'],
+ });
+ expect(r.expectedMode).toBe('link');
+ });
+
+ it('ignores conflicted and alias-covered hosts in the vote', () => {
+ // A conflicted slot holds a DIFFERENT skill, so its form is not evidence.
+ const r = derive({
+ ...base,
+ hosts: ['claude', 'codex', 'cursor'],
+ symlinkedHosts: ['codex'],
+ conflictHosts: ['cursor'],
+ linkMode: false,
+ });
+ expect(r.convertible.map((c) => c.target)).toEqual(['codex']);
+ expect(r.expectedMode).toBe('link');
+ });
+
+ it('counts custom placements alongside host locations', () => {
+ const r = derive({
+ ...base,
+ customPlacements: [
+ { path: '.team/skills/trip-log', mode: 'link' },
+ { path: '.vendor/skills/trip-log', mode: 'link' },
+ ],
+ } as SkillInstallMenuSkill);
+ expect(r.expectedMode).toBe('link');
+ });
+});
+
+describe('convertible locations', () => {
+ it('never includes the source — it is the folder the others point at', () => {
+ const r = derive({ ...base, hosts: ['claude', 'codex'] });
+ expect(r.convertible.map((c) => c.target)).toEqual(['codex']);
+ });
+
+ it('reports each location with the form it is actually in', () => {
+ const r = derive({ ...base, hosts: ['claude', 'codex'], symlinkedHosts: ['codex'] });
+ expect(r.convertible[0]).toMatchObject({ target: 'codex', mode: 'link' });
+ expect(r.convertible[0]?.display).toContain('codex');
+ });
+});
+
+describe('custom root rows', () => {
+ const placed: SkillInstallMenuSkill = {
+ ...base,
+ customPlacements: [{ path: '.team/skills/trip-log', mode: 'copy' }],
+ } as SkillInstallMenuSkill;
+
+ it('marks a root this skill is placed under as occupied', () => {
+ const r = derive(placed);
+ expect(r.customRootRows).toEqual([
+ { root: '.team/skills', display: '.team/skills/trip-log', placed: expect.anything() },
+ ]);
+ });
+
+ it('offers a root ANOTHER same-scope skill uses, unchecked', () => {
+ const r = derive(base, {
+ allSkills: [
+ entry({ name: 'other', customPlacements: [{ path: '.team/skills/other', mode: 'copy' }] }),
+ ],
+ });
+ expect(r.customRootRows).toEqual([
+ { root: '.team/skills', display: '.team/skills/trip-log', placed: null },
+ ]);
+ });
+
+ it('ignores custom roots from a DIFFERENT scope', () => {
+ const r = derive(base, {
+ allSkills: [
+ entry({
+ name: 'other',
+ scope: 'global',
+ customPlacements: [{ path: '.team/skills/other', mode: 'copy' }],
+ }),
+ ],
+ });
+ expect(r.customRootRows).toEqual([]);
+ });
+
+ it('drops a root that is alias-covered or already a host/source row', () => {
+ const aliased = derive({ ...placed, hostAliases: { '.team/skills': '.claude/skills' } });
+ expect(aliased.customRootRows).toEqual([]);
+
+ const isSource = derive({
+ ...placed,
+ path: '.team/skills/trip-log/SKILL.md',
+ });
+ expect(isSource.customRootRows).toEqual([]);
+ });
+});
+
+describe('no skill', () => {
+ it('derives an empty, non-throwing shape', () => {
+ const r = derive(undefined);
+ expect(r.customRootRows).toEqual([]);
+ expect(r.sourceRow).toBeNull();
+ expect(r.pathFor('claude')).toBeNull();
+ });
+});
diff --git a/packages/app/src/lib/skill-install-rows.ts b/packages/app/src/lib/skill-install-rows.ts
new file mode 100644
index 000000000..1c62e6278
--- /dev/null
+++ b/packages/app/src/lib/skill-install-rows.ts
@@ -0,0 +1,251 @@
+import type {
+ SkillInstallTarget,
+ SkillsListEntry,
+ SkillTargetEditor,
+} from '@inkeep/open-knowledge-core';
+import { SkillTargetEditorSchema } from '@inkeep/open-knowledge-core';
+import { customPlacementRoot, skillHostRootDir } from '@/lib/skill-scope';
+
+/**
+ * The install menu's row derivation — which locations are offered, which are
+ * occupied, what form each is in, and which of them a convert would rewrite.
+ *
+ * Pure, and extracted from the menu component because it is the part with
+ * actual decisions in it: alias-covered roots get no row of their own, the
+ * `.agents` hub is existence-activated rather than always offered, and
+ * `expectedMode` is a majority vote over the skill's OTHER locations that
+ * decides both the per-row convert tags and what a NEW location lands as. The
+ * JSX around it stays where it is.
+ */
+
+/** The editors a project skill can install into — the narrowed `.options` of the
+ * canonical schema, so this can never drift from the install verb + picker. */
+export const INSTALL_EDITORS: readonly SkillTargetEditor[] = SkillTargetEditorSchema.options;
+
+/** A skill living anywhere under `.agents/` counts as the project having adopted
+ * the hub, not just one directly in `AGENTS_SKILLS_ROOT`. Deliberately a
+ * literal and not derived from that constant: the adoption MARKER ("does this
+ * project use `.agents/` at all?") is a different question from the hub's
+ * install path, and deriving one from the other would silently broaden this
+ * check if the hub ever moved to a nested path. Same bare form as the other
+ * reader of this concept, `AgentIconCluster`. */
+const AGENTS_DIR_PREFIX = '.agents/';
+
+/** What the menu knows about the skill. An un-imported explore preview carries
+ * only `{scope, name}`, so every detail field is optional. */
+export type SkillInstallMenuSkill = Pick<SkillsListEntry, 'scope' | 'name'> &
+ Partial<
+ Pick<
+ SkillsListEntry,
+ | 'hosts'
+ | 'symlinkedHosts'
+ | 'path'
+ | 'customPlacements'
+ | 'hostAliases'
+ | 'conflictHosts'
+ | 'driftPaths'
+ | 'installableEditors'
+ >
+ >;
+
+export interface SkillInstallRowsInput {
+ skill: SkillInstallMenuSkill | undefined;
+ /** Every skill at any scope, or null while the list has not loaded. Several
+ * derivations fall back to the same-scope union across it for a preview skill
+ * that carries no entry of its own. */
+ allSkills: readonly SkillsListEntry[] | null;
+ /** Hosts the skill occupies, overlay applied. */
+ hostSet: ReadonlySet<string>;
+ /** Source host with the optimistic overlay applied. */
+ sourceHostOverlay: string | undefined;
+ /** The server's effective fan-out preference, used only when the skill has no
+ * other location to compare against. */
+ linkMode: boolean;
+}
+
+interface SkillConvertibleLocation {
+ target: string;
+ display: string;
+ mode: 'copy' | 'link';
+}
+
+interface SkillCustomRootRow {
+ root: string;
+ display: string;
+ placed: { path: string; mode: 'copy' | 'link' } | null;
+}
+
+export interface SkillInstallRows {
+ /** Display path for a host row, or null when there is no skill. */
+ pathFor: (host: string) => string | null;
+ /** Folder-level aliases (host id → base-relative target root). */
+ aliases: Record<string, string>;
+ /** Host rows to render, in order. */
+ rows: SkillInstallTarget[];
+ /** The skill's own folder when it is NOT one of the host rows, in display
+ * form (`~/`-prefixed at global scope). */
+ sourceRow: string | null;
+ /** The host row that carries the SOURCE badge, if any. */
+ sourceHost: string | undefined;
+ conflicted: ReadonlySet<string>;
+ drifted: ReadonlySet<string>;
+ linked: ReadonlySet<string>;
+ expectedMode: 'copy' | 'link';
+ convertible: SkillConvertibleLocation[];
+ customRootRows: SkillCustomRootRow[];
+}
+
+export function deriveSkillInstallRows({
+ skill,
+ allSkills,
+ hostSet,
+ sourceHostOverlay,
+ linkMode,
+}: SkillInstallRowsInput): SkillInstallRows {
+ const pathFor = (host: string): string | null =>
+ skill ? `${skillHostRootDir(host, skill.scope)}/${skill.name}` : null;
+
+ // The `.agents` hub is EXISTENCE-ACTIVATED: offered only when this project
+ // already adopted it (any skill lives there or lists it as a host). OK never
+ // pushes the hub on a repo — adopting it is one Custom path away, and the
+ // first placement there lights this row up for every skill.
+ const hubActive =
+ skill !== undefined &&
+ ((skill.hosts ?? []).includes('agents') ||
+ allSkills?.some((s) => s.hosts.includes('agents') || s.path.startsWith(AGENTS_DIR_PREFIX)));
+
+ // Folder-level aliases. An aliased folder is a derived view of its target: NO
+ // row of its own (checking it could only write through the alias), its agent
+ // icon rides the target root's row instead. Folder-level links are a property
+ // of the SCOPE's dirs, not of one skill — a not-yet-installed skill has no
+ // entry to carry them, so fall back to the union across installed same-scope
+ // skills; otherwise the preview menu shows aliased folders as plain rows.
+ const aliases: Record<string, string> =
+ skill?.hostAliases ??
+ (skill && allSkills !== null
+ ? Object.assign(
+ {},
+ ...allSkills.filter((s) => s.scope === skill.scope).map((s) => s.hostAliases ?? {}),
+ )
+ : {});
+
+ // Only OFFER editors installable on THIS machine for the skill's scope — for
+ // global skills that is the set whose user-home dir exists, so we don't show
+ // an editor whose install silently no-ops and flashes a checkmark that
+ // reverts. Same same-scope fallback as `aliases`; null = no data → offer
+ // everything (never over-hide). The `.agents` hub and any editor the skill is
+ // ALREADY in are always kept (uninstall stays reachable).
+ const installableList: readonly string[] | undefined =
+ skill?.installableEditors ??
+ (skill && allSkills !== null
+ ? allSkills.find((s) => s.scope === skill.scope)?.installableEditors
+ : undefined);
+ const installable = installableList ? new Set<string>(installableList) : null;
+ const rows: SkillInstallTarget[] = (
+ hubActive ? (['agents', ...INSTALL_EDITORS] as SkillInstallTarget[]) : INSTALL_EDITORS
+ )
+ .filter((e) => !(e in aliases))
+ .filter((e) => e === 'agents' || installable === null || installable.has(e) || hostSet.has(e));
+
+ const stdPaths = new Set(rows.map((e) => pathFor(e)));
+ const homePrefix = skill?.scope === 'global' ? '~/' : '';
+ // `path` is `<dir>/SKILL.md`; the guard on '/' skips placeholder entries.
+ const entryDir = skill?.path?.includes('/')
+ ? `${homePrefix}${skill.path.replace(/\/SKILL\.mdx?$/i, '')}`
+ : null;
+ const sourceRow = entryDir !== null && !stdPaths.has(entryDir) ? entryDir : null;
+ // A host row carries the SOURCE badge ONLY when the skill's real dir IS that
+ // host's dir (in-place skills). A store-backed skill's source is its own row
+ // (`sourceRow`) — badging hosts[0] there showed TWO sources.
+ const sourceHost = sourceRow === null ? (sourceHostOverlay ?? skill?.hosts?.[0]) : undefined;
+
+ const conflicted = new Set(skill?.conflictHosts ?? []);
+ // Drift = OK's record of what it wrote disagrees with disk (another tool
+ // rewrote the path). PASSIVE disclosure only.
+ const drifted = new Set(skill?.driftPaths ?? []);
+ const linked = new Set(skill?.symlinkedHosts ?? []);
+
+ // Every location this skill has BESIDES its source, with the form each one is
+ // in. The source is never included: it is the real folder the others copy or
+ // point at.
+ const convertible: SkillConvertibleLocation[] = [
+ ...[...hostSet]
+ .filter((h) => h !== sourceHost && !(h in aliases) && !conflicted.has(h) && !h.includes('/'))
+ .map((h) => ({
+ target: h,
+ // `pathFor` is null only when there is no skill at all, in which case
+ // there are no hosts to be here for.
+ display: pathFor(h) ?? h,
+ mode: linked.has(h) ? ('link' as const) : ('copy' as const),
+ })),
+ ...(skill?.customPlacements ?? []).map((cp) => ({
+ target: customPlacementRoot(cp),
+ display: `${homePrefix}${cp.path}`,
+ mode: cp.mode,
+ })),
+ ];
+
+ // The mode a location is EXPECTED to have: what the skill's other locations
+ // are, falling back to the server's effective preference when there are none
+ // to compare against. A row matching this says nothing (a menu of identical
+ // COPY tags was pure noise); a row that DIVERGES gets a tag that converts it.
+ const otherStates = convertible.map((c) => c.mode);
+ const linkCount = otherStates.filter((st) => st === 'link').length;
+ const expectedMode: 'copy' | 'link' =
+ otherStates.length === 0
+ ? linkMode
+ ? 'link'
+ : 'copy'
+ : linkCount * 2 >= otherStates.length
+ ? 'link'
+ : 'copy';
+
+ // Non-standard locations that actually hold this skill get their own rows.
+ // KNOWN custom roots travel between SKILLS (per-machine): every distinct
+ // parent dir any skill at this scope has a recorded placement under becomes an
+ // offerable row on EVERY skill's menu. Checked when THIS skill is placed there.
+ const myPlacements = new Map(
+ (skill?.customPlacements ?? []).map((cp) => [customPlacementRoot(cp), cp]),
+ );
+ const knownRoots = new Set<string>(myPlacements.keys());
+ if (allSkills !== null && skill) {
+ for (const s of allSkills) {
+ if (s.scope !== skill.scope) continue;
+ for (const cp of s.customPlacements ?? []) {
+ const root = customPlacementRoot(cp);
+ // `.ok/skills` is the retired store, offered like any other custom root
+ // so projects that still keep skills there can manage them; the rest of
+ // `.ok/` is OK's own state and the server refuses it.
+ if (root !== '') knownRoots.add(root);
+ }
+ }
+ }
+ const customRootRows: SkillCustomRootRow[] =
+ skill !== undefined
+ ? [...knownRoots]
+ .sort()
+ .map((root) => ({
+ root,
+ display: `${homePrefix}${root}/${skill.name}`,
+ placed: myPlacements.get(root) ?? null,
+ }))
+ // Alias-covered custom roots (a folder-symlink into another root) get
+ // NO row — same rule as editor folders: their icon rides the target
+ // root's audience instead.
+ .filter((r) => !stdPaths.has(r.display) && r.display !== entryDir && !(r.root in aliases))
+ : [];
+
+ return {
+ pathFor,
+ aliases,
+ rows,
+ sourceRow,
+ sourceHost,
+ conflicted,
+ drifted,
+ linked,
+ expectedMode,
+ convertible,
+ customRootRows,
+ };
+}
diff --git a/packages/app/src/lib/skill-scope.ts b/packages/app/src/lib/skill-scope.ts
index 822dab02d..aaa6dce8b 100644
--- a/packages/app/src/lib/skill-scope.ts
+++ b/packages/app/src/lib/skill-scope.ts
@@ -1,4 +1,5 @@
import {
+ AGENTS_SKILLS_ROOT,
EDITOR_PROJECT_SKILL_ROOT,
EDITOR_USER_SKILL_ROOT,
PACK_SKILL_PREFIX,
@@ -114,7 +115,7 @@ export function skillHostRootDir(host: string, scope: SkillScope): string {
const map = scope === 'global' ? EDITOR_USER_SKILL_ROOT : EDITOR_PROJECT_SKILL_ROOT;
const rel =
host === 'agents'
- ? '.agents/skills'
+ ? AGENTS_SKILLS_ROOT
: ((map as Record<string, string | null>)[host] ?? `.${host}/skills`);
return scope === 'global' ? `~/${rel}` : rel;
}
diff --git a/packages/app/src/lib/skill-track-prompt-store.ts b/packages/app/src/lib/skill-track-prompt-store.ts
new file mode 100644
index 000000000..c4849ed2b
--- /dev/null
+++ b/packages/app/src/lib/skill-track-prompt-store.ts
@@ -0,0 +1,58 @@
+import type { SkillScope } from '@inkeep/open-knowledge-core';
+
+/**
+ * The one pending "this skill is gitignored" prompt, module-level.
+ *
+ * The guard fires from `useOpenSkill` — the shared opener every surface routes
+ * through (sidebar click, post-install redirect, adopt, deep link) — so it has
+ * no dialog of its own to raise, and mounting one per surface would mean each
+ * of them re-implementing the offer. One store plus one host mounted in `App`
+ * keeps the answer identical wherever the open came from, which is the same
+ * reason the install overlay lives in a store rather than component state.
+ */
+export interface SkillTrackPrompt {
+ scope: SkillScope;
+ name: string;
+}
+
+let pending: SkillTrackPrompt | null = null;
+const listeners = new Set<() => void>();
+
+export function getSkillTrackPrompt(): SkillTrackPrompt | null {
+ return pending;
+}
+
+export function subscribeToSkillTrackPrompt(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+function notify(): void {
+ // Deleting from a Set mid-iteration is safe (the entry is simply not
+ // visited), so an unsubscribe during notify needs no defensive copy —
+ // matching `skill-install-overlay-store`.
+ for (const listener of listeners) listener();
+}
+
+/** Ask the host to explain why this skill can't open, and offer the fix. */
+export function requestSkillTrackPrompt(prompt: SkillTrackPrompt): void {
+ if (pending !== null && pending.scope === prompt.scope && pending.name === prompt.name) {
+ return;
+ }
+ pending = prompt;
+ notify();
+}
+
+export function clearSkillTrackPrompt(): void {
+ if (pending === null) return;
+ pending = null;
+ notify();
+}
+
+/** Test seam — a leaked prompt would make the next test render a stray dialog. */
+export function __resetSkillTrackPromptForTests(): void {
+ pending = null;
+ listeners.clear();
+}
diff --git a/packages/app/src/lib/skills-api.ts b/packages/app/src/lib/skills-api.ts
index 0042b7e94..92383a0ca 100644
--- a/packages/app/src/lib/skills-api.ts
+++ b/packages/app/src/lib/skills-api.ts
@@ -526,6 +526,41 @@ export async function moveSkillScope(input: {
}
}
+/**
+ * `POST /api/skill/track-in-git`. A gitignored bundle is listed but never
+ * indexed, so it cannot be opened — this offers the one `.gitignore` line that
+ * changes that. Call with `apply: false` first: every caller shows the user the
+ * literal line before writing to their repo.
+ */
+export async function trackSkillInGit(input: {
+ name: string;
+ scope: SkillScope;
+ apply?: boolean;
+}): Promise<WriteResult<{ line: string; gitignorePath: string; applied: boolean }>> {
+ try {
+ const res = await fetch('/api/skill/track-in-git', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(input),
+ });
+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };
+ const payload = (await res.json().catch(() => null)) as {
+ line?: string;
+ gitignorePath?: string;
+ applied?: boolean;
+ } | null;
+ if (input.apply === true) emitSkillsChanged();
+ return {
+ ok: true,
+ line: payload?.line ?? '',
+ gitignorePath: payload?.gitignorePath ?? '.gitignore',
+ applied: payload?.applied === true,
+ };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
/**
* POST `/api/skill` — rename `fromName` → `toName` within one scope. Optional
* `frontmatter`/`body` rewrite the relocated `SKILL.md` in the same request, so
diff --git a/packages/app/src/lib/skills-tree-paths.test.ts b/packages/app/src/lib/skills-tree-paths.test.ts
new file mode 100644
index 000000000..74768f0db
--- /dev/null
+++ b/packages/app/src/lib/skills-tree-paths.test.ts
@@ -0,0 +1,280 @@
+import type { CatalogSkill, SkillsListEntry } from '@inkeep/open-knowledge-core';
+import { describe, expect, it } from 'vitest';
+import {
+ buildSkillsTreePaths,
+ detectedId,
+ EMPTY_SCOPE_SENTINEL,
+ isSkillDocActive,
+ type SkillsTreePathsInput,
+} from './skills-tree-paths';
+
+const scopeLabel = { project: 'PROJECT', global: 'GLOBAL' } as const;
+
+function skill(over: Partial<SkillsListEntry> & Pick<SkillsListEntry, 'name'>): SkillsListEntry {
+ return { scope: 'project', hosts: [], installed: false, ...over } as SkillsListEntry;
+}
+
+function detectedSkill(name: string, scope: 'project' | 'user' = 'user'): CatalogSkill {
+ return { name, provenance: { scope }, files: { skillMd: `/x/${name}/SKILL.md` } } as CatalogSkill;
+}
+
+function build(over: Partial<SkillsTreePathsInput> = {}) {
+ return buildSkillsTreePaths({
+ skills: [],
+ detected: null,
+ scopeLabel,
+ filesByKey: {},
+ detectedFilesById: {},
+ userExpanded: new Set(),
+ hostQualifierOf: () => undefined,
+ rowKeyFor: (s) => `${s.scope}:${s.name}`,
+ isSkillMdActive: () => false,
+ isFileActive: () => false,
+ isDetectedActive: () => false,
+ ...over,
+ });
+}
+
+describe('scope rows', () => {
+ it('always emits both scope folders, expanded', () => {
+ const r = build();
+ expect(r.paths).toContain('PROJECT/');
+ expect(r.paths).toContain('GLOBAL/');
+ expect(r.expanded).toEqual(expect.arrayContaining(['PROJECT/', 'GLOBAL/']));
+ });
+
+ it('gives an EMPTY scope a sentinel child so its folder + Add menu survive', () => {
+ // A childless directory is dropped from the visible tree, taking the scope
+ // header (and its only entry point for creating a skill) with it.
+ const r = build({ skills: [skill({ name: 'a' })] });
+ expect(r.paths).toContain(`GLOBAL/${EMPTY_SCOPE_SENTINEL}`);
+ expect(r.paths).not.toContain(`PROJECT/${EMPTY_SCOPE_SENTINEL}`);
+ });
+
+ it('drops the sentinel when only a DETECTED skill occupies the scope', () => {
+ const r = build({ detected: [detectedSkill('found')] });
+ expect(r.paths).not.toContain(`GLOBAL/${EMPTY_SCOPE_SENTINEL}`);
+ expect(r.paths).toContain(`PROJECT/${EMPTY_SCOPE_SENTINEL}`);
+ });
+});
+
+describe('segment disambiguation', () => {
+ it('uses the stripped display name when it is unique', () => {
+ const r = build({ skills: [skill({ name: 'open-knowledge-pack-trip-log' })] });
+ expect([...r.skillByPrefix.keys()]).toEqual(['PROJECT/trip-log']);
+ });
+
+ it('falls back to the FULL name for two skills that strip to the same thing', () => {
+ // A shared segment collapses both into one row and hides one outright.
+ const r = build({
+ skills: [skill({ name: 'trip-log' }), skill({ name: 'open-knowledge-pack-trip-log' })],
+ });
+ expect([...r.skillByPrefix.keys()].sort()).toEqual([
+ 'PROJECT/open-knowledge-pack-trip-log',
+ 'PROJECT/trip-log',
+ ]);
+ });
+
+ it('falls back to the host dir when even the full names are identical', () => {
+ const r = build({
+ skills: [
+ skill({ name: 'trip-log', hosts: ['claude'] }),
+ skill({ name: 'trip-log', hosts: ['agents'] }),
+ ],
+ hostQualifierOf: (s) => s.hosts[0],
+ });
+ expect([...r.skillByPrefix.keys()].sort()).toEqual([
+ 'PROJECT/trip-log (.agents)',
+ 'PROJECT/trip-log (claude)',
+ ]);
+ });
+
+ it('does not disambiguate ACROSS scopes — the label already separates them', () => {
+ const r = build({
+ skills: [skill({ name: 'trip-log' }), skill({ name: 'trip-log', scope: 'global' })],
+ });
+ expect([...r.skillByPrefix.keys()].sort()).toEqual(['GLOBAL/trip-log', 'PROJECT/trip-log']);
+ });
+});
+
+describe('detected skills', () => {
+ it('nests a detected skill under the scope its PROVENANCE names', () => {
+ const r = build({ detected: [detectedSkill('found', 'project')] });
+ expect([...r.detectedByPrefix.keys()]).toEqual(['PROJECT/found']);
+ });
+
+ it('skips one already managed — it is the same skill, seen through its symlink', () => {
+ const r = build({ skills: [skill({ name: 'dup' })], detected: [detectedSkill('dup')] });
+ expect(r.detectedByPrefix.size).toBe(0);
+ });
+
+ it('skips a managed skill detected at the OTHER scope', () => {
+ const r = build({
+ skills: [skill({ name: 'dup', scope: 'global' })],
+ detected: [detectedSkill('dup', 'project')],
+ });
+ expect(r.detectedByPrefix.size).toBe(0);
+ });
+
+ it("skips OK's own product skills — managing them with OK is circular", () => {
+ const r = build({ detected: [detectedSkill('open-knowledge')] });
+ expect(r.detectedByPrefix.size).toBe(0);
+ });
+
+ it('adopts OK shipped PACK skills, which are fair game', () => {
+ const r = build({ detected: [detectedSkill('open-knowledge-pack-notes')] });
+ expect(r.detectedByPrefix.size).toBe(1);
+ });
+
+ it('falls back to the full name when the display name is already taken', () => {
+ const r = build({
+ skills: [skill({ name: 'notes', scope: 'global' })],
+ detected: [detectedSkill('open-knowledge-pack-notes')],
+ });
+ expect([...r.detectedByPrefix.keys()]).toEqual(['GLOBAL/open-knowledge-pack-notes']);
+ });
+
+ it('drops a hard collision rather than stealing the row that got there first', () => {
+ // Both tiers exhausted: the display name is taken and the full name IS the
+ // display name, so there is no third spelling left to fall back to.
+ const r = build({ detected: [detectedSkill('notes'), detectedSkill('notes')] });
+ expect([...r.detectedByPrefix.keys()]).toEqual(['GLOBAL/notes']);
+ });
+
+ it('marks a detected skill active and expands its ancestors', () => {
+ // The whole point of extracting this was testability; this branch drives the
+ // sidebar highlight for an un-managed skill whose editable buffer is open.
+ const r = build({
+ detected: [detectedSkill('found')],
+ isDetectedActive: (s) => s.name === 'found',
+ });
+ expect(r.activePath).toBe('GLOBAL/found/SKILL.md');
+ expect(r.expanded).toContain('GLOBAL/found/');
+ expect(r.expanded).toContain('GLOBAL/');
+ });
+
+ it('lets an active MANAGED skill win over an active detected one', () => {
+ // Managed rows are emitted first and the detected branch is `!activePath`
+ // guarded, so two actives must not fight over the highlight.
+ const r = build({
+ skills: [skill({ name: 'trip-log' })],
+ detected: [detectedSkill('found')],
+ isSkillMdActive: () => true,
+ isDetectedActive: () => true,
+ });
+ expect(r.activePath).toBe('PROJECT/trip-log/SKILL.md');
+ });
+
+ it('nests a detected skill’s loaded bundle files and keeps it expanded', () => {
+ const s = detectedSkill('found');
+ const r = build({ detected: [s], detectedFilesById: { [detectedId(s)]: ['references/x.md'] } });
+ expect(r.paths).toContain('GLOBAL/found/references/x.md');
+ expect(r.expanded).toContain('GLOBAL/found/');
+ });
+});
+
+describe('bundle files and active row', () => {
+ it('nests a managed skill’s bundle files under it', () => {
+ const s = skill({ name: 'trip-log' });
+ const r = build({
+ skills: [s],
+ filesByKey: { 'project:trip-log': [{ path: 'scripts/go.sh' }] },
+ });
+ expect(r.paths).toContain('PROJECT/trip-log/scripts/go.sh');
+ });
+
+ it('marks SKILL.md active and expands its ancestors', () => {
+ const r = build({ skills: [skill({ name: 'trip-log' })], isSkillMdActive: () => true });
+ expect(r.activePath).toBe('PROJECT/trip-log/SKILL.md');
+ expect(r.expanded).toContain('PROJECT/trip-log/');
+ });
+
+ it('lets SKILL.md win over a bundle file, never both', () => {
+ const r = build({
+ skills: [skill({ name: 'trip-log' })],
+ filesByKey: { 'project:trip-log': [{ path: 'references/x.md' }] },
+ isSkillMdActive: () => true,
+ isFileActive: () => true,
+ });
+ expect(r.activePath).toBe('PROJECT/trip-log/SKILL.md');
+ });
+
+ it('marks a bundle file active when SKILL.md is not', () => {
+ const r = build({
+ skills: [skill({ name: 'trip-log' })],
+ filesByKey: { 'project:trip-log': [{ path: 'references/x.md' }] },
+ isFileActive: (_s, f) => f === 'references/x.md',
+ });
+ expect(r.activePath).toBe('PROJECT/trip-log/references/x.md');
+ });
+});
+
+describe('user-expanded restore', () => {
+ it('restores folders the user opened by hand', () => {
+ const r = build({
+ skills: [skill({ name: 'trip-log' })],
+ userExpanded: new Set(['PROJECT/trip-log/']),
+ });
+ expect(r.expanded).toContain('PROJECT/trip-log/');
+ });
+
+ it('drops a remembered path that no longer names a real folder', () => {
+ // A renamed/deleted skill leaves a stale entry; re-expanding it would
+ // resurrect a row that is not in the tree.
+ const r = build({ userExpanded: new Set(['PROJECT/gone/']) });
+ expect(r.expanded).not.toContain('PROJECT/gone/');
+ });
+});
+
+describe('isSkillDocActive', () => {
+ const docName = '.claude/skills/demo/SKILL';
+
+ it('is active when a real open tab backs it', () => {
+ expect(
+ isSkillDocActive({
+ activeTargetKind: 'doc',
+ activeDocName: docName,
+ openTabs: [docName],
+ docName,
+ }),
+ ).toBe(true);
+ });
+
+ it('is NOT active when the name matches but no tab is open', () => {
+ // The retry case: an open that never landed leaves `activeDocName` pointing
+ // at a doc with no tab. Reading that as active makes the row highlighted and
+ // the tree's click guard swallow the click that would open it.
+ expect(
+ isSkillDocActive({
+ activeTargetKind: 'doc',
+ activeDocName: docName,
+ openTabs: [],
+ docName,
+ }),
+ ).toBe(false);
+ });
+
+ it('is NOT active while a non-doc target owns the surface', () => {
+ // A skill-file viewer or preview carries no docName, so `activeDocName`
+ // stays stale on the last doc tab — often this very skill.
+ expect(
+ isSkillDocActive({
+ activeTargetKind: 'skill-preview',
+ activeDocName: docName,
+ openTabs: [docName],
+ docName,
+ }),
+ ).toBe(false);
+ });
+
+ it('is NOT active for a different skill', () => {
+ expect(
+ isSkillDocActive({
+ activeTargetKind: 'doc',
+ activeDocName: '.claude/skills/other/SKILL',
+ openTabs: ['.claude/skills/other/SKILL'],
+ docName,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/app/src/lib/skills-tree-paths.ts b/packages/app/src/lib/skills-tree-paths.ts
new file mode 100644
index 000000000..c5b35a773
--- /dev/null
+++ b/packages/app/src/lib/skills-tree-paths.ts
@@ -0,0 +1,216 @@
+import {
+ type CatalogSkill,
+ catalogRawScopeToOkScope,
+ type SkillScope,
+ type SkillsListEntry,
+} from '@inkeep/open-knowledge-core';
+import { SKILL_SCOPE_ORDER, skillDisplayName } from '@/lib/skill-scope';
+import { SKILL_MD_PATH } from '@/lib/skill-sort';
+
+/**
+ * The Skills sidebar's tree-path builder: turns the managed skill list plus the
+ * detected-skill catalog into the flat `<scopeLabel>/<segment>/<file>` paths the
+ * Pierre tree renders, along with the prefix→skill lookups, which folders start
+ * expanded, and which row is active.
+ *
+ * Extracted from the sidebar component because the interesting parts are pure
+ * and were untestable inside it: the three-tier segment disambiguation (display
+ * name → full name → host dir), the cross-tier collision guard that keeps a
+ * detected skill from stealing a managed skill's row, and the empty-scope
+ * sentinel that keeps a childless scope's "New / Add" menu reachable at all.
+ */
+
+// Hidden sentinel child for a scope with no skills. Pierre drops a childless
+// directory from the visible tree, which makes the whole scope (and its
+// New/Add menu) disappear and slides the sibling to the top. Underscores can't
+// appear in a real skill name, so it can't collide.
+export const EMPTY_SCOPE_SENTINEL = '__ok_empty_scope__';
+
+// OK's own core product skills — managing them with OK is circular, so they
+// never show as "Detected". Its shipped *packs* (`open-knowledge-pack-*`) are
+// fair game to adopt, so they are NOT excluded.
+const OK_OWN_SKILLS: ReadonlySet<string> = new Set([
+ 'open-knowledge',
+ 'open-knowledge-discovery',
+ 'open-knowledge-write-skill',
+]);
+
+/** Cache key for a detected skill's lazily-fetched bundle files. */
+export function detectedId(s: CatalogSkill): string {
+ return `${catalogRawScopeToOkScope(s.provenance.scope)}::${s.name}`;
+}
+
+export interface SkillsTreePathsInput {
+ skills: readonly SkillsListEntry[];
+ /** Detected (un-managed) skills; null/absent while the scan is in flight. */
+ detected: readonly CatalogSkill[] | null;
+ scopeLabel: Record<SkillScope, string>;
+ /** Managed skills' bundle files, keyed by `rowKeyFor`. */
+ filesByKey: Record<string, readonly { path: string }[]>;
+ /** Detected skills' bundle-file paths, keyed by `detectedId`. */
+ detectedFilesById: Record<string, readonly string[]>;
+ /** Folder paths the user expanded by hand, restored across the tree's remount. */
+ userExpanded: ReadonlySet<string>;
+ /** Host that disambiguates two same-named skills in one scope, else undefined. */
+ hostQualifierOf: (s: SkillsListEntry) => string | undefined;
+ rowKeyFor: (s: SkillsListEntry) => string;
+ isSkillMdActive: (s: SkillsListEntry) => boolean;
+ isFileActive: (s: SkillsListEntry, filePath: string) => boolean;
+ /** Is this detected skill's editable in-place buffer the open doc? */
+ isDetectedActive: (s: CatalogSkill) => boolean;
+}
+
+export interface SkillsTreePaths {
+ paths: string[];
+ expanded: string[];
+ activePath: string | undefined;
+ skillByPrefix: Map<string, SkillsListEntry>;
+ detectedByPrefix: Map<string, CatalogSkill>;
+}
+
+/**
+ * Does an OPEN tab make this skill's doc the active one?
+ *
+ * "Active" drives two things: the highlighted row, and the tree's
+ * row highlight. Matching `activeDocName`
+ * alone gets both wrong in the same way — `activeDocName` survives on the last
+ * doc tab when a non-doc target (skill-file viewer, preview) takes over, and an
+ * open that never landed leaves it pointing at a doc with no tab behind it. The
+ * row then reads active, and clicking it — the obvious way to retry — returns
+ * before it opens anything. Requiring the tab to actually be open makes the
+ * retry work, which is the one thing a user in that state will try.
+ */
+export function isSkillDocActive(input: {
+ activeTargetKind: string | undefined;
+ activeDocName: string | null;
+ openTabs: readonly string[];
+ docName: string;
+}): boolean {
+ if (input.activeTargetKind !== 'doc') return false;
+ if (input.activeDocName !== input.docName) return false;
+ return input.openTabs.includes(input.docName);
+}
+
+export function buildSkillsTreePaths({
+ skills,
+ detected,
+ scopeLabel,
+ filesByKey,
+ detectedFilesById,
+ userExpanded,
+ hostQualifierOf,
+ rowKeyFor,
+ isSkillMdActive,
+ isFileActive,
+ isDetectedActive,
+}: SkillsTreePathsInput): SkillsTreePaths {
+ // The tree segment is normally the stripped display name, but Pierre labels
+ // rows by the path basename — so when two skills in one scope strip to the
+ // same name (e.g. a user `foo` beside the shipped `open-knowledge-pack-foo`)
+ // a shared segment would collapse both to one row and hide one. Only the
+ // colliding skills fall back to their full (unstripped) name to stay distinct.
+ // Third tier: distinct-content skills that share a name outright, where even
+ // the full name is identical — those take the host dir that holds them, which
+ // is the thing that actually tells them apart.
+ const displayCounts = new Map<string, number>();
+ for (const s of skills) {
+ const key = `${s.scope}\x00${skillDisplayName(s.name)}`;
+ displayCounts.set(key, (displayCounts.get(key) ?? 0) + 1);
+ }
+ const segmentFor = (s: SkillsListEntry): string => {
+ const display = skillDisplayName(s.name);
+ const host = hostQualifierOf(s);
+ if (host) return `${s.name} (${host === 'agents' ? '.agents' : host})`;
+ return (displayCounts.get(`${s.scope}\x00${display}`) ?? 0) > 1 ? s.name : display;
+ };
+
+ const skillByPrefix = new Map<string, SkillsListEntry>();
+ const paths: string[] = [];
+ let activePath: string | undefined;
+ // Both scope rows stay expanded. The tree remounts on any skill
+ // add/remove/rename, and Pierre exposes no expansion callback to snapshot user
+ // state across that — so pinning the section headers open keeps a sibling
+ // scope from collapsing when an unrelated skill is deleted. Individual skill
+ // folders still expand only for the active doc.
+ const expanded: string[] = [];
+ // Segments already taken per scope — so a detected skill can't collide with a
+ // managed skill's row (or another detected skill's).
+ const usedSegments = new Map<SkillScope, Set<string>>(
+ SKILL_SCOPE_ORDER.map((s) => [s, new Set<string>()]),
+ );
+ for (const scope of SKILL_SCOPE_ORDER) {
+ paths.push(`${scopeLabel[scope]}/`);
+ expanded.push(`${scopeLabel[scope]}/`);
+ }
+ for (const s of skills) {
+ const segment = segmentFor(s);
+ usedSegments.get(s.scope)?.add(segment);
+ const prefix = `${scopeLabel[s.scope]}/${segment}`;
+ skillByPrefix.set(prefix, s);
+ paths.push(`${prefix}/${SKILL_MD_PATH}`);
+ if (isSkillMdActive(s)) {
+ activePath = `${prefix}/${SKILL_MD_PATH}`;
+ expanded.push(`${scopeLabel[s.scope]}/`, `${prefix}/`);
+ }
+ for (const f of filesByKey[rowKeyFor(s)] ?? []) {
+ paths.push(`${prefix}/${f.path}`);
+ if (!activePath && isFileActive(s, f.path)) {
+ activePath = `${prefix}/${f.path}`;
+ expanded.push(`${scopeLabel[s.scope]}/`, `${prefix}/`);
+ }
+ }
+ }
+
+ // Detected (un-managed) skills — badged rows nested under their OWN scope
+ // alongside the managed ones. A detected skill's level comes from the harness
+ // provenance, NOT where the file lives, so a project-scoped plugin skill lands
+ // under PROJECT even though its files are in a user-global home. A detected
+ // skill whose name is already OK-managed (at either scope) is skipped: the
+ // managed skill is re-detected via its editor symlink, and it already shows as
+ // its managed row.
+ const managedNames = new Set<string>(skills.map((s) => s.name));
+ const detectedByPrefix = new Map<string, CatalogSkill>();
+ for (const s of detected ?? []) {
+ if (managedNames.has(s.name) || OK_OWN_SKILLS.has(s.name)) continue;
+ const scope = catalogRawScopeToOkScope(s.provenance.scope);
+ const used = usedSegments.get(scope);
+ if (!used) continue;
+ let segment = skillDisplayName(s.name);
+ if (used.has(segment)) segment = s.name;
+ if (used.has(segment)) continue; // hard collision (rare) → don't hide a real row
+ used.add(segment);
+ const prefix = `${scopeLabel[scope]}/${segment}`;
+ detectedByPrefix.set(prefix, s);
+ paths.push(`${prefix}/${SKILL_MD_PATH}`);
+ if (!activePath && isDetectedActive(s)) {
+ activePath = `${prefix}/${SKILL_MD_PATH}`;
+ expanded.push(`${scopeLabel[scope]}/`, `${prefix}/`);
+ }
+ // Once loaded, nest the detected skill's reference/script files under it and
+ // keep it expanded so the tree it just revealed doesn't collapse on re-render.
+ const detectedFiles = detectedFilesById[detectedId(s)] ?? [];
+ for (const rel of detectedFiles) paths.push(`${prefix}/${rel}`);
+ if (detectedFiles.length > 0) expanded.push(`${prefix}/`);
+ }
+
+ // Every scope with NO skills (managed or detected) gets a hidden sentinel
+ // child so Pierre still renders its folder + header.
+ for (const scope of SKILL_SCOPE_ORDER) {
+ if (usedSegments.get(scope)?.size === 0) {
+ paths.push(`${scopeLabel[scope]}/${EMPTY_SCOPE_SENTINEL}`);
+ }
+ }
+
+ // Restore folders the user manually expanded across a remount: the set of all
+ // valid folder tree paths is the scope rows + every managed/detected skill's
+ // folder; keep only the ones the inner tree recorded as expanded.
+ const validFolderPaths = new Set<string>();
+ for (const scope of SKILL_SCOPE_ORDER) validFolderPaths.add(`${scopeLabel[scope]}/`);
+ for (const prefix of skillByPrefix.keys()) validFolderPaths.add(`${prefix}/`);
+ for (const prefix of detectedByPrefix.keys()) validFolderPaths.add(`${prefix}/`);
+ for (const p of userExpanded) {
+ if (validFolderPaths.has(p)) expanded.push(p);
+ }
+
+ return { paths, expanded, activePath, skillByPrefix, detectedByPrefix };
+}
diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.json
index cc3f2b5e4..0bd8d2b4a 100644
--- a/packages/app/src/locales/ar/messages.json
+++ b/packages/app/src/locales/ar/messages.json
@@ -288,6 +288,7 @@
")"
],
"3LbBJn": ["إرفاق صور"],
+ "3MA3Hh": ["تعذّرت قراءة قاعدة ", ["gitignorePath"], ": ", ["previewError"]],
"3MnvrL": ["تُعرض أفضل ", ["0"], " تطابق — تابع الكتابة للتضييق"],
"3Mwaly": ["تعذّرت تهيئة ", ["0"], "."],
"3SDfZl": [
@@ -1149,6 +1150,11 @@
"Ef6ukL": ["عبر الأب"],
"Ef7StM": ["غير معروف"],
"EhDLBx": ["عدّلت <0>", ["filePath"], "</0> محليًا، لكنه حُذف في المستودع البعيد."],
+ "Ehb_JP": [
+ "لا يزال وكلاؤك يحمّلون هذه المهارة، لكن OpenKnowledge لا يستطيع فتحها أو تحريرها: فهو لا يفهرس ملفًا ضبط git على تجاهله، لأن المزامنة ستفشل. إضافة سطر واحد إلى ",
+ ["gitignorePath"],
+ " يجعلها قابلة للتحرير هنا."
+ ],
"Ehkru0": ["افتح اقتراحات الإكمال في CodeMirror وتنقّل بينها واقبلها أو تجاهلها."],
"EiVgl5": ["ليس لديك إذن بالدفع إلى هذا المستودع."],
"Eiowpn": [
@@ -1187,6 +1193,7 @@
"F-vBv0": ["اسأل"],
"F0OA00": ["احصل على ", ["displayName"]],
"F1T9y_": ["تُعرض أفضل التطابقات — تابع الكتابة للتضييق"],
+ "F1yEaG": ["تعذر تحديث ", ["gitignorePath"], ": ", ["0"]],
"F4IYWe": ["مشاركة المستند"],
"F4_wQj": ["البحث باستخدام Google"],
"F4vEsL": ["حالة المزامنة: ", ["syncStateLabel"]],
@@ -1426,6 +1433,7 @@
"يخزّن OpenKnowledge إعداداته وملفاته الداخلية داخل مجلد <0>.ok</0> يُنشأ حديثًا في مجلد جذر مشروعك."
],
"Hrz9NY": ["رابط ويكي"],
+ "HwAKaw": ["يتجاهل git \"", ["0"], "\""],
"HzVAoz": [
"انقل هذا الملف أو أعد تسميته داخل المهارة — يبقى المسار تحت references/ أو scripts/."
],
@@ -3001,6 +3009,7 @@
}
]
],
+ "cUagXn": ["إضافة إلى ", ["gitignorePath"]],
"cUk6TF": ["فشلت المزامنة — راجع سجلات الخادم للتفاصيل."],
"cUt8yN": ["تُحفظ التغييرات تلقائيًا."],
"cV7LOw": ["ويكي الفريق"],
diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.po
index 663511c47..1bdb9de57 100644
--- a/packages/app/src/locales/ar/messages.po
+++ b/packages/app/src/locales/ar/messages.po
@@ -60,6 +60,11 @@ msgstr "«{0}»"
msgid "\"{0}\" install refreshed ({1})"
msgstr "تم تحديث تثبيت «{0}» ({1})"
+#. placeholder {0}: prompt.name
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "\"{0}\" is ignored by git"
+msgstr "يتجاهل git \"{0}\""
+
#. placeholder {0}: result.name
#: src/lib/skill-import-toast.ts
msgid "\"{0}\" was already added (identical content)."
@@ -1317,6 +1322,10 @@ msgstr "أضف الأمر <0>ok</0> إلى طرفيتك"
msgid "Add the next matching source selection."
msgstr "أضف تحديد المصدر المطابق التالي."
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Add to {gitignorePath}"
+msgstr "إضافة إلى {gitignorePath}"
+
#: src/lib/native-menu-catalog.ts
msgid "Add to Dictionary"
msgstr "إضافة إلى القاموس"
@@ -2093,6 +2102,7 @@ msgstr "تعذّرت مشاركة هذا المسار."
#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillScopeMoveDialog.tsx
+#: src/components/SkillTrackInGitDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -3492,6 +3502,10 @@ msgstr "تعذّر الوصول إلى خادم Open Knowledge لرفع {fileNam
msgid "Couldn't read {fileName}. It may have been moved, deleted, or not finished downloading. Try adding it again."
msgstr "تعذّرت قراءة {fileName}. ربما نُقل أو حُذف أو لم يكتمل تنزيله. حاول إضافته مرة أخرى."
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't read the {gitignorePath} rule: {previewError}"
+msgstr "تعذّرت قراءة قاعدة {gitignorePath}: {previewError}"
+
#: src/comments/store.ts
msgid "Couldn't read the comments waiting to send — nothing was sent."
msgstr "تعذّرت قراءة التعليقات المنتظرة للإرسال — لم يُرسل شيء."
@@ -3656,6 +3670,11 @@ msgstr "تعذّر التبديل إلى «أنا فقط»"
msgid "Couldn't unmark that comment — it's still waiting to send."
msgstr "تعذّر إلغاء تحديد ذلك التعليق — لا يزال في انتظار الإرسال."
+#. placeholder {0}: result.error
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't update {gitignorePath}: {0}"
+msgstr "تعذر تحديث {gitignorePath}: {0}"
+
#. placeholder {0}: r.error
#: src/components/SkillInstallMenu.tsx
msgid "Couldn't update {subRoot}: {0}"
@@ -13643,6 +13662,10 @@ msgstr "تم اشتراكك!"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to {gitignorePath} makes it editable here."
+msgstr "لا يزال وكلاؤك يحمّلون هذه المهارة، لكن OpenKnowledge لا يستطيع فتحها أو تحريرها: فهو لا يفهرس ملفًا ضبط git على تجاهله، لأن المزامنة ستفشل. إضافة سطر واحد إلى {gitignorePath} يجعلها قابلة للتحرير هنا."
+
#: src/components/settings/SearchSection.tsx
msgid "Your change is still being saved — run the test again in a moment."
msgstr "لا يزال تغييرك قيد الحفظ — أعد تشغيل الاختبار بعد قليل."
diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.json
index aaf8164a9..d78ae4c33 100644
--- a/packages/app/src/locales/bn/messages.json
+++ b/packages/app/src/locales/bn/messages.json
@@ -249,6 +249,7 @@
")"
],
"3LbBJn": ["ছবি সংযুক্ত করুন"],
+ "3MA3Hh": [["gitignorePath"], " নিয়ম পড়া যায়নি: ", ["previewError"]],
"3MnvrL": ["শীর্ষ ", ["0"], "টি মিল দেখানো হচ্ছে — সংকীর্ণ করতে লিখতে থাকুন"],
"3Mwaly": [["0"], " চালু করা যায়নি।"],
"3SDfZl": [
@@ -971,6 +972,11 @@
["filePath"],
"</0> স্থানীয়ভাবে বদলেছেন, কিন্তু সেটি আপস্ট্রিমে মুছে ফেলা হয়েছিল।"
],
+ "Ehb_JP": [
+ "আপনার এজেন্টরা এখনও এই স্কিলটি লোড করে, কিন্তু OpenKnowledge এটি খুলতে বা সম্পাদনা করতে পারে না: git যে ফাইল উপেক্ষা করতে সেট করা আছে সেটি এটি ইনডেক্স করে না, কারণ সিঙ্ক ব্যর্থ হবে। ",
+ ["gitignorePath"],
+ "-এ একটি লাইন যোগ করলে এটি এখানে সম্পাদনাযোগ্য হয়ে যায়।"
+ ],
"Ehkru0": ["CodeMirror-এর সম্পূর্ণকরণ পরামর্শ খুলুন, তাতে চলাচল করুন, গ্রহণ করুন, বা সরিয়ে দিন।"],
"EiVgl5": ["এই রিপোজিটরিতে পুশ করার অনুমতি আপনার নেই।"],
"Eiowpn": [
@@ -1013,6 +1019,7 @@
"F-vBv0": ["জিজ্ঞেস করুন"],
"F0OA00": [["displayName"], " নিন"],
"F1T9y_": ["শীর্ষ মিলগুলো দেখানো হচ্ছে — সংকীর্ণ করতে লিখতে থাকুন"],
+ "F1yEaG": [["gitignorePath"], " আপডেট করা যায়নি: ", ["0"]],
"F4IYWe": ["নথি ভাগ করুন"],
"F4_wQj": ["Google দিয়ে খুঁজুন"],
"F4vEsL": ["সিঙ্কের অবস্থা: ", ["syncStateLabel"]],
@@ -1205,6 +1212,7 @@
"OpenKnowledge তার কনফিগারেশন ও অভ্যন্তরীণ ফাইল আপনার প্রকল্পের রুট ফোল্ডারে নতুন তৈরি হওয়া <0>.ok</0> ডিরেক্টরির ভেতরে রাখে।"
],
"Hrz9NY": ["উইকি লিংক"],
+ "HwAKaw": ["\"", ["0"], "\" git উপেক্ষা করছে"],
"HzVAoz": [
"এই ফাইলটি স্কিলের ভেতরে সরান বা এর নাম বদলান — পথটি references/ বা scripts/-এর নিচেই থাকে।"
],
@@ -2594,6 +2602,7 @@
"cT_pW4": ["সংকোচনযোগ্য কনটেন্ট ব্লক (Notion-ধাঁচের টগল)।"],
"cU-seF": ["কার্সরে থাকা ব্লকের markdown সোর্সে যান, মাঝখানে ও হাইলাইট করা অবস্থায়।"],
"cUK8lW": [["conflictCount", "plural", { "one": ["#", " দ্বন্দ্ব"], "other": ["#", " দ্বন্দ্ব"] }]],
+ "cUagXn": [["gitignorePath"], "-এ যোগ করুন"],
"cUk6TF": ["সিঙ্ক ব্যর্থ — বিস্তারিত জানতে সার্ভার লগ দেখুন।"],
"cUt8yN": ["পরিবর্তনগুলি স্বয়ংক্রিয়ভাবে সংরক্ষিত হয়।"],
"cV7LOw": ["দলগত উইকি"],
diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.po
index cadce3459..2581b9e98 100644
--- a/packages/app/src/locales/bn/messages.po
+++ b/packages/app/src/locales/bn/messages.po
@@ -60,6 +60,11 @@ msgstr "“{0}”"
msgid "\"{0}\" install refreshed ({1})"
msgstr "\"{0}\" ইনস্টল সতেজ করা হয়েছে ({1})"
+#. placeholder {0}: prompt.name
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "\"{0}\" is ignored by git"
+msgstr "\"{0}\" git উপেক্ষা করছে"
+
#. placeholder {0}: result.name
#: src/lib/skill-import-toast.ts
msgid "\"{0}\" was already added (identical content)."
@@ -1313,6 +1318,10 @@ msgstr "আপনার টার্মিনালে <0>ok</0> কমান্
msgid "Add the next matching source selection."
msgstr "পরবর্তী মিলে যাওয়া সোর্স নির্বাচন যোগ করুন।"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Add to {gitignorePath}"
+msgstr "{gitignorePath}-এ যোগ করুন"
+
#: src/lib/native-menu-catalog.ts
msgid "Add to Dictionary"
msgstr "অভিধানে যোগ করুন"
@@ -2089,6 +2098,7 @@ msgstr "এই পাথ শেয়ার করা যাচ্ছে না
#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillScopeMoveDialog.tsx
+#: src/components/SkillTrackInGitDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -3488,6 +3498,10 @@ msgstr "{fileName} আপলোড করতে Open Knowledge সার্ভ
msgid "Couldn't read {fileName}. It may have been moved, deleted, or not finished downloading. Try adding it again."
msgstr "{fileName} পড়া যায়নি। হয়তো সেটি সরানো হয়েছে, মুছে ফেলা হয়েছে, বা ডাউনলোড শেষ হয়নি। আবার যোগ করে দেখুন।"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't read the {gitignorePath} rule: {previewError}"
+msgstr "{gitignorePath} নিয়ম পড়া যায়নি: {previewError}"
+
#: src/comments/store.ts
msgid "Couldn't read the comments waiting to send — nothing was sent."
msgstr "পাঠানোর অপেক্ষায় থাকা মন্তব্যগুলো পড়া যায়নি — কিছুই পাঠানো হয়নি।"
@@ -3652,6 +3666,11 @@ msgstr "শুধু আমার-এ যাওয়া যায়নি"
msgid "Couldn't unmark that comment — it's still waiting to send."
msgstr "ওই মন্তব্যের চিহ্ন সরানো যায়নি — সেটি এখনও পাঠানোর অপেক্ষায়।"
+#. placeholder {0}: result.error
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't update {gitignorePath}: {0}"
+msgstr "{gitignorePath} আপডেট করা যায়নি: {0}"
+
#. placeholder {0}: r.error
#: src/components/SkillInstallMenu.tsx
msgid "Couldn't update {subRoot}: {0}"
@@ -13639,6 +13658,10 @@ msgstr "আপনি সদস্য হয়েছেন!"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to {gitignorePath} makes it editable here."
+msgstr "আপনার এজেন্টরা এখনও এই স্কিলটি লোড করে, কিন্তু OpenKnowledge এটি খুলতে বা সম্পাদনা করতে পারে না: git যে ফাইল উপেক্ষা করতে সেট করা আছে সেটি এটি ইনডেক্স করে না, কারণ সিঙ্ক ব্যর্থ হবে। {gitignorePath}-এ একটি লাইন যোগ করলে এটি এখানে সম্পাদনাযোগ্য হয়ে যায়।"
+
#: src/components/settings/SearchSection.tsx
msgid "Your change is still being saved — run the test again in a moment."
msgstr "আপনার পরিবর্তন এখনও সংরক্ষিত হচ্ছে — একটু পরে পরীক্ষাটি আবার চালান।"
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 92133359e..f17474b8b 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -254,6 +254,7 @@
")"
],
"3LbBJn": ["Attach images"],
+ "3MA3Hh": ["Couldn't read the ", ["gitignorePath"], " rule: ", ["previewError"]],
"3MnvrL": ["Showing top ", ["0"], " matches — keep typing to narrow"],
"3Mwaly": ["Could not initialize ", ["0"], "."],
"3SDfZl": [
@@ -1001,6 +1002,11 @@
"Ef6ukL": ["via parent"],
"Ef7StM": ["Unknown"],
"EhDLBx": ["You modified <0>", ["filePath"], "</0> locally, but it was deleted upstream."],
+ "Ehb_JP": [
+ "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to ",
+ ["gitignorePath"],
+ " makes it editable here."
+ ],
"Ehkru0": ["Open, navigate, accept, or dismiss CodeMirror completion suggestions."],
"EiVgl5": ["You don't have permission to push to this repo."],
"Eiowpn": [
@@ -1043,6 +1049,7 @@
"F-vBv0": ["Ask"],
"F0OA00": ["Get ", ["displayName"]],
"F1T9y_": ["Showing top matches — keep typing to narrow"],
+ "F1yEaG": ["Couldn't update ", ["gitignorePath"], ": ", ["0"]],
"F4IYWe": ["Share doc"],
"F4_wQj": ["Search with Google"],
"F4vEsL": ["Sync status: ", ["syncStateLabel"]],
@@ -1246,6 +1253,7 @@
"OpenKnowledge stores its configuration and internal files inside a newly created <0>.ok</0> directory in your project root folder."
],
"Hrz9NY": ["Wiki link"],
+ "HwAKaw": ["\"", ["0"], "\" is ignored by git"],
"HzVAoz": [
"Move or rename this file inside the skill — the path stays under references/ or scripts/."
],
@@ -2652,6 +2660,7 @@
"cUK8lW": [
["conflictCount", "plural", { "one": ["#", " conflict"], "other": ["#", " conflicts"] }]
],
+ "cUagXn": ["Add to ", ["gitignorePath"]],
"cUk6TF": ["Sync failed — check the server logs for details."],
"cUt8yN": ["Changes save automatically."],
"cV7LOw": ["Team Wiki"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 37defb5b2..d0d98ee62 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -60,6 +60,11 @@ msgstr "\"{0}\""
msgid "\"{0}\" install refreshed ({1})"
msgstr "\"{0}\" install refreshed ({1})"
+#. placeholder {0}: prompt.name
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "\"{0}\" is ignored by git"
+msgstr "\"{0}\" is ignored by git"
+
#. placeholder {0}: result.name
#: src/lib/skill-import-toast.ts
msgid "\"{0}\" was already added (identical content)."
@@ -1317,6 +1322,10 @@ msgstr "Add the <0>ok</0> command to your terminal"
msgid "Add the next matching source selection."
msgstr "Add the next matching source selection."
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Add to {gitignorePath}"
+msgstr "Add to {gitignorePath}"
+
#: src/lib/native-menu-catalog.ts
msgid "Add to Dictionary"
msgstr "Add to Dictionary"
@@ -2093,6 +2102,7 @@ msgstr "Can't share this path."
#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillScopeMoveDialog.tsx
+#: src/components/SkillTrackInGitDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -3492,6 +3502,10 @@ msgstr "Couldn't reach the Open Knowledge server to upload {fileName}."
msgid "Couldn't read {fileName}. It may have been moved, deleted, or not finished downloading. Try adding it again."
msgstr "Couldn't read {fileName}. It may have been moved, deleted, or not finished downloading. Try adding it again."
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't read the {gitignorePath} rule: {previewError}"
+msgstr "Couldn't read the {gitignorePath} rule: {previewError}"
+
#: src/comments/store.ts
msgid "Couldn't read the comments waiting to send — nothing was sent."
msgstr "Couldn't read the comments waiting to send — nothing was sent."
@@ -3656,6 +3670,11 @@ msgstr "Couldn't switch to Only me"
msgid "Couldn't unmark that comment — it's still waiting to send."
msgstr "Couldn't unmark that comment — it's still waiting to send."
+#. placeholder {0}: result.error
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't update {gitignorePath}: {0}"
+msgstr "Couldn't update {gitignorePath}: {0}"
+
#. placeholder {0}: r.error
#: src/components/SkillInstallMenu.tsx
msgid "Couldn't update {subRoot}: {0}"
@@ -13643,6 +13662,10 @@ msgstr "You're subscribed!"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to {gitignorePath} makes it editable here."
+msgstr "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to {gitignorePath} makes it editable here."
+
#: src/components/settings/SearchSection.tsx
msgid "Your change is still being saved — run the test again in a moment."
msgstr "Your change is still being saved — run the test again in a moment."
diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.json
index ae6e5fe33..c3979b39f 100644
--- a/packages/app/src/locales/es/messages.json
+++ b/packages/app/src/locales/es/messages.json
@@ -287,6 +287,7 @@
")"
],
"3LbBJn": ["Adjuntar imágenes"],
+ "3MA3Hh": ["No se pudo leer la regla de ", ["gitignorePath"], ": ", ["previewError"]],
"3MnvrL": [
"Mostrando las ",
["0"],
@@ -1155,6 +1156,11 @@
"Ef6ukL": ["vía la carpeta superior"],
"Ef7StM": ["Desconocido"],
"EhDLBx": ["Modificaste <0>", ["filePath"], "</0> en local, pero se eliminó en el remoto."],
+ "Ehb_JP": [
+ "Tus agentes siguen cargando esta habilidad, pero OpenKnowledge no puede abrirla ni editarla: no indexa un archivo que git está configurado para ignorar, porque la sincronización fallaría. Añadir una línea a ",
+ ["gitignorePath"],
+ " la hace editable aquí."
+ ],
"Ehkru0": ["Abre, recorre, acepta o descarta las sugerencias de autocompletado de CodeMirror."],
"EiVgl5": ["No tienes permiso para hacer push a este repositorio."],
"Eiowpn": [
@@ -1197,6 +1203,7 @@
"F-vBv0": ["Preguntar"],
"F0OA00": ["Obtener ", ["displayName"]],
"F1T9y_": ["Mostrando las coincidencias principales; sigue escribiendo para acotar"],
+ "F1yEaG": ["No se pudo actualizar ", ["gitignorePath"], ": ", ["0"]],
"F4IYWe": ["Compartir el documento"],
"F4_wQj": ["Buscar con Google"],
"F4vEsL": ["Estado de sincronización: ", ["syncStateLabel"]],
@@ -1448,6 +1455,7 @@
"OpenKnowledge guarda su configuración y sus archivos internos en un directorio <0>.ok</0> recién creado en la carpeta raíz de tu proyecto."
],
"Hrz9NY": ["Enlace wiki"],
+ "HwAKaw": ["«", ["0"], "» está ignorado por git"],
"HzVAoz": [
"Mueve o renombra este archivo dentro de la habilidad: la ruta se mantiene bajo references/ o scripts/."
],
@@ -3068,6 +3076,7 @@
{ "one": ["#", " conflicto"], "many": ["#", " conflictos"], "other": ["#", " conflictos"] }
]
],
+ "cUagXn": ["Añadir a ", ["gitignorePath"]],
"cUk6TF": [
"Falló la sincronización: consulta los registros del servidor para ver los detalles."
],
diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.po
index 44b368325..e0579d722 100644
--- a/packages/app/src/locales/es/messages.po
+++ b/packages/app/src/locales/es/messages.po
@@ -60,6 +60,11 @@ msgstr "«{0}»"
msgid "\"{0}\" install refreshed ({1})"
msgstr "Se actualizó la instalación de \"{0}\" ({1})"
+#. placeholder {0}: prompt.name
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "\"{0}\" is ignored by git"
+msgstr "«{0}» está ignorado por git"
+
#. placeholder {0}: result.name
#: src/lib/skill-import-toast.ts
msgid "\"{0}\" was already added (identical content)."
@@ -1317,6 +1322,10 @@ msgstr "Añade el comando <0>ok</0> a tu terminal"
msgid "Add the next matching source selection."
msgstr "Añade la siguiente coincidencia de la selección de origen."
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Add to {gitignorePath}"
+msgstr "Añadir a {gitignorePath}"
+
#: src/lib/native-menu-catalog.ts
msgid "Add to Dictionary"
msgstr "Añadir al diccionario"
@@ -2093,6 +2102,7 @@ msgstr "No se puede compartir esta ruta."
#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillScopeMoveDialog.tsx
+#: src/components/SkillTrackInGitDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -3492,6 +3502,10 @@ msgstr "No se pudo contactar con el servidor de Open Knowledge para subir {fileN
msgid "Couldn't read {fileName}. It may have been moved, deleted, or not finished downloading. Try adding it again."
msgstr "No se pudo leer {fileName}. Puede que se haya movido, eliminado o que no haya terminado de descargarse. Prueba a añadirlo de nuevo."
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't read the {gitignorePath} rule: {previewError}"
+msgstr "No se pudo leer la regla de {gitignorePath}: {previewError}"
+
#: src/comments/store.ts
msgid "Couldn't read the comments waiting to send — nothing was sent."
msgstr "No se pudieron leer los comentarios pendientes de envío; no se envió nada."
@@ -3656,6 +3670,11 @@ msgstr "No se pudo cambiar a Solo yo"
msgid "Couldn't unmark that comment — it's still waiting to send."
msgstr "No se pudo desmarcar ese comentario: sigue pendiente de envío."
+#. placeholder {0}: result.error
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't update {gitignorePath}: {0}"
+msgstr "No se pudo actualizar {gitignorePath}: {0}"
+
#. placeholder {0}: r.error
#: src/components/SkillInstallMenu.tsx
msgid "Couldn't update {subRoot}: {0}"
@@ -13643,6 +13662,10 @@ msgstr "¡Te has suscrito!"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to {gitignorePath} makes it editable here."
+msgstr "Tus agentes siguen cargando esta habilidad, pero OpenKnowledge no puede abrirla ni editarla: no indexa un archivo que git está configurado para ignorar, porque la sincronización fallaría. Añadir una línea a {gitignorePath} la hace editable aquí."
+
#: src/components/settings/SearchSection.tsx
msgid "Your change is still being saved — run the test again in a moment."
msgstr "Tu cambio todavía se está guardando; vuelve a ejecutar la prueba en un momento."
diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.json
index 556699cac..60f4c8acc 100644
--- a/packages/app/src/locales/fr/messages.json
+++ b/packages/app/src/locales/fr/messages.json
@@ -299,6 +299,7 @@
")"
],
"3LbBJn": ["Joindre des images"],
+ "3MA3Hh": ["Impossible de lire la règle de ", ["gitignorePath"], " : ", ["previewError"]],
"3MnvrL": [
"Affichage des ",
["0"],
@@ -1191,6 +1192,11 @@
["filePath"],
"</0> en local, mais il a été supprimé en amont."
],
+ "Ehb_JP": [
+ "Vos agents chargent toujours cette compétence, mais OpenKnowledge ne peut ni l'ouvrir ni la modifier : il n'indexe pas un fichier que git est configuré pour ignorer, car la synchronisation échouerait. Ajouter une ligne à ",
+ ["gitignorePath"],
+ " la rend modifiable ici."
+ ],
"Ehkru0": ["Ouvre, parcourt, accepte ou ferme les suggestions de complétion de CodeMirror."],
"EiVgl5": ["Vous n'avez pas la permission de pousser vers ce dépôt."],
"Eiowpn": [
@@ -1232,6 +1238,7 @@
"F-vBv0": ["Demander"],
"F0OA00": ["Obtenir ", ["displayName"]],
"F1T9y_": ["Affichage des résultats les plus pertinents — continuez à saisir pour affiner"],
+ "F1yEaG": ["Impossible de mettre à jour ", ["gitignorePath"], " : ", ["0"]],
"F4IYWe": ["Partager le document"],
"F4_wQj": ["Rechercher avec Google"],
"F4vEsL": ["État de la synchronisation : ", ["syncStateLabel"]],
@@ -1475,6 +1482,7 @@
"OpenKnowledge stocke sa configuration et ses fichiers internes dans un répertoire <0>.ok</0> nouvellement créé à la racine de votre projet."
],
"Hrz9NY": ["Lien wiki"],
+ "HwAKaw": ["« ", ["0"], " » est ignoré par git"],
"HzVAoz": [
"Déplacez ou renommez ce fichier à l'intérieur de la compétence — le chemin reste sous references/ ou scripts/."
],
@@ -3103,6 +3111,7 @@
{ "one": ["#", " conflit"], "many": ["#", " conflits"], "other": ["#", " conflits"] }
]
],
+ "cUagXn": ["Ajouter à ", ["gitignorePath"]],
"cUk6TF": ["Échec de la synchronisation — consultez les journaux du serveur pour les détails."],
"cUt8yN": ["Les modifications sont enregistrées automatiquement."],
"cV7LOw": ["Wiki d'équipe"],
diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.po
index 3b0ac12f2..fdb4eeefd 100644
--- a/packages/app/src/locales/fr/messages.po
+++ b/packages/app/src/locales/fr/messages.po
@@ -60,6 +60,11 @@ msgstr "« {0} »"
msgid "\"{0}\" install refreshed ({1})"
msgstr "Installation de « {0} » actualisée ({1})"
+#. placeholder {0}: prompt.name
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "\"{0}\" is ignored by git"
+msgstr "« {0} » est ignoré par git"
+
#. placeholder {0}: result.name
#: src/lib/skill-import-toast.ts
msgid "\"{0}\" was already added (identical content)."
@@ -1317,6 +1322,10 @@ msgstr "Ajoutez la commande <0>ok</0> à votre terminal"
msgid "Add the next matching source selection."
msgstr "Ajoute la sélection source correspondante suivante."
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Add to {gitignorePath}"
+msgstr "Ajouter à {gitignorePath}"
+
#: src/lib/native-menu-catalog.ts
msgid "Add to Dictionary"
msgstr "Ajouter au dictionnaire"
@@ -2093,6 +2102,7 @@ msgstr "Impossible de partager ce chemin."
#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillScopeMoveDialog.tsx
+#: src/components/SkillTrackInGitDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -3492,6 +3502,10 @@ msgstr "Impossible de joindre le serveur Open Knowledge pour envoyer {fileName}.
msgid "Couldn't read {fileName}. It may have been moved, deleted, or not finished downloading. Try adding it again."
msgstr "Impossible de lire {fileName}. Il a peut-être été déplacé, supprimé, ou son téléchargement n'est pas terminé. Essayez de l'ajouter à nouveau."
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't read the {gitignorePath} rule: {previewError}"
+msgstr "Impossible de lire la règle de {gitignorePath} : {previewError}"
+
#: src/comments/store.ts
msgid "Couldn't read the comments waiting to send — nothing was sent."
msgstr "Impossible de lire les commentaires en attente d'envoi — rien n'a été envoyé."
@@ -3656,6 +3670,11 @@ msgstr "Impossible de passer à Moi uniquement"
msgid "Couldn't unmark that comment — it's still waiting to send."
msgstr "Impossible de retirer la marque de ce commentaire — il attend toujours d'être envoyé."
+#. placeholder {0}: result.error
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't update {gitignorePath}: {0}"
+msgstr "Impossible de mettre à jour {gitignorePath} : {0}"
+
#. placeholder {0}: r.error
#: src/components/SkillInstallMenu.tsx
msgid "Couldn't update {subRoot}: {0}"
@@ -13643,6 +13662,10 @@ msgstr "Vous êtes abonné !"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to {gitignorePath} makes it editable here."
+msgstr "Vos agents chargent toujours cette compétence, mais OpenKnowledge ne peut ni l'ouvrir ni la modifier : il n'indexe pas un fichier que git est configuré pour ignorer, car la synchronisation échouerait. Ajouter une ligne à {gitignorePath} la rend modifiable ici."
+
#: src/components/settings/SearchSection.tsx
msgid "Your change is still being saved — run the test again in a moment."
msgstr "Votre modification est encore en cours d'enregistrement — relancez le test dans un instant."
diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.json
index 1496384b4..b2eeaa335 100644
--- a/packages/app/src/locales/hi/messages.json
+++ b/packages/app/src/locales/hi/messages.json
@@ -249,6 +249,7 @@
")"
],
"3LbBJn": ["छवियाँ संलग्न करें"],
+ "3MA3Hh": [["gitignorePath"], " नियम नहीं पढ़ा जा सका: ", ["previewError"]],
"3MnvrL": ["शीर्ष ", ["0"], " मेल दिखाए जा रहे हैं — सीमित करने के लिए लिखते रहें"],
"3Mwaly": [["0"], " आरंभ नहीं किया जा सका।"],
"3SDfZl": [
@@ -966,6 +967,11 @@
"Ef6ukL": ["मूल के ज़रिए"],
"Ef7StM": ["अज्ञात"],
"EhDLBx": ["आपने <0>", ["filePath"], "</0> स्थानीय रूप से बदली, पर उसे अपस्ट्रीम में हटा दिया गया था।"],
+ "Ehb_JP": [
+ "आपके एजेंट यह स्किल अब भी लोड करते हैं, लेकिन OpenKnowledge इसे खोल या संपादित नहीं कर सकता: यह ऐसी फ़ाइल को इंडेक्स नहीं करता जिसे अनदेखा करने के लिए git सेट है, क्योंकि सिंक विफल हो जाएगा। ",
+ ["gitignorePath"],
+ " में एक पंक्ति जोड़ने से यह यहाँ संपादन योग्य हो जाती है।"
+ ],
"Ehkru0": ["CodeMirror के पूर्णता सुझाव खोलें, उनमें जाएँ, स्वीकारें या ख़ारिज करें।"],
"EiVgl5": ["आपके पास इस रिपॉज़िटरी में पुश करने की अनुमति नहीं है।"],
"Eiowpn": [
@@ -1008,6 +1014,7 @@
"F-vBv0": ["पूछें"],
"F0OA00": [["displayName"], " लें"],
"F1T9y_": ["शीर्ष मेल दिखाए जा रहे हैं — सीमित करने के लिए लिखते रहें"],
+ "F1yEaG": [["gitignorePath"], " अपडेट नहीं हो सका: ", ["0"]],
"F4IYWe": ["दस्तावेज़ साझा करें"],
"F4_wQj": ["Google से खोजें"],
"F4vEsL": ["सिंक स्थिति: ", ["syncStateLabel"]],
@@ -1196,6 +1203,7 @@
"OpenKnowledge अपना कॉन्फ़िगरेशन और आंतरिक फ़ाइलें आपके प्रोजेक्ट के मूल फ़ोल्डर में नई बनी <0>.ok</0> निर्देशिका के भीतर रखता है।"
],
"Hrz9NY": ["विकी लिंक"],
+ "HwAKaw": ["\"", ["0"], "\" को git अनदेखा कर रहा है"],
"HzVAoz": [
"इस फ़ाइल को स्किल के भीतर हिलाएँ या इसका नाम बदलें — पथ references/ या scripts/ के अंतर्गत ही रहता है।"
],
@@ -2579,6 +2587,7 @@
"cT_pW4": ["संक्षिप्त किया जा सकने वाला सामग्री ब्लॉक (Notion-शैली टॉगल)।"],
"cU-seF": ["कर्सर वाले ब्लॉक के markdown स्रोत पर जाएँ, बीच में और उभारा हुआ।"],
"cUK8lW": [["conflictCount", "plural", { "one": ["#", " टकराव"], "other": ["#", " टकराव"] }]],
+ "cUagXn": [["gitignorePath"], " में जोड़ें"],
"cUk6TF": ["सिंक विफल — विवरण के लिए सर्वर लॉग देखें।"],
"cUt8yN": ["बदलाव अपने आप सहेजे जाते हैं।"],
"cV7LOw": ["टीम विकी"],
diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.po
index 945a78444..f0b2d0514 100644
--- a/packages/app/src/locales/hi/messages.po
+++ b/packages/app/src/locales/hi/messages.po
@@ -60,6 +60,11 @@ msgstr "“{0}”"
msgid "\"{0}\" install refreshed ({1})"
msgstr "\"{0}\" इंस्टॉल ताज़ा किया गया ({1})"
+#. placeholder {0}: prompt.name
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "\"{0}\" is ignored by git"
+msgstr "\"{0}\" को git अनदेखा कर रहा है"
+
#. placeholder {0}: result.name
#: src/lib/skill-import-toast.ts
msgid "\"{0}\" was already added (identical content)."
@@ -1313,6 +1318,10 @@ msgstr "अपने टर्मिनल में <0>ok</0> कमांड
msgid "Add the next matching source selection."
msgstr "अगला मेल खाता स्रोत चयन जोड़ें।"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Add to {gitignorePath}"
+msgstr "{gitignorePath} में जोड़ें"
+
#: src/lib/native-menu-catalog.ts
msgid "Add to Dictionary"
msgstr "शब्दकोश में जोड़ें"
@@ -2089,6 +2098,7 @@ msgstr "यह पथ साझा नहीं किया जा सकता
#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillScopeMoveDialog.tsx
+#: src/components/SkillTrackInGitDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -3488,6 +3498,10 @@ msgstr "{fileName} अपलोड करने के लिए Open Knowledge
msgid "Couldn't read {fileName}. It may have been moved, deleted, or not finished downloading. Try adding it again."
msgstr "{fileName} नहीं पढ़ी जा सकी। शायद इसे हिलाया गया, हटाया गया, या इसका डाउनलोड पूरा नहीं हुआ। इसे फिर से जोड़ने की कोशिश करें।"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't read the {gitignorePath} rule: {previewError}"
+msgstr "{gitignorePath} नियम नहीं पढ़ा जा सका: {previewError}"
+
#: src/comments/store.ts
msgid "Couldn't read the comments waiting to send — nothing was sent."
msgstr "भेजे जाने की प्रतीक्षा में मौजूद टिप्पणियाँ नहीं पढ़ी जा सकीं — कुछ भी नहीं भेजा गया।"
@@ -3652,6 +3666,11 @@ msgstr "केवल मेरे लिए पर नहीं जाया ज
msgid "Couldn't unmark that comment — it's still waiting to send."
msgstr "उस टिप्पणी का चिह्न नहीं हटाया जा सका — यह अब भी भेजे जाने की प्रतीक्षा में है।"
+#. placeholder {0}: result.error
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't update {gitignorePath}: {0}"
+msgstr "{gitignorePath} अपडेट नहीं हो सका: {0}"
+
#. placeholder {0}: r.error
#: src/components/SkillInstallMenu.tsx
msgid "Couldn't update {subRoot}: {0}"
@@ -13639,6 +13658,10 @@ msgstr "आपने सदस्यता ले ली!"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to {gitignorePath} makes it editable here."
+msgstr "आपके एजेंट यह स्किल अब भी लोड करते हैं, लेकिन OpenKnowledge इसे खोल या संपादित नहीं कर सकता: यह ऐसी फ़ाइल को इंडेक्स नहीं करता जिसे अनदेखा करने के लिए git सेट है, क्योंकि सिंक विफल हो जाएगा। {gitignorePath} में एक पंक्ति जोड़ने से यह यहाँ संपादन योग्य हो जाती है।"
+
#: src/components/settings/SearchSection.tsx
msgid "Your change is still being saved — run the test again in a moment."
msgstr "आपका बदलाव अब भी सहेजा जा रहा है — कुछ देर बाद परीक्षण फिर चलाएँ।"
diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.json
index 4e44d162a..b0be4f56e 100644
--- a/packages/app/src/locales/id/messages.json
+++ b/packages/app/src/locales/id/messages.json
@@ -251,6 +251,7 @@
")"
],
"3LbBJn": ["Lampirkan gambar"],
+ "3MA3Hh": ["Tidak dapat membaca aturan ", ["gitignorePath"], ": ", ["previewError"]],
"3MnvrL": ["Menampilkan ", ["0"], " kecocokan teratas — terus ketik untuk mempersempit"],
"3Mwaly": [["0"], " tidak dapat diinisialisasi."],
"3SDfZl": [
@@ -992,6 +993,11 @@
["filePath"],
"</0> secara lokal, tetapi ia dihapus di remote."
],
+ "Ehb_JP": [
+ "Agen Anda tetap memuat keterampilan ini, tetapi OpenKnowledge tidak dapat membuka atau mengeditnya: OpenKnowledge tidak mengindeks berkas yang diatur untuk diabaikan oleh git, karena sinkronisasi akan gagal. Menambahkan satu baris ke ",
+ ["gitignorePath"],
+ " membuatnya dapat diedit di sini."
+ ],
"Ehkru0": ["Membuka, menelusuri, menerima, atau menutup saran pelengkapan CodeMirror."],
"EiVgl5": ["Anda tidak punya izin push ke repo ini."],
"Eiowpn": [
@@ -1034,6 +1040,7 @@
"F-vBv0": ["Tanya"],
"F0OA00": ["Dapatkan ", ["displayName"]],
"F1T9y_": ["Menampilkan kecocokan teratas — terus ketik untuk mempersempit"],
+ "F1yEaG": ["Tidak dapat memperbarui ", ["gitignorePath"], ": ", ["0"]],
"F4IYWe": ["Bagikan dokumen"],
"F4_wQj": ["Cari dengan Google"],
"F4vEsL": ["Status sinkronisasi: ", ["syncStateLabel"]],
@@ -1248,6 +1255,7 @@
"OpenKnowledge menyimpan konfigurasi dan berkas internalnya di dalam direktori <0>.ok</0> yang baru dibuat di folder akar proyek Anda."
],
"Hrz9NY": ["Tautan wiki"],
+ "HwAKaw": ["\"", ["0"], "\" diabaikan oleh git"],
"HzVAoz": [
"Pindahkan atau ganti nama berkas ini di dalam keterampilan — jalurnya tetap di bawah references/ atau scripts/."
],
@@ -2687,6 +2695,7 @@
"cT_pW4": ["Blok konten yang dapat dilipat (toggle gaya Notion)."],
"cU-seF": ["Lompat ke sumber markdown untuk blok di posisi kursor, terpusat dan tersorot."],
"cUK8lW": [["conflictCount", "plural", { "other": ["#", " konflik"] }]],
+ "cUagXn": ["Tambahkan ke ", ["gitignorePath"]],
"cUk6TF": ["Sinkronisasi gagal — periksa log server untuk detailnya."],
"cUt8yN": ["Perubahan disimpan otomatis."],
"cV7LOw": ["Wiki Tim"],
diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.po
index 86c386c21..4222407e5 100644
--- a/packages/app/src/locales/id/messages.po
+++ b/packages/app/src/locales/id/messages.po
@@ -60,6 +60,11 @@ msgstr "“{0}”"
msgid "\"{0}\" install refreshed ({1})"
msgstr "Pemasangan \"{0}\" diperbarui ({1})"
+#. placeholder {0}: prompt.name
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "\"{0}\" is ignored by git"
+msgstr "\"{0}\" diabaikan oleh git"
+
#. placeholder {0}: result.name
#: src/lib/skill-import-toast.ts
msgid "\"{0}\" was already added (identical content)."
@@ -1313,6 +1318,10 @@ msgstr "Tambahkan perintah <0>ok</0> ke terminal Anda"
msgid "Add the next matching source selection."
msgstr "Menambahkan pilihan sumber berikutnya yang cocok."
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Add to {gitignorePath}"
+msgstr "Tambahkan ke {gitignorePath}"
+
#: src/lib/native-menu-catalog.ts
msgid "Add to Dictionary"
msgstr "Tambahkan ke kamus"
@@ -2089,6 +2098,7 @@ msgstr "Tidak dapat membagikan jalur ini."
#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillScopeMoveDialog.tsx
+#: src/components/SkillTrackInGitDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -3488,6 +3498,10 @@ msgstr "Server Open Knowledge tidak bisa dihubungi untuk mengunggah {fileName}."
msgid "Couldn't read {fileName}. It may have been moved, deleted, or not finished downloading. Try adding it again."
msgstr "{fileName} tidak bisa dibaca. Mungkin ia sudah dipindahkan, dihapus, atau belum selesai diunduh. Coba tambahkan lagi."
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't read the {gitignorePath} rule: {previewError}"
+msgstr "Tidak dapat membaca aturan {gitignorePath}: {previewError}"
+
#: src/comments/store.ts
msgid "Couldn't read the comments waiting to send — nothing was sent."
msgstr "Komentar yang menunggu dikirim tidak bisa dibaca — tidak ada yang dikirim."
@@ -3652,6 +3666,11 @@ msgstr "Tidak bisa berpindah ke Hanya saya"
msgid "Couldn't unmark that comment — it's still waiting to send."
msgstr "Tanda pada komentar itu tidak bisa dilepas — ia masih menunggu dikirim."
+#. placeholder {0}: result.error
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't update {gitignorePath}: {0}"
+msgstr "Tidak dapat memperbarui {gitignorePath}: {0}"
+
#. placeholder {0}: r.error
#: src/components/SkillInstallMenu.tsx
msgid "Couldn't update {subRoot}: {0}"
@@ -13639,6 +13658,10 @@ msgstr "Anda sudah berlangganan!"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to {gitignorePath} makes it editable here."
+msgstr "Agen Anda tetap memuat keterampilan ini, tetapi OpenKnowledge tidak dapat membuka atau mengeditnya: OpenKnowledge tidak mengindeks berkas yang diatur untuk diabaikan oleh git, karena sinkronisasi akan gagal. Menambahkan satu baris ke {gitignorePath} membuatnya dapat diedit di sini."
+
#: src/components/settings/SearchSection.tsx
msgid "Your change is still being saved — run the test again in a moment."
msgstr "Perubahan Anda masih disimpan — jalankan pengujiannya lagi sebentar."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 7dc7ee4d4..7e4c49977 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -254,6 +254,7 @@
")"
],
"3LbBJn": ["Àţţàćĥ ĩḿàĝēś"],
+ "3MA3Hh": ["Ćōũĺďń'ţ ŕēàď ţĥē ", ["gitignorePath"], " ŕũĺē: ", ["previewError"]],
"3MnvrL": ["Śĥōŵĩńĝ ţōƥ ", ["0"], " ḿàţćĥēś — ķēēƥ ţŷƥĩńĝ ţō ńàŕŕōŵ"],
"3Mwaly": ["Ćōũĺď ńōţ ĩńĩţĩàĺĩźē ", ["0"], "."],
"3SDfZl": [
@@ -1001,6 +1002,11 @@
"Ef6ukL": ["vĩà ƥàŕēńţ"],
"Ef7StM": ["Ũńķńōŵń"],
"EhDLBx": ["Ŷōũ ḿōďĩƒĩēď <0>", ["filePath"], "</0> ĺōćàĺĺŷ, ƀũţ ĩţ ŵàś ďēĺēţēď ũƥśţŕēàḿ."],
+ "Ehb_JP": [
+ "Ŷōũŕ àĝēńţś śţĩĺĺ ĺōàď ţĥĩś śķĩĺĺ, ƀũţ ŌƥēńĶńōŵĺēďĝē ćàń'ţ ōƥēń ōŕ ēďĩţ ĩţ: ĩţ ŵōń'ţ ĩńďēx à ƒĩĺē ţĥàţ ĝĩţ ĩś śēţ ţō ĩĝńōŕē, ƀēćàũśē śŷńćĩńĝ ĩţ ŵōũĺď ƒàĩĺ. Àďďĩńĝ ōńē ĺĩńē ţō ",
+ ["gitignorePath"],
+ " ḿàķēś ĩţ ēďĩţàƀĺē ĥēŕē."
+ ],
"Ehkru0": ["Ōƥēń, ńàvĩĝàţē, àććēƥţ, ōŕ ďĩśḿĩśś ĆōďēḾĩŕŕōŕ ćōḿƥĺēţĩōń śũĝĝēśţĩōńś."],
"EiVgl5": ["Ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō."],
"Eiowpn": [
@@ -1043,6 +1049,7 @@
"F-vBv0": ["Àśķ"],
"F0OA00": ["Ĝēţ ", ["displayName"]],
"F1T9y_": ["Śĥōŵĩńĝ ţōƥ ḿàţćĥēś — ķēēƥ ţŷƥĩńĝ ţō ńàŕŕōŵ"],
+ "F1yEaG": ["Ćōũĺďń'ţ ũƥďàţē ", ["gitignorePath"], ": ", ["0"]],
"F4IYWe": ["Śĥàŕē ďōć"],
"F4_wQj": ["Śēàŕćĥ ŵĩţĥ Ĝōōĝĺē"],
"F4vEsL": ["Śŷńć śţàţũś: ", ["syncStateLabel"]],
@@ -1246,6 +1253,7 @@
"ŌƥēńĶńōŵĺēďĝē śţōŕēś ĩţś ćōńƒĩĝũŕàţĩōń àńď ĩńţēŕńàĺ ƒĩĺēś ĩńśĩďē à ńēŵĺŷ ćŕēàţēď <0>.ōķ</0> ďĩŕēćţōŕŷ ĩń ŷōũŕ ƥŕōĴēćţ ŕōōţ ƒōĺďēŕ."
],
"Hrz9NY": ["Ŵĩķĩ ĺĩńķ"],
+ "HwAKaw": ["\"", ["0"], "\" ĩś ĩĝńōŕēď ƀŷ ĝĩţ"],
"HzVAoz": [
"Ḿōvē ōŕ ŕēńàḿē ţĥĩś ƒĩĺē ĩńśĩďē ţĥē śķĩĺĺ — ţĥē ƥàţĥ śţàŷś ũńďēŕ ŕēƒēŕēńćēś/ ōŕ śćŕĩƥţś/."
],
@@ -2652,6 +2660,7 @@
"cUK8lW": [
["conflictCount", "plural", { "one": ["#", " ćōńƒĺĩćţ"], "other": ["#", " ćōńƒĺĩćţś"] }]
],
+ "cUagXn": ["Àďď ţō ", ["gitignorePath"]],
"cUk6TF": ["Śŷńć ƒàĩĺēď — ćĥēćķ ţĥē śēŕvēŕ ĺōĝś ƒōŕ ďēţàĩĺś."],
"cUt8yN": ["Ćĥàńĝēś śàvē àũţōḿàţĩćàĺĺŷ."],
"cV7LOw": ["Ţēàḿ Ŵĩķĩ"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 0d6a2d4e1..a520b7b78 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -60,6 +60,11 @@ msgstr ""
msgid "\"{0}\" install refreshed ({1})"
msgstr ""
+#. placeholder {0}: prompt.name
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "\"{0}\" is ignored by git"
+msgstr ""
+
#. placeholder {0}: result.name
#: src/lib/skill-import-toast.ts
msgid "\"{0}\" was already added (identical content)."
@@ -1313,6 +1318,10 @@ msgstr ""
msgid "Add the next matching source selection."
msgstr ""
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Add to {gitignorePath}"
+msgstr ""
+
#: src/lib/native-menu-catalog.ts
msgid "Add to Dictionary"
msgstr ""
@@ -2089,6 +2098,7 @@ msgstr ""
#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillScopeMoveDialog.tsx
+#: src/components/SkillTrackInGitDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -3488,6 +3498,10 @@ msgstr ""
msgid "Couldn't read {fileName}. It may have been moved, deleted, or not finished downloading. Try adding it again."
msgstr ""
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't read the {gitignorePath} rule: {previewError}"
+msgstr ""
+
#: src/comments/store.ts
msgid "Couldn't read the comments waiting to send — nothing was sent."
msgstr ""
@@ -3652,6 +3666,11 @@ msgstr ""
msgid "Couldn't unmark that comment — it's still waiting to send."
msgstr ""
+#. placeholder {0}: result.error
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't update {gitignorePath}: {0}"
+msgstr ""
+
#. placeholder {0}: r.error
#: src/components/SkillInstallMenu.tsx
msgid "Couldn't update {subRoot}: {0}"
@@ -13639,6 +13658,10 @@ msgstr ""
msgstr ""
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to {gitignorePath} makes it editable here."
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "Your change is still being saved — run the test again in a moment."
msgstr ""
diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.json
index cb8780382..41845af25 100644
--- a/packages/app/src/locales/pt-BR/messages.json
+++ b/packages/app/src/locales/pt-BR/messages.json
@@ -283,6 +283,7 @@
")"
],
"3LbBJn": ["Anexar imagens"],
+ "3MA3Hh": ["Não foi possível ler a regra de ", ["gitignorePath"], ": ", ["previewError"]],
"3MnvrL": [
"Mostrando as ",
["0"],
@@ -1147,6 +1148,11 @@
["filePath"],
"</0> localmente, mas ele foi excluído no remoto."
],
+ "Ehb_JP": [
+ "Seus agentes continuam carregando esta habilidade, mas o OpenKnowledge não consegue abri-la nem editá-la: ele não indexa um arquivo que o git está configurado para ignorar, porque a sincronização falharia. Adicionar uma linha ao ",
+ ["gitignorePath"],
+ " a torna editável aqui."
+ ],
"Ehkru0": ["Abre, percorre, aceita ou dispensa as sugestões de autocompletar do CodeMirror."],
"EiVgl5": ["Você não tem permissão para enviar a este repositório."],
"Eiowpn": [
@@ -1189,6 +1195,7 @@
"F-vBv0": ["Perguntar"],
"F0OA00": ["Obter ", ["displayName"]],
"F1T9y_": ["Mostrando as principais ocorrências — continue digitando para restringir"],
+ "F1yEaG": ["Não foi possível atualizar ", ["gitignorePath"], ": ", ["0"]],
"F4IYWe": ["Compartilhar o documento"],
"F4_wQj": ["Pesquisar com o Google"],
"F4vEsL": ["Status da sincronização: ", ["syncStateLabel"]],
@@ -1436,6 +1443,7 @@
"O OpenKnowledge guarda sua configuração e seus arquivos internos em um diretório <0>.ok</0> recém-criado na pasta raiz do seu projeto."
],
"Hrz9NY": ["Link wiki"],
+ "HwAKaw": ["\"", ["0"], "\" é ignorado pelo git"],
"HzVAoz": [
"Mova ou renomeie este arquivo dentro da habilidade — o caminho continua sob references/ ou scripts/."
],
@@ -2998,6 +3006,7 @@
{ "one": ["#", " conflito"], "many": ["#", " conflitos"], "other": ["#", " conflitos"] }
]
],
+ "cUagXn": ["Adicionar a ", ["gitignorePath"]],
"cUk6TF": ["Falha na sincronização — veja os logs do servidor para os detalhes."],
"cUt8yN": ["As alterações são salvas automaticamente."],
"cV7LOw": ["Wiki da equipe"],
diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.po
index 50cf6975f..484889d04 100644
--- a/packages/app/src/locales/pt-BR/messages.po
+++ b/packages/app/src/locales/pt-BR/messages.po
@@ -60,6 +60,11 @@ msgstr "“{0}”"
msgid "\"{0}\" install refreshed ({1})"
msgstr "Instalação de \"{0}\" atualizada ({1})"
+#. placeholder {0}: prompt.name
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "\"{0}\" is ignored by git"
+msgstr "\"{0}\" é ignorado pelo git"
+
#. placeholder {0}: result.name
#: src/lib/skill-import-toast.ts
msgid "\"{0}\" was already added (identical content)."
@@ -1313,6 +1318,10 @@ msgstr "Adicione o comando <0>ok</0> ao seu terminal"
msgid "Add the next matching source selection."
msgstr "Adiciona a próxima correspondência da seleção de origem."
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Add to {gitignorePath}"
+msgstr "Adicionar a {gitignorePath}"
+
#: src/lib/native-menu-catalog.ts
msgid "Add to Dictionary"
msgstr "Adicionar ao dicionário"
@@ -2089,6 +2098,7 @@ msgstr "Não é possível compartilhar este caminho."
#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillScopeMoveDialog.tsx
+#: src/components/SkillTrackInGitDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -3488,6 +3498,10 @@ msgstr "Não deu para contatar o servidor do Open Knowledge para enviar {fileNam
msgid "Couldn't read {fileName}. It may have been moved, deleted, or not finished downloading. Try adding it again."
msgstr "Não deu para ler {fileName}. Ele pode ter sido movido, excluído ou não terminou de baixar. Tente adicioná-lo de novo."
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't read the {gitignorePath} rule: {previewError}"
+msgstr "Não foi possível ler a regra de {gitignorePath}: {previewError}"
+
#: src/comments/store.ts
msgid "Couldn't read the comments waiting to send — nothing was sent."
msgstr "Não deu para ler os comentários que aguardam envio — nada foi enviado."
@@ -3652,6 +3666,11 @@ msgstr "Não deu para mudar para Somente eu"
msgid "Couldn't unmark that comment — it's still waiting to send."
msgstr "Não deu para desmarcar esse comentário — ele continua aguardando envio."
+#. placeholder {0}: result.error
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't update {gitignorePath}: {0}"
+msgstr "Não foi possível atualizar {gitignorePath}: {0}"
+
#. placeholder {0}: r.error
#: src/components/SkillInstallMenu.tsx
msgid "Couldn't update {subRoot}: {0}"
@@ -13639,6 +13658,10 @@ msgstr "Assinatura confirmada!"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to {gitignorePath} makes it editable here."
+msgstr "Seus agentes continuam carregando esta habilidade, mas o OpenKnowledge não consegue abri-la nem editá-la: ele não indexa um arquivo que o git está configurado para ignorar, porque a sincronização falharia. Adicionar uma linha ao {gitignorePath} a torna editável aqui."
+
#: src/components/settings/SearchSection.tsx
msgid "Your change is still being saved — run the test again in a moment."
msgstr "Sua alteração ainda está sendo salva — rode o teste de novo em instantes."
diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.json
index c6ecf1a06..36306a51a 100644
--- a/packages/app/src/locales/ur/messages.json
+++ b/packages/app/src/locales/ur/messages.json
@@ -253,6 +253,7 @@
")"
],
"3LbBJn": ["تصاویر منسلک کریں"],
+ "3MA3Hh": [["gitignorePath"], " قاعدہ نہیں پڑھا جا سکا: ", ["previewError"]],
"3MnvrL": ["سرِ فہرست ", ["0"], " مماثلتیں دکھائی جا رہی ہیں — محدود کرنے کے لیے لکھتے رہیں"],
"3Mwaly": [["0"], " کا ابتدائیہ نہیں ہو سکا۔"],
"3SDfZl": [
@@ -1008,6 +1009,11 @@
["filePath"],
"</0> میں مقامی طور پر ترمیم کی، مگر اپ سٹریم یہ حذف ہو گئی۔"
],
+ "Ehb_JP": [
+ "آپ کے ایجنٹ اب بھی یہ مہارت لوڈ کرتے ہیں، لیکن OpenKnowledge اسے کھول یا ترمیم نہیں کر سکتا: یہ ایسی فائل کو انڈیکس نہیں کرتا جسے نظر انداز کرنے کے لیے git مقرر ہے، کیونکہ سنک ناکام ہو جائے گا۔ ",
+ ["gitignorePath"],
+ " میں ایک سطر شامل کرنے سے یہ یہاں قابلِ ترمیم ہو جاتی ہے۔"
+ ],
"Ehkru0": ["CodeMirror کی تکمیلی تجاویز کھولیں، ان میں گھومیں، قبول کریں یا برخاست کریں۔"],
"EiVgl5": ["آپ کو اس ریپو میں پُش کرنے کی اجازت نہیں۔"],
"Eiowpn": [
@@ -1050,6 +1056,7 @@
"F-vBv0": ["پوچھیں"],
"F0OA00": [["displayName"], " حاصل کریں"],
"F1T9y_": ["سرِ فہرست مماثلتیں دکھائی جا رہی ہیں — محدود کرنے کے لیے لکھتے رہیں"],
+ "F1yEaG": [["gitignorePath"], " اپ ڈیٹ نہیں ہو سکا: ", ["0"]],
"F4IYWe": ["دستاویز شیئر کریں"],
"F4_wQj": ["Google سے تلاش کریں"],
"F4vEsL": ["مطابقت پذیری کی حالت: ", ["syncStateLabel"]],
@@ -1263,6 +1270,7 @@
"OpenKnowledge اپنی کنفیگریشن اور داخلی فائلیں آپ کے پروجیکٹ کے جڑ فولڈر میں نئے بنے <0>.ok</0> ڈائریکٹری کے اندر رکھتا ہے۔"
],
"Hrz9NY": ["وکی لنک"],
+ "HwAKaw": ["\"", ["0"], "\" کو git نظر انداز کر رہا ہے"],
"HzVAoz": [
"اس فائل کو مہارت کے اندر منتقل کریں یا اس کا نام بدلیں — راستہ references/ یا scripts/ کے تحت ہی رہتا ہے۔"
],
@@ -2724,6 +2732,7 @@
"cT_pW4": ["سکڑنے والا مواد بلاک (Notion طرز کا ٹوگل)۔"],
"cU-seF": ["کرسر والے بلاک کے Markdown سورس پر جائیں، بیچ میں اور نمایاں۔"],
"cUK8lW": [["conflictCount", "plural", { "one": ["#", " تصادم"], "other": ["#", " تصادمات"] }]],
+ "cUagXn": [["gitignorePath"], " میں شامل کریں"],
"cUk6TF": ["مطابقت پذیری ناکام رہی — تفصیلات کے لیے سرور کے لاگز دیکھیں۔"],
"cUt8yN": ["تبدیلیاں خودکار طور پر محفوظ ہو جاتی ہیں۔"],
"cV7LOw": ["ٹیم وکی"],
diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.po
index d7a2722b4..0a9c8e4e7 100644
--- a/packages/app/src/locales/ur/messages.po
+++ b/packages/app/src/locales/ur/messages.po
@@ -60,6 +60,11 @@ msgstr "«{0}»"
msgid "\"{0}\" install refreshed ({1})"
msgstr "«{0}» کی تنصیب تازہ کر دی گئی ({1})"
+#. placeholder {0}: prompt.name
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "\"{0}\" is ignored by git"
+msgstr "\"{0}\" کو git نظر انداز کر رہا ہے"
+
#. placeholder {0}: result.name
#: src/lib/skill-import-toast.ts
msgid "\"{0}\" was already added (identical content)."
@@ -1317,6 +1322,10 @@ msgstr "اپنے ٹرمینل میں <0>ok</0> کمانڈ شامل کریں"
msgid "Add the next matching source selection."
msgstr "اگلا مماثل سورس انتخاب شامل کریں۔"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Add to {gitignorePath}"
+msgstr "{gitignorePath} میں شامل کریں"
+
#: src/lib/native-menu-catalog.ts
msgid "Add to Dictionary"
msgstr "لغت میں شامل کریں"
@@ -2093,6 +2102,7 @@ msgstr "یہ راستہ شیئر نہیں کیا جا سکتا۔"
#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillScopeMoveDialog.tsx
+#: src/components/SkillTrackInGitDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -3492,6 +3502,10 @@ msgstr "{fileName} اپ لوڈ کرنے کے لیے Open Knowledge سرور تک
msgid "Couldn't read {fileName}. It may have been moved, deleted, or not finished downloading. Try adding it again."
msgstr "{fileName} پڑھی نہیں جا سکی۔ ہو سکتا ہے یہ منتقل ہو گئی ہو، حذف ہو گئی ہو، یا مکمل ڈاؤن لوڈ نہ ہوئی ہو۔ اسے دوبارہ شامل کرنے کی کوشش کریں۔"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't read the {gitignorePath} rule: {previewError}"
+msgstr "{gitignorePath} قاعدہ نہیں پڑھا جا سکا: {previewError}"
+
#: src/comments/store.ts
msgid "Couldn't read the comments waiting to send — nothing was sent."
msgstr "بھیجنے کے منتظر تبصرے پڑھے نہیں جا سکے — کچھ نہیں بھیجا گیا۔"
@@ -3656,6 +3670,11 @@ msgstr "«صرف میں» پر تبدیل نہیں ہو سکا"
msgid "Couldn't unmark that comment — it's still waiting to send."
msgstr "اس تبصرے کا نشان نہیں ہٹایا جا سکا — یہ اب بھی بھیجنے کا منتظر ہے۔"
+#. placeholder {0}: result.error
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't update {gitignorePath}: {0}"
+msgstr "{gitignorePath} اپ ڈیٹ نہیں ہو سکا: {0}"
+
#. placeholder {0}: r.error
#: src/components/SkillInstallMenu.tsx
msgid "Couldn't update {subRoot}: {0}"
@@ -13643,6 +13662,10 @@ msgstr "آپ رکن بن گئے!"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to {gitignorePath} makes it editable here."
+msgstr "آپ کے ایجنٹ اب بھی یہ مہارت لوڈ کرتے ہیں، لیکن OpenKnowledge اسے کھول یا ترمیم نہیں کر سکتا: یہ ایسی فائل کو انڈیکس نہیں کرتا جسے نظر انداز کرنے کے لیے git مقرر ہے، کیونکہ سنک ناکام ہو جائے گا۔ {gitignorePath} میں ایک سطر شامل کرنے سے یہ یہاں قابلِ ترمیم ہو جاتی ہے۔"
+
#: src/components/settings/SearchSection.tsx
msgid "Your change is still being saved — run the test again in a moment."
msgstr "آپ کی تبدیلی ابھی محفوظ ہو رہی ہے — تھوڑی دیر بعد ٹیسٹ دوبارہ چلائیں۔"
diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.json
index 70834d042..e08053199 100644
--- a/packages/app/src/locales/zh-Hans/messages.json
+++ b/packages/app/src/locales/zh-Hans/messages.json
@@ -228,6 +228,7 @@
")"
],
"3LbBJn": ["附加图片"],
+ "3MA3Hh": ["无法读取 ", ["gitignorePath"], " 规则:", ["previewError"]],
"3MnvrL": ["正在显示最相关的 ", ["0"], " 条匹配——继续输入可缩小范围"],
"3Mwaly": ["无法初始化 ", ["0"], "。"],
"3SDfZl": [
@@ -895,6 +896,11 @@
"Ef6ukL": ["通过上级目录"],
"Ef7StM": ["未知"],
"EhDLBx": ["你在本地修改了 <0>", ["filePath"], "</0>,但它在上游被删除了。"],
+ "Ehb_JP": [
+ "你的智能体仍会加载该技能,但 OpenKnowledge 无法打开或编辑它:它不会索引 git 设置为忽略的文件,因为同步会失败。在 ",
+ ["gitignorePath"],
+ " 中添加一行即可在这里编辑它。"
+ ],
"Ehkru0": ["打开、浏览、接受或关闭 CodeMirror 的补全建议。"],
"EiVgl5": ["你没有推送到这个仓库的权限。"],
"Eiowpn": ["你的评论正在当前回合之后等待——它们会排队,直到智能体取用该消息。"],
@@ -931,6 +937,7 @@
"F-vBv0": ["询问"],
"F0OA00": ["获取 ", ["displayName"]],
"F1T9y_": ["正在显示最相关的匹配——继续输入可缩小范围"],
+ "F1yEaG": ["无法更新 ", ["gitignorePath"], ":", ["0"]],
"F4IYWe": ["共享文档"],
"F4_wQj": ["使用 Google 搜索"],
"F4vEsL": ["同步状态:", ["syncStateLabel"]],
@@ -1101,6 +1108,7 @@
"HqOPpj": ["Git 需要一个辅助工具(例如 git-lfs),但它未安装或找不到。请先安装再重试。"],
"HqiZvw": ["OpenKnowledge 会把配置和内部文件保存在你项目根目录中新建的 <0>.ok</0> 目录里。"],
"Hrz9NY": ["维基链接"],
+ "HwAKaw": ["git 已忽略“", ["0"], "”"],
"HzVAoz": ["在技能内部移动或重命名这个文件——路径仍保持在 references/ 或 scripts/ 下。"],
"HzVv6g": ["粘贴"],
"I1gRhX": ["重命名失败"],
@@ -2374,6 +2382,7 @@
"cT_pW4": ["可折叠内容块(Notion 风格折叠)。"],
"cU-seF": ["跳到光标所在块的 markdown 源码,居中并高亮显示。"],
"cUK8lW": [["conflictCount", "plural", { "other": ["#", " 处冲突"] }]],
+ "cUagXn": ["添加到 ", ["gitignorePath"]],
"cUk6TF": ["同步失败——详情请查看服务器日志。"],
"cUt8yN": ["更改会自动保存。"],
"cV7LOw": ["团队维基"],
diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.po
index 2ac840169..c95d44704 100644
--- a/packages/app/src/locales/zh-Hans/messages.po
+++ b/packages/app/src/locales/zh-Hans/messages.po
@@ -60,6 +60,11 @@ msgstr "“{0}”"
msgid "\"{0}\" install refreshed ({1})"
msgstr "已刷新“{0}”的安装({1})"
+#. placeholder {0}: prompt.name
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "\"{0}\" is ignored by git"
+msgstr "git 已忽略“{0}”"
+
#. placeholder {0}: result.name
#: src/lib/skill-import-toast.ts
msgid "\"{0}\" was already added (identical content)."
@@ -1317,6 +1322,10 @@ msgstr "把 <0>ok</0> 命令添加到你的终端"
msgid "Add the next matching source selection."
msgstr "添加下一处与所选来源匹配的内容。"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Add to {gitignorePath}"
+msgstr "添加到 {gitignorePath}"
+
#: src/lib/native-menu-catalog.ts
msgid "Add to Dictionary"
msgstr "添加到词典"
@@ -2093,6 +2102,7 @@ msgstr "无法共享此路径。"
#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillScopeMoveDialog.tsx
+#: src/components/SkillTrackInGitDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -3492,6 +3502,10 @@ msgstr "无法连接到 Open Knowledge 服务器以上传 {fileName}。"
msgid "Couldn't read {fileName}. It may have been moved, deleted, or not finished downloading. Try adding it again."
msgstr "无法读取 {fileName}。它可能已被移动、删除,或尚未下载完成。请尝试重新添加。"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't read the {gitignorePath} rule: {previewError}"
+msgstr "无法读取 {gitignorePath} 规则:{previewError}"
+
#: src/comments/store.ts
msgid "Couldn't read the comments waiting to send — nothing was sent."
msgstr "无法读取等待发送的评论——什么都没有发送。"
@@ -3656,6 +3670,11 @@ msgstr "无法切换到「仅自己」"
msgid "Couldn't unmark that comment — it's still waiting to send."
msgstr "无法取消标记那条评论——它仍在等待发送。"
+#. placeholder {0}: result.error
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't update {gitignorePath}: {0}"
+msgstr "无法更新 {gitignorePath}:{0}"
+
#. placeholder {0}: r.error
#: src/components/SkillInstallMenu.tsx
msgid "Couldn't update {subRoot}: {0}"
@@ -13643,6 +13662,10 @@ msgstr "订阅成功!"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to {gitignorePath} makes it editable here."
+msgstr "你的智能体仍会加载该技能,但 OpenKnowledge 无法打开或编辑它:它不会索引 git 设置为忽略的文件,因为同步会失败。在 {gitignorePath} 中添加一行即可在这里编辑它。"
+
#: src/components/settings/SearchSection.tsx
msgid "Your change is still being saved — run the test again in a moment."
msgstr "你的更改还在保存中——请稍后再运行一次测试。"
diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.json
index 5456b7d95..b1e8436d4 100644
--- a/packages/app/src/locales/zh-Hant/messages.json
+++ b/packages/app/src/locales/zh-Hant/messages.json
@@ -230,6 +230,7 @@
")"
],
"3LbBJn": ["附加圖片"],
+ "3MA3Hh": ["無法讀取 ", ["gitignorePath"], " 規則:", ["previewError"]],
"3MnvrL": ["正在顯示最相關的 ", ["0"], " 個相符項——繼續輸入可以縮小範圍"],
"3Mwaly": ["無法初始化 ", ["0"], "。"],
"3SDfZl": [
@@ -901,6 +902,11 @@
"Ef6ukL": ["透過上層目錄"],
"Ef7StM": ["未知"],
"EhDLBx": ["你在本機修改了 <0>", ["filePath"], "</0>,但它在上游被刪除了。"],
+ "Ehb_JP": [
+ "你的智慧代理仍會載入該技能,但 OpenKnowledge 無法開啟或編輯它:它不會索引 git 設定為忽略的檔案,因為同步會失敗。在 ",
+ ["gitignorePath"],
+ " 中新增一行即可在這裡編輯它。"
+ ],
"Ehkru0": ["開啟、瀏覽、接受或關閉 CodeMirror 的自動完成建議。"],
"EiVgl5": ["你沒有推送到這個儲存庫的權限。"],
"Eiowpn": ["你的評論正在目前回合之後等待——它們會排隊,直到智慧體取用該訊息。"],
@@ -937,6 +943,7 @@
"F-vBv0": ["詢問"],
"F0OA00": ["取得 ", ["displayName"]],
"F1T9y_": ["正在顯示最相關的相符項——繼續輸入可以縮小範圍"],
+ "F1yEaG": ["無法更新 ", ["gitignorePath"], ":", ["0"]],
"F4IYWe": ["分享文件"],
"F4_wQj": ["使用 Google 搜尋"],
"F4vEsL": ["同步狀態:", ["syncStateLabel"]],
@@ -1109,6 +1116,7 @@
"HqOPpj": ["Git 需要一個輔助工具(例如 git-lfs),但它沒有安裝或找不到。請先安裝再試一次。"],
"HqiZvw": ["OpenKnowledge 會把設定和內部檔案放在你專案根資料夾中新建的 <0>.ok</0> 目錄裡。"],
"Hrz9NY": ["維基連結"],
+ "HwAKaw": ["git 已忽略「", ["0"], "」"],
"HzVAoz": ["在技能內部移動或重新命名這個檔案——路徑仍會留在 references/ 或 scripts/ 底下。"],
"HzVv6g": ["貼上"],
"I1gRhX": ["重新命名失敗"],
@@ -2394,6 +2402,7 @@
"cT_pW4": ["可摺疊內容區塊(Notion 風格摺疊)。"],
"cU-seF": ["跳到游標所在區塊的 markdown 原始碼,置中並醒目提示。"],
"cUK8lW": [["conflictCount", "plural", { "other": ["#", " 處衝突"] }]],
+ "cUagXn": ["新增至 ", ["gitignorePath"]],
"cUk6TF": ["同步失敗——詳情請看伺服器記錄。"],
"cUt8yN": ["變更會自動儲存。"],
"cV7LOw": ["團隊維基"],
diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.po
index 93dd6f373..83b055bf0 100644
--- a/packages/app/src/locales/zh-Hant/messages.po
+++ b/packages/app/src/locales/zh-Hant/messages.po
@@ -60,6 +60,11 @@ msgstr "「{0}」"
msgid "\"{0}\" install refreshed ({1})"
msgstr "已重新整理「{0}」的安裝({1})"
+#. placeholder {0}: prompt.name
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "\"{0}\" is ignored by git"
+msgstr "git 已忽略「{0}」"
+
#. placeholder {0}: result.name
#: src/lib/skill-import-toast.ts
msgid "\"{0}\" was already added (identical content)."
@@ -1317,6 +1322,10 @@ msgstr "把 <0>ok</0> 指令加到你的終端機"
msgid "Add the next matching source selection."
msgstr "加入下一處與所選來源相符的內容。"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Add to {gitignorePath}"
+msgstr "新增至 {gitignorePath}"
+
#: src/lib/native-menu-catalog.ts
msgid "Add to Dictionary"
msgstr "加入詞典"
@@ -2093,6 +2102,7 @@ msgstr "無法分享這個路徑。"
#: src/components/SkillPluginBundleDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillScopeMoveDialog.tsx
+#: src/components/SkillTrackInGitDialog.tsx
#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
@@ -3492,6 +3502,10 @@ msgstr "無法連上 Open Knowledge 伺服器來上傳 {fileName}。"
msgid "Couldn't read {fileName}. It may have been moved, deleted, or not finished downloading. Try adding it again."
msgstr "無法讀取 {fileName}。它可能已被移動、刪除,或還沒下載完。請試著重新加入。"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't read the {gitignorePath} rule: {previewError}"
+msgstr "無法讀取 {gitignorePath} 規則:{previewError}"
+
#: src/comments/store.ts
msgid "Couldn't read the comments waiting to send — nothing was sent."
msgstr "無法讀取等著傳送的註解——什麼都沒有送出。"
@@ -3656,6 +3670,11 @@ msgstr "無法切換到「僅自己」"
msgid "Couldn't unmark that comment — it's still waiting to send."
msgstr "無法取消標記那則註解——它仍在等著傳送。"
+#. placeholder {0}: result.error
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Couldn't update {gitignorePath}: {0}"
+msgstr "無法更新 {gitignorePath}:{0}"
+
#. placeholder {0}: r.error
#: src/components/SkillInstallMenu.tsx
msgid "Couldn't update {subRoot}: {0}"
@@ -13643,6 +13662,10 @@ msgstr "訂閱成功!"
+#: src/components/SkillTrackInGitDialog.tsx
+msgid "Your agents still load this skill, but OpenKnowledge can't open or edit it: it won't index a file that git is set to ignore, because syncing it would fail. Adding one line to {gitignorePath} makes it editable here."
+msgstr "你的智慧代理仍會載入該技能,但 OpenKnowledge 無法開啟或編輯它:它不會索引 git 設定為忽略的檔案,因為同步會失敗。在 {gitignorePath} 中新增一行即可在這裡編輯它。"
+
#: src/components/settings/SearchSection.tsx
msgid "Your change is still being saved — run the test again in a moment."
msgstr "你的變更還在儲存中——請等一下再執行一次測試。"
diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
index ad0abed2f..d499f488e 100644
--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts
+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
@@ -290,6 +290,11 @@ const EXEMPT_HANDLERS = new Set([
// `extractActorIdentity` to attribute the revert as a new version, same posture
// as restore.
'handleSkillRevert',
+ // `/api/skill/track-in-git` (appends a `.gitignore` negation so a gitignored
+ // bundle becomes trackable). It rewrites a config file fs-direct and never
+ // authors doc content, so there is no contributor to record — same posture as
+ // the other project-config skill handlers.
+ 'handleSkillTrackInGit',
'handleSuggestLinks',
'handlePageHeadings',
'handleHistory',
diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.ts
index ff45c920a..903e2dc2c 100644
--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts
+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts
@@ -264,6 +264,11 @@ const EXEMPT_HANDLERS = new Set([
'handleSkillRestore',
'handleSkillRevert',
'handleSkillsManagement',
+ // POST /api/skill/track-in-git — appends a negation to the project's
+ // `.gitignore` so a gitignored bundle becomes trackable. It targets a config
+ // file, never a Y.Doc body, so the per-doc conflict gate does not apply —
+ // same posture as `handleFolderConfig`.
+ 'handleSkillTrackInGit',
// Skill discovery + import (skills marketplace). Search/detail/installed are
// read-only proxies; import/reimport/upload materialize an upstream (or
// uploaded) skill to disk fs-direct (like seed/clone) rather than mutating a
diff --git a/packages/core/src/constants/skills.ts b/packages/core/src/constants/skills.ts
index 466179d08..b23fdee97 100644
--- a/packages/core/src/constants/skills.ts
+++ b/packages/core/src/constants/skills.ts
@@ -1,3 +1,12 @@
+/**
+ * The vendor-neutral `.agents/skills` hub, cwd-relative (home-relative at global
+ * scope). A first-class in-place skill host with no `EditorId` of its own — it is
+ * addressed by the `agents` host id, so it is absent from `EDITOR_PROJECT_SKILL_ROOT`
+ * and every consumer had spelled it as a bare literal instead. Server, core and app
+ * all resolve the same hub, so a change to it has to reach every site at once.
+ */
+export const AGENTS_SKILLS_ROOT = '.agents/skills';
+
/**
* LEGACY prefix the starter-pack skills carried before the marketplace rename
* (`open-knowledge-pack-<packId>[-<member>]`). It no longer names anything the
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index d44a02bf0..8bd1328e0 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -392,6 +392,7 @@ export {
export { PRODUCT_NAME } from './constants/product.ts';
export { DEFAULT_SERVER_HOST } from './constants/server.ts';
export {
+ AGENTS_SKILLS_ROOT,
extractSkillRefs,
isOpenKnowledgeSkillsSource,
isSkillRefCandidate,
@@ -1261,6 +1262,10 @@ export {
SkillTargetsPutRequestSchema,
type SkillTargetsPutSuccess,
SkillTargetsPutSuccessSchema,
+ type SkillTrackInGitRequest,
+ SkillTrackInGitRequestSchema,
+ type SkillTrackInGitSuccess,
+ SkillTrackInGitSuccessSchema,
type SkillUninstallRequest,
SkillUninstallRequestSchema,
type SkillUninstallSuccess,
diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.ts
index 63521c67c..0dd87db1a 100644
--- a/packages/core/src/schemas/api/tags-search.ts
+++ b/packages/core/src/schemas/api/tags-search.ts
@@ -482,6 +482,18 @@ export const SkillsListEntrySchema = z
description: z.string().optional(),
scope: SkillScopeSchema,
path: z.string().min(1),
+ /**
+ * Set ONLY when `path` sits under a directory-symlink alias: the same
+ * SKILL.md addressed through the canonical dir it links to (a repo that
+ * keeps its skills in `plugins/<x>/skills/` and links them into
+ * `.agents/skills/`). The document index holds ONE page per inode, under
+ * the canonical name — so `path` itself is not a page, and a tab opened
+ * there is pruned the moment the page list syncs (the skill flickers open
+ * and vanishes). Opening the alias name anyway would be worse: a second
+ * Y.Doc fighting the canonical over one file on disk. Doc-name builders
+ * prefer this when present; `path` still reports where the bundle lives.
+ */
+ canonicalPath: z.string().min(1).optional(),
/** Absolute on-disk path to the skill's SKILL.md — drives the desktop
* Reveal-in-Finder / Open-in-Terminal / Copy-Path row actions. Always set on
* `/api/skills` list entries; omitted on partial entries built client-side
@@ -539,10 +551,52 @@ export const SkillsListEntrySchema = z
// fails: a `modified` skill in a non-git project has a `localHash` (Modified
// shows) but no `baselineRef` (nothing to revert to), so Revert stays hidden.
revertable: z.boolean().optional(),
+ // The bundle sits on a GITIGNORED path, so it is listed but NOT admitted as
+ // content: OK will not index a doc the sync engine could never commit. The
+ // skill is real and agents load it; OK just cannot open or edit it.
+ //
+ // Without this the list and the document index disagreed in silence — the
+ // row was there, the click produced a tab with no doc behind it, and nothing
+ // anywhere said why. Every surface that offers to OPEN a skill reads this
+ // first and offers `POST /api/skill/track-in-git` instead.
+ ignored: z.boolean().optional(),
})
.strict() satisfies StandardSchemaV1;
export type SkillsListEntry = z.infer<typeof SkillsListEntrySchema>;
+/**
+ * Make a gitignored skill bundle trackable, so OK can index (and therefore
+ * open) it. `apply: false` previews the exact `.gitignore` line without writing
+ * — every caller shows the user that line before it touches their repo.
+ *
+ * Project scope only: a global skill lives under `$HOME`, outside any repo.
+ */
+export const SkillTrackInGitRequestSchema = z
+ .object({
+ name: z.string().min(1),
+ scope: SkillScopeSchema,
+ // Write the rule. Omitted/false returns the proposed line only.
+ apply: z.boolean().optional(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillTrackInGitRequest = z.infer<typeof SkillTrackInGitRequestSchema>;
+
+export const SkillTrackInGitSuccessSchema = z
+ .object({
+ // The exact line, e.g. `!/.claude/skills/`. Re-includes the whole skills
+ // DIRECTORY, never one bundle: git cannot re-include a file whose parent
+ // directory is excluded, so a per-skill negation silently does nothing.
+ line: z.string().min(1),
+ // Project-relative path of the file the line goes in.
+ gitignorePath: z.string().min(1),
+ // Did this call write? False for a preview, and for a rule already present.
+ applied: z.boolean(),
+ // The bundle was already trackable — nothing to do.
+ alreadyTracked: z.boolean().optional(),
+ })
+ .strict() satisfies StandardSchemaV1;
+export type SkillTrackInGitSuccess = z.infer<typeof SkillTrackInGitSuccessSchema>;
+
/** Success body for `GET /api/skills`. Flat enumeration across in-scope stores. */
export const SkillsListSuccessSchema = z
.object({
diff --git a/packages/server/src/api-extension.test.ts b/packages/server/src/api-extension.test.ts
index ac9543159..0240b7ad8 100644
--- a/packages/server/src/api-extension.test.ts
+++ b/packages/server/src/api-extension.test.ts
@@ -1,10 +1,13 @@
-import { existsSync, mkdirSync, symlinkSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
+ healUnservableSkillAdmission,
+ indexedSkillContentPath,
resumeSyncOnAuthEvent,
+ type SkillAdmissionHealState,
safeSubdir,
sanitizeFilename,
} from './api-extension.test-helper.ts';
@@ -726,3 +729,161 @@ describe('resumeSyncOnAuthEvent (reconnect → resume wiring)', () => {
await Promise.resolve();
});
});
+
+describe('indexedSkillContentPath', () => {
+ let contentDir: string;
+
+ beforeEach(() => {
+ contentDir = mkdtempSync(join(tmpdir(), 'ok-skill-canonical-'));
+ });
+ afterEach(() => {
+ rmSync(contentDir, { recursive: true, force: true });
+ });
+
+ function bundle(rel: string): string {
+ const dir = join(contentDir, rel);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), '---\nname: x\ndescription: d\n---\n');
+ return join(dir, 'SKILL.md');
+ }
+
+ test('resolves a skill mounted through a directory symlink to its indexed doc', () => {
+ bundle('plugins/ok/skills/demo');
+ mkdirSync(join(contentDir, '.agents/skills'), { recursive: true });
+ symlinkSync(
+ join(contentDir, 'plugins/ok/skills/demo'),
+ join(contentDir, '.agents/skills/demo'),
+ );
+
+ expect(
+ indexedSkillContentPath(join(contentDir, '.agents/skills/demo/SKILL.md'), contentDir),
+ ).toBe('plugins/ok/skills/demo/SKILL.md');
+ });
+
+ test('resolves a symlinked SKILL.md file, not just a symlinked dir', () => {
+ bundle('plugins/ok/skills/demo');
+ mkdirSync(join(contentDir, '.agents/skills/demo'), { recursive: true });
+ symlinkSync(
+ join(contentDir, 'plugins/ok/skills/demo/SKILL.md'),
+ join(contentDir, '.agents/skills/demo/SKILL.md'),
+ );
+
+ expect(
+ indexedSkillContentPath(join(contentDir, '.agents/skills/demo/SKILL.md'), contentDir),
+ ).toBe('plugins/ok/skills/demo/SKILL.md');
+ });
+
+ test('an unlinked bundle indexes at its own path (caller emits no redirect)', () => {
+ const real = bundle('.agents/skills/plain');
+ expect(indexedSkillContentPath(real, contentDir)).toBe('.agents/skills/plain/SKILL.md');
+ });
+
+ test('null when the link escapes contentDir — no canonical content doc exists', () => {
+ const outside = mkdtempSync(join(tmpdir(), 'ok-skill-outside-'));
+ try {
+ mkdirSync(join(outside, 'demo'), { recursive: true });
+ writeFileSync(join(outside, 'demo/SKILL.md'), '---\nname: x\ndescription: d\n---\n');
+ mkdirSync(join(contentDir, '.agents/skills'), { recursive: true });
+ symlinkSync(join(outside, 'demo'), join(contentDir, '.agents/skills/demo'));
+
+ expect(
+ indexedSkillContentPath(join(contentDir, '.agents/skills/demo/SKILL.md'), contentDir),
+ ).toBeNull();
+ } finally {
+ rmSync(outside, { recursive: true, force: true });
+ }
+ });
+
+ test('null for a dangling link rather than throwing', () => {
+ mkdirSync(join(contentDir, '.agents/skills'), { recursive: true });
+ symlinkSync(join(contentDir, 'gone'), join(contentDir, '.agents/skills/demo'));
+ expect(
+ indexedSkillContentPath(join(contentDir, '.agents/skills/demo/SKILL.md'), contentDir),
+ ).toBeNull();
+ });
+});
+
+describe('healUnservableSkillAdmission', () => {
+ function makeFilter(excluded: Set<string>) {
+ const rebuilds: number[] = [];
+ return {
+ rebuilds,
+ filter: {
+ isExcluded: (p: string) => excluded.has(p),
+ rebuildIgnorePatterns: async () => {
+ rebuilds.push(1);
+ // A real rebuild re-scans and admits the dir; model that.
+ excluded.clear();
+ },
+ },
+ };
+ }
+
+ test('rebuilds when a listed skill dir is not servable', async () => {
+ const { filter, rebuilds } = makeFilter(new Set(['.claude/skills/new/SKILL.md']));
+ const state: SkillAdmissionHealState = { lastKey: null };
+ await expect(
+ healUnservableSkillAdmission(['.claude/skills/new/SKILL.md'], filter, state),
+ ).resolves.toBe(true);
+ expect(rebuilds.length).toBe(1);
+ });
+
+ test('does not rebuild when every listed skill is already servable', async () => {
+ const { filter, rebuilds } = makeFilter(new Set());
+ const state: SkillAdmissionHealState = { lastKey: null };
+ await expect(
+ healUnservableSkillAdmission(['.claude/skills/ok/SKILL.md'], filter, state),
+ ).resolves.toBe(false);
+ expect(rebuilds.length).toBe(0);
+ });
+
+ test('rebuilds at most once per skill-dir set, then again when the set changes', async () => {
+ // A permanently-excluded bundle (gitignored) must not re-walk the tree on
+ // every sidebar refresh — that is a list call per `files` signal.
+ const excluded = new Set(['.claude/skills/ignored/SKILL.md']);
+ const rebuilds: number[] = [];
+ const filter = {
+ isExcluded: (p: string) => excluded.has(p),
+ rebuildIgnorePatterns: async () => {
+ rebuilds.push(1);
+ },
+ };
+ const state: SkillAdmissionHealState = { lastKey: null };
+ const paths = ['.claude/skills/ignored/SKILL.md'];
+ await healUnservableSkillAdmission(paths, filter, state);
+ await healUnservableSkillAdmission(paths, filter, state);
+ await healUnservableSkillAdmission([...paths], filter, state);
+ expect(rebuilds.length).toBe(1);
+
+ excluded.add('.claude/skills/fresh/SKILL.md');
+ await healUnservableSkillAdmission([...paths, '.claude/skills/fresh/SKILL.md'], filter, state);
+ expect(rebuilds.length).toBe(2);
+ });
+
+ test('ordering of the listed paths does not count as a changed set', async () => {
+ const excluded = new Set(['b/SKILL.md']);
+ const rebuilds: number[] = [];
+ const filter = {
+ isExcluded: (p: string) => excluded.has(p),
+ rebuildIgnorePatterns: async () => {
+ rebuilds.push(1);
+ },
+ };
+ const state: SkillAdmissionHealState = { lastKey: null };
+ await healUnservableSkillAdmission(['a/SKILL.md', 'b/SKILL.md'], filter, state);
+ await healUnservableSkillAdmission(['b/SKILL.md', 'a/SKILL.md'], filter, state);
+ expect(rebuilds.length).toBe(1);
+ });
+
+ test('a failing rebuild is swallowed, and no filter at all is a no-op', async () => {
+ const state: SkillAdmissionHealState = { lastKey: null };
+ const filter = {
+ isExcluded: () => true,
+ rebuildIgnorePatterns: () => Promise.reject(new Error('boom')),
+ };
+ await expect(healUnservableSkillAdmission(['x/SKILL.md'], filter, state)).resolves.toBe(false);
+ await expect(
+ healUnservableSkillAdmission(['x/SKILL.md'], null, { lastKey: null }),
+ ).resolves.toBe(false);
+ });
+});
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 902830b01..a221d93dc 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -19,6 +19,7 @@ import {
readdirSync,
readFileSync,
realpathSync,
+ rmSync,
statSync,
unlinkSync,
writeFileSync,
@@ -33,6 +34,7 @@ import type { Document, Extension, Hocuspocus } from '@hocuspocus/server';
import {
type AdvisoryWarning,
AGENT_ICON_COLORS,
+ AGENTS_SKILLS_ROOT,
AgentActivitySuccessSchema,
AgentBurstDiffSuccessSchema,
AgentPatchRequestSchema,
@@ -220,6 +222,8 @@ import {
SkillTargetsGetSuccessSchema,
SkillTargetsPutRequestSchema,
SkillTargetsPutSuccessSchema,
+ SkillTrackInGitRequestSchema,
+ SkillTrackInGitSuccessSchema,
SkillUninstallRequestSchema,
SkillUninstallSuccessSchema,
SYSTEM_DOC_NAME,
@@ -611,6 +615,7 @@ import { successResponse } from './http/success-response.ts';
import {
aliasedSourceRoots,
knownSkillRootsFor,
+ removableSkillOccurrenceDirs,
resolveDefaultSkillHomeRel,
resolveGlobalNativeSkillDir,
scanGlobalInPlaceSkills,
@@ -712,6 +717,7 @@ import {
import { rejectDisallowedGitSpec } from './skill-git-spec-guard.ts';
import { resolveSkillInstallReportSettings } from './skill-install-report-config.ts';
import {
+ clearSkillPlacements,
readFolderExpectations,
readSkillInstallModeRaw,
readSkillPlacements,
@@ -1184,6 +1190,88 @@ export function safeSubdir(baseDir: string, subdir: string): string {
return resolved;
}
+/**
+ * The contentDir-relative path a skill's SKILL.md is INDEXED under, which is
+ * NOT always where the bundle is mounted. Null when there is no such path
+ * (unreadable, or the link escapes contentDir); callers compare against the
+ * mounted path to decide whether the difference is worth reporting.
+ *
+ * A repo may keep its bundles in `plugins/<x>/skills/` and symlink them into
+ * the editor dir agents read from. Both names reach the same inode, and the
+ * document index holds one doc per inode under the resolved one, so the mounted
+ * name is not openable: a tab there has no page behind it and the next
+ * page-list sync prunes it.
+ *
+ * Resolved with `realpath` rather than the watcher's folder-alias index, which
+ * is populated asynchronously after boot — the list must not answer differently
+ * depending on how warm the watcher is, since clicking a skill right after
+ * launch is exactly when it is cold. A target OUTSIDE contentDir has no
+ * canonical content doc to point at, so it stays null.
+ */
+export function indexedSkillContentPath(absolutePath: string, contentDir: string): string | null {
+ let real: string;
+ let realContentDir: string;
+ try {
+ real = realpathSync(absolutePath);
+ // Resolve the root too, or a project under a symlinked ancestor (on macOS
+ // every `/var` path is one) reads as "outside contentDir" and the whole
+ // redirect silently turns itself off.
+ realContentDir = realpathSync(contentDir);
+ } catch {
+ // Unreadable / dangling — the mounted path is all we can honestly report.
+ return null;
+ }
+ if (!isWithinDir(real, realContentDir)) return null;
+ return relative(realContentDir, real).split(sep).join('/');
+}
+
+/** State for {@link healUnservableSkillAdmission} — one per API extension. */
+export interface SkillAdmissionHealState {
+ lastKey: string | null;
+}
+
+/**
+ * An in-place skill dir is only servable once the content filter's allow-list
+ * knows about it, and that list refreshes on rebuild — at boot, and in each
+ * skill-writing handler. Anything else that puts a bundle on disk (an older
+ * build that predates those rebuilds, an agent writing the files directly, a
+ * branch switch) leaves a skill that LISTS but cannot be opened: there is no
+ * page for it, so the editor falls back to a Files tab. Until now the only
+ * cure was restarting the server.
+ *
+ * So heal on READ. The Skills sidebar refetches the list on open and on every
+ * `files` signal, which makes this the one place that sees every such dir no
+ * matter who wrote it — no new per-writer obligation, and a tenth handler
+ * shipping without a rebuild degrades to one late refresh instead of a skill
+ * nobody can open.
+ *
+ * Rebuilds at most once per distinct skill-dir set: a bundle excluded for a
+ * legitimate reason (gitignored, so the user has said that path stays out of
+ * git) must not re-walk the tree on every sidebar refresh.
+ */
+export async function healUnservableSkillAdmission(
+ paths: readonly string[],
+ filter: {
+ isExcluded: (relativePath: string) => boolean;
+ rebuildIgnorePatterns: () => Promise<unknown>;
+ } | null,
+ state: SkillAdmissionHealState,
+): Promise<boolean> {
+ if (!filter) return false;
+ const key = [...paths].sort().join('');
+ if (key === state.lastKey) return false;
+ state.lastKey = key;
+ if (!paths.some((p) => filter.isExcluded(p))) return false;
+ try {
+ await filter.rebuildIgnorePatterns();
+ return true;
+ } catch {
+ // Fail-soft, matching every other rebuild call site: a stale allow-list
+ // costs this skill its page until the next refresh, not the response.
+ return false;
+ }
+}
+
/**
* Synthesize an `assetExt` string for files surfaced by Show All Files mode
* that fall outside the markdown / standard-asset extension set. Schema
@@ -13728,7 +13816,11 @@ export function createApiExtension(
// live at `<home>/.ok/skills/`; the user-level install marker is
// `<home>/.ok/local/installed-skills.json` (readInstalledSkills(skillsHome)).
const skillsHome = homeDirOverride ?? homedir();
- const skillInstallOps = createSkillInstallOpsService({ contentDir, skillsHome });
+ const skillInstallOps = createSkillInstallOpsService({
+ contentDir,
+ skillsHome,
+ effectiveInstallMode,
+ });
/**
* Resolve a skill scope to its absolute `.ok/skills` store root. Project
@@ -14019,7 +14111,7 @@ export function createApiExtension(
id: editorId as string,
root: EDITOR_PROJECT_SKILL_ROOT[editorId] ?? '',
})),
- { id: 'agents', root: '.agents/skills' },
+ { id: 'agents', root: AGENTS_SKILLS_ROOT },
];
for (const { id, root } of roots) {
if (!root) continue;
@@ -14204,8 +14296,33 @@ export function createApiExtension(
base: string,
name: string,
scope: 'project' | 'global',
+ /**
+ * `purge`: leave NOTHING at this scope. A cross-scope move has already put
+ * the bytes at the destination, so the hub-consolidation an uninstall
+ * performs below is wrong here — it kept a copy in `.agents/skills`, which
+ * the next scan re-detected as a second skill of the same name at the scope
+ * the user just moved away from.
+ */
+ opts: { purge?: { contentHash: string } } = {},
): Promise<boolean> {
const installed = await removeSkillInstall(base, name);
+ const scanBaseForPurge = scope === 'project' ? contentDir : skillsHome;
+ if (opts.purge !== undefined) {
+ reverseProjectSkill(name, base, PROJECT_SKILL_EDITOR_IDS, skillProjectionRoots(scope));
+ // Content-guarded: only THIS skill's occurrences go. Two same-named
+ // bundles with different bytes are two distinct skills by design
+ // (`conflictHosts`), and deleting the other one because this one moved
+ // away destroys a bundle its owner never touched.
+ for (const dir of removableSkillOccurrenceDirs(
+ scanBaseForPurge,
+ scope,
+ name,
+ opts.purge.contentHash,
+ )) {
+ tracedRmSync(dir, { recursive: true, force: true });
+ }
+ return installed !== null;
+ }
if (!existsSync(resolve(resolveSkillsRoot(scope), name, 'SKILL.md'))) {
const entry = (
scope === 'project' ? scanInPlaceSkills(contentDir) : scanGlobalInPlaceSkills(skillsHome)
@@ -14328,6 +14445,137 @@ export function createApiExtension(
return { skills, truncated };
}
+ /**
+ * The `.gitignore` line that re-includes a skill bundle's SKILLS ROOT.
+ *
+ * Whole directory, never the one bundle: git cannot re-include a file whose
+ * parent directory is excluded, and the common rule (`.claude/*`) excludes
+ * `.claude/skills` itself — so `!/.claude/skills/<name>/` silently does
+ * nothing while looking exactly like a fix. Verified in
+ * `api-extension.test.ts`.
+ */
+ function trackInGitLine(skillDirRel: string): string {
+ const root = dirname(skillDirRel);
+ return `!/${root.split(sep).join('/')}/`;
+ }
+
+ const handleSkillTrackInGit = withValidation(
+ SkillTrackInGitRequestSchema,
+ catchErrors(
+ async (_req, res, body) => {
+ if (!validateSkillName(body.name, res, 'skill-track-in-git')) return;
+ if (body.scope !== 'project') {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Only project skills live in the repository; a global skill is outside any .gitignore.',
+ { handler: 'skill-track-in-git' },
+ );
+ return;
+ }
+ if (!projectDir) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project directory.', {
+ handler: 'skill-track-in-git',
+ });
+ return;
+ }
+ const inPlace = scanInPlaceSkills(contentDir).find((s) => s.name === body.name);
+ const mountedDirRel = inPlace?.dir ?? `${LEGACY_SKILL_STORE_ROOT}/${body.name}`;
+ // Resolve through any symlink first: the rule has to name the directory
+ // git is actually excluding, which for an aliased bundle is the
+ // canonical one, not the mount. A negation for the mount would verify
+ // as ineffective and be reverted — correct, but useless to the user.
+ const indexedFileRel =
+ indexedSkillContentPath(resolve(contentDir, mountedDirRel, 'SKILL.md'), contentDir) ??
+ `${mountedDirRel}/SKILL.md`;
+ const skillDirRel = dirname(indexedFileRel);
+ const skillFileRel = indexedFileRel;
+ const line = trackInGitLine(skillDirRel);
+ const gitignoreRel = '.gitignore';
+ const gitignoreAbs = resolve(contentDir, gitignoreRel);
+
+ // Already admitted: nothing to do, and saying so beats writing a rule
+ // that changes nothing.
+ if (contentFilter && !contentFilter.isPathIgnored(skillFileRel)) {
+ successResponse(
+ res,
+ 200,
+ SkillTrackInGitSuccessSchema,
+ { line, gitignorePath: gitignoreRel, applied: false, alreadyTracked: true },
+ { handler: 'skill-track-in-git' },
+ );
+ return;
+ }
+ if (body.apply !== true) {
+ successResponse(
+ res,
+ 200,
+ SkillTrackInGitSuccessSchema,
+ { line, gitignorePath: gitignoreRel, applied: false },
+ { handler: 'skill-track-in-git' },
+ );
+ return;
+ }
+
+ const before = existsSync(gitignoreAbs) ? readFileSync(gitignoreAbs, 'utf-8') : null;
+ const lines = (before ?? '').split('\n');
+ if (lines.some((l) => l.trim() === line)) {
+ // The rule is present but the path is still ignored — appending a
+ // duplicate would not change that. Report rather than no-op silently.
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:invalid-request',
+ `"${line}" is already in ${gitignoreRel}, but ${skillFileRel} is still ignored — another rule excludes it.`,
+ { handler: 'skill-track-in-git' },
+ );
+ return;
+ }
+ const next = `${before === null || before.endsWith('\n') || before === '' ? (before ?? '') : `${before}\n`}${line}\n`;
+ writeFileSync(gitignoreAbs, next, 'utf-8');
+ await contentFilter?.rebuildIgnorePatterns();
+
+ // VERIFY, then keep or revert. A negation rule is not universally
+ // sufficient — an ancestor excluded as a directory (`.claude/`, not
+ // `.claude/*`) cannot be re-included from below — so the only honest
+ // way to report success is to ask the filter again. Leaving a rule
+ // behind that did not work would be the same class of silent lie this
+ // whole endpoint exists to end.
+ if (contentFilter?.isPathIgnored(skillFileRel)) {
+ if (before === null) rmSync(gitignoreAbs, { force: true });
+ else writeFileSync(gitignoreAbs, before, 'utf-8');
+ await contentFilter.rebuildIgnorePatterns();
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:invalid-request',
+ `Adding "${line}" did not make ${skillFileRel} trackable — another .gitignore rule excludes a parent directory. ${gitignoreRel} was left unchanged.`,
+ { handler: 'skill-track-in-git' },
+ );
+ return;
+ }
+ // Every other handler that rebuilds the filter broadcasts; without it
+ // the newly admitted skill sits unindexed in the UI until an unrelated
+ // refresh — the same "it's right there and won't open" this endpoint
+ // exists to end.
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillTrackInGitSuccessSchema,
+ { line, gitignorePath: gitignoreRel, applied: true },
+ { handler: 'skill-track-in-git' },
+ );
+ },
+ { handler: 'skill-track-in-git', title: 'Failed to update .gitignore.' },
+ ),
+ { handler: 'skill-track-in-git', method: 'POST' },
+ );
+
+ // Per-extension state for the read-side allow-list heal in the list handler.
+ const skillAdmissionHeal: SkillAdmissionHealState = { lastKey: null };
+
const handleSkillsList = withValidation(
EmptyRequestSchema,
catchErrors(
@@ -14627,17 +14875,56 @@ export function createApiExtension(
.map((name) => builtinSkillListEntry(skillsHome, name, 'global'))
.filter((e): e is NonNullable<typeof e> => e !== null);
const inPlaceNames = new Set(inPlace.map((e) => e.name));
+ const listed = [
+ ...enrich(project, projectInstalled, true).filter((e) => !inPlaceNames.has(e.name)),
+ ...inPlace,
+ ...enrich(globalSkills, globalInstalled, false),
+ ...globalInPlace,
+ ...(projectBuiltin ? [projectBuiltin] : []),
+ ...globalBuiltins,
+ ];
+ // A project skill dir can be a SYMLINK to a canonical dir elsewhere in
+ // the content tree. Report BOTH: `path` is where the bundle is mounted
+ // (what install / reveal / host wiring reasons about), `canonicalPath`
+ // is the name the document index actually holds, which is the only one
+ // that opens. Global entries are home-relative, not content paths.
const enriched = {
- skills: [
- ...enrich(project, projectInstalled, true).filter((e) => !inPlaceNames.has(e.name)),
- ...inPlace,
- ...enrich(globalSkills, globalInstalled, false),
- ...globalInPlace,
- ...(projectBuiltin ? [projectBuiltin] : []),
- ...globalBuiltins,
- ],
+ skills: listed.map((entry) => {
+ const canonicalPath =
+ entry.scope === 'project' && entry.absolutePath
+ ? indexedSkillContentPath(entry.absolutePath, contentDir)
+ : null;
+ const withCanonical =
+ canonicalPath === null || canonicalPath === entry.path
+ ? entry
+ : { ...entry, canonicalPath };
+ // Listed but NOT admitted: a gitignored bundle is deliberately kept
+ // out of the document index, so it has no doc to open. Say so here
+ // rather than letting the click produce an empty tab.
+ //
+ // Judged on the path the client will actually OPEN, not the mounted
+ // one: for a symlinked bundle those differ, and asking about the
+ // wrong one gets it backwards both ways — a mount under a gitignored
+ // dir whose canonical is tracked opens fine yet would be refused,
+ // and the reverse would offer a `.gitignore` line for a directory
+ // that is not the one doing the excluding.
+ const openedPath = canonicalPath ?? entry.path;
+ return entry.scope === 'project' && contentFilter?.isPathIgnored(openedPath) === true
+ ? { ...withCanonical, ignored: true }
+ : withCanonical;
+ }),
truncated: project.truncated || globalSkills.truncated,
};
+ // Heal a stale in-place allow-list on the way out: a dir written by
+ // anything that skipped the rebuild lists here but has no page, so the
+ // skill opens into a Files fallback until the server restarts. The
+ // rebuild's re-scan lands asynchronously, so the skill becomes openable
+ // on the next refresh rather than in this response.
+ await healUnservableSkillAdmission(
+ inPlace.map((e) => e.path),
+ contentFilter ?? null,
+ skillAdmissionHeal,
+ );
successResponse(res, 200, SkillsListSuccessSchema, enriched, { handler: 'skills-list' });
},
{ handler: 'skills-list', title: 'Failed to list skills.' },
@@ -15656,7 +15943,30 @@ export function createApiExtension(
// Re-project on ANY resolved host (marker OR scan) — a scan-only in-place
// skill has no marker entry but still occupies real editor dirs. Stamp the
// new marker with the DESTINATION scope (not the source's stale scope).
- if (fromBase) await uninstallSkillFromHostDirs(fromBase, name, fromScope);
+ // The scan entry captured BEFORE the move carries the hash that decides
+ // which same-named occurrences are this skill. Without it we cannot tell
+ // a projection of the moved bundle from somebody else's fork, so skip
+ // the purge rather than guess — a leftover is recoverable, a wrongly
+ // deleted skill is not.
+ if (fromBase) {
+ await uninstallSkillFromHostDirs(
+ fromBase,
+ name,
+ fromScope,
+ scanEntry ? { purge: { contentHash: scanEntry.contentHash } } : {},
+ );
+ }
+ // The placement ledger is keyed by NAME and would otherwise survive the
+ // move describing locations in their pre-move form, which the list then
+ // reports as "changed outside" — OK accusing another tool of its own
+ // rewrite. Clear the source scope's records; the destination records its
+ // own as it projects.
+ // `fromBase` (the install base) is what every placement reader uses —
+ // `readSkillPlacements(projectDir)` in the list handler, and the ledger
+ // ops in `services/skill-*-ops.ts`. Passing the CONTENT dir would clear
+ // a ledger nobody reads and mint a stray `.ok/local/` beside the content
+ // whenever the two differ, leaving the drift this is meant to end.
+ if (fromBase) await clearSkillPlacements(fromBase, name);
if (toBase && priorHosts.length > 0) {
const newHosts = projectSkill(
toDir,
@@ -15719,6 +16029,12 @@ export function createApiExtension(
return;
}
+ // The destination scope's skill dir is not servable until the filter's
+ // in-place allow-list knows about it, so without this the moved SKILL.md
+ // 404s and the editor falls back to a Files tab. Same reason and same
+ // placement as `handleSkillInstall`, which rebuilds before every exit.
+ await contentFilter?.rebuildIgnorePatterns();
+
signalChannel?.('files');
successResponse(
res,
@@ -15828,6 +16144,11 @@ export function createApiExtension(
await commitOkArtifactWrite('skill-duplicate');
}
signalChannel?.('files');
+ // A skill dir is not servable until the filter's in-place allow-list knows
+ // about it, and an API write does not otherwise trigger a rebuild. Same
+ // call, same reason, same placement as `handleSkillInstall`.
+ await contentFilter?.rebuildIgnorePatterns();
+
successResponse(
res,
200,
@@ -16886,6 +17207,11 @@ export function createApiExtension(
resolveSkillInstallReportSettings(),
);
}
+ // The imported skill dir is brand new on disk; until the filter's in-place
+ // allow-list is rebuilt its SKILL.md is not servable, and opening the skill
+ // the user just imported falls back to a Files tab.
+ await contentFilter?.rebuildIgnorePatterns();
+
respondSkillImport(res, outcome);
} catch (e) {
errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to import skill.', {
@@ -17112,6 +17438,11 @@ export function createApiExtension(
);
}
}
+ // A skill dir is not servable until the filter's in-place allow-list knows
+ // about it, and an API write does not otherwise trigger a rebuild. Same
+ // call, same reason, same placement as `handleSkillInstall`.
+ await contentFilter?.rebuildIgnorePatterns();
+
successResponse(
res,
200,
@@ -17583,6 +17914,14 @@ export function createApiExtension(
}
}
signalChannel?.('files');
+ // Admit the just-written skill dirs to the content-filter allow-list
+ // BEFORE responding. A skill dir only enters that allow-list on
+ // `rebuildIgnorePatterns()`, which an API write does not otherwise
+ // trigger — so the client could open the freshly installed SKILL.md,
+ // have it judged excluded, and hang until the 30s sync timeout before
+ // a later rebuild made the retry work. `skill-get` and the scope-move
+ // handler already do this; install was the gap.
+ await contentFilter?.rebuildIgnorePatterns();
successResponse(
res,
200,
@@ -17683,6 +18022,14 @@ export function createApiExtension(
return;
}
signalChannel?.('files');
+ // Admit the just-written skill dirs to the content-filter allow-list
+ // BEFORE responding. A skill dir only enters that allow-list on
+ // `rebuildIgnorePatterns()`, which an API write does not otherwise
+ // trigger — so the client could open the freshly installed SKILL.md,
+ // have it judged excluded, and hang until the 30s sync timeout before
+ // a later rebuild made the retry work. `skill-get` and the scope-move
+ // handler already do this; install was the gap.
+ await contentFilter?.rebuildIgnorePatterns();
successResponse(
res,
200,
@@ -17750,6 +18097,14 @@ export function createApiExtension(
if (!('alreadyAtSource' in placed)) {
signalChannel?.('files');
}
+ // Admit the just-written skill dirs to the content-filter allow-list
+ // BEFORE responding. A skill dir only enters that allow-list on
+ // `rebuildIgnorePatterns()`, which an API write does not otherwise
+ // trigger — so the client could open the freshly installed SKILL.md,
+ // have it judged excluded, and hang until the 30s sync timeout before
+ // a later rebuild made the retry work. `skill-get` and the scope-move
+ // handler already do this; install was the gap.
+ await contentFilter?.rebuildIgnorePatterns();
successResponse(
res,
200,
@@ -17836,6 +18191,14 @@ export function createApiExtension(
}
}
signalChannel?.('files');
+ // Admit the just-written skill dirs to the content-filter allow-list
+ // BEFORE responding. A skill dir only enters that allow-list on
+ // `rebuildIgnorePatterns()`, which an API write does not otherwise
+ // trigger — so the client could open the freshly installed SKILL.md,
+ // have it judged excluded, and hang until the 30s sync timeout before
+ // a later rebuild made the retry work. `skill-get` and the scope-move
+ // handler already do this; install was the gap.
+ await contentFilter?.rebuildIgnorePatterns();
successResponse(
res,
200,
@@ -18550,6 +18913,11 @@ export function createApiExtension(
);
await commitOkArtifactWrite('skill-restore');
signalChannel?.('files');
+ // A skill dir is not servable until the filter's in-place allow-list knows
+ // about it, and an API write does not otherwise trigger a rebuild. Same
+ // call, same reason, same placement as `handleSkillInstall`.
+ await contentFilter?.rebuildIgnorePatterns();
+
successResponse(
res,
200,
@@ -18679,6 +19047,11 @@ export function createApiExtension(
},
},
}));
+ // A skill dir is not servable until the filter's in-place allow-list knows
+ // about it, and an API write does not otherwise trigger a rebuild. Same
+ // call, same reason, same placement as `handleSkillInstall`.
+ await contentFilter?.rebuildIgnorePatterns();
+
successResponse(
res,
200,
@@ -18812,6 +19185,11 @@ export function createApiExtension(
// Already up to date — nothing to write. (Temp dir is dropped by the
// handler's `finally { cleanup() }` — no explicit call needed here.)
if (acquired.contentHash === entry.contentHash && removedUpstream.length === 0) {
+ // A skill dir is not servable until the filter's in-place allow-list knows
+ // about it, and an API write does not otherwise trigger a rebuild. Same
+ // call, same reason, same placement as `handleSkillInstall`.
+ await contentFilter?.rebuildIgnorePatterns();
+
successResponse(
res,
200,
@@ -18849,6 +19227,11 @@ export function createApiExtension(
gitTracked = undefined; // not a git repo / unborn index — no gate
}
}
+ // A skill dir is not servable until the filter's in-place allow-list knows
+ // about it, and an API write does not otherwise trigger a rebuild. Same
+ // call, same reason, same placement as `handleSkillInstall`.
+ await contentFilter?.rebuildIgnorePatterns();
+
successResponse(
res,
200,
@@ -18979,6 +19362,11 @@ export function createApiExtension(
}
signalChannel?.('files');
+ // A skill dir is not servable until the filter's in-place allow-list knows
+ // about it, and an API write does not otherwise trigger a rebuild. Same
+ // call, same reason, same placement as `handleSkillInstall`.
+ await contentFilter?.rebuildIgnorePatterns();
+
successResponse(
res,
200,
@@ -21588,6 +21976,7 @@ export function createApiExtension(
'/api/skill/restore': handleSkillRestore,
'/api/skill/reimport': handleSkillReimport,
'/api/skill/revert': handleSkillRevert,
+ '/api/skill/track-in-git': handleSkillTrackInGit,
'/api/skill-targets': handleSkillTargets,
'/api/search': handleSearch,
'/api/semantic-status': handleSemanticStatus,
@@ -21721,6 +22110,7 @@ export function createApiExtension(
'/api/skill/restore',
'/api/skill/reimport',
'/api/skill/revert',
+ '/api/skill/track-in-git',
// Read-shaped GETs, but each triggers an arbitrary `git clone` (network egress)
// + local SKILL.md reads, so they ride the loopback/host gate, not the read posture.
'/api/skills/preview',
diff --git a/packages/server/src/in-place-skills.test.ts b/packages/server/src/in-place-skills.test.ts
index 9c1876fe6..4705d9bab 100644
--- a/packages/server/src/in-place-skills.test.ts
+++ b/packages/server/src/in-place-skills.test.ts
@@ -1,9 +1,11 @@
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createContentFilter } from './content-filter.ts';
import {
+ removableSkillOccurrenceDirs,
resolveGlobalNativeSkillDir,
scanGlobalInPlaceSkills,
scanHostRootAliases,
@@ -350,3 +352,57 @@ describe('scanHostRootAliases (folder-level aliases, observable facts only)', ()
expect(foo?.hosts).not.toContain('.tim/skills');
});
});
+
+describe('removableSkillOccurrenceDirs', () => {
+ let base: string;
+ beforeEach(() => {
+ base = mkdtempSync(join(tmpdir(), 'ok-occurrences-'));
+ });
+ afterEach(() => {
+ rmSync(base, { recursive: true, force: true });
+ });
+
+ const hashOf = (rel: string) => parseSkillDir(join(base, rel))?.contentHash as string;
+
+ test('removes THIS skill everywhere, and never a same-named fork', () => {
+ // The blocker this guards: the registry models two same-named bundles with
+ // different bytes as two DISTINCT skills (`conflictHosts`). Deleting
+ // `.cursor/skills/foo` because `.claude/skills/foo` moved away destroys a
+ // bundle its owner never touched — unrecoverably when it is untracked.
+ writeSkill(base, '.claude/skills/foo', '# Moved');
+ writeSkill(base, '.agents/skills/foo', '# Moved');
+ writeSkill(base, '.cursor/skills/foo', '# A DIFFERENT skill that happens to share the name');
+ const moved = hashOf('.claude/skills/foo');
+
+ const dirs = removableSkillOccurrenceDirs(base, 'project', 'foo', moved);
+
+ expect(new Set(dirs)).toEqual(
+ new Set([join(base, '.claude/skills/foo'), join(base, '.agents/skills/foo')]),
+ );
+ expect(dirs).not.toContain(join(base, '.cursor/skills/foo'));
+ });
+
+ test('a symlink goes even when its target is already gone', () => {
+ // A projection whose target the move deleted is still a dir entry the next
+ // scan trips on, and `existsSync` reports it absent — hence lstat.
+ mkdirSync(join(base, '.claude/skills'), { recursive: true });
+ symlinkSync(join(base, 'gone'), join(base, '.claude/skills/foo'));
+ expect(removableSkillOccurrenceDirs(base, 'project', 'foo', 'any-hash')).toEqual([
+ join(base, '.claude/skills/foo'),
+ ]);
+ });
+
+ test('covers the legacy .ok/skills store, not just host roots', () => {
+ // A copy parked outside the standard roots would otherwise survive the move
+ // and be re-detected as a second skill at the scope just moved away from.
+ writeSkill(base, '.ok/skills/foo', '# Moved');
+ const moved = hashOf('.ok/skills/foo');
+ expect(removableSkillOccurrenceDirs(base, 'project', 'foo', moved)).toEqual([
+ join(base, '.ok/skills/foo'),
+ ]);
+ });
+
+ test('nothing to remove is an empty list', () => {
+ expect(removableSkillOccurrenceDirs(base, 'project', 'nothing-here', 'h')).toEqual([]);
+ });
+});
diff --git a/packages/server/src/in-place-skills.ts b/packages/server/src/in-place-skills.ts
index 5845fd0e4..81221020f 100644
--- a/packages/server/src/in-place-skills.ts
+++ b/packages/server/src/in-place-skills.ts
@@ -20,9 +20,11 @@
import { existsSync, lstatSync, readdirSync, realpathSync, statSync } from 'node:fs';
import { join } from 'node:path';
import {
+ AGENTS_SKILLS_ROOT,
EDITOR_PROJECT_SKILL_ROOT,
EDITOR_USER_SKILL_ROOT,
type EditorId,
+ LEGACY_SKILL_STORE_ROOT,
type SkillScope,
} from '@inkeep/open-knowledge-core';
import {
@@ -53,10 +55,10 @@ function hostRoots(
/** host → project-relative skills root: every editor primary (non-null) plus
* the vendor-neutral `.agents/skills` hub (first-class in-place host). */
-const EDITOR_SKILL_ROOTS = hostRoots(EDITOR_PROJECT_SKILL_ROOT, '.agents/skills');
+const EDITOR_SKILL_ROOTS = hostRoots(EDITOR_PROJECT_SKILL_ROOT, AGENTS_SKILLS_ROOT);
/** host → home-relative skills root for USER scope (editors + the `~/.agents` hub). */
-const USER_SKILL_ROOTS = hostRoots(EDITOR_USER_SKILL_ROOT, '.agents/skills');
+const USER_SKILL_ROOTS = hostRoots(EDITOR_USER_SKILL_ROOT, AGENTS_SKILLS_ROOT);
/** One in-place skill the registry canonicalized — the list-surface projection. */
export interface InPlaceSkill {
@@ -187,6 +189,58 @@ export function standardSkillRoots(scope: SkillScope): ReadonlySet<string> {
return new Set(roots.map((r) => r.root));
}
+/**
+ * The `<root>/<name>` bundle dirs a cross-scope MOVE may remove from the source
+ * scope — every occurrence that is THIS skill, and nothing else.
+ *
+ * A move relocated the bytes, so nothing of this skill may survive here. But
+ * "same name" is not "same skill": the registry deliberately models two
+ * same-named bundles with different content as two DISTINCT skills
+ * (`conflictHosts`), and an uninstall protects them via the hash-guarded
+ * `removeInPlaceSkillCopies`. A move must protect them too — deleting
+ * `.cursor/skills/foo` because `.claude/skills/foo` moved away destroys a
+ * bundle its owner never touched, unrecoverably when it is untracked.
+ *
+ * So: symlinks go (a projection of the moved tree, dangling or not), and a real
+ * directory goes ONLY when its content hash matches the skill that moved.
+ * Anything else is somebody else's skill and stays.
+ *
+ * Roots come from `knownSkillRootsFor` (host roots + recorded custom roots) plus
+ * the legacy `.ok/skills` store, so a copy parked outside the standard roots
+ * cannot survive to be re-detected as a second skill at the scope the user just
+ * moved away from.
+ */
+export function removableSkillOccurrenceDirs(
+ base: string,
+ scope: SkillScope,
+ name: string,
+ /** Content hash of the bundle that moved; a real dir must match it to go. */
+ contentHash: string,
+): string[] {
+ const roots = new Set<string>([
+ ...knownSkillRootsFor(base, scope).map((r) => r.root),
+ LEGACY_SKILL_STORE_ROOT,
+ ]);
+ const dirs: string[] = [];
+ for (const root of roots) {
+ const dir = join(base, root, name);
+ let stat: ReturnType<typeof lstatSync>;
+ try {
+ // `lstat`, not `existsSync`: a projection whose target the move already
+ // deleted is still a dir entry the next scan trips on.
+ stat = lstatSync(dir);
+ } catch {
+ continue;
+ }
+ if (stat.isSymbolicLink()) {
+ dirs.push(dir);
+ continue;
+ }
+ if (parseSkillDir(dir)?.contentHash === contentHash) dirs.push(dir);
+ }
+ return dirs;
+}
+
/**
* The SOURCE roots of the aliases `scanHostRootAliases` found — the paths that
* are themselves symlinked folders (e.g. `.codex/skills` when it links to
@@ -219,7 +273,7 @@ export function aliasedSourceRoots(
*/
export function resolveDefaultSkillHomeRel(base: string, scope: SkillScope): string {
const roots = scope === 'project' ? EDITOR_SKILL_ROOTS : USER_SKILL_ROOTS;
- if (existsSync(join(base, '.agents'))) return '.agents/skills';
+ if (existsSync(join(base, '.agents'))) return AGENTS_SKILLS_ROOT;
const byPrecedence = [...roots]
.filter((r) => r.editor !== 'agents')
.sort((a, b) => {
diff --git a/packages/server/src/mcp/tools/skills.ts b/packages/server/src/mcp/tools/skills.ts
index 1cf9be20d..127f5bbdd 100644
--- a/packages/server/src/mcp/tools/skills.ts
+++ b/packages/server/src/mcp/tools/skills.ts
@@ -9,7 +9,11 @@
* NEVER browses `.ok/` to find or read a skill — `.ok/` stays opaque (no `ls`,
* no raw `.ok/skills/...` paths). Read-only; mutation stays with the verb tools.
*/
-import { EDITOR_PROJECT_SKILL_ROOT, EDITOR_USER_SKILL_ROOT } from '@inkeep/open-knowledge-core';
+import {
+ AGENTS_SKILLS_ROOT,
+ EDITOR_PROJECT_SKILL_ROOT,
+ EDITOR_USER_SKILL_ROOT,
+} from '@inkeep/open-knowledge-core';
import { z } from 'zod';
import { INTERNAL_BUNDLE_SKILL_NAMES, isInternalBundleSkillName } from '../../skill-bundles.ts';
import {
@@ -66,7 +70,7 @@ function projectListRow(s: Record<string, unknown>): {
const aliases = (s.hostAliases ?? {}) as Record<string, string>;
const drift = new Set(Array.isArray(s.driftPaths) ? (s.driftPaths as string[]) : []);
const rootOf = (h: string): string => {
- if (h === 'agents') return '.agents/skills';
+ if (h === 'agents') return AGENTS_SKILLS_ROOT;
if (h.includes('/')) return h; // custom-root id IS its path
const map = scope === 'project' ? EDITOR_PROJECT_SKILL_ROOT : EDITOR_USER_SKILL_ROOT;
return (map as Record<string, string | null>)[h] ?? h;
diff --git a/packages/server/src/services/skill-install-ops.ts b/packages/server/src/services/skill-install-ops.ts
index c717b3a68..156fbfd31 100644
--- a/packages/server/src/services/skill-install-ops.ts
+++ b/packages/server/src/services/skill-install-ops.ts
@@ -1,6 +1,7 @@
import { existsSync, lstatSync, readFileSync } from 'node:fs';
import { dirname, join, relative, resolve, sep } from 'node:path';
import {
+ AGENTS_SKILLS_ROOT,
applyPatchToFm,
detectFmRegion,
EDITOR_PROJECT_SKILL_ROOT,
@@ -61,6 +62,9 @@ interface ForkCanonical {
dir: string;
contentHash: string;
hosts: readonly string[];
+ /** Hosts reaching this skill via a SYMLINK rather than their own copy. Needed
+ * to judge the skill's existing form when no install mode is requested. */
+ linkedHosts?: readonly string[];
}
type ResolveForkOutcome =
@@ -94,6 +98,23 @@ type FanOutInPlaceOutcome =
export interface SkillInstallOpsDeps {
contentDir: string;
skillsHome: string;
+ /**
+ * The form a NEW location should take when the caller names none: the skill's
+ * own recorded preference, else whatever its existing locations are.
+ *
+ * Without it this fan-out passed `undefined` straight through and
+ * `projectInPlaceSkill` fell back to its `copy` default, so re-installing a
+ * skill whose locations were SYMLINKS silently rewrote them as full copies —
+ * duplicating bytes into git and detaching those locations from the source,
+ * then reporting the result as "changed outside" because the placement ledger
+ * still described links. `skill-import` already takes this dep; the install
+ * path was the one that did not.
+ */
+ effectiveInstallMode: (
+ scope: 'project' | 'global',
+ name: string,
+ entry: { hosts: readonly string[]; linkedHosts: readonly string[] },
+ ) => 'copy' | 'link';
}
export interface SkillInstallOpsService {
@@ -185,7 +206,7 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillIn
const forkWarnings: string[] = [];
const rootMap = scope === 'project' ? EDITOR_PROJECT_SKILL_ROOT : EDITOR_USER_SKILL_ROOT;
const forkRootRel =
- fork.editor === 'agents' ? '.agents/skills' : (rootMap[fork.editor as EditorId] ?? null);
+ fork.editor === 'agents' ? AGENTS_SKILLS_ROOT : (rootMap[fork.editor as EditorId] ?? null);
if (forkRootRel === null) {
return { ok: false, kind: 'unknown-editor', editor: fork.editor };
}
@@ -340,7 +361,7 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillIn
) {
const subRoot =
id === 'agents'
- ? '.agents/skills'
+ ? AGENTS_SKILLS_ROOT
: ((scope === 'project' ? EDITOR_PROJECT_SKILL_ROOT : EDITOR_USER_SKILL_ROOT)[
id as EditorId
] ?? null);
@@ -356,7 +377,7 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillIn
) {
const subRoot =
id === 'agents'
- ? '.agents/skills'
+ ? AGENTS_SKILLS_ROOT
: ((scope === 'project' ? EDITOR_PROJECT_SKILL_ROOT : EDITOR_USER_SKILL_ROOT)[
id as EditorId
] ?? null);
@@ -446,14 +467,60 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillIn
return { ok: false, kind: 'source-occupied', reason: moved.reason };
}
sourceMovedTo = relative(inPlaceScanBase, moved.newAbs).split(sep).join('/');
- // The swap left a symlink at the old source path (relocate's
- // `leaveLinkBehind`). RECORD it as the expected form — without
- // the receipt, an external tool rewriting that link as a copy
- // would be invisible to drift detection (the .agents blind spot).
- await recordSkillPlacement(ledgerBase, name, {
- path: oldSourceRel,
- mode: 'link',
+ // Record the old source path so an external rewrite of it stays visible
+ // to drift detection (the .agents blind spot) — but record the form it
+ // ACTUALLY has, not the form relocate is expected to leave.
+ //
+ // This assumed `link` unconditionally, on the premise that the swap
+ // always leaves a symlink behind. When it does not, the receipt claims
+ // a symlink while a real directory sits there, and the very next drift
+ // read flags OK's own promote as "changed outside" — always on the
+ // PREVIOUS source, and clearing as soon as any install rewrites and
+ // re-records that location. Reading the form back costs one lstat and
+ // cannot claim something the disk disagrees with.
+ // Match the siblings, per `effectiveInstallMode`'s stated contract: "a
+ // skill whose locations are all copies keeps getting copies, so a new
+ // one matches its siblings rather than silently mixing forms."
+ //
+ // relocate always leaves a SYMLINK behind, hard-coded. When the skill's
+ // other locations are copies that mixes forms — and the menu then tags
+ // the symlink as divergent and offers to convert it, so the app warns
+ // about the state it just created. Guaranteed, not incidental: a promote
+ // leaves exactly one link, so it is always the minority.
+ //
+ // Decided HERE rather than inside the primitive, matching how import and
+ // the install fan-out already consult this helper and pass the result
+ // down.
+ const oldSourceAbs = resolve(inPlaceScanBase, oldSourceRel);
+ const siblingForm = deps.effectiveInstallMode(scope, name, {
+ hosts: inPlaceEntry.hosts,
+ linkedHosts: inPlaceEntry.linkedHosts ?? [],
});
+ if (siblingForm === 'copy') {
+ try {
+ if (lstatSync(oldSourceAbs).isSymbolicLink()) {
+ tracedRmSync(oldSourceAbs, { recursive: true, force: true });
+ tracedCpSync(moved.newAbs, oldSourceAbs, { recursive: true, dereference: true });
+ }
+ } catch {
+ // Absent or unreadable — leave whatever relocate did.
+ }
+ }
+ let oldSourceIsLink = false;
+ try {
+ oldSourceIsLink = lstatSync(oldSourceAbs).isSymbolicLink();
+ } catch {
+ // Gone entirely — nothing to describe, so leave the ledger alone
+ // rather than assert a form for a path that no longer exists.
+ oldSourceIsLink = true;
+ }
+ await recordSkillPlacement(
+ ledgerBase,
+ name,
+ oldSourceIsLink
+ ? { path: oldSourceRel, mode: 'link' }
+ : { path: oldSourceRel, mode: 'copy', hash: inPlaceEntry.contentHash },
+ );
// Re-point recorded placement SYMLINKS that referenced the old
// source: `relocateInPlaceCanonical`'s own sweep only walks host dirs,
// so the ledger is a second slot source over the same relocation. Both
@@ -585,11 +652,24 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillIn
name,
cwd: base,
targets: inPlaceTargets,
- mode: input.installMode,
+ // An explicit choice wins; otherwise match the skill's existing form
+ // rather than defaulting to copy. `convertLinks` below still honours an
+ // EXPLICIT copy request, so deliberate link→copy conversion is intact —
+ // only the implicit default changes.
+ mode:
+ // The CALLER owns mode resolution: `installMode` is required on this
+ // interface and the only call site resolves it via
+ // `effectiveInstallMode` before calling in, so a `??` fallback here
+ // could never fire and made the service look like it defaulted when
+ // it does not. `deps.effectiveInstallMode` stays wired for the
+ // sibling service and for tests.
+ input.installMode,
// An EXPLICIT copy choice converts existing links back to copies
// (lossless — the link's bytes ARE the canonical's); an implicit
// copy default never touches links.
convertLinks: input.linkModeReq === false,
+ // The mirror: only an EXPLICIT link request restamps existing copies.
+ convertCopies: input.linkModeReq === true,
roots: skillProjectionRoots(scope),
});
for (const editor of fanned.conflicted) {
@@ -631,7 +711,7 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillIn
// drift detection can spot another tool rewriting the path.
for (const editor of fanned.hosts) {
const editorRoot =
- editor === 'agents' ? '.agents/skills' : EDITOR_PROJECT_SKILL_ROOT[editor];
+ editor === 'agents' ? AGENTS_SKILLS_ROOT : EDITOR_PROJECT_SKILL_ROOT[editor];
if (editorRoot === null || editorRoot === input.canonicalRootRel) continue;
const copyAbs = resolve(base, editorRoot, name);
let isLink = false;
diff --git a/packages/server/src/services/skill-placement-ops.ts b/packages/server/src/services/skill-placement-ops.ts
index 63e3ac80e..7b0b1d130 100644
--- a/packages/server/src/services/skill-placement-ops.ts
+++ b/packages/server/src/services/skill-placement-ops.ts
@@ -1,7 +1,7 @@
import { existsSync } from 'node:fs';
import { dirname, relative, resolve, sep } from 'node:path';
import type { EditorId } from '@inkeep/open-knowledge-core';
-import { isSkillInstallTarget } from '@inkeep/open-knowledge-core';
+import { AGENTS_SKILLS_ROOT, isSkillInstallTarget } from '@inkeep/open-knowledge-core';
import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
import { tracedCpSync, tracedMkdirSync, tracedRmSync, tracedSymlinkSync } from '../fs-traced.ts';
import {
@@ -159,7 +159,7 @@ export function createSkillPlacementOpsService(): SkillPlacementOpsService {
const isHost = isSkillInstallTarget(input.target);
const rootRel = isHost
? input.target === 'agents'
- ? '.agents/skills'
+ ? AGENTS_SKILLS_ROOT
: roots[input.target as EditorId]
: input.target
.replace(/\\/g, '/')
diff --git a/packages/server/src/skill-migrate.ts b/packages/server/src/skill-migrate.ts
index bdc230e25..3614196a0 100644
--- a/packages/server/src/skill-migrate.ts
+++ b/packages/server/src/skill-migrate.ts
@@ -22,6 +22,7 @@
import { existsSync, readdirSync, realpathSync } from 'node:fs';
import { dirname, join, relative, resolve, sep } from 'node:path';
import {
+ AGENTS_SKILLS_ROOT,
EDITOR_PROJECT_SKILL_ROOT,
EDITOR_USER_SKILL_ROOT,
type EditorId,
@@ -47,7 +48,7 @@ function rootsByPrecedence(
map: Record<EditorId, string | null>,
): ReadonlyArray<{ host: SkillHostId; root: string }> {
return [
- { host: 'agents' as SkillHostId, root: '.agents/skills' },
+ { host: 'agents' as SkillHostId, root: AGENTS_SKILLS_ROOT },
...(Object.entries(map) as [EditorId, string | null][])
.filter((e): e is [EditorId, string] => e[1] !== null)
.map(([host, root]) => ({ host: host as SkillHostId, root })),
diff --git a/packages/server/src/skill-placements.test.ts b/packages/server/src/skill-placements.test.ts
index 542a425d5..7dfd46f0f 100644
--- a/packages/server/src/skill-placements.test.ts
+++ b/packages/server/src/skill-placements.test.ts
@@ -5,6 +5,7 @@ import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import type { InPlaceSkill } from './in-place-skills.ts';
import {
+ clearSkillPlacements,
readSkillPlacements,
recordSkillPlacement,
resyncRecordedSkillCopies,
@@ -139,3 +140,32 @@ describe('concurrent ledger writes', () => {
expect(recorded).toEqual([...paths].sort());
});
});
+
+describe('clearSkillPlacements', () => {
+ test('drops every record for one skill and leaves the others alone', async () => {
+ writeSkill(join(projectDir, '.claude/skills/guarded'), '# A');
+ writeSkill(join(projectDir, '.agents/skills/guarded'), '# A');
+ writeSkill(join(projectDir, '.claude/skills/other'), '# B');
+ await recordSkillPlacement(projectDir, 'guarded', {
+ path: '.claude/skills/guarded',
+ mode: 'link',
+ });
+ await recordSkillPlacement(projectDir, 'guarded', {
+ path: '.agents/skills/guarded',
+ mode: 'link',
+ });
+ await recordSkillPlacement(projectDir, 'other', { path: '.claude/skills/other', mode: 'copy' });
+
+ await clearSkillPlacements(projectDir, 'guarded');
+
+ const store = readSkillPlacementsStore(projectDir);
+ // The stale "link" records are what a move leaves behind to be re-read as
+ // drift once the round trip re-creates those locations as copies.
+ expect(store.skills.guarded).toBeUndefined();
+ expect(store.skills.other).toHaveLength(1);
+ });
+
+ test('clearing a skill with no records is a no-op', async () => {
+ await expect(clearSkillPlacements(projectDir, 'never-placed')).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/server/src/skill-placements.ts b/packages/server/src/skill-placements.ts
index 9db87cb3e..7a2fe73d8 100644
--- a/packages/server/src/skill-placements.ts
+++ b/packages/server/src/skill-placements.ts
@@ -127,6 +127,24 @@ export async function removeSkillPlacement(
});
}
+/**
+ * Drop EVERY recorded placement for a skill.
+ *
+ * The ledger is keyed by skill NAME and outlives a cross-scope move, so records
+ * written before the move describe locations that no longer exist in that form.
+ * Coming back, the re-projection re-creates them as copies while the ledger
+ * still claims links — and the list then reports drift ("changed outside"),
+ * blaming another tool for a shape OK itself produced. A move clears the source
+ * scope's records instead of leaving them to be re-read as evidence.
+ */
+export async function clearSkillPlacements(projectDir: string, name: string): Promise<void> {
+ await mutateSkillPlacementsStore(projectDir, (file) => {
+ if (file.skills[name] === undefined) return;
+ file.skills = { ...file.skills };
+ delete file.skills[name];
+ });
+}
+
/** Record (or refresh) one placement for a skill. */
export async function recordSkillPlacement(
projectDir: string,
diff --git a/packages/server/src/skill-projection.form-preservation.test.ts b/packages/server/src/skill-projection.form-preservation.test.ts
new file mode 100644
index 000000000..dfcdcb423
--- /dev/null
+++ b/packages/server/src/skill-projection.form-preservation.test.ts
@@ -0,0 +1,121 @@
+import { lstatSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
+import { afterEach, describe, expect, test } from 'vitest';
+import { projectInPlaceSkill } from './skill-projection.ts';
+
+/**
+ * Adding ONE editor must not restamp the form of locations the user already set
+ * up. The two directions used to be asymmetric — an existing symlink survived an
+ * implicit install, an existing copy did not — so installing a new host silently
+ * converted every copy into a symlink (and, with the other default, every
+ * symlink into a copy). Either way the placement ledger then disagreed with disk
+ * and the UI reported the user's own install as "changed outside".
+ */
+const dirs: string[] = [];
+afterEach(() => {
+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
+});
+
+function setup() {
+ const cwd = mkdtempSync(join(tmpdir(), 'ok-form-'));
+ dirs.push(cwd);
+ const canonical = join(cwd, '.claude/skills/demo');
+ mkdirSync(canonical, { recursive: true });
+ writeFileSync(join(canonical, 'SKILL.md'), '---\nname: demo\n---\nbody\n');
+ const canonicalHash = parseSkillDir(canonical)?.contentHash ?? '';
+ return { cwd, canonical, canonicalHash };
+}
+
+const form = (p: string) => (lstatSync(p).isSymbolicLink() ? 'link' : 'copy');
+
+describe('projectInPlaceSkill form preservation', () => {
+ test('an implicit link install leaves an existing COPY as a copy', () => {
+ const { cwd, canonical, canonicalHash } = setup();
+ // .cursor already holds an independent copy the user set up.
+ const cursor = join(cwd, '.cursor/skills/demo');
+ mkdirSync(cursor, { recursive: true });
+ writeFileSync(join(cursor, 'SKILL.md'), '---\nname: demo\n---\nbody\n');
+
+ projectInPlaceSkill({
+ canonicalAbs: canonical,
+ canonicalHash,
+ canonicalRootRel: '.claude/skills',
+ name: 'demo',
+ cwd,
+ targets: ['cursor', 'codex'],
+ mode: 'link', // implicit preference, NOT an explicit user choice
+ });
+
+ expect(form(cursor)).toBe('copy');
+ // The brand-new location still follows the preference.
+ expect(form(join(cwd, '.codex/skills/demo'))).toBe('link');
+ });
+
+ test('an EXPLICIT link choice does convert an existing copy', () => {
+ const { cwd, canonical, canonicalHash } = setup();
+ const cursor = join(cwd, '.cursor/skills/demo');
+ mkdirSync(cursor, { recursive: true });
+ writeFileSync(join(cursor, 'SKILL.md'), '---\nname: demo\n---\nbody\n');
+
+ projectInPlaceSkill({
+ canonicalAbs: canonical,
+ canonicalHash,
+ canonicalRootRel: '.claude/skills',
+ name: 'demo',
+ cwd,
+ targets: ['cursor'],
+ mode: 'link',
+ convertCopies: true,
+ });
+
+ expect(form(cursor)).toBe('link');
+ });
+
+ test("the CANONICAL host's own dir also follows an explicit link flip", () => {
+ // Distinct branch: when the target editor's root IS the canonical root, the
+ // loop never creates a copy — it takes the early arm and only converts an
+ // EXISTING occurrence. Every other test here exercises the non-canonical
+ // arm, so this one covers the leftover-same-hash-copy case that would
+ // otherwise stay a copy while the menu claims the skill is linked.
+ const { cwd, canonical, canonicalHash } = setup();
+
+ projectInPlaceSkill({
+ canonicalAbs: canonical,
+ canonicalHash,
+ // The canonical root and the target host's root are the SAME dir.
+ canonicalRootRel: '.claude/skills',
+ name: 'demo',
+ cwd,
+ targets: ['claude'],
+ mode: 'link',
+ convertCopies: true,
+ });
+
+ // The canonical is the source of truth and stays a real directory (`copy`
+ // in this helper's vocabulary) — the flip must never turn it into a link to
+ // itself, which is what makes this arm's early `continue` load-bearing.
+ expect(form(canonical)).toBe('copy');
+ });
+
+ test('an implicit copy install leaves an existing SYMLINK as a symlink', () => {
+ const { cwd, canonical, canonicalHash } = setup();
+ const agentsRoot = join(cwd, '.agents/skills');
+ mkdirSync(agentsRoot, { recursive: true });
+ const agents = join(agentsRoot, 'demo');
+ symlinkSync(canonical, agents, 'dir');
+
+ projectInPlaceSkill({
+ canonicalAbs: canonical,
+ canonicalHash,
+ canonicalRootRel: '.claude/skills',
+ name: 'demo',
+ cwd,
+ targets: ['agents', 'codex'],
+ mode: 'copy',
+ });
+
+ expect(form(agents)).toBe('link');
+ });
+});
diff --git a/packages/server/src/skill-projection.ts b/packages/server/src/skill-projection.ts
index 25feb60fc..8aa23049d 100644
--- a/packages/server/src/skill-projection.ts
+++ b/packages/server/src/skill-projection.ts
@@ -28,6 +28,7 @@
import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import {
+ AGENTS_SKILLS_ROOT,
containsXmlTag,
EDITOR_PROJECT_CONFIG_PATH,
EDITOR_PROJECT_SKILL_ROOT,
@@ -234,7 +235,7 @@ function skillTargetDir(
name: string,
roots: SkillProjectionRoots = EDITOR_PROJECT_SKILL_ROOT,
): string | null {
- if (target === 'agents') return resolve(cwd, '.agents/skills', name);
+ if (target === 'agents') return resolve(cwd, AGENTS_SKILLS_ROOT, name);
return skillHostDir(cwd, target, name, roots);
}
@@ -417,6 +418,16 @@ export function projectInPlaceSkill(opts: {
/** With copy mode: ALSO convert existing links-to-canonical into copies —
* only for an EXPLICIT user copy choice (lossless; links otherwise kept). */
convertLinks?: boolean;
+ /** Mirror of {@link convertLinks} for the other direction: with link mode,
+ * ALSO convert existing same-hash COPIES into links — again only for an
+ * EXPLICIT user choice.
+ *
+ * Without this the two directions were asymmetric: a link survived an
+ * implicit install but a copy did not, so simply adding one more editor
+ * restamped every existing copy as a symlink. An install the user did not
+ * ask to convert must leave each location in the form it is already in;
+ * `mode` then only decides what a BRAND-NEW location gets. */
+ convertCopies?: boolean;
/** Project-vs-user root map; defaults to project roots. */
roots?: SkillProjectionRoots;
}): { hosts: SkillHostId[]; conflicted: SkillHostId[] } {
@@ -440,7 +451,7 @@ export function projectInPlaceSkill(opts: {
for (const editor of targets) {
if (
editor === 'agents'
- ? canonicalRootRel === '.agents/skills'
+ ? canonicalRootRel === AGENTS_SKILLS_ROOT
: roots[editor] === canonicalRootRel
) {
// This host's own dir IS the canonical root — never CREATE a copy here.
@@ -452,7 +463,7 @@ export function projectInPlaceSkill(opts: {
if (own !== null && !hostSkillsRootEscapes(cwd, dirname(own))) {
const cls = classifyInPlaceDest(own, canonicalAbs, canonicalHash);
if (
- (mode === 'link' && cls === 'same-copy') ||
+ (mode === 'link' && opts.convertCopies === true && cls === 'same-copy') ||
(mode === 'copy' && opts.convertLinks === true && cls === 'link-to-canonical')
) {
materialize(own, dirname(own));
@@ -489,8 +500,12 @@ export function projectInPlaceSkill(opts: {
hosts.push(editor);
break;
case 'same-copy':
- // Lossless conversion when the preference is link; already right in copy mode.
- if (mode === 'link') materialize(dest, hostRoot);
+ // Lossless conversion when the user EXPLICITLY chose links; an implicit
+ // link preference leaves an existing copy alone. Symmetric with the
+ // link-to-canonical arm above, which already required an explicit copy
+ // choice — the asymmetry is what let one added editor restamp the form
+ // of every location the user had already set up.
+ if (mode === 'link' && opts.convertCopies === true) materialize(dest, hostRoot);
hosts.push(editor);
break;
case 'different':
diff --git a/packages/server/src/skill-reconcile.ts b/packages/server/src/skill-reconcile.ts
index cf4780fd8..a9be806aa 100644
--- a/packages/server/src/skill-reconcile.ts
+++ b/packages/server/src/skill-reconcile.ts
@@ -43,6 +43,7 @@
import { existsSync, lstatSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import {
+ AGENTS_SKILLS_ROOT,
EDITOR_PROJECT_SKILL_ROOT,
type EditorId,
PROJECT_SKILL_EDITOR_IDS,
@@ -104,7 +105,7 @@ function detectionRoots(): DetectionRoot[] {
}
// The generic broadcast dir is scanned for foreign skills but is not any
// editor's per-editor install root, so it carries no marker host.
- roots.push({ rel: '.agents/skills', editor: null });
+ roots.push({ rel: AGENTS_SKILLS_ROOT, editor: null });
return roots;
}
diff --git a/packages/server/src/skills-list-admission.test.ts b/packages/server/src/skills-list-admission.test.ts
new file mode 100644
index 000000000..8ffe7be9d
--- /dev/null
+++ b/packages/server/src/skills-list-admission.test.ts
@@ -0,0 +1,267 @@
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { afterAll, beforeAll, expect, test } from 'vitest';
+import type { BootedServer } from './boot.ts';
+import { bootCompositionRig } from './composition-rig.test-helper.ts';
+
+/**
+ * A skill the sidebar LISTS but the editor cannot open is the same bug twice:
+ * the doc name the list hands the client is not one the document index holds,
+ * so the tab it opens has nothing behind it, the next page-list sync prunes it,
+ * and the surface falls back to Files. Two independent ways in, both covered
+ * here against a real booted server:
+ *
+ * 1. the skill dir is a SYMLINK, so its docs are indexed once per inode under
+ * the canonical dir they link to, never under the alias;
+ * 2. the skill dir landed on disk AFTER boot without a handler that rebuilds
+ * the content filter's in-place allow-list, so it is not admitted at all.
+ *
+ * The tab-level half of (1) — alias name pruned, canonical name kept, canonical
+ * still classified as a Skills tab — is pinned in the app's
+ * `managed-artifact-doc-name.test.ts`.
+ */
+
+function writeSkill(root: string, rel: string, body: string): void {
+ const dir = join(root, rel);
+ mkdirSync(dir, { recursive: true });
+ const name = rel.split('/').pop();
+ writeFileSync(join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: d\n---\n\n${body}\n`);
+}
+
+interface SkillRow {
+ name: string;
+ scope: string;
+ path: string;
+ canonicalPath?: string;
+}
+
+interface DocRow {
+ kind: string;
+ path?: string;
+ docName?: string;
+ isSymlink?: boolean;
+ canonicalDocName?: string | null;
+}
+
+let tmpRoot: string;
+let contentDir: string;
+let booted: BootedServer;
+
+async function listSkills(): Promise<SkillRow[]> {
+ const res = await fetch(`http://127.0.0.1:${booted.port}/api/skills`);
+ expect(res.status).toBe(200);
+ return ((await res.json()) as { skills: SkillRow[] }).skills;
+}
+
+async function indexedDocs(): Promise<Map<string, DocRow>> {
+ const res = await fetch(`http://127.0.0.1:${booted.port}/api/documents`);
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { documents: DocRow[] };
+ return new Map(
+ body.documents.filter((d) => d.kind === 'document').map((d) => [d.docName ?? '', d]),
+ );
+}
+
+/** The doc name a client opens for an entry — what the app's builder mints. */
+function liveDocName(entry: SkillRow): string {
+ return (entry.canonicalPath ?? entry.path).replace(/\.mdx?$/i, '');
+}
+
+beforeAll(async () => {
+ tmpRoot = await mkdtemp(resolve(tmpdir(), 'ok-skills-admission-'));
+ contentDir = mkdtempSync(resolve(tmpRoot, 'proj-'));
+ // A repo that keeps its bundles in `plugins/<x>/skills/` and symlinks them
+ // into the editor dir agents actually read from.
+ writeSkill(contentDir, 'plugins/ok/skills/linked', '# Linked');
+ mkdirSync(join(contentDir, '.agents/skills'), { recursive: true });
+ symlinkSync(
+ resolve(contentDir, 'plugins/ok/skills/linked'),
+ join(contentDir, '.agents/skills/linked'),
+ 'dir',
+ );
+ writeSkill(contentDir, '.agents/skills/plain', '# Plain');
+ booted = await bootCompositionRig(contentDir);
+}, 60_000);
+
+afterAll(async () => {
+ await booted?.destroy();
+ // `destroy()` stops accepting work but does not join every background flush:
+ // the server keeps writing under `.ok/local/cache/**`, so a plain recursive
+ // delete can walk a directory that is repopulated under it and die on
+ // ENOTEMPTY. Seen on CI (twice, including the retry) while passing locally —
+ // a slower, more contended filesystem widens the window. Retry the unlink,
+ // and never let cleanup of a tmpdir fail the suite: the assertions have
+ // already run, and the OS reaps /tmp regardless.
+ try {
+ await rm(tmpRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+ } catch {
+ // Best-effort.
+ }
+});
+
+test('a symlinked skill dir is reported at BOTH its mount path and its canonical doc', async () => {
+ const linked = (await listSkills()).find((s) => s.name === 'linked');
+ expect(linked).toBeDefined();
+ // `path` still answers "where is this bundle mounted" — install targets,
+ // reveal-in-Finder and host wiring all reason about the editor dir.
+ expect(linked?.path).toBe('.agents/skills/linked/SKILL.md');
+ expect(linked?.canonicalPath).toBe('plugins/ok/skills/linked/SKILL.md');
+});
+
+test('the doc name that mints from the entry is the one the index holds', async () => {
+ const docs = await indexedDocs();
+ const linked = (await listSkills()).find((s) => s.name === 'linked');
+ expect(linked && docs.has(liveDocName(linked))).toBe(true);
+ // The alias name resolves to the SAME inode, which is why it must not be
+ // opened as its own doc: two Y.Docs would fight over one file.
+ expect(docs.get('.agents/skills/linked/SKILL')?.canonicalDocName).toBe(
+ 'plugins/ok/skills/linked/SKILL',
+ );
+ expect(docs.get('plugins/ok/skills/linked/SKILL')?.canonicalDocName).toBeNull();
+});
+
+test('an ordinary in-place skill carries no canonicalPath and opens at its own path', async () => {
+ const plain = (await listSkills()).find((s) => s.name === 'plain');
+ expect(plain?.canonicalPath).toBeUndefined();
+ expect(plain && liveDocName(plain)).toBe('.agents/skills/plain/SKILL');
+ expect((await indexedDocs()).has('.agents/skills/plain/SKILL')).toBe(true);
+});
+
+test('a skill dir written after boot becomes servable via the list, with no restart', async () => {
+ // Written straight to disk — the shape any writer that skips the allow-list
+ // rebuild leaves behind, and what an older build did on every import.
+ writeSkill(contentDir, '.claude/skills/late', '# Late');
+ const docName = '.claude/skills/late/SKILL';
+
+ // It lists immediately (the scan reads disk) but is not admitted as content:
+ // exactly the state a user sees as "the skill is right there and won't open".
+ expect((await indexedDocs()).has(docName)).toBe(false);
+ expect((await listSkills()).some((s) => s.name === 'late')).toBe(true);
+
+ // The heal rides that list call; the rebuild's re-scan lands asynchronously,
+ // so the doc shows up on a later refresh rather than in that response.
+ const deadline = Date.now() + 20_000;
+ let docs = await indexedDocs();
+ while (!docs.has(docName) && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 250));
+ docs = await indexedDocs();
+ }
+ expect(docs.has(docName)).toBe(true);
+ // Admitting a doc must never touch the bytes on disk. The rebuild fans out to
+ // an index prune + re-scan and a derived-scope refresh; a list read is not a
+ // licence for any of them to reach the working tree.
+ expect(existsSync(join(contentDir, '.claude/skills/late/SKILL.md'))).toBe(true);
+ expect(readFileSync(join(contentDir, '.claude/skills/late/SKILL.md'), 'utf-8')).toContain(
+ '# Late',
+ );
+}, 40_000);
+
+test('the skills a list call reports are all still on disk afterwards', async () => {
+ // Blast-radius check for the read-side heal: every listed project bundle must
+ // survive being listed, including one mounted through a symlink.
+ const before = (await listSkills()).filter((s) => s.scope === 'project');
+ await listSkills();
+ await listSkills();
+ for (const s of before) {
+ expect(existsSync(join(contentDir, s.path))).toBe(true);
+ }
+ const after = (await listSkills()).filter((s) => s.scope === 'project').map((s) => s.name);
+ expect(after.sort()).toEqual(before.map((s) => s.name).sort());
+});
+
+/**
+ * A gitignored bundle is listed but deliberately NOT admitted as content (OK
+ * will not index a doc the sync engine could never commit). That is correct,
+ * and it is also the single cause behind "the skill is right there and won't
+ * open": `.claude/*` is a very common rule, so every skill installed into
+ * `.claude/skills/` in such a repo is unopenable. The list has to SAY so, and
+ * the offered fix has to be one git actually honours.
+ */
+test('a gitignored bundle lists as ignored and is not indexed', async () => {
+ writeFileSync(join(contentDir, '.gitignore'), '.claude/*\n');
+ writeSkill(contentDir, '.claude/skills/hidden', '# Hidden');
+ // Both halves of the disagreement, in one place: it lists...
+ const entry = (await listSkills()).find((s) => s.name === 'hidden');
+ expect(entry?.ignored).toBe(true);
+ // ...and it has no doc to open.
+ expect((await indexedDocs()).has('.claude/skills/hidden/SKILL')).toBe(false);
+});
+
+test('an ordinary bundle is not flagged ignored', async () => {
+ const plain = (await listSkills()).find((s) => s.name === 'plain');
+ expect(plain?.ignored).toBeUndefined();
+});
+
+test('track-in-git previews the exact line without touching .gitignore', async () => {
+ const before = readFileSync(join(contentDir, '.gitignore'), 'utf-8');
+ const res = await fetch(`http://127.0.0.1:${booted.port}/api/skill/track-in-git`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ name: 'hidden', scope: 'project' }),
+ });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { line: string; gitignorePath: string; applied: boolean };
+ // The whole skills DIRECTORY: git cannot re-include a file whose parent dir
+ // is excluded, so a per-skill negation would look right and do nothing.
+ expect(body.line).toBe('!/.claude/skills/');
+ expect(body.gitignorePath).toBe('.gitignore');
+ expect(body.applied).toBe(false);
+ expect(readFileSync(join(contentDir, '.gitignore'), 'utf-8')).toBe(before);
+});
+
+test('applying it makes the skill indexed, with no restart', async () => {
+ const res = await fetch(`http://127.0.0.1:${booted.port}/api/skill/track-in-git`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ name: 'hidden', scope: 'project', apply: true }),
+ });
+ expect(res.status).toBe(200);
+ expect((await res.json()) as { applied: boolean }).toMatchObject({ applied: true });
+ expect(readFileSync(join(contentDir, '.gitignore'), 'utf-8')).toContain('!/.claude/skills/');
+
+ const entry = (await listSkills()).find((s) => s.name === 'hidden');
+ expect(entry?.ignored).toBeUndefined();
+
+ const deadline = Date.now() + 20_000;
+ let docs = await indexedDocs();
+ while (!docs.has('.claude/skills/hidden/SKILL') && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 250));
+ docs = await indexedDocs();
+ }
+ expect(docs.has('.claude/skills/hidden/SKILL')).toBe(true);
+}, 40_000);
+
+test('a rule that cannot work is reverted, not left behind', async () => {
+ // `.claude/` excludes the DIRECTORY, so nothing under it can be re-included
+ // from below — the negation is powerless. Writing it anyway would leave the
+ // user with a rule that looks like a fix and a skill that still won't open.
+ writeFileSync(join(contentDir, '.gitignore'), '.codex/\n');
+ writeSkill(contentDir, '.codex/skills/buried', '# Buried');
+ const before = readFileSync(join(contentDir, '.gitignore'), 'utf-8');
+
+ const res = await fetch(`http://127.0.0.1:${booted.port}/api/skill/track-in-git`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ name: 'buried', scope: 'project', apply: true }),
+ });
+ expect(res.status).toBe(409);
+ expect(readFileSync(join(contentDir, '.gitignore'), 'utf-8')).toBe(before);
+});
+
+test('a global skill is refused — it lives outside any repo', async () => {
+ const res = await fetch(`http://127.0.0.1:${booted.port}/api/skill/track-in-git`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ name: 'hidden', scope: 'global' }),
+ });
+ expect(res.status).toBe(400);
+});