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
@@ -48,7 +48,7 @@ export const DEFAULT_EVENT_RETENTION_DAYS = 90;
48
48
  */
49
49
  export function retentionNotes(args) {
50
50
  const stores = [
51
- { store: "usage_events (search, show, curate and feedback rows)", days: args.usageRetentionDays },
51
+ { store: "usage_events (search, show, curate, feedback and rules rows)", days: args.usageRetentionDays },
52
52
  { store: "events (selects, LLM calls and index runs)", days: args.eventRetentionDays },
53
53
  ];
54
54
  const notes = [];
@@ -95,6 +95,10 @@ export function toUsageRow(row) {
95
95
  const tags = Array.isArray(metadata.tags)
96
96
  ? metadata.tags.filter((tag) => typeof tag === "string")
97
97
  : undefined;
98
+ const refs = Array.isArray(metadata.refs)
99
+ ? metadata.refs.filter((ref) => typeof ref === "string")
100
+ : undefined;
101
+ const chars = finiteNumber(metadata.chars);
98
102
  const agent = metadata.agent;
99
103
  const harness = typeof agent?.harness === "string" && agent.harness ? agent.harness : undefined;
100
104
  const session = typeof agent?.session === "string" && agent.session ? agent.session : undefined;
@@ -110,6 +114,7 @@ export function toUsageRow(row) {
110
114
  ...(totalMs !== undefined ? { totalMs } : {}),
111
115
  ...(reason !== undefined ? { reason } : {}),
112
116
  ...(tags && tags.length > 0 ? { tags } : {}),
117
+ ...(row.event_type === "rules" ? { rules: { refs: refs ?? [], chars: chars ?? 0 } } : {}),
113
118
  ...(harness ? { agent: { harness, ...(session ? { session } : {}) } } : {}),
114
119
  };
115
120
  }
@@ -193,7 +198,7 @@ function buildUsage(input, rows) {
193
198
  const days = new Map();
194
199
  const bump = (at, field) => {
195
200
  const day = at.slice(0, 10);
196
- const entry = days.get(day) ?? { day, search: 0, show: 0, curate: 0, feedback: 0 };
201
+ const entry = days.get(day) ?? { day, search: 0, show: 0, curate: 0, feedback: 0, rules: 0 };
197
202
  entry[field] += 1;
198
203
  days.set(day, entry);
199
204
  };
@@ -219,6 +224,7 @@ function buildUsage(input, rows) {
219
224
  let zeroResultSearches = 0;
220
225
  let shows = 0;
221
226
  let curates = 0;
227
+ const ruleLoads = { loads: 0, rules: 0, chars: 0, byRule: new Map() };
222
228
  for (const row of rows) {
223
229
  bySource[row.source] = (bySource[row.source] ?? 0) + 1;
224
230
  if (row.eventType === "search") {
@@ -270,6 +276,14 @@ function buildUsage(input, rows) {
270
276
  touch(entry, row.at);
271
277
  }
272
278
  }
279
+ else if (row.eventType === "rules") {
280
+ ruleLoads.loads += 1;
281
+ bump(row.at, "rules");
282
+ for (const ref of row.rules?.refs ?? [])
283
+ ruleLoads.byRule.set(ref, (ruleLoads.byRule.get(ref) ?? 0) + 1);
284
+ ruleLoads.rules += row.rules?.refs.length ?? 0;
285
+ ruleLoads.chars += row.rules?.chars ?? 0;
286
+ }
273
287
  else if (row.eventType === "feedback") {
274
288
  // Signed rows only, so the daily series and the totals count the same rows.
275
289
  if (row.signal === undefined)
@@ -305,6 +319,15 @@ function buildUsage(input, rows) {
305
319
  distinctQueries: queries.size,
306
320
  },
307
321
  selectsPerSearch: searchesWithHits > 0 ? input.selects.length / searchesWithHits : null,
322
+ rules: {
323
+ loads: ruleLoads.loads,
324
+ meanRules: mean(ruleLoads.loads > 0 ? [ruleLoads.rules / ruleLoads.loads] : []),
325
+ meanChars: mean(ruleLoads.loads > 0 ? [ruleLoads.chars / ruleLoads.loads] : []),
326
+ byRule: [...ruleLoads.byRule.entries()]
327
+ .map(([ref, loads]) => ({ ref, loads }))
328
+ .sort((a, b) => b.loads - a.loads || a.ref.localeCompare(b.ref))
329
+ .slice(0, input.top),
330
+ },
308
331
  searchMedianMs: median(searchMs),
309
332
  daily: [...days.values()].sort((a, b) => a.day.localeCompare(b.day)),
310
333
  topAssets: [...assets.values()]
@@ -54,6 +54,9 @@ export function buildMetricsView(r, detail) {
54
54
  ["shows", int(usage.totals.shows)],
55
55
  ["curates", int(usage.totals.curates)],
56
56
  ["selects", int(usage.totals.selects)],
57
+ ["rule loads", int(usage.rules.loads)],
58
+ ["rules per load", fixed(usage.rules.meanRules, 1)],
59
+ ["characters per load", fixed(usage.rules.meanChars, 0)],
57
60
  ["searches with hits", int(usage.totals.searchesWithHits)],
58
61
  ["selects per search with hits", fixed(usage.selectsPerSearch, 2)],
59
62
  [
@@ -79,6 +82,12 @@ export function buildMetricsView(r, detail) {
79
82
  dash(a.lastUsedAt),
80
83
  ]),
81
84
  },
85
+ {
86
+ title: "Rule loads",
87
+ headers: ["ref", "loads"],
88
+ rows: cut(usage.rules.byRule).map((rule) => [rule.ref, int(rule.loads)]),
89
+ hideWhenEmpty: true,
90
+ },
82
91
  {
83
92
  title: "Top queries",
84
93
  headers: ["query", "count", "avg results", "last"],
@@ -91,10 +100,10 @@ export function buildMetricsView(r, detail) {
91
100
  },
92
101
  {
93
102
  title: "Daily",
94
- headers: ["day", "search", "show", "curate", "feedback"],
103
+ headers: ["day", "search", "show", "curate", "feedback", "rules"],
95
104
  rows: brief
96
105
  ? []
97
- : usage.daily.map((d) => [d.day, int(d.search), int(d.show), int(d.curate), int(d.feedback)]),
106
+ : usage.daily.map((d) => [d.day, int(d.search), int(d.show), int(d.curate), int(d.feedback), int(d.rules)]),
98
107
  hideWhenEmpty: true,
99
108
  },
100
109
  ],
@@ -98,6 +98,7 @@ export async function akmProposalAccept(options) {
98
98
  ref: result.ref,
99
99
  assetPath: result.assetPath,
100
100
  proposal: result.proposal,
101
+ ...(result.commit ? { commit: result.commit } : {}),
101
102
  };
102
103
  }
103
104
  /**
@@ -109,6 +110,7 @@ export async function akmProposalAcceptMany(options) {
109
110
  const { ids, ...rest } = options;
110
111
  const commitCollector = [];
111
112
  const results = [];
113
+ let outcomes = new Map();
112
114
  try {
113
115
  for (const id of ids) {
114
116
  try {
@@ -126,9 +128,12 @@ export async function akmProposalAcceptMany(options) {
126
128
  }
127
129
  }
128
130
  finally {
129
- commitCollectedAccepts(commitCollector, "akm proposal accept");
131
+ outcomes = commitCollectedAccepts(commitCollector, "akm proposal accept");
130
132
  }
131
- return results;
133
+ return results.map((result) => {
134
+ const commit = result.ok ? outcomes.get(result.id) : undefined;
135
+ return commit ? { ...result, commit } : result;
136
+ });
132
137
  }
133
138
  export async function akmProposalReject(options) {
134
139
  return withAssetMutationLease("proposal-reject", async () => {
@@ -1117,18 +1117,21 @@ function acceptCommitMessage(proposal) {
1117
1117
  return `akm accept: ${proposal.source} ${proposal.id.slice(0, 8)} ${proposal.ref}`;
1118
1118
  }
1119
1119
  function commitAccept(collector, target, proposal, paths) {
1120
- if (collector)
1120
+ if (collector) {
1121
1121
  collector.push({ target, proposal, paths });
1122
- else
1123
- commitAcceptedPaths(target, acceptCommitMessage(proposal), paths);
1122
+ return undefined;
1123
+ }
1124
+ return commitAcceptedPaths(target, acceptCommitMessage(proposal), paths);
1124
1125
  }
1125
1126
  /**
1126
1127
  * Commit everything `collector` holds, one commit per target repository: a lone
1127
1128
  * accept keeps its own subject; several get `<label>: N accepted (source count,
1128
1129
  * ...)` with one `<id8> <source> <ref>` body line per proposal. Empties the
1129
- * collector. A failed commit only warns, as for a single accept.
1130
+ * collector. A failed commit only warns, as for a single accept. Returns what
1131
+ * each proposal's commit came to, by proposal id.
1130
1132
  */
1131
1133
  export function commitCollectedAccepts(collector, label) {
1134
+ const outcomes = new Map();
1132
1135
  const byRepo = new Map();
1133
1136
  for (const entry of collector.splice(0)) {
1134
1137
  const key = path.resolve(entry.target.source.repoPath ?? entry.target.source.path);
@@ -1137,15 +1140,18 @@ export function commitCollectedAccepts(collector, label) {
1137
1140
  for (const entries of byRepo.values()) {
1138
1141
  const first = entries[0];
1139
1142
  if (entries.length === 1) {
1140
- commitAcceptedPaths(first.target, acceptCommitMessage(first.proposal), first.paths);
1143
+ outcomes.set(first.proposal.id, commitAcceptedPaths(first.target, acceptCommitMessage(first.proposal), first.paths));
1141
1144
  continue;
1142
1145
  }
1143
1146
  const counts = new Map();
1144
1147
  for (const { proposal } of entries)
1145
1148
  counts.set(proposal.source, (counts.get(proposal.source) ?? 0) + 1);
1146
1149
  const bySource = [...counts].sort((a, b) => b[1] - a[1]).map(([source, count]) => `${source} ${count}`);
1147
- commitAcceptedPaths(first.target, `${label}: ${entries.length} accepted (${bySource.join(", ")})`, entries.flatMap((entry) => entry.paths), entries.map(({ proposal }) => `${proposal.id.slice(0, 8)} ${proposal.source} ${proposal.ref}`));
1150
+ const outcome = commitAcceptedPaths(first.target, `${label}: ${entries.length} accepted (${bySource.join(", ")})`, entries.flatMap((entry) => entry.paths), entries.map(({ proposal }) => `${proposal.id.slice(0, 8)} ${proposal.source} ${proposal.ref}`));
1151
+ for (const { proposal } of entries)
1152
+ outcomes.set(proposal.id, outcome);
1148
1153
  }
1154
+ return outcomes;
1149
1155
  }
1150
1156
  /**
1151
1157
  * O1 (alpha.9): an accepted consolidate PROMOTION retires its source memory
@@ -1254,8 +1260,8 @@ async function promoteProposalWithLease(stashDir, config, id, options, ctx) {
1254
1260
  const paths = [assetPath];
1255
1261
  if (accepted.status === "accepted" && accepted.source === "consolidate")
1256
1262
  retirePromotionSource(mutationTarget, accepted, paths);
1257
- commitAccept(options.commitCollector, mutationTarget, accepted, paths);
1258
- return { proposal: accepted, assetPath, ref: accepted.ref };
1263
+ const commit = commitAccept(options.commitCollector, mutationTarget, accepted, paths);
1264
+ return { proposal: accepted, assetPath, ref: accepted.ref, ...(commit ? { commit } : {}) };
1259
1265
  }
1260
1266
  /**
1261
1267
  * Every archive dir a tombstone under `.akm/memory-cleanup/archive/` claims
@@ -1547,8 +1553,7 @@ async function retireProposalWithLease(stashDir, config, proposal, options, ctx)
1547
1553
  }
1548
1554
  throw error;
1549
1555
  }
1550
- if (paths.length > 0)
1551
- commitAccept(options.commitCollector, mutationTarget, proposal, paths);
1556
+ const commit = paths.length > 0 ? commitAccept(options.commitCollector, mutationTarget, proposal, paths) : undefined;
1552
1557
  if (archiveDirs.length === 0) {
1553
1558
  // Recorded intent, but neither file is at its original location NOR
1554
1559
  // archived under this proposal's id: something else removed the target
@@ -1571,7 +1576,7 @@ async function retireProposalWithLease(stashDir, config, proposal, options, ctx)
1571
1576
  }, ctx);
1572
1577
  // The moved files left the index's view; drop their rows now, not at the next `akm index`.
1573
1578
  await indexWrittenProposalAssets(mutationTarget, twinPath ? [intent.assetPath, twinPath] : [intent.assetPath]);
1574
- return { proposal: accepted, assetPath: intent.assetPath, ref: accepted.ref };
1579
+ return { proposal: accepted, assetPath: intent.assetPath, ref: accepted.ref, ...(commit ? { commit } : {}) };
1575
1580
  }
1576
1581
  /**
1577
1582
  * Restore an accepted proposal's target from the backup taken at promotion.
@@ -0,0 +1,142 @@
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
+ * `akm rules`: the rules that apply here, in full. Read from the files of the
6
+ * bundles the selection names (never the index), recognized by the same adapter
7
+ * and filtered by the same project and scope functions search uses, so it works
8
+ * with no index and a new rule applies at once. Records one `rules` usage event.
9
+ */
10
+ import path from "node:path";
11
+ import { getStringArg, PROJECT_ARG } from "../../cli/parse-args.js";
12
+ import { defineJsonCommand, output, parseAllFlagValues } from "../../cli/shared.js";
13
+ import { akmAdapter } from "../../core/adapter/adapters/akm-adapter.js";
14
+ import { parseFrontmatter } from "../../core/asset/frontmatter.js";
15
+ import { displayRefForConceptId } from "../../core/asset/resolve-ref.js";
16
+ import { compareCodePoints } from "../../core/common.js";
17
+ import { loadConfig } from "../../core/config/config.js";
18
+ import { resolveProject } from "../../core/projects.js";
19
+ import { withStateDbTelemetry } from "../../core/state-db.js";
20
+ import { warnOnce } from "../../core/warn.js";
21
+ import { deriveInstallations } from "../../indexer/installations.js";
22
+ import { isProposedQuality, scopeMatchesFilters } from "../../indexer/passes/metadata.js";
23
+ import { resolveReadSources } from "../../indexer/read-preflight.js";
24
+ import { drainDirDocuments } from "../../indexer/scan/drain-dir.js";
25
+ import { appliesUnder } from "../../indexer/search/db-search.js";
26
+ import { insertUsageEvent, resolveUsageEventSource } from "../../indexer/usage/usage-events.js";
27
+ import { buildFileContext } from "../../indexer/walk/file-context.js";
28
+ import { walkedFiles, walkStash } from "../../indexer/walk/walker.js";
29
+ import { registerMdRenderer } from "../../output/render-registry.js";
30
+ import { formatRulesText } from "../../output/text/rules.js";
31
+ import { TELEMETRY_BUSY_TIMEOUT_MS } from "../../storage/repositories/index-db.js";
32
+ import { assertNamedSourceExists, narrowSourcesToName, normalizeScopeFilters, parseScopeFilterFlags, parseSearchSource, } from "./search.js";
33
+ import { fromValues, projectContext, scopeFilterArg, stampedProject, withProjectDefaults } from "./search-cli.js";
34
+ /** `--from` values that select a search scope, not a bundle: they do not apply to rules. */
35
+ const SCOPE_KEYWORDS = ["local", "registry", "all"];
36
+ /** The bundle names in a `--from` value; scope keywords are ignored with one warning. `undefined`: none left. */
37
+ function bundleNames(from) {
38
+ if (from === undefined)
39
+ return undefined;
40
+ const parsed = parseSearchSource(from);
41
+ const given = Array.isArray(parsed) ? parsed : [parsed];
42
+ const names = given.filter((name) => !SCOPE_KEYWORDS.includes(name));
43
+ if (names.length < given.length) {
44
+ warnOnce("rules:from-keyword", "`akm rules` reads named bundles: --from local, registry and all are ignored.");
45
+ }
46
+ return names.length > 0 ? names : undefined;
47
+ }
48
+ export function akmRules(input) {
49
+ const config = loadConfig();
50
+ const project = resolveProject(config, { project: input.project, cwd: input.cwd });
51
+ const { filters, view } = withProjectDefaults(project, {
52
+ source: input.from,
53
+ filters: parseScopeFilterFlags(input.filters ?? [], "--filter"),
54
+ });
55
+ const names = bundleNames(input.from) ?? bundleNames(project?.from);
56
+ for (const name of names ?? [])
57
+ assertNamedSourceExists(config, name);
58
+ const sources = resolveReadSources(undefined, config).sources;
59
+ const wanted = names
60
+ ? names.flatMap((name) => narrowSourcesToName(sources, [name]))
61
+ : [
62
+ ...sources.filter((source) => source.isDefault),
63
+ ...(project?.write.bundle ? narrowSourcesToName(sources, [project.write.bundle]) : []),
64
+ ];
65
+ const installations = deriveInstallations(sources);
66
+ const scope = normalizeScopeFilters(filters);
67
+ const context = projectContext(project, filters);
68
+ const bundles = [];
69
+ const found = [];
70
+ for (const source of new Set(wanted)) {
71
+ const component = installations[sources.indexOf(source)]?.components[0];
72
+ if (!component || component.adapter !== "akm" || source.unresolved)
73
+ continue;
74
+ bundles.push(component.id);
75
+ const files = walkedFiles(component.root, walkStash(path.join(component.root, "rules"), "rule").flatMap((group) => group.files));
76
+ for (const file of files) {
77
+ const ctx = buildFileContext(component.root, file);
78
+ const drained = drainDirDocuments(akmAdapter, component, [ctx]);
79
+ const entry = drained.entries[0];
80
+ const conceptId = drained.conceptIdByFile.get(ctx.absPath);
81
+ if (entry?.type !== "rule" || conceptId === undefined)
82
+ continue;
83
+ if (isProposedQuality(entry.quality) || !appliesUnder(entry, context))
84
+ continue;
85
+ if (scope && !scopeMatchesFilters(entry, scope))
86
+ continue;
87
+ const named = entry.frontmatter?.project;
88
+ found.push({
89
+ ref: displayRefForConceptId(conceptId, component.id, config.defaultBundle ?? (source.isDefault ? component.id : undefined)),
90
+ durableRef: `${component.id}//${conceptId}`,
91
+ ...(entry.description ? { description: entry.description } : {}),
92
+ ...(named?.length ? { project: named.length === 1 ? named[0] : named } : {}),
93
+ content: parseFrontmatter(ctx.content()).content.trim(),
94
+ shared: !named?.length,
95
+ });
96
+ }
97
+ }
98
+ found.sort((a, b) => Number(a.shared) - Number(b.shared) || compareCodePoints(a.ref, b.ref));
99
+ const rules = found.map(({ shared: _shared, durableRef: _durableRef, ...rule }) => rule);
100
+ recordRulesUsage({
101
+ project: stampedProject(project),
102
+ bundles,
103
+ refs: found.map((rule) => rule.durableRef),
104
+ chars: found.reduce((sum, rule) => sum + rule.content.length, 0),
105
+ eventSource: input.eventSource ?? resolveUsageEventSource(),
106
+ });
107
+ return { schemaVersion: 1, ...(view ? { project: view } : {}), bundles, rules };
108
+ }
109
+ /** One `rules` usage event per call: what was loaded, not a search or a show. */
110
+ function recordRulesUsage(load) {
111
+ const { eventSource, ...metadata } = load;
112
+ try {
113
+ withStateDbTelemetry((stateDb) => {
114
+ insertUsageEvent(stateDb, { event_type: "rules", metadata: JSON.stringify(metadata), source: eventSource });
115
+ }, TELEMETRY_BUSY_TIMEOUT_MS);
116
+ }
117
+ catch {
118
+ /* telemetry is fire-and-forget */
119
+ }
120
+ }
121
+ export const rulesCommand = defineJsonCommand({
122
+ meta: {
123
+ name: "rules",
124
+ description: "The rules that apply here, in full: the project's and the shared ones, read from the files of the project's bundles (its `from`, else the default bundle and its write bundle)",
125
+ },
126
+ args: {
127
+ from: {
128
+ type: "string",
129
+ description: "Bundle name (repeatable); default: the project's from, else the default bundle",
130
+ },
131
+ filter: scopeFilterArg,
132
+ ...PROJECT_ARG,
133
+ },
134
+ async run({ args }) {
135
+ output("rules", akmRules({
136
+ from: fromValues(args.from),
137
+ filters: parseAllFlagValues("--filter"),
138
+ project: getStringArg(args, "project"),
139
+ }));
140
+ },
141
+ });
142
+ registerMdRenderer("rules", (result) => formatRulesText(result));
@@ -28,7 +28,7 @@ import { deliverRendered } from "../../output/stdout.js";
28
28
  import { akmCurate, packCuratedHits } from "./curate.js";
29
29
  import { akmSearch, parseBeliefFilterMode, parseScopeFilterFlags, parseSearchSource } from "./search.js";
30
30
  import { akmShowUnified } from "./show.js";
31
- const scopeFilterArg = {
31
+ export const scopeFilterArg = {
32
32
  type: "string",
33
33
  description: "Frontmatter key=value filter (repeatable); a repeated key matches any value, different keys must all match",
34
34
  };
@@ -151,12 +151,12 @@ export const doctorMetricsAssetsCommand = defineJsonCommand({
151
151
  },
152
152
  });
153
153
  /** The value a project's writes carry as `project`: what its rules and usage are matched against. */
154
- function stampedProject(project) {
154
+ export function stampedProject(project) {
155
155
  const value = project?.write.metadata.project;
156
156
  return value === undefined ? undefined : String(value);
157
157
  }
158
158
  /** The project a search or curate runs under; a `project` filter in force has already decided eligibility. */
159
- function projectContext(project, filters) {
159
+ export function projectContext(project, filters) {
160
160
  return {
161
161
  name: stampedProject(project),
162
162
  ...(filters && Object.hasOwn(filters, "project") ? { byFilter: true } : {}),
@@ -167,7 +167,7 @@ function projectContext(project, filters) {
167
167
  * project's value for that kind, and a kind neither gave stays at today's default.
168
168
  * `view` is the project as applied: the same effective values, for the response to report.
169
169
  */
170
- function withProjectDefaults(project, explicit) {
170
+ export function withProjectDefaults(project, explicit) {
171
171
  const include = explicit.include ?? project?.include;
172
172
  const from = explicit.source ?? project?.from;
173
173
  const filters = explicit.filters ?? project?.filters;
@@ -181,7 +181,7 @@ function withProjectDefaults(project, explicit) {
181
181
  };
182
182
  }
183
183
  /** `--from` is repeatable; citty keeps only the last value, so read every occurrence from argv. */
184
- function fromValues(parsed) {
184
+ export function fromValues(parsed) {
185
185
  const all = parseAllFlagValues("--from");
186
186
  return all.length > 1 ? all : parsed;
187
187
  }
@@ -324,7 +324,7 @@ function logSearchEvent(rawQuery, response, mode = "keyword", eventSource = "use
324
324
  * source entry's `name`, or an exact path). Throws INVALID_SOURCE_VALUE with
325
325
  * the known names before any stash access can fail differently.
326
326
  */
327
- function assertNamedSourceExists(config, namedSourceName) {
327
+ export function assertNamedSourceExists(config, namedSourceName) {
328
328
  const configSources = getSources(config);
329
329
  const foundInConfig = configSources.find((source) => source.name === namedSourceName || source.path === namedSourceName);
330
330
  if (foundInConfig?.enabled === false) {