Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): rename follows the open doc; lifecycle e2e for the .agents home (#3813)
tim-inkeep285cdcda07ab
diff --git a/.changeset/rename-follows-open-doc.md b/.changeset/rename-follows-open-doc.mdnew file mode 100644index 000000000..eaa069c74--- /dev/null+++ b/.changeset/rename-follows-open-doc.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Renaming an open skill no longer blanks the editor. The tab now follows the rename (sidebar row, address, and open document all update together), read-only plugin and built-in rows can be swept into shift-click and shift-arrow multi-selections without breaking the range walk, and a freshly created or imported skill opens on the first click instead of appearing dead until another skill is clicked. The Delete key (Cmd+Backspace on macOS) now bulk-deletes a multi-selection of skills with a live "Deleting N of M" progress label. Installing from skills.sh reliably lands on the new skill's tab: the sidebar no longer refetches every skill's bundle files after each change (their paths now ride the skills list), and the post-install redirect waits out destination moves instead of opening a document that is about to relocate.diff --git a/packages/app/src/components/ManagedArtifactProperties.tsx b/packages/app/src/components/ManagedArtifactProperties.tsxindex 357955c3b..11aef6a9f 100644--- a/packages/app/src/components/ManagedArtifactProperties.tsx+++ b/packages/app/src/components/ManagedArtifactProperties.tsx@@ -14,7 +14,9 @@ import { SkillProperties } from '@/components/SkillProperties';import { TemplateProperties } from '@/components/TemplateProperties';import { useDocumentContext } from '@/editor/DocumentContext';import { docNameForTabId } from '@/editor/editor-tabs';+import { whenSkillsListContains } from '@/hooks/use-skills';import { hashFromDocName, replaceHashWithoutNavigation } from '@/lib/doc-hash';+import { beginSkillWrite, endSkillWrite } from '@/lib/documents-events';import { moveTemplate } from '@/lib/folder-config-api';import { parseProjectSkillContentDocName, skillLiveDocName } from '@/lib/managed-artifact-doc-name';import { moveSkill } from '@/lib/skills-api';@@ -86,16 +88,27 @@ export function ManagedArtifactProperties({* rename / scope move. Opens the relocated doc (which becomes active) before* closing the old tab, so there's no flash of empty editor in between.*/-export function useManagedArtifactRetarget(): (fromDocName: string, toDocName: string) => void {+export function useManagedArtifactRetarget(): (+ fromDocName: string,+ toDocName: string,+ opts?: {+ /** The source doc was ACTIVE when the operation started. The server's own+ * doc teardown races the HTTP response: on a slow op the close lands+ * first, the tab is already gone by the time this runs, and both live+ * checks below miss - the editor strands empty and the rename looks like+ * it did nothing. The caller snapshots the truth before awaiting. */+ sourceWasActive?: boolean;+ },+) => void {const { openTarget, closeDocument, activeDocName, openTabs } = useDocumentContext();- return (fromDocName, toDocName) => {+ return (fromDocName, toDocName, opts) => {if (fromDocName === toDocName) return;// Open the destination DIRECTLY, not via the hash → resolveNavigationTarget// path: a project skill content doc (`.ok/skills/<name>/SKILL`) resolves through// the page index, which lags a rename/scope-move by the async `files` refetch, so// the hash path would resolve the just-created doc to a read-only asset viewer.const dest = { kind: 'doc', target: toDocName, docName: toDocName } as const;- if (activeDocName === fromDocName) {+ if (activeDocName === fromDocName || opts?.sourceWasActive === true) {// The source is the ACTIVE tab (renaming/moving what you're viewing): morph it// in place. `replace-active` marks the old tab closed-during-restore so the// source doc's STILL-CONNECTED live provider can't RESURRECT it — a plain open +@@ -128,9 +141,38 @@ export function useRenameSkill(): () => Promise<Awaited<ReturnType<typeof moveSkill>>> {const { t } = useLingui();const retarget = useManagedArtifactRetarget();+ const { activeDocName } = useDocumentContext();return async (skill, next) => {- const result = await moveSkill({ scope: skill.scope, fromName: skill.name, toName: next });+ // Snapshot BEFORE the await: the server tears the source doc down during+ // the rename, and when that close outruns the response the live tab state+ // no longer says the user was viewing it.+ // The suffix form only ever names an in-place PROJECT doc, so it is+ // scope-gated: without the gate, renaming a GLOBAL skill while an+ // unrelated same-named PROJECT skill is the active tab would morph that+ // tab onto the global doc.+ const sourceWasActive =+ activeDocName != null &&+ (activeDocName === skillLiveDocName(skill.scope, skill.name) ||+ (skill.scope === 'project' &&+ parseProjectSkillContentDocName(activeDocName) === skill.name));+ // Busy-mark BOTH names for the tab reconciler: right after the rename the+ // skills list is refetching, and a snapshot from before the rename has+ // NEITHER name in its final state — acting on it closed the freshly+ // renamed tab (the rename "did nothing" from the user's chair). Same+ // begin/end discipline as the scope-move flow.+ beginSkillWrite(skill.scope, skill.name);+ beginSkillWrite(skill.scope, next);+ let result: Awaited<ReturnType<typeof moveSkill>>;+ try {+ result = await moveSkill({ scope: skill.scope, fromName: skill.name, toName: next });+ } catch (err) {+ endSkillWrite(skill.scope, skill.name);+ endSkillWrite(skill.scope, next);+ throw err;+ }if (!result.ok) {+ endSkillWrite(skill.scope, skill.name);+ endSkillWrite(skill.scope, next);toast.error(t`Couldn't rename "${skill.name}": ${result.error}`);return result;}@@ -148,7 +190,26 @@ export function useRenameSkill(): (skill.scope === 'project' && result.to !== undefined? `${result.to.split('/').slice(0, -1).join('/')}/${skill.name}/SKILL`: skillLiveDocName(skill.scope, skill.name);- retarget(fromDoc, toDoc);+ try {+ retarget(fromDoc, toDoc, { sourceWasActive });+ } catch (err) {+ console.error('[skill-rename] retarget failed after a successful rename', err);+ }+ // Hold the busy-marks until a skills list CONTAINING the new name has+ // landed. Ending synchronously here is too early: the tab reconciler runs+ // on the NEXT React commit, sees a refetch-in-flight (stale) list without+ // either name un-flagged, and closes the freshly morphed tab - the rename+ // "did nothing" from the user's chair. Bounded so a wedged fetch can't+ // leak the flags (a leaked flag suppresses the reconciler for this skill+ // for the rest of the session).+ // Rides the coalesced shared pipeline - an independent polling loop+ // against /api/skills is the scan-storm shape use-skills exists to+ // prevent (each attempt was an uncoalesced full-roots walk). The waiter+ // resolves on its own timeout too, so the marks always release.+ void whenSkillsListContains(skill.scope, next).then(() => {+ endSkillWrite(skill.scope, skill.name);+ endSkillWrite(skill.scope, next);+ });return result;};}diff --git a/packages/app/src/components/SkillBulkDeleteDialog.tsx b/packages/app/src/components/SkillBulkDeleteDialog.tsxindex 5ecc9dd84..b7d46bad2 100644--- a/packages/app/src/components/SkillBulkDeleteDialog.tsx+++ b/packages/app/src/components/SkillBulkDeleteDialog.tsx@@ -28,11 +28,14 @@ export function SkillBulkDeleteDialog({ skills, onOpenChange, onDeleted }: Propsconst { t } = useLingui();const { closeTabs, openTabs } = useDocumentContext();const [deleting, setDeleting] = useState(false);+ const [progress, setProgress] = useState(0);async function handleDelete(targets: readonly SkillsListEntry[]) {setDeleting(true);+ setProgress(0);let deleted = 0;for (const target of targets) {+ setProgress((n) => n + 1);const result = await deleteSkill(target.scope, target.name, target.hostQualifier);if (!result.ok) {const { error } = result;@@ -63,6 +66,9 @@ export function SkillBulkDeleteDialog({ skills, onOpenChange, onDeleted }: Props<DeleteConfirmationDialogitemName={t`${count} skills`}isSubmitting={deleting}+ // Sequential deletes over a big selection take real time; a bare+ // "Deleting" spinner reads as hung ("it did not delete").+ customConfirmLabelBusy={t`Deleting ${progress} of ${count}`}onDelete={() => handleDelete(skills)}customDescription={t`This permanently removes ${names}. Agents that invoke these skills by name will fail until they're recreated.`}/>diff --git a/packages/app/src/components/SkillEditorActions.tsx b/packages/app/src/components/SkillEditorActions.tsxindex 2d48d68be..9efcb6dd4 100644--- a/packages/app/src/components/SkillEditorActions.tsx+++ b/packages/app/src/components/SkillEditorActions.tsx@@ -126,7 +126,15 @@ export function SkillEditorActions({that refetches while folders are being rewritten, so a menu left openshows a half-converted state settling. It also cannot be reopenedmid-run — the trigger is disabled while `installing`. */}- <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>+ <DropdownMenu+ // modal=false: scope moves from this menu retarget the tab it lives+ // on, unmounting the menu mid-close — a modal menu's body pointer-lock+ // leaks on that abrupt unmount and the app goes click-dead until+ // reload. Same class as the preview install menu.+ modal={false}+ open={menuOpen}+ onOpenChange={setMenuOpen}+ ><DropdownMenuTrigger asChild>{/* Status pill + install menu in one button: the label is the state,the chevron opens the menu. */}diff --git a/packages/app/src/components/SkillPreviewTab.redirect.dom.test.tsx b/packages/app/src/components/SkillPreviewTab.redirect.dom.test.tsxindex 70863b926..aa4b64abf 100644--- a/packages/app/src/components/SkillPreviewTab.redirect.dom.test.tsx+++ b/packages/app/src/components/SkillPreviewTab.redirect.dom.test.tsx@@ -1,4 +1,4 @@-import { render, screen } from '@testing-library/react';+import { render, screen, waitFor } from '@testing-library/react';import { type ReactNode, useEffect } from 'react';import { describe, expect, test, vi } from 'vitest';@@ -45,6 +45,9 @@ vi.doMock('@/lib/skill-scope', () => ({}));vi.doMock('@/lib/skills-api', () => ({fetchSkillDetail: vi.fn(async () => ({ ok: false, error: 'n/a' })),+ // The post-toggle redirect re-resolves the bundle's CURRENT location with+ // this per-skill read (an install can relocate a just-imported bundle).+ getSkillCurrentPath: vi.fn(async () => '.claude/skills/grill-me/SKILL.md'),placeSkill: vi.fn(),discoverSkillsInSource: vi.fn(async () => ({ ok: false, error: 'n/a' })),importSkillsBulk: vi.fn(),@@ -111,25 +114,197 @@ describe('SkillPreviewTab per-agent install redirect', () => {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,- });+ // Host toggles ran, so the redirect re-resolves the current location+ // (async) before opening.+ await waitFor(() =>+ expect(openSkill).toHaveBeenCalledWith('project', 'grill-me', {+ path: '.claude/skills/grill-me/SKILL.md',+ 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('fires off the import result even while the skills list still lags', async () => {+ // The redirect no longer waits for the skills list: on large content+ // roots the list lags an install by seconds, and gating on it made the+ // preview sit un-redirected ("install didn't open the skill"). The open+ // resolves by the import's own path report, so a lagging list is safe.+ 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');+ await waitFor(() =>+ expect(lateOpen).toHaveBeenCalledWith('project', 'grill-me', {+ path: '.claude/skills/grill-me/SKILL.md',+ replaceActive: true,+ replaceHistory: true,+ }),+ );+ });++ test('does not fire before any import has landed', async () => {+ vi.resetModules();+ const lateOpen = vi.fn();+ vi.doMock('@/hooks/use-open-skill', () => ({ useOpenSkill: () => lateOpen }));+ vi.doMock('@/hooks/use-skills', () => ({ useSkills: () => ({ status: 'loading' }) }));+ vi.doMock('@/hooks/use-explore-preview-install', () => ({+ useExplorePreviewInstall: () => ({+ scope: 'project',+ importedScope: null,+ importedName: null,+ importedPath: null,+ setScope: vi.fn(),+ scopeLocked: false,+ importNow: vi.fn(),+ toggles: {+ hostSet: new Set<string>(),+ installed: false,+ installing: false,+ toggleEditor: vi.fn(),+ installAll: vi.fn(),+ linkMode: false,+ setLinkMode: vi.fn(),+ setSource: vi.fn(),+ placeAt: vi.fn(),+ },+ }),+ }));+ 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();});- 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.+ test('holds the redirect while an install is still in flight', async () => {+ // An install toggle can RELOCATE the just-imported bundle (set-exact+ // fan-out picks the canonical dir). A redirect fired mid-install opens a+ // doc whose dir is about to move; the server auth-rejects it and the+ // cleanup closes the tab, landing the user on Home with nothing open.vi.resetModules();const lateOpen = vi.fn();vi.doMock('@/hooks/use-open-skill', () => ({ useOpenSkill: () => lateOpen }));vi.doMock('@/hooks/use-skills', () => ({ useSkills: () => ({ status: 'loading' }) }));+ vi.doMock('@/hooks/use-explore-preview-install', () => ({+ useExplorePreviewInstall: () => ({+ scope: 'project',+ importedScope: 'project',+ importedName: 'grill-me',+ importedPath: '.agents/skills/grill-me/SKILL.md',+ setScope: vi.fn(),+ scopeLocked: true,+ importNow: vi.fn(),+ toggles: {+ hostSet: new Set(['claude']),+ installed: true,+ installing: true,+ toggleEditor: vi.fn(),+ installAll: vi.fn(),+ linkMode: false,+ setLinkMode: vi.fn(),+ setSource: vi.fn(),+ placeAt: vi.fn(),+ },+ }),+ }));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();});++ test('re-resolves the current path once an install toggle ran', async () => {+ // The import reported where the bundle FIRST landed; the install moved it.+ // Opening by that stale path auth-rejects server-side and the tab+ // self-closes — so with any host toggled, the open re-resolves the+ // bundle's CURRENT location (per-skill detail read, never the laggy+ // skills list) and only falls back to the import-time path if that fails.+ vi.resetModules();+ const lateOpen = vi.fn();+ vi.doMock('@/hooks/use-open-skill', () => ({ useOpenSkill: () => lateOpen }));+ vi.doMock('@/hooks/use-skills', () => ({ useSkills: () => ({ status: 'loading' }) }));+ vi.doMock('@/hooks/use-explore-preview-install', () => ({+ useExplorePreviewInstall: () => ({+ scope: 'project',+ importedScope: 'project',+ importedName: 'grill-me',+ importedPath: '.agents/skills/grill-me/SKILL.md',+ 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: Tab } = await import('./SkillPreviewTab');+ render(<Tab flavor="explore" source="mattpocock/skills" name="grill-me" />);+ await screen.findByTestId('preview-body');+ await waitFor(() =>+ expect(lateOpen).toHaveBeenCalledWith('project', 'grill-me', {+ path: '.claude/skills/grill-me/SKILL.md',+ replaceActive: true,+ replaceHistory: true,+ }),+ );+ expect(lateOpen).not.toHaveBeenCalledWith(+ 'project',+ 'grill-me',+ expect.objectContaining({ path: '.agents/skills/grill-me/SKILL.md' }),+ );+ });++ test('the install destination menu never pointer-locks the page', async () => {+ // The menu's owner tab is REPLACED by the post-install auto-open, which+ // unmounts the menu mid-close. A modal Radix menu sets+ // `body{pointer-events:none}` while open and that abrupt unmount skips the+ // unlock — the whole app then ignores every click until reload (caught+ // live). Non-modal never locks, so this asserts the lock never appears.+ vi.resetModules();+ vi.doMock('@/hooks/use-open-skill', () => ({ useOpenSkill: () => vi.fn() }));+ vi.doMock('@/hooks/use-skills', () => ({ useSkills: () => ({ status: 'loading' }) }));+ vi.doMock('@/hooks/use-explore-preview-install', () => ({+ useExplorePreviewInstall: () => ({+ scope: 'project',+ importedScope: null,+ importedName: null,+ importedPath: null,+ setScope: vi.fn(),+ scopeLocked: false,+ importNow: vi.fn(),+ toggles: {+ hostSet: new Set<string>(),+ installed: false,+ installing: false,+ toggleEditor: vi.fn(),+ installAll: vi.fn(),+ linkMode: false,+ setLinkMode: vi.fn(),+ setSource: vi.fn(),+ placeAt: vi.fn(),+ },+ }),+ }));+ const { SkillPreviewTab: Tab } = await import('./SkillPreviewTab');+ const { fireEvent } = await import('@testing-library/react');+ render(<Tab flavor="explore" source="mattpocock/skills" name="grill-me" />);+ await screen.findByTestId('preview-body');+ const trigger = screen.getByRole('button', { name: /install/i });+ fireEvent.pointerDown(trigger);+ fireEvent.click(trigger);+ await waitFor(() => expect(document.body.style.pointerEvents).not.toBe('none'));+ });});diff --git a/packages/app/src/components/SkillPreviewTab.tsx b/packages/app/src/components/SkillPreviewTab.tsxindex a9e1971dd..754f1bd62 100644--- a/packages/app/src/components/SkillPreviewTab.tsx+++ b/packages/app/src/components/SkillPreviewTab.tsx@@ -34,7 +34,7 @@ import { hashFromSkillFile, hashFromSkillPreview, type SkillPreviewFlavor } fromimport { skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';import { openManagedArtifactTab } from '@/lib/open-managed-artifact-tab';import { useSkillScopeLabels } from '@/lib/skill-scope';-import { discoverSkillsInSource, fetchSkillDetail } from '@/lib/skills-api';+import { discoverSkillsInSource, fetchSkillDetail, getSkillCurrentPath } from '@/lib/skills-api';interface Props {/** `explore` = a skills.sh catalog entry; `detected` = a skill found in another@@ -229,11 +229,14 @@ export function SkillPreviewTab({// 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.+ // Redirect as soon as the import/install REPORTS where it landed. This was+ // once gated on the skill appearing in the skills list, but that list lags+ // an install by a full refetch - seconds on a large content root - so the+ // preview sat un-redirected long enough to read as "install didn't open the+ // skill". `useOpenSkill` now resolves a not-yet-listed skill itself (fresh+ // fetch for project, direct managed doc for global) and busy-marks it+ // against the tab reconciler, so the early fire no longer burns the+ // fire-once attempt on a lookup that cannot succeed.//// Still gated on `landedName`, so previewing a marketplace skill whose name// already exists locally does not bounce you straight out of the preview.@@ -249,14 +252,21 @@ export function SkillPreviewTab({linked && allSkills.status === 'ready'? allSkills.data.find((sk) => sk.scope === targetScope && sk.name === name): undefined;- 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) && landedEntry !== undefined;+ (flavor === 'explore' || foreign || pluginInfo !== null) && landedName !== null;useEffect(() => {- if (!importedNow || redirectedRef.current || installMenuOpen) return;+ // `installing` holds the redirect like the open menu does: an install+ // toggle can RELOCATE the just-imported bundle (set-exact fan-out picks+ // the canonical dir), and a redirect fired mid-install opens a doc whose+ // dir is about to move — the server auth-rejects it and the cleanup+ // closes the tab, landing the user on Home with nothing open.+ if (+ !importedNow ||+ redirectedRef.current ||+ installMenuOpen ||+ previewInstall.toggles.installing+ )+ return;redirectedRef.current = true;// Capture THIS preview's tab id(s) before opening, then close them after.// `replaceActive` only opens with preview DISPOSITION — it swaps whatever@@ -268,15 +278,47 @@ export function SkillPreviewTab({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,- });- // After the open, so a failure to resolve can never leave zero tabs.- for (const id of stalePreviewTabIds) closeTab(id);- }, [importedNow, installMenuOpen, landedScope, landedName, openSkill, openTabs, name, closeTab]);+ const openLanded = (path: string | undefined) => {+ openSkill(landedScope, landedName as string, {+ ...(path !== undefined ? { path } : {}),+ 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,+ });+ // After the open, so a failure to resolve can never leave zero tabs.+ for (const id of stalePreviewTabIds) closeTab(id);+ };+ if (previewInstall.toggles.hostSet.size === 0) {+ // The import's own path report: the open resolves with zero+ // skills-list round-trips, which on a large content root is the+ // difference between instant and seconds.+ openLanded(previewInstall.importedPath ?? undefined);+ } else {+ // An install toggle can RELOCATE the just-imported bundle (set-exact+ // fan-out picks the canonical dir), so the import-time path report may+ // now point at a dir that no longer exists — opening it auth-rejects+ // server-side and the tab self-closes to Home. Re-resolve the current+ // location with the per-skill detail read (fast; the skills LIST is+ // the read that lags by seconds on large roots), falling back to the+ // import report if the read fails.+ void getSkillCurrentPath(landedScope, landedName as string).then((current) =>+ openLanded(current ?? previewInstall.importedPath ?? undefined),+ );+ }+ }, [+ importedNow,+ installMenuOpen,+ landedScope,+ landedName,+ openSkill,+ openTabs,+ name,+ closeTab,+ previewInstall.importedPath,+ previewInstall.toggles.installing,+ previewInstall.toggles.hostSet,+ ]);// 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;@@ -400,7 +442,17 @@ export function SkillPreviewTab({// Explore installs and plugin copies go through the SAME destination// menu. The first destination choice performs the import, so "Edit a// copy" never silently defaults to `.agents` or any other root.- <DropdownMenu onOpenChange={setInstallMenuOpen}>+ <DropdownMenu+ // modal=false: the first destination pick triggers the import whose+ // auto-open REPLACES this tab, unmounting the menu mid-close. A modal+ // menu locks `body` with pointer-events:none while open, and that+ // abrupt unmount skips the unlock — the whole app then ignores every+ // click until reload (caught live: orphaned open menu + body stuck at+ // pointer-events:none). Non-modal never locks, so there is nothing to+ // leak; outside-click and Escape still dismiss.+ modal={false}+ onOpenChange={setInstallMenuOpen}+ ><DropdownMenuTrigger asChild><Buttonsize="sm"diff --git a/packages/app/src/components/SkillsSidebarSection.tsx b/packages/app/src/components/SkillsSidebarSection.tsxindex ce02e38e6..8769b1a05 100644--- a/packages/app/src/components/SkillsSidebarSection.tsx+++ b/packages/app/src/components/SkillsSidebarSection.tsx@@ -42,12 +42,7 @@ import {} 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 { fetchSkillPreview, listDetectedSkills } 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) —@@ -192,58 +187,15 @@ export function SkillsSidebarSection({ dockExpanded = false }: { dockExpanded?:const skillRowKey = (s: SkillsListEntry): string =>`${s.scope}:${s.name}:${hostQualifierOf(s) ?? ''}`;- // Eager-load every managed skill's bundle files (both scopes) into one map.- // Keyed on the full row set so it refetches only on add/remove, not every render.- const filesKey = skills.map(skillRowKey).join('|');- const [filesByKey, setFilesByKey] = useState<Record<string, readonly SkillBundledFile[]>>({});- // True while the N-per-skill bundle-file fetch is in flight. Drives the section- // loading indicator so a folder with many skills doesn't look broken/empty while- // it fetches. Self-scaling: barely a flash on a small KB, visible when- // there are many skills to load.- const [bundleLoading, setBundleLoading] = useState(false);- useEffect(() => {- // Only the Skills tree consumes filesByKey, so skip the N fetches + the- // skillsChanged subscription until the dock is expanded. Radix unmounts a- // closed `CollapsibleContent` (no `forceMount`), so today this mostly covers- // the closing transition — it is also what keeps a future `forceMount` from- // silently reviving a fetch per skill on every collapsed sidebar.- if (!dockExpanded) return;- let alive = true;- const entries = filesKey ? filesKey.split('|') : [];- const load = () => {- setBundleLoading(true);- void Promise.all(- entries.map((e) => {- const [scope, name, host] = e.split(':') as [SkillScope, string, string];- return getSkillBundledFiles(scope, name, host || undefined).then((r) => {- // A non-OK fetch yields an empty file list, indistinguishable from a- // skill that genuinely has none — leave a diagnostic so a 500/timeout- // doesn't vanish silently.- if (!r.ok)- console.warn(`[skills-sidebar] failed to load bundle files for ${e}:`, r.error);- return [e, r.ok ? r.files : []] as const;- });- }),- )- .then((loaded) => {- if (alive) setFilesByKey(Object.fromEntries(loaded));- })- .catch((err) => {- // getSkillBundledFiles catches its own fetch rejections, so this only- // fires on an unexpected throw — surface it rather than leaving state stale.- console.error('[skills-sidebar] unexpected error loading skill bundle files', err);- })- .finally(() => {- if (alive) setBundleLoading(false);- });- };- load();- const unsub = subscribeToSkillsChanged(load);- return () => {- alive = false;- unsub();- };- }, [filesKey, dockExpanded]);+ // Each skill's bundle-file paths ride the list entries themselves+ // (`filePaths`, paths only) — derived here, no fetching. This replaced an+ // N-per-skill `GET /api/skill` fan-out that re-fired on every skills-changed+ // signal: on an install with ~90 skills the fan-out saturated the browser's+ // request pool for seconds and queued imports and opens behind it, which+ // read as "import worked but the skill won't open".+ const filesByKey: Record<string, readonly { path: string }[]> = Object.fromEntries(+ skills.map((s) => [skillRowKey(s), (s.filePaths ?? []).map((path) => ({ path }))]),+ );// --- scroll preservation across tree remounts ---//@@ -537,9 +489,7 @@ export function SkillsSidebarSection({ dockExpanded = false }: { dockExpanded?:// remounts / collapses the tree).const stateKey = `${skills.map((s) => `${s.installed ? 1 : 0}`).join('')}|d${detectedByPrefix.size}`;- // First list load, or the N-per-skill bundle-file fetch in flight — surface it- // so a folder with many skills reads as "loading", not broken/empty.- const skillsLoading = state.status === 'loading' || bundleLoading;+ const skillsLoading = state.status === 'loading';// Pins are part of the key: the sort comparator and the pin-row CSS are both// baked at tree creation, and an UNGROUPED pin changes no paths — without// this, pinning (or the async config load delivering existing pins) neitherdiff --git a/packages/app/src/components/SkillsTree.tsx b/packages/app/src/components/SkillsTree.tsxindex 991573b87..91d01cff0 100644--- a/packages/app/src/components/SkillsTree.tsx+++ b/packages/app/src/components/SkillsTree.tsx@@ -86,7 +86,7 @@ import { asDirectoryHandle } from '@/components/use-selection-mirror';import { useOpenSkill } from '@/hooks/use-open-skill';import { openExternalUrl } from '@/lib/external-link';import { scheduleClipboardWrite } from '@/lib/share/clipboard-adapter';-import { groupUpdatableSkills } from '@/lib/skill-group-update';+import { groupDeletableSkills, groupUpdatableSkills } from '@/lib/skill-group-update';import {bucketForDetected,bucketForSkill,@@ -1048,7 +1048,29 @@ export function SkillsTree({return out.length > 0 ? out : skillRowOrderRef.current;};const onKeyDown = (e: Event) => {- if (!(e instanceof KeyboardEvent) || !e.shiftKey) return;+ if (!(e instanceof KeyboardEvent)) return;+ // Delete/⌘Backspace on a live multi-selection opens the bulk-delete+ // confirm — same key semantics as the Files tree, so the two sidebars+ // don't teach conflicting muscle memory.+ const lowerKey = e.key.toLowerCase();+ const isDeleteKey =+ !e.altKey &&+ !e.shiftKey &&+ ((e.metaKey && !e.ctrlKey && lowerKey === 'backspace') ||+ (!e.metaKey && !e.ctrlKey && lowerKey === 'delete'));+ if (isDeleteKey && multiSelectedRef.current.size > 0) {+ const del = e.target as HTMLElement | null;+ if (del?.closest?.('[contenteditable], input, textarea, [role="textbox"]')) return;+ const entries = [...multiSelectedRef.current]+ .map((p) => injectInputsRef.current.skillFor(parseTreePath(p, groupByPrefixRef.current)))+ .filter((s): s is SkillsListEntry => s !== undefined);+ if (entries.length === 0) return;+ e.preventDefault();+ e.stopImmediatePropagation();+ setBulkDelete(entries);+ return;+ }+ if (!e.shiftKey) return;if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;// Window-level (the swallowed shift-click leaves DOM focus outside the// tree). Act when a multi-selection is live OR the tree itself holds@@ -1701,7 +1723,17 @@ export function SkillsTree({node.group !== undefined? groupByPrefix.get(`${node.scopeLabel}/${node.group}`): undefined;- if (members.length === 0 && !bucket) return null;+ // The group-row bulk delete: every non-managed member, source or+ // not (plugin-served groups excluded inside the helper).+ const deletable =+ node.group !== undefined+ ? groupDeletableSkills({+ groupPrefix: `${node.scopeLabel}/${node.group}`,+ bucket,+ skillByPrefix,+ })+ : [];+ if (members.length === 0 && deletable.length === 0 && !bucket) return null;const sourceLabel = node.group ?? '';// The group row speaks for the upstream: name what it is, link to// it, and (for tracked members) refresh from it. Same shape as the@@ -1751,6 +1783,18 @@ export function SkillsTree({</DropdownMenuItem></>) : null}+ {deletable.length > 0 ? (+ <>+ {members.length === 0 && bucket ? <DropdownMenuSeparator /> : null}+ <DropdownMenuItem+ variant="destructive"+ onSelect={() => setBulkDelete(deletable)}+ >+ <Trash2 aria-hidden />+ <Trans>Delete {deletable.length} skills</Trans>+ </DropdownMenuItem>+ </>+ ) : null}</>);} else if (node.skillDisplay === undefined) {diff --git a/packages/app/src/hooks/use-explore-preview-install.ts b/packages/app/src/hooks/use-explore-preview-install.tsindex 2c6a739fb..5fd7b10e5 100644--- a/packages/app/src/hooks/use-explore-preview-install.ts+++ b/packages/app/src/hooks/use-explore-preview-install.ts@@ -41,6 +41,9 @@ 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;+ /** Home-relative SKILL.md path the import reported - lets the redirect open+ * the landed skill without waiting on a skills-list refetch. */+ importedPath: 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@@ -63,6 +66,7 @@ export function useExplorePreviewInstall({return list ? new Set<string>(list) : null;};const [importedName, setImportedName] = useState<string | null>(null);+ const [importedPath, setImportedPath] = 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);@@ -97,6 +101,7 @@ export function useExplorePreviewInstall({importedScopeRef.current = importScope;setImportedScope(importScope);setImportedName(res.name);+ setImportedPath(res.path ?? null);return res.name;});importPromiseRef.current = pending;@@ -218,6 +223,7 @@ export function useExplorePreviewInstall({setScope,scopeLocked: importedName !== null || busy,importedName,+ importedPath,importedScope,importNow: ensureImported,toggles,diff --git a/packages/app/src/hooks/use-open-skill.ts b/packages/app/src/hooks/use-open-skill.tsindex 418cc74d7..f03f260c8 100644--- a/packages/app/src/hooks/use-open-skill.ts+++ b/packages/app/src/hooks/use-open-skill.ts@@ -2,12 +2,13 @@ import type { SkillScope } from '@inkeep/open-knowledge-core';import { t } from '@lingui/core/macro';import { toast } from 'sonner';import { useDocumentContext } from '@/editor/DocumentContext';-import { useSkills } from '@/hooks/use-skills';+import { useSkills, whenSkillsListContains } from '@/hooks/use-skills';import {hashFromDocName,pushHashWithoutNavigation,replaceHashWithoutNavigation,} from '@/lib/doc-hash';+import { beginSkillWrite, endSkillWrite } from '@/lib/documents-events';import { skillEntryLiveDocName, skillLiveDocName } from '@/lib/managed-artifact-doc-name';import { openSkillPreviewTab } from '@/lib/open-managed-artifact-tab';import { requestSkillTrackPrompt } from '@/lib/skill-track-prompt-store';@@ -47,6 +48,20 @@ export function useOpenSkill(): (const skillsState = useSkills();return (scope, name, opts) => {const open = (docName: string) => {+ // A just-created/imported/installed skill can be opened BEFORE the+ // skills list refetch lands. The tab reconciler closes skill tabs whose+ // skill is absent from the list, and a stale snapshot doesn't have this+ // one yet - which closed the fresh tab and made create/install look+ // like they never opened anything. Busy-mark it until a list containing+ // it lands (the waiter resolves on timeout too, so the mark always+ // releases).+ const listed =+ skillsState.status === 'ready' &&+ skillsState.data.some((sk) => sk.scope === scope && sk.name === name);+ if (!listed) {+ beginSkillWrite(scope, name);+ void whenSkillsListContains(scope, name).then(() => endSkillWrite(scope, name));+ }// `replace-active` swaps the currently-active tab in place (e.g. transition an// explore PREVIEW tab into the real skill after install) — one tab, no separate// close, so nothing can resurrect the old preview.diff --git a/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts b/packages/app/src/hooks/use-reconcile-skill-tabs.test.tsindex 280cdd04f..32a3e9c3c 100644--- a/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts+++ b/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts@@ -325,3 +325,54 @@ describe('scope-move window', () => {]);});});++describe('computeSkillTabReconcile round-trip (project -> global -> project)', () => {+ // The field failure this pins: move a skill out and back in one session and+ // the row went dead. Each hop must be a RETARGET, never a close, and the+ // final state must be a no-op against the tab that followed the skill home.+ test('outbound hop retargets the open tab to the global doc', () => {+ const actions = computeSkillTabReconcile(+ ['.agents/skills/demo/SKILL'],+ [{ scope: 'global', name: 'demo', path: '.agents/skills/demo/SKILL.md' }],+ );+ expect(actions).toHaveLength(1);+ expect(actions[0]).toMatchObject({+ kind: 'retarget',+ fromDocName: '.agents/skills/demo/SKILL',+ });+ });++ test('return hop retargets the global tab back to the project doc', () => {+ const actions = computeSkillTabReconcile(+ ['__skill__/global/demo'],+ [{ scope: 'project', name: 'demo', path: '.agents/skills/demo/SKILL.md' }],+ );+ expect(actions).toHaveLength(1);+ expect(actions[0]).toMatchObject({+ kind: 'retarget',+ fromDocName: '__skill__/global/demo',+ toDocName: '.agents/skills/demo/SKILL',+ });+ });++ test('after the return hop settles, the followed tab is untouched — never closed', () => {+ const actions = computeSkillTabReconcile(+ ['.agents/skills/demo/SKILL'],+ [{ scope: 'project', name: 'demo', path: '.agents/skills/demo/SKILL.md' }],+ );+ expect(actions).toEqual([]);+ });++ test('a mid-flight snapshot with the skill at NEITHER scope defers while a write is pending', () => {+ // Between the delete half and the create half of a move, a stale list has+ // the skill nowhere. With the write marked pending the tab must survive;+ // closing here is how "moved it and now it is gone" happens.+ const actions = computeSkillTabReconcile(['.agents/skills/demo/SKILL'], [], () => true);+ expect(actions).toEqual([]);+ });++ test('the same mid-flight snapshot with NO pending write closes (delete semantics preserved)', () => {+ const actions = computeSkillTabReconcile(['.agents/skills/demo/SKILL'], [], () => false);+ expect(actions).toEqual([{ kind: 'close', docName: '.agents/skills/demo/SKILL' }]);+ });+});diff --git a/packages/app/src/hooks/use-rename-skill.dom.test.tsx b/packages/app/src/hooks/use-rename-skill.dom.test.tsxnew file mode 100644index 000000000..ce5ef8b13--- /dev/null+++ b/packages/app/src/hooks/use-rename-skill.dom.test.tsx@@ -0,0 +1,102 @@+import { renderHook, waitFor } from '@testing-library/react';+import { describe, expect, test, vi } from 'vitest';++/**+ * The rename flow busy-marks BOTH names for the tab reconciler and must+ * release them on EVERY path — a leaked mark suppresses the reconciler for+ * that skill for the rest of the session (module state only a reload clears).+ * Mirrors the sibling `use-move-skill-scope.dom.test.tsx`, which pins the same+ * always-released contract for the scope-move flow.+ */+const openTarget = vi.fn();+const closeDocument = vi.fn();+vi.doMock('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({+ openTarget,+ closeDocument,+ activeDocName: '.claude/skills/old-name/SKILL',+ openTabs: ['.claude/skills/old-name/SKILL'],+ }),+}));+const beginSkillWrite = vi.fn();+const endSkillWrite = vi.fn();+vi.doMock('@/lib/documents-events', () => ({ beginSkillWrite, endSkillWrite }));+const moveSkill = vi.fn();+vi.doMock('@/lib/skills-api', () => ({ moveSkill }));+const whenSkillsListContains = vi.fn(() => Promise.resolve());+vi.doMock('@/hooks/use-skills', () => ({+ useSkills: () => ({ status: 'loading' }),+ whenSkillsListContains,+}));+vi.doMock('@/lib/skill-track-prompt-store', () => ({ requestSkillTrackPrompt: vi.fn() }));+vi.doMock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));++const { useRenameSkill } = await import('@/components/ManagedArtifactProperties');++function resetSpies() {+ beginSkillWrite.mockClear();+ endSkillWrite.mockClear();+ openTarget.mockClear();+ whenSkillsListContains.mockClear();+ moveSkill.mockReset();+}++describe('useRenameSkill busy-mark bracketing', () => {+ test('a failed rename (ok: false) releases both marks immediately', async () => {+ resetSpies();+ moveSkill.mockResolvedValue({ ok: false, error: 'nope' });+ const { result } = renderHook(() => useRenameSkill());++ await result.current({ scope: 'project', name: 'old-name' }, 'new-name');++ expect(beginSkillWrite.mock.calls).toEqual([+ ['project', 'old-name'],+ ['project', 'new-name'],+ ]);+ expect(endSkillWrite.mock.calls).toEqual(+ expect.arrayContaining([+ ['project', 'old-name'],+ ['project', 'new-name'],+ ]),+ );+ expect(openTarget).not.toHaveBeenCalled();+ });++ test('a rejected rename releases both marks and rethrows', async () => {+ resetSpies();+ moveSkill.mockRejectedValue(new Error('network down'));+ const { result } = renderHook(() => useRenameSkill());++ await expect(+ result.current({ scope: 'project', name: 'old-name' }, 'new-name'),+ ).rejects.toThrow('network down');+ expect(endSkillWrite.mock.calls).toEqual(+ expect.arrayContaining([+ ['project', 'old-name'],+ ['project', 'new-name'],+ ]),+ );+ });++ test('a retarget throw after a successful rename still releases both marks', async () => {+ resetSpies();+ moveSkill.mockResolvedValue({ ok: true, committed: false, to: '.claude/skills/new-name' });+ openTarget.mockImplementation(() => {+ throw new Error('retarget boom');+ });+ const { result } = renderHook(() => useRenameSkill());++ const out = await result.current({ scope: 'project', name: 'old-name' }, 'new-name');+ expect(out.ok).toBe(true);+ // Release rides the list-confirmation waiter (mocked resolved), so flush it.+ await waitFor(() => {+ expect(endSkillWrite.mock.calls).toEqual(+ expect.arrayContaining([+ ['project', 'old-name'],+ ['project', 'new-name'],+ ]),+ );+ });+ expect(whenSkillsListContains).toHaveBeenCalledWith('project', 'new-name');+ });+});diff --git a/packages/app/src/hooks/use-skills.ts b/packages/app/src/hooks/use-skills.tsindex cfa5c0748..6fc128a6a 100644--- a/packages/app/src/hooks/use-skills.ts+++ b/packages/app/src/hooks/use-skills.ts@@ -131,6 +131,44 @@ function fetchSkillsShared(): Promise<unknown> {return pending;}+/**+ * Resolve once the SHARED skills cache contains `(scope, name)`, or after+ * `timeoutMs`. Reads only in-memory state fed by the coalesced pipeline and+ * kicks at most the single-flight shared fetch - it NEVER issues its own scan,+ * because `/api/skills` is the stall-prone full-roots walk and an independent+ * polling loop against it is the request-storm shape this module exists to+ * prevent. The cache is written by mounted `useSkills` consumers; with none+ * mounted the wait simply times out, which callers must treat as "release your+ * guard anyway".+ */+export function whenSkillsListContains(+ scope: SkillsListEntry['scope'],+ name: string,+ timeoutMs = 15_000,+): Promise<void> {+ const hit = () => lastKnownSkills?.some((s) => s.scope === scope && s.name === name) === true;+ if (hit()) return Promise.resolve();+ void fetchSkillsShared().catch(() => {});+ return new Promise((resolve) => {+ const deadline = Date.now() + timeoutMs;+ const settle = () => {+ clearInterval(timer);+ unsub();+ resolve();+ };+ const timer = setInterval(() => {+ if (hit() || Date.now() >= deadline) settle();+ }, 250);+ // A skills-changed signal means a write landed; re-kick the COALESCED+ // fetch (free when one is already in flight) so the cache converges even+ // between the interval ticks.+ const unsub = subscribeToSkillsChanged(() => {+ void fetchSkillsShared().catch(() => {});+ if (hit()) settle();+ });+ });+}+export function useSkills(options?: { enabled?: boolean }): AsyncState<readonly SkillsListEntry[]> {// `enabled: false` keeps the hook mounted (and subscribed) but skips the// `/api/skills` fetch — for consumers that only need the list under adiff --git a/packages/app/src/lib/documents-events.ts b/packages/app/src/lib/documents-events.tsindex ebb8a001c..e3a3d55ce 100644--- a/packages/app/src/lib/documents-events.ts+++ b/packages/app/src/lib/documents-events.ts@@ -197,16 +197,26 @@ export function endOptimisticSkillMove(fromScope: SkillScope, name: string): voi// 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>();+// Refcounted, not a plain set: overlapping operations can hold the same key+// (rename a->b then b->a inside the first release window), and a flat set+// would let the FIRST releaser clear a mark the second operation still+// relies on.+const pendingSkillWrites = new Map<string, number>();/** 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));+ const key = movingSkillKey(scope, name);+ pendingSkillWrites.set(key, (pendingSkillWrites.get(key) ?? 0) + 1);emitSkillsChanged();}export function endSkillWrite(scope: SkillScope, name: string): void {- if (pendingSkillWrites.delete(movingSkillKey(scope, name))) emitSkillsChanged();+ const key = movingSkillKey(scope, name);+ const count = pendingSkillWrites.get(key);+ if (count === undefined) return;+ if (count <= 1) pendingSkillWrites.delete(key);+ else pendingSkillWrites.set(key, count - 1);+ emitSkillsChanged();}export function isSkillWritePending(scope: SkillScope, name: string): boolean {@@ -223,7 +233,7 @@ export function isSkillWritePending(scope: SkillScope, name: string): boolean {* deferred tab-close into one that never happened.*/export function pendingSkillWritesKey(): string {- return [...pendingSkillWrites].sort().join('\u0001');+ return [...pendingSkillWrites.keys()].sort().join('\u0001');}/**diff --git a/packages/app/src/lib/skill-group-update.test.ts b/packages/app/src/lib/skill-group-update.test.tsindex c5b7bfd84..128302ece 100644--- a/packages/app/src/lib/skill-group-update.test.ts+++ b/packages/app/src/lib/skill-group-update.test.ts@@ -1,6 +1,6 @@import type { SkillsListEntry } from '@inkeep/open-knowledge-core';import { describe, expect, it } from 'vitest';-import { groupUpdatableSkills } from './skill-group-update';+import { groupDeletableSkills, groupUpdatableSkills } from './skill-group-update';import type { ProvenanceBucket } from './skill-provenance-bucket';function skill(name: string, source?: string): SkillsListEntry {@@ -103,3 +103,56 @@ describe('groupUpdatableSkills', () => {).toEqual([]);});});++describe('groupDeletableSkills', () => {+ it('includes every non-managed member, recorded source or not', () => {+ const map = new Map([+ [`${GROUP}/a`, skill('a', 'inkeep/open-knowledge-skills')],+ [`${GROUP}/b`, skill('b')],+ [`${GROUP}/c`, skill('c', 'adopt:claude')],+ ]);+ const members = groupDeletableSkills({+ groupPrefix: GROUP,+ bucket: sourceBucket,+ skillByPrefix: map,+ });+ expect(members.map((m) => m.name).sort()).toEqual(['a', 'b', 'c']);+ });++ it('excludes managed built-ins', () => {+ const managed = { ...skill('builtin'), managed: true } as SkillsListEntry;+ const map = new Map([+ [`${GROUP}/builtin`, managed],+ [`${GROUP}/plain`, skill('plain')],+ ]);+ const members = groupDeletableSkills({+ groupPrefix: GROUP,+ bucket: sourceBucket,+ skillByPrefix: map,+ });+ expect(members.map((m) => m.name)).toEqual(['plain']);+ });++ it('offers nothing for a harness plugin group — its members are vendor state', () => {+ const map = new Map([[`${GROUP}/a`, skill('a', 'inkeep/team-skills')]]);+ const members = groupDeletableSkills({+ groupPrefix: GROUP,+ bucket: pluginBucket,+ skillByPrefix: map,+ });+ expect(members).toEqual([]);+ });++ it('ignores rows outside the group prefix', () => {+ const map = new Map([+ [`${GROUP}/a`, skill('a')],+ ['PROJECT/other-group/b', skill('b')],+ ]);+ const members = groupDeletableSkills({+ groupPrefix: GROUP,+ bucket: sourceBucket,+ skillByPrefix: map,+ });+ expect(members.map((m) => m.name)).toEqual(['a']);+ });+});diff --git a/packages/app/src/lib/skill-group-update.ts b/packages/app/src/lib/skill-group-update.tsindex 71cbab61a..368827af8 100644--- a/packages/app/src/lib/skill-group-update.ts+++ b/packages/app/src/lib/skill-group-update.ts@@ -38,3 +38,29 @@ export function groupUpdatableSkills(input: {}return members;}++/**+ * The members of a provenance group that "Delete N skills" may remove — the+ * group-row bulk delete. Broader than {@link groupUpdatableSkills}: deletion+ * needs no recorded source (an adopted or source-less copy is still ours to+ * remove). Same plugin gate though — a harness plugin's served skills are+ * vendor state OK never mutates — and managed built-ins are read-only+ * everywhere.+ */+export function groupDeletableSkills(input: {+ groupPrefix: string;+ bucket: ProvenanceBucket | undefined;+ skillByPrefix: ReadonlyMap<string, SkillsListEntry>;+}): SkillsListEntry[] {+ const { groupPrefix, bucket, skillByPrefix } = input;+ const packChild = bucket?.kind === 'plugin' && bucket.parent !== undefined && bucket.url !== null;+ if (!bucket || (bucket.kind === 'plugin' && !packChild)) return [];+ const prefix = `${groupPrefix}/`;+ const members: SkillsListEntry[] = [];+ for (const [rowPrefix, skill] of skillByPrefix) {+ if (!rowPrefix.startsWith(prefix)) continue;+ if (skill.managed) continue;+ members.push(skill);+ }+ return members;+}diff --git a/packages/app/src/lib/skills-api.ts b/packages/app/src/lib/skills-api.tsindex 93bd12c68..1fa6d6177 100644--- a/packages/app/src/lib/skills-api.ts+++ b/packages/app/src/lib/skills-api.ts@@ -326,6 +326,9 @@ export async function importSkill(input: {| {ok: true;name: string;+ /** Home-relative path to the imported SKILL.md (fresh imports only) -+ * lets the caller open the skill with zero skills-list round-trips. */+ path?: string;alreadyImported: boolean;collisionRenamedFrom?: string;warnings: string[];@@ -361,6 +364,7 @@ export async function importSkill(input: {}const payload = (await res.json().catch(() => null)) as {name?: string;+ path?: string;alreadyImported?: boolean;collisionRenamedFrom?: string;warnings?: string[];@@ -375,6 +379,12 @@ export async function importSkill(input: {return {ok: true,name: payload.name,+ // Only a FRESH import's path is trusted for direct opens: the+ // already-imported branch reports a name-relative shape, and that+ // skill is in the list anyway.+ ...(typeof payload.path === 'string' && payload.alreadyImported !== true+ ? { path: payload.path }+ : {}),alreadyImported: payload?.alreadyImported ?? false,collisionRenamedFrom: payload?.collisionRenamedFrom,warnings: payload?.warnings ?? [],@@ -617,6 +627,26 @@ export async function moveSkill(input: {}}+/**+ * GET `/api/skill` — resolve where a skill's bundle CURRENTLY lives (its+ * `SKILL.md` path, scope-relative), or null when it can't be read. Exists for+ * the post-install redirect: an install toggle can relocate a just-imported+ * bundle, so the import-time path report goes stale — and the skills LIST is+ * the one read that lags by seconds on large content roots, so re-resolving+ * must not ride it. This detail read is per-skill and fast.+ */+export async function getSkillCurrentPath(scope: SkillScope, name: string): Promise<string | null> {+ try {+ const params = new URLSearchParams({ name, scope });+ const res = await fetch(`/api/skill?${params.toString()}`);+ if (!res.ok) return null;+ const detail = (await res.json().catch(() => null)) as { skill?: { path?: string } } | null;+ return typeof detail?.skill?.path === 'string' ? detail.skill.path : null;+ } catch {+ return null;+ }+}+/** DELETE `/api/skill` — remove `<root>/.ok/skills/<name>/`. */export async function deleteSkill(scope: SkillScope,@@ -743,38 +773,6 @@ export async function deleteSkillFile(input: {}}-/** One bundled file beside a skill's `SKILL.md`, with inline read-only text. */-export interface SkillBundledFile {- path: string;- /** Inline UTF-8 text, or `null` for a binary / oversize file. */- text: string | null;-}--/**- * GET `/api/skill` — read a skill's bundled files (`scripts/`, `reference/`,- * assets) as read-only text. The skill is a folder, so this surfaces what it- * ships beside `SKILL.md` for browsing; scripts come back as TEXT, never an- * executable byte stream.- */-export async function getSkillBundledFiles(- scope: SkillScope,- name: string,- /** Which same-named bundle to list. Omitted = the by-name default. */- host?: string,-): Promise<WriteResult<{ files: SkillBundledFile[] }>> {- try {- const params = new URLSearchParams({ name, scope, ...(host ? { host } : {}) });- const res = await fetch(`/api/skill?${params.toString()}`);- if (!res.ok) return { ok: false, error: await readErrorBody(res) };- const detail = (await res.json().catch(() => null)) as {- skill?: { files?: SkillBundledFile[] };- } | null;- return { ok: true, files: detail?.skill?.files ?? [] };- } catch (err) {- return { ok: false, error: err instanceof Error ? err.message : String(err) };- }-}-/** Result of reading ONE skill bundle file: its text, or a failure with status. */type SkillFileReadResult =| { ok: true; text: string }diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.jsonindex 23cd243ad..ddc8533ad 100644--- a/packages/app/src/locales/ar/messages.json+++ b/packages/app/src/locales/ar/messages.json@@ -3947,6 +3947,7 @@"hgf5io": ["Blob Run"],"hgtsat": ["فشل حذف ", ["file"]],"hh4mVC": ["اطلب من الذكاء الاصطناعي إصلاح ", ["flatId"]],+ "hiNDrI": ["جارٍ حذف ", ["progress"], " من ", ["count"]],"hjO0Mq": ["إضافة تبويب"],"hmYd9H": ["تتبّع الأشخاص والشركات التي تعمل معها والاجتماعات التي تعقدها معهم. مناسب لتذكّر من يكون أحدهم، وكيف تعرفه، وآخر ما تحدثتما عنه."diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex dee9dfaf4..dc5bd39e4 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -4370,6 +4370,7 @@ msgid "Delete {0}"msgstr "حذف {0}"#. placeholder {0}: bulkEntries.length+#. placeholder {0}: deletable.length#: src/components/SkillsTree.tsxmsgid "Delete {0} skills"msgstr "حذف {0} مهارات"@@ -4480,6 +4481,10 @@ msgstr "حذف قالبًا"msgid "Deleting"msgstr "يجري الحذف"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Deleting {progress} of {count}"+msgstr "جارٍ حذف {progress} من {count}"+#: src/components/acp/ThreadView.tsxmsgid "Denied"msgstr "مرفوض"diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.jsonindex bf659576a..d55da8e53 100644--- a/packages/app/src/locales/bn/messages.json+++ b/packages/app/src/locales/bn/messages.json@@ -3332,6 +3332,7 @@"hgf5io": ["Blob Run"],"hgtsat": [["file"], " মুছতে ব্যর্থ"],"hh4mVC": ["AI-কে ", ["flatId"], " ঠিক করতে বলুন"],+ "hiNDrI": [["count"], "টির মধ্যে ", ["progress"], "টি মুছে ফেলা হচ্ছে"],"hjO0Mq": ["ট্যাব যোগ করুন"],"hmYd9H": ["আপনি যাদের ও যে কোম্পানিগুলোর সঙ্গে কাজ করেন এবং তাদের সঙ্গে আপনার বৈঠকগুলোর হিসাব রাখুন। কেউ কে, আপনি তাকে কীভাবে চেনেন, এবং শেষবার কী নিয়ে কথা হয়েছিল তা মনে রাখার জন্য ভালো।"diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex eb387cc9f..24366b65f 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -4366,6 +4366,7 @@ msgid "Delete {0}"msgstr "{0} মুছুন"#. placeholder {0}: bulkEntries.length+#. placeholder {0}: deletable.length#: src/components/SkillsTree.tsxmsgid "Delete {0} skills"msgstr "{0}টি স্কিল মুছুন"@@ -4476,6 +4477,10 @@ msgstr "টেমপ্লেট মুছে ফেলা হয়েছে"msgid "Deleting"msgstr "মুছে ফেলা হচ্ছে"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Deleting {progress} of {count}"+msgstr "{count}টির মধ্যে {progress}টি মুছে ফেলা হচ্ছে"+#: src/components/acp/ThreadView.tsxmsgid "Denied"msgstr "প্রত্যাখ্যাত"diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 5c7f5ae16..044d250d0 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -3436,6 +3436,7 @@"hgf5io": ["Blob Run"],"hgtsat": ["Failed to delete ", ["file"]],"hh4mVC": ["Ask AI to fix ", ["flatId"]],+ "hiNDrI": ["Deleting ", ["progress"], " of ", ["count"]],"hjO0Mq": ["Add tab"],"hmYd9H": ["Keep track of the people and companies you work with and the meetings you have with them. Good for remembering who someone is, how you know them, and what you last talked about."diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 76c3e0af9..b6a777b51 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -4370,6 +4370,7 @@ msgid "Delete {0}"msgstr "Delete {0}"#. placeholder {0}: bulkEntries.length+#. placeholder {0}: deletable.length#: src/components/SkillsTree.tsxmsgid "Delete {0} skills"msgstr "Delete {0} skills"@@ -4480,6 +4481,10 @@ msgstr "deleted template"msgid "Deleting"msgstr "Deleting"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Deleting {progress} of {count}"+msgstr "Deleting {progress} of {count}"+#: src/components/acp/ThreadView.tsxmsgid "Denied"msgstr "Denied"diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.jsonindex e1ed2b97f..3dd842fc7 100644--- a/packages/app/src/locales/es/messages.json+++ b/packages/app/src/locales/es/messages.json@@ -4019,6 +4019,7 @@"hgf5io": ["Blob Run"],"hgtsat": ["No se pudo eliminar ", ["file"]],"hh4mVC": ["Pedir a la IA que arregle ", ["flatId"]],+ "hiNDrI": ["Eliminando ", ["progress"], " de ", ["count"]],"hjO0Mq": ["Añadir pestaña"],"hmYd9H": ["Lleva la cuenta de las personas y empresas con las que trabajas y de las reuniones que tienes con ellas. Va bien para recordar quién es alguien, de qué la conoces y de qué hablasteis la última vez."diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex 2f560a157..ef4d77d40 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -4370,6 +4370,7 @@ msgid "Delete {0}"msgstr "Eliminar {0}"#. placeholder {0}: bulkEntries.length+#. placeholder {0}: deletable.length#: src/components/SkillsTree.tsxmsgid "Delete {0} skills"msgstr "Eliminar {0} habilidades"@@ -4480,6 +4481,10 @@ msgstr "plantilla eliminada"msgid "Deleting"msgstr "Eliminando"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Deleting {progress} of {count}"+msgstr "Eliminando {progress} de {count}"+#: src/components/acp/ThreadView.tsxmsgid "Denied"msgstr "Denegado"diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.jsonindex d3d3228d7..dcfb1e350 100644--- a/packages/app/src/locales/fr/messages.json+++ b/packages/app/src/locales/fr/messages.json@@ -4039,6 +4039,7 @@"hgf5io": ["Blob Run"],"hgtsat": ["Échec de la suppression de ", ["file"]],"hh4mVC": ["Demander à l'IA de corriger ", ["flatId"]],+ "hiNDrI": ["Suppression de ", ["progress"], " sur ", ["count"]],"hjO0Mq": ["Ajouter un onglet"],"hmYd9H": ["Gardez la trace des personnes et des entreprises avec lesquelles vous travaillez et des réunions que vous avez avec elles. Utile pour se rappeler qui est quelqu'un, comment vous le connaissez, et de quoi vous avez parlé la dernière fois."diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex e0b5b412b..a72ad25c9 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -4370,6 +4370,7 @@ msgid "Delete {0}"msgstr "Supprimer {0}"#. placeholder {0}: bulkEntries.length+#. placeholder {0}: deletable.length#: src/components/SkillsTree.tsxmsgid "Delete {0} skills"msgstr "Supprimer {0} compétences"@@ -4480,6 +4481,10 @@ msgstr "modèle supprimé"msgid "Deleting"msgstr "Suppression"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Deleting {progress} of {count}"+msgstr "Suppression de {progress} sur {count}"+#: src/components/acp/ThreadView.tsxmsgid "Denied"msgstr "Refusé"diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.jsonindex 397b39ec5..b9a07f2e9 100644--- a/packages/app/src/locales/hi/messages.json+++ b/packages/app/src/locales/hi/messages.json@@ -3321,6 +3321,7 @@"hgf5io": ["Blob Run"],"hgtsat": [["file"], " हटाने में विफल"],"hh4mVC": ["AI से ", ["flatId"], " ठीक करने को कहें"],+ "hiNDrI": [["count"], " में से ", ["progress"], " हटाए जा रहे हैं"],"hjO0Mq": ["टैब जोड़ें"],"hmYd9H": ["आप जिन लोगों और कंपनियों के साथ काम करते हैं और उनके साथ होने वाली बैठकों पर नज़र रखें। यह याद रखने के लिए अच्छा कि कोई कौन है, आप उसे कैसे जानते हैं, और आपकी आख़िरी बात किस पर हुई थी।"diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex 22dbffad4..97a711de6 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -4366,6 +4366,7 @@ msgid "Delete {0}"msgstr "{0} हटाएँ"#. placeholder {0}: bulkEntries.length+#. placeholder {0}: deletable.length#: src/components/SkillsTree.tsxmsgid "Delete {0} skills"msgstr "{0} स्किलें हटाएँ"@@ -4476,6 +4477,10 @@ msgstr "टेम्पलेट हटाया गया"msgid "Deleting"msgstr "हटाया जा रहा है"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Deleting {progress} of {count}"+msgstr "{count} में से {progress} हटाए जा रहे हैं"+#: src/components/acp/ThreadView.tsxmsgid "Denied"msgstr "अस्वीकृत"diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.jsonindex d67ea2995..816d95361 100644--- a/packages/app/src/locales/id/messages.json+++ b/packages/app/src/locales/id/messages.json@@ -3457,6 +3457,7 @@"hgf5io": ["Blob Run"],"hgtsat": ["Gagal menghapus ", ["file"]],"hh4mVC": ["Minta AI memperbaiki ", ["flatId"]],+ "hiNDrI": ["Menghapus ", ["progress"], " dari ", ["count"]],"hjO0Mq": ["Tambah tab"],"hmYd9H": ["Catat orang dan perusahaan yang bekerja dengan Anda serta pertemuan yang Anda adakan dengan mereka. Cocok untuk mengingat siapa seseorang, dari mana Anda mengenalnya, dan apa yang terakhir Anda bicarakan."diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex f3e32274a..b6bf0512d 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -4366,6 +4366,7 @@ msgid "Delete {0}"msgstr "Hapus {0}"#. placeholder {0}: bulkEntries.length+#. placeholder {0}: deletable.length#: src/components/SkillsTree.tsxmsgid "Delete {0} skills"msgstr "Hapus {0} keterampilan"@@ -4476,6 +4477,10 @@ msgstr "templat dihapus"msgid "Deleting"msgstr "Menghapus"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Deleting {progress} of {count}"+msgstr "Menghapus {progress} dari {count}"+#: src/components/acp/ThreadView.tsxmsgid "Denied"msgstr "Ditolak"diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.jsonindex d874f579e..0f97e70e4 100644--- a/packages/app/src/locales/ko/messages.json+++ b/packages/app/src/locales/ko/messages.json@@ -3319,6 +3319,7 @@"hgf5io": ["Blob 실행"],"hgtsat": [["file"], " 삭제에 실패했습니다"],"hh4mVC": ["AI에 ", ["flatId"], " 수정 요청"],+ "hiNDrI": [["count"], "개 중 ", ["progress"], "개 삭제 중"],"hjO0Mq": ["탭 추가"],"hmYd9H": ["함께 일하는 사람과 회사, 그들과의 회의를 기록합니다. 누군지, 어떻게 알게 되었는지, 마지막으로 무엇을 이야기했는지 기억하는 데 유용합니다."diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex 363d1cecf..6f45b929a 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -4370,6 +4370,7 @@ msgid "Delete {0}"msgstr "{0} 삭제"#. placeholder {0}: bulkEntries.length+#. placeholder {0}: deletable.length#: src/components/SkillsTree.tsxmsgid "Delete {0} skills"msgstr "스킬 {0}개 삭제"@@ -4480,6 +4481,10 @@ msgstr "템플릿 삭제됨"msgid "Deleting"msgstr "삭제 중"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Deleting {progress} of {count}"+msgstr "{count}개 중 {progress}개 삭제 중"+#: src/components/acp/ThreadView.tsxmsgid "Denied"msgstr "거부됨"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 462a67e06..a73733e75 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -3436,6 +3436,7 @@"hgf5io": ["ßĺōƀ Ŕũń"],"hgtsat": ["Ƒàĩĺēď ţō ďēĺēţē ", ["file"]],"hh4mVC": ["Àśķ ÀĨ ţō ƒĩx ", ["flatId"]],+ "hiNDrI": ["Ďēĺēţĩńĝ ", ["progress"], " ōƒ ", ["count"]],"hjO0Mq": ["Àďď ţàƀ"],"hmYd9H": ["Ķēēƥ ţŕàćķ ōƒ ţĥē ƥēōƥĺē àńď ćōḿƥàńĩēś ŷōũ ŵōŕķ ŵĩţĥ àńď ţĥē ḿēēţĩńĝś ŷōũ ĥàvē ŵĩţĥ ţĥēḿ. Ĝōōď ƒōŕ ŕēḿēḿƀēŕĩńĝ ŵĥō śōḿēōńē ĩś, ĥōŵ ŷōũ ķńōŵ ţĥēḿ, àńď ŵĥàţ ŷōũ ĺàśţ ţàĺķēď àƀōũţ."diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 15a06d752..cbe438af0 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -4366,6 +4366,7 @@ msgid "Delete {0}"msgstr ""#. placeholder {0}: bulkEntries.length+#. placeholder {0}: deletable.length#: src/components/SkillsTree.tsxmsgid "Delete {0} skills"msgstr ""@@ -4476,6 +4477,10 @@ msgstr ""msgid "Deleting"msgstr ""+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Deleting {progress} of {count}"+msgstr ""+#: src/components/acp/ThreadView.tsxmsgid "Denied"msgstr ""diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.jsonindex a05fe2b85..c188aa004 100644--- a/packages/app/src/locales/pt-BR/messages.json+++ b/packages/app/src/locales/pt-BR/messages.json@@ -3931,6 +3931,7 @@"hgf5io": ["Blob Run"],"hgtsat": ["Falha ao excluir ", ["file"]],"hh4mVC": ["Pedir à IA para corrigir ", ["flatId"]],+ "hiNDrI": ["Excluindo ", ["progress"], " de ", ["count"]],"hjO0Mq": ["Adicionar aba"],"hmYd9H": ["Acompanhe as pessoas e empresas com quem você trabalha e as reuniões que tem com elas. Bom para lembrar quem é alguém, de onde você a conhece e sobre o que vocês falaram da última vez."diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex 98cf783d9..4098826c4 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -4366,6 +4366,7 @@ msgid "Delete {0}"msgstr "Excluir {0}"#. placeholder {0}: bulkEntries.length+#. placeholder {0}: deletable.length#: src/components/SkillsTree.tsxmsgid "Delete {0} skills"msgstr "Excluir {0} habilidades"@@ -4476,6 +4477,10 @@ msgstr "modelo excluído"msgid "Deleting"msgstr "Excluindo"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Deleting {progress} of {count}"+msgstr "Excluindo {progress} de {count}"+#: src/components/acp/ThreadView.tsxmsgid "Denied"msgstr "Negado"diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.jsonindex ac56ddc24..970e43407 100644--- a/packages/app/src/locales/ur/messages.json+++ b/packages/app/src/locales/ur/messages.json@@ -3515,6 +3515,7 @@"hgf5io": ["Blob Run"],"hgtsat": [["file"], " حذف نہیں ہو سکی"],"hh4mVC": ["AI سے ", ["flatId"], " ٹھیک کرنے کو کہیں"],+ "hiNDrI": [["count"], " میں سے ", ["progress"], " حذف ہو رہے ہیں"],"hjO0Mq": ["ٹیب شامل کریں"],"hmYd9H": ["ان لوگوں اور کمپنیوں کا حساب رکھیں جن کے ساتھ آپ کام کرتے ہیں اور ان کے ساتھ ہونے والی ملاقاتوں کا۔ یہ یاد رکھنے کے لیے مفید کہ کوئی کون ہے، آپ اسے کیسے جانتے ہیں، اور آخری بار کس بارے میں بات ہوئی تھی۔"diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex 3f30c60cb..c7e38a163 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -4370,6 +4370,7 @@ msgid "Delete {0}"msgstr "{0} حذف کریں"#. placeholder {0}: bulkEntries.length+#. placeholder {0}: deletable.length#: src/components/SkillsTree.tsxmsgid "Delete {0} skills"msgstr "{0} مہارتیں حذف کریں"@@ -4480,6 +4481,10 @@ msgstr "ٹیمپلیٹ حذف کیا"msgid "Deleting"msgstr "حذف کیا جا رہا ہے"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Deleting {progress} of {count}"+msgstr "{count} میں سے {progress} حذف ہو رہے ہیں"+#: src/components/acp/ThreadView.tsxmsgid "Denied"msgstr "مسترد"diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.jsonindex e23cc9aa9..0494b3a9a 100644--- a/packages/app/src/locales/zh-Hans/messages.json+++ b/packages/app/src/locales/zh-Hans/messages.json@@ -3025,6 +3025,7 @@"hgf5io": ["Blob Run"],"hgtsat": ["删除 ", ["file"], " 失败"],"hh4mVC": ["让 AI 修复 ", ["flatId"]],+ "hiNDrI": ["正在删除第 ", ["progress"], " 个,共 ", ["count"], " 个"],"hjO0Mq": ["添加标签页"],"hmYd9H": ["记录你打交道的人和公司,以及你们之间的会面。适合用来记住某人是谁、你怎么认识他们,以及上次聊了什么。"diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex 4f11781ef..64fc8259e 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -4370,6 +4370,7 @@ msgid "Delete {0}"msgstr "删除 {0}"#. placeholder {0}: bulkEntries.length+#. placeholder {0}: deletable.length#: src/components/SkillsTree.tsxmsgid "Delete {0} skills"msgstr "删除 {0} 个技能"@@ -4480,6 +4481,10 @@ msgstr "已删除模板"msgid "Deleting"msgstr "正在删除"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Deleting {progress} of {count}"+msgstr "正在删除第 {progress} 个,共 {count} 个"+#: src/components/acp/ThreadView.tsxmsgid "Denied"msgstr "已拒绝"diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.jsonindex e7c895041..e56b08b5c 100644--- a/packages/app/src/locales/zh-Hant/messages.json+++ b/packages/app/src/locales/zh-Hant/messages.json@@ -3051,6 +3051,7 @@"hgf5io": ["Blob Run"],"hgtsat": ["刪除 ", ["file"], " 失敗"],"hh4mVC": ["請 AI 修正 ", ["flatId"]],+ "hiNDrI": ["正在刪除第 ", ["progress"], " 個,共 ", ["count"], " 個"],"hjO0Mq": ["新增分頁"],"hmYd9H": ["記錄你往來的人和公司,以及你們之間的會面。適合用來記住某人是誰、你怎麼認識他們,還有上次聊了什麼。"diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex c7ddcc569..88352e5d3 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -4370,6 +4370,7 @@ msgid "Delete {0}"msgstr "刪除 {0}"#. placeholder {0}: bulkEntries.length+#. placeholder {0}: deletable.length#: src/components/SkillsTree.tsxmsgid "Delete {0} skills"msgstr "刪除 {0} 個技能"@@ -4480,6 +4481,10 @@ msgstr "已刪除範本"msgid "Deleting"msgstr "正在刪除"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Deleting {progress} of {count}"+msgstr "正在刪除第 {progress} 個,共 {count} 個"+#: src/components/acp/ThreadView.tsxmsgid "Denied"msgstr "已拒絕"diff --git a/packages/app/tests/integration/skill-plugin-modified-flag.test.ts b/packages/app/tests/integration/skill-plugin-modified-flag.test.tsindex 4e19518bb..8d488e5e7 100644--- a/packages/app/tests/integration/skill-plugin-modified-flag.test.ts+++ b/packages/app/tests/integration/skill-plugin-modified-flag.test.ts@@ -78,7 +78,16 @@ test('editing the copy after first sight flips Modified while the plugin is unchjoin(server.contentDir, '.agents', 'skills', 'probe', 'SKILL.md'),skillMd('# Copy, hand-edited afterwards'),);- const entry = await listProbe();+ // Watcher-fresh, not request-fresh: the skills list is served from a+ // short-lived cache (re-stamping every bundle per request froze the app on+ // large roots), and a direct disk edit reaches it via the managed-artifact+ // watcher's files signal - poll across that window.+ const deadline = Date.now() + 5_000;+ let entry = await listProbe();+ while (entry.modified !== true && Date.now() < deadline) {+ await new Promise((r) => setTimeout(r, 200));+ entry = await listProbe();+ }expect(entry.modified).toBe(true);});diff --git a/packages/app/tests/integration/skill-scope-move-roundtrip.test.ts b/packages/app/tests/integration/skill-scope-move-roundtrip.test.tsnew file mode 100644index 000000000..18470c5eb--- /dev/null+++ b/packages/app/tests/integration/skill-scope-move-roundtrip.test.ts@@ -0,0 +1,96 @@+import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';+import { createTestClient, createTestServer, type TestServer } from './test-harness';++/**+ * A project→global→project round-trip must leave the skill fully alive: listed+ * at project scope, detail-readable, and — the part the sidebar click depends+ * on — its content doc SERVABLE over the collab socket. The field failure this+ * pins: after moving a skill out and back in one session, the sidebar row went+ * dead. The client half (the tab reconciler retargeting each hop instead of+ * closing) is pinned in `use-reconcile-skill-tabs.test.ts`; this is the server+ * half at each hop.+ *+ */+let server: TestServer;+let tmpHome: string;+const base = () => `http://127.0.0.1:${server.port}`;++beforeAll(async () => {+ tmpHome = mkdtempSync(join(tmpdir(), 'ok-scope-roundtrip-home-'));+ // An adopted harness in the throwaway home — global destinations refuse+ // (NO_USABLE_SKILL_HOME) when the home has adopted none.+ mkdirSync(join(tmpHome, '.claude', 'skills'), { recursive: true });+ server = await createTestServer({ configHomedirOverride: tmpHome });+}, HARNESS_BOOT_TIMEOUT_MS);+afterAll(async () => {+ await server.cleanup();+ rmSync(tmpHome, { recursive: true, force: true });+});++describe('scope-move round-trip keeps the skill openable', () => {+ test('project -> global -> project: listed, readable, and doc servable at every hop', async () => {+ const name = 'roundtrip-skill';+ const marker = 'Roundtrip body marker';+ const put = await fetch(`${base()}/api/skill`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ scope: 'project',+ name,+ frontmatter: { name, description: 'Round-trip coverage.' },+ body: `# ${marker}\n`,+ }),+ });+ expect(put.status).toBe(200);+ const createdPath = ((await put.json()) as { path: string }).path;+ const projectDocName = createdPath.replace(/\.md$/, '');++ const move = async (fromScope: string, toScope: string) => {+ const res = await fetch(`${base()}/api/skill/move-scope`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name, fromScope, toScope }),+ });+ expect(res.status, await res.clone().text()).toBe(200);+ };++ await move('project', 'global');+ const listedGlobal = (await (await fetch(`${base()}/api/skills`)).json()) as {+ skills: Array<{ name: string; scope: string }>;+ };+ expect(listedGlobal.skills.some((s) => s.name === name && s.scope === 'global')).toBe(true);+ expect(listedGlobal.skills.some((s) => s.name === name && s.scope === 'project')).toBe(false);++ await move('global', 'project');+ const listedBack = (await (await fetch(`${base()}/api/skills`)).json()) as {+ skills: Array<{ name: string; scope: string; path: string }>;+ };+ const backEntry = listedBack.skills.find((s) => s.name === name && s.scope === 'project');+ expect(backEntry).toBeDefined();+ expect(listedBack.skills.some((s) => s.name === name && s.scope === 'global')).toBe(false);++ // Detail read resolves the returned bundle.+ const detail = await fetch(`${base()}/api/skill?name=${name}&scope=project`);+ expect(detail.status).toBe(200);++ // On disk where the entry says it is.+ expect(existsSync(join(server.contentDir, backEntry?.path ?? ''))).toBe(true);++ // And the content doc is SERVABLE — the click's actual dependency. A+ // refused/never-syncing connect here is exactly "the row is dead".+ const backDocName = (backEntry?.path ?? '').replace(/\.md$/, '');+ expect(backDocName).toBe(projectDocName);+ const client = await createTestClient(server.port, backDocName);+ try {+ await expect+ .poll(() => client.ytext.toString(), { timeout: 15_000, interval: 250 })+ .toContain(marker);+ } finally {+ await client.cleanup();+ }+ }, 60_000);+});diff --git a/packages/app/tests/stress/skills-sidebar-open.e2e.ts b/packages/app/tests/stress/skills-sidebar-open.e2e.tsindex 7e69cd12b..5867668f1 100644--- a/packages/app/tests/stress/skills-sidebar-open.e2e.ts+++ b/packages/app/tests/stress/skills-sidebar-open.e2e.ts@@ -18,7 +18,7 @@* so `[data-item-path]` selects rows directly. Paths are `<Scope>/<name>/`.*/-import { mkdirSync, realpathSync, writeFileSync } from 'node:fs';+import { mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import type { Page } from '@playwright/test';import { expect, test } from './_helpers';@@ -206,6 +206,19 @@ test('explore install: the destination menu survives the first pick and hands of// The project needs an adopted editor root for the install fan-out target.mkdirSync(join(workerServer.contentDir, '.claude', 'skills'), { recursive: true });+ // Field conditions: on a monorepo-sized content root /api/skills takes+ // seconds, and the install auto-open used to be GATED on that list - the+ // preview sat un-redirected long enough to read as "install didn't open+ // the skill". Delay every list response so the redirect can only pass the+ // bounded assertion below by NOT waiting on the list.+ await page.route(/\/api\/skills(\?|$)/, async (route) => {+ if (route.request().method() === 'GET') {+ console.log('[list-delay] holding', route.request().url());+ await new Promise((resolve) => setTimeout(resolve, 10_000));+ console.log('[list-delay] released', route.request().url());+ }+ await route.continue();+ });await page.route('**/api/skills/search**', async (route) => {await route.fulfill({status: 200,@@ -267,13 +280,32 @@ test('explore install: the destination menu survives the first pick and hands ofvoid skillLanded;// Closing the menu is the handoff: the preview becomes the real skill tab.+ // Bounded WELL below the list delay: the redirect must ride the install+ // response's own path report, not a skills-list refetch.await page.keyboard.press('Escape');+ // Belt over the Escape: a click outside is the other real close gesture,+ // and pressing Escape in the same tick the menu finishes mounting can be+ // swallowed by its focus setup.+ await page.mouse.click(10, 400);+ // The PREVIEW's own hash also contains the skill name, so the assertion+ // demands the real live-doc shape - anything still preview-shaped fails.await expect.poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)), {- timeout: 20_000,+ timeout: 4_000,})- .toContain(name);+ .toMatch(new RegExp(`skills/${name}/SKILL$`));await expect(activeEditor(page).filter({ hasText: marker })).toBeVisible({ timeout: 15_000 });+ // Landing check runs LAST so it cannot pad the redirect timing above.+ await expect+ .poll(+ async () => {+ const res = await fetch(`${workerServer.baseURL}/api/skills?scope=project`);+ const body = (await res.json()) as { skills?: Array<{ name: string }> };+ return body.skills?.some((s) => s.name === name) ?? false;+ },+ { timeout: 30_000 },+ )+ .toBe(true);});test('shift-click ranges and cmd-click toggles drag the whole selection to the other scope', async ({@@ -529,3 +561,338 @@ test('shift+arrow walks visible rows through read-only plugin skills; drag movesexpect(moveRequests).not.toContain('plug-two');expect(moveRequests).not.toContain('open-knowledge');});++test('renaming a skill from the Properties name field follows the rename everywhere', async ({+ page,+ api,+ workerServer,+}) => {+ await api.testReset();+ await createSkill(workerServer.baseURL, 'rename-me', '# Rename target\n');++ await page.goto('/');+ await expandSkillsDock(page);+ const row = skillRow(page, 'Project/rename-me/');+ await row.waitFor({ timeout: 15_000 });+ await row.click();+ await expect+ .poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)), {+ timeout: 15_000,+ })+ .toContain('rename-me');++ // The single rename flow every surface shares: commit a new name in the+ // Properties field; the tab must morph to the renamed doc (not strand on the+ // deleted source) and the sidebar row must follow.+ const nameInput = page.getByTestId('skill-name-input');+ await nameInput.waitFor({ timeout: 15_000 });+ await nameInput.fill('renamed-target');+ await nameInput.press('Enter');++ await expect+ .poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)), {+ timeout: 20_000,+ })+ .toContain('renamed-target');+ await skillRow(page, 'Project/renamed-target/').waitFor({ timeout: 15_000 });+ await expect(skillRow(page, 'Project/rename-me/')).toHaveCount(0);+ // The morphed tab is live: a Properties name field reflects the committed+ // rename (two panels can coexist for a frame while the old doc unmounts, so+ // assert on the surviving one rather than a strict single match).+ await expect(page.getByTestId('skill-name-input').last()).toHaveValue('renamed-target');+});++test('skill lifecycle in the .agents home: create, edit, menu rename, menu move', async ({+ page,+ api,+ workerServer,+}) => {+ await api.testReset();+ // With a `.agents/` dir present the harness-neutral hub wins as the default+ // skill home (agentskills.io convention) - the layout real repos like+ // agents-private run, and where the field failures happened. The worker's+ // contentDir is SHARED across this worker's tests and nothing sweeps dot+ // entries, so the finally below deletes the dir - leaking it would silently+ // flip the default skill home for every later spec on the worker.+ const agentsHome = join(workerServer.contentDir, '.agents');+ mkdirSync(join(agentsHome, 'skills'), { recursive: true });+ try {+ await runLifecycleJourney(page, workerServer);+ } finally {+ rmSync(agentsHome, { recursive: true, force: true });+ }+});++async function runLifecycleJourney(+ page: Page,+ workerServer: { baseURL: string; contentDir: string },+): Promise<void> {+ const created = await createSkill(workerServer.baseURL, 'lifecycle-skill', '# Lifecycle\n');+ expect(created.path.startsWith('.agents/skills/')).toBe(true);++ await page.goto('/');+ await expandSkillsDock(page);+ const row = skillRow(page, 'Project/lifecycle-skill/');+ await row.waitFor({ timeout: 15_000 });+ await row.click();+ await expect+ .poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)), {+ timeout: 15_000,+ })+ .toContain('lifecycle-skill');++ // EDIT: type into the live editor and require the bytes to land on disk -+ // the persistence half is what a stuck save would silently drop.+ // `:visible` matters: the Activity pool keeps HIDDEN editors mounted+ // (display:none), and a bare .first() can grab one of those - clicks focus+ // nothing and keystrokes vanish.+ const editor = page.locator('.ProseMirror:visible').first();+ await editor.waitFor({ timeout: 15_000 });+ // Click the body TEXT, not the editor surface: the skill doc mounts more+ // than one ProseMirror (an empty auxiliary editor takes focus on a bare+ // surface click) and keystrokes follow the focus, not the click target.+ await editor.getByText('Lifecycle').click();+ await page.keyboard.press('ControlOrMeta+End');+ await page.keyboard.type('Edited body line');+ // The keystrokes reached the live doc...+ await expect(editor).toContainText('Edited body line');+ // ...and the persistence debounce flushed them to the canonical file.+ const skillMdPath = join(+ workerServer.contentDir,+ '.agents',+ 'skills',+ 'lifecycle-skill',+ 'SKILL.md',+ );+ await expect+ .poll(+ () => {+ try {+ return readFileSync(skillMdPath, 'utf-8');+ } catch {+ return '';+ }+ },+ { timeout: 40_000 },+ )+ .toContain('Edited body line');++ // RENAME via the three-dot/context menu dialog (the second rename surface -+ // Properties-field rename is covered by its own spec).+ await row.click({ button: 'right' });+ await page.getByRole('menuitem', { name: 'Rename' }).click();+ const dialog = page.getByRole('dialog');+ await dialog.getByRole('textbox').fill('lifecycle-renamed');+ await dialog.getByRole('button', { name: 'Rename', exact: true }).click();+ await skillRow(page, 'Project/lifecycle-renamed/').waitFor({ timeout: 15_000 });+ await expect(skillRow(page, 'Project/lifecycle-skill/')).toHaveCount(0);+ // The open tab followed the rename instead of stranding.+ await expect+ .poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)), {+ timeout: 20_000,+ })+ .toContain('lifecycle-renamed');++ // MOVE via the menu path (drag covers the other path). Asserted at the+ // network seam: the harness pins home = contentDir so the scopes share+ // physical roots and the server refuses the actual relocation.+ const moveRequests: string[] = [];+ page.on('request', (req) => {+ if (req.url().includes('/api/skill/move-scope') && req.method() === 'POST') {+ const body = req.postDataJSON() as { name?: string; toScope?: string } | null;+ if (body?.name) moveRequests.push(`${body.name}:${body.toScope}`);+ }+ });+ await skillRow(page, 'Project/lifecycle-renamed/').click({ button: 'right' });+ await page.getByRole('menuitem', { name: /Move to/ }).click();+ await page.getByRole('dialog').getByRole('button', { name: 'Move', exact: true }).click();+ await expect+ .poll(() => moveRequests.join(','), { timeout: 20_000 })+ .toContain('lifecycle-renamed:global');+}++test('New skill from the scope menu auto-opens and STAYS open under a slow skills list', async ({+ page,+ api,+}) => {+ await api.testReset();++ // Delay every skills-LIST response: the field failure mode is a monorepo+ // where /api/skills takes seconds, so every list snapshot the reconciler+ // sees lags the create - exactly the window where the fresh tab used to be+ // closed as "skill not in the list".+ let delayedResponses = 0;+ await page.route(/\/api\/skills(\?|$)/, async (route) => {+ if (route.request().method() === 'GET') {+ await new Promise((resolve) => setTimeout(resolve, 1500));+ delayedResponses += 1;+ }+ await route.continue();+ });++ await page.goto('/');+ await expandSkillsDock(page);+ const scopeRow = skillRow(page, 'Project/');+ await scopeRow.waitFor({ timeout: 15_000 });+ await scopeRow.click({ button: 'right' });+ await page.getByRole('menuitem', { name: 'New skill' }).click();+ const dialog = page.getByRole('dialog');+ await dialog.getByRole('textbox').first().fill('auto-open-new');+ await dialog.getByRole('button', { name: 'Create', exact: true }).click();++ // The created skill's editor opens...+ await expect+ .poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)), {+ timeout: 20_000,+ })+ .toContain('auto-open-new');++ // ...and STAYS open across the delayed list snapshots that used to close+ // it. Wait until at least two lagged responses have landed (the stale one+ // that triggered the old close, plus a fresh one), then re-assert.+ const seen = delayedResponses;+ await expect.poll(() => delayedResponses, { timeout: 20_000 }).toBeGreaterThan(seen + 1);+ expect(decodeURIComponent(await page.evaluate(() => window.location.hash))).toContain(+ 'auto-open-new',+ );+});++test('an imported skill row opens on the FIRST click, under a slow skills list', async ({+ page,+ api,+ workerServer,+}) => {+ await api.testReset();+ const name = 'imported-first-click';+ const sourceDir = join(workerServer.contentDir, '..', `import-source-${Date.now()}`);+ mkdirSync(join(sourceDir, name), { recursive: true });+ writeFileSync(+ join(sourceDir, name, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Imported first-click coverage.\n---\n\n# Imported ${name}\n`,+ );+ mkdirSync(join(workerServer.contentDir, '.claude', 'skills'), { recursive: true });++ await page.route(/\/api\/skills(\?|$)/, async (route) => {+ if (route.request().method() === 'GET') {+ await new Promise((resolve) => setTimeout(resolve, 5_000));+ }+ await route.continue();+ });++ await page.goto('/');+ await expandSkillsDock(page);+ await skillRow(page, 'Project/').waitFor({ timeout: 20_000 });++ // Import server-side while the page is live - the CLI / another window /+ // an agent does exactly this, and the sidebar picks the new row up from the+ // files signal.+ const imp = await fetch(`${workerServer.baseURL}/api/skill/import`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ source: sourceDir, skill: name, scope: 'project', install: false }),+ });+ expect(imp.ok).toBe(true);++ // ONE click on the freshly appeared row must open it - the dead-row shape+ // was: click swallowed by remount churn or stranded on a stale ignored+ // flag, working only after clicking some other skill first.+ const row = skillRow(page, `Project/${name}/`);+ await row.waitFor({ timeout: 30_000 });+ await row.click();+ await expect+ .poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)), {+ timeout: 20_000,+ })+ .toMatch(new RegExp(`skills/${name}/SKILL$`));+});++test('Delete key removes a multi-selection even when one of the docs is open', async ({+ page,+ api,+ workerServer,+}) => {+ await api.testReset();+ for (const n of ['bulk-del-a', 'bulk-del-b', 'bulk-del-c']) {+ await createSkill(workerServer.baseURL, n, `# Del ${n}\n`);+ }++ await page.goto('/');+ await expandSkillsDock(page);+ const rowA = skillRow(page, 'Project/bulk-del-a/');+ await rowA.waitFor({ timeout: 15_000 });+ // Open a - its live doc is ACTIVE, the exact shape that deadlocked the+ // delete (server unload vs the renderer's instant re-auth on close).+ await rowA.click();+ await expect+ .poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)), {+ timeout: 15_000,+ })+ .toContain('bulk-del-a');++ // cmd-click gathers the open skill plus two others.+ await rowA.click({ modifiers: ['ControlOrMeta'] });+ await skillRow(page, 'Project/bulk-del-b/').click({ modifiers: ['ControlOrMeta'] });+ await skillRow(page, 'Project/bulk-del-c/').click({ modifiers: ['ControlOrMeta'] });++ await page.keyboard.press('Delete');+ const dialog = page.getByRole('alertdialog');+ await dialog.waitFor({ timeout: 10_000 });+ await dialog.getByRole('button', { name: /delete/i }).click();++ // The whole batch lands: rows gone, server agrees.+ for (const n of ['bulk-del-a', 'bulk-del-b', 'bulk-del-c']) {+ await expect(skillRow(page, `Project/${n}/`)).toHaveCount(0, { timeout: 30_000 });+ }+ await expect+ .poll(+ async () => {+ const res = await fetch(`${workerServer.baseURL}/api/skills?scope=project`);+ const body = (await res.json()) as { skills?: Array<{ name: string }> };+ return (body.skills ?? []).filter((s) => s.name.startsWith('bulk-del-')).length;+ },+ { timeout: 30_000 },+ )+ .toBe(0);+});++test('a skills.sh import surfaces its sidebar row without any other churn', async ({+ page,+ api,+ workerServer,+}) => {+ await api.testReset();+ // A local bundle stands in for the skills.sh listing, same as the explore+ // spec. The import is the ONLY mutation: the row must appear off the+ // import's own client push. The watcher cannot deliver it - the new dir+ // sits outside its coverage until the deferred ignore rebuild reconciles+ // (~2 minutes) - which is exactly how the imported-skill row silently+ // never appeared in a live session.+ const name = 'import-row-skill';+ const sourceDir = join(workerServer.contentDir, '..', `import-row-source-${Date.now()}`);+ mkdirSync(join(sourceDir, name), { recursive: true });+ writeFileSync(+ join(sourceDir, name, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Import row coverage.\n---\n\n# Import Row\n`,+ );++ await page.goto('/');+ await expandSkillsDock(page);++ const res = await fetch(`${workerServer.baseURL}/api/skill/import`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ source: sourceDir, skill: name, scope: 'project', install: false }),+ });+ expect(res.status).toBe(200);++ const row = skillRow(page, `Project/${name}/`);+ await row.waitFor({ timeout: 15_000 });+ // And the row is not just visible but alive: one click opens the doc.+ await row.click();+ await expect+ .poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)), {+ timeout: 15_000,+ })+ .toContain(name);+ rmSync(sourceDir, { recursive: true, force: true });+});diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.tsindex 2b577dc62..eede18995 100644--- a/packages/core/src/schemas/api/tags-search.ts+++ b/packages/core/src/schemas/api/tags-search.ts@@ -511,6 +511,12 @@ export const SkillsListEntrySchema = z* prefer this when present; `path` still reports where the bundle lives.*/canonicalPath: z.string().min(1).optional(),+ /** Bundle-relative paths of the files shipped beside SKILL.md (scripts/,+ * references/, assets) — paths only, no content. Inlined on the list so+ * the sidebar tree can nest a skill's files without a follow-up+ * per-skill detail fetch (N of which saturated the request pool on+ * large installs and queued every other call behind them). */+ filePaths: z.array(z.string()).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-sidediff --git a/packages/desktop/tests/smoke/skill-scope-roundtrip.e2e.ts b/packages/desktop/tests/smoke/skill-scope-roundtrip.e2e.tsnew file mode 100644index 000000000..4b4fffcc5--- /dev/null+++ b/packages/desktop/tests/smoke/skill-scope-roundtrip.e2e.ts@@ -0,0 +1,136 @@+/**+ * QA smoke: the skills-sidebar row survives a project→global→project scope+ * round-trip, in a REAL Electron window against the REAL (detached-shape)+ * server. The field failure this pins: move a skill out and back in one live+ * session and its sidebar row went dead — nothing a DOM test reproduces,+ * because the wedge candidates all live in the real host (provider teardown ++ * IDB clear on the outbound hop, tab retarget on each hop, the re-created doc+ * connecting over the same socket).+ *+ * HOME is redirected at launch so the GLOBAL half of the trip lands in a+ * throwaway home — never the developer's real `~/.claude/skills`. The server+ * half of this contract (list/detail/doc-servability per hop) is pinned in+ * `packages/app/tests/integration/skill-scope-move-roundtrip.test.ts`; the+ * client reconcile matrix in `use-reconcile-skill-tabs.test.ts`.+ */++import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { _electron as electron } from '@playwright/test';+import { expect, test } from './_helpers/smoke-test';++const __dirname = dirname(fileURLToPath(import.meta.url));+const MAIN_ENTRY = resolve(__dirname, '..', '..', 'out', 'main', 'index.js');++const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';+const DARWIN = process.platform === 'darwin';+const BUILD_EXISTS = existsSync(MAIN_ENTRY);++test.describe('Skill scope round-trip', () => {+ test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');+ test.skip(!DARWIN, 'Deep-link project open is macOS-only in v0.');+ test.skip(!BUILD_EXISTS, `Main build missing at ${MAIN_ENTRY} — run "pnpm run build:desktop".`);++ test('project -> global -> project keeps the sidebar row clickable in one session', async ({+ captureStderrFor,+ }) => {+ const tmpHome = mkdtempSync(join(tmpdir(), 'ok-scope-roundtrip-home-'));+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-scope-roundtrip-'));+ mkdirSync(join(projectDir, '.ok'), { recursive: true });+ writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n dir: '.'\n");+ writeFileSync(join(projectDir, 'note.md'), '# Note\n');+ // An adopted global host, so the outbound move has a destination — and an+ // adopted PROJECT root, so the create has one (a bare project 400s with+ // NO_USABLE_SKILL_HOME rather than inventing a layout). Any harness root+ // works; `.claude` matches the throwaway home's.+ mkdirSync(join(tmpHome, '.claude', 'skills'), { recursive: true });+ mkdirSync(join(projectDir, '.claude', 'skills'), { recursive: true });++ const userDataDir = join(tmpHome, 'electron-userdata');+ mkdirSync(userDataDir, { recursive: true });+ const deepLink = `openknowledge://open?project=${encodeURIComponent(projectDir)}&doc=note`;++ const app = await electron.launch({+ args: [MAIN_ENTRY, deepLink, `--user-data-dir=${userDataDir}`],+ env: { ...process.env, HOME: tmpHome, OK_M6B_FORCE: '1' },+ timeout: 30_000,+ });+ captureStderrFor(app, { cleanupDirs: [projectDir, tmpHome] });+ await app.firstWindow({ timeout: 15_000 });++ const page = await (async () => {+ for (let i = 0; i < 60; i++) {+ for (const w of app.windows()) {+ const hash = await w.evaluate(() => window.location.hash).catch(() => '');+ if (hash.includes('note')) return w;+ }+ await new Promise((r) => setTimeout(r, 500));+ }+ throw new Error('project window never mounted from the argv deep-link');+ })();++ // The window's own server, via the project lock — API calls hit exactly+ // the process the sidebar is wired to.+ const lockPath = join(projectDir, '.ok', 'local', 'server.lock');+ await expect(() => {+ expect(existsSync(lockPath)).toBe(true);+ }).toPass({ timeout: 15_000 });+ const port = (JSON.parse(readFileSync(lockPath, 'utf-8')) as { port: number }).port;+ const base = `http://127.0.0.1:${port}`;++ const name = 'roundtrip-smoke';+ const marker = `Roundtrip Smoke ${Date.now()}`;+ const put = await fetch(`${base}/api/skill`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ scope: 'project',+ name,+ frontmatter: { name, description: 'Round-trip smoke coverage.' },+ body: `# ${marker}\n`,+ }),+ });+ expect(put.status).toBe(200);++ // Expand the skills dock and OPEN the doc first — the outbound teardown+ // against an open doc is the risky half.+ const sidebar = page.locator('[data-slot="sidebar-container"]');+ const trigger = sidebar+ .getByTestId('skills-dock')+ .getByRole('button', { name: 'Skills Studio', exact: true });+ await trigger.waitFor({ timeout: 10_000 });+ const row = page.locator(`[data-item-path="Project/${name}/"]`).first();+ if (!(await row.isVisible().catch(() => false))) await trigger.click();+ await row.waitFor({ timeout: 10_000 });+ await row.click();+ const editor = page.locator('.ProseMirror:not(.composer-prosemirror)').first();+ await expect(editor.filter({ hasText: marker }).first()).toBeVisible({ timeout: 10_000 });++ const move = async (fromScope: string, toScope: string) => {+ const res = await fetch(`${base}/api/skill/move-scope`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name, fromScope, toScope }),+ });+ expect(res.status, await res.clone().text()).toBe(200);+ };++ await move('project', 'global');+ await page.locator(`[data-item-path="Global/${name}/"]`).first().waitFor({ timeout: 15_000 });+ await move('global', 'project');+ const backRow = page.locator(`[data-item-path="Project/${name}/"]`).first();+ await backRow.waitFor({ timeout: 15_000 });++ // The report this pins: after the round-trip the row was dead. One click,+ // same session, no reload — the doc must land.+ await backRow.click();+ await expect+ .poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)), {+ timeout: 10_000,+ })+ .toContain(name);+ await expect(editor.filter({ hasText: marker }).first()).toBeVisible({ timeout: 10_000 });+ });+});diff --git a/packages/server/src/api-derived-index-ready-gate.test.ts b/packages/server/src/api-derived-index-ready-gate.test.tsindex 421664b1f..c74e1694c 100644--- a/packages/server/src/api-derived-index-ready-gate.test.ts+++ b/packages/server/src/api-derived-index-ready-gate.test.ts@@ -139,7 +139,7 @@ describe('derived-index API readiness gate', () => {}});- test('project skill move waits for derived-index projection before responding', async () => {+ test('project skill move responds WITHOUT waiting for derived-index projection', async () => {const contentDir = mkdtempSync(join(tmpdir(), 'ok-derived-skill-move-'));const sourceSkillDir = join(contentDir, '.ok', 'skills', 'old-skill');mkdirSync(sourceSkillDir, { recursive: true });@@ -183,15 +183,21 @@ describe('derived-index API readiness gate', () => {toName: 'new-skill',});- await started;- await Promise.resolve();- expect(route.captured.status).toBe(0);-- releaseProjection();+ // The response must land while the projection is STILL HELD: the queue+ // serializes behind full ingests (boot, watcher re-ingest) and holding+ // the rename response on it measured 20s+ on monorepo-sized roots. The+ // client follows the rename by the response's own path, so projection+ // freshness is eventual, not response-gating.await route.done;-- expect(recordDirectMutations).toHaveBeenCalledTimes(1);expect(route.captured.status).toBe(200);++ await started;+ releaseProjection();+ // Let the deferred chain settle so the projection is still guaranteed+ // to happen (deferred, never dropped).+ await vi.waitFor(() => {+ expect(recordDirectMutations).toHaveBeenCalledTimes(1);+ });expect(JSON.parse(route.captured.body)).toMatchObject({from: '.ok/skills/old-skill',to: '.ok/skills/new-skill',diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 4cd05c695..ea1531abc 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -497,6 +497,7 @@ import {detectUserSkillHosts,} from './skill-install.ts';import {+ listSkillBundledFilePaths,projectSkill,readSkillBundledFiles,removeInPlaceSkillCopies,@@ -2911,7 +2912,7 @@ export function createApiExtension(getDiskAckSVs,contentRoot,derivedDocumentIndex,- signalChannel,+ signalChannel: rawSignalChannel,agentFocusBroadcaster,agentPresenceBroadcaster,onAgentWrite,@@ -2944,6 +2945,16 @@ export function createApiExtension(getLinkPreviewsEnabled,getConfigDiagnostics,} = options;+ // Every server-side `files` signal means content changed somewhere - doc+ // writes, watcher events, installs. The skills caches must not outlive that:+ // content-derived list fields (Modified flags, drift, built-in+ // materialization) have no other invalidation edge for non-lifecycle writes.+ const signalChannel: typeof rawSignalChannel = rawSignalChannel+ ? (channel) => {+ if (channel === 'files') bumpSkillsCatalogGen();+ rawSignalChannel(channel);+ }+ : undefined;// Concurrency guard: at most 1 in-flight request per local-op endpointconst localOpGuard = localOpConcurrencyGuard ?? createConcurrencyGuard();@@ -5238,6 +5249,86 @@ export function createApiExtension(* mis-attributed to an unrelated later doc write). Best-effort: a flush* failure is logged, never fatal to the mutation that already succeeded.*/+ // Interactive write handlers must NOT hold their response on this flush:+ // the shadow-git staging walk scales with the content tree and measured+ // 27-48s on monorepo-sized roots - a create that "never auto-opens" is a+ // create whose response is still staging git state. The chain keeps flushes+ // serialized so version boundaries survive; a handler that needs the+ // PREVIOUS write committed before ITS write lands (the create-then-edit+ // coalescing hazard) drains the chain first - milliseconds in the common+ // case, and the cost lands only on back-to-back writers.+ // Skill lifecycle ops used to kick an immediate (already-deferred) full+ // ignore rebuild - but the walk floods the single-threaded event loop with+ // readdir/stat completions on monorepo roots, starving the very responses+ // the deferral was protecting (profiled live: readdir+stat dominated a 30s+ // create). The sync allow-list swap already admits the dir for SERVING;+ // the walk only re-admits it for the FILE WATCHER, which tolerates a+ // settle delay. One trailing rebuild after the burst quiets: interactive+ // work stays smooth and external-edit pickup self-heals in ~15s. Real+ // ignore-RULE changes still rebuild immediately via the ignore-watcher.+ // The detected-skill catalog enumeration stat-walks every bundle across all+ // harness homes SYNCHRONOUSLY - ~37k files under ~/.claude/plugins on a+ // real machine - and the client refetches the list on every skills-changed+ // signal, so uncached back-to-back requests pile sync walks onto the event+ // loop (profiled live inside a 24s create). Generation + short TTL: any+ // skill mutation bumps the generation, and even a missed bump is capped at+ // TTL staleness.+ let skillsCatalogGen = 0;+ // Same shape for the FULL /api/skills payload: the handler stamp-walks every+ // in-place bundle synchronously (129 dirs on a worktree-heavy monorepo), the+ // client refetches on every skills-changed signal, and those bursts queue+ // ahead of whatever mutation is in flight - measured as 25s creates with a+ // renderer attached vs 92ms without one.+ let skillsListCache: { at: number; gen: number; fp: string; body: unknown } | null = null;+ let installedCatalogCache: {+ at: number;+ gen: number;+ key: string;+ value: ReturnType<typeof enumerateInstalledSkills>;+ } | null = null;+ function bumpSkillsCatalogGen(): void {+ skillsCatalogGen += 1;+ }+ function enumerateInstalledSkillsCached(+ opts: Parameters<typeof enumerateInstalledSkills>[0],+ ): ReturnType<typeof enumerateInstalledSkills> {+ const key = `${opts?.projectDir ?? ''}|${opts && 'home' in opts ? opts.home : ''}`;+ const now = Date.now();+ if (+ installedCatalogCache !== null &&+ installedCatalogCache.gen === skillsCatalogGen &&+ installedCatalogCache.key === key &&+ now - installedCatalogCache.at < 5_000+ ) {+ return installedCatalogCache.value;+ }+ const value = enumerateInstalledSkills(opts);+ installedCatalogCache = { at: now, gen: skillsCatalogGen, key, value };+ return value;+ }+ let deferredIgnoreRebuildTimer: NodeJS.Timeout | null = null;+ function scheduleDeferredIgnoreRebuild(): void {+ if (!contentFilter) return;+ if (deferredIgnoreRebuildTimer !== null) clearTimeout(deferredIgnoreRebuildTimer);+ deferredIgnoreRebuildTimer = setTimeout(() => {+ deferredIgnoreRebuildTimer = null;+ void contentFilter?.rebuildIgnorePatterns().catch(() => {});+ // Two minutes, not seconds: the rebuild's completion cascades into+ // derived-view rebuilds (backlink full re-read of the corpus), and any+ // fuse short enough to land between two interactive ops makes the+ // SECOND op pay for the first one's cascade - measured repeatedly as+ // 20-40s ops on a monorepo root. Skill ops never change ignore RULES;+ // this walk only re-admits the new dir to the file watcher, and the+ // managed-artifact watcher covers skill-dir edits in the meantime.+ }, 120_000);+ }+ let okArtifactFlushChain: Promise<void> = Promise.resolve();+ function scheduleOkArtifactFlush(context: string): void {+ bumpSkillsCatalogGen();+ okArtifactFlushChain = okArtifactFlushChain+ .then(() => commitOkArtifactWrite(context))+ .catch(() => {});+ }async function commitOkArtifactWrite(context: string): Promise<void> {if (!flushContributors) return;try {@@ -6540,7 +6631,7 @@ export function createApiExtension(const identity = resolveProjectIdentity(projectDir ?? contentDir);// Same `homeDirOverride` seam as every other home-scanning surface here —// without it a rig (or embedded host) enumerates the REAL ~/.claude/plugins.- const catalog = enumerateInstalledSkills({+ const catalog = enumerateInstalledSkillsCached({projectDir: identity,...(homeDirOverride !== undefined ? { home: homeDirOverride } : {}),});@@ -7549,6 +7640,7 @@ export function createApiExtension(writeFileSync(okignorePath, '', 'utf-8');}if (contentFilter) {+ bumpSkillsCatalogGen();await contentFilter.rebuildIgnorePatterns();}} catch (err) {@@ -9136,7 +9228,9 @@ export function createApiExtension();}}- await recordDerivedDocumentBestEffort(docName, initialContent, 'create-page');+ // Best-effort for real (see the skill-put site): never hold a create+ // response on the derived-index command queue.+ void recordDerivedDocumentBestEffort(docName, initialContent, 'create-page');signalChannel?.('files');if (templateScopeForLog !== undefined) {// Cardinality-bounded structured event — `templateScope` is one of@@ -12675,7 +12769,7 @@ export function createApiExtension(okArtifactKey('folder-frontmatter', validated.folderRel),`folder-frontmatter-${result.action === 'deleted' ? 'delete' : 'edit'}: ${result.path}`,);- await commitOkArtifactWrite('folder-config-put');+ scheduleOkArtifactFlush('folder-config-put');}}@@ -13215,7 +13309,7 @@ export function createApiExtension(okArtifactKey('template', validated.folderRel, name),`${templateCreated ? 'template-create' : 'template-edit'}: ${templateRelPath}`,);- await commitOkArtifactWrite('template-put');+ scheduleOkArtifactFlush('template-put');successResponse(res,200,@@ -13312,7 +13406,7 @@ export function createApiExtension(okArtifactKey('template', validated.folderRel, name),`template-delete: ${result.path}`,);- await commitOkArtifactWrite('template-delete');+ scheduleOkArtifactFlush('template-delete');// Mark the content doc removed so a stale tab redirects instead of// offering to resurrect it (parity with ordinary doc deletion).recentlyRemovedDocs?.setDeleted(templateDocNameFor(validated.folderRel, name));@@ -13512,7 +13606,7 @@ export function createApiExtension(`template-rename: ${result.fromPath} -> ${result.toPath}`,[{ from: result.fromPath, to: result.toPath }],);- await commitOkArtifactWrite('template-move');+ scheduleOkArtifactFlush('template-move');signalChannel?.('files');if (contentEditError) {@@ -13799,7 +13893,7 @@ export function createApiExtension(});}- await commitOkArtifactWrite('template-import');+ scheduleOkArtifactFlush('template-import');signalChannel?.('files');successResponse(@@ -14275,7 +14369,7 @@ export function createApiExtension(// Enumeration and hashing are the IO; the join itself is pure and lives in// core, where it can be tested without a plugin cache on disk.byName = pluginUpstreamsByName(- enumerateInstalledSkills({+ enumerateInstalledSkillsCached({projectDir: identity,...(homeDirOverride !== undefined ? { home: homeDirOverride } : {}),}).skills,@@ -14806,6 +14900,7 @@ export function createApiExtension(}const next = `${before === null || before.endsWith('\n') || before === '' ? (before ?? '') : `${before}\n`}${line}\n`;writeFileSync(gitignoreAbs, next, 'utf-8');+ bumpSkillsCatalogGen();await contentFilter?.rebuildIgnorePatterns();// VERIFY, then keep or revert. A negation rule is not universally@@ -14817,6 +14912,7 @@ export function createApiExtension(if (contentFilter?.isPathIgnored(skillFileRel)) {if (before === null) rmSync(gitignoreAbs, { force: true });else writeFileSync(gitignoreAbs, before, 'utf-8');+ bumpSkillsCatalogGen();await contentFilter.rebuildIgnorePatterns();errorResponse(res,@@ -14852,6 +14948,52 @@ export function createApiExtension(EmptyRequestSchema,catchErrors(async (_req, res) => {+ // Cache hit still runs a CHEAP in-place rescan (5-60ms): a skill dir+ // written straight to disk by an external writer must list without any+ // API mutation having bumped the generation - the no-restart admission+ // contract skills-list-admission.test.ts pins. PEEK, never swap: the+ // admission heal below fires off the PRE-swap excluded state, and+ // swapping here would silently defuse it.+ // Editor-home detection folds in too: a bare `mkdir .github/skills`+ // changes the offered install targets without emitting any signal, and+ // the probes are a handful of existsSync calls.+ const inPlaceFp =+ (contentFilter?.peekFreshInPlaceSkillDirsFingerprint() ?? '') ++ '\u0001' ++ (projectDir ? detectProjectSkillEditors(projectDir).join(',') : '') ++ '\u0001' ++ detectUserSkillHosts(skillsHome)+ .map((h) => h.editorId)+ .join(',') ++ '\u0001' ++ // GLOBAL host-dir bundles fold in too: the desktop bridge (and any+ // external tool) installs into `~/.claude/skills` & co without any+ // HTTP mutation, so no generation bump ever fires for those writes.+ // The one client refetch they trigger lands inside the cache TTL and+ // then nothing re-asks - the row read stale forever (the desktop+ // skills-studio smoke pins this).+ scanGlobalInPlaceSkills(skillsHome)+ .map((s) => s.dir)+ .sort()+ .join(',');+ // A moved fingerprint means external on-disk state changed; the+ // enumeration cache keys on the generation alone, so bump it or the+ // rebuilt response below would still be assembled from the stale+ // enumeration.+ if (skillsListCache !== null && skillsListCache.fp !== inPlaceFp) {+ bumpSkillsCatalogGen();+ }+ if (+ skillsListCache !== null &&+ skillsListCache.gen === skillsCatalogGen &&+ skillsListCache.fp === inPlaceFp &&+ Date.now() - skillsListCache.at < 5_000+ ) {+ successResponse(res, 200, SkillsListSuccessSchema, skillsListCache.body, {+ handler: 'skills-list',+ });+ return;+ }// Union both scopes: project skills (`<contentDir>/.ok/skills`, git-// shared) + global skills (`<home>/.ok/skills`, user-level). Each is// enriched from ITS OWN install marker — the project marker at@@ -15242,10 +15384,19 @@ export function createApiExtension(entry.scope === 'project' && entry.absolutePath? indexedSkillContentPath(entry.absolutePath, contentDir): null;+ // Bundle file PATHS ride the list (no content reads, and the list+ // response cache above absorbs the walks) so the sidebar tree can+ // nest each skill's files without a per-skill `GET /api/skill`+ // fan-out — N of those saturated the browser's request pool on+ // every skills-changed signal and queued imports/opens behind them.+ const filePaths = entry.absolutePath+ ? listSkillBundledFilePaths(dirname(entry.absolutePath))+ : [];+ const withFiles = filePaths.length > 0 ? { ...entry, filePaths } : entry;const withCanonical =canonicalPath === null || canonicalPath === entry.path- ? entry- : { ...entry, canonicalPath };+ ? withFiles+ : { ...withFiles, 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.@@ -15268,12 +15419,40 @@ export function createApiExtension(// 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(+ const healed = await healUnservableSkillAdmission(inPlace.map((e) => e.path),contentFilter ?? null,skillAdmissionHeal,);- successResponse(res, 200, SkillsListSuccessSchema, enriched, { handler: 'skills-list' });+ // The heal awaited a pattern rebuild, so the `ignored` flags computed+ // during the build above may already be stale - a bundle gitignored+ // moments ago must report `ignored: true` in THIS response, not the+ // next one (the immediate-admission contract the admission tests pin).+ // Only the ig-derived flag can change; recompute it in place.+ const responseBody = !healed+ ? enriched+ : {+ ...enriched,+ skills: enriched.skills.map((entry) => {+ if (entry.scope !== 'project') return entry;+ const opened = (entry as { canonicalPath?: string }).canonicalPath ?? entry.path;+ const nowIgnored = contentFilter?.isPathIgnored(opened) === true;+ const wasIgnored = (entry as { ignored?: boolean }).ignored === true;+ if (nowIgnored === wasIgnored) return entry;+ if (nowIgnored) return { ...entry, ignored: true };+ const { ignored: _drop, ...rest } = entry as { ignored?: boolean } & typeof entry;+ return rest;+ }),+ };+ skillsListCache = {+ at: Date.now(),+ gen: skillsCatalogGen,+ fp: inPlaceFp,+ body: responseBody,+ };+ successResponse(res, 200, SkillsListSuccessSchema, responseBody, {+ handler: 'skills-list',+ });},{ handler: 'skills-list', title: 'Failed to list skills.' },),@@ -15388,23 +15567,25 @@ export function createApiExtension(// seed DELETED it from the index instead of indexing it: its links never got// extracted and nothing pointed at its references until an unrelated rescan.if (contentFilter) {+ // The synchronous allow-list swap is what admits the new skill dir; the+ // FULL rebuild is a whole-content-tree walk that took seconds-to-minutes+ // on monorepo-sized roots and was holding the create response hostage+ // (every skill op queued behind it once walks overlapped). The client no+ // longer needs the awaited walk: opens resolve by the write's own path+ // and re-verify a stale ignored flag against a fresh list, so the walk+ // self-heals off-path.+ bumpSkillsCatalogGen();contentFilter.refreshInPlaceSkillDirs();- try {- // AWAITED on the authoring path, unlike the lifecycle ops' deferred- // rebuilds: the watcher event for the just-written SKILL.md fired- // BEFORE the allow-list swap and was rejected, and only the rebuild's- // reconcile re-admits it — a hash navigation straight to the new doc- // otherwise strands on a page index that does not have it yet.- await contentFilter.rebuildIgnorePatterns();- } catch {- // Fail-soft, matching the watcher's own rebuild: a stale allow-list- // costs this doc its links until the next rescan, not the write.- }+ scheduleDeferredIgnoreRebuild();}// Best-effort like every other derived-index mutation: the skill is already// on disk and committed by now, so a shutdown-time index error must not turn// a successful write into a 500 the caller retries.- await recordDerivedDocumentBestEffort(docName, markdown, 'skill-put');+ // Actually best-effort: the derived-index command queue serializes behind+ // any in-flight full ingest (boot, watcher re-ingest), which measured 20s++ // on monorepo roots - the freshness of search/links for this one doc is+ // not worth holding the create response.+ void recordDerivedDocumentBestEffort(docName, markdown, 'skill-put');}const handleSkillPut = withValidation(@@ -15423,6 +15604,12 @@ export function createApiExtension(}if (!validateSkillName(body.name, res, 'skill-put')) return;if (rejectReservedBuiltinSkill(body.name, res, 'skill-put')) return;+ // Deliberately NOT draining the flush chain here: on a live server the+ // chain routinely holds a monorepo-scale shadow staging job (25-90s+ // measured), and draining it made every create pay for it. The+ // serialized chain still orders commits; the rapid create-then-edit+ // coalescing window this loses is narrow and recoverable, a half-minute+ // create is neither.// Compose + validate the SKILL.md bytes server-side (OK// builds name+description). The body itself is then written through the@@ -15490,12 +15677,12 @@ export function createApiExtension(`${homeRel}/${body.name}/SKILL`,`skill-create: ${homeRel}/${body.name}/SKILL.md`,);- // AWAITED, unlike the lifecycle ops' fire-and-forget flushes: authoring+ // scheduled on the serialized flush chain (fire-and-forget; the chain keeps commits ordered): authoring// writes are versions. Two rapid PUTs (create then edit) with a// deferred flush coalesce into ONE commit, folding the create into// the edit — the timeline loses the version boundary and the// create snapshot stops being a restore target.- await commitOkArtifactWrite('skill-put');+ scheduleOkArtifactFlush('skill-put');}await seedSkillDerivedViews(body.scope === 'project'@@ -15573,12 +15760,12 @@ export function createApiExtension(okArtifactKey('skill', '', body.name),`${created ? 'skill-create' : 'skill-edit'}: ${relPath}`,);- // AWAITED, unlike the lifecycle ops' fire-and-forget flushes: authoring+ // scheduled on the serialized flush chain (fire-and-forget; the chain keeps commits ordered): authoring// writes are versions. Two rapid PUTs (create then edit) with a// deferred flush coalesce into ONE commit, folding the create into// the edit — the timeline loses the version boundary and the// create snapshot stops being a restore target.- await commitOkArtifactWrite('skill-put');+ scheduleOkArtifactFlush('skill-put');}// Seed the derived views from the bytes we just wrote. The live-derived// index refreshes on a debounce after a change hook, which an API write@@ -15735,6 +15922,7 @@ export function createApiExtension(if (result.existed) {if (scope === 'project') {attributeOkArtifactWrite(actor, dirRel, `skill-delete: ${dirRel}`);+ bumpSkillsCatalogGen();void commitOkArtifactWrite('skill-delete');}signalChannel?.('files');@@ -15958,17 +16146,12 @@ export function createApiExtension(// rename ~1.7s on a big project. Ordering inside the chain preserved:// rebuild before re-index, or we re-index against the pre-rename// world.+ bumpSkillsCatalogGen();contentFilter?.refreshInPlaceSkillDirs();- // The PROJECTION is awaited: when this responds, the moved docs are- // queryable (the derived-index API readiness gate contract). It- // reads the relocated files from disk and mutates the index- // directly, so the synchronous allow-list swap above is the only- // admission it relies on — the full nested-ignore rebuild (watcher- // reconcile + content-scope refresh) is derived state that- // self-heals and stays off the response path.- await reindexMovedProjectSkillDocs(skillsRoot, body.fromName, body.toName);- await reindexRewrittenSkillRefDocs(refRewrites, body.toName);- void contentFilter?.rebuildIgnorePatterns().catch(() => {});+ void reindexMovedProjectSkillDocs(skillsRoot, body.fromName, body.toName)+ .then(() => reindexRewrittenSkillRefDocs(refRewrites, body.toName))+ .catch(() => {});+ scheduleDeferredIgnoreRebuild();}const fromKeyPath = skillRelPath(resolve(skillsRoot, body.fromName), body.scope);@@ -16477,8 +16660,9 @@ export function createApiExtension(// 404s and the editor falls back to a Files tab. Same reason and same// placement as `handleSkillInstall`, which rebuilds before every exit.// Allow-list swap sync; the expensive rebuild self-heals off-path.+ bumpSkillsCatalogGen();contentFilter?.refreshInPlaceSkillDirs();- void contentFilter?.rebuildIgnorePatterns().catch(() => {});+ scheduleDeferredIgnoreRebuild();signalChannel?.('files');successResponse(@@ -16605,8 +16789,9 @@ export function createApiExtension(// call, same reason, same placement as `handleSkillInstall`. The// allow-list SWAP is synchronous (admission gates the client's next// open); the full rebuild + watcher reconcile self-heal off-path.+ bumpSkillsCatalogGen();contentFilter?.refreshInPlaceSkillDirs();- void contentFilter?.rebuildIgnorePatterns().catch(() => {});+ scheduleDeferredIgnoreRebuild();successResponse(res,@@ -17801,8 +17986,14 @@ export function createApiExtension(// allow-list is rebuilt its SKILL.md is not servable, and opening the skill// the user just imported falls back to a Files tab. Allow-list swap// sync; the expensive rebuild self-heals off-path.+ bumpSkillsCatalogGen();contentFilter?.refreshInPlaceSkillDirs();- void contentFilter?.rebuildIgnorePatterns().catch(() => {});+ scheduleDeferredIgnoreRebuild();+ // Tell clients the catalog moved. The watcher cannot: the new dir is+ // outside its coverage until the deferred rebuild reconciles it, so+ // without this push the sidebar never refetches and the skill the+ // user just imported has no row to click for two minutes.+ signalChannel?.('files');respondSkillImport(res, outcome);} catch (e) {@@ -18035,8 +18226,12 @@ export function createApiExtension(// call, same reason, same placement as `handleSkillInstall`. The// allow-list SWAP is synchronous (admission gates the client's next// open); the full rebuild + watcher reconcile self-heal off-path.+ bumpSkillsCatalogGen();contentFilter?.refreshInPlaceSkillDirs();- void contentFilter?.rebuildIgnorePatterns().catch(() => {});+ scheduleDeferredIgnoreRebuild();+ // Same client push as the single-import path: the watcher cannot see+ // the new dirs until the deferred rebuild reconciles them.+ signalChannel?.('files');successResponse(res,@@ -18539,8 +18734,9 @@ export function createApiExtension(// 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.+ bumpSkillsCatalogGen();contentFilter?.refreshInPlaceSkillDirs();- void contentFilter?.rebuildIgnorePatterns().catch(() => {});+ scheduleDeferredIgnoreRebuild();successResponse(res,200,@@ -18648,8 +18844,9 @@ export function createApiExtension(// 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.+ bumpSkillsCatalogGen();contentFilter?.refreshInPlaceSkillDirs();- void contentFilter?.rebuildIgnorePatterns().catch(() => {});+ scheduleDeferredIgnoreRebuild();successResponse(res,200,@@ -18724,8 +18921,9 @@ export function createApiExtension(// 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.+ bumpSkillsCatalogGen();contentFilter?.refreshInPlaceSkillDirs();- void contentFilter?.rebuildIgnorePatterns().catch(() => {});+ scheduleDeferredIgnoreRebuild();successResponse(res,200,@@ -18819,8 +19017,9 @@ export function createApiExtension(// 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.+ bumpSkillsCatalogGen();contentFilter?.refreshInPlaceSkillDirs();- void contentFilter?.rebuildIgnorePatterns().catch(() => {});+ scheduleDeferredIgnoreRebuild();successResponse(res,200,@@ -19586,8 +19785,9 @@ export function createApiExtension(// call, same reason, same placement as `handleSkillInstall`. The// allow-list SWAP is synchronous (admission gates the client's next// open); the full rebuild + watcher reconcile self-heal off-path.+ bumpSkillsCatalogGen();contentFilter?.refreshInPlaceSkillDirs();- void contentFilter?.rebuildIgnorePatterns().catch(() => {});+ scheduleDeferredIgnoreRebuild();successResponse(res,@@ -19699,10 +19899,12 @@ 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();+ // The sync allow-list swap admits the dir; the full walk self-heals+ // off-path (it held the response for a whole content-tree scan on+ // large roots).+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();successResponse(res,@@ -19804,8 +20006,9 @@ export function createApiExtension(// call, same reason, same placement as `handleSkillInstall`. The// allow-list SWAP is synchronous (admission gates the client's next// open); the full rebuild + watcher reconcile self-heal off-path.+ bumpSkillsCatalogGen();contentFilter?.refreshInPlaceSkillDirs();- void contentFilter?.rebuildIgnorePatterns().catch(() => {});+ scheduleDeferredIgnoreRebuild();respondSkillReimport(res, outcome);} catch (e) {@@ -20052,6 +20255,9 @@ export function createApiExtension(// everything had. The endpoint's whole contract is that it reports what// happened; a bookkeeping failure must not erase that report.try {+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ bumpSkillsCatalogGen();await contentFilter?.rebuildIgnorePatterns();} catch (e) {getLogger('skills-reimport-bulk').warn(diff --git a/packages/server/src/backlink-index.test.ts b/packages/server/src/backlink-index.test.tsindex 1218072b4..158e8f557 100644--- a/packages/server/src/backlink-index.test.ts+++ b/packages/server/src/backlink-index.test.ts@@ -2002,7 +2002,13 @@ describe('reconcileWithDisk', () => {const reloaded = new BacklinkIndex({ projectDir, contentDir });expect(await reloaded.loadFromDisk()).toBe(true);const diff = await reloaded.reconcileWithDisk();- expect(diff).toEqual({ added: 0, updated: 0, deleted: 0, deletedDocNames: [] });+ expect(diff).toEqual({+ added: 0,+ updated: 0,+ deleted: 0,+ deletedDocNames: [],+ changedDocs: [],+ });// Backlinks should still be intact after a no-op reconcile.expect(reloaded.getBacklinks('beta')).toEqual([diff --git a/packages/server/src/backlink-index.ts b/packages/server/src/backlink-index.tsindex 9c2983174..582ba551a 100644--- a/packages/server/src/backlink-index.ts+++ b/packages/server/src/backlink-index.ts@@ -2384,6 +2384,13 @@ export class BacklinkIndex {added: number;updated: number;deleted: number;+ /**+ * The docs this reconcile re-parsed (new or mtime-changed), with the disk+ * path each was read from. Lets the caller update sibling per-doc indexes+ * (local targets) for exactly the changed set instead of re-parsing the+ * whole corpus. Paths only - contents are not retained.+ */+ changedDocs: Array<{ docName: string; filePath: string }>;/*** DocNames dropped because their file is gone from disk (global skill* bundle nodes excluded — they live outside contentDir). Includes docs@@ -2411,9 +2418,10 @@ export class BacklinkIndex {updated: number;deleted: number;deletedDocNames: string[];+ changedDocs: Array<{ docName: string; filePath: string }>;}> {if (!existsSync(this.contentDir))- return { added: 0, updated: 0, deleted: 0, deletedDocNames: [] };+ return { added: 0, updated: 0, deleted: 0, deletedDocNames: [], changedDocs: [] };const storedMtimes = this.mtimesByBranch.get(branch) ?? new Map<string, number>();const rawDocs: Array<{ docName: string; filePath: string }> = [];@@ -2499,7 +2507,13 @@ export class BacklinkIndex {}this.mtimesByBranch.set(branch, newMtimes);- return { added, updated, deleted, deletedDocNames };+ return {+ added,+ updated,+ deleted,+ deletedDocNames,+ changedDocs: toProcess.map(({ docName, filePath }) => ({ docName, filePath })),+ };}/**diff --git a/packages/server/src/content-filter.ts b/packages/server/src/content-filter.tsindex b8aefb7c6..201414c4a 100644--- a/packages/server/src/content-filter.ts+++ b/packages/server/src/content-filter.ts@@ -1147,6 +1147,14 @@ export interface ContentFilter {* refresh step). No-op when no provider was supplied.*/refreshInPlaceSkillDirs(): void;+ /** Cheap identity of the current in-place allow-list — lets read-side caches+ * detect a skill dir that appeared on disk without any API mutation. */+ inPlaceSkillDirsFingerprint(): string;+ /** Fingerprint of a FRESH rescan WITHOUT swapping the live allow-list - the+ * read-side cache uses it to detect external skill-dir changes while the+ * admission-heal's excluded-detection still sees the pre-swap state (a+ * pre-heal swap would silently defuse the heal's trigger). */+ peekFreshInPlaceSkillDirsFingerprint(): string;}/**@@ -1677,6 +1685,19 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {}},+ inPlaceSkillDirsFingerprint(): string {+ return [...inPlaceSkillDirs].sort().join('\n');+ },++ peekFreshInPlaceSkillDirsFingerprint(): string {+ if (!opts.rescanInPlaceSkillDirs) return [...inPlaceSkillDirs].sort().join('\n');+ try {+ return [...opts.rescanInPlaceSkillDirs()].sort().join('\n');+ } catch {+ return [...inPlaceSkillDirs].sort().join('\n');+ }+ },+async rebuildIgnorePatterns(): Promise<RebuildResult> {// Single-flight with one trailing run. Every skill lifecycle op// calls this, a bulk move once PER SKILL, and each run is a full@@ -1720,8 +1741,12 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {try {const counts = buildPatternState();// Refresh sibling-asset counts against the new ignore rules.+ // Yielding: the rebuild is background work and must not hold the+ // event loop for the whole walk.dirCount.clear();- refreshDirCount();+ if (singleDocRelPath === undefined) {+ await populateDirCountYielding(contentDir, isIgnored, dirCount);+ }const durationMs = Date.now() - startedAt;span.setAttributes({@@ -1816,6 +1841,50 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {* Walk contentDir to count included `.md`/`.mdx` files per directory.* Populates the refcount map used by the sibling-asset inclusion rule.*/+/**+ * Yielding variant for RUNTIME rebuilds: same traversal as+ * {@link populateDirCount}, but hands the event loop back every+ * `YIELD_EVERY_DIRS` directories. On monorepo-sized roots the synchronous+ * walk holds the loop for 20s+, and a rebuild scheduled after a skill op+ * then starves the NEXT interactive request - the walk may take its time,+ * but never in one uninterruptible slice. Boot keeps the sync version (one+ * blocking walk before serving is the boot scan's contract).+ */+const YIELD_EVERY_DIRS = 50;+async function populateDirCountYielding(+ dir: string,+ isIgnored: (path: string) => boolean,+ dirCount: Map<string, number>,+): Promise<void> {+ const stack: Array<{ dir: string; relPath: string }> = [{ dir, relPath: '' }];+ let sinceYield = 0;+ while (stack.length > 0) {+ const { dir: cur, relPath } = stack.pop() as { dir: string; relPath: string };+ sinceYield += 1;+ if (sinceYield >= YIELD_EVERY_DIRS) {+ sinceYield = 0;+ await new Promise((resolve) => setImmediate(resolve));+ }+ let entries: import('node:fs').Dirent[];+ try {+ entries = readdirSync(cur, { withFileTypes: true });+ } catch (err) {+ log.warn({ dir: cur, err }, `Failed to read directory for dir-count: ${cur}`);+ continue;+ }+ for (const entry of entries) {+ const childRel = relPath ? `${relPath}/${entry.name}` : entry.name;+ if (entry.isDirectory()) {+ if (BUILTIN_SKIP_DIRS.has(entry.name)) continue;+ if (isIgnored(childRel) || isIgnored(`${childRel}/`)) continue;+ stack.push({ dir: join(cur, entry.name), relPath: childRel });+ } else if (entry.isFile() && isSupportedDocFile(entry.name) && !isIgnored(childRel)) {+ dirCount.set(relPath, (dirCount.get(relPath) ?? 0) + 1);+ }+ }+ }+}+function populateDirCount(dir: string,relPath: string,@@ -2390,6 +2459,19 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom}},+ inPlaceSkillDirsFingerprint(): string {+ return [...inPlaceSkillDirs].sort().join('\n');+ },++ peekFreshInPlaceSkillDirsFingerprint(): string {+ if (!opts.rescanInPlaceSkillDirs) return [...inPlaceSkillDirs].sort().join('\n');+ try {+ return [...opts.rescanInPlaceSkillDirs()].sort().join('\n');+ } catch {+ return [...inPlaceSkillDirs].sort().join('\n');+ }+ },+async rebuildIgnorePatterns(): Promise<RebuildResult> {// Single-flight with one trailing run. Every skill lifecycle op// calls this, a bulk move once PER SKILL, and each run is a fulldiff --git a/packages/server/src/derived-document-index.test.ts b/packages/server/src/derived-document-index.test.tsindex cd47cfffa..bb1928c20 100644--- a/packages/server/src/derived-document-index.test.ts+++ b/packages/server/src/derived-document-index.test.ts@@ -432,12 +432,20 @@ describe('DerivedDocumentIndex', () => {await settleStartup(rig);const backlinksReplacement = createDeferred();const tagsReplacement = createDeferred();- vi.spyOn(BacklinkIndex.prototype, 'rebuildFromDisk').mockImplementationOnce(- async () => backlinksReplacement.promise,+ vi.spyOn(BacklinkIndex.prototype, 'reconcileWithDisk').mockImplementationOnce(() =>+ backlinksReplacement.promise.then(() => ({+ added: 0,+ updated: 0,+ deleted: 0,+ deletedDocNames: [],+ changedDocs: [],+ })),);const tagInit = vi- .spyOn(TagIndex.prototype, 'init')- .mockImplementationOnce(async () => tagsReplacement.promise);+ .spyOn(TagIndex.prototype, 'reconcileWithDisk')+ .mockImplementationOnce(() =>+ tagsReplacement.promise.then(() => ({ added: 0, updated: 0, deleted: 0 })),+ );const refresh = rig.index.refreshContentScope();let mutationSettled = false;diff --git a/packages/server/src/derived-document-index.ts b/packages/server/src/derived-document-index.tsindex cbd21a258..1d4930a95 100644--- a/packages/server/src/derived-document-index.ts+++ b/packages/server/src/derived-document-index.ts@@ -1,3 +1,4 @@+import { readFile } from 'node:fs/promises';import type { DerivedViewChannel } from '@inkeep/open-knowledge-core';import {type BacklinkEntry,@@ -548,7 +549,17 @@ export class DerivedDocumentIndexrefreshContentScope(): Promise<void> {return this.runCommand(async () => {const branch = this.backlinkIndex.getActiveBranch();- await this.backlinkIndex.rebuildFromDisk(branch);+ // Incremental, not the full rebuild: this runs after every content-filter+ // rebuild, and each skill op schedules one of those — so on a+ // monorepo-sized root the full variant re-parsed the whole corpus+ // (~20-30s of CPU) minutes after every skill op, pegging the single+ // server thread and freezing whatever op landed during it. A scope+ // change only adds/removes a handful of files, which is exactly what+ // the mtime-witnessed reconcile covers: both walks apply the LIVE+ // filter, so newly admitted files parse as new, newly excluded ones+ // prune, and an empty witness map (first pass on a branch) degrades to+ // the full scan on its own.+ const scopeDiff = await this.backlinkIndex.reconcileWithDisk(branch);let globalIngestFailed = false;let globalIngestFailure: unknown;try {@@ -557,8 +568,28 @@ export class DerivedDocumentIndexglobalIngestFailed = true;globalIngestFailure = err;}- await this.tagIndex.init();- await this.rebuildLocalTargets('content-filter');+ // Same incremental treatment: `init()` is the tag index's own full-corpus+ // parse, doubling the storm the backlink swap above removes.+ await this.tagIndex.reconcileWithDisk();+ // The local-target leg was the LAST full-corpus parse on this path+ // (`rebuildLocalTargets` -> `populateFromDisk` reads and assesses every+ // doc; profiled at ~10s on a monorepo root, pegging the server during+ // whatever op triggered the refresh). Targets reconcile from the watcher+ // inventory as before; SOURCE assessments update for exactly the docs+ // the backlink reconcile re-parsed, plus removals for the ones it+ // dropped. A read that fails downgrades to removal - matching the live+ // update path's admission-flip behavior.+ this.reconcileLocalTargetInventory();+ for (const { docName, filePath } of scopeDiff.changedDocs) {+ try {+ this.localTargetIndex.setSource(docName, await readFile(filePath, 'utf-8'));+ } catch {+ this.localTargetIndex.removeSource(docName);+ }+ }+ for (const docName of scopeDiff.deletedDocNames) {+ this.localTargetIndex.removeSource(docName);+ }await this.saveBothLogOnly('content-filter', branch);// Content scope changed wholesale; signalAllRelations() -> maybeSignalLocalTargets// emits `local-targets` off the rebuild's generation jump (no baseline sync).diff --git a/packages/server/src/skill-projection.ts b/packages/server/src/skill-projection.tsindex fbf8894c1..f7ce36f15 100644--- a/packages/server/src/skill-projection.ts+++ b/packages/server/src/skill-projection.ts@@ -844,6 +844,21 @@ export function reverseProjectSkill(/** Max bytes inlined as text for a bundled skill file; larger files report `text: null`. */const MAX_BUNDLED_FILE_BYTES = 256 * 1024;+/**+ * Paths-only bundle listing for the skills LIST response: every file beside+ * SKILL.md, no content reads. Fail-soft (empty on a vanished/unreadable dir) —+ * a listing miss costs the sidebar its nested file rows for one refresh, never+ * the list response.+ */+export function listSkillBundledFilePaths(skillDir: string): string[] {+ try {+ if (!existsSync(skillDir)) return [];+ return listSkillFiles(skillDir).filter((rel) => rel !== 'SKILL.md');+ } catch {+ return [];+ }+}+/** Recursively list files under `dir`, POSIX-relative, sorted (deterministic). */function listSkillFiles(dir: string, prefix = ''): string[] {const out: string[] = [];