Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): repair skill lifecycle contracts (PRD-8343) (#4266)
tim-inkeepa117abb69f93
diff --git a/.changeset/fluffy-clouds-report.md b/.changeset/fluffy-clouds-report.mdnew file mode 100644index 000000000..4ff8046fd--- /dev/null+++ b/.changeset/fluffy-clouds-report.md@@ -0,0 +1,13 @@+---+"@inkeep/open-knowledge": patch+---++`move` on a skill across the Project and Global levels (`skill: { from, to, scope, toScope }`) now uses the same scope-move endpoint as the Skills Studio. The whole bundle moves, binary files included, its entry in `.ok/skills-lock.json` follows it, and it is re-projected into the editor locations the destination level can host. History does not transfer, and everything else (the `agents` hub, custom roots, and any editor with no skills root at that level) is removed at the source and not re-created at the destination; the response returns them as `droppedLocations` so you can re-add the ones that level can place with `install`, and the tool's success text names the `agents`-hub equivalent for an editor that reads the hub there and says so when no destination-level placement exists. That reading of `droppedLocations` holds only on a success: on a reported failure the field lists source-side placements the call had already removed, so installing them at the destination would spread a retained copy rather than restore anything. Before, the MCP tool copied text files one at a time, dropped binary files and the lock entry, landed the skill with no locations, and still reported that it had been re-projected. A move that also renames the skill lands directly under the new name (`POST /api/skill/move-scope` accepts an optional `toName`), and nothing is written when that name is already taken at the destination. If the destination name patch fails before source removal, cleanup removes only the new copy when possible and reports any cleanup failure; the source stays intact. If source removal fails after deleting some files, the complete destination copy is retained for recovery; unrelated skills with the old name are untouched. Errors identify the partial source and retained destination so callers can inspect both before retrying, and the endpoint stamps a `moveState` code on the failures it reports (`nothing-written`, `destination-removed`, `destination-stray`, `destination-retained`, `destination-retained-blocking`, `destination-unreadable`, `partially-applied`) so a caller can tell what is on disk without reading the English. When a retained destination is reported, `sourceState` (`intact`, `lossy`, `unknown`) says what the source looked like when its removal failed, so a caller can tell a safe-to-remove duplicate from a copy that may hold the only surviving files. A retained destination is marked on disk, so a retry against it is refused as `destination-retained-blocking`, which replays the recorded `sourceState` alongside it: on `intact` the retained copy is a redundant duplicate and removing it is what unblocks the retry, and otherwise the caller reconciles rather than deletes. A failure that could not clear the destination name also carries `retentionLedger` (`unreadable`, `occupant-unverifiable`): `unreadable` means the retained-destination ledger itself could not be read, and `occupant-unverifiable` means the directory at the destination could not be read, so the server could not confirm whether it is a copy an earlier failed move retained. Either way, treat that occupant the way you would a `sourceState` other than `intact` and compare it against the source before deleting it, including on a `nothing-written` failure that would otherwise read as an ordinary, safely-retryable collision. `SKILL_RETENTION_LEDGER_CODES`, `SkillRetentionLedgerCode`, and `isSkillRetentionLedgerCode` ship from core beside the existing move-state and source-state guards. Copying, source removal, lock transfer, and editor projection remain separate steps, not an all-or-nothing transaction.++`PUT /api/skill`, `POST /api/skill/reimport`, and the bulk import and update endpoints now return `warningCodes` (`skill-name-vendor-word`, `skill-body-too-long`) aligned 1:1 with `warnings`, matching `POST /api/skill/import`. The MCP `import` tool concatenates acquisition and placement codes in the same order as their display text, so `warningCodes[i]` is always the code for `warnings[i]`. MCP `write` and `edit` expose these arrays in their structured SKILL.md results and declare them in their output schemas, including empty arrays when there are no warnings. Creating a skill through `PUT /api/skill` no longer returns each warning twice. A non-string warning inside a `warnings` array is now rendered as text and keeps its paired code instead of being dropped from the structured list while still showing in `content[0].text`, and a `warnings` payload that is not an array at all now yields one explicit "treat this result as unverified" warning instead of an empty, code-paired all-clear.++The three records under `.ok/` that track installs (`installed-skills.json`, `.ok/skills-lock.json`, and the placements store) now refuse to rewrite a file they could not read, rather than replacing every entry it held with the one being written. A corrupt or truncated file is reported instead of silently clobbered.++Because that refusal can land after the change it accompanies has already been made, the operations it can interrupt no longer report a completed change as a failure. Deleting, renaming, or moving a skill across levels whose bookkeeping fails now answers 200 with a `warnings` member naming what could not be recorded, so a caller can tell "the skill moved and one record is stale" from "the move did not happen". Before, a delete that had already removed the skill answered `500 Failed to delete skill.`, and retrying it re-ran the same refusal indefinitely.++`install` refuses `mode` passed without `add` or `convert` (`` `mode` needs `add` or `convert` ``) instead of silently ignoring it, and reports a missing `mode` on `convert` before contacting the server.diff --git a/docs/content/features/skills/reference.mdx b/docs/content/features/skills/reference.mdxindex ff22ff04f..b1396fea3 100644--- a/docs/content/features/skills/reference.mdx+++ b/docs/content/features/skills/reference.mdx@@ -25,7 +25,7 @@ A new skill goes into a skills folder the project already has. OpenKnowledge nevOpenKnowledge keeps one source folder per skill. Other locations use symlinks by default, so they read the same bytes. The install menu can convert a location to a copy, which OpenKnowledge refreshes until it is edited independently outside the app.-**Make source** relocates the real folder. Moving between Project and Global recreates the skill and its locations; history does not transfer. Project skills are versioned with project content. Global skills outside a base carry no version history.+**Make source** relocates the real folder. Moving between Project and Global re-creates the skill in the destination scope: history does not transfer, and the editor locations the destination scope can host are re-projected there. Its `.agents/skills` hub entry, any **Add custom path** locations, and any AI tool with no skills folder at that scope are removed at the source and not re-created at the destination; add the ones the destination scope can hold again from the destination skill. That applies to a move that succeeded: if the move fails, the same list names locations it had already removed at the source, so adding them from the destination would spread the copy the failure left behind. Project skills are versioned with project content. Global skills outside a base carry no version history.## Existing skillsdiff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdxindex 991d19ad1..822967fab 100644--- a/docs/content/reference/mcp.mdx+++ b/docs/content/reference/mcp.mdx@@ -30,7 +30,7 @@ To point an MCP client at this server, locally or over a tunnel from another mac| `write` | Create or overwrite a `document`, `folder`, `template`, `skill`, or `asset`. For a document: `{ path, content }`, or `{ path, template }` to instantiate from a folder template. `position` selects `replace` (full rewrite; the only mode that touches frontmatter), `append`, or `prepend`. `extension` selects `.md` (default) or `.mdx` for a new document; an existing doc keeps its extension (the MCP cannot change it). An `asset` takes exactly one of `content` (base64, for small files) or `source` (a local path the server reads, for large files) || `edit` | Modify a `document` (body find/replace **or** a frontmatter merge-patch), a `folder` (frontmatter merge-patch), a `template`, or a `skill`. Body edits take `{ path, find, replace, occurrence? }`; `occurrence` selects which match (1 = first) || `delete` | Delete a `document` (one path or an array), `folder`, `template`, `skill`, or `asset` |-| `move` | Move or rename a `document`, `folder`, `asset`, `template`, or `skill`, rewriting every affected link (templates and skills carry no inbound links). A skill also moves between Project and Global scope via `scope` + `toScope`: history does not transfer, and you re-establish its editor locations with `install` |+| `move` | Move or rename a `document`, `folder`, `asset`, `template`, or `skill`, rewriting every affected link (templates and skills carry no inbound links). A skill also moves between Project and Global scope via `scope` + `toScope`: history does not transfer; the editor locations the destination level can host are re-projected there, while everything else (the `agents` hub, custom roots, and any editor with no skills root at that level) is removed at the source and not re-created at the destination. The removed locations come back as `droppedLocations`; re-add the ones that level can place with `install`. That only holds on a success: on a failed move the same field lists source-side placements the call had already removed, so installing them at the destination would spread a retained copy instead of restoring anything || `install` | Manage **where** a skill is available. A skill is one real folder (its source, which itself loads) plus managed copies/symlinks at other locations — there is no draft state and no "uninstall everywhere". `add` / `remove` change the other locations (editor ids, `agents`, or custom root paths); `mode` flips an editor copy↔symlink; `source` relocates the real folder. To make a skill stop existing, use `delete` || `import` | Acquire a skill from a full skills.sh skill-page URL (`https://www.skills.sh/<owner>/<repo>/<skill>`, or `https://www.skills.sh/site/<hostname>/<skill>` for a website catalog), `owner/repo[/subpath]`, a git URL, or a local / `file://` path into the vendor-neutral `.agents/skills/<name>/` hub as versioned content — live immediately, with cross-harness projection via `install`. Pass the required `add` array with at least one install location (an editor id, `agents`, or a custom root path). Use `skill` to choose one skill from a multi-skill source or a `skills({ query })` result. Records provenance in `.ok/skills-lock.json`; a name collision lands under `<name>-imported`; scripts are imported as content and never executed || `checkpoint` | Save a project-wide version snapshot — a single restore point. Returns its `version` |@@ -46,6 +46,8 @@ The write verbs nest their result under the same target key you wrote, mirroring`write` and `edit` results may carry a `warnings` array on the document entry (per entry for a batch); `restore_version` carries it at the top level. Entries are discriminated by `kind`. `content-divergence` and `disk-edit-reconciled` are write-integrity signals — the stored doc differs from what the call composed, so re-read it before editing further. `mermaid-parse-error` means the write landed but that fence won't render — fix the fence and re-edit.+`delete`, `move` and `install` on a `skill` target carry a separate `warnings` array of plain strings, not `kind`-discriminated entries. It reports work that did not undo the operation: bookkeeping records the server could not update after the skill itself was already deleted, renamed or moved, and — on a delete — that the directory removed was one an earlier failed move had retained for recovery. The operation succeeded; the warning names what to check or repair.+## Instantiating from a template`write` accepts a `template` field on the `document` target — `write({ document: { path, template } })` — that resolves against the cascade of templates available for the target document's parent folder, using the same folder-up walk the [Folders and templates](../advanced/folders-and-templates.mdx#templates) page describes. The template body becomes the new document's content; the template's own info block (its name and description) is stripped, so it doesn't bleed onto the document.diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 83dab157b..f460b2178 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -122,6 +122,7 @@ The app runs a collaboration server for the open project. It writes runtime stat| `.ok/local/logs/server-*.jsonl` | Local server logs, rotated at ~25 MB | In-project, gitignored || `.ok/local/cache/<branch>/backlinks.json` | Backlink-graph cache | In-project, gitignored || `.ok/local/installed-skills.json` | Per-project skill-install markers (which editors each skill is projected into) | In-project, gitignored |+| `.ok/local/skill-move-retained.json` | Bookkeeping for a skill move between Project and Global scope that could not finish: which destination copy was kept, why, and what the source looked like at the time. Keyed by scope and skill name, one record each. A record clears when a later move of that skill completes, when the copy at the destination stops matching the one recorded, or when you delete that skill at that scope. No document content | In-project, gitignored || `.ok/local/terminal/claude-settings-{mcp,tools,mcp-tools}.json` | Windows-only Claude launch settings written when **Open in Claude** requests MCP or tool preapproval; one of three possible files, overwritten rather than appended on each launch that uses that combination. macOS and Linux pass the same settings inline | In-project, gitignored || `.ok/local/comments/` | [Comments](/docs/features/comments) left on documents, one JSON file each — the note, the passage it quotes, and whether it has been sent | In-project, gitignored || `.ok/worktrees/<branch>/` | Git worktree checkout created when you open a branch in its own window (project switcher); the path is also added to `.git/info/exclude` | In-project, gitignored |@@ -142,6 +143,7 @@ On each launch and project open, the app also runs **repair sweeps**: it rewrite| `~/.ok/auth.yml` | Auth-token fallback, used only when the Keychain is unavailable. Written `0600` | **Yes** (`0600`) || `~/.ok/skill-state.yml`, `~/.ok/skill-install-events.jsonl` | Skill-install bookkeeping | No || `~/.agents/skills/<name>/`, `~/.claude/skills/<name>/`, … | Your global-scope skills, versioned in place in your home editor dirs (kept by `ok uninstall` unless `--purge-content`) | No |+| `~/.ok/local/installed-skills.json`, `~/.ok/local/skill-move-retained.json` | The same skill-install markers and unfinished-scope-move bookkeeping the tables above list under a project's `.ok/local/`, written under your home directory for Global-scope skills instead | No || `~/.ok/stats.jsonl` | Local "open with AI" handoff stats — local-only, no phone-home | No || `~/.ok/themes/` | Your saved color themes from the [Themes plugin](../plugins/themes.mdx), one Tinted Theming base16 YAML file per theme, written when you create or edit a theme | No || `~/.ok/mcp-status.json` | First-launch MCP consent record | No |@@ -243,6 +245,7 @@ On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` a| `.ok/local/logs/server-*.jsonl` | Local server logs, rotated at ~25 MB | In-project, gitignored || `.ok/local/cache/<branch>/backlinks.json` | Backlink-graph cache | In-project, gitignored || `.ok/local/installed-skills.json` | Per-project skill-install markers (which editors each skill is projected into) | In-project, gitignored |+| `.ok/local/skill-move-retained.json` | Bookkeeping for a skill move between Project and Global scope that could not finish: which destination copy was kept, why, and what the source looked like at the time. Keyed by scope and skill name, one record each. A record clears when a later move of that skill completes, when the copy at the destination stops matching the one recorded, or when you delete that skill at that scope. No document content | In-project, gitignored || `.ok/local/comments/` | [Comments](/docs/features/comments) left on documents, one JSON file each — the note, the passage it quotes, and whether it has been sent | In-project, gitignored || `.git/ok/` — or `.git/worktrees/<name>/ok/` in a linked worktree, or the enclosing repo's `.git/ok-<slug>/` when your project is a subfolder of a larger repo | Shadow git repo holding per-writer work-in-progress refs (powers the timeline); always inside a git admin dir, never in your content tree | In-project, gitignored (inside `.git/`) |@@ -270,6 +273,7 @@ Disable both with `OK_RECLAIM_DISABLE=1`. `ok start` does not touch skill files;| `~/.ok/auth.yml` | Auth-token fallback, used when no OS credential store is reachable. Written `0600` | **Yes** (`0600`) || `~/.ok/skill-state.yml`, `~/.ok/skill-install-events.jsonl` | Skill-install bookkeeping | No || `~/.agents/skills/<name>/`, `~/.claude/skills/<name>/`, … | Your global-scope skills, versioned in place in your home editor dirs (kept by `ok uninstall` unless `--purge-content`) | No |+| `~/.ok/local/installed-skills.json`, `~/.ok/local/skill-move-retained.json` | The same skill-install markers and unfinished-scope-move bookkeeping the tables above list under a project's `.ok/local/`, written under your home directory for Global-scope skills instead | No || `~/.ok/stats.jsonl` | Local "open with AI" handoff stats — local-only, no phone-home | No || `~/.ok/themes/` | Your saved color themes from the [Themes plugin](../plugins/themes.mdx), one Tinted Theming base16 YAML file per theme, written when you create or edit a theme | No || `~/.ok/logs/` | CLI logs (`cli.<date>.log`), size- and age-capped | No |diff --git a/packages/app/src/components/SkillBulkDeleteDialog.tsx b/packages/app/src/components/SkillBulkDeleteDialog.tsxindex c0116035f..8a3d305d0 100644--- a/packages/app/src/components/SkillBulkDeleteDialog.tsx+++ b/packages/app/src/components/SkillBulkDeleteDialog.tsx@@ -24,6 +24,7 @@ export function SkillBulkDeleteDialog({ skills, onOpenChange, onDeleted }: PropssetDeleting(true);setProgress(0);let deleted = 0;+ const warned: { key: string; name: string; text: string }[] = [];for (const target of targets) {setProgress((n) => n + 1);const result = await deleteSkill(target.scope, target.name, target.hostQualifier);@@ -33,10 +34,32 @@ export function SkillBulkDeleteDialog({ skills, onOpenChange, onDeleted }: Propscontinue;}deleted += 1;+ if (result.warnings.length > 0) {+ warned.push({+ key: `${target.scope}/${target.name}`,+ name: target.name,+ text: result.warnings.join(' '),+ });+ }closeTabs(tabIdsForSkill(openTabs, target.scope, target.name), { force: true });}setDeleting(false);- if (deleted > 0) toast.success(t`Deleted ${deleted} skills`);+ if (warned.length > 0) {+ toast.warning(t`Some skills were deleted with a warning`, {+ duration: 30_000,+ description: (+ <ul className="flex list-none flex-col gap-1">+ {warned.map((entry) => (+ <li key={entry.key}>+ {entry.name}: {entry.text}+ </li>+ ))}+ </ul>+ ),+ });+ } else if (deleted > 0) {+ toast.success(t`Deleted ${deleted} skills`);+ }onDeleted();onOpenChange(false);}diff --git a/packages/app/src/components/SkillDeleteDialog.tsx b/packages/app/src/components/SkillDeleteDialog.tsxindex ca2e1865d..ec70b8150 100644--- a/packages/app/src/components/SkillDeleteDialog.tsx+++ b/packages/app/src/components/SkillDeleteDialog.tsx@@ -28,7 +28,15 @@ export function SkillDeleteDialog({ skill, onOpenChange, onDeleted }: Props) {toast.error(t`Couldn't delete skill: ${error}`);return;}- toast.success(t`Skill "${target.name}" deleted`);+ const title = t`Skill "${target.name}" deleted`;+ if (result.warnings.length > 0) {+ toast.warning(title, {+ description: result.warnings.join(' '),+ duration: 30_000,+ });+ } else {+ toast.success(title);+ }closeTabs(tabIdsForSkill(openTabs, target.scope, target.name), { force: true });onDeleted();onOpenChange(false);diff --git a/packages/app/src/components/SkillDeleteDialog.warnings.dom.test.tsx b/packages/app/src/components/SkillDeleteDialog.warnings.dom.test.tsxnew file mode 100644index 000000000..996d2f867--- /dev/null+++ b/packages/app/src/components/SkillDeleteDialog.warnings.dom.test.tsx@@ -0,0 +1,131 @@+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import type { ReactElement } from 'react';+import { beforeEach, describe, expect, test, vi } from 'vitest';+import * as linguiShim from '../../tests/lingui-macro-shim';++vi.doMock('@lingui/react/macro', () => linguiShim);++const deleteSkill = vi.fn();+const closeTabs = vi.fn();+const toastSuccess = vi.fn();+const toastWarning = vi.fn();+const noop = vi.fn();++vi.doMock('@/lib/skills-api', () => ({ deleteSkill }));+vi.doMock('sonner', () => ({+ toast: { error: vi.fn(), success: toastSuccess, warning: toastWarning },+}));+vi.doMock('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({ closeTabs, openTabs: [] }),+}));++function skill(name: string) {+ return {+ scope: 'project' as const,+ name,+ path: `.agents/skills/${name}/SKILL.md`,+ installed: true,+ hosts: [],+ };+}++const ALPHA_WARNING =+ 'Also removed a copy at .ok/skills/alpha that an earlier failed move had kept.';+const GAMMA_WARNING =+ 'Also removed a copy at .ok/skills/gamma that an earlier failed move had kept.';++async function confirmDelete() {+ await userEvent.click(screen.getByRole('button', { name: /^Delete$/ }));+}++describe('SkillDeleteDialog surfaces a successful-deletion warning', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ async function renderDialog() {+ const { SkillDeleteDialog } = await import('./SkillDeleteDialog');+ render(<SkillDeleteDialog skill={skill('alpha')} onOpenChange={noop} onDeleted={noop} />);+ }++ test('the server sentence is shown verbatim instead of a plain success', async () => {+ deleteSkill.mockResolvedValue({ ok: true, existed: true, warnings: [ALPHA_WARNING] });+ await renderDialog();++ await confirmDelete();++ await waitFor(() => expect(toastWarning).toHaveBeenCalled());+ const [, options] = toastWarning.mock.calls[0] as [+ string,+ { description: string; duration: number },+ ];+ expect(options.description).toBe(ALPHA_WARNING);+ expect(options.duration).toBeGreaterThan(4000);+ expect(toastSuccess).not.toHaveBeenCalled();+ expect(closeTabs).toHaveBeenCalled();+ });++ test('a delete the server had nothing to say about keeps the plain success', async () => {+ deleteSkill.mockResolvedValue({ ok: true, existed: true, warnings: [] });+ await renderDialog();++ await confirmDelete();++ await waitFor(() => expect(toastSuccess).toHaveBeenCalled());+ expect(toastWarning).not.toHaveBeenCalled();+ });+});++describe('SkillBulkDeleteDialog keeps each warning attributed to its skill', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ test('two warned skills stay distinguishable and the quiet one is not named', async () => {+ deleteSkill+ .mockResolvedValueOnce({ ok: true, existed: true, warnings: [ALPHA_WARNING] })+ .mockResolvedValueOnce({ ok: true, existed: true, warnings: [] })+ .mockResolvedValueOnce({ ok: true, existed: true, warnings: [GAMMA_WARNING] });+ const { SkillBulkDeleteDialog } = await import('./SkillBulkDeleteDialog');+ render(+ <SkillBulkDeleteDialog+ skills={[skill('alpha'), skill('beta'), skill('gamma')]}+ onOpenChange={noop}+ onDeleted={noop}+ />,+ );++ await confirmDelete();++ await waitFor(() => expect(toastWarning).toHaveBeenCalledTimes(1));+ const [, options] = toastWarning.mock.calls[0] as [+ string,+ { description: ReactElement; duration: number },+ ];+ const { container } = render(options.description);++ expect(container.textContent).toContain(`alpha: ${ALPHA_WARNING}`);+ expect(container.textContent).toContain(`gamma: ${GAMMA_WARNING}`);+ expect(container.textContent).not.toContain('beta');+ expect(options.duration).toBeGreaterThan(4000);+ expect(toastSuccess).not.toHaveBeenCalled();+ });++ test('a bulk delete the server had nothing to say about keeps the plain success', async () => {+ deleteSkill.mockResolvedValue({ ok: true, existed: true, warnings: [] });+ const { SkillBulkDeleteDialog } = await import('./SkillBulkDeleteDialog');+ render(+ <SkillBulkDeleteDialog+ skills={[skill('alpha'), skill('beta')]}+ onOpenChange={noop}+ onDeleted={noop}+ />,+ );++ await confirmDelete();++ await waitFor(() => expect(toastSuccess).toHaveBeenCalled());+ expect(toastWarning).not.toHaveBeenCalled();+ });+});diff --git a/packages/app/src/components/SkillsTree.tsx b/packages/app/src/components/SkillsTree.tsxindex 0d99a3ab9..62155ad95 100644--- a/packages/app/src/components/SkillsTree.tsx+++ b/packages/app/src/components/SkillsTree.tsx@@ -1,4 +1,9 @@-import type { CatalogSkill, SkillScope, SkillsListEntry } from '@inkeep/open-knowledge-core';+import type {+ CatalogSkill,+ SkillMoveFailureOutcome,+ SkillScope,+ SkillsListEntry,+} from '@inkeep/open-knowledge-core';import { Trans, useLingui } from '@lingui/react/macro';import { FILE_TREE_TAG_NAME, type FileTreeSortComparator } from '@pierre/trees';import { useFileTree } from '@pierre/trees/react';@@ -89,9 +94,10 @@ import {skillEntryDirs,skillHostRootDir,tildeHomePath,+ useSkillScopeLabels,} from '@/lib/skill-scope';import { SKILL_MD_PATH } from '@/lib/skill-sort';-import { importSkill, moveSkillScope } from '@/lib/skills-api';+import { importSkill, moveSkillScope, skillMoveRetainedBatchToast } from '@/lib/skills-api';import { EMPTY_SCOPE_SENTINEL } from '@/lib/skills-tree-paths';const PLUGIN_PACKAGE_ICON_ID = 'ok-skills-plugin-package-decoration';@@ -273,6 +279,7 @@ export function SkillsTree({onTogglePin: (scope: SkillScope, name: string, pinned: boolean) => void;}) {const { t } = useLingui();+ const scopeLabels = useSkillScopeLabels();const { resolvedTheme } = useTheme();const hostRef = useRef<HTMLDivElement | null>(null);const iconPoolRef = useRef<HTMLDivElement | null>(null);@@ -571,12 +578,27 @@ export function SkillsTree({}async function bulkMoveScope(entries: readonly SkillsListEntry[], toScope: SkillScope) {let moved = 0;+ const failures: { name: string; outcome: SkillMoveFailureOutcome }[] = [];for (const s of entries) {const r = await moveSkillScope({ name: s.name, fromScope: s.scope, toScope });- if (r.ok) moved += 1;- else toast.error(t`Couldn't move ${s.name}: ${r.error}`);+ if (r.ok) {+ moved += 1;+ } else {+ failures.push({ name: s.name, outcome: r.outcome });+ toast.error(t`Couldn't move ${s.name}: ${r.error}`);+ }}- if (moved > 0) {+ const retainedSummary = skillMoveRetainedBatchToast({+ failures,+ moved,+ total: entries.length,+ toScope,+ scopeLabel: scopeLabels[toScope],+ });+ if (retainedSummary !== undefined) {+ const { title, ...options } = retainedSummary;+ toast.warning(title, options);+ } else if (moved > 0) {toast.success(toScope === 'global'? t`Moved ${moved} skills to Global`diff --git a/packages/app/src/hooks/use-move-skill-scope.dom.test.tsx b/packages/app/src/hooks/use-move-skill-scope.dom.test.tsxindex 9839206fc..0b3438ab4 100644--- a/packages/app/src/hooks/use-move-skill-scope.dom.test.tsx+++ b/packages/app/src/hooks/use-move-skill-scope.dom.test.tsx@@ -1,3 +1,9 @@+import type {+ SkillMoveStateCode,+ SkillRetentionLedgerCode,+ SkillSourceStateCode,+} from '@inkeep/open-knowledge-core';+import { interpretSkillMoveFailure } from '@inkeep/open-knowledge-core';import { renderHook } from '@testing-library/react';import { describe, expect, test, vi } from 'vitest';@@ -23,9 +29,15 @@ vi.doMock('@/lib/documents-events', () => ({beginOptimisticSkillMove: vi.fn(),endOptimisticSkillMove: vi.fn(),}));-vi.doMock('@/lib/skills-api', () => ({+vi.doMock('@/lib/skills-api', async () => ({+ ...(await vi.importActual<typeof import('@/lib/skills-api')>('@/lib/skills-api')),moveSkillScope: vi.fn(async () => ({ ok: true })),}));+const toastError = vi.fn();+const toastDismiss = vi.fn();+vi.doMock('sonner', () => ({+ toast: { error: toastError, success: vi.fn(), dismiss: toastDismiss },+}));const { useMoveSkillScope } = await import('./use-move-skill-scope');@@ -55,7 +67,12 @@ describe('useMoveSkillScope retarget source', () => {describe('the write flag is always released', () => {test('a FAILED move releases it too', async () => {const api = await import('@/lib/skills-api');- vi.mocked(api.moveSkillScope).mockResolvedValueOnce({ ok: false, error: 'nope' });+ vi.mocked(api.moveSkillScope).mockResolvedValueOnce({+ ok: false,+ error: 'nope',+ outcome: interpretSkillMoveFailure({}),+ droppedLocations: [],+ });const { result } = renderHook(() => useMoveSkillScope());const moved = await result.current(@@ -83,3 +100,117 @@ describe('the write flag is always released', () => {expect(endSkillWrite).toHaveBeenCalledWith('project', 'improve-codebase-architecture');});});++describe('a failed move reports the retained copy it actually left behind', () => {+ type ToastOptions = { description?: string; id?: string; duration?: number };++ async function failWith(state: {+ moveState?: SkillMoveStateCode;+ sourceState?: SkillSourceStateCode;+ retentionLedger?: SkillRetentionLedgerCode;+ }): Promise<ToastOptions | undefined> {+ toastError.mockClear();+ const api = await import('@/lib/skills-api');+ const reported = {+ ...(state.moveState ? { moveState: state.moveState } : {}),+ ...(state.sourceState ? { sourceState: state.sourceState } : {}),+ ...(state.retentionLedger ? { retentionLedger: state.retentionLedger } : {}),+ };+ vi.mocked(api.moveSkillScope).mockResolvedValueOnce({+ ok: false,+ error: "A global skill named 'trip-log' already exists.",+ droppedLocations: [],+ outcome: interpretSkillMoveFailure(reported),+ });+ const { result } = renderHook(() => useMoveSkillScope());++ await result.current({ scope: 'project', name: 'trip-log' }, 'global');++ const call = toastError.mock.calls.at(-1) as [string, ToastOptions | undefined];+ return call[1];+ }++ test('a verified-intact source makes the retained copy a duplicate to remove before retrying', async () => {+ const options = await failWith({+ moveState: 'destination-retained',+ sourceState: 'intact',+ });++ expect(options?.description).toContain('redundant duplicate');+ expect(options?.description).toContain('Remove that copy, then retry the move.');+ expect(options?.description).not.toContain("Don't delete it");+ });++ test('a source that is not verified intact keeps the do-not-delete warning', async () => {+ for (const sourceState of ['lossy', 'unknown', undefined] as const) {+ const options = await failWith({ moveState: 'destination-retained', sourceState });++ expect(options?.description).toMatch(/Don't delete (it|anything)/);+ expect(options?.description).toContain('comparing it with the original');+ expect(options?.description).not.toContain('redundant duplicate');+ }+ });++ test('the intact and not-intact arms cannot collapse back into one sentence', async () => {+ const intact = await failWith({ moveState: 'destination-retained', sourceState: 'intact' });+ const lossy = await failWith({ moveState: 'destination-retained', sourceState: 'lossy' });++ expect(intact?.description).not.toBe(lossy?.description);+ });++ test('a blocked retry reports the blocking retained copy the same way', async () => {+ expect(+ (await failWith({ moveState: 'destination-retained-blocking', sourceState: 'intact' }))+ ?.description,+ ).toContain('redundant duplicate');+ expect(+ (await failWith({ moveState: 'destination-retained-blocking', sourceState: 'lossy' }))+ ?.description,+ ).toContain("Don't delete it");+ });++ test('the guidance names the destination scope and the skill it is talking about', async () => {+ const options = await failWith({+ moveState: 'destination-retained',+ sourceState: 'unknown',+ });++ expect(options?.description).toContain('Global');+ expect(options?.description).toContain('trip-log');+ });++ test('a retained copy pins the toast open under a per-skill id', async () => {+ const first = await failWith({ moveState: 'destination-retained', sourceState: 'intact' });+ const second = await failWith({+ moveState: 'destination-retained-blocking',+ sourceState: 'lossy',+ });++ expect(first?.duration).toBe(Infinity);+ expect(second?.duration).toBe(Infinity);+ expect(first?.id).toBe('skill-move-retained:global:trip-log');+ expect(second?.id).toBe(first?.id);+ });++ test('a retention-ledger code warns about the unverifiable occupant on an otherwise-quiet moveState', async () => {+ for (const retentionLedger of ['unreadable', 'occupant-unverifiable'] as const) {+ const options = await failWith({ moveState: 'nothing-written', retentionLedger });++ expect(options?.description).toContain("couldn't confirm what it is");+ expect(options?.description).toContain('trip-log');+ expect(options?.description).toContain('Global');+ expect(options?.duration).toBe(Infinity);+ expect(options?.id).toBe('skill-move-retained:global:trip-log');+ }+ });++ test('an ordinary failure adds no guidance and keeps the default toast lifetime', async () => {+ for (const state of [{ moveState: 'destination-removed' as const }, {}]) {+ const options = await failWith(state);++ expect(options?.description).toBeUndefined();+ expect(options?.duration).toBeUndefined();+ expect(options?.id).toBeUndefined();+ }+ });+});diff --git a/packages/app/src/hooks/use-move-skill-scope.ts b/packages/app/src/hooks/use-move-skill-scope.tsindex a72dcaa59..459c48326 100644--- a/packages/app/src/hooks/use-move-skill-scope.ts+++ b/packages/app/src/hooks/use-move-skill-scope.ts@@ -14,7 +14,7 @@ import {} from '@/lib/documents-events';import { skillEntryLiveDocName, skillLiveDocName } from '@/lib/managed-artifact-doc-name';import { useSkillScopeLabels } from '@/lib/skill-scope';-import { moveSkillScope } from '@/lib/skills-api';+import { moveSkillScope, skillMoveRetainedCopyToast } from '@/lib/skills-api';export function useMoveSkillScope(): (skill: { scope: SkillScope; name: string },@@ -33,7 +33,15 @@ export function useMoveSkillScope(): (endOptimisticSkillMove(skill.scope, skill.name);if (!result.ok) {endSkillWrite(skill.scope, skill.name);- toast.error(t`Couldn't move skill: ${result.error}`);+ toast.error(+ t`Couldn't move skill: ${result.error}`,+ skillMoveRetainedCopyToast({+ outcome: result.outcome,+ name: skill.name,+ toScope,+ scopeLabel: scopeLabels[toScope],+ }),+ );return false;}toast.success(t`Moved "${skill.name}" to ${scopeLabels[toScope]}`);diff --git a/packages/app/src/lib/skills-api.move-scope.dom.test.ts b/packages/app/src/lib/skills-api.move-scope.dom.test.tsnew file mode 100644index 000000000..9f8bca649--- /dev/null+++ b/packages/app/src/lib/skills-api.move-scope.dom.test.ts@@ -0,0 +1,551 @@+import { toast } from 'sonner';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { subscribeToSkillsChanged } from './documents-events';+import {+ deleteSkill,+ moveSkillScope,+ skillMoveRetainedBatchToast,+ skillMoveRetainedCopyToast,+} from './skills-api';++vi.mock('sonner', () => ({+ toast: { dismiss: vi.fn(), error: vi.fn(), success: vi.fn(), warning: vi.fn() },+}));++const originalFetch = globalThis.fetch;++function countSkillsChanged(): { count: () => number; stop: () => void } {+ let seen = 0;+ const stop = subscribeToSkillsChanged(() => {+ seen += 1;+ });+ return { count: () => seen, stop };+}++describe('moveSkillScope transport', () => {+ afterEach(() => {+ globalThis.fetch = originalFetch;+ });++ test('carries droppedLocations from a successful move back to the caller', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ scope: 'global',+ path: '.ok/skills/example',+ droppedLocations: ['agents', '.team/skills'],+ }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ ),+ );+ const changed = countSkillsChanged();++ const result = await moveSkillScope({+ name: 'example',+ fromScope: 'project',+ toScope: 'global',+ });+ changed.stop();++ expect(result).toEqual({+ ok: true,+ scope: 'global',+ path: '.ok/skills/example',+ droppedLocations: ['agents', '.team/skills'],+ });+ expect(changed.count()).toBe(1);+ });++ test('defaults droppedLocations to an empty list when the body omits or malforms it', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ scope: 'global', droppedLocations: ['agents', 7, null] }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ }),+ );++ const result = await moveSkillScope({+ name: 'example',+ fromScope: 'project',+ toScope: 'global',+ });++ expect(result).toEqual({ ok: true, scope: 'global', droppedLocations: ['agents'] });+ });++ test('carries moveState alongside the message when the move fails', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ type: 'urn:ok:error:internal-server-error',+ title: 'The destination copy could not be read back.',+ status: 500,+ moveState: 'destination-unreadable',+ }),+ { status: 500, headers: { 'Content-Type': 'application/problem+json' } },+ ),+ );+ const changed = countSkillsChanged();++ const result = await moveSkillScope({+ name: 'example',+ fromScope: 'project',+ toScope: 'global',+ });+ changed.stop();++ expect(result).toEqual({+ ok: false,+ error: 'The destination copy could not be read back.',+ outcome: { kind: 'coherent', moveState: 'destination-unreadable' },+ droppedLocations: [],+ });+ expect(changed.count()).toBe(1);+ });++ test('omits moveState when the failure body carries a code outside the advertised set', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ title: 'Move failed.', moveState: 'some-future-state' }), {+ status: 500,+ headers: { 'Content-Type': 'application/problem+json' },+ }),+ );++ const result = await moveSkillScope({+ name: 'example',+ fromScope: 'project',+ toScope: 'global',+ });++ expect(result).toEqual({+ ok: false,+ error: 'Move failed.',+ outcome: { kind: 'unverified' },+ droppedLocations: [],+ });+ expect(result).not.toHaveProperty('outcome.moveState');+ });++ test('carries sourceState alongside moveState when the server reports the source verdict', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ title: 'Failed to move skill (source removal failed).',+ moveState: 'destination-retained',+ sourceState: 'intact',+ }),+ { status: 500, headers: { 'Content-Type': 'application/problem+json' } },+ ),+ );++ const result = await moveSkillScope({+ name: 'example',+ fromScope: 'project',+ toScope: 'global',+ });++ expect(result).toEqual({+ ok: false,+ error: 'Failed to move skill (source removal failed).',+ outcome: { kind: 'coherent', moveState: 'destination-retained', sourceState: 'intact' },+ droppedLocations: [],+ });+ });++ test('carries retentionLedger alongside moveState when the destination occupant is unverifiable', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ title: 'A project skill named "example" already exists.',+ moveState: 'nothing-written',+ retentionLedger: 'occupant-unverifiable',+ }),+ { status: 409, headers: { 'Content-Type': 'application/problem+json' } },+ ),+ );++ const result = await moveSkillScope({+ name: 'example',+ fromScope: 'global',+ toScope: 'project',+ });++ expect(result).toEqual({+ ok: false,+ error: 'A project skill named "example" already exists.',+ outcome: {+ kind: 'coherent',+ moveState: 'nothing-written',+ retentionLedger: 'occupant-unverifiable',+ },+ droppedLocations: [],+ });+ });++ test('omits retentionLedger when the failure body carries a code outside the advertised set', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ title: 'Move failed.',+ moveState: 'nothing-written',+ retentionLedger: 'occupant-probably-fine',+ }),+ { status: 409, headers: { 'Content-Type': 'application/problem+json' } },+ ),+ );++ const result = await moveSkillScope({+ name: 'example',+ fromScope: 'global',+ toScope: 'project',+ });++ expect(result).not.toHaveProperty('outcome.retentionLedger');+ });++ test('omits sourceState when the failure body carries a verdict outside the advertised set', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ title: 'Move failed.',+ moveState: 'destination-retained',+ sourceState: 'probably-fine',+ }),+ { status: 500, headers: { 'Content-Type': 'application/problem+json' } },+ ),+ );++ const result = await moveSkillScope({+ name: 'example',+ fromScope: 'project',+ toScope: 'global',+ });++ expect(result).not.toHaveProperty('outcome.sourceState');+ });++ test('carries droppedLocations from a failed move back to the caller', async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ title: 'The source could not be removed.',+ moveState: 'destination-retained',+ droppedLocations: ['lm-studio', 9],+ }),+ { status: 500, headers: { 'Content-Type': 'application/problem+json' } },+ ),+ );++ const result = await moveSkillScope({+ name: 'example',+ fromScope: 'project',+ toScope: 'global',+ });++ expect(result).toEqual({+ ok: false,+ error: 'The source could not be removed.',+ outcome: { kind: 'unverified', moveState: 'destination-retained' },+ droppedLocations: ['lm-studio'],+ });+ });++ test('refreshes the skills list when the response is lost in transport', async () => {+ globalThis.fetch = vi.fn().mockRejectedValue(new Error('network down'));+ const changed = countSkillsChanged();++ const result = await moveSkillScope({+ name: 'example',+ fromScope: 'project',+ toScope: 'global',+ });+ changed.stop();++ expect(result).toEqual({+ ok: false,+ error: 'network down',+ outcome: { kind: 'coherent' },+ droppedLocations: [],+ });+ expect(changed.count()).toBe(1);+ });++ test('does not refresh when the source and destination scopes match and no request is sent', async () => {+ const fetchMock = vi.fn();+ globalThis.fetch = fetchMock;+ const changed = countSkillsChanged();++ const result = await moveSkillScope({+ name: 'example',+ fromScope: 'global',+ toScope: 'global',+ });+ changed.stop();++ expect(result).toEqual({ ok: true, scope: 'global', droppedLocations: [] });+ expect(fetchMock).not.toHaveBeenCalled();+ expect(changed.count()).toBe(0);+ });+});++describe('skillMoveRetainedCopyToast', () => {+ const base = { name: 'example', toScope: 'project' as const, scopeLabel: 'Project' };++ test.for(['unreadable', 'occupant-unverifiable'] as const)(+ 'warns to compare before deleting when the server reports retentionLedger %s',+ (retentionLedger) => {+ const options = skillMoveRetainedCopyToast({+ outcome: { kind: 'coherent', moveState: 'nothing-written', retentionLedger },+ ...base,+ });++ expect(options).toEqual({+ description:+ 'Something named "example" is already in Project, and the server couldn\'t confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it.',+ id: 'skill-move-retained:project:example',+ duration: Number.POSITIVE_INFINITY,+ });+ },+ );++ test('stays silent for a nothing-written move the server could fully account for', () => {+ expect(+ skillMoveRetainedCopyToast({+ outcome: { kind: 'coherent', moveState: 'nothing-written' },+ ...base,+ }),+ ).toBeUndefined();+ });++ test('offers removal only when the server verified the source intact', () => {+ expect(+ skillMoveRetainedCopyToast({+ outcome: { kind: 'coherent', moveState: 'destination-retained', sourceState: 'intact' },+ ...base,+ })?.description,+ ).toContain('redundant duplicate');+ });++ test('an unverified report never offers removal, even when it claims an intact source', () => {+ const description = skillMoveRetainedCopyToast({+ outcome: { kind: 'unverified', moveState: 'destination-retained', sourceState: 'intact' },+ ...base,+ })?.description;++ expect(description).toContain("Don't delete anything");+ expect(description).not.toContain('redundant duplicate');+ });++ test('a retained destination with no source verdict stays cautionary', () => {+ const description = skillMoveRetainedCopyToast({+ outcome: { kind: 'unverified', moveState: 'destination-retained-blocking' },+ ...base,+ })?.description;++ expect(description).toContain("Don't delete anything");+ expect(description).not.toContain('redundant duplicate');+ });++ test('a completely unknown peer outcome remains cautionary', () => {+ const options = skillMoveRetainedCopyToast({ outcome: { kind: 'unverified' }, ...base });++ expect(options?.description).toContain('A copy may remain');+ expect(options?.description).toContain("Don't delete anything");+ expect(options?.duration).toBe(Number.POSITIVE_INFINITY);+ expect(options?.description).not.toContain('original was verified unchanged');+ });++ test('gives each skill in a bulk move its own toast id so warnings do not collapse', () => {+ const ids = ['alpha', 'beta', 'gamma', 'delta'].map(+ (name) =>+ skillMoveRetainedCopyToast({+ outcome: {+ kind: 'coherent',+ moveState: 'nothing-written',+ retentionLedger: 'occupant-unverifiable',+ },+ ...base,+ name,+ })?.id,+ );++ expect(ids).toEqual([+ 'skill-move-retained:project:alpha',+ 'skill-move-retained:project:beta',+ 'skill-move-retained:project:gamma',+ 'skill-move-retained:project:delta',+ ]);+ });+});++describe('skillMoveRetainedBatchToast', () => {+ const base = { toScope: 'project' as const, scopeLabel: 'Project' };+ const retainedIntact = {+ kind: 'coherent',+ moveState: 'destination-retained',+ sourceState: 'intact',+ } as const;+ const retainedLossy = {+ kind: 'coherent',+ moveState: 'destination-retained',+ sourceState: 'lossy',+ } as const;+ const ordinary = { kind: 'coherent', moveState: 'destination-removed' } as const;++ test('one summary names every retained skill in a batch that also had a success', () => {+ const summary = skillMoveRetainedBatchToast({+ failures: [+ { name: 'alpha', outcome: retainedIntact },+ { name: 'beta', outcome: retainedLossy },+ { name: 'gamma', outcome: ordinary },+ ],+ moved: 1,+ total: 4,+ ...base,+ });++ expect(summary?.description).toContain('alpha');+ expect(summary?.description).toContain('beta');+ expect(summary?.description).not.toContain('gamma');+ expect(summary?.description).toContain('Project');+ expect(summary?.title).toBe('Moved 1 of 4 skills to Project');+ expect(summary?.duration).toBe(Number.POSITIVE_INFINITY);+ expect(summary?.id).toBe('skill-move-retained-batch:project');+ });++ test('a batch holding one uncertain member never advises removing any copy', () => {+ const summary = skillMoveRetainedBatchToast({+ failures: [+ { name: 'alpha', outcome: retainedIntact },+ { name: 'beta', outcome: retainedLossy },+ ],+ moved: 0,+ total: 2,+ ...base,+ });++ expect(summary?.description).toContain("Don't delete anything there");+ expect(summary?.description).not.toContain('remove those copies');+ });++ test('a batch whose retained copies are all redundant says they can be removed', () => {+ const summary = skillMoveRetainedBatchToast({+ failures: [{ name: 'alpha', outcome: retainedIntact }],+ moved: 2,+ total: 3,+ ...base,+ });++ expect(summary?.description).toContain('remove those copies');+ });++ test('stays silent when nothing was retained, so the batch keeps its plain success', () => {+ expect(+ skillMoveRetainedBatchToast({+ failures: [{ name: 'gamma', outcome: ordinary }],+ moved: 2,+ total: 3,+ ...base,+ }),+ ).toBeUndefined();+ });++ test('caps the names so a large multi-select cannot grow the summary without bound', () => {+ const summary = skillMoveRetainedBatchToast({+ failures: ['alpha', 'beta', 'gamma', 'delta', 'epsilon'].map((name) => ({+ name,+ outcome: retainedIntact,+ })),+ moved: 0,+ total: 5,+ ...base,+ });++ expect(summary?.description).toContain('alpha, beta, gamma and 2 more');+ expect(summary?.description).not.toContain('delta');+ expect(summary?.description).not.toContain('epsilon');+ });+});++describe('the retained batch summary drains through the per-skill success chokepoints', () => {+ const retainedIntact = {+ kind: 'coherent',+ moveState: 'destination-retained',+ sourceState: 'intact',+ } as const;++ afterEach(() => {+ globalThis.fetch = originalFetch;+ });++ function respondOk(body: object): void {+ globalThis.fetch = vi.fn().mockResolvedValue(+ new Response(JSON.stringify(body), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ }),+ );+ }++ function summarize(toScope: 'project' | 'global', names: readonly string[]): void {+ skillMoveRetainedBatchToast({+ failures: names.map((name) => ({ name, outcome: retainedIntact })),+ moved: 0,+ total: names.length,+ toScope,+ scopeLabel: toScope === 'global' ? 'Global' : 'Project',+ });+ }++ function dismissed(): string[] {+ return vi.mocked(toast.dismiss).mock.calls.map((call) => String(call[0]));+ }++ test('a retry that succeeds one at a time holds the summary until the last name resolves', async () => {+ summarize('global', ['alpha', 'beta']);+ respondOk({ scope: 'global' });+ vi.mocked(toast.dismiss).mockClear();++ await moveSkillScope({ name: 'alpha', fromScope: 'project', toScope: 'global' });++ expect(dismissed()).toEqual(['skill-move-retained:global:alpha']);++ await moveSkillScope({ name: 'beta', fromScope: 'project', toScope: 'global' });++ expect(dismissed()).toContain('skill-move-retained-batch:global');+ });++ test('deleting the retained copy resolves that name for the summary as well', async () => {+ summarize('project', ['alpha', 'beta']);+ respondOk({ existed: true });+ vi.mocked(toast.dismiss).mockClear();++ await deleteSkill('project', 'alpha');++ expect(dismissed()).not.toContain('skill-move-retained-batch:project');++ await deleteSkill('project', 'beta');++ expect(dismissed()).toContain('skill-move-retained-batch:project');+ });++ test('a host-qualified delete resolves nothing, so the summary stays up', async () => {+ summarize('project', ['alpha']);+ respondOk({ existed: true });+ vi.mocked(toast.dismiss).mockClear();++ await deleteSkill('project', 'alpha', 'claude');++ expect(dismissed()).toEqual([]);+ });++ test('a name outside the summary never drains it', async () => {+ summarize('global', ['alpha']);+ respondOk({ scope: 'global' });+ vi.mocked(toast.dismiss).mockClear();++ await moveSkillScope({ name: 'unrelated', fromScope: 'project', toScope: 'global' });++ expect(dismissed()).toEqual(['skill-move-retained:global:unrelated']);+ });+});diff --git a/packages/app/src/lib/skills-api.ts b/packages/app/src/lib/skills-api.tsindex 556b727fe..8ba8ea3ba 100644--- a/packages/app/src/lib/skills-api.ts+++ b/packages/app/src/lib/skills-api.ts@@ -5,6 +5,7 @@ import type {SkillFolderLinkPreview,SkillFrontmatter,SkillInstallWarningCode,+ SkillMoveFailureOutcome,SkillPreview,SkillRefResolution,SkillScope,@@ -14,8 +15,15 @@ import type {SkillsReimportBulkSuccess,SkillsSearchSuccess,} from '@inkeep/open-knowledge-core';-import { SkillFolderLinkPreviewSchema, SkillsListSuccessSchema } from '@inkeep/open-knowledge-core';+import {+ interpretSkillMoveFailure,+ isSkillMoveRetainedDestinationCode,+ normalizeApiWarnings,+ SkillFolderLinkPreviewSchema,+ SkillsListSuccessSchema,+} from '@inkeep/open-knowledge-core';import { t } from '@lingui/core/macro';+import { toast } from 'sonner';import { emitSkillScopeMoved, emitSkillsChanged } from '@/lib/documents-events';import { parseApiError } from '@/lib/parse-api-error';@@ -363,30 +371,164 @@ export async function duplicateSkill(input: {}}+export type MoveSkillScopeResult =+ | { ok: true; scope: SkillScope; path?: string; droppedLocations: string[] }+ | {+ ok: false;+ error: string;+ outcome: SkillMoveFailureOutcome;+ droppedLocations: string[];+ };++function skillMoveRetainedToastId(toScope: SkillScope, name: string): string {+ return `skill-move-retained:${toScope}:${name}`;+}++function skillMoveRetainedBatchToastId(toScope: SkillScope): string {+ return `skill-move-retained-batch:${toScope}`;+}++const outstandingRetainedNames = new Map<SkillScope, Set<string>>();++function clearSkillMoveRetained(scope: SkillScope, name: string): void {+ toast.dismiss(skillMoveRetainedToastId(scope, name));+ const outstanding = outstandingRetainedNames.get(scope);+ if (outstanding === undefined || !outstanding.delete(name)) return;+ if (outstanding.size > 0) return;+ outstandingRetainedNames.delete(scope);+ toast.dismiss(skillMoveRetainedBatchToastId(scope));+}++function skillMoveRetentionClass(+ outcome: SkillMoveFailureOutcome,+): 'none' | 'redundant' | 'uncertain' {+ if (outcome.kind === 'unverified') return 'uncertain';+ const retained =+ outcome.moveState !== undefined && isSkillMoveRetainedDestinationCode(outcome.moveState);+ if (!retained && outcome.retentionLedger === undefined) return 'none';+ if (outcome.retentionLedger !== undefined) return 'uncertain';+ return outcome.sourceState === 'intact' ? 'redundant' : 'uncertain';+}++export function skillMoveRetainedCopyToast(input: {+ outcome: SkillMoveFailureOutcome;+ name: string;+ toScope: SkillScope;+ scopeLabel: string;+}): { description: string; id: string; duration: number } | undefined {+ const { outcome, name, toScope, scopeLabel } = input;+ const retention = skillMoveRetentionClass(outcome);+ if (retention === 'none') return undefined;+ const id = skillMoveRetainedToastId(toScope, name);+ if (outcome.kind === 'unverified') {+ const names = name;+ return {+ description: t`A copy may remain in ${scopeLabel} for: ${names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed.`,+ id,+ duration: Infinity,+ };+ }+ if (outcome.retentionLedger !== undefined) {+ return {+ description: t`Something named "${name}" is already in ${scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it.`,+ id,+ duration: Infinity,+ };+ }+ const description =+ retention === 'redundant'+ ? t`The copy of "${name}" kept in ${scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move.`+ : t`A copy of "${name}" was kept in ${scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed.`;+ return { description, id, duration: Infinity };+}++const RETAINED_NAMES_SHOWN = 3;++function retainedNamesText(names: readonly string[]): string {+ if (names.length <= RETAINED_NAMES_SHOWN) return names.join(', ');+ const shown = names.slice(0, RETAINED_NAMES_SHOWN).join(', ');+ const more = names.length - RETAINED_NAMES_SHOWN;+ return t`${shown} and ${more} more`;+}++export function skillMoveRetainedBatchToast(input: {+ failures: readonly { name: string; outcome: SkillMoveFailureOutcome }[];+ moved: number;+ total: number;+ toScope: SkillScope;+ scopeLabel: string;+}): { title: string; description: string; id: string; duration: number } | undefined {+ const { failures, moved, total, toScope, scopeLabel } = input;+ const retained = failures+ .map((failure) => ({ name: failure.name, retention: skillMoveRetentionClass(failure.outcome) }))+ .filter((failure) => failure.retention !== 'none');+ if (retained.length === 0) return undefined;+ outstandingRetainedNames.set(toScope, new Set(retained.map((failure) => failure.name)));+ const names = retainedNamesText(retained.map((failure) => failure.name));+ const description = retained.some((failure) => failure.retention === 'uncertain')+ ? t`A copy may remain in ${scopeLabel} for: ${names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed.`+ : t`A redundant copy was kept in ${scopeLabel} for: ${names}. Each original was verified unchanged, so remove those copies and retry the move.`;+ return {+ title: t`Moved ${moved} of ${total} skills to ${scopeLabel}`,+ description,+ id: skillMoveRetainedBatchToastId(toScope),+ duration: Infinity,+ };+}++function readField(body: unknown, key: string): unknown {+ return body === null || typeof body !== 'object'+ ? undefined+ : (body as Record<string, unknown>)[key];+}++function parseDroppedLocations(body: unknown): string[] {+ const value = readField(body, 'droppedLocations');+ return Array.isArray(value)+ ? value.filter((entry): entry is string => typeof entry === 'string')+ : [];+}+export async function moveSkillScope(input: {name: string;fromScope: SkillScope;toScope: SkillScope;-}): Promise<WriteResult<{ scope: SkillScope; path?: string }>> {+}): Promise<MoveSkillScopeResult> {const { name, fromScope, toScope } = input;- if (fromScope === toScope) return { ok: true, scope: toScope };+ if (fromScope === toScope) return { ok: true, scope: toScope, droppedLocations: [] };try {const res = await fetch('/api/skill/move-scope', {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({ name, fromScope, toScope }),});- if (!res.ok) return { ok: false, error: await readErrorBody(res) };- const payload = (await res.json().catch(() => null)) as { path?: string } | null;+ const payload = (await res.json().catch(() => null)) as unknown;+ if (!res.ok) {+ return {+ ok: false,+ error: parseApiError(payload) ?? `HTTP ${res.status}`,+ outcome: interpretSkillMoveFailure(payload),+ droppedLocations: parseDroppedLocations(payload),+ };+ }+ const path = readField(payload, 'path');emitSkillScopeMoved({ name, fromScope, toScope });- emitSkillsChanged();+ clearSkillMoveRetained(toScope, name);return {ok: true,scope: toScope,- ...(typeof payload?.path === 'string' ? { path: payload.path } : {}),+ ...(typeof path === 'string' ? { path } : {}),+ droppedLocations: parseDroppedLocations(payload),};} catch (err) {- return { ok: false, error: err instanceof Error ? err.message : String(err) };+ return {+ ok: false,+ error: err instanceof Error ? err.message : String(err),+ outcome: { kind: 'coherent' },+ droppedLocations: [],+ };+ } finally {+ emitSkillsChanged();}}@@ -464,14 +606,19 @@ export async function deleteSkill(scope: SkillScope,name: string,host?: string,-): Promise<WriteResult<{ existed: boolean }>> {+): Promise<WriteResult<{ existed: boolean; warnings: string[] }>> {try {const qs = `?name=${encodeURIComponent(name)}&scope=${encodeURIComponent(scope)}${host ? `&host=${encodeURIComponent(host)}` : ''}`;const res = await fetch(`/api/skill${qs}`, { method: 'DELETE' });if (!res.ok) return { ok: false, error: await readErrorBody(res) };const payload = (await res.json().catch(() => null)) as { existed?: boolean } | null;emitSkillsChanged();- return { ok: true, existed: payload?.existed ?? false };+ if (host === undefined) clearSkillMoveRetained(scope, name);+ return {+ ok: true,+ existed: payload?.existed ?? false,+ warnings: normalizeApiWarnings(readField(payload, 'warnings')),+ };} catch (err) {return { ok: false, error: err instanceof Error ? err.message : String(err) };}diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.jsonindex ec8aad432..86ee21b66 100644--- a/packages/app/src/locales/ar/messages.json+++ b/packages/app/src/locales/ar/messages.json@@ -861,6 +861,7 @@"851WA-": ["يمكن ضبط هذا في الإعدادات > أدوات الذكاء الاصطناعي وواجهة سطر الأوامر"],"87GMKe": ["هل تريد كشف هذا المشروع على الشبكة؟"],"881Uwh": ["حذف الجدول المحدد"],+ "89TmeV": ["تم حذف بعض المهارات مع تحذير"],"89TtiD": ["ملف جديد من القالب «", ["displayTitle"], "» (", ["fileName"], ") في جذر المشروع"],"8AjnFz": ["«", ["0"], "» مستورد بالفعل (محتوى مطابق)."],"8F1i42": ["الصفحة غير موجودة"],@@ -1676,6 +1677,7 @@"GbzBEk": ["أعاد الخادم استجابة مهارات غير مكتملة."],"GceAYf": ["تم نقل ", ["label"], " إلى جزء جديد على اليمين."],"GemPfn": ["فشل تحليل استجابة خطأ الروابط الصادرة (HTTP ", ["status"], ")"],+ "GesfyX": [["shown"], " و", ["more"], " أخرى"],"Gfr4fu": ["لا يستطيع الخادم فتح المستندات"],"GhjUB_": ["أُعيد الاتصال"],"Gi8Akx": ["لم يُعدّ أي وكيل بعد — لإرفاق الملفات، أضف وكيلًا داخل التطبيق من «اتصالات الوكلاء»."],@@ -2360,6 +2362,13 @@"OKImo8": ["الملفات المتعارضة"],"OLBz-_": ["فشل عرض مخطط Mermaid."],"OLIKgw": ["اسحب العنصر ", ["0"], " لإعادة الترتيب"],+ "OMS7Xp": [+ "تم الاحتفاظ بنسخة من “",+ ["name"],+ "” في ",+ ["scopeLabel"],+ " عن قصد. لا تحذفها قبل مقارنتها بالنسخة الأصلية: فقد تحتوي على النسخة الوحيدة من الملفات التي حذفها النقل الفاشل بالفعل."+ ],"ONPvOb": ["يجري تحميل نشاط الوكيل"],"ONUgxB": ["هذا التعارض لم يعد متاحًا."],"ONWvwQ": ["رفع"],@@ -2598,6 +2607,7 @@"RD8cCw": ["إدارة اتصالات الوكلاء غير متاحة في هذا الإصدار."],"RDjuBN": ["الإعداد"],"RDrXh4": ["اضبط إعدادات المستخدم والمشروع والتكاملات."],+ "RDzxes": ["تم نقل ", ["moved"], " من ", ["total"], " مهارات إلى ", ["scopeLabel"]],"REkvLz": ["المنفذ ",["0"],@@ -2636,6 +2646,13 @@"R_U_A4": ["أضف نمط ملف أو مجلد، مثل guides/**/*"],"RaPMZv": ["اختصارات لوحة المفاتيح المتاحة في المحرر ومساحة العمل."],"RaUKLu": ["التحكم عن بُعد"],+ "Raayoq": [+ "النسخة من “",+ ["name"],+ "” المحفوظة في ",+ ["scopeLabel"],+ " هي نسخة مكررة زائدة: تم التحقق من أن الأصل لم يتغير. احذف تلك النسخة ثم أعد محاولة النقل."+ ],"Rah7yq": ["ما الذي ينبغي أن يفعله الذكاء الاصطناعي؟ (اختياري)"],"Rb1zMa": ["لا يوجد مقتطف"],"RcrskJ": ["بدا التنسيق خاطئًا"],@@ -3465,6 +3482,13 @@"_G7A92": ["الحفاظ على index.md"],"_GRWOJ": ["هل تريد تغيير مزوّد التضمينات؟"],"_HgF9q": ["الترتيب حسب"],+ "_HlScO": [+ "قد تبقى نسخة في ",+ ["scopeLabel"],+ " من: ",+ ["names"],+ ". لا تحذف أي شيء هناك قبل مقارنته بالنسخة الأصلية: فقد يحتوي على النسخة الوحيدة من الملفات التي حذفها نقل فاشل بالفعل."+ ],"_IGfXZ": ["أُغلق OpenKnowledge على نحو غير متوقع في المرة السابقة."],"_IX_7x": ["أخرى"],"_IfSZn": ["توجد سمة محفوظة بهذا الاسم بالفعل."],@@ -3958,6 +3982,13 @@"eFJkVt": ["فشل الاستنساخ: ", ["cloneError"]],"eG8Jsg": ["تبديل وضع تركيز مفتاح Tab في المصدر"],"eGUbmF": ["نسخ الملف أو المجلد المحدد"],+ "eGkfGQ": [+ "تم الاحتفاظ بنسخة مكررة زائدة في ",+ ["scopeLabel"],+ " من: ",+ ["names"],+ ". تم التحقق من أن كل أصل لم يتغير، لذا احذف تلك النسخ ثم أعد محاولة النقل."+ ],"eJitUk": ["الرفع من الجهاز"],"eKThTQ": ["فشلت إعادة الترتيب"],"eMWRAs": ["الصفحات المفهرسة: ", ["semanticIndexedCount"], " من ", ["semanticTotalCount"], "."],@@ -5924,6 +5955,13 @@"xSVO3J": ["ما الذي يُنشأ"],"xV5sXw": ["قبل ", ["0"], " أسبوع"],"xW5AUw": ["تم السحب ", ["pulled"]],+ "xW7KK3": [+ "يوجد بالفعل شيء باسم “",+ ["name"],+ "” في ",+ ["scopeLabel"],+ "، ولم يتمكن الخادم من تأكيد ماهيته. ربما تركه هناك عن قصد نقلٌ فاشل سابق: قارنه بالنسخة الأصلية قبل حذفه أو استبداله."+ ],"xWEvuo": ["اسأل الذكاء الاصطناعي"],"xWomUD": ["استخدام نسخة ", ["editor"]],"xXo8FT": ["فشل الحفظ: ", ["error"]],diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex deb187842..19449d2c3 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -1020,6 +1020,10 @@ msgstr "خصائص {settingsDescriptorLabel}"msgid "{shareBranch} isn't a valid branch name."msgstr "{shareBranch} ليس اسم فرع صالحًا."+#: src/lib/skills-api.ts+msgid "{shown} and {more} more"+msgstr "{shown} و{more} أخرى"+#: src/components/ReportBugDialogBody.tsxmsgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"msgstr "{sizeText} · تم إخفاء الأسرار · {fileCount, plural, zero {# ملف} one {ملف واحد} two {ملفان} few {# ملفات} many {# ملفًا} other {# ملف}}"@@ -1275,6 +1279,14 @@ msgstr "النسخة مجلد حقيقي قائم بذاته، ويبقيها OKmsgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."msgstr "النسخة مجلد حقيقي قائم بذاته، ويبقيها OK متوافقة مع المصدر: حرِّر المهارة هنا فتُحدَّث كل نسخة. يتوقف ذلك لحظة تحريرك نسخةً يدويًا خارج OK — عندها تسير في طريقها الخاص وتظهر كمهارة منفصلة. أما الرابط الرمزي فمؤشِّر إلى المصدر، فلا شيء يمكن أن ينحرف، لكن الموقع يتوقف عن العمل إذا حُذف المصدر."+#: src/lib/skills-api.ts+msgid "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+msgstr "قد تبقى نسخة في {scopeLabel} من: {names}. لا تحذف أي شيء هناك قبل مقارنته بالنسخة الأصلية: فقد يحتوي على النسخة الوحيدة من الملفات التي حذفها نقل فاشل بالفعل."++#: src/lib/skills-api.ts+msgid "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+msgstr "تم الاحتفاظ بنسخة من “{name}” في {scopeLabel} عن قصد. لا تحذفها قبل مقارنتها بالنسخة الأصلية: فقد تحتوي على النسخة الوحيدة من الملفات التي حذفها النقل الفاشل بالفعل."+#. placeholder {0}: path ?? label#: src/components/SkillInstallMenu.tsxmsgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."@@ -1363,6 +1375,10 @@ msgstr "الاقتباس البارز يتميز عن النص المحيط بهmsgid "A real shell is off for this project. Turning it on runs commands with the full access of your user account."msgstr "الصدفة الحقيقية معطّلة لهذا المشروع. تشغيلها يجعل الأوامر تُنفَّذ بكامل صلاحيات حساب المستخدم الخاص بك."+#: src/lib/skills-api.ts+msgid "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+msgstr "تم الاحتفاظ بنسخة مكررة زائدة في {scopeLabel} من: {names}. تم التحقق من أن كل أصل لم يتغير، لذا احذف تلك النسخ ثم أعد محاولة النقل."+#: src/components/ReportBugDialogBody.tsxmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr "يساعدنا التقرير في معرفة السبب. لا يُرسل شيء قبل مراجعتك له."@@ -8507,6 +8523,10 @@ msgstr "تم نقل {label} إلى جزء جديد على اليسار."msgid "Moved {label} to a new pane on the right."msgstr "تم نقل {label} إلى جزء جديد على اليمين."+#: src/lib/skills-api.ts+msgid "Moved {moved} of {total} skills to {scopeLabel}"+msgstr "تم نقل {moved} من {total} مهارات إلى {scopeLabel}"+#: src/components/SkillsTree.tsxmsgid "Moved {moved} skills to Global"msgstr "تم نقل {moved} مهارات إلى العام"@@ -12869,6 +12889,10 @@ msgstr "بعض الملفات غير مدرجة: شجرة العمل تحتويmsgid "Some saved themes aren’t shown because the theme folder exceeds the scan limit."msgstr "لا تظهر بعض السمات المحفوظة لأن مجلد السمات يتجاوز حد الفحص."+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Some skills were deleted with a warning"+msgstr "تم حذف بعض المهارات مع تحذير"+#: src/components/FeedbackForm.tsxmsgid "Something broke"msgstr "حدث عطل"@@ -12877,6 +12901,10 @@ msgstr "حدث عطل"msgid "Something else"msgstr "شيء آخر"+#: src/lib/skills-api.ts+msgid "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+msgstr "يوجد بالفعل شيء باسم “{name}” في {scopeLabel}، ولم يتمكن الخادم من تأكيد ماهيته. ربما تركه هناك عن قصد نقلٌ فاشل سابق: قارنه بالنسخة الأصلية قبل حذفه أو استبداله."+#: src/components/AppErrorBoundary.tsxmsgid "Something went wrong"msgstr "حدث خطأ ما"@@ -13669,6 +13697,10 @@ msgstr "محتوى اللوحة ليس مشهد Excalidraw صالحًا."msgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "لم يفتح تطبيق Claude Desktop الملف. هل هو مثبَّت؟ ({msg})"+#: src/lib/skills-api.ts+msgid "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+msgstr "النسخة من “{name}” المحفوظة في {scopeLabel} هي نسخة مكررة زائدة: تم التحقق من أن الأصل لم يتغير. احذف تلك النسخة ثم أعد محاولة النقل."+#: src/components/SyncStatusBadge.tsxmsgid "The default branch is protected — pushes need a pull request."msgstr "الفرع الافتراضي محمي — يتطلب الدفع طلب سحب."diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.jsonindex d7e1587e7..b886cee47 100644--- a/packages/app/src/locales/bn/messages.json+++ b/packages/app/src/locales/bn/messages.json@@ -685,6 +685,7 @@"851WA-": ["এটি Settings > AI tools & CLI-তে কনফিগার করা যায়"],"87GMKe": ["এই প্রজেক্টটি নেটওয়ার্কে এক্সপোজ করবেন?"],"881Uwh": ["নির্বাচিত টেবিল মুছুন"],+ "89TmeV": ["কিছু স্কিল সতর্কবার্তাসহ মুছে ফেলা হয়েছে"],"89TtiD": ["প্রকল্পের রুটে টেমপ্লেট \"", ["displayTitle"], "\" (", ["fileName"], ") থেকে নতুন ফাইল"],"8AjnFz": ["\"", ["0"], "\" আগেই আমদানি করা হয়েছিল (একই বিষয়বস্তু)।"],"8F1i42": ["পাতা পাওয়া যায়নি"],@@ -1392,6 +1393,7 @@"GbzBEk": ["সার্ভার একটি অসম্পূর্ণ স্কিল প্রতিক্রিয়া ফেরত দিয়েছে।"],"GceAYf": [["label"], "-কে ডান পাশের নতুন প্যানে সরানো হয়েছে।"],"GemPfn": ["বহির্গামী লিংকের ত্রুটি সাড়া পড়তে ব্যর্থ (HTTP ", ["status"], ")"],+ "GesfyX": [["shown"], " এবং আরও ", ["more"], "টি"],"Gfr4fu": ["সার্ভার নথি খুলতে পারছে না"],"GhjUB_": ["পুনরায় যুক্ত হয়েছে"],"Gi8Akx": [@@ -1975,6 +1977,12 @@"OKImo8": ["দ্বন্দ্বযুক্ত ফাইল"],"OLBz-_": ["Mermaid চিত্র রেন্ডার করা যায়নি।"],"OLIKgw": ["ক্রম বদলাতে আইটেম ", ["0"], " টেনে আনুন"],+ "OMS7Xp": [+ ["scopeLabel"],+ "-এ “",+ ["name"],+ "”-এর একটি কপি ইচ্ছে করেই রাখা হয়েছে। মুছে ফেলার আগে সেটি মূলটির সঙ্গে মিলিয়ে দেখুন: ব্যর্থ সরানোর সময় যে ফাইলগুলো ইতিমধ্যে মুছে গেছে, তার একমাত্র কপি এতে থাকতে পারে।"+ ],"ONPvOb": ["এজেন্ট কার্যকলাপ লোড হচ্ছে"],"ONUgxB": ["সেই কনফ্লিক্টটি আর উপলব্ধ নেই।"],"ONWvwQ": ["আপলোড করুন"],@@ -2198,6 +2206,7 @@"RD8cCw": ["এই বিল্ডে এজেন্ট সংযোগ পরিচালনা করা যায় না।"],"RDjuBN": ["সেটআপ"],"RDrXh4": ["ব্যবহারকারী, প্রকল্প ও সংযুক্তির সেটিং কনফিগার করুন।"],+ "RDzxes": [["total"], "টির মধ্যে ", ["moved"], "টি স্কিল ", ["scopeLabel"], "-এ সরানো হয়েছে"],"REkvLz": ["পোর্ট ",["0"],@@ -2235,6 +2244,12 @@"R_U_A4": ["ফাইল বা ফোল্ডার প্যাটার্ন যোগ করুন, যেমন guides/**/*"],"RaPMZv": ["সম্পাদক ও ওয়ার্কস্পেসে যেসব কীবোর্ড শর্টকাট আছে।"],"RaUKLu": ["রিমোট কন্ট্রোল"],+ "Raayoq": [+ ["scopeLabel"],+ "-এ রাখা “",+ ["name"],+ "”-এর কপিটি একটি অপ্রয়োজনীয় নকল: যাচাই করে দেখা গেছে মূলটি অপরিবর্তিত আছে। ওই কপিটি মুছে ফেলুন, তারপর সরানোর কাজটি আবার চেষ্টা করুন।"+ ],"Rah7yq": ["AI-এর কী করা উচিত? (ঐচ্ছিক)"],"Rb1zMa": ["কোনো উদ্ধৃতাংশ নেই"],"RcrskJ": ["বিন্যাস ভুল মনে হয়েছে"],@@ -2925,6 +2940,12 @@"_G7A92": ["index.md বজায় রাখুন"],"_GRWOJ": ["এমবেডিং সরবরাহকারী বদলাবেন?"],"_HgF9q": ["এই অনুযায়ী সাজান"],+ "_HlScO": [+ ["scopeLabel"],+ "-এ এগুলোর একটি কপি থেকে যেতে পারে: ",+ ["names"],+ "। সেখানে কিছু মোছার আগে সেটি মূলটির সঙ্গে মিলিয়ে দেখুন: ব্যর্থ সরানোর সময় যে ফাইলগুলো ইতিমধ্যে মুছে গেছে, তার একমাত্র কপি এতে থাকতে পারে।"+ ],"_IGfXZ": ["গতবার OpenKnowledge অপ্রত্যাশিতভাবে বন্ধ হয়ে গিয়েছিল।"],"_IX_7x": ["অন্যান্য"],"_IfSZn": ["এই নামে ইতিমধ্যেই একটি সংরক্ষিত থিম আছে।"],@@ -3307,6 +3328,12 @@"eFJkVt": ["ক্লোন ব্যর্থ: ", ["cloneError"]],"eG8Jsg": ["সোর্স ট্যাব ফোকাস মোড চালু বা বন্ধ করুন"],"eGUbmF": ["নির্বাচিত ফাইল বা ফোল্ডার কপি করুন"],+ "eGkfGQ": [+ ["scopeLabel"],+ "-এ এগুলোর একটি অপ্রয়োজনীয় কপি রাখা হয়েছে: ",+ ["names"],+ "। যাচাই করে দেখা গেছে প্রতিটি মূল অপরিবর্তিত আছে, তাই ওই কপিগুলো মুছে ফেলুন এবং সরানোর কাজটি আবার চেষ্টা করুন।"+ ],"eJitUk": ["কম্পিউটার থেকে আপলোড করুন"],"eKThTQ": ["ক্রম বদলাতে ব্যর্থ"],"eMWRAs": [@@ -5010,6 +5037,12 @@"xSVO3J": ["যা যা তৈরি হয়"],"xV5sXw": [["0"], " সপ্তাহ আগে"],"xW5AUw": [["pulled"], " টানা হয়েছে"],+ "xW7KK3": [+ ["scopeLabel"],+ "-এ “",+ ["name"],+ "” নামে কিছু আগে থেকেই আছে, আর সার্ভার নিশ্চিত করতে পারেনি সেটি কী। আগের কোনো ব্যর্থ সরানো হয়তো ইচ্ছে করেই সেটি সেখানে রেখে গেছে: মুছে ফেলা বা বদলে ফেলার আগে সেটি মূলটির সঙ্গে মিলিয়ে দেখুন।"+ ],"xWEvuo": ["AI-কে জিজ্ঞেস করুন"],"xWomUD": [["editor"], " সংস্করণ ব্যবহার করুন"],"xXo8FT": ["সংরক্ষণ ব্যর্থ: ", ["error"]],diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex 992b1215b..3b3d7eee8 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -1020,6 +1020,10 @@ msgstr "{settingsDescriptorLabel} প্রপার্টি"msgid "{shareBranch} isn't a valid branch name."msgstr "{shareBranch} একটি বৈধ ব্রাঞ্চ নাম নয়।"+#: src/lib/skills-api.ts+msgid "{shown} and {more} more"+msgstr "{shown} এবং আরও {more}টি"+#: src/components/ReportBugDialogBody.tsxmsgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"msgstr "{sizeText} · গোপন তথ্য সরানো হয়েছে · {fileCount, plural, one {# ফাইল} other {# ফাইল}}"@@ -1271,6 +1275,14 @@ msgstr "অনুলিপি নিজেই একটি সত্যিকাmsgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."msgstr "অনুলিপি নিজেই একটি সত্যিকারের ফোল্ডার, আর OK সেটিকে উৎসের সঙ্গে মিলিয়ে রাখে: স্কিলটি এখানে সম্পাদনা করুন, প্রতিটি অনুলিপি সতেজ হয়ে যায়। আপনি OK-এর বাইরে কোনো অনুলিপি হাতে সম্পাদনা করলেই সেটি বন্ধ হয়ে যায় — তারপর থেকে সেটি নিজের পথে চলে এবং আলাদা স্কিল হিসেবে দেখা দেয়। সিমলিংক বরং উৎসের দিকে একটি নির্দেশক, তাই কিছুই আলাদা হয়ে যেতে পারে না, তবে উৎস মুছে ফেললে সেই জায়গাটি কাজ করা বন্ধ করে দেয়।"+#: src/lib/skills-api.ts+msgid "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+msgstr "{scopeLabel}-এ এগুলোর একটি কপি থেকে যেতে পারে: {names}। সেখানে কিছু মোছার আগে সেটি মূলটির সঙ্গে মিলিয়ে দেখুন: ব্যর্থ সরানোর সময় যে ফাইলগুলো ইতিমধ্যে মুছে গেছে, তার একমাত্র কপি এতে থাকতে পারে।"++#: src/lib/skills-api.ts+msgid "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+msgstr "{scopeLabel}-এ “{name}”-এর একটি কপি ইচ্ছে করেই রাখা হয়েছে। মুছে ফেলার আগে সেটি মূলটির সঙ্গে মিলিয়ে দেখুন: ব্যর্থ সরানোর সময় যে ফাইলগুলো ইতিমধ্যে মুছে গেছে, তার একমাত্র কপি এতে থাকতে পারে।"+#. placeholder {0}: path ?? label#: src/components/SkillInstallMenu.tsxmsgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."@@ -1359,6 +1371,10 @@ msgstr "একটি পুল কোট চারপাশের লেখাmsgid "A real shell is off for this project. Turning it on runs commands with the full access of your user account."msgstr "এই প্রকল্পের জন্য আসল শেল বন্ধ আছে। চালু করলে কমান্ডগুলো আপনার ইউজার অ্যাকাউন্টের পূর্ণ অ্যাক্সেস নিয়ে চলে।"+#: src/lib/skills-api.ts+msgid "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+msgstr "{scopeLabel}-এ এগুলোর একটি অপ্রয়োজনীয় কপি রাখা হয়েছে: {names}। যাচাই করে দেখা গেছে প্রতিটি মূল অপরিবর্তিত আছে, তাই ওই কপিগুলো মুছে ফেলুন এবং সরানোর কাজটি আবার চেষ্টা করুন।"+#: src/components/ReportBugDialogBody.tsxmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr "একটি রিপোর্ট আমাদের কারণ খুঁজে পেতে সাহায্য করে। আপনার পর্যালোচনার আগে কিছুই পাঠানো হয় না।"@@ -8503,6 +8519,10 @@ msgstr "{label}-কে বাঁ পাশের নতুন প্যানেmsgid "Moved {label} to a new pane on the right."msgstr "{label}-কে ডান পাশের নতুন প্যানে সরানো হয়েছে।"+#: src/lib/skills-api.ts+msgid "Moved {moved} of {total} skills to {scopeLabel}"+msgstr "{total}টির মধ্যে {moved}টি স্কিল {scopeLabel}-এ সরানো হয়েছে"+#: src/components/SkillsTree.tsxmsgid "Moved {moved} skills to Global"msgstr "{moved}টি স্কিল গ্লোবালে সরানো হয়েছে"@@ -12865,6 +12885,10 @@ msgstr "কিছু ফাইল তালিকায় নেই: ওয়msgid "Some saved themes aren’t shown because the theme folder exceeds the scan limit."msgstr "থিম ফোল্ডারটি স্ক্যানের সীমা ছাড়িয়ে যাওয়ায় কিছু সংরক্ষিত থিম দেখানো হচ্ছে না।"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Some skills were deleted with a warning"+msgstr "কিছু স্কিল সতর্কবার্তাসহ মুছে ফেলা হয়েছে"+#: src/components/FeedbackForm.tsxmsgid "Something broke"msgstr "কিছু ভেঙে গেছে"@@ -12873,6 +12897,10 @@ msgstr "কিছু ভেঙে গেছে"msgid "Something else"msgstr "অন্য কিছু"+#: src/lib/skills-api.ts+msgid "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+msgstr "{scopeLabel}-এ “{name}” নামে কিছু আগে থেকেই আছে, আর সার্ভার নিশ্চিত করতে পারেনি সেটি কী। আগের কোনো ব্যর্থ সরানো হয়তো ইচ্ছে করেই সেটি সেখানে রেখে গেছে: মুছে ফেলা বা বদলে ফেলার আগে সেটি মূলটির সঙ্গে মিলিয়ে দেখুন।"+#: src/components/AppErrorBoundary.tsxmsgid "Something went wrong"msgstr "কিছু একটা ভুল হয়েছে"@@ -13665,6 +13693,10 @@ msgstr "বোর্ডের বিষয়বস্তু কোনো বৈmsgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "Claude Desktop App ফাইলটি খোলেনি। সেটি কি ইনস্টল করা আছে? ({msg})"+#: src/lib/skills-api.ts+msgid "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+msgstr "{scopeLabel}-এ রাখা “{name}”-এর কপিটি একটি অপ্রয়োজনীয় নকল: যাচাই করে দেখা গেছে মূলটি অপরিবর্তিত আছে। ওই কপিটি মুছে ফেলুন, তারপর সরানোর কাজটি আবার চেষ্টা করুন।"+#: src/components/SyncStatusBadge.tsxmsgid "The default branch is protected — pushes need a pull request."msgstr "ডিফল্ট ব্রাঞ্চটি সুরক্ষিত — পাঠাতে একটি পুল রিকোয়েস্ট লাগে।"diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex ffb05248b..68420069f 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -700,6 +700,7 @@"851WA-": ["This can be configured in Settings > AI tools & CLI"],"87GMKe": ["Expose this project to the network?"],"881Uwh": ["Delete selected table"],+ "89TmeV": ["Some skills were deleted with a warning"],"89TtiD": ["New file from template \"",["displayTitle"],@@ -1436,6 +1437,7 @@"GbzBEk": ["Server returned an incomplete skills response."],"GceAYf": ["Moved ", ["label"], " to a new pane on the right."],"GemPfn": ["Failed to parse forward-links error response (HTTP ", ["status"], ")"],+ "GesfyX": [["shown"], " and ", ["more"], " more"],"Gfr4fu": ["Server can't open documents"],"GhjUB_": ["Reconnected"],"Gi8Akx": [@@ -2041,6 +2043,13 @@"OKImo8": ["Conflicted files"],"OLBz-_": ["Mermaid diagram failed to render."],"OLIKgw": ["Drag item ", ["0"], " to reorder"],+ "OMS7Xp": [+ "A copy of \"",+ ["name"],+ "\" was kept in ",+ ["scopeLabel"],+ " on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+ ],"ONPvOb": ["Loading agent activity"],"ONUgxB": ["That conflict is no longer available."],"ONWvwQ": ["Upload"],@@ -2262,6 +2271,7 @@"RD8cCw": ["Managing agent connections is unavailable in this build."],"RDjuBN": ["Setup"],"RDrXh4": ["Configure user, project, and integration settings."],+ "RDzxes": ["Moved ", ["moved"], " of ", ["total"], " skills to ", ["scopeLabel"]],"REkvLz": ["Port ",["0"],@@ -2300,6 +2310,13 @@"R_U_A4": ["Add file or folder pattern, e.g. guides/**/*"],"RaPMZv": ["Keyboard shortcuts available in the editor and workspace."],"RaUKLu": ["Remote control"],+ "Raayoq": [+ "The copy of \"",+ ["name"],+ "\" kept in ",+ ["scopeLabel"],+ " is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+ ],"Rah7yq": ["What should the AI do? (optional)"],"Rb1zMa": ["No excerpt"],"RcrskJ": ["Formatting looked wrong"],@@ -2994,6 +3011,13 @@"_G7A92": ["Maintain index.md"],"_GRWOJ": ["Change the embeddings provider?"],"_HgF9q": ["Sort by"],+ "_HlScO": [+ "A copy may remain in ",+ ["scopeLabel"],+ " for: ",+ ["names"],+ ". Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+ ],"_IGfXZ": ["OpenKnowledge quit unexpectedly last time."],"_IX_7x": ["Other"],"_IfSZn": ["A saved theme already uses this name."],@@ -3404,6 +3428,13 @@"eFJkVt": ["Clone failed: ", ["cloneError"]],"eG8Jsg": ["Toggle source tab focus mode"],"eGUbmF": ["Copy selected file or folder"],+ "eGkfGQ": [+ "A redundant copy was kept in ",+ ["scopeLabel"],+ " for: ",+ ["names"],+ ". Each original was verified unchanged, so remove those copies and retry the move."+ ],"eJitUk": ["Upload from computer"],"eKThTQ": ["Failed to reorder"],"eMWRAs": ["Pages indexed: ", ["semanticIndexedCount"], " of ", ["semanticTotalCount"], "."],@@ -5185,6 +5216,13 @@"xSVO3J": ["What gets created"],"xV5sXw": [["0"], "w ago"],"xW5AUw": ["Pulled ", ["pulled"]],+ "xW7KK3": [+ "Something named \"",+ ["name"],+ "\" is already in ",+ ["scopeLabel"],+ ", and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+ ],"xWEvuo": ["Ask AI"],"xWomUD": ["Use ", ["editor"], " version"],"xXo8FT": ["Save failed: ", ["error"]],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 4538638dd..c1b59e10a 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -1020,6 +1020,10 @@ msgstr "{settingsDescriptorLabel} properties"msgid "{shareBranch} isn't a valid branch name."msgstr "{shareBranch} isn't a valid branch name."+#: src/lib/skills-api.ts+msgid "{shown} and {more} more"+msgstr "{shown} and {more} more"+#: src/components/ReportBugDialogBody.tsxmsgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"msgstr "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"@@ -1275,6 +1279,14 @@ msgstr "A copy is a real folder of its own, and OK keeps it in step with the soumsgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."msgstr "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."+#: src/lib/skills-api.ts+msgid "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+msgstr "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."++#: src/lib/skills-api.ts+msgid "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+msgstr "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+#. placeholder {0}: path ?? label#: src/components/SkillInstallMenu.tsxmsgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."@@ -1363,6 +1375,10 @@ msgstr "A pull quote stands out from the surrounding text."msgid "A real shell is off for this project. Turning it on runs commands with the full access of your user account."msgstr "A real shell is off for this project. Turning it on runs commands with the full access of your user account."+#: src/lib/skills-api.ts+msgid "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+msgstr "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+#: src/components/ReportBugDialogBody.tsxmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr "A report helps us find the cause. Nothing is sent until you review it."@@ -8507,6 +8523,10 @@ msgstr "Moved {label} to a new pane on the left."msgid "Moved {label} to a new pane on the right."msgstr "Moved {label} to a new pane on the right."+#: src/lib/skills-api.ts+msgid "Moved {moved} of {total} skills to {scopeLabel}"+msgstr "Moved {moved} of {total} skills to {scopeLabel}"+#: src/components/SkillsTree.tsxmsgid "Moved {moved} skills to Global"msgstr "Moved {moved} skills to Global"@@ -12869,6 +12889,10 @@ msgstr "Some files are not listed — the working tree has too many changes."msgid "Some saved themes aren’t shown because the theme folder exceeds the scan limit."msgstr "Some saved themes aren’t shown because the theme folder exceeds the scan limit."+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Some skills were deleted with a warning"+msgstr "Some skills were deleted with a warning"+#: src/components/FeedbackForm.tsxmsgid "Something broke"msgstr "Something broke"@@ -12877,6 +12901,10 @@ msgstr "Something broke"msgid "Something else"msgstr "Something else"+#: src/lib/skills-api.ts+msgid "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+msgstr "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+#: src/components/AppErrorBoundary.tsxmsgid "Something went wrong"msgstr "Something went wrong"@@ -13669,6 +13697,10 @@ msgstr "The board's content is not a valid Excalidraw scene."msgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "The Claude Desktop App didn't open the file. Is it installed? ({msg})"+#: src/lib/skills-api.ts+msgid "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+msgstr "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+#: src/components/SyncStatusBadge.tsxmsgid "The default branch is protected — pushes need a pull request."msgstr "The default branch is protected — pushes need a pull request."diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.jsonindex ac976db76..7873bab84 100644--- a/packages/app/src/locales/es/messages.json+++ b/packages/app/src/locales/es/messages.json@@ -838,6 +838,7 @@"851WA-": ["Esto se puede configurar en Ajustes > Herramientas de IA y CLI"],"87GMKe": ["¿Exponer este proyecto a la red?"],"881Uwh": ["Eliminar la tabla seleccionada"],+ "89TmeV": ["Algunas habilidades se eliminaron con una advertencia"],"89TtiD": ["Archivo nuevo a partir de la plantilla \"",["displayTitle"],@@ -1675,6 +1676,7 @@["status"],")"],+ "GesfyX": [["shown"], " y ", ["more"], " más"],"Gfr4fu": ["El servidor no puede abrir documentos"],"GhjUB_": ["Reconectado"],"Gi8Akx": [@@ -2369,6 +2371,13 @@"OKImo8": ["Archivos en conflicto"],"OLBz-_": ["No se pudo renderizar el diagrama de Mermaid."],"OLIKgw": ["Arrastra el elemento ", ["0"], " para reordenar"],+ "OMS7Xp": [+ "Se conservó a propósito una copia de «",+ ["name"],+ "» en ",+ ["scopeLabel"],+ ". No la elimines antes de compararla con el original: puede contener la única copia de los archivos que el movimiento fallido ya eliminó."+ ],"ONPvOb": ["Cargando la actividad del agente"],"ONUgxB": ["Ese conflicto ya no está disponible."],"ONWvwQ": ["Subir"],@@ -2610,6 +2619,7 @@"RD8cCw": ["La gestión de conexiones de agentes no está disponible en esta versión."],"RDjuBN": ["Configuración"],"RDrXh4": ["Configura los ajustes de usuario, de proyecto y de integraciones."],+ "RDzxes": [["moved"], " de ", ["total"], " habilidades movidas a ", ["scopeLabel"]],"REkvLz": ["El puerto ",["0"],@@ -2648,6 +2658,13 @@"R_U_A4": ["Añade un patrón de archivo o carpeta, p. ej. guides/**/*"],"RaPMZv": ["Atajos de teclado disponibles en el editor y en el espacio de trabajo."],"RaUKLu": ["Control remoto"],+ "Raayoq": [+ "La copia de «",+ ["name"],+ "» conservada en ",+ ["scopeLabel"],+ " es un duplicado redundante: se verificó que el original no cambió. Elimina esa copia y vuelve a intentar el movimiento."+ ],"Rah7yq": ["¿Qué debería hacer la IA? (opcional)"],"Rb1zMa": ["Sin extracto"],"RcrskJ": ["El formato se veía mal"],@@ -3480,6 +3497,13 @@"_G7A92": ["Mantener index.md"],"_GRWOJ": ["¿Cambiar el proveedor de embeddings?"],"_HgF9q": ["Ordenar por"],+ "_HlScO": [+ "Puede quedar una copia en ",+ ["scopeLabel"],+ " de: ",+ ["names"],+ ". No elimines nada de ahí antes de compararlo con el original: puede contener la única copia de los archivos que un movimiento fallido ya eliminó."+ ],"_IGfXZ": ["La última vez OpenKnowledge se cerró de forma inesperada."],"_IX_7x": ["Otro"],"_IfSZn": ["Ya existe un tema guardado con este nombre."],@@ -3970,6 +3994,13 @@"eFJkVt": ["No se pudo clonar: ", ["cloneError"]],"eG8Jsg": ["Activar o desactivar el modo de foco del tabulador en el código"],"eGUbmF": ["Copiar el archivo o la carpeta seleccionados"],+ "eGkfGQ": [+ "Se conservó una copia redundante en ",+ ["scopeLabel"],+ " de: ",+ ["names"],+ ". Se verificó que cada original no cambió, así que elimina esas copias y vuelve a intentar el movimiento."+ ],"eJitUk": ["Subir desde el equipo"],"eKThTQ": ["No se pudo reordenar"],"eMWRAs": [@@ -5985,6 +6016,13 @@"xSVO3J": ["Qué se crea"],"xV5sXw": ["hace ", ["0"], " sem"],"xW5AUw": ["Traído ", ["pulled"]],+ "xW7KK3": [+ "Ya hay algo llamado «",+ ["name"],+ "» en ",+ ["scopeLabel"],+ " y el servidor no pudo confirmar qué es. Puede que un movimiento fallido anterior lo dejara ahí a propósito: compáralo con el original antes de eliminarlo o reemplazarlo."+ ],"xWEvuo": ["Preguntar a la IA"],"xWomUD": ["Usar la versión de ", ["editor"]],"xXo8FT": ["Falló al guardar: ", ["error"]],diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex 4e6fe043b..4f24bd41b 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -1020,6 +1020,10 @@ msgstr "Propiedades de {settingsDescriptorLabel}"msgid "{shareBranch} isn't a valid branch name."msgstr "{shareBranch} no es un nombre de rama válido."+#: src/lib/skills-api.ts+msgid "{shown} and {more} more"+msgstr "{shown} y {more} más"+#: src/components/ReportBugDialogBody.tsxmsgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"msgstr "{sizeText} · secretos ocultos · {fileCount, plural, one {# archivo} many {# archivos} other {# archivos}}"@@ -1275,6 +1279,14 @@ msgstr "Una copia es una carpeta propia, y OK la mantiene alineada con el origenmsgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."msgstr "Una copia es una carpeta propia, y OK la mantiene alineada con el origen: edita la habilidad aquí y todas las copias se actualizan. Eso se detiene en cuanto editas a mano una copia fuera de OK; a partir de ahí sigue su propio camino y aparece como una habilidad aparte. Un enlace simbólico, en cambio, apunta al origen, así que nada se desvía, pero una ubicación deja de funcionar si se elimina el origen."+#: src/lib/skills-api.ts+msgid "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+msgstr "Puede quedar una copia en {scopeLabel} de: {names}. No elimines nada de ahí antes de compararlo con el original: puede contener la única copia de los archivos que un movimiento fallido ya eliminó."++#: src/lib/skills-api.ts+msgid "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+msgstr "Se conservó a propósito una copia de «{name}» en {scopeLabel}. No la elimines antes de compararla con el original: puede contener la única copia de los archivos que el movimiento fallido ya eliminó."+#. placeholder {0}: path ?? label#: src/components/SkillInstallMenu.tsxmsgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."@@ -1363,6 +1375,10 @@ msgstr "Una cita destacada resalta sobre el texto que la rodea."msgid "A real shell is off for this project. Turning it on runs commands with the full access of your user account."msgstr "El shell real está desactivado para este proyecto. Al activarlo, los comandos se ejecutan con todo el acceso de tu cuenta de usuario."+#: src/lib/skills-api.ts+msgid "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+msgstr "Se conservó una copia redundante en {scopeLabel} de: {names}. Se verificó que cada original no cambió, así que elimina esas copias y vuelve a intentar el movimiento."+#: src/components/ReportBugDialogBody.tsxmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr "Un informe nos ayuda a encontrar la causa. No se envía nada hasta que lo revises."@@ -8507,6 +8523,10 @@ msgstr "Se movió {label} a un panel nuevo a la izquierda."msgid "Moved {label} to a new pane on the right."msgstr "Se movió {label} a un panel nuevo a la derecha."+#: src/lib/skills-api.ts+msgid "Moved {moved} of {total} skills to {scopeLabel}"+msgstr "{moved} de {total} habilidades movidas a {scopeLabel}"+#: src/components/SkillsTree.tsxmsgid "Moved {moved} skills to Global"msgstr "{moved} habilidades movidas a Global"@@ -12869,6 +12889,10 @@ msgstr "Algunos archivos no aparecen: el árbol de trabajo tiene demasiados cambmsgid "Some saved themes aren’t shown because the theme folder exceeds the scan limit."msgstr "Algunos temas guardados no se muestran porque la carpeta de temas supera el límite de análisis."+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Some skills were deleted with a warning"+msgstr "Algunas habilidades se eliminaron con una advertencia"+#: src/components/FeedbackForm.tsxmsgid "Something broke"msgstr "Algo se rompió"@@ -12877,6 +12901,10 @@ msgstr "Algo se rompió"msgid "Something else"msgstr "Otra cosa"+#: src/lib/skills-api.ts+msgid "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+msgstr "Ya hay algo llamado «{name}» en {scopeLabel} y el servidor no pudo confirmar qué es. Puede que un movimiento fallido anterior lo dejara ahí a propósito: compáralo con el original antes de eliminarlo o reemplazarlo."+#: src/components/AppErrorBoundary.tsxmsgid "Something went wrong"msgstr "Algo salió mal"@@ -13669,6 +13697,10 @@ msgstr "El contenido de la pizarra no es una escena de Excalidraw válida."msgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "La aplicación Claude Desktop no abrió el archivo. ¿Está instalada? ({msg})"+#: src/lib/skills-api.ts+msgid "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+msgstr "La copia de «{name}» conservada en {scopeLabel} es un duplicado redundante: se verificó que el original no cambió. Elimina esa copia y vuelve a intentar el movimiento."+#: src/components/SyncStatusBadge.tsxmsgid "The default branch is protected — pushes need a pull request."msgstr "La rama por defecto está protegida: los push requieren una pull request."diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.jsonindex 0fb50f440..c80a54802 100644--- a/packages/app/src/locales/fr/messages.json+++ b/packages/app/src/locales/fr/messages.json@@ -865,6 +865,7 @@"851WA-": ["Cela se configure dans Paramètres > Outils IA et CLI"],"87GMKe": ["Exposer ce projet au réseau ?"],"881Uwh": ["Supprimer le tableau sélectionné"],+ "89TmeV": ["Certaines compétences ont été supprimées avec un avertissement"],"89TtiD": ["Nouveau fichier à partir du modèle « ",["displayTitle"],@@ -1711,6 +1712,7 @@["status"],")"],+ "GesfyX": [["shown"], " et ", ["more"], " de plus"],"Gfr4fu": ["Le serveur ne peut pas ouvrir de documents"],"GhjUB_": ["Reconnecté"],"Gi8Akx": [@@ -2410,6 +2412,13 @@"OKImo8": ["Fichiers en conflit"],"OLBz-_": ["Le rendu du diagramme Mermaid a échoué."],"OLIKgw": ["Faites glisser l'élément ", ["0"], " pour réorganiser"],+ "OMS7Xp": [+ "Une copie de « ",+ ["name"],+ " » a été conservée dans ",+ ["scopeLabel"],+ " de façon délibérée. Ne la supprimez pas avant de l'avoir comparée à l'original : elle peut contenir la seule copie des fichiers que le déplacement échoué a déjà supprimés."+ ],"ONPvOb": ["Chargement de l'activité de l'agent"],"ONUgxB": ["Ce conflit n'est plus disponible."],"ONWvwQ": ["Envoyer"],@@ -2653,6 +2662,7 @@"RD8cCw": ["La gestion des connexions des agents n'est pas disponible dans cette version."],"RDjuBN": ["Configuration"],"RDrXh4": ["Configurez les paramètres utilisateur, projet et intégrations."],+ "RDzxes": [["moved"], " compétences sur ", ["total"], " déplacées vers ", ["scopeLabel"]],"REkvLz": ["Le port ",["0"],@@ -2691,6 +2701,13 @@"R_U_A4": ["Ajoutez un motif de fichier ou de dossier, par ex. guides/**/*"],"RaPMZv": ["Raccourcis clavier disponibles dans l'éditeur et l'espace de travail."],"RaUKLu": ["Contrôle à distance"],+ "Raayoq": [+ "La copie de « ",+ ["name"],+ " » conservée dans ",+ ["scopeLabel"],+ " est un doublon redondant : l'original a été vérifié comme inchangé. Supprimez cette copie, puis réessayez le déplacement."+ ],"Rah7yq": ["Que doit faire l'IA ? (facultatif)"],"Rb1zMa": ["Pas d'extrait"],"RcrskJ": ["La mise en forme semblait incorrecte"],@@ -3525,6 +3542,13 @@"_G7A92": ["Maintenir index.md"],"_GRWOJ": ["Changer de fournisseur d'embeddings ?"],"_HgF9q": ["Trier par"],+ "_HlScO": [+ "Une copie peut subsister dans ",+ ["scopeLabel"],+ " pour : ",+ ["names"],+ ". Ne supprimez rien à cet endroit avant de l'avoir comparé à l'original : cela peut contenir la seule copie des fichiers qu'un déplacement échoué a déjà supprimés."+ ],"_IGfXZ": ["OpenKnowledge s'est arrêté de façon inattendue la dernière fois."],"_IX_7x": ["Autre"],"_IfSZn": ["Un thème enregistré utilise déjà ce nom."],@@ -4017,6 +4041,13 @@"eFJkVt": ["Échec du clonage : ", ["cloneError"]],"eG8Jsg": ["Basculer le mode focus de la touche Tab dans la source"],"eGUbmF": ["Copier le fichier ou dossier sélectionné"],+ "eGkfGQ": [+ "Une copie redondante a été conservée dans ",+ ["scopeLabel"],+ " pour : ",+ ["names"],+ ". Chaque original a été vérifié comme inchangé : supprimez ces copies, puis réessayez le déplacement."+ ],"eJitUk": ["Envoyer depuis l'ordinateur"],"eKThTQ": ["Échec de la réorganisation"],"eMWRAs": ["Pages indexées : ", ["semanticIndexedCount"], " sur ", ["semanticTotalCount"], "."],@@ -6053,6 +6084,13 @@"xSVO3J": ["Ce qui est créé"],"xV5sXw": ["il y a ", ["0"], " sem"],"xW5AUw": ["Récupéré ", ["pulled"]],+ "xW7KK3": [+ "Quelque chose nommé « ",+ ["name"],+ " » se trouve déjà dans ",+ ["scopeLabel"],+ ", et le serveur n'a pas pu confirmer de quoi il s'agit. Un déplacement échoué antérieur l'y a peut-être conservé de façon délibérée : comparez-le à l'original avant de le supprimer ou de le remplacer."+ ],"xWEvuo": ["Demander à l'IA"],"xWomUD": ["Utiliser la version ", ["editor"]],"xXo8FT": ["Échec de l'enregistrement : ", ["error"]],diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex 8f6070e11..db4cf4bd4 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -1020,6 +1020,10 @@ msgstr "Propriétés de {settingsDescriptorLabel}"msgid "{shareBranch} isn't a valid branch name."msgstr "{shareBranch} n'est pas un nom de branche valide."+#: src/lib/skills-api.ts+msgid "{shown} and {more} more"+msgstr "{shown} et {more} de plus"+#: src/components/ReportBugDialogBody.tsxmsgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"msgstr "{sizeText} · secrets masqués · {fileCount, plural, one {# fichier} many {# fichiers} other {# fichiers}}"@@ -1275,6 +1279,14 @@ msgstr "Une copie est un vrai dossier à part entière, et OK la maintient alignmsgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."msgstr "Une copie est un vrai dossier à part entière, et OK la maintient alignée sur la source : modifiez la compétence ici et chaque copie est actualisée. Cela s'arrête dès que vous modifiez une copie à la main en dehors d'OK — à partir de là elle suit son propre chemin et apparaît comme une compétence distincte. Un lien symbolique, lui, pointe vers la source, donc rien ne peut diverger, mais un emplacement cesse de fonctionner si la source est supprimée."+#: src/lib/skills-api.ts+msgid "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+msgstr "Une copie peut subsister dans {scopeLabel} pour : {names}. Ne supprimez rien à cet endroit avant de l'avoir comparé à l'original : cela peut contenir la seule copie des fichiers qu'un déplacement échoué a déjà supprimés."++#: src/lib/skills-api.ts+msgid "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+msgstr "Une copie de « {name} » a été conservée dans {scopeLabel} de façon délibérée. Ne la supprimez pas avant de l'avoir comparée à l'original : elle peut contenir la seule copie des fichiers que le déplacement échoué a déjà supprimés."+#. placeholder {0}: path ?? label#: src/components/SkillInstallMenu.tsxmsgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."@@ -1363,6 +1375,10 @@ msgstr "Une citation mise en exergue se détache du texte qui l'entoure."msgid "A real shell is off for this project. Turning it on runs commands with the full access of your user account."msgstr "Le vrai shell est désactivé pour ce projet. L'activer exécute les commandes avec tous les droits de votre compte utilisateur."+#: src/lib/skills-api.ts+msgid "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+msgstr "Une copie redondante a été conservée dans {scopeLabel} pour : {names}. Chaque original a été vérifié comme inchangé : supprimez ces copies, puis réessayez le déplacement."+#: src/components/ReportBugDialogBody.tsxmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr "Un rapport nous aide à trouver la cause. Rien n'est envoyé avant que vous l'ayez relu."@@ -8507,6 +8523,10 @@ msgstr "{label} déplacé vers un nouveau volet à gauche."msgid "Moved {label} to a new pane on the right."msgstr "{label} déplacé vers un nouveau volet à droite."+#: src/lib/skills-api.ts+msgid "Moved {moved} of {total} skills to {scopeLabel}"+msgstr "{moved} compétences sur {total} déplacées vers {scopeLabel}"+#: src/components/SkillsTree.tsxmsgid "Moved {moved} skills to Global"msgstr "{moved} compétences déplacées vers Global"@@ -12869,6 +12889,10 @@ msgstr "Certains fichiers ne sont pas listés : l'arbre de travail contient tropmsgid "Some saved themes aren’t shown because the theme folder exceeds the scan limit."msgstr "Certains thèmes enregistrés ne sont pas affichés car le dossier des thèmes dépasse la limite d’analyse."+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Some skills were deleted with a warning"+msgstr "Certaines compétences ont été supprimées avec un avertissement"+#: src/components/FeedbackForm.tsxmsgid "Something broke"msgstr "Quelque chose s'est cassé"@@ -12877,6 +12901,10 @@ msgstr "Quelque chose s'est cassé"msgid "Something else"msgstr "Autre chose"+#: src/lib/skills-api.ts+msgid "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+msgstr "Quelque chose nommé « {name} » se trouve déjà dans {scopeLabel}, et le serveur n'a pas pu confirmer de quoi il s'agit. Un déplacement échoué antérieur l'y a peut-être conservé de façon délibérée : comparez-le à l'original avant de le supprimer ou de le remplacer."+#: src/components/AppErrorBoundary.tsxmsgid "Something went wrong"msgstr "Une erreur s'est produite"@@ -13669,6 +13697,10 @@ msgstr "Le contenu du tableau n'est pas une scène Excalidraw valide."msgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "L'application Claude Desktop n'a pas ouvert le fichier. Est-elle installée ? ({msg})"+#: src/lib/skills-api.ts+msgid "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+msgstr "La copie de « {name} » conservée dans {scopeLabel} est un doublon redondant : l'original a été vérifié comme inchangé. Supprimez cette copie, puis réessayez le déplacement."+#: src/components/SyncStatusBadge.tsxmsgid "The default branch is protected — pushes need a pull request."msgstr "La branche par défaut est protégée — les push nécessitent une pull request."diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.jsonindex 4bc0acfc7..f124087f8 100644--- a/packages/app/src/locales/hi/messages.json+++ b/packages/app/src/locales/hi/messages.json@@ -690,6 +690,7 @@"851WA-": ["इसे Settings > AI tools & CLI में कॉन्फ़िगर किया जा सकता है"],"87GMKe": ["क्या इस प्रोजेक्ट को नेटवर्क पर एक्सपोज़ करें?"],"881Uwh": ["चयनित तालिका हटाएँ"],+ "89TmeV": ["कुछ स्किलें चेतावनी के साथ हटाई गईं"],"89TtiD": ["प्रोजेक्ट रूट में टेम्पलेट \"", ["displayTitle"], "\" (", ["fileName"], ") से नई फ़ाइल"],"8AjnFz": ["\"", ["0"], "\" पहले ही आयात किया जा चुका था (समान सामग्री)।"],"8F1i42": ["पेज नहीं मिला"],@@ -1396,6 +1397,7 @@"GbzBEk": ["सर्वर ने अधूरी स्किल प्रतिक्रिया लौटाई।"],"GceAYf": [["label"], " को दाईं ओर के नए फलक में ले जाया गया।"],"GemPfn": ["आगे जाने वाले लिंक की त्रुटि प्रतिक्रिया पढ़ने में विफल (HTTP ", ["status"], ")"],+ "GesfyX": [["shown"], " और ", ["more"], " अन्य"],"Gfr4fu": ["सर्वर दस्तावेज़ नहीं खोल सकता"],"GhjUB_": ["फिर से जुड़ गया"],"Gi8Akx": ["अभी कोई एजेंट सेट अप नहीं है — फ़ाइलें संलग्न करने के लिए एजेंट कनेक्शन में ऐप के भीतर का एजेंट जोड़ें।"],@@ -1984,6 +1986,13 @@"OKImo8": ["विरोध वाली फ़ाइलें"],"OLBz-_": ["Mermaid आरेख रेंडर नहीं हो सका।"],"OLIKgw": ["क्रम बदलने के लिए आइटम ", ["0"], " खींचें"],+ "OMS7Xp": [+ "“",+ ["name"],+ "” की एक कॉपी ",+ ["scopeLabel"],+ " में जान-बूझकर रखी गई है। इसे मिटाने से पहले मूल से मिलाकर देखें: इसमें उन फ़ाइलों की इकलौती कॉपी हो सकती है जिन्हें असफल मूव पहले ही हटा चुका है।"+ ],"ONPvOb": ["एजेंट गतिविधि लोड हो रही है"],"ONUgxB": ["वह कॉन्फ़्लिक्ट अब उपलब्ध नहीं है।"],"ONWvwQ": ["अपलोड करें"],@@ -2201,6 +2210,7 @@"RD8cCw": ["इस बिल्ड में एजेंट कनेक्शन प्रबंधित करना उपलब्ध नहीं है।"],"RDjuBN": ["सेटअप"],"RDrXh4": ["उपयोगकर्ता, प्रोजेक्ट और एकीकरण सेटिंग कॉन्फ़िगर करें।"],+ "RDzxes": [["total"], " में से ", ["moved"], " स्किलें ", ["scopeLabel"], " में ले जाई गईं"],"REkvLz": ["पोर्ट ",["0"],@@ -2235,6 +2245,12 @@"R_U_A4": ["फ़ाइल या फ़ोल्डर पैटर्न जोड़ें, जैसे guides/**/*"],"RaPMZv": ["संपादक और कार्यक्षेत्र में उपलब्ध कीबोर्ड शॉर्टकट।"],"RaUKLu": ["रिमोट कंट्रोल"],+ "Raayoq": [+ ["scopeLabel"],+ " में रखी गई “",+ ["name"],+ "” की कॉपी एक ग़ैरज़रूरी नक़ल है: जाँच में मूल अपरिवर्तित मिला। उस कॉपी को हटाएँ, फिर मूव दोबारा आज़माएँ।"+ ],"Rah7yq": ["AI को क्या करना चाहिए? (वैकल्पिक)"],"Rb1zMa": ["कोई अंश नहीं"],"RcrskJ": ["फ़ॉर्मैटिंग ग़लत लगी"],@@ -2915,6 +2931,12 @@"_G7A92": ["index.md बनाए रखें"],"_GRWOJ": ["एम्बेडिंग प्रदाता बदलें?"],"_HgF9q": ["इसके अनुसार क्रम"],+ "_HlScO": [+ ["scopeLabel"],+ " में इनकी एक कॉपी बची रह सकती है: ",+ ["names"],+ "। वहाँ कुछ भी मिटाने से पहले उसे मूल से मिलाकर देखें: उसमें उन फ़ाइलों की इकलौती कॉपी हो सकती है जिन्हें असफल मूव पहले ही हटा चुका है।"+ ],"_IGfXZ": ["पिछली बार OpenKnowledge अप्रत्याशित रूप से बंद हो गया था।"],"_IX_7x": ["अन्य"],"_IfSZn": ["एक सहेजी गई थीम पहले से इस नाम का उपयोग कर रही है।"],@@ -3298,6 +3320,12 @@"eFJkVt": ["क्लोन विफल: ", ["cloneError"]],"eG8Jsg": ["स्रोत टैब फ़ोकस मोड चालू या बंद करें"],"eGUbmF": ["चयनित फ़ाइल या फ़ोल्डर कॉपी करें"],+ "eGkfGQ": [+ ["scopeLabel"],+ " में इनकी एक ग़ैरज़रूरी कॉपी रखी गई है: ",+ ["names"],+ "। जाँच में हर मूल अपरिवर्तित मिला, इसलिए उन कॉपियों को हटाएँ और मूव दोबारा आज़माएँ।"+ ],"eJitUk": ["कंप्यूटर से अपलोड करें"],"eKThTQ": ["क्रम बदलने में विफल"],"eMWRAs": ["इंडेक्स किए गए पेज: ", ["semanticTotalCount"], " में से ", ["semanticIndexedCount"], "।"],@@ -4998,6 +5026,12 @@"xSVO3J": ["क्या बनता है"],"xV5sXw": [["0"], " सप्ताह पहले"],"xW5AUw": [["pulled"], " खींचा"],+ "xW7KK3": [+ ["scopeLabel"],+ " में “",+ ["name"],+ "” नाम की कोई चीज़ पहले से मौजूद है, और सर्वर यह पुष्टि नहीं कर सका कि वह क्या है। हो सकता है पहले का कोई असफल मूव उसे जान-बूझकर वहाँ छोड़ गया हो: मिटाने या बदलने से पहले उसे मूल से मिलाकर देखें।"+ ],"xWEvuo": ["AI से पूछें"],"xWomUD": [["editor"], " संस्करण उपयोग करें"],"xXo8FT": ["सहेजना विफल: ", ["error"]],diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex 58118a084..b85dd776c 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -1020,6 +1020,10 @@ msgstr "{settingsDescriptorLabel} प्रॉपर्टी"msgid "{shareBranch} isn't a valid branch name."msgstr "{shareBranch} एक मान्य ब्रांच नाम नहीं है।"+#: src/lib/skills-api.ts+msgid "{shown} and {more} more"+msgstr "{shown} और {more} अन्य"+#: src/components/ReportBugDialogBody.tsxmsgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"msgstr "{sizeText} · गोपनीय जानकारी हटाई गई · {fileCount, plural, one {# फ़ाइल} other {# फ़ाइलें}}"@@ -1271,6 +1275,14 @@ msgstr "प्रति अपने आप में एक असली फ़msgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."msgstr "प्रति अपने आप में एक असली फ़ोल्डर है, और OK उसे स्रोत के साथ तालमेल में रखता है: स्किल को यहाँ संपादित करें और हर प्रति ताज़ा हो जाती है। यह उसी क्षण रुक जाता है जब आप OK के बाहर किसी प्रति को हाथ से संपादित करते हैं — उसके बाद वह अपने रास्ते चली जाती है और एक अलग स्किल के रूप में दिखती है। इसके बजाय सिमलिंक स्रोत की ओर एक संकेतक है, इसलिए कुछ भी अलग नहीं हो सकता, पर स्रोत हटने पर वह स्थान काम करना बंद कर देता है।"+#: src/lib/skills-api.ts+msgid "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+msgstr "{scopeLabel} में इनकी एक कॉपी बची रह सकती है: {names}। वहाँ कुछ भी मिटाने से पहले उसे मूल से मिलाकर देखें: उसमें उन फ़ाइलों की इकलौती कॉपी हो सकती है जिन्हें असफल मूव पहले ही हटा चुका है।"++#: src/lib/skills-api.ts+msgid "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+msgstr "“{name}” की एक कॉपी {scopeLabel} में जान-बूझकर रखी गई है। इसे मिटाने से पहले मूल से मिलाकर देखें: इसमें उन फ़ाइलों की इकलौती कॉपी हो सकती है जिन्हें असफल मूव पहले ही हटा चुका है।"+#. placeholder {0}: path ?? label#: src/components/SkillInstallMenu.tsxmsgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."@@ -1359,6 +1371,10 @@ msgstr "एक पुल कोट आसपास के पाठ से अmsgid "A real shell is off for this project. Turning it on runs commands with the full access of your user account."msgstr "इस प्रोजेक्ट के लिए असली शेल बंद है। इसे चालू करने पर कमांड आपके उपयोगकर्ता खाते की पूरी पहुँच के साथ चलते हैं।"+#: src/lib/skills-api.ts+msgid "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+msgstr "{scopeLabel} में इनकी एक ग़ैरज़रूरी कॉपी रखी गई है: {names}। जाँच में हर मूल अपरिवर्तित मिला, इसलिए उन कॉपियों को हटाएँ और मूव दोबारा आज़माएँ।"+#: src/components/ReportBugDialogBody.tsxmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr "एक रिपोर्ट हमें कारण खोजने में मदद करती है। आपकी समीक्षा से पहले कुछ भी नहीं भेजा जाता।"@@ -8503,6 +8519,10 @@ msgstr "{label} को बाईं ओर के नए फलक में लmsgid "Moved {label} to a new pane on the right."msgstr "{label} को दाईं ओर के नए फलक में ले जाया गया।"+#: src/lib/skills-api.ts+msgid "Moved {moved} of {total} skills to {scopeLabel}"+msgstr "{total} में से {moved} स्किलें {scopeLabel} में ले जाई गईं"+#: src/components/SkillsTree.tsxmsgid "Moved {moved} skills to Global"msgstr "{moved} स्किलें ग्लोबल में ले जाई गईं"@@ -12865,6 +12885,10 @@ msgstr "कुछ फ़ाइलें सूचीबद्ध नहींmsgid "Some saved themes aren’t shown because the theme folder exceeds the scan limit."msgstr "कुछ सहेजी गई थीम नहीं दिखाई जा रही हैं क्योंकि थीम फ़ोल्डर स्कैन सीमा से बड़ा है।"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Some skills were deleted with a warning"+msgstr "कुछ स्किलें चेतावनी के साथ हटाई गईं"+#: src/components/FeedbackForm.tsxmsgid "Something broke"msgstr "कुछ टूट गया"@@ -12873,6 +12897,10 @@ msgstr "कुछ टूट गया"msgid "Something else"msgstr "कुछ और"+#: src/lib/skills-api.ts+msgid "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+msgstr "{scopeLabel} में “{name}” नाम की कोई चीज़ पहले से मौजूद है, और सर्वर यह पुष्टि नहीं कर सका कि वह क्या है। हो सकता है पहले का कोई असफल मूव उसे जान-बूझकर वहाँ छोड़ गया हो: मिटाने या बदलने से पहले उसे मूल से मिलाकर देखें।"+#: src/components/AppErrorBoundary.tsxmsgid "Something went wrong"msgstr "कुछ ग़लत हो गया"@@ -13665,6 +13693,10 @@ msgstr "बोर्ड की सामग्री एक मान्य Excamsgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "Claude Desktop App ने फ़ाइल नहीं खोली। क्या वह इंस्टॉल है? ({msg})"+#: src/lib/skills-api.ts+msgid "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+msgstr "{scopeLabel} में रखी गई “{name}” की कॉपी एक ग़ैरज़रूरी नक़ल है: जाँच में मूल अपरिवर्तित मिला। उस कॉपी को हटाएँ, फिर मूव दोबारा आज़माएँ।"+#: src/components/SyncStatusBadge.tsxmsgid "The default branch is protected — pushes need a pull request."msgstr "डिफ़ॉल्ट ब्रांच सुरक्षित है — भेजने के लिए एक पुल रिक्वेस्ट चाहिए।"diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.jsonindex 9fc2ed9d5..cfe475b84 100644--- a/packages/app/src/locales/id/messages.json+++ b/packages/app/src/locales/id/messages.json@@ -715,6 +715,7 @@"851WA-": ["Ini bisa diatur di Pengaturan > Alat AI & CLI"],"87GMKe": ["Ekspos proyek ini ke jaringan?"],"881Uwh": ["Hapus tabel terpilih"],+ "89TmeV": ["Beberapa keterampilan dihapus dengan peringatan"],"89TtiD": ["Berkas baru dari templat \"",["displayTitle"],@@ -1449,6 +1450,7 @@"GbzBEk": ["Server mengembalikan respons skill yang tidak lengkap."],"GceAYf": [["label"], " dipindahkan ke panel baru di sebelah kanan."],"GemPfn": ["Gagal mengurai respons galat tautan keluar (HTTP ", ["status"], ")"],+ "GesfyX": [["shown"], " dan ", ["more"], " lagi"],"Gfr4fu": ["Server tidak bisa membuka dokumen"],"GhjUB_": ["Tersambung kembali"],"Gi8Akx": [@@ -2056,6 +2058,13 @@"OKImo8": ["Berkas yang berkonflik"],"OLBz-_": ["Diagram Mermaid gagal dirender."],"OLIKgw": ["Seret item ", ["0"], " untuk menata ulang"],+ "OMS7Xp": [+ "Sebuah salinan “",+ ["name"],+ "” sengaja disimpan di ",+ ["scopeLabel"],+ ". Jangan hapus salinan itu sebelum dibandingkan dengan aslinya: salinan itu mungkin menyimpan satu-satunya salinan berkas yang sudah dihapus oleh pemindahan yang gagal."+ ],"ONPvOb": ["Memuat aktivitas agen"],"ONUgxB": ["Konflik itu sudah tidak tersedia."],"ONWvwQ": ["Unggah"],@@ -2271,6 +2280,7 @@"RD8cCw": ["Pengelolaan koneksi agen tidak tersedia di build ini."],"RDjuBN": ["Penyiapan"],"RDrXh4": ["Atur pengaturan pengguna, proyek, dan integrasi."],+ "RDzxes": [["moved"], " dari ", ["total"], " keterampilan dipindahkan ke ", ["scopeLabel"]],"REkvLz": ["Port ",["0"],@@ -2309,6 +2319,13 @@"R_U_A4": ["Tambahkan pola berkas atau folder, mis. guides/**/*"],"RaPMZv": ["Pintasan papan ketik yang tersedia di penyunting dan ruang kerja."],"RaUKLu": ["Kontrol jarak jauh"],+ "Raayoq": [+ "Salinan “",+ ["name"],+ "” yang disimpan di ",+ ["scopeLabel"],+ " adalah duplikat yang tidak diperlukan: aslinya sudah diverifikasi tidak berubah. Hapus salinan itu, lalu coba pemindahan lagi."+ ],"Rah7yq": ["Apa yang harus dilakukan AI? (opsional)"],"Rb1zMa": ["Tanpa cuplikan"],"RcrskJ": ["Format terlihat salah"],@@ -3010,6 +3027,13 @@"_G7A92": ["Pertahankan index.md"],"_GRWOJ": ["Ganti penyedia embedding?"],"_HgF9q": ["Urutkan menurut"],+ "_HlScO": [+ "Sebuah salinan mungkin masih ada di ",+ ["scopeLabel"],+ " untuk: ",+ ["names"],+ ". Jangan hapus apa pun di sana sebelum dibandingkan dengan aslinya: salinan itu mungkin menyimpan satu-satunya salinan berkas yang sudah dihapus oleh pemindahan yang gagal."+ ],"_IGfXZ": ["OpenKnowledge berhenti tak terduga terakhir kali."],"_IX_7x": ["Lainnya"],"_IfSZn": ["Tema tersimpan lain sudah menggunakan nama ini."],@@ -3414,6 +3438,13 @@"eFJkVt": ["Kloning gagal: ", ["cloneError"]],"eG8Jsg": ["Alihkan mode fokus Tab di sumber"],"eGUbmF": ["Salin berkas atau folder terpilih"],+ "eGkfGQ": [+ "Salinan yang tidak diperlukan disimpan di ",+ ["scopeLabel"],+ " untuk: ",+ ["names"],+ ". Setiap aslinya sudah diverifikasi tidak berubah, jadi hapus salinan itu lalu coba pemindahan lagi."+ ],"eJitUk": ["Unggah dari komputer"],"eKThTQ": ["Gagal menata ulang"],"eMWRAs": [@@ -5191,6 +5222,13 @@"xSVO3J": ["Apa yang dibuat"],"xV5sXw": [["0"], " mgg lalu"],"xW5AUw": ["Ditarik ", ["pulled"]],+ "xW7KK3": [+ "Sudah ada sesuatu bernama “",+ ["name"],+ "” di ",+ ["scopeLabel"],+ ", dan server tidak dapat memastikan apa itu. Pemindahan yang gagal sebelumnya mungkin sengaja menyimpannya di sana: bandingkan dengan aslinya sebelum dihapus atau diganti."+ ],"xWEvuo": ["Tanya AI"],"xWomUD": ["Pakai versi ", ["editor"]],"xXo8FT": ["Gagal menyimpan: ", ["error"]],diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex 80390f007..bed6ad4bd 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -1020,6 +1020,10 @@ msgstr "Properti {settingsDescriptorLabel}"msgid "{shareBranch} isn't a valid branch name."msgstr "{shareBranch} bukan nama cabang yang valid."+#: src/lib/skills-api.ts+msgid "{shown} and {more} more"+msgstr "{shown} dan {more} lagi"+#: src/components/ReportBugDialogBody.tsxmsgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"msgstr "{sizeText} · rahasia disunting · {fileCount, plural, other {# berkas}}"@@ -1271,6 +1275,14 @@ msgstr "Salinan adalah folder tersendiri, dan OK menjaganya tetap selaras denganmsgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."msgstr "Salinan adalah folder tersendiri, dan OK menjaganya tetap selaras dengan sumbernya: sunting keterampilan di sini dan setiap salinan ikut diperbarui. Itu berhenti begitu Anda menyunting sebuah salinan secara manual di luar OK — sejak saat itu ia berjalan sendiri dan muncul sebagai keterampilan terpisah. Symlink justru merupakan penunjuk ke sumbernya, jadi tidak ada yang bisa melenceng, tetapi sebuah lokasi berhenti bekerja jika sumbernya dihapus."+#: src/lib/skills-api.ts+msgid "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+msgstr "Sebuah salinan mungkin masih ada di {scopeLabel} untuk: {names}. Jangan hapus apa pun di sana sebelum dibandingkan dengan aslinya: salinan itu mungkin menyimpan satu-satunya salinan berkas yang sudah dihapus oleh pemindahan yang gagal."++#: src/lib/skills-api.ts+msgid "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+msgstr "Sebuah salinan “{name}” sengaja disimpan di {scopeLabel}. Jangan hapus salinan itu sebelum dibandingkan dengan aslinya: salinan itu mungkin menyimpan satu-satunya salinan berkas yang sudah dihapus oleh pemindahan yang gagal."+#. placeholder {0}: path ?? label#: src/components/SkillInstallMenu.tsxmsgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."@@ -1359,6 +1371,10 @@ msgstr "Kutipan sorot menonjol dari teks di sekitarnya."msgid "A real shell is off for this project. Turning it on runs commands with the full access of your user account."msgstr "Shell asli dinonaktifkan untuk proyek ini. Mengaktifkannya membuat perintah berjalan dengan akses penuh akun pengguna Anda."+#: src/lib/skills-api.ts+msgid "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+msgstr "Salinan yang tidak diperlukan disimpan di {scopeLabel} untuk: {names}. Setiap aslinya sudah diverifikasi tidak berubah, jadi hapus salinan itu lalu coba pemindahan lagi."+#: src/components/ReportBugDialogBody.tsxmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr "Laporan membantu kami menemukan penyebabnya. Tidak ada yang dikirim sampai Anda meninjaunya."@@ -8503,6 +8519,10 @@ msgstr "{label} dipindahkan ke panel baru di sebelah kiri."msgid "Moved {label} to a new pane on the right."msgstr "{label} dipindahkan ke panel baru di sebelah kanan."+#: src/lib/skills-api.ts+msgid "Moved {moved} of {total} skills to {scopeLabel}"+msgstr "{moved} dari {total} keterampilan dipindahkan ke {scopeLabel}"+#: src/components/SkillsTree.tsxmsgid "Moved {moved} skills to Global"msgstr "{moved} keterampilan dipindahkan ke Global"@@ -12865,6 +12885,10 @@ msgstr "Sebagian file tidak ditampilkan: working tree memiliki terlalu banyak pemsgid "Some saved themes aren’t shown because the theme folder exceeds the scan limit."msgstr "Beberapa tema tersimpan tidak ditampilkan karena folder tema melewati batas pemindaian."+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Some skills were deleted with a warning"+msgstr "Beberapa keterampilan dihapus dengan peringatan"+#: src/components/FeedbackForm.tsxmsgid "Something broke"msgstr "Ada yang rusak"@@ -12873,6 +12897,10 @@ msgstr "Ada yang rusak"msgid "Something else"msgstr "Hal lain"+#: src/lib/skills-api.ts+msgid "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+msgstr "Sudah ada sesuatu bernama “{name}” di {scopeLabel}, dan server tidak dapat memastikan apa itu. Pemindahan yang gagal sebelumnya mungkin sengaja menyimpannya di sana: bandingkan dengan aslinya sebelum dihapus atau diganti."+#: src/components/AppErrorBoundary.tsxmsgid "Something went wrong"msgstr "Ada yang tidak beres"@@ -13665,6 +13693,10 @@ msgstr "Konten papan bukan scene Excalidraw yang valid."msgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "Aplikasi Claude Desktop tidak membuka berkasnya. Apakah ia terpasang? ({msg})"+#: src/lib/skills-api.ts+msgid "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+msgstr "Salinan “{name}” yang disimpan di {scopeLabel} adalah duplikat yang tidak diperlukan: aslinya sudah diverifikasi tidak berubah. Hapus salinan itu, lalu coba pemindahan lagi."+#: src/components/SyncStatusBadge.tsxmsgid "The default branch is protected — pushes need a pull request."msgstr "Cabang bawaannya terlindungi — push memerlukan pull request."diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.jsonindex 1c6911d06..74c5b9cb5 100644--- a/packages/app/src/locales/ko/messages.json+++ b/packages/app/src/locales/ko/messages.json@@ -687,6 +687,7 @@"851WA-": ["Settings > AI tools & CLI에서 설정 가능"],"87GMKe": ["이 프로젝트를 네트워크에 노출할까요?"],"881Uwh": ["선택한 표 삭제"],+ "89TmeV": ["일부 스킬이 경고와 함께 삭제되었습니다"],"89TtiD": ["템플릿 \"",["displayTitle"],@@ -1388,6 +1389,7 @@"GbzBEk": ["서버에서 불완전한 스킬 응답을 반환했습니다."],"GceAYf": [["label"], "을 오른쪽의 새 패널로 이동했습니다."],"GemPfn": ["포워드 링크 오류 응답을 해석하지 못했습니다 (HTTP ", ["status"], ")"],+ "GesfyX": [["shown"], " 및 ", ["more"], "개 더"],"Gfr4fu": ["서버에서 문서를 열 수 없습니다"],"GhjUB_": ["다시 연결됨"],"Gi8Akx": [@@ -1972,6 +1974,13 @@"OKImo8": ["충돌한 파일"],"OLBz-_": ["Mermaid 다이어그램을 렌더링하지 못했습니다."],"OLIKgw": ["항목 ", ["0"], "을 드래그하여 순서 변경"],+ "OMS7Xp": [+ "“",+ ["name"],+ "”의 사본을 ",+ ["scopeLabel"],+ "에 일부러 남겨 두었습니다. 원본과 비교하기 전에는 삭제하지 마세요. 실패한 이동이 이미 지운 파일의 유일한 사본일 수 있습니다."+ ],"ONPvOb": ["에이전트 활동 불러오는 중"],"ONUgxB": ["해당 충돌은 더 이상 사용할 수 없습니다."],"ONWvwQ": ["업로드"],@@ -2172,6 +2181,7 @@"RD8cCw": ["이 빌드에서는 에이전트 연결 관리를 사용할 수 없습니다."],"RDjuBN": ["설정"],"RDrXh4": ["사용자, 프로젝트 및 통합 설정을 구성합니다."],+ "RDzxes": ["스킬 ", ["total"], "개 중 ", ["moved"], "개를 ", ["scopeLabel"], "(으)로 이동함"],"REkvLz": ["포트 ",["0"],@@ -2209,6 +2219,12 @@"R_U_A4": ["파일 또는 폴더 패턴 추가, 예: guides/**/*"],"RaPMZv": ["편집기와 워크스페이스에서 사용할 수 있는 키보드 단축키입니다."],"RaUKLu": ["원격 제어"],+ "Raayoq": [+ ["scopeLabel"],+ "에 남아 있는 “",+ ["name"],+ "” 사본은 불필요한 중복입니다. 원본이 변경되지 않았음을 확인했습니다. 그 사본을 삭제한 뒤 이동을 다시 시도하세요."+ ],"Rah7yq": ["AI 작업 내용? (선택 사항)"],"Rb1zMa": ["발췌문 없음"],"RcrskJ": ["서식이 잘못 표시됨"],@@ -2889,6 +2905,12 @@"_G7A92": ["index.md 유지"],"_GRWOJ": ["임베딩 제공업체를 변경하시겠습니까?"],"_HgF9q": ["정렬 기준"],+ "_HlScO": [+ ["scopeLabel"],+ "에 다음 스킬의 사본이 남아 있을 수 있습니다: ",+ ["names"],+ ". 원본과 비교하기 전에는 그곳의 어떤 것도 삭제하지 마세요. 실패한 이동이 이미 지운 파일의 유일한 사본일 수 있습니다."+ ],"_IGfXZ": ["OpenKnowledge가 지난번에 예기치 않게 종료되었습니다."],"_IX_7x": ["기타"],"_IfSZn": ["이미 이 이름을 사용하는 저장된 테마가 있습니다."],@@ -3272,6 +3294,12 @@"eFJkVt": ["클론 실패: ", ["cloneError"]],"eG8Jsg": ["소스 탭 포커스 모드 전환"],"eGUbmF": ["선택한 파일 또는 폴더 복사"],+ "eGkfGQ": [+ ["scopeLabel"],+ "에 다음 스킬의 불필요한 중복 사본이 남았습니다: ",+ ["names"],+ ". 각 원본이 변경되지 않았음을 확인했으니 그 사본을 삭제한 뒤 이동을 다시 시도하세요."+ ],"eJitUk": ["컴퓨터에서 업로드"],"eKThTQ": ["순서 변경 실패"],"eMWRAs": [@@ -4956,6 +4984,13 @@"xSVO3J": ["생성되는 항목"],"xV5sXw": [["0"], "주 전"],"xW5AUw": [["pulled"], " 풀"],+ "xW7KK3": [+ "“",+ ["name"],+ "”(이)라는 항목이 이미 ",+ ["scopeLabel"],+ "에 있는데, 서버가 그것이 무엇인지 확인하지 못했습니다. 이전에 실패한 이동이 일부러 남겨 둔 것일 수 있습니다. 삭제하거나 교체하기 전에 원본과 비교하세요."+ ],"xWEvuo": ["AI에게 묻기"],"xWomUD": [["editor"], " 버전 사용"],"xXo8FT": ["저장 실패: ", ["error"]],diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex e8664f0de..dcd1ab764 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -1020,6 +1020,10 @@ msgstr "{settingsDescriptorLabel} 속성"msgid "{shareBranch} isn't a valid branch name."msgstr "유효하지 않은 브랜치 이름입니다: {shareBranch}"+#: src/lib/skills-api.ts+msgid "{shown} and {more} more"+msgstr "{shown} 및 {more}개 더"+#: src/components/ReportBugDialogBody.tsxmsgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"msgstr "{sizeText} · 시크릿이 비공개 처리됨 · {fileCount, plural, other {파일 #개}}"@@ -1275,6 +1279,14 @@ msgstr "복사본은 독립된 실제 폴더이며, OK가 소스와 동기화합msgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."msgstr "복사본은 독립된 실제 폴더이며, OK가 소스와 동기화합니다. 여기에서 스킬을 편집하면 모든 복사본이 새로고침됩니다. OK 외부에서 복사본을 직접 편집하는 순간 동기화가 중단됩니다. 그때부터 복사본은 별도 경로로 작동하며 별도 스킬로 표시됩니다. 심볼릭 링크는 대신 소스를 가리키므로 내용이 달라질 수 없지만, 소스를 삭제하면 해당 위치가 작동하지 않습니다."+#: src/lib/skills-api.ts+msgid "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+msgstr "{scopeLabel}에 다음 스킬의 사본이 남아 있을 수 있습니다: {names}. 원본과 비교하기 전에는 그곳의 어떤 것도 삭제하지 마세요. 실패한 이동이 이미 지운 파일의 유일한 사본일 수 있습니다."++#: src/lib/skills-api.ts+msgid "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+msgstr "“{name}”의 사본을 {scopeLabel}에 일부러 남겨 두었습니다. 원본과 비교하기 전에는 삭제하지 마세요. 실패한 이동이 이미 지운 파일의 유일한 사본일 수 있습니다."+#. placeholder {0}: path ?? label#: src/components/SkillInstallMenu.tsxmsgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."@@ -1363,6 +1375,10 @@ msgstr "인용문이 주변 텍스트에서 돋보입니다."msgid "A real shell is off for this project. Turning it on runs commands with the full access of your user account."msgstr "이 프로젝트에서 실제 셸이 꺼져 있습니다. 켜면 사용자 계정의 전체 권한으로 명령을 실행합니다."+#: src/lib/skills-api.ts+msgid "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+msgstr "{scopeLabel}에 다음 스킬의 불필요한 중복 사본이 남았습니다: {names}. 각 원본이 변경되지 않았음을 확인했으니 그 사본을 삭제한 뒤 이동을 다시 시도하세요."+#: src/components/ReportBugDialogBody.tsxmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr "보고서는 원인을 찾는 데 도움이 됩니다. 검토할 때까지 아무것도 전송되지 않습니다."@@ -8507,6 +8523,10 @@ msgstr "{label}을 왼쪽의 새 패널로 이동했습니다."msgid "Moved {label} to a new pane on the right."msgstr "{label}을 오른쪽의 새 패널로 이동했습니다."+#: src/lib/skills-api.ts+msgid "Moved {moved} of {total} skills to {scopeLabel}"+msgstr "스킬 {total}개 중 {moved}개를 {scopeLabel}(으)로 이동함"+#: src/components/SkillsTree.tsxmsgid "Moved {moved} skills to Global"msgstr "스킬 {moved}개를 전역으로 이동함"@@ -12869,6 +12889,10 @@ msgstr "일부 파일이 표시되지 않았습니다. 작업 트리의 변경msgid "Some saved themes aren’t shown because the theme folder exceeds the scan limit."msgstr "테마 폴더가 스캔 한도를 초과해 일부 저장된 테마가 나타나지 않습니다."+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Some skills were deleted with a warning"+msgstr "일부 스킬이 경고와 함께 삭제되었습니다"+#: src/components/FeedbackForm.tsxmsgid "Something broke"msgstr "문제가 발생했습니다"@@ -12877,6 +12901,10 @@ msgstr "문제가 발생했습니다"msgid "Something else"msgstr "기타"+#: src/lib/skills-api.ts+msgid "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+msgstr "“{name}”(이)라는 항목이 이미 {scopeLabel}에 있는데, 서버가 그것이 무엇인지 확인하지 못했습니다. 이전에 실패한 이동이 일부러 남겨 둔 것일 수 있습니다. 삭제하거나 교체하기 전에 원본과 비교하세요."+#: src/components/AppErrorBoundary.tsxmsgid "Something went wrong"msgstr "문제가 발생했습니다"@@ -13669,6 +13697,10 @@ msgstr "보드의 내용이 유효한 Excalidraw 장면이 아닙니다."msgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "Claude Desktop App 파일 열기 실패. 설치 상태 확인: ({msg})"+#: src/lib/skills-api.ts+msgid "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+msgstr "{scopeLabel}에 남아 있는 “{name}” 사본은 불필요한 중복입니다. 원본이 변경되지 않았음을 확인했습니다. 그 사본을 삭제한 뒤 이동을 다시 시도하세요."+#: src/components/SyncStatusBadge.tsxmsgid "The default branch is protected — pushes need a pull request."msgstr "기본 브랜치가 보호되어 푸시하려면 풀 리퀘스트가 필요합니다."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex d1dea66a9..740224ca8 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -700,6 +700,7 @@"851WA-": ["Ţĥĩś ćàń ƀē ćōńƒĩĝũŕēď ĩń Śēţţĩńĝś > ÀĨ ţōōĺś & ĆĹĨ"],"87GMKe": ["Ēxƥōśē ţĥĩś ƥŕōĴēćţ ţō ţĥē ńēţŵōŕķ?"],"881Uwh": ["Ďēĺēţē śēĺēćţēď ţàƀĺē"],+ "89TmeV": ["Śōḿē śķĩĺĺś ŵēŕē ďēĺēţēď ŵĩţĥ à ŵàŕńĩńĝ"],"89TtiD": ["Ńēŵ ƒĩĺē ƒŕōḿ ţēḿƥĺàţē \"",["displayTitle"],@@ -1436,6 +1437,7 @@"GbzBEk": ["Śēŕvēŕ ŕēţũŕńēď àń ĩńćōḿƥĺēţē śķĩĺĺś ŕēśƥōńśē."],"GceAYf": ["Ḿōvēď ", ["label"], " ţō à ńēŵ ƥàńē ōń ţĥē ŕĩĝĥţ."],"GemPfn": ["Ƒàĩĺēď ţō ƥàŕśē ƒōŕŵàŕď-ĺĩńķś ēŕŕōŕ ŕēśƥōńśē (ĤŢŢƤ ", ["status"], ")"],+ "GesfyX": [["shown"], " àńď ", ["more"], " ḿōŕē"],"Gfr4fu": ["Śēŕvēŕ ćàń'ţ ōƥēń ďōćũḿēńţś"],"GhjUB_": ["Ŕēćōńńēćţēď"],"Gi8Akx": [@@ -2041,6 +2043,13 @@"OKImo8": ["Ćōńƒĺĩćţēď ƒĩĺēś"],"OLBz-_": ["Ḿēŕḿàĩď ďĩàĝŕàḿ ƒàĩĺēď ţō ŕēńďēŕ."],"OLIKgw": ["Ďŕàĝ ĩţēḿ ", ["0"], " ţō ŕēōŕďēŕ"],+ "OMS7Xp": [+ "À ćōƥŷ ōƒ \"",+ ["name"],+ "\" ŵàś ķēƥţ ĩń ",+ ["scopeLabel"],+ " ōń ƥũŕƥōśē. Ďōń'ţ ďēĺēţē ĩţ ƀēƒōŕē ćōḿƥàŕĩńĝ ĩţ ŵĩţĥ ţĥē ōŕĩĝĩńàĺ: ĩţ ḿàŷ ĥōĺď ţĥē ōńĺŷ ćōƥŷ ōƒ ƒĩĺēś ţĥē ƒàĩĺēď ḿōvē àĺŕēàďŷ ŕēḿōvēď."+ ],"ONPvOb": ["Ĺōàďĩńĝ àĝēńţ àćţĩvĩţŷ"],"ONUgxB": ["Ţĥàţ ćōńƒĺĩćţ ĩś ńō ĺōńĝēŕ àvàĩĺàƀĺē."],"ONWvwQ": ["Ũƥĺōàď"],@@ -2262,6 +2271,7 @@"RD8cCw": ["Ḿàńàĝĩńĝ àĝēńţ ćōńńēćţĩōńś ĩś ũńàvàĩĺàƀĺē ĩń ţĥĩś ƀũĩĺď."],"RDjuBN": ["Śēţũƥ"],"RDrXh4": ["Ćōńƒĩĝũŕē ũśēŕ, ƥŕōĴēćţ, àńď ĩńţēĝŕàţĩōń śēţţĩńĝś."],+ "RDzxes": ["Ḿōvēď ", ["moved"], " ōƒ ", ["total"], " śķĩĺĺś ţō ", ["scopeLabel"]],"REkvLz": ["Ƥōŕţ ",["0"],@@ -2300,6 +2310,13 @@"R_U_A4": ["Àďď ƒĩĺē ōŕ ƒōĺďēŕ ƥàţţēŕń, ē.ĝ. ĝũĩďēś/**/*"],"RaPMZv": ["Ķēŷƀōàŕď śĥōŕţćũţś àvàĩĺàƀĺē ĩń ţĥē ēďĩţōŕ àńď ŵōŕķśƥàćē."],"RaUKLu": ["Ŕēḿōţē ćōńţŕōĺ"],+ "Raayoq": [+ "Ţĥē ćōƥŷ ōƒ \"",+ ["name"],+ "\" ķēƥţ ĩń ",+ ["scopeLabel"],+ " ĩś à ŕēďũńďàńţ ďũƥĺĩćàţē: ţĥē ōŕĩĝĩńàĺ ŵàś vēŕĩƒĩēď ũńćĥàńĝēď. Ŕēḿōvē ţĥàţ ćōƥŷ, ţĥēń ŕēţŕŷ ţĥē ḿōvē."+ ],"Rah7yq": ["Ŵĥàţ śĥōũĺď ţĥē ÀĨ ďō? (ōƥţĩōńàĺ)"],"Rb1zMa": ["Ńō ēxćēŕƥţ"],"RcrskJ": ["Ƒōŕḿàţţĩńĝ ĺōōķēď ŵŕōńĝ"],@@ -2994,6 +3011,13 @@"_G7A92": ["Ḿàĩńţàĩń ĩńďēx.ḿď"],"_GRWOJ": ["Ćĥàńĝē ţĥē ēḿƀēďďĩńĝś ƥŕōvĩďēŕ?"],"_HgF9q": ["Śōŕţ ƀŷ"],+ "_HlScO": [+ "À ćōƥŷ ḿàŷ ŕēḿàĩń ĩń ",+ ["scopeLabel"],+ " ƒōŕ: ",+ ["names"],+ ". Ďōń'ţ ďēĺēţē àńŷţĥĩńĝ ţĥēŕē ƀēƒōŕē ćōḿƥàŕĩńĝ ĩţ ŵĩţĥ ţĥē ōŕĩĝĩńàĺ: ĩţ ḿàŷ ĥōĺď ţĥē ōńĺŷ ćōƥŷ ōƒ ƒĩĺēś à ƒàĩĺēď ḿōvē àĺŕēàďŷ ŕēḿōvēď."+ ],"_IGfXZ": ["ŌƥēńĶńōŵĺēďĝē ǫũĩţ ũńēxƥēćţēďĺŷ ĺàśţ ţĩḿē."],"_IX_7x": ["Ōţĥēŕ"],"_IfSZn": ["À śàvēď ţĥēḿē àĺŕēàďŷ ũśēś ţĥĩś ńàḿē."],@@ -3404,6 +3428,13 @@"eFJkVt": ["Ćĺōńē ƒàĩĺēď: ", ["cloneError"]],"eG8Jsg": ["Ţōĝĝĺē śōũŕćē ţàƀ ƒōćũś ḿōďē"],"eGUbmF": ["Ćōƥŷ śēĺēćţēď ƒĩĺē ōŕ ƒōĺďēŕ"],+ "eGkfGQ": [+ "À ŕēďũńďàńţ ćōƥŷ ŵàś ķēƥţ ĩń ",+ ["scopeLabel"],+ " ƒōŕ: ",+ ["names"],+ ". Ēàćĥ ōŕĩĝĩńàĺ ŵàś vēŕĩƒĩēď ũńćĥàńĝēď, śō ŕēḿōvē ţĥōśē ćōƥĩēś àńď ŕēţŕŷ ţĥē ḿōvē."+ ],"eJitUk": ["Ũƥĺōàď ƒŕōḿ ćōḿƥũţēŕ"],"eKThTQ": ["Ƒàĩĺēď ţō ŕēōŕďēŕ"],"eMWRAs": ["Ƥàĝēś ĩńďēxēď: ", ["semanticIndexedCount"], " ōƒ ", ["semanticTotalCount"], "."],@@ -5185,6 +5216,13 @@"xSVO3J": ["Ŵĥàţ ĝēţś ćŕēàţēď"],"xV5sXw": [["0"], "ŵ àĝō"],"xW5AUw": ["Ƥũĺĺēď ", ["pulled"]],+ "xW7KK3": [+ "Śōḿēţĥĩńĝ ńàḿēď \"",+ ["name"],+ "\" ĩś àĺŕēàďŷ ĩń ",+ ["scopeLabel"],+ ", àńď ţĥē śēŕvēŕ ćōũĺďń'ţ ćōńƒĩŕḿ ŵĥàţ ĩţ ĩś. Àń ēàŕĺĩēŕ ƒàĩĺēď ḿōvē ḿàŷ ĥàvē ķēƥţ ĩţ ţĥēŕē ōń ƥũŕƥōśē: ćōḿƥàŕē ĩţ ŵĩţĥ ţĥē ōŕĩĝĩńàĺ ƀēƒōŕē ŷōũ ďēĺēţē ōŕ ŕēƥĺàćē ĩţ."+ ],"xWEvuo": ["Àśķ ÀĨ"],"xWomUD": ["Ũśē ", ["editor"], " vēŕśĩōń"],"xXo8FT": ["Śàvē ƒàĩĺēď: ", ["error"]],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 2eb3e191a..127b269ff 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -1020,6 +1020,10 @@ msgstr ""msgid "{shareBranch} isn't a valid branch name."msgstr ""+#: src/lib/skills-api.ts+msgid "{shown} and {more} more"+msgstr ""+#: src/components/ReportBugDialogBody.tsxmsgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"msgstr ""@@ -1271,6 +1275,14 @@ msgstr ""msgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."msgstr ""+#: src/lib/skills-api.ts+msgid "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+msgstr ""++#: src/lib/skills-api.ts+msgid "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+msgstr ""+#. placeholder {0}: path ?? label#: src/components/SkillInstallMenu.tsxmsgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."@@ -1359,6 +1371,10 @@ msgstr ""msgid "A real shell is off for this project. Turning it on runs commands with the full access of your user account."msgstr ""+#: src/lib/skills-api.ts+msgid "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+msgstr ""+#: src/components/ReportBugDialogBody.tsxmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr ""@@ -8503,6 +8519,10 @@ msgstr ""msgid "Moved {label} to a new pane on the right."msgstr ""+#: src/lib/skills-api.ts+msgid "Moved {moved} of {total} skills to {scopeLabel}"+msgstr ""+#: src/components/SkillsTree.tsxmsgid "Moved {moved} skills to Global"msgstr ""@@ -12865,6 +12885,10 @@ msgstr ""msgid "Some saved themes aren’t shown because the theme folder exceeds the scan limit."msgstr ""+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Some skills were deleted with a warning"+msgstr ""+#: src/components/FeedbackForm.tsxmsgid "Something broke"msgstr ""@@ -12873,6 +12897,10 @@ msgstr ""msgid "Something else"msgstr ""+#: src/lib/skills-api.ts+msgid "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+msgstr ""+#: src/components/AppErrorBoundary.tsxmsgid "Something went wrong"msgstr ""@@ -13665,6 +13693,10 @@ msgstr ""msgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr ""+#: src/lib/skills-api.ts+msgid "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+msgstr ""+#: src/components/SyncStatusBadge.tsxmsgid "The default branch is protected — pushes need a pull request."msgstr ""diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.jsonindex a8f4b8f01..441e61c0f 100644--- a/packages/app/src/locales/pt-BR/messages.json+++ b/packages/app/src/locales/pt-BR/messages.json@@ -832,6 +832,7 @@"851WA-": ["Isto pode ser configurado em Configurações > Ferramentas de IA e CLI"],"87GMKe": ["Expor este projeto à rede?"],"881Uwh": ["Excluir a tabela selecionada"],+ "89TmeV": ["Algumas habilidades foram excluídas com um aviso"],"89TtiD": ["Novo arquivo a partir do modelo \"",["displayTitle"],@@ -1663,6 +1664,7 @@["status"],")"],+ "GesfyX": [["shown"], " e mais ", ["more"]],"Gfr4fu": ["O servidor não consegue abrir documentos"],"GhjUB_": ["Reconectado"],"Gi8Akx": [@@ -2343,6 +2345,13 @@"OKImo8": ["Arquivos em conflito"],"OLBz-_": ["Falha ao renderizar o diagrama do Mermaid."],"OLIKgw": ["Arraste o item ", ["0"], " para reordenar"],+ "OMS7Xp": [+ "Uma cópia de “",+ ["name"],+ "” foi mantida em ",+ ["scopeLabel"],+ " de propósito. Não apague essa cópia antes de comparar com o original: ela pode ter a única cópia dos arquivos que a movimentação com falha já removeu."+ ],"ONPvOb": ["Carregando a atividade do agente"],"ONUgxB": ["Esse conflito não está mais disponível."],"ONWvwQ": ["Enviar"],@@ -2580,6 +2589,7 @@"RD8cCw": ["O gerenciamento de conexões de agentes não está disponível nesta versão."],"RDjuBN": ["Configuração"],"RDrXh4": ["Configure as opções de usuário, de projeto e de integrações."],+ "RDzxes": [["moved"], " de ", ["total"], " habilidades movidas para ", ["scopeLabel"]],"REkvLz": ["A porta ",["0"],@@ -2618,6 +2628,13 @@"R_U_A4": ["Adicione um padrão de arquivo ou pasta, ex.: guides/**/*"],"RaPMZv": ["Atalhos de teclado disponíveis no editor e no espaço de trabalho."],"RaUKLu": ["Controle remoto"],+ "Raayoq": [+ "A cópia de “",+ ["name"],+ "” mantida em ",+ ["scopeLabel"],+ " é uma duplicata redundante: o original foi verificado e está inalterado. Remova essa cópia e tente a movimentação de novo."+ ],"Rah7yq": ["O que a IA deve fazer? (opcional)"],"Rb1zMa": ["Sem trecho"],"RcrskJ": ["A formatação parecia errada"],@@ -3419,6 +3436,13 @@"_G7A92": ["Manter index.md"],"_GRWOJ": ["Trocar o provedor de embeddings?"],"_HgF9q": ["Ordenar por"],+ "_HlScO": [+ "Pode ter ficado uma cópia em ",+ ["scopeLabel"],+ " de: ",+ ["names"],+ ". Não apague nada de lá antes de comparar com o original: pode ter a única cópia dos arquivos que uma movimentação com falha já removeu."+ ],"_IGfXZ": ["Da última vez o OpenKnowledge fechou de forma inesperada."],"_IX_7x": ["Outro"],"_IfSZn": ["Um tema salvo já usa este nome."],@@ -3891,6 +3915,13 @@"eFJkVt": ["Falha ao clonar: ", ["cloneError"]],"eG8Jsg": ["Ativar ou desativar o modo de foco do Tab no código"],"eGUbmF": ["Copiar o arquivo ou a pasta selecionados"],+ "eGkfGQ": [+ "Uma cópia redundante foi mantida em ",+ ["scopeLabel"],+ " de: ",+ ["names"],+ ". Cada original foi verificado e está inalterado, então remova essas cópias e tente a movimentação de novo."+ ],"eJitUk": ["Enviar do computador"],"eKThTQ": ["Falha ao reordenar"],"eMWRAs": [@@ -5875,6 +5906,13 @@"xSVO3J": ["O que é criado"],"xV5sXw": ["há ", ["0"], " sem"],"xW5AUw": ["Baixado ", ["pulled"]],+ "xW7KK3": [+ "Já existe algo chamado “",+ ["name"],+ "” em ",+ ["scopeLabel"],+ ", e o servidor não conseguiu confirmar o que é. Uma movimentação com falha anterior pode tê-lo mantido ali de propósito: compare com o original antes de apagar ou substituir."+ ],"xWEvuo": ["Perguntar à IA"],"xWomUD": ["Usar a versão do ", ["editor"]],"xXo8FT": ["Falha ao salvar: ", ["error"]],diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex 9bdb221d2..07cdd825c 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -1020,6 +1020,10 @@ msgstr "Propriedades de {settingsDescriptorLabel}"msgid "{shareBranch} isn't a valid branch name."msgstr "{shareBranch} não é um nome de ramo válido."+#: src/lib/skills-api.ts+msgid "{shown} and {more} more"+msgstr "{shown} e mais {more}"+#: src/components/ReportBugDialogBody.tsxmsgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"msgstr "{sizeText} · segredos ocultados · {fileCount, plural, one {# arquivo} many {# arquivos} other {# arquivos}}"@@ -1271,6 +1275,14 @@ msgstr "Uma cópia é uma pasta de verdade, e o OK a mantém em sintonia com a fmsgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."msgstr "Uma cópia é uma pasta de verdade, e o OK a mantém em sintonia com a fonte: edite a habilidade aqui e todas as cópias são atualizadas. Isso para no momento em que você edita uma cópia à mão fora do OK — a partir daí ela segue seu próprio caminho e aparece como uma habilidade separada. Já um link simbólico aponta para a fonte, então nada se desvia, mas um local para de funcionar se a fonte for excluída."+#: src/lib/skills-api.ts+msgid "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+msgstr "Pode ter ficado uma cópia em {scopeLabel} de: {names}. Não apague nada de lá antes de comparar com o original: pode ter a única cópia dos arquivos que uma movimentação com falha já removeu."++#: src/lib/skills-api.ts+msgid "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+msgstr "Uma cópia de “{name}” foi mantida em {scopeLabel} de propósito. Não apague essa cópia antes de comparar com o original: ela pode ter a única cópia dos arquivos que a movimentação com falha já removeu."+#. placeholder {0}: path ?? label#: src/components/SkillInstallMenu.tsxmsgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."@@ -1359,6 +1371,10 @@ msgstr "Uma citação em destaque se sobressai do texto ao redor."msgid "A real shell is off for this project. Turning it on runs commands with the full access of your user account."msgstr "O shell real está desativado para este projeto. Ativá-lo faz os comandos rodarem com todo o acesso da sua conta de usuário."+#: src/lib/skills-api.ts+msgid "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+msgstr "Uma cópia redundante foi mantida em {scopeLabel} de: {names}. Cada original foi verificado e está inalterado, então remova essas cópias e tente a movimentação de novo."+#: src/components/ReportBugDialogBody.tsxmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr "Um relatório nos ajuda a achar a causa. Nada é enviado até você revisar."@@ -8503,6 +8519,10 @@ msgstr "{label} movido para um novo painel à esquerda."msgid "Moved {label} to a new pane on the right."msgstr "{label} movido para um novo painel à direita."+#: src/lib/skills-api.ts+msgid "Moved {moved} of {total} skills to {scopeLabel}"+msgstr "{moved} de {total} habilidades movidas para {scopeLabel}"+#: src/components/SkillsTree.tsxmsgid "Moved {moved} skills to Global"msgstr "{moved} habilidades movidas para Global"@@ -12865,6 +12885,10 @@ msgstr "Alguns arquivos não estão listados: a árvore de trabalho tem alteraçmsgid "Some saved themes aren’t shown because the theme folder exceeds the scan limit."msgstr "Alguns temas salvos não são exibidos porque a pasta de temas excede o limite de verificação."+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Some skills were deleted with a warning"+msgstr "Algumas habilidades foram excluídas com um aviso"+#: src/components/FeedbackForm.tsxmsgid "Something broke"msgstr "Algo quebrou"@@ -12873,6 +12897,10 @@ msgstr "Algo quebrou"msgid "Something else"msgstr "Outra coisa"+#: src/lib/skills-api.ts+msgid "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+msgstr "Já existe algo chamado “{name}” em {scopeLabel}, e o servidor não conseguiu confirmar o que é. Uma movimentação com falha anterior pode tê-lo mantido ali de propósito: compare com o original antes de apagar ou substituir."+#: src/components/AppErrorBoundary.tsxmsgid "Something went wrong"msgstr "Algo deu errado"@@ -13665,6 +13693,10 @@ msgstr "O conteúdo do quadro não é uma cena válida do Excalidraw."msgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "O app Claude Desktop não abriu o arquivo. Ele está instalado? ({msg})"+#: src/lib/skills-api.ts+msgid "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+msgstr "A cópia de “{name}” mantida em {scopeLabel} é uma duplicata redundante: o original foi verificado e está inalterado. Remova essa cópia e tente a movimentação de novo."+#: src/components/SyncStatusBadge.tsxmsgid "The default branch is protected — pushes need a pull request."msgstr "O ramo padrão é protegido — os envios exigem um pull request."diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.jsonindex 852512de5..729b526c6 100644--- a/packages/app/src/locales/ur/messages.json+++ b/packages/app/src/locales/ur/messages.json@@ -718,6 +718,7 @@"851WA-": ["یہ ترتیبات > AI ٹولز اور CLI میں مقرر کیا جا سکتا ہے"],"87GMKe": ["کیا اس پروجیکٹ کو نیٹ ورک پر ایکسپوز کیا جائے؟"],"881Uwh": ["منتخب ٹیبل حذف کریں"],+ "89TmeV": ["کچھ مہارتیں انتباہ کے ساتھ حذف ہوئیں"],"89TtiD": ["پروجیکٹ کی جڑ میں ٹیمپلیٹ «",["displayTitle"],@@ -1460,6 +1461,7 @@"GbzBEk": ["سرور نے نامکمل اسکلز جواب لوٹایا۔"],"GceAYf": [["label"], " کو دائیں جانب کے نئے پین میں منتقل کر دیا گیا۔"],"GemPfn": ["باہر جانے والے لنکس کی خرابی کا جواب پارس نہیں ہو سکا (HTTP ", ["status"], ")"],+ "GesfyX": [["shown"], " اور ", ["more"], " مزید"],"Gfr4fu": ["سرور دستاویزات نہیں کھول سکتا"],"GhjUB_": ["دوبارہ منسلک ہو گیا"],"Gi8Akx": [@@ -2082,6 +2084,13 @@"OKImo8": ["متضاد فائلیں"],"OLBz-_": ["Mermaid خاکہ رینڈر نہیں ہو سکا۔"],"OLIKgw": ["ترتیب بدلنے کے لیے آئٹم ", ["0"], " کھینچیں"],+ "OMS7Xp": [+ "“",+ ["name"],+ "” کی ایک کاپی ",+ ["scopeLabel"],+ " میں جان بوجھ کر رکھی گئی ہے۔ اسے حذف کرنے سے پہلے اصل سے موازنہ کریں: اس میں اُن فائلوں کی واحد کاپی ہو سکتی ہے جو ناکام منتقلی پہلے ہی حذف کر چکی ہے۔"+ ],"ONPvOb": ["ایجنٹ کی سرگرمی لوڈ ہو رہی ہے"],"ONUgxB": ["وہ کنفلکٹ اب دستیاب نہیں ہے۔"],"ONWvwQ": ["اپ لوڈ کریں"],@@ -2307,6 +2316,7 @@"RD8cCw": ["اس بلڈ میں ایجنٹ کنکشنز کا انتظام دستیاب نہیں ہے۔"],"RDjuBN": ["سیٹ اپ"],"RDrXh4": ["صارف، پروجیکٹ اور انضمام کی ترتیبات مقرر کریں۔"],+ "RDzxes": [["total"], " میں سے ", ["moved"], " مہارتیں ", ["scopeLabel"], " میں منتقل ہو گئیں"],"REkvLz": ["پورٹ ",["0"],@@ -2344,6 +2354,12 @@"R_U_A4": ["فائل یا فولڈر کا پیٹرن شامل کریں، مثلاً guides/**/*"],"RaPMZv": ["ایڈیٹر اور ورک اسپیس میں دستیاب کی بورڈ شارٹ کٹس۔"],"RaUKLu": ["ریموٹ کنٹرول"],+ "Raayoq": [+ ["scopeLabel"],+ " میں رکھی گئی “",+ ["name"],+ "” کی کاپی ایک غیر ضروری نقل ہے: جانچ میں اصل غیر تبدیل شدہ پایا گیا۔ وہ کاپی حذف کریں، پھر منتقلی دوبارہ آزمائیں۔"+ ],"Rah7yq": ["AI کو کیا کرنا چاہیے؟ (اختیاری)"],"Rb1zMa": ["کوئی اقتباس نہیں"],"RcrskJ": ["فارمیٹنگ غلط لگی"],@@ -3059,6 +3075,12 @@"_G7A92": ["برقرار رکھیں index.md"],"_GRWOJ": ["ایمبیڈنگز فراہم کنندہ بدلیں؟"],"_HgF9q": ["ترتیب کا معیار"],+ "_HlScO": [+ ["scopeLabel"],+ " میں اِن کی ایک کاپی باقی رہ سکتی ہے: ",+ ["names"],+ "۔ وہاں کچھ بھی حذف کرنے سے پہلے اصل سے موازنہ کریں: اس میں اُن فائلوں کی واحد کاپی ہو سکتی ہے جو کسی ناکام منتقلی نے پہلے ہی حذف کر دی ہیں۔"+ ],"_IGfXZ": ["پچھلی بار OpenKnowledge غیر متوقع طور پر بند ہو گیا تھا۔"],"_IX_7x": ["دیگر"],"_IfSZn": ["اس نام کی ایک محفوظ شدہ تھیم پہلے سے موجود ہے۔"],@@ -3481,6 +3503,12 @@"eFJkVt": ["کلون ناکام: ", ["cloneError"]],"eG8Jsg": ["سورس ٹیب فوکس موڈ بدلیں"],"eGUbmF": ["منتخب فائل یا فولڈر نقل کریں"],+ "eGkfGQ": [+ ["scopeLabel"],+ " میں اِن کی ایک غیر ضروری کاپی رکھی گئی ہے: ",+ ["names"],+ "۔ جانچ میں ہر اصل غیر تبدیل شدہ پایا گیا، اس لیے وہ کاپیاں حذف کریں اور منتقلی دوبارہ آزمائیں۔"+ ],"eJitUk": ["کمپیوٹر سے اپ لوڈ کریں"],"eKThTQ": ["ترتیب نہیں بدلی جا سکی"],"eMWRAs": [@@ -5270,6 +5298,12 @@"xSVO3J": ["کیا بنتا ہے"],"xV5sXw": [["0"], " ہفتے پہلے"],"xW5AUw": [["pulled"], " کھینچا گیا"],+ "xW7KK3": [+ ["scopeLabel"],+ " میں “",+ ["name"],+ "” نام کی کوئی چیز پہلے سے موجود ہے، اور سرور یہ تصدیق نہیں کر سکا کہ وہ کیا ہے۔ ممکن ہے پہلے کی کوئی ناکام منتقلی اسے جان بوجھ کر وہاں چھوڑ گئی ہو: حذف کرنے یا بدلنے سے پہلے اسے اصل سے موازنہ کریں۔"+ ],"xWEvuo": ["AI سے پوچھیں"],"xWomUD": [["editor"], " والا ورژن استعمال کریں"],"xXo8FT": ["محفوظ کرنا ناکام: ", ["error"]],diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex 15c271b42..a18f7e2e5 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -1020,6 +1020,10 @@ msgstr "{settingsDescriptorLabel} کی خصوصیات"msgid "{shareBranch} isn't a valid branch name."msgstr "{shareBranch} برانچ کا درست نام نہیں ہے۔"+#: src/lib/skills-api.ts+msgid "{shown} and {more} more"+msgstr "{shown} اور {more} مزید"+#: src/components/ReportBugDialogBody.tsxmsgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"msgstr "{sizeText} · رازداری کی معلومات چھپا دی گئیں · {fileCount, plural, one {# فائل} other {# فائلیں}}"@@ -1275,6 +1279,14 @@ msgstr "نقل اپنا الگ حقیقی فولڈر ہوتی ہے، اور OKmsgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."msgstr "نقل اپنا الگ حقیقی فولڈر ہوتی ہے، اور OK اسے ماخذ کے ساتھ ہم آہنگ رکھتا ہے: یہاں مہارت میں ترمیم کریں اور ہر نقل تازہ ہو جاتی ہے۔ یہ اسی لمحے رک جاتا ہے جب آپ OK سے باہر کسی نقل میں ہاتھ سے ترمیم کر دیں — اس کے بعد وہ اپنی راہ چلتی ہے اور الگ مہارت کے طور پر ظاہر ہوتی ہے۔ سِم لنک اس کے بجائے ماخذ کی طرف اشارہ ہوتا ہے، اس لیے کچھ بھی الگ نہیں ہو سکتا، مگر اگر ماخذ حذف ہو جائے تو وہ مقام کام کرنا بند کر دیتا ہے۔"+#: src/lib/skills-api.ts+msgid "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+msgstr "{scopeLabel} میں اِن کی ایک کاپی باقی رہ سکتی ہے: {names}۔ وہاں کچھ بھی حذف کرنے سے پہلے اصل سے موازنہ کریں: اس میں اُن فائلوں کی واحد کاپی ہو سکتی ہے جو کسی ناکام منتقلی نے پہلے ہی حذف کر دی ہیں۔"++#: src/lib/skills-api.ts+msgid "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+msgstr "“{name}” کی ایک کاپی {scopeLabel} میں جان بوجھ کر رکھی گئی ہے۔ اسے حذف کرنے سے پہلے اصل سے موازنہ کریں: اس میں اُن فائلوں کی واحد کاپی ہو سکتی ہے جو ناکام منتقلی پہلے ہی حذف کر چکی ہے۔"+#. placeholder {0}: path ?? label#: src/components/SkillInstallMenu.tsxmsgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."@@ -1363,6 +1375,10 @@ msgstr "نمایاں اقتباس ارد گرد کے متن سے الگ نظرmsgid "A real shell is off for this project. Turning it on runs commands with the full access of your user account."msgstr "اس پروجیکٹ کے لیے اصل شیل بند ہے۔ اسے آن کرنے پر کمانڈز آپ کے صارف اکاؤنٹ کی مکمل رسائی کے ساتھ چلتی ہیں۔"+#: src/lib/skills-api.ts+msgid "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+msgstr "{scopeLabel} میں اِن کی ایک غیر ضروری کاپی رکھی گئی ہے: {names}۔ جانچ میں ہر اصل غیر تبدیل شدہ پایا گیا، اس لیے وہ کاپیاں حذف کریں اور منتقلی دوبارہ آزمائیں۔"+#: src/components/ReportBugDialogBody.tsxmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr "رپورٹ ہمیں وجہ جاننے میں مدد دیتی ہے۔ آپ کے جائزے سے پہلے کچھ نہیں بھیجا جاتا۔"@@ -8507,6 +8523,10 @@ msgstr "{label} کو بائیں جانب کے نئے پین میں منتقل کmsgid "Moved {label} to a new pane on the right."msgstr "{label} کو دائیں جانب کے نئے پین میں منتقل کر دیا گیا۔"+#: src/lib/skills-api.ts+msgid "Moved {moved} of {total} skills to {scopeLabel}"+msgstr "{total} میں سے {moved} مہارتیں {scopeLabel} میں منتقل ہو گئیں"+#: src/components/SkillsTree.tsxmsgid "Moved {moved} skills to Global"msgstr "{moved} مہارتیں گلوبل میں منتقل ہو گئیں"@@ -12869,6 +12889,10 @@ msgstr "کچھ فائلیں فہرست میں نہیں ہیں: ورکنگ ٹریmsgid "Some saved themes aren’t shown because the theme folder exceeds the scan limit."msgstr "تھیم فولڈر اسکین کی حد سے بڑا ہونے کی وجہ سے کچھ محفوظ شدہ تھیمز نہیں دکھائی جا رہیں۔"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Some skills were deleted with a warning"+msgstr "کچھ مہارتیں انتباہ کے ساتھ حذف ہوئیں"+#: src/components/FeedbackForm.tsxmsgid "Something broke"msgstr "کچھ ٹوٹ گیا"@@ -12877,6 +12901,10 @@ msgstr "کچھ ٹوٹ گیا"msgid "Something else"msgstr "کچھ اور"+#: src/lib/skills-api.ts+msgid "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+msgstr "{scopeLabel} میں “{name}” نام کی کوئی چیز پہلے سے موجود ہے، اور سرور یہ تصدیق نہیں کر سکا کہ وہ کیا ہے۔ ممکن ہے پہلے کی کوئی ناکام منتقلی اسے جان بوجھ کر وہاں چھوڑ گئی ہو: حذف کرنے یا بدلنے سے پہلے اسے اصل سے موازنہ کریں۔"+#: src/components/AppErrorBoundary.tsxmsgid "Something went wrong"msgstr "کچھ غلط ہو گیا"@@ -13669,6 +13697,10 @@ msgstr "بورڈ کا مواد کوئی درست Excalidraw منظر نہیں ہmsgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "Claude Desktop App نے فائل نہیں کھولی۔ کیا یہ نصب ہے؟ ({msg})"+#: src/lib/skills-api.ts+msgid "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+msgstr "{scopeLabel} میں رکھی گئی “{name}” کی کاپی ایک غیر ضروری نقل ہے: جانچ میں اصل غیر تبدیل شدہ پایا گیا۔ وہ کاپی حذف کریں، پھر منتقلی دوبارہ آزمائیں۔"+#: src/components/SyncStatusBadge.tsxmsgid "The default branch is protected — pushes need a pull request."msgstr "طے شدہ برانچ محفوظ ہے — پُش کے لیے پُل ریکویسٹ درکار ہے۔"diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.jsonindex 4fd3399f6..e4ea2ca7b 100644--- a/packages/app/src/locales/zh-Hans/messages.json+++ b/packages/app/src/locales/zh-Hans/messages.json@@ -627,6 +627,7 @@"851WA-": ["这可以在「设置 > AI 工具与 CLI」中配置"],"87GMKe": ["要将此项目公开到网络吗?"],"881Uwh": ["删除选中的表格"],+ "89TmeV": ["部分技能删除时带有警告"],"89TtiD": ["在项目根目录中用模板“", ["displayTitle"], "”新建文件(", ["fileName"], ")"],"8AjnFz": ["“", ["0"], "”已导入过(内容相同)。"],"8F1i42": ["找不到页面"],@@ -1259,6 +1260,7 @@"GbzBEk": ["服务器返回的技能响应不完整。"],"GceAYf": ["已将 ", ["label"], " 移动到右侧的新窗格。"],"GemPfn": ["解析出链的错误响应失败(HTTP ", ["status"], ")"],+ "GesfyX": [["shown"], " 另外还有 ", ["more"], " 个"],"Gfr4fu": ["服务器无法打开文档"],"GhjUB_": ["已重新连接"],"Gi8Akx": ["还没有配置任何智能体——要附加文件,请在「智能体连接」中添加应用内智能体。"],@@ -1786,6 +1788,13 @@"OKImo8": ["冲突文件"],"OLBz-_": ["Mermaid 图示渲染失败。"],"OLIKgw": ["拖动项目 ", ["0"], " 以重新排序"],+ "OMS7Xp": [+ "已在",+ ["scopeLabel"],+ "中有意保留了“",+ ["name"],+ "”的一份副本。请先与原件比对再删除:它可能保存着失败的移动已经删掉的文件的唯一副本。"+ ],"ONPvOb": ["正在加载智能体活动"],"ONUgxB": ["该冲突已不再可用。"],"ONWvwQ": ["上传"],@@ -1976,6 +1985,7 @@"RD8cCw": ["此版本无法管理智能体连接。"],"RDjuBN": ["设置"],"RDrXh4": ["配置用户、项目和集成相关的设置。"],+ "RDzxes": ["已将 ", ["total"], " 个技能中的 ", ["moved"], " 个移至", ["scopeLabel"]],"REkvLz": ["端口 ",["0"],@@ -2008,6 +2018,13 @@"R_U_A4": ["添加文件或文件夹模式,例如 guides/**/*"],"RaPMZv": ["编辑器和工作区中可用的键盘快捷键。"],"RaUKLu": ["远程控制"],+ "Raayoq": [+ "保留在",+ ["scopeLabel"],+ "中的“",+ ["name"],+ "”副本是多余的重复:原件已核实未被改动。请删除该副本,然后重试移动。"+ ],"Rah7yq": ["希望 AI 做什么?(可选)"],"Rb1zMa": ["没有摘要"],"RcrskJ": ["排版看起来不对"],@@ -2633,6 +2650,12 @@"_G7A92": ["维护index.md"],"_GRWOJ": ["要更换嵌入服务提供方吗?"],"_HgF9q": ["排序方式"],+ "_HlScO": [+ ["scopeLabel"],+ "中可能残留以下技能的副本:",+ ["names"],+ "。请先与原件比对再删除其中任何内容:它可能保存着失败的移动已经删掉的文件的唯一副本。"+ ],"_IGfXZ": ["OpenKnowledge 上次意外退出了。"],"_IX_7x": ["其他"],"_IfSZn": ["已有一个已保存的主题使用此名称。"],@@ -2976,6 +2999,12 @@"eFJkVt": ["克隆失败:", ["cloneError"]],"eG8Jsg": ["切换源码 Tab 焦点模式"],"eGUbmF": ["复制选中的文件或文件夹"],+ "eGkfGQ": [+ ["scopeLabel"],+ "中保留了以下技能的多余副本:",+ ["names"],+ "。每个原件都已核实未被改动,请删除这些副本,然后重试移动。"+ ],"eJitUk": ["从电脑上传"],"eKThTQ": ["重新排序失败"],"eMWRAs": ["已建立索引的页面:", ["semanticIndexedCount"], " / ", ["semanticTotalCount"], "。"],@@ -4500,6 +4529,12 @@"xSVO3J": ["会创建什么"],"xV5sXw": [["0"], " 周前"],"xW5AUw": [["pulled"], "拉取"],+ "xW7KK3": [+ ["scopeLabel"],+ "中已经有名为“",+ ["name"],+ "”的内容,服务器无法确认它是什么。它可能是此前一次失败的移动有意保留下来的:删除或替换之前,请先与原件比对。"+ ],"xWEvuo": ["问 AI"],"xWomUD": ["使用 ", ["editor"], " 的版本"],"xXo8FT": ["保存失败:", ["error"]],diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex 0bb411d60..0ed8549b4 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -1020,6 +1020,10 @@ msgstr "{settingsDescriptorLabel} 属性"msgid "{shareBranch} isn't a valid branch name."msgstr "{shareBranch} 不是有效的分支名。"+#: src/lib/skills-api.ts+msgid "{shown} and {more} more"+msgstr "{shown} 另外还有 {more} 个"+#: src/components/ReportBugDialogBody.tsxmsgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"msgstr "{sizeText} · 已隐去机密信息 · {fileCount, plural, other {# 个文件}}"@@ -1275,6 +1279,14 @@ msgstr "副本是一个独立的真实文件夹,OK 会让它与来源保持一msgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."msgstr "副本是一个独立的真实文件夹,OK 会让它与来源保持一致:在这里编辑技能,每个副本都会同步更新。一旦你在 OK 之外手动改动某个副本,同步就会停止——从那时起它就自成一份,并显示为一个单独的技能。符号链接则是指向来源的指针,因此不会产生偏差,但来源一旦被删除,该位置就会失效。"+#: src/lib/skills-api.ts+msgid "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+msgstr "{scopeLabel}中可能残留以下技能的副本:{names}。请先与原件比对再删除其中任何内容:它可能保存着失败的移动已经删掉的文件的唯一副本。"++#: src/lib/skills-api.ts+msgid "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+msgstr "已在{scopeLabel}中有意保留了“{name}”的一份副本。请先与原件比对再删除:它可能保存着失败的移动已经删掉的文件的唯一副本。"+#. placeholder {0}: path ?? label#: src/components/SkillInstallMenu.tsxmsgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."@@ -1363,6 +1375,10 @@ msgstr "引文块会从周围的正文中凸显出来。"msgid "A real shell is off for this project. Turning it on runs commands with the full access of your user account."msgstr "本项目未启用真实 shell。启用后,命令将以你的用户账户的完整权限运行。"+#: src/lib/skills-api.ts+msgid "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+msgstr "{scopeLabel}中保留了以下技能的多余副本:{names}。每个原件都已核实未被改动,请删除这些副本,然后重试移动。"+#: src/components/ReportBugDialogBody.tsxmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr "报告能帮我们找到原因。在你确认之前不会发送任何内容。"@@ -8507,6 +8523,10 @@ msgstr "已将 {label} 移动到左侧的新窗格。"msgid "Moved {label} to a new pane on the right."msgstr "已将 {label} 移动到右侧的新窗格。"+#: src/lib/skills-api.ts+msgid "Moved {moved} of {total} skills to {scopeLabel}"+msgstr "已将 {total} 个技能中的 {moved} 个移至{scopeLabel}"+#: src/components/SkillsTree.tsxmsgid "Moved {moved} skills to Global"msgstr "已将 {moved} 个技能移至全局"@@ -12869,6 +12889,10 @@ msgstr "部分文件未列出:工作区的更改过多。"msgid "Some saved themes aren’t shown because the theme folder exceeds the scan limit."msgstr "因为主题文件夹超出扫描限制,部分已保存的主题未显示。"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Some skills were deleted with a warning"+msgstr "部分技能删除时带有警告"+#: src/components/FeedbackForm.tsxmsgid "Something broke"msgstr "有东西坏了"@@ -12877,6 +12901,10 @@ msgstr "有东西坏了"msgid "Something else"msgstr "其他原因"+#: src/lib/skills-api.ts+msgid "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+msgstr "{scopeLabel}中已经有名为“{name}”的内容,服务器无法确认它是什么。它可能是此前一次失败的移动有意保留下来的:删除或替换之前,请先与原件比对。"+#: src/components/AppErrorBoundary.tsxmsgid "Something went wrong"msgstr "出了点问题"@@ -13669,6 +13697,10 @@ msgstr "画板内容不是有效的 Excalidraw 场景。"msgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "Claude 桌面应用没有打开这个文件。它安装了吗?({msg})"+#: src/lib/skills-api.ts+msgid "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+msgstr "保留在{scopeLabel}中的“{name}”副本是多余的重复:原件已核实未被改动。请删除该副本,然后重试移动。"+#: src/components/SyncStatusBadge.tsxmsgid "The default branch is protected — pushes need a pull request."msgstr "默认分支受保护——推送需要通过 pull request。"diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.jsonindex df5b77f2d..05720b493 100644--- a/packages/app/src/locales/zh-Hant/messages.json+++ b/packages/app/src/locales/zh-Hant/messages.json@@ -627,6 +627,7 @@"851WA-": ["這可以在「設定 > AI 工具與 CLI」中設定"],"87GMKe": ["要將此專案公開到網路上嗎?"],"881Uwh": ["刪除選取的表格"],+ "89TmeV": ["部分技能刪除時帶有警告"],"89TtiD": ["在專案根目錄中用範本「", ["displayTitle"], "」新增檔案(", ["fileName"], ")"],"8AjnFz": ["「", ["0"], "」先前已匯入過(內容相同)。"],"8F1i42": ["找不到頁面"],@@ -1263,6 +1264,7 @@"GbzBEk": ["伺服器回傳的技能回應不完整。"],"GceAYf": ["已將 ", ["label"], " 移動到右側的新窗格。"],"GemPfn": ["解析外連連結的錯誤回應失敗(HTTP ", ["status"], ")"],+ "GesfyX": [["shown"], " 另外還有 ", ["more"], " 個"],"Gfr4fu": ["伺服器無法開啟文件"],"GhjUB_": ["已重新連線"],"Gi8Akx": ["還沒有設定任何代理——要附加檔案,請在「智慧代理連線」中新增應用程式內的智慧代理。"],@@ -1804,6 +1806,13 @@"OKImo8": ["衝突的檔案"],"OLBz-_": ["Mermaid 圖表顯示失敗。"],"OLIKgw": ["拖曳項目 ", ["0"], " 以重新排序"],+ "OMS7Xp": [+ "已在",+ ["scopeLabel"],+ "中刻意保留了「",+ ["name"],+ "」的一份副本。請先與原件比對再刪除:它可能保存著失敗的移動已經刪除的檔案的唯一副本。"+ ],"ONPvOb": ["正在載入代理活動"],"ONUgxB": ["該衝突已不再可用。"],"ONWvwQ": ["上傳"],@@ -1994,6 +2003,7 @@"RD8cCw": ["此版本無法管理智慧代理連線。"],"RDjuBN": ["設定"],"RDrXh4": ["設定使用者、專案和整合相關的選項。"],+ "RDzxes": ["已將 ", ["total"], " 個技能中的 ", ["moved"], " 個移至", ["scopeLabel"]],"REkvLz": ["連接埠 ",["0"],@@ -2026,6 +2036,13 @@"R_U_A4": ["新增檔案或資料夾模式,例如 guides/**/*"],"RaPMZv": ["編輯器和工作區中可用的鍵盤快速鍵。"],"RaUKLu": ["遠端控制"],+ "Raayoq": [+ "保留在",+ ["scopeLabel"],+ "中的「",+ ["name"],+ "」副本是多餘的重複:原件已核實未被更動。請刪除該副本,然後重試移動。"+ ],"Rah7yq": ["希望 AI 做什麼?(選填)"],"Rb1zMa": ["沒有摘錄"],"RcrskJ": ["排版看起來不對"],@@ -2649,6 +2666,12 @@"_G7A92": ["維護index.md"],"_GRWOJ": ["要更換嵌入服務供應商嗎?"],"_HgF9q": ["排序方式"],+ "_HlScO": [+ ["scopeLabel"],+ "中可能殘留以下技能的副本:",+ ["names"],+ "。請先與原件比對再刪除其中任何內容:它可能保存著失敗的移動已經刪除的檔案的唯一副本。"+ ],"_IGfXZ": ["OpenKnowledge 上次非預期地結束了。"],"_IX_7x": ["其他"],"_IfSZn": ["已有已儲存的主題使用這個名稱。"],@@ -2994,6 +3017,12 @@"eFJkVt": ["複製失敗:", ["cloneError"]],"eG8Jsg": ["切換原始碼 Tab 焦點模式"],"eGUbmF": ["複製選取的檔案或資料夾"],+ "eGkfGQ": [+ ["scopeLabel"],+ "中保留了以下技能的多餘副本:",+ ["names"],+ "。每個原件都已核實未被更動,請刪除這些副本,然後重試移動。"+ ],"eJitUk": ["從電腦上傳"],"eKThTQ": ["重新排序失敗"],"eMWRAs": ["已建立索引的頁面:", ["semanticIndexedCount"], " / ", ["semanticTotalCount"], "。"],@@ -4522,6 +4551,12 @@"xSVO3J": ["會建立什麼"],"xV5sXw": [["0"], " 週前"],"xW5AUw": [["pulled"], "拉取"],+ "xW7KK3": [+ ["scopeLabel"],+ "中已經有名為「",+ ["name"],+ "」的內容,伺服器無法確認它是什麼。它可能是先前一次失敗的移動刻意保留下來的:刪除或取代之前,請先與原件比對。"+ ],"xWEvuo": ["問 AI"],"xWomUD": ["使用 ", ["editor"], " 的版本"],"xXo8FT": ["儲存失敗:", ["error"]],diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex aa8a558ea..2953cbd77 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -1020,6 +1020,10 @@ msgstr "{settingsDescriptorLabel} 屬性"msgid "{shareBranch} isn't a valid branch name."msgstr "{shareBranch} 不是有效的分支名稱。"+#: src/lib/skills-api.ts+msgid "{shown} and {more} more"+msgstr "{shown} 另外還有 {more} 個"+#: src/components/ReportBugDialogBody.tsxmsgid "{sizeText} · secrets redacted · {fileCount, plural, one {# file} other {# files}}"msgstr "{sizeText} · 已遮蔽機密資訊 · {fileCount, plural, other {# 個檔案}}"@@ -1275,6 +1279,14 @@ msgstr "副本是一個獨立的真實資料夾,OK 會讓它與來源保持同msgid "A copy is a real folder of its own, and OK keeps it in step with the source: edit the skill here and every copy is refreshed. That stops the moment you hand-edit a copy outside OK — from then on it goes its own way and shows up as a separate skill. A symlink is a pointer to the source instead, so nothing can drift, but a location stops working if the source is deleted."msgstr "副本是一個獨立的真實資料夾,OK 會讓它與來源保持同步:在這裡編輯技能,每個副本都會跟著更新。一旦你在 OK 之外手動改動某個副本,同步就會停止——從那時起它就自成一份,並顯示為另一個技能。符號連結則是指向來源的指標,因此不會產生偏差,但來源一旦被刪除,該位置就會失效。"+#: src/lib/skills-api.ts+msgid "A copy may remain in {scopeLabel} for: {names}. Don't delete anything there before comparing it with the original: it may hold the only copy of files a failed move already removed."+msgstr "{scopeLabel}中可能殘留以下技能的副本:{names}。請先與原件比對再刪除其中任何內容:它可能保存著失敗的移動已經刪除的檔案的唯一副本。"++#: src/lib/skills-api.ts+msgid "A copy of \"{name}\" was kept in {scopeLabel} on purpose. Don't delete it before comparing it with the original: it may hold the only copy of files the failed move already removed."+msgstr "已在{scopeLabel}中刻意保留了「{name}」的一份副本。請先與原件比對再刪除:它可能保存著失敗的移動已經刪除的檔案的唯一副本。"+#. placeholder {0}: path ?? label#: src/components/SkillInstallMenu.tsxmsgid "A DIFFERENT skill named like this one lives at {0} — that folder is not this skill. Rename or delete one of the two to resolve."@@ -1363,6 +1375,10 @@ msgstr "引言區塊會從周圍的內文中凸顯出來。"msgid "A real shell is off for this project. Turning it on runs commands with the full access of your user account."msgstr "本專案未啟用真實 shell。啟用後,命令會以你的使用者帳戶的完整權限執行。"+#: src/lib/skills-api.ts+msgid "A redundant copy was kept in {scopeLabel} for: {names}. Each original was verified unchanged, so remove those copies and retry the move."+msgstr "{scopeLabel}中保留了以下技能的多餘副本:{names}。每個原件都已核實未被更動,請刪除這些副本,然後重試移動。"+#: src/components/ReportBugDialogBody.tsxmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr "回報能幫我們找出原因。在你檢查過之前不會送出任何內容。"@@ -8507,6 +8523,10 @@ msgstr "已將 {label} 移動到左側的新窗格。"msgid "Moved {label} to a new pane on the right."msgstr "已將 {label} 移動到右側的新窗格。"+#: src/lib/skills-api.ts+msgid "Moved {moved} of {total} skills to {scopeLabel}"+msgstr "已將 {total} 個技能中的 {moved} 個移至{scopeLabel}"+#: src/components/SkillsTree.tsxmsgid "Moved {moved} skills to Global"msgstr "已將 {moved} 個技能移至全域"@@ -12869,6 +12889,10 @@ msgstr "部分檔案未列出:工作區的變更過多。"msgid "Some saved themes aren’t shown because the theme folder exceeds the scan limit."msgstr "因為主題資料夾超出掃描限制,部分已儲存的主題未顯示。"+#: src/components/SkillBulkDeleteDialog.tsx+msgid "Some skills were deleted with a warning"+msgstr "部分技能刪除時帶有警告"+#: src/components/FeedbackForm.tsxmsgid "Something broke"msgstr "有東西壞了"@@ -12877,6 +12901,10 @@ msgstr "有東西壞了"msgid "Something else"msgstr "其他原因"+#: src/lib/skills-api.ts+msgid "Something named \"{name}\" is already in {scopeLabel}, and the server couldn't confirm what it is. An earlier failed move may have kept it there on purpose: compare it with the original before you delete or replace it."+msgstr "{scopeLabel}中已經有名為「{name}」的內容,伺服器無法確認它是什麼。它可能是先前一次失敗的移動刻意保留下來的:刪除或取代之前,請先與原件比對。"+#: src/components/AppErrorBoundary.tsxmsgid "Something went wrong"msgstr "出了點問題"@@ -13669,6 +13697,10 @@ msgstr "畫板內容不是有效的 Excalidraw 場景。"msgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "Claude Desktop App 沒有開啟這個檔案。它有安裝嗎?({msg})"+#: src/lib/skills-api.ts+msgid "The copy of \"{name}\" kept in {scopeLabel} is a redundant duplicate: the original was verified unchanged. Remove that copy, then retry the move."+msgstr "保留在{scopeLabel}中的「{name}」副本是多餘的重複:原件已核實未被更動。請刪除該副本,然後重試移動。"+#: src/components/SyncStatusBadge.tsxmsgid "The default branch is protected — pushes need a pull request."msgstr "預設分支受保護——推送需要透過 pull request。"diff --git a/packages/app/tests/integration/skill-authoring-warning-contract.test.ts b/packages/app/tests/integration/skill-authoring-warning-contract.test.tsnew file mode 100644index 000000000..50c7de1bf--- /dev/null+++ b/packages/app/tests/integration/skill-authoring-warning-contract.test.ts@@ -0,0 +1,115 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import { writeSkill } from '../../../server/src/mcp/tools/skill-target.ts';+import { createTestServer, HARNESS_BOOT_TIMEOUT_MS, type TestServer } from './test-harness.ts';++let server: TestServer;+let sourceRoot: string;+const codes = ['skill-name-vendor-word', 'skill-body-too-long'];+const body = (count: number) => Array.from({ length: count }, (_, i) => `Line ${i}.`).join('\n');+const request = async (path: string, input: Record<string, unknown>, method = 'POST') => {+ const response = await fetch(`http://127.0.0.1:${server.port}${path}`, {+ method,+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(input),+ });+ const result = await response.json();+ expect(response.status, JSON.stringify(result)).toBe(200);+ return result;+};++function seed(name: string, lines: number): string {+ const source = join(sourceRoot, name);+ mkdirSync(source, { recursive: true });+ writeFileSync(+ join(source, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Warnings\n---\n${body(lines)}`,+ );+ return source;+}++function expectWarnings(result: { warnings: string[]; warningCodes: string[] }): void {+ expect(result.warningCodes).toEqual(codes);+ expect(result.warnings).toEqual([+ expect.stringContaining('"claude"'),+ expect.stringContaining('lines'),+ ]);+}++beforeAll(async () => {+ sourceRoot = mkdtempSync(join(tmpdir(), 'ok-warning-contract-'));+ server = await createTestServer();+}, HARNESS_BOOT_TIMEOUT_MS);++afterAll(async () => {+ await server.cleanup();+ rmSync(sourceRoot, { recursive: true, force: true });+});++describe('authoring warning codes across skill entry points', () => {+ test('create and edit emit each authoring warning once with the matching code', async () => {+ const name = 'claude-write-warning';+ for (const lines of [601, 602]) {+ expectWarnings(+ await request(+ '/api/skill',+ { name, body: body(lines), frontmatter: { name, description: 'Warnings' } },+ 'PUT',+ ),+ );+ }+ });++ test('single import and reimport retain warning codes and no-op responses return empty pairs', async () => {+ const name = 'claude-single-warning';+ const source = seed(name, 601);+ expectWarnings(await request('/api/skill/import', { source }));+ seed(name, 602);+ expectWarnings(await request('/api/skill/reimport', { name }));+ for (const input of [{ name }, { name, setAutoUpdate: true }]) {+ expect(await request('/api/skill/reimport', input)).toMatchObject({+ warnings: [],+ warningCodes: [],+ });+ }+ });++ test('bulk import and reimport retain warning codes on each result', async () => {+ const name = 'claude-bulk-warning';+ seed(name, 601);+ const imported = await request('/api/skills/import-bulk', {+ source: sourceRoot,+ skills: [name],+ });+ expectWarnings(imported.results[0]);+ seed(name, 602);+ const refreshed = await request('/api/skills/reimport-bulk', {+ names: [name, 'absent-warning-skill'],+ });+ expectWarnings(refreshed.results.find((row: { requested: string }) => row.requested === name));+ expect(+ refreshed.results.find((row: { requested: string }) => row.requested !== name),+ ).toMatchObject({ warnings: [], warningCodes: [] });+ const unchanged = await request('/api/skills/reimport-bulk', { names: [name] });+ expect(unchanged.results[0]).toMatchObject({ warnings: [], warningCodes: [] });+ });++ test('MCP skill writes expose warning codes alongside their display text', async () => {+ const result = await writeSkill(`http://127.0.0.1:${server.port}`, {+ name: 'claude-mcp-warning',+ description: 'Warnings',+ body: body(601),+ });+ expect(result.isError).toBeUndefined();+ expect(result).toMatchObject({+ structuredContent: {+ skill: {+ warningCodes: codes,+ warnings: [expect.stringContaining('"claude"'), expect.stringContaining('lines')],+ },+ },+ });+ });+});diff --git a/packages/app/tests/integration/skill-import.test.ts b/packages/app/tests/integration/skill-import.test.tsindex 6d22a4d7d..ac61da05f 100644--- a/packages/app/tests/integration/skill-import.test.ts+++ b/packages/app/tests/integration/skill-import.test.ts@@ -1,8 +1,17 @@-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { EDITOR_USER_SKILL_ROOT } from '@inkeep/open-knowledge-core';import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';+import { withFsCopyCompletionObserver } from '../../../server/src/fs-copy-observer.test-helper.ts';import {createTestServer,HARNESS_BOOT_TIMEOUT_MS,@@ -188,6 +197,75 @@ describe('POST /api/skill/import', () => {expect(missing.status).toBe(404);});+ test('an unparseable source frontmatter fails the duplicate with the parse reason', async () => {+ const dir = join(srcRoot, 'dup-bad-fm');+ writeSkillDir(dir, 'dup-bad-fm', 'source');+ expect((await importSkill({ source: dir, install: false })).status).toBe(200);+ const home = existsSync(join(server.contentDir, '.agents')) ? '.agents' : '.claude';+ const sourceDir = resolve(server.contentDir, home, 'skills', 'dup-bad-fm');+ const copyDir = resolve(server.contentDir, home, 'skills', 'dup-bad-fm-copy');+ writeFileSync(join(sourceDir, 'SKILL.md'), '---\nname: [unclosed\n---\n\nBody.\n');++ const response = await fetch(`${base()}/api/skill/duplicate`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ scope: 'project',+ name: 'dup-bad-fm',+ toName: 'dup-bad-fm-copy',+ }),+ });+ const result = (await response.json()) as { detail?: string; title?: string; type?: string };++ expect(response.status).toBe(400);+ expect(result.type).toBe('urn:ok:error:invalid-request');+ expect(result.title).toContain('destination copy removed');+ expect(result.detail).toMatch(/parse_failed \(frontmatter region unparseable: .+\)/);+ expect(result.detail).toContain('was not touched');+ expect(existsSync(copyDir)).toBe(false);+ });++ test('duplicate write and cleanup failures report the stray copy', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory write permissions.');+ }+ const dir = join(srcRoot, 'dup-cleanup');+ writeSkillDir(dir, 'dup-cleanup', 'source');+ expect((await importSkill({ source: dir, install: false })).status).toBe(200);+ const home = existsSync(join(server.contentDir, '.agents')) ? '.agents' : '.claude';+ const copyDir = resolve(server.contentDir, home, 'skills', 'dup-cleanup-copy');++ try {+ const response = await withFsCopyCompletionObserver(+ (path) => path.endsWith(join('skills', 'dup-cleanup-copy')),+ () => {+ chmodSync(join(copyDir, 'SKILL.md'), 0o444);+ chmodSync(copyDir, 0o555);+ },+ () =>+ fetch(`${base()}/api/skill/duplicate`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ scope: 'project',+ name: 'dup-cleanup',+ toName: 'dup-cleanup-copy',+ }),+ }),+ );+ const result = (await response.json()) as { detail?: string; title?: string };++ expect(response.status).toBe(500);+ expect(result.title).toContain('destination cleanup failed');+ expect(result.detail).toContain('UNLINK_FAILED');+ expect(result.detail).toContain(`${home}/skills/dup-cleanup-copy`);+ expect(result.detail).toContain('Inspect the destination before retrying');+ expect(existsSync(copyDir)).toBe(true);+ } finally {+ if (existsSync(copyDir)) chmodSync(copyDir, 0o755);+ }+ });+test('name collision with different content lands under -imported', async () => {const a = join(srcRoot, 'collide-a');const b = join(srcRoot, 'collide-b');diff --git a/packages/app/tests/integration/skill-mcp-edit-schema.test.ts b/packages/app/tests/integration/skill-mcp-edit-schema.test.tsnew file mode 100644index 000000000..53ee878e0--- /dev/null+++ b/packages/app/tests/integration/skill-mcp-edit-schema.test.ts@@ -0,0 +1,83 @@+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import { connectMcpTestClient } from '../../../server/src/mcp/client.test-helper.ts';+import { createTestServer, HARNESS_BOOT_TIMEOUT_MS, type TestServer } from './test-harness.ts';++let server: TestServer;+let client: Awaited<ReturnType<typeof connectMcpTestClient>>;++function seedSkill(name: string, body: string): string {+ const dir = join(server.contentDir, '.claude', 'skills', name);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: Edit me\n---\n${body}`);+ return dir;+}++beforeAll(async () => {+ server = await createTestServer();+ client = await connectMcpTestClient(`${server.baseUrl}/mcp`);+ const { tools } = await client.listTools();+ expect(tools.find((tool) => tool.name === 'edit')?.outputSchema).toBeDefined();+}, HARNESS_BOOT_TIMEOUT_MS);++afterAll(async () => {+ await client?.close();+ await server?.cleanup();+});++describe('registered MCP edit output validates in an SDK client', () => {+ test('two authoring warnings survive the advertised output schema', async () => {+ const name = 'claude-edit-warnings';+ const dir = seedSkill(name, 'Replace this body.');+ const body = Array.from({ length: 601 }, (_, index) => `Line ${index}.`).join('\n');+ const result = await client.callTool({+ name: 'edit',+ arguments: { skill: { name, find: 'Replace this body.', replace: body } },+ });+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject({+ skill: {+ ok: true,+ created: false,+ warnings: [expect.stringContaining('"claude"'), expect.stringContaining('lines')],+ warningCodes: ['skill-name-vendor-word', 'skill-body-too-long'],+ },+ });+ expect(readFileSync(join(dir, 'SKILL.md'), 'utf8')).toContain(body);+ });++ test('metadata edits with empty warning arrays survive the advertised output schema', async () => {+ const name = 'quiet-edit';+ const dir = seedSkill(name, 'Body stays.');+ const result = await client.callTool({+ name: 'edit',+ arguments: { skill: { name, description: 'Updated description' } },+ });+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject({+ skill: { ok: true, created: false, warnings: [], warningCodes: [] },+ });+ expect(readFileSync(join(dir, 'SKILL.md'), 'utf8')).toContain('Updated description');+ expect(readFileSync(join(dir, 'SKILL.md'), 'utf8')).toContain('Body stays.');+ });++ test('bundle-file edits still validate without SKILL.md warning fields', async () => {+ const name = 'bundle-edit';+ const dir = seedSkill(name, 'Unchanged skill body.');+ const original = readFileSync(join(dir, 'SKILL.md'), 'utf8');+ mkdirSync(join(dir, 'references'));+ const file = 'references/guide.md';+ writeFileSync(join(dir, file), 'Original reference.');+ const result = await client.callTool({+ name: 'edit',+ arguments: { skill: { name, file, find: 'Original', replace: 'Updated' } },+ });+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject({+ skill: { ok: true, file: { path: file, created: false } },+ });+ expect(readFileSync(join(dir, file), 'utf8')).toBe('Updated reference.');+ expect(readFileSync(join(dir, 'SKILL.md'), 'utf8')).toBe(original);+ });+});diff --git a/packages/app/tests/integration/skill-mcp-move.test.ts b/packages/app/tests/integration/skill-mcp-move.test.tsnew file mode 100644index 000000000..44edb533d--- /dev/null+++ b/packages/app/tests/integration/skill-mcp-move.test.ts@@ -0,0 +1,1302 @@+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import { withFsCopyCompletionObserver } from '../../../server/src/fs-copy-observer.test-helper.ts';+import { moveSkillCrossScope } from '../../../server/src/mcp/tools/skill-target.ts';+import { createTestServer, HARNESS_BOOT_TIMEOUT_MS, type TestServer } from './test-harness.ts';++let server: TestServer;+let fixtureRoot: string;+const post = (path: string, body: Record<string, unknown>) =>+ fetch(`http://127.0.0.1:${server.port}${path}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });++function retentionLedger(): Record<string, Record<string, unknown>> {+ const path = join(fixtureRoot, 'home', '.ok', 'local', 'skill-move-retained.json');+ if (!existsSync(path)) return {};+ return JSON.parse(readFileSync(path, 'utf8')).retained;+}++function seedSkill(root: string, name: string): string {+ const dir = join(root, '.claude', 'skills', name);+ mkdirSync(dir, { recursive: true });+ const text = `---\nname: ${name}\ndescription: Bundle\nmetadata:\n pack: sample-pack\n custom: keep-me\n---\n\nBody stays byte-identical.\n`;+ writeFileSync(join(dir, 'SKILL.md'), text);+ return text;+}++beforeAll(async () => {+ fixtureRoot = mkdtempSync(join(tmpdir(), 'ok-mcp-move-'));+ const home = join(fixtureRoot, 'home');+ mkdirSync(join(home, '.claude', 'skills'), { recursive: true });+ server = await createTestServer({ configHomedirOverride: home });+}, HARNESS_BOOT_TIMEOUT_MS);++afterAll(async () => {+ await server.cleanup();+ rmSync(fixtureRoot, { recursive: true, force: true });+});++describe('MCP cross-scope move', () => {+ test('preserves binary bundles, provenance and installed editors', async () => {+ const name = 'complete-bundle';+ const source = join(fixtureRoot, 'source', name);+ mkdirSync(join(source, 'references'), { recursive: true });+ writeFileSync(+ join(source, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Bundle\n---\n\nBody.\n`,+ );+ const binary = Buffer.from([0, 255, 128, 13, 10, 0, 24]);+ writeFileSync(join(source, 'references', 'data.bin'), binary);+ expect((await post('/api/skill/import', { source, scope: 'project' })).status).toBe(200);+ expect((await post('/api/skill/install', { name, add: ['claude', 'cursor'] })).status).toBe(+ 200,+ );++ const result = await moveSkillCrossScope(`http://127.0.0.1:${server.port}`, {+ fromScope: 'project',+ toScope: 'global',+ fromName: name,+ toName: name,+ });++ expect(result.isError).toBeUndefined();+ for (const host of ['claude', 'cursor']) {+ const dest = join(fixtureRoot, 'home', `.${host}`, 'skills', name);+ expect(readFileSync(join(dest, 'references', 'data.bin'))).toEqual(binary);+ expect(existsSync(join(server.contentDir, `.${host}`, 'skills', name))).toBe(false);+ }+ const globalLock = JSON.parse(+ readFileSync(join(fixtureRoot, 'home', '.ok', 'skills-lock.json'), 'utf8'),+ );+ expect(globalLock.skills[name].source).toBe(source);+ const projectLock = JSON.parse(+ readFileSync(join(server.contentDir, '.ok', 'skills-lock.json'), 'utf8'),+ );+ expect(projectLock.skills[name]).toBeUndefined();+ });++ test('a renaming move re-keys provenance, install records and editor placements under the new name', async () => {+ const home = join(fixtureRoot, 'home');+ const fromName = 'rekey-original';+ const toName = 'rekey-renamed';+ const source = join(fixtureRoot, 'source', fromName);+ mkdirSync(source, { recursive: true });+ writeFileSync(+ join(source, 'SKILL.md'),+ `---\nname: ${fromName}\ndescription: Bundle\n---\n\nBody.\n`,+ );+ expect((await post('/api/skill/import', { source, scope: 'project' })).status).toBe(200);+ expect(+ (await post('/api/skill/install', { name: fromName, add: ['claude', 'cursor'] })).status,+ ).toBe(200);+ const importedLocalHash = JSON.parse(+ readFileSync(join(server.contentDir, '.ok', 'skills-lock.json'), 'utf8'),+ ).skills[fromName].localHash;+ expect(importedLocalHash).toEqual(expect.any(String));++ const result = await moveSkillCrossScope(server.baseUrl, {+ fromScope: 'project',+ toScope: 'global',+ fromName,+ toName,+ });++ expect(result.isError).toBeUndefined();+ const globalLock = JSON.parse(readFileSync(join(home, '.ok', 'skills-lock.json'), 'utf8'));+ expect(globalLock.skills[toName]?.source).toBe(source);+ expect(globalLock.skills[fromName]).toBeUndefined();+ expect(globalLock.skills[toName]?.localHash).toEqual(expect.any(String));+ expect(globalLock.skills[toName]?.localHash).not.toBe(importedLocalHash);+ const installed = JSON.parse(+ readFileSync(join(home, '.ok', 'local', 'installed-skills.json'), 'utf8'),+ );+ expect(installed.skills[toName]?.hosts).toEqual(expect.arrayContaining(['claude', 'cursor']));+ expect(installed.skills[fromName]).toBeUndefined();+ for (const host of ['claude', 'cursor']) {+ expect(existsSync(join(home, `.${host}`, 'skills', toName, 'SKILL.md'))).toBe(true);+ expect(existsSync(join(home, `.${host}`, 'skills', fromName))).toBe(false);+ expect(existsSync(join(server.contentDir, `.${host}`, 'skills', fromName))).toBe(false);+ }+ });++ test('renames directly across scopes without colliding with unrelated intermediate names', async () => {+ const home = join(fixtureRoot, 'home');+ const fromName = 'direct-original';+ const toName = 'direct-renamed';+ const original = seedSkill(server.contentDir, fromName);+ const unrelatedGlobal = seedSkill(home, fromName);+ const unrelatedProject = seedSkill(server.contentDir, toName);++ const result = await moveSkillCrossScope(`http://127.0.0.1:${server.port}`, {+ fromScope: 'project',+ toScope: 'global',+ fromName,+ toName,+ });++ expect(result.isError).toBeUndefined();+ expect(readFileSync(join(home, '.claude', 'skills', toName, 'SKILL.md'), 'utf8')).toBe(+ original.replace(`name: ${fromName}`, `name: ${toName}`),+ );+ expect(readFileSync(join(home, '.claude', 'skills', fromName, 'SKILL.md'), 'utf8')).toBe(+ unrelatedGlobal,+ );+ expect(+ readFileSync(join(server.contentDir, '.claude', 'skills', toName, 'SKILL.md'), 'utf8'),+ ).toBe(unrelatedProject);+ expect(existsSync(join(server.contentDir, '.claude', 'skills', fromName))).toBe(false);+ });++ test('refuses the final destination collision before moving or deleting the source', async () => {+ const home = join(fixtureRoot, 'home');+ const fromName = 'collision-original';+ const toName = 'collision-renamed';+ const original = seedSkill(server.contentDir, fromName);+ const destination = seedSkill(home, toName);++ const result = await moveSkillCrossScope(`http://127.0.0.1:${server.port}`, {+ fromScope: 'project',+ toScope: 'global',+ fromName,+ toName,+ });++ expect(result.isError).toBe(true);+ expect(result.structuredContent?.moveState).toBe('nothing-written');+ expect(result.content[0]?.text).toContain('Delete or rename it first');+ expect(+ readFileSync(join(server.contentDir, '.claude', 'skills', fromName, 'SKILL.md'), 'utf8'),+ ).toBe(original);+ expect(readFileSync(join(home, '.claude', 'skills', toName, 'SKILL.md'), 'utf8')).toBe(+ destination,+ );+ expect(existsSync(join(home, '.claude', 'skills', fromName))).toBe(false);+ });++ test('partial source-removal failure retains the complete renamed destination for recovery', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory write permissions.');+ }+ const home = join(fixtureRoot, 'home');+ const fromName = 'rollback-original';+ const toName = 'rollback-renamed';+ const original = seedSkill(server.contentDir, fromName);+ const unrelated = seedSkill(home, fromName);+ const source = join(server.contentDir, '.claude', 'skills', fromName);+ const destination = join(home, '.claude', 'skills', toName);+ chmodSync(dirname(source), 0o555);+ try {+ const response = await post('/api/skill/move-scope', {+ name: fromName,+ toName,+ fromScope: 'project',+ toScope: 'global',+ });+ const result = await response.json();+ expect(response.status).toBe(500);+ expect(result.detail).toContain('UNLINK_FAILED');+ expect(existsSync(join(home, '.claude', 'skills', fromName, 'SKILL.md'))).toBe(true);+ expect(readFileSync(join(home, '.claude', 'skills', fromName, 'SKILL.md'), 'utf8')).toBe(+ unrelated,+ );+ expect(existsSync(destination)).toBe(true);+ expect(readFileSync(join(destination, 'SKILL.md'), 'utf8')).toBe(+ original.replace(`name: ${fromName}`, `name: ${toName}`),+ );+ expect(existsSync(source)).toBe(true);+ expect(existsSync(join(source, 'SKILL.md'))).toBe(false);+ expect(result.moveState).toBe('destination-retained');+ expect(result.sourceState).toBe('lossy');+ expect(result.detail).toContain('recover missing source files from the retained copy');+ expect(result.detail).not.toContain('no files were lost');+ expect(retentionLedger()[`global:${toName}`]).toMatchObject({ sourceState: 'lossy' });+ expect(result.detail).toContain('Inspect both locations before retrying');+ expect(result.detail).toContain(toName);+ expect(JSON.stringify(result)).not.toContain('rolled back');+ } finally {+ chmodSync(dirname(source), 0o755);+ }+ });++ test('rename write and cleanup failures retain the source and report the stray destination', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory write permissions.');+ }+ const home = join(fixtureRoot, 'home');+ const fromName = 'cleanup-original';+ const toName = 'cleanup-renamed';+ const original = seedSkill(server.contentDir, fromName);+ const unrelated = seedSkill(home, fromName);+ const source = join(server.contentDir, '.claude', 'skills', fromName);+ const destination = join(home, '.claude', 'skills', toName);+ try {+ const response = await withFsCopyCompletionObserver(+ (path) => path.endsWith(join('skills', toName)),+ () => {+ chmodSync(join(destination, 'SKILL.md'), 0o444);+ chmodSync(destination, 0o555);+ },+ () =>+ post('/api/skill/move-scope', {+ name: fromName,+ toName,+ fromScope: 'project',+ toScope: 'global',+ }),+ );+ const result = await response.json();+ expect(response.status).toBe(500);+ expect(result.moveState).toBe('destination-stray');+ expect(result.detail).toContain('UNLINK_FAILED');+ expect(result.detail).toContain(toName);+ expect(result.detail).toContain('Inspect the destination before retrying');+ expect(JSON.stringify(result)).not.toContain('rolled back');+ expect(existsSync(join(home, '.claude', 'skills', fromName, 'SKILL.md'))).toBe(true);+ expect(readFileSync(join(home, '.claude', 'skills', fromName, 'SKILL.md'), 'utf8')).toBe(+ unrelated,+ );+ expect(readFileSync(join(source, 'SKILL.md'), 'utf8')).toBe(original);+ expect(readFileSync(join(destination, 'SKILL.md'), 'utf8')).toBe(original);+ } finally {+ if (existsSync(destination)) chmodSync(destination, 0o755);+ }+ });++ test('a copied SKILL.md the rename cannot rewrite is cleaned up while the intact source remains retryable', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce file permissions.');+ }+ const home = join(fixtureRoot, 'home');+ const fromName = 'write-failed-original';+ const toName = 'write-failed-renamed';+ const original = seedSkill(server.contentDir, fromName);+ const unrelated = seedSkill(home, fromName);+ const destination = join(home, '.claude', 'skills', toName);+ const input = { name: fromName, toName, fromScope: 'project', toScope: 'global' };+ try {+ const response = await withFsCopyCompletionObserver(+ (path) => path.endsWith(join('skills', toName)),+ () => {+ const copied = join(destination, 'SKILL.md');+ rmSync(copied);+ mkdirSync(copied);+ writeFileSync(join(copied, 'occupant.txt'), 'Not a skill file.');+ },+ () => post('/api/skill/move-scope', input),+ );+ const result = await response.json();+ expect(response.status).toBe(500);+ expect(result.moveState).toBe('destination-removed');+ expect(result.detail).toContain('RENAME_FAILED');+ expect(result.detail).toContain('was not removed');+ expect(existsSync(destination)).toBe(false);+ expect(+ readFileSync(join(server.contentDir, '.claude', 'skills', fromName, 'SKILL.md'), 'utf8'),+ ).toBe(original);+ expect(readFileSync(join(home, '.claude', 'skills', fromName, 'SKILL.md'), 'utf8')).toBe(+ unrelated,+ );+ expect((await post('/api/skill/move-scope', input)).status).toBe(200);+ expect(readFileSync(join(destination, 'SKILL.md'), 'utf8')).toBe(+ original.replace(`name: ${fromName}`, `name: ${toName}`),+ );+ } finally {+ if (existsSync(join(destination, 'SKILL.md', 'occupant.txt'))) {+ rmSync(destination, { recursive: true, force: true });+ }+ }+ });++ test('an unreadable copied frontmatter reports failed cleanup without touching its source', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory write permissions.');+ }+ const fromName = 'invalid-copy-original';+ const toName = 'invalid-copy-renamed';+ const original = seedSkill(server.contentDir, fromName);+ writeFileSync(join(server.contentDir, '.claude', 'skills', fromName, 'note.txt'), 'Keep me.');+ const destination = join(fixtureRoot, 'home', '.claude', 'skills', toName);+ try {+ const response = await withFsCopyCompletionObserver(+ (path) => path.endsWith(join('skills', toName)),+ () => {+ rmSync(join(destination, 'SKILL.md'));+ chmodSync(destination, 0o555);+ },+ () =>+ post('/api/skill/move-scope', {+ name: fromName,+ toName,+ fromScope: 'project',+ toScope: 'global',+ }),+ );+ const result = await response.json();+ expect(response.status).toBe(500);+ expect(result.moveState).toBe('destination-stray');+ expect(result.detail).toContain('UNREADABLE_SKILL');+ expect(result.detail).toContain('UNLINK_FAILED');+ expect(+ readFileSync(join(server.contentDir, '.claude', 'skills', fromName, 'SKILL.md'), 'utf8'),+ ).toBe(original);+ expect(readFileSync(join(destination, 'note.txt'), 'utf8')).toBe('Keep me.');+ } finally {+ if (existsSync(destination)) chmodSync(destination, 0o755);+ }+ });++ test('only editor placements transfer across scopes, not the agents hub or custom roots', async () => {+ const name = 'placement-boundaries';+ const home = join(fixtureRoot, 'home');+ const original = seedSkill(server.contentDir, name);+ expect(+ (+ await post('/api/skill/install', {+ name,+ add: ['agents', '.team/skills'],+ mode: 'copy',+ })+ ).status,+ ).toBe(200);+ for (const root of ['.agents/skills', '.team/skills']) {+ expect(readFileSync(join(server.contentDir, root, name, 'SKILL.md'), 'utf8')).toBe(original);+ }+ const result = await moveSkillCrossScope(server.baseUrl, {+ fromName: name,+ toName: name,+ fromScope: 'project',+ toScope: 'global',+ });+ expect(result.isError).toBeUndefined();+ expect(readFileSync(join(home, '.claude', 'skills', name, 'SKILL.md'), 'utf8')).toBe(original);+ for (const root of ['.agents/skills', '.team/skills']) {+ expect(existsSync(join(home, root, name))).toBe(false);+ expect(existsSync(join(server.contentDir, root, name))).toBe(false);+ }+ expect(result.structuredContent?.droppedLocations).toEqual(['.team/skills', 'agents']);+ expect(result.content[0]?.text).toContain('.team/skills');+ expect(result.content[0]?.text).toContain(+ `install({ name: "${name}", scope: "global", add: [".team/skills", "agents"] })`,+ );++ const replayed = result.structuredContent?.droppedLocations as string[];+ const replay = await post('/api/skill/install', {+ name,+ scope: 'global',+ add: replayed,+ mode: 'copy',+ });+ expect(replay.status).toBe(200);+ try {+ for (const root of ['.agents/skills', '.team/skills']) {+ expect(readFileSync(join(home, root, name, 'SKILL.md'), 'utf8')).toBe(original);+ expect(existsSync(join(home, root, name, name))).toBe(false);+ }+ } finally {+ await post('/api/skill/install', { name, scope: 'global', remove: replayed });+ rmSync(join(home, '.team'), { recursive: true, force: true });+ rmSync(join(home, '.agents'), { recursive: true, force: true });+ }+ });++ test('a destination lost after source removal reports the committed state and recovery guidance', async (ctx) => {+ if (process.platform === 'win32') ctx.skip('Requires unprivileged file symlinks.');+ const name = 'destination-disappears';+ seedSkill(server.contentDir, name);+ const source = join(server.contentDir, '.claude', 'skills', name);+ const swept = join(server.contentDir, '.cursor', 'skills', name);+ const destination = join(fixtureRoot, 'home', '.claude', 'skills', name);+ expect((await post('/api/skill/install', { name, add: ['cursor'], mode: 'copy' })).status).toBe(+ 200,+ );+ expect(existsSync(join(swept, 'SKILL.md'))).toBe(true);+ const response = await withFsCopyCompletionObserver(+ (path) => path.endsWith(join('skills', name)),+ () => {+ rmSync(join(destination, 'SKILL.md'));+ symlinkSync(join(source, 'SKILL.md'), join(destination, 'SKILL.md'), 'file');+ },+ () =>+ post('/api/skill/move-scope', {+ name,+ fromScope: 'project',+ toScope: 'global',+ }),+ );+ const result = await response.json();+ expect(response.status).toBe(500);+ expect(existsSync(source)).toBe(false);+ expect(existsSync(join(destination, 'SKILL.md'))).toBe(false);+ expect(result.moveState).toBe('destination-unreadable');+ expect(result.detail).toContain('shadow-repo history');+ expect(result.detail).toContain('before retrying');+ expect(JSON.stringify(result)).not.toContain('nothing was reported as moved');+ expect(existsSync(swept)).toBe(false);+ expect(result.droppedLocations).toEqual(['cursor']);++ rmSync(join(server.contentDir, '.cursor'), { recursive: true, force: true });+ rmSync(join(fixtureRoot, 'home', '.cursor'), { recursive: true, force: true });+ rmSync(destination, { recursive: true, force: true });+ });++ test('a built-in destination name is refused by naming the destination, not the source', async () => {+ const fromName = 'builtin-dest-original';+ seedSkill(server.contentDir, fromName);++ const response = await post('/api/skill/move-scope', {+ name: fromName,+ toName: 'open-knowledge',+ fromScope: 'project',+ toScope: 'global',+ });+ const result = await response.json();++ expect(response.status).toBe(400);+ expect(result.moveState).toBe('nothing-written');+ expect(result.title).toContain('"open-knowledge" is a built-in skill name');+ expect(result.title).not.toContain(fromName);+ expect(existsSync(join(server.contentDir, '.claude', 'skills', fromName, 'SKILL.md'))).toBe(+ true,+ );+ });++ test('a destination directory with no readable SKILL.md is not reported as a skill to delete', async () => {+ const fromName = 'stray-occupant-original';+ const toName = 'stray-occupant-renamed';+ seedSkill(server.contentDir, fromName);+ const occupant = join(fixtureRoot, 'home', '.claude', 'skills', toName);+ mkdirSync(join(occupant, 'references'), { recursive: true });+ writeFileSync(join(occupant, 'references', 'kept.txt'), 'Left behind by hand.');++ const response = await post('/api/skill/move-scope', {+ name: fromName,+ toName,+ fromScope: 'project',+ toScope: 'global',+ });+ const result = await response.json();++ expect(response.status).toBe(409);+ expect(result.moveState).toBe('nothing-written');+ expect(result.retentionLedger).toBeUndefined();+ expect(result.detail).toContain('no readable SKILL.md');+ expect(result.detail).not.toContain('Delete or rename it first');+ expect(readFileSync(join(occupant, 'references', 'kept.txt'), 'utf8')).toBe(+ 'Left behind by hand.',+ );+ });++ test('a retained intact source blocks the retry with the same verdict the failure gave', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory write permissions.');+ }+ const name = 'intact-source';+ const original = seedSkill(server.contentDir, name);+ const source = join(server.contentDir, '.claude', 'skills', name);+ const destination = join(fixtureRoot, 'home', '.claude', 'skills', name);+ chmodSync(source, 0o555);+ try {+ const response = await post('/api/skill/move-scope', {+ name,+ fromScope: 'project',+ toScope: 'global',+ });+ const result = await response.json();++ expect(response.status).toBe(500);+ expect(result.moveState).toBe('destination-retained');+ expect(result.sourceState).toBe('intact');+ expect(result.detail).toContain('UNLINK_FAILED');+ expect(result.detail).toContain('is unchanged at its original scope');+ expect(result.detail).not.toContain('recover missing source files');+ expect(result.detail).not.toContain('may be partially removed');+ expect(result.detail).not.toContain('could not record the retention');+ expect(readFileSync(join(source, 'SKILL.md'), 'utf8')).toBe(original);+ expect(readFileSync(join(destination, 'SKILL.md'), 'utf8')).toBe(original);++ expect(readdirSync(destination)).toEqual(['SKILL.md']);+ expect(retentionLedger()['global:intact-source']).toMatchObject({+ from: 'project:intact-source',+ to: 'global:intact-source',+ sourceState: 'intact',+ reason: 'UNLINK_FAILED',+ });++ const retry = await post('/api/skill/move-scope', {+ name,+ fromScope: 'project',+ toScope: 'global',+ });+ const retried = await retry.json();++ expect(retry.status).toBe(409);+ expect(retried.moveState).toBe('destination-retained-blocking');+ expect(retried.sourceState).toBe('intact');+ expect(retried.detail).toContain('a move of "project:intact-source"');+ expect(retried.detail).toContain('redundant duplicate');+ expect(retried.detail).toContain('remove it, then retry');+ expect(retried.detail).not.toContain('Do NOT delete it');+ expect(retried.detail).not.toContain('only copy');+ expect(retried.detail).not.toContain('Delete or rename it first');+ expect(readFileSync(join(destination, 'SKILL.md'), 'utf8')).toBe(original);+ } finally {+ chmodSync(source, 0o755);+ rmSync(destination, { recursive: true, force: true });+ }+ });++ test('a retention the server cannot write is disclosed, not silently swallowed', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory write permissions.');+ }+ const name = 'retention-write-refused';+ const home = join(fixtureRoot, 'home');+ const localDir = join(home, '.ok', 'local');+ const ledgerPath = join(localDir, 'skill-move-retained.json');+ const original = seedSkill(server.contentDir, name);+ const source = join(server.contentDir, '.claude', 'skills', name);+ const destination = join(home, '.claude', 'skills', name);+ mkdirSync(localDir, { recursive: true });+ if (!existsSync(ledgerPath)) {+ writeFileSync(ledgerPath, `${JSON.stringify({ schema: 1, retained: {} }, null, 2)}\n`);+ }+ const ledgerBefore = readFileSync(ledgerPath, 'utf8');+ chmodSync(source, 0o555);+ chmodSync(localDir, 0o555);+ try {+ const response = await post('/api/skill/move-scope', {+ name,+ fromScope: 'project',+ toScope: 'global',+ });+ const result = await response.json();++ expect(response.status).toBe(500);+ expect(result.moveState).toBe('destination-retained');+ expect(result.sourceState).toBe('intact');+ expect(result.detail).toContain('could not record the retention');+ expect(result.detail).toContain('ordinary name collision');+ expect(readFileSync(join(source, 'SKILL.md'), 'utf8')).toBe(original);+ expect(readdirSync(destination)).toEqual(['SKILL.md']);+ expect(readFileSync(join(destination, 'SKILL.md'), 'utf8')).toBe(original);+ expect(readFileSync(ledgerPath, 'utf8')).toBe(ledgerBefore);+ expect(JSON.parse(ledgerBefore).retained[`global:${name}`]).toBeUndefined();+ } finally {+ chmodSync(localDir, 0o755);+ chmodSync(source, 0o755);+ writeFileSync(ledgerPath, ledgerBefore);+ rmSync(destination, { recursive: true, force: true });+ rmSync(source, { recursive: true, force: true });+ }+ });++ test('a resolved retention is cleared, so a later collision on the name is reported as one', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory write permissions.');+ }+ const name = 'retention-lifecycle';+ seedSkill(server.contentDir, name);+ const source = join(server.contentDir, '.claude', 'skills', name);+ const destination = join(fixtureRoot, 'home', '.claude', 'skills', name);+ const move = () =>+ post('/api/skill/move-scope', { name, fromScope: 'project', toScope: 'global' });++ chmodSync(source, 0o555);+ try {+ expect((await move()).status).toBe(500);+ expect(retentionLedger()[`global:${name}`]).toBeDefined();+ } finally {+ chmodSync(source, 0o755);+ }++ rmSync(destination, { recursive: true, force: true });+ expect((await move()).status).toBe(200);+ expect(retentionLedger()[`global:${name}`]).toBeUndefined();++ seedSkill(server.contentDir, name);+ const collision = await move();+ const refused = await collision.json();++ expect(collision.status).toBe(409);+ expect(refused.moveState).toBe('nothing-written');+ expect(refused.sourceState).toBeUndefined();+ expect(refused.detail).toContain('Delete or rename it first');+ expect(refused.detail).not.toContain('retained');+ expect(refused.detail).not.toContain('only copy');+ });++ test('a record whose retained copy is gone does not warn about a copy that is not there', async () => {+ const name = 'retention-stale';+ seedSkill(server.contentDir, name);+ const elsewhere = join(fixtureRoot, 'home', '.cursor', 'skills', name);+ mkdirSync(elsewhere, { recursive: true });+ writeFileSync(+ join(elsewhere, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Occupant\n---\n\nElsewhere.\n`,+ );+ const ledger = join(fixtureRoot, 'home', '.ok', 'local', 'skill-move-retained.json');+ mkdirSync(dirname(ledger), { recursive: true });+ writeFileSync(+ ledger,+ JSON.stringify({+ schema: 1,+ retained: {+ [`global:${name}`]: {+ retainedAt: '2026-01-01T00:00:00.000Z',+ from: `project:${name}`,+ to: `global:${name}`,+ sourceState: 'lossy',+ reason: 'UNLINK_FAILED',+ },+ },+ }),+ );++ const response = await post('/api/skill/move-scope', {+ name,+ fromScope: 'project',+ toScope: 'global',+ });+ const refused = await response.json();++ expect(existsSync(join(fixtureRoot, 'home', '.claude', 'skills', name))).toBe(false);+ expect(response.status).toBe(409);+ expect(refused.moveState).toBe('nothing-written');+ expect(refused.detail).not.toContain('Do NOT delete it');+ expect(refused.detail).not.toContain('only copy');+ rmSync(elsewhere, { recursive: true, force: true });+ rmSync(ledger, { force: true });+ });++ test('a record whose retained copy was replaced does not vouch for the replacement', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory write permissions.');+ }+ const name = 'retention-superseded';+ seedSkill(server.contentDir, name);+ const source = join(server.contentDir, '.claude', 'skills', name);+ const destination = join(fixtureRoot, 'home', '.claude', 'skills', name);+ chmodSync(source, 0o555);+ try {+ expect(+ (await post('/api/skill/move-scope', { name, fromScope: 'project', toScope: 'global' }))+ .status,+ ).toBe(500);+ expect(retentionLedger()[`global:${name}`]).toBeDefined();+ } finally {+ chmodSync(source, 0o755);+ }++ rmSync(destination, { recursive: true, force: true });+ mkdirSync(destination, { recursive: true });+ writeFileSync(+ join(destination, 'SKILL.md'),+ `---\nname: ${name}\ndescription: An unrelated skill that happens to own the name\n---\n\nNot the retained copy.\n`,+ );++ const response = await post('/api/skill/move-scope', {+ name,+ fromScope: 'project',+ toScope: 'global',+ });+ const refused = await response.json();++ expect(response.status).toBe(409);+ expect(refused.moveState).toBe('nothing-written');+ expect(refused.sourceState).toBeUndefined();+ expect(refused.detail).toContain('Delete or rename it first');+ expect(refused.detail).not.toContain('retained');+ expect(refused.detail).not.toContain('remove it, then retry');+ expect(retentionLedger()[`global:${name}`]).toBeUndefined();++ rmSync(destination, { recursive: true, force: true });+ rmSync(source, { recursive: true, force: true });+ });++ test('an unreadable ledger refuses without telling the operator to delete the occupant', async () => {+ const name = 'retention-unreadable-ledger';+ seedSkill(server.contentDir, name);+ const destination = join(fixtureRoot, 'home', '.claude', 'skills', name);+ mkdirSync(destination, { recursive: true });+ writeFileSync(+ join(destination, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Occupant\n---\n\nOccupant body.\n`,+ );+ const ledger = join(fixtureRoot, 'home', '.ok', 'local', 'skill-move-retained.json');+ mkdirSync(dirname(ledger), { recursive: true });+ writeFileSync(ledger, '{"schema":1,"retained":{"global:');++ try {+ const response = await post('/api/skill/move-scope', {+ name,+ fromScope: 'project',+ toScope: 'global',+ });+ const refused = await response.json();++ expect(response.status).toBe(409);+ expect(refused.moveState).toBe('nothing-written');+ expect(refused.retentionLedger).toBe('unreadable');+ expect(refused.detail).toContain('could not read its retained-destination ledger');+ expect(refused.detail).toContain('Do NOT delete it before comparing it against the source');+ expect(refused.detail).not.toContain('Delete or rename it first');+ expect(readFileSync(ledger, 'utf8')).toBe('{"schema":1,"retained":{"global:');+ } finally {+ rmSync(destination, { recursive: true, force: true });+ rmSync(join(server.contentDir, '.claude', 'skills', name), { recursive: true, force: true });+ rmSync(ledger, { force: true });+ }+ });++ test('a retained copy the server cannot re-read is not reported as an ordinary collision', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce file read permissions.');+ }+ const name = 'retained-unreadable-copy';+ const source = join(server.contentDir, '.claude', 'skills', name);+ const destination = join(fixtureRoot, 'home', '.claude', 'skills', name);+ const destinationBundleFile = join(destination, 'references', 'data.md');+ mkdirSync(join(source, 'references'), { recursive: true });+ writeFileSync(+ join(source, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Bundle\n---\n\nBody.\n`,+ );+ writeFileSync(join(source, 'references', 'data.md'), 'Bundle body.\n');+ chmodSync(source, 0o555);+ try {+ const failed = await (+ await post('/api/skill/move-scope', { name, fromScope: 'project', toScope: 'global' })+ ).json();+ expect(failed.moveState).toBe('destination-retained');+ expect(retentionLedger()[`global:${name}`]).toBeDefined();++ chmodSync(destinationBundleFile, 0o000);+ const response = await post('/api/skill/move-scope', {+ name,+ fromScope: 'project',+ toScope: 'global',+ });+ const refused = await response.json();++ expect(response.status).toBe(409);+ expect(refused.moveState).toBe('nothing-written');+ expect(refused.retentionLedger).toBe('occupant-unverifiable');+ expect(refused.detail).toContain('has a record of retaining a copy under that name');+ expect(refused.detail).toContain(`from a move of "project:${name}"`);+ expect(refused.detail).toContain('Do NOT delete it before comparing it against the source');+ expect(refused.detail).not.toContain('Delete or rename it first');+ expect(refused.detail).toContain('(EACCES)');+ expect(refused.detail).not.toContain(fixtureRoot);+ expect(retentionLedger()[`global:${name}`]).toBeDefined();+ } finally {+ chmodSync(source, 0o755);+ if (existsSync(destinationBundleFile)) chmodSync(destinationBundleFile, 0o644);+ rmSync(destination, { recursive: true, force: true });+ rmSync(source, { recursive: true, force: true });+ }+ });++ test('a same-scope rename onto a retained copy carries the reconcile-first detail', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory permissions.');+ }+ const name = 'rename-onto-retained';+ const fromName = 'rename-onto-retained-source';+ const home = join(fixtureRoot, 'home');+ const source = join(server.contentDir, '.claude', 'skills', name);+ const bundle = join(source, 'references');+ const retainedCopy = join(home, '.claude', 'skills', name);+ const renameSource = join(home, '.claude', 'skills', fromName);+ seedSkill(server.contentDir, name);+ mkdirSync(bundle, { recursive: true });+ writeFileSync(join(bundle, 'data.md'), 'Bundle body.\n');+ try {+ const seeded = await (+ await withFsCopyCompletionObserver(+ (path) => path.endsWith(join('skills', name)),+ () => {+ chmodSync(bundle, 0o000);+ chmodSync(source, 0o555);+ },+ () => post('/api/skill/move-scope', { name, fromScope: 'project', toScope: 'global' }),+ )+ ).json();+ expect(seeded.moveState).toBe('destination-retained');+ expect(seeded.sourceState).toBe('unknown');+ expect(retentionLedger()[`global:${name}`]).toMatchObject({ sourceState: 'unknown' });+ chmodSync(bundle, 0o755);+ chmodSync(source, 0o755);+ rmSync(source, { recursive: true, force: true });++ mkdirSync(renameSource, { recursive: true });+ writeFileSync(+ join(renameSource, 'SKILL.md'),+ `---\nname: ${fromName}\ndescription: Bundle\n---\n\nBody.\n`,+ );+ const response = await post('/api/skill', { scope: 'global', fromName, toName: name });+ const refused = await response.json();++ expect(response.status).toBe(409);+ expect(refused.detail).toContain('Do NOT delete it before reconciling it against the source');+ expect(refused.detail).toContain(`a move of "project:${name}"`);+ expect(refused.detail).not.toContain('Delete or rename it first');+ expect(retentionLedger()[`global:${name}`]).toBeDefined();+ expect(existsSync(join(renameSource, 'SKILL.md'))).toBe(true);+ } finally {+ if (existsSync(bundle)) chmodSync(bundle, 0o755);+ if (existsSync(source)) chmodSync(source, 0o755);+ rmSync(source, { recursive: true, force: true });+ rmSync(retainedCopy, { recursive: true, force: true });+ rmSync(renameSource, { recursive: true, force: true });+ }+ });++ test('a collision at a non-default host root stays an ordinary delete-or-rename refusal', async () => {+ const name = 'collision-off-default-root';+ const home = join(fixtureRoot, 'home');+ const source = join(server.contentDir, '.claude', 'skills', name);+ const occupant = join(home, '.cursor', 'skills', name);+ const defaultDestination = join(home, '.claude', 'skills', name);+ seedSkill(server.contentDir, name);+ mkdirSync(occupant, { recursive: true });+ writeFileSync(+ join(occupant, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Occupant\n---\n\nOccupant body.\n`,+ );+ try {+ expect(existsSync(defaultDestination)).toBe(false);+ const response = await post('/api/skill/move-scope', {+ name,+ fromScope: 'project',+ toScope: 'global',+ });+ const refused = await response.json();++ expect(response.status).toBe(409);+ expect(refused.moveState).toBe('nothing-written');+ expect(refused.retentionLedger).toBeUndefined();+ expect(refused.detail).toBe('Delete or rename it first; this move will not overwrite it.');+ } finally {+ rmSync(join(home, '.cursor'), { recursive: true, force: true });+ rmSync(source, { recursive: true, force: true });+ }+ });++ test('an unreadable first-time occupant is never reported as delete-or-rename', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce file read permissions.');+ }+ const name = 'unreadable-first-collision';+ const source = join(server.contentDir, '.claude', 'skills', name);+ const destination = join(fixtureRoot, 'home', '.claude', 'skills', name);+ const destinationBundleFile = join(destination, 'references', 'data.md');+ mkdirSync(source, { recursive: true });+ writeFileSync(+ join(source, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Bundle\n---\n\nBody.\n`,+ );+ mkdirSync(join(destination, 'references'), { recursive: true });+ writeFileSync(+ join(destination, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Occupant\n---\n\nOccupant body.\n`,+ );+ writeFileSync(destinationBundleFile, 'Occupant bundle.\n');+ chmodSync(destinationBundleFile, 0o000);+ try {+ expect(retentionLedger()[`global:${name}`]).toBeUndefined();+ const response = await post('/api/skill/move-scope', {+ name,+ fromScope: 'project',+ toScope: 'global',+ });+ const refused = await response.json();++ expect(response.status).toBe(409);+ expect(refused.moveState).toBe('nothing-written');+ expect(refused.retentionLedger).toBe('occupant-unverifiable');+ expect(refused.detail).toContain('could not read it to determine whether it is a skill');+ expect(refused.detail).toContain('Verify it against the source before removing it');+ expect(refused.detail).not.toContain('Delete or rename it first');+ expect(refused.detail).toContain('(EACCES)');+ expect(refused.detail).not.toContain(fixtureRoot);+ expect(existsSync(join(source, 'SKILL.md'))).toBe(true);+ } finally {+ chmodSync(destinationBundleFile, 0o644);+ rmSync(destination, { recursive: true, force: true });+ rmSync(source, { recursive: true, force: true });+ }+ });++ test('a source that cannot be verified reports sourceState unknown, not a claim of no loss', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory read permissions.');+ }+ const name = 'unverifiable-source';+ seedSkill(server.contentDir, name);+ const source = join(server.contentDir, '.claude', 'skills', name);+ const bundle = join(source, 'references');+ mkdirSync(bundle, { recursive: true });+ writeFileSync(join(bundle, 'data.md'), 'Bundle body.\n');++ try {+ const response = await withFsCopyCompletionObserver(+ (path) => path.endsWith(join('skills', name)),+ () => {+ chmodSync(bundle, 0o000);+ chmodSync(source, 0o555);+ },+ () => post('/api/skill/move-scope', { name, fromScope: 'project', toScope: 'global' }),+ );+ const result = await response.json();++ expect(response.status).toBe(500);+ expect(result.moveState).toBe('destination-retained');+ expect(result.sourceState).toBe('unknown');+ expect(result.detail).toContain('whether any files were lost is unknown');+ expect(result.detail).not.toContain('no files were lost');+ expect(result.detail).not.toContain('may be partially removed');++ chmodSync(source, 0o755);+ chmodSync(bundle, 0o755);+ const retry = await post('/api/skill/move-scope', {+ name,+ fromScope: 'project',+ toScope: 'global',+ });+ const retried = await retry.json();++ expect(retry.status).toBe(409);+ expect(retried.moveState).toBe('destination-retained-blocking');+ expect(retried.sourceState).toBe('unknown');+ expect(retried.detail).toContain(`a move of "project:${name}"`);+ expect(retried.detail).toContain('Do NOT delete it');+ expect(retried.detail).not.toContain('redundant duplicate');+ expect(retried.detail).not.toContain('Delete or rename it first');+ } finally {+ chmodSync(source, 0o755);+ chmodSync(bundle, 0o755);+ rmSync(source, { recursive: true, force: true });+ }+ });++ test('an unreadable destination copy is cleaned up before the source is touched', async () => {+ const name = 'precommit-unreadable';+ const original = seedSkill(server.contentDir, name);+ const source = join(server.contentDir, '.claude', 'skills', name);+ const destination = join(fixtureRoot, 'home', '.claude', 'skills', name);++ const response = await withFsCopyCompletionObserver(+ (path) => path.endsWith(join('skills', name)),+ () => {+ rmSync(join(destination, 'SKILL.md'));+ },+ () => post('/api/skill/move-scope', { name, fromScope: 'project', toScope: 'global' }),+ );+ const result = await response.json();++ expect(response.status).toBe(500);+ expect(result.moveState).toBe('destination-removed');+ expect(result.detail).toContain('was not touched and is unchanged');+ expect(readFileSync(join(source, 'SKILL.md'), 'utf8')).toBe(original);+ expect(existsSync(destination)).toBe(false);+ });++ test('an unreadable destination copy whose cleanup fails is reported as stray, source untouched', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory write permissions.');+ }+ const name = 'precommit-stray';+ const original = seedSkill(server.contentDir, name);+ const source = join(server.contentDir, '.claude', 'skills', name);+ writeFileSync(join(source, 'note.txt'), 'Keep me.');+ const destination = join(fixtureRoot, 'home', '.claude', 'skills', name);++ try {+ const response = await withFsCopyCompletionObserver(+ (path) => path.endsWith(join('skills', name)),+ () => {+ rmSync(join(destination, 'SKILL.md'));+ chmodSync(destination, 0o555);+ },+ () => post('/api/skill/move-scope', { name, fromScope: 'project', toScope: 'global' }),+ );+ const result = await response.json();++ expect(response.status).toBe(500);+ expect(result.moveState).toBe('destination-stray');+ expect(result.detail).toContain('UNLINK_FAILED');+ expect(result.detail).toContain('Inspect the destination before retrying');+ expect(result.detail).toContain('was not touched and is unchanged');+ expect(readFileSync(join(source, 'SKILL.md'), 'utf8')).toBe(original);+ expect(readFileSync(join(source, 'note.txt'), 'utf8')).toBe('Keep me.');+ expect(readFileSync(join(destination, 'note.txt'), 'utf8')).toBe('Keep me.');+ } finally {+ if (existsSync(destination)) chmodSync(destination, 0o755);+ rmSync(destination, { recursive: true, force: true });+ rmSync(source, { recursive: true, force: true });+ }+ });++ test('an unparseable copied frontmatter reports the parse reason, not just the error kind', async () => {+ const fromName = 'fm-parse-original';+ const toName = 'fm-parse-renamed';+ const original = seedSkill(server.contentDir, fromName);+ const destination = join(fixtureRoot, 'home', '.claude', 'skills', toName);++ const response = await withFsCopyCompletionObserver(+ (path) => path.endsWith(join('skills', toName)),+ () => {+ writeFileSync(join(destination, 'SKILL.md'), '---\nname: [unclosed\n---\n\nBody.\n');+ },+ () =>+ post('/api/skill/move-scope', {+ name: fromName,+ toName,+ fromScope: 'project',+ toScope: 'global',+ }),+ );+ const result = await response.json();++ expect(response.status).toBe(400);+ expect(result.moveState).toBe('destination-removed');+ expect(result.detail).toMatch(/parse_failed \(frontmatter region unparseable: .+\)/);+ expect(existsSync(destination)).toBe(false);+ expect(+ readFileSync(join(server.contentDir, '.claude', 'skills', fromName, 'SKILL.md'), 'utf8'),+ ).toBe(original);+ });++ test('a frontmatter region too large to re-key reports both its size and the limit', async () => {+ const fromName = 'oversized-fm-original';+ const toName = 'oversized-fm-renamed';+ const source = join(server.contentDir, '.claude', 'skills', fromName);+ const destination = join(fixtureRoot, 'home', '.claude', 'skills', toName);+ const filler = Array.from(+ { length: 1600 },+ (_, index) => `filler${String(index).padStart(4, '0')}: ${'x'.repeat(48)}`,+ ).join('\n');+ const oversized = `---\nname: ${fromName}\ndescription: Bundle\n${filler}\n---\n\nBody.\n`;+ mkdirSync(source, { recursive: true });+ writeFileSync(join(source, 'SKILL.md'), oversized);++ try {+ const response = await post('/api/skill/move-scope', {+ name: fromName,+ toName,+ fromScope: 'project',+ toScope: 'global',+ });+ const result = await response.json();++ expect(response.status).toBe(400);+ expect(result.moveState).toBe('destination-removed');+ const sized = /region_too_large \(frontmatter region too large: (\d+) > (\d+) bytes\)/.exec(+ result.detail,+ );+ expect(sized).not.toBeNull();+ expect(Number(sized?.[1])).toBeGreaterThan(65536);+ expect(sized?.[2]).toBe('65536');+ expect(result.detail).toContain(`project:${fromName}`);+ expect(result.detail).toContain('was not removed');+ expect(readFileSync(join(source, 'SKILL.md'), 'utf8')).toBe(oversized);+ expect(existsSync(destination)).toBe(false);+ } finally {+ rmSync(source, { recursive: true, force: true });+ rmSync(destination, { recursive: true, force: true });+ }+ });++ test('an unexpected copy failure directs callers to inspect both locations without claiming rollback', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory write permissions.');+ }+ const fromName = 'copy-failed-original';+ const toName = 'copy-failed-renamed';+ const original = seedSkill(server.contentDir, fromName);+ const destinationRoot = join(fixtureRoot, 'home', '.claude', 'skills');+ chmodSync(destinationRoot, 0o555);+ try {+ const response = await post('/api/skill/move-scope', {+ name: fromName,+ toName,+ fromScope: 'project',+ toScope: 'global',+ });+ const result = await response.json();+ expect(response.status).toBe(500);+ expect(result.moveState).toBe('partially-applied');+ expect(result.detail).toContain(`project:${fromName}`);+ expect(result.detail).toContain(`global:${toName}`);+ expect(result.detail).toContain('before retrying');+ expect(+ readFileSync(join(server.contentDir, '.claude', 'skills', fromName, 'SKILL.md'), 'utf8'),+ ).toBe(original);+ expect(existsSync(join(destinationRoot, toName))).toBe(false);+ } finally {+ chmodSync(destinationRoot, 0o755);+ }+ });++ test('a source-removal failure reports every in-place copy the sweep deleted', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory write permissions.');+ }+ const name = 'retained-placements';+ const home = join(fixtureRoot, 'home');+ const source = join(home, '.claude', 'skills', name);+ const swept = join(home, '.lmstudio', 'skills', name);+ const hostable = join(home, '.cursor', 'skills', name);+ const body = `---\nname: ${name}\ndescription: Bundle\n---\n\nBody.\n`;+ mkdirSync(source, { recursive: true });+ writeFileSync(join(source, 'SKILL.md'), body);+ expect(+ (+ await post('/api/skill/install', {+ name,+ scope: 'global',+ add: ['lm-studio', 'cursor'],+ mode: 'copy',+ })+ ).status,+ ).toBe(200);+ expect(readFileSync(join(swept, 'SKILL.md'), 'utf8')).toBe(body);+ expect(readFileSync(join(hostable, 'SKILL.md'), 'utf8')).toBe(body);+ const destination = join(server.contentDir, '.claude', 'skills', name);+ chmodSync(source, 0o555);+ try {+ const response = await post('/api/skill/move-scope', {+ name,+ fromScope: 'global',+ toScope: 'project',+ });+ const result = await response.json();++ expect(response.status).toBe(500);+ expect(result.moveState).toBe('destination-retained');+ expect(existsSync(swept)).toBe(false);+ expect(existsSync(hostable)).toBe(false);+ expect(result.droppedLocations).toEqual(['cursor', 'lm-studio']);+ } finally {+ chmodSync(source, 0o755);+ rmSync(destination, { recursive: true, force: true });+ rmSync(source, { recursive: true, force: true });+ rmSync(hostable, { recursive: true, force: true });+ rmSync(join(home, '.lmstudio'), { recursive: true, force: true });+ }+ });++ test('a global-to-project move drops hosts the destination scope cannot host', async () => {+ const name = 'lmstudio-only';+ const home = join(fixtureRoot, 'home');+ const source = join(home, '.lmstudio', 'skills', name);+ mkdirSync(source, { recursive: true });+ writeFileSync(+ join(source, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Bundle\n---\n\nBody.\n`,+ );++ let movedRel: string | undefined;+ try {+ const response = await post('/api/skill/move-scope', {+ name,+ fromScope: 'global',+ toScope: 'project',+ });+ const result = await response.json();+ movedRel = result.path;++ expect(response.status).toBe(200);+ expect(result.droppedLocations).toContain('lm-studio');+ expect(existsSync(source)).toBe(false);+ expect(existsSync(join(server.contentDir, '.lmstudio', 'skills', name))).toBe(false);+ } finally {+ if (movedRel !== undefined) {+ rmSync(join(server.contentDir, movedRel), { recursive: true, force: true });+ }+ rmSync(join(home, '.lmstudio'), { recursive: true, force: true });+ }+ });++ test('a duplicate that fails before creating the destination does not claim a started copy', async (ctx) => {+ if (process.platform === 'win32' || process.getuid?.() === 0) {+ ctx.skip('Requires a non-root POSIX user to enforce directory write permissions.');+ }+ const name = 'duplicate-mkdir-blocked';+ const home = join(fixtureRoot, 'home');+ const source = join(home, '.claude', 'skills', name);+ const agentsRoot = join(home, '.agents');+ mkdirSync(source, { recursive: true });+ writeFileSync(+ join(source, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Bundle\n---\n\nBody.\n`,+ );+ mkdirSync(agentsRoot, { recursive: true });+ chmodSync(agentsRoot, 0o555);+ try {+ const response = await post('/api/skill/duplicate', {+ name,+ toName: `${name}-copy`,+ scope: 'global',+ });+ const result = await response.json();++ expect(response.status).toBe(500);+ expect(existsSync(join(agentsRoot, 'skills'))).toBe(false);+ expect(result.detail ?? '').not.toContain('was started at');+ expect(result.detail ?? '').not.toContain('was created at');+ } finally {+ chmodSync(agentsRoot, 0o755);+ rmSync(agentsRoot, { recursive: true, force: true });+ rmSync(source, { recursive: true, force: true });+ }+ });++ test('an invalid source name is refused with a machine-readable nothing-written state', async () => {+ const response = await post('/api/skill/move-scope', {+ name: 'Invalid Name',+ fromScope: 'project',+ toScope: 'global',+ });+ const result = await response.json();++ expect(response.status).toBe(400);+ expect(result.moveState).toBe('nothing-written');+ expect(result.droppedLocations).toEqual([]);+ });++ test('an invalid destination name is refused without touching the source', async () => {+ const name = 'invalid-toname-source';+ const original = seedSkill(server.contentDir, name);++ const response = await post('/api/skill/move-scope', {+ name,+ toName: 'Invalid Name',+ fromScope: 'project',+ toScope: 'global',+ });+ const result = await response.json();++ expect(response.status).toBe(400);+ expect(result.moveState).toBe('nothing-written');+ expect(result.droppedLocations).toEqual([]);+ expect(+ readFileSync(join(server.contentDir, '.claude', 'skills', name, 'SKILL.md'), 'utf8'),+ ).toBe(original);+ });+});diff --git a/packages/app/tests/stress/skills-sidebar-open.e2e.ts b/packages/app/tests/stress/skills-sidebar-open.e2e.tsindex fba743d5d..69f01c9d4 100644--- a/packages/app/tests/stress/skills-sidebar-open.e2e.ts+++ b/packages/app/tests/stress/skills-sidebar-open.e2e.ts@@ -347,6 +347,129 @@ test('shift-click ranges and cmd-click toggles drag the whole selection to the o.toBe(`${names[0]}:global,${names[2]}:global`);});+test('UI wiring against routed failures: a wholly failed bulk move reports one summary naming every skill, cleared by a successful retry', async ({+ page,+ api,+ workerServer,+}) => {+ await api.testReset();+ const names = ['bulk-retained-a', 'bulk-retained-b'];+ for (const n of names) {+ await createSkill(workerServer.baseURL, n, `# Bulk ${n}\n`);+ }++ await page.goto('/');+ await expandSkillsDock(page);+ await skillRow(page, `Project/${names[0]}/`).waitFor({ timeout: 15_000 });++ let failMoves = true;+ await page.route('**/api/skill/move-scope', async (route) => {+ if (!failMoves) {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ scope: 'global', droppedLocations: [] }),+ });+ return;+ }+ const sent = route.request().postDataJSON() as { name?: string } | null;+ const skill = sent?.name ?? '';+ await route.fulfill({+ status: 409,+ contentType: 'application/json',+ body: JSON.stringify({+ type: 'urn:ok:error:conflict',+ title: `A global skill named "${skill}" already exists.`,+ status: 409,+ moveState: 'nothing-written',+ retentionLedger: 'occupant-unverifiable',+ detail: `A directory exists at .claude/skills/${skill} and this server could not read it to determine whether it is a skill (EACCES). Verify it against the source before removing it. This call wrote nothing.`,+ droppedLocations: [],+ }),+ });+ });++ const selectedPaths = () =>+ page.evaluate(() => {+ const out: string[] = [];+ const walk = (root: Document | ShadowRoot) => {+ for (const e of root.querySelectorAll('[data-item-path][data-item-selected="true"]'))+ out.push(e.getAttribute('data-item-path') ?? '');+ for (const e of root.querySelectorAll('*')) if (e.shadowRoot) walk(e.shadowRoot);+ };+ walk(document);+ return out.sort().join(',');+ });++ const selectBoth = async () => {+ await skillRow(page, `Project/${names[0]}/`).click();+ await skillRow(page, `Project/${names[0]}/`).click({ modifiers: ['ControlOrMeta'] });+ await skillRow(page, `Project/${names[1]}/`).click({ modifiers: ['ControlOrMeta'] });+ await expect.poll(selectedPaths, { timeout: 15_000 }).toContain(`Project/${names[1]}/`);+ };++ const dragSelectionToGlobal = () =>+ page.evaluate(+ ({ src, dst }) => {+ const find = (p: string) => {+ let el: Element | null = null;+ const walk = (root: Document | ShadowRoot) => {+ for (const e of root.querySelectorAll(`[data-item-path="${p}"]`)) el = e;+ for (const e of root.querySelectorAll('*')) if (e.shadowRoot) walk(e.shadowRoot);+ };+ walk(document);+ return el;+ };+ const source = find(src);+ const target = find(dst);+ if (!source || !target) throw new Error('drag rows missing');+ const dt = new DataTransfer();+ const fire = (el: Element, type: string) =>+ el.dispatchEvent(+ new DragEvent(type, {+ bubbles: true,+ composed: true,+ cancelable: true,+ dataTransfer: dt,+ }),+ );+ fire(source, 'dragstart');+ fire(target, 'dragover');+ fire(target, 'drop');+ fire(source, 'dragend');+ },+ { src: `Project/${names[0]}/`, dst: 'Global/' },+ );++ const toasts = page.locator('[data-sonner-toast]');+ const retainedGuidanceTexts = async () => {+ const texts = await toasts.allInnerTexts();+ return texts.filter((text) => /compare|don't delete|do not delete/i.test(text));+ };+ const retainedGuidanceToasts = async () => (await retainedGuidanceTexts()).length;++ await selectBoth();+ await dragSelectionToGlobal();++ await expect.poll(retainedGuidanceToasts, { timeout: 20_000 }).toBe(1);+ const summary = ((await retainedGuidanceTexts())[0] ?? '').replace(/\s+/g, ' ');+ expect(summary).toContain(names[0]);+ expect(summary).toContain(names[1]);+ expect(summary).not.toMatch(/moved \d+ skills?/i);+ expect((await toasts.allInnerTexts()).join(' | ')).not.toMatch(/moved \d+ skills? to/i);+ await expect(skillRow(page, `Project/${names[0]}/`)).toHaveCount(1);+ await expect(skillRow(page, `Project/${names[1]}/`)).toHaveCount(1);++ failMoves = false;+ await selectBoth();+ await dragSelectionToGlobal();++ await expect+ .poll(async () => (await toasts.allInnerTexts()).join(' | '), { timeout: 30_000 })+ .toMatch(/moved 2 skills to global/i);+ await expect.poll(retainedGuidanceToasts, { timeout: 20_000 }).toBe(0);+});+test('shift+arrow walks visible rows through read-only plugin skills; drag moves only movable members', async ({page,api,diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 27f6479df..0cb8c232c 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1263,8 +1263,13 @@ export {InstallSkillRequestSchema,type InstallSkillSuccess,InstallSkillSuccessSchema,+ interpretSkillMoveFailure,isBranchNotFoundGitError,isLoginFixableGitAuthError,+ isSkillMoveRetainedDestinationCode,+ isSkillMoveStateCode,+ isSkillRetentionLedgerCode,+ isSkillSourceStateCode,isValidBranchName,isWriteWarningKind,type LifecycleStatus,@@ -1327,6 +1332,7 @@ export {MetricsReconciliationSuccessSchema,type MetricsWatcherRecentSuccess,MetricsWatcherRecentSuccessSchema,+ normalizeApiWarnings,type OrphanEntry,OrphanEntrySchema,type OrphanHint,@@ -1463,9 +1469,15 @@ export {ShareTargetStatusResponseSchema,type ShareTargetStatusVerdict,ShareTargetStatusVerdictSchema,+ SKILL_AUTHORING_WARNING_CODES,SKILL_INSTALL_WARNING_CODES,+ SKILL_MOVE_RETAINED_DESTINATION,+ SKILL_MOVE_STATE_CODES,SKILL_NAME_REGEX,+ SKILL_RETENTION_LEDGER_CODES,+ SKILL_SOURCE_STATE_CODES,SKILLS_IMPORT_BULK_MAX,+ type SkillAuthoringWarningCode,type SkillDeleteSuccess,SkillDeleteSuccessSchema,type SkillDuplicateRequest,@@ -1521,12 +1533,14 @@ export {type SkillInstallWarningCode,type SkillLocationId,SkillLocationIdSchema,+ type SkillMoveFailureOutcome,type SkillMoveRequest,SkillMoveRequestSchema,type SkillMoveScopeRequest,SkillMoveScopeRequestSchema,type SkillMoveScopeSuccess,SkillMoveScopeSuccessSchema,+ type SkillMoveStateCode,type SkillMoveSuccess,SkillMoveSuccessSchema,type SkillOrigin,@@ -1547,6 +1561,7 @@ export {SkillRestoreRequestSchema,type SkillRestoreSuccess,SkillRestoreSuccessSchema,+ type SkillRetentionLedgerCode,type SkillRevertRequest,SkillRevertRequestSchema,type SkillRevertSuccess,@@ -1554,6 +1569,7 @@ export {SkillRootPathSchema,type SkillScope,SkillScopeSchema,+ type SkillSourceStateCode,type SkillsImportBulkRequest,SkillsImportBulkRequestSchema,type SkillsImportBulkSuccess,@@ -1667,6 +1683,7 @@ export {TrashCleanupRequestSchema,type TrashCleanupSuccess,TrashCleanupSuccessSchema,+ UNREADABLE_WARNINGS_TEXT,type UploadAssetSuccess,UploadAssetSuccessSchema,type UploadRequest,diff --git a/packages/core/src/schemas/api/tags-search.test.ts b/packages/core/src/schemas/api/tags-search.test.tsindex d7cebf77b..12a01de50 100644--- a/packages/core/src/schemas/api/tags-search.test.ts+++ b/packages/core/src/schemas/api/tags-search.test.ts@@ -1,5 +1,18 @@import { describe, expect, test } from 'vitest';-import { TemplateGetSuccessSchema, TemplatePayloadSchema } from './tags-search.ts';+import {+ interpretSkillMoveFailure,+ isSkillMoveRetainedDestinationCode,+ isSkillMoveStateCode,+ isSkillRetentionLedgerCode,+ isSkillSourceStateCode,+ normalizeApiWarnings,+ SKILL_MOVE_RETAINED_DESTINATION,+ SKILL_MOVE_STATE_CODES,+ SKILL_RETENTION_LEDGER_CODES,+ SKILL_SOURCE_STATE_CODES,+ TemplateGetSuccessSchema,+ TemplatePayloadSchema,+} from './tags-search.ts';const validPayload = (scope: 'local' | 'inherited') => ({name: 'daily-journal',@@ -10,6 +23,53 @@ const validPayload = (scope: 'local' | 'inherited') => ({body: '## Morning\n',});+describe('API warning compatibility', () => {+ test('absent warnings remain compatible with older servers', () => {+ expect(normalizeApiWarnings(undefined)).toEqual([]);+ expect(normalizeApiWarnings([])).toEqual([]);+ });++ test.each([null, 'warning', { warning: 'recovery copy deleted' }, [null]])(+ 'malformed present warnings remain visibly unverified: %j',+ (value) => {+ expect(normalizeApiWarnings(value).join(' ')).toContain('treat this result as unverified');+ },+ );++ test('unreadable entries do not erase readable warnings', () => {+ const warnings = normalizeApiWarnings(['A recovery copy was deleted.', null]);+ expect(warnings[0]).toBe('A recovery copy was deleted.');+ expect(warnings[1]).toContain('treat this result as unverified');+ expect(normalizeApiWarnings(['A recovery copy was deleted.'])).toEqual([warnings[0]]);+ });+});++describe('move failure compatibility', () => {+ test.each([+ {},+ { moveState: 'nothing-written' },+ { moveState: 'nothing-written', retentionLedger: 'unreadable' },+ { moveState: 'destination-retained', sourceState: 'intact' },+ { moveState: 'destination-retained-blocking', sourceState: 'lossy' },+ { moveState: 'destination-removed' },+ ])('preserves coherent outcomes: %j', (body) => {+ expect(interpretSkillMoveFailure(body)).toEqual({ kind: 'coherent', ...body });+ });++ test.each([+ { moveState: 'future-outcome' },+ { sourceState: 'intact' },+ { retentionLedger: 'future-reason' },+ { moveState: 'destination-retained' },+ { moveState: 'destination-retained', sourceState: 'future-state' },+ { moveState: 'destination-removed', sourceState: 'intact' },+ { moveState: 'destination-retained', sourceState: 'intact', retentionLedger: 'unreadable' },+ { moveState: 'destination-retained', sourceState: 'intact', retentionLedger: 'future-reason' },+ ])('does not treat incomplete or contradictory peer data as coherent: %j', (body) => {+ expect(interpretSkillMoveFailure(body).kind).toBe('unverified');+ });+});+describe('TemplatePayloadSchema.scope', () => {test.each(['local', 'inherited'] as const)('accepts scope=%s', (scope) => {const result = TemplatePayloadSchema.safeParse(validPayload(scope));@@ -47,3 +107,79 @@ describe('TemplateGetSuccessSchema', () => {expect(result.success).toBe(true);});});++describe('skill move-state, source-state and retention-ledger code guards', () => {+ test('the move-state enum carries exactly the seven documented codes', () => {+ expect([...SKILL_MOVE_STATE_CODES]).toEqual([+ 'nothing-written',+ 'destination-removed',+ 'destination-stray',+ 'destination-retained',+ 'destination-retained-blocking',+ 'destination-unreadable',+ 'partially-applied',+ ]);+ for (const code of SKILL_MOVE_STATE_CODES) {+ expect(isSkillMoveStateCode(code)).toBe(true);+ }+ });++ test('the source-state enum carries exactly the three documented codes', () => {+ expect([...SKILL_SOURCE_STATE_CODES]).toEqual(['intact', 'lossy', 'unknown']);+ for (const code of SKILL_SOURCE_STATE_CODES) {+ expect(isSkillSourceStateCode(code)).toBe(true);+ }+ });++ test('the retention-ledger enum carries exactly the two documented codes', () => {+ expect([...SKILL_RETENTION_LEDGER_CODES]).toEqual(['unreadable', 'occupant-unverifiable']);+ for (const code of SKILL_RETENTION_LEDGER_CODES) {+ expect(isSkillRetentionLedgerCode(code)).toBe(true);+ }+ });++ test('every move-state code answers the retained-destination question explicitly', () => {+ expect(Object.keys(SKILL_MOVE_RETAINED_DESTINATION).sort()).toEqual(+ [...SKILL_MOVE_STATE_CODES].sort(),+ );+ expect(+ [...SKILL_MOVE_STATE_CODES].filter((code) => isSkillMoveRetainedDestinationCode(code)),+ ).toEqual(['destination-retained', 'destination-retained-blocking']);+ });++ test('all three guards reject near-miss spellings and non-string values', () => {+ const rejected: unknown[] = [+ '',+ ' ',+ 'INTACT',+ 'Intact',+ 'destination_retained',+ 'destination-retained ',+ 'destination-retained-blocked',+ 'partially applied',+ 'UNREADABLE',+ 'occupant_unverifiable',+ 'occupant-unverifiable ',+ null,+ undefined,+ 0,+ true,+ ['intact'],+ { code: 'intact' },+ ];+ for (const value of rejected) {+ expect(isSkillMoveStateCode(value)).toBe(false);+ expect(isSkillSourceStateCode(value)).toBe(false);+ expect(isSkillRetentionLedgerCode(value)).toBe(false);+ }+ });++ test('the three enums share no member, so a code identifies which field it came from', () => {+ const all = [+ ...SKILL_MOVE_STATE_CODES,+ ...SKILL_SOURCE_STATE_CODES,+ ...SKILL_RETENTION_LEDGER_CODES,+ ];+ expect(new Set(all).size).toBe(all.length);+ });+});diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.tsindex 07ae85434..f9a8f92cc 100644--- a/packages/core/src/schemas/api/tags-search.ts+++ b/packages/core/src/schemas/api/tags-search.ts@@ -355,11 +355,22 @@ export const SkillPutRequestSchema = z.strict() satisfies StandardSchemaV1;export type SkillPutRequest = z.infer<typeof SkillPutRequestSchema>;+export const SKILL_AUTHORING_WARNING_CODES = [+ 'skill-name-vendor-word',+ 'skill-body-too-long',+] as const;+export type SkillAuthoringWarningCode = (typeof SKILL_AUTHORING_WARNING_CODES)[number];+const authoringWarningCodesField = z.array(z.enum(SKILL_AUTHORING_WARNING_CODES)).meta({+ description:+ 'Machine-readable codes aligned 1:1 with `warnings` (`warnings[i]` is the display text for `warningCodes[i]`).',+});+export const SkillPutSuccessSchema = z.object({path: z.string().min(1),created: z.boolean(),warnings: z.array(z.string()),+ warningCodes: authoringWarningCodesField,}).strict() satisfies StandardSchemaV1;export type SkillPutSuccess = z.infer<typeof SkillPutSuccessSchema>;@@ -385,6 +396,7 @@ export const SkillReimportSuccessSchema = zupstreamBody: z.string().optional(),gitTracked: z.boolean().optional(),warnings: z.array(z.string()),+ warningCodes: authoringWarningCodesField,}).strict() satisfies StandardSchemaV1;export type SkillReimportSuccess = z.infer<typeof SkillReimportSuccessSchema>;@@ -409,10 +421,19 @@ export const SkillRevertSuccessSchema = z.strict() satisfies StandardSchemaV1;export type SkillRevertSuccess = z.infer<typeof SkillRevertSuccessSchema>;+const BOOKKEEPING_WARNING_CLAUSE =+ 'This member also carries the one bookkeeping failure that does not undo the operation: the content change landed, but a state file this server keeps beside it refused to be rewritten because it could not be read, so the install or import records still describe the old state until an operator repairs that file. Absent when there is nothing to report; a server that predates this member omits it, so treat its absence as no warning rather than as an error.';+export const SkillDeleteSuccessSchema = z.object({existed: z.boolean(),path: z.string().min(1),+ warnings: z+ .array(z.string())+ .optional()+ .meta({+ description: `Present when this delete removed a directory a retention record ties to a recovery copy an earlier failed move kept, whose source was never verified unchanged — either because this server verified the deleted directory against the copy that record describes, or because it could not read the directory and so could not confirm either way. Each entry says which of the two it is; neither claims more than the check established. ${BOOKKEEPING_WARNING_CLAUSE}`,+ }),}).strict() satisfies StandardSchemaV1;export type SkillDeleteSuccess = z.infer<typeof SkillDeleteSuccessSchema>;@@ -435,6 +456,12 @@ export const SkillMoveSuccessSchema = zfrom: z.string().min(1),to: z.string().min(1),committed: z.boolean(),+ warnings: z+ .array(z.string())+ .optional()+ .meta({+ description: `Present when the rename itself completed but something beside it did not. ${BOOKKEEPING_WARNING_CLAUSE}`,+ }),}).strict() satisfies StandardSchemaV1;export type SkillMoveSuccess = z.infer<typeof SkillMoveSuccessSchema>;@@ -442,6 +469,10 @@ export type SkillMoveSuccess = z.infer<typeof SkillMoveSuccessSchema>;export const SkillMoveScopeRequestSchema = z.object({name: z.string(),+ toName: z.string().optional().meta({+ description:+ 'Name for the skill at the destination scope; defaults to `name`. The SKILL.md `name` frontmatter is rewritten to match.',+ }),fromScope: SkillScopeSchema,toScope: SkillScopeSchema,...agentIdentityFields,@@ -450,12 +481,130 @@ export const SkillMoveScopeRequestSchema = z.strict() satisfies StandardSchemaV1;export type SkillMoveScopeRequest = z.infer<typeof SkillMoveScopeRequestSchema>;+export const SKILL_MOVE_STATE_CODES = [+ 'nothing-written',+ 'destination-removed',+ 'destination-stray',+ 'destination-retained',+ 'destination-retained-blocking',+ 'destination-unreadable',+ 'partially-applied',+] as const;+export type SkillMoveStateCode = (typeof SKILL_MOVE_STATE_CODES)[number];++export function isSkillMoveStateCode(value: unknown): value is SkillMoveStateCode {+ return typeof value === 'string' && (SKILL_MOVE_STATE_CODES as readonly string[]).includes(value);+}++export const SKILL_SOURCE_STATE_CODES = ['intact', 'lossy', 'unknown'] as const;+export type SkillSourceStateCode = (typeof SKILL_SOURCE_STATE_CODES)[number];++export function isSkillSourceStateCode(value: unknown): value is SkillSourceStateCode {+ return (+ typeof value === 'string' && (SKILL_SOURCE_STATE_CODES as readonly string[]).includes(value)+ );+}++export const SKILL_RETENTION_LEDGER_CODES = ['unreadable', 'occupant-unverifiable'] as const;+export type SkillRetentionLedgerCode = (typeof SKILL_RETENTION_LEDGER_CODES)[number];++export function isSkillRetentionLedgerCode(value: unknown): value is SkillRetentionLedgerCode {+ return (+ typeof value === 'string' && (SKILL_RETENTION_LEDGER_CODES as readonly string[]).includes(value)+ );+}++export const SKILL_MOVE_RETAINED_DESTINATION: Record<SkillMoveStateCode, boolean> = {+ 'nothing-written': false,+ 'destination-removed': false,+ 'destination-stray': false,+ 'destination-retained': true,+ 'destination-retained-blocking': true,+ 'destination-unreadable': false,+ 'partially-applied': false,+};++export function isSkillMoveRetainedDestinationCode(value: SkillMoveStateCode): boolean {+ return SKILL_MOVE_RETAINED_DESTINATION[value];+}++interface SkillMoveFailureFields {+ moveState?: SkillMoveStateCode;+ sourceState?: SkillSourceStateCode;+ retentionLedger?: SkillRetentionLedgerCode;+}++export type SkillMoveFailureOutcome =+ | ({ kind: 'coherent' } & SkillMoveFailureFields)+ | ({ kind: 'unverified' } & SkillMoveFailureFields);++export function interpretSkillMoveFailure(body: unknown): SkillMoveFailureOutcome {+ const fields: Record<string, unknown> =+ typeof body === 'object' && body !== null ? (body as Record<string, unknown>) : {};+ const rawMoveState = fields.moveState;+ const rawSourceState = fields.sourceState;+ const rawRetentionLedger = fields.retentionLedger;+ if (+ rawMoveState === undefined &&+ rawSourceState === undefined &&+ rawRetentionLedger === undefined+ ) {+ return { kind: 'coherent' };+ }+ const moveState = isSkillMoveStateCode(rawMoveState) ? rawMoveState : undefined;+ const sourceState = isSkillSourceStateCode(rawSourceState) ? rawSourceState : undefined;+ const retentionLedger = isSkillRetentionLedgerCode(rawRetentionLedger)+ ? rawRetentionLedger+ : undefined;+ const decoded: SkillMoveFailureFields = {+ ...(moveState !== undefined ? { moveState } : {}),+ ...(sourceState !== undefined ? { sourceState } : {}),+ ...(retentionLedger !== undefined ? { retentionLedger } : {}),+ };+ const unrecognized =+ (rawMoveState !== undefined && moveState === undefined) ||+ (rawSourceState !== undefined && sourceState === undefined) ||+ (rawRetentionLedger !== undefined && retentionLedger === undefined);+ if (unrecognized || moveState === undefined) return { kind: 'unverified', ...decoded };+ const coherent = isSkillMoveRetainedDestinationCode(moveState)+ ? sourceState !== undefined && retentionLedger === undefined+ : moveState === 'nothing-written'+ ? sourceState === undefined+ : sourceState === undefined && retentionLedger === undefined;+ return coherent ? { kind: 'coherent', ...decoded } : { kind: 'unverified', ...decoded };+}++export const UNREADABLE_WARNINGS_TEXT =+ 'The server reported warnings in a shape this build does not recognise; treat this result as unverified.';++export function normalizeApiWarnings(value: unknown): string[] {+ if (value === undefined) return [];+ const unreadable = UNREADABLE_WARNINGS_TEXT;+ if (!Array.isArray(value)) return [unreadable];+ const warnings = value.filter((entry): entry is string => typeof entry === 'string');+ return warnings.length === value.length ? warnings : [...warnings, unreadable];+}+export const SkillMoveScopeSuccessSchema = z.object({scope: SkillScopeSchema,path: z.string().optional(),+ droppedLocations: z.array(z.string()).default([]).meta({+ description:+ "Locations the skill occupied at the source that were removed and not re-created at the destination: the `agents` hub and custom roots, which projection does not cover. Entries are install location ids, so they can be passed straight back as an install `add` list with `scope` set to the destination scope; custom roots resolve against that scope's base.",+ }),+ warnings: z+ .array(z.string())+ .optional()+ .meta({+ description: `Present when the move itself completed but something beside it did not. ${BOOKKEEPING_WARNING_CLAUSE}`,+ }),})- .strict() satisfies StandardSchemaV1;+ .strict()+ .meta({+ description:+ 'Scope-move result. Rename paths deliberately do not emit authoring warnings, consistent with same-scope rename and duplicate. Content-authoring and import responses carry those warnings and their codes. The Skills Studio client parses `droppedLocations` off the wire but deliberately does not render it yet; how a human is told what was removed is an open product decision.',+ }) satisfies StandardSchemaV1;export type SkillMoveScopeSuccess = z.infer<typeof SkillMoveScopeSuccessSchema>;export const SkillDuplicateRequestSchema = z@@ -1011,6 +1160,7 @@ export const SkillImportBulkResultSchema = zname: z.string().optional(),collisionRenamedFrom: z.string().optional(),warnings: z.array(z.string()),+ warningCodes: authoringWarningCodesField,error: z.string().optional(),}).loose() satisfies StandardSchemaV1;@@ -1046,6 +1196,7 @@ export const SkillReimportBulkResultSchema = zstatus: z.enum(['updated', 'up-to-date', 'not-found', 'failed']),source: z.string().optional(),warnings: z.array(z.string()),+ warningCodes: authoringWarningCodesField,error: z.string().optional(),}).loose() satisfies StandardSchemaV1;@@ -1090,6 +1241,7 @@ export const SkillImportSuccessSchema = zwarnings: z.array(z.string()).meta({ description: 'Non-fatal import warnings, such as skipped unsupported files.' }),+ warningCodes: authoringWarningCodesField,}).loose() satisfies StandardSchemaV1;export type SkillImportSuccess = z.infer<typeof SkillImportSuccessSchema>;diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.mdindex ca4ef8bb8..01a341656 100644--- a/packages/server/assets/skills/project/SKILL.md+++ b/packages/server/assets/skills/project/SKILL.md@@ -25,8 +25,8 @@ OpenKnowledge (OK) is a markdown-CRDT collaboration platform exposed via MCP. Th## Tool index — 21 tools (router; the MCP tool descriptions carry each tool's full contract)-- **Reads** — `exec` (primary; `cat`/`ls`/`grep`/… on a read-only filesystem, plus frontmatter/backlink/history enrichment; one command or one pipe, not a shell), `search` (ranked BM25 + recency), `history` (doc versions), `links` (`kind: backlinks|forward|dead|orphans|hubs|suggest`, or an array for one call), `skills` (search + read: `query` → skills.sh; omit `name` to LIST managed (Project + Global); `name` READs one — by `name`+`scope`, never path), `config` (resolved config), `palette` (authoring forms + `html preview` starters + theme tokens; `palette({ components })` for JSX schemas), `preview_url` (browser preview URL on demand), `share_link` (GitHub-substrate share URL; read-only, errors without a GitHub remote), `lint` (markdown-lint violations: `document` for one doc, omit for the project; `fix: true` with `document` auto-fixes fixable rules in place — attributed, live in the preview; the rest need `edit`/`write`), `audit` (every lint violation + broken internal link in one read-only report, by source file with lines; `path` scopes; for link VALIDATION use this, not `links`; caveats in `references/linking.md`). **Read `ran` on successful `lint`/`audit` results to see which enabled source families were selected. A family absent from `ran` was not checked, and `[]` means no checks were selected at all.**-- **Writes** — four native CRUD verbs, polymorphic over `document` / `folder` / `template` / `skill` / `asset` (pass EXACTLY ONE target, nested under its address key): `write` (create/overwrite; `write({ skill: {…} })` authors a skill as a REAL folder at the project's default skill home — live immediately for that folder's agent), `edit` (body find/replace/frontmatter merge-patch; no asset), `delete` (remove), `move` (move/rename, rewrites referrers; a skill also takes `scope`/`toScope` for Project↔Global — history resets, re-`install`). Output mirrors the input key; the preview envelope (`previewUrl`, `warning`) stays top-level. Plus `install` (WHERE a `skill` lives: `add`/`remove` locations additively — editor ids, `agents`, or custom roots; `mode` + `convert` re-form ONLY the locations named; `source` moves the real folder. The source folder IS the skill — no "uninstall everywhere"; a skill dies only via `delete`), `import` (acquire a skill-dir into `add`'s locations; scripts never run), `checkpoint` (named version), and `restore_version` (roll back). A folder's frontmatter is open-shape and self-only (does NOT cascade); templates are what new docs start with.+- **Reads** — `exec` (primary; `cat`/`ls`/`grep`/… on a read-only filesystem, plus frontmatter/backlink/history enrichment; one command or one pipe, not a shell), `search` (ranked BM25 + recency), `history` (doc versions), `links` (`kind: backlinks|forward|dead|orphans|hubs|suggest`, or an array for one call), `skills` (search + read: `query` → skills.sh; omit `name` to LIST managed (Project + Global); `name` READs one — by `name`+`scope`, never path), `config` (resolved config), `palette` (authoring forms + `html preview` starters + theme tokens; `palette({ components })` for JSX schemas), `preview_url` (preview URL on demand), `share_link` (GitHub-substrate share URL; read-only, errors without a GitHub remote), `lint` (markdown-lint violations: `document` for one doc, omit for the project; `fix: true` with `document` auto-fixes fixable rules in place — attributed, live in the preview; the rest need `edit`/`write`), `audit` (every lint violation + broken internal link in one report, by source file with lines; `path` scopes; for link VALIDATION use this, not `links`; caveats in `references/linking.md`). **Read `ran` on successful `lint`/`audit` results: a family absent from `ran` was not checked, and `[]` means no checks were selected.**+- **Writes** — four native CRUD verbs, polymorphic over `document` / `folder` / `template` / `skill` / `asset` (pass EXACTLY ONE target, nested under its address key): `write` (create/overwrite; `write({ skill: {…} })` authors a skill as a REAL folder at the project's default skill home — live immediately for that folder's agent), `edit` (body find/replace/frontmatter merge-patch; no asset), `delete`, `move` (move/rename, rewrites referrers; a skill also takes `scope`/`toScope` for Project↔Global: history resets, only what the destination level can host re-projects; the rest is removed at source, returned as `droppedLocations` (success: re-add with `install`)). Output mirrors the input key; the preview envelope (`previewUrl`, `warning`) stays top-level. Plus `install` (WHERE a `skill` lives: `add`/`remove` locations additively — editor ids, `agents`, or custom roots; `mode` + `convert` re-form ONLY the locations named; `source` moves the real folder. The source folder IS the skill — no "uninstall everywhere"; a skill dies only via `delete`), `import` (acquire a skill-dir into `add`'s locations; scripts never run), `checkpoint` (named version), and `restore_version` (roll back). A folder's frontmatter is open-shape and self-only (does NOT cascade); templates are what new docs start with.- **Conflicts** — `conflicts` (`kind: list|content`), `resolve_conflict` (write a resolution; commits for Git-index conflicts only; destructive). See `references/conflict-resolution.md`.**Self-correcting on misuse:** constraints JSON Schema can't express ("exactly one target", "`find` needs a `replace`", body-XOR-frontmatter) return `isError: true` with a one-line corrective shape. Read it and retry with that shape; don't guess.@@ -126,7 +126,7 @@ Onboarding a repo that already has content: `references/onboard-existing-repo.md## Capabilities beyond this skill-OK does more than this skill describes, and what it does changes between releases. When a request implies something not covered here, read rather than guess:+OK does more than this skill describes, and it changes between releases. Not covered here? Read rather than guess:- **Docs** — <https://openknowledge.ai/docs>- **Source** — <https://github.com/inkeep/open-knowledge>diff --git a/packages/server/src/agent-presence.test.ts b/packages/server/src/agent-presence.test.tsindex b77da2403..9ce3a8260 100644--- a/packages/server/src/agent-presence.test.ts+++ b/packages/server/src/agent-presence.test.ts@@ -318,6 +318,7 @@ describe('AgentPresenceBroadcaster', () => {const dir = import.meta.dirname ?? new URL('.', import.meta.url).pathname;const files = ['api-extension.ts',+ 'content/skills-write.ts',...readdirSync(resolve(dir, 'http')).filter((file) => file.endsWith('-routes.ts')).sort()diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 621a13693..bf1a4db68 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -254,7 +254,11 @@ import { catchErrors } from './http/catch-errors.ts';import { createCommentRoutes } from './http/comment-routes.ts';import { createConfigSystemRoutes } from './http/config-system-routes.ts';import { createDocumentRoutes } from './http/document-routes.ts';-import { errorResponse, type HttpErrorStatus } from './http/error-response.ts';+import {+ type ErrorExtensions,+ errorResponse,+ type HttpErrorStatus,+} from './http/error-response.ts';import {createFileOpsRoutes,type ManagedRenameRewrittenDoc,@@ -412,6 +416,9 @@ export const MANAGED_RENAME_ORIGIN = {const log = getLogger('api');+const storeRefusalDetail = (err: unknown): string | undefined =>+ err instanceof Error && err.message.startsWith('Refusing to rewrite ') ? err.message : undefined;+function safeDocPath(docName: string, contentRoot: string): { path: string } | { error: string } {if (!docName || docName.includes('..') || docName.includes('\0')) {return { error: 'Invalid document name.' };@@ -3205,22 +3212,36 @@ export function createApiExtension(void contentFilter?.rebuildIgnorePatterns().catch(() => {});}, 120_000);}+ function invalidateSkillCatalog(): void {+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();+ }+ function settleSkillCatalog(): void {+ invalidateSkillCatalog();+ signalChannel?.('files');+ }+ type OkArtifactFlush = 'flushed' | 'unavailable' | 'failed';let okArtifactFlushChain: Promise<void> = Promise.resolve();function scheduleOkArtifactFlush(context: string): void {bumpSkillsCatalogGen();okArtifactFlushChain = okArtifactFlushChain- .then(() => commitOkArtifactWrite(context))+ .then(async () => {+ await commitOkArtifactWrite(context);+ }).catch(() => {});}- async function commitOkArtifactWrite(context: string): Promise<void> {- if (!flushContributors) return;+ async function commitOkArtifactWrite(context: string): Promise<OkArtifactFlush> {+ if (!flushContributors) return 'unavailable';try {await flushContributors();+ return 'flushed';} catch (flushErr) {log.warn({ context, err: flushErr },`[${context}] flushContributors failed; attribution stays queued for the next flush`,);+ return 'failed';}}@@ -3892,14 +3913,19 @@ export function createApiExtension(function isValidSkillName(name: string): boolean {return Boolean(name) && name.length <= 64 && SKILL_NAME_REGEX.test(name);}- function validateSkillName(name: string, res: ServerResponse, handler: string): boolean {+ function validateSkillName(+ name: string,+ res: ServerResponse,+ handler: string,+ extensions?: ErrorExtensions,+ ): boolean {if (!isValidSkillName(name)) {errorResponse(res,400,'urn:ok:error:invalid-request','Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).',- { handler },+ { handler, ...(extensions ? { extensions } : {}) },);return false;}@@ -4200,13 +4226,12 @@ export function createApiExtension(return scope === 'global' ? skillsHome : projectDir;}- async function uninstallSkillFromHostDirs(+ function removeSkillFromHostDirs(base: string,name: string,scope: 'project' | 'global',- opts: { purge?: { contentHash: string } } = {},- ): Promise<boolean> {- const installed = await removeSkillInstall(base, name);+ opts: { purge?: { contentHash: string } },+ ): void {const scanBaseForPurge = scope === 'project' ? contentDir : skillsHome;if (opts.purge !== undefined) {reverseProjectSkill(name, base, skillProjectionEditorIds(scope), skillProjectionRoots(scope));@@ -4218,7 +4243,7 @@ export function createApiExtension()) {tracedRmSync(dir, { recursive: true, force: true });}- return installed !== null;+ return;}if (!existsSync(resolve(resolveSkillsRoot(scope), name, 'SKILL.md'))) {const entry = (@@ -4247,11 +4272,20 @@ export function createApiExtension(targets: [...skillProjectionEditorIds(scope)],roots: skillProjectionRoots(scope),});- return installed !== null;+ return;}}reverseProjectSkill(name, base, skillProjectionEditorIds(scope), skillProjectionRoots(scope));- return installed !== null;+ }++ async function uninstallSkillFromHostDirs(+ base: string,+ name: string,+ scope: 'project' | 'global',+ opts: { purge?: { contentHash: string } } = {},+ ): Promise<boolean> {+ removeSkillFromHostDirs(base, name, scope, opts);+ return (await removeSkillInstall(base, name)) !== null;}function resolveSkillsList(@@ -4470,6 +4504,7 @@ export function createApiExtension('Failed to uninstall skill.',{handler: 'skill-uninstall',+ ...(storeRefusalDetail(e) !== undefined ? { detail: storeRefusalDetail(e) } : {}),cause: e,},);@@ -5170,6 +5205,8 @@ export function createApiExtension(derivedDocumentIndex,contentFilter,bumpSkillsCatalogGen,+ settleSkillCatalog,+ invalidateSkillCatalog,scheduleDeferredIgnoreRebuild,recordDerivedDocumentBestEffort,getPrincipal,diff --git a/packages/server/src/api-skill-store-refusal.test.ts b/packages/server/src/api-skill-store-refusal.test.tsnew file mode 100644index 000000000..0de7b4bc3--- /dev/null+++ b/packages/server/src/api-skill-store-refusal.test.ts@@ -0,0 +1,289 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import type { IncomingMessage, ServerResponse } from 'node:http';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { Readable } from 'node:stream';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { createApiExtension } from './api-extension.test-helper.ts';++interface CapturedResponse {+ status: number;+ body: Record<string, unknown>;+}++let home: string;+let contentDir: string;++const globalSkillDir = (name: string): string => join(home, '.ok', 'skills', name);+const globalHostSkillDir = (name: string): string => join(home, '.agents', 'skills', name);+const projectSkillDir = (name: string): string => join(contentDir, '.ok', 'skills', name);+const markerPath = (base: string): string => join(base, '.ok', 'local', 'installed-skills.json');+const retentionPath = (base: string): string =>+ join(base, '.ok', 'local', 'skill-move-retained.json');+const lockPath = (base: string): string => join(base, '.ok', 'skills-lock.json');++const TRUNCATED_MARKER = '{"schema":1,"skills":{"trip-log":{"hosts":["cla';++function writeSkill(dir: string, name: string, body = 'hello'): void {+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: d\n---\n\n${body}\n`);+}++function seedFile(path: string, contents: string): void {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, contents, 'utf-8');+}++function seedRetention(base: string, key: string, record: Record<string, unknown>): void {+ seedFile(+ retentionPath(base),+ `${JSON.stringify({ schema: 1, retained: { [key]: record } }, null, 2)}\n`,+ );+}++function retentionKeys(base: string): string[] {+ if (!existsSync(retentionPath(base))) return [];+ const parsed = JSON.parse(readFileSync(retentionPath(base), 'utf-8')) as {+ retained?: Record<string, unknown>;+ };+ return Object.keys(parsed.retained ?? {});+}++const retainedRecord = {+ retainedAt: '2026-01-01T00:00:00.000Z',+ from: 'project:trip-log',+ to: 'global:trip-log',+ sourceState: 'lossy',+ reason: 'UNLINK_FAILED',+ retainedContentHash: 'deadbeef',+};++function makeReq(method: string, url: string, body: unknown): IncomingMessage {+ const raw = body === undefined ? '' : JSON.stringify(body);+ const readable = Readable.from(+ raw === '' ? [] : [Buffer.from(raw)],+ ) as unknown as IncomingMessage;+ readable.method = method;+ readable.url = url;+ readable.headers = { host: 'localhost' };+ return readable;+}++function makeRes(): { res: ServerResponse; captured: { status: number; raw: string } } {+ const captured = { status: 0, raw: '' };+ const res = {+ writeHead(status: number) {+ captured.status = status;+ },+ end(body?: string) {+ captured.raw = body ?? '';+ },+ } as unknown as ServerResponse;+ return { res, captured };+}++async function callApi(method: string, url: string, body?: unknown): Promise<CapturedResponse> {+ const ext = createApiExtension({+ hocuspocus: {+ documents: new Map(),+ closeConnections() {},+ unloadDocument: async () => {},+ debouncer: { isDebounced: () => false, executeNow: async () => undefined },+ } as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],+ sessionManager: {+ closeSession: async () => {},+ closeAllForDoc: async () => {},+ } as unknown as Parameters<typeof createApiExtension>[0]['sessionManager'],+ contentDir,+ projectDir: contentDir,+ homeDirOverride: home,+ getFileIndex: () => new Map(),+ });+ const req = makeReq(method, url, body);+ const { res, captured } = makeRes();+ await (+ ext as {+ onRequest: (ctx: { request: IncomingMessage; response: ServerResponse }) => Promise<void>;+ }+ ).onRequest({ request: req, response: res });+ return {+ status: captured.status,+ body: captured.raw === '' ? {} : (JSON.parse(captured.raw) as Record<string, unknown>),+ };+}++const warningText = (body: Record<string, unknown>): string =>+ ((body.warnings as string[] | undefined) ?? []).join(' ');++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'ok-store-refusal-home-'));+ contentDir = mkdtempSync(join(tmpdir(), 'ok-store-refusal-proj-'));+ mkdirSync(join(home, '.agents'), { recursive: true });+});++afterEach(() => {+ rmSync(home, { recursive: true, force: true });+ rmSync(contentDir, { recursive: true, force: true });+});++describe('a bookkeeping refusal does not turn a completed skill delete into a 500', () => {+ test('the delete reports the deletion it performed and warns about the bookkeeping', async () => {+ writeSkill(globalSkillDir('trip-log'), 'trip-log');+ seedFile(markerPath(home), TRUNCATED_MARKER);++ const res = await callApi('DELETE', '/api/skill?name=trip-log&scope=global');++ expect(res.status).toBe(200);+ expect(res.body.existed).toBe(true);+ expect(existsSync(globalSkillDir('trip-log'))).toBe(false);+ expect(warningText(res.body)).toContain('installed-skills.json');+ });++ test('the retry after a refusal converges instead of 500-ing forever', async () => {+ writeSkill(globalSkillDir('trip-log'), 'trip-log');+ seedFile(markerPath(home), TRUNCATED_MARKER);++ await callApi('DELETE', '/api/skill?name=trip-log&scope=global');+ const retry = await callApi('DELETE', '/api/skill?name=trip-log&scope=global');++ expect(retry.status).toBe(200);+ expect(retry.body.existed).toBe(false);+ });++ test('the retained-destination record is still cleared when the marker refuses', async () => {+ writeSkill(globalSkillDir('trip-log'), 'trip-log');+ seedRetention(home, 'global:trip-log', retainedRecord);+ seedFile(markerPath(home), TRUNCATED_MARKER);++ const res = await callApi('DELETE', '/api/skill?name=trip-log&scope=global');++ expect(res.status).toBe(200);+ expect(retentionKeys(home)).toEqual([]);+ });++ test('an unreadable marker reaches the caller as an errno, not as a parse failure', async () => {+ writeSkill(globalSkillDir('trip-log'), 'trip-log');+ mkdirSync(markerPath(home), { recursive: true });++ const res = await callApi('DELETE', '/api/skill?name=trip-log&scope=global');++ expect(res.status).toBe(200);+ expect(warningText(res.body)).toContain('EISDIR');+ });+});++describe('a delete that could not read the directory it removed says so', () => {+ test('an unreadable occupant with a retained record reaches the caller as a hedged warning', async () => {+ const dir = globalSkillDir('trip-log');+ mkdirSync(dir, { recursive: true });+ mkdirSync(join(dir, 'SKILL.md'), { recursive: true });+ seedRetention(home, 'global:trip-log', retainedRecord);++ const res = await callApi('DELETE', '/api/skill?name=trip-log&scope=global');++ expect(res.status).toBe(200);+ expect(warningText(res.body)).toContain('could not confirm');+ });+});++describe('a bookkeeping refusal does not turn a completed skill rename into a 500', () => {+ test('the rename reports the move it performed and warns about the bookkeeping', async () => {+ writeSkill(globalSkillDir('trip-log'), 'trip-log');+ seedFile(markerPath(home), TRUNCATED_MARKER);++ const res = await callApi('POST', '/api/skill', {+ scope: 'global',+ fromName: 'trip-log',+ toName: 'travel-log',+ });++ expect(res.status).toBe(200);+ expect(existsSync(globalSkillDir('travel-log'))).toBe(true);+ expect(existsSync(globalSkillDir('trip-log'))).toBe(false);+ expect(warningText(res.body)).toContain('installed-skills.json');+ });++ test('a lock file that refuses to rewrite does not hide the rename either', async () => {+ writeSkill(globalSkillDir('trip-log'), 'trip-log');+ seedFile(lockPath(home), '{"schema":1,"skills":{"trip-log":{"sour');++ const res = await callApi('POST', '/api/skill', {+ scope: 'global',+ fromName: 'trip-log',+ toName: 'travel-log',+ });++ expect(res.status).toBe(200);+ expect(existsSync(globalSkillDir('travel-log'))).toBe(true);+ expect(warningText(res.body)).toContain('skills-lock.json');+ });+});++describe('a bookkeeping refusal does not report a completed cross-scope move as partial', () => {+ test('the move reports success with a bookkeeping warning', async () => {+ writeSkill(projectSkillDir('trip-log'), 'trip-log');+ seedFile(markerPath(contentDir), TRUNCATED_MARKER);++ const res = await callApi('POST', '/api/skill/move-scope', {+ name: 'trip-log',+ fromScope: 'project',+ toScope: 'global',+ });++ expect(res.status).toBe(200);+ expect(existsSync(globalHostSkillDir('trip-log'))).toBe(true);+ expect(existsSync(projectSkillDir('trip-log'))).toBe(false);+ expect(warningText(res.body)).toContain('installed-skills.json');+ });+});++describe('a bookkeeping refusal names the file the operator has to repair', () => {+ test('the uninstall failure detail names the refusing path', async () => {+ writeSkill(globalSkillDir('trip-log'), 'trip-log');+ mkdirSync(markerPath(home), { recursive: true });++ const res = await callApi('POST', '/api/skill/uninstall', {+ name: 'trip-log',+ scope: 'global',+ });++ expect(res.status).toBe(500);+ expect(String(res.body.detail)).toContain('installed-skills.json');+ });+});++describe('a retained record beside a manifest-less directory is not described as unreadable', () => {+ test('the refusal does not claim the directory could not be read', async () => {+ writeSkill(projectSkillDir('trip-log'), 'trip-log');+ mkdirSync(globalHostSkillDir('trip-log'), { recursive: true });+ writeFileSync(join(globalHostSkillDir('trip-log'), 'notes.md'), 'kept\n');+ seedRetention(home, 'global:trip-log', retainedRecord);++ const res = await callApi('POST', '/api/skill/move-scope', {+ name: 'trip-log',+ fromScope: 'project',+ toScope: 'global',+ });++ expect(res.status).toBe(409);+ expect(String(res.body.detail)).not.toContain('could not read');+ expect(res.body.retentionLedger).toBe('occupant-unverifiable');+ });+});++describe('a within-level rename is not refused with cross-scope wording', () => {+ test('the collision detail names no operation the caller did not invoke', async () => {+ writeSkill(globalSkillDir('trip-log'), 'trip-log');+ mkdirSync(join(globalSkillDir('travel-log'), 'SKILL.md'), { recursive: true });++ const res = await callApi('POST', '/api/skill', {+ scope: 'global',+ fromName: 'trip-log',+ toName: 'travel-log',+ });++ expect(res.status).toBe(409);+ expect(String(res.body.detail)).toContain('could not read it');+ expect(String(res.body.detail)).not.toContain('cross-scope');+ });+});diff --git a/packages/server/src/content/skills-write.test.ts b/packages/server/src/content/skills-write.test.tsindex ba44b990f..13d94b9c7 100644--- a/packages/server/src/content/skills-write.test.ts+++ b/packages/server/src/content/skills-write.test.ts@@ -90,6 +90,7 @@ describe('applySkillWrite', () => {expect(result.ok).toBe(true);if (result.ok) {expect(result.warnings.some((w) => w.includes('"claude"'))).toBe(true);+ expect(result.warningCodes).toEqual(['skill-name-vendor-word']);}});@@ -115,7 +116,26 @@ describe('applySkillWrite', () => {frontmatter: fm('big'),});expect(result.ok).toBe(true);- if (result.ok) expect(result.warnings.some((w) => w.includes('600 lines'))).toBe(true);+ if (result.ok) {+ expect(result.warnings.some((w) => w.includes('600 lines'))).toBe(true);+ expect(result.warningCodes).toEqual(['skill-body-too-long']);+ }+ });++ test('two warnings on one write keep codes positionally aligned with their text', () => {+ const result = applySkillWrite({+ skillsRoot,+ name: 'claude-helper',+ body: Array.from({ length: 600 }, (_, i) => `line ${i}`).join('\n'),+ frontmatter: fm('claude-helper'),+ });+ expect(result.ok).toBe(true);+ if (result.ok) {+ expect(result.warningCodes).toEqual(['skill-name-vendor-word', 'skill-body-too-long']);+ expect(result.warnings).toHaveLength(2);+ expect(result.warnings[0]).toContain('"claude"');+ expect(result.warnings[1]).toContain('600 lines');+ }});});diff --git a/packages/server/src/content/skills-write.ts b/packages/server/src/content/skills-write.tsindex cad0715f5..17c9c49d7 100644--- a/packages/server/src/content/skills-write.ts+++ b/packages/server/src/content/skills-write.ts@@ -1,8 +1,12 @@-import { existsSync, readdirSync, statSync } from 'node:fs';-import { isAbsolute, join, normalize, sep } from 'node:path';+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import { basename, dirname, isAbsolute, join, normalize, sep } from 'node:path';import {+ applyPatchToFm,containsXmlTag,+ detectFmRegion,+ type FmEditError,SKILL_NAME_REGEX,+ type SkillAuthoringWarningCode,type SkillFrontmatter,} from '@inkeep/open-knowledge-core';import { stringify as stringifyYaml } from 'yaml';@@ -26,11 +30,22 @@ const BODY_SOFT_MAX_LINES = 500;const SKILL_FILE = 'SKILL.md';type SkillWriteResult =- | { ok: true; path: string; created: boolean; warnings: string[] }+ | {+ ok: true;+ path: string;+ created: boolean;+ warnings: string[];+ warningCodes: SkillAuthoringWarningCode[];+ }| { ok: false; error: { code: string; message: string } };export type SkillContentResult =- | { ok: true; content: string; warnings: string[] }+ | {+ ok: true;+ content: string;+ warnings: string[];+ warningCodes: SkillAuthoringWarningCode[];+ }| { ok: false; error: { code: string; message: string } };type SkillDeleteResult =@@ -75,19 +90,32 @@ export function composeSkillContent(input: {const content = `---\n${fmYaml}---\n${input.body}`;const warnings: string[] = [];+ const warningCodes: SkillAuthoringWarningCode[] = [];const discouraged = DISCOURAGED_NAME_WORDS.filter((w) => input.name.includes(w));if (discouraged.length > 0) {warnings.push(`Skill name contains ${discouraged.map((w) => `"${w}"`).join(', ')} — Anthropic's authoring guidance discourages vendor words in skill names.`,);+ warningCodes.push('skill-name-vendor-word');}const lineCount = input.body.split('\n').length;if (lineCount > BODY_SOFT_MAX_LINES) {warnings.push(`SKILL.md body is ${lineCount} lines — keep it under ${BODY_SOFT_MAX_LINES} for performance (every line is a recurring token cost). Move detail into one-level-deep references/.`,);+ warningCodes.push('skill-body-too-long');}- return { ok: true, content, warnings };+ return { ok: true, content, warnings, warningCodes };+}++function sweepStaleTmpSiblings(targetPath: string): void {+ const dir = dirname(targetPath);+ const prefix = `${basename(targetPath)}.tmp.`;+ try {+ for (const entry of readdirSync(dir)) {+ if (entry.startsWith(prefix)) tracedUnlinkSync(join(dir, entry));+ }+ } catch {}}export function applySkillWrite(input: WriteSkillInput): SkillWriteResult {@@ -100,7 +128,7 @@ export function applySkillWrite(input: WriteSkillInput): SkillWriteResult {frontmatter: input.frontmatter,});if (!composed.ok) return { ok: false, error: composed.error };- const { content, warnings } = composed;+ const { content, warnings, warningCodes } = composed;const { skillDir, filePath } = skillPaths(input.skillsRoot, input.name);@@ -118,6 +146,7 @@ export function applySkillWrite(input: WriteSkillInput): SkillWriteResult {const created = !existsSync(filePath);+ sweepStaleTmpSiblings(filePath);const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;try {tracedWriteFileSync(tmpPath, content, 'utf-8');@@ -135,7 +164,53 @@ export function applySkillWrite(input: WriteSkillInput): SkillWriteResult {};}- return { ok: true, path: relPathOf(input.skillsRoot, filePath), created, warnings };+ return {+ ok: true,+ path: relPathOf(input.skillsRoot, filePath),+ created,+ warnings,+ warningCodes,+ };+}++export type SkillDirNameSyncResult =+ | { ok: true }+ | { ok: false; stage: 'read'; cause: unknown }+ | { ok: false; stage: 'patch'; error: FmEditError }+ | { ok: false; stage: 'write'; cause: unknown };++export function applySkillDirNameSync(input: {+ skillDir: string;+ toName: string;+ skillMd?: string;+}): SkillDirNameSyncResult {+ const filePath = join(input.skillDir, SKILL_FILE);+ let raw: string;+ if (input.skillMd !== undefined) {+ raw = input.skillMd;+ } else {+ try {+ raw = readFileSync(filePath, 'utf-8');+ } catch (cause) {+ return { ok: false, stage: 'read', cause };+ }+ }+ const { fenced, body } = detectFmRegion(raw);+ // presence-exempt: no CRDT write, no agent identity+ const renamed = applyPatchToFm(fenced, { name: input.toName });+ if (!renamed.ok) return { ok: false, stage: 'patch', error: renamed.error };+ sweepStaleTmpSiblings(filePath);+ const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;+ try {+ tracedWriteFileSync(tmpPath, `${renamed.nextFenced}${body}`, 'utf-8');+ tracedRenameSync(tmpPath, filePath);+ } catch (cause) {+ try {+ tracedUnlinkSync(tmpPath);+ } catch {}+ return { ok: false, stage: 'write', cause };+ }+ return { ok: true };}export const BUNDLE_FILE_MAX_BYTES = 256 * 1024;@@ -284,6 +359,7 @@ export function applySkillBundleFileWrite(},};}+ sweepStaleTmpSiblings(abs);const tmpPath = `${abs}.tmp.${process.pid}.${Date.now()}`;try {if (typeof payload === 'string') tracedWriteFileSync(tmpPath, payload, 'utf-8');diff --git a/packages/server/src/fm-edit-error.test.ts b/packages/server/src/fm-edit-error.test.tsnew file mode 100644index 000000000..af992f41c--- /dev/null+++ b/packages/server/src/fm-edit-error.test.ts@@ -0,0 +1,70 @@+import type { FmEditError } from '@inkeep/open-knowledge-core';+import { describe, expect, it } from 'vitest';+import { describeFmEditError } from './fm-edit-error.ts';++const CASES: ReadonlyArray<{ label: string; error: FmEditError; expected: string }> = [+ {+ label: 'invalid_value names the key and the reason',+ error: { kind: 'invalid_value', key: 'allowed-tools', reason: 'expected a list of strings' },+ expected: 'invalid_value (allowed-tools: expected a list of strings)',+ },+ {+ label: 'reserved_key quotes the key',+ error: { kind: 'reserved_key', key: 'name' },+ expected: "reserved_key ('name' is reserved)",+ },+ {+ label: 'unknown_key quotes the key',+ error: { kind: 'unknown_key', key: 'colour' },+ expected: "unknown_key ('colour' is not a recognized key)",+ },+ {+ label: 'duplicate_target quotes the key',+ error: { kind: 'duplicate_target', key: 'description' },+ expected: "duplicate_target ('description' appears more than once)",+ },+ {+ label: 'reorder_mismatch renders expected before got, in order',+ error: { kind: 'reorder_mismatch', expected: ['name', 'description'], got: ['description'] },+ expected: 'reorder_mismatch (expected: name, description; got: description)',+ },+ {+ label: 'region_too_large carries the measured bytes and the limit',+ error: { kind: 'region_too_large', bytes: 70_144, limit: 65_536 },+ expected: 'region_too_large (frontmatter region too large: 70144 > 65536 bytes)',+ },+ {+ label: 'parse_failed carries the parser reason',+ error: { kind: 'parse_failed', reason: 'unexpected end of stream' },+ expected: 'parse_failed (frontmatter region unparseable: unexpected end of stream)',+ },+ {+ label: 'invalid_path joins a populated path with dots',+ error: { kind: 'invalid_path', path: ['metadata', 0, 'id'], reason: 'not a string' },+ expected: 'invalid_path (metadata.0.id: not a string)',+ },+ {+ label: 'invalid_path renders an empty path as __path__',+ error: { kind: 'invalid_path', path: [], reason: 'not an object' },+ expected: 'invalid_path (__path__: not an object)',+ },+];++describe('describeFmEditError', () => {+ for (const { label, error, expected } of CASES) {+ it(label, () => {+ expect(describeFmEditError(error)).toBe(expected);+ });+ }++ it('renders every variant distinctly so a collapsed mapper cannot pass', () => {+ const rendered = CASES.map((entry) => describeFmEditError(entry.error));+ expect(new Set(rendered).size).toBe(CASES.length);+ });++ it('leads every message with the variant kind', () => {+ for (const { error } of CASES) {+ expect(describeFmEditError(error).startsWith(`${error.kind} (`)).toBe(true);+ }+ });+});diff --git a/packages/server/src/fm-edit-error.ts b/packages/server/src/fm-edit-error.tsnew file mode 100644index 000000000..30b9521a7--- /dev/null+++ b/packages/server/src/fm-edit-error.ts@@ -0,0 +1,26 @@+import type { FmEditError } from '@inkeep/open-knowledge-core';++export function describeFmEditError(error: FmEditError): string {+ switch (error.kind) {+ case 'invalid_value':+ return `${error.kind} (${error.key}: ${error.reason})`;+ case 'reserved_key':+ return `${error.kind} ('${error.key}' is reserved)`;+ case 'unknown_key':+ return `${error.kind} ('${error.key}' is not a recognized key)`;+ case 'duplicate_target':+ return `${error.kind} ('${error.key}' appears more than once)`;+ case 'reorder_mismatch':+ return `${error.kind} (expected: ${error.expected.join(', ')}; got: ${error.got.join(', ')})`;+ case 'region_too_large':+ return `${error.kind} (frontmatter region too large: ${error.bytes} > ${error.limit} bytes)`;+ case 'parse_failed':+ return `${error.kind} (frontmatter region unparseable: ${error.reason})`;+ case 'invalid_path':+ return `${error.kind} (${error.path.map(String).join('.') || '__path__'}: ${error.reason})`;+ default: {+ const _exhaustive: never = error;+ return `unhandled frontmatter edit error (${String(_exhaustive)})`;+ }+ }+}diff --git a/packages/server/src/fs-copy-observer.test-helper.ts b/packages/server/src/fs-copy-observer.test-helper.tsnew file mode 100644index 000000000..72ad4c53a--- /dev/null+++ b/packages/server/src/fs-copy-observer.test-helper.ts@@ -0,0 +1,53 @@+import { trace } from '@opentelemetry/api';+import { BasicTracerProvider } from '@opentelemetry/sdk-trace-base';++export async function withFsCopyCompletionObserver<T>(+ matches: (destination: string) => boolean,+ onCopy: (destination: string) => void,+ run: () => Promise<T>,+): Promise<T> {+ let fired = false;+ let callbackError: unknown;+ const observed: string[] = [];+ const provider = new BasicTracerProvider({+ spanProcessors: [+ {+ onStart() {},+ onEnd(span) {+ const destination = span.attributes['fs.path'];+ if (fired || span.name !== 'fs.cpSync' || typeof destination !== 'string') return;+ observed.push(destination);+ try {+ if (!matches(destination)) return;+ fired = true;+ onCopy(destination);+ } catch (err) {+ callbackError = err;+ }+ },+ async forceFlush() {},+ async shutdown() {},+ },+ ],+ });+ if (!trace.setGlobalTracerProvider(provider)) {+ await provider.shutdown();+ throw new Error(+ 'A tracing provider is already registered. This helper unregisters the global provider on teardown instead of restoring the previous one, so it cannot wrap a server booted through initTelemetry.',+ );+ }+ let result: T;+ try {+ result = await run();+ } finally {+ trace.disable();+ await provider.shutdown();+ }+ if (callbackError !== undefined) throw callbackError;+ if (!fired) {+ throw new Error(+ `No fs.cpSync span whose destination the caller's matcher accepted was recorded, so the copy callback never ran. fs-traced.ts normalizes every destination to its final two path segments; the ${observed.length} it recorded during this run were: ${observed.length > 0 ? observed.join(', ') : '(none — check that fs-traced.ts still names the span fs.cpSync and still records the destination under fs.path)'}.`,+ );+ }+ return result;+}diff --git a/packages/server/src/fs-copy-observer.test.ts b/packages/server/src/fs-copy-observer.test.tsnew file mode 100644index 000000000..f80860413--- /dev/null+++ b/packages/server/src/fs-copy-observer.test.ts@@ -0,0 +1,91 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { withFsCopyCompletionObserver } from './fs-copy-observer.test-helper.ts';+import { tracedCpSync } from './fs-traced.ts';++let root: string;+let source: string;+let witness: string;++const at = (...segments: string[]): string => join(root, ...segments);++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'ok-fs-copy-observer-'));+ source = join(root, 'source');+ mkdirSync(source, { recursive: true });+ writeFileSync(join(source, 'file.txt'), 'source bytes');+ witness = join(root, 'witness.txt');+ writeFileSync(witness, 'untouched');+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++describe('fs copy completion observer', () => {+ test('an unrelated copy landing first does not consume the one-shot latch', async () => {+ const fired: string[] = [];+ let unrelatedExistedAtFire: boolean | undefined;+ let laterMatchExistedAtFire: boolean | undefined;++ await withFsCopyCompletionObserver(+ (destination) => destination.endsWith(join('copies', 'wanted')),+ (destination) => {+ fired.push(destination);+ unrelatedExistedAtFire = existsSync(at('host-a', 'copies', 'unrelated'));+ laterMatchExistedAtFire = existsSync(at('host-b', 'copies', 'wanted'));+ writeFileSync(witness, `fired at ${destination}`);+ },+ async () => {+ tracedCpSync(source, at('host-a', 'copies', 'unrelated'), { recursive: true });+ tracedCpSync(source, at('host-a', 'copies', 'wanted'), { recursive: true });+ tracedCpSync(source, at('host-b', 'copies', 'wanted'), { recursive: true });+ },+ );++ expect(fired).toHaveLength(1);+ expect(fired[0]).toContain(join('copies', 'wanted'));+ expect(unrelatedExistedAtFire).toBe(true);+ expect(laterMatchExistedAtFire).toBe(false);+ expect(readFileSync(witness, 'utf8')).toBe(`fired at ${fired[0]}`);+ for (const copied of [+ ['host-a', 'copies', 'unrelated'],+ ['host-a', 'copies', 'wanted'],+ ['host-b', 'copies', 'wanted'],+ ]) {+ expect(readFileSync(join(at(...copied), 'file.txt'), 'utf8')).toBe('source bytes');+ }+ });++ test('a run the matcher never accepted fails loudly and names the destinations it saw', async () => {+ await expect(+ withFsCopyCompletionObserver(+ (destination) => destination.endsWith(join('copies', 'never-copied')),+ () => {+ writeFileSync(witness, 'callback ran');+ },+ async () => {+ tracedCpSync(source, at('host-a', 'copies', 'unrelated'), { recursive: true });+ },+ ),+ ).rejects.toThrow(join('copies', 'unrelated'));++ expect(readFileSync(witness, 'utf8')).toBe('untouched');+ });++ test('a throwing callback surfaces its own error rather than the no-match diagnostic', async () => {+ await expect(+ withFsCopyCompletionObserver(+ (destination) => destination.endsWith(join('copies', 'wanted')),+ () => {+ throw new Error('callback exploded');+ },+ async () => {+ tracedCpSync(source, at('host-a', 'copies', 'wanted'), { recursive: true });+ },+ ),+ ).rejects.toThrow('callback exploded');+ });+});diff --git a/packages/server/src/http/error-response.ts b/packages/server/src/http/error-response.tsindex b044bc421..c83b9e754 100644--- a/packages/server/src/http/error-response.ts+++ b/packages/server/src/http/error-response.ts@@ -41,13 +41,15 @@ export function apiErrorCounter(): Counter {return _apiErrorCounter;}+export type ErrorExtensions = Record<string, unknown> & {+ [K in 'type' | 'title' | 'status' | 'instance' | 'detail']?: never;+};+interface ErrorResponseOptions {handler?: string;instance?: string;detail?: string;- extensions?: Record<string, unknown> & {- [K in 'type' | 'title' | 'status' | 'instance' | 'detail']?: never;- };+ extensions?: ErrorExtensions;extraHeaders?: Record<string, string>;cause?: unknown;logLevel?: 'debug' | 'warn' | 'error';diff --git a/packages/server/src/http/history-routes.ts b/packages/server/src/http/history-routes.tsindex e0795fd64..7caab578e 100644--- a/packages/server/src/http/history-routes.ts+++ b/packages/server/src/http/history-routes.ts@@ -25,7 +25,7 @@ export interface HistoryRouteDeps {log: PinoLogger;shadowRef: ShadowRef | undefined;flushGitCommit: (() => Promise<void>) | undefined;- commitOkArtifactWrite: (context: string) => Promise<void>;+ commitOkArtifactWrite: (context: string) => Promise<unknown>;getCurrentBranch: (() => string | null) | undefined;validateFolderRel: (raw: string,diff --git a/packages/server/src/http/skills-document-routes.ts b/packages/server/src/http/skills-document-routes.tsindex b73ea3858..c2ca736de 100644--- a/packages/server/src/http/skills-document-routes.ts+++ b/packages/server/src/http/skills-document-routes.ts@@ -1,10 +1,15 @@+import { randomUUID } from 'node:crypto';import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';import { readFile } from 'node:fs/promises';import type { IncomingMessage, ServerResponse } from 'node:http';import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';+import type {+ ProblemType,+ SkillMoveStateCode,+ SkillRetentionLedgerCode,+ SkillSourceStateCode,+} from '@inkeep/open-knowledge-core';import {- applyPatchToFm,- detectFmRegion,EmptyRequestSchema,externalSkillLiveDocName,isSkillInstallTarget,@@ -34,6 +39,7 @@ import { composeAndWriteRawBody } from '../bridge-intake.ts';import { isLinkIndexExcludedDoc } from '../cc1-broadcast.ts';import {applySkillDelete,+ applySkillDirNameSync,applySkillMove,applySkillWrite,composeSkillContent,@@ -46,7 +52,8 @@ import type {import type { StoreFailure } from '../document-durability-state.ts';import { registerExternalSkill } from '../external-skill-registry.ts';import { extractActorIdentity } from '../extract-actor-identity.ts';-import { tracedCpSync, tracedMkdirSync, tracedRmSync, tracedWriteFileSync } from '../fs-traced.ts';+import { describeFmEditError } from '../fm-edit-error.ts';+import { tracedCpSync, tracedMkdirSync, tracedRmSync } from '../fs-traced.ts';import {resolveDefaultSkillHomeRel,scanGlobalInPlaceSkills,@@ -61,6 +68,13 @@ import {import type { PinoLogger } from '../logger.ts';import { getLogger } from '../logger.ts';import { isInternalBundleSkillName } from '../skill-bundles.ts';+import {+ clearSkillMoveRetention,+ readSkillMoveRetention,+ recordSkillMoveRetention,+ type SkillMoveRetentionRead,+ type SkillMoveRetentionRecord,+} from '../skill-move-retained-store.ts';import { clearSkillPlacements } from '../skill-placements.ts';import {projectSkill,@@ -73,14 +87,22 @@ import {} from '../skill-projection.ts';import { rewriteSkillRefsAcrossScope, type SkillRefRewrite } from '../skill-ref-rename.ts';import { mutateSkillsLock, readSkillsLockFile } from '../skills-lock-store.ts';+import { getMeter } from '../telemetry.ts';import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';+import type { ErrorExtensions, HttpErrorStatus } from './error-response.ts';import { errorResponse } from './error-response.ts';import { methodRouter } from './method-router.ts';+import { getRequestId } from './request-id.ts';import { withValidation } from './request-validation.ts';import { successResponse } from './success-response.ts';export interface SkillsDocumentRouteDeps {- validateSkillName: (name: string, res: ServerResponse, handler: string) => boolean;+ validateSkillName: (+ name: string,+ res: ServerResponse,+ handler: string,+ extensions?: ErrorExtensions,+ ) => boolean;parseSkillScope: (raw: string | null,res: ServerResponse,@@ -104,6 +126,8 @@ export interface SkillsDocumentRouteDeps {derivedDocumentIndex: Pick<DerivedDocumentIndexApiPort, 'recordDirectMutations'> | undefined;contentFilter: ContentFilter | undefined;bumpSkillsCatalogGen: () => void;+ settleSkillCatalog: () => void;+ invalidateSkillCatalog: () => void;scheduleDeferredIgnoreRebuild: () => void;recordDerivedDocumentBestEffort: (documentName: string,@@ -158,7 +182,7 @@ export interface SkillsDocumentRouteDeps {lifecycleStatus: 'deleted-upstream' | 'renamed',) => Promise<Map<string, string>>;log: PinoLogger;- commitOkArtifactWrite: (context: string) => Promise<void>;+ commitOkArtifactWrite: (context: string) => Promise<unknown>;skillInstallBase: (scope: 'project' | 'global') => string | undefined;uninstallSkillFromHostDirs: (base: string,@@ -200,6 +224,8 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRoderivedDocumentIndex,contentFilter,bumpSkillsCatalogGen,+ settleSkillCatalog,+ invalidateSkillCatalog,scheduleDeferredIgnoreRebuild,recordDerivedDocumentBestEffort,getPrincipal,@@ -270,6 +296,7 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRofromScope: 'project' | 'global',toScope: 'project' | 'global',name: string,+ toName: string = name,): Promise<boolean> {const fromPath = skillLockPath(fromScope);const toPath = skillLockPath(toScope);@@ -281,7 +308,7 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRoif (toScope === 'global') delete movedEntry.baselineRef;await mutateSkillsLock(toPath, (lock) => ({...lock,- skills: { ...lock.skills, [name]: movedEntry },+ skills: { ...lock.skills, [toName]: movedEntry },}));await mutateSkillsLock(fromPath, (lock) => {const remaining = { ...lock.skills };@@ -563,7 +590,8 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo{path: `${homeRel}/${body.name}/SKILL.md`,created: true,- warnings: [...composed.warnings, ...wr.warnings],+ warnings: wr.warnings,+ warningCodes: wr.warningCodes,},{ handler: 'skill-put' },);@@ -622,7 +650,12 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRores,200,SkillPutSuccessSchema,- { path: relPath, created, warnings: composed.warnings },+ {+ path: relPath,+ created,+ warnings: composed.warnings,+ warningCodes: composed.warningCodes,+ },{ handler: 'skill-put' },);} catch (e) {@@ -635,13 +668,13 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo{ handler: 'skill-put', method: 'PUT' },);- function sweepSkillOccurrences(scope: 'project' | 'global', name: string): void {+ function sweepSkillOccurrences(scope: 'project' | 'global', name: string): SkillHostId[] {const base = scope === 'project' ? contentDir : skillsHome;const inPlace = (scope === 'project' ? scanInPlaceSkills(contentDir) : scanGlobalInPlaceSkills(skillsHome)).find((sk) => sk.name === name);- if (!inPlace) return;- removeInPlaceSkillCopies({+ if (!inPlace) return [];+ return removeInPlaceSkillCopies({canonicalAbs: resolve(base, inPlace.dir),canonicalHash: inPlace.contentHash,name,@@ -662,6 +695,18 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRoif (scope === null) return;const host = url.searchParams.get('host') ?? undefined;const { root: skillsRoot, dirRel, realDir } = effectiveSkillRoot(scope, name, host);+ const retentionBase = host === undefined ? skillInstallBase(scope) : undefined;+ const priorRetention =+ retentionBase !== undefined+ ? readSkillMoveRetention(retentionBase, scope, name)+ : ({ state: 'none' } as const);+ const preDeleteHash =+ priorRetention.state === 'record' &&+ priorRetention.record.sourceState !== 'intact' &&+ priorRetention.record.retainedContentHash !== '' &&+ realDir !== null+ ? readSkillContentHash(realDir)+ : undefined;if (host !== undefined && realDir === null) {errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {handler: 'skill-delete',@@ -726,14 +771,75 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRosignalChannel?.('files');}const uninstallBase = skillInstallBase(scope);+ const deleteWarnings: string[] = [];if (host === undefined && uninstallBase) {- await uninstallSkillFromHostDirs(uninstallBase, name, scope);+ try {+ await uninstallSkillFromHostDirs(uninstallBase, name, scope);+ } catch (err) {+ log.error(+ { requestId: getRequestId(req), handler: 'skill-delete', name, scope, err },+ '[skill-delete] skill content removed, but install bookkeeping could not be updated',+ );+ deleteWarnings.push(+ `The skill was deleted, but this server could not update its install records (${thrownMessage(err)}). A stale entry may remain until that file is repaired.`,+ );+ }+ }+ if (host === undefined) {+ if (priorRetention.state === 'record' && priorRetention.record.sourceState !== 'intact') {+ const record = priorRetention.record;+ const verified =+ record.retainedContentHash !== '' &&+ preDeleteHash?.ok === true &&+ record.retainedContentHash === preDeleteHash.hash;+ const unverifiable =+ preDeleteHash !== undefined && !preDeleteHash.ok && preDeleteHash.kind !== 'absent';+ const origin = record.from !== '' ? `a move of "${record.from}"` : 'an earlier move';+ const when = record.retainedAt ? ` on ${record.retainedAt}` : '';+ if (verified || unverifiable) {+ log.error(+ {+ requestId: getRequestId(req),+ handler: 'skill-delete',+ name,+ scope,+ from: record.from,+ retainedAt: record.retainedAt,+ sourceState: record.sourceState,+ verified,+ ...(unverifiable && preDeleteHash.kind === 'read-error'+ ? { err: preDeleteHash.cause }+ : {}),+ },+ verified+ ? '[skill-delete] deleted a copy this server retained when an earlier move failed to remove its source; the source was never verified unchanged, so files that only existed here may now be gone'+ : '[skill-delete] deleted a directory carrying an unverified retained-copy record; this server could not read that directory before removing it, so it could not confirm whether it was the copy an earlier failed move retained',+ );+ }+ if (verified) {+ deleteWarnings.push(+ `A recovery copy was deleted: ${origin} failed to remove its source${when}, and this server kept this copy in case it held files that failed removal had already deleted. That source was never verified unchanged. Check the other location before relying on this deletion.`,+ );+ } else if (unverifiable) {+ deleteWarnings.push(+ `A directory this server could not read was deleted: ${origin} failed to remove its source${when}, and this server has a record of keeping a copy under this name in case it held files that failed removal had already deleted. It could not read the directory before removing it, so it could not confirm whether that was the copy it kept. Check the other location before assuming nothing was lost.`,+ );+ }+ }+ await clearSkillMoveRetentionQuietly(retentionBase, scope, name, {+ requestId: getRequestId(req),+ handler: 'skill-delete',+ });}successResponse(res,200,SkillDeleteSuccessSchema,- { existed: result.existed, path: result.path },+ {+ existed: result.existed,+ path: result.path,+ ...(deleteWarnings.length > 0 ? { warnings: deleteWarnings } : {}),+ },{ handler: 'skill-delete' },);} catch (e) {@@ -767,13 +873,39 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRobody.scope,body.fromName,);- if (resolveSkillDirForRead(body.scope, body.toName) !== null) {+ const occupiedToDir = resolveSkillDirForRead(body.scope, body.toName);+ if (occupiedToDir !== null) {+ const retentionBase = skillInstallBase(body.scope);+ const ledger =+ retentionBase !== undefined+ ? readSkillMoveRetention(retentionBase, body.scope, body.toName)+ : ({ state: 'none' } as const);+ const occupant = readSkillContentHash(occupiedToDir);+ const { verdict, detail } = describeRetainedOccupant(+ effectiveSkillRoot(body.scope, body.toName).dirRel,+ ledger,+ occupant,+ );+ if (ledger.state === 'record' && verdict.kind === 'plain-collision') {+ await clearSkillMoveRetentionQuietly(retentionBase, body.scope, body.toName, {+ requestId: getRequestId(_req),+ handler: 'skill-move',+ });+ }errorResponse(res,409,'urn:ok:error:doc-already-exists',`A skill named "${body.toName}" already exists.`,- { handler: 'skill-move' },+ {+ handler: 'skill-move',+ detail: detail ?? 'Delete or rename it first; this move will not overwrite it.',+ ...(!occupant.ok && occupant.kind === 'read-error'+ ? { cause: occupant.cause }+ : ledger.state === 'unreadable' && ledger.cause !== undefined+ ? { cause: ledger.cause }+ : {}),+ },);return;}@@ -891,20 +1023,32 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo}if (body.scope === 'project' && !contentEditError) {- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();+ invalidateSkillCatalog();void reindexMovedProjectSkillDocs(skillsRoot, body.fromName, body.toName).then(() => reindexRewrittenSkillRefDocs(refRewrites, body.toName)).catch(() => {});- scheduleDeferredIgnoreRebuild();}const fromKeyPath = skillRelPath(resolve(skillsRoot, body.fromName), body.scope);const toKeyPath = skillRelPath(resolve(skillsRoot, body.toName), body.scope);const renamedLocalHash = localSkillHash(skillsRoot, body.toName);- await rekeySkillLockEntry(body.scope, body.fromName, body.toName, {- localHash: renamedLocalHash,- });+ const moveWarnings: string[] = [];+ const warnBookkeeping = (err: unknown, records: string): void => {+ log.error(+ { err, fromName: body.fromName, toName: body.toName, scope: body.scope },+ 'skill renamed, but its bookkeeping could not be updated',+ );+ moveWarnings.push(+ `The skill was renamed to "${body.toName}", but this server could not update its ${records} (${thrownMessage(err)}). A stale entry may remain until that file is repaired.`,+ );+ };+ try {+ await rekeySkillLockEntry(body.scope, body.fromName, body.toName, {+ localHash: renamedLocalHash,+ });+ } catch (err) {+ warnBookkeeping(err, 'import records');+ }if (body.scope === 'project') {attributeOkArtifactWrite(actor,@@ -929,7 +1073,11 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo}if (moveBase) {- await removeSkillInstall(moveBase, body.fromName);+ try {+ await removeSkillInstall(moveBase, body.fromName);+ } catch (err) {+ warnBookkeeping(err, 'install records');+ }reverseProjectSkill(body.fromName,moveBase,@@ -946,14 +1094,19 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRoprojectionModeFor(body.scope, body.toName),skillProjectionRoots(body.scope),);- await recordSkillInstall(moveBase, body.toName, {- ...priorInstall,- scope: body.scope,- hosts: newHosts,- scripts:- priorInstall?.scripts ?? validateSkillForInstall(movedDir, body.toName).hasScripts,- installedAt: priorInstall?.installedAt ?? new Date().toISOString(),- });+ try {+ await recordSkillInstall(moveBase, body.toName, {+ ...priorInstall,+ scope: body.scope,+ hosts: newHosts,+ scripts:+ priorInstall?.scripts ??+ validateSkillForInstall(movedDir, body.toName).hasScripts,+ installedAt: priorInstall?.installedAt ?? new Date().toISOString(),+ });+ } catch (err) {+ warnBookkeeping(err, 'install records');+ }}}signalChannel?.('files');@@ -981,6 +1134,7 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRofrom: fromKeyPath,to: toKeyPath,committed: result.committed,+ ...(moveWarnings.length > 0 ? { warnings: moveWarnings } : {}),},{ handler: 'skill-move' },);@@ -1035,49 +1189,343 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo},);+ type SkillOccupantHash =+ | { ok: true; hash: string }+ | { ok: false; kind: 'no-manifest'; reason: string }+ | { ok: false; kind: 'absent'; reason: string }+ | { ok: false; kind: 'read-error'; reason: string; cause: unknown };++ type RetainedOccupantVerdict =+ | { kind: 'retained'; record: SkillMoveRetentionRecord }+ | { kind: 'ledger-unreadable' }+ | { kind: 'occupant-unverifiable' }+ | { kind: 'retained-slot-unverifiable' }+ | { kind: 'occupant-unreadable' }+ | { kind: 'stray-occupant' }+ | { kind: 'plain-collision' };++ const RETENTION_LEDGER_CODE_BY_VERDICT: Record<+ RetainedOccupantVerdict['kind'],+ SkillRetentionLedgerCode | undefined+ > = {+ retained: undefined,+ 'plain-collision': undefined,+ 'stray-occupant': undefined,+ 'ledger-unreadable': 'unreadable',+ 'occupant-unverifiable': 'occupant-unverifiable',+ 'retained-slot-unverifiable': 'occupant-unverifiable',+ 'occupant-unreadable': 'occupant-unverifiable',+ };++ let _skillMoveScopeOutcomeCounter: ReturnType<+ ReturnType<typeof getMeter>['createCounter']+ > | null = null;+ function skillMoveScopeOutcomeCounter(): ReturnType<+ ReturnType<typeof getMeter>['createCounter']+ > {+ _skillMoveScopeOutcomeCounter ||= getMeter().createCounter('ok.skill_move_scope.outcome', {+ description:+ 'Count of cross-scope skill-move handler invocations by terminal outcome, one per invocation. Bounded labels: move_state ∈ SKILL_MOVE_STATE_CODES plus `success`; source_state ∈ SKILL_SOURCE_STATE_CODES plus `none`; retention_ledger ∈ SKILL_RETENTION_LEDGER_CODES plus `none`. Skill names, filesystem paths, droppedLocations, problem detail text, error messages and request IDs are never labels. Transport-level and schema-level rejections happen outside the handler and stay covered by ok.api.error.',+ });+ return _skillMoveScopeOutcomeCounter;+ }++ function recordMoveScopeOutcome(+ moveState: SkillMoveStateCode | 'success',+ sourceState?: SkillSourceStateCode,+ retentionLedger?: SkillRetentionLedgerCode,+ context?: {+ requestId?: string;+ status?: number;+ instance?: string;+ droppedLocationCount?: number;+ logLevel?: 'debug' | 'warn' | 'error';+ message?: string;+ },+ ): void {+ skillMoveScopeOutcomeCounter().add(1, {+ move_state: moveState,+ source_state: sourceState ?? 'none',+ retention_ledger: retentionLedger ?? 'none',+ });+ getLogger('skill-move-scope')[+ context?.logLevel ?? ((context?.status ?? 200) >= 500 ? 'error' : 'warn')+ ](+ {+ event: 'skill-move-scope.outcome',+ ...(context?.instance !== undefined ? { instance: context.instance } : {}),+ ...(context?.requestId !== undefined ? { requestId: context.requestId } : {}),+ handler: 'skill-move-scope',+ ...(context?.status !== undefined ? { status: context.status } : {}),+ moveState,+ sourceState: sourceState ?? null,+ retentionLedger: retentionLedger ?? null,+ droppedLocationCount: context?.droppedLocationCount ?? 0,+ },+ context?.message ?? 'cross-scope skill move did not complete',+ );+ }++ function readSkillContentHash(dir: string): SkillOccupantHash {+ try {+ const parsed = parseSkillDir(dir);+ if (parsed !== null) return { ok: true, hash: parsed.contentHash };+ return existsSync(dir)+ ? { ok: false, kind: 'no-manifest', reason: 'it has no readable SKILL.md' }+ : { ok: false, kind: 'absent', reason: 'it does not exist' };+ } catch (err) {+ const code = (err as NodeJS.ErrnoException | undefined)?.code;+ return {+ ok: false,+ kind: 'read-error',+ reason: code ? `it could not be read (${code})` : 'it could not be read',+ cause: err,+ };+ }+ }++ function describeRetainedOccupant(+ toDirRel: string,+ ledger: SkillMoveRetentionRead,+ occupant: SkillOccupantHash,+ ): { verdict: RetainedOccupantVerdict; detail: string | undefined } {+ const record = ledger.state === 'record' ? ledger.record : null;+ const retained =+ record !== null &&+ record.retainedContentHash !== '' &&+ occupant.ok &&+ record.retainedContentHash === occupant.hash+ ? record+ : null;+ const origin =+ record !== null && record.from !== '' ? `a move of "${record.from}"` : 'an earlier move';+ const when = record?.retainedAt ? ` on ${record.retainedAt}` : '';+ if (retained?.sourceState === 'intact') {+ return {+ verdict: { kind: 'retained', record: retained },+ detail: `${toDirRel} is a copy this server retained${when} when ${origin} failed to remove the source. That source was verified unchanged, so this copy is a redundant duplicate whose install records never transferred: remove it, then retry. This call wrote nothing.`,+ };+ }+ if (retained !== null) {+ return {+ verdict: { kind: 'retained', record: retained },+ detail: `${toDirRel} is a copy this server retained${when} when ${origin} failed to remove the source. Do NOT delete it before reconciling it against the source: it may hold the only copy of files that failed removal already deleted. Reconcile the two locations, then remove whichever copy is redundant. This call wrote nothing.`,+ };+ }+ if (ledger.state === 'unreadable') {+ return {+ verdict: { kind: 'ledger-unreadable' },+ detail: `A directory already exists at ${toDirRel}, and this server could not read its retained-destination ledger (${ledger.reason}), so it cannot tell whether that directory is a copy an earlier failed move retained. Do NOT delete it before comparing it against the source. This call wrote nothing.`,+ };+ }+ if (record !== null && !occupant.ok && occupant.kind === 'no-manifest') {+ return {+ verdict: { kind: 'retained-slot-unverifiable' },+ detail: `A directory already exists at ${toDirRel} with no readable SKILL.md, and this server has a record of retaining a copy under this name${when} when ${origin} failed to remove the source. Nothing in it could be matched against that record, so verify it against the source before assuming it is that copy.`,+ };+ }+ if (record !== null && !occupant.ok) {+ return {+ verdict: { kind: 'occupant-unverifiable' },+ detail: `A directory already exists at ${toDirRel}, and this server has a record of retaining a copy under that name${when} from ${origin}, but it could not read that directory to confirm the copy is the one it retained (${occupant.reason}). Do NOT delete it before comparing it against the source. This call wrote nothing.`,+ };+ }+ if (!occupant.ok && occupant.kind === 'read-error') {+ return {+ verdict: { kind: 'occupant-unreadable' },+ detail: `A directory exists at ${toDirRel} and this server could not read it to determine whether it is a skill (${occupant.reason}). Verify it against the source before removing it; this move will not overwrite it. This call wrote nothing.`,+ };+ }+ if (!occupant.ok && occupant.kind === 'no-manifest') {+ return {+ verdict: { kind: 'stray-occupant' },+ detail: `A directory exists at ${toDirRel} with no readable SKILL.md. Verify it against the source before removing it; this move will not overwrite it. This call wrote nothing.`,+ };+ }+ return { verdict: { kind: 'plain-collision' }, detail: undefined };+ }++ async function clearSkillMoveRetentionQuietly(+ base: string | undefined,+ scope: 'project' | 'global',+ name: string,+ context: Record<string, unknown>,+ ): Promise<void> {+ if (base === undefined) return;+ try {+ await clearSkillMoveRetention(base, scope, name);+ } catch (err) {+ getLogger('skill-move-scope').warn(+ {+ event: 'skill-move-scope.retention-clear-failed',+ scope,+ name,+ ...context,+ err,+ },+ 'could not clear a retained-destination record — a later collision on this name may still report it as retained',+ );+ }+ }++ type MoveScopeFailureOutcome =+ | {+ moveState: 'destination-retained' | 'destination-retained-blocking';+ sourceState: SkillSourceStateCode;+ retentionLedger?: never;+ }+ | {+ moveState: 'nothing-written';+ sourceState?: never;+ retentionLedger?: SkillRetentionLedgerCode;+ }+ | {+ moveState:+ | 'destination-removed'+ | 'destination-stray'+ | 'destination-unreadable'+ | 'partially-applied';+ sourceState?: never;+ retentionLedger?: never;+ };++ const thrownMessage = (err: unknown): string =>+ err instanceof Error ? err.message : String(err);++ const MOVE_SCOPE_TOUCHED_DISK: Record<SkillMoveStateCode, boolean> = {+ 'nothing-written': false,+ 'destination-removed': true,+ 'destination-stray': true,+ 'destination-retained': true,+ 'destination-retained-blocking': false,+ 'destination-unreadable': true,+ 'partially-applied': true,+ };+const handleSkillMoveScope = withValidation(SkillMoveScopeRequestSchema,async (_req, res, body) => {+ let actor: ReturnType<typeof extractActorIdentity>;try {- const actor = extractActorIdentity(- body as unknown as Record<string, unknown>,- getPrincipal,+ actor = extractActorIdentity(body as unknown as Record<string, unknown>, getPrincipal);+ } catch (e) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Failed to move skill across scopes.',+ {+ handler: 'skill-move-scope',+ detail: 'Could not resolve who is making the request. Nothing was written.',+ extensions: { moveState: 'nothing-written', droppedLocations: [] },+ cause: e,+ },);+ recordMoveScopeOutcome('nothing-written', undefined, undefined, {+ requestId: getRequestId(_req),+ status: 400,+ });+ return;+ }+ const settle = settleSkillCatalog;+ let wrote = false;+ let mutated = false;+ let droppedLocations: string[] = [];+ const failMove = (+ status: HttpErrorStatus,+ type: ProblemType,+ title: string,+ options: MoveScopeFailureOutcome & {+ detail?: string;+ cause?: unknown;+ logLevel?: 'debug' | 'warn' | 'error';+ },+ ): void => {+ const instance = `urn:uuid:${randomUUID()}`;+ recordMoveScopeOutcome(options.moveState, options.sourceState, options.retentionLedger, {+ instance,+ requestId: getRequestId(_req),+ status,+ droppedLocationCount: droppedLocations.length,+ ...(options.logLevel !== undefined ? { logLevel: options.logLevel } : {}),+ });+ if (mutated || MOVE_SCOPE_TOUCHED_DISK[options.moveState]) settle();+ errorResponse(res, status, type, title, {+ instance,+ handler: 'skill-move-scope',+ ...(options.detail !== undefined ? { detail: options.detail } : {}),+ extensions: {+ moveState: options.moveState,+ droppedLocations,+ ...(options.sourceState !== undefined ? { sourceState: options.sourceState } : {}),+ ...(options.retentionLedger !== undefined+ ? { retentionLedger: options.retentionLedger }+ : {}),+ },+ ...(options.cause !== undefined ? { cause: options.cause } : {}),+ ...(options.logLevel ? { logLevel: options.logLevel } : {}),+ });+ };+ try {if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-move-scope',+ failMove(400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ moveState: 'nothing-written',});return;}const { name, fromScope, toScope } = body;- if (!validateSkillName(name, res, 'skill-move-scope')) return;+ const toName = body.toName ?? name;+ const nameRefusal: ErrorExtensions = {+ moveState: 'nothing-written',+ droppedLocations: [],+ } satisfies { moveState: SkillMoveStateCode; droppedLocations: string[] };+ if (!validateSkillName(name, res, 'skill-move-scope', nameRefusal)) {+ recordMoveScopeOutcome('nothing-written', undefined, undefined, {+ requestId: getRequestId(_req),+ status: 400,+ });+ return;+ }+ if (!validateSkillName(toName, res, 'skill-move-scope', nameRefusal)) {+ recordMoveScopeOutcome('nothing-written', undefined, undefined, {+ requestId: getRequestId(_req),+ status: 400,+ });+ return;+ }if (isInternalBundleSkillName(name)) {- errorResponse(- res,+ failMove(400,'urn:ok:error:invalid-request',`"${name}" is a built-in skill and always lives at its own scope.`,- { handler: 'skill-move-scope', detail: 'BUILTIN_SCOPE_FIXED' },+ { moveState: 'nothing-written', detail: 'BUILTIN_SCOPE_FIXED' },+ );+ return;+ }+ if (isInternalBundleSkillName(toName)) {+ failMove(+ 400,+ 'urn:ok:error:invalid-request',+ `"${toName}" is a built-in skill name and cannot be used as a destination name.`,+ { moveState: 'nothing-written', detail: 'BUILTIN_SCOPE_FIXED' },);return;}if (fromScope === toScope) {- errorResponse(- res,+ failMove(400,'urn:ok:error:invalid-request','Source and destination scope are the same.',- { handler: 'skill-move-scope' },+ { moveState: 'nothing-written' },);return;}if (toScope === 'project' && !projectDir) {- errorResponse(- res,+ failMove(400,'urn:ok:error:invalid-request','Cannot move to project scope — no project root is resolved for this server.',- { handler: 'skill-move-scope', detail: 'NO_PROJECT_ROOT' },+ { moveState: 'nothing-written', detail: 'NO_PROJECT_ROOT' },);return;}@@ -1094,20 +1542,20 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRoconst toBase2 = toScope === 'project' ? contentDir : skillsHome;const toHomeRel = resolveDefaultSkillHomeRel(toBase2, toScope);if (toHomeRel === null) {- errorResponse(- res,+ failMove(400,'urn:ok:error:invalid-request','No agent skill host is available in the destination scope.',- { handler: 'skill-move-scope', detail: 'NO_USABLE_SKILL_HOME' },+ { moveState: 'nothing-written', detail: 'NO_USABLE_SKILL_HOME' },);return;}const toRoot = resolve(toBase2, toHomeRel);- const toDir = resolve(toRoot, name);+ const toDir = resolve(toRoot, toName);+ const toDirRel = relative(toBase2, toDir).split(sep).join('/');if (realDir === null || !existsSync(fromDir)) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {- handler: 'skill-move-scope',+ failMove(404, 'urn:ok:error:not-found', 'Skill not found.', {+ moveState: 'nothing-written',detail: `Skill "${name}" not found in ${fromScope} scope.`,});return;@@ -1116,22 +1564,60 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRoresolve(realDir) === resolve(toDir) ||(existsSync(toDir) && realpathSync(realDir) === realpathSync(toDir))) {- errorResponse(- res,+ failMove(409,'urn:ok:error:doc-already-exists','The source and destination resolve to the same skill directory.',- { handler: 'skill-move-scope', detail: 'SAME_STORAGE' },+ { moveState: 'nothing-written', detail: 'SAME_STORAGE' },);return;}- if (resolveSkillDirForRead(toScope, name) !== null || existsSync(toDir)) {- errorResponse(- res,+ if (resolveSkillDirForRead(toScope, toName) !== null || existsSync(toDir)) {+ const retentionBase = skillInstallBase(toScope);+ const ledger =+ retentionBase !== undefined && existsSync(toDir)+ ? readSkillMoveRetention(retentionBase, toScope, toName)+ : ({ state: 'none' } as const);+ const occupant = readSkillContentHash(toDir);+ const { verdict, detail: retainedDetail } = describeRetainedOccupant(+ toDirRel,+ ledger,+ occupant,+ );+ if (ledger.state === 'record' && verdict.kind === 'plain-collision') {+ await clearSkillMoveRetentionQuietly(retentionBase, toScope, toName, {+ requestId: getRequestId(_req),+ handler: 'skill-move-scope',+ toDirRel,+ });+ }+ const retentionLedgerCode = RETENTION_LEDGER_CODE_BY_VERDICT[verdict.kind];+ const collisionOutcome: MoveScopeFailureOutcome =+ verdict.kind === 'retained'+ ? {+ moveState: 'destination-retained-blocking',+ sourceState: verdict.record.sourceState,+ }+ : {+ moveState: 'nothing-written',+ ...(retentionLedgerCode !== undefined+ ? { retentionLedger: retentionLedgerCode }+ : {}),+ };+ failMove(409,'urn:ok:error:doc-already-exists',- `A ${toScope} skill named "${name}" already exists.`,- { handler: 'skill-move-scope' },+ `A ${toScope} skill named "${toName}" already exists.`,+ {+ ...collisionOutcome,+ detail:+ retainedDetail ?? 'Delete or rename it first; this move will not overwrite it.',+ ...(!occupant.ok && occupant.kind === 'read-error'+ ? { cause: occupant.cause }+ : ledger.state === 'unreadable' && ledger.cause !== undefined+ ? { cause: ledger.cause }+ : {}),+ },);return;}@@ -1159,22 +1645,102 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo...resolvedHosts(aliasAudience, fromScope),]),];+ const unprojectable = (hosts: readonly string[]): string[] =>+ hosts.filter((host) => resolvedHosts([host], toScope).length === 0);+ const unhostableAtDestination = [+ ...new Set([+ ...unprojectable(priorInstall?.hosts ?? []),+ ...unprojectable(scanEntry?.hosts ?? []),+ ]),+ ].sort();+ mutated = true;await captureAndCloseDocuments([...new Set([...(fromScope === 'project' ? [`${fromDirRel}/SKILL`] : []),skillLiveDocName(fromScope, name),- skillLiveDocName(toScope, name),+ skillLiveDocName(toScope, toName),]),],'renamed',);+ wrote = true;tracedMkdirSync(toRoot, { recursive: true });tracedCpSync(fromContentDir, toDir, { recursive: true, dereference: true });+ if (toName !== name) {+ const failCopiedRename = (+ status: 400 | 500,+ detail: string,+ cause?: unknown,+ logLevel?: 'debug' | 'warn' | 'error',+ ): void => {+ const cleanup = applySkillDelete({ skillsRoot: toRoot, name: toName });+ failMove(+ cleanup.ok ? status : 500,+ cleanup.ok && status === 400+ ? 'urn:ok:error:invalid-request'+ : 'urn:ok:error:internal-server-error',+ cleanup.ok+ ? 'Failed to rename the copied skill; destination copy removed.'+ : 'Failed to rename the copied skill; destination cleanup failed.',+ {+ moveState: cleanup.ok ? 'destination-removed' : 'destination-stray',+ detail: cleanup.ok+ ? `Rename failed (${detail}). The source "${fromScope}:${name}" was not removed.`+ : `Rename failed (${detail}); destination cleanup failed (${cleanup.error.code}). The source "${fromScope}:${name}" was not removed. A partial copy may remain at "${toScope}:${toName}" (${toDirRel}). Inspect the destination before retrying.`,+ cause: cleanup.ok ? cause : new Error(cleanup.error.message, { cause }),+ ...(logLevel ? { logLevel } : {}),+ },+ );+ };+ try {+ const copied = parseSkillDir(toDir);+ if (copied === null) {+ failCopiedRename(400, 'UNREADABLE_SKILL', new Error('UNREADABLE_SKILL'), 'error');+ return;+ }+ const synced = applySkillDirNameSync({+ skillDir: toDir,+ toName,+ skillMd: copied.skillMd,+ });+ if (!synced.ok) {+ if (synced.stage === 'patch') {+ const failure = describeFmEditError(synced.error);+ failCopiedRename(400, failure, new Error(failure), 'error');+ } else {+ failCopiedRename(500, 'RENAME_FAILED', synced.cause);+ }+ return;+ }+ } catch (error) {+ failCopiedRename(500, 'RENAME_FAILED', error);+ return;+ }+ }- sweepSkillOccurrences(fromScope, name);+ if (!existsSync(join(toDir, 'SKILL.md'))) {+ const cleanup = applySkillDelete({ skillsRoot: toRoot, name: toName });+ failMove(+ 500,+ 'urn:ok:error:internal-server-error',+ cleanup.ok+ ? 'The copied skill is unreadable; destination copy removed.'+ : 'The copied skill is unreadable; destination cleanup failed.',+ {+ moveState: cleanup.ok ? 'destination-removed' : 'destination-stray',+ detail: cleanup.ok+ ? `No readable SKILL.md at the destination copy (${toDirRel}); it was removed. The source "${fromScope}:${name}" was not touched and is unchanged.`+ : `No readable SKILL.md at the destination copy (${toDirRel}); cleanup failed (${cleanup.error.code}). The source "${fromScope}:${name}" was not touched and is unchanged. A partial copy remains at "${toScope}:${toName}". Inspect the destination before retrying.`,+ ...(cleanup.ok ? {} : { cause: new Error(cleanup.error.message) }),+ },+ );+ return;+ }++ droppedLocations = [...new Set(sweepSkillOccurrences(fromScope, name))].sort();const del = applySkillDelete({ skillsRoot: fromRoot, name });if (del.ok && fromContentDir !== fromDir) {const realScanBase = (() => {@@ -1190,110 +1756,240 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo}}if (!del.ok) {- applySkillDelete({ skillsRoot: toRoot, name });- errorResponse(- res,+ let rescanError: unknown;+ const sourceState = ((): SkillSourceStateCode => {+ if (!scanEntry) return 'unknown';+ try {+ const rescanned = parseSkillDir(fromDir);+ if (!rescanned) return 'lossy';+ return rescanned.contentHash === scanEntry.contentHash ? 'intact' : 'lossy';+ } catch (error) {+ rescanError = error;+ return 'unknown';+ }+ })();+ let retentionRecorded = false;+ const retainedHash = readSkillContentHash(toDir);+ if (toBase !== undefined) {+ let retentionError: unknown = retainedHash.ok+ ? undefined+ : new Error(`the destination copy could not be hashed (${retainedHash.reason})`, {+ cause: retainedHash.kind === 'read-error' ? retainedHash.cause : undefined,+ });+ if (retainedHash.ok) {+ try {+ await recordSkillMoveRetention(toBase, toScope, toName, {+ retainedAt: new Date().toISOString(),+ from: `${fromScope}:${name}`,+ to: `${toScope}:${toName}`,+ sourceState,+ reason: del.error.code,+ retainedContentHash: retainedHash.hash,+ });+ retentionRecorded = true;+ } catch (err) {+ retentionError = err;+ }+ }+ if (!retentionRecorded) {+ getLogger('skill-move-scope').error(+ {+ event: 'skill-move-scope.retention-record-failed',+ requestId: getRequestId(_req),+ handler: 'skill-move-scope',+ toScope,+ toDirRel,+ sourceState,+ err: retentionError,+ },+ 'could not record the retained destination copy — a retry will report an ordinary name collision instead of a retained copy',+ );+ }+ }+ const retentionUnrecordedNote = retentionRecorded+ ? ''+ : retainedHash.ok+ ? ` This server could not record the retention, so a retry will not recognise ${toDirRel} as a copy it retained and will report an ordinary name collision instead.`+ : ` This server could not read the destination copy at ${toDirRel} to confirm it is intact (${retainedHash.reason}), so do not rely on it for recovery until you have inspected it yourself. It was not recorded as a retained copy either, so a retry will report an ordinary name collision instead.`;+ failMove(500,'urn:ok:error:internal-server-error',- 'Failed to move skill (source removal failed); rolled back the copy.',+ 'Failed to move skill (source removal failed); destination copy retained for recovery.',{- handler: 'skill-move-scope',- detail: del.error.code,- cause: new Error(del.error.message),+ moveState: 'destination-retained',+ sourceState,+ detail:+ sourceState === 'intact'+ ? `Source removal failed (${del.error.code}) without deleting anything. The source "${fromScope}:${name}" is unchanged at its original scope, so no files were lost. The destination copy "${toScope}:${toName}" at ${toDirRel} is a duplicate whose install records have not transferred; remove it before retrying.${retentionUnrecordedNote}`+ : sourceState === 'lossy'+ ? `Source removal failed (${del.error.code}). The source "${fromScope}:${name}" may be partially removed. The destination copy "${toScope}:${toName}" remains at ${toDirRel}; its install records have not transferred. Inspect both locations before retrying, and recover missing source files from the retained copy.${retentionUnrecordedNote}`+ : `Source removal failed (${del.error.code}). The source "${fromScope}:${name}" could not be verified against a known content hash, so whether any files were lost is unknown. The destination copy "${toScope}:${toName}" remains at ${toDirRel}; its install records have not transferred. Compare both locations before removing either.${retentionUnrecordedNote}`,+ cause: rescanError+ ? new Error(del.error.message, { cause: rescanError })+ : new Error(del.error.message),},);return;}- const movedLockEntry = await transferSkillLockEntry(fromScope, toScope, name);+ await clearSkillMoveRetentionQuietly(toBase, toScope, toName, {+ requestId: getRequestId(_req),+ handler: 'skill-move-scope',+ toDirRel,+ });++ const moveScopeWarnings: string[] = [];+ let movedLockEntry = false;+ try {+ movedLockEntry = await transferSkillLockEntry(fromScope, toScope, name, toName);++ if (fromBase) {+ await uninstallSkillFromHostDirs(+ fromBase,+ name,+ fromScope,+ scanEntry ? { purge: { contentHash: scanEntry.contentHash } } : {},+ );+ }+ if (fromBase) await clearSkillPlacements(fromBase, name);+ if (toBase && priorHosts.length > 0) {+ const newHosts = projectSkill(+ toDir,+ toName,+ toBase,+ priorHosts,+ projectionModeFor(toScope, toName),+ skillProjectionRoots(toScope),+ );+ await recordSkillInstall(toBase, toName, {+ ...priorInstall,+ scope: toScope,+ hosts: newHosts,+ scripts: priorInstall?.scripts ?? validateSkillForInstall(toDir, toName).hasScripts,+ installedAt: priorInstall?.installedAt ?? new Date().toISOString(),+ });+ }- if (fromBase) {- await uninstallSkillFromHostDirs(- fromBase,- name,- fromScope,- scanEntry ? { purge: { contentHash: scanEntry.contentHash } } : {},+ if (movedLockEntry) {+ const movedLocalHash = localSkillHash(toRoot, toName);+ await updateSkillLockEntry(toScope, toName, { localHash: movedLocalHash });+ }+ } catch (err) {+ getLogger('skill-move-scope').error(+ { err, name, toName, fromScope, toScope, requestId: getRequestId(_req) },+ 'skill moved across scopes, but its bookkeeping could not be updated',);- }- if (fromBase) await clearSkillPlacements(fromBase, name);- if (toBase && priorHosts.length > 0) {- const newHosts = projectSkill(- toDir,- name,- toBase,- priorHosts,- projectionModeFor(toScope, body.name),- skillProjectionRoots(toScope),+ moveScopeWarnings.push(+ `The skill moved to ${toScope}, but this server could not update its install records (${thrownMessage(err)}). A stale entry may remain until that file is repaired.`,);- await recordSkillInstall(toBase, name, {- ...priorInstall,- scope: toScope,- hosts: newHosts,- scripts: priorInstall?.scripts ?? validateSkillForInstall(toDir, name).hasScripts,- installedAt: priorInstall?.installedAt ?? new Date().toISOString(),- });}- if (movedLockEntry) {- const movedLocalHash = localSkillHash(toRoot, name);- await updateSkillLockEntry(toScope, name, { localHash: movedLocalHash });+ if (!existsSync(join(toDir, 'SKILL.md'))) {+ failMove(+ 500,+ 'urn:ok:error:internal-server-error',+ 'The source was removed, but the destination skill is unreadable.',+ {+ moveState: 'destination-unreadable',+ detail: `Inspect "${toScope}:${toName}" at ${toDirRel} before retrying. Restore the skill from a backup, or check the project Timeline / shadow-repo history for an earlier version if available.`,+ },+ );+ return;}+if (fromScope === 'project' || toScope === 'project') {attributeOkArtifactWrite(actor,fromScope === 'project' ? fromDirRel : relative(contentDir, toDir).split(sep).join('/'),- `skill-move-scope: ${fromScope} -> ${toScope} ${name}`,+ `skill-move-scope: ${fromScope} -> ${toScope} ${name}${toName !== name ? ` -> ${toName}` : ''}`,);const toKeyForBaseline = relative(contentDir, toDir).split(sep).join('/');const wantBaseline = Boolean(movedLockEntry) && toScope === 'project';+ const deferredRequestId = getRequestId(_req);void (async () => {+ const flush = await commitOkArtifactWrite('skill-move-scope');+ if (!wantBaseline) return;+ if (flush !== 'flushed') {+ getLogger('skill-move-scope').warn(+ {+ event: 'skill-move-scope.revert-baseline-unset',+ requestId: deferredRequestId,+ handler: 'skill-move-scope',+ toScope,+ toName,+ flush,+ },+ 'the deferred shadow flush did not complete, so this move did not establish or update its Revert baseline; any baseline an earlier write recorded is unchanged',+ );+ return;+ }try {- await commitOkArtifactWrite('skill-move-scope');- if (wantBaseline) {- const baselineRef = await shadowHeadSha(artifactWriterId(actor), toKeyForBaseline);- if (baselineRef !== undefined) {- await updateSkillLockEntry(toScope, name, { baselineRef });- }+ const baselineRef = await shadowHeadSha(artifactWriterId(actor), toKeyForBaseline);+ if (baselineRef === undefined) {+ getLogger('skill-move-scope').warn(+ {+ event: 'skill-move-scope.revert-baseline-unset',+ requestId: deferredRequestId,+ handler: 'skill-move-scope',+ toScope,+ toName,+ flush,+ },+ 'no shadow head was readable after the flush, so this move did not establish or update its Revert baseline; any baseline an earlier write recorded is unchanged',+ );+ return;}+ await updateSkillLockEntry(toScope, toName, { baselineRef });} catch (err) {getLogger('skill-move-scope').warn(- { err, name },- 'deferred shadow flush / revert-baseline failed — Revert stays unarmed until the next flush',+ {+ event: 'skill-move-scope.baseline-update-failed',+ requestId: deferredRequestId,+ handler: 'skill-move-scope',+ toScope,+ toName,+ err,+ },+ 'could not record the Revert baseline for the moved skill, so this move did not establish or update its baseline; any baseline an earlier write recorded is unchanged',);}})();}- if (!existsSync(join(toDir, 'SKILL.md'))) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'The move did not leave a readable skill at the destination; nothing was reported as moved.',- { handler: 'skill-move-scope', detail: relative(toBase2, toDir).split(sep).join('/') },- );- return;- }-- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();-- signalChannel?.('files');+ settle();+ recordMoveScopeOutcome('success', undefined, undefined, {+ requestId: getRequestId(_req),+ status: 200,+ droppedLocationCount: unhostableAtDestination.length,+ logLevel: 'debug',+ message: 'cross-scope skill move completed',+ });successResponse(res,200,SkillMoveScopeSuccessSchema,- { scope: toScope, path: relative(toBase2, toDir).split(sep).join('/') },+ {+ scope: toScope,+ path: toDirRel,+ droppedLocations: unhostableAtDestination,+ ...(moveScopeWarnings.length > 0 ? { warnings: moveScopeWarnings } : {}),+ },{ handler: 'skill-move-scope' },);} catch (e) {- errorResponse(- res,+ failMove(500,'urn:ok:error:internal-server-error',- 'Failed to move skill across scopes.',- { handler: 'skill-move-scope', cause: e },+ wrote+ ? 'Failed to move skill across scopes; the move may be partially applied.'+ : 'Failed to move skill across scopes; nothing was written.',+ {+ moveState: wrote ? 'partially-applied' : 'nothing-written',+ detail: wrote+ ? `Inspect the source "${body.fromScope}:${body.name}" and destination "${body.toScope}:${body.toName ?? body.name}" before retrying. Preserve any remaining copies and recover missing files from a backup or available project Timeline / shadow-repo history.`+ : `The failure happened before any file was copied, so no files were copied or removed for "${body.fromScope}:${body.name}" or "${body.toScope}:${body.toName ?? body.name}". Retrying is safe once the underlying error clears.`,+ cause: e,+ },);}},@@ -1303,6 +1999,10 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRoconst handleSkillDuplicate = withValidation(SkillDuplicateRequestSchema,async (_req, res, body) => {+ const settle = settleSkillCatalog;+ let touchedDisk = false;+ let copyStarted = false;+ let copied = false;try {const actor = extractActorIdentity(body as unknown as Record<string, unknown>,@@ -1358,31 +2058,53 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo});return;}+ const targetDirRel = relative(base, targetDir).split(sep).join('/');+ touchedDisk = true;tracedMkdirSync(targetRoot, { recursive: true });+ copyStarted = true;tracedCpSync(sourceDir, targetDir, { recursive: true, dereference: true });- const { fenced, body: sourceBody } = detectFmRegion(source.skillMd);- // presence-exempt: no CRDT write, no agent identity- const renamed = applyPatchToFm(fenced, { name: body.toName });- if (!renamed.ok) {- applySkillDelete({ skillsRoot: targetRoot, name: body.toName });+ copied = true;+ const failCopiedDuplicate = (+ status: 400 | 500,+ detail: string,+ cause: unknown,+ logLevel?: 'debug' | 'warn' | 'error',+ ): void => {+ const cleanup = applySkillDelete({ skillsRoot: targetRoot, name: body.toName });+ settle();errorResponse(res,- 400,- 'urn:ok:error:invalid-request',- 'Failed to write duplicated skill.',+ cleanup.ok ? status : 500,+ cleanup.ok && status === 400+ ? 'urn:ok:error:invalid-request'+ : 'urn:ok:error:internal-server-error',+ cleanup.ok+ ? 'Failed to write duplicated skill; destination copy removed.'+ : 'Failed to write duplicated skill; destination cleanup failed.',{handler: 'skill-duplicate',- detail: renamed.error.kind,+ detail: cleanup.ok+ ? `Duplicate failed (${detail}). The source "${body.scope}:${body.name}" was not touched.`+ : `Duplicate failed (${detail}); destination cleanup failed (${cleanup.error.code}). The source "${body.scope}:${body.name}" was not touched. A partial copy may remain at "${body.scope}:${body.toName}" (${targetDirRel}). Inspect the destination before retrying.`,+ cause: cleanup.ok ? cause : new Error(cleanup.error.message, { cause }),+ ...(logLevel ? { logLevel } : {}),},);+ };+ const synced = applySkillDirNameSync({+ skillDir: targetDir,+ toName: body.toName,+ skillMd: source.skillMd,+ });+ if (!synced.ok) {+ if (synced.stage === 'patch') {+ const failure = describeFmEditError(synced.error);+ failCopiedDuplicate(400, failure, new Error(failure), 'error');+ } else {+ failCopiedDuplicate(500, 'WRITE_FAILED', synced.cause);+ }return;}- try {- tracedWriteFileSync(join(targetDir, 'SKILL.md'), `${renamed.nextFenced}${sourceBody}`);- } catch (error) {- applySkillDelete({ skillsRoot: targetRoot, name: body.toName });- throw error;- }if (body.scope === 'project') {const targetRel = relative(contentDir, targetDir).split(sep).join('/');@@ -1393,10 +2115,7 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo);void commitOkArtifactWrite('skill-duplicate');}- signalChannel?.('files');- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();+ settle();successResponse(res,@@ -1406,12 +2125,25 @@ export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRo{ handler: 'skill-duplicate' },);} catch (e) {+ if (touchedDisk) settle();errorResponse(res,500,'urn:ok:error:internal-server-error','Failed to duplicate skill.',- { handler: 'skill-duplicate', cause: e },+ {+ handler: 'skill-duplicate',+ ...(copied+ ? {+ detail: `A complete copy was created at "${body.scope}:${body.toName}" and was left in place. Inspect it before retrying.`,+ }+ : copyStarted+ ? {+ detail: `A copy of "${body.scope}:${body.name}" was started at "${body.scope}:${body.toName}" and may be incomplete; it was left in place, and its SKILL.md may still carry the source's name. Inspect or remove it before retrying.`,+ }+ : {}),+ cause: e,+ },);}},diff --git a/packages/server/src/http/skills-file-routes.ts b/packages/server/src/http/skills-file-routes.tsindex e92d012c2..9579eca53 100644--- a/packages/server/src/http/skills-file-routes.ts+++ b/packages/server/src/http/skills-file-routes.ts@@ -33,13 +33,19 @@ import { extractActorIdentity } from '../extract-actor-identity.ts';import type { PinoLogger } from '../logger.ts';import { isInternalBundleSkillName } from '../skill-bundles.ts';import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';+import type { ErrorExtensions } from './error-response.ts';import { errorResponse } from './error-response.ts';import { methodRouter } from './method-router.ts';import { withValidation } from './request-validation.ts';import { successResponse } from './success-response.ts';export interface SkillsFileRouteDeps {- validateSkillName: (name: string, res: ServerResponse, handler: string) => boolean;+ validateSkillName: (+ name: string,+ res: ServerResponse,+ handler: string,+ extensions?: ErrorExtensions,+ ) => boolean;parseSkillScope: (raw: string | null,res: ServerResponse,@@ -106,7 +112,7 @@ export interface SkillsFileRouteDeps {lifecycleStatus: 'deleted-upstream' | 'renamed',) => Promise<Map<string, string>>;log: PinoLogger;- commitOkArtifactWrite: (context: string) => Promise<void>;+ commitOkArtifactWrite: (context: string) => Promise<unknown>;recordDerivedMutationsBestEffort: (mutations: DerivedDocumentIndexMutation[],reason: string,diff --git a/packages/server/src/http/skills-import-routes.ts b/packages/server/src/http/skills-import-routes.tsindex ce11d68bf..aad18e1f5 100644--- a/packages/server/src/http/skills-import-routes.ts+++ b/packages/server/src/http/skills-import-routes.ts@@ -319,6 +319,7 @@ export function createSkillsImportRoutes(deps: SkillsImportRouteDeps): ApiRouteGrequested,status: e instanceof SkillFetchError ? 'not-found' : 'failed',warnings: [],+ warningCodes: [],...(e instanceof SkillFetchError ? {} : { error: String(e) }),});continue;@@ -329,7 +330,7 @@ export function createSkillsImportRoutes(deps: SkillsImportRouteDeps): ApiRouteGdirs.find((d) => parseSkillDir(d.dir)?.name === requested) ??dirs.find((d) => d.name === RENAMED_PACK_SKILLS[requested]);if (!found) {- results.push({ requested, status: 'not-found', warnings: [] });+ results.push({ requested, status: 'not-found', warnings: [], warningCodes: [] });continue;}acquiredDir = found.dir;@@ -355,6 +356,7 @@ export function createSkillsImportRoutes(deps: SkillsImportRouteDeps): ApiRouteGrequested,status: 'failed',warnings: [],+ warningCodes: [],error: outcome.detail ?? outcome.title,});continue;@@ -367,6 +369,7 @@ export function createSkillsImportRoutes(deps: SkillsImportRouteDeps): ApiRouteG? { collisionRenamedFrom: outcome.body.collisionRenamedFrom }: {}),warnings: outcome.body.warnings,+ warningCodes: outcome.body.warningCodes,});} catch (e) {getLogger('skills-import-bulk').warn(@@ -377,6 +380,7 @@ export function createSkillsImportRoutes(deps: SkillsImportRouteDeps): ApiRouteGrequested,status: 'failed',warnings: [],+ warningCodes: [],error: e instanceof Error ? e.message : String(e),});} finally {diff --git a/packages/server/src/http/skills-recovery-routes.ts b/packages/server/src/http/skills-recovery-routes.tsindex e75d91a2d..fdda4d34c 100644--- a/packages/server/src/http/skills-recovery-routes.ts+++ b/packages/server/src/http/skills-recovery-routes.ts@@ -364,7 +364,13 @@ export function createSkillsRecoveryRoutes(deps: SkillsRecoveryRouteDeps): ApiRores,200,SkillReimportSuccessSchema,- { name: body.name, updated: false, source: entry.source, warnings: [] },+ {+ name: body.name,+ updated: false,+ source: entry.source,+ warnings: [],+ warningCodes: [],+ },{ handler: 'skill-reimport' },);return;@@ -488,7 +494,13 @@ export function createSkillsRecoveryRoutes(deps: SkillsRecoveryRouteDeps): ApiRoconst named = new Set(body.names);const wellFormed = [...named].filter((name) => {if (isValidSkillName(name)) return true;- results.push({ requested: name, status: 'failed', warnings: [], error: 'INVALID_NAME' });+ results.push({+ requested: name,+ status: 'failed',+ warnings: [],+ error: 'INVALID_NAME',+ warningCodes: [],+ });return false;});const { bySource, unrecorded } = groupReimportNamesBySource(wellFormed, (name) =>@@ -500,7 +512,7 @@ export function createSkillsRecoveryRoutes(deps: SkillsRecoveryRouteDeps): ApiRo),);for (const name of unrecorded) {- results.push({ requested: name, status: 'not-found', warnings: [] });+ results.push({ requested: name, status: 'not-found', warnings: [], warningCodes: [] });}for (const group of bySource) {@@ -531,6 +543,7 @@ export function createSkillsRecoveryRoutes(deps: SkillsRecoveryRouteDeps): ApiRostatus: 'failed',source: group.source,warnings: [],+ warningCodes: [],error: 'INVALID_SOURCE',});}@@ -551,6 +564,7 @@ export function createSkillsRecoveryRoutes(deps: SkillsRecoveryRouteDeps): ApiRostatus: 'failed',source: group.source,warnings: [],+ warningCodes: [],error: e instanceof Error ? e.message : String(e),});}@@ -564,7 +578,12 @@ export function createSkillsRecoveryRoutes(deps: SkillsRecoveryRouteDeps): ApiRolock,);if (!entry) {- results.push({ requested: name, status: 'not-found', warnings: [] });+ results.push({+ requested: name,+ status: 'not-found',+ warnings: [],+ warningCodes: [],+ });continue;}const pick = pickReimportDir(dirs, {@@ -578,6 +597,7 @@ export function createSkillsRecoveryRoutes(deps: SkillsRecoveryRouteDeps): ApiRostatus: 'not-found',source: entry.source,warnings: [],+ warningCodes: [],});continue;}@@ -606,6 +626,7 @@ export function createSkillsRecoveryRoutes(deps: SkillsRecoveryRouteDeps): ApiRostatus: 'failed',source: entry.source,warnings: [],+ warningCodes: [],error: outcome.detail ?? outcome.title,});continue;@@ -615,6 +636,7 @@ export function createSkillsRecoveryRoutes(deps: SkillsRecoveryRouteDeps): ApiRostatus: outcome.body.updated ? 'updated' : 'up-to-date',source: outcome.body.source,warnings: outcome.body.warnings,+ warningCodes: outcome.body.warningCodes,});} catch (e) {getLogger('skills-reimport-bulk').warn(@@ -626,6 +648,7 @@ export function createSkillsRecoveryRoutes(deps: SkillsRecoveryRouteDeps): ApiRostatus: 'failed',source: entry.source,warnings: [],+ warningCodes: [],error: e instanceof Error ? e.message : String(e),});}diff --git a/packages/server/src/installed-skills-marker.test.ts b/packages/server/src/installed-skills-marker.test.tsindex 9d215bf71..21a5b7209 100644--- a/packages/server/src/installed-skills-marker.test.ts+++ b/packages/server/src/installed-skills-marker.test.ts@@ -1,6 +1,6 @@-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { dirname, join } from 'node:path';import { afterEach, beforeEach, describe, expect, test } from 'vitest';import {installedSkillsPath,@@ -19,6 +19,11 @@ const entry = (hosts: string[]) => ({installedAt: '2026-06-05T00:00:00.000Z',});+const seedMarker = (contents: string): void => {+ mkdirSync(dirname(installedSkillsPath(projectDir)), { recursive: true });+ writeFileSync(installedSkillsPath(projectDir), contents, 'utf-8');+};+beforeEach(() => {projectDir = mkdtempSync(join(tmpdir(), 'ok-marker-'));});@@ -66,4 +71,60 @@ describe('installed-skills marker', () => {const state = readInstalledSkills(projectDir);expect(state.skills).toEqual({});});++ test('recording over a corrupt marker refuses and leaves the file byte-identical', async () => {+ await recordSkillInstall(projectDir, 'seed', entry(['claude']));+ const truncated = '{"schema":1,"skills":{"seed":{"hosts":["cla';+ writeFileSync(installedSkillsPath(projectDir), truncated, 'utf-8');++ await expect(recordSkillInstall(projectDir, 'next', entry(['cursor']))).rejects.toThrow(+ /Refusing to rewrite/,+ );+ expect(readFileSync(installedSkillsPath(projectDir), 'utf-8')).toBe(truncated);+ });++ test('recording over a marker version this server cannot read keeps every sibling install', async () => {+ const future = `${JSON.stringify(+ { schema: 2, skills: { seed: { hosts: ['claude'], scope: 'project' } } },+ null,+ 2,+ )}\n`;+ seedMarker(future);++ await expect(recordSkillInstall(projectDir, 'next', entry(['cursor']))).rejects.toThrow(+ /Refusing to rewrite/,+ );+ expect(readFileSync(installedSkillsPath(projectDir), 'utf-8')).toBe(future);+ });++ test('removing over a corrupt marker refuses rather than reporting nothing to remove', async () => {+ const truncated = '{"schema":1,"skills":{"gone":{"hosts":["cla';+ seedMarker(truncated);++ await expect(removeSkillInstall(projectDir, 'gone')).rejects.toThrow(/Refusing to rewrite/);+ expect(readFileSync(installedSkillsPath(projectDir), 'utf-8')).toBe(truncated);+ });++ test('a marker that cannot be opened at all refuses with the errno, not a parse verdict', async () => {+ mkdirSync(installedSkillsPath(projectDir), { recursive: true });++ await expect(recordSkillInstall(projectDir, 'next', entry(['cursor']))).rejects.toThrow(+ /Refusing to rewrite .*: it could not be read \(EISDIR\)/,+ );+ });++ test('an entry field this server does not model survives a sibling record', async () => {+ seedMarker(+ JSON.stringify({+ schema: 1,+ skills: { seed: { ...entry(['claude']), futureField: 'keep-me' } },+ }),+ );++ await recordSkillInstall(projectDir, 'next', entry(['cursor']));++ const state = JSON.parse(readFileSync(installedSkillsPath(projectDir), 'utf-8'));+ expect(state.skills.seed.futureField).toBe('keep-me');+ expect(state.skills.next.hosts).toEqual(['cursor']);+ });});diff --git a/packages/server/src/installed-skills-marker.ts b/packages/server/src/installed-skills-marker.tsindex 53d149766..3dee66dee 100644--- a/packages/server/src/installed-skills-marker.ts+++ b/packages/server/src/installed-skills-marker.ts@@ -9,18 +9,12 @@ import {parseInstalledSkills,} from '@inkeep/open-knowledge-core';import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';-import { tracedMkdir, tracedRename, tracedWriteFile } from './fs-traced.ts';+import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';import { createKeyedSerializer } from './keyed-serializer.ts';import { getLogger } from './logger.ts';const logger = getLogger('installed-skills-marker');-export const TRACED_FS_ADAPTER = {- writeFile: (path: string, content: string, opts: { encoding: 'utf-8'; mode?: number }) =>- tracedWriteFile(path, content, opts),- rename: (from: string, to: string) => tracedRename(from, to),-};-export function installedSkillsPath(projectDir: string): string {return join(projectDir, ...INSTALLED_SKILLS_REL);}@@ -41,6 +35,46 @@ export function readInstalledSkills(projectDir: string): InstalledSkills {}}+type MarkerRead =+ | { ok: true; state: InstalledSkills }+ | { ok: false; reason: string; cause?: unknown };++function readInstalledSkillsForMutation(projectDir: string): MarkerRead {+ const path = installedSkillsPath(projectDir);+ if (!existsSync(path)) return { ok: true, state: emptyInstalledSkills() };+ let raw: string;+ try {+ raw = readFileSync(path, 'utf-8');+ } catch (err) {+ const code = (err as NodeJS.ErrnoException | undefined)?.code;+ if (code === 'ENOENT') return { ok: true, state: emptyInstalledSkills() };+ return {+ ok: false,+ reason: code ? `it could not be read (${code})` : 'it could not be read',+ cause: err,+ };+ }+ const parsed = parseInstalledSkills(raw);+ if (parsed === null) {+ return {+ ok: false,+ reason: 'its contents are not an installed-skills marker this server understands',+ };+ }+ return { ok: true, state: parsed };+}++function requireMutableInstalledSkills(projectDir: string): InstalledSkills {+ const read = readInstalledSkillsForMutation(projectDir);+ if (read.ok) return read.state;+ const path = installedSkillsPath(projectDir);+ logger.error(+ { path, reason: read.reason, err: read.cause },+ 'refusing to rewrite the installed-skills marker because it could not be read — rewriting it would replace every install it records with this one',+ );+ throw new Error(`Refusing to rewrite ${path}: ${read.reason}`);+}+async function writeInstalledSkills(projectDir: string, state: InstalledSkills): Promise<void> {const parsed = InstalledSkillsSchema.safeParse(state);if (!parsed.success) {@@ -52,9 +86,7 @@ async function writeInstalledSkills(projectDir: string, state: InstalledSkills):}const path = installedSkillsPath(projectDir);await tracedMkdir(dirname(path), { recursive: true });- await atomicWriteFile(path, `${JSON.stringify(parsed.data, null, 2)}\n`, {- fs: TRACED_FS_ADAPTER,- });+ await atomicWriteFile(path, `${JSON.stringify(parsed.data, null, 2)}\n`, { fs: tracedAtomicFs });}export async function recordSkillInstall(@@ -63,7 +95,7 @@ export async function recordSkillInstall(entry: InstalledSkillEntry,): Promise<void> {return withMarkerLock(projectDir, async () => {- const state = readInstalledSkills(projectDir);+ const state = requireMutableInstalledSkills(projectDir);await writeInstalledSkills(projectDir, {...state,skills: { ...state.skills, [name]: entry },@@ -76,7 +108,7 @@ export async function removeSkillInstall(name: string,): Promise<InstalledSkillEntry | null> {return withMarkerLock(projectDir, async () => {- const state = readInstalledSkills(projectDir);+ const state = requireMutableInstalledSkills(projectDir);const removed = state.skills[name] ?? null;if (removed === null) return null;const { [name]: _dropped, ...rest } = state.skills;diff --git a/packages/server/src/mcp-local-dispatch-parity.test.ts b/packages/server/src/mcp-local-dispatch-parity.test.tsindex b71fbf58b..2bc99d338 100644--- a/packages/server/src/mcp-local-dispatch-parity.test.ts+++ b/packages/server/src/mcp-local-dispatch-parity.test.ts@@ -9,10 +9,10 @@ import type { AddressInfo } from 'node:net';import { tmpdir } from 'node:os';import { resolve } from 'node:path';import { OK_DIR } from '@inkeep/open-knowledge-core';-import { Client } from '@modelcontextprotocol/sdk/client/index.js';-import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';import { type BootedServer, bootServer } from './boot.ts';import { ConfigSchema } from './config/schema.ts';+import { connectMcpTestClient } from './mcp/client.test-helper.ts';import { createMcpHttpHandler, type McpHttpHandler } from './mcp-http.ts';const TEST_CONFIG = ConfigSchema.parse({});@@ -37,11 +37,8 @@ function seedOkScaffold(projectDir: string): void {writeFileSync(resolve(okDir, '.gitignore'), '', 'utf-8');}-async function connectClient(url: string, name: string): Promise<Client> {- const client = new Client({ name, version: '0.0.0-test' });- await client.connect(new StreamableHTTPClientTransport(new URL(url)));- return client;-}+const connectClient = (url: string, name: string): Promise<Client> =>+ connectMcpTestClient(url, { name, version: '0.0.0-test' });function maskVolatile(result: ToolResult): unknown {return JSON.parse(diff --git a/packages/server/src/mcp/client.test-helper.ts b/packages/server/src/mcp/client.test-helper.tsnew file mode 100644index 000000000..3b3c33602--- /dev/null+++ b/packages/server/src/mcp/client.test-helper.ts@@ -0,0 +1,14 @@+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';++export async function connectMcpTestClient(+ url: string,+ identity?: { name?: string; version?: string },+): Promise<Client> {+ const client = new Client({+ name: identity?.name ?? 'integration-test',+ version: identity?.version ?? '0.0.0',+ });+ await client.connect(new StreamableHTTPClientTransport(new URL(url)));+ return client;+}diff --git a/packages/server/src/mcp/tools/cross-level-move-contract.test.ts b/packages/server/src/mcp/tools/cross-level-move-contract.test.tsnew file mode 100644index 000000000..661f3f6ee--- /dev/null+++ b/packages/server/src/mcp/tools/cross-level-move-contract.test.ts@@ -0,0 +1,160 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, test } from 'vitest';+import { CROSS_LEVEL_TRANSFER_CLAUSE, DROPPED_LOCATIONS_DESCRIPTION } from './move.ts';+import { crossScopeMoveSuccessText } from './skill-target.ts';++const repoFile = (...segments: string[]) =>+ readFileSync(join(import.meta.dir, '../../..', ...segments), 'utf-8');++const PROJECT_SKILL = repoFile('assets', 'skills', 'project', 'SKILL.md');+const MCP_REFERENCE = repoFile('../../docs/content/reference/mcp.mdx');+const SKILLS_REFERENCE = repoFile('../../docs/content/features/skills/reference.mdx');+const CHANGESET = repoFile('../../.changeset/fluffy-clouds-report.md');++function mcpReferenceRow(tool: string): string {+ const row = MCP_REFERENCE.split('\n').find((line) => line.startsWith(`| \`${tool}\` |`));+ if (row === undefined) throw new Error(`no mcp.mdx table row for \`${tool}\``);+ return row;+}++const successText = crossScopeMoveSuccessText({+ fromName: 'trip-log',+ toName: 'trip-log',+ fromScope: 'global',+ toScope: 'project',+ droppedLocations: [],+});++const SURFACES: ReadonlyArray<readonly [string, string]> = [+ ['move `toScope` / `crossScope` clause', CROSS_LEVEL_TRANSFER_CLAUSE],+ ['move `droppedLocations` description', DROPPED_LOCATIONS_DESCRIPTION],+ ['moveSkillCrossScope success text', successText],+ ['project SKILL.md router bullet', PROJECT_SKILL],+ ['docs mcp.mdx `move` row', mcpReferenceRow('move')],+ ['docs features/skills/reference.mdx scope-move paragraph', SKILLS_REFERENCE],+ ['the changeset release note', CHANGESET],+];++const ENUMERATING: ReadonlyArray<readonly [string, string]> = SURFACES.filter(+ ([name]) =>+ name !== 'project SKILL.md router bullet' && name !== 'moveSkillCrossScope success text',+);++const OUTCOME_INDEPENDENT: ReadonlyArray<readonly [string, string]> = SURFACES.filter(+ ([name]) => name !== 'moveSkillCrossScope success text',+);++describe('cross-level skill move — what re-projects and what drops, stated in lockstep', () => {+ test('every surface derives the split from what the destination can host or place, not from a fixed list', () => {+ for (const [name, surface] of SURFACES) {+ expect(surface, name).toMatch(+ /(?:destination|Project|Global) (?:level|scope) can(?:not)? (?:host|place)/i,+ );+ }+ });++ test('the split is stated as a capability, never negated at this clause', () => {+ for (const [name, surface] of SURFACES) {+ expect(surface, name).not.toMatch(+ /(?:destination|Project|Global) (?:level|scope) cannot (?:host|place)/i,+ );+ }+ });++ test('every surface with room names all three dropped classes, editors included', () => {+ for (const [name, surface] of ENUMERATING) {+ expect(surface, `${name} — the \`agents\` hub`).toMatch(/`(?:agents|\.agents\/skills)`/);+ expect(surface, `${name} — custom roots`).toMatch(/custom roots?|Add custom path/);+ expect(surface, `${name} — editors with no root at that level`).toMatch(+ /no skills (?:root|folder) at that (?:level|scope)/,+ );+ }+ });++ test('the router bullet states the rule by cause and still names the field to read', () => {+ expect(PROJECT_SKILL).toContain('only what the destination level can host re-projects');+ expect(PROJECT_SKILL).toContain(+ 'the rest is removed at source, returned as `droppedLocations`',+ );+ });++ test('no surface states the re-add remedy without naming the outcome it holds for', () => {+ const remedy = /re-add(?:ing)?|add the ones|adding them|go back with/gi;+ for (const [name, surface] of OUTCOME_INDEPENDENT) {+ const stated = [...surface.matchAll(remedy)];+ expect(stated.length, `${name} — states the remedy at all`).toBeGreaterThan(0);+ for (const match of stated) {+ expect(+ surface.slice(Math.max(0, match.index - 600), match.index + match[0].length + 600),+ `${name} — the remedy at ${match.index} names the outcome it holds for`,+ ).toMatch(/succe|fail/i);+ }+ }+ });++ test('no surface still claims every occupied location is re-projected', () => {+ for (const [name, surface] of SURFACES) {+ expect(surface, name).not.toMatch(/editor locations it (?:occupied|already occupied)/);+ }+ });+});++describe('the dropped-location remedy an agent is told to run', () => {+ const move = (droppedLocations: readonly string[], toScope: 'project' | 'global') =>+ crossScopeMoveSuccessText({+ fromName: 'trip-log',+ toName: 'trip-log',+ fromScope: toScope === 'project' ? 'global' : 'project',+ toScope,+ droppedLocations,+ });++ test('a hub-reading editor with no destination root gets the `agents` equivalent, not a no-op install', () => {+ const text = move(['lm-studio'], 'project');+ expect(text).toContain('no Project-level skills root');+ expect(text).toContain('install({ name: "trip-log", scope: "project", add: ["agents"] })');+ expect(text).not.toContain('add: ["lm-studio"]');+ });++ test('an editor with no destination root and no hub fallback is told no placement exists', () => {+ const text = move(['antigravity'], 'project');+ expect(text).toContain('no Project-level placement exists');+ expect(text).not.toContain('add: ["antigravity"]');+ });++ test('placeable locations keep the rendered install call and the custom-root base caveat', () => {+ const text = move(['.team/skills', 'agents'], 'global');+ expect(text).toContain(+ 'install({ name: "trip-log", scope: "global", add: [".team/skills", "agents"] })',+ );+ expect(text).toContain('destination base — your home directory —');+ });++ test('a mixed list splits: placeable ones are installed, unplaceable ones are called out', () => {+ const text = move(['agents', 'lm-studio', 'antigravity'], 'project');+ expect(text).toContain('install({ name: "trip-log", scope: "project", add: ["agents"] })');+ expect(text).toContain('lm-studio');+ expect(text).toContain('antigravity');+ expect(text).not.toContain('add: ["agents", "lm-studio", "antigravity"]');+ });++ test('a list mixing all three classes renders one install call naming only the placeable ones', () => {+ const text = move(['agents', '.team/skills', 'lm-studio', 'antigravity'], 'project');+ expect(text).toContain(+ 'install({ name: "trip-log", scope: "project", add: ["agents", ".team/skills"] })',+ );+ expect(text).not.toContain('add: ["agents", ".team/skills", "lm-studio"');+ expect(text).toContain('destination base — the project directory —');+ expect(text).toContain(+ 'lm-studio has no Project-level skills root, so `install` cannot place the skill there',+ );+ expect(text).toContain(+ 'antigravity has no Project-level skills root and does not read the `agents` hub there, so no Project-level placement exists',+ );+ });++ test('nothing dropped means no remedy sentence at all', () => {+ expect(move([], 'global')).not.toContain('install(');+ });+});diff --git a/packages/server/src/mcp/tools/delete.ts b/packages/server/src/mcp/tools/delete.tsindex 2fa3f1dda..a887e0482 100644--- a/packages/server/src/mcp/tools/delete.ts+++ b/packages/server/src/mcp/tools/delete.ts@@ -172,6 +172,12 @@ export function register(server: ServerInstance, deps: DeleteDeps): void {files: looseObjectArray.optional().describe('Per-bundle-file delete results `{ path, ok, existed?, error? }`.'),+ warnings: z+ .array(z.string())+ .optional()+ .describe(+ 'Whole-skill delete only: what the deletion took with it that a caller would not expect from the name alone — a destination copy an earlier failed cross-level move had retained, whose content the server confirmed matched the record before removing it. Absent when there is nothing to report; never present on a bundle-file delete.',+ ),}).optional().describe('Skill delete result (whole skill or specific bundle files).'),diff --git a/packages/server/src/mcp/tools/edit.ts b/packages/server/src/mcp/tools/edit.tsindex 6fccc6f1e..4de0d599c 100644--- a/packages/server/src/mcp/tools/edit.ts+++ b/packages/server/src/mcp/tools/edit.ts@@ -2,6 +2,7 @@ import { existsSync, readFileSync } from 'node:fs';import {type FrontmatterPatch,renderInventoryList,+ SKILL_AUTHORING_WARNING_CODES,stripFrontmatter,unwrapFrontmatterFences,} from '@inkeep/open-knowledge-core';@@ -24,6 +25,7 @@ import { resolveWithinRoot } from './path-safety.ts';import { buildPreviewAttachWarning, resolvePreviewUrl, START_UI_TEXT_HINT } from './preview-url.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {+ AUTHORING_WARNING_CODE_GLOSS,agentIdentityFields,documentResultBaseShape,HOCUSPOCUS_NOT_RUNNING_ERROR,@@ -41,6 +43,8 @@ import {summaryArgSchema,textPlusStructured,textResult,+ WARNING_CODES_CONTRACT,+ WARNINGS_FIELD_CONTRACT,} from './shared.ts';import {fetchSkill,@@ -680,6 +684,16 @@ export function register(server: ServerInstance, deps: EditDeps): void {.boolean().optional().describe('Always false for an edit (the skill already existed).'),+ warnings: z+ .array(z.string())+ .optional()+ .describe(+ `Non-fatal authoring warnings for the SKILL.md that was written. ${WARNINGS_FIELD_CONTRACT}`,+ ),+ warningCodes: z+ .array(z.enum(SKILL_AUTHORING_WARNING_CODES))+ .optional()+ .describe(`${WARNING_CODES_CONTRACT} ${AUTHORING_WARNING_CODE_GLOSS}`),file: z.object({path: z.string(),diff --git a/packages/server/src/mcp/tools/import.test.ts b/packages/server/src/mcp/tools/import.test.tsindex f42831f7e..3d7508b4f 100644--- a/packages/server/src/mcp/tools/import.test.ts+++ b/packages/server/src/mcp/tools/import.test.ts@@ -1,7 +1,7 @@import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { type Config, ConfigSchema } from '../../config/schema.ts';import { register as registerImport } from './import.ts';-import type { ServerInstance } from './shared.ts';+import { type ServerInstance, UNREADABLE_WARNINGS_TEXT } from './shared.ts';const BASE_CONFIG: Config = ConfigSchema.parse({});@@ -140,7 +140,12 @@ describe('import MCP tool', () => {globalThis.fetch = vi.fn(async (url: string | URL | Request) =>String(url).endsWith('/api/skill/import')? new Response(- JSON.stringify({ ok: true, name: 'review-bot', warnings: ['skipped an odd file'] }),+ JSON.stringify({+ ok: true,+ name: 'review-bot',+ warnings: ['Skill name contains "claude".', 'SKILL.md body is 600 lines.'],+ warningCodes: ['skill-name-vendor-word', 'skill-body-too-long'],+ }),{ status: 200, headers: { 'content-type': 'application/json' } },): new Response(@@ -159,10 +164,42 @@ describe('import MCP tool', () => {expect(r.isError).toBeUndefined();expect(text(r)).toContain('hand-edited');expect(r.structuredContent?.warnings).toEqual([- 'skipped an odd file',+ 'Skill name contains "claude".',+ 'SKILL.md body is 600 lines.','The copy at .cursor/skills/review-bot has been hand-edited — refused.',]);- expect(r.structuredContent?.warningCodes).toEqual(['place-fork-refused']);+ expect(r.structuredContent?.warningCodes).toEqual([+ 'skill-name-vendor-word',+ 'skill-body-too-long',+ 'place-fork-refused',+ ]);+ });++ test('an unreadable warnings payload from one step is rendered in the text, not only in the structured field', async () => {+ globalThis.fetch = vi.fn(async (url: string | URL | Request) =>+ String(url).endsWith('/api/skill/import')+ ? new Response(+ JSON.stringify({+ ok: true,+ name: 'review-bot',+ warnings: 'Skipped an unsupported bundle file.',+ warningCodes: ['skill-body-too-long'],+ }),+ { status: 200, headers: { 'content-type': 'application/json' } },+ )+ : new Response(JSON.stringify({ ok: true, warnings: [], warningCodes: [] }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ }),+ ) as unknown as typeof fetch;++ const handler = captureImport('http://localhost:4321');+ const r = await handler({ source: 'acme/skills', add: ['agents'] });++ expect(r.isError).toBeUndefined();+ expect(text(r)).toContain('treat this result as unverified');+ expect(r.structuredContent?.warnings).toEqual([UNREADABLE_WARNINGS_TEXT]);+ expect(r.structuredContent).not.toHaveProperty('warningCodes');});test('a failed placement is reported, not swallowed as a clean import', async () => {diff --git a/packages/server/src/mcp/tools/import.ts b/packages/server/src/mcp/tools/import.tsindex 4775bb852..3d9ecf7ea 100644--- a/packages/server/src/mcp/tools/import.ts+++ b/packages/server/src/mcp/tools/import.ts@@ -1,4 +1,5 @@import {+ SKILL_AUTHORING_WARNING_CODES,SKILL_INSTALL_WARNING_CODES,type SkillLocationId,SkillLocationIdSchema,@@ -10,18 +11,28 @@ import type { LocalApiDispatch } from '../../http/local-api-dispatch.ts';import type { AgentIdentity } from '../agent-identity.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {+ AUTHORING_WARNING_CODE_GLOSS,agentIdentityFields,+ alignWarningCodes,apiTarget,httpPost,+ INSTALL_WARNING_CODE_GLOSS,outputSchemaWithText,ROUTED_CWD_DESCRIPTION,requireProjectServer,summaryArgSchema,textPlusStructured,textResult,+ warningCodesContract,+ warningsFieldContract,} from './shared.ts';import { SkillScopeArg } from './verb-schemas.ts';+const KNOWN_CODES: ReadonlySet<string> = new Set<string>([+ ...SKILL_AUTHORING_WARNING_CODES,+ ...SKILL_INSTALL_WARNING_CODES,+]);+const DESCRIPTION = ['[Requires: Hocuspocus server] Import a skill into this project as versioned content.','',@@ -95,13 +106,13 @@ export function register(server: ServerInstance, deps: ImportDeps): void {.array(z.string()).optional().describe(- 'Non-fatal warnings from BOTH steps: the acquire (skipped unsupported bundle files) and the placement `add` runs.',+ `Non-fatal warnings from BOTH steps: the acquire (skipped unsupported bundle files) first, then the placement \`add\` runs. ${warningsFieldContract('each step')} One step sending an unreadable shape replaces only its own slice of this list; the other step's text still comes through.`,),warningCodes: z- .array(z.enum(SKILL_INSTALL_WARNING_CODES))+ .array(z.enum([...SKILL_AUTHORING_WARNING_CODES, ...SKILL_INSTALL_WARNING_CODES])).optional().describe(- 'Machine-readable codes aligned 1:1 with `warnings` (`warnings[i]` is the display text for `warningCodes[i]`) — switch on these, never on the English. `no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a hand-edited copy was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md.',+ `${warningCodesContract('either step')} Authoring codes (from the imported SKILL.md): ${AUTHORING_WARNING_CODE_GLOSS} Placement codes: ${INSTALL_WARNING_CODE_GLOSS}`,),}),},@@ -154,13 +165,9 @@ export function register(server: ServerInstance, deps: ImportDeps): void {const alreadyImported = result.alreadyImported === true;const renamedFrom =typeof result.collisionRenamedFrom === 'string' ? result.collisionRenamedFrom : undefined;- const warnings = [- ...(Array.isArray(result.warnings) ? (result.warnings as string[]) : []),- ...(Array.isArray(placed.warnings) ? (placed.warnings as string[]) : []),- ];- const warningCodes = Array.isArray(placed.warningCodes)- ? (placed.warningCodes as string[])- : [];+ const acquired = alignWarningCodes(result.warnings, result.warningCodes, KNOWN_CODES);+ const projected = alignWarningCodes(placed.warnings, placed.warningCodes, KNOWN_CODES);+ const warnings = [...acquired.warnings, ...projected.warnings];const line = alreadyImported? `Skill "${name}" was already imported (identical content); its placement was applied.`: `Imported "${name}"${renamedFrom ? ` (renamed from "${renamedFrom}" — the name was taken)` : ''} into .agents/skills as content. Scripts shown, never run. Use \`install\` to change where it lives.`;@@ -170,7 +177,9 @@ export function register(server: ServerInstance, deps: ImportDeps): void {alreadyImported,...(renamedFrom ? { collisionRenamedFrom: renamedFrom } : {}),warnings,- ...(warningCodes.length > 0 ? { warningCodes } : {}),+ ...(acquired.warningCodes && projected.warningCodes+ ? { warningCodes: [...acquired.warningCodes, ...projected.warningCodes] }+ : {}),});},);diff --git a/packages/server/src/mcp/tools/install.test.ts b/packages/server/src/mcp/tools/install.test.tsindex f0c04d81d..8a5501276 100644--- a/packages/server/src/mcp/tools/install.test.ts+++ b/packages/server/src/mcp/tools/install.test.ts@@ -1,7 +1,7 @@import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { type Config, ConfigSchema } from '../../config/schema.ts';import { register as registerInstall } from './install.ts';-import type { ServerInstance } from './shared.ts';+import { type ServerInstance, UNREADABLE_WARNINGS_TEXT } from './shared.ts';const BASE_CONFIG: Config = ConfigSchema.parse({});@@ -122,6 +122,17 @@ describe('install MCP tool', () => {expect(calls).toHaveLength(0);});+ test('`mode` without `add` or `convert` is refused before any request', async () => {+ stubOk();+ const r = await captureInstall('http://localhost:4321')({+ name: 'trip-log',+ mode: 'copy',+ });+ expect(r.isError).toBe(true);+ expect(text(r)).toContain('`mode` needs `add` or `convert`');+ expect(calls).toHaveLength(0);+ });+test('a failed shaping reports what already landed', async () => {globalThis.fetch = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {const body = JSON.parse(String(init?.body)) as Record<string, unknown>;@@ -214,6 +225,16 @@ describe('skillFolders — folder topology, moved off the read-only `config` tooexpect(text(res)).toContain('nothing stopped working');});+ test('an unreadable warnings payload is rendered in the text, not only in the structured field', async () => {+ stubOk({ warnings: 'Nothing was projected.', warningCodes: ['no-targets'] });++ const r = await captureInstall('http://localhost:4321')({ name: 'trip-log', add: ['claude'] });++ expect(r.isError).toBeUndefined();+ expect(text(r)).toContain('treat this result as unverified');+ expect(r.structuredContent?.warnings).toEqual([UNREADABLE_WARNINGS_TEXT]);+ });+test('refuses to combine with `name` — it acts on folders, not one skill', async () => {stubOk();const install = captureInstall('http://localhost:1234');diff --git a/packages/server/src/mcp/tools/install.ts b/packages/server/src/mcp/tools/install.tsindex d64620685..7019acc14 100644--- a/packages/server/src/mcp/tools/install.ts+++ b/packages/server/src/mcp/tools/install.ts@@ -12,19 +12,25 @@ import type { AgentIdentity } from '../agent-identity.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {agentIdentityFields,+ alignWarningCodes,apiTarget,errorTextWithDetail,httpPost,httpPut,+ INSTALL_WARNING_CODE_GLOSS,outputSchemaWithText,ROUTED_CWD_DESCRIPTION,requireProjectServer,summaryArgSchema,textPlusStructured,textResult,+ WARNING_CODES_CONTRACT,+ WARNINGS_FIELD_CONTRACT,} from './shared.ts';import { resolveSkillName, SKILL_NAME_DESCRIBE, SkillScopeArg } from './verb-schemas.ts';+const KNOWN_INSTALL_CODES: ReadonlySet<string> = new Set(SKILL_INSTALL_WARNING_CODES);+const DESCRIPTION = ['[Requires: Hocuspocus server] Manage WHERE a skill is available. A skill is ONE real folder (its SOURCE — the skill itself) plus managed copies/symlinks at other locations. `add`/`remove` change the other locations; `mode` flips copies↔symlinks; `source` moves the real folder. There is NO "uninstall everywhere" and no draft state — a skill with no extra locations still lives (and loads) at its source folder; to make a skill stop existing, use `delete`.','',@@ -34,7 +40,7 @@ const DESCRIPTION = [`- \`name\` — ${SKILL_NAME_DESCRIBE}`,'- `add` — Locations to ADD the skill to (everything else untouched). Editor ids fan out a copy/symlink; a custom root path places the bundle there. Omitting both `add` and `remove` installs into the project-configured editors.','- `remove` — Locations to REMOVE it from (lossless only: a hand-edited fork is refused, never deleted). Works however the agent gets the skill: removing an editor that reads it through a folder alias (its skills folder symlinked into a shared root) automatically unfollows that folder from the root MINUS this skill — the editor keeps its other skills. The SOURCE cannot be removed — its folder is the skill; move it with `source` or use `delete`.',- '- `mode` — `"link"`: a live symlink to the source. `"copy"`: an independent folder, auto-refreshed from the source until hand-edited (a hand-edit forks that copy). Applies ONLY to the locations this call names — the ones in `add`, or the ones in `convert` — and sets no skill-wide default. Omit it on `add` and the new location takes the form the skill already uses.',+ '- `mode` — `"link"`: a live symlink to the source. `"copy"`: an independent folder, auto-refreshed from the source until hand-edited (a hand-edit forks that copy). Applies ONLY to the locations this call names — the ones in `add`, or the ones in `convert` — and sets no skill-wide default. Omit it on `add` and the new location takes the form the skill already uses. Requires `add` or `convert` — passing `mode` alone is refused rather than silently ignored.','- `convert` — Existing locations to change the FORM of, leaving membership alone. Requires `mode`. Pass every location to make them uniform. Lossless both ways; a hand-edited copy is refused rather than overwritten.',"- `source` — Move the skill's REAL folder to this location; the old source becomes a symlink to it. Run alone (not with add/remove).",'- `scope` — `project` (default, shared via git) or `global` (user-level, every project on this machine).',@@ -117,7 +123,7 @@ export function register(server: ServerInstance, deps: InstallDeps): void {.enum(['copy', 'link']).optional().describe(- 'The form for the locations THIS call touches — the ones in `add`, or the ones in `convert`. "link": a pointer to the source, so nothing can drift. "copy": an independent folder, auto-refreshed from the source until hand-edited. Omit on `add` to follow the form the skill already uses. This does not change locations the call does not name, and sets no skill-wide default.',+ 'The form for the locations THIS call touches — the ones in `add`, or the ones in `convert`. "link": a pointer to the source, so nothing can drift. "copy": an independent folder, auto-refreshed from the source until hand-edited. Omit on `add` to follow the form the skill already uses. This does not change locations the call does not name, and sets no skill-wide default. Requires `add` or `convert` — passing `mode` alone is refused rather than silently ignored.',),source: SkillLocationIdSchema.optional().describe("Move the skill's REAL folder to this location (the old source becomes a symlink — never a removal). Run alone, not combined with add/remove.",@@ -145,9 +151,7 @@ export function register(server: ServerInstance, deps: InstallDeps): void {warningCodes: z.array(z.enum(SKILL_INSTALL_WARNING_CODES)).optional()- .describe(- 'Machine-readable codes aligned 1:1 with `warnings` (`warnings[i]` is the display text for `warningCodes[i]`) — switch on these, never on the English. `no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a hand-edited copy was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md.',- ),+ .describe(`${WARNING_CODES_CONTRACT} ${INSTALL_WARNING_CODE_GLOSS}`),scripts: z.boolean().optional()@@ -155,7 +159,9 @@ export function register(server: ServerInstance, deps: InstallDeps): void {warnings: z.array(z.string()).optional()- .describe('Non-fatal install/uninstall warnings from target projection.'),+ .describe(+ `Non-fatal install/uninstall warnings from target projection. ${WARNINGS_FIELD_CONTRACT}`,+ ),folder: z.object({moved: z.array(z.string()).describe('Skill bundles moved into the target root.'),@@ -194,6 +200,22 @@ export function register(server: ServerInstance, deps: InstallDeps): void {}const resolved = resolveSkillName(args.name);if (!resolved.ok) return textResult(`Error: ${resolved.error}`, true);+ if (args.convert !== undefined && args.mode === undefined) {+ return textResult(+ 'Error: `convert` needs `mode` — the form to convert those locations to.',+ true,+ );+ }+ if (+ args.mode !== undefined &&+ (args.add?.length ?? 0) === 0 &&+ (args.convert?.length ?? 0) === 0+ ) {+ return textResult(+ 'Error: `mode` needs `add` or `convert` — name the locations whose form should change.',+ true,+ );+ }const context = await requireProjectServer(deps.resolveCwd,deps.config,@@ -202,13 +224,6 @@ export function register(server: ServerInstance, deps: InstallDeps): void {);if (!context.ok) return context.result;- if (args.convert !== undefined && args.mode === undefined) {- return textResult(- 'Error: `convert` needs `mode` — the form to convert those locations to.',- true,- );- }-for (const target of args.convert ?? []) {const converted = await httpPost(apiTarget(context.url, deps.localApi),@@ -264,24 +279,21 @@ export function register(server: ServerInstance, deps: InstallDeps): void {const hosts = Array.isArray(result.hosts) ? (result.hosts as string[]) : [];const scripts = result.scripts === true;- const warnings = Array.isArray(result.warnings) ? (result.warnings as string[]) : [];- const warningCodes = Array.isArray(result.warningCodes)- ? (result.warningCodes as string[])- : [];+ const aligned = alignWarningCodes(result.warnings, result.warningCodes, KNOWN_INSTALL_CODES);const sourceMovedTo =typeof result.sourceMovedTo === 'string' ? result.sourceMovedTo : undefined;const lines = [sourceMovedTo !== undefined? `Moved skill "${args.name}"'s source folder to ${sourceMovedTo}; other locations now link to it.`: `Skill "${args.name}" now lives at: ${hosts.join(', ') || '(its source folder)'}.`,- ...warnings,+ ...aligned.warnings,];return textPlusStructured(lines.join('\n'), {name: args.name,hosts,scripts,- warnings,- ...(warningCodes.length > 0 ? { warningCodes } : {}),+ warnings: aligned.warnings,+ ...(aligned.warningCodes ? { warningCodes: aligned.warningCodes } : {}),...(sourceMovedTo !== undefined ? { sourceMovedTo } : {}),});},diff --git a/packages/server/src/mcp/tools/move.test.ts b/packages/server/src/mcp/tools/move.test.tsnew file mode 100644index 000000000..12fcb893b--- /dev/null+++ b/packages/server/src/mcp/tools/move.test.ts@@ -0,0 +1,93 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { type Config, ConfigSchema } from '../../config/schema.ts';+import { register as registerMove } from './move.ts';+import type { ServerInstance } from './shared.ts';++const BASE_CONFIG: Config = ConfigSchema.parse({});++interface ToolResult {+ content: Array<{ type: 'text'; text: string }>;+ structuredContent?: Record<string, unknown>;+ isError?: true;+}+type Handler = (args: Record<string, unknown>) => Promise<ToolResult>;++function captureMove(serverUrl: string): Handler {+ let handler: Handler | undefined;+ const server = {+ registerTool(_name: string, _cfg: unknown, h: Handler) {+ handler = h;+ },+ } as unknown as ServerInstance;+ registerMove(server, {+ serverUrl,+ config: BASE_CONFIG,+ resolveCwd: async () => process.cwd(),+ });+ if (!handler) throw new Error('tool did not register');+ return handler;+}++let originalFetch: typeof fetch;+let calls: Array<{ path: string; body: Record<string, unknown> }>;++beforeEach(() => {+ originalFetch = globalThis.fetch;+ calls = [];+ globalThis.fetch = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {+ calls.push({ path: new URL(String(url)).pathname, body: JSON.parse(String(init?.body)) });+ return new Response(JSON.stringify({ ok: true, committed: true, scope: 'global' }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+ }) as unknown as typeof fetch;+});+afterEach(() => {+ globalThis.fetch = originalFetch;+});++describe('move MCP tool — skill dispatch', () => {+ test('a differing `toScope` routes distinct names to the canonical scope-move endpoint', async () => {+ const r = await captureMove('http://localhost:4321')({+ skill: { from: 'trip-log', to: 'fishing-log', toScope: 'global' },+ });+ expect(r.isError).toBeUndefined();+ expect(calls).toEqual([+ {+ path: '/api/skill/move-scope',+ body: {+ name: 'trip-log',+ toName: 'fishing-log',+ fromScope: 'project',+ toScope: 'global',+ },+ },+ ]);+ });++ test('an omitted or equal `toScope` is a same-level rename', async () => {+ const handler = captureMove('http://localhost:4321');+ await handler({ skill: { from: 'trip-log', to: 'fishing-log' } });+ await handler({+ skill: { from: 'trip-log', to: 'fishing-log', scope: 'global', toScope: 'global' },+ });+ expect(calls.map((c) => c.path)).toEqual(['/api/skill', '/api/skill']);+ expect(calls[0]?.body).toEqual({ fromName: 'trip-log', toName: 'fishing-log' });+ expect(calls[1]?.body).toEqual({+ scope: 'global',+ fromName: 'trip-log',+ toName: 'fishing-log',+ });+ });++ test('`skill` combined with flat `from`/`to` is refused before any request', async () => {+ const r = await captureMove('http://localhost:4321')({+ from: 'a',+ to: 'b',+ skill: { from: 'trip-log', to: 'trip-log' },+ });+ expect(r.isError).toBe(true);+ expect(r.content[0]?.text).toContain('not both');+ expect(calls).toHaveLength(0);+ });+});diff --git a/packages/server/src/mcp/tools/move.ts b/packages/server/src/mcp/tools/move.tsindex c13caaa02..725a92ef0 100644--- a/packages/server/src/mcp/tools/move.ts+++ b/packages/server/src/mcp/tools/move.ts@@ -1,6 +1,11 @@import { existsSync, statSync } from 'node:fs';import { join } from 'node:path';-import { MANAGED_ARTIFACT_SCOPES } from '@inkeep/open-knowledge-core';+import {+ MANAGED_ARTIFACT_SCOPES,+ SKILL_MOVE_STATE_CODES,+ SKILL_RETENTION_LEDGER_CODES,+ SKILL_SOURCE_STATE_CODES,+} from '@inkeep/open-knowledge-core';import { z } from 'zod';import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';import type { AgentIdentity } from '../agent-identity.ts';@@ -28,6 +33,12 @@ import {import { moveSkill, moveSkillCrossScope, type SkillScope } from './skill-target.ts';import { resolveTemplatePath } from './verb-schemas.ts';+export const CROSS_LEVEL_TRANSFER_CLAUSE =+ 'history does not transfer; the editor locations the destination level can host are re-projected there, while everything else — the `agents` hub, custom roots, and any editor with no skills root at that level — is removed at the source and not re-created at the destination. Re-add the ones the destination level can place with `install` (every removed location comes back as `droppedLocations`) — but only on a success: on a reported failure `droppedLocations` instead lists what this call had already removed at the source, so installing those at the destination spreads a retained copy rather than restoring anything (see `droppedLocations` for the per-`moveState` split).';++export const DROPPED_LOCATIONS_DESCRIPTION =+ 'Skill cross-level move only: locations the skill occupied at the source that the move did not automatically re-project at the destination — the `agents` hub, custom roots, and any editor with no skills root at that level — as `install` location ids. On a SUCCESS they were removed at the source and not re-created at the destination, and the ones the destination level can place (the `agents` hub and custom roots) go back with `install` as `add`, together with `scope` set to the DESTINATION level; an editor with no skills root there cannot be placed at all — `install` accepts its id and projects nothing, so the move\'s own success text names the equivalent (an editor that reads the `agents` hub at that level takes `add: ["agents"]` instead) or states that no destination-level placement exists. Custom roots resolve against that level\'s base — your home directory at the Global level, the project directory at the Project level — not wherever the root lived before the move. On a FAILURE this is instead the set of source-side placements this call had already removed, and whether the skill moved is what `moveState` says: on `nothing-written`, `destination-removed`, `destination-stray` and the two retained states the source is still there, so do not pass these to `install` at the DESTINATION level — re-add them at the SOURCE level, and retry the move only once that state is resolved. On `destination-unreadable` and `partially-applied` the source removal may already have run, so inspect both locations before re-adding anywhere.';+const DESCRIPTION = ['[Requires: Hocuspocus server] Move or rename a document, folder, or asset through the managed flow at `POST /api/rename-path`. Works for all three — the tool probes the content directory to decide. Inbound wiki-links plus supported inline Markdown links are rewritten across affected docs; renamed assets are reported.','',@@ -35,10 +46,10 @@ const DESCRIPTION = ['- `from` — Current path. Doc: docName (trailing `.md`/`.mdx` stripped). Folder: relative path, no leading/trailing slash. Asset: the file path incl. extension.','- `to` — New path. Same shape as `from`.','- `template` — Move/rename a TEMPLATE instead of a doc/folder/asset: `{ from: "<folder>/<name>", to: "<folder>/<name>" }` (nested — a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc). Mutually exclusive with flat `from`/`to`. Inherited templates are not moved (move the local copy / the owning folder); templates carry no inbound links, so nothing is rewritten.',- '- `skill` — Move/rename a SKILL: `{ from: "<name>", to: "<name>", scope?, toScope? }` (nested). Within one level (omit `toScope`, or `toScope` === `scope`): renames the skill folder and keeps the SKILL.md `name` in sync. ACROSS levels (`toScope` differs from `scope`): moves the skill between the Project level (this KB) and the Global level (your user home); history does NOT transfer (it re-creates fresh in the new level), and the skill is re-projected into the locations it already occupied. Mutually exclusive with flat `from`/`to`.',+ `- \`skill\` — Move/rename a SKILL: \`{ from: "<name>", to: "<name>", scope?, toScope? }\` (nested). Within one level (omit \`toScope\`, or \`toScope\` === \`scope\`): renames the skill folder and keeps the SKILL.md \`name\` in sync. ACROSS levels (\`toScope\` differs from \`scope\`): moves the skill between the Project level (this KB) and the Global level (your user home); ${CROSS_LEVEL_TRANSFER_CLAUSE} Mutually exclusive with flat \`from\`/\`to\`.`,'- `summary` — Optional one-line user-outcome (≤80 chars). If omitted, defaults to "Renamed X → Y". Avoid secrets or PII — persisted to git history.','',- '**Errors:** 400 — invalid path / excluded by `.gitignore`/`.okignore`; 404 — source does not exist; 409 — destination already exists (`colliding[]` returned).',+ `**Errors:** 400 — invalid path / excluded by \`.gitignore\`/\`.okignore\`; 404 — source does not exist; 409 — destination already exists (\`colliding[]\` returned); 500 — a cross-level skill move can leave partial state (source, destination, or both), so it is not a safe blind retry. Every cross-level skill-move failure this handler reports carries a \`moveState\` code whatever its status, and the two refusals that turn on a retained destination copy arrive as 409, not 500 — \`destination-retained-blocking\`, and the \`nothing-written\` collision that carries a \`retentionLedger\` — so read \`moveState\` before retrying regardless of status. The one exception is a response whose \`moveState\`/\`sourceState\`/\`retentionLedger\` triple this build cannot recognise as consistent: all three are withheld and the text says so instead — "The server returned an unrecognized or inconsistent move outcome. Do not remove either copy before comparing the source and destination."`,].join('\n');interface RenameMapping {@@ -168,12 +179,12 @@ export function register(server: ServerInstance, deps: MoveDeps): void {.enum(MANAGED_ARTIFACT_SCOPES).optional().describe(- 'Destination level. Omit (or set equal to `scope`) for a within-level rename. Set to the OTHER level to move the skill across levels (project↔global) — history does not transfer and it lands with no locations beyond its source.',+ `Destination level. Omit (or set equal to \`scope\`) for a within-level rename. Set to the OTHER level to move the skill across levels (project↔global): ${CROSS_LEVEL_TRANSFER_CLAUSE}`,),}).optional().describe(- 'Move/rename a SKILL: `{ from: "<name>", to: "<name>", scope?, toScope? }`. Within one level: renames the skill folder and keeps SKILL.md `name` in sync. Across levels (`toScope` differs from `scope`): moves between Project and Global, resetting history. Mutually exclusive with flat `from`/`to`.',+ `Move/rename a SKILL: \`{ from: "<name>", to: "<name>", scope?, toScope? }\`. Within one level: renames the skill folder and keeps SKILL.md \`name\` in sync. Across levels (\`toScope\` differs from \`scope\`): moves between Project and Global; ${CROSS_LEVEL_TRANSFER_CLAUSE} Mutually exclusive with flat \`from\`/\`to\`.`,),summary: summaryArgSchema.describe('Optional one-line user-outcome (≤80 chars). Defaults to "Renamed X → Y". Persisted to git history.',@@ -224,19 +235,26 @@ export function register(server: ServerInstance, deps: MoveDeps): void {.boolean().optional().describe(- 'Skill cross-level move only: `true` when the skill was moved between the Project and Global levels. History resets; the locations it occupied are re-projected.',+ `Skill cross-level move only: \`true\` when the skill was moved between the Project and Global levels. ${CROSS_LEVEL_TRANSFER_CLAUSE}`,),- skippedBinaryFiles: z- .array(z.string())+ droppedLocations: z.array(z.string()).optional().describe(DROPPED_LOCATIONS_DESCRIPTION),+ moveState: z+ .enum(SKILL_MOVE_STATE_CODES).optional().describe(- 'Skill cross-level move only: bundle files NOT copied because they fall outside the text-only bundle contract (binary or oversize). The move still succeeded and the source is gone, so these are the files you must carry over by hand.',+ 'Skill cross-level move failures only: what is on disk, so you can decide whether to retry. Present on every cross-level skill-move failure this handler reports whose triple this build recognises as consistent, at whatever status it reports it. Do not read it as a 500-only concern: `destination-retained-blocking`, and the `nothing-written` collision that carries a `retentionLedger`, both arrive as 409, while `destination-retained` is the 500. Withheld here, together with `sourceState` and `retentionLedger`, when the three do not form a triple this build recognises as consistent; that case reports "The server returned an unrecognized or inconsistent move outcome. Do not remove either copy before comparing the source and destination." in the text instead, and is to be treated as unknown state, not as an ordinary collision. A request rejected before it runs — wrong method, an oversized or unreadable body, a timeout, or a body that fails schema validation against a differently-versioned server — carries none, as does a transport failure that never reached the server. Treat an absent `moveState` on a failure as unknown state, not as a state that cannot occur. `nothing-written` = THIS call wrote nothing, so it changed neither location; it says nothing about damage an earlier call left behind. Safe to retry once the refusal is addressed. `destination-removed` = the destination copy failed and was cleaned up; the source is intact; safe to retry. `destination-stray` = the destination copy failed and cleanup also failed; the source is intact but a stray copy remains; remove it before retrying. `destination-retained` = source removal failed and the complete destination copy was deliberately kept; a retry will collide with it, so read `sourceState` first. `destination-retained-blocking` = this call refused because the destination is a copy an EARLIER failed move retained; read `sourceState` before touching it — on `intact` it is a redundant duplicate and removing it unblocks the retry, otherwise do not delete it before reconciling it against the source, since it may hold the only copy of files that failed removal already deleted. `destination-unreadable` = the source was removed and the destination is not readable; do not retry, recover from history or a backup. `partially-applied` = an unexpected failure after the copy began left an indeterminate state; inspect both locations before doing anything.',),- bothScopes: z- .boolean()+ sourceState: z+ .enum(SKILL_SOURCE_STATE_CODES)+ .optional()+ .describe(+ 'Skill cross-level move failures only: accompanies both states that report a retained destination — `moveState: destination-retained` (this call kept it) and `moveState: destination-retained-blocking` (an earlier call did, and this retry was refused) — and reports what the SOURCE looked like when its removal failed. Every value is an as-of-then observation: on `destination-retained` this call took it, and on `destination-retained-blocking` it is replayed out of the record the earlier call wrote, so nothing has re-read the source since. `intact` = the source matched the content hash recorded before the move, so the retained destination copy is a redundant duplicate; it is safe to remove before retrying, and removing it is what unblocks the retry. `lossy` = the source no longer matched that hash, so it is partially removed; do not remove either location before recovering the missing source files from the retained copy. `unknown` = the source could not be verified against a known content hash, so whether files were lost is undetermined; do not remove either location before comparing them.',+ ),+ retentionLedger: z+ .enum(SKILL_RETENTION_LEDGER_CODES).optional().describe(- 'Skill cross-level move only: `true` when the destination write succeeded but deleting the source failed, so the skill now exists in BOTH levels and the source copy must be removed manually.',+ 'Skill cross-level move failures only: present when this call could not determine whether the occupant at the destination is a copy an earlier failed move retained. `unreadable` = the retained-destination ledger itself could not be read. `occupant-unverifiable` = the directory at the destination could not be verified against the copy this server recorded — either it could not be read at all, or it carries no SKILL.md to compare — so this server could not confirm whether it is the copy an earlier failed move retained. It accompanies `moveState: nothing-written` — that code is still true of this call, which wrote nothing — but do NOT read it as an ordinary collision: treat the occupant the way you would a `sourceState` other than `intact` and compare it against the source before deleting it. A triple this MCP process cannot recognise as consistent is withheld whole — `moveState`, `sourceState` and `retentionLedger` together — so once any server on this connection can emit this field, treat an absent `retentionLedger` on a `nothing-written` refusal that reports a destination collision (`urn:ok:error:doc-already-exists`) as unverified rather than as an unconditionally safe retry. The other `nothing-written` refusals — invalid arguments, no project root, no usable skill home — never reached a destination occupant to verify, so they stay safe to retry once the refusal is addressed.',),}),},diff --git a/packages/server/src/mcp/tools/output-schema-strictness.test.ts b/packages/server/src/mcp/tools/output-schema-strictness.test.tsindex 3fa818fc4..d600b3ca5 100644--- a/packages/server/src/mcp/tools/output-schema-strictness.test.ts+++ b/packages/server/src/mcp/tools/output-schema-strictness.test.ts@@ -9,11 +9,14 @@ import { afterEach, describe, expect, test, vi } from 'vitest';import { type Config, ConfigSchema } from '../../config/schema.ts';import { register as registerAudit } from './audit.ts';import { register as registerConfig } from './config.ts';+import { register as registerEdit } from './edit.ts';+import { register as registerImport } from './import.ts';import { registerAllTools } from './index.ts';+import { register as registerInstall } from './install.ts';import { register as registerLint } from './lint.ts';import { register as registerPalette } from './palette.ts';import { register as registerSearch } from './search.ts';-import { AUDIT_WARNING_CAP, type ServerInstance } from './shared.ts';+import { AUDIT_WARNING_CAP, type ServerInstance, WARNINGS_FIELD_CONTRACT } from './shared.ts';const BASE_CONFIG: Config = ConfigSchema.parse({});@@ -827,6 +830,66 @@ describe('audit and lint emitted coverage validates against the client schema',}});+describe('the warnings-field contract is single-sourced across every tool that states it', () => {+ const INVARIANT_TAIL = WARNINGS_FIELD_CONTRACT.slice(+ WARNINGS_FIELD_CONTRACT.indexOf('`content[0].text`'),+ );++ function warningsDescriptions(tool: string, container: string | null): string[] {+ const cwd = newProject();+ const captured: Array<{ name: string; outputSchema?: unknown }> = [];+ const server = {+ registerTool(name: string, cfg: { outputSchema?: unknown }) {+ captured.push({ name, outputSchema: cfg.outputSchema });+ },+ tool() {},+ } as unknown as ServerInstance;+ registerAllTools(server, {+ config: BASE_CONFIG,+ resolveCwd: async () => cwd,+ serverUrl: undefined,+ });+ const registered = captured.find((r) => r.name === tool);+ if (!registered?.outputSchema) throw new Error(`${tool} did not register an outputSchema`);+ const found: string[] = [];+ const walk = (node: unknown, key: string | null): void => {+ if (!node || typeof node !== 'object') return;+ const record = node as Record<string, unknown>;+ if (key === 'warnings' && typeof record.description === 'string') {+ found.push(record.description);+ }+ for (const [childKey, child] of Object.entries(record.properties ?? {})) {+ walk(child, childKey);+ }+ for (const branch of ['items', 'anyOf', 'allOf', 'oneOf'] as const) {+ const value = record[branch];+ if (Array.isArray(value)) for (const entry of value) walk(entry, key);+ else if (value) walk(value, key);+ }+ };+ const compiled = compileOutputSchemaForClient(registered.outputSchema);+ const properties = (compiled.properties ?? {}) as Record<string, unknown>;+ walk(container === null ? compiled : properties[container], null);+ return found;+ }++ test.each([+ ['write', 'skill'],+ ['edit', 'skill'],+ ['install', null],+ ['import', null],+ ] as ReadonlyArray<readonly [string, string | null]>)(+ '%s states the same unreadable-payload invariant, verbatim',+ (tool, container) => {+ const descriptions = warningsDescriptions(tool, container);+ expect(descriptions.length).toBeGreaterThan(0);+ for (const description of descriptions) {+ expect(description).toContain(INVARIANT_TAIL);+ }+ },+ );+});+describe('move outputSchema admits the cross-level skill-move payloads (CORR-1)', () => {function moveOutputJsonSchema(): Record<string, unknown> {const cwd = newProject();@@ -854,17 +917,49 @@ describe('move outputSchema admits the cross-level skill-move payloads (CORR-1)'crossScope: true,text: 'Moved skill "trip-log" (Project) → "trip-log" (Global). …',};+ const crossScopeRefusal = {+ ok: false,+ kind: 'skill',+ error: 'A global skill named "fishing-log" already exists.',+ moveState: 'nothing-written',+ droppedLocations: [],+ text: 'Error: A global skill named "fishing-log" already exists.',+ };const crossScopePartialFailure = {ok: false,kind: 'skill',- error: 'source delete failed',- bothScopes: true,- text: 'Partially moved skill … exists in BOTH levels …',+ error: 'Failed to move skill (source removal failed); destination copy retained for recovery.',+ moveState: 'destination-retained',+ sourceState: 'lossy',+ droppedLocations: ['.team/skills', 'agents'],+ text: 'Error: Failed to move skill (source removal failed); destination copy retained for recovery.',+ };+ const crossScopeRefusalWithUnverifiableOccupant = {+ ...crossScopeRefusal,+ retentionLedger: 'occupant-unverifiable',+ };+ const crossScopeRefusalWithUnreadableLedger = {+ ...crossScopeRefusal,+ retentionLedger: 'unreadable',+ };+ const crossScopeSuccessWithDroppedLocations = {+ ...crossScopeSuccess,+ droppedLocations: ['.team/skills', 'agents'],};for (const [label, payload] of [['cross-level success', crossScopeSuccess],- ['cross-level partial-failure (both levels)', crossScopePartialFailure],+ ['cross-level success carrying droppedLocations', crossScopeSuccessWithDroppedLocations],+ ['cross-level refusal (destination taken)', crossScopeRefusal],+ ['cross-level partial failure (destination retained)', crossScopePartialFailure],+ [+ 'cross-level refusal with an unverifiable occupant',+ crossScopeRefusalWithUnverifiableOccupant,+ ],+ [+ 'cross-level refusal with an unreadable retention ledger',+ crossScopeRefusalWithUnreadableLedger,+ ],] as const) {test(`${label} structuredContent validates against the compiled move schema`, () => {const validator = new AjvJsonSchemaValidator();@@ -949,3 +1044,202 @@ describe('share_link outputSchema admits emitted success and error payloads', ()});}});++describe('skill warningCodes normalize across server skew (closed enum, 1:1 with warnings)', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ const skillDeps = () => ({+ config: BASE_CONFIG,+ resolveCwd: async () => newProject(),+ serverUrl: 'http://127.0.0.1:31337',+ });++ const jsonRoutes = (routes: Array<[test: (url: string) => boolean, body: unknown]>) =>+ vi.fn(async (url: string | URL | Request) => {+ const href = String(url);+ const hit = routes.find(([matches]) => matches(href));+ if (!hit) throw new Error(`unexpected fetch: ${href}`);+ return Response.json(hit[1]);+ });++ const expectValidates = (captured: Captured, structured: unknown) => {+ const validate = new AjvJsonSchemaValidator().getValidator(+ compileOutputSchemaForClient(captured.cfg.outputSchema),+ );+ const validation = validate(structured);+ expect(validation.valid, validation.errorMessage).toBe(true);+ };++ test('edit withholds authoring codes a newer server skewed, and keeps every warning', async () => {+ const captured = captureRegistration(registerEdit, skillDeps());+ vi.stubGlobal(+ 'fetch',+ jsonRoutes([+ [+ (href) => href.includes('/api/skill?'),+ { skill: { frontmatter: { description: 'old' }, body: 'body', files: [] } },+ ],+ [+ () => true,+ {+ path: '.agents/skills/review-bot/SKILL.md',+ created: false,+ warnings: ['Skill name contains "claude".', 'A warning from the future.'],+ warningCodes: ['skill-name-vendor-word', 'skill-warning-from-the-future'],+ },+ ],+ ]),+ );++ const result = await captured.handler({ skill: { name: 'review-bot', description: 'new' } });++ expect(result.isError).toBeUndefined();+ expect(result.structuredContent?.skill).toMatchObject({+ warnings: ['Skill name contains "claude".', 'A warning from the future.'],+ });+ expect(result.structuredContent?.skill).not.toHaveProperty('warningCodes');+ expect(result.content[0]?.text).toContain('A warning from the future.');+ expectValidates(captured, result.structuredContent);+ });++ test('import keeps a code-less half text and omits warningCodes rather than reporting an all-clear', async () => {+ const captured = captureRegistration(registerImport, skillDeps());+ vi.stubGlobal(+ 'fetch',+ jsonRoutes([+ [+ (href) => href.endsWith('/api/skill/import'),+ {+ name: 'review-bot',+ warnings: ['Skill name contains "claude".', 'SKILL.md body is 600 lines.'],+ warningCodes: ['skill-name-vendor-word', 'skill-body-too-long'],+ },+ ],+ [() => true, { warnings: ['An older server sent no codes.'] }],+ ]),+ );++ const result = await captured.handler({ source: 'acme/skills', add: ['agents'] });++ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject({+ warnings: [+ 'Skill name contains "claude".',+ 'SKILL.md body is 600 lines.',+ 'An older server sent no codes.',+ ],+ });+ expect(result.structuredContent).not.toHaveProperty('warningCodes');+ expect(result.content[0]?.text).toContain('An older server sent no codes.');+ expectValidates(captured, result.structuredContent);+ });++ test('import withholds codes when a step sent one a newer server invented, and keeps every warning', async () => {+ const captured = captureRegistration(registerImport, skillDeps());+ vi.stubGlobal(+ 'fetch',+ jsonRoutes([+ [(href) => href.endsWith('/api/skill/import'), { name: 'review-bot', warnings: [] }],+ [+ () => true,+ {+ warnings: ['A placement warning from the future.', 'Nothing was projected.'],+ warningCodes: ['place-from-the-future', 'no-targets'],+ },+ ],+ ]),+ );++ const result = await captured.handler({ source: 'acme/skills', add: ['agents'] });++ expect(result.structuredContent).toMatchObject({+ warnings: ['A placement warning from the future.', 'Nothing was projected.'],+ });+ expect(result.structuredContent).not.toHaveProperty('warningCodes');+ expect(result.content[0]?.text).toContain('A placement warning from the future.');+ expectValidates(captured, result.structuredContent);+ });++ test('import emits both arrays empty rather than absent when there are no warnings', async () => {+ const captured = captureRegistration(registerImport, skillDeps());+ vi.stubGlobal(+ 'fetch',+ jsonRoutes([+ [(href) => href.endsWith('/api/skill/import'), { name: 'review-bot', warnings: [] }],+ [() => true, { warnings: [] }],+ ]),+ );++ const result = await captured.handler({ source: 'acme/skills', add: ['agents'] });++ expect(result.structuredContent).toHaveProperty('warnings', []);+ expect(result.structuredContent).toHaveProperty('warningCodes', []);+ expectValidates(captured, result.structuredContent);+ });+ test('install withholds codes on an unknown one, and still emits both arrays when there are none', async () => {+ const skewed = captureRegistration(registerInstall, skillDeps());+ vi.stubGlobal(+ 'fetch',+ jsonRoutes([+ [+ () => true,+ {+ hosts: ['agents'],+ scripts: false,+ warnings: ['A placement warning from the future.', 'Nothing was projected.'],+ warningCodes: ['place-from-the-future', 'no-targets'],+ },+ ],+ ]),+ );++ const skewedResult = await skewed.handler({ name: 'review-bot', add: ['agents'] });++ expect(skewedResult.structuredContent).toMatchObject({+ warnings: ['A placement warning from the future.', 'Nothing was projected.'],+ });+ expect(skewedResult.structuredContent).not.toHaveProperty('warningCodes');+ expect(skewedResult.content[0]?.text).toContain('A placement warning from the future.');+ expectValidates(skewed, skewedResult.structuredContent);++ vi.unstubAllGlobals();+ const quiet = captureRegistration(registerInstall, skillDeps());+ vi.stubGlobal(+ 'fetch',+ jsonRoutes([[() => true, { hosts: ['agents'], scripts: false, warnings: [] }]]),+ );++ const quietResult = await quiet.handler({ name: 'review-bot', add: ['agents'] });++ expect(quietResult.structuredContent).toHaveProperty('warnings', []);+ expect(quietResult.structuredContent).toHaveProperty('warningCodes', []);+ expectValidates(quiet, quietResult.structuredContent);+ });++ test('install keeps a pre-codes server warnings and omits warningCodes rather than reporting an all-clear', async () => {+ const captured = captureRegistration(registerInstall, skillDeps());+ vi.stubGlobal(+ 'fetch',+ jsonRoutes([+ [+ () => true,+ {+ hosts: ['agents'],+ scripts: true,+ warnings: ['This skill ships executable scripts/.'],+ },+ ],+ ]),+ );++ const result = await captured.handler({ name: 'review-bot', add: ['agents'] });++ expect(result.structuredContent).toMatchObject({+ warnings: ['This skill ships executable scripts/.'],+ });+ expect(result.structuredContent).not.toHaveProperty('warningCodes');+ expectValidates(captured, result.structuredContent);+ });+});diff --git a/packages/server/src/mcp/tools/shared.test.ts b/packages/server/src/mcp/tools/shared.test.tsindex a58ceb4e3..1187ecebf 100644--- a/packages/server/src/mcp/tools/shared.test.ts+++ b/packages/server/src/mcp/tools/shared.test.ts@@ -11,6 +11,7 @@ import {import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';import {AUDIT_WARNING_CAP,+ alignWarningCodes,capAuditWarnings,HOCUSPOCUS_NOT_RUNNING_ERROR,httpGet,@@ -24,6 +25,7 @@ import {TEXT_CHANNEL_FIELD,textPlusStructured,textResult,+ UNREADABLE_WARNINGS_TEXT,} from './shared.ts';describe('capAuditWarnings', () => {@@ -732,6 +734,97 @@ describe('parseRenameCollidingPairs — defensive parsing at trust boundary', ()});});+describe('alignWarningCodes — defensive normalization at trust boundary', () => {+ const known: ReadonlySet<string> = new Set(['no-targets', 'scripts-present']);++ test('every warning paired with a code this build knows → text and codes survive in index order', () => {+ expect(+ alignWarningCodes(+ ['Nothing was projected.', 'Ships scripts/.'],+ ['no-targets', 'scripts-present'],+ known,+ ),+ ).toEqual({+ warnings: ['Nothing was projected.', 'Ships scripts/.'],+ warningCodes: ['no-targets', 'scripts-present'],+ });+ });++ test('one code this build does not know → every warning survives, codes are withheld', () => {+ const aligned = alignWarningCodes(+ ['Nothing was projected.', 'A warning from the future.', 'Ships scripts/.'],+ ['no-targets', 'from-the-future', 'scripts-present'],+ known,+ );+ expect(aligned).toEqual({+ warnings: ['Nothing was projected.', 'A warning from the future.', 'Ships scripts/.'],+ });+ expect(aligned).not.toHaveProperty('warningCodes');+ });++ test('every code unknown → every warning survives, codes are withheld', () => {+ const aligned = alignWarningCodes(['One.', 'Two.'], ['from-the-future', 'also-unknown'], known);+ expect(aligned).toEqual({ warnings: ['One.', 'Two.'] });+ expect(aligned).not.toHaveProperty('warningCodes');+ });++ test('more warnings than codes → every warning survives, codes are withheld', () => {+ const aligned = alignWarningCodes(+ ['Nothing was projected.', 'Ships scripts/.'],+ ['no-targets'],+ known,+ );+ expect(aligned).toEqual({ warnings: ['Nothing was projected.', 'Ships scripts/.'] });+ expect(aligned).not.toHaveProperty('warningCodes');+ });++ test('more codes than warnings → the warning survives, codes are withheld', () => {+ const aligned = alignWarningCodes(+ ['Nothing was projected.'],+ ['no-targets', 'scripts-present'],+ known,+ );+ expect(aligned).toEqual({ warnings: ['Nothing was projected.'] });+ expect(aligned).not.toHaveProperty('warningCodes');+ });++ test('a server that sent no warnings at all is the one paired empty all-clear', () => {+ expect(alignWarningCodes(undefined, undefined, known)).toEqual({+ warnings: [],+ warningCodes: [],+ });+ });++ test('a warnings payload this build cannot read is reported, never flattened to an all-clear', () => {+ for (const unreadable of ['Nothing was projected.', null, { warnings: [] }, 7]) {+ const aligned = alignWarningCodes(unreadable, ['no-targets'], known);+ expect(aligned).toEqual({ warnings: [UNREADABLE_WARNINGS_TEXT] });+ expect(aligned).not.toHaveProperty('warningCodes');+ }+ });++ test('an unreadable warnings payload alongside unreadable codes still is not an all-clear', () => {+ const aligned = alignWarningCodes(null, 'no-targets', known);+ expect(aligned).toEqual({ warnings: [UNREADABLE_WARNINGS_TEXT] });+ expect(aligned).not.toHaveProperty('warningCodes');+ });++ test('a non-string warning is rendered as text rather than dropped, so it still counts against the codes', () => {+ const aligned = alignWarningCodes(['Nothing was projected.', 42], ['no-targets'], known);+ expect(aligned).toEqual({ warnings: ['Nothing was projected.', '42'] });+ expect(aligned).not.toHaveProperty('warningCodes');+ });++ test('a non-string warning paired with a known code keeps that pairing, index-aligned', () => {+ expect(+ alignWarningCodes(['Nothing was projected.', 42], ['no-targets', 'scripts-present'], known),+ ).toEqual({+ warnings: ['Nothing was projected.', '42'],+ warningCodes: ['no-targets', 'scripts-present'],+ });+ });+});+describe('okReservedPathRedirect', () => {test('.ok/skills/ path → skill-verb redirect naming write-skill', () => {const msg = okReservedPathRedirect('.ok/skills/research/SKILL');diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.tsindex 2e618534e..f518270a8 100644--- a/packages/server/src/mcp/tools/shared.ts+++ b/packages/server/src/mcp/tools/shared.ts@@ -4,6 +4,7 @@ import {AdvisoryWarningSchema,BrokenLinkSchema,BrokenLinkSuppressionSchema,+ UNREADABLE_WARNINGS_TEXT,validateDocName,} from '@inkeep/open-knowledge-core';import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';@@ -535,6 +536,44 @@ export function parseRenameCollidingPairs(value: unknown): RenameCollisionPair[]});}+export { UNREADABLE_WARNINGS_TEXT };++export function alignWarningCodes(+ warnings: unknown,+ codes: unknown,+ known: ReadonlySet<string>,+): { warnings: string[]; warningCodes?: string[] } {+ if (warnings !== undefined && !Array.isArray(warnings)) {+ return { warnings: [UNREADABLE_WARNINGS_TEXT] };+ }+ const text = (Array.isArray(warnings) ? warnings : []).map((entry) =>+ typeof entry === 'string' ? entry : String(entry),+ );+ const rawCodes = Array.isArray(codes) ? (codes as string[]) : [];+ if (text.length !== rawCodes.length) return { warnings: text };+ return rawCodes.every((code) => known.has(code))+ ? { warnings: text, warningCodes: rawCodes }+ : { warnings: text };+}++export function warningCodesContract(reporter: string): string {+ return `Machine-readable codes aligned 1:1 with \`warnings\` (\`warnings[i]\` is the display text for \`warningCodes[i]\`) — switch on these, never on the English. Absent when ${reporter} sent warning text it did not pair with codes, or paired one with a code this build does not recognise; \`warnings\` still carries the full text either way, so treat a missing field as unknown rather than as an all-clear.`;+}++export const WARNING_CODES_CONTRACT = warningCodesContract('the server');++export function warningsFieldContract(reporter: string): string {+ return `Always emitted, \`[]\` when there were none. \`warningCodes\` accompanies this list 1:1 whenever ${reporter} paired every warning it sent with a code this build recognises; otherwise \`warningCodes\` is absent and this list still carries the full text. \`content[0].text\` lists every warning either way. A \`warnings\` payload in a shape this build cannot read at all becomes one entry saying so, with \`warningCodes\` absent — \`[]\` never means "unreadable".`;+}++export const WARNINGS_FIELD_CONTRACT = warningsFieldContract('the server');++export const AUTHORING_WARNING_CODE_GLOSS =+ '`skill-name-vendor-word`: the name contains a vendor word. `skill-body-too-long`: the body exceeds the 500-line soft cap.';++export const INSTALL_WARNING_CODE_GLOSS =+ '`no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a hand-edited copy was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md.';+export const AUDIT_FILE_CAP = 10;export const AUDIT_FILE_DIAGNOSTIC_CAP = 10;diff --git a/packages/server/src/mcp/tools/skill-target.test.ts b/packages/server/src/mcp/tools/skill-target.test.tsindex 1ecc8e53d..b04bb061f 100644--- a/packages/server/src/mcp/tools/skill-target.test.ts+++ b/packages/server/src/mcp/tools/skill-target.test.ts@@ -1,9 +1,10 @@import { afterEach, describe, expect, test } from 'vitest';-import { HOCUSPOCUS_NOT_RUNNING_ERROR } from './shared.ts';+import { HOCUSPOCUS_NOT_RUNNING_ERROR, UNREADABLE_WARNINGS_TEXT } from './shared.ts';import { deleteSkill, moveSkill, moveSkillCrossScope, writeSkill } from './skill-target.ts';interface ToolResult {content: Array<{ type: 'text'; text: string }>;+ structuredContent?: Record<string, unknown>;isError?: boolean;}@@ -79,27 +80,70 @@ describe('skill verb tools — name grammar short-circuits before the network',});});-describe('moveSkillCrossScope — write-dest-then-delete-source compose', () => {+describe('moveSkill — a same-level rename collision surfaces the RFC 9457 detail', () => {const realFetch = globalThis.fetch;afterEach(() => {globalThis.fetch = realFetch;});- function mockFetch(handler: (method: string, path: string) => Record<string, unknown>) {- const calls: Array<{ method: string; path: string }> = [];- globalThis.fetch = (async (input: string, init?: { method?: string }) => {- const method = init?.method ?? 'GET';- const url = new URL(input);- const path = url.pathname + url.search;- calls.push({ method, path });- const body = handler(method, path);- if (body.ok === false) {- return new Response(JSON.stringify({ error: body.error ?? 'error' }), {- status: typeof body.status === 'number' ? body.status : 500,+ test('the retained-copy safety prose reaches the text channel, not just the title', async () => {+ globalThis.fetch = (async () =>+ new Response(+ JSON.stringify({+ type: 'urn:ok:error:conflict',+ title: 'A skill named "fishing-log" already exists.',+ status: 409,+ detail:+ 'Do NOT delete it before reconciling it against the source: it may hold the only copy of files that failed removal already deleted.',+ }),+ { status: 409, headers: { 'content-type': 'application/problem+json' } },+ )) as typeof fetch;+ const r = (await moveSkill('http://127.0.0.1:9', {+ fromName: 'trip-log',+ toName: 'fishing-log',+ })) as ToolResult;+ expect(r.isError).toBe(true);+ expect(text(r)).toContain('A skill named "fishing-log" already exists.');+ expect(text(r)).toContain(+ 'it may hold the only copy of files that failed removal already deleted',+ );+ expect(r.structuredContent).toMatchObject({+ ok: false,+ kind: 'skill',+ error: 'A skill named "fishing-log" already exists.',+ });+ });+});++describe('moveSkillCrossScope — delegates to the canonical /api/skill/move-scope endpoint', () => {+ const realFetch = globalThis.fetch;+ afterEach(() => {+ globalThis.fetch = realFetch;+ });++ interface Call {+ method: string;+ path: string;+ body: Record<string, unknown>;+ }++ function mockFetch(handler: (call: Call) => Record<string, unknown>) {+ const calls: Call[] = [];+ globalThis.fetch = (async (input: string, init?: { method?: string; body?: string }) => {+ const call: Call = {+ method: init?.method ?? 'GET',+ path: new URL(input).pathname,+ body: init?.body ? (JSON.parse(init.body) as Record<string, unknown>) : {},+ };+ calls.push(call);+ const res = handler(call);+ if (res.ok === false) {+ return new Response(JSON.stringify({ ...res, error: res.error ?? 'error' }), {+ status: typeof res.status === 'number' ? res.status : 500,headers: { 'content-type': 'application/json' },});}- return new Response(JSON.stringify(body), {+ return new Response(JSON.stringify(res), {status: 200,headers: { 'content-type': 'application/json' },});@@ -107,136 +151,278 @@ describe('moveSkillCrossScope — write-dest-then-delete-source compose', () =>return calls;}- const getSourceExistsDestAbsent =- (destScope: 'global' | 'project') => (method: string, path: string) => {- if (method === 'GET') {- if (path.includes(`scope=${destScope}`))- return { ok: false, status: 404, error: 'not found' };- return { ok: true, skill: { frontmatter: { description: 'd' }, body: '## When\n\nx.' } };- }- return { ok: false, error: 'unexpected' };- };-- test('reads source, writes destination, THEN deletes source — and reports the re-projection', async () => {- const base = getSourceExistsDestAbsent('global');- const calls = mockFetch((method, path) => {- if (method === 'PUT') return { ok: true, created: true, path: 'trip-log/SKILL.md' };- if (method === 'DELETE') return { ok: true, existed: true };- return base(method, path);- });- const r = (await moveSkillCrossScope('http://127.0.0.1:9', {+ const move = (toName: string) =>+ moveSkillCrossScope('http://127.0.0.1:9', {fromScope: 'project',toScope: 'global',fromName: 'trip-log',- toName: 'trip-log',- })) as ToolResult;+ toName,+ }) as Promise<ToolResult>;++ test.each(['unreadable', 'future-ledger-reason'])(+ 'an inconsistent retained result cannot advertise an intact source: %s',+ async (retentionLedger) => {+ mockFetch(() => ({+ ok: false,+ status: 409,+ error: 'Move did not complete.',+ detail: 'The destination must be compared with the source.',+ moveState: 'destination-retained',+ sourceState: 'intact',+ retentionLedger,+ droppedLocations: ['agents'],+ }));+ const result = await move('trip-log');+ expect(result.isError).toBe(true);+ expect(text(result)).toContain('The destination must be compared with the source.');+ expect(text(result)).toContain('Do not remove either copy before comparing');+ expect(result.structuredContent).toMatchObject({ droppedLocations: ['agents'] });+ expect(result.structuredContent).not.toHaveProperty('sourceState');+ expect(result.structuredContent).not.toHaveProperty('moveState');+ expect(result.structuredContent).not.toHaveProperty('retentionLedger');+ },+ );++ test('a name-preserving move is one canonical request and reports editor re-projection', async () => {+ const calls = mockFetch(() => ({ ok: true, scope: 'global', path: '.agents/skills/trip-log' }));+ const r = await move('trip-log');expect(r.isError).toBeUndefined();- expect(calls.map((c) => c.method)).toEqual(['GET', 'GET', 'PUT', 'DELETE']);- expect(calls.findIndex((c) => c.method === 'PUT')).toBeLessThan(- calls.findIndex((c) => c.method === 'DELETE'),- );- expect(text(r)).toContain('re-projected');- expect(text(r)).not.toContain('Run `install`');- expect(text(r)).toContain('Global');+ expect(calls).toEqual([+ {+ method: 'POST',+ path: '/api/skill/move-scope',+ body: { name: 'trip-log', fromScope: 'project', toScope: 'global' },+ },+ ]);+ expect(text(r)).toContain('editor locations the Global level can host');+ expect(text(r)).not.toContain('install(');+ expect(text(r)).toContain('(Global)');+ expect(r.structuredContent).toMatchObject({+ ok: true,+ kind: 'skill',+ crossScope: true,+ committed: false,+ droppedLocations: [],+ });+ });++ test('a renaming move is still ONE request, carrying the destination name', async () => {+ const calls = mockFetch(() => ({ ok: true, scope: 'global' }));+ const r = await move('fishing-log');+ expect(r.isError).toBeUndefined();+ expect(calls.map((c) => [c.path, c.body])).toEqual([+ [+ '/api/skill/move-scope',+ { name: 'trip-log', toName: 'fishing-log', fromScope: 'project', toScope: 'global' },+ ],+ ]);+ expect(text(r)).toContain('"fishing-log" (Global)');+ expect(r.structuredContent).toMatchObject({ ok: true, crossScope: true });});- test('refuses to overwrite an existing destination-scope skill (collision guard)', async () => {- const calls = mockFetch((method) => {- if (method === 'GET')- return { ok: true, skill: { frontmatter: { description: 'd' }, body: 'x' } };- return { ok: false, error: 'unexpected' };+ test('dropped locations are named with the install call that restores them', async () => {+ mockFetch(() => ({+ ok: true,+ scope: 'global',+ path: '.agents/skills/trip-log',+ droppedLocations: ['.team/skills', 'agents'],+ }));+ const r = await move('trip-log');+ expect(r.isError).toBeUndefined();+ expect(text(r)).toContain('.team/skills, agents');+ expect(text(r)).toContain(+ 'install({ name: "trip-log", scope: "global", add: [".team/skills", "agents"] })',+ );+ expect(r.structuredContent).toMatchObject({+ droppedLocations: ['.team/skills', 'agents'],});- const r = (await moveSkillCrossScope('http://127.0.0.1:9', {- fromScope: 'project',- toScope: 'global',- fromName: 'trip-log',- toName: 'trip-log',- })) as ToolResult;+ });++ test('the custom-root caveat names the destination base for the direction moved', async () => {+ const dropped = () => ({ ok: true, scope: 'global', droppedLocations: ['.team/skills'] });+ const crossScope = (fromScope: 'project' | 'global', toScope: 'project' | 'global') =>+ moveSkillCrossScope('http://127.0.0.1:9', {+ fromScope,+ toScope,+ fromName: 'trip-log',+ toName: 'trip-log',+ }) as Promise<ToolResult>;++ mockFetch(dropped);+ const toGlobal = await crossScope('project', 'global');+ expect(text(toGlobal)).toContain('destination base — your home directory —');+ expect(text(toGlobal)).not.toContain('the project directory');++ mockFetch(dropped);+ const toProject = await crossScope('global', 'project');+ expect(text(toProject)).toContain('destination base — the project directory —');+ expect(text(toProject)).not.toContain('your home directory');+ });++ test('a failure that destroyed the source ledger still carries the dropped locations', async () => {+ mockFetch(() => ({+ ok: false,+ status: 500,+ error: 'The source was removed, but the destination skill is unreadable.',+ moveState: 'destination-unreadable',+ droppedLocations: ['.team/skills', 'agents'],+ }));+ const r = await move('trip-log');expect(r.isError).toBe(true);- expect(text(r)).toContain('already exists');- expect(calls.some((c) => c.method === 'PUT' || c.method === 'DELETE')).toBe(false);+ expect(r.structuredContent).toMatchObject({+ ok: false,+ moveState: 'destination-unreadable',+ droppedLocations: ['.team/skills', 'agents'],+ });});- test('aborts before any write when the destination scope read fails transiently', async () => {- const calls = mockFetch((method, path) => {- if (method === 'GET') {- if (path.includes('scope=global')) return { ok: false, status: 500, error: 'db down' };- return { ok: true, skill: { frontmatter: { description: 'd' }, body: 'x' } };- }- return { ok: false, error: 'unexpected' };+ test('a retained destination from an earlier failure is not reported as safe to retry', async () => {+ mockFetch(() => ({+ ok: false,+ status: 409,+ error: 'A global skill named "trip-log" already exists.',+ moveState: 'destination-retained-blocking',+ sourceState: 'intact',+ }));+ const r = await move('trip-log');+ expect(r.isError).toBe(true);+ expect(r.structuredContent).toMatchObject({+ moveState: 'destination-retained-blocking',+ sourceState: 'intact',});- const r = (await moveSkillCrossScope('http://127.0.0.1:9', {- fromScope: 'project',- toScope: 'global',- fromName: 'trip-log',- toName: 'trip-log',- })) as ToolResult;+ });++ test('a retained destination with no source state is withheld rather than half-reported', async () => {+ mockFetch(() => ({+ ok: false,+ status: 409,+ error: 'A global skill named "trip-log" already exists.',+ moveState: 'destination-retained-blocking',+ }));+ const r = await move('trip-log');expect(r.isError).toBe(true);- expect(text(r)).toContain('could not verify');- expect(calls.some((c) => c.method === 'PUT' || c.method === 'DELETE')).toBe(false);+ expect(text(r)).toContain('Do not remove either copy before comparing');+ expect(r.structuredContent).not.toHaveProperty('moveState');+ expect(r.structuredContent).not.toHaveProperty('sourceState');+ expect(r.structuredContent).not.toHaveProperty('retentionLedger');});- test('skips a binary bundle file (415) with a warning instead of aborting', async () => {- const calls = mockFetch((method, path) => {- if (method === 'GET') {- if (path.includes('/api/skill-file'))- return { ok: false, status: 415, error: 'unsupported media type' };- if (path.includes('scope=global')) return { ok: false, status: 404, error: 'not found' };- return {- ok: true,- skill: {- frontmatter: { description: 'd' },- body: '## When\n\nx.',- files: [{ path: 'references/diagram.png' }],- },- };- }- if (method === 'PUT') return { ok: true, created: true, path: 'trip-log/SKILL.md' };- if (method === 'DELETE') return { ok: true, existed: true };- return { ok: false, error: 'unexpected' };- });- const r = (await moveSkillCrossScope('http://127.0.0.1:9', {+ test('a refusal before the request is made reports that nothing was written', async () => {+ const calls = mockFetch(() => ({ ok: true, scope: 'global' }));+ const r = (await moveSkillCrossScope(undefined, {fromScope: 'project',toScope: 'global',fromName: 'trip-log',toName: 'trip-log',})) as ToolResult;- expect(r.isError).toBeUndefined();- expect(text(r)).toContain('binary');- expect(text(r)).toContain('references/diagram.png');- expect(calls.some((c) => c.method === 'DELETE')).toBe(true);+ expect(r.isError).toBe(true);+ expect(calls).toHaveLength(0);+ expect(r.structuredContent).toMatchObject({+ ok: false,+ kind: 'skill',+ moveState: 'nothing-written',+ });});- test('a failed source delete reports the skill now lives in BOTH levels', async () => {- const base = getSourceExistsDestAbsent('global');- mockFetch((method, path) => {- if (method === 'PUT') return { ok: true, created: true };- if (method === 'DELETE') return { ok: false, error: 'locked' };- return base(method, path);+ test('an endpoint refusal surfaces its message and attempts nothing else', async () => {+ const calls = mockFetch(() => ({+ ok: false,+ status: 409,+ error: 'A global skill named "trip-log" already exists.',+ moveState: 'nothing-written',+ }));+ const r = await move('fishing-log');+ expect(r.isError).toBe(true);+ expect(text(r)).toContain('already exists');+ expect(calls).toHaveLength(1);+ expect(r.structuredContent).toMatchObject({+ ok: false,+ kind: 'skill',+ moveState: 'nothing-written',});- const r = (await moveSkillCrossScope('http://127.0.0.1:9', {- fromScope: 'project',- toScope: 'global',- fromName: 'trip-log',- toName: 'trip-log',- })) as ToolResult;+ });++ test.each(['unreadable', 'occupant-unverifiable'] as const)(+ 'a %s retention ledger survives the adapter, so the caller can see the occupant is unverified',+ async (retentionLedger) => {+ mockFetch(() => ({+ ok: false,+ status: 409,+ error: 'A global skill named "trip-log" already exists.',+ moveState: 'nothing-written',+ retentionLedger,+ }));+ const r = await move('trip-log');+ expect(r.isError).toBe(true);+ expect(r.structuredContent).toMatchObject({+ moveState: 'nothing-written',+ retentionLedger,+ });+ },+ );++ test('a retentionLedger outside the advertised enum is dropped rather than forwarded', async () => {+ mockFetch(() => ({+ ok: false,+ status: 409,+ error: 'A global skill named "trip-log" already exists.',+ moveState: 'nothing-written',+ retentionLedger: 'some-future-ledger-state',+ }));+ const r = await move('trip-log');expect(r.isError).toBe(true);- expect(text(r)).toContain('BOTH');+ expect(r.structuredContent).not.toHaveProperty('retentionLedger');});- test('a failed destination write aborts WITHOUT deleting the source', async () => {- const base = getSourceExistsDestAbsent('project');- const calls = mockFetch((method, path) => {- if (method === 'PUT') return { ok: false, error: 'disk full' };- return base(method, path);- });- const r = (await moveSkillCrossScope('http://127.0.0.1:9', {- fromScope: 'global',- toScope: 'project',- fromName: 'trip-log',- toName: 'trip-log',- })) as ToolResult;+ test('a moveState outside the advertised enum is dropped rather than forwarded', async () => {+ mockFetch(() => ({+ ok: false,+ status: 500,+ error: 'Failed to move skill across scopes.',+ moveState: 'some-future-state',+ }));+ const r = await move('fishing-log');expect(r.isError).toBe(true);- expect(calls.some((c) => c.method === 'DELETE')).toBe(false);+ expect(r.structuredContent).not.toHaveProperty('moveState');+ });++ test('endpoint details stay in the text channel while the structured error stays the title', async () => {+ const error = 'Cannot move to project scope.';+ mockFetch(() => ({ ok: false, status: 400, error, detail: 'NO_PROJECT_ROOT' }));+ const result = await move('fishing-log');+ expect(text(result)).toBe(`Error: ${error} (NO_PROJECT_ROOT)`);+ expect(result.structuredContent).toMatchObject({ ok: false, error });+ });+});++describe('writeSkill — an unreadable warnings payload reaches BOTH channels', () => {+ const realFetch = globalThis.fetch;+ afterEach(() => {+ globalThis.fetch = realFetch;+ });++ test('a non-array `warnings` is rendered in the text, not only in the structured field', async () => {+ globalThis.fetch = (async () =>+ new Response(+ JSON.stringify({+ ok: true,+ created: true,+ path: '.agents/skills/trip-log/SKILL.md',+ warnings: 'Skill name contains "claude".',+ warningCodes: ['skill-name-vendor-word'],+ }),+ { status: 200, headers: { 'content-type': 'application/json' } },+ )) as typeof fetch;++ const r = (await writeSkill('http://127.0.0.1:9', {+ name: 'trip-log',+ description: 'Use when logging a trip.',+ })) as ToolResult;++ expect(r.isError).toBeUndefined();+ expect(text(r)).toContain('treat this result as unverified');+ expect((r.structuredContent?.skill as { warnings?: unknown })?.warnings).toEqual([+ UNREADABLE_WARNINGS_TEXT,+ ]);});});diff --git a/packages/server/src/mcp/tools/skill-target.ts b/packages/server/src/mcp/tools/skill-target.tsindex 99d949984..6fc3b1220 100644--- a/packages/server/src/mcp/tools/skill-target.ts+++ b/packages/server/src/mcp/tools/skill-target.ts@@ -1,8 +1,20 @@-import type { SkillScope } from '@inkeep/open-knowledge-core';+import {+ ALL_EDITOR_IDS,+ EDITOR_PROJECT_SKILL_ROOT,+ EDITOR_USER_SKILL_ROOT,+ type EditorId,+ HUB_READER_EDITORS,+ interpretSkillMoveFailure,+ normalizeApiWarnings,+ SKILL_AUTHORING_WARNING_CODES,+ type SkillScope,+} from '@inkeep/open-knowledge-core';import type { AgentIdentity } from '../agent-identity.ts';import { resolveSkillPreviewUrl } from './preview-url.ts';import {agentIdentityFields,+ alignWarningCodes,+ errorTextWithDetail,HOCUSPOCUS_NOT_RUNNING_ERROR,httpDelete,httpGet,@@ -15,6 +27,8 @@ import { resolveSkillName } from './verb-schemas.ts';export type { SkillScope };+const KNOWN_AUTHORING_WARNING_CODES: ReadonlySet<string> = new Set(SKILL_AUTHORING_WARNING_CODES);+interface SkillIdentity {summary?: string;identity?: AgentIdentity;@@ -50,16 +64,20 @@ export async function writeSkill(if (!result.ok) return textResult(`Error: ${result.error}`, true);const created = result.created === true;const path = typeof result.path === 'string' ? result.path : undefined;- const warnings = Array.isArray(result.warnings) ? (result.warnings as string[]) : [];+ const aligned = alignWarningCodes(+ result.warnings,+ result.warningCodes,+ KNOWN_AUTHORING_WARNING_CODES,+ );const lines = [`${created ? 'Created' : 'Updated'} skill "${input.name}"${path ? ` (${path})` : ''} — live for that folder's agent. Use \`install\` with \`add\` to put it in your other editors.`,- ...warnings,+ ...aligned.warnings,];const preview = input.lockDir? resolveSkillPreviewUrl(input.scope ?? 'project', input.name, { lockDir: input.lockDir }): null;return textPlusStructured(lines.join('\n'), {- skill: { ok: true, path, created },+ skill: { ok: true, path, created, ...aligned },...(preview ? { previewUrl: preview.url, previewUrlSource: preview.source } : {}),});}@@ -185,12 +203,16 @@ export async function deleteSkill(const result = await httpDelete(url, `/api/skill?${params.toString()}`);if (!result.ok) return textResult(`Error: ${result.error}`, true);const existed = result.existed === true;- return textPlusStructured(+ const warnings = normalizeApiWarnings(result.warnings);+ const lines = [existed? `Deleted skill "${input.name}".`: `Skill "${input.name}" did not exist — nothing to delete.`,- { skill: { ok: true, existed } },- );+ ...warnings,+ ];+ return textPlusStructured(lines.join('\n'), {+ skill: { ok: true, existed, ...(warnings.length > 0 ? { warnings } : {}) },+ });}export async function moveSkill(@@ -211,7 +233,11 @@ export async function moveSkill(});if (!result.ok) {const error = typeof result.error === 'string' ? result.error : 'Skill move failed';- return textPlusStructured(`Error: ${error}`, { ok: false, kind: 'skill', error }, true);+ return textPlusStructured(+ errorTextWithDetail({ ...result, error }),+ { ok: false, kind: 'skill', error },+ true,+ );}const committed = result.committed === true;const from = typeof result.from === 'string' ? result.from : input.fromName;@@ -224,6 +250,66 @@ export async function moveSkill();}+function destinationSkillRoot(entry: string, scope: SkillScope): string | null | undefined {+ if (!(ALL_EDITOR_IDS as readonly string[]).includes(entry)) return undefined;+ const roots = scope === 'global' ? EDITOR_USER_SKILL_ROOT : EDITOR_PROJECT_SKILL_ROOT;+ return roots[entry as EditorId];+}++function readsHubAt(entry: string, scope: SkillScope): boolean {+ return HUB_READER_EDITORS.some((reader) => reader.editorId === entry && reader.scope === scope);+}++export function crossScopeMoveSuccessText(input: {+ fromName: string;+ toName: string;+ fromScope: SkillScope;+ toScope: SkillScope;+ droppedLocations: readonly string[];+}): string {+ const fromLabel = input.fromScope === 'global' ? 'Global' : 'Project';+ const toLabel = input.toScope === 'global' ? 'Global' : 'Project';+ const unhostable = input.droppedLocations.filter(+ (entry) => destinationSkillRoot(entry, input.toScope) === null,+ );+ const hubEquivalent = unhostable.filter((entry) => readsHubAt(entry, input.toScope));+ const noPlacement = unhostable.filter((entry) => !readsHubAt(entry, input.toScope));+ const reinstallable = input.droppedLocations.filter((entry) => !unhostable.includes(entry));+ const list = (entries: readonly string[]) => entries.join(', ');+ const verb = (entries: readonly string[]) => (entries.length === 1 ? 'has' : 'have');++ const lead = `Moved skill "${input.fromName}" (${fromLabel}) → "${input.toName}" (${toLabel}) with its references, scripts, and bundle files, and re-projected it into the editor locations the ${toLabel} level can host. History did not transfer; it starts fresh at the ${toLabel} level.`;+ if (input.droppedLocations.length === 0) return lead;++ const parts = [+ `${lead} It also occupied ${list(input.droppedLocations)}; those were removed at the source and not re-created at the destination.`,+ ];+ if (reinstallable.length > 0) {+ const add = reinstallable.map((entry) => `"${entry}"`).join(', ');+ parts.push(+ `Re-add ${list(reinstallable)} with \`install({ name: "${input.toName}", scope: "${input.toScope}", add: [${add}] })\`.`,+ );+ if (reinstallable.some((entry) => entry.includes('/'))) {+ const destinationBase =+ input.toScope === 'global' ? 'your home directory' : 'the project directory';+ parts.push(+ `Custom roots resolve against the destination base — ${destinationBase} — not wherever the root lived before the move.`,+ );+ }+ }+ if (hubEquivalent.length > 0) {+ parts.push(+ `${list(hubEquivalent)} ${verb(hubEquivalent)} no ${toLabel}-level skills root, so \`install\` cannot place the skill there; ${hubEquivalent.length === 1 ? 'it reads' : 'they read'} the \`agents\` hub at that level, so \`install({ name: "${input.toName}", scope: "${input.toScope}", add: ["agents"] })\` is the equivalent.`,+ );+ }+ if (noPlacement.length > 0) {+ parts.push(+ `${list(noPlacement)} ${verb(noPlacement)} no ${toLabel}-level skills root and ${noPlacement.length === 1 ? 'does' : 'do'} not read the \`agents\` hub there, so no ${toLabel}-level placement exists — \`install\` would accept the id and project nothing.`,+ );+ }+ return parts.join(' ');+}+export async function moveSkillCrossScope(url: string | undefined,input: {@@ -233,110 +319,67 @@ export async function moveSkillCrossScope(toName: string;} & SkillIdentity,) {- const rf = resolveSkillName(input.fromName);- if (!rf.ok) return textResult(`Error: ${rf.error}`, true);- const rt = resolveSkillName(input.toName);- if (!rt.ok) return textResult(`Error: ${rt.error}`, true);- if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);-- const src = await fetchSkill(url, input.fromScope, input.fromName);- if (!src.ok) {- return textPlusStructured(- `Error: ${src.error}`,- { ok: false, kind: 'skill', error: src.error },+ const refuse = (error: string) =>+ textPlusStructured(+ error,+ { ok: false, kind: 'skill', error, moveState: 'nothing-written' as const },true,);- }-- const dest = await fetchSkill(url, input.toScope, input.toName);- if (dest.ok) {- const label = input.toScope === 'global' ? 'Global' : 'Project';- return textPlusStructured(- `Error: a ${label} skill named "${input.toName}" already exists — delete or rename it first (cross-level move will not overwrite it).`,- { ok: false, kind: 'skill', error: 'destination already exists' },- true,- );- }- if (!dest.notFound) {- return textPlusStructured(- `Error: could not verify the ${input.toScope} destination "${input.toName}" is free (${dest.error}); aborting before any write so an existing skill can't be overwritten. Retry once the server is reachable.`,- { ok: false, kind: 'skill', error: dest.error },- true,- );- }+ const rf = resolveSkillName(input.fromName);+ if (!rf.ok) return refuse(`Error: ${rf.error}`);+ const rt = resolveSkillName(input.toName);+ if (!rt.ok) return refuse(`Error: ${rt.error}`);+ if (!url) return refuse(HOCUSPOCUS_NOT_RUNNING_ERROR);- const put = await httpPut(url, '/api/skill', {- scope: input.toScope,- name: input.toName,- body: src.body,- frontmatter: { name: input.toName, description: src.description },+ const moved = await httpPost(url, '/api/skill/move-scope', {+ name: input.fromName,+ ...(input.toName !== input.fromName ? { toName: input.toName } : {}),+ fromScope: input.fromScope,+ toScope: input.toScope,...(input.summary !== undefined ? { summary: input.summary } : {}),...agentIdentityFields(input.identity),});- if (!put.ok) {- const error = typeof put.error === 'string' ? put.error : 'Skill move failed';- return textPlusStructured(`Error: ${error}`, { ok: false, kind: 'skill', error }, true);- }-- const skippedBinary: string[] = [];- for (const file of src.files) {- const read = await readSkillFile(url, input.fromScope, input.fromName, file.path);- if (!read.ok) {- if (read.status === 415) {- skippedBinary.push(file.path);- continue;- }- return textPlusStructured(- `Error: copied skill "${input.toName}" into ${input.toScope} scope, but reading its bundle file "${file.path}" from the source failed (${read.error}); aborting before deleting the source. The original ${input.fromScope} skill is intact — retry or fix the file, then move again. (A partial ${input.toScope} copy may exist; delete it first.)`,- { ok: false, kind: 'skill', error: read.error },- true,- );- }- const copy = await httpPut(url, '/api/skill-file', {- scope: input.toScope,- name: input.toName,- path: file.path,- content: read.text,- ...(input.summary !== undefined ? { summary: input.summary } : {}),- ...agentIdentityFields(input.identity),- });- if (!copy.ok) {- const error = typeof copy.error === 'string' ? copy.error : 'bundle-file copy failed';- return textPlusStructured(- `Error: copied skill "${input.toName}" into ${input.toScope} scope, but copying its bundle file "${file.path}" failed (${error}); aborting before deleting the source. The original ${input.fromScope} skill is intact — retry. (A partial ${input.toScope} copy may exist; delete it first.)`,- { ok: false, kind: 'skill', error },- true,- );- }- }-- const params = new URLSearchParams({ name: input.fromName, scope: input.fromScope });- if (input.summary !== undefined) params.set('summary', input.summary);- appendIdentityParams(params, input.identity);- const del = await httpDelete(url, `/api/skill?${params.toString()}`);- if (!del.ok) {- const error = typeof del.error === 'string' ? del.error : 'source delete failed';+ const readDroppedLocations = (raw: unknown): string[] =>+ Array.isArray(raw) ? raw.filter((entry): entry is string => typeof entry === 'string') : [];+ if (!moved.ok) {+ const error = typeof moved.error === 'string' ? moved.error : 'Skill move failed';+ const outcome = interpretSkillMoveFailure(moved);+ const detail = errorTextWithDetail({ ...moved, error });return textPlusStructured(- `Partially moved skill "${input.fromName}" → ${input.toScope} scope as "${input.toName}", but deleting the ${input.fromScope}-scope original failed (${error}). The skill now exists in BOTH scopes — delete the ${input.fromScope} copy manually. Run \`install\` to project the new ${input.toScope} skill.`,- { ok: false, kind: 'skill', error, bothScopes: true },+ outcome.kind === 'unverified'+ ? `${detail}\nThe server returned an unrecognized or inconsistent move outcome. Do not remove either copy before comparing the source and destination.`+ : detail,+ {+ ok: false,+ kind: 'skill',+ error,+ droppedLocations: readDroppedLocations(moved.droppedLocations),+ ...(outcome.kind === 'coherent'+ ? {+ ...(outcome.moveState ? { moveState: outcome.moveState } : {}),+ ...(outcome.sourceState ? { sourceState: outcome.sourceState } : {}),+ ...(outcome.retentionLedger ? { retentionLedger: outcome.retentionLedger } : {}),+ }+ : {}),+ },true,);}-- const fromLabel = input.fromScope === 'global' ? 'Global' : 'Project';- const toLabel = input.toScope === 'global' ? 'Global' : 'Project';- const skippedNote =- skippedBinary.length > 0- ? ` ${skippedBinary.length} binary/oversize bundle file(s) were NOT copied (outside the text-only bundle contract): ${skippedBinary.join(', ')}.`- : '';+ const droppedLocations = readDroppedLocations(moved.droppedLocations);return textPlusStructured(- `Moved skill "${input.fromName}" (${fromLabel}) → "${input.toName}" (${toLabel}) with its references and scripts, and re-projected into the locations it occupied. History did not transfer — it starts fresh at the ${toLabel} level.${skippedNote}`,+ crossScopeMoveSuccessText({+ fromName: input.fromName,+ toName: input.toName,+ fromScope: input.fromScope,+ toScope: input.toScope,+ droppedLocations,+ }),{ok: true,kind: 'skill',committed: false,crossScope: true,- ...(skippedBinary.length > 0 ? { skippedBinaryFiles: skippedBinary } : {}),+ droppedLocations,},);}diff --git a/packages/server/src/mcp/tools/write.test.ts b/packages/server/src/mcp/tools/write.test.tsindex fe9368099..80430c966 100644--- a/packages/server/src/mcp/tools/write.test.ts+++ b/packages/server/src/mcp/tools/write.test.ts@@ -1,7 +1,17 @@+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { stripFrontmatter } from '@inkeep/open-knowledge-core';-import { describe, expect, it } from 'vitest';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { ConfigSchema } from '../../config/schema.ts';import { splitPayloadFrontmatter } from '../../payload-frontmatter.ts';-import { composeWithFrontmatter, frontmatterIgnoredNote } from './write.ts';+import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';+import type { ServerInstance } from './shared.ts';+import {+ composeWithFrontmatter,+ frontmatterIgnoredNote,+ register as registerWrite,+} from './write.ts';function frontmatterBlockCount(markdown: string): number {let remaining = markdown;@@ -137,3 +147,69 @@ describe('frontmatterIgnoredNote — the two outcomes are distinguishable', () =expect(frontmatterIgnoredNote('replace', '---\ntitle: Fine\n---\nbody\n')).toBeNull();});});++describe('write({ skill }) with bundle files — the per-file report reaches both text channels', () => {+ interface ToolResult {+ content: Array<{ type: 'text'; text: string }>;+ structuredContent?: Record<string, unknown>;+ isError?: true;+ }+ type Handler = (args: Record<string, unknown>) => Promise<ToolResult>;++ let testServer: FetchTestServer;+ let cwd: string;+ let handler: Handler;++ beforeAll(async () => {+ testServer = await startFetchTestServer({+ hostname: '127.0.0.1',+ fetch(request) {+ const { pathname } = new URL(request.url);+ if (pathname === '/api/skill') {+ return Response.json({+ ok: true,+ path: '.agents/skills/trip-log/SKILL.md',+ created: true,+ });+ }+ return Response.json({ error: 'Bundle file rejected by the server.' }, { status: 500 });+ },+ });+ cwd = mkdtempSync(join(tmpdir(), 'ok-write-skill-files-'));+ mkdirSync(join(cwd, '.ok'), { recursive: true });++ let captured: Handler | null = null;+ const server = {+ registerTool(_name: string, _cfg: unknown, toolHandler: Handler) {+ captured = toolHandler;+ },+ } as unknown as ServerInstance;+ registerWrite(server, {+ serverUrl: `http://127.0.0.1:${testServer.port}`,+ config: ConfigSchema.parse({}),+ resolveCwd: async () => cwd,+ });+ if (captured === null) throw new Error('write tool did not register');+ handler = captured;+ });++ afterAll(() => {+ testServer.stop();+ rmSync(cwd, { recursive: true, force: true });+ });++ it('mirrors a failed bundle file into structuredContent.text, not just content[0].text', async () => {+ const result = await handler({+ skill: {+ name: 'trip-log',+ description: 'Use when logging a fishing trip.',+ files: [{ path: 'references/gear.md', content: '# Gear\n' }],+ },+ });++ expect(result.isError).toBe(true);+ expect(result.content[0]?.text).toContain('0/1 bundle file(s) written.');+ expect(result.content[0]?.text).toContain('Failed references/gear.md');+ expect(result.structuredContent?.text).toBe(result.content[0]?.text);+ });+});diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.tsindex ce5fd8638..64246770b 100644--- a/packages/server/src/mcp/tools/write.ts+++ b/packages/server/src/mcp/tools/write.ts@@ -8,6 +8,7 @@ import {normalizeBridge,parseFrontmatterYaml,renderInventoryFooter,+ SKILL_AUTHORING_WARNING_CODES,serializeFrontmatterMap,stripFrontmatter,unwrapFrontmatterFences,@@ -38,6 +39,7 @@ import {import { buildPreviewAttachWarning, resolvePreviewUrl, START_UI_TEXT_HINT } from './preview-url.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {+ AUTHORING_WARNING_CODE_GLOSS,agentIdentityFields,apiTarget,docExtensionOnDisk,@@ -58,6 +60,8 @@ import {summaryArgSchema,textPlusStructured,textResult,+ WARNING_CODES_CONTRACT,+ WARNINGS_FIELD_CONTRACT,} from './shared.ts';import { writeSkill, writeSkillFile } from './skill-target.ts';import {@@ -632,8 +636,9 @@ async function handleSkillWrite(| Record<string, unknown>| undefined) ?? {};const baseSkill = (baseStructured.skill as Record<string, unknown> | undefined) ?? { ok: true };+ const { text: _skillMdOnlyText, ...baseWithoutText } = baseStructured;const structured: Record<string, unknown> = {- ...baseStructured,+ ...baseWithoutText,skill: { ...baseSkill, ...(files.length > 0 ? { files: fileResults } : {}) },};@@ -959,6 +964,16 @@ export function register(server: ServerInstance, deps: WriteDeps): void {files: looseObjectArray.optional().describe('Per-bundle-file results `{ path, kind, created, ok, error? }`.'),+ warnings: z+ .array(z.string())+ .optional()+ .describe(+ `Non-fatal authoring warnings for the SKILL.md that was written. ${WARNINGS_FIELD_CONTRACT}`,+ ),+ warningCodes: z+ .array(z.enum(SKILL_AUTHORING_WARNING_CODES))+ .optional()+ .describe(`${WARNING_CODES_CONTRACT} ${AUTHORING_WARNING_CODE_GLOSS}`),}).optional().describe('Skill-create result (SKILL.md and/or bundle files).'),diff --git a/packages/server/src/services/skill-import.ts b/packages/server/src/services/skill-import.tsindex e0067443e..ef20f4474 100644--- a/packages/server/src/services/skill-import.ts+++ b/packages/server/src/services/skill-import.ts@@ -79,7 +79,7 @@ export interface SkillImportDeps {resolveSkillDirForRead: (scope: 'project' | 'global', name: string) => string | null;parseFrontmatterDoc: (raw: string) => { frontmatter: Record<string, unknown>; body: string };attributeOkArtifactWrite: (actor: ActorIdentity, keyPath: string, summary: string) => void;- commitOkArtifactWrite: (context: string) => Promise<void>;+ commitOkArtifactWrite: (context: string) => Promise<unknown>;shadowHeadSha: (writerId?: string, verifyPathRel?: string) => Promise<string | undefined>;artifactWriterId: (actor: ActorIdentity) => string | undefined;effectiveInstallMode: (@@ -178,6 +178,7 @@ export function createSkillImportService(deps: SkillImportDeps): SkillImportServalreadyImported: true,provenance: { source: sourceLabel, ref, contentHash: acquired.contentHash, publisher },warnings: [],+ warningCodes: [],},};}@@ -327,6 +328,7 @@ export function createSkillImportService(deps: SkillImportDeps): SkillImportServ...(collided ? { collisionRenamedFrom: acquired.name } : {}),provenance: { source: sourceLabel, ref, contentHash: acquired.contentHash, publisher },warnings,+ warningCodes: wr.warningCodes,},};},diff --git a/packages/server/src/services/skill-install-ops.ts b/packages/server/src/services/skill-install-ops.tsindex 34f615f50..6d472a5a8 100644--- a/packages/server/src/services/skill-install-ops.ts+++ b/packages/server/src/services/skill-install-ops.ts@@ -1,9 +1,7 @@-import { existsSync, lstatSync, readFileSync } from 'node:fs';+import { existsSync, lstatSync } from 'node:fs';import { dirname, join, relative, resolve, sep } from 'node:path';import {AGENTS_SKILLS_ROOT,- applyPatchToFm,- detectFmRegion,EDITOR_PROJECT_SKILL_ROOT,EDITOR_USER_SKILL_ROOT,type EditorId,@@ -12,13 +10,13 @@ import {type SkillInstallWarningCode,} from '@inkeep/open-knowledge-core';import { parseSkillDir, type SkillHostId } from '@inkeep/open-knowledge-core/skills-catalog';+import { applySkillDirNameSync } from '../content/skills-write.ts';import {tracedCpSync,tracedMkdirSync,tracedRenameSync,tracedRmSync,tracedSymlinkSync,- tracedWriteFileSync,} from '../fs-traced.ts';import {scanGlobalInPlaceSkills,@@ -229,27 +227,22 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillIn}const dest = resolve(inPlaceScanBase, forkRootRel, toName);tracedRenameSync(forkDir, dest);- const skillMdPath = resolve(dest, 'SKILL.md');- try {- const raw = readFileSync(skillMdPath, 'utf-8');- const { fenced, body: skillBody } = detectFmRegion(raw);- const renamed = applyPatchToFm(fenced, { name: toName });- if (renamed.ok) {- tracedWriteFileSync(skillMdPath, `${renamed.nextFenced}${skillBody}`);- } else {+ const synced = applySkillDirNameSync({ skillDir: dest, toName });+ if (!synced.ok) {+ if (synced.stage === 'patch') {log.warn(- { name: toName, reason: renamed.error.kind },+ { name: toName, reason: synced.error.kind },'[skill-fork] frontmatter rename failed',);forkWarnings.push(`Renamed the folder to "${toName}", but its SKILL.md still declares the old name — edit the frontmatter to match.`,);+ } else {+ log.warn({ name: toName, err: synced.cause }, '[skill-fork] frontmatter rename failed');+ forkWarnings.push(+ `Renamed the folder to "${toName}", but its SKILL.md could not be updated — edit the frontmatter to match.`,+ );}- } catch (e) {- log.warn({ name: toName, err: e }, '[skill-fork] frontmatter rename failed');- forkWarnings.push(- `Renamed the folder to "${toName}", but its SKILL.md could not be updated — edit the frontmatter to match.`,- );}}return { ok: true, warnings: forkWarnings };diff --git a/packages/server/src/services/skill-reimport.ts b/packages/server/src/services/skill-reimport.tsindex 8df195048..ea52af73e 100644--- a/packages/server/src/services/skill-reimport.ts+++ b/packages/server/src/services/skill-reimport.ts@@ -47,7 +47,7 @@ export interface SkillReimportDeps {) => { root: string; dirRel: string; realDir: string | null };parseFrontmatterDoc: (raw: string) => { frontmatter: Record<string, unknown>; body: string };attributeOkArtifactWrite: (actor: ActorIdentity, keyPath: string, summary: string) => void;- commitOkArtifactWrite: (context: string) => Promise<void>;+ commitOkArtifactWrite: (context: string) => Promise<unknown>;shadowHeadSha: (writerId?: string, verifyPathRel?: string) => Promise<string | undefined>;artifactWriterId: (actor: ActorIdentity) => string | undefined;skillArtifactKey: (name: string) => string;@@ -198,7 +198,10 @@ export function createSkillReimportService(deps: SkillReimportDeps): SkillReimpo: null,});if (upToDate) {- return { ok: true, body: { name, updated: false, source: entry.source, warnings: [] } };+ return {+ ok: true,+ body: { name, updated: false, source: entry.source, warnings: [], warningCodes: [] },+ };}const acquiredDoc = deps.parseFrontmatterDoc(acquired.skillMd);@@ -226,6 +229,7 @@ export function createSkillReimportService(deps: SkillReimportDeps): SkillReimpoupstreamBody: skillBody,...(gitTracked !== undefined ? { gitTracked } : {}),warnings: [],+ warningCodes: [],},};}@@ -330,7 +334,16 @@ export function createSkillReimportService(deps: SkillReimportDeps): SkillReimpo}deps.signalFiles();- return { ok: true, body: { name, updated: true, source: entry.source, warnings } };+ return {+ ok: true,+ body: {+ name,+ updated: true,+ source: entry.source,+ warnings,+ warningCodes: wr.warningCodes,+ },+ };},};}diff --git a/packages/server/src/skill-move-retained-store.test.ts b/packages/server/src/skill-move-retained-store.test.tsnew file mode 100644index 000000000..c6b40dc72--- /dev/null+++ b/packages/server/src/skill-move-retained-store.test.ts@@ -0,0 +1,193 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import {+ clearSkillMoveRetention,+ readSkillMoveRetention,+ recordSkillMoveRetention,+} from './skill-move-retained-store.ts';++let base: string;++const ledgerPath = () => join(base, '.ok', 'local', 'skill-move-retained.json');++const seedLedger = (contents: string): void => {+ mkdirSync(join(base, '.ok', 'local'), { recursive: true });+ writeFileSync(ledgerPath(), contents);+};++const record = {+ retainedAt: '2026-09-08T00:00:00.000Z',+ from: 'project:alpha',+ to: 'global:alpha',+ sourceState: 'intact' as const,+ reason: 'UNLINK_FAILED',+ retainedContentHash: 'hash-alpha',+};++beforeEach(() => {+ base = mkdtempSync(join(tmpdir(), 'ok-move-retained-'));+});++afterEach(() => {+ rmSync(base, { recursive: true, force: true });+});++describe('skill move retained store', () => {+ test('a recorded retention reads back its source state, origin and destination fingerprint', async () => {+ await recordSkillMoveRetention(base, 'global', 'alpha', record);++ expect(readSkillMoveRetention(base, 'global', 'alpha')).toEqual({+ state: 'record',+ record,+ });+ });++ test('a retention is keyed by destination identity, not by name alone', async () => {+ await recordSkillMoveRetention(base, 'global', 'alpha', record);++ expect(readSkillMoveRetention(base, 'project', 'alpha')).toEqual({ state: 'none' });+ expect(readSkillMoveRetention(base, 'global', 'beta')).toEqual({ state: 'none' });+ });++ test('the ledger lives under .ok/local and keeps the full payload for operators', async () => {+ await recordSkillMoveRetention(base, 'global', 'alpha', record);++ expect(existsSync(ledgerPath())).toBe(true);+ expect(JSON.parse(readFileSync(ledgerPath(), 'utf-8'))).toEqual({+ schema: 1,+ retained: { 'global:alpha': record },+ });+ });++ test('clearing a retention removes it and leaves siblings intact', async () => {+ await recordSkillMoveRetention(base, 'global', 'alpha', record);+ await recordSkillMoveRetention(base, 'global', 'beta', {+ ...record,+ from: 'project:beta',+ to: 'global:beta',+ });++ await clearSkillMoveRetention(base, 'global', 'alpha');++ expect(readSkillMoveRetention(base, 'global', 'alpha')).toEqual({ state: 'none' });+ const beta = readSkillMoveRetention(base, 'global', 'beta');+ expect(beta.state === 'record' && beta.record.from).toBe('project:beta');+ });++ test('clearing an absent retention does not create a ledger', async () => {+ await clearSkillMoveRetention(base, 'global', 'alpha');++ expect(existsSync(ledgerPath())).toBe(false);+ });++ test('an unreadable ledger reads as unreadable, not as absent', () => {+ seedLedger('{ this is not json');++ expect(readSkillMoveRetention(base, 'global', 'alpha')).toEqual({+ state: 'unreadable',+ reason: 'it is not valid JSON',+ });+ });++ test('a ledger written by a schema this server does not understand reads as unreadable', () => {+ seedLedger(JSON.stringify({ schema: 2, retained: { 'global:alpha': record } }));++ expect(readSkillMoveRetention(base, 'global', 'alpha').state).toBe('unreadable');+ });++ test('recording over an unreadable ledger rejects and leaves the file byte-identical', async () => {+ const truncated = '{"schema":1,"retained":{"global:beta":{"sourceSt';+ seedLedger(truncated);++ await expect(recordSkillMoveRetention(base, 'global', 'alpha', record)).rejects.toThrow(+ /Refusing to rewrite/,+ );+ expect(readFileSync(ledgerPath(), 'utf-8')).toBe(truncated);+ });++ test('recording over a ledger this server cannot version-match leaves every sibling record intact', async () => {+ const future = `${JSON.stringify(+ {+ schema: 2,+ retained: {+ 'global:beta': { ...record, from: 'project:beta', sourceState: 'catastrophic' },+ },+ },+ null,+ 2,+ )}\n`;+ seedLedger(future);++ await expect(recordSkillMoveRetention(base, 'global', 'alpha', record)).rejects.toThrow(+ /Refusing to rewrite/,+ );+ expect(readFileSync(ledgerPath(), 'utf-8')).toBe(future);+ });++ test('a present record with an unusable source state degrades to unknown, not to absent', () => {+ seedLedger(+ JSON.stringify({+ schema: 1,+ retained: { 'global:alpha': { ...record, sourceState: 'totally-fine' } },+ }),+ );++ expect(readSkillMoveRetention(base, 'global', 'alpha')).toEqual({+ state: 'record',+ record: { ...record, sourceState: 'unknown' },+ });+ });++ test('a present key that is not a record still counts as a retention, not as an absence', () => {+ seedLedger(JSON.stringify({ schema: 1, retained: { 'global:alpha': 'wat' } }));++ expect(readSkillMoveRetention(base, 'global', 'alpha')).toEqual({+ state: 'record',+ record: {+ retainedAt: '',+ from: '',+ to: '',+ sourceState: 'unknown',+ reason: '',+ retainedContentHash: '',+ },+ });+ });++ test('a record with no usable origin reports it empty rather than inventing one', () => {+ seedLedger(+ JSON.stringify({ schema: 1, retained: { 'global:alpha': { sourceState: 'lossy' } } }),+ );++ expect(readSkillMoveRetention(base, 'global', 'alpha')).toEqual({+ state: 'record',+ record: {+ retainedAt: '',+ from: '',+ to: '',+ sourceState: 'lossy',+ reason: '',+ retainedContentHash: '',+ },+ });+ });++ test('concurrent records for different skills all survive', async () => {+ await Promise.all(+ ['alpha', 'beta', 'gamma'].map((name) =>+ recordSkillMoveRetention(base, 'global', name, {+ ...record,+ from: `project:${name}`,+ to: `global:${name}`,+ }),+ ),+ );++ for (const name of ['alpha', 'beta', 'gamma']) {+ const read = readSkillMoveRetention(base, 'global', name);+ expect(read.state === 'record' && read.record.from).toBe(`project:${name}`);+ }+ });+});diff --git a/packages/server/src/skill-move-retained-store.ts b/packages/server/src/skill-move-retained-store.tsnew file mode 100644index 000000000..c161b7a4c--- /dev/null+++ b/packages/server/src/skill-move-retained-store.ts@@ -0,0 +1,169 @@+import { existsSync, readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { isSkillSourceStateCode, type SkillSourceStateCode } from '@inkeep/open-knowledge-core';+import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';+import { getLocalDir } from './config/paths.ts';+import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';+import { createKeyedSerializer } from './keyed-serializer.ts';+import { getLogger } from './logger.ts';++const RETAINED_FILENAME = 'skill-move-retained.json';+const SCHEMA_VERSION = 1;++export type SkillMoveScope = 'project' | 'global';++export interface SkillMoveRetentionRecord {+ retainedAt: string;+ from: string;+ to: string;+ sourceState: SkillSourceStateCode;+ reason: string;+ retainedContentHash: string;+}++interface SkillMoveRetainedStore {+ schema: number;+ retained: Record<string, SkillMoveRetentionRecord>;+}++export type SkillMoveRetentionRead =+ | { state: 'none' }+ | { state: 'unreadable'; reason: string; cause?: unknown }+ | { state: 'record'; record: SkillMoveRetentionRecord };++function retainedKey(scope: SkillMoveScope, name: string): string {+ return `${scope}:${name}`;+}++function retainedPath(base: string): string {+ return join(getLocalDir(base), RETAINED_FILENAME);+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function str(value: unknown): string {+ return typeof value === 'string' ? value : '';+}++type StoreRead =+ | { ok: true; store: SkillMoveRetainedStore }+ | { ok: false; reason: string; cause?: unknown };++const emptyStore = (): StoreRead => ({+ ok: true,+ store: { schema: SCHEMA_VERSION, retained: {} },+});++function readStore(base: string): StoreRead {+ const path = retainedPath(base);+ if (!existsSync(path)) return emptyStore();+ let raw: string;+ try {+ raw = readFileSync(path, 'utf-8');+ } catch (err) {+ const code = (err as NodeJS.ErrnoException | undefined)?.code;+ if (code === 'ENOENT') return emptyStore();+ return {+ ok: false,+ reason: code ? `it could not be read (${code})` : 'it could not be read',+ cause: err,+ };+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return { ok: false, reason: 'it is not valid JSON' };+ }+ if (!isRecord(parsed) || !isRecord(parsed.retained)) {+ return { ok: false, reason: 'its contents are not a retained-record ledger' };+ }+ if (parsed.schema !== SCHEMA_VERSION) {+ return {+ ok: false,+ reason:+ typeof parsed.schema === 'number'+ ? `it declares schema ${parsed.schema}, which this server does not understand (it writes schema ${SCHEMA_VERSION})`+ : `it declares a schema this server does not understand (it writes schema ${SCHEMA_VERSION})`,+ };+ }+ const retained: Record<string, SkillMoveRetentionRecord> = {};+ for (const [key, value] of Object.entries(parsed.retained)) {+ const fields = isRecord(value) ? value : {};+ retained[key] = {+ retainedAt: str(fields.retainedAt),+ from: str(fields.from),+ to: str(fields.to),+ sourceState: isSkillSourceStateCode(fields.sourceState) ? fields.sourceState : 'unknown',+ reason: str(fields.reason),+ retainedContentHash: str(fields.retainedContentHash),+ };+ }+ return { ok: true, store: { schema: SCHEMA_VERSION, retained } };+}++export function readSkillMoveRetention(+ base: string,+ scope: SkillMoveScope,+ name: string,+): SkillMoveRetentionRead {+ const read = readStore(base);+ if (!read.ok) {+ return {+ state: 'unreadable',+ reason: read.reason,+ ...(read.cause !== undefined ? { cause: read.cause } : {}),+ };+ }+ const record = read.store.retained[retainedKey(scope, name)];+ return record === undefined ? { state: 'none' } : { state: 'record', record };+}++const serializeRetainedWrite = createKeyedSerializer();++function mutateRetained(+ base: string,+ mutate: (retained: Record<string, SkillMoveRetentionRecord>) => boolean,+): Promise<void> {+ const path = retainedPath(base);+ return serializeRetainedWrite(path, async () => {+ const read = readStore(base);+ if (!read.ok) {+ getLogger('skill-move-retained').error(+ { event: 'skill-move-retained.unreadable', path, reason: read.reason },+ 'refusing to rewrite the retained-destination ledger because it could not be read — rewriting it would replace every record it holds with this one',+ );+ throw new Error(`Refusing to rewrite ${path}: ${read.reason}`);+ }+ if (!mutate(read.store.retained)) return;+ await tracedMkdir(dirname(path), { recursive: true });+ await atomicWriteFile(path, `${JSON.stringify(read.store, null, 2)}\n`, { fs: tracedAtomicFs });+ });+}++export function recordSkillMoveRetention(+ base: string,+ scope: SkillMoveScope,+ name: string,+ record: SkillMoveRetentionRecord,+): Promise<void> {+ return mutateRetained(base, (retained) => {+ retained[retainedKey(scope, name)] = record;+ return true;+ });+}++export function clearSkillMoveRetention(+ base: string,+ scope: SkillMoveScope,+ name: string,+): Promise<void> {+ return mutateRetained(base, (retained) => {+ const key = retainedKey(scope, name);+ if (!(key in retained)) return false;+ delete retained[key];+ return true;+ });+}diff --git a/packages/server/src/skill-placements-store.test.ts b/packages/server/src/skill-placements-store.test.tsnew file mode 100644index 000000000..5cc5d20df--- /dev/null+++ b/packages/server/src/skill-placements-store.test.ts@@ -0,0 +1,125 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { mutateSkillPlacementsStore, readSkillPlacementsStore } from './skill-placements-store.ts';++let base: string;+let ledgerPath: string;++const seedLedger = (contents: string): void => {+ mkdirSync(dirname(ledgerPath), { recursive: true });+ writeFileSync(ledgerPath, contents, 'utf-8');+};++const recordAlpha = () =>+ mutateSkillPlacementsStore(base, (store) => {+ store.skills.alpha = [{ path: '.claude/skills/alpha', mode: 'copy' }];+ });++beforeEach(() => {+ base = mkdtempSync(join(tmpdir(), 'ok-placements-'));+ ledgerPath = join(base, '.ok', 'local', 'skill-placements.json');+});++afterEach(() => {+ rmSync(base, { recursive: true, force: true });+});++describe('skill placements store', () => {+ test('an absent ledger initializes and records the first placement', async () => {+ expect(existsSync(ledgerPath)).toBe(false);++ await recordAlpha();++ expect(readSkillPlacementsStore(base).skills.alpha).toEqual([+ { path: '.claude/skills/alpha', mode: 'copy' },+ ]);+ expect(JSON.parse(readFileSync(ledgerPath, 'utf-8')).schema).toBe(1);+ });++ test('a corrupt ledger still reads as an empty ledger', () => {+ seedLedger('{ this is not json');++ expect(readSkillPlacementsStore(base).skills).toEqual({});+ });++ test('mutating over a corrupt ledger refuses and leaves the file byte-identical', async () => {+ const truncated = '{"schema":1,"skills":{"beta":[{"path":".claude/skills/be';+ seedLedger(truncated);++ await expect(recordAlpha()).rejects.toThrow(/Refusing to rewrite/);+ expect(readFileSync(ledgerPath, 'utf-8')).toBe(truncated);+ });++ test('mutating over an explicitly unsupported schema keeps every recorded placement', async () => {+ const future = `${JSON.stringify(+ { schema: 2, skills: { beta: [{ path: '.claude/skills/beta', mode: 'copy' }] } },+ null,+ 2,+ )}\n`;+ seedLedger(future);++ await expect(recordAlpha()).rejects.toThrow(/Refusing to rewrite/);+ expect(readFileSync(ledgerPath, 'utf-8')).toBe(future);+ });++ test('mutating over a top-level shape that is not a ledger leaves the file byte-identical', async () => {+ const notALedger = '["skills"]';+ seedLedger(notALedger);++ await expect(recordAlpha()).rejects.toThrow(/Refusing to rewrite/);+ expect(readFileSync(ledgerPath, 'utf-8')).toBe(notALedger);+ });++ test('an invalid schema does not echo arbitrary ledger content in the refusal', async () => {+ const contents = '{"schema":{"privateValue":"private ledger text"},"skills":{}}';+ seedLedger(contents);++ await expect(recordAlpha()).rejects.toEqual(+ new Error(`Refusing to rewrite ${ledgerPath}: it declares an unsupported schema value`),+ );+ expect(readFileSync(ledgerPath, 'utf-8')).toBe(contents);+ });++ test('a schema-less legacy ledger is still accepted and keeps its readable placements', async () => {+ seedLedger(+ JSON.stringify({ skills: { beta: [{ path: '.claude/skills/beta', mode: 'link' }] } }),+ );++ await recordAlpha();++ const written = JSON.parse(readFileSync(ledgerPath, 'utf-8'));+ expect(written.schema).toBe(1);+ expect(written.skills.beta).toEqual([{ path: '.claude/skills/beta', mode: 'link' }]);+ expect(written.skills.alpha).toEqual([{ path: '.claude/skills/alpha', mode: 'copy' }]);+ });++ test('a ledger that cannot be opened at all refuses with the errno, not a parse verdict', async () => {+ mkdirSync(ledgerPath, { recursive: true });++ await expect(recordAlpha()).rejects.toThrow(+ /Refusing to rewrite .*: it could not be read \(EISDIR\)/,+ );+ });++ test('a valid ledger still drops placements that escape the base on mutation', async () => {+ seedLedger(+ JSON.stringify({+ schema: 1,+ skills: {+ beta: [+ { path: '../outside/skills/beta', mode: 'copy' },+ { path: '.claude/skills/beta', mode: 'copy' },+ ],+ },+ }),+ );++ await recordAlpha();++ expect(JSON.parse(readFileSync(ledgerPath, 'utf-8')).skills.beta).toEqual([+ { path: '.claude/skills/beta', mode: 'copy' },+ ]);+ });+});diff --git a/packages/server/src/skill-placements-store.ts b/packages/server/src/skill-placements-store.tsindex 3ab69df3a..e5a8074c3 100644--- a/packages/server/src/skill-placements-store.ts+++ b/packages/server/src/skill-placements-store.ts@@ -1,8 +1,7 @@import { existsSync, readFileSync, realpathSync } from 'node:fs';import { dirname, isAbsolute, join, resolve, sep } from 'node:path';import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';-import { tracedMkdir } from './fs-traced.ts';-import { TRACED_FS_ADAPTER } from './installed-skills-marker.ts';+import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';import { createKeyedSerializer } from './keyed-serializer.ts';import { getLogger } from './logger.ts';@@ -120,38 +119,41 @@ function parseFolders(base: string, value: unknown): Record<string, FolderExpectreturn entries.length > 0 ? Object.fromEntries(entries) : undefined;}+function normalizePlacements(base: string, parsed: Record<string, unknown>): SkillPlacementsStore {+ const skills: Record<string, SkillPlacement[]> = {};+ if (parsed.skills && typeof parsed.skills === 'object') {+ for (const [name, list] of Object.entries(parsed.skills)) {+ if (!Array.isArray(list)) continue;+ const valid = list.filter((placement) => isPlacement(base, placement));+ if (valid.length > 0) skills[name] = valid;+ }+ }+ const roots = Array.isArray(parsed.roots)+ ? parsed.roots.filter(+ (root): root is string =>+ typeof root === 'string' && resolveSkillPlacementPath(base, root) !== null,+ )+ : [];+ const preferences = parsePreferences(parsed.preferences);+ const sources = parseSources(parsed.sources);+ const folders = parseFolders(base, parsed.folders);+ return {+ schema: SCHEMA_VERSION,+ skills,+ ...(preferences ? { preferences } : {}),+ ...(sources ? { sources } : {}),+ ...(roots.length > 0 ? { roots } : {}),+ ...(folders ? { folders } : {}),+ };+}+export function readSkillPlacementsStore(base: string): SkillPlacementsStore {const path = skillPlacementsPath(base);if (!existsSync(path)) return emptyStore();try {const parsed = JSON.parse(readFileSync(path, 'utf-8')) as Record<string, unknown> | null;if (!parsed || typeof parsed !== 'object') return emptyStore();-- const skills: Record<string, SkillPlacement[]> = {};- if (parsed.skills && typeof parsed.skills === 'object') {- for (const [name, list] of Object.entries(parsed.skills)) {- if (!Array.isArray(list)) continue;- const valid = list.filter((placement) => isPlacement(base, placement));- if (valid.length > 0) skills[name] = valid;- }- }- const roots = Array.isArray(parsed.roots)- ? parsed.roots.filter(- (root): root is string =>- typeof root === 'string' && resolveSkillPlacementPath(base, root) !== null,- )- : [];- const preferences = parsePreferences(parsed.preferences);- const sources = parseSources(parsed.sources);- const folders = parseFolders(base, parsed.folders);- return {- schema: SCHEMA_VERSION,- skills,- ...(preferences ? { preferences } : {}),- ...(sources ? { sources } : {}),- ...(roots.length > 0 ? { roots } : {}),- ...(folders ? { folders } : {}),- };+ return normalizePlacements(base, parsed);} catch (err) {getLogger('skill-placements').warn({ err, path },@@ -161,6 +163,47 @@ export function readSkillPlacementsStore(base: string): SkillPlacementsStore {}}+type PlacementsRead =+ | { ok: true; store: SkillPlacementsStore }+ | { ok: false; reason: string; cause?: unknown };++function readSkillPlacementsForMutation(base: string): PlacementsRead {+ const path = skillPlacementsPath(base);+ if (!existsSync(path)) return { ok: true, store: emptyStore() };+ let raw: string;+ try {+ raw = readFileSync(path, 'utf-8');+ } catch (err) {+ const code = (err as NodeJS.ErrnoException | undefined)?.code;+ if (code === 'ENOENT') return { ok: true, store: emptyStore() };+ return {+ ok: false,+ reason: code ? `it could not be read (${code})` : 'it could not be read',+ cause: err,+ };+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (err) {+ return { ok: false, reason: 'it is not valid JSON', cause: err };+ }+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {+ return { ok: false, reason: 'its contents are not a placements ledger' };+ }+ const schema = (parsed as { schema?: unknown }).schema;+ if (schema !== undefined && schema !== SCHEMA_VERSION) {+ return {+ ok: false,+ reason:+ typeof schema === 'number'+ ? `it declares schema ${schema}, which this server does not understand (it writes schema ${SCHEMA_VERSION})`+ : 'it declares an unsupported schema value',+ };+ }+ return { ok: true, store: normalizePlacements(base, parsed as Record<string, unknown>) };+}+const serializeLedgerWrite = createKeyedSerializer();export function mutateSkillPlacementsStore(@@ -168,7 +211,16 @@ export function mutateSkillPlacementsStore(mutate: (store: SkillPlacementsStore) => void,): Promise<void> {return serializeLedgerWrite(skillPlacementsPath(base), async () => {- const store = readSkillPlacementsStore(base);+ const read = readSkillPlacementsForMutation(base);+ if (!read.ok) {+ const path = skillPlacementsPath(base);+ getLogger('skill-placements').error(+ { path, reason: read.reason, err: read.cause },+ 'refusing to rewrite skill-placements.json because it could not be read — rewriting it would replace every placement it records with this one',+ );+ throw new Error(`Refusing to rewrite ${path}: ${read.reason}`);+ }+ const store = read.store;mutate(store);await writeSkillPlacementsStore(base, store);});@@ -178,7 +230,7 @@ async function writeSkillPlacementsStore(base: string, store: SkillPlacementsStoconst path = skillPlacementsPath(base);await tracedMkdir(dirname(path), { recursive: true });await atomicWriteFile(path, `${JSON.stringify(store, null, 2)}\n`, {- fs: TRACED_FS_ADAPTER,+ fs: tracedAtomicFs,});}diff --git a/packages/server/src/skills-lock-store.test.ts b/packages/server/src/skills-lock-store.test.tsnew file mode 100644index 000000000..1fd3cbc35--- /dev/null+++ b/packages/server/src/skills-lock-store.test.ts@@ -0,0 +1,92 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import type { SkillLockEntry } from '@inkeep/open-knowledge-core/skills-catalog';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { mutateSkillsLock, readSkillsLockFile } from './skills-lock-store.ts';++let base: string;+let lockPath: string;++const entry: SkillLockEntry = {+ source: '/sources/alpha',+ contentHash: 'hash-alpha',+ importedAt: '2026-09-08T00:00:00.000Z',+};++const seedLock = (contents: string): void => {+ mkdirSync(dirname(lockPath), { recursive: true });+ writeFileSync(lockPath, contents, 'utf-8');+};++const record = (name: string, value: SkillLockEntry) =>+ mutateSkillsLock(lockPath, (lock) => ({ ...lock, skills: { ...lock.skills, [name]: value } }));++beforeEach(() => {+ base = mkdtempSync(join(tmpdir(), 'ok-skills-lock-'));+ lockPath = join(base, '.ok', 'skills-lock.json');+});++afterEach(() => {+ rmSync(base, { recursive: true, force: true });+});++describe('skills lock store', () => {+ test('an absent lock initializes an empty lock and records the first import', async () => {+ expect(existsSync(lockPath)).toBe(false);++ await record('alpha', entry);++ expect(readSkillsLockFile(lockPath).skills.alpha?.source).toBe('/sources/alpha');+ expect(JSON.parse(readFileSync(lockPath, 'utf-8')).schema).toBe(1);+ });++ test('a corrupt lock still reads as an empty lock', () => {+ seedLock('{ this is not json');++ expect(readSkillsLockFile(lockPath).skills).toEqual({});+ });++ test('recording over a corrupt lock refuses and leaves the file byte-identical', async () => {+ const truncated = '{"schema":1,"skills":{"beta":{"source":"/sources/be';+ seedLock(truncated);++ await expect(record('alpha', entry)).rejects.toThrow(/Refusing to rewrite/);+ expect(readFileSync(lockPath, 'utf-8')).toBe(truncated);+ });++ test('recording over a lock schema this server cannot read keeps every sibling import', async () => {+ const future = `${JSON.stringify(+ { schema: 2, skills: { beta: { source: '/sources/beta' } } },+ null,+ 2,+ )}\n`;+ seedLock(future);++ await expect(record('alpha', entry)).rejects.toThrow(/Refusing to rewrite/);+ expect(readFileSync(lockPath, 'utf-8')).toBe(future);+ });++ test('a lock that cannot be opened at all refuses with the errno, not a parse verdict', async () => {+ mkdirSync(lockPath, { recursive: true });++ await expect(record('alpha', entry)).rejects.toThrow(+ /Refusing to rewrite .*: it could not be read \(EISDIR\)/,+ );+ });++ test('an entry field this server does not model survives a sibling record', async () => {+ seedLock(+ JSON.stringify({+ schema: 1,+ skills: { beta: { ...entry, source: '/sources/beta', futureField: 'keep-me' } },+ }),+ );++ await record('alpha', entry);++ const written = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(written.skills.beta.futureField).toBe('keep-me');+ expect(written.skills.alpha.source).toBe('/sources/alpha');+ });+});diff --git a/packages/server/src/skills-lock-store.ts b/packages/server/src/skills-lock-store.tsindex d19e146d1..ba70790c3 100644--- a/packages/server/src/skills-lock-store.ts+++ b/packages/server/src/skills-lock-store.ts@@ -6,8 +6,7 @@ import {parseSkillsLock,type SkillsLock,} from '@inkeep/open-knowledge-core/skills-catalog';-import { tracedMkdir } from './fs-traced.ts';-import { TRACED_FS_ADAPTER } from './installed-skills-marker.ts';+import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';import { createKeyedSerializer } from './keyed-serializer.ts';import { getLogger } from './logger.ts';@@ -22,6 +21,28 @@ export function readSkillsLockFile(lockPath: string): SkillsLock {return emptySkillsLock();}+type LockRead = { ok: true; lock: SkillsLock } | { ok: false; reason: string; cause?: unknown };++function readSkillsLockForMutation(lockPath: string): LockRead {+ if (!existsSync(lockPath)) return { ok: true, lock: emptySkillsLock() };+ let raw: string;+ try {+ raw = readFileSync(lockPath, 'utf-8');+ } catch (err) {+ const code = (err as NodeJS.ErrnoException | undefined)?.code;+ if (code === 'ENOENT') return { ok: true, lock: emptySkillsLock() };+ return {+ ok: false,+ reason: code ? `it could not be read (${code})` : 'it could not be read',+ cause: err,+ };+ }+ const parsed = parseSkillsLock(raw);+ return parsed === null+ ? { ok: false, reason: 'its contents are not a skills lock this server understands' }+ : { ok: true, lock: parsed };+}+const serializeLockWrite = createKeyedSerializer();export function mutateSkillsLock(@@ -29,11 +50,19 @@ export function mutateSkillsLock(mutate: (lock: SkillsLock) => SkillsLock | undefined,): Promise<void> {return serializeLockWrite(lockPath, async () => {- const current = readSkillsLockFile(lockPath);+ const read = readSkillsLockForMutation(lockPath);+ if (!read.ok) {+ getLogger('skills-lock').error(+ { lockPath, reason: read.reason, err: read.cause },+ 'refusing to rewrite skills-lock.json because it could not be read — rewriting it would replace every import it records with this one',+ );+ throw new Error(`Refusing to rewrite ${lockPath}: ${read.reason}`);+ }+ const current = read.lock;const next = mutate(current) ?? current;await tracedMkdir(dirname(lockPath), { recursive: true });await atomicWriteFile(lockPath, `${JSON.stringify(next, null, 2)}\n`, {- fs: TRACED_FS_ADAPTER,+ fs: tracedAtomicFs,});});}