akm-cli 0.10.261129 → 0.10.261130-beta.2

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.
Files changed (114) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/STABILITY.md +11 -0
  3. package/dist/assets/hints/cli-hints-full.md +1 -1
  4. package/dist/assets/hints/cli-hints-short.md +1 -0
  5. package/dist/assets/stash-skeleton/facts/conventions/assets/rule.md +1 -1
  6. package/dist/cli/usage-report.js +184 -0
  7. package/dist/cli/usage.js +24 -7
  8. package/dist/cli.js +8 -2
  9. package/dist/commands/completions.js +5 -4
  10. package/dist/commands/health/checks.js +18 -4
  11. package/dist/commands/health/connections-and-harnesses-check.js +1 -0
  12. package/dist/commands/health/egress.js +1 -2
  13. package/dist/commands/health/plugin-staleness.js +75 -159
  14. package/dist/commands/health/scheduler-binary.js +7 -2
  15. package/dist/commands/health/semantic-search-check.js +7 -6
  16. package/dist/commands/health/version-drift.js +2 -0
  17. package/dist/commands/improve/extract.js +2 -2
  18. package/dist/commands/improve/preparation.js +6 -1
  19. package/dist/commands/lint/base-linter.js +90 -48
  20. package/dist/commands/lint/index.js +128 -185
  21. package/dist/commands/lint/moved-refs.js +69 -0
  22. package/dist/commands/lint/scope.js +41 -0
  23. package/dist/commands/metrics/collect.js +25 -2
  24. package/dist/commands/metrics/report-view.js +11 -2
  25. package/dist/commands/proposal/proposal.js +7 -2
  26. package/dist/commands/proposal/repository.js +16 -11
  27. package/dist/commands/read/rules.js +142 -0
  28. package/dist/commands/read/search-cli.js +5 -5
  29. package/dist/commands/read/search.js +1 -1
  30. package/dist/commands/sources/plugin-upgrade.js +139 -71
  31. package/dist/commands/sources/source-clone.js +4 -4
  32. package/dist/commands/sources/sources-cli.js +3 -20
  33. package/dist/commands/sources/sync.js +24 -0
  34. package/dist/commands/tasks/tasks.js +1 -1
  35. package/dist/core/adapter/adapters/akm-adapter.js +32 -23
  36. package/dist/core/adapter/adapters/akm-lint.js +55 -61
  37. package/dist/core/adapter/adapters/akm-workflow-adapter.js +10 -14
  38. package/dist/core/adapter/adapters/llm-wiki-adapter.js +6 -17
  39. package/dist/core/adapter/adapters/okf-adapter.js +5 -9
  40. package/dist/core/adapter/adapters/shared.js +52 -200
  41. package/dist/core/adapter/adapters/tool-dir-shared.js +3 -2
  42. package/dist/core/adapter/adapters/website-snapshot-adapter.js +4 -4
  43. package/dist/core/adapter/validate-context.js +7 -11
  44. package/dist/core/asset/asset-placement.js +29 -0
  45. package/dist/core/asset/frontmatter-edit.js +124 -0
  46. package/dist/core/asset/lint-text.js +18 -2
  47. package/dist/core/asset/llm-wiki-root.js +30 -0
  48. package/dist/core/asset/ref-rewrite.js +39 -0
  49. package/dist/core/asset/type-keys.js +59 -0
  50. package/dist/core/config/schema/local-state.js +5 -1
  51. package/dist/core/config/schema/output.js +4 -4
  52. package/dist/core/config/schema/search.js +4 -0
  53. package/dist/core/write-source.js +75 -25
  54. package/dist/indexer/index-written-assets.js +16 -8
  55. package/dist/indexer/indexer.js +68 -19
  56. package/dist/indexer/legacy-refs.js +1 -26
  57. package/dist/indexer/links/declared-links.js +13 -11
  58. package/dist/indexer/ref-moves.js +75 -0
  59. package/dist/indexer/search/db-search.js +3 -2
  60. package/dist/indexer/walk/place-rules.js +25 -0
  61. package/dist/indexer/walk/walker.js +5 -1
  62. package/dist/integrations/session-logs/pre-filter.js +1 -0
  63. package/dist/output/context.js +6 -2
  64. package/dist/output/shapes/passthrough.js +1 -0
  65. package/dist/output/text/rules.js +14 -0
  66. package/dist/output/text.js +2 -0
  67. package/dist/scripts/akm-migrate-node.js +4651 -3584
  68. package/dist/scripts/akm-migrate.js +4650 -3584
  69. package/dist/setup/registry-stash-loader.js +4 -2
  70. package/dist/sources/providers/git-stash.js +13 -5
  71. package/dist/storage/repositories/index-entries-repository.js +8 -3
  72. package/dist/storage/repositories/index-llm-cache-repository.js +4 -0
  73. package/dist/workspace/activity.js +69 -8
  74. package/dist/workspace/asset-improve.js +9 -5
  75. package/dist/workspace/assets.js +33 -19
  76. package/dist/workspace/bundle-files.js +39 -2
  77. package/dist/workspace/bundles.js +53 -3
  78. package/dist/workspace/check-text.js +121 -0
  79. package/dist/workspace/config.js +3 -0
  80. package/dist/workspace/copy-entry.js +129 -0
  81. package/dist/workspace/derive.js +13 -4
  82. package/dist/workspace/documents.js +11 -16
  83. package/dist/workspace/file-actions.js +130 -0
  84. package/dist/workspace/frontmatter.js +41 -0
  85. package/dist/workspace/git-read.js +42 -27
  86. package/dist/workspace/graph.js +11 -2
  87. package/dist/workspace/impact.js +14 -5
  88. package/dist/workspace/metrics.js +1 -1
  89. package/dist/workspace/misses.js +8 -3
  90. package/dist/workspace/moved-links.js +57 -0
  91. package/dist/workspace/new-file.js +141 -0
  92. package/dist/workspace/proposals.js +12 -38
  93. package/dist/workspace/pulse.js +16 -9
  94. package/dist/workspace/readers.js +14 -0
  95. package/dist/workspace/sensitive.js +12 -6
  96. package/dist/workspace/setup.js +2 -1
  97. package/dist/workspace/stats.js +4 -0
  98. package/dist/workspace.d.ts +100 -1
  99. package/docs/architecture/adapters.md +15 -0
  100. package/docs/architecture/internals/health-advisories.md +13 -8
  101. package/docs/architecture/internals/indexing.md +1 -0
  102. package/docs/architecture/internals/storage-locations.md +3 -3
  103. package/docs/architecture/persisted-data-compat.md +2 -0
  104. package/docs/architecture/specs/ref.md +27 -13
  105. package/docs/guides/author-bundles.md +13 -12
  106. package/docs/integration/bundling-akm.md +3 -0
  107. package/docs/maintainers/implementation-details.md +1 -1
  108. package/docs/reference/api.md +3 -3
  109. package/docs/reference/cli.md +143 -35
  110. package/docs/reference/configuration.md +2 -1
  111. package/docs/reference/data-and-telemetry.md +49 -10
  112. package/docs/reference/workspace.md +122 -36
  113. package/package.json +1 -1
  114. package/schemas/akm-config.json +6 -0
@@ -75,14 +75,39 @@ function refreshed(harness, from, to) {
75
75
  const moved = from !== undefined && to !== undefined && from !== to;
76
76
  return { harness, outcome: moved ? "updated" : "current", from, to };
77
77
  }
78
- /** Unknown, in `--check`: knowing whether a newer build exists needs a marketplace fetch, which `--check` does not do. */
79
- function unknownRefresh(harness, from) {
80
- return {
81
- harness,
82
- outcome: "unknown",
83
- from,
84
- message: "checking needs a fetch of the akm-plugins marketplace, which --check does not do; `akm upgrade` refreshes it",
85
- };
78
+ /**
79
+ * What `--check` says an update would do to a marketplace plugin, from the same read as the real switch
80
+ * ({@link marketplacePlan}): the build the channel's branch of the registered marketplace offers. A switch to a channel
81
+ * with nothing newer returns `keep`, the plugin the real switch leaves alone. A marketplace that cannot be read leaves
82
+ * the entry `unknown`, with the reason.
83
+ */
84
+ function planEntry(harness, installed, source, ref, channel, allowDowngrade) {
85
+ const from = installed[0];
86
+ const followed = channel ?? refChannel(ref);
87
+ // A marketplace pinned to one tag never offers anything newer.
88
+ if (followed === "pinned")
89
+ return { entry: refreshed(harness, from, from) };
90
+ const unknown = (reason) => ({
91
+ entry: {
92
+ harness,
93
+ outcome: "unknown",
94
+ from,
95
+ message: `the ${followed} build could not be read (${reason}); \`akm upgrade\` refreshes it`,
96
+ },
97
+ });
98
+ let plan;
99
+ try {
100
+ plan = marketplacePlan(harness, source(), installed, followed, allowDowngrade);
101
+ }
102
+ catch (error) {
103
+ return unknown(error instanceof Error ? error.message : String(error));
104
+ }
105
+ if (plan.target instanceof Error && !(channel && plan.keep))
106
+ return unknown(plan.target.message);
107
+ if (plan.keep)
108
+ return { entry: refreshed(harness, from, from), keep: plan.keep };
109
+ const to = plan.target;
110
+ return { entry: to === from ? refreshed(harness, from, from) : { harness, outcome: "pending", from, to } };
86
111
  }
87
112
  function claudePlugins() {
88
113
  const listed = runCommand("claude", ["plugin", "list", "--json"], READ_TIMEOUT_MS);
@@ -143,11 +168,15 @@ function stays(harness, installed, channel, before, reason) {
143
168
  message: `${harness} stays at ${installed}; ${reason ?? `${channel} has nothing newer`}`,
144
169
  };
145
170
  }
146
- function upgradeClaudeCode(dryRun, next, channel, keep) {
171
+ function upgradeClaudeCode(dryRun, next, channel, keep, allowDowngrade = false) {
147
172
  const detected = detectClaudeCode(channel !== undefined);
148
173
  if ("entry" in detected)
149
174
  return detected.entry;
150
175
  const before = refChannel(detected.ref);
176
+ const planned = dryRun
177
+ ? planEntry("claude-code", detected.installations.map((p) => p.version), () => claudeMarketplace(claudePluginsRoot()).source, detected.ref, channel, allowDowngrade)
178
+ : undefined;
179
+ keep ??= planned?.keep;
151
180
  if (channel && keep !== undefined)
152
181
  return stays("claude-code", keep.installed, channel, before, keep.reason);
153
182
  let backups = [];
@@ -163,13 +192,11 @@ function upgradeClaudeCode(dryRun, next, channel, keep) {
163
192
  return channelWriteFailure("claude-code", error, before);
164
193
  }
165
194
  }
166
- const entry = refreshClaudeCode(dryRun, detected.version, channel ? detected.installations : undefined);
195
+ const entry = planned?.entry ?? refreshClaudeCode(detected.version, channel ? detected.installations : undefined);
167
196
  const noted = next && !channel ? withChannelNote(entry, detected.ref) : entry;
168
197
  return channelResult(noted, before, channel, dryRun, backups);
169
198
  }
170
- function refreshClaudeCode(dryRun, from, installations) {
171
- if (dryRun)
172
- return unknownRefresh("claude-code", from);
199
+ function refreshClaudeCode(from, installations) {
173
200
  const marketplace = runCommand("claude", ["plugin", "marketplace", "update", MARKETPLACE], REFRESH_TIMEOUT_MS);
174
201
  if (!marketplace.ok)
175
202
  return failed("claude-code", marketplace.error);
@@ -202,7 +229,7 @@ export function codexMarketplaceRef() {
202
229
  return undefined;
203
230
  }
204
231
  }
205
- function upgradeCodex(dryRun, next, channel, keep) {
232
+ function upgradeCodex(dryRun, next, channel, keep, allowDowngrade = false) {
206
233
  const before = codexPluginVersion();
207
234
  if ("error" in before)
208
235
  return channel && (!before.error.missing || fs.existsSync(codexConfigFile()))
@@ -212,6 +239,10 @@ function upgradeCodex(dryRun, next, channel, keep) {
212
239
  return skipped("codex", `the akm plugin is not installed from the ${MARKETPLACE} marketplace`);
213
240
  }
214
241
  const previous = refChannel(codexMarketplaceRef());
242
+ const planned = dryRun
243
+ ? planEntry("codex", [before.version], () => codexMarketplaceRegistration().source, codexMarketplaceRef(), channel, allowDowngrade)
244
+ : undefined;
245
+ keep ??= planned?.keep;
215
246
  if (channel && keep !== undefined)
216
247
  return stays("codex", keep.installed, channel, previous, keep.reason);
217
248
  const backups = [];
@@ -223,12 +254,10 @@ function upgradeCodex(dryRun, next, channel, keep) {
223
254
  return channelWriteFailure("codex", error, previous);
224
255
  }
225
256
  }
226
- const entry = refreshCodex(dryRun, before.version);
257
+ const entry = planned?.entry ?? refreshCodex(before.version);
227
258
  return channelResult(next && !channel ? withChannelNote(entry, codexMarketplaceRef()) : entry, previous, channel, dryRun, backups);
228
259
  }
229
- function refreshCodex(dryRun, from) {
230
- if (dryRun)
231
- return unknownRefresh("codex", from);
260
+ function refreshCodex(from) {
232
261
  // Also refreshes the installed plugin's cache, so no re-add is needed.
233
262
  const upgrade = runCommand("codex", ["plugin", "marketplace", "upgrade", MARKETPLACE], REFRESH_TIMEOUT_MS);
234
263
  if (!upgrade.ok)
@@ -491,7 +520,7 @@ function upgradeOpenCode(dryRun, target) {
491
520
  * The note `--next` adds to a marketplace harness. The channel is the ref the marketplace follows (`next` is the
492
521
  * prerelease branch, the default branch is stable); only an explicit --channel switches it.
493
522
  */
494
- function refChannel(ref) {
523
+ export function refChannel(ref) {
495
524
  return !ref || ref === "main" || ref === "master" ? "latest" : ref === "next" ? "next" : "pinned";
496
525
  }
497
526
  function channelResult(entry, before, target, dryRun, backups = []) {
@@ -519,8 +548,8 @@ function withChannelNote(entry, ref) {
519
548
  }
520
549
  export function upgradePlugins(opts) {
521
550
  return [
522
- upgradeClaudeCode(opts.dryRun, opts.next, opts.channel, opts.keep?.claude),
523
- upgradeCodex(opts.dryRun, opts.next, opts.channel, opts.keep?.codex),
551
+ upgradeClaudeCode(opts.dryRun, opts.next, opts.channel, opts.keep?.claude, opts.allowDowngrade),
552
+ upgradeCodex(opts.dryRun, opts.next, opts.channel, opts.keep?.codex, opts.allowDowngrade),
524
553
  ...opts.openCode.map((target) => {
525
554
  const entry = upgradeOpenCode(opts.dryRun, target);
526
555
  if (target.keepInstalled)
@@ -639,8 +668,12 @@ function resolveOpenCodeTargets(next, channel) {
639
668
  targets.push(resolveOpenCodeTarget(next, OPENCODE_V2, v2, channel));
640
669
  return targets;
641
670
  }
642
- /** Inspect the requested branch in a disposable clone before changing any installation. */
643
- function marketplaceTargetVersion(source, channel, harness) {
671
+ /**
672
+ * The newest akm plugin build on `channel` of the marketplace at `source`: the version its catalog names. Only the
673
+ * catalog and the plugin manifest are read, from a blobless clone with nothing checked out, so the channel's other
674
+ * files are never downloaded. The real channel switch, `akm upgrade --check` and `akm health` all read it here.
675
+ */
676
+ export function marketplaceTargetVersion(source, channel, harness) {
644
677
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "akm-channel-check-"));
645
678
  const checkout = path.join(root, "marketplace");
646
679
  try {
@@ -649,6 +682,8 @@ function marketplaceTargetVersion(source, channel, harness) {
649
682
  "--depth",
650
683
  "1",
651
684
  "--single-branch",
685
+ "--filter=blob:none",
686
+ "--no-checkout",
652
687
  ...(channel === "next" ? ["--branch", "next"] : []),
653
688
  "--",
654
689
  source,
@@ -656,10 +691,16 @@ function marketplaceTargetVersion(source, channel, harness) {
656
691
  ], REFRESH_TIMEOUT_MS);
657
692
  if (!cloned.ok)
658
693
  throw new UsageError(`Could not check the target plugin version: ${cloned.error}`);
659
- const catalog = parseJson(fs.readFileSync(path.join(checkout, ...(harness === "codex" ? [".agents", "plugins"] : [".claude-plugin"]), "marketplace.json"), "utf8"));
694
+ const show = (file) => runCommand("git", ["-C", checkout, "show", `HEAD:${file}`], REFRESH_TIMEOUT_MS);
695
+ const manifestDir = harness === "codex" ? ".codex-plugin" : ".claude-plugin";
696
+ const catalogFile = harness === "codex" ? ".agents/plugins/marketplace.json" : ".claude-plugin/marketplace.json";
697
+ const catalogText = show(catalogFile);
698
+ if (!catalogText.ok)
699
+ throw new UsageError(`Could not read the marketplace catalog: ${catalogText.error}`);
700
+ const catalog = parseJson(catalogText.stdout);
660
701
  const plugin = catalog?.plugins?.find((p) => p.name === "akm");
661
702
  const entry = typeof plugin?.source === "object" ? plugin.source : undefined;
662
- // A `git-subdir` entry (Codex) names its build by tag; one in this same repo can also be read from the checkout.
703
+ // A `git-subdir` entry (Codex) names its build by tag; one in this same repo can also be read from the repository.
663
704
  const tagged = entry?.source === "git-subdir" ? entry.ref?.replace(/^v/, "") : undefined;
664
705
  const sameRepo = (url) => url !== undefined && url.replace(/\.git$/, "").toLowerCase() === source.replace(/\.git$/, "").toLowerCase();
665
706
  const relative = typeof plugin?.source === "string"
@@ -667,13 +708,17 @@ function marketplaceTargetVersion(source, channel, harness) {
667
708
  : entry?.source === "local" || (entry?.source === "git-subdir" && sameRepo(entry.url))
668
709
  ? entry.path
669
710
  : undefined;
670
- const local = relative ? path.resolve(checkout, relative) : undefined;
671
- const contained = local === checkout || local?.startsWith(`${checkout}${path.sep}`);
672
- const version = plugin?.version ??
673
- (tagged && isExactSemver(tagged) ? tagged : undefined) ??
674
- (local && contained
675
- ? readPackageVersion(path.join(local, harness === "codex" ? ".codex-plugin" : ".claude-plugin", "plugin.json"))
676
- : undefined);
711
+ const dir = relative ? path.posix.normalize(relative) : undefined;
712
+ const contained = dir !== undefined && !path.posix.isAbsolute(dir) && dir !== ".." && !dir.startsWith("../");
713
+ let manifestVersion;
714
+ if (contained) {
715
+ const manifest = show(path.posix.join(dir, manifestDir, "plugin.json"));
716
+ const version = manifest.ok
717
+ ? parseJson(manifest.stdout)?.version
718
+ : undefined;
719
+ manifestVersion = typeof version === "string" ? version : undefined;
720
+ }
721
+ const version = plugin?.version ?? (tagged && isExactSemver(tagged) ? tagged : undefined) ?? manifestVersion;
677
722
  if (!version || !isExactSemver(version))
678
723
  throw new UsageError("Could not determine the requested marketplace's akm plugin version; no channel was changed");
679
724
  return version;
@@ -682,60 +727,76 @@ function marketplaceTargetVersion(source, channel, harness) {
682
727
  fs.rmSync(root, { recursive: true, force: true });
683
728
  }
684
729
  }
730
+ function claudePluginsRoot() {
731
+ const configDir = process.env.CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), ".claude");
732
+ return (process.env.AKM_CLAUDE_PLUGINS_DIR ?? process.env.CLAUDE_CODE_PLUGIN_CACHE_DIR ?? path.join(configDir, "plugins"));
733
+ }
734
+ /** The Git source and ref Claude has registered for a marketplace. */
735
+ export function claudeMarketplace(pluginsRoot, marketplace = MARKETPLACE) {
736
+ const known = parseJson(fs.readFileSync(path.join(pluginsRoot, "known_marketplaces.json"), "utf8"));
737
+ const registered = known[marketplace]?.source;
738
+ const url = registered?.source === "github" && registered.repo ? `https://github.com/${registered.repo}.git` : registered?.url;
739
+ if (!url)
740
+ throw new UsageError("Could not determine the Claude marketplace Git source; no channel was changed");
741
+ return { source: url, ref: typeof registered?.ref === "string" ? registered.ref : undefined };
742
+ }
743
+ /** The Git source and ref Codex has registered for the akm-plugins marketplace. */
744
+ export function codexMarketplaceRegistration() {
745
+ const source = codexMarketplace(codexConfigFile())?.source;
746
+ if (typeof source !== "string")
747
+ throw new UsageError("Could not determine the Codex marketplace Git source; no channel was changed");
748
+ return { source, ref: codexMarketplaceRef() };
749
+ }
750
+ /**
751
+ * What moving one marketplace plugin to `channel` does, read without changing anything: the build the channel's branch
752
+ * of the registered `source` offers (or why it could not be read), and, unless a downgrade is allowed, the installed
753
+ * version that switch leaves alone because the channel has nothing newer. The real switch and `--check` both decide
754
+ * from this.
755
+ */
756
+ function marketplacePlan(harness, source, installed, channel, allowDowngrade) {
757
+ let target;
758
+ try {
759
+ target = marketplaceTargetVersion(source, channel, harness === "codex" ? "codex" : "claude");
760
+ }
761
+ catch (error) {
762
+ target = error instanceof Error ? error : new Error(String(error));
763
+ }
764
+ let keep;
765
+ for (const version of installed) {
766
+ if (allowDowngrade || !version)
767
+ continue;
768
+ // An unreadable channel build leaves this plugin where it is; it never blocks the rest of the upgrade.
769
+ if (target instanceof Error)
770
+ keep = { installed: version, reason: `could not read the ${channel} build's version (${target.message})` };
771
+ else if (semverOrder(target, version) <= 0 && (!keep || semverOrder(keep.installed, version) < 0))
772
+ keep = { installed: version };
773
+ }
774
+ return { target, ...(keep ? { keep } : {}) };
775
+ }
685
776
  /**
686
777
  * Checks the marketplace channel switch can be made and returns the harnesses to leave alone: those whose
687
778
  * installed build is as new as, or newer than, the channel's.
688
779
  */
689
780
  function preflightMarketplaceChannels(channel, allowDowngrade) {
690
781
  const keep = {};
691
- const versions = new Map();
692
- const verify = (harness, source, installed) => {
693
- if (allowDowngrade || !installed)
694
- return;
695
- const key = `${harness}:${source}`;
696
- let target = versions.get(key);
697
- if (target === undefined) {
698
- try {
699
- target = marketplaceTargetVersion(source, channel, harness);
700
- }
701
- catch (error) {
702
- target = error instanceof Error ? error : new Error(String(error));
703
- }
704
- versions.set(key, target);
705
- }
706
- // An unreadable channel version leaves this plugin where it is; it never blocks the rest of the upgrade.
707
- if (target instanceof Error) {
708
- keep[harness] = { installed, reason: `could not read the ${channel} build's version (${target.message})` };
709
- return;
710
- }
711
- const kept = keep[harness];
712
- if (semverOrder(target, installed) <= 0 && (!kept || semverOrder(kept.installed, installed) < 0))
713
- keep[harness] = { installed };
714
- };
715
782
  const claude = detectClaudeCode(true);
716
783
  if ("entry" in claude && claude.entry.outcome === "failed")
717
784
  throw new UsageError(`Could not inventory Claude before switching channels: ${claude.entry.message}`);
718
785
  if (!("entry" in claude)) {
719
- const configDir = process.env.CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), ".claude");
720
- const pluginsRoot = process.env.AKM_CLAUDE_PLUGINS_DIR ?? process.env.CLAUDE_CODE_PLUGIN_CACHE_DIR ?? path.join(configDir, "plugins");
721
- claudeChannelEdits(configDir, pluginsRoot, channel, claude.installations.flatMap((p) => (p.projectPath ? [p.projectPath] : [])));
722
- const known = parseJson(fs.readFileSync(path.join(pluginsRoot, "known_marketplaces.json"), "utf8"));
723
- const source = known[MARKETPLACE]?.source;
724
- const url = source?.source === "github" && source.repo ? `https://github.com/${source.repo}.git` : source?.url;
725
- if (!url)
726
- throw new UsageError("Could not determine the Claude marketplace Git source; no channel was changed");
727
- for (const installed of claude.installations)
728
- verify("claude", url, installed.version);
786
+ const pluginsRoot = claudePluginsRoot();
787
+ claudeChannelEdits(process.env.CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), ".claude"), pluginsRoot, channel, claude.installations.flatMap((p) => (p.projectPath ? [p.projectPath] : [])));
788
+ const plan = marketplacePlan("claude-code", claudeMarketplace(pluginsRoot).source, claude.installations.map((p) => p.version), channel, allowDowngrade);
789
+ if (plan.keep)
790
+ keep.claude = plan.keep;
729
791
  }
730
792
  const codex = codexPluginVersion();
731
793
  if ("error" in codex && (!codex.error.missing || fs.existsSync(codexConfigFile())))
732
794
  throw new UsageError(`Could not inventory Codex before switching channels: ${codex.error.error}`);
733
795
  if (!("error" in codex) && codex.version !== undefined) {
734
796
  codexChannelEdit(codexConfigFile(), channel);
735
- const source = codexMarketplace(codexConfigFile())?.source;
736
- if (typeof source !== "string")
737
- throw new UsageError("Could not determine the Codex marketplace Git source; no channel was changed");
738
- verify("codex", source, codex.version);
797
+ const plan = marketplacePlan("codex", codexMarketplaceRegistration().source, [codex.version], channel, allowDowngrade);
798
+ if (plan.keep)
799
+ keep.codex = plan.keep;
739
800
  }
740
801
  return keep;
741
802
  }
@@ -763,7 +824,14 @@ export async function runUpgrade(args, currentVersion, deps) {
763
824
  mode: "check",
764
825
  result: {
765
826
  ...check,
766
- plugins: withEngineSkew(upgradePlugins({ dryRun: true, next, openCode, channel: switchChannel, currentChannel }), currentVersion),
827
+ plugins: withEngineSkew(upgradePlugins({
828
+ dryRun: true,
829
+ next,
830
+ openCode,
831
+ channel: switchChannel,
832
+ currentChannel,
833
+ allowDowngrade: args.allowDowngrade,
834
+ }), currentVersion),
767
835
  },
768
836
  };
769
837
  }
@@ -311,7 +311,7 @@ function slugName(conceptId) {
311
311
  * byte stays as written. A file whose frontmatter cannot be edited that way
312
312
  * (and still parse back to exactly the intended mapping) is left untouched.
313
313
  */
314
- function stampCloneOrigin(filePath, originRef) {
314
+ export function stampCloneOrigin(filePath, originRef) {
315
315
  if (!originRef)
316
316
  return;
317
317
  const raw = fs.readFileSync(filePath, "utf8");
@@ -344,7 +344,7 @@ function lstatIfExists(filePath) {
344
344
  throw error;
345
345
  }
346
346
  }
347
- function assertNoDestinationSymlinkParent(root, destination) {
347
+ export function assertNoDestinationSymlinkParent(root, destination) {
348
348
  const resolvedRoot = path.resolve(root);
349
349
  const parentDir = path.dirname(path.resolve(destination));
350
350
  const relativeParent = path.relative(resolvedRoot, parentDir);
@@ -358,7 +358,7 @@ function assertNoDestinationSymlinkParent(root, destination) {
358
358
  }
359
359
  }
360
360
  /** Replace each file symlink under `root` with a regular file holding its target's bytes. Directory links are left as links. */
361
- function materializeFileLinks(root) {
361
+ export function materializeFileLinks(root) {
362
362
  for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
363
363
  const entryPath = path.join(root, entry.name);
364
364
  if (entry.isDirectory()) {
@@ -372,7 +372,7 @@ function materializeFileLinks(root) {
372
372
  }
373
373
  }
374
374
  }
375
- function listTreeFiles(root) {
375
+ export function listTreeFiles(root) {
376
376
  const files = [];
377
377
  for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
378
378
  const entryPath = path.join(root, entry.name);
@@ -27,13 +27,11 @@
27
27
  */
28
28
  import { defineCommand } from "citty";
29
29
  import { defineJsonCommand, EXIT_CODES, GLOBAL_OUTPUT_ARGS, output, outputWithExitCode, runWithJsonErrors, } from "../../cli/shared.js";
30
- import { loadConfig } from "../../core/config/config.js";
31
- import { appendEvent } from "../../core/events.js";
32
- import { resolveWritableOverride, saveGitStash } from "../../sources/providers/git.js";
33
30
  import { pkgVersion } from "../../version.js";
34
31
  import { runUpgrade } from "./plugin-upgrade.js";
35
32
  import { checkForUpdate, performUpgrade } from "./self-update.js";
36
33
  import { akmClone } from "./source-clone.js";
34
+ import { akmSync } from "./sync.js";
37
35
  export const upgradeCommand = defineJsonCommand({
38
36
  meta: {
39
37
  name: "upgrade",
@@ -89,28 +87,13 @@ export const upgradeCommand = defineJsonCommand({
89
87
  outputWithExitCode("upgrade", run.result, run.failed ? EXIT_CODES.GENERAL : undefined);
90
88
  },
91
89
  });
92
- // `sync` body, standalone so the git-commit/push logic stays in one place.
90
+ // `sync` body: the output wrapper around `akmSync`, which the workspace's bundle commit runs too.
93
91
  async function runSyncBody(args) {
94
92
  await runWithJsonErrors(async () => {
95
93
  // The optional `name` positional is safe to trust: the global output flags
96
94
  // are declared on the command (GLOBAL_OUTPUT_ARGS), so `akm sync --format
97
95
  // json` parses `json` as the flag's value, never as a stash name.
98
- const effectiveName = args.name;
99
- let writable;
100
- if (effectiveName === undefined) {
101
- // Primary stash — honour the configured default bundle's writable flag.
102
- writable = resolveWritableOverride(loadConfig());
103
- }
104
- const result = saveGitStash(effectiveName, args.message, writable, { push: args.push !== false });
105
- appendEvent({
106
- eventType: "sync",
107
- metadata: {
108
- name: effectiveName ?? null,
109
- message: args.message ?? null,
110
- ok: result.ok !== false,
111
- },
112
- });
113
- output("sync", result);
96
+ output("sync", akmSync(args));
114
97
  });
115
98
  }
116
99
  export const syncCommand = defineCommand({
@@ -0,0 +1,24 @@
1
+ // This Source Code Form is subject to the terms of the Mozilla Public
2
+ // License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
+ import { loadConfig } from "../../core/config/config.js";
5
+ import { appendEvent } from "../../core/events.js";
6
+ import { resolveWritableOverride, saveGitStash } from "../../sources/providers/git.js";
7
+ /**
8
+ * `akm sync`: commit every unignored change inside a git-backed bundle (the named one, or the primary bundle), and push when
9
+ * it is writable with a remote configured. The CLI and the workspace's bundle commit both run this.
10
+ */
11
+ export function akmSync(args) {
12
+ // Primary stash — honour the configured default bundle's writable flag.
13
+ const writable = args.name === undefined ? resolveWritableOverride(loadConfig()) : undefined;
14
+ const result = saveGitStash(args.name, args.message, writable, { push: args.push !== false });
15
+ appendEvent({
16
+ eventType: "sync",
17
+ metadata: {
18
+ name: args.name ?? null,
19
+ message: args.message ?? null,
20
+ ok: result.ok !== false,
21
+ },
22
+ });
23
+ return result;
24
+ }
@@ -805,7 +805,7 @@ function renderInputsFromParams(params) {
805
805
  }
806
806
  return inputs;
807
807
  }
808
- function renderTaskYaml(input) {
808
+ export function renderTaskYaml(input) {
809
809
  const obj = { version: 4 };
810
810
  if (input.workflow) {
811
811
  obj.uses = input.workflow;
@@ -51,8 +51,8 @@
51
51
  *
52
52
  * ── validate ──
53
53
  *
54
- * Shared base checks (`validateChangesWithBaseChecks` — the ported
55
- * unquoted-colon / missing-updated / stale-path / missing-ref), then the
54
+ * The shared base checks (`createBaseChecker`: unquoted-colon / missing-updated /
55
+ * stale-path / missing-ref / redacted-content), then the
56
56
  * per-type linters (SkillLinter/WorkflowLinter/TaskLinter/…) in `akm-lint.ts`.
57
57
  *
58
58
  * ── Cycle-safety ──
@@ -76,13 +76,13 @@ import { buildFileContext } from "../../../indexer/walk/file-context.js";
76
76
  import { declaredTypeForPath } from "../../../indexer/walk/matchers.js";
77
77
  import { assetPathCandidatesForName, deriveCanonicalAssetNameFromStashRoot, placementTypes, refForFile, stashDirNames, typeForStashDir, } from "../../asset/asset-placement.js";
78
78
  import { parseFrontmatter } from "../../asset/frontmatter.js";
79
+ import { looksLikeLlmWikiRoot } from "../../asset/llm-wiki-root.js";
79
80
  import { sensitiveMarkerPath } from "../../sensitive-marker-path.js";
80
81
  import { executionDefaultsFromFrontmatter, renderMarkdownExecutionSource } from "../execution-source.js";
81
82
  import { recognizeMatch } from "../recognize-match.js";
82
- import { perTypeValidateChecks, skillDirectoryDiagnostics } from "./akm-lint.js";
83
+ import { derivedSiblingPath, perTypeDiagnostics, skillDirectoryDiagnostics } from "./akm-lint.js";
83
84
  import { applyFoldedMetadata, foldRecognizedMetadata } from "./akm-metadata.js";
84
- import { llmWikiAdapter } from "./llm-wiki-adapter.js";
85
- import { hashContent, RESERVED_FILES, runBaseValidateChecks } from "./shared.js";
85
+ import { createBaseChecker, hashContent, parseForValidate, RESERVED_FILES } from "./shared.js";
86
86
  // `recognizeMatch` + the builtin matcher list moved to the cycle-free leaf
87
87
  // `../recognize-match` (Chunk 5 M-b) so both this adapter AND the indexer
88
88
  // metadata pass import it without closing a metadata ↔ adapter cycle. Re-exported
@@ -267,13 +267,19 @@ function isWikiRaw(c, file) {
267
267
  return false;
268
268
  const dirs = file.ancestorDirs;
269
269
  for (let i = 0; i < dirs.length; i++) {
270
- if (dirs[i] === "raw" && llmWikiAdapter.looksLikeRoot?.(path.join(c.root, ...dirs.slice(0, i))) === true) {
270
+ if (dirs[i] === "raw" && looksLikeLlmWikiRoot(path.join(c.root, ...dirs.slice(0, i)))) {
271
271
  return true;
272
272
  }
273
273
  }
274
274
  return false;
275
275
  }
276
- function recognize(c, file) {
276
+ /**
277
+ * The type the akm adapter gives a file of the bundle at `root`, with its ref and canonical name, or `null` when the
278
+ * file is not an asset (a reserved structural file, one the adapter abstains on, one no matcher claims, or one whose
279
+ * placement gives no ref). Path rules and matchers only: this is the one place that decides what an akm bundle holds,
280
+ * for the index (`recognize`) and for `akm lint`.
281
+ */
282
+ export function classifyAkmFile(root, file) {
277
283
  // `index.md` / `log.md` are OKF reserved structural files at
278
284
  // every depth — never items. Excluded BEFORE classification so a directory
279
285
  // listing or update log never becomes a `knowledge` (or other) concept.
@@ -282,7 +288,7 @@ function recognize(c, file) {
282
288
  // Adapter-owned filtering (owner ruling 2026-07-21): AKM-stash policy that used
283
289
  // to live in the indexer's `shouldIndexStashFile` pre-filter. Path/stat-based —
284
290
  // `file.content()` is never read to reach this abstention.
285
- if (akmStashAbstains(c.root, file.absPath))
291
+ if (akmStashAbstains(root, file.absPath))
286
292
  return null;
287
293
  const match = recognizeMatch(file);
288
294
  if (match === null)
@@ -291,10 +297,17 @@ function recognize(c, file) {
291
297
  // `entry.name` below keeps the canonical name relative to the type folder
292
298
  // (identity != search text). Invalid placements are not projected onto a
293
299
  // different identity.
294
- const conceptId = refForFile(match.type, c.root, file.absPath);
295
- const canonicalName = deriveCanonicalAssetNameFromStashRoot(match.type, c.root, file.absPath);
300
+ const conceptId = refForFile(match.type, root, file.absPath);
301
+ const canonicalName = deriveCanonicalAssetNameFromStashRoot(match.type, root, file.absPath);
296
302
  if (conceptId === undefined || canonicalName === undefined)
297
303
  return null;
304
+ return { match, conceptId, canonicalName };
305
+ }
306
+ function recognize(c, file) {
307
+ const classified = classifyAkmFile(c.root, file);
308
+ if (classified === null)
309
+ return null;
310
+ const { match, conceptId, canonicalName } = classified;
298
311
  const dirPath = path.dirname(file.absPath);
299
312
  // recognize carries the FULL index-time metadata surface,
300
313
  // reproducing `buildEntryFromFile`'s flat-walk metadata
@@ -411,6 +424,7 @@ function buildOverlayContext(root, relPathInput, raw) {
411
424
  async function validate(c, changes, ctx) {
412
425
  const diagnostics = [];
413
426
  const seenSkillDirs = new Set();
427
+ const { check, rulesFor } = createBaseChecker(c.root, ctx);
414
428
  for (const change of changes) {
415
429
  if (change.op === "delete")
416
430
  continue;
@@ -420,18 +434,11 @@ async function validate(c, changes, ctx) {
420
434
  const overlay = buildOverlayContext(c.root, change.path, raw);
421
435
  const match = recognizeMatch(overlay);
422
436
  const type = match?.type;
423
- // Task parsing belongs to perTypeValidateChecks' canonical v3 parser. Base
437
+ // Task parsing belongs to perTypeChecks' canonical v3 parser. Base
424
438
  // checks need only a frontmatter-free placeholder here.
425
- let parsed;
426
- if (type === "task") {
427
- parsed = { data: {}, content: raw, frontmatter: null, bodyStartLine: 1 };
428
- }
429
- else {
430
- const p = parseFrontmatter(raw);
431
- parsed = { data: p.data, content: p.content, frontmatter: p.frontmatter, bodyStartLine: p.bodyStartLine };
432
- }
433
- diagnostics.push(...(await runBaseValidateChecks(change.path, parsed, c.root, ctx)));
434
- diagnostics.push(...(await perTypeValidateChecks({
439
+ const parsed = type === "task" ? { raw, data: {}, content: raw, frontmatter: null, bodyStartLine: 1 } : parseForValidate(raw);
440
+ diagnostics.push(...check(change.path, parsed));
441
+ const input = {
435
442
  type,
436
443
  relPath: change.path,
437
444
  raw,
@@ -439,8 +446,10 @@ async function validate(c, changes, ctx) {
439
446
  frontmatter: parsed.frontmatter,
440
447
  body: parsed.content,
441
448
  ext: overlay.ext,
442
- ctx,
443
- })));
449
+ rules: rulesFor(change.path),
450
+ derivedSiblingExists: (await ctx.readFile(derivedSiblingPath(change.path))) !== null,
451
+ };
452
+ diagnostics.push(...perTypeDiagnostics(input, change.path));
444
453
  diagnostics.push(...(await skillDirectoryDiagnostics(change.path, seenSkillDirs, ctx)));
445
454
  }
446
455
  return diagnostics;