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
@@ -0,0 +1,121 @@
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
+ * What akm says about text before it is saved at a path of a bundle: the findings `akm lint` reports for the file, and
6
+ * whether akm could still read the asset (its frontmatter parses, a workflow or task validates). The text is written
7
+ * to a scratch copy of the path so the indexer's own recognition runs on it; nothing in the bundle is read or written.
8
+ */
9
+ import fs from "node:fs";
10
+ import os from "node:os";
11
+ import path from "node:path";
12
+ import { parseDocument } from "yaml";
13
+ import { lintDocumentText } from "../commands/lint/index.js";
14
+ import { classifyAkmFile } from "../core/adapter/adapters/akm-adapter.js";
15
+ import { detectAdapterId } from "../core/adapter/detect-adapter.js";
16
+ import { adapterForId } from "../core/adapter/registry.js";
17
+ import { normalizeAkmMarkdown } from "../core/asset/akm-markdown.js";
18
+ import { documentStashDirFor } from "../core/asset/asset-placement.js";
19
+ import { parseFrontmatterBlock } from "../core/asset/frontmatter.js";
20
+ import { isWithin } from "../core/common.js";
21
+ import { loadConfig } from "../core/config/config.js";
22
+ import { UsageError } from "../core/errors.js";
23
+ import { drainDirDocuments } from "../indexer/scan/drain-dir.js";
24
+ import { resolveSourceEntries } from "../indexer/search/search-source.js";
25
+ import { buildFileContext } from "../indexer/walk/file-context.js";
26
+ import { protectedTypeOf } from "../indexer/walk/place-rules.js";
27
+ import { folderBlocker } from "./file-actions.js";
28
+ /** The line of a frontmatter YAML error in the file (the block starts on line 2), when the YAML parser gives one. */
29
+ function frontmatterErrorLine(content) {
30
+ const block = parseFrontmatterBlock(content);
31
+ const line = block ? parseDocument(block.frontmatter).errors[0]?.linePos?.[0]?.line : undefined;
32
+ return line === undefined ? undefined : line + 1;
33
+ }
34
+ /** Why akm could not read the asset this text would be, or null when it could. */
35
+ function unreadableReason(type, relative, content, scratchRoot, bundle, taskFinding) {
36
+ if (type === null)
37
+ return null;
38
+ if (relative.toLowerCase().endsWith(".md")) {
39
+ try {
40
+ normalizeAkmMarkdown(content, type);
41
+ }
42
+ catch (error) {
43
+ return { reason: error instanceof Error ? error.message : String(error), line: frontmatterErrorLine(content) };
44
+ }
45
+ }
46
+ if (taskFinding !== undefined)
47
+ return { reason: taskFinding };
48
+ const component = { id: bundle, adapter: "akm", root: scratchRoot, writable: true };
49
+ const file = buildFileContext(scratchRoot, path.join(scratchRoot, relative));
50
+ const adapter = adapterForId("akm");
51
+ const drained = adapter ? drainDirDocuments(adapter, component, [file]) : undefined;
52
+ if (drained === undefined || drained.entries.length > 0)
53
+ return null;
54
+ // The scratch folder is not the person's: a path in the reason is the bundle-relative one.
55
+ const reason = (drained.warnings[0] ?? "akm does not index a file here.").split(`${scratchRoot}${path.sep}`).join("");
56
+ return { reason };
57
+ }
58
+ /** The akm bundle named `bundle`, and `path` as a path inside it that akm checks (not a protected or managed place). */
59
+ export function akmBundleFile(input, anyAdapter = false) {
60
+ const bundle = typeof input.bundle === "string" ? input.bundle.trim() : "";
61
+ const relative = typeof input.path === "string" ? input.path.trim().replaceAll("\\", "/") : "";
62
+ if (!bundle || !relative)
63
+ throw new UsageError("Choose a bundle and a path inside it.", "MISSING_REQUIRED_ARGUMENT");
64
+ if (typeof input.content !== "string" || input.content.includes("\0"))
65
+ throw new UsageError("content must be text.");
66
+ if (path.posix.isAbsolute(relative) || relative.split("/").some((segment) => segment === ".." || segment === ""))
67
+ throw new UsageError("Use a path inside the bundle.");
68
+ const config = loadConfig();
69
+ const source = resolveSourceEntries(undefined, config).find((entry) => entry.registryId === bundle && !entry.unresolved);
70
+ if (!source)
71
+ throw new UsageError(`Bundle "${bundle}" is disabled or unavailable.`);
72
+ const adapter = source.adapterId ?? detectAdapterId(source.path);
73
+ if (!anyAdapter && adapter !== "akm")
74
+ throw new UsageError(`akm checks the files of akm bundles; "${bundle}" is not one.`);
75
+ const blocked = folderBlocker(path.posix.dirname(relative)) ??
76
+ (protectedTypeOf(relative) ? "Env and secret files are checked in the protected-file view." : null);
77
+ if (blocked !== null)
78
+ throw new UsageError(blocked);
79
+ return { bundle, relative, source, config, isAkm: adapter === "akm" };
80
+ }
81
+ /** Run `fn` on a scratch copy of the file at `relative` holding `content`: the indexer's own recognition runs on a real file. */
82
+ export function withScratchFile(relative, content, fn) {
83
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "akm-check-"));
84
+ try {
85
+ const scratchFile = path.join(scratch, relative);
86
+ if (!isWithin(scratchFile, scratch))
87
+ throw new UsageError("Use a path inside the bundle.");
88
+ fs.mkdirSync(path.dirname(scratchFile), { recursive: true });
89
+ fs.writeFileSync(scratchFile, content);
90
+ return fn(scratch, scratchFile);
91
+ }
92
+ finally {
93
+ fs.rmSync(scratch, { recursive: true, force: true });
94
+ }
95
+ }
96
+ /** The type akm gives a file at `relative` holding `content`, or null when it is no asset. */
97
+ export function typeOfText(relative, content) {
98
+ return withScratchFile(relative, content, (root, file) => classifyAkmFile(root, buildFileContext(root, file))?.match.type ?? null);
99
+ }
100
+ /** The findings and readability for `content` as the text of `relative` in `bundle`. */
101
+ export async function check(input) {
102
+ const { bundle, relative, source, config } = akmBundleFile(input);
103
+ return withScratchFile(relative, input.content, (scratch, scratchFile) => {
104
+ const type = classifyAkmFile(scratch, buildFileContext(scratch, scratchFile))?.match.type ?? null;
105
+ const subdir = type === null ? undefined : documentStashDirFor(type);
106
+ const found = subdir
107
+ ? lintDocumentText({ root: source.path, relPath: relative, subdir, content: input.content, config })
108
+ : { flagged: [], warnings: [] };
109
+ const task = found.flagged.find((finding) => finding.issue === "invalid-task-yaml");
110
+ const unreadable = unreadableReason(type, relative, input.content, scratch, bundle, task?.detail);
111
+ return {
112
+ bundle,
113
+ path: relative,
114
+ type,
115
+ findings: found.flagged,
116
+ warnings: found.warnings,
117
+ readable: unreadable === null,
118
+ ...(unreadable === null ? {} : { unreadable }),
119
+ };
120
+ });
121
+ }
@@ -4,6 +4,7 @@
4
4
  /** The effective config the owner can read, and the validated changes they can make to it. */
5
5
  import fs from "node:fs";
6
6
  import { isDeepStrictEqual } from "node:util";
7
+ import { usageReportEnabled } from "../cli/usage-report.js";
7
8
  import { assertUnsettable, listConfig, setConfigValue, unsetConfigValue } from "../commands/config-cli.js";
8
9
  import { isRecord } from "../core/common.js";
9
10
  import { defaultConnection, inheritedConnectionsOf, loadConfig, mutateConfig, resetConfigCache, } from "../core/config/config.js";
@@ -56,6 +57,8 @@ const redactEndpoint = (endpoint) => endpoint === undefined ? null : redactUrlCr
56
57
  export function get() {
57
58
  const live = loadConfig();
58
59
  const effective = redactForUi(listConfig(live));
60
+ // The report switch is read from the config file by the report itself; show that answer, not the loaded config's.
61
+ effective.usage = { ...(isRecord(effective.usage) ? effective.usage : {}), report: usageReportEnabled() };
59
62
  // Projects hold no credentials; redaction would turn a value such as `filters.env` into "[redacted]" and a save would write that back.
60
63
  if (live.projects)
61
64
  effective.projects = live.projects;
@@ -0,0 +1,129 @@
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
+ * Copy a file or folder of a bundle to a folder of a bundle (the same or another), the way a file manager does and with
6
+ * what akm's clone adds to a bare copy: the work is staged beside the destination and renamed into place (a failed copy
7
+ * leaves nothing), file links are copied by content and never leave the bundle, the asset-mutation lease and the Git
8
+ * boundary commit apply, the copy is indexed, and a Markdown asset records where it came from in its `sources`. The
9
+ * destination is a folder the person chose, so the copy is a new file wherever it lands; nothing is overwritten.
10
+ */
11
+ import { randomUUID } from "node:crypto";
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+ import { assertNoDestinationSymlinkParent, listTreeFiles, materializeFileLinks, stampCloneOrigin, } from "../commands/sources/source-clone.js";
15
+ import { assertFlatAssetName, normalizeCreateSubPath } from "../core/asset/asset-create.js";
16
+ import { isWithin, safeRealpath } from "../core/common.js";
17
+ import { loadConfig } from "../core/config/config.js";
18
+ import { UsageError } from "../core/errors.js";
19
+ import { resolveBundleWriteTarget } from "../core/mutation-target.js";
20
+ import { assertPlainWritable, commitWriteTargetBoundary, prepareWriteTargetForMutation } from "../core/write-source.js";
21
+ import { indexWrittenAssets } from "../indexer/index-written-assets.js";
22
+ import { resolveSourceEntries } from "../indexer/search/search-source.js";
23
+ import { managedFolderOf, protectedTypeOf } from "../indexer/walk/place-rules.js";
24
+ import { closeDatabase, openReadonlyExistingDatabase } from "../storage/repositories/index-connection.js";
25
+ import { getAssetRefsForFiles } from "../storage/repositories/index-entries-repository.js";
26
+ import { folderBlocker, plainWriteBlocker } from "./file-actions.js";
27
+ import { interactive } from "./lease.js";
28
+ const text = (value, key) => {
29
+ if (typeof value !== "string" || !value.trim())
30
+ throw new UsageError(`${key} is required.`);
31
+ return value.trim();
32
+ };
33
+ /** The ref of the one asset the index holds for a Markdown file, or undefined. */
34
+ function originOf(bundle, file) {
35
+ if (!file.toLowerCase().endsWith(".md"))
36
+ return undefined;
37
+ const db = openReadonlyExistingDatabase();
38
+ if (!db)
39
+ return undefined;
40
+ try {
41
+ const found = getAssetRefsForFiles(db, [file], bundle).get(file) ?? [];
42
+ return found.length === 1 && found[0]?.type !== "workflow" ? found[0]?.ref : undefined;
43
+ }
44
+ finally {
45
+ closeDatabase(db);
46
+ }
47
+ }
48
+ function isSkillManifest(bundle, file) {
49
+ const db = openReadonlyExistingDatabase();
50
+ if (!db)
51
+ return false;
52
+ try {
53
+ return (getAssetRefsForFiles(db, [file], bundle).get(file) ?? []).some((asset) => asset.type === "skill");
54
+ }
55
+ finally {
56
+ closeDatabase(db);
57
+ }
58
+ }
59
+ export async function copyEntry(input) {
60
+ const bundle = text(input.bundle, "bundle");
61
+ let from = text(input.from, "from");
62
+ const toBundle = input.toBundle === undefined ? bundle : text(input.toBundle, "toBundle");
63
+ const name = text(input.name, "name");
64
+ assertFlatAssetName(name);
65
+ if (name === "." || name === ".." || name.includes("\0"))
66
+ throw new UsageError(`"${name}" is not a file name.`);
67
+ const folder = normalizeCreateSubPath(input.folder);
68
+ if (path.posix.isAbsolute(from) || from.split("/").includes(".."))
69
+ throw new UsageError("Use a path inside the bundle.");
70
+ if (protectedTypeOf(from) !== undefined || managedFolderOf(from) !== undefined)
71
+ throw new UsageError("Env and secret files and the folders akm manages are not copied.");
72
+ const config = loadConfig();
73
+ const blocker = folderBlocker(folder) ?? plainWriteBlocker(config, toBundle);
74
+ if (blocker !== null)
75
+ throw new UsageError(blocker);
76
+ const sourceRoot = resolveSourceEntries(undefined, config).find((entry) => entry.registryId === bundle && !entry.unresolved)?.path;
77
+ if (!sourceRoot)
78
+ throw new UsageError(`Bundle "${bundle}" is disabled or unavailable.`);
79
+ // A skill's manifest is not a skill: it copies as the skill's folder, the rule `move` states for the same file.
80
+ if (path.posix.basename(from) === "SKILL.md" && isSkillManifest(bundle, path.join(sourceRoot, from)))
81
+ from = path.posix.dirname(from);
82
+ const absolute = path.join(sourceRoot, from);
83
+ if (!isWithin(safeRealpath(absolute), safeRealpath(sourceRoot)))
84
+ throw new UsageError("The file must stay inside its bundle.", "PATH_ESCAPE_VIOLATION");
85
+ const stat = fs.statSync(absolute, { throwIfNoEntry: false });
86
+ if (!stat || !(stat.isFile() || stat.isDirectory()))
87
+ throw new UsageError("Choose a file or a folder to copy.");
88
+ return interactive("ui-file-copy", async () => {
89
+ const resolved = resolveBundleWriteTarget(config, toBundle, { requireWritable: true });
90
+ const target = prepareWriteTargetForMutation(resolved, { allowedAdapters: [resolved.source.adapterId ?? "akm"] });
91
+ assertPlainWritable(target.source, target.config);
92
+ const root = target.source.path;
93
+ const destination = path.join(root, folder, name);
94
+ if (!isWithin(destination, root))
95
+ throw new UsageError(`"${name}" resolves outside the bundle.`, "PATH_ESCAPE_VIOLATION");
96
+ assertNoDestinationSymlinkParent(root, destination);
97
+ if (fs.lstatSync(destination, { throwIfNoEntry: false }) !== undefined)
98
+ throw new UsageError("That file name is already used in this folder.", "RESOURCE_ALREADY_EXISTS");
99
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
100
+ const staging = `${destination}.tmp-${randomUUID()}`;
101
+ try {
102
+ if (stat.isDirectory()) {
103
+ fs.cpSync(absolute, staging, { recursive: true, errorOnExist: true, force: false });
104
+ materializeFileLinks(staging);
105
+ // A skill is its folder: its SKILL.md records where it came from.
106
+ const manifest = path.join(absolute, "SKILL.md");
107
+ if (fs.existsSync(manifest))
108
+ stampCloneOrigin(path.join(staging, "SKILL.md"), originOf(bundle, manifest));
109
+ }
110
+ else {
111
+ fs.copyFileSync(absolute, staging, fs.constants.COPYFILE_EXCL);
112
+ stampCloneOrigin(staging, originOf(bundle, absolute));
113
+ }
114
+ fs.renameSync(staging, destination);
115
+ }
116
+ catch (error) {
117
+ fs.rmSync(staging, { recursive: true, force: true });
118
+ throw error;
119
+ }
120
+ const files = stat.isDirectory() ? listTreeFiles(destination) : [destination];
121
+ const commitRoot = target.source.repoPath ?? root;
122
+ const to = path.posix.join(folder, name);
123
+ commitWriteTargetBoundary(target, `Copy ${bundle}//${from} to ${toBundle}//${to}`, {
124
+ paths: files.map((file) => path.relative(commitRoot, file).replaceAll(path.sep, "/")),
125
+ });
126
+ const indexed = await indexWrittenAssets(root, files, { bundleId: toBundle });
127
+ return { bundle, from, toBundle, to, indexed };
128
+ });
129
+ }
@@ -46,19 +46,28 @@ export function againstUsual(x, n, baselineX, baselineN) {
46
46
  const share = x / n;
47
47
  return { rate, low, high, state: share > high ? "above" : share < low ? "below" : "within" };
48
48
  }
49
+ /** Whole weeks with observations a usual range needs before it is claimed. */
50
+ export const MIN_USUAL_WEEKS = 4;
49
51
  /**
50
52
  * Weekly proportions with p-chart control limits (centre ± 3 standard errors at each week's own n). A week with no
51
- * observations has no rate and no limits. The centre is the pooled share over every week.
53
+ * observations has no rate and no limits. The centre is the pooled share over the whole weeks only, and only when
54
+ * there are `MIN_USUAL_WEEKS` of them with observations: otherwise there is no usual (`enough` is false, the centre
55
+ * and every limit are null). A partial week has its rate and no limits.
52
56
  */
53
57
  export function pChart(weeks) {
54
- const totalN = weeks.reduce((sum, w) => sum + w.n, 0);
55
- const centre = totalN > 0 ? weeks.reduce((sum, w) => sum + w.x, 0) / totalN : null;
58
+ const whole = weeks.filter((w) => !w.partial && w.n > 0);
59
+ const enough = whole.length >= MIN_USUAL_WEEKS;
60
+ const totalN = whole.reduce((sum, w) => sum + w.n, 0);
61
+ const centre = enough ? whole.reduce((sum, w) => sum + w.x, 0) / totalN : null;
56
62
  return {
57
63
  centre,
64
+ enough,
58
65
  points: weeks.map((w) => {
59
- if (centre === null || w.n === 0)
66
+ if (w.n === 0)
60
67
  return { ...w, rate: null, lower: null, upper: null, signal: false };
61
68
  const rate = w.x / w.n;
69
+ if (centre === null || w.partial)
70
+ return { ...w, rate, lower: null, upper: null, signal: false };
62
71
  const margin = 3 * Math.sqrt((centre * (1 - centre)) / w.n);
63
72
  const lower = Math.max(0, centre - margin);
64
73
  const upper = Math.min(1, centre + margin);
@@ -14,7 +14,7 @@ import { createRetireProposal, recordGateDecision, rejectProposalDurably } from
14
14
  import { writeMarkdownAsset } from "../commands/read/knowledge.js";
15
15
  import { akmShowUnified } from "../commands/read/show.js";
16
16
  import { akmClone } from "../commands/sources/source-clone.js";
17
- import { assertFlatAssetName } from "../core/asset/asset-create.js";
17
+ import { assertFlatAssetName, normalizeCreateSubPath } from "../core/asset/asset-create.js";
18
18
  import { assetPathForName, stashDirFor } from "../core/asset/asset-placement.js";
19
19
  import { parseBundleRef } from "../core/asset/asset-ref.js";
20
20
  import { resolveStashDir, toErrorMessage } from "../core/common.js";
@@ -26,8 +26,13 @@ import { warn } from "../core/warn.js";
26
26
  import { assertAkmAssetWrite } from "../core/write-source.js";
27
27
  import { NO_INDEX_MESSAGE, readUsableIndex } from "../indexer/index-readiness.js";
28
28
  import { getEntryIdByFilePath, getItemRefById } from "../storage/repositories/index-entries-repository.js";
29
+ import { retireBlocker } from "./file-actions.js";
29
30
  import { interactive } from "./lease.js";
31
+ import { createFile } from "./new-file.js";
30
32
  import { redactUrlsInText } from "./redact.js";
33
+ export { check } from "./check-text.js";
34
+ export { applyFrontmatter, frontmatter } from "./frontmatter.js";
35
+ export { createFile };
31
36
  /** An indexed asset file whose bundle accepts AKM writes, found the way the UI reads it. */
32
37
  async function resolveWritableIndexedAsset(ref) {
33
38
  const { fragment } = parseBundleRef(ref);
@@ -120,20 +125,9 @@ export async function createKnowledge(input) {
120
125
  if (typeof input.content !== "string" || !input.content.trim())
121
126
  throw new UsageError("Document content is required.");
122
127
  const name = required(input.name, "name");
123
- const bundle = required(input.bundle, "bundle");
124
128
  assertFlatAssetName(name);
125
- return interactive("ui-knowledge-create", async () => {
126
- const result = await writeMarkdownAsset({
127
- type: "knowledge",
128
- content: input.content,
129
- name,
130
- fallbackPrefix: "knowledge",
131
- target: bundle,
132
- path: typeof input.path === "string" && input.path.trim() ? input.path.trim() : undefined,
133
- });
134
- appendEvent({ eventType: "import", ref: result.ref, metadata: { source: "-", path: result.path, force: false } });
135
- return result;
136
- });
129
+ const folder = path.posix.join("knowledge", normalizeCreateSubPath(input.path));
130
+ return createFile({ bundle: input.bundle, folder, name, content: input.content });
137
131
  }
138
132
  /** Copy an asset to a bundle. Overwriting an existing asset is never done here. */
139
133
  export async function copy(input) {
@@ -154,8 +148,9 @@ export async function retire(input) {
154
148
  const revision = required(input.revision, "revision");
155
149
  return interactive("manual-retire", async () => {
156
150
  const { canonical, target, type } = await resolveWritableIndexedAsset(ref);
157
- if (["skill", "env", "secret", "session"].includes(type))
158
- throw new UsageError("Retire supports single-file assets, not skill packages or protected files.");
151
+ const blocker = retireBlocker(type);
152
+ if (blocker !== undefined)
153
+ throw new UsageError(blocker);
159
154
  const stashDir = resolveStashDir();
160
155
  const minted = createRetireProposal(stashDir, {
161
156
  ref: canonical,
@@ -0,0 +1,130 @@
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
+ * What a person may do to a file or folder of a bundle, and the sentence why not. Each verdict is computed from the
6
+ * checks the operations themselves run (the write target's own checks, the protected-file rule, the retire guard), so a
7
+ * control shown from a verdict never fails after the click.
8
+ */
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { inspectWriteTarget } from "../core/write-source.js";
12
+ import { resolveSourceEntries } from "../indexer/search/search-source.js";
13
+ import { isProtectedPlace, managedFolderOf } from "../indexer/walk/place-rules.js";
14
+ /** The largest file Desktop opens for editing. */
15
+ export const MAX_TEXT_BYTES = 8 * 1_048_576;
16
+ const TEXT_PROBE_BYTES = 64 * 1024;
17
+ const allowed = { allowed: true };
18
+ const refuse = (reason) => ({ allowed: false, reason });
19
+ /** The retire guard: the types a retire proposal cannot take. `documents.retire` refuses with the same sentence. */
20
+ export function retireBlocker(type) {
21
+ return ["skill", "env", "secret", "session"].includes(type)
22
+ ? "Retire supports single-file assets, not skill packages or protected files."
23
+ : undefined;
24
+ }
25
+ const PROTECTED_REASON = "Env and secret files are shown and edited from the protected-file view, and stay where they are.";
26
+ /**
27
+ * What the first bytes of a file say: text (no NUL, valid UTF-8, a character the probe cuts is not invalid), not text,
28
+ * or why the file could not be opened (that failure is the answer, never read as text or as not text).
29
+ */
30
+ function probeText(file) {
31
+ let fd;
32
+ try {
33
+ fd = fs.openSync(file, "r");
34
+ if (fs.fstatSync(fd).size > MAX_TEXT_BYTES)
35
+ return "binary";
36
+ const probe = Buffer.alloc(TEXT_PROBE_BYTES);
37
+ const read = fs.readSync(fd, probe, 0, TEXT_PROBE_BYTES, 0);
38
+ if (probe.subarray(0, read).includes(0))
39
+ return "binary";
40
+ try {
41
+ new TextDecoder("utf-8", { fatal: true }).decode(probe.subarray(0, read), { stream: read === TEXT_PROBE_BYTES });
42
+ }
43
+ catch {
44
+ return "binary";
45
+ }
46
+ return "text";
47
+ }
48
+ catch (error) {
49
+ return { failure: error instanceof Error ? error.message : String(error) };
50
+ }
51
+ finally {
52
+ if (fd !== undefined)
53
+ fs.closeSync(fd);
54
+ }
55
+ }
56
+ export function plainWriteBlocker(config, bundle) {
57
+ const source = resolveSourceEntries(undefined, config).find((entry) => entry.registryId === bundle);
58
+ // A bundle that does not resolve is the caller's error to name, not a read-only bundle.
59
+ return source === undefined || source.writable === true
60
+ ? null
61
+ : `Bundle ${bundle} is read-only: akm does not write to it, and an update would replace the edit.`;
62
+ }
63
+ export function bundleWriteBlockers(config, bundle) {
64
+ return { plain: plainWriteBlocker(config, bundle), asset: inspectWriteTarget(config, bundle).blocker };
65
+ }
66
+ function managedReason(relative) {
67
+ const managed = managedFolderOf(relative);
68
+ return managed === undefined ? null : `${managed}/ is managed by akm.`;
69
+ }
70
+ /** Why nothing is created, moved into or taken out of this folder whatever the bundle allows: a protected or managed place. */
71
+ export function folderBlocker(relative) {
72
+ return isProtectedPlace(relative) ? PROTECTED_REASON : managedReason(relative);
73
+ }
74
+ /** Whether a folder may be made in `folder`, or a file or folder moved into it: plain file operations of any bundle that is not read-only. */
75
+ export function placeVerdict(folder, blockers) {
76
+ const blocker = folderBlocker(folder) ?? blockers.plain;
77
+ return blocker === null ? allowed : refuse(blocker);
78
+ }
79
+ /**
80
+ * The verdicts for one entry. `blockers` are the bundle's own answers ({@link bundleWriteBlockers}), computed once for a
81
+ * listing. Reading, editing, moving and deleting a file or folder are plain file operations and need only `plain`; retiring
82
+ * an asset is an akm asset write and needs `asset` too. Copying and reading leave a bundle as it is.
83
+ */
84
+ export function fileActions(entry, blockers) {
85
+ // What the entry is rules out an action whatever the bundle allows. A file is protected by akm's typing of it.
86
+ const nature = (entry.kind === "file"
87
+ ? entry.protected
88
+ ? PROTECTED_REASON
89
+ : managedReason(entry.relative)
90
+ : folderBlocker(entry.relative)) ??
91
+ entry.unavailable ??
92
+ undefined;
93
+ const probed = entry.kind === "file" && entry.absolute !== undefined && nature === undefined
94
+ ? probeText(entry.absolute)
95
+ : undefined;
96
+ const textVerdict = entry.kind !== "file"
97
+ ? refuse("A folder has no text to open.")
98
+ : probed === "text"
99
+ ? allowed
100
+ : probed === "binary"
101
+ ? refuse("This is not a text file.")
102
+ : refuse(probed ? `This file cannot be opened: ${probed.failure}` : "This file has no path to open.");
103
+ const skillManifest = entry.assets.some((asset) => asset.type === "skill") && path.posix.basename(entry.relative) === "SKILL.md";
104
+ const retire = entry.assets.map((asset) => retireBlocker(asset.type)).find((reason) => reason !== undefined);
105
+ const needsWrite = (verdict, blocker = blockers.plain) => nature !== undefined ? refuse(nature) : blocker !== null ? refuse(blocker) : verdict();
106
+ return {
107
+ read: nature !== undefined ? refuse(nature) : textVerdict,
108
+ edit: needsWrite(() => textVerdict),
109
+ move: needsWrite(() => (skillManifest ? refuse("A skill moves as its folder.") : allowed)),
110
+ copy: nature !== undefined
111
+ ? refuse(nature)
112
+ : typeof probed === "object"
113
+ ? textVerdict
114
+ : skillManifest
115
+ ? { allowed: true, as: path.posix.dirname(entry.relative) }
116
+ : allowed,
117
+ retire: needsWrite(() => entry.kind !== "file"
118
+ ? refuse("Retire applies to an asset; a folder is deleted when it is empty.")
119
+ : entry.assets.length === 0
120
+ ? refuse("This file is not an indexed asset, so there is nothing to retire; delete it instead.")
121
+ : retire !== undefined
122
+ ? refuse(retire)
123
+ : allowed, blockers.plain ?? blockers.asset),
124
+ delete: needsWrite(() => entry.assets.length > 0
125
+ ? refuse("An asset is retired, not deleted: retire it, and restore it from Review if needed.")
126
+ : entry.kind === "directory" && entry.absolute !== undefined && fs.readdirSync(entry.absolute).length > 0
127
+ ? refuse("The folder is not empty.")
128
+ : allowed),
129
+ };
130
+ }
@@ -0,0 +1,41 @@
1
+ // This Source Code Form is subject to the terms of the Mozilla Public
2
+ // License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
+ /**
5
+ * A file's frontmatter for a form: its keys and values as akm's own YAML code reads them, the keys akm knows for the file's
6
+ * type (and which are required), and the application of key changes to a text that leaves everything else as written.
7
+ */
8
+ import { changeFrontmatter, readFrontmatter } from "../core/asset/frontmatter-edit.js";
9
+ import { frontmatterKeysFor } from "../core/asset/type-keys.js";
10
+ import { UsageError } from "../core/errors.js";
11
+ import { akmBundleFile, typeOfText } from "./check-text.js";
12
+ const MARKDOWN_PATH = /\.(?:md|markdown)$/i;
13
+ /** The frontmatter of `content` as the text of `path` in `bundle`: entries in file order, and the keys akm knows for its type. */
14
+ export function frontmatter(input) {
15
+ // The reading of a text's frontmatter is the same in any bundle; the type and its keys are an akm bundle's.
16
+ const { bundle, relative, isAkm } = akmBundleFile(input, true);
17
+ const type = isAkm ? typeOfText(relative, input.content) : null;
18
+ const reading = readFrontmatter(input.content);
19
+ const known = type === null ? [] : frontmatterKeysFor(type);
20
+ return {
21
+ bundle,
22
+ path: relative,
23
+ type,
24
+ present: reading.present,
25
+ /** A Markdown file: akm reads frontmatter from it, and the body starts at `bodyStart` in the text. */
26
+ markdown: MARKDOWN_PATH.test(relative),
27
+ bodyStart: reading.bodyStart,
28
+ entries: reading.entries.map((entry) => ({ ...entry, known: known.some((key) => key.key === entry.key) })),
29
+ ...(reading.error ? { error: reading.error } : {}),
30
+ keys: known,
31
+ };
32
+ }
33
+ /** `content` with the changes applied to its frontmatter (a key set to a value, or removed), and nothing else changed. */
34
+ export function applyFrontmatter(input) {
35
+ if (typeof input.content !== "string")
36
+ throw new UsageError("content must be text.");
37
+ if (!Array.isArray(input.changes))
38
+ throw new UsageError("changes must be a list.");
39
+ const content = changeFrontmatter(input.content, input.changes);
40
+ return { content, bodyStart: readFrontmatter(content).bodyStart };
41
+ }