mdedit-cli 0.3.5 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -149,26 +149,32 @@ The CLI is designed to be used by AI agents without modification.
149
149
  - Use `--yes` on destructive commands to skip confirmation
150
150
  - Pipe content via `--file -` (stdin) or `--content-only` (stdout)
151
151
 
152
- ### Skill file
152
+ ### Agent skills
153
153
 
154
- A comprehensive agent skill document is included with the CLI. It covers all commands, flags, workflows, and error handling in a format optimised for AI agents (Claude Code, Cursor, GitHub Copilot, etc.).
154
+ The canonical Save, Find, Revise, Review, and Publish skills are bundled in focused CLI-backed and MCP-backed variants.
155
155
 
156
156
  ```bash
157
- # View the skill
158
- mdedit skill show
157
+ # List and inspect skills
158
+ mdedit skill list
159
+ mdedit skill show save-mdedit-document --via cli
160
+ mdedit skill show revise-mdedit-document --via mcp
159
161
 
160
- # Install the skill into all detected agent config files
162
+ # Install all five CLI-backed skills for the current project
161
163
  mdedit skill install
162
164
 
163
- # Install into a specific tool only
164
- mdedit skill install --target claude # → CLAUDE.md
165
- mdedit skill install --target cursor # → .cursor/rules/mdedit.mdc
166
- mdedit skill install --target codex # → .github/copilot-instructions.md
165
+ # Select a host-native directory or MCP-backed variant
166
+ mdedit skill install --target claude --via mcp
167
+ mdedit skill install --target cursor
168
+ mdedit skill install publish-mdedit-document --target gemini --via mcp
167
169
 
168
- # Install to home-directory (global) targets
169
- mdedit skill install --global
170
+ # User scope, diagnostics, and safe removal
171
+ mdedit skill install --scope user
172
+ mdedit skill doctor
173
+ mdedit skill uninstall save-mdedit-document
170
174
  ```
171
175
 
176
+ Project scope is the default. Installations carry mdedit ownership and content checksums: edited or unowned skills are not overwritten without `--force`, and uninstall removes only unchanged mdedit-owned artifacts. `doctor` reports legacy monolithic `CLAUDE.md`, Cursor rule, and Copilot instruction installs without modifying them.
177
+
172
178
  ### OpenClaw plugin
173
179
 
174
180
  An `openclaw.json` plugin manifest is included in the package. It defines every CLI tool as a structured, machine-readable entry that OpenClaw-compatible agents can load directly.
package/dist/index.js CHANGED
@@ -50,6 +50,30 @@ function getDefaultFetchers() {
50
50
  "MDEdit API client is not initialized. Call initApiClient(config) at app bootstrap (e.g. pages/_app.jsx) before using API functions."
51
51
  );
52
52
  }
53
+ async function buildApiError(resp) {
54
+ let data = void 0;
55
+ try {
56
+ data = await resp.clone().json();
57
+ } catch {
58
+ }
59
+ let text = "";
60
+ if (!data) {
61
+ try {
62
+ text = await resp.text();
63
+ } catch {
64
+ text = "";
65
+ }
66
+ }
67
+ const messageFromJson = data?.error?.message || data?.message || (typeof data?.error === "string" ? data.error : "");
68
+ const message = messageFromJson || text || `Request failed (${resp.status})`;
69
+ return new ApiError(resp.status, message, data);
70
+ }
71
+ async function getToolJobStatus(jobId, fetchers) {
72
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
73
+ const resp = await fetchV2(`/tools/jobs/${encodeURIComponent(jobId)}`);
74
+ if (!resp.ok) throw await buildApiError(resp);
75
+ return resp.json();
76
+ }
53
77
  async function fetchErrorFromResponse(prefix, response) {
54
78
  const text = await response.text();
55
79
  let data;
@@ -109,7 +133,29 @@ function createSdkClient(config) {
109
133
  await withFetchError(() => deleteArticle(workspaceId, articleId, fetchers));
110
134
  },
111
135
  saveContent: (workspaceId, articleId, content, options) => withFetchError(() => saveArticleContent(workspaceId, articleId, content, options, fetchers)),
112
- exportZip: (workspaceId, articleId) => withFetchError(() => exportArticleZip(workspaceId, articleId, fetchers))
136
+ exportZip: (workspaceId, articleId) => withFetchError(() => exportArticleZip(workspaceId, articleId, fetchers)),
137
+ presentation: (workspaceId, articleId) => withFetchError(() => getArticlePresentation(workspaceId, articleId, fetchers)),
138
+ startExport: (workspaceId, articleId, format) => withFetchError(() => createArticleExportJob(workspaceId, articleId, format, fetchers)),
139
+ exportStatus: (jobId) => withFetchError(() => getToolJobStatus(jobId, fetchers)),
140
+ assetUrls: async (workspaceId, articleId, fileNames) => {
141
+ const result = await withFetchError(() => getArticleAssetDownloadUrls(
142
+ workspaceId,
143
+ articleId,
144
+ fileNames,
145
+ fetchers
146
+ ));
147
+ return Object.fromEntries(result.assets.map((asset) => [asset.fileName, asset.downloadUrl]));
148
+ },
149
+ mediaProxyUrls: async (workspaceId, articleId, urls) => {
150
+ const result = await withFetchError(() => getArticleMediaProxyUrls(
151
+ workspaceId,
152
+ articleId,
153
+ urls,
154
+ fetchers
155
+ ));
156
+ return Object.fromEntries(result.urls.map((item) => [item.source, item.proxyUrl]));
157
+ },
158
+ safeGists: async (workspaceId, articleId, urls) => (await withFetchError(() => getArticleSafeGists(workspaceId, articleId, urls, fetchers))).gists
113
159
  },
114
160
  collaboration: {
115
161
  checkpoint: (workspaceId, articleId) => withFetchError(() => checkpointCollaboration(workspaceId, articleId, fetchers))
@@ -122,7 +168,7 @@ function createSdkClient(config) {
122
168
  }
123
169
  };
124
170
  }
125
- var _defaultFetchers, customFetchV2, FetchError, errors_default, createArticle, updateArticle, getArticles, getArticlesByFolder, getArticle, deleteArticle, exportArticleZip, saveArticleContent, getWorkspaces, createWorkspace, updateWorkspace, deleteWorkspace, getWorkspace, normalizeTimestampMs, readFolderErrorMessage, normalizeFolder, createFolder, updateFolder, getFolders, getFolder, deleteFolder, sleep, isRetriableStatus, withRetries, listApiKeys, createApiKey, revokeApiKey, checkpointCollaboration, publishArticle, unpublishArticle, getPublishStatus, updatePublishedArticle, FetchError2;
171
+ var _defaultFetchers, customFetchV2, FetchError, errors_default, createArticle, updateArticle, getArticles, getArticlesByFolder, getArticle, getArticlePresentation, getArticleAssetDownloadUrls, getArticleMediaProxyUrls, getArticleSafeGists, deleteArticle, exportArticleZip, createArticleExportJob, ApiError, saveArticleContent, getWorkspaces, createWorkspace, updateWorkspace, deleteWorkspace, getWorkspace, normalizeTimestampMs, readFolderErrorMessage, normalizeFolder, createFolder, updateFolder, getFolders, getFolder, deleteFolder, sleep, isRetriableStatus, withRetries, listApiKeys, createApiKey, revokeApiKey, checkpointCollaboration, publishArticle, unpublishArticle, getPublishStatus, updatePublishedArticle, FetchError2;
126
172
  var init_dist = __esm({
127
173
  "../sdk/dist/index.js"() {
128
174
  "use strict";
@@ -257,6 +303,50 @@ var init_dist = __esm({
257
303
  }
258
304
  return response.json();
259
305
  };
306
+ getArticlePresentation = async (workspaceId, articleId, fetchers) => {
307
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
308
+ const response = await fetchV2(
309
+ `/workspaces/${workspaceId}/articles/${articleId}/presentation`
310
+ );
311
+ if (!response.ok) {
312
+ throw new errors_default(
313
+ `Error fetching article presentation. ${await response.text()}`,
314
+ response.status
315
+ );
316
+ }
317
+ return response.json();
318
+ };
319
+ getArticleAssetDownloadUrls = async (workspaceId, articleId, fileNames, fetchers) => {
320
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
321
+ const response = await fetchV2(
322
+ `/workspaces/${workspaceId}/articles/${articleId}/assets/download-urls`,
323
+ { method: "POST", body: JSON.stringify({ fileNames }) }
324
+ );
325
+ if (!response.ok) {
326
+ throw new errors_default(`Error resolving article assets. ${await response.text()}`, response.status);
327
+ }
328
+ return response.json();
329
+ };
330
+ getArticleMediaProxyUrls = async (workspaceId, articleId, urls, fetchers) => {
331
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
332
+ const response = await fetchV2(
333
+ `/workspaces/${workspaceId}/articles/${articleId}/presentation/media-urls`,
334
+ { method: "POST", body: JSON.stringify({ urls }) }
335
+ );
336
+ if (!response.ok) {
337
+ throw new errors_default(`Error resolving article media. ${await response.text()}`, response.status);
338
+ }
339
+ return response.json();
340
+ };
341
+ getArticleSafeGists = async (workspaceId, articleId, urls, fetchers) => {
342
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
343
+ const response = await fetchV2(
344
+ `/workspaces/${workspaceId}/articles/${articleId}/presentation/gists`,
345
+ { method: "POST", body: JSON.stringify({ urls }) }
346
+ );
347
+ if (!response.ok) throw new errors_default(`Error loading Gists. ${await response.text()}`, response.status);
348
+ return response.json();
349
+ };
260
350
  deleteArticle = async (workspaceId, articleId, fetchers) => {
261
351
  const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
262
352
  const response = await fetchV2(
@@ -285,6 +375,33 @@ var init_dist = __esm({
285
375
  }
286
376
  return response.blob();
287
377
  };
378
+ createArticleExportJob = async (workspaceId, articleId, format, fetchers) => {
379
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
380
+ const response = await fetchV2(
381
+ `/workspaces/${workspaceId}/articles/${articleId}/export`,
382
+ {
383
+ method: "POST",
384
+ body: JSON.stringify({ format })
385
+ }
386
+ );
387
+ if (!response.ok) {
388
+ throw new errors_default(
389
+ `Error exporting article. ${await response.text()}`,
390
+ response.status
391
+ );
392
+ }
393
+ return response.json();
394
+ };
395
+ ApiError = class extends Error {
396
+ status;
397
+ data;
398
+ constructor(status, message, data) {
399
+ super(message);
400
+ this.name = "ApiError";
401
+ this.status = status;
402
+ this.data = data;
403
+ }
404
+ };
288
405
  saveArticleContent = async (workspaceId, articleId, content, optionsOrFetchers, fetchers) => {
289
406
  const maybeFetchers = optionsOrFetchers && "customFetchV2" in optionsOrFetchers ? optionsOrFetchers : fetchers;
290
407
  const options = optionsOrFetchers && !("customFetchV2" in optionsOrFetchers) ? optionsOrFetchers : void 0;
@@ -540,7 +657,7 @@ var init_dist = __esm({
540
657
  }
541
658
  return true;
542
659
  };
543
- sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
660
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
544
661
  isRetriableStatus = (status) => status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
545
662
  withRetries = async (fn, maxAttempts = 3) => {
546
663
  let lastError;
@@ -973,8 +1090,8 @@ async function startLoopbackCallback({
973
1090
  }
974
1091
  let resolveResult;
975
1092
  let rejectResult;
976
- const result = new Promise((resolve2, reject) => {
977
- resolveResult = resolve2;
1093
+ const result = new Promise((resolve, reject) => {
1094
+ resolveResult = resolve;
978
1095
  rejectResult = reject;
979
1096
  });
980
1097
  let settled = false;
@@ -1024,7 +1141,7 @@ async function startLoopbackCallback({
1024
1141
  }
1025
1142
  finish(void 0, code);
1026
1143
  });
1027
- await new Promise((resolve2, reject) => {
1144
+ await new Promise((resolve, reject) => {
1028
1145
  server.once("error", (error) => {
1029
1146
  if (error.code === "EADDRINUSE") {
1030
1147
  reject(new OAuthClientError(
@@ -1036,7 +1153,7 @@ async function startLoopbackCallback({
1036
1153
  }
1037
1154
  reject(error);
1038
1155
  });
1039
- server.listen(port, "127.0.0.1", resolve2);
1156
+ server.listen(port, "127.0.0.1", resolve);
1040
1157
  });
1041
1158
  const address = server.address();
1042
1159
  const boundPort = typeof address === "object" && address ? address.port : port;
@@ -1052,13 +1169,13 @@ async function startLoopbackCallback({
1052
1169
  return {
1053
1170
  port: boundPort,
1054
1171
  result,
1055
- close: () => new Promise((resolve2) => {
1172
+ close: () => new Promise((resolve) => {
1056
1173
  if (timeout) clearTimeout(timeout);
1057
1174
  if (!server.listening) {
1058
- resolve2();
1175
+ resolve();
1059
1176
  return;
1060
1177
  }
1061
- server.close(() => resolve2());
1178
+ server.close(() => resolve());
1062
1179
  })
1063
1180
  };
1064
1181
  }
@@ -1770,10 +1887,10 @@ function presentArticleDetails(article) {
1770
1887
  // src/commands/article.ts
1771
1888
  async function readContentFromFile(filePath) {
1772
1889
  if (filePath === "-") {
1773
- return new Promise((resolve2, reject) => {
1890
+ return new Promise((resolve, reject) => {
1774
1891
  const chunks = [];
1775
1892
  process.stdin.on("data", (d) => chunks.push(Buffer.isBuffer(d) ? d : Buffer.from(d)));
1776
- process.stdin.on("end", () => resolve2(Buffer.concat(chunks).toString("utf-8")));
1893
+ process.stdin.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
1777
1894
  process.stdin.on("error", reject);
1778
1895
  });
1779
1896
  }
@@ -1803,23 +1920,21 @@ function requestedPublicationMode(options) {
1803
1920
  if (options.live) return "live";
1804
1921
  return void 0;
1805
1922
  }
1806
- function publishRequest(options, defaultMode) {
1923
+ function publishRequest(options, defaultModeIfUnpublished) {
1807
1924
  const seoMetadata = {
1808
1925
  ...options.seoTitle ? { title: options.seoTitle } : {},
1809
1926
  ...options.seoDescription ? { description: options.seoDescription } : {}
1810
1927
  };
1811
- const mode = requestedPublicationMode(options) ?? defaultMode;
1928
+ const mode = requestedPublicationMode(options);
1812
1929
  return {
1813
1930
  ...options.slug ? { customSlug: options.slug } : {},
1814
1931
  ...Object.keys(seoMetadata).length > 0 ? { seoMetadata } : {},
1815
- ...mode ? { mode } : {}
1932
+ ...mode ? { mode } : {},
1933
+ ...!mode && defaultModeIfUnpublished ? { defaultModeIfUnpublished } : {}
1816
1934
  };
1817
1935
  }
1818
- async function agentPublishRequest(client, workspaceId, articleId, options) {
1819
- const requestedMode = requestedPublicationMode(options);
1820
- if (requestedMode) return publishRequest(options);
1821
- const status = await client.publish.status(workspaceId, articleId);
1822
- return publishRequest(options, status.isPublished ? void 0 : "live");
1936
+ function agentPublishRequest(options) {
1937
+ return publishRequest(options, "live");
1823
1938
  }
1824
1939
  async function readEditOperations(filePath) {
1825
1940
  const raw = await readFile(filePath, "utf-8");
@@ -1958,7 +2073,7 @@ function createArticleCommands() {
1958
2073
  throw error;
1959
2074
  }
1960
2075
  }
1961
- await new Promise((resolve2) => setTimeout(resolve2, 500));
2076
+ await new Promise((resolve) => setTimeout(resolve, 500));
1962
2077
  }
1963
2078
  if (checkpointedContentHash !== expectedContentHash) {
1964
2079
  throw new Error("Collaborative content did not reach a durable checkpoint within 10 seconds.");
@@ -2056,7 +2171,7 @@ function createArticleCommands() {
2056
2171
  const result = await client.publish.publish(
2057
2172
  workspaceId,
2058
2173
  articleId,
2059
- await agentPublishRequest(client, workspaceId, articleId, options)
2174
+ agentPublishRequest(options)
2060
2175
  );
2061
2176
  output.success("Article published publicly");
2062
2177
  output.output(result);
@@ -2606,96 +2721,251 @@ function createApiKeyCommands() {
2606
2721
 
2607
2722
  // src/commands/skill.ts
2608
2723
  init_output();
2609
- import { Command as Command6 } from "commander";
2610
- import { readFileSync as readFileSync2, mkdirSync as mkdirSync2, existsSync as existsSync2, appendFileSync, writeFileSync as writeFileSync2 } from "fs";
2611
- import { dirname, join as join2, resolve } from "path";
2724
+ import { createHash as createHash3 } from "crypto";
2725
+ import {
2726
+ existsSync as existsSync2,
2727
+ mkdirSync as mkdirSync2,
2728
+ readFileSync as readFileSync2,
2729
+ readdirSync,
2730
+ renameSync,
2731
+ rmSync,
2732
+ writeFileSync as writeFileSync2
2733
+ } from "fs";
2612
2734
  import { homedir as homedir2 } from "os";
2735
+ import { dirname, join as join2 } from "path";
2613
2736
  import { fileURLToPath } from "url";
2614
- var __filename = fileURLToPath(import.meta.url);
2615
- var __dirname = dirname(__filename);
2616
- function getSkillContent() {
2617
- const candidates = [join2(__dirname, "../skill.md"), join2(__dirname, "../../skill.md")];
2618
- for (const candidate of candidates) {
2619
- if (existsSync2(candidate)) return readFileSync2(candidate, "utf-8");
2737
+ import { Command as Command6 } from "commander";
2738
+ var __dirname = dirname(fileURLToPath(import.meta.url));
2739
+ var OWNER = "mdedit-cli";
2740
+ var METADATA_FILE = ".mdedit-skill.json";
2741
+ var TARGET_ROOTS = {
2742
+ agents: { project: [".agents", "skills"], user: [".agents", "skills"] },
2743
+ claude: { project: [".claude", "skills"], user: [".claude", "skills"] },
2744
+ cursor: { project: [".cursor", "skills"], user: [".cursor", "skills"] },
2745
+ gemini: { project: [".gemini", "skills"], user: [".gemini", "skills"] }
2746
+ };
2747
+ function skillsRoot() {
2748
+ const candidates = [join2(__dirname, "../skills"), join2(__dirname, "../../skills")];
2749
+ const found = candidates.find((candidate) => existsSync2(join2(candidate, "catalog.json")));
2750
+ if (!found) throw new Error(`Bundled skills catalog not found (searched: ${candidates.join(", ")})`);
2751
+ return found;
2752
+ }
2753
+ function catalog() {
2754
+ return JSON.parse(readFileSync2(join2(skillsRoot(), "catalog.json"), "utf8"));
2755
+ }
2756
+ function sha256(content) {
2757
+ return createHash3("sha256").update(content).digest("hex");
2758
+ }
2759
+ function parseVia(value) {
2760
+ const via = String(value || "cli").toLowerCase();
2761
+ if (via !== "cli" && via !== "mcp") throw new Error("Unknown variant. Valid values: cli, mcp");
2762
+ return via;
2763
+ }
2764
+ function parseScope(options) {
2765
+ const value = options.global ? "user" : String(options.scope || "project").toLowerCase();
2766
+ if (value !== "project" && value !== "user") {
2767
+ throw new Error("Unknown scope. Valid values: project, user");
2620
2768
  }
2621
- throw new Error(`skill.md not found (searched: ${candidates.join(", ")})`);
2622
- }
2623
- var NAMED_TARGETS = ["claude", "cursor", "codex"];
2624
- var TARGETS = {
2625
- claude: {
2626
- label: "Claude Code",
2627
- path: (_cwd, global) => global ? join2(homedir2(), ".claude", "CLAUDE.md") : join2(process.cwd(), "CLAUDE.md"),
2628
- mode: "append-section",
2629
- sectionHeading: "## mdedit CLI"
2630
- },
2631
- cursor: {
2632
- label: "Cursor",
2633
- path: (_cwd, global) => global ? join2(homedir2(), ".cursor", "rules", "mdedit.mdc") : join2(process.cwd(), ".cursor", "rules", "mdedit.mdc"),
2634
- mode: "write"
2635
- },
2636
- codex: {
2637
- label: "GitHub Copilot / Codex",
2638
- path: (cwd, _global) => join2(cwd, ".github", "copilot-instructions.md"),
2639
- mode: "append-section",
2640
- sectionHeading: "## mdedit CLI"
2769
+ return value;
2770
+ }
2771
+ function parseTarget(value) {
2772
+ const normalized = String(value || "agents").toLowerCase();
2773
+ const target = normalized === "codex" ? "agents" : normalized;
2774
+ if (!["agents", "claude", "cursor", "gemini"].includes(target)) {
2775
+ throw new Error("Unknown target. Valid values: agents, claude, cursor, gemini");
2641
2776
  }
2642
- };
2643
- function installToTarget(spec, skillContent, global) {
2644
- const targetPath = spec.path(process.cwd(), global);
2645
- const dir = dirname(resolve(targetPath));
2646
- if (!existsSync2(dir)) {
2647
- mkdirSync2(dir, { recursive: true });
2777
+ return target;
2778
+ }
2779
+ function targetRoot(target, scope) {
2780
+ const base = scope === "user" ? homedir2() : process.cwd();
2781
+ return join2(base, ...TARGET_ROOTS[target][scope]);
2782
+ }
2783
+ function selectSkills(skillIds, available) {
2784
+ const requested = skillIds?.filter(Boolean) || [];
2785
+ if (requested.length === 0 || requested.includes("all")) return available;
2786
+ const byId = new Map(available.map((skill) => [skill.id, skill]));
2787
+ const unknown = requested.filter((id) => !byId.has(id));
2788
+ if (unknown.length > 0) {
2789
+ throw new Error(`Unknown skill${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}`);
2648
2790
  }
2649
- if (spec.mode === "write") {
2650
- writeFileSync2(targetPath, skillContent, "utf-8");
2651
- output.success(`${spec.label}: skill written to ${targetPath}`);
2652
- return;
2791
+ return [...new Set(requested)].map((id) => byId.get(id));
2792
+ }
2793
+ function skillContent(skillId, via) {
2794
+ return readFileSync2(join2(skillsRoot(), skillId, via, "SKILL.md"), "utf8");
2795
+ }
2796
+ function readMetadata(path) {
2797
+ if (!existsSync2(path)) return null;
2798
+ try {
2799
+ const value = JSON.parse(readFileSync2(path, "utf8"));
2800
+ return value.owner === OWNER ? value : null;
2801
+ } catch {
2802
+ return null;
2653
2803
  }
2654
- const heading = spec.sectionHeading ?? "## mdedit CLI";
2655
- if (existsSync2(targetPath)) {
2656
- const existing = readFileSync2(targetPath, "utf-8");
2657
- if (existing.includes(heading)) {
2658
- output.info(`${spec.label}: skill section already present in ${targetPath} (skipped)`);
2659
- return;
2804
+ }
2805
+ function atomicWrite(path, content) {
2806
+ mkdirSync2(dirname(path), { recursive: true });
2807
+ const temporary = `${path}.tmp-${process.pid}-${Date.now()}`;
2808
+ writeFileSync2(temporary, content, { encoding: "utf8", flag: "wx" });
2809
+ renameSync(temporary, path);
2810
+ }
2811
+ function installOne(skill, via, root, catalogVersion, force) {
2812
+ const directory = join2(root, skill.id);
2813
+ const skillPath = join2(directory, "SKILL.md");
2814
+ const metadataPath = join2(directory, METADATA_FILE);
2815
+ const content = skillContent(skill.id, via);
2816
+ const contentSha256 = sha256(content);
2817
+ const metadata = readMetadata(metadataPath);
2818
+ if (existsSync2(skillPath)) {
2819
+ if (!metadata || metadata.skillId !== skill.id) {
2820
+ if (!force) throw new Error(`${skillPath} is not owned by mdedit; use --force to replace it`);
2821
+ } else {
2822
+ const currentSha = sha256(readFileSync2(skillPath, "utf8"));
2823
+ if (currentSha !== metadata.contentSha256 && !force) {
2824
+ throw new Error(`${skillPath} was edited after installation; use --force to replace it`);
2825
+ }
2826
+ if (currentSha === contentSha256 && metadata.via === via && metadata.catalogVersion === catalogVersion) {
2827
+ return { skillId: skill.id, status: "unchanged", path: skillPath, via };
2828
+ }
2660
2829
  }
2661
- const trimmed = existing.trimEnd();
2662
- appendFileSync(targetPath, `${trimmed}
2663
-
2664
- ${heading}
2665
-
2666
- ${skillContent}`, "utf-8");
2667
- } else {
2668
- writeFileSync2(targetPath, `${heading}
2669
-
2670
- ${skillContent}`, "utf-8");
2671
2830
  }
2672
- output.success(`${spec.label}: skill appended to ${targetPath}`);
2831
+ const status = existsSync2(skillPath) ? "updated" : "installed";
2832
+ const nextMetadata = {
2833
+ owner: OWNER,
2834
+ skillId: skill.id,
2835
+ via,
2836
+ catalogVersion,
2837
+ contentSha256,
2838
+ installedAt: (/* @__PURE__ */ new Date()).toISOString()
2839
+ };
2840
+ atomicWrite(skillPath, content);
2841
+ atomicWrite(metadataPath, `${JSON.stringify(nextMetadata, null, 2)}
2842
+ `);
2843
+ return { skillId: skill.id, status, path: skillPath, via };
2844
+ }
2845
+ function assertInstallable(skill, via, root, force) {
2846
+ const directory = join2(root, skill.id);
2847
+ const skillPath = join2(directory, "SKILL.md");
2848
+ skillContent(skill.id, via);
2849
+ if (!existsSync2(skillPath)) return;
2850
+ const metadata = readMetadata(join2(directory, METADATA_FILE));
2851
+ if ((!metadata || metadata.skillId !== skill.id) && !force) {
2852
+ throw new Error(`${skillPath} is not owned by mdedit; use --force to replace it`);
2853
+ }
2854
+ if (metadata?.skillId === skill.id && sha256(readFileSync2(skillPath, "utf8")) !== metadata.contentSha256 && !force) {
2855
+ throw new Error(`${skillPath} was edited after installation; use --force to replace it`);
2856
+ }
2857
+ }
2858
+ function uninstallOne(skill, root) {
2859
+ const directory = join2(root, skill.id);
2860
+ const skillPath = join2(directory, "SKILL.md");
2861
+ const metadataPath = join2(directory, METADATA_FILE);
2862
+ if (!existsSync2(skillPath) && !existsSync2(metadataPath)) {
2863
+ return { skillId: skill.id, status: "not-installed", path: skillPath };
2864
+ }
2865
+ const metadata = readMetadata(metadataPath);
2866
+ if (!metadata || metadata.skillId !== skill.id || !existsSync2(skillPath)) {
2867
+ throw new Error(`${directory} is not a complete mdedit-owned installation; it was left unchanged`);
2868
+ }
2869
+ if (sha256(readFileSync2(skillPath, "utf8")) !== metadata.contentSha256) {
2870
+ throw new Error(`${skillPath} was edited after installation; it was left unchanged`);
2871
+ }
2872
+ rmSync(skillPath);
2873
+ rmSync(metadataPath);
2874
+ if (readdirSync(directory).length === 0) rmSync(directory, { recursive: true });
2875
+ return { skillId: skill.id, status: "uninstalled", path: skillPath };
2876
+ }
2877
+ function legacyInstallations() {
2878
+ const locations = [
2879
+ { target: "Claude", path: join2(process.cwd(), "CLAUDE.md"), marker: "## mdedit CLI" },
2880
+ { target: "Cursor", path: join2(process.cwd(), ".cursor", "rules", "mdedit.mdc"), marker: "" },
2881
+ {
2882
+ target: "GitHub Copilot / Codex",
2883
+ path: join2(process.cwd(), ".github", "copilot-instructions.md"),
2884
+ marker: "## mdedit CLI"
2885
+ }
2886
+ ];
2887
+ return locations.filter(({ path, marker }) => {
2888
+ if (!existsSync2(path)) return false;
2889
+ return marker ? readFileSync2(path, "utf8").includes(marker) : true;
2890
+ }).map(({ target, path }) => ({
2891
+ target,
2892
+ path,
2893
+ guidance: "Remove the legacy mdedit block manually after reviewing it; doctor never edits host instructions."
2894
+ }));
2895
+ }
2896
+ function diagnosis(skill, via, root, catalogVersion) {
2897
+ const directory = join2(root, skill.id);
2898
+ const skillPath = join2(directory, "SKILL.md");
2899
+ const metadata = readMetadata(join2(directory, METADATA_FILE));
2900
+ if (!existsSync2(skillPath) && !metadata) return { skillId: skill.id, status: "missing", path: skillPath };
2901
+ if (!existsSync2(skillPath) || !metadata || metadata.skillId !== skill.id) {
2902
+ return { skillId: skill.id, status: "unowned-or-incomplete", path: skillPath };
2903
+ }
2904
+ const currentSha = sha256(readFileSync2(skillPath, "utf8"));
2905
+ if (currentSha !== metadata.contentSha256) return { skillId: skill.id, status: "modified", path: skillPath };
2906
+ const expectedSha = sha256(skillContent(skill.id, via));
2907
+ if (metadata.via !== via || metadata.catalogVersion !== catalogVersion || currentSha !== expectedSha) {
2908
+ return { skillId: skill.id, status: "stale", path: skillPath, installedVia: metadata.via };
2909
+ }
2910
+ return { skillId: skill.id, status: "current", path: skillPath, via };
2911
+ }
2912
+ function emitResults(results, message) {
2913
+ if (output.isJson()) output.output(results);
2914
+ else {
2915
+ output.output(results);
2916
+ output.info(message);
2917
+ }
2673
2918
  }
2674
2919
  function createSkillCommands() {
2675
- const skill = new Command6("skill").description("Manage and install the mdedit agent skill").action(() => skill.help());
2676
- skill.command("show").description("Print the mdedit agent skill to stdout").action(() => {
2677
- process.stdout.write(getSkillContent());
2920
+ const skill = new Command6("skill").description("List, inspect, install, diagnose, and safely remove mdedit agent skills").action(() => skill.help());
2921
+ skill.command("list").description("List the canonical mdedit skills").action(() => {
2922
+ const data = catalog();
2923
+ output.output(data.skills.map(({ id, title, shortDescription, scopes }) => ({ id, title, shortDescription, scopes })));
2678
2924
  });
2679
- skill.command("install").description(
2680
- "Install the mdedit skill into AI agent configuration files (Claude Code, Cursor, GitHub Copilot/Codex)"
2681
- ).option(
2682
- "-t, --target <target>",
2683
- "Which agent tool to install for: claude | cursor | codex | all (default: all)",
2684
- "all"
2685
- ).option("--global", "Install to home-directory targets instead of current project directory").action((options) => {
2686
- const target = String(options.target).toLowerCase();
2687
- const global = Boolean(options.global);
2688
- const skillContent = getSkillContent();
2689
- const validTargets = [...NAMED_TARGETS, "all"];
2690
- if (!validTargets.includes(target)) {
2691
- throw new Error(`Unknown target "${target}". Valid targets: ${validTargets.join(", ")}`);
2692
- }
2693
- const keys = target === "all" ? [...NAMED_TARGETS] : [target];
2694
- for (const key of keys) {
2695
- installToTarget(TARGETS[key], skillContent, global);
2696
- }
2697
- output.info("");
2698
- output.info("To view the installed skill at any time: mdedit skill show");
2925
+ skill.command("show <skillId>").description("Print one mdedit skill variant").option("--via <variant>", "Skill variant: cli | mcp", "cli").action((skillId, options) => {
2926
+ const data = catalog();
2927
+ const selected = selectSkills([skillId], data.skills)[0];
2928
+ const via = parseVia(options.via);
2929
+ const content = skillContent(selected.id, via);
2930
+ if (output.isJson()) output.output({ ...selected, via, content, catalogVersion: data.version });
2931
+ else process.stdout.write(content);
2932
+ });
2933
+ skill.command("install [skillIds...]").description("Install canonical mdedit skills into a native host skill directory").option("--via <variant>", "Skill variant: cli | mcp", "cli").option("--scope <scope>", "Installation scope: project | user", "project").option("--target <target>", "Host target: agents | claude | cursor | gemini", "agents").option("--global", "Legacy alias for --scope user").option("--force", "Replace an unowned or locally edited skill").action((skillIds, options) => {
2934
+ const data = catalog();
2935
+ const selected = selectSkills(skillIds, data.skills);
2936
+ const via = parseVia(options.via);
2937
+ const scope = parseScope(options);
2938
+ const target = parseTarget(options.target);
2939
+ const root = targetRoot(target, scope);
2940
+ selected.forEach((item) => assertInstallable(item, via, root, Boolean(options.force)));
2941
+ const results = selected.map((item) => installOne(item, via, root, data.version, Boolean(options.force)));
2942
+ emitResults({ target, scope, via, root, results }, "Use `mdedit skill doctor` to verify the installation.");
2943
+ });
2944
+ skill.command("uninstall [skillIds...]").description("Remove unchanged mdedit-owned skill installations").option("--scope <scope>", "Installation scope: project | user", "project").option("--target <target>", "Host target: agents | claude | cursor | gemini", "agents").option("--global", "Legacy alias for --scope user").action((skillIds, options) => {
2945
+ const data = catalog();
2946
+ const selected = selectSkills(skillIds, data.skills);
2947
+ const scope = parseScope(options);
2948
+ const target = parseTarget(options.target);
2949
+ const root = targetRoot(target, scope);
2950
+ const results = selected.map((item) => uninstallOne(item, root));
2951
+ emitResults({ target, scope, root, results }, "Only unchanged mdedit-owned files were removed.");
2952
+ });
2953
+ skill.command("doctor [skillIds...]").description("Check native skill installations and detect legacy monolithic instructions").option("--via <variant>", "Expected skill variant: cli | mcp", "cli").option("--scope <scope>", "Installation scope: project | user", "project").option("--target <target>", "Host target: agents | claude | cursor | gemini", "agents").option("--global", "Legacy alias for --scope user").action((skillIds, options) => {
2954
+ const data = catalog();
2955
+ const selected = selectSkills(skillIds, data.skills);
2956
+ const via = parseVia(options.via);
2957
+ const scope = parseScope(options);
2958
+ const target = parseTarget(options.target);
2959
+ const root = targetRoot(target, scope);
2960
+ output.output({
2961
+ target,
2962
+ scope,
2963
+ via,
2964
+ root,
2965
+ skills: selected.map((item) => diagnosis(item, via, root, data.version)),
2966
+ legacy: legacyInstallations(),
2967
+ installGuide: data.installUrl
2968
+ });
2699
2969
  });
2700
2970
  return skill;
2701
2971
  }
@@ -2855,8 +3125,8 @@ function createAuthCommands(runtime = defaultRuntime) {
2855
3125
  init_output();
2856
3126
  init_config();
2857
3127
  init_api();
2858
- var __filename2 = fileURLToPath2(import.meta.url);
2859
- var __dirname2 = dirname2(__filename2);
3128
+ var __filename = fileURLToPath2(import.meta.url);
3129
+ var __dirname2 = dirname2(__filename);
2860
3130
  var version = "0.0.0";
2861
3131
  try {
2862
3132
  const packageJson = JSON.parse(readFileSync3(join3(__dirname2, "../package.json"), "utf-8"));