akm-cli 0.7.5 → 0.8.0-rc.3

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 (155) hide show
  1. package/.github/CHANGELOG.md +1 -1
  2. package/dist/cli/parse-args.js +86 -0
  3. package/dist/cli.js +1023 -521
  4. package/dist/commands/agent-dispatch.js +107 -0
  5. package/dist/commands/agent-support.js +62 -0
  6. package/dist/commands/config-cli.js +68 -84
  7. package/dist/commands/consolidate.js +812 -0
  8. package/dist/commands/distill-promotion-policy.js +658 -0
  9. package/dist/commands/distill.js +218 -43
  10. package/dist/commands/eval-cases.js +40 -0
  11. package/dist/commands/events.js +2 -23
  12. package/dist/commands/graph.js +222 -0
  13. package/dist/commands/health.js +376 -0
  14. package/dist/commands/help/help-accept.md +9 -0
  15. package/dist/commands/help/help-improve.md +53 -0
  16. package/dist/commands/help/help-proposals.md +15 -0
  17. package/dist/commands/help/help-propose.md +17 -0
  18. package/dist/commands/help/help-reject.md +8 -0
  19. package/dist/commands/history.js +3 -30
  20. package/dist/commands/improve.js +1161 -0
  21. package/dist/commands/info.js +2 -2
  22. package/dist/commands/init.js +2 -2
  23. package/dist/commands/install-audit.js +5 -1
  24. package/dist/commands/installed-stashes.js +118 -138
  25. package/dist/commands/knowledge.js +133 -0
  26. package/dist/commands/lint/agent-linter.js +46 -0
  27. package/dist/commands/lint/base-linter.js +291 -0
  28. package/dist/commands/lint/command-linter.js +46 -0
  29. package/dist/commands/lint/default-linter.js +13 -0
  30. package/dist/commands/lint/index.js +145 -0
  31. package/dist/commands/lint/knowledge-linter.js +13 -0
  32. package/dist/commands/lint/memory-linter.js +58 -0
  33. package/dist/commands/lint/registry.js +33 -0
  34. package/dist/commands/lint/skill-linter.js +42 -0
  35. package/dist/commands/lint/task-linter.js +47 -0
  36. package/dist/commands/lint/types.js +1 -0
  37. package/dist/commands/lint/vault-key-rules.js +67 -0
  38. package/dist/commands/lint/workflow-linter.js +53 -0
  39. package/dist/commands/lint.js +1 -0
  40. package/dist/commands/proposal.js +8 -7
  41. package/dist/commands/propose.js +71 -28
  42. package/dist/commands/reflect.js +135 -35
  43. package/dist/commands/registry-search.js +2 -2
  44. package/dist/commands/remember.js +54 -0
  45. package/dist/commands/schema-repair.js +130 -0
  46. package/dist/commands/search.js +21 -5
  47. package/dist/commands/show.js +125 -20
  48. package/dist/commands/source-add.js +10 -10
  49. package/dist/commands/source-manage.js +11 -19
  50. package/dist/commands/tasks.js +385 -0
  51. package/dist/commands/url-checker.js +39 -0
  52. package/dist/commands/vault.js +168 -77
  53. package/dist/core/action-contributors.js +25 -0
  54. package/dist/core/asset-ref.js +4 -0
  55. package/dist/core/asset-registry.js +4 -16
  56. package/dist/core/asset-spec.js +10 -0
  57. package/dist/core/common.js +100 -0
  58. package/dist/core/concurrent.js +22 -0
  59. package/dist/core/config.js +233 -133
  60. package/dist/core/events.js +73 -126
  61. package/dist/core/frontmatter.js +0 -6
  62. package/dist/core/markdown.js +17 -0
  63. package/dist/core/memory-improve.js +678 -0
  64. package/dist/core/parse.js +155 -0
  65. package/dist/core/paths.js +101 -3
  66. package/dist/core/proposal-validators.js +61 -0
  67. package/dist/core/proposals.js +49 -38
  68. package/dist/core/state-db.js +731 -0
  69. package/dist/core/time.js +51 -0
  70. package/dist/core/warn.js +59 -1
  71. package/dist/indexer/db-search.js +52 -238
  72. package/dist/indexer/db.js +403 -54
  73. package/dist/indexer/ensure-index.js +61 -0
  74. package/dist/indexer/graph-boost.js +247 -94
  75. package/dist/indexer/graph-db.js +201 -0
  76. package/dist/indexer/graph-dedup.js +99 -0
  77. package/dist/indexer/graph-extraction.js +409 -76
  78. package/dist/indexer/index-context.js +10 -0
  79. package/dist/indexer/indexer.js +456 -290
  80. package/dist/indexer/llm-cache.js +47 -0
  81. package/dist/indexer/matchers.js +124 -160
  82. package/dist/indexer/memory-inference.js +63 -29
  83. package/dist/indexer/metadata-contributors.js +26 -0
  84. package/dist/indexer/metadata.js +196 -197
  85. package/dist/indexer/path-resolver.js +89 -0
  86. package/dist/indexer/ranking-contributors.js +204 -0
  87. package/dist/indexer/ranking.js +74 -0
  88. package/dist/indexer/search-hit-enrichers.js +22 -0
  89. package/dist/indexer/search-source.js +24 -9
  90. package/dist/indexer/semantic-status.js +2 -16
  91. package/dist/indexer/walker.js +25 -0
  92. package/dist/integrations/agent/builders.js +109 -0
  93. package/dist/integrations/agent/config.js +203 -3
  94. package/dist/integrations/agent/index.js +5 -2
  95. package/dist/integrations/agent/model-aliases.js +63 -0
  96. package/dist/integrations/agent/profiles.js +67 -5
  97. package/dist/integrations/agent/prompts.js +77 -72
  98. package/dist/integrations/agent/sdk-runner.js +120 -0
  99. package/dist/integrations/agent/spawn.js +93 -22
  100. package/dist/integrations/lockfile.js +10 -18
  101. package/dist/integrations/session-logs/index.js +65 -0
  102. package/dist/integrations/session-logs/providers/claude-code.js +56 -0
  103. package/dist/integrations/session-logs/providers/opencode.js +52 -0
  104. package/dist/integrations/session-logs/types.js +1 -0
  105. package/dist/llm/call-ai.js +74 -0
  106. package/dist/llm/client.js +61 -122
  107. package/dist/llm/feature-gate.js +27 -16
  108. package/dist/llm/graph-extract.js +297 -62
  109. package/dist/llm/memory-infer.js +49 -71
  110. package/dist/llm/metadata-enhance.js +39 -22
  111. package/dist/llm/prompts/graph-extract-user-prompt.md +12 -0
  112. package/dist/output/cli-hints-full.md +277 -0
  113. package/dist/output/cli-hints-short.md +65 -0
  114. package/dist/output/cli-hints.js +2 -318
  115. package/dist/output/renderers.js +220 -256
  116. package/dist/output/shapes.js +101 -93
  117. package/dist/output/text.js +256 -17
  118. package/dist/registry/providers/skills-sh.js +61 -49
  119. package/dist/registry/providers/static-index.js +44 -48
  120. package/dist/registry/resolve.js +8 -16
  121. package/dist/setup/setup.js +510 -11
  122. package/dist/sources/provider-factory.js +2 -1
  123. package/dist/sources/providers/filesystem.js +16 -23
  124. package/dist/sources/providers/git.js +4 -5
  125. package/dist/sources/providers/website.js +15 -22
  126. package/dist/sources/website-ingest.js +4 -0
  127. package/dist/tasks/backends/cron.js +200 -0
  128. package/dist/tasks/backends/exec-utils.js +25 -0
  129. package/dist/tasks/backends/index.js +32 -0
  130. package/dist/tasks/backends/launchd-template.xml +19 -0
  131. package/dist/tasks/backends/launchd.js +184 -0
  132. package/dist/tasks/backends/schtasks-template.xml +29 -0
  133. package/dist/tasks/backends/schtasks.js +212 -0
  134. package/dist/tasks/parser.js +198 -0
  135. package/dist/tasks/resolveAkmBin.js +84 -0
  136. package/dist/tasks/runner.js +432 -0
  137. package/dist/tasks/schedule.js +208 -0
  138. package/dist/tasks/schema.js +13 -0
  139. package/dist/tasks/validator.js +59 -0
  140. package/dist/wiki/index-template.md +12 -0
  141. package/dist/wiki/ingest-workflow-template.md +54 -0
  142. package/dist/wiki/log-template.md +8 -0
  143. package/dist/wiki/schema-template.md +61 -0
  144. package/dist/wiki/wiki-templates.js +12 -0
  145. package/dist/wiki/wiki.js +10 -61
  146. package/dist/workflows/authoring.js +5 -25
  147. package/dist/workflows/renderer.js +8 -3
  148. package/dist/workflows/runs.js +59 -91
  149. package/dist/workflows/validator.js +1 -1
  150. package/dist/workflows/workflow-template.md +24 -0
  151. package/docs/README.md +5 -2
  152. package/docs/migration/release-notes/0.7.0.md +1 -1
  153. package/docs/migration/release-notes/0.8.0.md +43 -0
  154. package/package.json +3 -2
  155. package/dist/templates/wiki-templates.js +0 -100
@@ -0,0 +1,385 @@
1
+ /**
2
+ * `akm tasks` — register, inspect, run, and remove scheduled task assets.
3
+ *
4
+ * Each handler exported here is a pure function that performs the real work;
5
+ * `src/cli.ts` wraps these in citty `defineCommand`s and shapes their return
6
+ * values via `output()`.
7
+ */
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { parseAssetRef } from "../core/asset-ref";
11
+ import { resolveAssetPathFromName } from "../core/asset-spec";
12
+ import { isWithin, resolveStashDir } from "../core/common";
13
+ import { loadConfig } from "../core/config";
14
+ import { ConfigError, NotFoundError, UsageError } from "../core/errors";
15
+ import { getTaskHistoryDir, getTaskLogDir } from "../core/paths";
16
+ import { listAgentProfileNames } from "../integrations/agent";
17
+ import { resolveAssetPath } from "../sources/resolve";
18
+ import { backendNameForPlatform, selectBackend } from "../tasks/backends";
19
+ import { parseTaskDocument } from "../tasks/parser";
20
+ import { resolveAkmInvocation } from "../tasks/resolveAkmBin";
21
+ import { exitCodeForStatus, readTaskHistory, runTask } from "../tasks/runner";
22
+ import { parseSchedule, SCHEDULE_SUPPORTED_SUBSET_HINT, translateToCron } from "../tasks/schedule";
23
+ import { validateTaskDocument } from "../tasks/validator";
24
+ export async function akmTasksAdd(input) {
25
+ const id = normaliseTaskId(input.id);
26
+ if ((input.workflow && input.prompt) || (!input.workflow && !input.prompt)) {
27
+ throw new UsageError("Pass exactly one of --workflow <ref> or --prompt <inline|asset-ref|./file.md>.", "INVALID_FLAG_VALUE");
28
+ }
29
+ // Validate the schedule for the active backend before writing anything.
30
+ const backend = backendNameForPlatform();
31
+ parseSchedule(input.schedule, backend);
32
+ const stashDir = resolveStashDir();
33
+ const typeRoot = path.join(stashDir, "tasks");
34
+ fs.mkdirSync(typeRoot, { recursive: true });
35
+ const assetPath = resolveAssetPathFromName("task", typeRoot, id);
36
+ if (!isWithin(assetPath, typeRoot)) {
37
+ throw new UsageError(`Resolved task path escapes the stash: "${id}".`, "PATH_ESCAPE_VIOLATION");
38
+ }
39
+ if (fs.existsSync(assetPath) && !input.force) {
40
+ throw new UsageError(`Task "${id}" already exists. Pass --force to overwrite, or use \`akm tasks remove ${id}\` first.`, "RESOURCE_ALREADY_EXISTS");
41
+ }
42
+ const markdown = renderTaskMarkdown({
43
+ id,
44
+ schedule: input.schedule,
45
+ workflow: input.workflow,
46
+ prompt: input.prompt,
47
+ profile: input.profile,
48
+ params: input.params,
49
+ description: input.description,
50
+ tags: input.tags,
51
+ enabled: input.disabled !== true,
52
+ });
53
+ const task = parseTaskDocument({ markdown, filePath: assetPath, id });
54
+ await validateTaskDocument(task, { backend, stashDir });
55
+ fs.writeFileSync(assetPath, markdown.endsWith("\n") ? markdown : `${markdown}\n`, "utf8");
56
+ // Install in the OS scheduler. If install fails after the file was written,
57
+ // delete the file so the on-disk state never claims a task is registered
58
+ // when it isn't.
59
+ try {
60
+ const sched = selectBackend();
61
+ await sched.install(task);
62
+ }
63
+ catch (err) {
64
+ try {
65
+ fs.rmSync(assetPath, { force: true });
66
+ }
67
+ catch {
68
+ /* ignore */
69
+ }
70
+ throw err;
71
+ }
72
+ return {
73
+ id,
74
+ ref: `task:${id}`,
75
+ path: assetPath,
76
+ stashDir,
77
+ schedule: task.schedule,
78
+ enabled: task.enabled,
79
+ backend,
80
+ target: task.target,
81
+ };
82
+ }
83
+ export async function akmTasksList() {
84
+ const stashDir = resolveStashDir();
85
+ const typeRoot = path.join(stashDir, "tasks");
86
+ if (!fs.existsSync(typeRoot))
87
+ return { tasks: [] };
88
+ const files = fs.readdirSync(typeRoot).filter((f) => f.endsWith(".md"));
89
+ const tasks = [];
90
+ for (const file of files) {
91
+ const id = file.slice(0, -3);
92
+ const filePath = path.join(typeRoot, file);
93
+ let task;
94
+ try {
95
+ task = parseTaskDocument({ markdown: fs.readFileSync(filePath, "utf8"), filePath, id });
96
+ }
97
+ catch {
98
+ continue; // skip malformed files; `akm tasks show <id>` will surface the error
99
+ }
100
+ tasks.push({
101
+ id: task.id,
102
+ ref: `task:${task.id}`,
103
+ path: filePath,
104
+ schedule: task.schedule,
105
+ enabled: task.enabled,
106
+ target: task.target,
107
+ description: task.description,
108
+ tags: task.tags,
109
+ });
110
+ }
111
+ return { tasks };
112
+ }
113
+ export async function akmTasksShow(id) {
114
+ const normalised = normaliseTaskId(id);
115
+ const stashDir = resolveStashDir();
116
+ const filePath = await resolveAssetPath(stashDir, "task", normalised);
117
+ const task = parseTaskDocument({
118
+ markdown: fs.readFileSync(filePath, "utf8"),
119
+ filePath,
120
+ id: normalised,
121
+ });
122
+ const spec = parseSchedule(task.schedule, backendNameForPlatform());
123
+ return {
124
+ id: task.id,
125
+ ref: `task:${task.id}`,
126
+ path: filePath,
127
+ schedule: task.schedule,
128
+ cron: translateToCron(spec),
129
+ enabled: task.enabled,
130
+ target: task.target,
131
+ description: task.description,
132
+ tags: task.tags,
133
+ };
134
+ }
135
+ export async function akmTasksRemove(id) {
136
+ const normalised = normaliseTaskId(id);
137
+ const stashDir = resolveStashDir();
138
+ const filePath = await resolveAssetPath(stashDir, "task", normalised);
139
+ const sched = selectBackend();
140
+ try {
141
+ await sched.uninstall(normalised);
142
+ }
143
+ finally {
144
+ fs.rmSync(filePath, { force: true });
145
+ }
146
+ return { id: normalised, removed: true, backend: sched.name };
147
+ }
148
+ export async function akmTasksSetEnabled(id, enabled) {
149
+ const normalised = normaliseTaskId(id);
150
+ const stashDir = resolveStashDir();
151
+ const filePath = await resolveAssetPath(stashDir, "task", normalised);
152
+ const markdown = fs.readFileSync(filePath, "utf8");
153
+ const updated = setEnabledInMarkdown(markdown, enabled);
154
+ fs.writeFileSync(filePath, updated, "utf8");
155
+ const sched = selectBackend();
156
+ try {
157
+ await sched.setEnabled(normalised, enabled);
158
+ }
159
+ catch (err) {
160
+ // Roll the file back so the markdown source-of-truth and the OS
161
+ // scheduler don't diverge silently when the backend call fails.
162
+ fs.writeFileSync(filePath, markdown, "utf8");
163
+ throw err;
164
+ }
165
+ return { id: normalised, enabled, backend: sched.name };
166
+ }
167
+ export async function akmTasksRun(id) {
168
+ const normalised = normaliseTaskId(id);
169
+ const result = await runTask(normalised);
170
+ return {
171
+ ok: result.status === "completed" || result.status === "disabled",
172
+ result,
173
+ exitCode: exitCodeForStatus(result.status),
174
+ };
175
+ }
176
+ export async function akmTasksHistory(input) {
177
+ const limit = input.limit !== undefined && input.limit > 0 ? input.limit : 50;
178
+ const id = input.id ? normaliseTaskId(input.id) : undefined;
179
+ return { rows: readTaskHistory({ id, limit }) };
180
+ }
181
+ /**
182
+ * Reconcile the on-disk task files with the OS scheduler.
183
+ * • install missing tasks (after validating them — invalid files are
184
+ * skipped with a per-task reason rather than aborting the whole sync)
185
+ * • remove orphan scheduler entries that no longer have a backing file
186
+ */
187
+ export async function akmTasksSync() {
188
+ const stashDir = resolveStashDir();
189
+ const typeRoot = path.join(stashDir, "tasks");
190
+ const fileIds = fs.existsSync(typeRoot)
191
+ ? fs
192
+ .readdirSync(typeRoot)
193
+ .filter((f) => f.endsWith(".md"))
194
+ .map((f) => f.slice(0, -3))
195
+ : [];
196
+ const sched = selectBackend();
197
+ const backend = backendNameForPlatform();
198
+ const present = new Set((await sched.list()).map((t) => t.id));
199
+ const installed = [];
200
+ const unchanged = [];
201
+ const skipped = [];
202
+ for (const id of fileIds) {
203
+ const filePath = path.join(typeRoot, `${id}.md`);
204
+ let task;
205
+ try {
206
+ task = parseTaskDocument({ markdown: fs.readFileSync(filePath, "utf8"), filePath, id });
207
+ }
208
+ catch (err) {
209
+ skipped.push({ id, reason: err instanceof Error ? err.message : String(err) });
210
+ continue;
211
+ }
212
+ try {
213
+ await validateTaskDocument(task, { backend, stashDir });
214
+ }
215
+ catch (err) {
216
+ skipped.push({ id, reason: err instanceof Error ? err.message : String(err) });
217
+ continue;
218
+ }
219
+ if (present.has(id)) {
220
+ unchanged.push(id);
221
+ }
222
+ else {
223
+ await sched.install(task);
224
+ installed.push(id);
225
+ }
226
+ }
227
+ const removed = [];
228
+ for (const installedId of present) {
229
+ if (!fileIds.includes(installedId)) {
230
+ await sched.uninstall(installedId);
231
+ removed.push(installedId);
232
+ }
233
+ }
234
+ return { installed, removed, unchanged, skipped, backend: sched.name };
235
+ }
236
+ export async function akmTasksDoctor() {
237
+ const warnings = [];
238
+ let invocation = { argv: [], via: "unresolved" };
239
+ try {
240
+ const r = resolveAkmInvocation();
241
+ invocation = { argv: r.argv, via: r.via };
242
+ }
243
+ catch (err) {
244
+ warnings.push(err instanceof Error ? err.message : String(err));
245
+ }
246
+ const backend = backendNameForPlatform();
247
+ const config = loadConfig();
248
+ const defaultProfile = config.agent?.default;
249
+ const profiles = listAgentProfileNames(config.agent);
250
+ return {
251
+ backend,
252
+ akm: invocation,
253
+ logDir: getTaskLogDir(),
254
+ historyDir: getTaskHistoryDir(),
255
+ agent: { defaultProfile, available: profiles },
256
+ scheduleSubset: SCHEDULE_SUPPORTED_SUBSET_HINT,
257
+ warnings,
258
+ };
259
+ }
260
+ // ── helpers ─────────────────────────────────────────────────────────────────
261
+ const VALID_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
262
+ function normaliseTaskId(raw) {
263
+ const id = raw.trim().replace(/\.md$/, "");
264
+ if (!id) {
265
+ throw new UsageError("Task id must be non-empty.", "MISSING_REQUIRED_ARGUMENT");
266
+ }
267
+ if (!VALID_ID_RE.test(id)) {
268
+ throw new UsageError(`Task id "${id}" is invalid. Use letters, digits, dots, underscores, and dashes only.`, "INVALID_FLAG_VALUE");
269
+ }
270
+ return id;
271
+ }
272
+ function renderTaskMarkdown(input) {
273
+ const lines = ["---"];
274
+ lines.push(`schedule: ${yamlQuote(input.schedule)}`);
275
+ if (input.workflow) {
276
+ lines.push(`workflow: ${yamlQuote(input.workflow)}`);
277
+ if (input.params) {
278
+ const parsed = parseJsonObjectArg(input.params);
279
+ lines.push("params:");
280
+ for (const [k, v] of Object.entries(parsed)) {
281
+ lines.push(` ${k}: ${yamlScalarValue(v)}`);
282
+ }
283
+ }
284
+ }
285
+ else if (input.prompt) {
286
+ if (looksLikeAssetRef(input.prompt) || isFilePath(input.prompt) || input.prompt === "inline") {
287
+ lines.push(`prompt: ${yamlQuote(input.prompt)}`);
288
+ }
289
+ else {
290
+ lines.push(`prompt: inline`);
291
+ }
292
+ if (input.profile)
293
+ lines.push(`profile: ${yamlQuote(input.profile)}`);
294
+ }
295
+ lines.push(`enabled: ${input.enabled}`);
296
+ if (input.description)
297
+ lines.push(`description: ${yamlQuote(input.description)}`);
298
+ if (input.tags && input.tags.length > 0) {
299
+ lines.push(`tags: [${input.tags.map((t) => yamlQuote(t)).join(", ")}]`);
300
+ }
301
+ lines.push("---", "");
302
+ if (input.workflow) {
303
+ lines.push(`# Task: ${humanise(input.id)}`, "");
304
+ }
305
+ else if (input.prompt) {
306
+ if (looksLikeAssetRef(input.prompt) || isFilePath(input.prompt) || input.prompt === "inline") {
307
+ lines.push(`# Task: ${humanise(input.id)}`, "");
308
+ }
309
+ else {
310
+ // Raw inline prompt — use the body itself.
311
+ lines.push(input.prompt.trim(), "");
312
+ }
313
+ }
314
+ return lines.join("\n");
315
+ }
316
+ function yamlQuote(value) {
317
+ if (/^[A-Za-z_][A-Za-z0-9_.\-/:]*$/.test(value))
318
+ return value;
319
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
320
+ }
321
+ function yamlScalarValue(v) {
322
+ if (typeof v === "string")
323
+ return yamlQuote(v);
324
+ if (typeof v === "number" || typeof v === "boolean")
325
+ return String(v);
326
+ if (v === null)
327
+ return "null";
328
+ return JSON.stringify(v);
329
+ }
330
+ function parseJsonObjectArg(raw) {
331
+ let parsed;
332
+ try {
333
+ parsed = JSON.parse(raw);
334
+ }
335
+ catch {
336
+ throw new UsageError("--params must be valid JSON.", "INVALID_JSON_ARGUMENT");
337
+ }
338
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
339
+ throw new UsageError("--params must be a JSON object.", "INVALID_JSON_ARGUMENT");
340
+ }
341
+ return parsed;
342
+ }
343
+ function looksLikeAssetRef(s) {
344
+ return /^[a-z][a-z0-9_-]*:[^\s]/i.test(s) && !s.startsWith("./") && !s.startsWith("/");
345
+ }
346
+ function isFilePath(s) {
347
+ return s.startsWith("./") || s.startsWith("../") || path.isAbsolute(s);
348
+ }
349
+ function humanise(id) {
350
+ return id.replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
351
+ }
352
+ /**
353
+ * Toggle the `enabled:` value in a task markdown's frontmatter without doing
354
+ * a round-trip through the parser+renderer (which would lose comments and
355
+ * formatting choices). Inserts the key right before the closing `---` if
356
+ * absent.
357
+ */
358
+ export function setEnabledInMarkdown(markdown, enabled) {
359
+ const m = markdown.match(/^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r\n|\r|\n|$))([\s\S]*)$/);
360
+ if (!m) {
361
+ throw new UsageError("Task markdown is missing frontmatter; cannot toggle enabled.", "INVALID_FLAG_VALUE");
362
+ }
363
+ const [, openFence, fmBody, closeFence, body] = m;
364
+ const replaced = fmBody.match(/(^|\r?\n)enabled:\s*[^\r\n]*/i)
365
+ ? fmBody.replace(/(^|\r?\n)enabled:\s*[^\r\n]*/i, `$1enabled: ${enabled}`)
366
+ : `${fmBody}\nenabled: ${enabled}`;
367
+ return `${openFence}${replaced}${closeFence}${body}`;
368
+ }
369
+ // Re-exported so tests can verify the validator path directly.
370
+ // Re-export error classes consumed by callers that want to instanceof-check.
371
+ // Re-export this so the CLI can decide what process exit code to use after
372
+ // `akm tasks run` completes.
373
+ export { ConfigError, exitCodeForStatus, NotFoundError, parseTaskDocument, UsageError };
374
+ // Helper: ensure the asset-spec resolver agrees with our id rules. If the
375
+ // user passes a ref, we accept the bare name part too.
376
+ export function parseTaskRef(input) {
377
+ if (input.includes(":")) {
378
+ const ref = parseAssetRef(input);
379
+ if (ref.type !== "task") {
380
+ throw new UsageError(`Expected a task id or task:<id> ref, got "${input}".`, "INVALID_FLAG_VALUE");
381
+ }
382
+ return { id: normaliseTaskId(ref.name) };
383
+ }
384
+ return { id: normaliseTaskId(input) };
385
+ }
@@ -0,0 +1,39 @@
1
+ const URL_RE = /https?:\/\/[^\s"'<>)\]]+/g;
2
+ const TIMEOUT_MS = 5000;
3
+ const MAX_URLS = 20;
4
+ export async function checkDeadUrls(_stashDir, entries) {
5
+ const urlsToCheck = [];
6
+ for (const entry of entries) {
7
+ if (urlsToCheck.length >= MAX_URLS)
8
+ break;
9
+ const matches = entry.body.match(URL_RE) ?? [];
10
+ for (const url of matches.slice(0, 3)) {
11
+ urlsToCheck.push({ ref: entry.ref, url });
12
+ if (urlsToCheck.length >= MAX_URLS)
13
+ break;
14
+ }
15
+ }
16
+ const results = [];
17
+ await Promise.allSettled(urlsToCheck.map(async ({ ref, url }) => {
18
+ try {
19
+ const controller = new AbortController();
20
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
21
+ const res = await fetch(url, {
22
+ method: "HEAD",
23
+ signal: controller.signal,
24
+ redirect: "follow",
25
+ });
26
+ clearTimeout(timer);
27
+ if (res.status >= 400) {
28
+ results.push({ ref, url, status: res.status });
29
+ }
30
+ }
31
+ catch (e) {
32
+ if (e.name === "AbortError") {
33
+ results.push({ ref, url, status: "timeout" });
34
+ }
35
+ // network errors (ENOTFOUND etc.) — skip, don't report as dead
36
+ }
37
+ }));
38
+ return results;
39
+ }