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
@@ -3,40 +3,32 @@
3
3
  // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
6
- import { factDiagnostics, MAX_SKILL_GROUP_DEPTH, matchWorkflowPlaceholder, memoryOrphanStubApplies, nameOrTypeDiagnostics, ORPHANED_STUB_DETAIL, taskDiagnostics, workflowFrontendDiagnostics, } from "../../core/adapter/adapters/akm-lint.js";
6
+ import { classifyAkmFile } from "../../core/adapter/adapters/akm-adapter.js";
7
+ import { derivedSiblingPath, MAX_SKILL_GROUP_DEPTH, matchWorkflowPlaceholder, perTypeChecks, perTypeFrontend, } from "../../core/adapter/adapters/akm-lint.js";
7
8
  import { detectAdapterId } from "../../core/adapter/detect-adapter.js";
8
9
  import { adapterForId } from "../../core/adapter/registry.js";
9
10
  import { createValidateContext } from "../../core/adapter/validate-context.js";
10
- import { refForFile, stashDirFor, typeForStashDir } from "../../core/asset/asset-placement.js";
11
+ import { documentFormatForStashDir, documentStashDirFor, documentStashDirs, documentTypes, refForFile, stashDirFor, typeForStashDir, } from "../../core/asset/asset-placement.js";
11
12
  import { parseFrontmatter } from "../../core/asset/frontmatter.js";
12
13
  import { conceptIdForStashFile, displayRefForConceptId } from "../../core/asset/resolve-ref.js";
13
- import { stalePathRoots } from "../../core/asset/stale-path.js";
14
14
  import { deriveBundleIds } from "../../core/bundle-id.js";
15
15
  import { compareCodePoints, isAkmRegistryCachePath, resolveStashDir, safeRealpath, samePath } from "../../core/common.js";
16
16
  import { loadConfig, primaryBundlePath } from "../../core/config/config.js";
17
17
  import { bundleKeyForContentRoot } from "../../core/config/config-sources.js";
18
+ import { defaultExcludedTypes } from "../../core/config/schema/search.js";
18
19
  import { UsageError } from "../../core/errors.js";
19
20
  import { warn } from "../../core/warn.js";
20
21
  import { resolveSourceEntries } from "../../indexer/search/search-source.js";
22
+ import { walkStashFlat } from "../../indexer/walk/walker.js";
21
23
  import { TASK_EXTENSION, TASK_NEAR_MISS_EXTENSION, taskExtensionDetail } from "../../tasks/source-v3.js";
22
24
  import { resolveWorkflowSourceDomains } from "../../workflows/source-files.js";
23
25
  import { runBaseChecks } from "./base-linter.js";
24
26
  import { bundleLintSkip } from "./bundle-skip.js";
25
27
  import { checkEnvForDangerousKeys } from "./env-key-rules.js";
28
+ import { readRecordedMoves } from "./moved-refs.js";
29
+ import { lintScope } from "./scope.js";
26
30
  import { trackedSecretIssues } from "./tracked-secrets.js";
27
31
  import { isAdvisoryLintIssue, LINT_RULES } from "./types.js";
28
- // ── Constants ─────────────────────────────────────────────────────────────────
29
- const STASH_SUBDIRS = [
30
- "agents",
31
- "commands",
32
- "memories",
33
- "skills",
34
- "workflows",
35
- "lessons",
36
- "tasks",
37
- "knowledge",
38
- "facts",
39
- ];
40
32
  // ── Helpers ───────────────────────────────────────────────────────────────────
41
33
  /**
42
34
  * Every task-shaped file under `tasks/`: the recognized `.yml` spelling AND the
@@ -66,47 +58,23 @@ function isTaskFileName(fileName) {
66
58
  function isNearMissTaskFileName(fileName) {
67
59
  return fileName.toLowerCase().endsWith(TASK_NEAR_MISS_EXTENSION);
68
60
  }
69
- function collectMarkdownFiles(dir, caseInsensitive = false) {
70
- if (!fs.existsSync(dir))
71
- return [];
72
- const results = [];
73
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
74
- if (entry.name === ".git" || entry.isSymbolicLink())
75
- continue;
76
- const full = path.join(dir, entry.name);
77
- if (entry.isDirectory()) {
78
- results.push(...collectMarkdownFiles(full, caseInsensitive));
79
- }
80
- else if (entry.isFile() && (caseInsensitive ? entry.name.toLowerCase() : entry.name).endsWith(".md")) {
81
- results.push(full);
82
- }
83
- }
84
- return results;
85
- }
86
- /** Workflow sources: Markdown only. */
87
- function collectWorkflowFiles(dir) {
88
- if (!fs.existsSync(dir))
89
- return [];
90
- const results = [];
91
- for (const entry of fs
92
- .readdirSync(dir, { withFileTypes: true })
93
- .sort((left, right) => compareCodePoints(left.name, right.name))) {
94
- if (entry.name === ".git")
95
- continue;
96
- const full = path.join(dir, entry.name);
97
- if (entry.isDirectory()) {
98
- if (isAkmRegistryCachePath(full))
99
- continue;
100
- results.push(...collectWorkflowFiles(full));
61
+ /**
62
+ * The Markdown assets of the bundle at `root` by the stash folder of their type: the files are the indexer's walk and
63
+ * each file's type is the akm adapter's classification, so lint reads what the index holds, wherever a file sits.
64
+ * Nothing under `env/` or `secrets/` is classified, because classifying a Markdown file reads it.
65
+ */
66
+ function markdownAssetsByType(root) {
67
+ const byDir = new Map();
68
+ for (const file of walkStashFlat(root)) {
69
+ if (file.ext !== ".md" || file.ancestorDirs.some((dir) => dir === "env" || dir === "secrets"))
101
70
  continue;
102
- }
103
- if (!entry.isFile() && !entry.isSymbolicLink())
71
+ const type = classifyAkmFile(root, file)?.match.type;
72
+ const dir = type === undefined ? undefined : documentStashDirFor(type);
73
+ if (dir === undefined || documentFormatForStashDir(dir) !== "markdown")
104
74
  continue;
105
- const extension = path.extname(entry.name).toLowerCase();
106
- if (extension === ".md")
107
- results.push(full);
75
+ byDir.set(dir, [...(byDir.get(dir) ?? []), file.absPath]);
108
76
  }
109
- return results.sort(compareCodePoints);
77
+ return byDir;
110
78
  }
111
79
  /**
112
80
  * Resolve the already-enumerated candidates through the same workflow-source
@@ -143,7 +111,7 @@ function resolveWorkflowLintOwnership(stashRoot, files) {
143
111
  // `lintOkfBundle` re-implementation this change deletes) and silently route
144
112
  // every OTHER non-akm bundle (llm-wiki, dotenv, claude, opencode,
145
113
  // agent-skills, website-snapshot, generic-files, akm-task, akm-workflow)
146
- // through the AKM-shaped STASH_SUBDIRS sweep — the wrong linter for the wrong
114
+ // through the AKM-shaped akm sweep — the wrong linter for the wrong
147
115
  // format, and the reason those adapters' own `validate()` checks (OKF's
148
116
  // `missing-ref`; llm-wiki's `uncited-raw`/`missing-description`/`broken-xref`/
149
117
  // `broken-source`) were unreachable dead code. Every bundle is now linted by
@@ -264,7 +232,12 @@ async function lintViaAdapter(adapterId, stashRoot, extraStashRoots, sources, cf
264
232
  const ids = deriveBundleIds(sources);
265
233
  const sourceIndex = sources.findIndex((s) => samePath(s.path, stashRoot));
266
234
  const componentId = sourceIndex >= 0 ? ids[sourceIndex] : stashRoot;
267
- const ctx = createValidateContext({ root: stashRoot, extraRoots: extraStashRoots });
235
+ const ctx = createValidateContext({
236
+ root: stashRoot,
237
+ sources,
238
+ config: cfg,
239
+ readMoves: options.readMoves ?? readRecordedMoves,
240
+ });
268
241
  const diagnostics = await adapter.validate({ id: componentId, adapter: adapterId, root: stashRoot, writable: true }, changes, ctx);
269
242
  const mapped = diagnostics.map(diagnosticToLintIssue);
270
243
  // Advisory diagnostics travel in their own channel — never `flagged`, so a
@@ -274,7 +247,7 @@ async function lintViaAdapter(adapterId, stashRoot, extraStashRoots, sources, cf
274
247
  const warnings = mapped.filter(isAdvisoryLintIssue);
275
248
  const flagged = mapped.filter((issue) => !isAdvisoryLintIssue(issue));
276
249
  // The cross-bundle env dangerous-key sweep (see `runEnvDangerousKeyPass`'s
277
- // doc comment) ran for every non-akm adapter via the STASH_SUBDIRS
250
+ // doc comment) ran for every non-akm adapter via the akm sweep
278
251
  // fallthrough this dispatch replaces — EXCEPT `okf`, which the old code
279
252
  // special-cased out before ever reaching that pass. Preserve both halves of
280
253
  // that history exactly: skip only for `okf`. Some adapters (`dotenv`) ALSO
@@ -322,7 +295,7 @@ function collectEnvFiles(dir) {
322
295
  * there per the CRITICAL akm-path constraint, and reused here for the
323
296
  * non-akm dispatch path so a non-akm PRIMARY bundle keeps the exact
324
297
  * cross-bundle coverage it already had — the pass previously reached every
325
- * non-akm adapter's bundle via the accidental STASH_SUBDIRS fallthrough this
298
+ * non-akm adapter's bundle via the accidental akm-sweep fallthrough this
326
299
  * change replaces with real dispatch).
327
300
  */
328
301
  function runEnvDangerousKeyPass(stashRoot, extraStashRoots, sources, cfg) {
@@ -422,69 +395,24 @@ function containsSkillManifest(dir, depth) {
422
395
  !entry.name.startsWith(".") &&
423
396
  containsSkillManifest(path.join(dir, entry.name), depth + 1));
424
397
  }
425
- /** MemoryLinter's `orphaned-stub` check WITH its `--fix` delete (memory-linter.ts:19-65). */
426
- function appendMemoryStubIssue(ctx, issues) {
427
- if (ctx.lintSkip?.includes("orphaned-stub") || !memoryOrphanStubApplies(ctx.data, ctx.body))
428
- return;
429
- const derivedPath = `${ctx.filePath.replace(/\.md$/i, "")}.derived.md`;
430
- if (fs.existsSync(derivedPath))
431
- return;
432
- if (ctx.fix) {
433
- try {
434
- fs.unlinkSync(ctx.filePath);
435
- issues.push({ file: ctx.relPath, issue: "orphaned-stub", detail: "deleted orphaned stub", fixed: true });
436
- }
437
- catch (e) {
438
- issues.push({
439
- file: ctx.relPath,
440
- issue: "orphaned-stub",
441
- detail: `could not delete: ${e instanceof Error ? e.message : String(e)}`,
442
- fixed: "failed",
443
- });
444
- }
445
- return;
398
+ /** Under `--fix`, a stub the per-type checks found is deleted; the finding then says so, or says why not. */
399
+ function deleteStubWhenFixing(ctx, found) {
400
+ const issue = found;
401
+ if (!ctx.fix || (issue.issue !== "orphaned-stub" && issue.issue !== "placeholder-stub"))
402
+ return issue;
403
+ try {
404
+ fs.unlinkSync(ctx.filePath);
405
+ return {
406
+ ...issue,
407
+ detail: issue.issue === "orphaned-stub"
408
+ ? "deleted orphaned stub"
409
+ : `deleted: found "${matchWorkflowPlaceholder(ctx.body)}"`,
410
+ fixed: true,
411
+ };
446
412
  }
447
- issues.push({ file: ctx.relPath, issue: "orphaned-stub", detail: ORPHANED_STUB_DETAIL, fixed: false });
448
- }
449
- /**
450
- * WorkflowLinter's `placeholder-stub` check WITH its `--fix` delete
451
- * (workflow-linter.ts:22-79). Its sibling `invalid-workflow-structure` check is
452
- * deliberately NOT here: parse+compile is a single pass shared with the
453
- * advisory channel, so {@link lintAkmSweep} runs it once per file and routes
454
- * both halves.
455
- */
456
- function appendWorkflowStubIssue(ctx, issues) {
457
- if (ctx.lintSkip?.includes("placeholder-stub"))
458
- return;
459
- const placeholder = matchWorkflowPlaceholder(ctx.body);
460
- if (!placeholder)
461
- return;
462
- if (ctx.fix) {
463
- try {
464
- fs.unlinkSync(ctx.filePath);
465
- issues.push({
466
- file: ctx.relPath,
467
- issue: "placeholder-stub",
468
- detail: `deleted: found "${placeholder}"`,
469
- fixed: true,
470
- });
471
- }
472
- catch (e) {
473
- issues.push({
474
- file: ctx.relPath,
475
- issue: "placeholder-stub",
476
- detail: `could not delete: ${e instanceof Error ? e.message : String(e)}`,
477
- fixed: "failed",
478
- });
479
- }
480
- return;
413
+ catch (e) {
414
+ return { ...issue, detail: `could not delete: ${e instanceof Error ? e.message : String(e)}`, fixed: "failed" };
481
415
  }
482
- issues.push({
483
- file: ctx.relPath,
484
- issue: "placeholder-stub",
485
- detail: `placeholder text: "${placeholder}"`,
486
- fixed: false,
487
- });
488
416
  }
489
417
  /**
490
418
  * Lint ONE asset file: the shared base checks, then the winning stash subdir's
@@ -498,34 +426,22 @@ function appendWorkflowStubIssue(ctx, issues) {
498
426
  */
499
427
  export function lintAssetFile(ctx, subdir) {
500
428
  const issues = runBaseChecks(ctx);
501
- switch (subdir) {
502
- case "agents":
503
- issues.push(...nameOrTypeDiagnostics(ctx.relPath, ctx.data, ctx.frontmatter, ["agent"]));
504
- break;
505
- case "commands":
506
- issues.push(...nameOrTypeDiagnostics(ctx.relPath, ctx.data, ctx.frontmatter, ["command"]));
507
- break;
508
- case "facts":
509
- issues.push(...factDiagnostics(ctx.relPath, ctx.data));
510
- break;
511
- case "tasks":
512
- issues.push(...taskDiagnostics(ctx.relPath, ctx.raw));
513
- break;
514
- case "memories":
515
- appendMemoryStubIssue(ctx, issues);
516
- break;
517
- case "workflows":
518
- appendWorkflowStubIssue(ctx, issues);
519
- break;
520
- // knowledge / lessons / skills: base checks only (skill directory-level
521
- // `missing-skill-md` runs separately, per-subdir, in the sweep loop).
522
- }
429
+ const found = perTypeChecks({
430
+ type: typeForStashDir(subdir),
431
+ relPath: ctx.relPath,
432
+ raw: ctx.raw,
433
+ data: ctx.data,
434
+ frontmatter: ctx.frontmatter,
435
+ body: ctx.body,
436
+ ext: path.extname(ctx.relPath).toLowerCase(),
437
+ rules: { relPath: ctx.relPath, llmWiki: ctx.llmWiki, skip: ctx.lintSkip },
438
+ derivedSiblingExists: fs.existsSync(derivedSiblingPath(ctx.filePath)),
439
+ });
440
+ issues.push(...found.map((finding) => deleteStubWhenFixing(ctx, finding)));
523
441
  return issues;
524
442
  }
525
443
  /** Lint one asset file of `subdir` and file its findings into `sinks` (the sweep loop body, shared with {@link lintFile}). */
526
- function lintSweepFile(filePath, relPath, subdir, scope, { fixed, flagged, warnings }) {
527
- const { stashRoot, extraStashRoots, fix, pruneDanglingEdges, stalePathRoots } = scope;
528
- const lintSkip = [...(scope.lintSkip ?? []), ...(scope.bundleSkip?.(relPath) ?? [])];
444
+ function lintSweepFile(filePath, relPath, subdir, scope, sinks) {
529
445
  let raw;
530
446
  try {
531
447
  raw = fs.readFileSync(filePath, "utf8");
@@ -533,6 +449,16 @@ function lintSweepFile(filePath, relPath, subdir, scope, { fixed, flagged, warni
533
449
  catch {
534
450
  return;
535
451
  }
452
+ lintDocument(raw, filePath, relPath, subdir, scope, sinks);
453
+ }
454
+ /**
455
+ * The checks of one asset's text, as the sweep runs them on a file: the file's own rules, its type's rules and the
456
+ * workflow frontend. {@link lintSweepFile} reads the file and calls this; {@link lintDocumentText} calls it for text not
457
+ * yet saved, so what a save is checked against is what a sweep would then report.
458
+ */
459
+ function lintDocument(raw, filePath, relPath, subdir, scope, { fixed, flagged, warnings }) {
460
+ const { stashRoot, extraStashRoots, fix, fixMovedRefs, moves, bundleRoots, inLlmWiki, pruneDanglingEdges, stalePathRoots, } = scope;
461
+ const lintSkip = [...(scope.lintSkip ?? []), ...(scope.bundleSkip?.(relPath) ?? [])];
536
462
  let data;
537
463
  let body;
538
464
  let frontmatter;
@@ -576,6 +502,10 @@ function lintSweepFile(filePath, relPath, subdir, scope, { fixed, flagged, warni
576
502
  frontmatter,
577
503
  bodyStartLine,
578
504
  fix,
505
+ fixMovedRefs,
506
+ moves,
507
+ bundleRoots,
508
+ llmWiki: inLlmWiki(relPath),
579
509
  pruneDanglingEdges,
580
510
  stashRoot,
581
511
  stalePathRoots,
@@ -625,21 +555,19 @@ function lintSweepFile(filePath, relPath, subdir, scope, { fixed, flagged, warni
625
555
  // `--fail-on-flagged`.
626
556
  // The CLI passes the absolute filePath to the shared source-IR frontend,
627
557
  // whereas the adapter passes the change relPath.
628
- if (subdir === "workflows") {
629
- const frontend = workflowFrontendDiagnostics(relPath, raw, filePath);
630
- for (const finding of [...frontend.errors, ...frontend.warnings]) {
631
- if (isAdvisoryLintIssue(finding)) {
632
- warnings.push(finding);
633
- }
634
- else {
635
- flagged.push(finding);
636
- }
558
+ const frontend = perTypeFrontend({ type: typeForStashDir(subdir), ext: path.extname(relPath).toLowerCase(), relPath, raw }, filePath);
559
+ for (const finding of [...frontend.errors, ...frontend.warnings]) {
560
+ if (isAdvisoryLintIssue(finding)) {
561
+ warnings.push(finding);
562
+ }
563
+ else {
564
+ flagged.push(finding);
637
565
  }
638
566
  }
639
567
  }
640
568
  // ── Main ──────────────────────────────────────────────────────────────────────
641
569
  /**
642
- * The `akm`-adapter sweep: STASH_SUBDIRS walk + per-file `lintAssetFile` +
570
+ * The `akm`-adapter sweep: document-folder walk + per-file `lintAssetFile` +
643
571
  * the env dangerous-key pass. UNTOUCHED by the adapter-dispatch wiring above
644
572
  * (CRITICAL CONSTRAINT — the overwhelming majority of real bundles use `akm`,
645
573
  * and its findings / `--fix` behavior / exact `LintIssueType` codes are
@@ -651,24 +579,21 @@ function lintAkmSweep(stashRoot, extraStashRoots, cfg, sources, options) {
651
579
  const fix = options.fix === true;
652
580
  // #884: the dangling-edge repair writes too, so it clears the same
653
581
  // read-only gate `--fix` does.
654
- if (fix || options.pruneDanglingEdges === true)
582
+ if (fix || options.pruneDanglingEdges === true || options.fixMovedRefs === true)
655
583
  assertFixTargetWritable(stashRoot, sources);
656
584
  const fixed = [];
657
585
  const flagged = [];
658
586
  const warnings = [];
659
- const bundleSkip = bundleLintSkip(cfg, stashRoot);
660
- const roots = stalePathRoots(cfg, stashRoot);
661
- const dirsToScan = options.typeFilter ? STASH_SUBDIRS.filter((d) => d === options.typeFilter) : STASH_SUBDIRS;
587
+ const scope = lintScope(stashRoot, cfg, sources, options.readMoves ?? readRecordedMoves);
588
+ // Types left out of an untyped search are left out of the sweep unless `--type` names one.
589
+ const leftOut = new Set(defaultExcludedTypes(cfg).map((type) => stashDirFor(type)));
590
+ const dirsToScan = documentStashDirs().filter((d) => options.typeFilter ? d === options.typeFilter : !leftOut.has(d));
591
+ const markdownAssets = markdownAssetsByType(stashRoot);
662
592
  for (const subdir of dirsToScan) {
663
593
  const dirPath = path.join(stashRoot, subdir);
664
- // Tasks have their own `.yml` plus near-miss collector; every other AKM
665
- // subdir is Markdown.
666
- const files = subdir === "tasks"
667
- ? collectTaskFiles(dirPath)
668
- : subdir === "workflows"
669
- ? collectWorkflowFiles(dirPath)
670
- : collectMarkdownFiles(dirPath, true);
671
- let assetFiles = subdir === "workflows" ? files.filter((file) => path.basename(file).toLowerCase() !== "readme.md") : files;
594
+ // Tasks have their own `.yml` plus near-miss collector; every other type is Markdown, wherever it sits.
595
+ const files = subdir === "tasks" ? collectTaskFiles(dirPath) : (markdownAssets.get(subdir) ?? []);
596
+ let assetFiles = files;
672
597
  if (subdir === "workflows") {
673
598
  assetFiles = assetFiles.filter((file) => !isAkmRegistryCachePath(file));
674
599
  const ownership = resolveWorkflowLintOwnership(stashRoot, assetFiles);
@@ -702,12 +627,10 @@ function lintAkmSweep(stashRoot, extraStashRoots, cfg, sources, options) {
702
627
  if (isAkmRegistryCachePath(filePath))
703
628
  continue;
704
629
  lintSweepFile(filePath, path.relative(stashRoot, filePath), subdir, {
705
- stashRoot,
706
- extraStashRoots,
630
+ ...scope,
707
631
  fix,
632
+ fixMovedRefs: options.fixMovedRefs === true,
708
633
  pruneDanglingEdges: options.pruneDanglingEdges === true,
709
- stalePathRoots: roots,
710
- bundleSkip,
711
634
  }, { fixed, flagged, warnings });
712
635
  }
713
636
  }
@@ -773,7 +696,7 @@ async function lintFile(file, options, cfg) {
773
696
  ]);
774
697
  // Symlink-resolved, so a file's bundle-relative path is right however either was spelled.
775
698
  const realRoot = root ? fs.realpathSync(root) : undefined;
776
- const typeValues = STASH_SUBDIRS.join(", ");
699
+ const typeValues = documentTypes().join(", ");
777
700
  let subdir;
778
701
  if (root) {
779
702
  const sources = resolveSourceEntries(root, cfg);
@@ -785,7 +708,11 @@ async function lintFile(file, options, cfg) {
785
708
  return finishLint({ fixed: [], flagged: only(result.flagged), warnings: only(result.warnings) }, cfg, options, root);
786
709
  }
787
710
  // The type comes from where the file sits, as the bundle sweep decides it.
788
- const located = STASH_SUBDIRS.find((d) => relPath.split(path.sep)[0] === d);
711
+ const located = documentStashDirs().find((d) => relPath.split(path.sep)[0] === d);
712
+ const firstSegment = relPath.split(path.sep)[0] ?? "";
713
+ if (!located && typeForStashDir(firstSegment) !== undefined) {
714
+ throw new UsageError(`lint: "${relPath}" is a ${typeForStashDir(firstSegment)} asset, which lint does not read as a document.`, "INVALID_FLAG_VALUE");
715
+ }
789
716
  if (located && options.typeFilter && options.typeFilter !== located) {
790
717
  throw new UsageError(`lint: --type "${options.typeFilter}" does not match "${relPath}", which is a ${located} file in this bundle.`, "INVALID_FLAG_VALUE");
791
718
  }
@@ -793,7 +720,7 @@ async function lintFile(file, options, cfg) {
793
720
  if (!subdir) {
794
721
  throw new UsageError(`lint: "${relPath}" is not under a known asset directory; pass --type (${typeValues}).`, "MISSING_REQUIRED_ARGUMENT", "Example: akm lint ./nightly.yml --type tasks");
795
722
  }
796
- if (options.fix)
723
+ if (options.fix || options.fixMovedRefs)
797
724
  assertFixTargetWritable(root, sources);
798
725
  }
799
726
  else {
@@ -802,7 +729,7 @@ async function lintFile(file, options, cfg) {
802
729
  throw new UsageError(`lint: "${file}" is outside every bundle; pass --type (${typeValues}).`, "MISSING_REQUIRED_ARGUMENT", "Example: akm lint ./nightly.yml --type tasks");
803
730
  }
804
731
  }
805
- if (!STASH_SUBDIRS.includes(subdir)) {
732
+ if (documentFormatForStashDir(subdir) === undefined) {
806
733
  throw new UsageError(`lint: --type "${subdir}" is not recognized; valid types: ${typeValues}.`, "INVALID_FLAG_VALUE");
807
734
  }
808
735
  const name = path.basename(absFile);
@@ -812,21 +739,34 @@ async function lintFile(file, options, cfg) {
812
739
  }
813
740
  const sinks = { fixed: [], flagged: [], warnings: [] };
814
741
  lintSweepFile(absFile, realRoot ? path.relative(realRoot, absFile) : file, subdir, {
815
- stashRoot: root ?? path.dirname(absFile),
816
- extraStashRoots: root
817
- ? resolveSourceEntries(root, cfg)
818
- .map((s) => s.path)
819
- .filter((p) => p !== root && fs.existsSync(p))
820
- : [],
742
+ ...(root
743
+ ? lintScope(root, cfg, resolveSourceEntries(root, cfg), options.readMoves ?? readRecordedMoves)
744
+ : lintScope(path.dirname(absFile), cfg, [], options.readMoves ?? readRecordedMoves)),
821
745
  fix: options.fix === true,
746
+ fixMovedRefs: options.fixMovedRefs === true,
822
747
  pruneDanglingEdges: false,
823
- stalePathRoots: stalePathRoots(cfg, root ?? path.dirname(absFile)),
824
- bundleSkip: root ? bundleLintSkip(cfg, root) : undefined,
825
748
  // Outside a bundle there are no other assets to resolve refs or a derived stub against.
826
749
  lintSkip: root ? undefined : ["missing-ref", "orphaned-stub"],
827
750
  }, sinks);
828
751
  return finishLint(sinks, cfg, options, root);
829
752
  }
753
+ /**
754
+ * The findings for `content` as the text of the asset at `relPath` of the akm bundle at `root`, by the checks `akm lint`
755
+ * runs on that file. Nothing is read from or written to the file. `subdir` is the stash folder of the asset's type.
756
+ */
757
+ export function lintDocumentText(input) {
758
+ const cfg = input.config ?? loadConfig();
759
+ const { root } = input;
760
+ const sinks = { fixed: [], flagged: [], warnings: [] };
761
+ lintDocument(input.content, path.join(root, input.relPath), input.relPath, input.subdir, {
762
+ ...lintScope(root, cfg, resolveSourceEntries(root, cfg), input.readMoves ?? readRecordedMoves),
763
+ fix: false,
764
+ fixMovedRefs: false,
765
+ pruneDanglingEdges: false,
766
+ }, sinks);
767
+ const { flagged, warnings } = finishLint(sinks, cfg, {}, root);
768
+ return { flagged, warnings };
769
+ }
830
770
  /** The ref of an asset of the bundle at `root` by its bundle-relative `file`; undefined when `file` is not an asset path. */
831
771
  function refOfFile(root, file, cfg) {
832
772
  const type = typeForStashDir(file.split(/[\\/]/)[0] ?? "");
@@ -885,7 +825,7 @@ function finishLint(found, cfg, options, root) {
885
825
  * `commands/improve/preparation.ts`) or is a test that can `await` it.
886
826
  */
887
827
  export async function akmLint(options = {}) {
888
- if (options.rule !== undefined && (options.fix || options.pruneDanglingEdges)) {
828
+ if (options.rule !== undefined && (options.fix || options.pruneDanglingEdges || options.fixMovedRefs)) {
889
829
  throw new UsageError("lint: --rule lists findings; run it without --fix or --prune-dangling-edges.", "INVALID_FLAG_VALUE");
890
830
  }
891
831
  // Fail closed on a mistyped invocation (§24.2 "Lint" release gate): a
@@ -898,6 +838,9 @@ export async function akmLint(options = {}) {
898
838
  // cross-stash refs (e.g. referencing assets in dimm-city/agent-stash) are
899
839
  // not falsely flagged as missing-ref.
900
840
  const cfg = options.config ?? loadConfig();
841
+ // `--type` names a type or its folder; the sweep and the single-file path work on the folder.
842
+ if (options.typeFilter)
843
+ options = { ...options, typeFilter: documentStashDirFor(options.typeFilter) ?? options.typeFilter };
901
844
  if (options.file !== undefined)
902
845
  return lintFile(options.file, options, cfg);
903
846
  // The primary stash is the defaultBundle's path.
@@ -915,9 +858,9 @@ export async function akmLint(options = {}) {
915
858
  // to filter the walk to ZERO directories — a false-clean result on the
916
859
  // classic singular/plural typo ("workflow" for "workflows"). Non-akm
917
860
  // adapters keep their own type vocabularies (see lintViaAdapter).
918
- if (options.typeFilter && !STASH_SUBDIRS.includes(options.typeFilter)) {
919
- warn(`Warning: lint --type "${options.typeFilter}" is not a recognized akm stash subdirectory — ` +
920
- `valid types: ${STASH_SUBDIRS.join(", ")}. The whole bundle was validated.`);
861
+ if (options.typeFilter && documentFormatForStashDir(options.typeFilter) === undefined) {
862
+ warn(`Warning: lint --type "${options.typeFilter}" is not a recognized akm asset type — ` +
863
+ `valid types: ${documentTypes().join(", ")}. The whole bundle was validated.`);
921
864
  options = { ...options, typeFilter: undefined };
922
865
  }
923
866
  const found = lintAkmSweep(stashRoot, extraStashRoots, cfg, sources, options);
@@ -0,0 +1,69 @@
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
+ /**
5
+ * Refs the index recorded as moved (`akm index` pairs a file renamed or moved on disk with its old entry and appends a
6
+ * `moved` event) and the rewrite of links to them. `akm lint` reports a link to a moved ref as a `missing-ref` that
7
+ * carries the new ref, and `--fix` rewrites it: only a ref with a recorded move is ever rewritten.
8
+ */
9
+ import { rewritePathTokens } from "../../core/asset/ref-rewrite.js";
10
+ import { readEvents } from "../../core/events.js";
11
+ import { findFenceRegions } from "./markdown-insertion.js";
12
+ /** The recorded moves through akm's ordinary read-only connection to state.db (an absent database has none). */
13
+ export const readRecordedMoves = () => readEvents({ type: "moved" }, { readOnly: true }).events;
14
+ const conceptOf = (itemRef) => itemRef.slice(itemRef.indexOf("//") + 2);
15
+ const bundleOf = (itemRef) => itemRef.slice(0, itemRef.indexOf("//"));
16
+ /**
17
+ * The recorded moves, each old ref with the ref its asset has now (a later move re-keys the earlier events). `read` is
18
+ * called once, on the first question asked of the result, so a run with no ref that failed to resolve never reads them.
19
+ */
20
+ export function readMovedRefs(read) {
21
+ let loaded;
22
+ const load = () => {
23
+ loaded ??= loadMovedRefs(read());
24
+ return loaded;
25
+ };
26
+ return {
27
+ get concepts() {
28
+ return load().concepts;
29
+ },
30
+ target: (link) => load().target(link),
31
+ };
32
+ }
33
+ function loadMovedRefs(events) {
34
+ const current = new Map();
35
+ for (const event of events) {
36
+ const from = event.metadata?.from;
37
+ if (typeof from === "string" && event.ref !== undefined && event.ref !== from)
38
+ current.set(from, event.ref);
39
+ }
40
+ const byConcept = new Map();
41
+ for (const from of current.keys())
42
+ byConcept.set(conceptOf(from), [...(byConcept.get(conceptOf(from)) ?? []), from]);
43
+ return {
44
+ concepts: new Set(byConcept.keys()),
45
+ target(link) {
46
+ const written = link.split("#", 1)[0];
47
+ // A bare link names the one moved asset with that path; two bundles that moved one path leave it ambiguous.
48
+ const candidates = byConcept.get(written);
49
+ const from = written.includes("//") ? written : candidates?.length === 1 ? candidates[0] : undefined;
50
+ const to = from === undefined ? undefined : current.get(from);
51
+ if (from === undefined || to === undefined)
52
+ return undefined;
53
+ return { to, spelled: written.includes("//") || bundleOf(to) !== bundleOf(from) ? to : conceptOf(to) };
54
+ },
55
+ };
56
+ }
57
+ /**
58
+ * `raw` with each link of `spellings` (as written, without a fragment) rewritten to its new spelling, outside code
59
+ * fences, where a link is an example and not a reference.
60
+ */
61
+ export function rewriteMovedLinks(raw, spellings) {
62
+ const lines = raw.split("\n");
63
+ const fenced = new Set();
64
+ for (const { start, end } of findFenceRegions(lines))
65
+ for (let i = start; i <= end; i++)
66
+ fenced.add(i);
67
+ const spell = (bundleId, stem) => spellings.get(bundleId === undefined ? stem : `${bundleId}//${stem}`);
68
+ return lines.map((line, index) => (fenced.has(index) ? line : rewritePathTokens(line, spell).text)).join("\n");
69
+ }
@@ -0,0 +1,41 @@
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 fs from "node:fs";
5
+ import { isInLlmWiki } from "../../core/asset/llm-wiki-root.js";
6
+ import { stalePathRoots } from "../../core/asset/stale-path.js";
7
+ import { bundleLintSkip } from "./bundle-skip.js";
8
+ import { readMovedRefs } from "./moved-refs.js";
9
+ /** The root of each configured bundle by its id, for the checks that look a qualified ref up in the bundle it names. */
10
+ function bundleRootsOf(sources) {
11
+ return new Map(sources.flatMap((source) => (source.registryId ? [[source.registryId, source.path]] : [])));
12
+ }
13
+ /** Whether a bundle-relative file is inside an LLM Wiki of the bundle at `root`; each directory is probed once. */
14
+ export function llmWikiPredicate(root) {
15
+ const byDir = new Map();
16
+ return (relPath) => {
17
+ const dirs = relPath.split(/[\\/]/).slice(0, -1);
18
+ const key = dirs.join("/");
19
+ let inside = byDir.get(key);
20
+ if (inside === undefined) {
21
+ inside = isInLlmWiki(root, dirs);
22
+ byDir.set(key, inside);
23
+ }
24
+ return inside;
25
+ };
26
+ }
27
+ /**
28
+ * The scope of the configured bundle at `root` among the configured `sources` (none for a file outside every bundle).
29
+ * `readMoves` is how the caller reads the recorded moves.
30
+ */
31
+ export function lintScope(root, cfg, sources, readMoves) {
32
+ return {
33
+ stashRoot: root,
34
+ extraStashRoots: sources.map((source) => source.path).filter((p) => p !== root && fs.existsSync(p)),
35
+ bundleRoots: bundleRootsOf(sources),
36
+ moves: readMovedRefs(readMoves),
37
+ stalePathRoots: stalePathRoots(cfg, root),
38
+ bundleSkip: bundleLintSkip(cfg, root),
39
+ inLlmWiki: llmWikiPredicate(root),
40
+ };
41
+ }