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
@@ -29,7 +29,7 @@ import path from "node:path";
29
29
  import { parse as parseYaml } from "yaml";
30
30
  import { parseFrontmatter, parseFrontmatterBlock } from "../../asset/frontmatter.js";
31
31
  import { toPosix } from "../../common.js";
32
- import { hashContent, nonEmptyString, runBaseValidateChecks } from "./shared.js";
32
+ import { createBaseChecker, hashContent, nonEmptyString, parseForValidate } from "./shared.js";
33
33
  /** A snapshot bundle is single-component; its one component is `main`. */
34
34
  const COMPONENT_ID = "main";
35
35
  /** The crawl page root the snapshot writer materializes pages under. */
@@ -104,6 +104,7 @@ function recognize(c, file) {
104
104
  }
105
105
  async function validate(c, changes, ctx) {
106
106
  const diagnostics = [];
107
+ const { check } = createBaseChecker(c.root, ctx);
107
108
  for (const change of changes) {
108
109
  if (change.op === "delete")
109
110
  continue;
@@ -112,10 +113,9 @@ async function validate(c, changes, ctx) {
112
113
  continue;
113
114
  if (!isSnapshotPage(change.path))
114
115
  continue;
115
- const base = await runBaseValidateChecks(toPosix(change.path), parseFrontmatter(raw), c.root, ctx);
116
116
  // A read-only crawl mirror carries `fetchedAt` provenance, never an `updated`
117
- // field — so `missing-updated` is not a defect on a snapshot page.
118
- diagnostics.push(...base.filter((d) => d.issue !== "missing-updated"));
117
+ // field — so the `missing-updated` rule does not apply to a snapshot page.
118
+ diagnostics.push(...check(toPosix(change.path), parseForValidate(raw), ["missing-updated"]));
119
119
  }
120
120
  return diagnostics;
121
121
  }
@@ -15,15 +15,10 @@
15
15
  * done up to now, see e.g. `tests/core/adapter/okf-adapter.test.ts`'s
16
16
  * `overlayCtx`/`diskCtx`).
17
17
  *
18
- * The two production callers wired onto this factory:
19
- * - `akm lint`'s non-akm adapter dispatch (`commands/lint/index.ts`) — a
20
- * plain sweep with NO pending changes, so the overlay is empty and every
21
- * read falls straight through to disk.
22
- * - the proposal promotion preflight (`commands/proposal/repository.ts`
23
- * `preflightProposalPromotion`) — the one proposal's own `changes` are the
24
- * overlay, so `validate()` sees the bundle AS IT WOULD LOOK the instant
25
- * after the transaction commits, without that transaction ever touching
26
- * disk.
18
+ * The production caller of this factory is `akm lint`'s non-akm adapter dispatch
19
+ * (`commands/lint/index.ts`): a plain sweep with NO pending changes, so the overlay
20
+ * is empty and every read falls straight through to disk. It also hands the context
21
+ * the run's `sources` and `config`, which the base checks read.
27
22
  *
28
23
  * ── resolveRef ──
29
24
  *
@@ -137,7 +132,8 @@ function stripBundlePrefix(ref) {
137
132
  */
138
133
  export function createValidateContext(options) {
139
134
  const root = options.root;
140
- const extraRoots = options.extraRoots ?? [];
135
+ const sources = options.sources ?? [];
136
+ const extraRoots = sources.map((source) => source.path).filter((sourcePath) => sourcePath !== root);
141
137
  const overlay = buildOverlay(root, options.changes ?? []);
142
138
  async function readFile(p) {
143
139
  // An absolute candidate (e.g. a `stale-path` scan hit, which is always an
@@ -196,5 +192,5 @@ export function createValidateContext(options) {
196
192
  }
197
193
  return { exists: false };
198
194
  }
199
- return { readFile, list, resolveRef };
195
+ return { sources, config: options.config, readMoves: options.readMoves, readFile, list, resolveRef };
200
196
  }
@@ -28,6 +28,7 @@ import path from "node:path";
28
28
  import { toPosix } from "../common.js";
29
29
  import { SCRIPT_EXTENSIONS, WORKFLOW_EXTENSIONS } from "../recognition-util.js";
30
30
  const workflowSpec = {
31
+ documentFormat: "markdown",
31
32
  isRelevantFile: (fileName) => WORKFLOW_EXTENSIONS.includes(path.extname(fileName).toLowerCase()),
32
33
  toCanonicalName: (typeRoot, filePath) => {
33
34
  const rel = toPosix(path.relative(typeRoot, filePath));
@@ -55,6 +56,7 @@ const workflowSpec = {
55
56
  },
56
57
  };
57
58
  const markdownSpec = {
59
+ documentFormat: "markdown",
58
60
  isRelevantFile: (fileName) => path.extname(fileName).toLowerCase() === ".md",
59
61
  toCanonicalName: (typeRoot, filePath) => {
60
62
  const rel = toPosix(path.relative(typeRoot, filePath));
@@ -75,6 +77,7 @@ const scriptSpec = {
75
77
  const BUILTIN_PLACEMENT_SPECS = {
76
78
  skill: {
77
79
  stashDir: "skills",
80
+ documentFormat: "markdown",
78
81
  isRelevantFile: (fileName) => fileName === "SKILL.md",
79
82
  toCanonicalName: (typeRoot, filePath) => {
80
83
  const relDir = toPosix(path.dirname(path.relative(typeRoot, filePath)));
@@ -146,6 +149,7 @@ const BUILTIN_PLACEMENT_SPECS = {
146
149
  // <stash>/tasks/<id>.yml.
147
150
  task: {
148
151
  stashDir: "tasks",
152
+ documentFormat: "yaml",
149
153
  isRelevantFile: (fileName) => path.extname(fileName).toLowerCase() === ".yml",
150
154
  toCanonicalName: (typeRoot, filePath) => {
151
155
  const rel = toPosix(path.relative(typeRoot, filePath));
@@ -199,6 +203,31 @@ export function typeForStashDir(stashDir) {
199
203
  }
200
204
  return undefined;
201
205
  }
206
+ /** The document format of the files in a stash subdir, or `undefined` when no registered type places plain-text documents there. */
207
+ export function documentFormatForStashDir(stashDir) {
208
+ for (const spec of Object.values(PLACEMENT_SPECS)) {
209
+ if (spec.stashDir === stashDir)
210
+ return spec.documentFormat;
211
+ }
212
+ return undefined;
213
+ }
214
+ /** The stash subdirs whose assets are plain-text documents (Markdown or YAML), in registry order. */
215
+ export function documentStashDirs() {
216
+ return Object.values(PLACEMENT_SPECS)
217
+ .filter((spec) => spec.documentFormat !== undefined)
218
+ .map((spec) => spec.stashDir);
219
+ }
220
+ /** The registered types whose assets are plain-text documents, in registry order. */
221
+ export function documentTypes() {
222
+ return Object.entries(PLACEMENT_SPECS)
223
+ .filter(([, spec]) => spec.documentFormat !== undefined)
224
+ .map(([type]) => type);
225
+ }
226
+ /** The document stash subdir a type name or a subdir name selects, or `undefined` when it selects none. */
227
+ export function documentStashDirFor(typeOrDir) {
228
+ const dir = documentFormatForStashDir(typeOrDir) !== undefined ? typeOrDir : stashDirFor(typeOrDir);
229
+ return dir !== undefined && documentFormatForStashDir(dir) !== undefined ? dir : undefined;
230
+ }
202
231
  /** All stash subdir names across the registered types. */
203
232
  export function stashDirNames() {
204
233
  return Object.values(PLACEMENT_SPECS).map((spec) => spec.stashDir);
@@ -0,0 +1,124 @@
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
+ * Reading a file's frontmatter as keys and values, and changing keys in it (set or remove) while every other byte stays as
6
+ * written: untouched keys keep their order, quoting, comments and line endings, and the body is not touched. A change that
7
+ * cannot be made that way is refused, never approximated.
8
+ */
9
+ import { isDeepStrictEqual } from "node:util";
10
+ import { parseDocument, parse as parseYaml } from "yaml";
11
+ import { UsageError } from "../errors.js";
12
+ import { serializeFrontmatter } from "./asset-serialize.js";
13
+ import { parseFrontmatterBlock } from "./frontmatter.js";
14
+ const KEY_RE = /^\w[\w-]*$/;
15
+ const KEY_LINE_RE = /^(\w[\w-]*):(?:[ \t]|$)/;
16
+ const MALFORMED = "AKM Markdown has malformed YAML frontmatter.";
17
+ function strictMapping(block) {
18
+ let parsed;
19
+ try {
20
+ parsed = block.trim() ? parseYaml(block) : {};
21
+ }
22
+ catch {
23
+ throw new UsageError(MALFORMED, "INVALID_FLAG_VALUE");
24
+ }
25
+ if (parsed === null)
26
+ return {};
27
+ if (typeof parsed !== "object" || Array.isArray(parsed))
28
+ throw new UsageError("AKM Markdown frontmatter must be a YAML mapping.", "INVALID_FLAG_VALUE");
29
+ return parsed;
30
+ }
31
+ /** The frontmatter of `content` as the strict YAML parser reads it, the way a write of the file would. */
32
+ export function readFrontmatter(content) {
33
+ const block = parseFrontmatterBlock(content);
34
+ if (!block)
35
+ return { present: false, bodyStart: 0, entries: [] };
36
+ const bodyStart = content.length - block.content.length;
37
+ try {
38
+ return {
39
+ present: true,
40
+ bodyStart,
41
+ entries: Object.entries(strictMapping(block.frontmatter)).map(([key, value]) => ({ key, value })),
42
+ };
43
+ }
44
+ catch (error) {
45
+ const line = parseDocument(block.frontmatter).errors[0]?.linePos?.[0]?.line;
46
+ return {
47
+ present: true,
48
+ bodyStart,
49
+ entries: [],
50
+ error: {
51
+ reason: error instanceof Error ? error.message : String(error),
52
+ ...(line === undefined ? {} : { line: line + 1 }),
53
+ },
54
+ };
55
+ }
56
+ }
57
+ /** The lines of a key's block in `parts` (alternating line and line ending): its `key:` line and the lines that continue it. */
58
+ function keyBlock(parts, closeAt, key) {
59
+ for (let i = 2; i < closeAt; i += 2) {
60
+ if (parts[i]?.match(KEY_LINE_RE)?.[1] !== key)
61
+ continue;
62
+ let end = i + 2;
63
+ while (end < closeAt && /^(?:[ \t]+\S|-(?:[ \t]|$))/.test(parts[end]))
64
+ end += 2;
65
+ return { start: i, end };
66
+ }
67
+ return undefined;
68
+ }
69
+ const withEnds = (lines, eol) => lines.flatMap((line) => [line, eol]);
70
+ /** `content` with the changes applied to its frontmatter, and nothing else changed. */
71
+ export function changeFrontmatter(content, changes) {
72
+ for (const change of changes) {
73
+ if (!KEY_RE.test(change.key))
74
+ throw new UsageError(`"${change.key}" is not a frontmatter key akm can edit as a field.`);
75
+ if ((change.remove === true) === "value" in change)
76
+ throw new UsageError(`Change "${change.key}" by setting a value or removing it, not both or neither.`);
77
+ }
78
+ const block = parseFrontmatterBlock(content);
79
+ const intended = block ? { ...strictMapping(block.frontmatter) } : {};
80
+ for (const change of changes) {
81
+ if (change.remove)
82
+ delete intended[change.key];
83
+ else
84
+ intended[change.key] = change.value;
85
+ }
86
+ if (!block) {
87
+ const sets = changes.filter((change) => !change.remove);
88
+ if (sets.length === 0)
89
+ return content;
90
+ return `---\n${serializeFrontmatter(Object.fromEntries(sets.map((change) => [change.key, change.value])))}\n---\n${content}`;
91
+ }
92
+ const parts = content.split(/(\r?\n)/);
93
+ const eol = parts[1] ?? "\n";
94
+ const current = strictMapping(block.frontmatter);
95
+ for (const change of changes) {
96
+ const closeAt = parts.findIndex((part, i) => i > 0 && part.trim() === "---");
97
+ const found = keyBlock(parts, closeAt, change.key);
98
+ if (change.remove) {
99
+ if (found)
100
+ parts.splice(found.start, found.end - found.start);
101
+ continue;
102
+ }
103
+ if (found && isDeepStrictEqual(current[change.key], change.value))
104
+ continue;
105
+ const lines = withEnds(serializeFrontmatter({ [change.key]: change.value }).split("\n"), eol);
106
+ if (found)
107
+ parts.splice(found.start, found.end - found.start, ...lines);
108
+ else
109
+ parts.splice(closeAt, 0, ...lines);
110
+ current[change.key] = change.value;
111
+ }
112
+ const result = parts.join("");
113
+ const written = parseFrontmatterBlock(result);
114
+ let reread;
115
+ try {
116
+ reread = written ? strictMapping(written.frontmatter) : undefined;
117
+ }
118
+ catch {
119
+ reread = undefined;
120
+ }
121
+ if (!isDeepStrictEqual(reread, intended))
122
+ throw new UsageError("These changes cannot be made to the frontmatter as written; edit its text instead.");
123
+ return result;
124
+ }
@@ -23,16 +23,32 @@ function stripTrailingSentencePunctuation(token) {
23
23
  return token.replace(/[.;:!?]+$/, "");
24
24
  }
25
25
  /** True for a file under a bundle's `skills/` directory: a skill carries no `updated` field. */
26
- export function isSkillPath(relPath) {
26
+ function isSkillPath(relPath) {
27
27
  return relPath.split(/[\\/]/)[0] === "skills";
28
28
  }
29
+ /** The rules that state what an authored akm asset carries; they do not apply inside an LLM Wiki. */
30
+ const AUTHORED_ASSET_RULES = new Set(["missing-updated", "missing-name-or-type"]);
31
+ /**
32
+ * Whether `rule` applies to the file: the one place that decides it. Every producer of a lint finding (the `akm lint`
33
+ * sweep and each adapter's `validate`) asks here before it reports a rule. What a check needs of the file's content (a
34
+ * frontmatter block, a type) stays in the check.
35
+ */
36
+ export function ruleApplies(rule, file) {
37
+ if (file.skip?.includes(rule))
38
+ return false;
39
+ if (file.llmWiki === true && AUTHORED_ASSET_RULES.has(rule))
40
+ return false;
41
+ if (rule === "missing-updated" && isSkillPath(file.relPath))
42
+ return false;
43
+ return true;
44
+ }
29
45
  /**
30
46
  * Absolute paths in `text` presented as current guidance. Paths on lines or in
31
47
  * sections that frame them as history or examples, run-time filename
32
48
  * templates, and trailing sentence punctuation are all excluded.
33
49
  */
34
50
  export function findCurrentPathReferences(text, firstLine = 1) {
35
- const pathRe = /(?<=^|[\s"'`([=])\/[^\s"'`)\]>,:\[\n]+/g;
51
+ const pathRe = /(?<=^|[\s"'`([=])\/[^\s"'`)\]>,:[\n]+/g;
36
52
  const out = [];
37
53
  let inNonCurrentSection = false;
38
54
  text.split(/\r?\n/).forEach((line, index) => {
@@ -0,0 +1,30 @@
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 path from "node:path";
6
+ /** The directory of an LLM Wiki that holds its pages, next to its root `schema.md`. */
7
+ export const LLM_WIKI_PAGES_DIR = "pages";
8
+ /** True when `root` is an LLM Wiki: a root `schema.md` plus a `pages/` directory. The one probe the `llm-wiki` adapter and lint share. */
9
+ export function looksLikeLlmWikiRoot(root) {
10
+ try {
11
+ if (!fs.existsSync(path.join(root, "schema.md")))
12
+ return false;
13
+ return fs.statSync(path.join(root, LLM_WIKI_PAGES_DIR)).isDirectory();
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ /**
20
+ * Whether a file whose bundle-relative directories are `ancestorDirs` sits inside an LLM Wiki of the bundle at `root`: the
21
+ * bundle root or an ancestor is a wiki root. A wiki keeps its own schema and log and is written by the wiki's own process,
22
+ * so its files are not authored akm assets.
23
+ */
24
+ export function isInLlmWiki(root, ancestorDirs) {
25
+ for (let i = 0; i <= ancestorDirs.length; i++) {
26
+ if (looksLikeLlmWikiRoot(path.join(root, ...ancestorDirs.slice(0, i))))
27
+ return true;
28
+ }
29
+ return false;
30
+ }
@@ -0,0 +1,39 @@
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
+ * Finding and rewriting the refs that text spells out. One tokenizer for every rewrite of a ref in content: the 0.10
6
+ * migration's old spellings and `akm lint --fix`'s links to a moved asset both go through {@link rewritePathTokens}.
7
+ */
8
+ /** The character before a ref token must not continue a path, a URL or a typed ref. */
9
+ export const SPELLING_BEFORE = String.raw `(?<![\w./~:-])`;
10
+ export function escapeRegExp(text) {
11
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
12
+ }
13
+ /** A matched run of path characters: without trailing dots (sentence punctuation), and with a `.md` told apart. */
14
+ export function splitRun(run) {
15
+ const stem = run.replace(/\.+$/, "");
16
+ const md = stem.endsWith(".md");
17
+ return { stem: md ? stem.slice(0, -".md".length) : stem, tail: run.slice(stem.length), md };
18
+ }
19
+ /**
20
+ * Rewrite every `[bundle//]<path>[.md]` token of `text` that `rewrite` gives a new spelling. `rewrite` receives the
21
+ * bundle (undefined for a bare path) and the path without `.md`, and returns the whole new token without `.md`, or
22
+ * undefined to leave the token as written. Returns the text and how many tokens were rewritten.
23
+ */
24
+ export function rewritePathTokens(text, rewrite, options = {}) {
25
+ const start = options.folders === undefined
26
+ ? String.raw `[\w][\w./-]*`
27
+ : `(?:${options.folders.map(escapeRegExp).join("|")})/[\\w./-]*`;
28
+ const token = new RegExp(`${SPELLING_BEFORE}(?:([\\w.-]+)//)?(${start})`, "g");
29
+ let count = 0;
30
+ const replaced = text.replace(token, (whole, bundleId, run) => {
31
+ const { stem, tail, md } = splitRun(run);
32
+ const to = rewrite(bundleId, stem);
33
+ if (to === undefined)
34
+ return whole;
35
+ count++;
36
+ return `${to}${md ? ".md" : ""}${tail}`;
37
+ });
38
+ return { text: replaced, count };
39
+ }
@@ -0,0 +1,59 @@
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
+ * The frontmatter keys akm knows for a type, with the ones its validators require. A key is required when its absence is
6
+ * a finding of the check that owns it: `lintLessonContent` (a lesson's `description` and `when_to_use`),
7
+ * `factDiagnostics` (a fact's `category`), `nameOrTypeDiagnostics` (a command's and an agent's `name` and `type`), the
8
+ * workflow compiler (`steps`) and `missing-updated` (every Markdown asset). Anything else in a file is kept as written.
9
+ */
10
+ import { KNOWN_CATEGORIES } from "../adapter/adapters/akm-lint.js";
11
+ const key = (name, kind, hint, options = {}) => ({ key: name, kind, hint, required: options.required ?? false, ...options });
12
+ const description = (required = false) => key("description", "text", "What the asset is, in one sentence.", { required });
13
+ const COMMON = [
14
+ description(),
15
+ key("tags", "list", "Words that find the asset in search."),
16
+ key("project", "text", "The project the asset belongs to."),
17
+ key("updated", "text", "The date the asset was last changed.", { required: true, stamped: true }),
18
+ key("aliases", "list", "Other names the asset is searched by."),
19
+ key("searchHints", "list", "Phrases that should find the asset."),
20
+ key("xrefs", "list", "Refs of related assets."),
21
+ key("supersededBy", "list", "Refs of the assets that replace this one."),
22
+ key("contradictedBy", "list", "Refs of the assets that contradict this one."),
23
+ key("beliefState", "text", "Whether the asset is current, superseded or contradicted."),
24
+ ];
25
+ const BY_TYPE = {
26
+ lesson: [
27
+ description(true),
28
+ key("when_to_use", "text", "The trigger that should make a caller apply the lesson.", { required: true }),
29
+ ],
30
+ fact: [key("category", "text", "Whose fact this is.", { required: true, values: [...KNOWN_CATEGORIES] })],
31
+ command: [
32
+ key("name", "text", "The command's name.", { required: true }),
33
+ key("type", "text", "The asset type.", { required: true, stamped: true }),
34
+ ],
35
+ agent: [
36
+ key("name", "text", "The agent's name.", { required: true }),
37
+ key("type", "text", "The asset type.", { required: true, stamped: true }),
38
+ key("model", "text", "The model the agent runs on."),
39
+ ],
40
+ workflow: [
41
+ description(true),
42
+ key("steps", "list", "The steps, in order, each with an id.", { required: true }),
43
+ key("params", "map", "The parameters a run takes."),
44
+ ],
45
+ memory: [
46
+ key("source", "text", "Where the memory came from."),
47
+ key("observed", "text", "When it was observed."),
48
+ key("expires", "text", "When it stops being true."),
49
+ key("subjective", "flag", "An opinion rather than a fact."),
50
+ ],
51
+ };
52
+ /** The keys for `type`, in the order a form shows them: description, tags, project and updated first. */
53
+ export function frontmatterKeysFor(type) {
54
+ const own = BY_TYPE[type] ?? [];
55
+ const merged = new Map();
56
+ for (const known of [...COMMON, ...own])
57
+ merged.set(known.key, { ...merged.get(known.key), ...known });
58
+ return [...merged.values()];
59
+ }
@@ -6,9 +6,13 @@
6
6
  * config load, from the file itself (see `./peek.ts`).
7
7
  */
8
8
  import { z } from "zod";
9
- /** `usage.capture`: record local-only CLI usage counts in `metrics.db`. Default `true`. */
9
+ /**
10
+ * `usage.capture`: record local-only CLI usage counts in `metrics.db`. Default `true`.
11
+ * `usage.report`: send the daily usage report (docs/reference/data-and-telemetry.md). Default `true`.
12
+ */
10
13
  export const UsageConfigSchema = z
11
14
  .object({
12
15
  capture: z.boolean().optional(),
16
+ report: z.boolean().optional(),
13
17
  })
14
18
  .passthrough();
@@ -6,12 +6,12 @@
6
6
  * monolith — no behavior change.
7
7
  */
8
8
  import { z } from "zod";
9
+ import { DETAIL_LEVELS, OUTPUT_FORMATS } from "../../../output/context.js";
9
10
  // ── Output ──────────────────────────────────────────────────────────────────
10
11
  export const OutputConfigSchema = z
11
12
  .object({
12
- // D7 — every `--format` value is a valid default. Kept in step with OUTPUT_FORMATS
13
- // (`src/output/context.ts`). The retired `html` is dropped with a warning before validation.
14
- format: z.enum(["json", "yaml", "text", "jsonl", "md"]).optional(),
15
- detail: z.enum(["brief", "normal", "full"]).optional(),
13
+ // D7 — every `--format` value is a valid default. The retired `html` is dropped with a warning before validation.
14
+ format: z.enum(OUTPUT_FORMATS).optional(),
15
+ detail: z.enum(DETAIL_LEVELS).optional(),
16
16
  })
17
17
  .passthrough();
@@ -10,3 +10,7 @@ export const SearchConfigSchema = z
10
10
  defaultExcludeTypes: z.array(nonEmptyString).optional(),
11
11
  })
12
12
  .passthrough();
13
+ /** Types left out of an untyped search unless asked for: the configured list, `["session"]` when the config sets none (an empty list leaves nothing out). */
14
+ export function defaultExcludedTypes(config) {
15
+ return config.search?.defaultExcludeTypes ?? ["session"];
16
+ }
@@ -205,15 +205,14 @@ export function assertAkmAssetWrite(source, allowedAdapters = ["akm"]) {
205
205
  throw new UsageError(`Bundle "${source.name}" uses adapter "${source.adapterId}", which does not support AKM asset writes.`, "INVALID_FLAG_VALUE");
206
206
  }
207
207
  /**
208
- * Validate a write target before a command mutates it. A git target must be a
209
- * materialized checkout on a branch; its repository root is resolved from the
210
- * content root (which may be a subdirectory) so the boundary commit uses
211
- * repository-relative paths. Being ahead of or behind upstream only warns.
208
+ * The read-only checks a write target must pass: the adapter takes AKM asset writes, and a git target is a
209
+ * materialized checkout on a branch. Its repository root is resolved from the content root (which may be a
210
+ * subdirectory) so the boundary commit uses repository-relative paths. Nothing is changed and nothing is fetched.
212
211
  */
213
- export function prepareWriteTargetForMutation(target, options = {}) {
212
+ function checkWriteTarget(target, options = {}) {
214
213
  assertAkmAssetWrite(target.source, options.allowedAdapters);
215
214
  if (target.source.kind !== "git")
216
- return target;
215
+ return { target };
217
216
  const contentRoot = path.resolve(target.source.path);
218
217
  const rootResult = runGit(["-C", contentRoot, "rev-parse", "--show-toplevel"]);
219
218
  if (rootResult.status !== 0 || !rootResult.stdout.trim()) {
@@ -224,6 +223,36 @@ export function prepareWriteTargetForMutation(target, options = {}) {
224
223
  if (branchResult.status !== 0 || !branchResult.stdout.trim()) {
225
224
  throw new UsageError(`Writable Git target "${target.source.name}" is detached from a branch.`, "INVALID_FLAG_VALUE");
226
225
  }
226
+ return { target, repoPath };
227
+ }
228
+ /**
229
+ * Whether a write to `explicitTarget` (or, with none, to where a write goes by default) would be accepted, and the
230
+ * sentence why not when it would not. It runs the checks the write path runs, so it never disagrees with a save.
231
+ * `name` is the bundle the write resolves to, or null when none resolves.
232
+ */
233
+ export function inspectWriteTarget(akmConfig, explicitTarget) {
234
+ try {
235
+ const resolved = resolveWriteTarget(akmConfig, explicitTarget);
236
+ checkWriteTarget(resolved);
237
+ return { name: resolved.source.name, blocker: null };
238
+ }
239
+ catch (error) {
240
+ let name = null;
241
+ try {
242
+ name = resolveWriteTarget(akmConfig, explicitTarget, { requireWritable: false }).source.name;
243
+ }
244
+ catch {
245
+ // Nothing resolves: the blocker above says why.
246
+ }
247
+ return { name, blocker: error instanceof Error ? error.message : String(error) };
248
+ }
249
+ }
250
+ /** Validate a write target before a command mutates it: the read-only checks, then an advisory upstream check. */
251
+ export function prepareWriteTargetForMutation(target, options = {}) {
252
+ const { repoPath } = checkWriteTarget(target, options);
253
+ if (repoPath === undefined)
254
+ return target;
255
+ const contentRoot = path.resolve(target.source.path);
227
256
  try {
228
257
  const upstream = inspectGitUpstream(repoPath);
229
258
  if (upstream.behind > 0) {
@@ -248,12 +277,32 @@ export function prepareWriteTargetForMutation(target, options = {}) {
248
277
  * target records the path for {@link commitWriteTargetBoundary}.
249
278
  */
250
279
  export async function writeAssetToSource(source, config, ref, content) {
280
+ assertWritableSource(source, config);
281
+ const filePath = resolveAssetFilePath(source, ref);
282
+ writeSourceFile(source, filePath, content, formatRefForMessage(ref), ref.type);
283
+ return {
284
+ path: filePath,
285
+ ref: displayRef({ conceptId: conceptIdFromTypeName(ref.type, ref.name), bundleId: ref.origin }),
286
+ };
287
+ }
288
+ /** The gates an asset write passes: {@link assertPlainWritable}, and an adapter that takes AKM asset writes. */
289
+ export function assertWritableSource(source, config) {
290
+ assertPlainWritable(source, config);
291
+ assertAkmAssetWrite(source);
292
+ }
293
+ /** The gates of a plain file write: the source takes writes and is a kind akm writes, whatever its adapter. */
294
+ export function assertPlainWritable(source, config) {
251
295
  ensureWritable(source, config);
252
296
  assertSupportedKind(source);
253
- assertAkmAssetWrite(source);
254
- const filePath = resolveAssetFilePath(source, ref);
255
- const authored = filePath.toLowerCase().endsWith(".md") ? normalizeAkmMarkdown(content, ref.type) : content;
256
- const normalized = authored.endsWith("\n") ? authored : `${authored}\n`;
297
+ }
298
+ /**
299
+ * Write a text file into `source` at `filePath` (already resolved inside it, after {@link assertWritableSource}), the
300
+ * atomic write every authored file goes through; `label` names it in warnings. Markdown of a known `type` is made a conformant document first; a file
301
+ * of no type (`type` undefined) is written as given; an empty file stays empty.
302
+ */
303
+ export function writeSourceFile(source, filePath, content, label, type) {
304
+ const authored = type !== undefined && filePath.toLowerCase().endsWith(".md") ? normalizeAkmMarkdown(content, type) : content;
305
+ const normalized = authored === "" || authored.endsWith("\n") ? authored : `${authored}\n`;
257
306
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
258
307
  // Atomic: sibling temp file, fdatasync, rename — a crash or a full disk never
259
308
  // leaves a half-written asset where a good one was.
@@ -264,19 +313,13 @@ export async function writeAssetToSource(source, config, ref, content) {
264
313
  // Non-fatal portability advisory, after the write so it never blocks it.
265
314
  const hostPaths = findAbsoluteHomePaths(normalized);
266
315
  if (hostPaths.length > 0) {
267
- warn(`warning: asset "${formatRefForMessage(ref)}" embeds absolute host path(s): ${hostPaths.join(", ")}. ` +
316
+ warn(`warning: asset "${label}" embeds absolute host path(s): ${hostPaths.join(", ")}. ` +
268
317
  "These make the stash non-portable and leak the local username — prefer $HOME or ~ relative references.");
269
318
  }
270
- return {
271
- path: filePath,
272
- ref: displayRef({ conceptId: conceptIdFromTypeName(ref.type, ref.name), bundleId: ref.origin }),
273
- };
274
319
  }
275
320
  /** Delete the asset at `ref` from `source`. Same gates as {@link writeAssetToSource}, no commit. */
276
321
  export async function deleteAssetFromSource(source, config, ref) {
277
- ensureWritable(source, config);
278
- assertSupportedKind(source);
279
- assertAkmAssetWrite(source);
322
+ assertWritableSource(source, config);
280
323
  const filePath = resolveAssetFilePath(source, ref);
281
324
  if (!fs.existsSync(filePath)) {
282
325
  throw new UsageError(`Asset "${formatRefForMessage(ref)}" not found in source "${source.name}" (expected at ${filePath}).`, "MISSING_REQUIRED_ARGUMENT");
@@ -424,24 +467,28 @@ export function withWriteTargetMutation(target, paths, options, mutate) {
424
467
  * that already landed.
425
468
  */
426
469
  export function commitWriteTargetBoundary(target, message, options) {
470
+ commitBoundary(target, message, options);
471
+ }
472
+ /** {@link commitWriteTargetBoundary}, reporting what the commit came to. */
473
+ function commitBoundary(target, message, options) {
427
474
  if (target.source.kind !== "git" && !options?.filesystem)
428
- return;
475
+ return { committed: false, reason: "not-git" };
429
476
  const repoDir = repoDirFor(target.source);
430
477
  const recorded = pendingGitPaths.get(repoDir) ?? new Set();
431
478
  pendingGitPaths.delete(repoDir);
432
479
  if (!isGitBackedStash(repoDir))
433
- return;
480
+ return { committed: false, reason: "not-git" };
434
481
  const toRepoRelative = (filePath) => (path.isAbsolute(filePath) ? path.relative(repoDir, filePath) : filePath).replaceAll(path.sep, "/");
435
482
  const paths = [...new Set([...(options?.paths ?? []), ...recorded].map(toRepoRelative))];
436
483
  if (paths.length === 0)
437
- return;
484
+ return { committed: false, reason: "nothing-to-commit" };
438
485
  const ignored = new Set(listIgnoredExactPaths(repoDir, paths));
439
486
  if (ignored.size > 0) {
440
487
  warn(`warning: ${ignored.size} path(s) in "${target.source.name}" are ignored by .gitignore and stay local (not committed): ${[...ignored].join(", ")}`);
441
488
  }
442
489
  const committable = paths.filter((filePath) => !ignored.has(filePath));
443
490
  if (committable.length === 0)
444
- return;
491
+ return { committed: false, reason: "ignored" };
445
492
  try {
446
493
  const saved = saveGitStash(undefined, message, resolveWritable(target.config), {
447
494
  repoDir,
@@ -451,6 +498,7 @@ export function commitWriteTargetBoundary(target, message, options) {
451
498
  });
452
499
  if (saved.reason)
453
500
  warn(`warning: "${target.source.name}" ${saved.reason}`);
501
+ return saved.commit ? { committed: true, sha: saved.commit } : { committed: false, reason: "nothing-to-commit" };
454
502
  }
455
503
  catch (error) {
456
504
  if (error instanceof GitStashPushError) {
@@ -466,11 +514,11 @@ export function commitWriteTargetBoundary(target, message, options) {
466
514
  * Commit exactly the paths an accepted proposal wrote or removed, when the
467
515
  * target is a git repository: a filesystem stash with a `.git` too, which the
468
516
  * boundary commit skips, locally (the end-of-run sync pushes). A failed commit
469
- * only warns, since the accept already landed.
517
+ * only warns, since the accept already landed. Returns what the commit came to.
470
518
  */
471
519
  export function commitAcceptedPaths(target, message, paths, body) {
472
520
  try {
473
- commitWriteTargetBoundary(target, message, {
521
+ return commitBoundary(target, message, {
474
522
  paths,
475
523
  ...(body ? { body } : {}),
476
524
  filesystem: true,
@@ -478,6 +526,8 @@ export function commitAcceptedPaths(target, message, paths, body) {
478
526
  });
479
527
  }
480
528
  catch (error) {
481
- warn(`warning: could not commit the accept (${message}): ${error instanceof Error ? error.message : String(error)}`);
529
+ const detail = error instanceof Error ? error.message : String(error);
530
+ warn(`warning: could not commit the accept (${message}): ${detail}`);
531
+ return { committed: false, reason: "failed", error: detail };
482
532
  }
483
533
  }