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
@@ -56,10 +56,11 @@ import { assertTaskScheduleCronValid, assertTaskScheduleInputsSatisfyContract }
56
56
  import { parseTaskSource } from "../../../tasks/source/parse-task-source.js";
57
57
  import { taskSourceErrorDetail } from "../../../tasks/source-v3.js";
58
58
  import { checkWorkflowPlan, compileWorkflowSource } from "../../../workflows/compile.js";
59
+ import { ruleApplies } from "../../asset/lint-text.js";
59
60
  import { conceptIdForStashFile } from "../../asset/resolve-ref.js";
60
61
  import { isAkmRegistryCachePath, scanEnvKeyNames } from "../../common.js";
61
62
  /** Recommended `category` values for facts — `commands/lint/fact-linter.ts:9`. */
62
- const KNOWN_CATEGORIES = new Set(["personal", "team", "project", "convention", "meta"]);
63
+ export const KNOWN_CATEGORIES = new Set(["personal", "team", "project", "convention", "meta"]);
63
64
  /** Placeholder markers a workflow stub carries — `commands/lint/workflow-linter.ts:10`. */
64
65
  const PLACEHOLDER_STRINGS = ["Describe what this workflow accomplishes", "Example Workflow"];
65
66
  /** Inline suppression token — `commands/lint/env-key-rules.ts:138` (not exported there; reproduced verbatim). */
@@ -223,33 +224,61 @@ export async function skillDirectoryDiagnostics(relPath, seen, ctx, skillDirs =
223
224
  }
224
225
  return [];
225
226
  }
227
+ /** The path of the `<name>.derived.md` sibling of a memory at `memoryPath`. */
228
+ export function derivedSiblingPath(memoryPath) {
229
+ return `${memoryPath.replace(/\.md$/i, "")}.derived.md`;
230
+ }
231
+ const nameOrType = (allowed) => (i) => ruleApplies("missing-name-or-type", i.rules)
232
+ ? nameOrTypeDiagnostics(i.relPath, i.data, i.frontmatter, [allowed])
233
+ : [];
234
+ const envKeys = (i) => dangerousEnvKeyDiagnostics(i.type, i.relPath, i.raw);
226
235
  /**
227
- * The winning `type`'s per-type EXTRA validate checks (base checks run
228
- * separately in `akm-adapter.ts`). Async: memory's orphaned-stub sibling probe
229
- * routes through `ctx`.
236
+ * The one table from an akm type to its own checks (what the base checks do not cover). It is read-only: the
237
+ * `orphaned-stub` and `placeholder-stub` findings are reported as not fixed, and the caller that may delete the
238
+ * file (`akm lint --fix`) does so. Types with no entry (knowledge, lesson, script, skill, wiki, session) have the base
239
+ * checks only; a skill's directory check is `skillDirectoryDiagnostics`.
230
240
  */
231
- export async function perTypeValidateChecks(args) {
232
- const { type, relPath, raw, data, frontmatter, body, ext, ctx } = args;
233
- switch (type) {
234
- case "command":
235
- return nameOrTypeDiagnostics(relPath, data, frontmatter, ["command"]);
236
- case "agent":
237
- return nameOrTypeDiagnostics(relPath, data, frontmatter, ["agent"]);
238
- case "fact":
239
- return factDiagnostics(relPath, data);
240
- case "task":
241
- return taskDiagnostics(relPath, raw);
242
- case "workflow":
243
- return ext === ".md" ? workflowDiagnostics(relPath, raw, body) : [];
244
- case "memory":
245
- return memoryDiagnostics(relPath, data, body, ctx);
246
- case "env":
247
- case "secret":
248
- return dangerousEnvKeyDiagnostics(type, relPath, raw);
249
- default:
250
- // knowledge / lesson / script / wiki / session → DefaultLinter (base only).
251
- return [];
252
- }
241
+ const TYPE_CHECKS = new Map([
242
+ ["command", nameOrType("command")],
243
+ ["agent", nameOrType("agent")],
244
+ ["fact", (i) => (ruleApplies("missing-category", i.rules) ? factDiagnostics(i.relPath, i.data) : [])],
245
+ ["task", (i) => (ruleApplies("invalid-task-yaml", i.rules) ? taskDiagnostics(i.relPath, i.raw) : [])],
246
+ [
247
+ "workflow",
248
+ (i) => {
249
+ const placeholder = i.ext === ".md" && ruleApplies("placeholder-stub", i.rules) ? matchWorkflowPlaceholder(i.body) : null;
250
+ return placeholder === null
251
+ ? []
252
+ : [{ file: i.relPath, issue: "placeholder-stub", detail: `placeholder text: "${placeholder}"`, fixed: false }];
253
+ },
254
+ ],
255
+ [
256
+ "memory",
257
+ (i) => ruleApplies("orphaned-stub", i.rules) && memoryOrphanStubApplies(i.data, i.body) && !i.derivedSiblingExists
258
+ ? [{ file: i.relPath, issue: "orphaned-stub", detail: ORPHANED_STUB_DETAIL, fixed: false }]
259
+ : [],
260
+ ],
261
+ ["env", envKeys],
262
+ ["secret", envKeys],
263
+ ]);
264
+ /** The checks of the file's own type. */
265
+ export function perTypeChecks(input) {
266
+ return (input.type === undefined ? undefined : TYPE_CHECKS.get(input.type))?.(input) ?? [];
267
+ }
268
+ /** Everything an adapter's `validate` reports of the file's own type: its checks, then its frontend's findings and advisories. */
269
+ export function perTypeDiagnostics(input, parsePath) {
270
+ const frontend = perTypeFrontend(input, parsePath);
271
+ return [...perTypeChecks(input), ...frontend.errors, ...frontend.warnings];
272
+ }
273
+ /**
274
+ * The parse+compile of a file whose type has a workflow frontend (a Markdown workflow): fatal findings, and the
275
+ * advisories that are routed apart from them. Other types have none. `parsePath` is the source identity handed to the
276
+ * compiler (the adapter passes the bundle-relative path; the CLI passes the absolute path).
277
+ */
278
+ export function perTypeFrontend(input, parsePath) {
279
+ return input.type === "workflow" && input.ext === ".md"
280
+ ? workflowFrontendDiagnostics(input.relPath, input.raw, parsePath)
281
+ : { errors: [], warnings: [] };
253
282
  }
254
283
  /** FactLinter extra check (`fact-linter.ts:23-44`). */
255
284
  export function factDiagnostics(relPath, data) {
@@ -407,26 +436,6 @@ export function workflowFrontendDiagnostics(relPath, raw, parsePath) {
407
436
  }
408
437
  return { errors, warnings };
409
438
  }
410
- /**
411
- * WorkflowLinter extra checks (`workflow-linter.ts:22-79`), READ-ONLY:
412
- * `placeholder-stub` is NEVER deleted here (validate MUST NOT write) — emitted
413
- * as a non-fixable Diagnostic. `invalid-workflow-structure` parses and compiles
414
- * the whole `raw` through the unified workflow frontend.
415
- */
416
- function workflowDiagnostics(relPath, raw, body) {
417
- const diagnostics = [];
418
- const placeholderMatch = matchWorkflowPlaceholder(body);
419
- if (placeholderMatch) {
420
- diagnostics.push({
421
- file: relPath,
422
- issue: "placeholder-stub",
423
- detail: `placeholder text: "${placeholderMatch}"`,
424
- fixed: false,
425
- });
426
- }
427
- diagnostics.push(...workflowStructureDiagnostics(relPath, raw, relPath));
428
- return diagnostics;
429
- }
430
439
  /** The non-fixable orphaned-stub finding detail (`memory-linter.ts` no-fix branch). Shared with the live linter. */
431
440
  export const ORPHANED_STUB_DETAIL = "inferenceProcessed stub with no derived sibling";
432
441
  /**
@@ -440,18 +449,3 @@ export const ORPHANED_STUB_DETAIL = "inferenceProcessed stub with no derived sib
440
449
  export function memoryOrphanStubApplies(data, body) {
441
450
  return data.inferenceProcessed === true && body.trim().length < 100;
442
451
  }
443
- /**
444
- * MemoryLinter extra check (`memory-linter.ts:19-65`), READ-ONLY: the
445
- * `orphaned-stub` DELETE fix is dropped (validate MUST NOT write) — emitted as
446
- * a non-fixable Diagnostic. The `<name>.derived.md` sibling probe routes
447
- * through `ctx.readFile` (overlay), not `fs.existsSync`.
448
- */
449
- async function memoryDiagnostics(relPath, data, body, ctx) {
450
- if (!memoryOrphanStubApplies(data, body))
451
- return [];
452
- const derivedPath = `${relPath.replace(/\.md$/, "")}.derived.md`;
453
- const sibling = await ctx.readFile(derivedPath);
454
- if (sibling !== null)
455
- return [];
456
- return [{ file: relPath, issue: "orphaned-stub", detail: ORPHANED_STUB_DETAIL, fixed: false }];
457
- }
@@ -10,7 +10,7 @@
10
10
  *
11
11
  * Reuses the akm adapter's per-type workflow checks (shared base checks +
12
12
  * `placeholder-stub` + `invalid-workflow-structure`). Delegates to the SAME
13
- * `perTypeValidateChecks` / `runBaseValidateChecks` the `akm` adapter uses, so
13
+ * `perTypeDiagnostics` / `createBaseChecker` the `akm` adapter uses, so
14
14
  * workflow validation has one home.
15
15
  *
16
16
  * Conformance oracle (authored, DO NOT modify): fixture
@@ -21,8 +21,8 @@ import fs from "node:fs";
21
21
  import path from "node:path";
22
22
  import { parseFrontmatter } from "../../asset/frontmatter.js";
23
23
  import { toPosix } from "../../common.js";
24
- import { perTypeValidateChecks } from "./akm-lint.js";
25
- import { hashContent, nonEmptyString, readTags, runBaseValidateChecks } from "./shared.js";
24
+ import { perTypeDiagnostics } from "./akm-lint.js";
25
+ import { createBaseChecker, hashContent, nonEmptyString, parseForValidate, readTags } from "./shared.js";
26
26
  /** A native workflow bundle is single-component; its one component is `main`. */
27
27
  const COMPONENT_ID = "main";
28
28
  /** The authoritative workflow source format. */
@@ -81,6 +81,7 @@ function recognize(c, file) {
81
81
  }
82
82
  async function validate(c, changes, ctx) {
83
83
  const diagnostics = [];
84
+ const { check, rulesFor } = createBaseChecker(c.root, ctx);
84
85
  for (const change of changes) {
85
86
  if (change.op === "delete")
86
87
  continue;
@@ -93,15 +94,9 @@ async function validate(c, changes, ctx) {
93
94
  const relPath = toPosix(change.path);
94
95
  if (!isWorkflowFile(raw))
95
96
  continue;
96
- const p = parseFrontmatter(raw);
97
- const parsed = {
98
- data: p.data,
99
- content: p.content,
100
- frontmatter: p.frontmatter,
101
- bodyStartLine: p.bodyStartLine,
102
- };
103
- diagnostics.push(...(await runBaseValidateChecks(relPath, parsed, c.root, ctx)));
104
- diagnostics.push(...(await perTypeValidateChecks({
97
+ const parsed = parseForValidate(raw);
98
+ diagnostics.push(...check(relPath, parsed));
99
+ diagnostics.push(...perTypeDiagnostics({
105
100
  type: "workflow",
106
101
  relPath,
107
102
  raw,
@@ -109,8 +104,9 @@ async function validate(c, changes, ctx) {
109
104
  frontmatter: parsed.frontmatter,
110
105
  body: parsed.content,
111
106
  ext,
112
- ctx,
113
- })));
107
+ rules: rulesFor(relPath),
108
+ derivedSiblingExists: false,
109
+ }, relPath));
114
110
  }
115
111
  return diagnostics;
116
112
  }
@@ -46,8 +46,8 @@
46
46
  * (a `raw/` source not cited by any page's `sources:`), `missing-description`
47
47
  * (a page with no description), and `broken-source` (a page `sources:` entry
48
48
  * with no matching raw file). Broken xrefs are TOLERATED (warning, non-blocking).
49
- * The shared `runBaseValidateChecks` (unquoted-colon / missing-updated
50
- * / stale-path / missing-ref) is NOT run: wiki files never carry an `updated`
49
+ * The shared base checks (`createBaseChecker`: unquoted-colon / missing-updated
50
+ * / stale-path / missing-ref) are NOT run: wiki files never carry an `updated`
51
51
  * field, so `missing-updated` would fire on every page/reserved file and
52
52
  * contradict the lint golden's clean result — the native checks are the wiki's
53
53
  * complete validation surface. The `orphan` issue CODE is APPROVED but the
@@ -67,10 +67,10 @@
67
67
  * runtime dep). Verified: `bun scripts/lint-import-cycles.ts` reports 0 cycle
68
68
  * participants with this file present.
69
69
  */
70
- import fs from "node:fs";
71
70
  import path from "node:path";
72
71
  import { parse as parseYaml } from "yaml";
73
72
  import { parseFrontmatter, parseFrontmatterBlock } from "../../asset/frontmatter.js";
73
+ import { LLM_WIKI_PAGES_DIR, looksLikeLlmWikiRoot } from "../../asset/llm-wiki-root.js";
74
74
  import { markdownLinkTargets } from "../../asset/markdown-link-targets.js";
75
75
  import { toPosix } from "../../common.js";
76
76
  import { hashContent, nonEmptyString } from "./shared.js";
@@ -84,8 +84,6 @@ const DEFAULT_PAGE_KIND = "note";
84
84
  const RESERVED_ROOT_FILES = new Set(["schema.md", "index.md", "log.md"]);
85
85
  /** Content subdirectory holding immutable ingested sources. */
86
86
  const RAW_SUBDIR = "raw";
87
- /** Content subdirectory holding agent-authored pages. */
88
- const PAGES_SUBDIR = "pages";
89
87
  /** POSIX-normalize separators. */
90
88
  /** conceptId = component-root-relative path minus `.md`. */
91
89
  function conceptIdOf(relPath) {
@@ -251,7 +249,7 @@ function recognize(c, file) {
251
249
  return null;
252
250
  const head = firstSegment(relPath);
253
251
  const isRaw = head === RAW_SUBDIR && relPath.includes("/");
254
- const isPage = head === PAGES_SUBDIR && relPath.includes("/");
252
+ const isPage = head === LLM_WIKI_PAGES_DIR && relPath.includes("/");
255
253
  // Only `raw/` sources and `pages/` pages are wiki assets. Everything else
256
254
  // (root README, stray root `.md`, other dirs) is abstained on.
257
255
  if (!isRaw && !isPage)
@@ -305,7 +303,7 @@ async function validate(c, changes, ctx) {
305
303
  continue; // reserved files are not concepts — no page checks
306
304
  const head = firstSegment(relPath);
307
305
  const isRaw = head === RAW_SUBDIR && relPath.includes("/");
308
- const isPage = head === PAGES_SUBDIR && relPath.includes("/");
306
+ const isPage = head === LLM_WIKI_PAGES_DIR && relPath.includes("/");
309
307
  if (!isRaw && !isPage)
310
308
  continue;
311
309
  items.push({
@@ -396,16 +394,7 @@ export const llmWikiAdapter = {
396
394
  return ["."];
397
395
  },
398
396
  /** Install-time probe (§1.2): a root is an LLM Wiki when it has a root `schema.md` AND a `pages/` directory. */
399
- looksLikeRoot(root) {
400
- try {
401
- if (!fs.existsSync(path.join(root, "schema.md")))
402
- return false;
403
- return fs.statSync(path.join(root, PAGES_SUBDIR)).isDirectory();
404
- }
405
- catch {
406
- return false;
407
- }
408
- },
397
+ looksLikeRoot: looksLikeLlmWikiRoot,
409
398
  };
410
399
  // Exported pure helpers for the conformance test.
411
400
  export { resolveBodyLinks, resolvePageLinks, resolveSources, resolveXref };
@@ -32,7 +32,7 @@ import { parseFrontmatter } from "../../asset/frontmatter.js";
32
32
  import { markdownLinkTargets } from "../../asset/markdown-link-targets.js";
33
33
  import { isScratchPath } from "../../asset/scratch.js";
34
34
  import { isRecord, toPosix } from "../../common.js";
35
- import { hashContent, nonEmptyString, RESERVED_FILES, readTags, runBaseValidateChecks } from "./shared.js";
35
+ import { createBaseChecker, hashContent, nonEmptyString, parseForValidate, RESERVED_FILES, readTags } from "./shared.js";
36
36
  /** v0.2 frontmatter keys consumed into first-class fields below (§0.1) — excluded from the generic `documentJson` extras fold alongside the v0.1 five, so nothing is duplicated between a first-class field and the opaque extras bag. */
37
37
  const CONSUMED_FRONTMATTER_KEYS = [
38
38
  "type",
@@ -272,6 +272,7 @@ function recognize(c, file) {
272
272
  }
273
273
  async function validate(c, changes, ctx) {
274
274
  const diagnostics = [];
275
+ const { check } = createBaseChecker(c.root, ctx);
275
276
  for (const change of changes) {
276
277
  if (change.op === "delete")
277
278
  continue;
@@ -281,15 +282,10 @@ async function validate(c, changes, ctx) {
281
282
  const relPath = toPosix(change.path);
282
283
  const fileName = relPath.split("/").pop() ?? relPath;
283
284
  const reserved = isReservedFileName(fileName);
284
- const parsed = parseFrontmatter(raw);
285
+ const parsed = parseForValidate(raw);
285
286
  // Base checks shared with native AKM formats. OKF's timestamp is optional,
286
- // so the AKM-specific freshness diagnostic is removed unconditionally.
287
- const base = await runBaseValidateChecks(relPath, parsed, c.root, ctx);
288
- for (const diag of base) {
289
- if (diag.issue === "missing-updated")
290
- continue;
291
- diagnostics.push(diag);
292
- }
287
+ // so the AKM-specific freshness rule does not apply.
288
+ diagnostics.push(...check(relPath, parsed, ["missing-updated"]));
293
289
  if (reserved)
294
290
  continue; // reserved files are not concepts — no type / link checks
295
291
  // §5: `missing-type` is INFO (not an error) — never blocks.
@@ -3,56 +3,22 @@
3
3
  // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
4
  /**
5
5
  * Shared helpers for the concrete `BundleAdapter` implementations under
6
- * `src/core/adapter/adapters/` — akm 0.9.0 chunk-2, WI-A (the `okf` adapter).
6
+ * `src/core/adapter/adapters/`.
7
7
  *
8
- * ── Cycle-safety (chunk-2 "cycle-safety watch") ──
8
+ * ── Base checks ──
9
9
  *
10
- * The base-check logic below is a PORT, not an import, of
11
- * `src/commands/lint/base-linter.ts`'s `runBaseChecks` (the 4 checks every
12
- * non-`DefaultLinter` class inherits: unquoted-colon, missing-updated,
13
- * stale-path, missing-ref). Importing `base-linter.ts` directly would add a
14
- * new `src/core/adapter` -> `src/commands/lint` edge; `base-linter.ts`
15
- * itself imports `core/asset/asset-spec.ts` (a baseline cycle participant,
16
- * `scripts/lint-import-cycles.ts`) and `commands/lint/markdown-insertion.ts`
17
- * — pulling either into `src/core/adapter/`'s import graph risks adding a
18
- * 19th cycle participant against the zero-tolerance ratchet (baseline 18).
19
- * Per the brief's explicit instruction ("copy the pure logic to a leaf ...
20
- * do NOT use dynamic import to launder"), the pure regex/string logic is
21
- * duplicated here, adapted to `Diagnostic`/`ValidateContext`. Verified
22
- * cycle-safe: `bun scripts/lint-import-cycles.ts` stays at 18 with this file
23
- * present (see the WI-A report).
24
- *
25
- * ── What did NOT get ported ──
26
- *
27
- * `bundle-adapter.ts`'s own doc comment is explicit that `validate()`
28
- * "MUST NOT write and MUST NOT read the live filesystem" — reads go through
29
- * `ValidateContext`, which serves the run snapshot WITH pending changes
30
- * overlaid. `stale-path`'s legacy check called `fs.existsSync` directly on
31
- * arbitrary absolute paths found in content; here it goes through
32
- * `ctx.readFile(candidate)` instead (a `null` result means "does not
33
- * exist") — the interface-compliant translation of the same check, not a
34
- * behavior change for any path that genuinely exists or doesn't.
35
- *
36
- * The `refs:`-frontmatter-array authoritative-list carve-out (session-
37
- * checkpoint memories; `base-linter.ts`'s `extractFrontmatterRefs`) is NOT
38
- * ported here — it is memory/session-specific and no OKF concept uses it. A
39
- * later memory/note adapter should extend `extractProseRefTokens`'s caller with
40
- * that carve-out when it ports memory/session.
41
- *
42
- * The fence-strip (`stripFencedBlocksSimple` below) is a simplified,
43
- * same-INTENT reimplementation of `markdown-insertion.ts`'s
44
- * `findFenceRegions` (which is also table/HTML-region aware, because it
45
- * additionally powers safe line INSERTION, a concern this module doesn't
46
- * have) — not byte-identical on every edge case, but sufficient for "don't
47
- * flag a ref/path inside a ``` example," which is the only thing this
48
- * module needs the strip for.
10
+ * The base asset checks (unquoted-colon, missing-updated, stale-path, missing-ref,
11
+ * redacted-content) have one implementation, `runBaseChecks`
12
+ * (`src/commands/lint/base-linter.ts`), and one decision on whether a rule applies to a
13
+ * file, `ruleApplies` (`core/asset/lint-text.ts`). {@link createBaseChecker} is an
14
+ * adapter's way in: it hands `runBaseChecks` the file's text and the bundle's scope and
15
+ * returns what it finds. `validate` never writes, so it never asks for a fix.
49
16
  */
50
17
  import { createHash } from "node:crypto";
51
- import { BUNDLE_REF_RE } from "../../asset/asset-ref.js";
18
+ import path from "node:path";
19
+ import { runBaseChecks } from "../../../commands/lint/base-linter.js";
20
+ import { lintScope } from "../../../commands/lint/scope.js";
52
21
  import { parseFrontmatter } from "../../asset/frontmatter.js";
53
- import { checkUnquotedDescriptionColon } from "../../asset/frontmatter-lint.js";
54
- import { isSkillPath } from "../../asset/lint-text.js";
55
- import { findStalePaths, stalePathRoots } from "../../asset/stale-path.js";
56
22
  import { toPosix } from "../../common.js";
57
23
  import { loadConfig } from "../../config/config.js";
58
24
  // ── Small pure helpers, reused across the concrete adapters ──────────────────
@@ -76,175 +42,61 @@ export function readTags(value) {
76
42
  }
77
43
  /** Reserved files (case-insensitive) every concrete adapter recognizes but never indexes as a concept. */
78
44
  export const RESERVED_FILES = new Set(["index.md", "log.md"]);
79
- // ── Base validate checks (port of `BaseLinter.runBaseChecks`) ────────────────
80
- function checkMissingUpdated(relPath, data, frontmatterText) {
81
- return frontmatterText !== null && !("updated" in data) && !isSkillPath(relPath);
45
+ /** The result of `parseFrontmatter(raw)`, with the text it parsed. */
46
+ export function parseForValidate(raw) {
47
+ const { data, content, frontmatter, bodyStartLine } = parseFrontmatter(raw);
48
+ return { raw, data, content, frontmatter, bodyStartLine };
82
49
  }
83
- /** See file header: same intent as `markdown-insertion.ts#findFenceRegions`, not byte-identical. */
84
- function stripFencedBlocksSimple(body) {
85
- const lines = body.split(/\r?\n/);
86
- let inFence = false;
87
- const out = lines.map((line) => {
88
- if (/^\s*```/.test(line)) {
89
- const wasInFence = inFence;
90
- inFence = !inFence;
91
- return wasInFence || inFence ? "" : line;
92
- }
93
- return inFence ? "" : line;
50
+ /** What a context with no way to read recorded moves offers. */
51
+ const noMoves = () => [];
52
+ /** The base checks for the files of the bundle at `componentRoot`, among the bundles and with the settings `ctx` names (the settings are read once, here, only when `ctx` carries none). The scope (other bundles, moved refs, stale-path roots, LLM Wikis) is read once. */
53
+ export function createBaseChecker(componentRoot, ctx) {
54
+ const scope = lintScope(componentRoot, ctx.config ?? loadConfig(), ctx.sources ?? [], ctx.readMoves ?? noMoves);
55
+ const rulesFor = (relPath, skip = []) => ({
56
+ relPath,
57
+ llmWiki: scope.inLlmWiki(relPath),
58
+ skip: [...skip, ...scope.bundleSkip(relPath)],
94
59
  });
95
- return out.join("\n");
96
- }
97
- // Prose refs use the canonical `BUNDLE_REF_RE` (`core/asset/asset-ref.ts`): the 0.9.0 FULLY-QUALIFIED
98
- // `<bundle>//<concept-id>[#fragment]` form ONLY. A bare short conceptId in prose is NOT a ref, so it is never flagged
99
- // here (it is a ref only in the ref-LIST channels — {@link refTokenFromListValue}).
100
- /**
101
- * A conceptId that is a lint false positive rather than a real ref — mirrors the
102
- * `isNonRefName` guards `base-linter.ts` applies deep in its existence check:
103
- * template placeholders (`skills/<name>`) and degenerate/incomplete tokens.
104
- */
105
- function isNonRefConceptId(conceptId) {
106
- const id = conceptId.split("#", 1)[0]; // drop the export #fragment selector
107
- if (!id || id.length <= 1 || id === "**")
108
- return true;
109
- if (id.includes("<"))
110
- return true; // template placeholder, e.g. `skills/<name>`
111
- return false;
112
- }
113
- /**
114
- * Extract the fully-qualified `bundle//conceptId` refs from PROSE — the flipped
115
- * `base-linter.ts#checkMissingRefs` semantics (`BUNDLE_REF_RE`, qualified-only;
116
- * bare short conceptIds are NOT refs, D-R3). Fenced code is stripped first so
117
- * example refs inside ``` are not flagged; shell-substitution (`$(`/`${`) and
118
- * ACP (`::`) false positives are dropped.
119
- */
120
- function extractProseRefTokens(text) {
121
- const re = new RegExp(BUNDLE_REF_RE.source, BUNDLE_REF_RE.flags);
122
- const scanBody = stripFencedBlocksSimple(text);
123
- const refs = [];
124
- let match;
125
- // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic regex loop
126
- while ((match = re.exec(scanBody)) !== null) {
127
- const token = match[1];
128
- if (token.includes("$(") || token.includes("${") || token.includes("::"))
129
- continue;
130
- if (isNonRefConceptId(token.slice(token.indexOf("//") + 2)))
131
- continue;
132
- refs.push(token);
133
- }
134
- return refs;
135
- }
136
- /**
137
- * Recognize a single frontmatter ref-LIST value (`xrefs:`/`supersededBy:`/
138
- * `contradictedBy:`) as a whole ref — the flipped `base-linter.ts#
139
- * checkMissingRefsInList` semantics. Unlike prose, a bare short `conceptId` IS a
140
- * ref here (the value's whole purpose is to name one asset). Returns the ref
141
- * token, or `null` for a false positive or a legacy `origin//type:name` value
142
- * (the colon-grammar is retired — D-R3).
143
- */
144
- function refTokenFromListValue(value) {
145
- const trimmed = value.trim();
146
- if (!trimmed || trimmed.includes("$(") || trimmed.includes("${") || trimmed.includes("::"))
147
- return null;
148
- const boundary = trimmed.indexOf("//");
149
- // Qualified `bundle//conceptId`: a colon in the tail marks a legacy/remote
150
- // `origin//type:name` — not the 0.9.0 grammar — so skip it. Un-prefixed values
151
- // are a 0.9.0 short conceptId; a colon there is likewise the retired grammar.
152
- const conceptId = boundary >= 0 ? trimmed.slice(boundary + 2) : trimmed;
153
- if (conceptId.includes(":") || isNonRefConceptId(conceptId))
154
- return null;
155
- return trimmed;
156
- }
157
- const XREF_FRONTMATTER_KEYS = ["xrefs", "supersededBy", "contradictedBy"];
158
- function readRefStringOrArray(value) {
159
- if (typeof value === "string") {
160
- const trimmed = value.trim();
161
- return trimmed ? [trimmed] : null;
162
- }
163
- if (!Array.isArray(value))
164
- return null;
165
- const out = value.filter((v) => typeof v === "string" && v.trim().length > 0).map((v) => v.trim());
166
- return out.length > 0 ? out : null;
167
- }
168
- /**
169
- * Port of `BaseLinter.runBaseChecks`, adapted to the read-only
170
- * `ValidateContext`/`Diagnostic` shapes. Reproduces
171
- * unquoted-colon / missing-updated / stale-path / missing-ref for ONE file's
172
- * already-parsed content.
173
- *
174
- * `fixed` is always `false`: `BundleAdapter.validate` MUST NOT write the
175
- * filesystem, so there is no fix-apply mechanism at this layer — a documented,
176
- * intentional behavior narrowing from the legacy `--fix`-capable linter.
177
- *
178
- * `componentRoot` is `BundleComponent.root` — used only for the stale-path
179
- * "portable form" hint (mirrors legacy `ctx.stashRoot`-relative substitution;
180
- * no I/O).
181
- */
182
- export async function runBaseValidateChecks(relPath, parsed, componentRoot, ctx) {
183
- const diagnostics = [];
184
- const { data, content: body, frontmatter, bodyStartLine } = parsed;
185
- const unquotedColonDetail = checkUnquotedDescriptionColon(frontmatter);
186
- if (unquotedColonDetail) {
187
- diagnostics.push({ file: relPath, issue: "unquoted-colon", detail: unquotedColonDetail, fixed: false });
188
- }
189
- if (checkMissingUpdated(relPath, data, frontmatter)) {
190
- diagnostics.push({
191
- file: relPath,
192
- issue: "missing-updated",
193
- detail: "no updated field in frontmatter",
194
- fixed: false,
195
- });
196
- }
197
- const roots = stalePathRoots(loadConfig(), componentRoot);
198
- const stale = [
199
- ...(frontmatter ? findStalePaths(frontmatter, 2, roots, componentRoot) : []),
200
- ...findStalePaths(body, bodyStartLine, roots, componentRoot),
201
- ];
202
- for (const finding of stale)
203
- diagnostics.push({ file: relPath, issue: "stale-path", fixed: false, ...finding });
204
- for (const ref of extractProseRefTokens(body)) {
205
- const { exists } = await ctx.resolveRef(ref);
206
- if (!exists)
207
- diagnostics.push({ file: relPath, issue: "missing-ref", detail: `missing ref: ${ref}`, fixed: false });
208
- }
209
- if (frontmatter !== null) {
210
- for (const key of XREF_FRONTMATTER_KEYS) {
211
- const values = readRefStringOrArray(data[key]);
212
- if (values === null)
213
- continue;
214
- for (const value of values) {
215
- const ref = refTokenFromListValue(value);
216
- if (ref === null)
217
- continue;
218
- const { exists } = await ctx.resolveRef(ref);
219
- if (!exists) {
220
- diagnostics.push({
221
- file: relPath,
222
- issue: "missing-ref",
223
- detail: `missing ref: ${ref} (frontmatter ${key})`,
224
- fixed: false,
225
- });
226
- }
227
- }
228
- }
229
- }
230
- return diagnostics;
60
+ return {
61
+ rulesFor,
62
+ check: (relPath, parsed, skip) => {
63
+ const { llmWiki, skip: lintSkip } = rulesFor(relPath, skip);
64
+ return runBaseChecks({
65
+ filePath: path.join(componentRoot, relPath),
66
+ relPath,
67
+ raw: parsed.raw,
68
+ data: parsed.data,
69
+ body: parsed.content,
70
+ frontmatter: parsed.frontmatter,
71
+ bodyStartLine: parsed.bodyStartLine,
72
+ fix: false,
73
+ stashRoot: scope.stashRoot,
74
+ stalePathRoots: scope.stalePathRoots,
75
+ extraStashRoots: scope.extraStashRoots,
76
+ bundleRoots: scope.bundleRoots,
77
+ moves: scope.moves,
78
+ llmWiki,
79
+ lintSkip,
80
+ });
81
+ },
82
+ };
231
83
  }
232
84
  /**
233
85
  * Shared per-change loop: for every non-delete change with readable content,
234
- * parse frontmatter and run {@link runBaseValidateChecks}. Adapters with extra
235
- * per-type checks (e.g. `okf`'s missing-type / OKF-link warnings) run their own
236
- * loop and call {@link runBaseValidateChecks} directly instead.
86
+ * parse frontmatter and run the base checks. Adapters with extra per-type checks
87
+ * (e.g. `okf`'s missing-type / OKF-link warnings) run their own loop and call
88
+ * {@link createBaseChecker} directly instead.
237
89
  */
238
90
  export async function validateChangesWithBaseChecks(c, changes, ctx) {
239
91
  const diagnostics = [];
92
+ const { check } = createBaseChecker(c.root, ctx);
240
93
  for (const change of changes) {
241
94
  if (change.op === "delete")
242
95
  continue;
243
96
  const raw = change.after ?? (await ctx.readFile(change.path));
244
97
  if (typeof raw !== "string")
245
98
  continue;
246
- const parsed = parseFrontmatter(raw);
247
- diagnostics.push(...(await runBaseValidateChecks(toPosix(change.path), parsed, c.root, ctx)));
99
+ diagnostics.push(...check(toPosix(change.path), parseForValidate(raw)));
248
100
  }
249
101
  return diagnostics;
250
102
  }
@@ -51,7 +51,7 @@ import { parseFrontmatter } from "../../asset/frontmatter.js";
51
51
  import { toPosix } from "../../common.js";
52
52
  import { executionDefaultsFromFrontmatter, renderMarkdownExecutionSource } from "../execution-source.js";
53
53
  import { skillDirectoryDiagnostics } from "./akm-lint.js";
54
- import { hashContent, nonEmptyString, RESERVED_FILES, readTags, runBaseValidateChecks } from "./shared.js";
54
+ import { createBaseChecker, hashContent, nonEmptyString, parseForValidate, RESERVED_FILES, readTags } from "./shared.js";
55
55
  /** The canonical (plural) subdir spellings writes normalize to (open-question-6). */
56
56
  const CANONICAL_COMMAND_DIR = "commands";
57
57
  const CANONICAL_AGENT_DIR = "agents";
@@ -166,6 +166,7 @@ function nameOrSignalDiagnostics(type, relPath, data, body) {
166
166
  export async function validateToolDir(layout, c, changes, ctx) {
167
167
  const diagnostics = [];
168
168
  const seenSkillDirs = new Set();
169
+ const { check } = createBaseChecker(c.root, ctx);
169
170
  for (const change of changes) {
170
171
  if (change.op === "delete")
171
172
  continue;
@@ -182,7 +183,7 @@ export async function validateToolDir(layout, c, changes, ctx) {
182
183
  if (cls === null)
183
184
  continue;
184
185
  if (cls.type === "instruction") {
185
- diagnostics.push(...(await runBaseValidateChecks(relPath, parseFrontmatter(raw), c.root, ctx)));
186
+ diagnostics.push(...check(relPath, parseForValidate(raw)));
186
187
  }
187
188
  else if (cls.type === "command" || cls.type === "agent") {
188
189
  const parsed = parseFrontmatter(raw);