@ferronhooi/aihub 0.0.1 → 0.1.0-next.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 (57) hide show
  1. package/dist/cli.js +10 -9
  2. package/dist/commands/comments.js +32 -0
  3. package/dist/commands/doctor.js +21 -0
  4. package/dist/commands/init.js +18 -0
  5. package/dist/commands/pr.js +75 -0
  6. package/dist/commands/skills.js +44 -0
  7. package/dist/lib/ado.js +158 -0
  8. package/dist/lib/auth.js +68 -0
  9. package/dist/lib/clients.js +26 -0
  10. package/dist/lib/comments.js +119 -0
  11. package/dist/lib/context.js +9 -0
  12. package/dist/lib/doctor.js +118 -0
  13. package/dist/lib/errors.js +7 -0
  14. package/dist/lib/git.js +79 -0
  15. package/dist/lib/init.js +157 -0
  16. package/dist/lib/install.js +141 -0
  17. package/dist/lib/pack.js +48 -0
  18. package/dist/lib/pr.js +131 -0
  19. package/dist/lib/schema.js +56 -0
  20. package/dist/lib/team.js +24 -0
  21. package/dist/lib/templates.js +184 -0
  22. package/dist/router.js +48 -0
  23. package/dist/tools/lintSkills.js +166 -0
  24. package/dist/tools/lintSkills.test.js +70 -0
  25. package/pack/commands/copilot/cherry-pick.prompt.md +6 -0
  26. package/pack/commands/copilot/pr-update.prompt.md +6 -0
  27. package/pack/commands/copilot/pr.prompt.md +6 -0
  28. package/pack/commands/copilot/refine.prompt.md +6 -0
  29. package/pack/commands/copilot/review.prompt.md +6 -0
  30. package/pack/commands/copilot/story.prompt.md +6 -0
  31. package/pack/commands/copilot/watch.prompt.md +6 -0
  32. package/pack/commands/opencode/cherry-pick.md +5 -0
  33. package/pack/commands/opencode/pr-update.md +5 -0
  34. package/pack/commands/opencode/pr.md +5 -0
  35. package/pack/commands/opencode/refine.md +5 -0
  36. package/pack/commands/opencode/review.md +5 -0
  37. package/pack/commands/opencode/story.md +5 -0
  38. package/pack/commands/opencode/watch.md +5 -0
  39. package/pack/skills/_shared/assets/commit-template.nl.txt +5 -0
  40. package/pack/skills/_shared/assets/commit-template.txt +5 -0
  41. package/pack/skills/_shared/assets/pull_request_template.md +16 -0
  42. package/pack/skills/_shared/assets/pull_request_template.nl.md +16 -0
  43. package/pack/skills/_shared/assets/story-template.md +12 -0
  44. package/pack/skills/_shared/assets/story-template.nl.md +12 -0
  45. package/pack/skills/_shared/references/team.schema.yaml +41 -0
  46. package/pack/skills/branch-sync/SKILL.md +31 -0
  47. package/pack/skills/implement/SKILL.md +25 -0
  48. package/pack/skills/pipeline-fix/SKILL.md +29 -0
  49. package/pack/skills/pr-create/SKILL.md +29 -0
  50. package/pack/skills/pr-update/SKILL.md +28 -0
  51. package/pack/skills/pr-watch/SKILL.md +30 -0
  52. package/pack/skills/release/SKILL.md +35 -0
  53. package/pack/skills/review-process/SKILL.md +35 -0
  54. package/pack/skills/start-here/SKILL.md +36 -0
  55. package/pack/skills/story-create/SKILL.md +28 -0
  56. package/pack/skills/story-refine/SKILL.md +28 -0
  57. package/package.json +13 -3
package/dist/lib/pr.js ADDED
@@ -0,0 +1,131 @@
1
+ import { branchRef, findActivePr, getPr, getWorkItemPrIds, getWorkItemTitle, repoDefaultBranch, shortBranch, } from "./ado.js";
2
+ import { repoClient } from "./context.js";
3
+ import { AihubError } from "./errors.js";
4
+ import { commitsSince, currentBranch, mergeBase, originDefaultBranch, pushIfNeeded, showFile, workItemFromBranch, git, } from "./git.js";
5
+ import { compose, DEFAULT_EMPTY, editSection, mergeSections, resolveTemplate } from "./templates.js";
6
+ import { defaultTargetFor, loadTeam, readUtf8 } from "./team.js";
7
+ export function parsePrRef(ref) {
8
+ const m = /pullrequest\/(\d+)/i.exec(ref) ?? /^!?(\d+)$/.exec(ref.trim());
9
+ if (!m)
10
+ throw new AihubError(`'${ref}' is not a pull request number or URL`);
11
+ return Number(m[1]);
12
+ }
13
+ export function commitList(commits) {
14
+ return commits.map((c) => `- ${c.subject} (${c.sha})`).join("\n");
15
+ }
16
+ export async function createPr(ctx, o) {
17
+ const { root, client } = repoClient(ctx);
18
+ const branch = currentBranch(root);
19
+ const team = loadTeam(root);
20
+ const target = o.target ??
21
+ defaultTargetFor(team, client.remote.repo) ??
22
+ (originDefaultBranch(root) || undefined) ??
23
+ (await repoDefaultBranch(client)) ??
24
+ "main";
25
+ if (target === branch)
26
+ throw new AihubError(`you are on the target branch '${branch}'; check out a feature branch first`);
27
+ const wi = o.workItem ?? workItemFromBranch(branch);
28
+ const wiTitle = wi ? await getWorkItemTitle(client, wi) : undefined;
29
+ const commits = commitsSince(root, mergeBase(root, target));
30
+ const title = o.title ?? (wi && wiTitle ? `${wi} ${wiTitle}` : (commits[0]?.subject ?? branch));
31
+ const existing = o.dryRun ? undefined : await findActivePr(client, branch);
32
+ const linkedIds = wi ? (await getWorkItemPrIds(client, wi)).filter((id) => id !== existing?.pullRequestId) : [];
33
+ const code = {
34
+ story: wi ? `AB#${wi}` : undefined,
35
+ commits: commits.length ? commitList(commits) : undefined,
36
+ linked: linkedIds.length ? linkedIds.map((i) => `- !${i}`).join("\n") : undefined,
37
+ };
38
+ const body = o.bodyFile ? readUtf8(o.bodyFile) : "";
39
+ const tpl = resolveTemplate(target, { readRef: (b, p) => showFile(root, b, p), localRoot: root });
40
+ const emptyText = team.pullRequest?.emptySection || DEFAULT_EMPTY;
41
+ let description;
42
+ let summary;
43
+ if (tpl) {
44
+ const c = compose({ template: tpl.content, body, code, emptyText });
45
+ description = c.text;
46
+ const by = (k) => c.filled.filter((f) => f.by === k).map((f) => f.heading);
47
+ summary = [
48
+ by("body").length ? `body: ${by("body").join(", ")}` : "",
49
+ by("code").length ? `code: ${by("code").join(", ")}` : "",
50
+ by("empty").length ? `${emptyText}: ${by("empty").join(", ")}` : "",
51
+ by("extra").length ? `extra: ${by("extra").join(", ")}` : "",
52
+ ]
53
+ .filter(Boolean)
54
+ .join("; ");
55
+ }
56
+ else {
57
+ const extra = [code.story, code.commits && `## Commits\n\n${code.commits}`].filter(Boolean).join("\n\n");
58
+ description = [body.trim(), extra].filter(Boolean).join("\n\n") + "\n";
59
+ summary = "no PR template found: body used as is";
60
+ }
61
+ if (o.dryRun) {
62
+ return o.json
63
+ ? JSON.stringify({ dryRun: true, title, target, source: branch, workItem: wi, template: tpl?.path, description })
64
+ : `dry-run: '${title}' ${branch} -> ${target} (${summary})\n${description}`;
65
+ }
66
+ if (existing) {
67
+ const upd = { description };
68
+ if (o.title)
69
+ upd.title = o.title;
70
+ if (o.draft !== undefined)
71
+ upd.isDraft = o.draft;
72
+ await client.patch(`${client.repoPath()}/pullrequests/${existing.pullRequestId}`, upd);
73
+ return line(o, { id: existing.pullRequestId, url: client.prUrl(existing.pullRequestId), action: "updated", summary }, `PR !${existing.pullRequestId} updated`, client, summary);
74
+ }
75
+ pushIfNeeded(root, branch);
76
+ const created = await client.post(`${client.repoPath()}/pullrequests`, {
77
+ sourceRefName: branchRef(branch),
78
+ targetRefName: branchRef(target),
79
+ title,
80
+ description,
81
+ isDraft: !!o.draft,
82
+ ...(wi ? { workItemRefs: [{ id: String(wi) }] } : {}),
83
+ });
84
+ return line(o, { id: created.pullRequestId, url: client.prUrl(created.pullRequestId), action: "created", summary }, `PR !${created.pullRequestId} created`, client, summary);
85
+ }
86
+ function line(o, j, text, c, summary) {
87
+ return o.json ? JSON.stringify(j) : `${text}: ${c.prUrl(j.id)} (${summary})`;
88
+ }
89
+ export async function resolvePr(ctx, client, root, ref) {
90
+ if (ref)
91
+ return getPr(client, parsePrRef(ref));
92
+ const branch = currentBranch(root);
93
+ const pr = await findActivePr(client, branch);
94
+ if (!pr)
95
+ throw new AihubError(`no active pull request for branch '${branch}'; pass --pr <number|url> or run 'aihub pr create'`);
96
+ return getPr(client, pr.pullRequestId);
97
+ }
98
+ export async function updatePr(ctx, o) {
99
+ const { root, client } = repoClient(ctx);
100
+ const pr = await resolvePr(ctx, client, root, o.pr);
101
+ let description = pr.description ?? "";
102
+ const changed = [];
103
+ if (o.bodyFile) {
104
+ description = mergeSections(description, readUtf8(o.bodyFile));
105
+ changed.push("body");
106
+ }
107
+ if (o.section) {
108
+ if (!o.appendFile && !o.replaceFile)
109
+ throw new AihubError("--section needs --append-file or --replace-file");
110
+ description = editSection(description, o.section, o.replaceFile ? { replace: readUtf8(o.replaceFile) } : { append: readUtf8(o.appendFile) });
111
+ changed.push(`section ${o.section}`);
112
+ }
113
+ else if (o.appendFile || o.replaceFile) {
114
+ throw new AihubError("--append-file/--replace-file need --section <heading>");
115
+ }
116
+ const patch = {};
117
+ if (changed.length)
118
+ patch.description = description;
119
+ if (o.title)
120
+ (patch.title = o.title), changed.push("title");
121
+ if (o.draft !== undefined)
122
+ (patch.isDraft = o.draft), changed.push(o.draft ? "draft" : "ready");
123
+ if (o.target)
124
+ (patch.targetRefName = branchRef(o.target)), changed.push(`target ${shortBranch(branchRef(o.target))}`);
125
+ if (!changed.length)
126
+ throw new AihubError("nothing to update: pass --body-file, --section, --title, --draft or --target");
127
+ await client.patch(`${client.repoPath()}/pullrequests/${pr.pullRequestId}`, patch);
128
+ const url = client.prUrl(pr.pullRequestId);
129
+ return o.json ? JSON.stringify({ id: pr.pullRequestId, url, changed }) : `PR !${pr.pullRequestId} updated: ${url} (${changed.join(", ")})`;
130
+ }
131
+ export { git };
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The team schema file is a documented YAML example: every key carries a comment ending in "(required)" or "(optional)".
3
+ * This reads those comments to find the required key paths (lists are written `repositories[].name`).
4
+ */
5
+ export function requiredPaths(schemaText) {
6
+ const stack = [];
7
+ const out = [];
8
+ for (const line of schemaText.replace(/\r\n/g, "\n").split("\n")) {
9
+ const m = /^(\s*)(-\s+)?([A-Za-z][A-Za-z0-9]*):(.*)$/.exec(line);
10
+ if (!m || line.trimStart().startsWith("#"))
11
+ continue;
12
+ const keyIndent = m[1].length + (m[2]?.length ?? 0);
13
+ while (stack.length && stack[stack.length - 1].indent >= keyIndent)
14
+ stack.pop();
15
+ if (m[2] && stack.length)
16
+ stack[stack.length - 1].isList = true;
17
+ stack.push({ indent: keyIndent, key: m[3], isList: false });
18
+ const comment = m[4].includes("#") ? m[4].slice(m[4].indexOf("#")) : "";
19
+ if (/\(required\b/.test(comment))
20
+ out.push(stack.map((s) => s.key + (s.isList ? "[]" : "")).join("."));
21
+ }
22
+ return out;
23
+ }
24
+ const get = (value, seg) => {
25
+ const isList = seg.endsWith("[]");
26
+ const key = isList ? seg.slice(0, -2) : seg;
27
+ if (value === null || typeof value !== "object" || Array.isArray(value))
28
+ return [];
29
+ const v = value[key];
30
+ if (v === undefined || v === null || v === "" || (Array.isArray(v) && v.length === 0))
31
+ return [];
32
+ return isList ? (Array.isArray(v) ? v : []) : [v];
33
+ };
34
+ /** Human-readable problems of a parsed team file against the required paths; empty when valid. */
35
+ export function validateTeam(data, required) {
36
+ const problems = [];
37
+ for (const path of required) {
38
+ const segs = path.split(".");
39
+ let level = [data];
40
+ let missing = false;
41
+ for (const s of segs) {
42
+ const next = level.flatMap((v) => get(v, s));
43
+ if (s.endsWith("[]") ? !next.length : next.length < level.length || !next.length)
44
+ missing = true;
45
+ level = next;
46
+ if (missing)
47
+ break;
48
+ }
49
+ if (missing)
50
+ problems.push(`missing ${path}`);
51
+ }
52
+ const v = data?.version;
53
+ if (v !== undefined && !Number.isInteger(v))
54
+ problems.push("version must be an integer");
55
+ return problems;
56
+ }
@@ -0,0 +1,24 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { parse } from "yaml";
4
+ export const TEAM_FILE = ".agents/skills/_shared/references/team.yaml";
5
+ /** Read a UTF-8 file, dropping a BOM and normalising CRLF. */
6
+ export function readUtf8(path) {
7
+ return readFileSync(path, "utf8").replace(/^/, "").replace(/\r\n/g, "\n");
8
+ }
9
+ export function loadTeam(repoRoot) {
10
+ const p = join(repoRoot, TEAM_FILE);
11
+ if (!existsSync(p))
12
+ return {};
13
+ try {
14
+ return parse(readUtf8(p)) ?? {};
15
+ }
16
+ catch {
17
+ return {};
18
+ }
19
+ }
20
+ export function defaultTargetFor(team, repoName) {
21
+ const repos = team.repositories ?? [];
22
+ const r = repos.find((x) => x.name?.toLowerCase() === repoName.toLowerCase()) ?? (repos.length === 1 && !repos[0].name ? repos[0] : undefined);
23
+ return r?.defaultTarget;
24
+ }
@@ -0,0 +1,184 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { readUtf8 } from "./team.js";
4
+ export const TEMPLATE_DIRS = [".azuredevops", ".vsts", "docs", ""];
5
+ export const DEFAULT_EMPTY = "n.v.t.";
6
+ export const MAX_DESCRIPTION = 4000;
7
+ /** Candidate paths in Azure DevOps order: branch-specific first, then the default template. */
8
+ export function templateCandidates(target) {
9
+ const join2 = (d, f) => (d ? `${d}/${f}` : f);
10
+ const out = [];
11
+ for (const d of TEMPLATE_DIRS)
12
+ out.push(join2(d, `pull_request_template/branches/${target}.md`));
13
+ for (const d of TEMPLATE_DIRS)
14
+ out.push(join2(d, "pull_request_template.md"));
15
+ return out;
16
+ }
17
+ export function resolveTemplate(target, src) {
18
+ const cands = templateCandidates(target);
19
+ if (src.readRef) {
20
+ for (const p of cands) {
21
+ const c = src.readRef(target, p);
22
+ if (c !== undefined)
23
+ return { path: p, content: c.replace(/\r\n/g, "\n"), from: "ref" };
24
+ }
25
+ }
26
+ if (src.localRoot) {
27
+ for (const p of cands) {
28
+ const full = join(src.localRoot, p);
29
+ if (existsSync(full))
30
+ return { path: p, content: readUtf8(full), from: "local" };
31
+ }
32
+ }
33
+ return undefined;
34
+ }
35
+ /** Split markdown at `## ` headings (outside code fences). */
36
+ export function parseSections(md) {
37
+ const lines = md.replace(/^/, "").replace(/\r\n/g, "\n").split("\n");
38
+ const sections = [];
39
+ const pre = [];
40
+ let fence = false;
41
+ for (const line of lines) {
42
+ if (/^\s*(```|~~~)/.test(line))
43
+ fence = !fence;
44
+ const m = !fence ? /^##\s+(.+?)\s*#*\s*$/.exec(line) : null;
45
+ if (m && !line.startsWith("###"))
46
+ sections.push({ heading: m[1].trim(), lines: [] });
47
+ else if (sections.length)
48
+ sections[sections.length - 1].lines.push(line);
49
+ else
50
+ pre.push(line);
51
+ }
52
+ return {
53
+ preamble: pre.join("\n").trim(),
54
+ sections: sections.map((s) => ({ heading: s.heading, body: s.lines.join("\n").trim() })),
55
+ };
56
+ }
57
+ export function renderSections(sections) {
58
+ return sections.map((s) => `## ${s.heading}\n\n${s.body}`.trimEnd()).join("\n\n") + "\n";
59
+ }
60
+ const stripComments = (s) => s.replace(/<!--[\s\S]*?-->/g, "").trim();
61
+ export function normHeading(h) {
62
+ return h
63
+ .toLowerCase()
64
+ .normalize("NFD")
65
+ .replace(/[̀-ͯ]/g, "")
66
+ .replace(/\(.*?\)/g, "")
67
+ .replace(/[^a-z0-9]+/g, "");
68
+ }
69
+ export function headingsMatch(a, b) {
70
+ const x = normHeading(a);
71
+ const y = normHeading(b);
72
+ if (!x || !y)
73
+ return false;
74
+ if (x === y)
75
+ return true;
76
+ return Math.min(x.length, y.length) >= 4 && (x.includes(y) || y.includes(x));
77
+ }
78
+ export function codeKindOf(heading) {
79
+ const words = heading.trim().split(/\s+/).length;
80
+ if (/(gerelateerde|gekoppelde|linked|related)\W+(pr|prs|pull)|(pr|prs|pull requests?)\W+(link|gerelateerd)/i.test(heading))
81
+ return "linked";
82
+ if (/commit/i.test(heading))
83
+ return "commits";
84
+ if (words <= 4 && /(story|work ?item|werk ?item|ticket|ab#)/i.test(heading))
85
+ return "story";
86
+ return undefined;
87
+ }
88
+ export function compose(input) {
89
+ const empty = input.emptyText || DEFAULT_EMPTY;
90
+ const tpl = parseSections(input.template).sections;
91
+ const body = parseSections(input.body);
92
+ const pool = body.sections.map((s) => ({ ...s, used: false }));
93
+ const filled = [];
94
+ const out = [];
95
+ // A body without any `##` heading is free text: it goes to the first non-code section.
96
+ const freeText = body.sections.length === 0 ? stripComments(input.body) : "";
97
+ let freeUsed = false;
98
+ const take = (heading) => {
99
+ const exact = pool.find((p) => !p.used && normHeading(p.heading) === normHeading(heading));
100
+ const hit = exact ?? pool.find((p) => !p.used && headingsMatch(p.heading, heading));
101
+ if (!hit)
102
+ return undefined;
103
+ hit.used = true;
104
+ const t = stripComments(hit.body);
105
+ return t || undefined;
106
+ };
107
+ for (const s of tpl) {
108
+ const kind = codeKindOf(s.heading);
109
+ const fromBody = take(s.heading);
110
+ let text;
111
+ let by = "empty";
112
+ const codeVal = kind ? input.code[kind] : undefined;
113
+ if (codeVal) {
114
+ text = codeVal;
115
+ by = "code";
116
+ }
117
+ else if (fromBody) {
118
+ text = fromBody;
119
+ by = "body";
120
+ }
121
+ else if (freeText && !freeUsed && !kind) {
122
+ text = freeText;
123
+ freeUsed = true;
124
+ by = "body";
125
+ }
126
+ out.push({ heading: s.heading, body: text ?? empty });
127
+ filled.push({ heading: s.heading, by: text ? by : "empty" });
128
+ }
129
+ // Never lose prose: sections the template does not know are appended in order.
130
+ for (const p of pool) {
131
+ const t = stripComments(p.body);
132
+ if (!p.used && t) {
133
+ out.push({ heading: p.heading, body: t });
134
+ filled.push({ heading: p.heading, by: "extra" });
135
+ }
136
+ }
137
+ return { text: capLength(renderSections(out), input.code.commits), filled };
138
+ }
139
+ /** Azure DevOps caps descriptions at 4000 characters; shrink the commit list first. */
140
+ function capLength(text, commits) {
141
+ if (text.length <= MAX_DESCRIPTION)
142
+ return text;
143
+ let t = text;
144
+ if (commits) {
145
+ const lines = commits.split("\n");
146
+ while (t.length > MAX_DESCRIPTION && lines.length > 1) {
147
+ const before = lines.join("\n");
148
+ lines.pop();
149
+ t = t.replace(before, lines.join("\n") + "\n- ...");
150
+ }
151
+ }
152
+ return t.length > MAX_DESCRIPTION ? t.slice(0, MAX_DESCRIPTION - 4).trimEnd() + "\n..." : t;
153
+ }
154
+ /** Replace/append content of one section in an existing description; other sections stay intact. */
155
+ export function editSection(description, heading, change) {
156
+ const parsed = parseSections(description);
157
+ const idx = parsed.sections.findIndex((s) => headingsMatch(s.heading, heading));
158
+ if (idx < 0) {
159
+ parsed.sections.push({ heading, body: (change.replace ?? change.append ?? "").trim() });
160
+ }
161
+ else {
162
+ const cur = parsed.sections[idx];
163
+ const curText = stripComments(cur.body);
164
+ const placeholder = curText === "" || normHeading(curText) === normHeading(DEFAULT_EMPTY);
165
+ cur.body =
166
+ change.replace !== undefined
167
+ ? change.replace.trim()
168
+ : placeholder
169
+ ? (change.append ?? "").trim()
170
+ : `${cur.body}\n\n${(change.append ?? "").trim()}`;
171
+ }
172
+ const head = parsed.preamble ? `${parsed.preamble}\n\n` : "";
173
+ return head + renderSections(parsed.sections);
174
+ }
175
+ /** Merge sections of `patch` into `description` (matching headings replace, new ones append). */
176
+ export function mergeSections(description, patch) {
177
+ const p = parseSections(patch);
178
+ if (p.sections.length === 0)
179
+ return patch.trim() + "\n";
180
+ let out = description;
181
+ for (const s of p.sections)
182
+ out = editSection(out, s.heading, { replace: s.body });
183
+ return out;
184
+ }
package/dist/router.js ADDED
@@ -0,0 +1,48 @@
1
+ import { AihubError } from "./lib/errors.js";
2
+ import { cliVersion } from "./lib/pack.js";
3
+ import * as comments from "./commands/comments.js";
4
+ import * as doctor from "./commands/doctor.js";
5
+ import * as init from "./commands/init.js";
6
+ import * as pr from "./commands/pr.js";
7
+ import * as skills from "./commands/skills.js";
8
+ /**
9
+ * Command registry. To add a command: create src/commands/<name>.ts exporting
10
+ * `run(argv, ctx)` and add one line here. Commands print through ctx.out and
11
+ * throw AihubError for user-facing failures.
12
+ */
13
+ export const commands = {
14
+ pr: pr.run,
15
+ comments: comments.run,
16
+ init: init.run,
17
+ skills: skills.run,
18
+ doctor: doctor.run,
19
+ };
20
+ export const VERSION = cliVersion();
21
+ /** Returns the process exit code. */
22
+ export async function main(argv, ctx, registry = commands) {
23
+ const [name, ...rest] = argv;
24
+ if (!name || name === "--help" || name === "-h" || name === "help") {
25
+ ctx.out(`aihub ${VERSION}: Azure DevOps team workflows in one call. Commands: ${Object.keys(registry).join(", ")}.`);
26
+ return 0;
27
+ }
28
+ if (name === "--version" || name === "-v") {
29
+ ctx.out(VERSION);
30
+ return 0;
31
+ }
32
+ const fn = registry[name];
33
+ if (!fn) {
34
+ ctx.err(`aihub: unknown command '${name}'. Commands: ${Object.keys(registry).join(", ")}.`);
35
+ return 2;
36
+ }
37
+ try {
38
+ await fn(rest, ctx);
39
+ return 0;
40
+ }
41
+ catch (e) {
42
+ if (e instanceof AihubError)
43
+ ctx.err(`aihub: ${e.message}`);
44
+ else
45
+ ctx.err(`aihub: unexpected error: ${e.message}`);
46
+ return 1;
47
+ }
48
+ }
@@ -0,0 +1,166 @@
1
+ #!/usr/bin/env node
2
+ // Lints the generic skill pack: front matter, "Use when", token budget, relative links,
3
+ // absolute paths, forbidden names and that the slash commands match the skills.
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ export const DEFAULT_FORBIDDEN = ["iqbs", "mydataintelligence", "ferronhooi", "ferron hooi"];
8
+ /** The slash commands, each loading one skill. Files must equal expectedCommand(). */
9
+ export const COMMANDS = [
10
+ { name: "pr", skill: "pr-create", description: "Create a pull request", hint: "optional story id or remarks" },
11
+ { name: "pr-update", skill: "pr-update", description: "Update the open pull request", hint: "optional remarks" },
12
+ { name: "cherry-pick", skill: "branch-sync", description: "Cherry-pick a PR to other branches", hint: "PR id and target branches" },
13
+ { name: "story", skill: "story-create", description: "Create a story", hint: "what the story is about" },
14
+ { name: "refine", skill: "story-refine", description: "Refine a story", hint: "story id" },
15
+ { name: "review", skill: "review-process", description: "Process review comments", hint: "optional PR id" },
16
+ { name: "watch", skill: "pr-watch", description: "Follow a PR and its pipeline", hint: "optional PR id or link" },
17
+ ];
18
+ export function expectedCommand(kind, c) {
19
+ const load = `Load the \`${c.skill}\` skill and follow it exactly.`;
20
+ if (kind === "opencode") {
21
+ return `---\ndescription: ${c.description}\n---\n${load}\nArguments: $ARGUMENTS\n`;
22
+ }
23
+ return `---\nmode: agent\ndescription: ${c.description}\n---\n${load}\nInput: \${input:args:${c.hint}}\n`;
24
+ }
25
+ export function commandFileName(kind, c) {
26
+ return kind === "opencode" ? `${c.name}.md` : `${c.name}.prompt.md`;
27
+ }
28
+ export function parseFrontMatter(text) {
29
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text);
30
+ if (!m)
31
+ return null;
32
+ const data = {};
33
+ for (const line of m[1].split(/\r?\n/)) {
34
+ const kv = /^([A-Za-z_-]+):\s*(.*)$/.exec(line);
35
+ if (!kv)
36
+ continue;
37
+ let v = kv[2].trim();
38
+ if (/^".*"$/.test(v))
39
+ v = v.slice(1, -1);
40
+ data[kv[1]] = v;
41
+ }
42
+ return { data, body: m[2] };
43
+ }
44
+ export const tokens = (s) => Math.ceil(s.length / 4);
45
+ function walk(dir, out = []) {
46
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
47
+ const p = path.join(dir, e.name);
48
+ if (e.isDirectory())
49
+ walk(p, out);
50
+ else
51
+ out.push(p);
52
+ }
53
+ return out;
54
+ }
55
+ const ABSOLUTE = /(?<![A-Za-z0-9])[A-Za-z]:\\|(?<![A-Za-z0-9])[A-Za-z]:\/(?!\/)|\/Users\/|\/home\/[a-z]|~\//;
56
+ function checkText(file, text, forbidden, errors) {
57
+ const lower = text.toLowerCase();
58
+ for (const f of forbidden)
59
+ if (f && lower.includes(f.toLowerCase()))
60
+ errors.push(`${file}: forbidden name "${f}"`);
61
+ if (ABSOLUTE.test(text))
62
+ errors.push(`${file}: absolute path`);
63
+ const dir = path.dirname(file);
64
+ for (const m of text.matchAll(/\]\(([^)\s]+)\)/g)) {
65
+ const target = m[1].split("#")[0];
66
+ if (!target || /^[a-z]+:/i.test(target))
67
+ continue;
68
+ if (!fs.existsSync(path.resolve(dir, target)))
69
+ errors.push(`${file}: link does not resolve: ${m[1]}`);
70
+ }
71
+ }
72
+ export function lintSkills(skillsDir, opts = {}) {
73
+ const errors = [];
74
+ const forbidden = opts.forbidden ?? DEFAULT_FORBIDDEN;
75
+ const max = opts.maxTokens ?? 500;
76
+ const min = opts.minTokens ?? 200;
77
+ const skillNames = [];
78
+ for (const e of fs.readdirSync(skillsDir, { withFileTypes: true })) {
79
+ if (!e.isDirectory() || e.name.startsWith("_"))
80
+ continue;
81
+ const file = path.join(skillsDir, e.name, "SKILL.md");
82
+ if (!fs.existsSync(file)) {
83
+ errors.push(`${e.name}: SKILL.md missing`);
84
+ continue;
85
+ }
86
+ skillNames.push(e.name);
87
+ const text = fs.readFileSync(file, "utf8");
88
+ const fm = parseFrontMatter(text);
89
+ if (!fm) {
90
+ errors.push(`${file}: front matter missing`);
91
+ continue;
92
+ }
93
+ if (fm.data.name !== e.name)
94
+ errors.push(`${file}: name "${fm.data.name}" must equal folder "${e.name}"`);
95
+ if (!/^Use when /.test(fm.data.description ?? ""))
96
+ errors.push(`${file}: description must start with "Use when "`);
97
+ const n = tokens(fm.body);
98
+ if (n > max)
99
+ errors.push(`${file}: body is ~${n} tokens, max ${max}`);
100
+ if (n < min)
101
+ errors.push(`${file}: body is ~${n} tokens, min ${min}`);
102
+ for (const h of ["## When", "## Steps", "## What the CLI fills", "## If it fails"]) {
103
+ if (!fm.body.includes(h))
104
+ errors.push(`${file}: section "${h}" missing`);
105
+ }
106
+ }
107
+ for (const file of walk(skillsDir)) {
108
+ if (/\.(md|txt|ya?ml)$/.test(file))
109
+ checkText(file, fs.readFileSync(file, "utf8"), forbidden, errors);
110
+ }
111
+ const commandsDir = opts.commandsDir ?? path.resolve(skillsDir, "..", "commands");
112
+ if (fs.existsSync(commandsDir)) {
113
+ for (const kind of ["opencode", "copilot"]) {
114
+ for (const c of COMMANDS) {
115
+ if (!skillNames.includes(c.skill)) {
116
+ errors.push(`command ${c.name}: skill "${c.skill}" does not exist`);
117
+ continue;
118
+ }
119
+ const file = path.join(commandsDir, kind, commandFileName(kind, c));
120
+ if (!fs.existsSync(file))
121
+ errors.push(`${file}: missing`);
122
+ else if (fs.readFileSync(file, "utf8").replace(/\r\n/g, "\n") !== expectedCommand(kind, c)) {
123
+ errors.push(`${file}: does not match the skill "${c.skill}" (expected generated content)`);
124
+ }
125
+ }
126
+ const dir = path.join(commandsDir, kind);
127
+ if (fs.existsSync(dir)) {
128
+ const known = new Set(COMMANDS.map((c) => commandFileName(kind, c)));
129
+ for (const f of fs.readdirSync(dir))
130
+ if (!known.has(f))
131
+ errors.push(`${path.join(dir, f)}: unknown command file`);
132
+ for (const f of fs.readdirSync(dir)) {
133
+ const p = path.join(dir, f);
134
+ checkText(p, fs.readFileSync(p, "utf8"), forbidden, errors);
135
+ }
136
+ }
137
+ }
138
+ }
139
+ else {
140
+ errors.push(`${commandsDir}: commands directory missing`);
141
+ }
142
+ return errors;
143
+ }
144
+ function main() {
145
+ const args = process.argv.slice(2);
146
+ let forbidden;
147
+ const rest = [];
148
+ for (let i = 0; i < args.length; i++) {
149
+ if (args[i] === "--forbidden")
150
+ forbidden = (args[++i] ?? "").split(",").map((s) => s.trim()).filter(Boolean);
151
+ else
152
+ rest.push(args[i]);
153
+ }
154
+ forbidden ??= process.env.AIHUB_FORBIDDEN_NAMES?.split(",").map((s) => s.trim()).filter(Boolean);
155
+ const dir = path.resolve(rest[0] ?? "../skills");
156
+ const errors = lintSkills(dir, { forbidden });
157
+ if (errors.length) {
158
+ for (const e of errors)
159
+ console.error(e);
160
+ console.error(`lint:skills failed with ${errors.length} error(s)`);
161
+ process.exit(1);
162
+ }
163
+ console.log("lint:skills ok");
164
+ }
165
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url))
166
+ main();