Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Opt-in consent for the two global OpenKnowledge skills (#2437)

tim-inkeep8c16c9483203
diff --git a/.changeset/global-skills-opt-in.md b/.changeset/global-skills-opt-in.md
new file mode 100644
index 000000000..8add865e3
--- /dev/null
+++ b/.changeset/global-skills-opt-in.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': minor
+---
+
+Add per-skill opt-in for the two user-global OpenKnowledge skills (`open-knowledge-discovery` and `open-knowledge-write-skill`). The first-launch desktop consent dialog now shows a checkbox per skill (pre-checked), and `ok init` accepts `--skills <ids>` / `--no-skills`. The decision is recorded in `~/.ok/skill-state.yml` and honored by every install path — desktop launch reclaim, `ok start`, `ok repair-skills`, and `ok init` — so a declined skill is never re-installed, and unchecking one that is already installed removes it. Existing installs are grandfathered (treated as opted in, nothing removed). `ok init` now installs both user-global skills when enabled instead of only `discovery`.
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index 78c8c9301..5aa249f04 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -64,6 +64,12 @@ The managed block is clearly fenced so you can see and remove it:
Delete the block and the app **won't re-add it** — the removal is recorded and respected. Or set `OK_RECLAIM_DISABLE=1` to disable all of this before first launch.
+### User-global Agent Skills
+
+OpenKnowledge ships two user-global [Agent Skills](/docs/features/skills) — `open-knowledge-discovery` (helps your coding agent recognize and route through OpenKnowledge projects) and `open-knowledge-write-skill` (a workflow for authoring new skills). They install into each detected editor's global skill folder (`~/.claude/skills/`, `~/.cursor/skills/`, `~/.codex/skills/`, `~/.opencode/skills/`) plus the shared `~/.agents/skills/` hub.
+
+These are **consent-gated**, one checkbox per skill in the same first-launch dialog (both checked by default). Uncheck one and it is never installed; uncheck an already-installed one and its copies are **removed**. The choice is recorded in `~/.ok/skill-state.yml` and honored by every install path — the desktop app, `ok init`, and `ok start` — so a skill you declined is never re-added. Machines that already had the skills before the consent dialog are treated as consented (left in place). Re-enable later from **File → Set up OpenKnowledge integrations…**.
+
### Setting up a project
When you initialize or open a project, the app scaffolds the same project files the CLI's `ok init` creates, and registers the `open-knowledge` MCP server with the AI editors it detects. The MCP registration is **surgical** — it adds only its own entry and leaves your other settings, comments, and formatting byte-for-byte intact.
@@ -158,11 +164,12 @@ With `--scope user` or `both` (the default), `ok init` also registers the `open-
| `~/.codex/config.toml` | Codex | Outside-project (editor config) |
| `~/.config/opencode/opencode.json` | OpenCode | Outside-project (editor config) |
-`ok init` also re-runs the user-global skill install (the discovery skill above) and, if you choose **local-only** sharing, adds the OpenKnowledge paths to `.git/info/exclude` so `.ok/` stays off your remote.
+`ok init` also installs the two user-global skills (`open-knowledge-discovery` and `open-knowledge-write-skill`), honoring any prior consent choice, and, if you choose **local-only** sharing, adds the OpenKnowledge paths to `.git/info/exclude` so `.ok/` stays off your remote.
<Callout type="info" title="Controlling it">
- `--no-mcp` — scaffold `.ok/` only; register nothing with any editor.
- `--scope user | project | both` — where the MCP entry is written. In an interactive terminal, `ok init` prompts for this; scripted/CI runs default to `both`, so pass the flag to constrain them.
+ - `--no-skills` — install no user-global skills; `--skills discovery,write-skill` — install only the named bundles. Default installs both. The choice is recorded and honored by the desktop app too.
- `--local-only` (vs `--shared`) — keep `.ok/` out of git.
</Callout>
diff --git a/packages/app/src/components/McpConsentDialog.dom.test.tsx b/packages/app/src/components/McpConsentDialog.dom.test.tsx
index fbb5c31de..d1436ede6 100644
--- a/packages/app/src/components/McpConsentDialog.dom.test.tsx
+++ b/packages/app/src/components/McpConsentDialog.dom.test.tsx
@@ -23,12 +23,14 @@ const payload: OkMcpWiringShowPayload = {
rcFilesToTouch: ['~/.zshrc', '~/.config/fish/conf.d/open-knowledge.fish'],
alreadyInstalled: false,
},
+ globalSkills: [],
};
/** Same editors, zero detected — exercises the Add-enable matrix. */
const noneDetectedPayload: OkMcpWiringShowPayload = {
detectedEditors: [{ id: 'codex', label: 'Codex', detected: false, willReplace: false }],
pathInstall: payload.pathInstall,
+ globalSkills: [],
};
function deferredResult() {
@@ -42,8 +44,27 @@ function deferredResult() {
interface RecordedConfirm {
editorIds: readonly string[];
pathInstall: boolean | undefined;
+ skills?: readonly string[];
}
+/** Payload variant that offers both skill rows — exercises the skills section. */
+const skillsPayload: OkMcpWiringShowPayload = {
+ detectedEditors: [{ id: 'claude', label: 'Claude', detected: true, willReplace: false }],
+ pathInstall: { shellDetected: false, rcFilesToTouch: [], alreadyInstalled: false },
+ globalSkills: [
+ {
+ id: 'discovery',
+ name: 'open-knowledge-discovery',
+ alreadyInstalled: false,
+ },
+ {
+ id: 'write-skill',
+ name: 'open-knowledge-write-skill',
+ alreadyInstalled: true,
+ },
+ ],
+};
+
function makeHarness({
confirmResult = async () => ({ ok: true as const }),
skipResult = async () => ({ ok: true as const }),
@@ -58,7 +79,11 @@ function makeHarness({
const toastErrors: string[] = [];
const store: McpConsentStore = {
confirm: async (request) => {
- confirmCalls.push({ editorIds: [...request.editorIds], pathInstall: request.pathInstall });
+ confirmCalls.push({
+ editorIds: [...request.editorIds],
+ pathInstall: request.pathInstall,
+ skills: request.skills ? [...request.skills] : undefined,
+ });
return confirmResult(request.editorIds);
},
dismiss: () => {},
@@ -292,3 +317,44 @@ describe('McpConsentDialog PATH consent row', () => {
});
});
});
+
+describe('McpConsentDialog skills section', () => {
+ afterEach(() => cleanup());
+
+ test('FR2: renders one pre-checked row per bundle', async () => {
+ await renderDialog(makeHarness({ snapshot: skillsPayload }));
+ for (const id of ['discovery', 'write-skill']) {
+ expect(
+ screen.getByTestId(`mcp-consent-skill-checkbox-${id}`).getAttribute('aria-checked'),
+ ).toBe('true');
+ }
+ });
+
+ test('FR9: unchecking write-skill sends only the checked bundle on Add', async () => {
+ const harness = await renderDialog(makeHarness({ snapshot: skillsPayload }));
+ await userEvent.click(screen.getByTestId('mcp-consent-skill-checkbox-write-skill'));
+ // Unchecking an already-installed bundle surfaces the removal warning.
+ expect(screen.getByTestId('mcp-consent-skill-warning-write-skill')).toBeTruthy();
+ await userEvent.click(screen.getByTestId('mcp-consent-add'));
+ await waitFor(() => {
+ expect(harness.confirmCalls).toEqual([
+ { editorIds: ['claude'], pathInstall: undefined, skills: ['discovery'] },
+ ]);
+ });
+ });
+
+ test('declining every skill keeps Add enabled and confirms an empty skill set', async () => {
+ const harness = await renderDialog(makeHarness({ snapshot: skillsPayload }));
+ await userEvent.click(screen.getByTestId('mcp-consent-skill-checkbox-discovery'));
+ await userEvent.click(screen.getByTestId('mcp-consent-skill-checkbox-write-skill'));
+ // Uncheck the only detected editor too — Add stays enabled because skills
+ // were offered (declining is itself an action).
+ await userEvent.click(screen.getByTestId('mcp-consent-checkbox-claude'));
+ const add = screen.getByTestId('mcp-consent-add') as HTMLButtonElement;
+ expect(add.disabled).toBe(false);
+ await userEvent.click(add);
+ await waitFor(() => {
+ expect(harness.confirmCalls).toEqual([{ editorIds: [], pathInstall: undefined, skills: [] }]);
+ });
+ });
+});
diff --git a/packages/app/src/components/McpConsentDialogBody.tsx b/packages/app/src/components/McpConsentDialogBody.tsx
index 37eafab38..63e3a4087 100644
--- a/packages/app/src/components/McpConsentDialogBody.tsx
+++ b/packages/app/src/components/McpConsentDialogBody.tsx
@@ -38,6 +38,7 @@ import { type McpConsentStore, mcpConsentStore } from '@/lib/mcp-consent-store';
type EditorDetection = OkMcpWiringShowPayload['detectedEditors'][number];
type PathInstallDescriptor = OkMcpWiringShowPayload['pathInstall'];
+type GlobalSkillDescriptor = OkMcpWiringShowPayload['globalSkills'][number];
/**
* Pure helper: whether the PATH row solicits a decision. Hidden rows
@@ -90,6 +91,33 @@ export function selectedIdsOrdered(
return out;
}
+/**
+ * Pure helper: initial skill checkbox state — every offered bundle starts
+ * checked (opt-out default: preserves today's install-everywhere behavior
+ * while making it one-click-off).
+ */
+export function computeInitialSkillSelection(
+ globalSkills: readonly GlobalSkillDescriptor[],
+): ReadonlySet<string> {
+ return new Set(globalSkills.map((s) => s.id));
+}
+
+/** Pure helper: toggle a skill checkbox; returns a new Set. */
+export function toggleSkillId(prev: ReadonlySet<string>, id: string): ReadonlySet<string> {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+}
+
+/** Pure helper: project the checked skills back into payload order. */
+export function skillIdsOrdered(
+ selection: ReadonlySet<string>,
+ globalSkills: readonly GlobalSkillDescriptor[],
+): string[] {
+ return globalSkills.filter((s) => selection.has(s.id)).map((s) => s.id);
+}
+
/**
* Test-injectable store + toast — production consumers use the default
* exports. Exposed as props so `bun test` doesn't need to reset module
@@ -146,6 +174,8 @@ function McpConsentDialogForm({ payload, store, toast }: McpConsentDialogFormPro
const { t } = useLingui();
const detectedEditors = payload.detectedEditors;
const pathInstall = payload.pathInstall;
+ const globalSkills = payload.globalSkills;
+ const skillsOffered = globalSkills.length > 0;
const pathActionable = isPathRowActionable(pathInstall);
const [selection, setSelection] = useState<ReadonlySet<OkMcpWiringEditorId>>(() =>
computeInitialSelection(detectedEditors),
@@ -153,6 +183,10 @@ function McpConsentDialogForm({ payload, store, toast }: McpConsentDialogFormPro
// Pre-checked (opt-out) when the row solicits a decision; informational
// rows render force-checked + disabled below and never read this state.
const [pathChecked, setPathChecked] = useState(true);
+ // Pre-checked (opt-out) — every offered bundle starts on.
+ const [skillSelection, setSkillSelection] = useState<ReadonlySet<string>>(() =>
+ computeInitialSkillSelection(globalSkills),
+ );
const [busy, setBusy] = useState(false);
const idPrefix = useId();
@@ -165,6 +199,9 @@ function McpConsentDialogForm({ payload, store, toast }: McpConsentDialogFormPro
const result = await store.confirm({
editorIds: selectedIdsOrdered(selection, detectedEditors),
pathInstall: pathActionable ? pathChecked : undefined,
+ // When skills are offered, always send the (possibly empty) selection so
+ // main records a decision for every bundle — an empty list declines both.
+ skills: skillsOffered ? skillIdsOrdered(skillSelection, globalSkills) : undefined,
});
// Success: the store clears `currentRequest` → useSyncExternalStore
// unmounts this subtree, so there's nothing to reset. Failure
@@ -339,6 +376,78 @@ function McpConsentDialogForm({ payload, store, toast }: McpConsentDialogFormPro
</ul>
</DialogBody>
+ {/*
+ * User-global Agent Skills consent section — one pre-checked row per
+ * bundle. Distinct from the editor list because skills install to every
+ * detected host by design (not per-editor). Unchecking an already-
+ * installed bundle removes it; the decision is honored by every install
+ * actor (desktop reclaim, ok init, ok start).
+ */}
+ {skillsOffered && (
+ <div className="flex flex-col gap-1.5">
+ <span className="text-xs font-medium text-muted-foreground">
+ <Trans comment="Section label above the skill checkboxes in the first-launch dialog">
+ Agent Skills
+ </Trans>
+ </span>
+ <ul className="rounded-md border border-border bg-card/50 divide-y divide-border overflow-hidden">
+ {globalSkills.map((skill) => {
+ const checked = skillSelection.has(skill.id);
+ const checkboxId = `${idPrefix}-skill-${skill.id}`;
+ return (
+ <li key={skill.id}>
+ <Label
+ htmlFor={checkboxId}
+ className="flex cursor-pointer items-start gap-2.5 px-3 py-2.5 font-normal hover:bg-accent"
+ >
+ <Checkbox
+ id={checkboxId}
+ checked={checked}
+ disabled={busy}
+ onCheckedChange={() =>
+ setSkillSelection((prev) => toggleSkillId(prev, skill.id))
+ }
+ className="mt-0.5"
+ data-testid={`mcp-consent-skill-checkbox-${skill.id}`}
+ />
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="text-sm font-medium text-foreground">
+ <code>{skill.name}</code>
+ </span>
+ <span
+ className="text-xs text-muted-foreground"
+ data-testid={`mcp-consent-skill-status-${skill.id}`}
+ >
+ {skill.id === 'discovery' ? (
+ <Trans comment="Subtext for the open-knowledge-discovery skill row">
+ Helps your coding agent recognize OpenKnowledge projects and route
+ reads and writes through it.
+ </Trans>
+ ) : (
+ <Trans comment="Subtext for the open-knowledge-write-skill skill row">
+ Adds a guided workflow for authoring new Agent Skills.
+ </Trans>
+ )}
+ </span>
+ {skill.alreadyInstalled && !checked && (
+ <span
+ className="text-xs text-amber-600 dark:text-amber-400"
+ data-testid={`mcp-consent-skill-warning-${skill.id}`}
+ >
+ <Trans comment="Warning shown when the user unchecks an already-installed skill">
+ Removes this skill from your editors.
+ </Trans>
+ </span>
+ )}
+ </span>
+ </Label>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ )}
+
<DialogFooter>
<Button
variant="outline"
@@ -353,7 +462,9 @@ function McpConsentDialogForm({ payload, store, toast }: McpConsentDialogFormPro
</Button>
<Button
onClick={() => void onAdd()}
- disabled={busy || (selection.size === 0 && !(pathActionable && pathChecked))}
+ disabled={
+ busy || (selection.size === 0 && !(pathActionable && pathChecked) && !skillsOffered)
+ }
data-testid="mcp-consent-add"
>
{busy ? (
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index 22ebe7f9d..8e7bc509f 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -429,15 +429,27 @@ export interface OkMcpWiringShowPayload {
readonly rcFilesToTouch: readonly string[];
readonly alreadyInstalled: boolean;
};
+ /** Per-bundle opt-in rows for the two user-global skills. Empty ⇒ no skill
+ * decision solicited. `alreadyInstalled: true` renders the row pre-checked
+ * as an existing install the user can uncheck to remove. */
+ readonly globalSkills: readonly {
+ readonly id: string;
+ readonly name: string;
+ readonly alreadyInstalled: boolean;
+ }[];
}
/** Confirm payload for `mcpWiring.confirm`. `pathInstall` is the PATH
* toggle, tri-state: `true` → append the managed rc block; `false` →
* record declined, touch nothing; absent → no PATH decision was solicited
- * (row hidden or informational). */
+ * (row hidden or informational).
+ *
+ * `skills` — bundle ids the user left checked. Present ⇒ a skill decision was
+ * solicited; every offered bundle not in the list is recorded declined. */
export interface OkMcpWiringConfirmRequest {
readonly editorIds: readonly OkMcpWiringEditorId[];
readonly pathInstall?: boolean;
+ readonly skills?: readonly string[];
}
/** Result shape for `mcpWiring.confirm` / `skip`. */
diff --git a/packages/app/src/lib/mcp-consent-store.test.ts b/packages/app/src/lib/mcp-consent-store.test.ts
index fe9bc10bc..5bfe9e776 100644
--- a/packages/app/src/lib/mcp-consent-store.test.ts
+++ b/packages/app/src/lib/mcp-consent-store.test.ts
@@ -72,6 +72,7 @@ const sampleShowPayload: OkMcpWiringShowPayload = {
{ id: 'cursor', label: 'Cursor', detected: false, willReplace: false },
],
pathInstall: { shellDetected: true, rcFilesToTouch: ['~/.zshrc'], alreadyInstalled: false },
+ globalSkills: [],
};
describe('createMcpConsentStore — install', () => {
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 7d21d2767..334df77dc 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -62,6 +62,9 @@
],
"0eHrMb": ["Could not complete delete"],
"0g7rCZ": ["Duplicated to \"", ["0"], "\""],
+ "0inVGS": [
+ "Helps your coding agent recognize OpenKnowledge projects and route reads and writes through it."
+ ],
"0jD-Gn": ["A team knowledge base, a personal wiki, project docs..."],
"0kTAXe": ["Open source: ", ["mirrorSrc"]],
"0njBIq": [
@@ -103,6 +106,7 @@
"237hSL": ["Ended"],
"25Pw6a": ["Cloning"],
"27XW26": ["Clone happens in the Project Navigator. Reclick the share link there."],
+ "28B21t": ["Agent Skills"],
"29VNqC": ["Unknown error"],
"29XZXN": ["Set git identity"],
"2BBAbc": ["List"],
@@ -654,6 +658,7 @@
["0"],
")."
],
+ "FXk_zY": ["Adds a guided workflow for authoring new Agent Skills."],
"FjkaiT": ["Zoom out"],
"FnMkli": ["Sync disabled — you don't have permission to push"],
"FqTpiN": ["Bird wiki"],
@@ -1551,6 +1556,7 @@
"Add meaning-based ranking to search so conceptually-related pages surface even when they share no keywords. This setting applies only to this computer."
],
"dURmlQ": ["\"frontmatter\" is a reserved property name"],
+ "dXWMFn": ["Removes this skill from your editors."],
"dbapvC": ["Follow us on social media"],
"dbhUX1": ["Hide this file"],
"dbtjJh": ["(opens in new tab)"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 680e600dc..6712f7db4 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -708,6 +708,11 @@ msgstr "Add the <0>ok</0> command to your terminal"
msgid "Add the next matching source selection."
msgstr "Add the next matching source selection."
+#. Subtext for the open-knowledge-write-skill skill row
+#: src/components/McpConsentDialogBody.tsx
+msgid "Adds a guided workflow for authoring new Agent Skills."
+msgstr "Adds a guided workflow for authoring new Agent Skills."
+
#. placeholder {0}: pathInstall.rcFilesToTouch.join(', ')
#: src/components/McpConsentDialogBody.tsx
msgid "Adds a managed block to {0}"
@@ -738,6 +743,11 @@ msgstr "Agent activity"
msgid "Agent configuration file"
msgstr "Agent configuration file"
+#. Section label above the skill checkboxes in the first-launch dialog
+#: src/components/McpConsentDialogBody.tsx
+msgid "Agent Skills"
+msgstr "Agent Skills"
+
#. Section label above the editor checkbox list in the first-launch dialog
#: src/components/McpConsentDialogBody.tsx
msgid "AI tools"
@@ -3276,6 +3286,11 @@ msgstr "Heads up"
msgid "Hello, world!"
msgstr "Hello, world!"
+#. Subtext for the open-knowledge-discovery skill row
+#: src/components/McpConsentDialogBody.tsx
+msgid "Helps your coding agent recognize OpenKnowledge projects and route reads and writes through it."
+msgstr "Helps your coding agent recognize OpenKnowledge projects and route reads and writes through it."
+
#: src/components/FileTree.tsx
msgid "Hidden “{basename}”"
msgstr "Hidden “{basename}”"
@@ -5439,6 +5454,11 @@ msgstr "Remove selection"
msgid "Remove the parent <0>.git</0> folder"
msgstr "Remove the parent <0>.git</0> folder"
+#. Warning shown when the user unchecks an already-installed skill
+#: src/components/McpConsentDialogBody.tsx
+msgid "Removes this skill from your editors."
+msgstr "Removes this skill from your editors."
+
#: src/components/CreateProjectDialog.tsx
msgid "Removing"
msgstr "Removing"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index e00acde6f..64cf8f425 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -62,6 +62,9 @@
],
"0eHrMb": ["Ćōũĺď ńōţ ćōḿƥĺēţē ďēĺēţē"],
"0g7rCZ": ["Ďũƥĺĩćàţēď ţō \"", ["0"], "\""],
+ "0inVGS": [
+ "Ĥēĺƥś ŷōũŕ ćōďĩńĝ àĝēńţ ŕēćōĝńĩźē ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţś àńď ŕōũţē ŕēàďś àńď ŵŕĩţēś ţĥŕōũĝĥ ĩţ."
+ ],
"0jD-Gn": ["À ţēàḿ ķńōŵĺēďĝē ƀàśē, à ƥēŕśōńàĺ ŵĩķĩ, ƥŕōĴēćţ ďōćś..."],
"0kTAXe": ["Ōƥēń śōũŕćē: ", ["mirrorSrc"]],
"0njBIq": [
@@ -103,6 +106,7 @@
"237hSL": ["Ēńďēď"],
"25Pw6a": ["Ćĺōńĩńĝ"],
"27XW26": ["Ćĺōńē ĥàƥƥēńś ĩń ţĥē ƤŕōĴēćţ Ńàvĩĝàţōŕ. Ŕēćĺĩćķ ţĥē śĥàŕē ĺĩńķ ţĥēŕē."],
+ "28B21t": ["Àĝēńţ Śķĩĺĺś"],
"29VNqC": ["Ũńķńōŵń ēŕŕōŕ"],
"29XZXN": ["Śēţ ĝĩţ ĩďēńţĩţŷ"],
"2BBAbc": ["Ĺĩśţ"],
@@ -654,6 +658,7 @@
["0"],
")."
],
+ "FXk_zY": ["Àďďś à ĝũĩďēď ŵōŕķƒĺōŵ ƒōŕ àũţĥōŕĩńĝ ńēŵ Àĝēńţ Śķĩĺĺś."],
"FjkaiT": ["Źōōḿ ōũţ"],
"FnMkli": ["Śŷńć ďĩśàƀĺēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ"],
"FqTpiN": ["ßĩŕď ŵĩķĩ"],
@@ -1551,6 +1556,7 @@
"Àďď ḿēàńĩńĝ-ƀàśēď ŕàńķĩńĝ ţō śēàŕćĥ śō ćōńćēƥţũàĺĺŷ-ŕēĺàţēď ƥàĝēś śũŕƒàćē ēvēń ŵĥēń ţĥēŷ śĥàŕē ńō ķēŷŵōŕďś. Ţĥĩś śēţţĩńĝ àƥƥĺĩēś ōńĺŷ ţō ţĥĩś ćōḿƥũţēŕ."
],
"dURmlQ": ["\"ƒŕōńţḿàţţēŕ\" ĩś à ŕēśēŕvēď ƥŕōƥēŕţŷ ńàḿē"],
+ "dXWMFn": ["Ŕēḿōvēś ţĥĩś śķĩĺĺ ƒŕōḿ ŷōũŕ ēďĩţōŕś."],
"dbapvC": ["Ƒōĺĺōŵ ũś ōń śōćĩàĺ ḿēďĩà"],
"dbhUX1": ["Ĥĩďē ţĥĩś ƒĩĺē"],
"dbtjJh": ["(ōƥēńś ĩń ńēŵ ţàƀ)"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index b24ae1c2f..1ed2e1a2f 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -703,6 +703,11 @@ msgstr ""
msgid "Add the next matching source selection."
msgstr ""
+#. Subtext for the open-knowledge-write-skill skill row
+#: src/components/McpConsentDialogBody.tsx
+msgid "Adds a guided workflow for authoring new Agent Skills."
+msgstr ""
+
#. placeholder {0}: pathInstall.rcFilesToTouch.join(', ')
#: src/components/McpConsentDialogBody.tsx
msgid "Adds a managed block to {0}"
@@ -733,6 +738,11 @@ msgstr ""
msgid "Agent configuration file"
msgstr ""
+#. Section label above the skill checkboxes in the first-launch dialog
+#: src/components/McpConsentDialogBody.tsx
+msgid "Agent Skills"
+msgstr ""
+
#. Section label above the editor checkbox list in the first-launch dialog
#: src/components/McpConsentDialogBody.tsx
msgid "AI tools"
@@ -3271,6 +3281,11 @@ msgstr ""
msgid "Hello, world!"
msgstr ""
+#. Subtext for the open-knowledge-discovery skill row
+#: src/components/McpConsentDialogBody.tsx
+msgid "Helps your coding agent recognize OpenKnowledge projects and route reads and writes through it."
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Hidden “{basename}”"
msgstr ""
@@ -5434,6 +5449,11 @@ msgstr ""
msgid "Remove the parent <0>.git</0> folder"
msgstr ""
+#. Warning shown when the user unchecks an already-installed skill
+#: src/components/McpConsentDialogBody.tsx
+msgid "Removes this skill from your editors."
+msgstr ""
+
#: src/components/CreateProjectDialog.tsx
msgid "Removing"
msgstr ""
diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.ts
index 25b2c6fdb..096bd9de1 100644
--- a/packages/cli/src/commands/init.test.ts
+++ b/packages/cli/src/commands/init.test.ts
@@ -13,6 +13,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
+import { readBundleDecision } from '@inkeep/open-knowledge-server';
import { loadConfig } from '../config/loader.ts';
import { OK_DIR } from '../constants.ts';
import { previewContent } from '../content/preview.ts';
@@ -50,6 +51,7 @@ import {
LAUNCH_UI_CHAIN_SENTINEL,
LAUNCH_UI_CHAIN_V1,
readExistingMcpEntry,
+ resolveInitSkillEnablement,
resolveMcpScope,
resolveRequestedContentDir,
resolveSharingMode,
@@ -1152,6 +1154,82 @@ describe('runInit', () => {
});
expect(capturedHome).toBe(fakeHome);
});
+
+ it('FR6/D8: installs BOTH user-global bundles by default and records both enabled', async () => {
+ const installed: (string | undefined)[] = [];
+ await runInitForTest({
+ installUserSkill: async (opts) => {
+ installed.push(opts?.bundleId);
+ return 'installed';
+ },
+ });
+ expect(installed.sort()).toEqual(['discovery', 'write-skill']);
+ // Decisions persisted so the desktop / start reclaim gates agree.
+ expect(await readBundleDecision(fakeHome, 'open-knowledge-discovery')).toBe(true);
+ expect(await readBundleDecision(fakeHome, 'open-knowledge-write-skill')).toBe(true);
+ });
+
+ it('--no-skills installs nothing and records both declined', async () => {
+ const installed: (string | undefined)[] = [];
+ await runInitForTest({
+ skills: false,
+ installUserSkill: async (opts) => {
+ installed.push(opts?.bundleId);
+ return 'installed';
+ },
+ });
+ expect(installed).toEqual([]);
+ expect(await readBundleDecision(fakeHome, 'open-knowledge-discovery')).toBe(false);
+ expect(await readBundleDecision(fakeHome, 'open-knowledge-write-skill')).toBe(false);
+ });
+
+ it('--skills discovery installs only discovery', async () => {
+ const installed: (string | undefined)[] = [];
+ await runInitForTest({
+ skills: 'discovery',
+ installUserSkill: async (opts) => {
+ installed.push(opts?.bundleId);
+ return 'installed';
+ },
+ });
+ expect(installed).toEqual(['discovery']);
+ expect(await readBundleDecision(fakeHome, 'open-knowledge-discovery')).toBe(true);
+ expect(await readBundleDecision(fakeHome, 'open-knowledge-write-skill')).toBe(false);
+ });
+
+ it('installs every enabled bundle with force so the shared cli-hosts version key cannot skip the second', async () => {
+ const forced: (boolean | undefined)[] = [];
+ await runInitForTest({
+ installUserSkill: async (opts) => {
+ forced.push(opts?.force);
+ return 'installed';
+ },
+ });
+ // Both bundles must force-install; without force, bundle 1's version write
+ // would satisfy bundle 2's skip-current gate and freeze its content.
+ expect(forced).toEqual([true, true]);
+ });
+
+ it('--no-skills reports declined, not a false "already installed"', async () => {
+ const result = await runInitForTest({
+ skills: false,
+ installUserSkill: async () => 'installed',
+ });
+ expect(result.skillInstall).toBe('declined');
+ const output = formatInitResult(result, testDir);
+ expect(output).toContain('opted out');
+ expect(output).not.toContain('already installed at current version');
+ });
+
+ it('surfaces the manual-install hint when one bundle fails even if the other installs', async () => {
+ const result = await runInitForTest({
+ installUserSkill: async (opts) =>
+ opts?.bundleId === 'write-skill' ? 'failed' : 'installed',
+ });
+ expect(result.skillInstall).toBe('failed');
+ const output = formatInitResult(result, testDir);
+ expect(output).toContain('install failed');
+ });
});
// -----------------------------------------------------------------------
@@ -3123,3 +3201,32 @@ describe('resolveSharingMode', () => {
expect(mode).toBe('local-only');
});
});
+
+describe('resolveInitSkillEnablement — --skills / --no-skills flag parsing', () => {
+ const sorted = (skills: string | boolean | undefined): string[] =>
+ [...resolveInitSkillEnablement(skills)].sort();
+
+ it('undefined (no flag) enables every user-global bundle', () => {
+ expect(sorted(undefined)).toEqual(['discovery', 'write-skill']);
+ });
+
+ it('true (bare --skills) enables every bundle', () => {
+ expect(sorted(true)).toEqual(['discovery', 'write-skill']);
+ });
+
+ it('false (--no-skills) enables none', () => {
+ expect(sorted(false)).toEqual([]);
+ });
+
+ it('a comma list enables only the named bundles', () => {
+ expect(sorted('discovery')).toEqual(['discovery']);
+ expect(sorted('write-skill')).toEqual(['write-skill']);
+ expect(sorted('discovery,write-skill')).toEqual(['discovery', 'write-skill']);
+ });
+
+ it('trims whitespace and drops unknown names', () => {
+ expect(sorted(' discovery , write-skill ')).toEqual(['discovery', 'write-skill']);
+ expect(sorted('discovery,bogus')).toEqual(['discovery']);
+ expect(sorted('bogus')).toEqual([]);
+ });
+});
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index b5fb89f2d..6be649a64 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -20,14 +20,17 @@ import {
statSync,
writeFileSync,
} from 'node:fs';
+import { homedir } from 'node:os';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { inspect } from 'node:util';
import { atomicWriteFileSync, withFileLockSync } from '@inkeep/open-knowledge-core/server';
import type {
+ BundleId,
InstallUserSkillOptions,
InstallUserSkillResult,
} from '@inkeep/open-knowledge-server';
import {
+ BUNDLE_SKILL_NAME,
ensureProjectGit,
GitNotAvailableError,
GitTooOldError,
@@ -35,6 +38,8 @@ import {
installUserSkill,
MCP_SERVER_NAME,
ProjectGitInitError,
+ USER_GLOBAL_BUNDLE_IDS,
+ writeBundleDecision,
writeRootGitignoreForNewRepo,
} from '@inkeep/open-knowledge-server';
import checkbox from '@inquirer/checkbox';
@@ -52,6 +57,7 @@ import { stringify as stringifyToml } from 'smol-toml';
import { CONFIG_FILENAME, OK_DIR } from '../constants.ts';
import { formatPreviewBlock, type PreviewResult } from '../content/preview.ts';
import { resolveProjectRoot } from '../integrations/resolve-project-root.ts';
+import { removeUserGlobalSkillBundle } from '../integrations/skill-teardown.ts';
import {
assertProjectPathSafe,
type ProjectSkillResult,
@@ -73,7 +79,7 @@ import {
type SharingMode,
type TrackedRefusal,
} from '../sharing/git-exclude.ts';
-import { accent, error, info, success, warning } from '../ui/colors.ts';
+import { accent, dim, error, info, success, warning } from '../ui/colors.ts';
import { isObject } from '../utils/is-object.ts';
import {
ALL_EDITOR_IDS,
@@ -586,6 +592,13 @@ interface InitCommandOptions {
* `@inkeep/open-knowledge-server`.
*/
installUserSkill?: (opts?: InstallUserSkillOptions) => Promise<InstallUserSkillResult>;
+ /**
+ * User-global skill opt-in. `undefined` (default) enables every bundle;
+ * `false` (`--no-skills`) declines all; a comma list (`--skills discovery`)
+ * enables only the named bundles. The decision is recorded so the desktop /
+ * CLI reclaim gates never re-install a declined bundle.
+ */
+ skills?: string | boolean;
/** MCP scope: user-level only, project-level only, or both. */
scope?: McpScope;
/** Test hook: override isTTY detection for the interactive scope prompt. */
@@ -627,6 +640,22 @@ export class ContentDirError extends Error {
}
}
+/**
+ * Resolve which user-global bundles `ok init` should enable from the `--skills`
+ * / `--no-skills` flag: `undefined`/`true` → every bundle; `false`
+ * (`--no-skills`) → none; a comma list (`--skills discovery`) → only the named
+ * bundle ids (unknown tokens ignored — the known-id set wins).
+ */
+export function resolveInitSkillEnablement(skills: string | boolean | undefined): Set<BundleId> {
+ if (skills === undefined || skills === true) return new Set(USER_GLOBAL_BUNDLE_IDS);
+ if (skills === false) return new Set();
+ const requested = skills
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+ return new Set(USER_GLOBAL_BUNDLE_IDS.filter((id) => requested.includes(id)));
+}
+
/**
* Resolve a user-supplied `--content-dir` (cwd-relative) into the git-root
* relative value stored in `config.yml`. Rejects paths that escape the project
@@ -706,7 +735,7 @@ interface InitCommandResult {
* `undefined` only when `content` scaffolding failed before the install
* step could run.
*/
- skillInstall?: InstallUserSkillResult;
+ skillInstall?: InstallUserSkillResult | 'declined';
/** Content preview result (undefined if preview failed or was not run). */
preview?: PreviewResult;
/** Claude launch.json result (undefined when Claude is not a selected editor). */
@@ -1664,11 +1693,48 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitCom
// user-global Agent Skill installed via `installUserSkill` from
// @inkeep/open-knowledge-server.
- // 4. Install the user-global Agent Skill. Non-fatal — init exits 0 even
- // on install failure; users see a warning + a manual-install hint in
- // the summary.
+ // 4. Install the enabled user-global Agent Skills. Per-bundle opt-in
+ // (`--skills` / `--no-skills`); the decision is recorded so the desktop /
+ // CLI reclaim gates never re-install a declined bundle. Non-fatal — init
+ // exits 0 even on install failure; users see a warning + manual-install hint.
const installSkill = options.installUserSkill ?? installUserSkill;
- const skillInstall = await installSkill({ home: options.home });
+ const skillHome = options.home ?? homedir();
+ const enabledBundles = resolveInitSkillEnablement(options.skills);
+ let anyEnabled = false;
+ let anyInstalled = false;
+ let anyFailed = false;
+ let anySkipped = false;
+ for (const id of USER_GLOBAL_BUNDLE_IDS) {
+ const enabled = enabledBundles.has(id);
+ await writeBundleDecision(skillHome, BUNDLE_SKILL_NAME[id], enabled).catch(() => {});
+ if (enabled) {
+ anyEnabled = true;
+ // force: the loop shares the `cli-hosts` version key across bundles, so
+ // one bundle's version write must not satisfy another's skip-current gate.
+ const result = await installSkill({ home: options.home, bundleId: id, force: true });
+ if (result === 'installed') anyInstalled = true;
+ else if (result === 'failed') anyFailed = true;
+ else anySkipped = true;
+ } else {
+ try {
+ removeUserGlobalSkillBundle(skillHome, id);
+ } catch {
+ // Fail-soft — the decline is already recorded; teardown is best-effort.
+ }
+ }
+ }
+ // Honest summary: a failure (even partial) surfaces the manual-install hint;
+ // declining every skill reports declined, not a false "already installed".
+ // The `skip-current` arm can't be reached from a real `ok init` (force always
+ // reinstalls) but is retained so an injected `installUserSkill` that returns
+ // `skip-current` still renders honestly.
+ const skillInstall: InstallUserSkillResult | 'declined' = anyFailed
+ ? 'failed'
+ : anyInstalled
+ ? 'installed'
+ : anyEnabled && anySkipped
+ ? 'skip-current'
+ : 'declined';
// Derive backward-compat fields from the Claude entry (preferred) or first result
const defaultAction: EditorMcpResult['action'] = skipMcp ? 'skipped-flag' : 'skipped-missing';
@@ -2037,6 +2103,9 @@ export function formatInitResult(result: InitCommandResult, cwd: string): string
case 'skip-current':
lines.push(` open-knowledge ${success('already installed at current version')}`);
break;
+ case 'declined':
+ lines.push(` open-knowledge ${dim('skipped (opted out via --no-skills)')}`);
+ break;
case 'failed':
lines.push(
` ${warning('open-knowledge install failed — MCP still configured; run manually:')}`,
@@ -2279,6 +2348,11 @@ export function initCommand(): Command {
`Limit content to <dir> instead of the whole project. <dir> is interpreted relative to your current directory (e.g. "." = the folder you run the command in), then saved to ${OK_DIR}/config.yml as content.dir.`,
)
.option('--json', 'Emit a structured JSON summary to stdout (diagnostics stay on stderr)')
+ .option(
+ '--skills <ids>',
+ 'Install only the named user-global skill bundles (comma list: discovery,write-skill)',
+ )
+ .option('--no-skills', 'Do not install any user-global skill bundles')
.addOption(
new Option(
'--scope <scope>',
@@ -2306,6 +2380,7 @@ export function initCommand(): Command {
localOnly?: boolean;
contentDir?: string;
json?: boolean;
+ skills?: string | boolean;
}) => {
const cwd = process.cwd();
@@ -2327,6 +2402,7 @@ export function initCommand(): Command {
scope: opts.scope,
sharing,
contentDir: opts.contentDir,
+ skills: opts.skills,
});
} catch (err) {
// Invalid `--content-dir` (outside the project, missing, or a file):
diff --git a/packages/cli/src/commands/repair-skills.test.ts b/packages/cli/src/commands/repair-skills.test.ts
index e3e7a8d93..58a3b72a2 100644
--- a/packages/cli/src/commands/repair-skills.test.ts
+++ b/packages/cli/src/commands/repair-skills.test.ts
@@ -61,6 +61,10 @@ function depsBuilder(opts: {
recordedEvents?: SkillInstallEvent[];
/** When true, `writeRecordedVersion` throws. */
failWrite?: boolean;
+ /** Per-bundle opt-in decision the sweep reads. Default consented. */
+ bundleDecision?: boolean | null;
+ /** Spy: pushed-to whenever `removeBundleFromDisk` is called. */
+ removals?: string[];
}): RepairSkillsDeps {
return {
resolveProjectBundledSkillDir: () => opts.projectBundleDir,
@@ -74,6 +78,13 @@ function depsBuilder(opts: {
recordEvent: async (event) => {
opts.recordedEvents?.push(event);
},
+ // Default consented so the user sweep proceeds (existing tests predate the
+ // opt-in gate). Gate-specific tests override these.
+ readBundleDecision: async () => opts.bundleDecision ?? true,
+ writeBundleDecision: async () => {},
+ removeBundleFromDisk: (_home, bundleId) => {
+ opts.removals?.push(bundleId);
+ },
};
}
@@ -491,6 +502,14 @@ describe('repairSkills — user sweep version gate (AC-B1, AC-B2, AC-B3, AC-B4)'
});
it('AC-B1: skips user sweep when recorded version equals bundled version', async () => {
+ // The version-current fast-path requires every ENABLED bundle already on
+ // disk (a missing bundle self-heals via reinstall — parity with
+ // installUserSkill). Seed both central dirs so the skip path is exercised.
+ for (const name of ['open-knowledge-discovery', 'open-knowledge-write-skill']) {
+ const dir = join(scratch.home, '.agents', 'skills', name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), 'preexisting');
+ }
const written: Array<{ home: string; version: string }> = [];
const result = await repairSkills({
projectDir: scratch.project,
@@ -511,14 +530,94 @@ describe('repairSkills — user sweep version gate (AC-B1, AC-B2, AC-B3, AC-B4)'
expect(result.user.reason).toBe('version-current');
expect(written).toHaveLength(0);
- // Critically: no writes touched the central store either.
- expect(existsSync(join(scratch.home, '.agents', 'skills', USER_SKILL_DIR_NAME))).toBe(false);
+ // The seeded central store is left byte-untouched by the skip.
+ expect(
+ readFileSync(
+ join(scratch.home, '.agents', 'skills', USER_SKILL_DIR_NAME, 'SKILL.md'),
+ 'utf-8',
+ ),
+ ).toBe('preexisting');
expect(logEvents.some((e) => e.event === 'user-skill-reclaim-skipped-version-current')).toBe(
true,
);
});
+ it('D4/G2 cross-actor stomp: a declined bundle is removed and never re-installed by the sweep', async () => {
+ // Seed both bundles on disk, then decline them. The sweep must remove them
+ // and NOT re-install — the CLI half of the invariant that stops `ok start`
+ // from re-adding what the desktop dialog removed.
+ for (const name of ['open-knowledge-discovery', 'open-knowledge-write-skill']) {
+ const dir = join(scratch.home, '.agents', 'skills', name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), 'preexisting');
+ }
+ const written: Array<{ home: string; version: string }> = [];
+ const removals: string[] = [];
+ const result = await repairSkills({
+ projectDir: scratch.project,
+ home: scratch.home,
+ logger: (event) => logEvents.push(event),
+ deps: depsBuilder({
+ projectBundleDir,
+ discoveryBundleDir,
+ bundledVersion: '9.9.9',
+ recordedVersion: '0.6.0', // version mismatch — sweep would install if enabled
+ writtenVersions: written,
+ bundleDecision: false,
+ removals,
+ }),
+ });
+
+ if (result.status !== 'done') throw new Error('unreachable');
+ expect(result.user.outcome).toBe('skipped');
+ if (result.user.outcome === 'skipped') expect(result.user.reason).toBe('all-bundles-declined');
+ // Both declined bundles were torn down; version not advanced.
+ expect(removals.sort()).toEqual(['discovery', 'write-skill']);
+ expect(written).toHaveLength(0);
+ });
+
+ it('mixed decision: the declined bundle is removed while the enabled bundle still installs', async () => {
+ // Seed both on disk, then decline ONLY write-skill. discovery must install
+ // (version mismatch) and write-skill must be torn down — the two gates run
+ // independently per bundle.
+ for (const name of ['open-knowledge-discovery', 'open-knowledge-write-skill']) {
+ const dir = join(scratch.home, '.agents', 'skills', name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), 'preexisting');
+ }
+ for (const host of ['.claude', '.cursor', '.codex']) {
+ mkdirSync(join(scratch.home, host), { recursive: true });
+ }
+ const written: Array<{ home: string; version: string }> = [];
+ const removals: string[] = [];
+ const deps = depsBuilder({
+ projectBundleDir,
+ discoveryBundleDir,
+ bundledVersion: '9.9.9',
+ recordedVersion: '0.6.0',
+ writtenVersions: written,
+ removals,
+ });
+ deps.readBundleDecision = async (_home, name) => name !== 'open-knowledge-write-skill';
+
+ const result = await repairSkills({
+ projectDir: scratch.project,
+ home: scratch.home,
+ logger: (event) => logEvents.push(event),
+ deps,
+ });
+
+ if (result.status !== 'done' || result.user.outcome !== 'done') throw new Error('unreachable');
+ expect(removals).toEqual(['write-skill']);
+ expect(
+ result.user.entries.some(
+ (e) => e.kind === 'central' && (e.outcome === 'written' || e.outcome === 'overwritten'),
+ ),
+ ).toBe(true);
+ expect(written).toHaveLength(1);
+ });
+
it('AC-B2: refreshes central + per-host and advances skill-state when version mismatches', async () => {
// Seed the per-host roots so they aren't `skipped-host-absent`.
mkdirSync(join(scratch.home, '.claude'), { recursive: true });
@@ -1016,6 +1115,13 @@ describe('repairSkills — JSONL telemetry parity with Desktop', () => {
});
it('emits NO event on the version-current fast-path', async () => {
+ // Seed both enabled bundles on disk so the version-current fast-path fires
+ // (a missing bundle self-heals via reinstall, which would emit events).
+ for (const name of ['open-knowledge-discovery', 'open-knowledge-write-skill']) {
+ const dir = join(scratch.home, '.agents', 'skills', name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), 'preexisting');
+ }
const written: Array<{ home: string; version: string }> = [];
const recordedEvents: SkillInstallEvent[] = [];
@@ -1155,6 +1261,7 @@ describe('repairSkills — JSONL telemetry parity with Desktop', () => {
recordEvent: async () => {
throw new Error('synthetic telemetry failure');
},
+ readBundleDecision: async () => true,
},
});
@@ -1237,7 +1344,11 @@ describe('repairSkillsResultExitCode (PR feedback: standalone exit code mapping)
function mkDone(opts: {
projectFailed?: boolean;
userFailedHost?: boolean;
- userSkipped?: 'version-current' | 'bundle-missing' | 'version-read-failed';
+ userSkipped?:
+ | 'version-current'
+ | 'bundle-missing'
+ | 'version-read-failed'
+ | 'all-bundles-declined';
}): RepairSkillsResult {
const project: RepairSkillsResult extends infer R
? R extends { project: infer P }
@@ -1275,6 +1386,14 @@ describe('repairSkillsResultExitCode (PR feedback: standalone exit code mapping)
expect(repairSkillsResultExitCode({ status: 'skipped', reason: 'reclaim-disabled' })).toBe(0);
});
+ it('all-bundles-declined user-sweep skip exits 0 (intentional opt-out, not a failure)', () => {
+ // The real shape: runUserSweep returns it as result.user.reason with a
+ // top-level status of 'done' — NOT a top-level skip.
+ const result = mkDone({ userSkipped: 'all-bundles-declined' });
+ expect(result.status).toBe('done');
+ expect(repairSkillsResultExitCode(result)).toBe(0);
+ });
+
it('any other top-level skip exits 1', () => {
expect(repairSkillsResultExitCode({ status: 'skipped', reason: 'something-else' })).toBe(1);
});
diff --git a/packages/cli/src/commands/repair-skills.ts b/packages/cli/src/commands/repair-skills.ts
index ab7e9a30a..bcdf54b36 100644
--- a/packages/cli/src/commands/repair-skills.ts
+++ b/packages/cli/src/commands/repair-skills.ts
@@ -32,15 +32,19 @@ import { dirname, join, resolve as resolvePath } from 'node:path';
import {
BUNDLE_SKILL_NAME,
type BundleId,
+ readBundleDecision,
readServerPackageVersion,
readTargetVersion,
recordSkillInstallEvent,
resolveBundledSkillDir,
+ resolveBundleEnabled,
type SkillInstallEvent,
USER_GLOBAL_BUNDLE_IDS,
+ writeBundleDecision,
writeTargetVersion,
} from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
+import { removeUserGlobalSkillBundle } from '../integrations/skill-teardown.ts';
import { assertProjectPathSafe } from '../integrations/write-project-skill.ts';
import {
CHAIN_VERSION_SENTINEL,
@@ -69,6 +73,8 @@ export interface RepairSkillsLogEvent {
version?: string;
preexisting?: boolean;
reason?: string;
+ /** Bundle id for per-bundle events. Matches the desktop reclaim's `bundle:` key. */
+ bundle?: string;
error?: string;
}
@@ -127,6 +133,12 @@ export interface RepairSkillsDeps {
* "did this install land?" question is answerable for CLI users too.
*/
recordEvent?(event: SkillInstallEvent): Promise<void>;
+ /** Override for `readBundleDecision(home, name)` — per-bundle opt-in gate. */
+ readBundleDecision?(home: string, bundleName: string): Promise<boolean | null>;
+ /** Override for `writeBundleDecision(home, name, enabled)` — grandfather materialization. */
+ writeBundleDecision?(home: string, bundleName: string, enabled: boolean): Promise<void>;
+ /** Override for `removeUserGlobalSkillBundle(home, id)` — decline removal. */
+ removeBundleFromDisk?(home: string, bundleId: BundleId): void;
}
const defaultDeps: Required<RepairSkillsDeps> = {
@@ -137,6 +149,9 @@ const defaultDeps: Required<RepairSkillsDeps> = {
writeRecordedVersion: (home, version) =>
writeTargetVersion(home, 'cli-hosts', version, 'cli-start'),
recordEvent: (event) => recordSkillInstallEvent(event),
+ readBundleDecision: (home, name) => readBundleDecision(home, name),
+ writeBundleDecision: (home, name, enabled) => writeBundleDecision(home, name, enabled),
+ removeBundleFromDisk: (home, bundleId) => removeUserGlobalSkillBundle(home, bundleId),
};
export interface RepairSkillsContext {
@@ -524,21 +539,6 @@ async function runUserSweep(
recordedVersion = null;
}
- if (recordedVersion !== null && recordedVersion === bundledVersion) {
- logger({
- event: 'user-skill-reclaim-skipped-version-current',
- scope: 'user',
- version: bundledVersion,
- });
- // No JSONL event on the version-current fast-path — Desktop force-writes
- // every launch and emits an `installed` event each time, which makes the
- // log noisy but answers "did the install land?". The CLI's version-gate
- // means the same answer is already in `skill-state.yml.cli-hosts` — a
- // version-current skip is provably equivalent to the prior successful
- // write, so logging it again is pure noise.
- return { outcome: 'skipped', reason: 'version-current' };
- }
-
// Resolve every user-global built-in bundle's source up front (discovery +
// write-skill, from the single-source `USER_GLOBAL_BUNDLE_IDS`). The bundles
// ship together, so a resolve failure means the assets dir is missing for
@@ -568,12 +568,86 @@ async function runUserSweep(
return { outcome: 'skipped', reason: 'bundle-missing' };
}
- // Force-install each resolved bundle into the central store + per-host dirs.
+ // Per-bundle opt-in gate — identical policy to the desktop reclaim. Declined
+ // bundles are removed and skipped; unrecorded bundles grandfather to disk
+ // presence (existing install stays + records the decision). Runs BEFORE the
+ // version fast-path so a decline is honored even when the recorded version is
+ // current.
+ const gatedBundles: Array<{ id: BundleId; sourceDir: string }> = [];
+ for (const bundle of resolvedBundles) {
+ const name = BUNDLE_SKILL_NAME[bundle.id];
+ const onDisk = fs.existsSync(join(home, '.agents', 'skills', name));
+ const decision = await deps.readBundleDecision(home, name).catch(() => null);
+ if (!resolveBundleEnabled(decision, { installedOnDisk: onDisk })) {
+ if (onDisk) {
+ try {
+ deps.removeBundleFromDisk(home, bundle.id);
+ logger({
+ event: 'user-skill-reclaim-bundle-declined-removed',
+ scope: 'user',
+ bundle: bundle.id,
+ });
+ } catch (err) {
+ logger({
+ event: 'user-skill-reclaim-bundle-remove-failed',
+ scope: 'user',
+ bundle: bundle.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ continue;
+ }
+ if (decision === null && onDisk) {
+ // Materialize the grandfathered decision. Fail-soft (the bundle stays
+ // installed regardless), but log so a persistently unwritable state file
+ // — which re-enters this path every boot — leaves a trail.
+ try {
+ await deps.writeBundleDecision(home, name, true);
+ } catch (err) {
+ logger({
+ event: 'user-skill-reclaim-grandfather-write-failed',
+ scope: 'user',
+ bundle: bundle.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ gatedBundles.push(bundle);
+ }
+ if (gatedBundles.length === 0) {
+ return { outcome: 'skipped', reason: 'all-bundles-declined' };
+ }
+
+ // Version fast-path — skip the copy only when the recorded version is current
+ // AND every enabled bundle is already on disk (a freshly-enabled bundle must
+ // install even at the current version).
+ const allEnabledOnDisk = gatedBundles.every((b) =>
+ fs.existsSync(join(home, '.agents', 'skills', BUNDLE_SKILL_NAME[b.id])),
+ );
+ if (recordedVersion !== null && recordedVersion === bundledVersion && allEnabledOnDisk) {
+ logger({
+ event: 'user-skill-reclaim-skipped-version-current',
+ scope: 'user',
+ version: bundledVersion,
+ });
+ // No JSONL event on the version-current fast-path — a version-current skip
+ // is provably equivalent to the prior successful write, so logging it again
+ // is pure noise. (See the pre-existing rationale retained from the eager path.)
+ return { outcome: 'skipped', reason: 'version-current' };
+ }
+
+ // Force-install each enabled bundle into the central store + per-host dirs.
const entries: UserSkillEntry[] = [];
- // A bundle that failed to resolve (rare — assets partially present) counts
- // against the version-advance gate so the next boot retries.
- let everyCentralWritten = resolvedBundles.length === USER_GLOBAL_BUNDLE_IDS.length;
- for (const { id, sourceDir } of resolvedBundles) {
+ // Two independent conditions gate the version advance, tracked separately so
+ // the gate below reads plainly. (1) Every user-global bundle resolved — a
+ // bundle that failed to resolve (rare — assets partially present) must leave
+ // the version unrecorded so the next boot retries. Declined bundles are
+ // excluded by choice, not failure, so they don't block the advance.
+ const allBundlesResolved = resolvedBundles.length === USER_GLOBAL_BUNDLE_IDS.length;
+ // (2) Every gated bundle's central write landed.
+ let allGatedCentralsWritten = true;
+ for (const { id, sourceDir } of gatedBundles) {
const result = installUserBundleToHostDirs(
home,
BUNDLE_SKILL_NAME[id],
@@ -583,7 +657,7 @@ async function runUserSweep(
bundledVersion,
);
entries.push(...result.entries);
- if (!result.centralWritten) everyCentralWritten = false;
+ if (!result.centralWritten) allGatedCentralsWritten = false;
}
// Gate version advance on EVERY bundle's central write landing — the same
@@ -594,7 +668,7 @@ async function runUserSweep(
const anyCentralWritten = entries.some(
(e) => e.kind === 'central' && (e.outcome === 'written' || e.outcome === 'overwritten'),
);
- if (everyCentralWritten && anyCentralWritten) {
+ if (allBundlesResolved && allGatedCentralsWritten && anyCentralWritten) {
let stateWriteError: string | null = null;
try {
await deps.writeRecordedVersion(home, bundledVersion);
@@ -615,7 +689,7 @@ async function runUserSweep(
// One outcome event per installed bundle, gated on the state-file write —
// an `installed` event paired with a stale `skill-state.yml` would mislead
// any operator chasing "did the install actually land?".
- for (const { id } of resolvedBundles) {
+ for (const { id } of gatedBundles) {
recordEventSoft({
ts: nowIso(),
surface: 'cli-start',
@@ -687,10 +761,22 @@ export async function repairSkills(ctx: RepairSkillsContext): Promise<RepairSkil
*/
function repairSkillsResultExitCode(result: RepairSkillsResult): number {
if (result.status === 'skipped') {
+ // Top-level skip is only the env kill-switch — an intentional opt-out.
return result.reason === 'reclaim-disabled' ? 0 : 1;
}
if (result.project.outcome === 'skipped') return 1;
- if (result.user.outcome === 'skipped' && result.user.reason !== 'version-current') return 1;
+ // `all-bundles-declined` arrives here as a user-sweep skip (result.user), NOT
+ // a top-level one. Like `version-current` it is a supported success state
+ // (the user opted out of every skill), so it must exit 0 — a non-zero exit
+ // would break `&&`-chains and CI gates. Every other user-sweep skip is a real
+ // failure.
+ if (
+ result.user.outcome === 'skipped' &&
+ result.user.reason !== 'version-current' &&
+ result.user.reason !== 'all-bundles-declined'
+ ) {
+ return 1;
+ }
if (result.project.entries.some((e) => e.outcome === 'failed')) return 1;
if (result.user.outcome === 'done' && result.user.entries.some((e) => e.outcome === 'failed'))
return 1;
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 08890364c..fead87d8f 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -99,6 +99,11 @@ export {
type ResolveProjectRootResult,
resolveProjectRoot,
} from './integrations/resolve-project-root.ts';
+export {
+ removeUserGlobalSkillBundle,
+ type SkillBundleTarget,
+ userGlobalSkillBundleTargets,
+} from './integrations/skill-teardown.ts';
export {
type ProjectAiIntegrationsResult,
writeProjectAiIntegrations,
diff --git a/packages/cli/src/integrations/skill-teardown.ts b/packages/cli/src/integrations/skill-teardown.ts
index fee97a01a..edd45d45c 100644
--- a/packages/cli/src/integrations/skill-teardown.ts
+++ b/packages/cli/src/integrations/skill-teardown.ts
@@ -23,6 +23,7 @@
* (OK-authored global skills) and `~/Downloads/openknowledge.skill`.
*/
+import { rmSync } from 'node:fs';
import { join } from 'node:path';
import {
BUNDLE_SKILL_NAME,
@@ -67,3 +68,36 @@ export function userGlobalSkillBundleTargets(home: string): SkillBundleTarget[]
}
return targets;
}
+
+/**
+ * Remove ONE user-global bundle's directories (central + every per-host copy)
+ * from disk. Used by the opt-out paths (dialog decline, `ok init --no-skills`,
+ * the reclaim/sweep gate) so an unchecked bundle actually leaves — the exact
+ * reverse of `installUserBundleToHostDirs`. Tolerant of already-absent dirs
+ * (`rmSync` with `force`). Only the specific `open-knowledge-*` dirs, never the
+ * shared `~/.agents/skills` root.
+ */
+export function removeUserGlobalSkillBundle(home: string, bundleId: BundleId): void {
+ // Attempt EVERY path before signaling failure. `force` swallows ENOENT but
+ // not EACCES/EBUSY/EIO — a throw on one host copy must not abort the rest, or
+ // a declined bundle half-leaves and the next reclaim sees inconsistent state
+ // across hosts. Collect failures and re-throw at the end so callers whose
+ // telemetry / gate depends on it (they wrap this in try/catch and log
+ // `bundle-remove-failed`) still observe a partial teardown rather than a
+ // false "removed".
+ const failures: Error[] = [];
+ for (const target of userGlobalSkillBundleTargets(home)) {
+ if (target.bundleId !== bundleId) continue;
+ try {
+ rmSync(target.path, { recursive: true, force: true });
+ } catch (err) {
+ failures.push(err instanceof Error ? err : new Error(String(err)));
+ }
+ }
+ if (failures.length > 0) {
+ throw new AggregateError(
+ failures,
+ `Failed to remove ${failures.length} path(s) for ${bundleId}`,
+ );
+ }
+}
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 63cd19916..a9b7ea6fa 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -387,6 +387,14 @@ interface OkMcpWiringShowPayload {
readonly rcFilesToTouch: readonly string[];
readonly alreadyInstalled: boolean;
};
+ /** Per-bundle opt-in rows for the two user-global skills. Empty ⇒ no skill
+ * decision solicited. `alreadyInstalled: true` renders the row pre-checked
+ * as an existing install the user can uncheck to remove. */
+ readonly globalSkills: readonly {
+ readonly id: string;
+ readonly name: string;
+ readonly alreadyInstalled: boolean;
+ }[];
}
/**
@@ -394,10 +402,15 @@ interface OkMcpWiringShowPayload {
* toggle, tri-state: `true` → append the managed rc block (consent
* granted); `false` → record declined, touch no rc file; absent → no PATH
* decision was solicited (row hidden or informational).
+ *
+ * `skills` — bundle ids the user left checked. Present ⇒ a skill decision was
+ * solicited; every offered bundle not in the list is recorded declined (and
+ * removed if already installed).
*/
interface OkMcpWiringConfirmRequest {
readonly editorIds: readonly OkMcpWiringEditorId[];
readonly pathInstall?: boolean;
+ readonly skills?: readonly string[];
}
/**
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index f68bd2bca..ece18a3b4 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1132,6 +1132,7 @@ export {
} from './sharing/index.ts';
export {
emptySkillState,
+ resolveBundleEnabled,
SKILL_STATE_FILENAME,
SKILL_STATE_REL,
SKILL_STATE_SCHEMA_VERSION,
@@ -1139,6 +1140,7 @@ export {
SKILL_STATE_TARGETS,
SKILL_STATE_VERSION_RE,
type SkillState,
+ type SkillStateBundleEntry,
SkillStateSchema,
type SkillStateSurface,
type SkillStateTarget,
diff --git a/packages/core/src/skill-state/schema.ts b/packages/core/src/skill-state/schema.ts
index ef4697235..a1bda8066 100644
--- a/packages/core/src/skill-state/schema.ts
+++ b/packages/core/src/skill-state/schema.ts
@@ -103,6 +103,23 @@ const TargetEntrySchema = z.looseObject({
.optional(),
});
+/**
+ * Per-bundle opt-in decision. Keyed by a bundle's install NAME (e.g.
+ * `open-knowledge-discovery`), NOT the install target. `enabled: false` is an
+ * explicit decline recorded via the first-launch consent dialog or `ok init
+ * --no-skills`; an absent key means "no recorded decision" (grandfather: the
+ * gate falls back to disk presence). Each leaf `.register()` BEFORE wrappers
+ * per the Zod v4 metadata-binding rule.
+ */
+const BundleDecisionEntrySchema = z.looseObject({
+ enabled: z.boolean().register(skillStateFieldRegistry, {
+ description: 'Whether this user-global skill bundle is opted in.',
+ }),
+ decidedAt: z.iso.datetime().register(skillStateFieldRegistry, {
+ description: 'ISO 8601 timestamp of the opt-in / opt-out decision.',
+ }),
+});
+
/**
* Top-level schema. `looseObject` everywhere for forward-compat: a future
* version can add target keys or per-entry fields without breaking older
@@ -121,10 +138,34 @@ export const SkillStateSchema = z.looseObject({
description: 'Per-target install-state entries. Absent target = no recorded install.',
})
.default({}),
+ bundles: z
+ .record(z.string(), BundleDecisionEntrySchema)
+ .register(skillStateFieldRegistry, {
+ description:
+ 'Per-bundle opt-in decisions keyed by install name. Absent key = no recorded decision.',
+ })
+ .optional(),
});
export type SkillState = z.infer<typeof SkillStateSchema>;
export type SkillStateTargetEntry = z.infer<typeof TargetEntrySchema>;
+export type SkillStateBundleEntry = z.infer<typeof BundleDecisionEntrySchema>;
+
+/**
+ * The single per-bundle enablement policy, kept pure (no disk) so it's
+ * trivially testable and shared by every install actor (desktop reclaim, CLI
+ * sweep, `ok init`, dialog confirm). Explicit recorded decision wins; an
+ * unrecorded bundle grandfathers to whatever is on disk (existing install
+ * stays, truly-fresh machine stays uninstalled until the dialog / `ok init`
+ * records a decision). Lives in core so the desktop module can reach it
+ * without importing the server package.
+ */
+export function resolveBundleEnabled(
+ decision: boolean | null,
+ opts: { installedOnDisk: boolean },
+): boolean {
+ return decision ?? opts.installedOnDisk;
+}
/**
* Build an empty `SkillState` document with a current schema version. Used
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index bfcfe9297..f6078249d 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -53,6 +53,7 @@ import {
type ProjectAiIntegrationsResult,
previewContent,
readExistingMcpEntry,
+ removeUserGlobalSkillBundle,
runStop,
type TrackedRefusal,
validateLocalFolderForShare,
@@ -83,6 +84,7 @@ import {
normalizeFsPath,
prepareSingleFileOpen,
RUNTIME_VERSION,
+ readBundleDecision,
readServerLock,
readServerPackageVersion,
recordSkillInstallEvent,
@@ -90,6 +92,7 @@ import {
resolveLockDir,
USER_GLOBAL_BUNDLE_IDS,
withSpan,
+ writeBundleDecision,
writeTargetVersion,
} from '@inkeep/open-knowledge-server';
import type { BrowserWindowConstructorOptions } from 'electron';
@@ -2225,6 +2228,47 @@ function buildEnsureCliOnPathOpts() {
};
}
+/**
+ * Shared opts for `reclaimUserSkillsOnLaunch` — one builder so the launch
+ * fire-and-forget leg and the consent-dialog confirm leg run the identical
+ * gate set (env gates, per-bundle opt-in, install/teardown) against the same
+ * marker. The reclaim itself honors the recorded per-bundle decisions.
+ */
+function buildReclaimUserSkillsOpts(): Parameters<typeof reclaimUserSkillsOnLaunch>[0] {
+ return {
+ home: osHomedir(),
+ isPackaged: app.isPackaged,
+ platform: process.platform,
+ executablePath: app.getPath('exe'),
+ forceEnv: process.env.OK_M6B_FORCE ?? null,
+ reclaimDisableEnv: process.env.OK_RECLAIM_DISABLE ?? null,
+ deps: {
+ // checkDesktop:false — the desktop resolves its own assets.
+ userGlobalBundles: USER_GLOBAL_BUNDLE_IDS.map((id) => ({ id, name: BUNDLE_SKILL_NAME[id] })),
+ resolveBundledSkillDir: (bundle) =>
+ resolveBundledSkillDir(bundle as (typeof USER_GLOBAL_BUNDLE_IDS)[number], {
+ checkDesktop: false,
+ }),
+ readServerPackageVersion,
+ writeTargetVersion: (home, target, version, surface) =>
+ writeTargetVersion(home, target, version, surface),
+ readBundleDecision: (home, name) => readBundleDecision(home, name),
+ writeBundleDecision: (home, name, enabled) => writeBundleDecision(home, name, enabled),
+ // `bundleId` originates from `USER_GLOBAL_BUNDLE_IDS`, so the cast to the
+ // CLI's `BundleId` is sound.
+ removeBundleFromDisk: (bundleId) =>
+ removeUserGlobalSkillBundle(
+ osHomedir(),
+ bundleId as (typeof USER_GLOBAL_BUNDLE_IDS)[number],
+ ),
+ // The reclaim module types `bundle` as `string` to stay import-free; the
+ // values come from `USER_GLOBAL_BUNDLE_IDS` so they're real ids.
+ recordSkillInstallEvent: (event) =>
+ recordSkillInstallEvent(event as Parameters<typeof recordSkillInstallEvent>[0]),
+ },
+ };
+}
+
function createMcpWiringOpts(opts: ArmMcpWiringOpts = {}) {
return {
isPackaged: app.isPackaged,
@@ -2261,6 +2305,48 @@ function createMcpWiringOpts(opts: ArmMcpWiringOpts = {}) {
return { ok: true as const };
},
},
+ // Skills leg of the first-launch consent dialog: per-bundle rows for the
+ // show payload + the confirm finalizer. `applyConsent` records every
+ // bundle's decision, then reuses the launch reclaim (now decision-gated)
+ // to install the enabled set and tear down any declined-but-present
+ // bundle — one code path for install + removal.
+ skills: {
+ computeDescriptors: () =>
+ USER_GLOBAL_BUNDLE_IDS.map((id) => ({
+ id,
+ name: BUNDLE_SKILL_NAME[id],
+ alreadyInstalled: existsSync(
+ join(osHomedir(), '.agents', 'skills', BUNDLE_SKILL_NAME[id]),
+ ),
+ })),
+ applyConsent: async (enabledIds: readonly string[]) => {
+ const home = osHomedir();
+ // The consent dialog is the trust boundary: a failed decision write
+ // must NOT be swallowed. If it were, the reclaim below would re-read a
+ // null decision, grandfather an already-installed declined bundle back
+ // to enabled, and still return ok — silently losing the user's
+ // decline. Surface {ok:false} so mcp-wiring defers the marker and the
+ // dialog re-fires for a retry (same as a failed PATH/editor write).
+ for (const id of USER_GLOBAL_BUNDLE_IDS) {
+ try {
+ await writeBundleDecision(home, BUNDLE_SKILL_NAME[id], enabledIds.includes(id));
+ } catch (err) {
+ return {
+ ok: false as const,
+ error: `Couldn't save your preference for ${BUNDLE_SKILL_NAME[id]}: ${
+ err instanceof Error ? err.message : String(err)
+ }`,
+ };
+ }
+ }
+ try {
+ await reclaimUserSkillsOnLaunch(buildReclaimUserSkillsOpts());
+ } catch (err) {
+ return { ok: false as const, error: err instanceof Error ? err.message : String(err) };
+ }
+ return { ok: true as const };
+ },
+ },
forceEnv: process.env.OK_M6B_FORCE ?? null,
reclaimDisableEnv: process.env.OK_RECLAIM_DISABLE ?? null,
forceShow: opts.forceShow ?? false,
@@ -4321,37 +4407,12 @@ function bootPrimaryInstance(): void {
}
// Fire-and-forget user-global Agent Skill reclaim. Runs on every launch
- // — force-writes the bundled SKILL into the central store and per-host
- // dirs. PATH-independent (no npx subprocess), so it survives the GUI
- // launch context where /opt/homebrew/bin and ~/.nvm/… are off PATH and
- // the prior `installUserSkill` path silently spawn-error'd. Never awaited
- // so window rendering + menu are unblocked.
- void reclaimUserSkillsOnLaunch({
- home: osHomedir(),
- isPackaged: app.isPackaged,
- platform: process.platform,
- executablePath: app.getPath('exe'),
- forceEnv: process.env.OK_M6B_FORCE ?? null,
- reclaimDisableEnv: process.env.OK_RECLAIM_DISABLE ?? null,
- deps: {
- // User-global reclaim installs every user-global built-in bundle
- // (discovery + write-skill), wired from the single source.
- // checkDesktop:false — the desktop resolves its own assets.
- userGlobalBundles: USER_GLOBAL_BUNDLE_IDS.map((id) => ({
- id,
- name: BUNDLE_SKILL_NAME[id],
- })),
- resolveBundledSkillDir: (bundle) =>
- resolveBundledSkillDir(bundle, { checkDesktop: false }),
- readServerPackageVersion,
- writeTargetVersion: (home, target, version, surface) =>
- writeTargetVersion(home, target, version, surface),
- // The reclaim module types `bundle` as `string` to stay import-free;
- // the values come from `USER_GLOBAL_BUNDLE_IDS` so they're real ids.
- recordSkillInstallEvent: (event) =>
- recordSkillInstallEvent(event as Parameters<typeof recordSkillInstallEvent>[0]),
- },
- }).catch((err) => {
+ // — force-writes each ENABLED bundle's SKILL into the central store and
+ // per-host dirs (per-bundle opt-in gated; declined bundles are removed).
+ // PATH-independent (no npx subprocess), so it survives the GUI launch
+ // context where /opt/homebrew/bin and ~/.nvm/… are off PATH. Never
+ // awaited so window rendering + menu are unblocked.
+ void reclaimUserSkillsOnLaunch(buildReclaimUserSkillsOpts()).catch((err) => {
console.warn('[main] user-skill reclaim failed', {
err: err instanceof Error ? err.message : String(err),
});
diff --git a/packages/desktop/src/main/mcp-wiring.test.ts b/packages/desktop/src/main/mcp-wiring.test.ts
index 56b86781c..791e91272 100644
--- a/packages/desktop/src/main/mcp-wiring.test.ts
+++ b/packages/desktop/src/main/mcp-wiring.test.ts
@@ -35,6 +35,7 @@ import {
type McpWiringDispatchTarget,
type McpWiringFsOps,
type McpWiringPathInstallSurface,
+ type McpWiringSkillsSurface,
readMcpStatusMarker,
runMcpWiringOnFirstLaunch,
writeMcpStatusMarker,
@@ -676,6 +677,25 @@ function stubPathInstall(
};
}
+/** Skills stub recording `applyConsent` calls. Defaults to NO skill rows so
+ * existing payload/confirm assertions are unaffected; dedicated skills tests
+ * pass descriptors. */
+function stubSkills(
+ descriptors: ReturnType<McpWiringSkillsSurface['computeDescriptors']> = [],
+ overrides: Partial<McpWiringSkillsSurface> = {},
+): McpWiringSkillsSurface & { consentCalls: string[][] } {
+ const consentCalls: string[][] = [];
+ return {
+ consentCalls,
+ computeDescriptors: () => descriptors,
+ applyConsent: async (enabledIds) => {
+ consentCalls.push([...enabledIds]);
+ return { ok: true as const };
+ },
+ ...overrides,
+ };
+}
+
function buildWiringOpts(overrides: Partial<WiringOpts> = {}): WiringOpts {
const { cli } = buildFirstLaunchCli();
return {
@@ -686,12 +706,88 @@ function buildWiringOpts(overrides: Partial<WiringOpts> = {}): WiringOpts {
ipcMain: stubIpcMain(),
cli,
pathInstall: stubPathInstall(),
+ skills: stubSkills(),
fs: memoryFs(),
logger: SILENT_LOGGER,
...overrides,
};
}
+describe('runMcpWiringOnFirstLaunch — skills consent leg', () => {
+ const TWO_SKILLS = [
+ {
+ id: 'discovery',
+ name: 'open-knowledge-discovery',
+ alreadyInstalled: false,
+ },
+ {
+ id: 'write-skill',
+ name: 'open-knowledge-write-skill',
+ alreadyInstalled: true,
+ },
+ ];
+
+ test('confirm applies the checked skill subset and emits per-bundle telemetry', async () => {
+ const ipcMain = stubIpcMain();
+ const wc = fakeWebContents(11);
+ const fs = memoryFs();
+ const { cli } = buildFirstLaunchCli();
+ const skills = stubSkills(TWO_SKILLS);
+ const events: Array<Record<string, unknown>> = [];
+ const logger = {
+ info: () => {},
+ warn: () => {},
+ error: () => {},
+ event: (p: { event: string; [k: string]: unknown }) => events.push(p),
+ };
+ runMcpWiringOnFirstLaunch(
+ buildWiringOpts({ ipcMain, cli, fs, skills, logger, immediateDispatchTarget: wc }),
+ );
+
+ // Skill rows rode along in the show payload.
+ expect(wc.sent[0]?.payload).toMatchObject({ globalSkills: TWO_SKILLS });
+
+ const confirm = ipcMain.handlers.get('ok:mcp-wiring:confirm');
+ const result = await confirm?.(
+ { sender: { id: 11 } },
+ { editorIds: ['claude'], skills: ['discovery'] },
+ );
+ expect(result).toEqual({ ok: true });
+ // Only the checked bundle is enabled; write-skill declined.
+ expect(skills.consentCalls).toEqual([['discovery']]);
+ expect(events).toContainEqual({
+ event: 'mcp-wiring-skill-consent-granted',
+ bundle: 'discovery',
+ });
+ expect(events).toContainEqual({
+ event: 'mcp-wiring-skill-consent-declined',
+ bundle: 'write-skill',
+ });
+ });
+
+ test('a failed skills leg defers the marker so the dialog re-fires', async () => {
+ const ipcMain = stubIpcMain();
+ const wc = fakeWebContents(11);
+ const fs = memoryFs();
+ const { cli } = buildFirstLaunchCli();
+ const skills = stubSkills(TWO_SKILLS, {
+ applyConsent: async () => ({ ok: false as const, error: 'disk full' }),
+ });
+ runMcpWiringOnFirstLaunch(
+ buildWiringOpts({ ipcMain, cli, fs, skills, immediateDispatchTarget: wc }),
+ );
+
+ const confirm = ipcMain.handlers.get('ok:mcp-wiring:confirm');
+ const result = await confirm?.(
+ { sender: { id: 11 } },
+ { editorIds: ['claude'], skills: ['discovery'] },
+ );
+ expect(result?.ok).toBe(false);
+ // Deferred-marker: nothing recorded, so a next-boot re-fire recovers.
+ expect(readMcpStatusMarker('/home/u', fs)).toBeNull();
+ });
+});
+
describe('runMcpWiringOnFirstLaunch — mid-session immediate dispatch', () => {
test('show dispatches to the provided target and binds confirm to its sender', async () => {
const ipcMain = stubIpcMain();
@@ -713,6 +809,7 @@ describe('runMcpWiringOnFirstLaunch — mid-session immediate dispatch', () => {
rcFilesToTouch: ['~/.zshrc'],
alreadyInstalled: false,
},
+ globalSkills: [],
},
},
]);
diff --git a/packages/desktop/src/main/mcp-wiring.ts b/packages/desktop/src/main/mcp-wiring.ts
index d73d03101..4f44e58aa 100644
--- a/packages/desktop/src/main/mcp-wiring.ts
+++ b/packages/desktop/src/main/mcp-wiring.ts
@@ -343,6 +343,30 @@ export interface McpWiringPathInstallSurface {
): Promise<{ ok: true } | { ok: false; error: string }>;
}
+/**
+ * User-global skills surface consumed by the first-launch consent flow.
+ * Injected (like `McpWiringPathInstallSurface`) so this module stays
+ * electron-free and tests stub it; `main/index.ts` wires the real reclaim +
+ * teardown pipeline in.
+ */
+export interface McpWiringSkillsSurface {
+ /** One row per user-global bundle for the dialog. Read-only — must not
+ * write. `alreadyInstalled` pre-checks the row (grandfathered install). */
+ computeDescriptors(): Array<{
+ id: string;
+ name: string;
+ alreadyInstalled: boolean;
+ }>;
+ /**
+ * Finalize the per-bundle decision. Records enabled for every id in
+ * `enabledBundleIds` and declined for the rest, then installs the enabled
+ * set and tears down any declined-but-present bundle.
+ */
+ applyConsent(
+ enabledBundleIds: readonly string[],
+ ): Promise<{ ok: true } | { ok: false; error: string }>;
+}
+
/** Minimal logger surface — bracket-prefix operational + structured events. */
interface McpWiringLogger {
info(msg: string, ctx?: object): void;
@@ -412,6 +436,7 @@ interface RunMcpWiringOpts {
*/
export interface RunMcpWiringFirstLaunchOpts extends RunMcpWiringOpts {
pathInstall: McpWiringPathInstallSurface;
+ skills: McpWiringSkillsSurface;
}
export interface RunMcpWiringHandle {
@@ -603,6 +628,7 @@ export function runMcpWiringOnFirstLaunch(opts: RunMcpWiringFirstLaunchOpts): Ru
ipcMain,
cli,
pathInstall,
+ skills,
forceEnv,
reclaimDisableEnv,
forceShow = false,
@@ -727,6 +753,19 @@ export function runMcpWiringOnFirstLaunch(opts: RunMcpWiringFirstLaunchOpts): Ru
pathDescriptor = { shellDetected: false, rcFilesToTouch: [], alreadyInstalled: false };
}
+ // Skill rows for the show payload. A descriptor failure degrades to no skill
+ // rows (empty ⇒ no skill decision solicited) rather than taking the dialog
+ // down — the File-menu re-trigger recovers once the cause is fixed.
+ let skillDescriptors: ReturnType<McpWiringSkillsSurface['computeDescriptors']>;
+ try {
+ skillDescriptors = skills.computeDescriptors();
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ logger.error('skill descriptors failed — skill rows hidden for this boot', { message });
+ logger.event({ event: 'mcp-wiring-skill-descriptors-failed', error: message });
+ skillDescriptors = [];
+ }
+
// Once-per-boot idempotence for SUCCESSFUL handler runs. Flipped
// synchronously at handler entry on first confirm/skip so a rage-click
// race (Add+Skip in quick succession) collapses to at most one effective
@@ -905,6 +944,50 @@ export function runMcpWiringOnFirstLaunch(opts: RunMcpWiringFirstLaunchOpts): Ru
logger.info('path consent applied', { decision: pathDecision });
}
+ // Skills leg — apply per-bundle consent when the dialog solicited a
+ // decision (skill rows were offered). Runs after PATH and BEFORE the
+ // marker write so a failed skills leg defers the marker like a failed
+ // editor/PATH write: the dialog stays mounted for a same-boot retry and
+ // re-fires next boot. `request.skills` is the checked subset; every offered
+ // bundle not listed is recorded declined (and removed if present).
+ if (skillDescriptors.length > 0) {
+ const offeredIds = new Set(skillDescriptors.map((d) => d.id));
+ const enabledIds = Array.isArray(request?.skills)
+ ? request.skills.filter((id) => offeredIds.has(id))
+ : [];
+ let skillResult: { ok: true } | { ok: false; error: string };
+ try {
+ skillResult = await skills.applyConsent(enabledIds);
+ } catch (err) {
+ skillResult = { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+ if (!skillResult.ok) {
+ logger.event({ event: 'mcp-wiring-skill-consent-failed', error: skillResult.error });
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:mcp-wiring:confirm',
+ reason: 'skill-consent-failed',
+ handler: 'mcpWiringConfirm',
+ cause: { error: skillResult.error },
+ });
+ handled = false;
+ return {
+ ok: false,
+ error: `Couldn't apply your skill choices (${skillResult.error}). The dialog will reappear on next launch so you can retry.`,
+ };
+ }
+ // Bounded per-bundle consent telemetry (bundle is a closed enum id).
+ for (const d of skillDescriptors) {
+ logger.event({
+ event: enabledIds.includes(d.id)
+ ? 'mcp-wiring-skill-consent-granted'
+ : 'mcp-wiring-skill-consent-declined',
+ bundle: d.id,
+ });
+ }
+ logger.info('skill consent applied', { enabled: enabledIds });
+ }
+
// Only editors we actually wired count as configured — a declined write
// touched nothing, so recording it here would falsely claim it's set up.
const configuredEditors = results
@@ -1031,6 +1114,7 @@ export function runMcpWiringOnFirstLaunch(opts: RunMcpWiringFirstLaunchOpts): Ru
sendToRenderer(target, 'ok:mcp-wiring:show', {
detectedEditors: detections,
pathInstall: pathDescriptor,
+ globalSkills: skillDescriptors,
});
logger.info('dispatched show to renderer', {
detectedCount: detections.length,
diff --git a/packages/desktop/src/main/skill-reclaim.test.ts b/packages/desktop/src/main/skill-reclaim.test.ts
index 17f865860..0722e82ee 100644
--- a/packages/desktop/src/main/skill-reclaim.test.ts
+++ b/packages/desktop/src/main/skill-reclaim.test.ts
@@ -89,9 +89,16 @@ interface FakeDeps {
version?: string;
reason?: string;
}): Promise<void>;
+ readBundleDecision(home: string, bundleName: string): Promise<boolean | null>;
+ writeBundleDecision(home: string, bundleName: string, enabled: boolean): Promise<void>;
+ removeBundleFromDisk(bundleId: string): void;
/** Captured state for assertions. */
stateWrites: Array<{ home: string; version: string }>;
events: CapturedEvent[];
+ /** Captured per-bundle decisions written (grandfather materialization). */
+ decisionWrites: Array<{ bundleName: string; enabled: boolean }>;
+ /** Captured bundle ids removed on decline. */
+ removals: string[];
}
/** Default test bundle set — discovery only, so existing single-bundle
@@ -106,9 +113,21 @@ function makeDeps(opts: {
/** Inject a throw into the writeTargetVersion mock — exercises the
* state-write-failure → outcome:'failed' regression guard. */
stateWriteThrows?: Error;
+ /** Per-bundle opt-in decision the gate reads. Default `true` (consented) so
+ * existing install-assertion tests hold; `null` grandfathers to disk;
+ * `false` declines. A map keys by bundle NAME for multi-bundle tests. */
+ bundleDecision?: boolean | null | Record<string, boolean | null>;
}): FakeDeps {
const stateWrites: Array<{ home: string; version: string }> = [];
const events: CapturedEvent[] = [];
+ const decisionWrites: Array<{ bundleName: string; enabled: boolean }> = [];
+ const removals: string[] = [];
+ const decisionFor = (bundleName: string): boolean | null => {
+ const d = opts.bundleDecision;
+ if (d === undefined) return true;
+ if (typeof d === 'object' && d !== null) return d[bundleName] ?? null;
+ return d;
+ };
return {
userGlobalBundles: DISCOVERY_ONLY_BUNDLES,
resolveBundledSkillDir: () => {
@@ -132,8 +151,17 @@ function makeDeps(opts: {
reason: event.reason,
});
},
+ readBundleDecision: async (_home, bundleName) => decisionFor(bundleName),
+ writeBundleDecision: async (_home, bundleName, enabled) => {
+ decisionWrites.push({ bundleName, enabled });
+ },
+ removeBundleFromDisk: (bundleId) => {
+ removals.push(bundleId);
+ },
stateWrites,
events,
+ decisionWrites,
+ removals,
};
}
@@ -440,6 +468,106 @@ describe('reclaimUserSkillsOnLaunch', () => {
});
});
+describe('reclaimUserSkillsOnLaunch — per-bundle opt-in gate', () => {
+ const DISCOVERY_DIR = ['.agents', 'skills', 'open-knowledge-discovery'] as const;
+
+ function seedCentral(home: string): void {
+ const dir = join(home, ...DISCOVERY_DIR);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), 'preexisting');
+ }
+
+ test('FR1: fresh machine (no decision, nothing on disk) installs nothing', async () => {
+ const home = makeHome();
+ const deps = makeDeps({ bundle: setupBundle(), bundleDecision: null });
+ const r = await reclaimUserSkillsOnLaunch({
+ home,
+ isPackaged: true,
+ platform: 'darwin',
+ executablePath: EXE,
+ deps,
+ });
+ expect(r.status).toBe('skipped');
+ if (r.status === 'skipped') expect(r.reason).toBe('all-bundles-declined');
+ expect(existsSync(join(home, ...DISCOVERY_DIR, 'SKILL.md'))).toBe(false);
+ expect(deps.events.some((e) => e.outcome === 'installed')).toBe(false);
+ });
+
+ test('D3b: declining an installed bundle removes it and does not re-install', async () => {
+ const home = makeHome();
+ seedCentral(home);
+ const deps = makeDeps({ bundle: setupBundle(), bundleDecision: false });
+ const r = await reclaimUserSkillsOnLaunch({
+ home,
+ isPackaged: true,
+ platform: 'darwin',
+ executablePath: EXE,
+ deps,
+ });
+ expect(r.status).toBe('skipped');
+ if (r.status === 'skipped') expect(r.reason).toBe('all-bundles-declined');
+ expect(deps.removals).toEqual(['discovery']);
+ // No install event for the declined bundle.
+ expect(deps.events.some((e) => e.outcome === 'installed')).toBe(false);
+ });
+
+ test('FR4: grandfather — installed with no decision is kept + records enabled', async () => {
+ const home = makeHome();
+ seedCentral(home);
+ const deps = makeDeps({ bundle: setupBundle(), version: '1.0.0', bundleDecision: null });
+ const r = await reclaimUserSkillsOnLaunch({
+ home,
+ isPackaged: true,
+ platform: 'darwin',
+ executablePath: EXE,
+ deps,
+ });
+ expect(r.status).toBe('done');
+ // Force-written (grandfathered install stays) + decision materialized.
+ expect(existsSync(join(home, ...DISCOVERY_DIR, 'SKILL.md'))).toBe(true);
+ expect(deps.decisionWrites).toEqual([
+ { bundleName: 'open-knowledge-discovery', enabled: true },
+ ]);
+ expect(deps.removals).toEqual([]);
+ });
+
+ test('mixed decision: declined bundle is removed while the enabled bundle installs', async () => {
+ const home = makeHome();
+ // Seed both bundles on disk, then decline ONLY write-skill.
+ for (const name of ['open-knowledge-discovery', 'open-knowledge-write-skill']) {
+ const dir = join(home, '.agents', 'skills', name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'SKILL.md'), 'preexisting');
+ }
+ const deps = {
+ ...makeDeps({
+ bundle: setupBundle(),
+ version: '1.0.0',
+ bundleDecision: {
+ 'open-knowledge-discovery': true,
+ 'open-knowledge-write-skill': false,
+ },
+ }),
+ userGlobalBundles: [
+ { id: 'discovery', name: 'open-knowledge-discovery' },
+ { id: 'write-skill', name: 'open-knowledge-write-skill' },
+ ],
+ };
+ const r = await reclaimUserSkillsOnLaunch({
+ home,
+ isPackaged: true,
+ platform: 'darwin',
+ executablePath: EXE,
+ deps,
+ });
+ expect(r.status).toBe('done');
+ // write-skill torn down; discovery installed (its central write landed).
+ expect(deps.removals).toEqual(['write-skill']);
+ const installed = deps.events.filter((e) => e.outcome === 'installed').map((e) => e.bundle);
+ expect(installed).toEqual(['discovery']);
+ });
+});
+
describe('reclaimProjectSkillsOnProjectOpen', () => {
test('skipped on non-darwin', async () => {
const projectDir = mkdtempSync(join(tmpdir(), 'ok-proj-'));
diff --git a/packages/desktop/src/main/skill-reclaim.ts b/packages/desktop/src/main/skill-reclaim.ts
index 3c63b0737..3c6058432 100644
--- a/packages/desktop/src/main/skill-reclaim.ts
+++ b/packages/desktop/src/main/skill-reclaim.ts
@@ -57,6 +57,7 @@ import {
EDITOR_TARGETS,
HOSTS_WITH_USER_SKILL_DIR,
} from '@inkeep/open-knowledge';
+import { resolveBundleEnabled } from '@inkeep/open-knowledge-core';
interface SkillReclaimLogger {
event(payload: { event: string; [key: string]: unknown }): void;
@@ -246,6 +247,16 @@ interface ReclaimUserSkillsOpts {
userGlobalBundles: ReadonlyArray<{ id: string; name: string }>;
resolveBundledSkillDir(bundle: string): string;
readServerPackageVersion(): Promise<string>;
+ /** Per-bundle opt-in gate (server `readBundleDecision`): explicit
+ * recorded enablement, or null when unrecorded. Injected so this module
+ * stays free of server imports. */
+ readBundleDecision(home: string, bundleName: string): Promise<boolean | null>;
+ /** Materialize a grandfathered install's decision (server
+ * `writeBundleDecision`) so later actors agree it's opted in. */
+ writeBundleDecision(home: string, bundleName: string, enabled: boolean): Promise<void>;
+ /** Remove a declined bundle's dirs from disk (CLI
+ * `removeUserGlobalSkillBundle`). Keyed by bundle id. */
+ removeBundleFromDisk(bundleId: string): void;
writeTargetVersion(
home: string,
target: 'cli-hosts',
@@ -448,10 +459,57 @@ export async function reclaimUserSkillsOnLaunch(
// `open-knowledge-discovery` bundle lands. Fail-soft.
removeLegacyUserSkillDirs(home, fs, logger);
- // Force-install each resolved user-global bundle (discovery + write-skill)
+ // Per-bundle opt-in gate. Explicit decline (`enabled: false`) is removed and
+ // never re-installed; an unrecorded bundle grandfathers to disk presence
+ // (existing install stays + records the decision, a truly-fresh machine
+ // stays uninstalled until the first-launch dialog records consent). This is
+ // the launch-side half of the cross-actor invariant — the CLI sweep applies
+ // the identical gate.
+ const gatedBundles: typeof resolvedBundles = [];
+ for (const bundle of resolvedBundles) {
+ const onDisk = fs.existsSync(join(home, '.agents', 'skills', bundle.name));
+ const decision = await deps.readBundleDecision(home, bundle.name).catch(() => null);
+ if (!resolveBundleEnabled(decision, { installedOnDisk: onDisk })) {
+ if (onDisk) {
+ try {
+ deps.removeBundleFromDisk(bundle.id);
+ logger.event({ event: 'user-skill-reclaim-bundle-declined-removed', bundle: bundle.id });
+ } catch (err) {
+ logger.event({
+ event: 'user-skill-reclaim-bundle-remove-failed',
+ bundle: bundle.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ continue;
+ }
+ if (decision === null && onDisk) {
+ // Grandfather: record so later actors don't treat it as fresh. Fail-soft
+ // (the bundle stays installed regardless), but log so a persistently
+ // unwritable state file — which re-enters this path every launch —
+ // leaves a trail instead of retrying invisibly forever.
+ try {
+ await deps.writeBundleDecision(home, bundle.name, true);
+ } catch (err) {
+ logger.event({
+ event: 'user-skill-reclaim-grandfather-write-failed',
+ bundle: bundle.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ gatedBundles.push(bundle);
+ }
+
+ if (gatedBundles.length === 0) {
+ return { status: 'skipped', reason: 'all-bundles-declined' };
+ }
+
+ // Force-install each enabled user-global bundle (discovery + write-skill)
// into the central store + per-host dirs, each under its own name.
const entries: UserSkillReclaimEntry[] = [];
- for (const bundle of resolvedBundles) {
+ for (const bundle of gatedBundles) {
entries.push(
...installUserBundleToHostDirs(home, bundle.name, bundle.sourceDir, fs, logger, version),
);
@@ -477,7 +535,7 @@ export async function reclaimUserSkillsOnLaunch(
// state file disagrees) would mislead operators chasing a "did the
// skill update?" question.
// One outcome event per installed bundle, gated on the state-file write.
- for (const bundle of resolvedBundles) {
+ for (const bundle of gatedBundles) {
await deps
.recordSkillInstallEvent({
ts: nowDate().toISOString(),
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index 4c386c5c9..ab2aae52b 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -495,6 +495,7 @@ const bridge: OkDesktopBridge = {
invoke('ok:mcp-wiring:confirm', {
editorIds: request.editorIds,
pathInstall: request.pathInstall,
+ skills: request.skills,
}),
skip: () => invoke('ok:mcp-wiring:skip'),
},
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index 20a80c1f8..ae2ed3c4d 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -386,15 +386,27 @@ export interface OkMcpWiringShowPayload {
readonly rcFilesToTouch: readonly string[];
readonly alreadyInstalled: boolean;
};
+ /** Per-bundle opt-in rows for the two user-global skills. Empty ⇒ no skill
+ * decision solicited. `alreadyInstalled: true` renders the row pre-checked
+ * as an existing install the user can uncheck to remove. */
+ readonly globalSkills: readonly {
+ readonly id: string;
+ readonly name: string;
+ readonly alreadyInstalled: boolean;
+ }[];
}
/** Confirm payload for `mcpWiring.confirm`. `pathInstall` is the PATH
* toggle, tri-state: `true` → append the managed rc block; `false` →
* record declined, touch nothing; absent → no PATH decision was solicited
- * (row hidden or informational). */
+ * (row hidden or informational).
+ *
+ * `skills` — bundle ids the user left checked. Present ⇒ a skill decision was
+ * solicited; every offered bundle not in the list is recorded declined. */
export interface OkMcpWiringConfirmRequest {
readonly editorIds: readonly OkMcpWiringEditorId[];
readonly pathInstall?: boolean;
+ readonly skills?: readonly string[];
}
/** Result shape for `mcpWiring.confirm` / `skip`. */
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index df6b71d0c..b11b323ed 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -388,6 +388,20 @@ export interface McpWiringPathInstallDescriptor {
export interface McpWiringConfirmRequest {
readonly editorIds: readonly McpWiringEditorId[];
readonly pathInstall?: boolean;
+ /** Bundle ids the user left checked. Present ⇒ a skill decision was
+ * solicited; every offered bundle not listed is recorded declined (and
+ * removed if already installed). */
+ readonly skills?: readonly string[];
+}
+
+/** One user-global skill row in the first-launch consent dialog. Computed
+ * read-only at arming time from `USER_GLOBAL_BUNDLE_IDS` + disk/marker state.
+ * `alreadyInstalled: true` renders the row pre-checked as an existing install
+ * the user can uncheck to remove. */
+export interface McpWiringGlobalSkillDescriptor {
+ readonly id: string;
+ readonly name: string;
+ readonly alreadyInstalled: boolean;
}
/** Confirm / skip response shape. `ok:false` surfaces when (a)
diff --git a/packages/desktop/src/shared/ipc-events.ts b/packages/desktop/src/shared/ipc-events.ts
index 4592eef92..3d0f729bd 100644
--- a/packages/desktop/src/shared/ipc-events.ts
+++ b/packages/desktop/src/shared/ipc-events.ts
@@ -28,6 +28,7 @@ import type {
} from './bridge-contract.ts';
import type {
McpWiringEditorDetection,
+ McpWiringGlobalSkillDescriptor,
McpWiringPathInstallDescriptor,
OnboardingShowPayload,
} from './ipc-channels.ts';
@@ -152,6 +153,7 @@ export interface EventChannels {
payload: {
detectedEditors: readonly McpWiringEditorDetection[];
pathInstall: McpWiringPathInstallDescriptor;
+ globalSkills: readonly McpWiringGlobalSkillDescriptor[];
};
};
/**
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index c2d2cb053..8c24f6d78 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -492,14 +492,17 @@ export {
} from './skill-management.ts';
export {
readAllTargets,
+ readBundleDecision,
readServerPackageVersion,
readSkillInstallStateSnapshot,
readTargetRecordedAt,
readTargetVersion,
+ resolveBundleEnabled,
SKILL_STATE_TARGETS,
type SkillInstallStateSnapshot,
type SkillStateLogger,
type SkillStateTarget,
+ writeBundleDecision,
writeTargetVersion,
} from './skill-state.ts';
export {
diff --git a/packages/server/src/skill-install.test.ts b/packages/server/src/skill-install.test.ts
index ff1afbfe1..915c68827 100644
--- a/packages/server/src/skill-install.test.ts
+++ b/packages/server/src/skill-install.test.ts
@@ -364,6 +364,20 @@ describe('installUserSkill — idempotency (skip-current)', () => {
expect(readSidecarIfExists(home)).toBe(`${currentVersion}\n`);
});
+ test('force bypasses the skip-current gate → subprocess IS invoked even when the version matches', async () => {
+ const home = freshHome();
+ writeSidecar(home, `${currentVersion}\n`);
+ writeCentralSkill(home);
+ const { spawn, calls } = makeSpawnFake({ outcome: { kind: 'exit', code: 0 } });
+
+ // `ok init` passes force so one bundle's shared-key version write can't
+ // freeze another bundle's content on an upgrade-then-reinit.
+ const result = await installUserSkill({ home, spawn, force: true });
+
+ expect(result).toBe('installed');
+ expect(calls.length).toBe(1);
+ });
+
test('sidecar without trailing newline still matches (tolerant parse)', async () => {
const home = freshHome();
writeSidecar(home, currentVersion);
diff --git a/packages/server/src/skill-install.ts b/packages/server/src/skill-install.ts
index 84a5d023b..723775c1f 100644
--- a/packages/server/src/skill-install.ts
+++ b/packages/server/src/skill-install.ts
@@ -8,6 +8,7 @@ import {
resolveBundledSkillDir,
} from './build-skill-zip.ts';
import { tracedMkdir } from './fs-traced.ts';
+import { BUNDLE_SKILL_NAME, type BundleId } from './skill-bundles.ts';
import { recordSkillInstallEvent, type SkillInstallEventOutcome } from './skill-install-events.ts';
import {
readServerPackageVersion,
@@ -74,23 +75,27 @@ export interface InstallUserSkillOptions {
* a real Windows host.
*/
platform?: NodeJS.Platform;
+ /**
+ * Which user-global bundle to install. Defaults to `'discovery'` so existing
+ * callers (and the `ok init` discovery leg) are unchanged; `ok init` calls
+ * once per enabled bundle. The central-dir gate + resolve key off
+ * `BUNDLE_SKILL_NAME[bundleId]`.
+ */
+ bundleId?: BundleId;
+ /**
+ * Bypass the version fast-path and always run the install. `ok init` sets
+ * this because it loops `installUserSkill` once per bundle over the SHARED
+ * `cli-hosts` version key: the first bundle's version write would otherwise
+ * satisfy the second bundle's `skip-current` gate, freezing the second
+ * bundle's content at its stale on-disk version on an upgrade-then-reinit.
+ * `ok init` is explicit and infrequent, so always installing is cheap and
+ * correct. The background sweep keeps its own batch-level fast-path.
+ */
+ force?: boolean;
}
export type InstallUserSkillResult = 'installed' | 'skip-current' | 'failed';
-/**
- * Central source directory the `skills` CLI writes when invoked with
- * `add … -g --copy`. The skip-current gate verifies this exists alongside the
- * sidecar version match — sidecar presence alone is not proof the skill is
- * still on disk (e.g. after a manual `npx skills remove -g`).
- *
- * Probes the SLIM `discovery` bundle's install dir, NOT the pre-split
- * `open-knowledge` dir: the user-global path installs discovery-only, and the
- * legacy `open-knowledge` dir is explicitly removed on migration — probing it
- * would wedge the gate permanently.
- */
-const CENTRAL_SKILL_DIR_REL = ['.agents', 'skills', 'open-knowledge-discovery'] as const;
-
/**
* Pre-split user-global skill name. The legacy migration removes any install
* under this name before the new `discovery` bundle lands. Sibling constant:
@@ -111,13 +116,13 @@ const SKILLS_CLI_SPEC = 'skills@~1.5.0';
/** Subprocess timeout default. */
const DEFAULT_TIMEOUT_MS = 60_000;
-function centralSkillDir(home: string): string {
- return join(home, ...CENTRAL_SKILL_DIR_REL);
+function centralSkillDir(home: string, bundleName: string): string {
+ return join(home, '.agents', 'skills', bundleName);
}
-async function centralSkillExists(home: string): Promise<boolean> {
+async function centralSkillExists(home: string, bundleName: string): Promise<boolean> {
try {
- const info = await stat(centralSkillDir(home));
+ const info = await stat(centralSkillDir(home, bundleName));
return info.isDirectory();
} catch {
return false;
@@ -288,6 +293,8 @@ export async function installUserSkill(
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const surfaceAttribution: SkillStateSurface = opts.surface ?? 'cli-npx-skills-add';
const platform = opts.platform ?? process.platform;
+ const bundleId = opts.bundleId ?? 'discovery';
+ const bundleName = BUNDLE_SKILL_NAME[bundleId];
const report = async (
outcome: SkillInstallEventOutcome,
@@ -299,7 +306,7 @@ export async function installUserSkill(
ts: new Date().toISOString(),
surface: surfaceAttribution,
target: 'cli-hosts',
- bundle: 'discovery',
+ bundle: bundleId,
outcome,
...(version !== undefined ? { version } : {}),
...(reason !== undefined ? { reason } : {}),
@@ -331,8 +338,8 @@ export async function installUserSkill(
);
return null;
});
- if (existingVersion !== null && existingVersion === currentVersion) {
- if (await centralSkillExists(home)) {
+ if (!opts.force && existingVersion !== null && existingVersion === currentVersion) {
+ if (await centralSkillExists(home, bundleName)) {
logger.info?.(
{ event: 'skill-install.skip-current', version: currentVersion },
'OpenKnowledge skill already installed at current version; skipping.',
@@ -344,17 +351,17 @@ export async function installUserSkill(
{
event: 'skill-install.reinstall-missing',
version: currentVersion,
- path: centralSkillDir(home),
+ path: centralSkillDir(home, bundleName),
},
'Sidecar matches current version but skill files are missing; reinstalling.',
);
}
- let discoveryDir: string;
+ let bundleDir: string;
try {
// checkDesktop:false — the user-global install never auto-points at a
- // co-installed OK Desktop's discovery bundle.
- discoveryDir = resolveBundledSkillDir('discovery', { checkDesktop: false });
+ // co-installed OK Desktop's bundle.
+ bundleDir = resolveBundledSkillDir(bundleId, { checkDesktop: false });
} catch (err) {
logger.warn(
{
@@ -362,7 +369,7 @@ export async function installUserSkill(
reason: 'bundled-asset-missing',
error: String(err),
},
- 'Skill install aborted — bundled discovery SKILL.md asset not found.',
+ 'Skill install aborted — bundled SKILL.md asset not found.',
);
await report('failed', currentVersion, 'bundled-asset-missing');
return 'failed';
@@ -373,8 +380,8 @@ export async function installUserSkill(
// fresh machine). Fail-soft — the `add` below is what the install gates on.
await removeLegacyUserSkill(home, spawnFn, env, timeoutMs, logger, platform);
- // Install the slim `discovery` bundle to every detected agent host.
- const args = ['-y', SKILLS_CLI_SPEC, 'add', discoveryDir, '--agent', '*', '-g', '-y', '--copy'];
+ // Install the bundle to every detected agent host.
+ const args = ['-y', SKILLS_CLI_SPEC, 'add', bundleDir, '--agent', '*', '-g', '-y', '--copy'];
const outcome = await runSpawn(spawnFn, 'npx', args, env, timeoutMs, platform);
if (outcome.kind === 'ok') {
@@ -400,7 +407,7 @@ export async function installUserSkill(
logger.warn(
{ event: 'skill-install.failed', reason: 'timeout', timeoutMs, stderr: outcome.stderr },
'Skill install subprocess timed out. Run manually: npx ' +
- `${SKILLS_CLI_SPEC} add ${discoveryDir} --agent '*' -g -y --copy`,
+ `${SKILLS_CLI_SPEC} add ${bundleDir} --agent '*' -g -y --copy`,
);
await report('failed', currentVersion, 'timeout');
return 'failed';
@@ -415,7 +422,7 @@ export async function installUserSkill(
stderr: outcome.stderr,
},
'Skill install failed — `npx` unavailable or spawn errored. Run manually: npx ' +
- `${SKILLS_CLI_SPEC} add ${discoveryDir} --agent '*' -g -y --copy`,
+ `${SKILLS_CLI_SPEC} add ${bundleDir} --agent '*' -g -y --copy`,
);
await report('failed', currentVersion, 'spawn-error');
return 'failed';
@@ -430,7 +437,7 @@ export async function installUserSkill(
stderr: outcome.stderr,
},
'Skill install subprocess exited non-zero. Run manually: npx ' +
- `${SKILLS_CLI_SPEC} add ${discoveryDir} --agent '*' -g -y --copy`,
+ `${SKILLS_CLI_SPEC} add ${bundleDir} --agent '*' -g -y --copy`,
);
await report('failed', currentVersion, `nonzero-exit:${outcome.exitCode ?? 'unknown'}`);
return 'failed';
diff --git a/packages/server/src/skill-state.test.ts b/packages/server/src/skill-state.test.ts
index e7f0bffdb..95f6e8e16 100644
--- a/packages/server/src/skill-state.test.ts
+++ b/packages/server/src/skill-state.test.ts
@@ -16,11 +16,14 @@ import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
readAllTargets,
+ readBundleDecision,
readServerPackageVersion,
readSkillInstallStateSnapshot,
readTargetRecordedAt,
readTargetVersion,
+ resolveBundleEnabled,
skillStateYamlPath,
+ writeBundleDecision,
writeTargetVersion,
} from './skill-state.ts';
@@ -28,6 +31,42 @@ function freshHome(): string {
return mkdtempSync(join(tmpdir(), 'ok-skill-state-'));
}
+describe('per-bundle opt-in decisions', () => {
+ test('resolveBundleEnabled: explicit decision wins; absent grandfathers to disk', () => {
+ // Fresh machine (no decision, nothing on disk) — stays uninstalled.
+ expect(resolveBundleEnabled(null, { installedOnDisk: false })).toBe(false);
+ // Grandfather: existing install with no recorded decision — enabled.
+ expect(resolveBundleEnabled(null, { installedOnDisk: true })).toBe(true);
+ // Explicit decisions override disk state either way.
+ expect(resolveBundleEnabled(true, { installedOnDisk: false })).toBe(true);
+ expect(resolveBundleEnabled(false, { installedOnDisk: true })).toBe(false);
+ });
+
+ test('readBundleDecision returns null when the file / entry is absent', async () => {
+ const home = freshHome();
+ expect(await readBundleDecision(home, 'open-knowledge-discovery')).toBeNull();
+ });
+
+ test('writeBundleDecision round-trips and preserves other bundles + targets', async () => {
+ const home = freshHome();
+ // Seed an unrelated target so we can assert it survives the RMW.
+ await writeTargetVersion(home, 'cli-hosts', '1.2.3', 'cli-start');
+
+ await writeBundleDecision(home, 'open-knowledge-discovery', true);
+ await writeBundleDecision(home, 'open-knowledge-write-skill', false);
+
+ expect(await readBundleDecision(home, 'open-knowledge-discovery')).toBe(true);
+ expect(await readBundleDecision(home, 'open-knowledge-write-skill')).toBe(false);
+ // The version target is untouched by bundle writes.
+ expect(await readTargetVersion(home, 'cli-hosts')).toBe('1.2.3');
+
+ // A later flip of one bundle leaves the other intact.
+ await writeBundleDecision(home, 'open-knowledge-discovery', false);
+ expect(await readBundleDecision(home, 'open-knowledge-discovery')).toBe(false);
+ expect(await readBundleDecision(home, 'open-knowledge-write-skill')).toBe(false);
+ });
+});
+
describe('readServerPackageVersion', () => {
test('reads the version field from `@inkeep/open-knowledge-server`/package.json', async () => {
const version = await readServerPackageVersion();
diff --git a/packages/server/src/skill-state.ts b/packages/server/src/skill-state.ts
index 98115994c..1565b6812 100644
--- a/packages/server/src/skill-state.ts
+++ b/packages/server/src/skill-state.ts
@@ -42,7 +42,7 @@ import {
type SkillStateSurface,
type SkillStateTarget,
} from '@inkeep/open-knowledge-core';
-import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';
+import { atomicWriteFile, withFileLock } from '@inkeep/open-knowledge-core/server';
import { type ParsedNode, parseDocument } from 'yaml';
import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';
@@ -51,6 +51,7 @@ const readFileAsync = promisify(readFile);
// Re-exports for downstream callers (HTTP handlers, MCP tools, CLI):
// keep importing from this module rather than core for a stable surface.
export {
+ resolveBundleEnabled,
SKILL_STATE_TARGETS,
type SkillStateSurface,
type SkillStateTarget,
@@ -61,6 +62,30 @@ export function skillStateYamlPath(home: string): string {
return join(home, ...SKILL_STATE_REL);
}
+/**
+ * Serialize a read-modify-write against `skill-state.yml`. Every writer
+ * (`writeBundleDecision`, `writeTargetVersion`) full-file RMWs the same file,
+ * and at desktop launch a fire-and-forget reclaim grandfather-write can race
+ * the dialog's consent decision on the same path. The advisory lock turns
+ * "last writer wins" into "writers serialize", so a grandfather write can't
+ * clobber a freshly-recorded decline. Fail-soft: on lock-acquire timeout,
+ * fall through and write anyway (degrading to the prior last-writer-wins
+ * behavior) rather than dropping the write.
+ */
+async function withSkillStateWriteLock<T>(home: string, fn: () => Promise<T>): Promise<T> {
+ const path = skillStateYamlPath(home);
+ // The lockfile lives beside skill-state.yml; create `~/.ok/` first (the
+ // writer would otherwise be the one to mkdir it, but that runs inside the
+ // lock, so the lockfile's openSync would ENOENT on a fresh home).
+ await tracedMkdir(dirname(path), { recursive: true });
+ try {
+ return await withFileLock(`${path}.lock`, fn);
+ } catch (err) {
+ if ((err as { code?: string }).code === 'LOCK_TIMEOUT') return fn();
+ throw err;
+ }
+}
+
/**
* Minimal logger duck-type. Compatible with `PinoLogger` (`warn(data, msg)`)
* and ad-hoc shims.
@@ -242,29 +267,79 @@ export async function writeTargetVersion(
throw new Error(`Refusing to write invalid version string: ${version}`);
}
- // Read existing or start fresh. A fresh document is generated when the
- // file is absent or unreadable — same fail-soft contract as readers.
- const existing = (await readSkillStateFile(home, logger)) ?? emptySkillState();
- const recordedAt = new Date().toISOString();
-
- // Preserve existing surface when caller doesn't pass one.
- const previousEntry = existing.targets[target];
- const nextSurface = surface !== undefined ? surface : (previousEntry?.surface ?? undefined);
-
- const entry =
- nextSurface !== undefined
- ? { version, recordedAt, surface: nextSurface }
- : { version, recordedAt };
-
- const next: SkillState = {
- ...existing,
- targets: {
- ...existing.targets,
- [target]: entry,
- },
- };
-
- await writeSkillStateFile(home, next);
+ await withSkillStateWriteLock(home, async () => {
+ // Read existing or start fresh. A fresh document is generated when the
+ // file is absent or unreadable — same fail-soft contract as readers.
+ const existing = (await readSkillStateFile(home, logger)) ?? emptySkillState();
+ const recordedAt = new Date().toISOString();
+
+ // Preserve existing surface when caller doesn't pass one.
+ const previousEntry = existing.targets[target];
+ const nextSurface = surface !== undefined ? surface : (previousEntry?.surface ?? undefined);
+
+ const entry =
+ nextSurface !== undefined
+ ? { version, recordedAt, surface: nextSurface }
+ : { version, recordedAt };
+
+ const next: SkillState = {
+ ...existing,
+ targets: {
+ ...existing.targets,
+ [target]: entry,
+ },
+ };
+
+ await writeSkillStateFile(home, next);
+ });
+}
+
+// ─── Per-bundle opt-in decisions ───────────────────────────────────────────
+//
+// The two user-global bundles (`open-knowledge-discovery`,
+// `open-knowledge-write-skill`) are opt-out-able via the first-launch consent
+// dialog and `ok init --skills`. The decision lives under the top-level
+// `bundles` map keyed by install NAME, separate from the version-keyed
+// `targets`. Every install actor (desktop reclaim, CLI sweep, `ok init`,
+// dialog confirm) reads `resolveBundleEnabled` (re-exported from core above)
+// so a declined bundle is never re-installed.
+
+/**
+ * Read the recorded opt-in decision for a bundle (by install name). Returns
+ * `null` when the file is absent, unreadable, or carries no entry for this
+ * bundle — the caller applies `resolveBundleEnabled` grandfathering.
+ */
+export async function readBundleDecision(
+ home: string,
+ bundleName: string,
+ logger?: SkillStateLogger,
+): Promise<boolean | null> {
+ const state = await readSkillStateFile(home, logger).catch(() => null);
+ const entry = state?.bundles?.[bundleName];
+ return typeof entry?.enabled === 'boolean' ? entry.enabled : null;
+}
+
+/**
+ * Record an opt-in decision for a bundle. Atomic RMW that preserves `targets`
+ * and any other bundles' decisions; stamps `decidedAt` to now.
+ */
+export async function writeBundleDecision(
+ home: string,
+ bundleName: string,
+ enabled: boolean,
+ logger?: SkillStateLogger,
+): Promise<void> {
+ await withSkillStateWriteLock(home, async () => {
+ const existing = (await readSkillStateFile(home, logger)) ?? emptySkillState();
+ const next: SkillState = {
+ ...existing,
+ bundles: {
+ ...existing.bundles,
+ [bundleName]: { enabled, decidedAt: new Date().toISOString() },
+ },
+ };
+ await writeSkillStateFile(home, next);
+ });
}
/**